﻿    var geoLocation = new Object();

    geoLocation.objGeoCoder = null;

    // internal storage objects
    geoLocation.aryMarkers = new Array();
    geoLocation.aryLines = new Array();
    geoLocation.mkrReference = null;
    geoLocation.aryAddresses = new Array();
    geoLocation.isProfessionalsPage = false;
    geoLocation.isServicePage = false;
    var storeArray = new Array();
    var strName = null;
    var strId = null;
    var strUrl = null;
    var strAddress = null;

    // initialisation method
    geoLocation.init = function () {
        geoLocation.objGeoCoder = new google.maps.ClientGeocoder();
        geoLocation.isReady = true;
        geoLocation.processQueue();
    }

    // set point of reference for calculating distance to surrounding points 
    geoLocation.setPointOfReferenceLatLng = function (lat, lng, address, description) {
        if (geoLocation.aryAddresses.length == 0 && geoLocation.objGeoCoder) {
            // remove old point
            if (geoLocation.mkrReference != null) geoLocation.objMap.removeOverlay(geoLocation.mkrReference);
            // add new point
            var point = new GLatLng(lat, lng, true);
            var objRefMarker = new GMarker(point);
            objRefMarker.address = address;
            objRefMarker.description = description;
            geoLocation.mkrReference = objRefMarker
            geoLocation.calculateDistance();
            geoLocation.selectTheClosestUnit();
            //        }
        } else {
            setTimeout("geoLocation.setPointOfReferenceLatLng(\"" + lat + "\",\"" + lng + "\",\"" + address + "\",\"" + description + "\")", 1000);
        }
    }

    // add new location by coordinates
    geoLocation.addPoint = function (point, address, description) {
        if (!point) {
            //alert(address + " not found");
        } else {
            var objMarker = new GMarker(point, { icon: geoLocation.objPointerIcon });
            objMarker.address = address;
            objMarker.description = description;
            geoLocation.aryMarkers[geoLocation.aryMarkers.length] = objMarker;
            geoLocation.calculateDistance();
        }
    }
    // add new location by address
    geoLocation.addPointByAddress = function (address, description) {
        var stcAddress = { address: address, description: description }
        geoLocation.aryAddresses.push(stcAddress);
    }

    // process queue of points
    geoLocation.processQueue = function () {
        if (geoLocation.aryAddresses.length > 0 && geoLocation.objGeoCoder) {
            if (!geoLocation.isRunning) {
                geoLocation.isRunning = true;
                var stcAddress = geoLocation.aryAddresses.shift();
                geoLocation.objGeoCoder.getLatLng(
				stcAddress.address,
				function (point) {
				    geoLocation.isRunning = false;
				    geoLocation.addPoint(point, stcAddress.address, stcAddress.description);
				    geoLocation.processQueue();
				}
			);
            }
        } else {
            setTimeout("geoLocation.processQueue()", 1000);
        }
    }

    // calculate distance between points
    geoLocation.calculateDistance = function () {
        if (geoLocation.mkrReference != null) {
            for (var i = 0; i < geoLocation.aryLines.length; i++) {
                geoLocation.objMap.removeOverlay(geoLocation.aryLines[i]);
            }
            geoLocation.aryLines = new Array();
            for (var i = 0; i < geoLocation.aryMarkers.length; i++) {
                var polyline = new GPolyline([
					geoLocation.mkrReference.getLatLng(),
					geoLocation.aryMarkers[i].getLatLng()
				],
				geoLocation.strLineColour,
				1
			);
                geoLocation.aryLines[geoLocation.aryLines.length] = polyline;
                geoLocation.aryMarkers[i].distance_direct = Math.round(polyline.getLength() / 100) / 10;
            }
        }
    }

    // show the closest retail unit
    geoLocation.selectTheClosestUnit = function () {
        if (geoLocation.aryAddresses.length == 0 && geoLocation.numLastMarkerLength != geoLocation.aryMarkers.length) {
            geoLocation.aryMarkers.sort(geoLocation.sortArray);
            geoLocation.numLastMarkerLength = geoLocation.aryMarkers.length;
            storeArray = geoLocation.aryMarkers[0]['description'].split('_');
            strName = storeArray[0].toString();
            strId = storeArray[1].toString();
            strUrl = storeArray[2].toString();
            //address = storeArray[3].toString();


            $.ajax({
                url: "/Services/StoreLocatorService.svc/SetLocatedStore",
                data: {
                    id: strId,
                    addToCache: true
                },
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    if (data.d == true) {
                        // Set the header store data
                        geoLocation.setHeaderStoreData(strUrl, strName, strId);
                        if (geoLocation.isProfessionalsPage) {
                            geoLocation.setProfessionalsPageData(strName);
                        }
                        if (geoLocation.isServicePage) {
                            geoLocation.setServicePageData(strName);
                        }
                    } else {
                        openColorBoxLink('http://' + window.location.host + '/Templates/Pages/CountrySelectionLB.aspx', '450px', '300px');
                    }
                },
                error: function () {
                    openColorBoxLink('http://' + window.location.host + '/Templates/Pages/CountrySelectionLB.aspx', '450px', '300px');
                }
            });

            //__doPostBack('<%= storeDDL.UniqueID%>','');
            //$("#<%= storeDDL.ClientID %>").click();
        }
    }
    // sets header data
    geoLocation.setHeaderStoreData = function (storeUrl, storeName, storeId) {
        $("#currentStore").attr("href", storeUrl);
        $("#currentStore").empty();
        $("#currentStore").append("<span>" + storeName + "</span>");
        $("#storeID").val(storeId);
    }
    // sets professional main page data
    geoLocation.setProfessionalsPageData = function (storeName) {
        $.ajax({
            url: "/Services/StoreLocatorService.svc/GetStoreData",
            data: {
                store: storeName
            },
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                $("#storeHeading").text(storeName);
                $("#storeAddress").html(data.d[1].toString());
                $("#storePostal").html(data.d[2].toString());
                $("#addSellers").attr("href", data.d[3].toString());
                $("#addMap").attr("href", data.d[4].toString());
                $("#addShops").attr("href", data.d[0].toString());
            },
            error: function () {
                openColorBoxLink('http://' + window.location.host + '/Templates/Pages/CountrySelectionLB.aspx', '450px', '300px');
            }
        });
    }
    // sets service page data
    geoLocation.setServicePageData = function (storeName) {
        $.ajax({
            url: "/Services/StoreLocatorService.svc/GetStoreDescriptionData",
            data: {
                storeName: storeName
            },
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                $("#storeServiceDesc").html(data.d);
            },
            error: function () {
                openColorBoxLink('http://' + window.location.host + '/Templates/Pages/CountrySelectionLB.aspx', '450px', '300px');
            }
        });
    }

    // helper method for sorting arrays (not public)
    geoLocation.sortArray = function (mkrA, mkrB) {
        if (mkrA.distance_direct < mkrB.distance_direct) {
            return -1;
        } else if (mkrA.distance_direct > mkrB.distance_direct) {
            return 1;
        } else {
            return 0;
        }
    }

    // set point of reference for calculating distance to surrounding points (address)
    //geoLocation.setPointOfReference = function (address, description) {
    //    if (geoLocation.aryAddresses.length == 0 && geoLocation.objGeoCoder) {
    //        if (!description) description = address;
    //        geoLocation.objGeoCoder.getLatLng(
    //			address,
    //			function (point) { geoLocation.setPointOfReference_result(point, address, description); }
    //		);
    //    } else {
    //        setTimeout("geoLocation.setPointOfReference(\"" + address + "\",\"" + description + "\")", 1000);
    //    }
    //}

    // callback when the setPointOfReference address has been resolved
    //geoLocation.setPointOfReference_result = function (point, address, description) {
    //    if (geoLocation.aryAddresses.length == 0 && geoLocation.objGeoCoder) {
    //        if (!point) {
    //            alert(address + " not found");
    //        } else {
    //        // remove old point
    //        if (geoLocation.mkrReference != null) geoLocation.objMap.removeOverlay(geoLocation.mkrReference);
    //        // add new point
    //        var point = new GLatLng(lat, lng, true);
    //        var objRefMarker = new GMarker(point);
    //        objRefMarker.address = address;
    //        objRefMarker.description = description;
    //        geoLocation.mkrReference = objRefMarker
    //        geoLocation.calculateDistance();
    //        geoLocation.selectTheClosestUnit();
    //        }
    //    } else {
    //        setTimeout("geoLocation.setPointOfReference_result(\"" + point + "\",\"" + address + "\",\"" + description + "\")", 1000);
    //    }
    //}

