﻿/// <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;
var ycywbase = ycywroot + '/ajax';
var displayMapFlag=true;
var hasDirections=true;
var DivID='';

function startGetMap()
{
    debugger ;
    setToken ();
}


function startGetMapwithID(id)
{
    DivID = id;
    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); 
}   

function getMapwithID(token)
{         
     var data = $('#mapXml').html();

     if (!data)
     {
      
        map = new VEMap(DivID);    
    
         map.SetClientToken(token); 
         map.LoadMap();
         return;
     }
     
        $(DivID).show();
            
            
     mapData = $.parseJSON( data ); 
     
  
         map = new VEMap(DivID);                   
       
        
        
     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); 
}   
function getPopupHtml(business)
{
    var desc = ""; 
     
    
     if (business.Address.length > 0)
        var busAddress = business.Address;
        desc += "<div>" + busAddress.replace(/\,\,/g,","); + "</div>";
    if (business.PhoneNumber.length > 0)
        desc += "<div>Phone: " + business.PhoneNumber + "</div>";
//    if (business.FaxNumber.length > 0)
//        desc += "<div>Fax: " + business.FaxNumber + "</div>";  
//    if (business.DisplayAdUrl.length > 0)
//        desc += "<div>"+ business.DisplayAdUrl + "</div>"; 
//    if (business.EmailAddress.length > 0)
//        desc += "<div>E-mail: " + business.EmailAddress + "</div>";            
    if (business.Website.length > 0)
        desc += "<div><a target=\"_blank\" href=\"" + "http://" + business.Website + "\">Web Site</a></div>";
//    if (business.Description.length > 0)
//        desc += "<div style=\"padding: 5px 0 5px 0;\">" + business.Description + "</div>"; 
//    if (business.CouponsUrl.length > 0)
//        desc += "<div><a target=\"_blank\" href=\"" + business.CouponsUrl + "\">Coupons for this business</a></div>";       
//    desc += "<div><a href='GetDirections.aspx?La=" + business.Latitude + "&Lo=" + business.Longitude + "&Bi=" + urlencode(escape(business.BusinessName)) + "&Ad=" + escape(business.Address) + "' target='GetDirections' title=\"Directions to this location\">Directions to this location</a></div>";           
//    desc += "<div><a href=\"javascript:sendToFriendOpen(" + "0" + ");\" title=\"Send map to friend\">Send map to friend</a></div>";

    return desc + "<br/>";                  
}
function urlencode(str) {
str = escape(str);
str = str.replace('+', '%2B');
str = str.replace('%20', '+');
str = str.replace('*', '%2A');
str = str.replace('/', '%2F');
str = str.replace('@', '%40');
return str;
}

function sendToFriendOpen(idx)
{
    $('#friendModal').jqmShow();
    $('#btnSendToFriend').bind('click', function(){ sendToFriendComplete (idx); });
}
function getDirections(reverse)
{
  DivID = 'Map12';
    if ($('#DirectionsLocation').val() == '' || $('#DirectionsEndLocation').val() == '')
    {
        alert('Please enter a valid start and end location');
        return;
    }
    var display = $("input[name=display]");
    if (display[0].checked)
    {
       
        $('#' + DivID).show();
    }
    else
    {
        $('#' + DivID).hide();    
    }
    
    map = new VEMap(DivID);
    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);     
    }
}

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 />";
    }
   // $('#Map1').html(turns);
    $('#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) { 
  
    
        getMapwithID(result)
  //       $('#' + DivID).show()
         }
    });
}

$(function() {   
  if(fromWhere == 'getdirections') 
  {
//    $('#YCYWMap').attr('style',mapStyle);
//    startGetMap();
//    $('#btnGo').bind('click', function(){ getDirections(); });
//    $('#btnReverse').bind('click', function(){ getDirections(true); });
//    $('#DirectionsEndLocation').bind('keyup', function() { clear = true; });
  }
});