﻿/// <reference path="jquery-1.3.2-vsdoc2.js"/>

var map = null;
var dragShape = null;
var dragMap = null;
var pushpins = new Array();
var pushpinsCookie = new Array();
var oldCenterLocation;
var mapStationBuffer = 0.3; // buffer (lat/long) of extra area stations will be received at
var stationZoomLevel = 8; // zoom level that the stations are turned on
var getStations = false;
var stationAmount = 30;
var userStarRating;
var ratePushPinId;
var rateStationId;
var pushpinLayer;
var stationLayer;
var ratings;
var stationHash = new Object();
var startX;
var startY;
var _hideInfoBox;

var pushpinIcon = '<div><img src="AspNetVisualAssets/PushPin1.png" /></div>';
var pushpinIconNoData = '<div><img src="AspNetVisualAssets/PushPinNoData1.png" /></div>';
var stationIcon = '<div><img src="AspNetVisualAssets/RatingIcons/EEAAirNoAQI.png" /></div>';
var stationIconNoData = '<div id=""><img src="AspNetVisualAssets/RatingIcons/ICON.png" /></div>';
var starFullIcon = "AspNetVisualAssets/FullStar.jpg";
var starEmptyIcon = "AspNetVisualAssets/EmptyStar.jpg";
var airStationIcon1 = '<div><img src="AspNetVisualAssets/RatingIcons/EEAAir1.png" /></div>';
var airStationIcon2 = '<div><img src="AspNetVisualAssets/RatingIcons/EEAAir2.png" /></div>';
var airStationIcon3 = '<div><img src="AspNetVisualAssets/RatingIcons/EEAAir3.png" /></div>';
var airStationIcon4 = '<div><img src="AspNetVisualAssets/RatingIcons/EEAAir4.png" /></div>';
var airStationIcon5 = '<div><img src="AspNetVisualAssets/RatingIcons/EEAAir5.png" /></div>';
var waterStationIcon1 = '<div><img src="AspNetVisualAssets/RatingIcons/EEAWater1.png" /></div>';
var waterStationIcon2 = '<div><img src="AspNetVisualAssets/RatingIcons/EEAWater2.png" /></div>';
var waterStationIcon3 = '<div><img src="AspNetVisualAssets/RatingIcons/EEAWater3.png" /></div>';
var waterStationIcon4 = '<div><img src="AspNetVisualAssets/RatingIcons/EEAWater4.png" /></div>';
var waterStationIcon5 = '<div><img src="AspNetVisualAssets/RatingIcons/EEAWater5.png" /></div>';
var userRatingIcons = new Array();
var loadingHtml = "<div id='loading'><p>loading</p></div>";
userRatingIcons[0] = "../AspNetVisualAssets/UserIcons/UserIconNoData.png";
userRatingIcons[1] = "../AspNetVisualAssets/UserIcons/UserIcon1.png";
userRatingIcons[2] = '../AspNetVisualAssets/UserIcons/UserIcon2.png';
userRatingIcons[3] = '../AspNetVisualAssets/UserIcons/UserIcon3.png';
userRatingIcons[4] = '../AspNetVisualAssets/UserIcons/UserIcon4.png';
userRatingIcons[5] = '../AspNetVisualAssets/UserIcons/UserIcon5.png';

function setCookie(cookieName, value, expiredays)
{
    var exdate = new Date();
    if (expiredays != null) {
        exdate.setDate(exdate.getDate() + expiredays);
    }
    document.cookie = cookieName + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString());
}

function getCookie(cookieName) 
{
    if (document.cookie.length > 0) 
    {
        cookieStartIndex = document.cookie.indexOf(cookieName + "=");

        if (cookieStartIndex != -1) 
        {
            cookieStartIndex = cookieStartIndex + cookieName.length + 1;

            cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex);

            if (cookieEndIndex == -1) 
            {
                cookieEndIndex = document.cookie.length;
            }

            return unescape(document.cookie.substring(cookieStartIndex, cookieEndIndex));
        }
    }
    return "";
}

function deleteCookie(name) {
    var cookie = getCookie(name);

    if (cookie != null && cookie != "") {
        document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
    }
}

function onChangeMapStyle() {    
    setCookie("mapStyle", map.GetMapStyle(), 365);    
}

function GetMap() {
    map = new VEMap('myMap');
    MapResize(true);
    map.LoadMap(new VELatLong(50, 6), 3, VEMapStyle.Aerial, false);
    map.SetMouseWheelZoomToCenter(false);

    map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
    
    var mapStyle = getCookie("mapStyle");
    MapResize(true);
    if (mapStyle != null && mapStyle != "") 
    {
        map.SetMapStyle(mapStyle);
    }
    
    oldCenterLocation = map.GetCenter();

    // Clear out the default InfoBox styles, build up from there.
    // The styles are defined in Pushpin.css, prefix: customInfoBox-*
    //
    map.ClearInfoBoxStyles();    

    pushpinLayer = new VEShapeLayer();
    
    map.AddShapeLayer(pushpinLayer);
   
    var count = 0;
    
    while(true) {
        pushpinCookie = getCookie("pushpin" + count);

        if (pushpinCookie != null && pushpinCookie != "") {
            //Delete cookie so we can reset from when any cookies were deleted in a previous session.
            deleteCookie(pushpinCookie);
            count++;
            if (pushpinCookie != "deleted") {                
                latlongArray = pushpinCookie.split(",")
                placePushPin(latlongArray[0], latlongArray[1], false);
            }                   
        }
        else {
            break;
        }
    }    
    
    stationLayer = new VEShapeLayer();
    map.AddShapeLayer(stationLayer);

    map.AttachEvent("onmousedown", MouseHandler);
    map.AttachEvent("onmouseup", MouseHandler);
    map.AttachEvent("onmousemove", MouseHandler);
    map.AttachEvent("onstartzoom", StartZoomHandler);    
    map.AttachEvent("onendzoom", EndZoomHandler);
    map.AttachEvent("onchangemapstyle", onChangeMapStyle);
    map.AttachEvent("onmouseover", mouseOverShape);
    $("#Compass").mousedown(function() { ClosePushpinControl(); });
        
    GetTiles();

    //ChangeHeatMapTileLayer() {
    var heatmap = getCookie("heatmap");

    if (heatmap != null && heatmap != "") {
        if (heatmap == "on") {
            document.getElementById("changeHeatMap").checked = true;
            ChangeHeatMapTileLayer();
        }
        else if (heatmap == "off") {
            document.getElementById("changeHeatMap").checked = false;
            ChangeHeatMapTileLayer();
        }
    }

    var stations = getCookie("station");

    if (stations != null && stations != "") {
        switch (stations) {
            case "None":
                document.getElementById("changeStationTileLayerSelect").selectedIndex = 0;
                break;
            case "All":
                document.getElementById("changeStationTileLayerSelect").selectedIndex = 1;
                break;
            case "Air":
                document.getElementById("changeStationTileLayerSelect").selectedIndex = 2;
                break;
            case "Water":
                document.getElementById("changeStationTileLayerSelect").selectedIndex = 3;
                break;
        }

        ShowTileLayer("Station", stations);
    }
    else {
        document.getElementById("changeStationTileLayerSelect").selectedIndex = 1;
        ShowTileLayer("Station", "All");
    }

    var userfeedback = getCookie("userfeedback");

    if (userfeedback != null && userfeedback != "") {
        switch (userfeedback) {
            case "None":
                document.getElementById("changeUserFeedbackTileLayerSelect").selectedIndex = 0;
                break;
            case "All":
                document.getElementById("changeUserFeedbackTileLayerSelect").selectedIndex = 1;
                break;
            case "Air":
                document.getElementById("changeUserFeedbackTileLayerSelect").selectedIndex = 2;
                break;
            case "Water":
                document.getElementById("changeUserFeedbackTileLayerSelect").selectedIndex = 3;
                break;
        }

        ShowTileLayer("UserFeedback", userfeedback);
    }
}

function mouseOverShape(e) {
    if (e.elementID != null) {
        if ($("#" + e.elementID + " img").attr("src").indexOf("PushPin", 0) <= 0) {
            var stationId = $("#" + e.elementID + " > div > div").attr("id");
            if (stationHash[stationId].GetDescription() == "") {
                stationHash[stationId].SetDescription(loadingHtml);
                GetStation(stationId);
            }
        }
    }
}

function ResizeMap() //resize
{
    if (map != null) {
        if (typeof (window.innerWidth) == 'number') {
            //Non-IE
            map.Resize();
        }
        else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            map.Resize();
        }
    }
}

function UnloadMap() //dispose map etc
{
    if (map != null) {
        map.Dispose();
    }
} 

function FindLoc(location) {
    if (location.length > 2) {
        if (map == null)
            GetMap();
            map.Find(null, location, null, null, null, null, null, null, false, null, callback);
    }
    else {
        IncorrectSearch();
    }
}

//confirms the location by clicking on location in the dropdown list of results
//find the coordinates and saves these in a hidden field.
function selectChange(where) {
    map.Find(null, where, null, null, null, 1, null, null, false, null, callback);
    document.getElementById("LocationSelectDiv").style.visibility = "hidden";
}

//callback function for map search results. creates a drop down list of results
function callback(a, b, c, d, e) {
    $(".dropdown dd ul").hide();
    if (c != null && c.length > 1) {
        var html = "";

        $(".dropdown dd ul").html("");
        for (var i in c) {
            html = $(".dropdown dd ul").html();
            $(".dropdown dd ul").html(html + "<li><a href='#'>" + c[i].Name + "</a></li>");
        }

        $(".dropdown dd ul li a").click(function() {
            var text = $(this).html();
            $("#SearchLocationTextBox").val(text);
            $(".dropdown dd ul").hide();
            selectChange(text);
        });

        $(document).bind('click', function(e) {
            var $clicked = $(e.target);
            if (!$clicked.parents().hasClass("dropdown"))
                $(".dropdown dd ul").hide();
        });

        $(".dropdown dd ul").toggle();
    }
    else if (c != null && c.length == 1) {
        placePushPin(c[0].LatLong.Latitude, c[0].LatLong.Longitude, false);
    }
    else {
        IncorrectSearch();
    }
}

function IncorrectSearch() {
    $(".dropdown dd ul").hide();
    document.getElementById("LocationSelectDiv").style.visibility = "hidden";
    $(".dropdown dd ul").html("");
    var html = "";
    html = $(".dropdown dd ul").html();
    $(".dropdown dd ul").html(html + "<li><a href='#'>" + $("#errorMessage").text() + "</a></li>");
    $(".dropdown dd ul").toggle();
}

function GetTiles() {
    var bounds = [new VELatLongRectangle(new VELatLong(59, -31), new VELatLong(23, 45))];
    var opacity = 1;

    //var url = document.location.protocol + "//" + document.location.host + "/";
    
    // CONFIG CHANGE - Update this to point to blob storage containing the map tiles
    var url = "http://eyeonearth.blob.core.windows.net/"

    var tileSourceSpec = new VETileSourceSpecification("airModel",
    url + "heatmaptileserver/%4.png");
    tileSourceSpec.NumServers = 1;
    tileSourceSpec.MinZoomLevel = 2;
    tileSourceSpec.MaxZoomLevel = 15;
    tileSourceSpec.Opacity = 0.7;
    tileSourceSpec.ZIndex = 100;

    map.AddTileLayer(tileSourceSpec, false);

    tileSourceSpec = new VETileSourceSpecification("userFeedbackAir",
    url + "userfeedbackairlightmap/%4.png");
    tileSourceSpec.NumServers = 1;
    tileSourceSpec.MinZoomLevel = 2;
    tileSourceSpec.MaxZoomLevel = 15;
    tileSourceSpec.Opacity = opacity;
    tileSourceSpec.ZIndex = 50;

    map.AddTileLayer(tileSourceSpec, false);

    tileSourceSpec = new VETileSourceSpecification("userFeedbackWater",
    url + "userfeedbackwaterlightmap/%4.png");
    tileSourceSpec.NumServers = 1;
    tileSourceSpec.MinZoomLevel = 2;
    tileSourceSpec.MaxZoomLevel = 15;
    tileSourceSpec.Opacity = opacity;
    tileSourceSpec.ZIndex = 50;

    map.AddTileLayer(tileSourceSpec, false);

    tileSourceSpec = new VETileSourceSpecification("airStations",
    url + "airstationlightmap/%4.png");
    tileSourceSpec.NumServers = 1;
    tileSourceSpec.Bounds = bounds;
    tileSourceSpec.MinZoomLevel = 2;
    tileSourceSpec.MaxZoomLevel = 15;
    tileSourceSpec.Opacity = opacity;
    tileSourceSpec.ZIndex = 25;

    map.AddTileLayer(tileSourceSpec, false);

    tileSourceSpec = new VETileSourceSpecification("waterStations",
    url + "waterstationlightmap/%4.png");
    tileSourceSpec.NumServers = 1;
    tileSourceSpec.Bounds = bounds;
    tileSourceSpec.MinZoomLevel = 2;
    tileSourceSpec.MaxZoomLevel = 15;
    tileSourceSpec.Opacity = opacity;
    tileSourceSpec.ZIndex = 25;

    map.AddTileLayer(tileSourceSpec, false);
}

function DeleteTileLayer() {
    map.DeleteTileLayer("airModel");
}

function SetLegendWidth() {
    var width = 0;

    $("#mapKeyBackground").children(":visible").each(function() {
        width += $(this).width();
    });
    
    var windowWidth;
    if (typeof (window.innerWidth) == 'number') {
        windowWidth = window.innerWidth;
    }
    else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        windowWidth = document.documentElement.clientWidth;
    }

    var left = (windowWidth / 2) - (width / 2);
    $(".mapKeyContainer").css("left", left + "px");
}

var stationLayers = new Array();
var userFeedbackLayers = new Array();

function ShowTileLayer(currentTile, currentSubTile) {
    HideTileLayer(currentTile);

    switch (currentTile) {
        case "Station":
            setCookie("station", currentSubTile);
            switch (currentSubTile) {
                case "None":
                    DeleteStationLayer();
                    stationLayers = undefined;
                    break;
                case "All":
                    DeleteStationLayer();
                    map.ShowTileLayer("airStations");
                    map.ShowTileLayer("waterStations");
                    stationLayers = new Array("airStations", "waterStations");
                    break;
                case "Air":
                    DeleteStationLayer();
                    map.ShowTileLayer("airStations");
                    stationLayers = new Array("airStations");
                    break;
                case "Water":
                    DeleteStationLayer();
                    map.ShowTileLayer("waterStations");
                    stationLayers = new Array("waterStations");
                    break;
            }
            if (stationLayers == undefined) {
                $("#StationsKey").css("display", "none");
            }
            else {
                $("#StationsKey").css("display", "block");
            }
            SetLegendWidth();
            break;
        case "UserFeedback":
            setCookie("userfeedback", currentSubTile);
            switch (currentSubTile) {
                case "None":
                    userFeedbackLayers = undefined;
                    break;
                case "All":
                    map.ShowTileLayer("userFeedbackAir");
                    map.ShowTileLayer("userFeedbackWater");
                    userFeedbackLayers = new Array("userFeedbackAir", "userFeedbackWater");
                    break;
                case "Air":
                    map.ShowTileLayer("userFeedbackAir");
                    userFeedbackLayers = new Array("userFeedbackAir");
                    break;
                case "Water":
                    map.ShowTileLayer("userFeedbackWater");
                    userFeedbackLayers = new Array("userFeedbackWater");
                    break;
            }
            if (userFeedbackLayers == undefined) {
                $("#UserFeedbackKey").css("display", "none");
            }
            else {
                $("#UserFeedbackKey").css("display", "block");
            }
            SetLegendWidth();
            break;
    }
}

function HideTileLayer(currentTile) {
    var layer;

    switch (currentTile) {
        case "Station":
            layer = stationLayers;
            break;
        case "UserFeedback":
            layer = userFeedbackLayers;
            break;
    }

    if (layer != undefined) {
        for (var i = 0; i < layer.length; i++) {
            map.HideTileLayer(layer[i]);
        }
    }
}

function HideAllTileLayers() {
    HideTileLayer("Station");
    HideTileLayer("UserFeedback");
}

function ShowSelectedTileLayers() {
    ShowTileLayer("Station", $("#changeStationTileLayerSelect").val())
    ShowTileLayer("UserFeedback", $("#changeUserFeedbackTileLayerSelect").val())
}

function ChangeTileLayer(typeOfLayer) {
    var currentTile;

    if (typeOfLayer == "Station") {
        currentTile = document.getElementById("changeStationTileLayerSelect").value;
        ShowTileLayer(typeOfLayer, currentTile);
    }
    else if (typeOfLayer == "UserFeedback") {
        currentTile = document.getElementById("changeUserFeedbackTileLayerSelect").value;
        ShowTileLayer(typeOfLayer, currentTile);
    }
    GetStations();
    return;
}

function ChangeSubTileLayer() {
    var currentTile = document.getElementById("changeTileLayerSelect").value;
    var currentSubTile = document.getElementById("changeSubTileLayerSelect").value;

    HideAllTileLayers();
    ShowTileLayer(currentTile, currentSubTile);
}

function ChangeHeatMapTileLayer() {
    var checked = document.getElementById("changeHeatMap").checked;

    if (checked) {
        map.ShowTileLayer("airModel");
        setCookie("heatmap", "on");
        $("#AirModelKey").css("display", "block");
    }
    else {
        map.HideTileLayer("airModel");
        setCookie("heatmap", "off");
        $("#AirModelKey").css("display", "none");
    }
    SetLegendWidth();
}

var oldAir = false;
var oldWater = false;

function DeleteStationLayer() {
    tempHash = new Object();
    stationHash = new Object();
    stationLayer.DeleteAllShapes();
}

function GetStations() 
{    
    var air = false;
    var water = false;

    for (var i in stationLayers)
    {
        if (stationLayers[i] == "waterStations") 
        {
            water = true;
        }

        if (stationLayers[i] == "airStations") 
        {
            air = true;
        }
    }

    if (air || water) 
    {
        var mapWidth = document.getElementById('myMap').clientWidth;
        var mapHeight = document.getElementById('myMap').clientHeight;

        var mapCenter = map.GetCenter();

        var pixelCenter = map.LatLongToPixel(mapCenter);

        var x1 = pixelCenter.x - (mapWidth / 2);
        var y1 = pixelCenter.y - (mapHeight / 2);
        var x2 = pixelCenter.x + (mapWidth / 2);
        var y2 = pixelCenter.y + (mapHeight / 2);

        var latLong1 = map.PixelToLatLong(new VEPixel(x1, y1));
        var latLong2 = map.PixelToLatLong(new VEPixel(x2, y2));

        if (air && water) 
        {
            if (oldAir && oldWater) 
            {
                tempHash = stationHash;
            }
            
            ScriptablePushpinService.GetStationDescriptionsForMapBoundaries(latLong1.Latitude, latLong2.Longitude, latLong2.Latitude, latLong1.Longitude, null, stationAmount, map.GetZoomLevel(), GetStationDescriptionsForMapBoundaries_OnSuccess, GetStationDescriptionsForMapBoundaries_OnFailed);            
        }
        else if (air) 
        {
            if (oldAir)
            {
                tempHash = stationHash;
            }

            ScriptablePushpinService.GetStationDescriptionsForMapBoundaries(latLong1.Latitude, latLong2.Longitude, latLong2.Latitude, latLong1.Longitude, "Air", stationAmount, map.GetZoomLevel(), GetStationDescriptionsForMapBoundaries_OnSuccess, GetStationDescriptionsForMapBoundaries_OnFailed);
        }
        else if (water) 
        {
            if (oldWater) 
            {
                tempHash = stationHash;
            }

            ScriptablePushpinService.GetStationDescriptionsForMapBoundaries(latLong1.Latitude, latLong2.Longitude, latLong2.Latitude, latLong1.Longitude, "Water", stationAmount, map.GetZoomLevel(), GetStationDescriptionsForMapBoundaries_OnSuccess, GetStationDescriptionsForMapBoundaries_OnFailed);
        }

        oldAir = air;
        oldWater = water;
    }
}

var tempHash = new Object();

function GetStationDescriptionsForMapBoundaries_OnSuccess(result) {
    if (result != null) {
        var stationArray = result;
        HideAllTileLayers();
        for (var i = 0; i < stationArray.length; i++) {
            if (!isStationIdLoaded(stationArray[i].StationId)) {
                var latLong = new VELatLong(stationArray[i].Latitude, stationArray[i].Longitude);
                var shape = new VEShape(VEShapeType.Pushpin, latLong);
                var localIcon = stationIconNoData.replace(/id=""/, "id='" + stationArray[i].StationId.toString() + "'");
                var value;

                switch (stationArray[i].StationPurpose) {
                    case "Water":
                        value = "EEAWater";
                        break;
                    case "Air":
                    default:
                        value = "EEAAir";
                        break;
                }

                if (stationArray[i].QualityIndex == 0 || stationArray[i].QualityIndex == null) {
                    value += "NoData";
                } else {
                    value += stationArray[i].QualityIndex.toString();
                }

                localIcon = localIcon.replace(/ICON/, value);
                shape.SetCustomIcon(localIcon);
                stationLayer.AddShape(shape);
                stationHash[stationArray[i].StationId.toString()] = shape;
            }
            else {
                stationHash[stationArray[i].StationId.toString()] = tempHash[stationArray[i].StationId.toString()];
            }
            stationLayer.Show();
        }
    } else {
        ShowSelectedTileLayers();
    }
}

function isStationIdLoaded(stationId) {
    for (var i in tempHash) {
        if (stationId == i) {
            return true;
        }
    }
    return false;
}

function GetStationDescriptionsForMapBoundaries_OnFailed(result) {
    // alert("Get stations failed - " + result);
}

function GetStation(stationId) {
    ScriptablePushpinService.GetStationHtml(stationId, stationId, userCulture, GetStation_OnSuccess, GetStation_OnFailed);
    return true;
}

function GetStation_OnSuccess(result) {

    if (stationHash[result.Id.toString()] == undefined) {
        stationHash[result.Id.toString()] = tempStation;
    }

    stationHash[result.Id.toString()].SetDescription(result.Html);
    
    var loadingDiv = $("#loading").parent().parent();
    if (loadingDiv.html() != null) {
        loadingDiv.html(result.Html);
    }
    else {
        $("#Pushpin").parent().html(result.Html);
    }
}

function GetStation_OnFailed(result) {
    // alert("Get station failed - " + result);
}

function GetPushpin(id, latitude, longitude) {
    ScriptablePushpinService.GetPushpinHtml(id, latitude, longitude, userCulture, GetPushpin_OnSuccess, GetPushpin_OnFailed);
    return true;
}

function GetCurrentPushpin(id, latitude, longitude) {
    ScriptablePushpinService.GetPushpinHtml(id, latitude, longitude, userCulture, GetCurrentPushpin_OnSuccess, GetPushpin_OnFailed);
    return true;
}

function GetCurrentPushpin_OnSuccess(result) {
    if (pushpins[result.Id] != null) {
        pushpins[result.Id].SetDescription(result.Html);
        if (result.HasData == true) {
            pushpins[result.Id].SetCustomIcon(pushpinIcon);
        }   
             
        var loadingDiv = $("#loading").parent().parent();
        if (loadingDiv.html() != null) {
                loadingDiv.html(result.Html);
        }
        else {
                $("#Pushpin").parent().html(result.Html);
        }
    }
}

function GetPushpin_OnSuccess(result) {
    if (pushpins[result.Id] != null) {
        pushpins[result.Id].SetDescription(result.Html);
        if (result.HasData == true) {
            pushpins[result.Id].SetCustomIcon(pushpinIcon);
        }
    }
}

function GetPushpin_OnFailed(result) {
    // alert("Get pushpin failed - " + result);
}

function RemovePushPins() {
    for (var i = 0; i < pushpins.length; i++) {
        deleteCookie("pushpin" + i);
        map.DeleteShape(pushpins[i]);
    }

    pushpins = new Array();
}

var newPushPin = false;

function DragNewPushPin() {
    if (dragShape != null && dragShape != map) {
        dragShape.Hide();
        dragShape = null;
    }
    else {
        var x = -1;
        var y = -1;
        pixel = new VEPixel(x, y);
        var LL = map.PixelToLatLong(pixel);
        var shape = new VEShape(VEShapeType.Pushpin, LL);
        shape.SetCustomIcon(pushpinIconNoData);
        pushpinLayer.AddShape(shape);
        dragShape = shape;
        dragShape.SetPoints(LL);
        newPushPin = true;
    }
}

function StartZoomHandler(e) {
    ClosePushpinControl();
    stationLayer.Hide();
}

function EndZoomHandler(e) {
    if (e.eventName == "onendzoom") {
        if (map.GetZoomLevel() > stationZoomLevel - 1) {
            getStations = true;
            oldCenterLocation = map.GetCenter();
            GetStations();
        }
        else {
            getStations = false;
            ShowSelectedTileLayers();
        }
    }
}

function MouseHandler(e) {
    if (e.eventName == "onmousedown") {
        $(".dropdown dd ul").hide();
    }

    if (e.eventName == "onmousedown" && e.elementID != null) {
        OnMouseDown(e);
    }
    else if (e.eventName == "onmousedown" && e.elementID == null) {
        ClosePushpinControl();
    }
    else if (e.eventName == "onmouseup" && dragShape != null && dragShape != map) {
        PushPinOnMouseUp(e);
    }
    else if (e.eventName == "onmouseup" && getStations == true) {
        GetStationTrueOnMouseUp();
    }
    else if (e.eventName == "onmousemove" && dragShape != null && dragShape != map) {
        handlePushPinOnMouseMove(e);
        return true; // prevent the default action
    }
}

function OnMouseDown(e){
        dragShape = map.GetShapeByID(e.elementID);
        if (dragShape._customIcon.indexOf("RatingIcons", 0) > 0) {
            disableInfoBoxHide();
        }
        
        if (dragShape._customIcon.indexOf("PushPin", 0) <= 0) {
            dragShape = map;
            return;
        } 

        if (!newPushPin) {
            disableInfoBoxHide();
            startX = e.mapX;
            startY = e.mapY;
        }
        
        return true;
}

function PushPinOnMouseUp(e){
        var x = e.mapX;
        var y = e.mapY;

        if (startX != x && startY != y) {        
            pixel = new VEPixel(x, y);
            var LL = map.PixelToLatLong(pixel);
            if (newPushPin) {
                placePushPin(LL.Latitude, LL.Longitude, false);
            }
            else {
                placePushPin(LL.Latitude, LL.Longitude, true);
            }
            
            newPushPin = false;
        }
    
        dragShape = null;
}

function GetStationTrueOnMouseUp(){
        dragShape = null;
        GetStations();
}

function handlePushPinOnMouseMove(e) {
        var x = e.mapX;
        var y = e.mapY;
        if (startX != x && startY != y) {
            ClosePushpinControl();
            pixel = new VEPixel(x, y);
            var LL = map.PixelToLatLong(pixel);
            dragShape.SetCustomIcon(pushpinIconNoData);
            dragShape.SetPoints(LL);
        }
}

function searchEnter(e) {
    e = e || window.event;
    var code = e.keyCode || e.which;
    if (code == 13)
        FindLoc(document.getElementById('SearchLocationTextBox').value);
}

function placePushPin(latitude, longitude, current) {
    var LL = new VELatLong(latitude, longitude, 0);
    var pushPinID;
    if (current) {
        dragShape.SetDescription(loadingHtml);
        pushPinID = dragShape.GetTitle();    
        deleteCookie(pushPinID);
        dragShape.SetPoints(LL);
        pushpins[pushPinID] = dragShape;
        GetCurrentPushpin(pushPinID, LL.Latitude, LL.Longitude);      
    }
    else if (newPushPin) {
        pushPinID = pushpins.length;
        dragShape.SetPoints(LL);
        dragShape.SetTitle(pushPinID.toString());
        dragShape.SetDescription(loadingHtml);
        pushpins[pushPinID] = dragShape;
        GetCurrentPushpin(pushPinID, LL.Latitude, LL.Longitude);
    }
    else{
        pushPinID = pushpins.length;
        var shape = new VEShape(VEShapeType.Pushpin, LL);
        shape.SetCustomIcon(pushpinIconNoData);
        shape.SetTitle(pushPinID.toString());
        shape.SetDescription(loadingHtml);
        pushpinLayer.AddShape(shape);
        var stationShape = shape;
        stationShape.SetPoints(LL);
        pushpins[pushPinID] = stationShape;
        GetPushpin(pushPinID, LL.Latitude, LL.Longitude);
    }
   
    setCookie("pushpin" + pushPinID, latitude + "," + longitude, 365);
}

function MapResize(firstLoad) {
    var heightChange = $("#banner").height() + $("#eoeControls").height();
    if (map != null) {
        if (typeof (window.innerWidth) == 'number') {
            //Non-IE
            var newHeight = window.innerHeight - heightChange
            if (!firstLoad) {
                map.Resize(window.innerWidth, newHeight);
            }
            else {
                $("#myMap").height(newHeight);
                $("#myMap").width(window.innerWidth);                
            } 
            $("#mapContainer").height(newHeight);
        }
        else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            var newHeight = document.documentElement.clientHeight - heightChange
            if (!firstLoad) {
                map.Resize(document.documentElement.clientWidth, newHeight);
            }
            else {
                $("#myMap").height(newHeight);
                $("#myMap").width(document.documentElement.clientWidth);
            }
            $("#mapContainer").height(newHeight);
        }
        SetLegendWidth();
    }
}