﻿//
// ********************************************************
//
// 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');    
map.SetDashboardSize(VEDashboardSize.Small);

//callback when it loads - if we don't do this we script stuff before the map loads      
map.LoadMap(new VELatLong(startlat, startlon),zoomlevel,'h', false, VEMapMode.Mode2D, false); 


//attach events for starting to move or zoom the map - to hide popup
map.AttachEvent("onstartzoom", _HidePopup);
map.AttachEvent("onstartpan",_HidePopup);

//attach event for getting data when the map moves
map.AttachEvent("onendzoom",LoadData);
map.AttachEvent("onendpan",LoadData);

if (units == 'metric')
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
    

map.onLoadMap = OnMapLoad();
}

//map has loaded - so we can play with it
function OnMapLoad()
{
//gets the stuff in view
LoadData();

map.ShowMessage("Pan and zoom map to see routes in the map area");
}

function LoadData()
{

_HidePopup();

//delete all the poi
//map.DeleteAllPushpins();

//***************************
//get the routes in view
//***************************

//TODO make this work for the 3d view
var MapCoords = map.GetMapView();

//build the bounding box
var myCoords = new sharemyroutes.webservice.Coords();

//convert pixels to lat/longs
var pixel  = new VEPixel(0, 0);
var TopLeftLatLong = new VELatLong(map.PixelToLatLong(pixel).Latitude, map.PixelToLatLong(pixel).Longitude);

myCoords.topLeftLat = TopLeftLatLong.Latitude;
myCoords.topLeftLon = TopLeftLatLong.Longitude;

//figure out the bounds of the map
var mapBox = Sys.UI.DomElement.getBounds($get("myMap"));

pixel = new VEPixel(mapBox.width, mapBox.height);
var BottomRightLatLong = new VELatLong(map.PixelToLatLong(pixel).Latitude, map.PixelToLatLong(pixel).Longitude);

myCoords.bottomRightLat = BottomRightLatLong.Latitude;
myCoords.bottomRightLon = BottomRightLatLong.Longitude;

var activity = $get(txtActivity).value;
var user = $get(txtUserName).value;

var tags = "";

//build the other params
var myRouteQueryParameters = new sharemyroutes.webservice.RouteQueryParameters();

myRouteQueryParameters.Coords = myCoords;
myRouteQueryParameters.activity = activity;
myRouteQueryParameters.author = user;
myRouteQueryParameters.tags = tags;

//var mindif = document.getElementById(txtMinDif).value;
//var maxdif = document.getElementById(txtMaxDif).value;

var mindif = document.getElementById(selMinDif).options[document.getElementById(selMinDif).selectedIndex].value;
var maxdif = document.getElementById(selMaxDif).options[document.getElementById(selMaxDif).selectedIndex].value;

if (mindif != "")
{
myRouteQueryParameters.minDifficulty = mindif;
}

if (maxdif != "")
{
myRouteQueryParameters.maxDifficulty = maxdif;
}


rtn = sharemyroutes.webservice.mapData.GetRoutesInBox(myRouteQueryParameters, OnGetRoutesRequestComplete, OnTimeout, OnTimeout);

//do the see also thing as well
SeeAlso();

//update the permalink
DoPermalink();

}

function OnTimeout(result)
{

    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 OnGetRoutesRequestComplete(result) 
{

//clear the list
$get("routelist").innerHTML = '';

//clear the points
map.Clear();

//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);
    AddToRouteList(objItem);
    }
    
//debugger;
    
//if we need to zoom to points do so and then cancel
if (bolZoomToPoints == true && result.length > 0)
    {
    //map.SetMapView(result); 
    bolZoomToPoints = false;
    }
        
}


//AddPin(objItem.lat, objItem.lon, objItem.title, objItem.description, objItem.imageid, objItem.mapicon, objItem.id, objItem.url, objItem.author, objItem.grading, objItem.activity);

function AddPin(objItem)
{   
var html = "<div id='popupbody'>";

    

//if (photoUrl != undefined && photoUrl != '')
if (objItem.imageid != '')
{

    var thumbnaiilLink = "/common/showthumbnail.ashx?lngimageid=" + objItem.imageid
    var icon = objItem.mapicon; //start with the passed icon and then play around with it
    
    html +=  "<div id='photo'><a href='" + objItem.url + "'><img style='width:45px;height:45px;' alt='click for route details' src='" + thumbnaiilLink + "' /></a></div>";
    html += "<div id='text'>" + objItem.description + "</div>";
    
    }
else
    {
    html += "<div id='textwide'>" + objItem.description + "</div>";
    }


//customise the html
html += "<div id='author'><a href='/users/" + objItem.author + "/default.aspx'>" + objItem.author + "</a>, <a href='/tag/" + objItem.activity + "/activity.aspx'>" + objItem.activity + "</A>"

if (objItem.grading > 0)
{
html +=  " (" + objItem.grading + "/5)";
}

html +=  "</div>";

icon = "/icons/star16x16.png";     //default for warning

//link stuff as well
if (objItem.url != undefined && objItem.url != '')
    html += "<div class='btns'><a href='" + objItem.url + "'>View route</a></div>";
 
html += "</div>";

var pin = new VEPushpin(pinID, 
            new VELatLong(objItem.lat, objItem.lon), 
            icon, 
            objItem.title, 
            html,
            'pinicon',
            'title',
            'textdescription'
            );

VEPushpin.ShowDetailOnMouseOver = false;
VEPushpin.OnMouseOverCallback = function(x, y, title, details) 
{  
//debugger;
var popupInfo = $get("popup");
popupInfo.style.display = 'block';
//popupInfo.style.left = x + 'px';
var elementBounds = Sys.UI.DomElement.getBounds($get("myMap"));
var listelementBounds = Sys.UI.DomElement.getBounds($get("routelistwrapper"));

if ($get(chkShowBigMap).checked != true)
    popupInfo.style.left = (x-elementBounds.x )+ 'px'
else
    popupInfo.style.left = (x-(elementBounds.x) + 440) + 'px'

popupInfo.style.top = y + 'px';

popupInfo.innerHTML = "<div id='top'><h2>" + unescape(title) + "</h2><span id='dismiss' onclick='_HidePopup();'>X</span></div>" + unescape(details);

}
       
map.AddPushpin(pin);
pinID++;
} 

function AddToRouteList(objItem)
{
var myLine;

if ($get(chkShowBigMap).checked == true)
{
    myLine = "<div class='routeStatFull'>";
     
    if (objItem.url != undefined && objItem.url != '')
        myLine += "<h2><a href='" + objItem.url + "'>" + objItem.title + "</a></h2>";
    else
        myLine += "<h2>" + objItem.title + "</h2>";

    //build up a line with innerHTML
    //if (photoUrl != undefined && photoUrl != '')
    if (objItem.imageid != '')
    {
    var thumbnaiilLink = "/common/showthumbnail.ashx?lngimageid=" + objItem.imageid    
        myLine +=  "<div class='photo'><a href='" + objItem.url + "'><img style='width:45px;height:45px;' alt='click for route details' src='" + thumbnaiilLink + "' /></a></div>";
    }
    else
    {
    var thumbnaiilLink = "/images/blank.png"   
        myLine +=  "<div class='photo'><a href='" + objItem.url + "'><img style='width:45px;height:45px;' alt='No photo' src='" + thumbnaiilLink + "' /></a></div>";
    }

    myLine += "<div class='text'><div class='description'>" + objItem.description + "</div>";


    //customise the html
    myLine += "<div class='stats'><a href='/users/" + objItem.author + "/default.aspx'>" + objItem.author + "</a>, <a href='/tag/" + objItem.activity + "/activity.aspx'>" + objItem.activity + "</a>"

    if (objItem.grading > 0)
    {
    myLine +=  " (<abbr title='Recommended: 5 is best'>" + objItem.grading + "/5</abbr>)";
    }

    myLine +=  "</div>";    //end of author etc

 
 }
 else
 {
     myLine = "<div class='routeStat'>";
   
    if (objItem.url != undefined && objItem.url != '')
        myLine += "<h2><a href='" + objItem.url + "'>" + objItem.title + "</a></h2>";
    else
        myLine += "<h2>" + objItem.title + "</h2>";

    //myLine += "<div class='text'><div class='description'>" + objItem.description + "</div>";
    myLine += "<div class='text'>";

    //customise the html
    myLine += "<div class='stats'><a href='/users/" + objItem.author + "/default.aspx'>" + objItem.author + "</a>, <a href='/tag/" + objItem.activity + "/activity.aspx'>" + objItem.activity + "</a>"

    if (objItem.grading > 0)
    {
    myLine +=  " (<abbr title='Recommended: 5 is best'>" + objItem.grading + "/5</abbr>)";
    }

    myLine +=  "</div>";    //end of author etc
        
 }
 
myLine +=  "</div>";    //end of text
myLine +=  "</div>";    //end of the routedetails


//add it to the list
$get("routelist").innerHTML += myLine;

}

// change the shape of the map etc 
function toggleList()
{

SetUpMap();
LoadData();

}

function SetUpMap()
{


mapCentre = new VELatLong(map.GetCenter().Latitude, map.GetCenter().Longitude);     //get the centre of the map
mapZoomlevel = map.GetZoomLevel();  //get zoom level


//change the map wrapper
if ($get(chkShowBigMap).checked == true)
{

    $get('mapwrapper').className = "smallMap";
    $get(chkMiniMap).checked = false;
    map.HideMiniMap();
    map.HideDashboard();
    
    $get('myMap').style.width = '440px';
    $get('myMap').style.height = '350px';


    $get('otherPOI').style.display = '';

    $get('routelistwrapper').style.width = '420px';

    //$get('routeStat').style.width = '320px';

    map.SetDashboardSize(VEDashboardSize.Tiny);
    map.LoadMap(mapCentre, mapZoomlevel-1, 'h', false, VEMapMode.Mode2D, false); 
 
    $get('mapControls').style.display = "none";
    
}
else
{


    $get('mapwrapper').className = "bigMap";
    $get('mapControls').style.display = "";

    $get('myMap').style.width = '880px';
    $get('myMap').style.height = '700px';

    $get('routelistwrapper').style.width = '870px';
 
    $get('otherPOI').style.display = 'none';

    map.LoadMap(mapCentre, mapZoomlevel+1, 'h', false, VEMapMode.Mode2D, false); 

    map.ShowDashboard();

    //restore the minimap
    if ($get(chkMiniMap).checked == true)
    {
        map.ShowMiniMap(470, 0);
    }
    else
    {
     map.HideMiniMap();
     }
     
}

}

function SeeAlso()
{

if ($get(txtActivity).value != '')
{
rtn = sharemyroutes.webservice.mapData.GetSeeAlso($get(txtActivity).value, OnGetSeeAlsoComplete, OnTimeout, OnTimeout);
}

}

function OnGetSeeAlsoComplete(result)
{
//debugger;

//clear the stuff
if (result.length > 0)
    $get("divSeeAlso").style.display = '';
else
    $get("divSeeAlso").style.display = 'none';

$get("spanSeeAlso").innerHTML = '';

//add the values in
for(i = 0; i < result.length; i++)
    {
    var objItem = result[i];
    $get("spanSeeAlso").innerHTML += '<a href="#" title="click to filter by this activity" onclick="return(setActivity(\'' + objItem + '\'));">' + objItem + '</a> ';
    }

}

function setActivity(activity)
{
$get(txtActivity).value = activity;
return false;
}

//hides the popup
function _HidePopup()
{ 
    var popupInfo = document.getElementById("popup");
    popupInfo.style.display = 'none';
    return false;
}


function  debugalert(msg)
{
//alert("debugging message: " + msg);
}

function ToggleMiniMap()
{

if ($get(chkMiniMap).checked == true)
{
    map.ShowMiniMap(680, 5);
}
else
{
 map.HideMiniMap();
 }

}

function toggleMap()
{

if ($get(chkShowMap).checked == true)
{
    $get('mapwrapper').style.display = '';
}
else
{
    $get('mapwrapper').style.display = 'none';
 }

}

//creates a permalink to this map
function DoPermalink()
{
//get parameters
mapCentre = new VELatLong(map.GetCenter().Latitude, map.GetCenter().Longitude);     //get the centre of the map
mapZoomlevel = map.GetZoomLevel();  //get zoom level

var UserName = $get(txtUserName).value;
var Activity = $get(txtActivity).value;

var mindif = document.getElementById(selMinDif).options[document.getElementById(selMinDif).selectedIndex].value;
var maxdif = document.getElementById(selMaxDif).options[document.getElementById(selMaxDif).selectedIndex].value;

var ShowBigMap = $get(chkShowBigMap).checked

//build the URL
myURL = "map.aspx?permalink=true&lat=" + mapCentre.Latitude + "&lon=" + mapCentre.Longitude + "&zoomlevel=" + mapZoomlevel + "&user=" + UserName + "&activity=" + Activity

if (mindif != "")
{
myURL += "&mindif=" + mindif;
}

if (maxdif != "")
{
myURL += "&maxdif=" +  maxdif;
}


myURL += "&ShowBigMap=" +  ShowBigMap;


//update the url
$get('hypPermalink').href= myURL;
}


