﻿var COORDINATES = {
    unitedStates: new VELatLong(45.84028105450087, -88.05816650390625),
    canada: new VELatLong(45.01141864227728, -78.629150390625),
    germany: new VELatLong(50.33143633083883, 10.711669921874986),
    france: new VELatLong(46.72480037466718, 3.5925292968750107),
    japan: new VELatLong(35.15584570226544, 136.05194091796875),
    iceland: new VELatLong(64.9793592199603, -19.302978515625003),
    switzerland: new VELatLong(46.80005944678731, 8.228759765625001),
    turkey: new VELatLong(39.60568817832082, 31.343994140625007),
    slovenia: new VELatLong(46.11998152139192, 14.821040923422231),
    austria: new VELatLong(47.59134647679711, 13.63403320312499)
};
var DEALER_LIST_TEMPLATE = "<li><div class=\"address\"><span class=\"name\">{Name}</span><span class=\"mailAddress\">{Address1}</span><span class=\"shipAddress\">{Address2}</span><span class=\"locality\">{City}</span>, <span class=\"region\">{State}</span> <span class=\"postalCode\">{PostalCode}</span><span class=\"country\">{Country}</span></div><div class=\"phone\">{Phone}</div><div class=\"webSite\"><a href=\"{WebSite}\" target=\"_blank\">{WebSite}</a></div></li>";
var INFOBOX_TEMPLATE = "<a id=\"close\" title=\"Close\">Close</a><div class=\"address\"><span class=\"name\">{Name}</span><span class=\"mailAddress\">{Address1}</span><span class=\"shipAddress\">{Address2}</span><span class=\"locality\">{City}</span>, <span class=\"region\">{State}</span> <span class=\"postalCode\">{PostalCode}</span><span class=\"country\">{Country}</span></div><div class=\"phone\">{Phone}</div><div class=\"webSite\"><a href=\"{WebSite}\" target=\"_blank\">{WebSite}</a></div>";
var MESSAGES = {
    invalidZoom: "Cannot display results at this zoom level. Please zoom in.",
    noResults: "There are no results for this area. Try moving or zooming out on the map to get more results."
};
var PAN_DELTAS = {
    northwest: { x: -100, y: -100 },
    north: { x: 0, y: -100 },
    northeast: { x: 100, y: -100 },
    east: { x: 100, y: 0 },
    southeast: { x: 100, y: 100 },
    south: { x: 0, y: 100 },
    southwest: { x: -100, y: 100 },
    west: { x: -100, y: 0 }
};
var PUSHPINS = {
    bluePin: "/content/images/bluepin.gif",
    bullseye: "/content/images/bullseye.gif",
    redPin: "/content/images/redpin.gif",
    yellowPin: "/content/images/yellowpin.gif"
};

var activeDealerIndex = -1;
var dealerLayer = null;
var dealerList = [];
var map = null;
var myLocationLayer = null;

$(function() {
    $.ajaxSetup({
        type: "GET",
        dataType: "json",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("__AjaxRequest", "true");
        }
    });

    map = new VEMap("map");
    map.LoadMap(null, null, null, null, null, false, null, null);
    map.HideDashboard();
    myLocationLayer = new VEShapeLayer();
    dealerLayer = new VEShapeLayer();
    map.AddShapeLayer(myLocationLayer);
    map.AddShapeLayer(dealerLayer);

    map.AttachEvent("onchangemapstyle", function() {
        var viewRoad = $("#viewRoad").removeClass("active");
        var viewAerial = $("#viewAerial").removeClass("active");
        if (map.GetMapStyle() == VEMapStyle.Hybrid)
            viewAerial.addClass("active");
        else
            viewRoad.addClass("active");
    });
    map.AttachEvent("onendzoom", function() {
        if (map.GetZoomLevel() < 6) {
            $("#dealerList").empty();
            dealerLayer.DeleteAllShapes();
            $("#mapMessage").text(MESSAGES.invalidZoom).show();
        }
        else {
            $("#mapMessage").hide();
            getDealersWithinViewBox();
        }
    });
    map.AttachEvent("onendpan", function() {
        if (map.GetZoomLevel() < 6) {
            $("#dealerList").empty();
            dealerLayer.DeleteAllShapes();
            $("#mapMessage").text(MESSAGES.invalidZoom).show();
        }
        else {
            $("#mapMessage").hide();
            getDealersWithinViewBox();
        }
    });
    map.AttachEvent("onmouseover", function(e) {
        var shape = map.GetShapeByID(e.elementID);
        if (shape && dealerLayer.GetShapeByID(shape.GetID()))
            setActiveDealer(shape.GetIndex());
    });
    map.AttachEvent("onmouseout", function(e) {
        setActiveDealer(-1);
    });
    map.AttachEvent("onmousedown", function(e) {
        showInfobox(-1);
    });
    map.AttachEvent("onclick", function(e) {
        var shape = map.GetShapeByID(e.elementID);
        if (shape && dealerLayer.GetShapeByID(shape.GetID()))
            showInfobox(shape.GetIndex());
    });

    $().mousedown(function(e) {
        showInfobox(-1);
    });
    $("#infobox").mousedown(function(e) {
        e.stopPropagation();
    });

    $("#countryList li").click(function(e) {
        var latLong = COORDINATES[this.id];
        if (latLong) {
            $("#countryContainer").fadeOut(500);
            map.SetCenterAndZoom(latLong, 6);
            getDealersWithinViewBox();
        }
    });
    $("#mapNavigation a").click(function(e) {
        var delta = PAN_DELTAS[this.id];
        if (delta)
            map.Pan(delta.x, delta.y);
    });
    $("#zoomNavigation a").click(function(e) {
        switch (this.id) {
            case "zoomIn":
                map.ZoomIn();
                break;
            default:
                map.ZoomOut();
                break;
        }
    });
    $("#viewNavigation a").click(function(e) {
        var style = (this.id == "viewAerial") ? VEMapStyle.Hybrid : VEMapStyle.Road;
        if (map.GetMapStyle() != style)
            map.SetMapStyle(style);
    });

    $("#searchButton").click(function(e) {
        findMyLocation($("#locationTextBox").val());
    });
    $("#locationTextBox").keypress(function(e) {
        if (e.which == 13) {
            findMyLocation(this.value);
            return false;
        }
        return true;
    });
});
var findMyLocation = function(address) {
    $("#countryContainer").fadeOut(500);
    myLocationLayer.DeleteAllShapes();
    map.Find(null, address, null, null, null, 1, false, false, true, null, function(a, b, results, hasMore, c) {
        if (results && (results.length > 0)) {
            var myLocation = results[0];
            var shape = new VEShape(VEShapeType.Pushpin, myLocation.LatLong);
            shape.SetCustomIcon(PUSHPINS.bullseye);
            myLocationLayer.AddShape(shape);
            map.SetCenterAndZoom(myLocation.LatLong, parseInt($("#distanceDropDownList").val()));
            getDealersWithinViewBox();
        }
    });
};
var getDealersWithinViewBox = function() {
    var view = map.GetMapView();
    var center = map.GetCenter();
    var loading = $("#dealerContainerLoading").show();
    $.ajax({
        url: "DealerLocator",
        data: {
            format : "json",
            NorthwestLatitude: view.TopLeftLatLong.Latitude,
            NorthwestLongitude: view.TopLeftLatLong.Longitude,
            SoutheastLatitude: view.BottomRightLatLong.Latitude,
            SoutheastLongitude: view.BottomRightLatLong.Longitude,
            SortLatitude: center.Latitude,
            SortLongitude: center.Longitude
        },
        success: function(result) {
            dealerList = result.Entries;
            plotDealers(dealerList);
            listDealers(dealerList);
            loading.hide();
        }
    });
};
var listDealers = function(dealers) {
    $("#dealerContainer")
        .empty()
        .append($("<ul id=\"dealerList\"></ul>"))
        .children()
        .appendTemplate(dealers, DEALER_LIST_TEMPLATE)
        .children()
        .each(function(index) {
            $(this)
                .click(function(e) {
                    showInfobox(index);
                })
                .mouseover(function(e) {
                    setActiveDealer(index);
                })
                .mouseout(function(e) {
                    setActiveDealer(-1);
                });
        });
};
var plotDealers = function(dealers) {
    dealerLayer.DeleteAllShapes();
    $.each(dealers, function(index, dealer) {
        var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(dealer.Latitude, dealer.Longitude));
        shape.SetCustomIcon(dealer.IsDistributor ? PUSHPINS.redPin : PUSHPINS.bluePin);
        dealerLayer.AddShape(shape);
    });
};
var setActiveDealer = function(index) {
    if (index != activeDealerIndex) {
        if (activeDealerIndex > -1) {
            var shape = dealerLayer.GetShapeByIndex(activeDealerIndex);
            if (shape)
                shape.SetCustomIcon(dealerList[activeDealerIndex].IsDistributor ? PUSHPINS.redPin : PUSHPINS.bluePin);
            $("#dealerList li:nth-child(" + (activeDealerIndex + 1) + ")").removeClass("hover");
            activeDealerIndex = -1
        }
        if ((index > -1) && (index < dealerList.length)) {
            var shape = dealerLayer.GetShapeByIndex(index);
            if (shape)
                shape.SetCustomIcon(PUSHPINS.yellowPin);
            $("#dealerList li:nth-child(" + (index + 1) + ")").addClass("hover");
            activeDealerIndex = index;
        }
    }
};
var showInfobox = function(index) {
    var shape = dealerLayer.GetShapeByIndex(index);
    if (shape) {
        var point = map.LatLongToPixel(shape.GetIconAnchor());
        $("#infobox")
            .appendTemplate(dealerList[index], INFOBOX_TEMPLATE)
            .children("#close").click(function(e) {
                showInfobox(-1);
            })
            .end()
            .css({
                left: point.x + "px",
                top: point.y + "px"
            })
            .show();
    }
    else
        $("#infobox").hide();
};