﻿
    var map = null;
    var courseLayer = new VEShapeLayer(); 
    var essentialPushpinLayer = new VEShapeLayer();
    var continuePushpinLayer = new VEShapeLayer();
    
    var globalCourseId = null;
    
    var panel = null;
    var courses = new Array();
    var showingMap = false;
    var pushPins = new Array();             // Associative array of pushpins indexed by CourseId  
    
    function calcOffset (heading)
    {
         //if (isFirefox()) return new VEPixel(28,28);
         //if (isSafari()) return new VEPixel(28,28);
         return new VEPixel(5,5)
    }
    
   function ActivityCodeChanged(e)
   {
        if (panel)
        {
           //panel.SetTitle(e.innerHTML);
           panel.style.visibility = "visible";
        }
        ClearMap();
        SetInitialSearchPosition();
   }
   

    function ToggleCourseProfile()
    {
        var img = document.getElementById("CourseProfile");
        var panel = document.getElementById("PanelProfile");
           
        if (panel.style.visibility == "hidden" && img.src.indexOf("GetAltitudeChart") >= 0 )
        {
           panel.style.visibility="visible";
        }
        else 
        {
           panel.style.visibility="hidden";
        }
    }
    
    function ToggleCourseList()
    {
        if (panel)
        {
           if (panel.style.visibility == "visible") panel.style.visibility = "hidden";
           else 
           {
              ClearMap();
              panel.style.visibility = "visible";
           }
        }
    }
    
    function OnEndZoomComplete()
    {
        if (!showingMap) 
            SelectCourses();
    }
    
    
    function CreateMap(latitude, longitude, zoomlevel)
    {
        var mapElement = document.getElementById("map");
        // 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) }
        }

        if (map != null) map.Dispose();    
        map = new VEMap('map');    
        var options = new VEMapOptions();
        options.EnableBirdseye = false;
        
        map.LoadMap( new VELatLong(latitude,longitude),zoomlevel, VEMapStyle.Hybrid,false,VEMapMode.Mode2D,false,0,options); 
        
        map.AttachEvent("onendzoom", OnEndZoomComplete);
        map.AttachEvent("onendpan", PanComplete);
        map.AttachEvent ("onerror", OnError);
        
        var options =  new VEClusteringOptions(); 
        options.Callback = ClusteringCallback; 
        courseLayer.SetClusteringConfiguration(VEClusteringType.Grid, options);

        map.AddShapeLayer(courseLayer);
        map.AddShapeLayer(essentialPushpinLayer);
        
        var spec = new VECustomIconSpecification();
        spec.Image = '../image/Continue.png';
        spec.ImageOffset = new VEPixel(7,-7);
        spec.TextContent = " ";     
        
        options =  new VEClusteringOptions(); 
        options.Callback = PushpinClusteringCallback; 
        options.Icon = spec;
        continuePushpinLayer.SetClusteringConfiguration(VEClusteringType.Grid, options);
        map.AddShapeLayer(continuePushpinLayer);

        return map;
    }    

    function ClusteringCallback(clusters) 
    { 
       for (var i=0; i < clusters.length; ++i) 
       { 
          var cluster = clusters[i]; 
          var clusterShape = cluster.GetClusterShape(); 
          clusterShape.SetTitle("This cluster has " + cluster.Shapes.length + " courses in it!"); 
          clusterShape.SetDescription("Zoom in for details"); 
       } 
    }

    function PushpinClusteringCallback(clusters) 
    { 
       for (var i=0; i < clusters.length; ++i) 
       { 
          var cluster = clusters[i]; 
          var clusterShape = cluster.GetClusterShape(); 
          var index = Math.floor (cluster.Shapes.length/2);
          var latlon = new VELatLong(cluster.Shapes[index].Latitude,cluster.Shapes[index].Longitude);
          clusterShape.data = cluster.Shapes[index].data;
         
          // Set to arrow
          var dir = Math.round (clusterShape.data.Heading / 3) * 3;   
          url='../image/Arrow/Arrow' + PadDigits(dir,3) + '.png';
          
          var spec = new VECustomIconSpecification();              
          spec.Image = url;
          spec.ImageOffset = calcOffset (clusterShape.data.Heading);
          spec.TextContent = " ";    
          clusterShape.SetCustomIcon(spec);
          
          clusterShape.SetPoints(latlon);
          clusterShape.SetTitle(""); 
          clusterShape.SetDescription(""); 
         
       } 
    }


    function AddCoursePanel()
    {
        panel = document.createElement("div"); 
        panel.style.width="250px";
        panel.style.top ="145px"; 
        panel.style.left = "5px"; 
        panel.style.border = "none";
        panel.style.background = "White";
        //panel.style.padding = "5px";
        panel.style.fontSize=".9em";
        panel.style.visibility = "visible";
        ChangeOpacity(panel,90);
        panel.innerHTML = ""; 
       
        map.AddControl(panel);
    }

    function pageLoad()
    {
        // To fix the drag and drop bug
        setBodyHeightToContentHeight();
        window.attachEvent('onresize', setBodyHeightToContentHeight);
        window.onscroll = setBodyHeightToContentHeight;
        
        if(isSafari())
	    {
	        
	    }
	    else if (isFirefox())
	    {       
            document.getElementById('menuDiv').style.top ="12px";
	    }
	    
        
        ClearCourseProfile();
                 
        if (getURLParameters()["CourseId"] == null)
        {
            SetInitialSearchPosition();
            AddCoursePanel();
        }
        else
            SetInitialCourse();  
            
   }
   
   function SetInitialSearchPosition()
   {     
        var lat = GetCookie("InitialUserLatitude");
        var lon = GetCookie("InitialUserLongitude");
        
        if (map)
            map.SetCenterAndZoom(new VELatLong(lat,lon),3);// Higher levels are closer to ground
        else 
            map = CreateMap(lat,lon,3);
            
        AddCoursePushPins();
   }
   
   function OnGetStartWaypointComplete(waypoint)
   {
        var lat = null;
        var lon = null;
        
        if (waypoint == null)
        {
           lat = GetCookie("InitialUserLatitude");
           lon = GetCookie("InitialUserLongitude");
        }
        else
        {
           lat = waypoint.Latitude;
           lon = waypoint.Longitude;
        }
        
        if (map)
            map.SetCenterAndZoom(lat,lon,10);// Higher levels are closer to ground
        else
            map = CreateMap(lat,lon, 10);
        
        //AddCoursePushPins();
        MapCourse(getURLParameters()["CourseId"]);
   }
     
   function SetInitialCourse()
   {    
        var courseId = getURLParameters()["CourseId"];
          
        if (courseId != null)
        {
           // Disable the Activity Code drop down and get rid of the courses panel for now..
           document.getElementById("SelectActivityCode").disabled ="disabled";
           if (panel)
            panel.style.visibility = "hidden";
               
           PeakSwc.GpsTrainer.WebService.GetStartWaypoint(courseId, OnGetStartWaypointComplete,WebServiceError);
        }
   }
   
    function GetToolbar()
    {
        var html = "<table cellpadding=\"0\" cellspacing=\"0\" ";
        html += "border=\"0\" align=\"left\">";
        html += "<tr><td valign=\"top\" align=\"center\">";
        html += "<a href=\"javascript:ClearMap();\" ";
        html += "oncontextmenu=\"return false;\">Clear Map</a> ";
        html += "</td></tr><tr><td> </td></tr></table>";
        return html;
    }

    function ClearPanel()
    {
        if (panel)
           panel.innerHTML='';
    }

    function OnError(e)
    {
        alert ("error:" + e.error);
    }
   
    function PanComplete()
    {
        if (showingMap) return;
        
        SelectCourses();
    }
   
    function SelectCourses()
    {
           
       var courseId = getURLParameters()["CourseId"];
       if (courseId) 
       {
            if (courses[courseId]) 
                OnGetCourseRequestComplete(courses[courseId]);
            else
                PeakSwc.GpsTrainer.WebService.GetCourse(courseId, OnGetCourseRequestComplete, WebServiceError);
       }
       else
       { 
          var actCodeSelect = document.getElementById("SelectActivityCode");
          //var radiusMeters = MetersPerPixel(map);
          var mapHeight = document.getElementById('map').clientHeight;
	      var mapWidth = document.getElementById('map').clientWidth;
	      
	      var rsquared = Math.pow (map.vemapcontrol.GetMetersPerPixel() * mapWidth / 2, 2) + Math.pow (map.vemapcontrol.GetMetersPerPixel() * mapHeight / 2, 2);
          var radiusMeters = Math.pow (rsquared,.5);
         
          PeakSwc.GpsTrainer.WebService.SelectCourses(eval(actCodeSelect.value), map.GetCenter().Longitude,map.GetCenter().Latitude,radiusMeters/1000, OnWSMapRequestComplete, WebServiceError);
      }
    }
    
    function AddCoursePushPins()
	{
        ClearPanel();

        map.DeleteAllPushpins();
        pushPins = new Array();
   
        SelectCourses();     
   }
    
   function EmailCourse(courseId)
    {
        var body = "http://www.gpsTrainer.com/Pages/VEMap.aspx?CourseId="+courseId+" \n\n";
      
        var url = 'mailto:?subject=gpsTrainer%20Course&body=' + escape(body);
        window.open(url);
    }
    
    function OnGetCourseRequestComplete(course)
    {
        var actCodes = document.getElementById("SelectActivityCode");
        actCodes.options[course.ActivityCode].selected = true;
        if (panel)
            panel.SetTitle(document.getElementById("SelectActivityCode").options[document.getElementById("SelectActivityCode").selectedIndex].text);

        var result = new Array();
        result.push (course);
        OnWSMapRequestComplete(result);
    }
    
    function FormatCourseData(course)
    {
        var result = "Dist: " + KilosToMiles(course.DistanceKM).toFixed(1) + " mi.<br/>" + "Alt Gain: " + KilosToFeet(course.AltitudeGainKM).toFixed(1) + " ft.<br/>";
        if (course.Url.length >0) result += "URL: <a href='" + course.Url + "'>" + course.Url + "</a>";
        return result;
    }
    
    function OnWSMapRequestComplete(result) 
    {
        for (var i=0; i<result.length; i++)
        {
            courses[result[i].CourseId] = result[i];
        }
        var body = "<div style=\"margin-left:5px;position: absolute;font-weight:bold\">COURSES</div>" +
           "<div style=\"background-color: #E8B836;border-bottom: #585880 1px  solid; \"><a style=\"font-weight: bold; text-decoration: none; width:250px; position:relative; left:235px\" href=\"javascript:ToggleCourseList();\">X</a></div>";
         
        if (panel)
           panel.innerHTML=body;
        
        VEPushpin.ShowDetailOnMouseOver=true;
        
        for (var i=0; i<result.length; i++)
        {         
             if (pushPins[result[i].CourseId] == null) 
             {             
	            var pp = new VEShape (VEShapeType.Pushpin, new VELatLong(result[i].StartLatitude, result[i].StartLongitude));  
	            pp.SetTitle(result[i].Name);
	            pp.SetDescription(FormatCourseData(result[i]) + GetCourseToolbar(result[i].CourseId));
	         
	            if (!showingMap)  // v3
	               courseLayer.AddShape(pp);
	            pushPins[result[i].CourseId] = pp;
	         }
		      
            body += "<b style=\"margin:5px\">" + i +": <a style=\"padding:3px;\" class='menu' href=\"javascript:MapCourse('"+result[i].CourseId+"',"+result[i].StartLatitude+","+result[i].StartLongitude+");\" oncontextmenu=\"return false;\">"+result[i].Name+"</a></b><br/>";
        }
        if (panel)
           panel.innerHTML = body; 
        
        var courseId = getURLParameters()["CourseId"]; 
    }
    
    function GetCourseToolbar(courseId)
    {
        var html = "<table cellpadding=\"0\" cellspacing=\"0\" ";
        html += "border=\"0\" align=\"left\">";
        html += "<tr><td valign=\"top\" align=\"left\">";
        html += "<a href=\"javascript:MapCourse('"+courseId+"');\" ";
        html += "oncontextmenu=\"return false;\">Draw Map</a></td></tr>";
        //html += "<a href=\"javascript:ClearMap();\" ";
        //html += "oncontextmenu=\"return false;\">Clear Map</a> | ";
        html += "<tr><td><a href=\"javascript:EmailCourse('"+courseId+"');\" ";
        html += "oncontextmenu=\"return false;\">Email Course</a> ";
        html += "</td></tr></table>";
        return html;
    }
    
    function ClearMap()
    {
        showingMap=false;
        if(panel)
            panel.style.visibility = "visible";
        map.DeleteAllShapes();
        ClearCourseProfile();
       
        // add back the courses
        AddCoursePushPins();
    }
    
    function MapCourse(courseId)
    {
        globalCourseId = courseId;
        if (panel)
            panel.style.visibility = 'hidden';
        map.DeleteAllPushpins();
        pushPins = new Array();
        showingMap = true;
        
        PeakSwc.GpsTrainer.WebService.WaypointBoundingRectangle(courseId, OnMapCourseZoom,WebServiceError);
        
         // Draw the map
        PeakSwc.GpsTrainer.WebService.SelectEssentialWaypoints(courseId, OnMapCourseRequestComplete2,WebServiceError);           
        //PeakSwc.GpsTrainer.WebService.GetWaypoints(courseId, OnMapCourseRequestComplete2,WebServiceError);           
    }
    
    function OnMapCourseZoom(result) 
    {
        // Zoom then Draw the map
        if (result != null)
            map.SetViewport(result.Northeast.Latitude, result.Southwest.Longitude, result.Southwest.Latitude, result.Northeast.Longitude); 
    }
    
    function ClearCourseProfile()
    {
        var img = document.getElementById("PanelProfile");
        //img.src = "";
        if (img)
           img.style.visibility="hidden";
    }
    
    function DrawCourseProfile(courseId)
    {  
        var img = document.getElementById("CourseProfile");
        var panel =  document.getElementById("PanelProfile");
        img.src = "GetAltitudeChart.aspx?Width=800&Height=200&Color=Blue&CourseId="+courseId;
        panel.style.visibility="visible";
    }
    
    function DrawMap(course)
    {
         var PATH_OPACITY = .8;
         var points= new Array();
        
         for (var i = 0; i < course.Points.length; i = i + 2)
         {
            points.push (new VELatLong(course.Points[i+1],course.Points[i]));
         }
        
        
        var poly = new VEShape(VEShapeType.Polyline, points);
        poly.SetLineColor(new VEColor(255,0,0,PATH_OPACITY));
        poly.SetLineWidth(2);
        poly.HideIcon();
        map.AddShape(poly);
                 
        if (course != null && poly != null && poly.GetPoints().length >= 2)
        {    
            var style='pinStart';
            var url = '../image/Start.png';
            // Start     
            	    
            var pp = new VEShape (VEShapeType.Pushpin, new VELatLong(poly.GetPoints()[0].Latitude, poly.GetPoints()[0].Longitude));
	       
	        var spec = new VECustomIconSpecification();
            spec.Image = url;
            //spec.ImageWidth = 12;
            //spec.ImageHeight = 20;
            spec.ImageOffset = new VEPixel(7,-7);  
            spec.TextContent = " ";        
	        pp.SetCustomIcon(spec);
	      
	        var title = "Start: "+ course.Name;
	        pp.SetTitle(title);
	        pp.SetDescription(FormatCourseData(course));
	    
	         
            map.AddShape(pp);
            
//            var id = document.getElementById(course.CourseId+'Start');                   
//            id.style.zIndex = 260;
//            id.children[0].style.zIndex = 260;
            
            var start = new Position( poly.GetPoints()[0].Latitude, poly.GetPoints()[0].Longitude);
            var finish = new Position( poly.GetPoints()[poly.GetPoints().length-1].Latitude, poly.GetPoints()[poly.GetPoints().length-1].Longitude);
            var title = "";
          
            if (start.DistanceTo(finish) * 1000 < 10)
            {
                url = '../image/StartFinish.png';
                style = 'pinStartFinish';
                title = "Start/Finish: "+course.Name;
            }
            else
            { 
                url = '../image/Finish.png';
                style = 'pinFinish';
                title = "Finish: "+course.Name;
            }
            
            // Finish
            // 6.2
            // pp = new VEPushpin(course.CourseId+'End', new VELatLong(poly.LatLongs[poly.LatLongs.length-1].Latitude, poly.LatLongs[poly.LatLongs.length-1].Longitude),url,"Finish: "+FormatCourseData(course),GetCourseToolbar(course.CourseId),style);
	         
	        var pp = new VEShape (VEShapeType.Pushpin, new VELatLong(poly.GetPoints()[poly.GetPoints().length-1].Latitude, poly.GetPoints()[poly.GetPoints().length-1].Longitude));
	        
	        
	        var spec = new VECustomIconSpecification();
            spec.Image = url;
            spec.ImageOffset = new VEPixel(7,-7);  
            spec.TextContent = " ";        
	        pp.SetCustomIcon(spec);
	        
	       
	        pp.SetTitle(title);
	        pp.SetDescription(FormatCourseData(course));
	         
	            
            map.AddShape(pp);
            
//            id = document.getElementById(course.CourseId+'End');  
//            id.style.zIndex = 159;
             
            DrawCourseProfile(course.CourseId);
        }
    }
    
    function OnMapCourseRequestComplete(course) 
    {
        map.DeleteAllShapes();
        
        if (course.Points.length == 0)
        {
            alert('No course map found.');
            showingMap = false;
        }
        else
        {
            DrawMap(course);
        }
    }
    
    function OnMapCourseRequestComplete2(waypoints) 
    {
        map.DeleteAllShapes();
        
        if (waypoints.length == 0)
        {
            alert('No course map found.');
            showingMap = false;
        }
        else
        {
            DrawMap2(waypoints);
        }
    }
    
    function DrawMap2(waypoints)
    {
         var PATH_OPACITY = .8;
         var points= new Array();
         var essentialPushpins = new Array();
         var continuePushpins = new Array();
        
         for (var i = 0; i < waypoints.length; i++)
         {
            points.push (new VELatLong(waypoints[i].Latitude,waypoints[i].Longitude));
         }
        
        
        var poly = new VEShape(VEShapeType.Polyline, points);
        poly.SetLineColor(new VEColor(255,0,0,PATH_OPACITY));
        poly.SetLineWidth(2);
        poly.HideIcon();
        map.AddShape(poly);
        
        
        for (var i=0; i < waypoints.length; i++) 
        {
            var waypoint = waypoints[i];
            
            if (waypoint.Timestamp == null) continue;
             
            var pp = new VEShape (VEShapeType.Pushpin, new VELatLong(waypoints[i].Latitude, waypoints[i].Longitude)); 
	         
            var style = waypoint.WaypointType;
            
            var zindex = 160;
            var url = '';
              
            if (style == WaypointType.TurnRight) { url='../image/TurnRight.png' }
            else if (style == WaypointType.TurnLeft) { url='../image/TurnLeft.png' }
            else if (style == WaypointType.TurnAround) { url='../image/TurnAround.png' } 
            else if (style == WaypointType.StartInterval) { url='../image/StartInterval.png';}
            else if (style == WaypointType.FinishInterval) { url='../image/FinishInterval.png';}
            else if (style == WaypointType.Announcement) { url='../image/Announcement.png';}
            else if (style == WaypointType.Continue) { 
                zindex=159;
                var dir = Math.round (waypoints[i].Heading / 3) * 3;   
                url='../image/Arrow/Arrow' + PadDigits(dir,3) + '.png';
            }
            else if (style == WaypointType.Start) { 
                zindex=161;
                url='../image/Start.png' 
                if (courses[globalCourseId])
                {
                   var title = "Start: "+ courses[globalCourseId].Name;
	               pp.SetTitle(title);
	               pp.SetDescription(FormatCourseData(courses[globalCourseId]));
	            }
            }
            else if (style == WaypointType.Summit) { url='../image/Summit.png' }
            else if (style == WaypointType.FeedZone) { url='../image/FeedZone.png' }
            else if (style == WaypointType.Finish) 
            { 
                zindex=162;
                var startIndex = 0;
                url = '../image/Finish.png';
                if (waypoints[i].Longitude == waypoints[startIndex].Longitude && waypoints[i].Latitude == waypoints[startIndex].Latitude && pruned && pruned[startIndex].WaypointType == "Start")
                {
                    url='../image/StartFinish.png';
                }
            }
                  
	        var spec = new VECustomIconSpecification();
            spec.Image = url;
            
            if (style == WaypointType.Continue)
               spec.ImageOffset = calcOffset (waypoints[i].Heading );
            else
               spec.ImageOffset = new VEPixel(7,-7);
               
            spec.TextContent = " ";     
                     
	        pp.SetCustomIcon(spec);
	        pp.SetZIndex(zindex);
	        pp.data = waypoints[i];
	     
	        if (style == WaypointType.Continue)
	           continuePushpins.push(pp);
	        else
	           essentialPushpins.push(pp);     
        }
        continuePushpinLayer.AddShape(continuePushpins);
        essentialPushpinLayer.AddShape(essentialPushpins);  
        DrawCourseProfile(globalCourseId);
    }
    
    