﻿

function loadMap() {
    google.load("maps", "2", { "callback": mapsLoaded });
}

//global variables
var map, pin, mgr, countryCode = 'uk', countrySW = GLatLng(49.5822260446217, -22.8955078125), countryNE = GLatLng(60.780618803458935, 3.4716796875), locationCircle, distanceCircle, distance = 2, batchLevel = 10, txtLookingFor, txtLocation, txtNameFilter, currentPoint, currentLocation = '', gmarkers = [];

var companyFilter = "";
var companyName = "";
var currentLat = 0.0;
var currentLng = 0.0;

//load maps function
function mapsLoaded() {
    //get map
    map = new google.maps.Map2(document.getElementById("map"));
    //set UI
    map.setUIToDefault();
    //set country code
    geocoder = new GClientGeocoder();
    if (countryCode != null) geocoder.setBaseCountryCode(countryCode);

    //set default center
    //LONDON
    var lat = 51.505377;
    var lng = -0.121536;

    //set center based on client location
    if (google.loader.ClientLocation) {
        lat = google.loader.ClientLocation.latitude;
        lng = google.loader.ClientLocation.longitude;
    }
    //set map center
    setCenterAndAreas(new google.maps.LatLng(lat, lng), "");

    //set default pin
    pin = new GIcon();
    pin.image = "pin_retailer.png";
    pin.shadow = "shadow.png";
    pin.iconSize = new GSize(24, 31);
    pin.shadowSize = new GSize(40, 31);
    pin.iconAnchor = new GPoint(12, 15);
    pin.infoWindowAnchor = new GPoint(12, 15);

    //add marker manager    
    var mgrOptions = { maxZoom: 15, trackMarkers: true };
    mgr = new MarkerManager(map);

    //search(lat + "," + lng);
    //find default retailers
    //findRetailers();
    currentLat = lat;
    currentLng = lng;
}

function CreateMarker(point, info, imp, pinImg) {
    function importanceOrder(marker, b) {
        return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance * 1000000;
    }
    if (pinImg != undefined) {
        pin.image = "../images/PinImages/" + pinImg;
    }
    else {
        pin.image = "../images/PinImages/pin_retailer.png";
    }
    var markerIcon = new GIcon(pin);
    markerOptions = { icon: markerIcon };
    if (imp > 0) markerOptions = { icon: markerIcon, zIndexProcess: importanceOrder };
    var marker = new GMarker(point, markerOptions);
    if (imp > 0) marker.importance = imp;
    GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(info); map.setCenter(point); });
    markerPoint = point;
    markerInfo = info;
    gmarkers.push(marker);
    return marker;
}


function setCenterAndAreas(point, location) {

    //clear overlay
    map.clearOverlays();

    var level = 10;
    switch (distance) {
        case 1:
            level = 14;
            break;
        case 2:
            level = 13;
            break;
        case 5:
            level = 11;
            break;
        case 10:
            level = 10;
            break;
        case 20:
            level = 9;
            break;
        case 50:
            level = 8;
            break;
    }
    //set center
    map.setCenter(point, level);

    //add distance circle
    //distanceCircle = new CircleOverlay(point, distance, "#336699", 3, 1, '', 0);
    //map.addOverlay(distanceCircle);

    //add center pin
    if (location != "") currentLocation = location;
    if (currentLocation != "") {
        map.addOverlay(CreateMarker(map.getCenter(), "<div style='width:240px;' class='mapInfo'><img src='window_logo.gif' width='75' height='47' /><h2>Location</h2><p>" + currentLocation + "</p></div>", 0, "pin_location.png"));
        document.getElementById("searchStr").innerHTML = currentLocation;
    }
    else {
        // Create and add the circle
        //locationCircle = new CircleOverlay(map.getCenter(), 0.5, "#9A3432", 3, 1, '', 0);
        //map.addOverlay(locationCircle);
    }
    currentPoint = map.getCenter();
}

function findRetailers() {
    map.clearOverlays();
    mgr.clearMarkers();
    mgr.refresh();
    map.openInfoWindowHtml(map.getCenter(), "<div class='mapInfo'><img src='window_logo.gif' width='75' height='47' /><h2>Loading Retailers</h2><p>The retailers for the searched location are being loaded.</p></div>");

    var companyNameFilter = trim10(txtNameFilter.value);
    if (companyNameFilter == "Retailer name") {
        companyNameFilter = "";
    }
   //get retailers from web service
 //  GDownloadUrl("PublicService.asmx/FindRetailers?centerLatitude=" + map.getCenter().lat() + "&centerLongitude=" + map.getCenter().lng() + "&distance=" + distance + "&filter=" + txtLookingFor.value + "&companyFilter=" + companyFilter, function(data, responseCode) {
GDownloadUrl("PublicService.asmx/FindRetailersWithName?centerLatitude=" + map.getCenter().lat() + "&centerLongitude=" + map.getCenter().lng() + "&distance=" + distance + "&filter=" + txtLookingFor.value + "&companyFilter=" + companyFilter + "&companyNameFilter=" + companyNameFilter, function(data, responseCode) {
        var xml = GXml.parse(data);
        var retailers = xml.documentElement.getElementsByTagName("Table");
        var batch = [];
        var buildPin = true;
        var point;
        document.getElementById("noRetailers").innerHTML = retailers.length;

        var table = "<table border='0' cellpadding='0' cellspacing='0'>";
        var showList = false;
        for (var i = 0; i < retailers.length; i++) {
            //get values
            var retailerNode = retailers[i];
            var Id = getNodeValue(retailerNode, "Id");
            var DisplayName = getNodeValue(retailerNode, "DisplayName");
            var Address = buildAddress(retailerNode);
            var Description = getNodeValue(retailerNode, "Description");
            var Telephone = getNodeValue(retailerNode, "Telephone");
            var Latitude = getNodeValue(retailerNode, "Latitude");
            var Longitude = getNodeValue(retailerNode, "Longitude");
            var Distance = roundNumber(getNodeValue(retailerNode, "distance"), 2) + "m";
            var pinImageShow = getNodeValue(retailerNode, "LogoDisplayPinImage");
            var pinImage = getNodeValue(retailerNode, "PinImage");
            if (!pinImageShow || pinImage == "") popupLogo = "pin_retailer.png";
            var popupLogoShow = getNodeValue(retailerNode, "LogoDisplayPopUpLogo");
            var popupLogo = getNodeValue(retailerNode, "PopUpLogoImage");
            if (!popupLogoShow || popupLogo == "") popupLogo = "window_logo.gif";

            var point = new GLatLng(Latitude, Longitude);
            //width='75' height='47'
            var info = "<div class='mapInfo'><img src='../images/PopUpLogos/" + popupLogo + "' alt='" + DisplayName + "'  /><h2>" + DisplayName + "</h2><p>" + Address + "<br />" + Telephone + "</p></div>";

            marker = CreateMarker(point, info, 0, pinImage);
            GEvent.addListener(marker, "click", function() { trackObject(Id); });
            batch.push(marker);

            //marker.openInfoWindowHtml(info); map.setCenter(point);

            //add list table row
            table += "<tr>";
            table += "<td width='275' valign='top'><a href='JavaScript:showOnMap(" + (gmarkers.length - 1) + ");'>" + DisplayName + "</a></td>";
            table += "<td width='265' valign='top'>" + Address + "</td>";
            //table += "<td width='100' valign='top'>" + Telephone + "</td>";
            table += "<td width='60' valign='top'>" + Distance + "</td>";
            table += "</tr>";

            showList = true;
        }

        table += "</table>";

        if (showList) {
            document.getElementById("listTableContent").innerHTML = table;
            document.getElementById("listTable").style.display = "block";
        }
        else {
            document.getElementById("listTableContent").innerHTML = "";
            document.getElementById("listTable").style.display = "none";
        }

        if (batch.length > 0) {
            mgr.addMarkers(batch, batchLevel);
            mgr.refresh();
        }
        map.closeInfoWindow();

        if (retailers.length == 0 && distance < 50) {
            if (companyName == "") {
                map.openInfoWindowHtml(map.getCenter(), "<div class='mapInfo'><img src='window_logo.gif' width='75' height='47' /><h2>No retailers found</h2><p>Extend your search</p><ul><li><a href='#' onclick='setDistance(5);return false;'>5 miles</a></li><li><a href='#' onclick='setDistance(10);return false;'>10 miles</a></li><li><a href='#' onclick='setDistance(20);return false;'>20 miles</a></li><li><a href='#' onclick='setDistance(50);return false;'>50 miles</a></li></ul></div>");
            }
            else {
                map.openInfoWindowHtml(map.getCenter(), "<div class='mapInfo'><img src='window_logo.gif' width='75' height='47' /><h2>No retailers found for " + companyName + "</h2><p><a href='javaScript:removeFilter();'>Cick to remove filter</a></p><p><b>or</b></p><p>Extend your search</p><ul><li><a href='#' onclick='setDistance(5);return false;'>5 miles</a></li><li><a href='#' onclick='setDistance(10);return false;'>10 miles</a></li><li><a href='#' onclick='setDistance(20);return false;'>20 miles</a></li><li><a href='#' onclick='setDistance(50);return false;'>50 miles</a></li></ul></div>");
            }
        }

        if (retailers.length == 0 && distance > 49) {
            map.openInfoWindowHtml(map.getCenter(), "<div class='mapInfo'><img src='window_logo.gif' width='75' height='47' /><h2>No Retailers Found</h2><p>Sorry but there are no retailers in that area, please try a different area.</p></div>");
        }

    }
    )
}

function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

function buildAddress(nodeParent) {

    var add = "";
    var Address1 = getNodeValue(nodeParent, "Address1");
    var Address2 = getNodeValue(nodeParent, "Address2");
    var Address3 = getNodeValue(nodeParent, "Address3");
    var Address4 = getNodeValue(nodeParent, "Address4");
    var Address5 = getNodeValue(nodeParent, "Address5");
    var PostCode = getNodeValue(nodeParent, "PostCode");
    var CountryName = getNodeValue(nodeParent, "CountryName");
    if (Address1 != "") add += Address1 + "<br />";
    if (Address2 != "") add += Address2 + "<br />";
    if (Address3 != "") add += Address3 + "<br />";
    if (Address4 != "") add += Address4 + "<br />";
    if (Address5 != "") add += Address5 + "<br />";
    if (PostCode != "") add += PostCode + "<br />";
    if (CountryName != "") add += CountryName + "<br />";
    return add;
}

function trackObject(i) {
    GDownloadUrl("PublicService.asmx/TrackStrongholdObject?objectId=" + i, function(data, responseCode) { })
}

function show(t) {
    var m = document.getElementById("map");
    var l = document.getElementById("list");
    var mb = document.getElementById("btnMap");
    var lb = document.getElementById("btnList");
    if (t == "map") {
        m.style.display = "block";
        mb.className = "on";
        l.style.display = "none";
        lb.className = "";
    }
    else {
        m.style.display = "none";
        mb.className = "";
        l.style.display = "block";
        lb.className = "on";
    }
}

function showOnMap(i) {
    show("map");
    GEvent.trigger(gmarkers[i], "click");
}

function getNodeValue(nodeParent, nodeName) {

    for(var i = 0;i<nodeParent.childNodes.length;i++) {

        if (nodeParent.childNodes[i].nodeName == nodeName && nodeParent.childNodes[i].childNodes.length > 0) {
            return nodeParent.childNodes[i].childNodes[0].nodeValue;
        }
    }
    return "";
}

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
    if (!response || response.Status.code != 200) {

        map.openInfoWindowHtml(map.getCenter(), "<div class='mapInfo'><img src='window_logo.gif' width='75' height='47' /><h2>Sorry, the address could not be found</h2><p>Please try again, providing more details of the address if possible.</p>");
    
        //map.openInfoWindow(map.getCenter(), document.createTextNode("Sorry, we were unable to find that address.<br/>Please try again, providing more details of the address if possible."));
    } else {
        var test = "";
        for (x = 0; x < response.Placemark.length; x++) {
            test += response.Placemark[x].address + "\n";
        }
        place = response.Placemark[0];

        point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
        setCenterAndAreas(point, place.address);
        findRetailers();
    }
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function search(srch) {
    var searchStr = srch;
    if (searchStr == undefined) searchStr = trim10(txtLocation.value);
    if (searchStr == "City, Postcode") searchStr = "";
    if (searchStr != "") {
        if (geocoder.getViewport() == null) {
            geocoder.setViewport(GLatLngBounds(countrySW, countryNE))
        }
        geocoder.setBaseCountryCode(countryCode);
        geocoder.getLocations(searchStr, addAddressToMap);
    }
    else {
        findRetailers();
    }
}

function trim10(str) {
    var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
    for (var i = 0; i < str.length; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    for (i = str.length - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}


function URLEncode(clearString) {
    var output = '';
    var x = 0;
    clearString = clearString.toString();
    var regex = /(^[a-zA-Z0-9_.]*)/;
    while (x < clearString.length) {
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != '') {
            output += match[1];
            x += match[1].length;
        } else {
            if (clearString[x] == ' ')
                output += '+';
            else {
                var charCode = clearString.charCodeAt(x);
                var hexVal = charCode.toString(16);
                output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
            }
            x++;
        }
    }
    return output;
}

function showDistance() {
    var d = document.getElementById("distance");
    var da = document.getElementById("hypDistance");
    d.style.left = (da.offsetLeft - 60) + "px";
    d.style.top = (da.offsetTop - 92) + "px";
    d.style.visibility = 'visible';

}

function setDistance(i) {
    //var d = document.getElementById("hypDistance");
    //d.innerHTML = i + " km";
    //d.title = i + " km";
    //document.getElementById("distance").style.visibility = 'hidden';
    distance = i;
    setCenterAndAreas(currentPoint, "");
    findRetailers();
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}
addLoadEvent(loadMap);

//window.onload = loadMap();

