var j$ = jQuery.noConflict();
var vemap = null;
var pntsLayer = null;
var gblOffset = 0;
var gblTar = null;
var gblTotal = 0;
var gblCount = 10; //default set to return 5 items
var LAT = null;
var LON = null;
var GblAddress;

//test for Safari and redirect if found
//ua = navigator.userAgent.toLowerCase();
//if (ua.indexOf("safari")!=-1) {window.location = "http://intl.local.live.com/";}

     j$(document).ready(function(){
	 
	 j$("#divMapDirections").toggle();
          
          j$(".close").unbind("click").click(function() {
            j$("#divMapDirections").hide();
            j$("#divMapContents").show();
            ClearMap();
          });
     
          j$(".print").unbind("click").click(function() {
            window.open("/PrintMap.htm");
          });
		  
	GetMap();
     //make initial call to get list
    j$.ajax({
           type: "POST",
           url: "/ajax.ashx",
           data: {method: "startup"},
           dataType: "json",
           success: function(ret){
             fnLoadMapButtons(ret); 
			 gblTar=ret[0].CategoryID;
			 //if (location.search.length>0){
				// j$("#CategoryLinks .MapButtonsSelected").removeClass("MapButtonsSelected");
				// var idx=(location.search.indexOf("=")+1);
				// if (location.search.substring(idx, location.search.length).indexOf("Holiday")>-1){
				//	vemap.Find("Hotel", "7501 W Saginaw Hwy Lansing, MI 48917");
				//}else{					
				//	vemap.Find("Hotel", "3121 E. Grand River Lansing, MI 48912");}
			//}else{
				j$("#divMapContentsHeader").html(ret[0].CategoryName);
				 j$.ajax({  
				   type: "POST",
				   url: "/ajax.ashx",
				   data: {method : "GetListItems", tarID : ret[0].CategoryID, Offset : "0", Count : gblCount},
				   dataType: "json",
				   success: function(rett){
					  DeleteLayer();
					  gblOffset = 0;
					  fnLoadMapItems(rett);  
				   } ,
				   error: function(msg){
					   j$("#divFeedbackItems").html("Error:  "+msg.responseText);
				   }
				 });
			//}
           }
     });
      
     j$("#divLoading").bind("ajaxSend", function(){
           j$(this).show();
         }).bind("ajaxComplete", function(){
           j$(this).hide();
		 
           if (gblOffset==0)
            {
                j$(".prev").hide();
            }
            else
            {
                j$(".prev").show();
				j$(".prev").unbind("click").click(function (){
                    j$.ajax({
                       type: "POST",
                       url: "/ajax.ashx",
                       data: {method : "GetListItems", tarID : gblTar, Offset : parseInt(gblOffset)-parseInt(gblCount), Count : gblCount},
                       dataType: "json",
                       success: function(ret){
                          DeleteLayer();
                          fnLoadMapItems(ret);  
                       } ,
                       error: function(msg){
                           j$("#divFeedbackItems").html("Error:  "+msg.responseText);
                       }
                       });
                    return false;
                });
            }
            
            if (gblOffset==gblTotal)
            {
                j$(".next").hide();
            }
            else
            {
                j$(".next").show();
                j$(".next").unbind("click").click(function (){
                    j$.ajax({
                       type: "POST",
                       url: "/ajax.ashx",
                       data: {method : "GetListItems", tarID : gblTar, Offset : parseInt(gblOffset)+parseInt(gblCount), Count : gblCount},
                       dataType: "json",
                       success: function(ret){
                          DeleteLayer();
                          fnLoadMapItems(ret);  
                       } ,
                       error: function(msg){
                           j$("#divFeedbackItems").html("Error:  "+msg.responseText);
                       }
                       });
                    return false;
                });
                
            }
     });
	  
     });
     
     function fnLoadMapButtons(Category) {
        j$.each(Category, function(i, n){
            j$("<li class=\"MapButtons\"><a id=\"aName\" href=\"#MapButtons\"></a></li>").appendTo("#CategoryLinks");
            var c = j$("#CategoryLinks :last-child");
    
		if (i == 0){
			c.addClass("MapButtonsSelected");
		}
           c.hover(function() {
                 j$(this).addClass("MapButtonsHover");
               },function(){
                 j$(this).removeClass("MapButtonsHover");
           });
            
            j$.each(Category[i], function(i, n){
                switch (i){
                   case "CategoryID":  
                        c.find("#aName").attr("target",n);
                   break;
                   case "CategoryName":
                        c.find("#aName").html(n);
                        c.find("#aName").click(function (){
                              j$("#ulContents").empty();
                              j$("#divMapContentsHeader").html(n);     				  
                             j$.ajax({  
                                   type: "POST",
                                   url: "/ajax.ashx",
                                   data: {method : "GetListItems", tarID : j$(this).attr("target"), Offset : "0", Count : gblCount},
                                   dataType: "json",
                                   success: function(ret){
                                      DeleteLayer();
                                      ClearMap();
                                      gblOffset = 0;
									  j$("#CategoryLinks .MapButtonsSelected").removeClass("MapButtonsSelected");
									  c.find("#aName").parent().addClass("MapButtonsSelected");
                                      gblTar = c.find("#aName").attr("target");
                                      fnLoadMapItems(ret, c.find("#aName").attr("target"));  
                                   } ,
                                   error: function(msg){
                                       j$("#divFeedbackItems").html("Error:  "+msg.responseText);
                                   }
                                 });
                            return false;
                        });
                   break;
                }
            });
			
        });
 }
 
 function fnLoadMapItems(Items)
 {
 CreateLayer();
 j$("#divMapDirections").hide();
 j$("#divMapContents").show();
 j$("#ulContents").empty();
    //j$("div .nav").show();
    j$.each(Items, function(i, n){
        if (i==0)
        {
            gblOffset=Items[i].Offset;
            gblTotal=Items[i].Total;
        }
        else
        {
            j$("<li class=\"lstMapItems\"><div class='pinStyle1'><div class='text'></div></div><p class=\"lstMapItemsp\"><span class=\"blue-text\"><strong><label id=\"Name\"/></strong></span><br /><label id=\"Address\" />, <label id=\"City\" /> <label id=\"Zip\" /><label id=\"Message\"/><br /><label id=\"Phone\"/><label id=\"Email\"/><br /><a id=\"Website\" class=\"blue-text\">Details</a>&nbsp;|&nbsp;<a class=\"aDirections\" href=\"#Directions\" class=\"blue-text\">Directions</a></li>").appendTo("#ulContents");
            var c = j$("#ulContents li:last-child");
        
            //add the number to the graphic
            c.find(".text").html(i);
			
		   /*c.hover(function() {
				 j$(this).addClass("lstMapItemsHover");
			   },function(){
				 j$(this).removeClass("lstMapItemsHover");
		   });*/
		   
		   c.hover(function() {
                 j$(this).addClass("lstMapItemsHover");
                 c.find(".pinStyle1").css("background-position","0px -35px");
                  var s = pntsLayer.GetShapeByIndex((i-1));
                  s.SetCustomIcon("<div class='pinStyle2' style='background-position: \"0px -35px\"'><div class='text'>"+i+"</div></div>");
               },function(){
                 j$(this).removeClass("lstMapItemsHover");
                 c.find(".pinStyle1").css("background-position","0px 0px");
                 var s = pntsLayer.GetShapeByIndex((i-1));
                 s.SetCustomIcon("<div class='pinStyle2' style='background-position: \"0px 0px\"'><div class='text'>"+i+"</div></div>");
           });
			          
            j$.each(Items[i], function(x, n){
                if (x=='Website')
                    {
                      if (n!='')
                      {
                        c.find("#"+x).attr("href",n);
                      } 
                      else
                      {
                        c.find("#"+x).hide();
                      } 
                    }
                else if (x=='Name')
                    {
					
                        c.find("#"+x).html(n).click(function(){
							try
							{
								vemap.HideInfoBox()
								var shp = pntsLayer.GetShapeByIndex((i-1));
								vemap.ShowInfoBox(shp, shp.GetIconAnchor());
							}
							catch(VEException)
					        {
						        //alert(VEException.message);
					        }	
                        }).bind("mouseout",function(){
                            setTimeout("vemap.HideInfoBox()",2000);
                        }).hover(function(){
                                j$(this).css("cursor","pointer");
                                j$(this).css("text-decoration","underline");
                            }, function(){
                                j$(this).css("cursor","default");
                                j$(this).css("text-decoration","none");
                            });
                    }
                else
                    {c.find("#"+x).html(n);}
            });
		
	    c.find(".pinStyle1").bind("click",function(){
		try
			{
			    vemap.HideInfoBox()
				var shp = pntsLayer.GetShapeByIndex((i-1));
				vemap.ShowInfoBox(shp, shp.GetIconAnchor());
			}
			catch(VEException)
			{
				//alert(VEException.message);
			}
	    }).bind("mouseout",function(){
		setTimeout("vemap.HideInfoBox()",3000);
            })
            
            c.find("a.aDirections").click(function() {
               var addy=Items[i].Address+", "+Items[i].City+" MI "+Items[i].Zip;
               ClearMap();
               fnGetDirections(Items[i].GeoX, Items[i].GeoY, addy);
                return false;
            });
            
            //add the map object
            var shape = new VEShape(VEShapeType.Pushpin,new VELatLong(Items[i].GeoX, Items[i].GeoY));
            shape.SetCustomIcon("<div class='pinStyle2'><div class='text'>"+i+"</div></div>");
            shape.SetTitle(Items[i].Name);
            var msg = (Items[i].Message==null)?"":Items[i].Message;
            var phone = (Items[i].Phone==null)?"":Items[i].Phone;
            var email = (Items[i].Email==null)?"":Items[i].Email;
            var web = (Items[i].Website==null)?"":Items[i].Website;
			var adddy=Items[i].Address+", "+Items[i].City+" MI "+Items[i].Zip;
            shape.SetDescription("<table cellpadding=\"1\" cellspacing=\"2\" width=\"100%\" border=\"0\"><tr><td colspan=\"2\">Title: "+Items[i].Name+"</td></tr><tr><td colspan=\"2\">Address: "+Items[i].Address+", "+Items[i].City+", "+Items[i].Zip+"</td></tr><tr><td colspan=\"2\">Description: "+msg+"</td></tr><tr><td colspan=\"2\">Phone: "+phone+" : Email: "+email+"</td></tr><tr><td><a id=\"awebsite\" style=\"color: #000000;\" target=\"_blank\" href="+web+">Details</a></td><td><a id=\"aDir\" href=\"#GetDirections\" onclick=\"javascript:fnGetDirections('"+Items[i].GeoX+"','"+Items[i].GeoY+"', '"+adddy+"')\" style=\"color: #000000;\">Directions</a></td></tr></table>");
            pntsLayer.AddShape(shape);
          }
      });
 }
     
 function fnGetDirections(x, y, addy)
 {
		GblAddress=addy;
		//load print js objects
		   LAT=x;
		   LON=y;
        j$("#divMapDirections").show();
		//dont know the jQuery call for this
        document.getElementById("divMapDirections").scrollTop=0;
        j$("#divMapContents").hide();
        var locations;
          locations = new Array("4100 Capitol City Blvd, Lansing, MI 48906",new VELatLong(x,y));
          var options = new VERouteOptions;
          options.DrawRoute = true;
          // Call this function when map route is determined:
          options.RouteCallback = ShowTurnByTurn;
          // Show as miles
          options.DistanceUnit = VERouteDistanceUnit.Mile;
          options.ShowDisambiguation = true;
          vemap.GetDirections(locations, options);
        return false;
 }
 
 function ShowTurnByTurn(route)
 {
    var Hcontent = "<h3>Turn-by-Turn Directions</h3>";
    Hcontent += "<p><b>Distance:</b> " + route.Distance.toFixed(1) + " miles";
    Hcontent += "<br/><b>Time:</b> " + GetTime(route.Time) + "</p>";
    Hcontent += "<hr/>";
    
   // Unroll route and populate DIV
   var legs          = route.RouteLegs;
   var leg           = null;
   var turns         = "";
   // 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
      var legDistance = null;  // The distance for this leg
      
      for(var j = 0; j < leg.Itinerary.Items.length; j ++)
      {

         turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
         turns += "<li class=\"Directions\">";
         if (j==0) //begin departure
         {
            turns += "<b>Start: </b>\t" + turn.Text;
         }
         else if (j==(leg.Itinerary.Items.length-1))//end arrive
         {
            turns += "<b>End: </b>\t" + GblAddress;
         }
         else
         {
            turns += "<p><b>" + j + "</b>\t" + turn.Text + "</p>";
         }
         legDistance = turn.Distance;

         // So we don't show 0.0 for the arrival
         if(legDistance.toFixed(1) > 0)
         {
            // Round distances to 1/10ths
            turns += "<span>" + legDistance.toFixed(1) + "m";

           // Append time if found
            /* if(turn.Time != null)
            {
               turns += "; " + GetTime(turn.Time);
            } */

            turns += "</span><br class='clear' />";
         }
         turns += "</li>";
      }
      // Populate with directions
      SetDirections(Hcontent, turns, "inline");
    }
 }

function SetDirections(headerContent, liItems, dspyPlace)
{
    if (dspyPlace=="inline")
    {
        //header content on General Trip Estimates
        j$("#DirectionHeader").html("");
        j$(headerContent).appendTo("#DirectionHeader");
        //populate list Items
        j$("#olDirections").empty();
        j$(liItems).appendTo("#olDirections");
    }
    else
    {
    
    }
}

 // time is an integer representing seconds
 // returns a formatted string
 function GetTime(time)
 {
    if(time == null)
    {
       return("");
    }

    if(time > 60)
    {                                 // if time == 100
       var seconds = time % 60;       // seconds == 40
       var minutes = time - seconds;  // minutes == 60
       minutes     = minutes / 60;    // minutes == 1


       if(minutes > 60)
       {                                     // if minutes == 100
          var minLeft = minutes % 60;        // minLeft    == 40
          var hours   = minutes - minLeft;   // hours      == 60
          hours       = hours / 60;          // hours      == 1

          return(hours + " hour(s), " + minLeft + " minute(s), " + seconds + " second(s)");
       }
       else
       {
          return(minutes + " minutes, " + seconds + " seconds");
       }
    }
    else
    {
       return(time + " seconds");
    }
 }

     
     
     
     
//*******************MAP FUNCTIONS**********************************
    function GetMap()         
    {          
	    try
	    {  
 		    vemap = new VEMap('divMap');
		    vemap.SetDashboardSize(VEDashboardSize.Normal);
		    vemap.LoadMap(new VELatLong(42.77419, -84.58857), 12 ,'r' ,false);
		    
	    }
	    catch(ex)
	    {
		    alert(ex.message);
	    }    
    }    
    
      function CreateLayer()
      {
         pntsLayer = new VEShapeLayer();
         vemap.AddShapeLayer(pntsLayer);
      }
      
      function DeleteLayer()
      {
         if(pntsLayer != null)
         {
            vemap.DeleteShapeLayer(pntsLayer);
            pntsLayer = null;
         }
      }
	  
	  function ClearMap()
      {
        vemap.DeleteRoute();
      }