﻿
//Used to render the iframe of fancybox first so that map is centered correctly.
function loadMap() {
    setTimeout("initialise()", 50);
}

function initialise() {
    if (currentLat != "" && currentLng != "") {
        setExistingMarker = true;
        //alert(setExistingMarker);
        //alert("1: Lat:" + currentLat + " Lng:" + currentLng);
        defaultZoom = 9;
    }
    else if (google.loader.ClientLocation) {
        currentLat = google.loader.ClientLocation.latitude;
        currentLng = google.loader.ClientLocation.longitude;
    }
    else {
        currentLat = 54.622978 //default UK Latitude
        currentLng = -2.592773 //default UK Longitude
    }

    map = new google.maps.Map2(document.getElementById("map"));
    map.disableDoubleClickZoom();
    geocoder = new GClientGeocoder();
    geocoder.setBaseCountryCode('UK');

    map.checkResize();
    var location = new google.maps.LatLng(currentLat, currentLng);
    map.setCenter(location);
    map.setZoom(defaultZoom);

    //Prepopulate the map if we have existing lng lat
    if (setExistingMarker) {
        //alert(markerDrag);
        //alert("2: Lat:" + currentLat + " Lng:" + currentLng);
        var existingPoint = new google.maps.LatLng(currentLat, currentLng);
        //console.log(currentLat);
        //console.log(currentLng);
        //console.log(existingPoint);
        addMarker(existingPoint);
        $("#" + lblLocationClientId).text($("input#" + hdnLocationClientId).val());
        $("#" + hdnLocationIdClientId).val($("input#" + hdnLocationIdClientId).val());
    }

    if (enableLargeMapControls) {
        if (enableMapButtons) {
            var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5, 40));
            map.addControl(new GLargeMapControl3D(), topLeft);
        } else {
            map.addControl(new GLargeMapControl3D());
        }
    } else {
        map.addControl(new GSmallZoomControl3D());
    }
}

function createMarker(latLng, iconImage, draggable) {
    if (iconImage != '') {
        var icon = new GIcon();
        icon.image = iconImage;
        icon.iconSize = new GSize(41, 52);
        icon.iconAnchor = new GPoint(27, 52);
        icon.infoWindowAnchor = new GPoint(14, 14);
        markerOptions = { icon: icon, draggable: draggable };
        var marker = new GMarker(latLng, markerOptions);
    }
    else {
        markerOptions = { draggable: draggable };
        var marker = new GMarker(latLng, markerOptions);
    }
    return marker;
}

function addMarker(latLng) {
    var marker = createMarker(latLng, defaultImage, markerDrag);
    GEvent.addListener(marker, "dragstart", function() {
        map.closeInfoWindow();
    });
    GEvent.addListener(marker, "dragend", function() {
        currentLat = marker.getLatLng().lat();
        currentLng = marker.getLatLng().lng();
        $("input#" + hdnLatClientId).val(currentLat);
        $("input#" + hdnLngClientId).val(currentLng);
    });
    var location = new google.maps.LatLng(marker.getLatLng().lat(), marker.getLatLng().lng());
    map.setCenter(location, defaultZoom);
    map.addOverlay(marker);
}

function gotoAddress(latitude, longitude, locationName, locationId) {
    map.clearOverlays();
    var location = new google.maps.LatLng(latitude, longitude);
    addMarker(location);
    $("#" + lblLocationClientId).text(locationName);
    $("input#" + hdnLatClientId).val(latitude);
    $("input#" + hdnLngClientId).val(longitude);
    $("input#" + hdnLocationClientId).val(locationName);
    $("input#" + hdnLocationIdClientId).val(locationId);
}

function changeView(type) {
    map.setMapType(type);
}


function searchLocation(search, countryId) {
    $.ajax({
        type: 'POST',
        url: '/WebServices/wsLocation.asmx/GetBySearch',
        data: '{"searchWord":"' + search + '","countryId": ' + countryId + ', "resultCount":"200"}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(msg) {
            ApplyLocationsTemplate(msg);
        }
    });
}

function ApplyLocationsTemplate(msg) {
    if (msg.d.length == 0) {
        $("#" + lblLocationErrorClientId).show();
        $("#" + lblLocationErrorClientId).text("Location not found please refine your search.");
        $("#divLocations").hide();
    }
    else {
        $("#" + lblLocationErrorClientId).hide();
        
        //only show scroll box if more than 1 results
        if (msg.d.length > 1) {
            if ($("#divLocationsCon").length > 0) {
                $("#divLocationsCon").show();
            }

            $("#divLocations").show();
            $("#divLocations").empty();
            for (var i = 0; i < msg.d.length; i++) {
                var locationId = msg.d[i].LocationId;
                var location = msg.d[i].Name;
                var latitude = msg.d[i].Latitude;
                var longitude = msg.d[i].Longitude;
                if (msg.d[i].Area.length > 0) { location += ", " + msg.d[i].Area; }

                $("#divLocations").append("<a href=\"javascript:gotoAddress('" + latitude + "','" + longitude + "','" + location + "',"+ locationId +");\" class=\"search_result grey size_12 bold\">" + location + "</a>");
            }
        }
        else {
            $("#divLocations").hide();
            if ($("#divLocationsCon").length > 0) {
                $("#divLocationsCon").hide();
            }
        }

        var locationId = msg.d[0].LocationId;
        var latitude = msg.d[0].Latitude;
        var longitude = msg.d[0].Longitude;
        var location = msg.d[0].Name;
        if (msg.d[0].Area.length > 0) { location += ", " + msg.d[0].Area; }
        if (msg.d[0].Region.length > 0) { location += ", " + msg.d[0].Region; }
        if (msg.d[0].CountryName.length > 0) { location += ", " + msg.d[0].CountryName; }

        gotoAddress(latitude, longitude, location, locationId);
    }
}

google.load("maps", "2");
google.setOnLoadCallback(loadMap);
window.unload = google.maps.Unload;
