﻿//AJ: Requires CssBrowserSelector.js
 
//AJ: Fields
var map;
var currentLocationShape;
var resultShapes;
var panningToShape;
var canSendDirections;
var canSendMainResults;
var directionsEmail;
var mainResultsEmail;
var destinationPng;
var destinationAddressPrint;
var destinationAddresses;
var hider;
 
function GetMap()
{
    PageMethods.GetVirtualEarthToken(GetVirtualEarthTokenCallback);
}
 
function GetVirtualEarthTokenCallback(token)
{
    map = new VEMap('myMap');
    
    map.SetClientToken(token);
    map.AttachEvent("onendpan", MapMoved);
    map.AttachEvent("onchangeview", MapMoved);

    var mapOptions = new VEMapOptions();
    mapOptions.EnableBirdseye = false;
    
    map.LoadMap(new VELatLong(mapInitalLat, mapInitalLon), mapInitalZoom, VEMapStyle.Road, false, VEMapMode.Mode2D, false, 1, mapOptions);
    
    var veDistanceUnit;

    if (distanceUnit == "Kilometers")
        veDistanceUnit = VEDistanceUnit.Kilometers;
    else
        veDistanceUnit = VEDistanceUnit.Miles;

    map.SetScaleBarDistanceUnit(veDistanceUnit);

    hider = new EroHide(map);
    hider.Init();
}

function FindLocation(location)
{
    try
    {
        ResetMap();
        results = map.Find(null, location, null, null, 0, 10, true, true, false, false, FoundLocationCallback);
    }
    catch (e) { }
}

function ResetMap()
{
    currentLocationShape = null;
    resultShapes = null;
    panningToShape = null;
    
    destinationAddressPrint = '';
    directionsEmail = '';
    mainResultsEmail = '';
    
    canSendDirections = false;
    canSendMainResults = false;
    
    destinationShape = null;
    
    $('#DirectionsDiv').html(directionsInstructions);
    $('#QuickResultsDiv').html("");
    $('#MainResultsDiv').html("");

    map.Clear();
    GoToDefaultView();
}

function GoToDefaultView()
{
    if (currentLocationShape == null)
    {
        map.SetCenterAndZoom(new VELatLong(mapInitalLat, mapInitalLon), mapInitalZoom);
    }
    else
    {
        GoToPinAndShow(currentLocationShape);
    }
}

function GoToPinIndexAndShow(shapeIndex)
{
    var shape = resultShapes[shapeIndex];
    GoToPinAndShow(shape);
}

function GoToPinAndShow(shape)
{
    var center = map.GetCenter();

    if (RoundNumber(center.Latitude, 9) == shape.Latitude && RoundNumber(center.Longitude, 9) == shape.Longitude && map.GetZoomLevel() == 17)
    {
        map.ShowInfoBox(shape);
    }
    else
    {
        panningToShape = shape;
        map.SetCenterAndZoom(new VELatLong(panningToShape.Latitude, panningToShape.Longitude), 17);
        //AJ: Show is done in MapMoved()
    }
}

function ShowDirections(shapeIndex)
{
    var destinationShape = resultShapes[shapeIndex];
    
    directionsEmail = destinationAddresses[shapeIndex] + "\n\n";
    destinationAddressPrint = destinationShape.GetTitle() + "<br/>" + destinationShape.GetDescription();
    destinationPng = destinationShape.GetCustomIcon().split("'")[1];
    
    var locations = new Array();
    locations[0] = new VELatLong(currentLocationShape.Latitude, currentLocationShape.Longitude);
    locations[1] = new VELatLong(destinationShape.Latitude, destinationShape.Longitude);
    
    var routeOptions = new VERouteOptions();
    routeOptions.DistanceUnit = VERouteDistanceUnit.Kilometer; //TODO: AJ: This should be internationalized.
    routeOptions.RouteCallback = RouteCallback;
    routeOptions.RouteMode = VERouteMode.Driving; //TODO: AJ: This should be configurable via radio button.
    routeOptions.UseMWS = false;

    map.GetDirections(locations, routeOptions);
}

function changeClass(myElementID) 
{
    if(document.getElementById(myElementID).className == "normal") 
    {
        document.getElementById(myElementID).className = "highlight";
    }
    else 
    {
        document.getElementById(myElementID).className = "normal";
    }
}

//AJ: Event Handlers

function LookupButtonClick()
{
    FindLocation($('#LocationToLookupTextBox').val());
}

function LocationToLookupTextBoxKeyDown(e)
{
    var keyCode = (e.which) ? e.which : e.keyCode;
    
    if(keyCode == 13)
    {
        LookupButtonClick();
        return false;
    }
    else
    {
        return true;
    }
}

function MapMoved()
{
    if (panningToShape != null)
    {
        setTimeout(function()
        {
            map.ShowInfoBox(panningToShape);
            panningToShape = null;
        }, 10);  //AJ: Have to wait 10ms otherwise the pin wont show ... wierd
    }
}

function LocationToLookupTextBoxFocus() 
{
    if ($('#LocationToLookupTextBox').val() == locationToLookupTextBoxEmptyText) 
        $('#LocationToLookupTextBox').val('');
}

function LocationToLookupTextBoxBlur() 
{
    if ($('#LocationToLookupTextBox').val() == '') 
        $('#LocationToLookupTextBox').val(locationToLookupTextBoxEmptyText);
}

function PrintDirectionsClick()
{
    if(canSendDirections)
    {
        var sendData = destinationAddressPrint + "<br/>" + $('#DirectionsContainerDiv').html();
        PageMethods.SetSendData(sendData, SetPrintDataCallback);
    }
    else
    {
        alert(noDirectionsToPrint);
    }
}

function PrintMainResultsClick()
{
    if(canSendMainResults)
    {
        PageMethods.SetSendData($('#MainResultsDivContainerDiv').html(), SetPrintDataCallback);
    }
    else
    {
        alert(noResultsToPrint);
    }
}

function SetPrintDataCallback()
{
    window.open('Print.aspx', 'open_window', 'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0');
}

function EmailDirectionsClick()
{
    if(canSendDirections)
    {
        PageMethods.EncodeForMailTo(directionsEmail, SendEmail);
    }
    else
    {
        alert(noDirectionsToEMail);
    }
}

function EmailMainResultsClick()
{
    if(canSendMainResults)
    {
        SendEmail(mainResultsEmail);
    }
    else
    {
        alert(noResultsToEMail);
    }
}

function SendEmail(body)
{
    var mailToLink = 'mailto:?body=' + body;
    var win = window.open(mailToLink, 'emailWindow');

    if (win && win.open && !win.closed)
        win.close();
}

//AJ: Callbacks

function FoundLocationCallback(layer, resultsArray, places, hasMore, veErrorMessage)
{
    var foundPlace;

    if (places != null && places.length > 0)
    {
        for (var index in places)
        {
            var currentPlace= places[index];
            var polygon = GetValidLocationPolygon();
            var isValidLocation = IsPointWithinPolygon(currentPlace.LatLong, polygon);
            
            if (isValidLocation && (foundPlace == null || places[index].MatchConfidence > places[index].MatchConfidence))
                foundPlace = currentPlace;
        }
        
        if (foundPlace != null)
        {
            var latitude = foundPlace.LatLong.Latitude;
            var longitude = foundPlace.LatLong.Longitude;
            var distance = $('#DistanceDropDown').val();
            
            var sim;
            var topUp;
            
            if($('#SimRadioButton').attr('checked'))
            {
                sim = true;
                topUp = false;
            }
            else if($('#TopUpRadioButton').attr('checked'))
            {
                sim = false;
                topUp = true;
            }
            else if($('#BothRadioButton').attr('checked'))
            {
                sim = true;
                topUp = true;
            }

            currentLocationShape = new VEShape(VEShapeType.Pushpin, new VELatLong(latitude, longitude));
            currentLocationShape.SetTitle("<div class='closebtn'><a onclick='hider.CustomHideInfoBox()'>X</a></div>" + currentLocation);
            
            if ($.browser.msie && parseInt($.browser.version,10) < 7) 
                currentLocationShape.SetCustomIcon("<img src='App_Themes/default/blank.png' style=\"position:absolute; top:-50px; left:-50px;filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='app_themes/default/target.png', sizingMethod=image );\" />"); 
            else        
                currentLocationShape.SetCustomIcon("<img src='App_Themes/default/target.png' style='position:absolute; top:-50px; left:-50px;'/>");
            
            map.AddShape(currentLocationShape);

            PageMethods.FindNearestStores(latitude, longitude, sim, topUp, distance, FindNearestStoresCallback);
        }
        else
        {
            alert(locationNotFoundText);
        }
    }
    else
    {
        alert(locationNotFoundText);
    }
}

function FindNearestStoresCallback(nearestStores)
{
    var nearestStoreLocations = new Array();
    resultShapes = new Object();
    destinationAddresses = new Array();
    
    for (var index in nearestStores)
    {
        var nearestStore = nearestStores[index].Store;
        nearestStoreLocations[index] = new VELatLong(nearestStore.Lat, nearestStore.Lon);
        
        destinationAddresses[index] = nearestStore.Name + "\n" + nearestStore.AddressLine + "\n" + nearestStore.PrimaryCity + "\n" + nearestStore.PostalCode + "\n" + nearestStore.Phone;
        
        var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(nearestStore.Lat, nearestStore.Lon));
        shape.SetTitle("<div class='closebtn'><a onclick='hider.CustomHideInfoBox()'>X</a></div><div style='text-align:left'>" + nearestStore.Retailer + "</div>");
        shape.SetDescription("<div style='text-align:left'>"
        + nearestStore.Name + "<br/>"
        + nearestStore.AddressLine + "<br/>"
        + nearestStore.PrimaryCity + "<br/>"
        + nearestStore.PostalCode + "<br/>" 
        + nearestStore.Phone + "<br/>"
        + "<div id='linksDiv'><span class='links' onclick='ShowDirections(" + index + ");'>" + getDirectionsText + "</span>&nbsp;|&nbsp;<span class='links' onclick='GoToPinIndexAndShow(" + index + ");'>" + zoomToText + "</span></div></div>");
        destinationPng = GetCustomIconName(nearestStore.SimReseller, nearestStore.TopUpReseller, index);
        shape.SetCustomIcon(getPNGFix(destinationPng));
        map.AddShape(shape);
        resultShapes[index] = shape;
    }

    PageMethods.GetQuickResultsHtml(GetQuickResultsHtmlCallback)
    PageMethods.GetMainResultsHtml(GetMainResultsHtmlCallback)

    if (nearestStoreLocations.length > 0)
    {
        PageMethods.GetMainResultsEmail(GetMainResultsEmailCallback);
        nearestStoreLocations[nearestStoreLocations.length] = currentLocationShape;
        map.SetMapView(nearestStoreLocations);
    }
    else
    {
        GoToDefaultView();
    }
}

function GetMainResultsEmailCallback(body)
{
    mainResultsEmail = body;
    canSendMainResults = true;
}

function RouteCallback(route)
{
    $('#DirectionsDiv').html("");
    
    var directionsHtml = "<div>";
    var legs = route.RouteLegs;
    var leg = legs[0];

    if (typeof leg == 'undefined')
    {
        directionsHtml += "<div>" + directionsNoRoute + "</div>";
        directionsEmail += directionsNoRoute;
    } 
    else
    {
        directionsHtml += "<div>" + directionsTotalDistance + " " + RoundNumber(route.Distance, 2) + abbreviatedDistanceUnits + "</div>";
        directionsHtml += "<div>" + directionsTurnByTurnDirections + "</div><br/>";
        
        directionsEmail += directionsTotalDistance + RoundNumber(route.Distance, 2) + abbreviatedDistanceUnits + "\n";
        directionsEmail += directionsTurnByTurnDirections + "\n\n";

        for (var itineraryItemIndex in leg.Itinerary.Items)
        {
            var itineraryItem = leg.Itinerary.Items[itineraryItemIndex];
            var itineraryItemCount = parseInt(itineraryItemIndex,10)+1;

            if(itineraryItemCount == 1)
            {
                map.DeleteShape(itineraryItem.Shape);
                directionsHtml += "<div><div class='count row'><img class='imgcount' src='app_themes/default/innertarget.png'/></div>";
                directionsHtml += "<div style='float:left;margin:3px;width:170px;font-weight:bold;'>" + itineraryItem.Text + "<br/>";   
                directionsHtml += "<span style='font-weight:normal'>" + RoundNumber(itineraryItem.Distance,2) + "&nbsp;" + abbreviatedDistanceUnits + "&nbsp;" + GetTimeFromSeconds(itineraryItem.Time) + "</span>";
                directionsHtml += "</div></div><div style='clear:both'/>"
                
                directionsEmail += itineraryItem.Text + "\n";
            }
            else if(itineraryItemCount == leg.Itinerary.Items.length)
            {
                map.DeleteShape(itineraryItem.Shape);
                
                directionsHtml += "<div><div class='count row'><img class='imgcount' src='" + destinationPng + "'/></div>";
                directionsHtml += "<div class='row' style='width:170px;font-weight:bold;'>" + itineraryItem.Text + "</div><br/>";   
                directionsHtml += "</div><div style='clear:both'/>"
                
                directionsEmail += itineraryItem.Text + "\n";
            }
            else
            {
                directionsHtml += "<div><div class='count row'>" + "<img class='imgcount' src='http://dev.virtualearth.net/mapcontrol/v6.2/i/bin/6.2.2008082210001.41/pins/RedCircle" + itineraryItemIndex + ".gif'/>" + "</div>";
                directionsHtml += "<div class='row' style='width:170px'>" + itineraryItem.Text + "<br/>";   
                directionsHtml += "" + RoundNumber(itineraryItem.Distance,2) + "&nbsp;" + abbreviatedDistanceUnits + "&nbsp;" + GetTimeFromSeconds(itineraryItem.Time) + "";
                directionsHtml += "</div></div><div style='clear:both'/>";
                
                directionsEmail += itineraryItemIndex + " " + itineraryItem.Text + ", " + RoundNumber(itineraryItem.Distance,2) + " " + abbreviatedDistanceUnits + ", " + GetTimeFromSeconds(itineraryItem.Time) + "\n";
            }
            
            directionsHtml += "<div style='clear:both'>"
        }
    }
    
    directionsHtml += "</div></div>";
    
    canSendDirections = true;

    $('#DirectionsDiv').html(directionsHtml);
}

function GetQuickResultsHtmlCallback(quickResultsHtml)
{
    $('#QuickResultsDiv').html(quickResultsHtml);
}

function GetMainResultsHtmlCallback(mainResultsHtml)
{
    $('#MainResultsDiv').html(mainResultsHtml);
}

function GetCustomIconName(simReseller, topUpReseller, index)
{
    var simText = '';

    if (simReseller)
        simText = 'Sim';

    var topUpText = '';

    if (topUpReseller)
        topUpText = 'TopUp';

    var count = parseInt(index, 10) + 1;
    var customIconName = simText + topUpText + count + ".png";

    return customIconName;
}

function getPNGFix(icon) 
{ 
    var retval; 
    
    if ($.browser.msie && parseInt($.browser.version,10) < 7)
    {
        retval = "<img src='app_themes/default/blank.png' style=\"filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='app_themes/default/" + icon + "', sizingMethod=image);\" />"; 
    }
    else 
    {
        retval = "<img src='app_themes/default/" + icon + "' />"; ; 
    }

    return retval; 
}

//TODO: AJ: These should be in a javascript utilites script
function RoundNumber(number, decimalPlaces)
{
    var result = Math.round(number * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
    return result;
}

function GetTimeFromSeconds(timeInSeconds)
{
    if (timeInSeconds > 59)
    {
        var seconds = timeInSeconds % 60;
        var minutes = timeInSeconds - seconds;
        minutes = minutes / 60;

        if (minutes > 59)
        {
            var minLeft = minutes % 60;
            var hours = minutes - minLeft;
            hours = hours / 60;

            return (PadStringLeft(hours, 0, 2) + ":" + PadStringLeft(minLeft, 0, 2) + ":" + PadStringLeft(seconds, 0, 2));
        }
        else
        {
            return ("00:" + PadStringLeft(minutes, 0, 2) + ":" + PadStringLeft(seconds, 0, 2));
        }
    }
    else
    {
        return ("00:00:" + PadStringLeft(timeInSeconds, 0, 2));
    }
}

function PadStringLeft(string, padCharecter, targetLength)
{
    var output = '' + string;
    
    while(output.length < targetLength)
    {
        output = padCharecter + output;
    }
    
    return output;
}

function IsPointWithinPolygon(point, polygon)
{
    var j = polygon.length-1;
    var isWithinPolygon = false;
    var lat = point.Latitude;
    var lon = point.Longitude;

    for (var i = 0; i < polygon.length; i++)
    {
        if (polygon[i].Longitude < lon && polygon[j].Longitude >= lon || polygon[j].Longitude < lon && polygon[i].Longitude >= lon) 
        {
            if (parseFloat(polygon[i].Latitude) + (lon - polygon[i].Longitude) / (polygon[j].Longitude - polygon[i].Longitude) * (polygon[j].Latitude - polygon[i].Latitude) < lat) 
            {
                isWithinPolygon=!isWithinPolygon; 
            }
        }
        
        j = i; 
    }

    return isWithinPolygon;
}

function ConfigureTopUpLink()
{
    if (logosHaveTopUpLink == "True")
    {
        var directionsDiv = $('#onlineRechargeDiv');
        directionsDiv.click(function() { location.href=topUpLink; });
        directionsDiv.css("cursor","pointer");
    }
}
