﻿//Constants
var mWidth = 800;
var mHeight = 600;
var PopupPrefix = "VPOP";

//public varibles
var map = null;  
var currentStorePins = new Array();
var constructionStorePins = new Array();
var CurrentPopupID = 0;
var menu = null; 
var menuLat = null;
var menuLong = null;

//class for clustered pin
function clusteredPin(loc, bounds) 
{
	this.loc = loc;
	this.bounds = bounds;
} 

//Map initialisation on page load.       
function GetMap()       
{            
    DisplayLoading();
    
    // Firefox support - see VE wiki.
    var ffv = 0;
    var ffn = "Firefox/"
    var ffp = navigator.userAgent.indexOf(ffn);
    if (ffp != -1) ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));
    // If we're using Firefox 1.5 or above override the Virtual Earth drawing functions to use SVG
    if (ffv >= 1.5) {
      Msn.Drawing.Graphic.CreateGraphic=function(f,b) { return new Msn.Drawing.SVGGraphic(f,b) }
    }
    //setup map over United States
    map = new VEMap('LovesMap');    
    map.LoadMap(new VELatLong(41, -99), 4 ,'r' , false); 
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);
    //map.ShowMiniMap();
    //setup the function to get new data whenever the map changes
    map.AttachEvent("onchangeview", GetPinData);
    //setup the function to get Latitude/Longitude whenever the map is clicked
    map.AttachEvent("onclick", mouseClicked);
    //attach our custom handler to the popup
    map.AttachEvent("onmouseover", PinHover);
    
    //Add some custom properties
    VEShape.prototype.Bounds = "";
    VEShape.prototype.StoreType = "";
    
    //get the data for the default view
    GetPinData();
}  

//Whenever the map view changes call the webservice for the latest data
function GetPinData()
{  
    DisplayLoading();
    
    //encode the current map bounds
    var points = new Array();
    var pixel; 
    
    pixel = new VEPixel(0, 0);
    points.push(map.PixelToLatLong(pixel));
    
    pixel = new VEPixel(mWidth, mHeight);
    points.push(map.PixelToLatLong(pixel));
    
    var bounds = createEncodings(points);

    //get zoomlevel
    var zoom = map.GetZoomLevel();
    
    //call webservice to get Current Stores
    GetPinData_CurrentStores(bounds, zoom); 
    
    //call webservice to get Construction Stores
    GetPinData_ConstructionStores(bounds, zoom);    
}


//Whenever the map is clicked get the latitude and longitude
function mouseClicked(e)
{    
    //Get the pixel coordinates of where the map was clicked
    var x = e.mapX;
    var y = e.mapY;
    
    var pixel = new VEPixel(x, y);
    
    var latlong = map.PixelToLatLong(pixel);
    
    //Round the coordinates to 5 decimal places
    var latitude = Math.round(10000*latlong.Latitude)/10000;
    var longitude = Math.round(10000*latlong.Longitude)/10000;
    
    if (e.leftMouseButton == true)
    {
        //Display the clicked coordinates
        var LatLong = document.getElementById('LatLong');
        LatLong.innerHTML = "Latitude: " + latitude + "    Longitude: " + longitude;
    }
    else if (e.rightMouseButton == true)
    {
        //Set the clicked cooridnates as a start or end location
        menuLat = latitude;
        menuLong = longitude;
      
        if (document.all)     //IE
        { 
            document.all.ContextMenuShadow.style.pixelLeft = (event.clientX + document.documentElement.scrollLeft); 
            document.all.ContextMenuShadow.style.pixelTop = (event.clientY + document.documentElement.scrollTop); 
            document.all.ContextMenuShadow.style.visibility = 'visible'; 
        
            return false; 
        } 
        else if (document.layers)     //Netscape
        { 
            if (evt.which == 3) 
            { 
              document.ContextMenuShadow.left = (evt.x + window.pageXOffset); 
              document.ContextMenuShadow.top = (evt.y + window.pageYOffset); 
              document.ContextMenuShadow.onmouseout = function (evt){ this.visibility = 'hide'; }; 
              document.ContextMenuShadow.visibility = 'show'; 
              return false; 
            } 
         } 
        return true; 
    }
}

// on pin hover   
function PinHover(e)
{
    //make sure we are over a shape
    if (e.elementID != null)
    {   
        //get a reference to the shape
        var shape = map.GetShapeByID(e.elementID);
       
        //get the pinID from the custom property Bounds
        var pinID = shape.Bounds;
        
        //get the pinType from the custom property StoreType
        var pinType = shape.StoreType;

        var DivID = PopupPrefix + pinID;

       //create the default VE popup with loading text.
       shape.SetTitle("<div id='" + DivID + "_Title'>Love's Store</div>");
       shape.SetDescription("<div id='" + DivID + "_Desc'>Getting Information...</div>");
        
        //document.getElementById("lbl_Debug").innerHTML = document.getElementById("lbl_Debug").innerHTML + "-" + pinID;
         
        //call the appropriate function depending on the pin type 
        if (pinType == "Current")
        {
            getAJAXContent_CurrentStores(pinID, currentStorePins[pinID].bounds, 0);
        }
        else if (pinType == "Construction")
        {
            getAJAXContent_ConstructionStores(pinID, constructionStorePins[pinID].bounds, 0);
        } 
     }
     
     return false;
}

//Find a location
function FindLocation()
{
    DisplayLoading();
    
    var location = document.getElementById("dnn_ctr402_VirtualEarth_Controls_txt_Location").value;
    
    map.Find(null, location, null, null, null, null, true, true, false, true, onFindLocation);
}


//Find location callback
function onFindLocation(e)
{
    HideLoading();
}


//Get a route
function GetRoute()
{
    DisplayLoading();
    
    //Delete any current route
    closeDirections();
    
    var routeStart = document.getElementById("dnn_ctr402_VirtualEarth_Controls_txt_Start").value;
    var routeEnd = document.getElementById("dnn_ctr402_VirtualEarth_Controls_txt_End").value;
    var routeTypeS = document.getElementById("dnn_ctr402_VirtualEarth_Controls_rbl_RouteType_0");
    var routeTypeQ = document.getElementById("dnn_ctr402_VirtualEarth_Controls_rbl_RouteType_1");
    var routeType;
    
    if (routeTypeS.checked == true)
    {
        routeType = VERouteType.Shortest;
    }
    else if (routeTypeQ.checked == true)
    {
        routeType = VERouteType.Quickest;
    }
    
    //Check if start coordinate is a latitude/longitude
    var bln_RouteStartLatLong = IsLatLong(routeStart);
    var bln_RouteEndLatLong = IsLatLong(routeEnd);

    //Get the route
    if ((bln_RouteStartLatLong == true) && (bln_RouteEndLatLong == true))
    { 
        var rSLatLongArray = routeStart.split(",");
        var rELatLongArray = routeEnd.split(",");
        
        map.GetRoute(new VELatLong(rSLatLongArray[0], rSLatLongArray[1]), new VELatLong(rELatLongArray[0], rELatLongArray[1]), null, routeType, onGotRoute);
    }
    
    if ((bln_RouteStartLatLong == true) && (bln_RouteEndLatLong == false))
    { 
        var rSLatLongArray = routeStart.split(",");
        
        map.GetRoute(new VELatLong(rSLatLongArray[0], rSLatLongArray[1]), routeEnd, null, routeType, onGotRoute);
    }
    
    if ((bln_RouteStartLatLong == false) && (bln_RouteEndLatLong == true))
    { 
        var rELatLongArray = routeEnd.split(",");
        map.GetRoute(routeStart, new VELatLong(rELatLongArray[0], rELatLongArray[1]), null, routeType, onGotRoute);
    }
    
    if ((bln_RouteStartLatLong == false) && (bln_RouteEndLatLong == false))
    { map.GetRoute(routeStart, routeEnd, null, routeType, onGotRoute);}
}


//Get route callback
function onGotRoute(route)         
{           
    var routeinfo = "";  
    var routetype = "";    

    var Directions = document.getElementById("Directions");
    Directions.style.visibility = 'visible';

    if (route.Itinerary.RouteType == 's'){routetype = "shortest route";}
    else if (route.Itinerary.RouteType == 'q'){routetype = "quickest route";}
		               
    var header = "<table style='width: 100%;' cellspacing='0' cellpadding='0' onmousedown='startLayerDrag(\"Directions\");' onmouseup='endLayerDrag();'>" +
                    "<tr>" +
                        "<td class='DirectionsHeaderText'>Route Summary (" + routetype + ")</td>" +
                        "<td style='text-align: right;' class='DirectionsHeaderCloseText'>" + 
                            "<img name='img_minmax' src='DesktopModules/Loves.VirtualEarthAjax/images/MinimizeButton.png' onclick='minmaxDirections();' onmouseover='this.style.cursor=\"pointer\"'; >" +
                            "    <img name='img_close' src='DesktopModules/Loves.VirtualEarthAjax/images/CloseButton.png' onclick='closeDirections();' onmouseover='this.style.cursor=\"pointer\"'; />" +
                        "</td>" +
                    "</tr>" +   
                    "<tr>" +
                        "<td colspan='2' class='DirectionsHeaderSubText'>Distance " + route.Itinerary.Distance + " " + route.Itinerary.DistanceUnit + "</td>" +
                    "</tr>" +
                    "<tr>" +
                        "<td class='DirectionsHeaderSubText'>Estimated Time " + route.Itinerary.Time + "</td>" +
                        "<td style='text-align: right;' class='RedText'>" +
                            "<a onclick='EmailDirections(\"" + routetype + "\",\"" + route.Itinerary.Distance + "\",\"" + route.Itinerary.DistanceUnit + "\",\"" + route.Itinerary.Time + "\",\"DirectionsDetail\")' onmouseover='this.style.cursor=\"pointer\"';>email</a>" + 
                            "&nbsp;&nbsp;&nbsp;&nbsp;" + 
                            "<a onclick='PrintDirections(\"" + routetype + "\",\"" + route.Itinerary.Distance + "\",\"" + route.Itinerary.DistanceUnit + "\",\"" + route.Itinerary.Time + "\",\"DirectionsDetail\")' onmouseover='this.style.cursor=\"pointer\"';>print</a>" + 
                        "</td>" +
                    "</tr>" +
                "</table>";
    
    var DirectionsHeader = document.getElementById("DirectionsHeader");
    DirectionsHeader.innerHTML = header;
    DirectionsHeader.style.visibility = 'visible';
	
    var steps = "<table class='DirectionsText'>";
    var len = route.Itinerary.Segments.length;
                
    for(var i = 0; i < len ;i++)               
    {
	    
	    steps += "<tr>";
		
	    var color;
		
	    if (i % 2 == 0){color = "#E6E6E6";}
	    else{color = "#FFFFFF";}

	    steps += "<td style='background-color: " + color + "; text-align: right; vertical-align: top;'><b>" + (i+1) + ".</b>";
	    steps += "</td>";
	    steps += "<td style='background-color: " + color + "'>";
		
	    steps += route.Itinerary.Segments[i].Instruction + " (";                  
	    steps += route.Itinerary.Segments[i].Distance + " ";                  
	    steps += route.Itinerary.DistanceUnit + ")";
		
	    steps += "</td>";
	    steps += "</tr>";        
    }   
	         
    routeinfo += steps + "</table>";
    
    var DirectionsDetail = document.getElementById("DirectionsDetail");
    DirectionsDetail.innerHTML = routeinfo;
    DirectionsDetail.style.visibility = 'visible';   
    
    //Set the position of the popup with javascript using pixels
    //because doing it in CSS or using a percentage caused it to behave funky when attempting to drag it....
    dWidth = (document.getElementById("LovesMap").offsetLeft) + (document.getElementById("LovesMap").offsetWidth) - 315;
    dHeight = (document.getElementById("LovesMap").offsetTop) + 5;
 
    Directions.style.left = dWidth + "px";
    Directions.style.top = dHeight + "px";
    
    HideLoading();
}


//Delete the route
function DeleteRoute()
{
    map.DeleteRoute();
}


//Minimize or Maximize the Directions
function minmaxDirections()
{
    var DirectionsDetail = document.getElementById("DirectionsDetail");
    minmax = new Image();

    if (DirectionsDetail.style.visibility == 'visible')
    {
        minmax.src = "DesktopModules/Loves.VirtualEarthAjax/images/MaximizeButton.png";
        document["img_minmax"].src = minmax.src;
        DirectionsDetail.style.visibility = 'hidden'; 
    }
    else
    {
        minmax.src = "DesktopModules/Loves.VirtualEarthAjax/images/MinimizeButton.png";
        document["img_minmax"].src = minmax.src;
        DirectionsDetail.style.visibility = 'visible'; 
    }
}


//Close the Directions
function closeDirections()
{
    var DirectionsHeader = document.getElementById("DirectionsHeader");
    DirectionsHeader.innerHTML = '';
    DirectionsHeader.style.visibility = 'hidden'; 

    var DirectionsDetail = document.getElementById("DirectionsDetail");
    DirectionsDetail.innerHTML = ''; 
    DirectionsDetail.style.visibility = 'hidden'; 
    
    var Directions = document.getElementById("Directions");
    Directions.style.visibility = 'hidden'; 
    
    //Delete the route
    DeleteRoute();
}


//Swap the starting and ending points
function swapDirectionStartEnd()
{
    var Start = document.getElementById("dnn_ctr402_VirtualEarth_Controls_txt_Start");
    var End = document.getElementById("dnn_ctr402_VirtualEarth_Controls_txt_End");

    var temp = Start.value;
    
    Start.value = End.value;
    End.value = temp;
}


//Print the Directions
function PrintDirections(RouteType, Distance, DistanceUnit, Time, divID)
{
    var prtDivContent = document.getElementById(divID);
    
    var Content = prtDivContent.innerHTML;
    
   Content = Content.replace("DirectionsText", "DirectionsPrintText");
    
    var WinPrint = window.open('','','left=100px,top=100px,width=650px,height=600px,toolbar=0,scrollbars=0,status=0');
    WinPrint.document.write("<LINK href='DesktopModules/Loves.VirtualEarthAjax/module.css' type='text/css' rel='stylesheet'>" +
                            "<div style='left: 0px; margin: 0px; padding: 0px; position: absolute; top: 0px; width: 650px;'>" +
                                "<img src='DesktopModules/Loves.VirtualEarthAjax/images/LovesDrivingDirections.png' style='border: none; text-align: left; vertical-align: top;' alt='' /><br/>" +
                                "<div class='DirectionsHeaderPrintText' style='position: relative; width: 650px;'>" +
                                    "<b>Route Summary</b> (" + RouteType + ")<br/>" +
                                    "<b>Distance</b> " + Distance + " " + DistanceUnit + "<br/>" +
                                    "<b>Estimated Time</b> " + Time +
                                 "</div>" +
                                 "<hr>" + 
                                 "<div style='position: relative; width: 650px;'>" + Content + "</div><br/>" +
                            "</div>");
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();
}

//Email the Directions
function EmailDirections(RouteType, Distance, DistanceUnit, Time, divID)
{
    var emailDivContent = document.getElementById(divID);
    
    var website = document.getElementById("dnn_ctr403_VirtualEarth_Map_hf_Website").value;
    
    var directions = "<div style='left: 0px; margin: 0px; padding: 0px; position: absolute; top: 0px; text-align: center; width: 100%;'>" +
                        "<div style='border: solid 2px grey; Text-align: left; width: 650px;'>" +
                            "<a href='" + website + "' alt='www.loves.com'>" +
                                "<img src='" + website + "/DesktopModules/Loves.VirtualEarthAjax/images/LovesDrivingDirections.png' style='border: none; text-align: left; vertical-align: top;' alt='' />" +
                            "</a><br/>" +
                            "<div style='padding: 5px; position: relative; width: 650px;'>" +
                                "Route Summary (" + RouteType + ")<br/>" +
                                "Distance " + Distance + " " + DistanceUnit + "<br/>" +
                                "Estimated Time " + Time +
                            "</div>" +
                            "<hr>" + 
                            "<div style='font-size: 11pt; padding: 5px; position: relative; text-align: center; width: 650px;'>" + emailDivContent.innerHTML + "</div><br/>" +
                        "</div>" +
                     "</div>";

    //Add the directions to the modal popup
    document.getElementById("dnn_ctr403_VirtualEarth_Map_hf_Directions").value = directions;
    
    //Show the modal popup
    $find("EmailDirections").show();
}



//Show the loading display
function DisplayLoading()
{
    document.getElementById("Loading").style.visibility = "visible";
}


//Hide the loading display
function HideLoading()
{
    document.getElementById("Loading").style.visibility = "hidden";
}


//Set the Start Location Latitude/Longitude
function SetStartLocation()
{
    var routeStart = document.getElementById("dnn_ctr402_VirtualEarth_Controls_txt_Start");
    
    routeStart.value = menuLat + "," + menuLong;
    SetNormalClass(routeStart);
}


//Set the End Location Latitude/Longitude
function SetEndLocation()
{
    var routeEnd = document.getElementById("dnn_ctr402_VirtualEarth_Controls_txt_End");
    
    routeEnd.value = '';
    routeEnd.value = menuLat + "," + menuLong;
    SetNormalClass(routeEnd);
}


// This is the failed callback function for all webservices.
function OnFailed(error)
{

    HideLoading();
    
    var stackTrace = error.get_stackTrace();
    var message = error.get_message();
    var statusCode = error.get_statusCode();
    var exceptionType = error.get_exceptionType();
    var timedout = error.get_timedOut();
   
    // Display the error.    
    var RsltElem = 
        "Stack Trace: " +  stackTrace + "<br/>" +
        "Service Error: " + message + "<br/>" +
        "Status Code: " + statusCode + "<br/>" +
        "Exception Type: " + exceptionType + "<br/>" +
        "Timedout: " + timedout;
        
        alert(RsltElem);
}


//Clean up all objects
function MapDispose()
{
    HideLoading();
    
    pins = null;
    if (map!=null)
    {
        map.Dispose();
        map = null;
    }
}


//set map to run onload and dispose on exit
if (window.attachEvent) {
	window.attachEvent("onload", GetMap);
	window.attachEvent("onunload", MapDispose);	
} else {
	window.addEventListener("load", GetMap, false);
	window.addEventListener("unload", MapDispose, false);
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
