﻿/*
 * Refreshes the list of saved maps for the File > Load menu.
 */

function SetUID() {
    CreateCookie("muid","ee8c9ccf-b3bf-4ad6-ae1a-c53fb9813bb1",1)
    RefreshListOfSavedMaps();
    Initialize();
    ToggleSlider_Nav('FindLocation');
    //RunMapWebService.SaveAndLoadMap.GetUID(GetUID_OnSuccess,GetUID_OnFail);
}

function GetUID_OnSuccess(ReturnValue){

    if(ReturnValue != null) {
        CreateCookie("muid",ReturnValue,1)
    }
    
    RefreshListOfSavedMaps();
    Initialize();
    ToggleSlider_Nav('FindLocation');
}

function GetUID_OnFail(ReturnValue){
    alert("You must login.");
}
 
function RefreshListOfSavedMaps()
{
    
    // Hide all three load map components then show only one
    //HideAllLoadMapComponents();
    
    // Is the user not logged in
    if(ReadCookie("muid")==null||ReadCookie("muid")=="")
    {
        //$get('LoginDialogBox').style['display']='block';
        return;
     }
    
    // Pull the user id out of a cookie
    var UserID=ReadCookie("muid");
    
    // Load a list of the user's maps from the server
    try
    {
        // We pass Success and Failure event handlers here
        RunMapWebService.SaveAndLoadMap.GetListOfSavedMapsForUser(UserID,
            GetListOfSavedMapsForUser_OnSuccess,GetListOfSavedMapsForUser_OnFail);
    }
    catch(Exception)
    {
    }
}

/*
 * Event handler for the Success event of the async web service that gets a list of the user's maps
 */
function GetListOfSavedMapsForUser_OnSuccess(ReturnValue)
{
    // Clear the list of maps that can be loaded
    EraseLoadMapLinkList();
    
    // If the new list is empty just return
    if(ReturnValue==null||ReturnValue.length==0)
    {
        $get('LoadMap_SavedMaps_NoMapsToShow').style['display']='block';
        return;
    }

    // Loop through the returned array and add a link for each map
    for(var i=0;i<ReturnValue.length;i++)
        AddLoadAndDeleteMapLink(ReturnValue[i].IdString,ReturnValue[i].Name);

    // We made it to the end so show the saved maps list
    $get('LoadMap_SavedMaps_Load').style['display']='block';    
}


/*
 * Adds a map load and delete link to the map
 *
 * Output Format: Map Name _Load_ _Delete_
 * Load and Delete are hyperlinks
 */
function AddLoadAndDeleteMapLink(MapIdString,MapName)
{

    // Create a link (anchor tag) to load the map
    var NewLoadAnchor=document.createElement('a');
    NewLoadAnchor.href="/";
    NewLoadAnchor.onclick = function() { LoadMap(MapIdString); return false; };
    NewLoadAnchor.appendChild(document.createTextNode(MapName));

    var UserIdString = ReadCookie("muid");

    // Create a link (anchor tag) to load the map
    var NewDeleteAnchor=document.createElement('a');
    NewDeleteAnchor.href="/";
    NewDeleteAnchor.onclick = function() { if(confirm('Do you want to delete this Map?')) DeleteMap(UserIdString,MapIdString); return false; };
    
    var NewImage = document.createElement('img');
    NewImage.alt = "Delete"
    NewImage.src = "css/app/HL/btn/delete.jpg"
    NewImage.style.border = "none";
    
    NewDeleteAnchor.appendChild(NewImage);
    
    // Append the anchor tag to the saved maps list on the page
    var LinksDiv = document.createElement('div');
    LinksDiv.className = "map_items";
    //LinksDiv.appendChild(NewLabel);
    
    LinksDiv.appendChild(NewDeleteAnchor);
    LinksDiv.appendChild(document.createTextNode(' '));
    LinksDiv.appendChild(NewLoadAnchor);
   
    $get('LoadMap_SavedMaps_Load').appendChild(LinksDiv);

    
    
}

function EraseLoadMapLinkList()
{
    var SavedMapsListContainerElement = $get('LoadMap_SavedMaps_Load');

    // Loop through the list of the 
    while(SavedMapsListContainerElement.hasChildNodes())
        SavedMapsListContainerElement.removeChild(SavedMapsListContainerElement.firstChild);
}

/*
 * Event handler for the Fail event of the async web service that gets a list of the user's maps
 */
function GetListOfSavedMapsForUser_OnFail()
{
}

/*
 * Saves the map
 */
function SaveMap()
{
    // Invoke a web service that saves the user's map
    try
    {
        var UserID=ReadCookie("muid")
        var DistanceInMeters=GetCourseDistance();
        var DistanceInMiles=DistanceInMeters*0.000621371192; // 1 meter = 0.000621371192 miles
        var name = $get('txtSaveMapName').value;
        if (name == "") {
            alert("Map must have a Name");
        }else {
            RunMapWebService.SaveAndLoadMap.SaveMap(UserID, name, buildPP(PathPoints), buildSP(Sprites), DistanceInMiles.toFixed(2), SaveMap_OnSuccess, SaveMap_OnFail);
            CloseSaveDialog();
        }
    }
    catch(Exception)
    {    
        alert(Exception.description);
        CloseSaveDialog();
    }
    
}

function buildPP(data) {
    var build = "";
    for(i=0;i<data.length;i++) {
        build += "[" + data[i].Location + "|(" + data[i].Note + ")]-";
    }
    return build;
}

function buildSP(data) {
    var build = "";
    for(i=0;i<data.length;i++) {
        build += "[" + data[i].Location + "|(" + data[i].Note + ")|(" + data[i].SpriteType + ")]-";
    }
    return build;
}


/*
 * Success handler for the SaveMap web service call
 */
function SaveMap_OnSuccess(ReturnValue)
{
    RefreshListOfSavedMaps(); // async
    alert(ReturnValue);
}

/*
 * Failure handler for the SaveMap web service call
 */
function SaveMap_OnFail(ReturnValue)
{   
   alert("Failed to save map. Make sure you're still connected to the Internet. " + ReturnValue);
}

function DeleteMap(UserId,MapId)
{
    RunMapWebService.SaveAndLoadMap.DeleteMap(UserId,MapId,DeleteMap_OnSuccess,DeleteMap_OnFailure);
}

/*
 * Success handler for the DeleteMap web service call
 */
function DeleteMap_OnSuccess()
{
    RefreshListOfSavedMaps();
    alert('Map deleted.');
}

/*
 * Failure handler for the DeleteMap web service call
 */
function DeleteMap_OnFailure()
{
    alert('Unable to delete the map.');
}

/*
 * Loads a map by invoking a web service. Completes asynchronously. Look at the success
 * and failure event handlers.
 */
function LoadMap(MapId)
{
    RunMapWebService.SaveAndLoadMap.LoadMap(MapId,LoadMap_OnSuccess,LoadMap_OnFailure);
//    RunMapWebService.SaveAndLoadMap.GetMapName(MapId,function(ReturnValue){ $get('txtSaveMapName').value = ReturnValue });
}

function LoadMap_OnSuccess(ReturnValue)
{
    // Default next save to loaded map
    $get('txtSaveMapName').value = ReturnValue.Name;
    
    PathPoints = new Array();
    if(ReturnValue.PathPoints.length>0)
    {
        // Create a new PathPoint object (defined in MapPathManager.js) for each path returned
        // from the web service.
        for(var i=0;i<ReturnValue.PathPoints.length;i++)
        {
            var Location = ReturnValue.PathPoints[i].Location;
            var LatLng = new GLatLng(Location.y,Location.x,true);
            PathPoints.push(new PathPoint(LatLng,ReturnValue.PathPoints[i].Note));
        }
    }
    Sprites = new Array();
    if(ReturnValue.Sprites.length>0)
    {
        for(var i=0;i<ReturnValue.Sprites.length;i++)
            Sprites.push(new Sprite(ReturnValue.Sprites[i].SpriteType,ReturnValue.Sprites[i].Location,ReturnValue.Sprites[i].Note));
    }

    RefreshMap(LastCursorPosition);

    // We need an array of just the path points and sprites to make a polyline
    // We need the polyline to figure out a containing boundary for zooming into the new map
    var LatLngs = new Array();
    for(var i=0;i<PathPoints.length;i++)
        LatLngs.push(PathPoints[i].getLocation());
    for(i=0;i<Sprites.length;i++)
        LatLngs.push(Sprites[i].getLocation());

    // Make a polyline and find the box that contains the polygon
    if(LatLngs.length>0)
    {
        var Polyline = new GPolyline(LatLngs);
        var TheBounds = Polyline.Bounds();
        var TheZoomLevel = map.getBoundsZoomLevel(TheBounds);
        map.setZoom(TheZoomLevel);
        map.panTo(TheBounds.getCenter());    
    }
    
    // Tell the user the map loaded
    if(Sprites.length==0&&PathPoints.length==0)
        alert('You have loaded a blank map.');
}

function LoadMap_OnFailure()
{
    alert('Failed to load the map. Check your connection to the Internet.');
}


/*
 * Loads the File > Save Map sub menu
 */
function ShowSaveMap()
{
    // Only show the Save Map sub menu
    $get('SaveMap').style['display'] = 'block';
    
    // If the user is not logged in just give a message to log in first
    if(ReadCookie("UserID")==null||ReadCookie("UserID")=="")
        $get('SaveMap_NotLoggedIn').style['display']='block';
    else
    {
        // The user is logged in so let them save the map
        $get('SaveMap_Save').style['display']='block';
        
        // Set focus to the save map name box
        $get('txtSaveMapName').focus();
    }
}


/*
 * Clears all markers from the map
 */
function ClearMap()
{
    // Clear the saved map name that is defaulted to the last loaded map or last map saved's name
    $get('txtSaveMapName').value = '';

    // Clear the sprite and path point list
    Sprites=new Array();
    PathPoints=new Array();
    
    // Refresh the map and fade the menu
    RefreshMap(LastCursorPosition);
    
    // Get rid of the print area
    HideNotesPrinoutArea();
}

