﻿var map;
var icon = null;
var gdir;
var directions;
var strDirections;
var strOriginPostcode;
var strDestPostcode;
var geocoder;
//var localSearch = new GlocalSearch();
var startPoint;
var endPoint;
//var noStockistsFound = false;
var htmls=[];

function populate() {
    if (gMapRecordCount != 0) {
        document.getElementById("stockistList").length = gMapRecordCount;
        for (intCounter = 0; intCounter < gMapRecordCount; intCounter++) {        
            document.getElementById("stockistList").options[intCounter].text = gMapStockist[intCounter] + " miles - " + gMapDistance[intCounter];
            document.getElementById("stockistList").options[intCounter].value = intCounter;
            buildAlternativeLocationList(gMapStockist[intCounter], gMapStockistAddress[intCounter], gMapDistance[intCounter], intCounter);
        }

        if (showTextLocationList == 1) {
            document.getElementById("locations").style.display = "none";
            document.getElementById("locationsAltList").style.display = "";
        }
        else {
            document.getElementById("locations").style.display = "";
        }
    }
}

function buildAlternativeLocationList(stockistName, stockistAddress, stockistDistance, count) {
    var d = document.createElement("div");
    var l = document.createElement("a");

    l.setAttribute("href", "javascript:gMapCentreV2(" + count + ");");
    l.setAttribute("id", count);
    l.innerHTML = viewButtonText;
    d.innerHTML = "<span class=" + '"sName">' +stockistName + "</span>" + "<br/>" + stockistAddress + "<br/>" + "<span class=" + '"sDistance">' + stockistDistance + "</span>";
    d.appendChild(l);
    document.getElementById("locationsAltList").appendChild(d);
}

function plotStockist(longitude, latitude, address, number) {
    var point = new GLatLng(latitude, longitude)
    var marker = new GMarker(point, icon);
    var innerDetail;

    gMapMarkers[number] = marker
    
    innerDetail = address + '<br><br>Start address/postcode:<br><form action="http://maps.google.com/maps" method="get" target="_blank">' +
      '<input type="text" size="30" maxlength="40" name="saddr" id="saddr" value="" /><br>' +
      '<input value="Get Directions" type="submit">' +
      '<input type="hidden" name="daddr" value="' +
      latitude + ',' + longitude + "(" + "Stockist" + ")" + '"/>';
    
      htmls[number] = innerDetail;
    
    GEvent.addListener(marker, "click", function () {
        marker.openInfoWindowHtml(htmls[number]);
    });
    map.addOverlay(marker);
}

function initialize() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.setCenter(new GLatLng(50.4217, -4.1888), 4); //Please adjust to prefered start location on map and zoom level: default 8

        if (showMapByDefault == 1) {
            document.getElementById("map").style.display = "";
            map.checkResize();
        }
        else {
            document.getElementById("map").style.display = "none";
        }
        
        map.checkResize();
        map.setCenter(new GLatLng(50.4217, -4.1888), 4);
  
        //Directions
        //geocoder = new GClientGeocoder();
        directions = new Array();

        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

        //usePointFromPostcode("ex329jl", setStartPoint);
        //usePointFromPostcode("ex329jl", setEndPoint);

        //setDirections(startPoint, endPoint, "en_US");
        //showLocation("ex329jl", "pl48ll", "en_US");

        //*****Please use below if you wish to use a custom marker******

        //icon = new GIcon();
        //icon.image = ""; //URL to image
        //icon.iconSize = new GSize(18, 25);
        //icon.shadowSize = new GSize(22, 20);
        //icon.iconAnchor = new GPoint(6, 20);
        //icon.infoWindowAnchor = new GPoint(5, 1);

        gMapMarkers.length = gMapRecordCount;

        if (gMapRecordCount != 0) {
            document.getElementById("map").style.display = "";
            map.checkResize();
            for (i = 0; i < gMapRecordCount; i++) {
                plotStockist(gMapLongWGS84[i], gMapLatWGS84[i], gMapStockistAddress[i], i);
            }
            plotStockistPrefered(gMapLongWGS84[0], gMapLatWGS84[0], 0);
            populate();
        }
        else {
              //noStockistsFound = true;
        }
    }

    else {
        alert("Sorry, the Google Maps API is not compatible with this browser");
    }

}

function plotStockistPrefered(longitude, latitude, i) {
    var point = new GLatLng(latitude, longitude);
    map.panTo(point);
    map.setCenter(point, 11);
    gMapMarkers[0].openInfoWindowHtml(htmls[i]);
}

function panStockist(longitude, latitude) {
    var point = new GLatLng(latitude, longitude);
    map.panTo(point);
    map.setCenter(point, 11);
}

function gMapCentre() {

    var strAddress = "";
    strAddress = htmls[document.getElementById("stockistList").value];
    panStockist(gMapLongWGS84[document.getElementById("stockistList").value], gMapLatWGS84[document.getElementById("stockistList").value]);
    gMapMarkers[document.getElementById("stockistList").value].openInfoWindowHtml(strAddress);
}

function gMapCentreV2(i) {

    var strAddress = "";
    strAddress = htmls[i];
    panStockist(gMapLongWGS84[i], gMapLatWGS84[i]);
    gMapMarkers[i].openInfoWindowHtml(strAddress);
}

if (window.attachEvent) {
    window.attachEvent("onunload", function () {
        GUnload();
    });
}
else {
    window.addEventListener("unload", function () {
        GUnload();
    },
    false);
}

//Direction Error Handler 
function handleErrors() {
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

    //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_KEY) alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

    else alert("An unknown error occurred.");

}

//Set Directions Function   
function setDirections(fromAddress, toAddress, locale) {
    document.getElementById("directions").style.display = "";

    gdir.load("from: " + fromAddress + " to: " + toAddress, {
        "locale": locale
    });
}

function showLocation(fromAddress, toAddress, locale) {
    geocoder.getLocations(fromAddress, function (response) {
        if (!response || response.Status.code != 200) {
            alert("Sorry, we were unable to geocode the first address");
        }
        else {
            location1 = {
                lat: response.Placemark[0].Point.coordinates[1],
                lon: response.Placemark[0].Point.coordinates[0],
                address: response.Placemark[0].address
            };
            geocoder.getLocations(toAddress, function (response) {
                if (!response || response.Status.code != 200) {
                    alert("Sorry, we were unable to geocode the second address");
                }
                else {
                    location2 = {
                        lat: response.Placemark[0].Point.coordinates[1],
                        lon: response.Placemark[0].Point.coordinates[0],
                        address: response.Placemark[0].address
                    };
                    gdir.load('from: ' + location1.address + ' to: ' + location2.address);
                }
            });
        }
    });
}

function onGDirectionsLoad() {
    // On Load Status
    map.addOverlay(gdir.getPolyline());
}

function setStartPoint(point) {
    startPoint = point;
}

function setEndPoint(point) {
    endPoint = point
}

function usePointFromPostcode(postcode, callbackFunction) {

    localSearch.setSearchCompleteCallback(null, function () {

        if (localSearch.results[0]) {
            var resultLat = localSearch.results[0].lat;
            var resultLng = localSearch.results[0].lng;
            var point = new GLatLng(resultLat, resultLng);
            callbackFunction(point);
        } else {
            alert("Postcode not found!");
        }
    });

    localSearch.execute(postcode + ", UK");
}

this.onload = initialize;