var map = Array();
var coord = Array();
var curr_map = Array();
var curr_coord = Array();
var zoom_level = 12;

	function onGotRoute(route_d)
    {
		var center = curr_map.GetCenter();
		var center_lat = center.Latitude;
		var center_long = center.Longitude;
		var start_lat = route_d.RouteLegs[0].StartLocation.Latitude;
		var start_long = route_d.RouteLegs[0].StartLocation.Longitude;
		var end_lat = route_d.RouteLegs[0].EndLocation.Latitude;
		var end_long = route_d.RouteLegs[0].EndLocation.Longitude;
		var zoom_level = curr_map.GetZoomLevel();
		var other_town = $('form.trip-calc').find('#zip').val();
		var bing_print_url = "http://www.bing.com/maps/print.aspx?mkt=en-us"+
			"&z="+zoom_level+"&s=r"+
			"&cp="+center_lat+","+center_long+"&pt=pf"+
			"&rtp=pos."+start_lat+"_"+start_long+"_"+other_town+"~pos."+end_lat+"_"+end_long+"_Toledo, OH"+"&mode=D"+"&KeepThis=true&TB_iframe=true&height=376&width=500"; 
		$('a.greybox').attr('href', bing_print_url);
    }
		
	function LoadAllMaps()
	{
		$.each(map,
			function(key,val)
			{
				val.LoadMap(coord[key], zoom_level);
				addMainShape(val,coord[key]);
				var map_id = val.ID.toString();
				if (map_id == "myMap")
				{
					AddShapes();
				}
	  			$('#'+map_id).parent().parent('.bing_map_container').css('display','none');
			}
		);
	}

	$(document).ready(
		function()
		{
			var checkingMap = $( '#myMap' );
			if( checkingMap.length > 0 )
			{
				var interval = setInterval(
					function()
					{
						if((eval("typeof VEMap") != "undefined") && (document.getElementById("myMap").attachEvent != undefined))   
						{
							clearInterval(interval);
							LoadAllMaps();
						}
					},
					100
				);
			}
		}
	);
        
    
    function addMainShape(curr_map,coords)
    {
		var shape = new VEShape(VEShapeType.Pushpin, coords);;
		shape.SetCustomIcon('<div class="pin_green_star_big"></div>');

		var shapeLayer = new VEShapeLayer();
		curr_map.AddShapeLayer(shapeLayer);
		shapeLayer.AddShape(shape);
    }
	
    function Find_ok(layer, resultsArray, places, hasMore, veErrorMessage)
    {
      if (places)
      {
        try
        {
          curr_map.DeleteShapeLayer(curr_map.GetShapeLayerByIndex(1));
        } catch(err) {}
        var locations = Array();
        var options = new VERouteOptions;
        locations.push(places[0].LatLong);
        locations.push(curr_coord);
        curr_coord = null;
        options.SetBestMapView = true;
        options.DrawRoute = true;
        options.RouteColor = new VEColor(0,0,0,0.7);
        options.DistanceUnit   = VERouteDistanceUnit.Mile;
        if ($('div.map-controls').length != 0)
          options.RouteCallback  = calcGas;
        curr_map.GetDirections(locations,options);
      } 
    }
    
    function RemoveLayers()
    {
		var count = curr_map.GetShapeLayerCount();
		try
		{
		  curr_map.DeleteShapeLayer(curr_map.GetShapeLayerByIndex(1));
		} catch(err) {}
		for (var i=count;i>1;i--)
		{
		try
		  {
			curr_map.DeleteShapeLayer(curr_map.GetShapeLayerByIndex(i));
		  } catch(err) {}
		}
    }
    
    function calcGas(route)
    {
		var miles_per_gallon = 20;
		var exist_print = $( 'div.print_d_button' );
		if( exist_print.length > 0 )
		{
			$( 'div.print_d_button' ).remove();
		}
		$('#'+curr_map.ID.toString()).find('#MSVE_navAction_topBar').append('<div class="print_d_button"><a href="#" class="greybox">Print Directions</a></div>');
		onGotRoute(route);
		/*$( 'div.print_d_button' ).mouseenter(
			function()
			{
				$( this ).animate( { 'opacity': 0.9 }, 200 );
			}
		);
		$( 'div.print_d_button' ).mouseleave(
			function()
			{
				$( this ).animate( { 'opacity': 0.7 }, 200 );
			}
		);*/
		$("a.greybox").bind('click',
			function()
			{
				var t = this.title || this.innerHTML || this.href;
				GB_show(t,this.href,600,700);
				return false;
			}
		);
		var price_res = route.Distance;
		$('form.trip-calc span.distance').text(price_res.toFixed()+' miles ');
		var gallons = price_res / miles_per_gallon;
		var price = $('form.trip-calc').find('#price').val();
		price = price.replace('$','');
		var result_price = (parseFloat(price) * gallons).toFixed(2);
		result_price = "$" + result_price.toString();      
		$('form.trip-calc').find('#price-result').val(result_price);
    }
    
    function Add_Shape(s_map,s_coord,s_num,s_desc,s_link)
    {
		var shape = new VEShape(VEShapeType.Pushpin, s_coord);
  		shape.SetCustomIcon('<div class="pin_big"><span>'+s_num+'</span></div>');
  		var desc = '<div>'+s_desc+'</div>';
  		if (s_link)
  			desc = '<a href="'+s_link+'">'+s_desc+'</a>';
  		shape.SetDescription(desc);
  
  		var shapeLayer = new VEShapeLayer();
  		s_map.AddShapeLayer(shapeLayer);
  		shapeLayer.AddShape(shape);
	}
    
    function AddShapes()
    {
      var cities_coord = $('div.map-controls div.cities');
      if( cities_coord.length == 0 )
      {
      	cities_coord = $('div.hotels-list div.cities')
      }
      $.each(cities_coord,function(key,val)
      	{
      		curr_coord = new VELatLong($(val).find('input.lat').val(),$(val).find('input.long').val());
      		Add_Shape(curr_map,curr_coord,$(val).find('div.pin').text(),$(val).siblings('a').text());
      		curr_coord = null;  		
      	});
    }
    
    $('form.trip-calc input.trip-submit').live('click',function()
      {
	    RemoveLayers();
        if ($('div.map-controls .active').length != 0)
        {
          var pin_g = $('div.map-controls .active');
          pin_g.removeClass('active');
        }
        if (curr_coord)
        {
        	var locations = Array();
        	var options = new VERouteOptions;
        	locations.push(curr_coord);
        	locations.push(coord[0]);
        	curr_coord = null;
        	options.SetBestMapView = true;
        	options.DrawRoute = true;
        	options.RouteColor = new VEColor(0,0,0,0.7);
        	options.DistanceUnit   = VERouteDistanceUnit.Mile;
        	if ($('div.map-controls').length != 0)
          		options.RouteCallback  = calcGas;
        	curr_map.GetDirections(locations,options);
        }
        else
        {
        	var search_val = $(this).parent().parent().find('input#zip').val();
      		curr_map = map[0];
      		curr_coord = coord[0];
      		curr_map.Find(null,
                 search_val,
                 null,
                 null,
                 null,
                 1,
                 false,
                 false,
                 false,
                 false,
                 Find_ok);
        }
        return false;
    });
    
    $('div.map-controls a').live('click',function()
    {
		RemoveLayers();
		$('form.trip-calc').find('#zip').val($(this).text());
		curr_coord = new VELatLong($(this).parent().find('input.lat').val(),$(this).parent().find('input.long').val());
		$('form.trip-calc input.trip-submit').trigger('click');
		if ($('div.map-controls tr.active').length != 0)
		{
		  	var pin_g = $('div.map-controls tr.active');
		  	pin_g.removeClass('active');
		}
		$(this).parent().parent().addClass('active');
		return false;
    });
    
    $('img.go_btn').live('click',function()
    {
      var search_val = $(this).prev('input').val();
      var map_id = $(this).attr('class').replace('go_btn key_','');
      curr_map = map[map_id];
      curr_coord = coord[map_id];
      curr_map.Find(null,
                 search_val,
                 null,
                 null,
                 null,
                 1,
                 false,
                 false,
                 false,
                 false,
                 Find_ok);
    });
    
    $('.rs_view_map a').live('click',function()
    {
      var parent_li = $(this).parent('li').parent('ul').parent('div').parent('li');
      if ($(parent_li).children('.bing_map_container').is(':visible'))
        {
          $(parent_li).children('.bing_map_container').slideUp('fast');
          $(this).text('View Map');
        }
      else
        {
          $(parent_li).children('.bing_map_container').slideDown('slow');
          $(this).text('Hide Map');
        }
       return false; 
    });



