﻿var map = null;
var arrLocations = new Array();
var arrCoords = new Array();
var arrNames = new Array();
var arrGLatLng = new Array();
var arrMarkers = new Array();
var mapBounds = null;
var _baseUrl = "";
var iconImageUrlPath = "App_Themes/Places/images/numbers/";

function initMap(divId, w, h) {
    // create the map
    map = new GMap2(document.getElementById(divId), { size: new GSize(w, h) });    
    map.setUIToDefault();
    map.disableScrollWheelZoom();
    map.enableDragging();
    arrLocations = new Array();
    arrCoords = new Array();
    arrNames = new Array();
    arrGLatLng = new Array();
    arrMarkers = new Array();
    mapBounds = null;
}

function loadLocation(baseUrl) {
    _baseUrl = baseUrl;
}

// plot a bunch of points based off some loctions
function loadLocations(baseUrl, hfCoordId, hfLocationId, hfNameId, mapId, loadingId, hfLocationQueryId, addressNotFoundCallback) {
    // setup global vars
    _baseUrl = baseUrl;

    if (hfLocationId != null && hfLocationId != "") {
        storeToArray(hfLocationId, arrLocations);
    }
    if (hfNameId != null && hfNameId != "") {
        storeToArray(hfNameId, arrNames);
    }
    if (hfCoordId != null && hfCoordId != "") {
        storeToArray(hfCoordId, arrCoords);

        var curIndex = 0;

        // parse locations
        $.each(arrCoords, function() {
            if (this != null && this != "") {
                lat = this.substring(0, this.lastIndexOf(','));
                lng = this.substring(this.lastIndexOf(',') + 1, this.length - 1);
                addMarker(curIndex++, lat, lng);
            }
        });
    }

    if (arrGLatLng == null) {
        arrGLatLng = new Array();
    }

    if (arrCoords != null && arrCoords.length > 0) {
        extendMapBounds();
    }
    else {
        showAddressOnMap($('#' + hfLocationQueryId).val(), addressNotFoundCallback);
    }

    $("#" + loadingId).hide();
    $("#" + mapId).fadeIn(500);

}

function showUnitedStatesOnMap() {
    geocoder = new GClientGeocoder();

    geocoder.getLatLng('United States', function(point) {
        map.setCenter(point, 3);
    });
}

function showAddressOnMap(address, addressNotFoundCallback) {
    geocoder = new GClientGeocoder();


    geocoder.getLatLng(address, function(point) {
        if (!point) {
            $("#divErrorMessage").fadeIn();
            $("#spError").text("Sorry, we were unable to locate this address.");

            if (addressNotFoundCallback) {
                addressNotFoundCallback();
            }
        }
        else {
            map.setCenter(point, 13);
            //                var marker = new GMarker(point);
            //                map.addOverlay(marker);
            //                marker.openInfoWindowHtml(address);
        }
    });
}

// centers a map to a marker
function centerMarker(index) {
    if (map == null && arrGLatLng != null) return;
    map.openInfoWindowHtml(arrMarkers[index].getLatLng(), getMarkerInfo(index));
    map.panTo(arrMarkers[index].getLatLng());
    c = map.getContainer();
    if (c != null) {
        scrollTo(c.id);
    }
}

// gets all values from hidden fields and stores values into the given array
function storeToArray(hfId, arr) {
    if (arr == null) {
        arr = new Array();
    }

    $("[id$='" + hfId + "']").each(
        function() {
            if ($(this).val() != "") {
                arr[arr.length] = $(this).val();
            } else if ($(this).text() != "") {
                arr[arr.length] = $(this).text();
            }
        });
}

// adds a marker to the map
function addMarker(index, lat, lng) {
    // create the icon
    var point = new GLatLng(lat, lng);
    arrGLatLng[arrGLatLng.length] = point

    var marker = new GMarker(point, { icon: getMarkerIcon(index) });
    marker.index = index;
    arrMarkers[arrMarkers.length] = marker;

    GEvent.addListener(marker, "click", function() {
        map.openInfoWindowHtml(marker.getLatLng(), getMarkerInfo(index));
    });
    map.addOverlay(marker);
}

// returns html for marker
function getMarkerInfo(index) {
    var name = arrNames[index].replace("'", "\'");    
    return "<strong>" + name + "</strong><br />" + arrLocations[index] + "<br/><br/><a id=\"hlDetailGetDirections\" href=\"javascript:void(0);\" onclick=\"attachStartFrom(this, " + index + ");\">Get directions to here</a>";
}

// numbered marker for map 
function getMarkerIcon(index) {
    var gIcon = new GIcon(G_DEFAULT_ICON);
    gIcon.image = _baseUrl + iconImageUrlPath + (index + 1) + ".png";
    return gIcon;
}

// attaches textbox to info window in map
function attachStartFrom(objPopup, index) {
    if ($("#txtMapInfoToAddress").length > 0) return;
    var a = $(objPopup).parent("div").append("<br/>Start address<br/><input id=\"txtMapInfoToAddress\" type=\"text\" onkeypress=\"submitButtonOnReturn(event, 'btnMapDir');\" /> <input id=\"btnMapDir\" type=\"button\" value=\"Go\" onclick=\"directionsGoClick(" + index + "); return false;\" />");
    map.updateInfoWindow();
}

function submitButtonOnReturn(event, btnId) {
    if(event.keyCode == 13){
        $("#" + btnId).click();
        return false;
    }
}

// redirects user to directions page with to and from values
function directionsGoClick(index) {
    window.location = _baseUrl + "Places/Directions.aspx?to=" + arrLocations[index].replace(" ", "+") + "&from=" + $("#txtMapInfoToAddress").val().replace(" ", "+");
}

function extendMapBounds() {
    // go through all coordinates and extend the bounds
    if (mapBounds == null) {
        mapBounds = new GLatLngBounds();
    }

    for (var i = 0; i < arrGLatLng.length; i++) {
        mapBounds.extend(arrGLatLng[i]);
    }

    map.setCenter(mapBounds.getCenter(), map.getBoundsZoomLevel(mapBounds));
    
}

var directions;
function initDirections(mapId, routeId) {    
    initMap(mapId,480, 360);
    directions = new GDirections(map, document.getElementById(routeId));
    GEvent.addListener(directions, "load", onMapLoad);
    GEvent.addListener(directions, "error", onMapError);
    
    $("[id$='txtFrom']").keypress(function(e) {
        if (e.which == 13) {
            $("#btnGo").click();
            return false;
        }
    });

    $("[id$='txtTo']").keypress(function(e) {
        if (e.which == 13) {
            $("#btnGo").click();
            return false;
        }
    });

    loadDirections();
}

function onMapLoad() {
    $("#divLoading").fadeOut(500, function() {
        $("#divMap").fadeIn();
        $("#divRoute").fadeIn();
        $("#divDirTop").fadeIn();
        $("#divDirContent").fadeIn();
        $("#divLoading").hide();
    });
}

function onMapError() {
    var errStatus = directions.getStatus();
    $("#divLoading").fadeOut(500, function() {
        $("#divErrorMessage").fadeIn();
        if (errStatus.code == 602) {
            errMsg = "Sorry, we were unable to locate one of the specified addresses. This may be due to the fact that the address is relatively new or it may be incorrect.";
        } else {
            errMsg = "An unknown error occurred while trying to process your request. Please try again later."
        }
        $("#spError").text(errMsg);
    });
}

function loadDirections() {
    Page_ClientValidate("vgDirections");
    
    if (!Page_IsValid) {
        $("#divLoading").fadeOut();
        return;
    }

    $("#divLoading").fadeIn();
    directions.clear();
    $("#spError").text("");
    directions.load("from: " + $("input[id$='txtFrom']").val() + " to: " + $("input[id$='txtTo']").val());
}

function updateAddresses(vgGroup) {
    Page_ClientValidate(vgGroup);
    
    if(!Page_IsValid){ 
        return;
    }

    $("#divRoute").fadeOut();
    $("#divMap").fadeOut(500, function() {
        $("#divLoading").fadeIn();
        loadDirections();
    });
}

//function checkValidAddress() {
//    var sFrom = $("input[id$='txtFrom']").val();
//    var sTo = $("input[id$='txtTo']").val()
//    if (sFrom == "" || sTo == "") {
//        return false;
//    }else{
//        return true;
//    }
//}

function clearFields() {
    $("input[id$='txtFrom']").val("");
    $("input[id$='txtTo']").val("");
}
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();