﻿/// <reference path="VeJavaScriptIntellisenseHelper.js" />

var map = null;
var mapData = null;    
var panToLat = null;
var panToLong = null;
var mStyle = null;
var legs;
var business = null;
var clear = null;
function startGetMap()
{
    setToken ();
}

function getMap(token)
{         

     var data = $('#mapXml').html();
     if (!data)
     {
         map = new VEMap('YCYWMap');     
         map.SetClientToken(token); 
         map.LoadMap();
         return;
     }
     $('#YCYWMap').show();
     mapData = $.parseJSON( data ); 
     map = new VEMap('YCYWMap');                 
     map.SetClientToken(token);      
     for (var i = 0; i < mapData.length; i++)
     {
        var current = mapData[i];
        business = current;
        $('#DirectionsEndLocation').val(current.Address);
        var latlong = new VELatLong (Number(current.Latitude), Number(current.Longitude),10, VEAltitudeMode.RelativeToGround);  
        if (i == 0) { map.LoadMap (latlong);}
        var icon = "<img src=\"" + imgPushPin + "\" alt=\"" + current.BusinessName + "\" title=\"" + current.BusinessName + "\" />";
        var shape = new  VEShape (VEShapeType.Pushpin, latlong);
        shape.SetDescription(getPopupHtml (current, i));
        shape.SetCustomIcon (icon);
        if (current.Heading.length > 0)
            shape.SetTitle(current.Heading);
        else
            shape.SetTitle(current.BusinessName); 
        map.AddShape (shape);  
        current.ShapeID = shape.GetID ();   
        if (current.HasFocus)
        {
            map.SetCenter (latlong);
        }           
     }
     map.SetZoomLevel (14); 
        document.getElementById('MSVE_obliqueNotification').innerHTML = "";
}   


function getPopupHtml(business)
{
    var desc = "<div><img src=\"" + ycywimgbase + "/m_communityway.jpg\" /></div>"; 
    desc += "<div><strong>" + business.BusinessName + "</strong></div>";
    return desc;                  
}

function getDirections(reverse)
{

    if ($('#DirectionsLocation').val() == '' || $('#DirectionsEndLocation').val() == '')
    {
        alert('Please enter a valid start and end location');
        return;
    }
    var display = $("input[name=display]");
    if (display[0].checked)
    {
        $('#YCYWMap').show();
    }
    else
    {
        $('#YCYWMap').hide();    
    }
    
    map = new VEMap('YCYWMap');
    map.LoadMap();
    map.SetMapStyle(VEMapStyle.Road);  
 
    var html = $('#mapXml').html();   

    if (reverse)
    {
        var tStart =  $('#DirectionsLocation').val();
        var tEnd = $('#DirectionsEndLocation').val();
        $('#DirectionsLocation').val(tEnd);
        $('#DirectionsEndLocation').val(tStart);
        clear = true;
    }
    var startLocation =  $('#DirectionsLocation').val();
    var endLocation =  $('#DirectionsEndLocation').val();
    var options = new VERouteOptions();    
    var route = $("input[name=route]");
    if (route[0].checked)
    {
        options.RouteOptimize = VERouteOptimize.MinimizeTime ;
    }
    else
    {
        options.RouteOptimize = VERouteOptimize.MinimizeDistance;        
    }    
    options.RouteCallback = onGotRoute;    
    
    if (html && !clear){
        var data = $.parseJSON(html);     
        var business = data[0];
        map.GetDirections([startLocation, new VELatLong (Number(business.Latitude), Number(business.Longitude))], 
                           options); 
    }
    else
    {
        map.GetDirections([startLocation, endLocation], options);     
    }
    
       document.getElementById('MSVE_obliqueNotification').innerHTML = "";
}

function onGotRoute(route)
{
   // Unroll route
   legs     = route.RouteLegs;
   var turns    = "Total distance: " + route.Distance.toFixed(1) + " mi\<br /><hr>";
   var numTurns = 0;
   var leg      = null;

   // Get intermediate legs
    for(var i = 0; i < legs.length; i++)
    {
       // Get this leg so we don't have to derefernce multiple times
       leg = legs[i];  // Leg is a VERouteLeg object
          
       // Unroll each intermediate leg
       var turn = null;  // The itinerary leg
          
       for(var j = 0; j < leg.Itinerary.Items.length; j ++)
       {
          turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
          numTurns++;
          var name = turn.Text;
          if (name == 'Arrive')
          {
            name = numTurns + ".\t" + '<strong>Arrive at ' + $('#DirectionsEndLocation').val() + " (" + turn.Distance.toFixed(1) + " mi)</strong><br />";
          }
          else
          {
            name = numTurns + ".\t" + turn.Text + " (" + turn.Distance.toFixed(1) + " mi)<br />";
          }
          turns += name;
       }
       turns += "<br />";
    }
    $('#divDirections').html(turns);
}

function setCenter(latitude, longitude)
{
    var latlong = new VELatLong (Number(latitude), Number(longitude)); 
    map.SetCenter(latlong);       
    panToLat = latitude;
    panToLong = longitude;
}

function setToken()
{
     $.ajax({
        type: 'POST',
        url: ycywbase + '/ajax.ashx?t=map&m=GetToken',
        data: "{}",
        success: function(result) { getMap(result) }
    });
}

$(function() {    
    $('#YCYWMap').attr('style',mapStyle);
    startGetMap();
    $('#btnGo').bind('click', function(){ getDirections(); });
    $('#btnReverse').bind('click', function(){ getDirections(true); });
    $('#DirectionsEndLocation').bind('keyup', function() { clear = true; });
});
