﻿var map = null;
var BaseShapeLayer = null;
var mapCenter = null;
var mapZoom = 5;
var CurrentShape = null;
var PinCenter = null;
var MapContainer = null;
var dealerLocatorBaseUrl = '/__service/OneChem.Modules.DealerLocator/';

$(document).ready(function() {
    MapContainer = $("#MapContainer");
    mapCenter = new VELatLong(53.808760650677456, -1.510620117187513);
//    mapCenter = new VELatLong(49.993615, 9.624023);

    
    $(".txtSearch").data("OriginalText",$(".txtSearch").val());
    $(".txtSearch").focus(function() {
        if ($(this).val() == $(".txtSearch").data("OriginalText")) {
            $(this).val('');
        }
    })
    .blur(function() {
        if ($(this).val() == '') {
            $(this).val($(".txtSearch").data("OriginalText"));
        }
    });
    //    VEMap.Find(what, where, findType, shapeLayer, startIndex, numberOfResults, showResults, createResults, useDefaultDisambiguation, setBestMapView, callback);
    $(".btnSearch").click(function() {
        var queryText = $(".txtSearch").val();
        if (queryText != '' && queryText != 'Search') {
            map.Find('',
                queryText + ', ' + MapContainer.data("CurrentCountryCode") ,
                null,
                null,
                null,
                null,
                true,
                true,
                false,
                false,
                Map_FoundSearchLocation);
            //        $.postJSON(dealerLocatorBaseUrl + 'Search', { query: queryText }, function(dealerSearchResult) {
            //            // alert($.compactJSON(dealerSearchResult.items));
            //            $("#KeywordSearchResults").html(dealerSearchResult.markup);
            //            AddLocations(dealerSearchResult.items);
            //        });
        }
    });
    $("#txtSearch").enterPressed(function() { $(".btnSearch").click(); });

});

function RegisterPlaceOptionClicks() {
    var placeOptionLinks = $("#PlaceOptionLinks");
    placeOptionLinks.find("li").each(function() {
        $(this).click(function() {
            var index = $(this).attr("rel");
            var placeOptions = $("#MapContainer").data("PlaceOptions");
            SetPlaceLocation(placeOptions[index]);
            $(this).parents(".messageBox:first").remove();
            $("#MapContainer").data("PlaceOptions", null);
        });
    });
}

function SetPlaceLocation(place) {
    var latitude = place.LatLong.Latitude;
    var longitude = place.LatLong.Longitude;
    //map.SetCenter(place.LatLong);
    map.SetCenterAndZoom(place.LatLong, 8);
    $("#MapContainer").data("CurrentPage", 1)
    $.postJSON('/__service/OneChem.Modules.DealerLocator/SearchByLocation', {
        latitude: latitude,
        longitude: longitude,
        currentPage: $("#MapContainer").data("CurrentPage"),
        itemsPerPage: $("#MapContainer").data("ItemsPerPage"),
        pages: 1
    }, function(response) {
        BaseShapeLayer.DeleteAllShapes();
        $(".dealerList").html(response.markup);
        $(".viewAll").click(function() {
            $.postJSON('/__service/OneChem.Modules.DealerLocator/ResetToAllDealers', {
                currentPage: 1,
                itemsPerPage: $("#MapContainer").data("ItemsPerPage")
            }, function(response) {
                $(".dealerList").html(response.markup);
                map.SetCenterAndZoom(mapCenter, mapZoom);
            });
        });
    });
}


function Map_FoundSearchLocation(layer, resultsArray, places, hasMore, veErrorMessage) {
    places = GetConfidentMatches(places);
    if (places.length > 1) {
        var mapContainer = $("#MapContainer");
        mapContainer.data("PlaceOptions", places);
        var placeOptionLinks = '<ul id="PlaceOptionLinks">';
        for (var i = 0; i < places.length; i++) {
            placeOptionLinks += '<li rel="'+i+'">'+places[i].Name+'</li>';
        }
        placeOptionLinks += '<ul>';
        fn_DisplayMessage(mapContainer, placeOptionLinks,RegisterPlaceOptionClicks);
    }
    else {
        SetPlaceLocation(places[0]);
    }
}

function GetConfidentMatches(places) {
    var confidentMatches = Array();
    for (var i = 0; i < places.length; i++) {
//        if (places[i].MatchConfidence == 1) {
        if (MapContainer.data("CurrentCountryCode") == "UK") {
            if (places[i].LatLong.Longitude > -10) {
                confidentMatches.push(places[i]);
            }
        }
        else {
            confidentMatches.push(places[i]);
        }
    }
    if (confidentMatches.length > 0) {
        return confidentMatches;
    }
    else {
        return places;
    }
}



function LoadLocations() {
    var map = $("#MapContainer");
    var postcodeDealers = map.data("PostcodeDealers");
    var coordinateDealers = map.data("CoordinateDealers");

    if (postcodeDealers.length > 0) {
        LoadNextPostcode();
    }
    if (coordinateDealers.length > 0) {
        AddLocationsFromCoordinates();
    }
}

function SaveDealer(dealer) {
    $.postJSON('/__service/OneChem.Core.Dealer/UpdateCoordinates', { dealer: $.compactJSON(dealer) }, function(response) { });
}

function DisplayPage() {
    $.postJSON('/__service/OneChem.Modules.DealerLocator/DisplayPage', { 
        itemsPerPage: $("#MapContainer").data("ItemsPerPage"),
        currentPage: $("#MapContainer").data("CurrentPage")
        }, function(response) { 
            BaseShapeLayer.DeleteAllShapes();
            $(".dealerList").html(response.markup);        
        });
}

function AddLocationsFromCoordinates() {
    var dealers = $("#MapContainer").data("CoordinateDealers");
    for (var i = 0; i < dealers.length; i++) {
        dealers[i].PinID = AddLocation(dealers[i]);
    }
}

function AddLocation(dealer) {
    var tmpLat = parseFloat(dealer.Latitude);
    var tmpLong = parseFloat(dealer.Longitude);
    var LL = new VELatLong(tmpLat, tmpLong);
    var pin = new VEShape(VEShapeType.Pushpin, LL);
    pin.SetTitle(addslashes('<h4 class="mapTitle">' + stripslashes(dealer.Title) + '</h4>'));
    pin.SetDescription('<div class="mapInfoBox">' + stripslashes(dealer.FullAddress) + '<br />' + stripslashes(dealer.PostCode) + '<br />' + stripslashes(dealer.Telephone) + (dealer.Website != undefined && dealer.Website != '' ? '<a target="_blank" href="http://' + dealer.Website +'">' + dealer.Website + '</a>' : '') + '<div class="clear">&nbsp;</div></div>');
    BaseShapeLayer.AddShape(pin);
    var pinID = pin.GetID();

    $("#" + dealer.DataObjectID)
        .mouseenter(function() {
            $("#MapContainer").data("CurrentPinID", SearchDealersByVarForVar('DataObjectID', $(this).attr("ID"), 'PinID'));
            map.AttachEvent("onendpan", Map_OnEndPan);
            map.SetCenter(new VELatLong(pin.Latitude, pin.Longitude));
        })
        //.mouseout(function() { map.HideInfoBox(CurrentShape); });

    return pinID;
}

function ShowCurrentInfoBox() {
    var pin = map.GetShapeByID($("#MapContainer").data("CurrentPinID"));
    map.ShowInfoBox(pin);
}

function Map_OnEndPan() {
    $("#MapContainer").oneTime(500, 'ShowCurrentInfoBox', ShowCurrentInfoBox);
    map.DetachEvent("onendpan", Map_OnEndPan);
}

function SearchDealersByVarForVar(searchProp, searchvalue, returnProp) {
    var dealers = FullListOfDealers();
    var search = $.grep(FullListOfDealers(), function(i) {
        return i[searchProp] == searchvalue;
    })
    if (search.length > 0) {
        return search[0][returnProp];
    }
    return null;
}

function FullListOfDealers() {
    if ($("#MapContainer").data("Dealers") == undefined ||
        $("#MapContainer").data("Dealers") == null ||
        $("#MapContainer").data("Dealers").length == 0) {
        $("#MapContainer").data("Dealers", new Array());
        var postcodeDealers = $("#MapContainer").data("PostcodeDealers");
        var coordinateDealers = $("#MapContainer").data("CoordinateDealers");
        $("#MapContainer").data("Dealers", $.merge(postcodeDealers, coordinateDealers));
    }
    return $("#MapContainer").data("Dealers");
}

function Map_OnMouseEvent(mapEvent) {
    var currentPinID = mapEvent.elementID.substr(0, mapEvent.elementID.lastIndexOf("_"));
    $("#MapContainer").data("CurrentPinID", currentPinID);
    var dataObjectID = SearchDealersByVarForVar('PinID', currentPinID, 'DataObjectID');
    switch (mapEvent.eventName) {
        case "onmouseover":
            $("#" + dataObjectID).addClass("hover");
            break;
        case "onmouseout":
            $("#" + dataObjectID).removeClass("hover");
            break;
    }
}

function LoadMap() {
    if (MapContainer.data("DefaultMapCenter") != undefined) {
        mapCenter = MapContainer.data("DefaultMapCenter");
    }
    map = new VEMap('MapContainer');
    map.LoadMap(mapCenter, mapZoom);
    map.useDefaultDisambiguation = false;
    map.ShowMessageBox = false;
    BaseShapeLayer = new VEShapeLayer();
    map.AddShapeLayer(BaseShapeLayer);
    map.AttachEvent("onmouseover", Map_OnMouseEvent);
    map.AttachEvent("onmouseout", Map_OnMouseEvent);

}

function LoadNextPostcode() {
    var postcodeDealers = $("#MapContainer").data("PostcodeDealers");
    var currentPostcodeIndex = $("#MapContainer").data("CurrentPostcodeIndex");
    if (postcodeDealers.length > 0) {
        results = map.Find('',
                (postcodeDealers[currentPostcodeIndex].PostCode != '' && 
                    postcodeDealers[currentPostcodeIndex].PostCode != null && 
                    postcodeDealers[currentPostcodeIndex].PostCode != undefined ?
                    postcodeDealers[currentPostcodeIndex].PostCode : postcodeDealers[currentPostcodeIndex].FullAddress + ', ' + $("#MapContainer").data("CurrentCountryCode")),
                null,
                null,
                null,
                null,
                true,
                true,
                true,
                true,
                AddPostcodePin);
    }
}

function AddPostcodePin(layer, resultsArray, places, hasMore, veErrorMessage) {
    var map = $("#MapContainer");
    var postcodeDealers = map.data("PostcodeDealers");
    var currentPostcodeIndex = map.data("CurrentPostcodeIndex");
    var dealer = postcodeDealers[currentPostcodeIndex];

    if (places != null) {
        dealer.Latitude = places[0].LatLong.Latitude.toString();
        dealer.Longitude = places[0].LatLong.Longitude.toString();
        SaveDealer(dealer);
        AddLocation(dealer);
    }
    else if (resultsArray == null) {
        dealer.AddressNotFound = true;
        SaveDealer(dealer);
    }

    map.data("CurrentPostcodeIndex", (currentPostcodeIndex + 1));

    if (map.data("CurrentPostcodeIndex") < postcodeDealers.length) {
        LoadNextPostcode();
    }
}


function HighlightPostcodeMapLocation(markerId) {
    var id = PostcodeLocations[markerId];
    if (id != null) {
        CurrentShape = BaseShapeLayer.GetShapeByIndex(markerId);
        map.ShowInfoBox(CurrentShape);
    }
}

function HidePostcodeMapLocation(markerId) {
    var id = PostcodeLocations[markerId];
    if (id != null) {
        CurrentShape = BaseShapeLayer.GetShapeByIndex(markerId);
        map.HideInfoBox(CurrentShape);
    }
}


function addslashes(str) {
    if (str != null && str != undefined && str != "undefined") {
        str = str.replace(/\\/g, '\\\\');
        str = str.replace(/\'/g, '\\\'');
        str = str.replace(/\"/g, '\\"');
        str = str.replace(/\0/g, '\\0');
    }
    else {
        str = "";
    }
    return str;
}
function stripslashes(str) {
    if (str != null && str != undefined && str != "undefined") {
        str = str.replace(/\\'/g, '\'');
        str = str.replace(/\\"/g, '"');
        str = str.replace(/\\0/g, '\0');
        str = str.replace(/\\\\/g, '\\');
    }
    else {
        str = "";
    }
    return str;
}

/* END - CALLED DIRECTLY FROM MAP APP */

