﻿//
// ********************************************************
//
// basic map drawing functionality
//
// ********************************************************
//

//keeps ajax happy if loaded via script manager
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded(); 

addLoadEvent(MapLoad);

function addLoadEvent(func) 
{ 
    var oldonload = window.onload; 
    if (typeof window.onload != 'function') 
        { window.onload = func; } 
    else 
        { window.onload = function() 
            { oldonload(); func(); } 
    }
}

//page has loaded so we can talk to the map
function MapLoad()
{

// If the browser is Firefox get the version number
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) }
}

map = new VEMap('myMap');    

//eval the dashboard size to make it into the structure
if (legend != "")
    map.SetDashboardSize(eval(legend));

//callback when it loads - if we don't do this we script stuff before the map loads
      
map.LoadMap(new VELatLong(startlat, startlon),5 ,'r', false);


//units
switch (units)
{
case 'metric':
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
    $get('metric').checked = true;
    break;
case 'mixed':

    map.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);
    $get('mixed').checked = true;
    break;

case 'imperial':
   map.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);
   $get('imperial').checked = true;
    break;

default:
   map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
   $get('metric').checked = true;
   break;
}

map.onLoadMap = OnMapLoad();
}

//map has loaded - so we can play with it
function OnMapLoad()
{
////points - we only bind onload as these don't change
var request = new JsonRequest("pointdata", "/webservice/pointdata.ashx?lngrouteid=" + routeid);
//add the callback
request.doRequest("OnGetPointsRequestComplete");
    
//add points of interest
rtn = ShareMyRoutes.webservice.mapData.GetPOI(routeid, OnGetPOIRequestComplete, OnTimeout, OnError);

map.AttachEvent("onstartzoom", _HidePopup);
map.AttachEvent("onstartpan",_HidePopup);

}

//replace with more friendly message in time
function OnError(result) 
{
    alert("Error:\n\n" + result.get_message() + "\n" + result.get_stackTrace());

    //trap empty error
    if (result == undefined)
        {
      alert("Error.\n\n");
       return false;
    }     
   
    if (gTestMode == true)
        alert("Error.\n\n" + result.get_message() + "\n" + result.get_stackTrace());
    else
        alert("Sorry, but something has gone wrong.\nIf you continue to experience problems please get in touch.");
}


function OnTimeout(result)
{

alert("Error or timed out: " + result._message);
}


function OnGetPOIRequestComplete(result) 
{


//bomb out if nothing comes back - this happens sometimes
if (result == undefined)
    {
    return false;
    }
    
//tell them the list is empty
if (result.length == 0)
{
    debugalert("empty")
  }     
   
for(i = 0; i < result.length; i++)
{
    var objItem = result[i];

    AddPin(objItem.lat, objItem.lon, objItem.title, objItem.description, objItem.imageid, objItem.mapicon, objItem.id);
    }  

}

function OnGetPointsRequestComplete(myCompactRoutePoints) 
{
    //bomb out if nothing comes back - this happens sometimes
    if (myCompactRoutePoints == undefined) {
        debugalert("result == undefined");

        return false;
    }

    //tell them the list is empty
    if (myCompactRoutePoints.length == 0) {
        debugalert("empty")
        return false;
    }

    //get the first point
    start = myCompactRoutePoints.start.split(",");

    startLat = parseFloat(start[0]);
    startLon = parseFloat(start[1]);
    var startAlt = parseInt(start[2]);

    points = new Array();   //store the points in

    //add the first point
    if (isFlight == true)
        myPoint = new VELatLong(startLat, startLon, startAlt);
    else
        myPoint = new VELatLong(startLat, startLon);

    points.push(myPoint);

    //now loop the rest adding points as we go
    rawpoints = myCompactRoutePoints.points.split(";");

    //initalise the values
    var lastLat = startLat;
    var lastLon = startLon;
    var lastAlt = startAlt;

    //loop around them
    for (i = 0; i < rawpoints.length - 1; i++) {

        //parse the string
        point = rawpoints[i].split(",");

        //only add if there's some points to add
        if (point.length > 3) {

            var currentLatDelta = parseFloat(point[0]);
            var currentLonDelta = parseFloat(point[1]);
            var currentAltDelta = parseInt(point[2]);

            //add the point
            if (isFlight == true)
                var myPoint = new VELatLong(trimPosition(lastLat + (currentLatDelta / multiplier)), trimPosition(lastLon + (currentLonDelta / multiplier)), lastAlt + currentAltDelta);
            else
                var myPoint = new VELatLong(trimPosition(lastLat + (currentLatDelta / multiplier)), trimPosition(lastLon + (currentLonDelta / multiplier)));

            points.push(myPoint);

            //grab the last one
            lastLat = lastLat + (currentLatDelta / multiplier);
            lastLon = lastLon + (currentLonDelta / multiplier);
            lastAlt = lastAlt + currentAltDelta;

        }

    }
    
  
//draw the pretty poly
poly = new VEShape(VEShapeType.Polyline, points)
poly.SetLineWidth(6);
poly.SetLineColor(new VEColor(255,153,0,0.57));

poly.HideIcon()

map.AddShape(poly);

//start of route
AddPin(startLat, startLon, "Start", routestart, 0, "start16x16.png", 0);
    
map.SetMapStyle(VEMapStyle.Hybrid);
map.SetMapView(points); 

map.AttachEvent("onstartcontinuouspan", _HidePopup);
map.AttachEvent("onstartzoom", _HidePopup);

}

function AddPin(lat, lon, title, description, imageid, icon, id)
{   
//var html = "<div id='popupbody'>";
var html = "<div id='waypointpopup'>";

//customise the html
var photoPopup = "image.aspx?lngpoiid=" + id + "";

if (imageid != '')
{
    var photoLink = "image.aspx?lngimageid=" + imageid

    var thumbnaiilLink = "/common/showthumbnail.ashx?lngimageid=" + imageid

    html +=  "<div id='photo'><a target='_top' href='" + photoPopup + "'><img alt='View photo on ShareMyRoutes.com' src='" + thumbnaiilLink + "' /></a></div>";
    html += "<div id='text'>" + description + "</div>";
    
    }
else
    {
    html += "<div id='textwide'>" + description + "</div>";
    }

    //get the right icon or a sensible default
    if (icon != undefined && icon != '')
        icon = "/icons/" + icon;
    else
         icon = "/icons/x16x16.png";     //default for warning
    
if (photoLink != undefined && photoLink != '')
{
    html += "<div class='btns'>";
    html += "<a target='_top' href='" + photoPopup + "'>View on " + sitename + "</a></div>";
 }
 
html += "</div>";

//set using the new shape method
var pin = new VEShape(VEShapeType.Pushpin,  new VELatLong(lat, lon) );

pin.SetCustomIcon(icon);
pin.SetDescription(html);
pin.SetTitle("<span id='waypointpopuptitle'>" + unescape(title) + "</span>");

map.AddShape(pin);
pinID++;

} 

//hides the popup
function _HidePopup()
{
    //hides the info popup
    map.HideInfoBox();
    
    //hide the details pane
    HideDetailsPane();  
}


function  debugalert(msg)
{
//alert("debugging message: " + msg);
}


function ToggleDetails()
{

//todo flick the drop down thingy
if ($get('moreDetailsContent').style.display != 'block')
   ShowDetailsPane()
else
   HideDetailsPane()

}

function ShowDetailsPane()
{
    _HidePopup();
    
    $get('moreDetailsHeader').innerHTML = "&gt;&gt;";
    //$get('moreDetailsHeader').innerHTML = "Hide Details....";
    $get('moreDetailsContent').style.display = 'block';

    
}

function HideDetailsPane()
{
    $get('moreDetailsHeader').innerHTML = "&lt;&lt;";
    //$get('moreDetailsHeader').innerHTML = "Show Details....";
   $get('moreDetailsContent').style.display = 'none';

}

function DoUnits(whatunits)
{

var unitsetid = 0;

switch (whatunits)
    {
case 'metric':
    unitsetid = 1;
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
    break;

case 'imperial':

    unitsetid = 2;
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);
    break;

case 'mixed':
    unitsetid = 3;
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);
    break;
  
default:

    unitsetid = 2;
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Miles);
    break;

}
 
 args = routeid + "|" + unitsetid;
 
 rtn = ShareMyRoutes.webservice.mapData.GetRouteDescription(args, OnGetRouteDescriptionRequestComplete, OnTimeout, OnError);
 
  whatunits=  units;
    
}

function OnGetRouteDescriptionRequestComplete(result)
{

$get('ctl00_ContentPlaceHolderContent_details_labelAscent').innerHTML = result.Ascent;
$get('ctl00_ContentPlaceHolderContent_details_labelDistance').innerHTML = result.Length;


}

//cuts off the least significant digits on a lat/lon to save some memory
function trimPosition(myNumber) {
    return Math.round(myNumber * 10000) / 10000
}