﻿/*
Contains all javascript logic used in the [LocatieKiezer]
  
ToDo
[25-okt-2010 RLI] Every javascript "class" should have it's own *.js file.
[25-okt-2010 RLI] Gmaps2 should be a class, so we don't have global variabels
[25-okt-2010 RLI] Global functions should go in a seperate helper *.js class file, that should be included in gmaps2.js, gmaps3.js and gmaps4.js

History
[03-mrt-2008 FSE] Creation
[05-feb-2010 RLI] Crossbrowser adjustments
[05-jul-2011 RLI/MVL] IE9 XSLT fix
[06-sep-2011 JST] modified var minMarkerManagerAddZoomLevel = 12; prior number was 13.
*/

/***********************************************************************************************************************************************************/
/*                                                                                                                                                         */
/*                                                                Global Locatiekiezer variables                                                           */
/*                                                                                                                                                         */
/***********************************************************************************************************************************************************/
var bMapMode;
var data;
var errorList;
var searchPoint;
var searchMarker;
var increase = 0; //for adding markers
var bIncludeInitialLocation = false;
var center;
var zoomLevel;
var fireEventZoomLevel = 13;
var theDutchZoomLevel = 7;
var moveTresh = 0.03;
var marginBounds = 0.03;
var locPicker;
var initialPoint;
var theDutch;
var bPanMoved;
var bMarkersWithinBounds = false;
var bInitialSearch = false;
var tempCenter;
var tempZoom;
var minMarkerManagerAddZoomLevel = 12;
var maxMarkerManagerAddZoomLevel = 17;
var bOutOfRange = false;
var startMoveCenter;
var startMoveZoom;
var endMoveCenter;
var endMoveZoom;
var bCanGetMarkers;
var defaultIconPath;
var serverUrl;
var iconServerUrl;
var userAddress;
var bCancel;
var streetView;

/***********************************************************************************************************************************************************/
/*                                                                                                                                                         */
/*                                                          Global General Helper Functions                                                                */
/*              When changed, must be updated in LocatieWijzer\gmaps3.js, LocatieWijzer\gmaps4.js and LocatieKiezer MashUp\gmaps2.js                       */
/*                                                                                                                                                         */
/***********************************************************************************************************************************************************/

/*
Returns a XML document object from a xml string
1. Use type DOMParser, if browser (FF, Safari, Chrome etc. or IE9) supports it
2. Use ActiveXObject [Microsoft.XMLDOM], if browser (IE6, IE7, IE8) supports it
3. Throws an error, when both types are not supported
*/
function GetXmlDocFromXmlString(xmlString) {
    // 1.
    if (typeof (DOMParser) != "undefined") {
        var parser = new DOMParser();
        return parser.parseFromString(xmlString, "text/xml");
    }
    // 2.
    try {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");        
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlString);
        return xmlDoc;
    }
    catch (e) {
        // 3.
        alert("The type [DOMParser] and the ActiveXObject [Microsoft.XMLDOM] are not supported by this browser, can't create XML document!");
        return null;
    }
}

/*
Returns a XML document object from a file path to a XML document
1. Use type XMLHttpRequest, if browser (FF, Safari, Chrome etc) supports it
2. Use ActiveXObject [Microsoft.XMLHTTP], if browser (IE6, IE7, IE8 etc) supports it
3. Throws an error, when both types are not supported
*/
function GetXmlDocFromPath(path) {
    // 1.
    if (typeof (XMLHttpRequest) != "undefined") {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", path, false);
        xhttp.send("");
        return xhttp.responseXML;
    }
    // 2.
    try {
        var mxhttp = new ActiveXObject("Microsoft.XMLHTTP");
        mxhttp.open("GET", path, false);
        mxhttp.send("");
        return mxhttp.responseXML;
    }
    catch (e) {
        // 3.
        alert("The type [XMLHttpRequest] and the ActiveXObject [Microsoft.XMLHTTP] are not supported by this browser, can't create XML document!");
        return null;
    }
}

/*
Returns a xml string from a XML document
1. Use type XMLSerializer, if browser (FF, Safari, Chrome etc) supports it
2. Use property [.xml] on the XmlDocument, if browser (IE6, IE7, IE8 etc) supports it
3. Throws an error, when both types are not supported
*/
function GetXmlStringFromXmlDoc(xmlDoc) {
    // 1.
    if (typeof (XMLSerializer) != "undefined") {
        return new XMLSerializer().serializeToString(xmlDoc);
    }

    // 2.
    if (xmlDoc.xml) {
        return xmlDoc.xml;
    }
    else {
        // 3.
        alert("The type [XMLSerializer] and the property [XmlDocument.xml] are not supported by this browser, can't create xml string!");
        return null;
    }
}

/*
Transforms a XML document to a HTML string by using a XSLT document
1. Use type XSLTProcessor, if browser (FF, Safari, Chrome etc) supports it
2. Use function [transformNode] on the XmlDocument, if browser (IE6, IE7, IE8) supports it
3. Use function transform on the XsltProcessor used for IE9 (which doesn't support [transformNode] any more) 
4. Throws an error, when both types are not supported
*/
function TransformToHtmlText(xmlDoc, xsltDoc) {
    // 1.
    if (typeof (XSLTProcessor) != "undefined") {
        var xsltProcessor = new XSLTProcessor();
        xsltProcessor.importStylesheet(xsltDoc);
        var xmlFragment = xsltProcessor.transformToFragment(xmlDoc, document);
        return GetXmlStringFromXmlDoc(xmlFragment);
    }
    // 2.
    if (typeof (xmlDoc.transformNode) != "undefined") {
        return xmlDoc.transformNode(xsltDoc);
    }
    else {

        try {
            // 3
            if (window.ActiveXObject) {
                var xslt = new ActiveXObject("Msxml2.XSLTemplate");
                var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
                xslDoc.loadXML(xsltDoc.xml);
                xslt.stylesheet = xslDoc;
                var xslProc = xslt.createProcessor();
                xslProc.input = xmlDoc;
                xslProc.transform();

                return xslProc.output;
            }
        }
        catch (e) {
            // 4
            alert("The type [XSLTProcessor] and the function [XmlDocument.transformNode] are not supported by this browser, can't transform XML document to HTML string!");
            return null;
        }

    }
}


/***********************************************************************************************************************************************************/
/*                                                                                                                                                         */
/*                                                                Global Locatiekiezer Functions                                                           */
/*                                                                                                                                                         */
/***********************************************************************************************************************************************************/

/*
Fix for Mozilla to make the event [onkeypress] work and let the event clickButton fire
This event will fire on each keypress on the current page
[25-okt-2010 RLI] Added to the [backlog] for inspection
*/
function stopRkey(evt) {
    var evt = (evt) ? evt : ((event) ? event : null);
    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
    if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
}
document.onkeypress = stopRkey;

/*
Start search when user presses the [Enter] key in the [txtSearch] textbox.
*/
function clickButton(e, buttonId) {
    var evt = e ? e : window.event;
    var buttonToClick = document.getElementById(buttonId);
    if (buttonToClick) {
        if (evt.keyCode == 13) {
            if (buttonToClick.click) {
                buttonToClick.click();
            }
            else {
                Search(document.getElementById('txtSearch').value);
            }
            return false;
        }
    }
}

/*
Shows the given error message, to the user
*/
function ShowNotice(type, message, errorarray) {

    //alert('shownotice' + message);
    var divNotice = locPicker.errorDisplay;
    divNotice.innerHTML = "";

    var divButtonContainer = document.createElement("div");
    divButtonContainer.id = "divButtonContainer";
    divButtonContainer.setAttribute("class", "toprightclosingbutton");

    var btnClose = document.createElement("a");
    btnClose.id = "btnClose";
    btnClose.href = "javascript:CloseErrorDisplay(document.getElementById('" + divNotice.id + "'));";
    divButtonContainer.appendChild(btnClose);
    divNotice.appendChild(divButtonContainer);

    if (!errorarray) {
        divNotice.innerHTML += "<br/>" + message;
    }
    else {
        for (var i = 0; i < errorarray.length; i++) {
            divNotice.innerHTML += "<br/>" + errorarray[i].ErrorMessage;
        }
    }
    divNotice.style.visibility = "visible";
}

/*
Transform the given xml to html
Parameter [style]: transform [detail] or [marker] xml
*/
function TransformXml(sXml, style) {
    var resultHTML;
    var objXML;
    var objXSL;
    try {

        objXML = GetXmlDocFromXmlString(sXml);

        if (style == "detail") {
            objXSL = GetXmlDocFromPath("xslt/locationDetail.xslt");
        }
        else if (style == "marker") {
            objXSL = GetXmlDocFromPath("xslt/locationMarker.xslt");
        }

        resultHTML = TransformToHtmlText(objXML, objXSL);
    }
    catch (e) {
        ShowNotice(23001, "Er heeft zich een fout voorgedaan in de functie 'TransformXml'");
    }
    return resultHTML;
}

/*
Always adds "nederland" to the query string
*/
function CheckCountry(oAddress) {
    oAddress = oAddress.toLowerCase();
    var countryIncluded = oAddress.match(/nederland/g);
    if (!countryIncluded) {
        oAddress += ' Nederland';
    }
    return oAddress;
}

/*
Parse the result from the NL.ADA.TPG.Lokatiekiezer.ServiceInterface.LocatieKiezerWS.GetLocationsFromAddress function
*/
function ParseResult(result) {
    try {
        var oXml = GetXmlDocFromXmlString(result);
        locationList = oXml.documentElement.getElementsByTagName("Location");
        errorList = oXml.documentElement.getElementsByTagName("ErrorData");

        iconServerUrl = oXml.documentElement.getAttribute("iconServerUrl");
        if (oXml.documentElement.getAttribute("iconCustomServerUrl") != null && oXml.documentElement.getAttribute("iconCustomServerUrl") != undefined) {
            iconCustomServerUrl = oXml.documentElement.getAttribute("iconCustomServerUrl");
        }

        defaultIconPath = oXml.documentElement.getAttribute("defaultIconUrl");
        serverUrl = oXml.documentElement.getAttribute("serverUrl");

        var errors = [];
        if (errorList.length > 0) {
            for (var i = 0; i < errorList.length; i++) {
                errors[i] = new ErrorData(errorList[i].getElementsByTagName("ErrorCode")[0].firstChild.nodeValue, errorList[i].getElementsByTagName("ErrorMessage")[0].firstChild.nodeValue);
            }
            throw new Error();
        }

        if (!bMapMode) {
            if (locationList.length === 0) {
                errors[0] = new ErrorData(23002, "  Er zijn helaas geen locaties gevonden voor dit adres.");
                throw new Error();
            }
        }
    }
    catch (e) {
        ShowNotice(null, e.message, errors);
    }

    for (var j = 0; j < locationList.length; j++) {
        var locationTypeId = locationList[j].getElementsByTagName("LocationTypeId")[0].firstChild.nodeValue;
        var point;
        var iconPath;
        var isCustomerLocation = 'false';

        if (bMapMode) {
            var foundLatLng = new GLatLng();
            foundLatLng.lat = parseFloat(locationList[j].getAttribute("lat"));
            foundLatLng.lng = parseFloat(locationList[j].getAttribute("lng"));

            if (locationList[j].getAttribute("IsCustomerLocation")) {
                isCustomerLocation = locationList[j].getAttribute("IsCustomerLocation");
            }

            point = new GPoint(foundLatLng.lng, foundLatLng.lat);
            if (locationList[j].getElementsByTagName("IconPath")[0].firstChild != null && locationList[j].getElementsByTagName("IconPath")[0].firstChild != undefined) {
                iconPath = locationList[j].getElementsByTagName("IconPath")[0].firstChild.nodeValue;
            }

            //Uncommented the if statement. For now, always use the TNT crown.
            //if (!iconPath || iconPath == "undefined")
            //{
            if (isCustomerLocation == 'false') {
                iconPath = iconServerUrl + defaultIconPath;
            }
            else {
                iconPath = iconCustomServerUrl + iconPath;
            }
            //}
        }
        else {
            iconPath = null;
            point = null;
        }

        var bDisplay = true;
        var locationXml = GetXmlStringFromXmlDoc(locationList[j]);
        var name;
        var city;

        if (locationList[j].getElementsByTagName("Name")[0].firstChild != null && locationList[j].getElementsByTagName("Name")[0].firstChild != undefined) {
            name = locationList[j].getElementsByTagName("Name")[0].firstChild.nodeValue;
        }

        if (locationList[j].getElementsByTagName("City")[0].firstChild != null && locationList[j].getElementsByTagName("City")[0].firstChild != undefined) {
            city = locationList[j].getElementsByTagName("City")[0].firstChild.nodeValue;
        }

        var foundMarker = locPicker.createMarker(point, name, city, "test", locationXml, locPicker.showDetailInfo, true, locationTypeId, iconPath);
    }
}

/*
Get all locations from the given address
Is used to call the [WebService] function: NL.ADA.TPG.Lokatiekiezer.ServiceInterface.LocatieKiezerWS.GetLocationsFromAddress
Used by the [Default2.aspx] to find [Locations] from a given address. 
The given address street should contain a location, else no entries are returned.
*/
function GetLocationsFromAddress(callBackSuccess, callBackFail) {
    locPicker.Loader.style.display = "block";
    locPicker.initialize();

    var openingHoursSpanCollection = "";
    if (this.Filter.IsActive()) {
        openingHoursSpanCollection = this.Filter.getDay() + ';' + this.Filter.getOpeningHour() + ';' + this.Filter.getCloseHour();
    }


    NL.ADA.TPG.Lokatiekiezer.ServiceInterface.LocatieKiezerWS.GetLocationsFromAddressOH
    (
        userAddress,
        openingHoursSpanCollection,
        data.apiKey,
        data.productLabel,

        function (result) {
            ParseResult(result);
            callBackSuccess("locationsFromAddress");
        },

        function (error) {
            if (error !== null) {
                ShowNotice(23003, "Er is een fout opgetreden in de functie 'GetLocationsFromAddress'");
            }
            callBackFail("locationsFromAddress");
        }
    );
}

/*
Is used by the [Default.aspx], to show all locations within bounds of the given address
It will return [Locations] even if the [Locations] are not in the same street.
Is used to call the [WebService] function: NL.ADA.TPG.Lokatiekiezer.ServiceInterface.LocatieKiezerWS.GetLocationsWithinBounds
*/
function GetMarkersWithinBounds(callBackSuccess, callBackFail) {
    locPicker.Loader.style.display = "block";
    var bounds = locPicker.map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var mapCenter = locPicker.map.getCenter();
    var cLat = mapCenter.y;
    var cLng = mapCenter.x;
    var swLat = southWest.lat() - marginBounds;
    var swLng = southWest.lng() - marginBounds;
    var neLat = northEast.lat() + marginBounds;
    var neLng = northEast.lng() + marginBounds;
    var openingHoursSpanCollection = "";
    if (this.Filter.IsActive()) {
        openingHoursSpanCollection = this.Filter.getDay() + ';' + this.Filter.getOpeningHour() + ';' + this.Filter.getCloseHour();
    }

    NL.ADA.TPG.Lokatiekiezer.ServiceInterface.LocatieKiezerWS.GetLocationsWithinBoundsOrdered_simpleOH
    (
        cLat,
        cLng,
        swLat,
        swLng,
        neLat,
        neLng,
        openingHoursSpanCollection,
        data.apiKey,
        data.productLabel,
    //succeeded:    
        function (result) {
            ParseResult(result);
            callBackSuccess("markersWithinBounds");
        }

    //failed:
        , function (error) {
            if (error !== null) {
                //hier was ik gebleven. bij dragging treedt er een fout op. DB error max value overschreden param name Query??? of zoiets
                ShowNotice(23004, "Er is een fout opgetreden in de functie 'GetMarkersWithinBounds'");
            }
            callBackFail("markersWithinBounds");
        }
    );
}

/*
[25-okt-2010 RLI] Added to [Backlog] for deletion
*/
function SetPannedTrue() {
    bPanMoved = true;
}

/* 
Refresh the google maps chart 
*/
function UpdateDisplay(center, zoomLevel) {

    if (center) {
        tempCenter = center;
        if (zoomLevel) {
            tempZoom = zoomLevel;
            locPicker.map.setCenter(tempCenter, tempZoom);
        } else {
            locPicker.map.setCenter(tempCenter);
        }
    }

    locPicker.manager.addMarkers(locPicker.displayMarkers, minMarkerManagerAddZoomLevel, maxMarkerManagerAddZoomLevel);
    locPicker.manager.refresh();
}

/*
Set zoomlevel and center to "The Netherlands" for the google map
*/
function ShowHolland(point, address) {

    locPicker.initialize();
    searchMarker = locPicker.createMarker(point, "found", null, address, null, locPicker.showDetailInfo, bIncludeInitialLocation, null, null);
    center = searchMarker.marker.getLatLng();

    if (bCanGetMarkers) {
        locPicker.map.setCenter(center, theDutchZoomLevel);
    }

    Succeeded("initialSearchNoAddress");
}

/*
Is the entrypoint for showing locations based on the user input.
- Hide StreetView
*/
function Search(oAddress) {
    if (locPicker) {
        locPicker.hideStreetView();
    }
    if (oAddress) {
        if (locPicker.Filter.isValid()) {
            locPicker.Loader.style.display = "block";
            bInitialSearch = false;
            if (bMapMode) {
                locPicker.findPointFromAddress(CheckCountry(oAddress), SucceededSearch);
                locPicker.Loader.style.display = "none";
            } else {
                userAddress = oAddress;
                locPicker.getLocations(Succeeded, Failed);
            }
        } else {
            ShowNotice(23008, "Opgegeven begintijd mag niet groter of gelijk zijn aan  eindtijd");
        }
    }
}

/* Close error message DIV */
function CloseErrorDisplay(element) {
    if (element.style.visibility == "visible") {
        element.style.visibility = "hidden";
        locPicker.Loader.style.display = "none";
    }
}

/* Reset the google map to the center of the Netherlands */
function Reset() {
    if (bMapMode) {
        ShowHolland(new GPoint(5.642743, 52.212400), "centrum nederland");
    }
    document.getElementById("txtSearch").value = "";
}


/* 
Executes when a users clicks on a link in the sidebar
- Hide streetview
- Click on marker
*/
function SidebarClick(i) {
    locPicker.hideStreetView();
    if (bMapMode) {
        try {
            GEvent.trigger(locPicker.locations[i].marker, "click");
        }
        catch (e) {
            //TODO:error
        }
    }
    else {
        locPicker.showDetailInfo(locPicker.locations[i].resultDetailHTML)
    }
}

/* Fires when the page loads and initialises the google map */
function start(urlPassedData, mode) {
    try {
        //common:
        if ((mode != undefined) && (mode === "gmaps")) {
            bMapMode = true;
        }
        else {
            bMapMode = false;
        }

        data = new UrlPassedData(urlPassedData);

        //with google maps:
        if (bMapMode) {
            try {

                theDutch = new GLatLng(52.212400, 5.642743);
                locPicker = new LocPicker(document.getElementById("divSideBar"),
                                        document.getElementById("divDetailInfo"),
                                        document.getElementById("divMap"),
                                        document.getElementById("divNotice"),
                                        document.getElementById("divSearchOptions"),
                                        document.getElementById("divLoader"),
                                        document.getElementById("divStreetView"));

                if (GBrowserIsCompatible()) {

                    if (data.address) {
                        locPicker.findPointFromAddress(data.get_address(), SucceededSearch);
                    }
                    else {
                        ShowHolland(new GPoint(5.642743, 52.212400), "centrum nederland");
                    }
                }
                else {
                    throw new Error("Sorry, uw browser is niet compatible met Google Maps");
                }
            }
            catch (e) {
                var qs = window.location.search;
                window.location = "Default2.aspx" + qs;
            }
        }
        else {
            //without google maps:
            locPicker = new LocPicker(document.getElementById("divSideBar"),
                                    document.getElementById("divDetailInfo"),
                                    null,
                                    document.getElementById("divNotice"),
                                    document.getElementById("divSearchOptions"),
                                    document.getElementById("divLoader"));
            locPicker.initialize();
            if (data.address) {
                Search(data.get_address());
            }
        }
    }
    catch (e) {
        ShowNotice(23005, "Er is een fout opgetreden in de functie 'Start'");
    }
}

/* Uses regular expressions to find start and end of string and then trims the string */
function trim(value) {
    value = value.replace(/^\s+/, '');
    value = value.replace(/\s+$/, '');
    return value;
}

/* Validate if address information is correct and complete */
function ConfirmAddress() {
    try {
        var name = trim(document.getElementById("tempName").innerHTML);
        var street = trim(document.getElementById("tempStreet").innerHTML);
        var houseNumber = trim(document.getElementById("tempHouseNumber").innerHTML);
        var houseNumberAdditional = trim(document.getElementById("tempHouseNumberAdditional").innerHTML);
        var postalCodeNumeric = trim(document.getElementById("tempPostalCodeNumeric").innerHTML);
        var postalCodeAlpha = trim(document.getElementById("tempPostalCodeAlpha").innerHTML);
        var city = trim(document.getElementById("tempCity").innerHTML);
        var locationType = trim(document.getElementById("tempLocationType").innerHTML);
        var productCode;

        if (bCancel) {
            productCode = "0000";
        } else {
            productCode = trim(document.getElementById("tempProductCode").innerHTML);
        }
        if (name && street && houseNumber && postalCodeNumeric && productCode) {

            //FF (name doesn't get parsed correctly)
            if (name.startsWith('<')) {
                // transformation didn't succeed
                throw new Error("het adres is niet compleet");
            }

            var passDataQuery = "?";
            passDataQuery += "name=" + escape(locationType + '&nbsp;&nbsp;' + name);
            passDataQuery += "&locationType=" + escape(locationType);
            passDataQuery += "&street=" + escape(street);
            passDataQuery += "&housenumber=" + houseNumber;
            passDataQuery += "&housenumberadd=" + houseNumberAdditional;
            passDataQuery += "&postalcodenum=" + postalCodeNumeric;
            passDataQuery += "&postalcodealpha=" + postalCodeAlpha;
            passDataQuery += "&city=" + escape(city);
            passDataQuery += "&productcode=" + productCode;
            passDataQuery += "&action=confirm";
            CallPassData(data.passDataUrl, passDataQuery);

        } else {
            throw new Error("het adres is niet compleet");
        }
    }
    catch (e) {
        ShowNotice(23006, "Het adres is niet volledig ingevuld.");
    }
}

/* Close the popup */
function ClosePopup() {
    CallPassData(data.passDataUrl, "?action=close");
}

/* Pass data to popup */
function CallPassData(dataUrl, dataQuery) {
    var divPassData = document.getElementById("divPassData");
    var uri = dataUrl + dataQuery; //encodeURI( dataUrl + dataQuery );
    divPassData.innerHTML =
    "<iframe id='iFramePassData' name='iFramePassData' style='display:none' src='" +
     uri + "' />";
}

/* Close the popup: [26-okt-2010 RLI] Added to the backlog for deletion */
function Cancel() {
    ClosePopup();
}

/***********************************************************************************************************************************************************/
/*                                                                                                                                                         */
/*                                                           Class [LocatieKiezer].[ErrorData]                                                             */
/*                                                                                                                                                         */
/***********************************************************************************************************************************************************/
function ErrorData(code, message) {
    this.ErrorCode = code;
    this.ErrorMessage = message;
}

/***********************************************************************************************************************************************************/
/*                                                                                                                                                         */
/*                                                           Class [LocatieKiezer].[LocFilter]                                                             */
/*                                                              Is used to filter locations                                                                */
/*                                                                                                                                                         */
/***********************************************************************************************************************************************************/
function LocFilter(filterElement) {
    this.OpeningHourFilter = document.getElementById("OpenDropDownList");
    this.ClosingHourFilter = document.getElementById("CloseDropDownList");
    this.DayFilter = document.getElementById("DayDropDownList");
    this.CheckBoxFilter = document.getElementById("filterCheckBox");
    this.initialize();
}

LocFilter.prototype = {

    initialize: function () {
        document.getElementById("divSearchOptionsContainer").disabled = true;
        this.CheckBoxFilter.onclick = function () {
            document.getElementById("divSearchOptionsContainer").disabled = !this.checked;
        };
    },

    getDay: function () {
        return this.DayFilter.options[this.DayFilter.selectedIndex].value;
    },
    getOpeningHour: function () {
        return this.OpeningHourFilter.options[this.OpeningHourFilter.selectedIndex].text;
    },
    getCloseHour: function () {
        return this.ClosingHourFilter.options[this.ClosingHourFilter.selectedIndex].text;
    },
    isValid: function () {
        var openingHour = this.getOpeningHour().replace(":", "");
        var closeHour = this.getCloseHour().replace(":", "");
        if (openingHour.indexOf("0") == 0) {
            openingHour = openingHour.substr(1);
        }
        if (closeHour.indexOf("0") == 0) {
            closeHour = closeHour.substr(1);
        }

        var openValue = parseInt(openingHour);
        var closeValue = parseInt(closeHour);

        if (openValue >= closeValue) {
            return false;
        } else {
            return true;
        }
    },
    IsActive: function () {
        return this.CheckBoxFilter.checked == true;
    }
};

/***********************************************************************************************************************************************************/
/*                                                                                                                                                                           */
/*                                                           Class [LocatieKiezer].[UrlPassedData]                                                         */
/*                                                              Convert data from QueryString to this class                                                                     */
/*                                                                                                                                                                                                   */
/***********************************************************************************************************************************************************/
function UrlPassedData(data) {
    this.productLabel = data[0];
    if (bMapMode) {
        if (data[1] != "") {
            this.address = CheckCountry(data[1]);
        }
    }
    else {
        this.address = data[1];
    }
    this.apiKey = data[2];
    this.styleSheet = data[3];
    this.passDataUrl = data[4];

}

UrlPassedData.prototype = {

    get_address: function () { return this.address; },
    set_address: function (oAddress) { this.address = CheckCountry(oAddress); }
};

/***********************************************************************************************************************************************************/
/*                                                                                                                                                         */
/*                                                           Class [LocatieKiezer].[LocMarker]                                                             */
/*                                                              A marker on the Google map                                                                 */
/*                                                                                                                                                         */
/***********************************************************************************************************************************************************/
//global marker counter [26-okt-20110 RLI] Added to the backlog for refactoring
var i = 0;
function LocMarker(point, name, city, html, xml, detailInfoCallBack, locationTypeId, iconPath) {
    if (bMapMode) {
        this.markerIcon = new GIcon();
        this.markerIcon.image = iconPath;
        this.markerIcon.iconSize = new GSize(30, 30);
        this.markerIcon.shadowSize = new GSize(40, 34);
        this.markerIcon.iconAnchor = new GPoint(9, 34);
        this.markerIcon.infoWindowAnchor = new GPoint(9, 2);
        this.markerIcon.infoShadowAnchor = new GPoint(18, 25);
        this.markerOptions = { icon: this.markerIcon };
        this.marker = new GMarker(point, this.markerOptions);
        this.iconPath = iconPath;
        this.point = point;
    }
    this.name = name;
    this.city = city;
    this.html = html;
    this.xml = xml;
    this.resultMarkerHtml = "";
    this.resultDetailHTML = "";
    this.locationType = locationTypeId;
    this.id = i;
    this.detailInfoCallBack = detailInfoCallBack;

    if (this.xml !== undefined && this.xml !== null) {
        this.resultMarkerHTML = TransformXml(this.xml, "marker");
        this.resultDetailHTML = TransformXml(this.xml, "detail");
    } else {
        this.resultMarkerHTML = this.html;
        this.resultDetailHTML = this.html;
    }

}

/***********************************************************************************************************************************************************/
/*                                                                                                                                                         */
/*                                                           Class [LocatieKiezer].[LocPicker]                                                             */
/*                                               Is used to show information from a location in a balloon                                                  */
/*                                                                                                                                                         */
/***********************************************************************************************************************************************************/
function LocPicker(oSideBarElement, oDetailInfoElement, oMapElement, oErrorElement, oFilterElement, oLoaderElement, oStreetViewElement) {
    this.xml = "";
    this.sideBarDisplay = oSideBarElement;
    this.detailInfoDisplay = oDetailInfoElement;
    this.streetViewDisplay = oStreetViewElement;
    this.mapDisplay = oMapElement;
    this.streetViewObject = null;
    this.errorDisplay = oErrorElement;
    if (bMapMode) {
        this.getLocations = GetMarkersWithinBounds;
        this.map = new GMap2(this.mapDisplay);
        this.map.addControl(new GLargeMapControl());
        this.map.addControl(new GMapTypeControl());
        this.map.enableScrollWheelZoom();
        this.map.setCenter(theDutch, 7);
        this.manager = new MarkerManager(this.map);
        this.initialPoint = new GPoint();
        // google maps events:
        GEvent.addListener(this.map, "zoomend", function (levelOld, levelNew) {
            tempZoom = levelNew;
            if (bInitialSearch && (levelNew == fireEventZoomLevel) && (levelNew > levelOld)) {
                center = locPicker.map.getCenter();
                if (bCanGetMarkers) {
                    locPicker.initialize();
                    locPicker.getLocations(Succeeded, Failed);
                }
            }
        }
        );

        GEvent.addListener(this.map, "dragstart", function () {
            if (!bOutOfRange && (tempZoom >= fireEventZoomLevel)) {
                startMoveCenter = locPicker.map.getCenter();
                bOutOfRange = true;
            }
        }
        );

        GEvent.addListener(this.map, "dragend", function () {
            if (tempZoom >= fireEventZoomLevel) {
                endMoveCenter = locPicker.map.getCenter();
                if (startMoveCenter && endMoveCenter) {
                    if (CheckMove(startMoveCenter, endMoveCenter)) {
                        locPicker.initialize();
                        locPicker.getLocations(Succeeded, Failed);
                        bOutOfRange = false;
                    }
                }
            }

        }
        );

    }
    else {
        this.getLocations = GetLocationsFromAddress;
    }

    this.ShowNotice = ShowNotice;
    this.search = Search;
    this.locations = [];
    this.displayMarkers = [];

    if (oFilterElement) {
        this.Filter = new LocFilter(oFilterElement);
    }

    if (oLoaderElement) {
        this.Loader = oLoaderElement;
    }

    function CheckMove(oldCenter, newCenter) {
        var result = false;
        if (oldCenter && newCenter) {
            var latDiff = oldCenter.lat() - newCenter.lat();
            var lngDiff = oldCenter.lng() - newCenter.lng();
            if ((Math.abs(latDiff) > moveTresh) ||
                (Math.abs(lngDiff) > moveTresh)) {
                result = true;
            } else {
                result = false;
            }
        }
        return result;
    }
}

LocPicker.prototype = {
    findPointFromAddress: function (oAddress, callBack) {
        var geocoder = new GClientGeocoder();
        searchPoint = new GPoint();
        if (oAddress) {
            if (geocoder) {
                geocoder.getLatLng(
                  oAddress,
                   function (point) {
                       try {

                           if (!point) {
                               throw new Error("Het door u ingevulde adres:'" + oAddress + "' is niet gevonden.");
                           } else {

                               callBack(point, oAddress);
                           }

                       } catch (e) {
                           ShowNotice(23007, e.message);
                       }
                   });
            }
        }

    },
    initialize: function () {
        if (bMapMode) {
            this.manager.clearMarkers();
            center = null;
        }
        increase = 0;
        this.locations = [];
        this.displayMarkers = [];
        this.sideBarDisplay.innerHTML = "";
        this.detailInfoDisplay.innerHTML = "";
        bMarkersWithinBounds = false;
        bCanGetMarkers = true;
        searchMarker = null;
        document.getElementById("btnSelectLocation").style.display = "none";
    },

    filter: function () {
        if (bCanGetMarkers) {
            if (locPicker.locations.length > 0) {
                locPicker.initialize();
                locPicker.getLocations(Succeeded, Failed);
            }
        }
    },
    showDetailInfo: function (html) {
        locPicker.detailInfoDisplay.innerHTML = html;
        if (locPicker.detailInfoDisplay.innerHTML !== "") {
            document.getElementById("btnSelectLocation").style.display = "block";
        }
    },

    /* 
    Show the given location in StreetView
    - Show back to google maps link
    - Show streetview container
    - Hide google maps container
    - Resize flash object to the streetview container
    */
    showStreetView: function (lat, lng) {
        locPicker.backToMapsLink = document.getElementById('backToMapsLink');
        locPicker.panoflash1 = document.getElementById('panoflash1');

        if (locPicker.backToMapsLink != null) { locPicker.backToMapsLink.style.display = 'block'; }
        if (locPicker.streetViewDisplay != null) { locPicker.streetViewDisplay.style.display = 'block' };
        if (locPicker.mapDisplay != null) { locPicker.mapDisplay.style.display = 'none' };
        if (locPicker.panoflash1 != null) { locPicker.panoflash1.style.width = '100%' };
        locPicker.streetViewObject.checkResize();
    },

    /*
    Hides StreetView, by showing the google maps chart and hiding the backToMapsLink
    */
    hideStreetView: function () {
        locPicker.backToMapsLink = document.getElementById('backToMapsLink');

        if (locPicker.streetViewDisplay != null) { locPicker.streetViewDisplay.style.display = 'none'; }
        if (locPicker.mapDisplay != null) { locPicker.mapDisplay.style.display = 'block'; }
        if (locPicker.backToMapsLink != null) { locPicker.backToMapsLink.style.display = 'none'; }
    },

    /*
    Hide the streetview link in the balloon, when streetview is not available on that location
    */
    hideStreetViewLink: function (point) {
        // Reset streetview objects to prevent Safari bug
        locPicker.streetViewDisplay.innerHTML = '';
        locPicker.streetViewObject = null;

        var locationToShow = new GLatLng(point.y, point.x);
        panoramaOptions = { latlng: locationToShow };
        locPicker.streetViewObject = new GStreetviewPanorama(locPicker.streetViewDisplay, panoramaOptions);
        GEvent.addListener(locPicker.streetViewObject, "error",
            function (errorCode) {
                if (errorCode == 603) {
                    alert("Error: Flash doesn't appear to be supported by your browser");
                    return;
                }
                if (errorCode != null) {
                    document.getElementById('showInStreetViewLink').style.display = 'none';
                }
            }
        );
    },
    createMarker: function (point, name, city, html, xml, callBack, display, locationTypeId, iconPath) {
        var result = new LocMarker(point, name, city, html, xml, callBack, locationTypeId, iconPath);
        if (display === true) {
            if (bMapMode) {
                GEvent.addListener(result.marker, "click",
                /*
                Event Fires when user clicks on the marker [TNT Crown] in google maps.
                - Show the balloon
                - Show the detail information below map area
                - Hide the [showInStreetViewLink], when no streetview is available
                */
                function () {
                    result.marker.openInfoWindowHtml(result.resultMarkerHTML);
                    result.detailInfoCallBack(result.resultDetailHTML);
                    locPicker.hideStreetViewLink(point);
                });
            }
            locPicker.locations[increase] = result;
            locPicker.displayMarkers[increase] = result.marker;
            if (bMapMode) {
                locPicker.sideBarDisplay.innerHTML += '<a href="javascript:SidebarClick(' + increase + ')">' + '<div name="sidebarLinkContainer" class="sidebarlinkcontainer">' + result.name + '</div></a>';
            }
            else {
                locPicker.sideBarDisplay.innerHTML += '<a href="javascript:SidebarClick(' + increase + ')">' + '<div name="sidebarLinkContainer" class="sidebarlinkcontainer"><div class="sidebarlinkleftcolumn">' + result.name + '</div><div class="sidebarlinkrightcolumn">' + result.city + '</div></div></a>';
            }
            increase++;
        }
        return result;
    }

};

/*
Callback for the [Succeeded] locPicker.getLocations function
[25-okt-2010 RLI] Added to the [Backlog] to be included in LocPicker.prototype
*/
function Succeeded(from) {
    if (from === "markersWithinBounds") {
        bMarkersWithinBounds = true;
        UpdateDisplay(locPicker.map.getCenter());
        locPicker.Loader.style.display = "none";

    }
    if (from === "initialSearch") {
        bInitialSearch = true;
        UpdateDisplay(locPicker.map.getCenter(), fireEventZoomLevel);
    }

    if (from === "initialSearchNoAddress") {
        bInitialSearch = true;
        UpdateDisplay(locPicker.map.getCenter(), theDutchZoomLevel);
    }


    if (from === "locationsFromAddress") {
        locPicker.Loader.style.display = "none";
    }
}

/*
Callback for the [Succeeded] locPicker.getLocations function
[25-okt-2010 RLI] Added to the [Backlog] to be included in LocPicker.prototype
*/
function Failed(from) {

    switch (from) {
        case "markersWithinBounds": bMarkersWithinBounds = false;
        case "initialSearch": bInitialSearch = false;
        case "locationsFromAddress": { };
    }
    UpdateDisplay();
}

/*
Callback for the [Succeeded] locPicker.findPointFromAddress function
[25-okt-2010 RLI] Added to the [Backlog] to be included in LocPicker.prototype
*/
function SucceededSearch(point, address) {
    locPicker.initialize();
    searchMarker = locPicker.createMarker(point, "found", null, address, null, locPicker.showDetailInfo, bIncludeInitialLocation, null, null);
    center = searchMarker.marker.getLatLng();

    if (bCanGetMarkers) {
        locPicker.map.setCenter(center, fireEventZoomLevel);
        locPicker.getLocations(Succeeded, Failed);
    }

    Succeeded("initialSearch");
}

