//========================================================================================
//                                  Copyright © 2005 NSCC
//
// NSCC search client-side script functions.
//
// $Log: /Internet/_Main/Web/scripts/search.js $
//
//6     25/11/05 12:38 Daviesa
//Added additional spaces between page nos in writePageNos
//
//5     31/10/05 12:01 Daviesa
//Moved goSearch, goGISProperty & displayGISDisclaimer to common +
//improved goResults
//
//4     28/10/05 17:07 Daviesa
//Added goResults
//
//3     26/10/05 11:55 Daviesa
//Added "skipReturnToCallingPage" param to printPage
//
//2     17/10/05 11:02 Daviesa
//Added isOnlySingleChars
//========================================================================================

function getTotalSelectedItems(selectObj) {
// Returns the number of options selected in the given SELECT object.
    if (selectObj.selectedIndex >= 0) {
        if (selectObj.multiple == true) {
            var totalSelectItems = 0;
            var selectOptions = selectObj.options;

            for (i = 0; i < selectOptions.length; i++) {
                if (selectOptions[i].selected == true) {
                    totalSelectItems += 1;
                }
            }

            return totalSelectItems;

        } else {
            return 1;
        }

    } else {
        return 0
    }
}

function trim(str) {
// Trims leading & trailing spaces from the given string & returns the result.
    return str.replace(/^(\s+)?(.*\S)(\s+)?$/gi, '$2');
}

function isOnlySingleChars(str) {
// Returns TRUE if the given string contains just single characters
//  (1 or more, seperated by spaces); otherwise returns FALSE.
	str = trim(str);

	if (str.length >= 1) {
    	if (str.indexOf(' ') < 0 && str.length > 1) {
	        return false;

    	} else {
        	asStrParts = str.split(' ');

	        for (i = 0; i < asStrParts.length; i++) {
		        if (asStrParts[i].length > 1) {
			        return false;
        		}
    		}
	    }
	}

	return true;
}

function rOver(obj) {
// Called whenever the user moves the mouse pointer over a result row (i.e. onmouseover).
    obj.style.backgroundColor = '#f2f2f2';
}

function rOut(obj) {
// Called whenever the user moves the mouse pointer off a result row (i.e. onblur).
    obj.style.backgroundColor = 'transparent';
}

function goSearch(urlSearchPage, urlDetailsPage) {
// If the referring page was not the given search or (optionally) details page, redirects to the
//  given search page (with no criteria i.e. a new search); otherwise redirects to the original
//  search page.
    var referringURL = document.referrer;

    if (referringURL.indexOf(urlSearchPage) < 0) { // If we didn't come from the search page...
        if (urlDetailsPage) { // If a details page was supplied...
            if (referringURL.indexOf(urlDetailsPage) < 0) { // If we didn't come from the details page...
                referringURL = urlSearchPage; // Go to a new search
            }

        } else {
            referringURL = urlSearchPage; // Go to a new search
        }
    }

    document.location.href = referringURL;
}

function goGISProperty(propertyID) {
// Displays the GIS disclaimer and, if accepted, navigates to the property in the GIS viewer.
    if (displayGISDisclaimer()) {
        window.open("http://publicgis.northshorecity.govt.nz/website/Internet/GISInternet/viewer.htm?ActiveLayer=36&Query=PROPERTY_I=" + propertyID + "&QueryZoom=Yes&layers=0000000000000000001110000110000110001001", "_blank");
    }
}

function displayGISDisclaimer() {
// Displays the GIS disclaimer. Returns TRUE if accepted; otherwise returns FALSE.
    var sDisclaimer = "NSCC GIS VIEWER DISCLAIMER:"
                      + "\n\nThe information provided in this plan is intended to be general information only. This plan is provided on the sole basis that the council accepts no liability or responsibility whatsoever to any party for its content or any error or omission in it, and excludes all responsibility and liability with relation to any claims whatsoever (including without limitation for contributory negligence by the council) arising from the use of this plan. Actual locations of any pipes or services shown on this plan should be physically verified on site prior to design or construction. Any damage to any of the pipes or services specified in this plan is the sole responsibility of the person damaging the pipes or services, whether or not the council's plans are accurate, and the council will seek to recover the cost of repairing any such damage to pipes or services from any such person."
                      + "\n\nThis website is best viewed with Internet Explorer 5.0+ at 1024 x 768 16 bit colour depth and above.";
    return window.confirm(sDisclaimer)
}

function goResults(resultsID) {
// If there are results, jump to the top of the search form (id=searchForm by default).
    if (!resultsID) {
        resultsID = "searchForm";
    }

    document.getElementById(resultsID).scrollIntoView(true);
}

function goPrint() {
// Directs the user's browser window to the current page but adds a '&print=yes'
//  to the QueryString (if not already there).
    var newHRef = location.href;

    if (location.href.indexOf('print=yes') < 0) {

        if (location.href.indexOf('?') < 0) {
            newHRef += '?';
        } else {
            newHRef += '&';
        }

        newHRef += 'print=yes';
    }

    location.href = newHRef;
}

function printPage(skipReturnToCallingPage) {
// Tries to print the current page (by calling the print dialog) and then returns
//  to the previous page in the URL history.
    if (window.print) {
        window.print() ;

    } else {
        var webBrowser = '<object id="WebBrowser1" width="0" height="0" classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object>';
        document.body.insertAdjacentHTML('beforeEnd', webBrowser);
        webBrowser.ExecWB(6, 2);  // Use a 1 vs. a 2 for a prompting dialog box
        webBrowser.outerHTML = "";
    }

    if (!skipReturnToCallingPage) { // If FALSE or not supplied...
        history.back();
    }
}

function writePageNos() {
// Draws the page numbers in the results pagination header & footer.
// Always overlaps one page i.e. 1-10 then 10-20 then 20-30 etc.
    var maxPageNos = 10; // Configurable

    var headerList = findObj('paginationHeader');
    var footerList = findObj('paginationFooter');
    var metaDataForm = document.forms.frmMetaData;

    if ((metaDataForm != null) &&
        ((headerList != null) || (footerList != null))) {
        var pageNoHTML = '';
        var pageCurrent = parseInt(metaDataForm.currentPage.value, 10);
        var pageStart   = parseInt(metaDataForm.startPage.value,   10);

        if ((pageStart <= 0) || (pageStart == '')) {
            pageStart = 1;

        } else { // Round to the nearest multiple of maxPageNos
            pageStart = pageStart - (pageStart % maxPageNos);

            if (pageStart < 1) {
                pageStart = 1;
            }
        }

        if (pageStart > 1) {
            var pageEnd = (pageStart + maxPageNos);
        } else {
            var pageEnd = (pageStart + (maxPageNos - 1));
        }

        var pagesTotal = parseInt(metaDataForm.totalPages.value, 10);

        for (i = 1; i <= pagesTotal; i++) {
            if ((i >= pageStart) && (i <= pageEnd)) {
                if (i == pageCurrent) {
                    pageNoHTML += '<span style="font-weight:bold;font-size:120%">' + i + '</span>  ';
                } else {
                    pageNoHTML += '<a href="../../NorthShoreLeisure/scripts/' + metaDataForm.currentURL.value + '&page=' + i + '" class="linkWhite" title="Open page ' + i + '">' + i + '</a>';
                    if (i < pagesTotal) {
                        pageNoHTML += '  ';
                    }
                }
            }
        }

        if (pageStart > 1) {
            pageStart -= maxPageNos;
            if (pageStart < 1) {
                pageStart = 1;
            }
            pageNoHTML = '<a href="javascript:adjustPageRange(\'' + pageStart + '\')" class="linkWhite" title="Previous - pages ' + pageStart + '-' + (pageEnd - maxPageNos) + '"><img src="../../NorthShoreLeisure/images/search/previous.gif" border="0"/>...</a> ' + pageNoHTML;
        }

        if (pageEnd < pagesTotal) {
            pageStart = pageEnd + 1;
            pageEnd += maxPageNos;
            if (pageEnd > pagesTotal) {
                pageEnd = pagesTotal;
            }
            pageNoHTML += ' <a href="javascript:adjustPageRange(\'' + pageStart + '\')" class="linkWhite" title="Next - pages ' + (pageStart - 1) + '-' + pageEnd + '">...<img src="../../NorthShoreLeisure/images/search/next.gif" border="0"/></a>';
        }

        if (headerList != null) {
            headerList.innerHTML = pageNoHTML;
        }

        if (footerList != null) {
            footerList.innerHTML = pageNoHTML;
        }
    }
}

function adjustPageRange(pageStart) {
// Called by code written by 'writePageNos' to adjust the page ranges displayed.
    document.forms['frmMetaData'].startPage.value = pageStart;

    writePageNos();
}

function popImg(url, name, width, height, title) {
// Displays the requested URL (image) in a pop-up window.
    var titleBarHeight    = 24;
    var windowBorderWidth = 4;
    var screenWidth       = 800;
    var screenHeight      = 600;

    if (window.screen) {
        if (window.screen.availWidth) {
            // Browser has the appropriate properties we need to centre it
            screenWidth = window.screen.availWidth;
            screenHeight = window.screen.availHeight;
        }
    }

    var windowWidth  = windowBorderWidth + width + windowBorderWidth;
    var windowHeight = titleBarHeight + height + windowBorderWidth;
    var left         = (screenWidth - windowWidth) / 2;
    var top          = (screenHeight - windowHeight) / 2;

    options = 'left=' + left + ',top=' + top + ',screenX=' + left
              + ',screenY=' + top + ',width=' + width + ',height=' + height
              + ',scrollbars=0,resizable=0,toolbar=0,location=0,directories=0,status=0,menubar=0,copyhistory=0';

    myhtml = '<html><head><title>' + title + '</title>';
    myhtml = myhtml + '</head><body bgcolor="white" topmargin="0" leftmargin="0">';
    myhtml = myhtml + '<div style="position:absolute; left:0px; top:0px">';
    myhtml = myhtml + '<img src="../../NorthShoreLeisure/scripts/' + url + '" border="0"></div>';
    myhtml = myhtml + '</p></body></html>';

    if (mywindow) {
        mywindow.close();
    }

    mywindow = window.open( '', name, options);
    mywindow.document.writeln(myhtml);
    mywindow.document.close();
    mywindow.focus();
}

function readCookie(cookieName) {
// Reads the value of the requested cookie, if it exists; otherwise returns "".
    var cookieValue = "";

    if (document.cookie.length > 0) { // If there are cookies present...
        var cookieNameSearch = cookieName + "=";

        var cookieOffset = document.cookie.indexOf(cookieNameSearch);

        if (cookieOffset != -1) {
            cookieOffset += cookieNameSearch.length;

            var cookieEnd = document.cookie.indexOf(";", cookieOffset);

            if (cookieEnd == -1) {
                cookieEnd = document.cookie.length;
            }

            cookieValue = unescape(document.cookie.substring(cookieOffset, cookieEnd));
        }
    }

    return cookieValue;
}

function writeCookie(cookieName, cookieValue, cookieExpiryInHours) {
// Writes the name+value pair to a cookie (with expiry if supplied).
    var cookieExpiryText = "";

    if (cookieExpiryInHours != null) {
        var cookieExpiryDate = new Date((new Date()).getTime() + (cookieExpiryInHours * 3600000)); // Add  to milliseconds

        cookieExpiryText = ";expires=" + cookieExpiryDate.toGMTString();
    }
    document.cookie = cookieName + "=" + escape(cookieValue) + cookieExpiryText;
}

function findObj(objNameOrID, theDoc) {
// Tries to find an object with a name or ID = objNameOrID.
// If objNameOrID is of the form "x?y" then assumes a frame called "x" and
//  an object called "y".
    var p, i, foundObj;

// If objNameOrID has a "?" then extract frame name & set doc to the frame
    if ((p = objNameOrID.indexOf("?")) > 0) {
        if (parent.frames.length > 0) {
            theDoc = parent.frames[objNameOrID.substring(p + 1)].document;
        }
        objNameOrID = objNameOrID.substring(0, p);
    }

// If no document then assume the current document by default
    if (!theDoc) {
        theDoc = document;
    }

// Search by name
    if (!(foundObj = theDoc[objNameOrID]) && theDoc.all) {
        foundObj = theDoc.all[objNameOrID];
    }

// Search all forms by name
    for (i = 0; !foundObj && i < theDoc.forms.length; i++) {
        foundObj = theDoc.forms[i][objNameOrID];
    }

// Search all layers
    for (i = 0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) {
        foundObj = findObj(objNameOrID, theDoc.layers[i].document);
    }

// Search by ID
    if (!foundObj && theDoc.getElementById) {
        foundObj = theDoc.getElementById(objNameOrID);
    }

    return foundObj;
}

function confirmAlert(msg, url) {
	var confirmAlert;
	if (confirm(msg))
	{
	window.open(url, target="_blank");
	}
	return confirmAlert;
}

// Makes elements with id's display or hide
function showHide(id)
{
	
	if (document.getElementById(id).style.display=='block') 
	{
		document.getElementById(id).style.display='none';
	}
	else
	{
		document.getElementById(id).style.display='block';
	}
}

// Dreamweaver popup window script
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
