﻿

/*

Contains all javascript logic used in the Locatiekiezer
  
History
03-03-2008 F. Senden  Creation
05-02-2010 R. Lisdonk Crossbrowser adjustments

*/


/**********************************************************************************************************************/
/*                                            Global 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 = 13;
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;


/**************************************************************************************************************************/
/*                                            Generic 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
*/
function GetXmlDocFromXmlString(xmlString) {
    // Use type DOMParser, if browser (FF, Safari, Chrome etc) supports it
    if (typeof (DOMParser) != "undefined") {
        var parser = new DOMParser();
        return parser.parseFromString(xmlString, "text/xml");
    }

    // Use ActiveXObject [Microsoft.XMLDOM], if browser (IE6, IE7, IE8 etc) supports it
    try {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlString);
        return xmlDoc;
    } catch (e) {
        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
*/
function GetXmlDocFromPath(path) {
    // Use type XMLHttpRequest, if browser (FF, Safari, Chrome etc) supports it
    if (typeof (XMLHttpRequest) != "undefined") {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", path, false);
        xhttp.send("");
        return xhttp.responseXML;
    }

    // Use ActiveXObject [Microsoft.XMLHTTP], if browser (IE6, IE7, IE8 etc) supports it
    try {
        var mxhttp = new ActiveXObject("Microsoft.XMLHTTP");
        mxhttp.open("GET", path, false);
        mxhttp.send("");
        return mxhttp.responseXML;
    } catch (e) {
        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
*/
function GetXmlStringFromXmlDoc(xmlDoc) {
    // Use type XMLSerializer, if browser (FF, Safari, Chrome etc) supports it
    if (typeof (XMLSerializer) != "undefined") {
        return new XMLSerializer().serializeToString(xmlDoc);
    }

    // Use property [.xml] on the XmlDocument, if browser (IE6, IE7, IE8 etc) supports it
    if (xmlDoc.xml) {
        return xmlDoc.xml;
    }
    else {
        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
*/
function TransformToHtmlText(xmlDoc, xsltDoc) {
    // Use type XSLTProcessor, if browser (FF, Safari, Chrome etc) supports it
    if (typeof (XSLTProcessor) != "undefined") {
        var xsltProcessor = new XSLTProcessor();
        xsltProcessor.importStylesheet(xsltDoc);
        var xmlFragment = xsltProcessor.transformToFragment(xmlDoc, document);
        return GetXmlStringFromXmlDoc(xmlFragment);
    }

    // Use function [transformNode] on the XmlDocument, if browser (IE6, IE7, IE8 etc) supports it
    if (typeof (xmlDoc.transformNode) != "undefined") {
        return xmlDoc.transformNode(xsltDoc);
    }
    else {
        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;
    }
}







/**********************************************************************************************************************/
/*                                            Locatiekiezer Specific Functions                                        */
/**********************************************************************************************************************/


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;


//setting searchbutton default:
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;
        }
    }
}


function ShowNotice(type, message, errorarray) {
    var divNotice = locPicker.errorDisplay;
    var divNoticeBottom = document.createElement("div");
    divNoticeBottom.id = "divNoticeBotom";
    var btnClose = document.createElement("a");

    btnClose.id = "btnClose";
    btnClose.href = "javascript:CloseErrorDisplay(document.getElementById('" + divNotice.id + "'));";
    btnClose.appendChild(document.createTextNode("ok"));

    divNotice.innerHTML = "";
    if (!errorarray) {
        divNotice.innerHTML += "<br/>" + message;
        divNotice.innerHTML += "<br/>error code: " + type;
    } else {
        for (var i = 0; i < errorarray.length; i++) {
            divNotice.innerHTML += "<br/>" + errorarray[i].ErrorMessage;
            divNotice.innerHTML += "<br/>error code: " + errorarray[i].ErrorCode;
        }
    }
    divNotice.style.visibility = "visible";
    divNoticeBottom.appendChild(btnClose);
    divNotice.appendChild(divNoticeBottom)
}


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);
        //alert(resultHTML);
    }
    catch (e) {
        ShowNotice(3333, error.message);
    }
    return resultHTML;
}


function CheckCountry(oAddress) {
    oAddress = oAddress.toLowerCase();
    var countryIncluded = oAddress.match(/nederland/g);
    if (!countryIncluded) {
        oAddress += ' nederland';
    }
    return oAddress;
}


function ErrorData(code, message) {
    this.ErrorCode = code;
    this.ErrorMessage = message;
}


function LocFilter(filterElement) {
    this.WeekendCheckBox = document.getElementById("chkWeekend");
    this.EveningCheckBox = document.getElementById("chkEvening");
    this.initialize();

}

LocFilter.prototype = {

    initialize: function() {
        this.WeekendCheckBox.checked = false;
        this.EveningCheckBox.checked = false;
    },
    filter: function() {
    },
    isEvening: function() {
        var result = 0;
        if (this.EveningCheckBox.checked) {
            result = 1;
        }
        return result;
    },
    isWeekend: function() {
        var result = 0;
        if (this.WeekendCheckBox.checked) {
            result = 1;
        }
        return result;

    }
};



function ParseResult(result) {
    try {
        var oXml = GetXmlDocFromXmlString(result);
        locationList = oXml.documentElement.getElementsByTagName("Location");
        errorList = oXml.documentElement.getElementsByTagName("ErrorData");

        iconServerUrl = oXml.documentElement.getAttribute("iconServerUrl");
        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(224, " 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;
        if (bMapMode) {

            var foundLatLng = new GLatLng();
            foundLatLng.lat = parseFloat(locationList[j].getAttribute("lat"));
            foundLatLng.lng = parseFloat(locationList[j].getAttribute("lng"));

            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;
            }
            //if (!iconPath || iconPath == "undefined"){
            //uncommented the if statement. For now, always use the TNT crown.  
            iconPath = defaultIconPath;
            //}


        } 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);

    }

}
function GetLocationsFromAddress(callBackSuccess, callBackFail) {
    locPicker.Loader.style.display = "block";
    locPicker.initialize();
    var ws_bWeekend = locPicker.Filter.isWeekend();
    var ws_bEvening = locPicker.Filter.isEvening();

    NL.ADA.TPG.Lokatiekiezer.ServiceInterface.LocatieKiezerWS.GetLocationsFromAddress(userAddress, ws_bWeekend, ws_bEvening, data.apiKey, data.productLabel,

        function(result) {
            ParseResult(result);
            callBackSuccess("locationsFromAddress");
        },

        function(error) {
            if (error !== null) {
                ShowNotice(2222, error.message);
            }
            callBackFail("locationsFromAddress");
        });


}

function GetMarkersWithinBounds(callBackSuccess, callBackFail) {
    locPicker.Loader.style.display = "block";
    var bounds = locPicker.map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();

    var ws_bWeekend = locPicker.Filter.isWeekend();
    var ws_bEvening = locPicker.Filter.isEvening();

    var wsLatLngSW = new NL.ADA.TPG.Lokatiekiezer.ServiceInterface.LatLngClient();
    wsLatLngSW.LatValue = southWest.lat() - marginBounds;
    wsLatLngSW.LngValue = southWest.lng() - marginBounds;

    var wsLatLngNE = new NL.ADA.TPG.Lokatiekiezer.ServiceInterface.LatLngClient();
    wsLatLngNE.LatValue = northEast.lat() + marginBounds;
    wsLatLngNE.LngValue = northEast.lng() + marginBounds;


    NL.ADA.TPG.Lokatiekiezer.ServiceInterface.LocatieKiezerWS.GetLocationsWithinBounds(wsLatLngSW, wsLatLngNE, ws_bWeekend, ws_bEvening, data.apiKey, data.productLabel,

    //succeeded:    
        function(result) {
            ParseResult(result);
            callBackSuccess("markersWithinBounds");
        }

    //failed:
        , function(error) {
            if (error !== null) {
                ShowNotice(49494, error.message);
            }
            callBackFail("markersWithinBounds");
        });
}


function SetPannedTrue() {
    bPanMoved = true;
}

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); }
};


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();
}

function UpdateDisplayNoMap() {



}

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";
        UpdateDisplayNoMap();

    }

}

function Failed(from) {

    switch (from) {
        case "markersWithinBounds": bMarkersWithinBounds = false;
        case "initialSearch": bInitialSearch = false;
        case "locationsFromAddress": { };
    }
    UpdateDisplay();
}


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");

}

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);
        //          locPicker.getLocations(Succeeded,Failed);
    }

    Succeeded("initialSearchNoAddress");

}
function Search(oAddress) {

    if (oAddress) {

        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);
        }

    }
}

/////////////   LocMarker    /////////////
//global marker counter:
var i = 0;
function LocMarker(point, name, city, html, xml, detailInfoCallBack, locationTypeId, iconPath) {
    if (bMapMode) {
        this.markerIcon = new GIcon();
        this.markerIcon.image = iconServerUrl + iconPath;
        this.markerIcon.iconSize = new GSize(24, 25);
        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;
    }

}


///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


function LocPicker(oSideBarElement, oDetailInfoElement, oMapElement, oErrorElement, oFilterElement, oLoaderElement) {
    this.xml = "";
    this.sideBarDisplay = oSideBarElement;
    this.detailInfoDisplay = oDetailInfoElement;
    this.errorDisplay = oErrorElement;
    if (bMapMode) {
        this.getLocations = GetMarkersWithinBounds;
        this.map = new GMap2(oMapElement);

        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);
        this.Filter.WeekendCheckBox.onclick = this.filter;
        this.Filter.EveningCheckBox.onclick = this.filter;

    }
    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("adres:'" + oAddress + "' niet gevonden.");
                           } else {

                               callBack(point, oAddress);
                           }

                       } catch (e) {
                           ShowNotice(11111, 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";
        }


    },
    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",
                        function() {
                            result.marker.openInfoWindowHtml(result.resultMarkerHTML);
                            result.detailInfoCallBack(result.resultDetailHTML);

                        });
            } else {


            }
            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;
    }

};


function SidebarClick(i) {
    if (bMapMode) {
        try {
            GEvent.trigger(locPicker.locations[i].marker, "click");
        } catch (e) {
            //TODO:error
        }
    } else {
        locPicker.showDetailInfo(locPicker.locations[i].resultDetailHTML)

    }

}

function CloseErrorDisplay(element) {
    if (element.style.visibility == "visible") {
        element.style.visibility = "hidden";
    }
}

function Reset() {
    if (bMapMode) {
        ShowHolland(new GPoint(5.642743, 52.212400), "centrum nederland");
    }
    document.getElementById("txtSearch").value = "";
}

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"));

                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(99999, e.message);
    }

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


function trim(value) {
    value = value.replace(/^\s+/, '');
    value = value.replace(/\s+$/, '');
    return value;
}

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(66666, e.message);
    }
}

function ClosePopup() {
    CallPassData(data.passDataUrl, "?action=close");
}

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 + "' />";
}

function Cancel() {

//    if (locPicker.detailInfoDisplay.innerHTML == "") {
        ClosePopup();
//    } else {
//        bCancel = true;
//        ConfirmAddress();
//        bCancel = false;
//    }
}


