// JavaScript Document
	var allPins = new Array();

// Onload function when page is initized

	$().ready(function() {
		initVEMap(default_Latitude, default_Longitude, default_ZoomLevel);
		checkURL();
		redefineFunctions();
		if (MLSNum!='')
		{
			$(mapSearchArea).hide();
			$(mapSearchDetailArea).show();
		}        
	});	
	
//********************************************************
// redefine the functions and elements for detail page
//********************************************************
	function resetMap()
	{
		ve_map.SetCenterAndZoom(new VELatLong(default_Latitude,default_Longitude), default_ZoomLevel);
		g_veslPushpin.DeleteAllShapes(allPins[i]);
	}

	function redefineFunctions()
	{
		$('#gobacktoMap').show();
	}

	function setMapSearchLongLat()
	{
		var VELatLongRectangle = ve_map.GetMapView();
		getObj('651180_min').value = VELatLongRectangle.BottomRightLatLong.Latitude;
		getObj('651180_max').value = VELatLongRectangle.TopLeftLatLong.Latitude;
		getObj('651190_min').value = VELatLongRectangle.TopLeftLatLong.Longitude;
		getObj('651190_max').value = VELatLongRectangle.BottomRightLatLong.Longitude;
	}
	
	function handleClear()
	{
		getObj('MapSearchForm').reset();
	}

	function LoadMap(isOpenHouse)
	{
		try
		{
			var tempArr = new Array();
			var i=(isOpenHouse) ? 0 : 1;
			var loopVal = (returnedJSON.length>maxProprtiesShow) ? maxProprtiesShow : returnedJSON.length;

			if (returnedJSON.length>maxProprtiesShow)
				$("#MapTotalResult").html("Properties found: " + returnedJSON.length + " (" + maxProprtiesShow + " shown)." + " Mouse over the pin for details.");
			else $("#MapTotalResult").html("Properties found: " + returnedJSON.length + " . Mouse over the pin for details.");
			for (var i=0; i<loopVal; i++)
			{
				if(returnedJSON[i].Latitude && returnedJSON[i].Latitude != '' && returnedJSON[i].Longitude && returnedJSON[i].Longitude != '' && returnedJSON[i].MLSNum != '')
				{
					/*var pin = new VEPushpin( returnedJSON[i].MLSNum, new VELatLong(returnedJSON[i].Latitude, returnedJSON[i].Longitude), DOCUMENT_ROOT+'/img/Mappin.png', returnedJSON[i].MLSNum, null ); 
					VEPushpin.ShowDetailOnMouseOver = false;            
					VEPushpin.OnMouseOverCallback = PinHover;
					allPins.push(returnedJSON[i].MLSNum);
					ve_map.AddPushpin(pin); */
					var theLatLong = new VELatLong(returnedJSON[i].Latitude, returnedJSON[i].Longitude);
					var pin = new VEShape(VEShapeType.Pushpin, theLatLong);					
					pin.Id = returnedJSON[i].MLSNum;
					pin.SetTitle(returnedJSON[i].MLSNum);
					pin.SetCustomIcon(DOCUMENT_ROOT+'/img/Mappin.png');
					pin.SetDescription(returnedJSON[i].MLSNum);
					tempArr.push(pin);
				}
			}
			g_veslPushpin.AddShape(tempArr);
		}
		catch(e)
		{
			alert(e.description + " in LoadMap");
		}		
	}
	//var AjaxCalls = array();
	function MapFormSubmit()
	{
		$("#MapInstruxLink").html('Click Here To Draw a Square Map Search Area');
		//if (quickSearchMLSNumValidate($('#350110').val()) == false){ return false;}
		try
		{
			var zoomLevel = ve_map.GetZoomLevel();

			if (zoomLevel>=8)
			{
				setMapSearchLongLat();
	
				g_veslPushpin.DeleteAllShapes(allPins[i]);
					
				$("#MapTotalResult").html("<img src='" + DOCUMENT_ROOT + "/img/loadingAnimation.gif'/>&#160;&#160;&#160;&#160;Now Loading...");
				var Params = serializeFormElements();
				var AjaxCall = $.ajax({
				  type: "POST",
				  url: DOCUMENT_ROOT + "/PHP/ProcessMapSearch.php",
				  data: Params,
				  success: function(msg){
					  if (DEBUG) alert(msg);
					  else
					  {
						 $("#MapTotalResult").html(msg);
						 //returnedJSON = msg.parseJSON();
						 returnedJSON = JSON.parse(msg);
						 LoadMap(0);
					  }
				  }
				});
				//AjaxCalls.push(AjaxCall);
			}else alert('Please zoom in closer to use the search function.')
			
		}
		catch(e)
		{
			alert(e.description + " in MapFormSubmit");
		}			  
	}

	function serializeFormElements()
	{
		return $("input[@type=hidden]",$("#MapSearchForm")).serialize() + '&' + $("input[@type=checkbox]",$("#MapSearchForm")).serialize() + '&' + $("input[@type=text]",$("#MapSearchForm")).serialize() + '&'  + $("select",$("#MapSearchForm")).serialize();;
	}
	
	function panToLocation(Long, Lat)
	{
		ve_map.PanToLatLong(new VELatLong(Long, Lat));
		setMapSearchLongLat();
		MapFormSubmit();
	}
	
	//***************************************************
	// From map search page to detail page
	//***************************************************
	function viewDetail(k)
	{
		MLSNum = k;
		$('#PropertyInfo_'+k).hide();
		$('#PFlabel').hide();
		$(mapSearchArea).hide();
		$(mapSearchDetailArea).fadeIn(2000);
		$('#homeinfo').empty();
//		initDetail();
	}
	
	//***************************************************
	// From map search page to detail page
	//***************************************************
	function gotoMapSearch()
	{
		$('#PFlabel').show();
		$(mapSearchArea).fadeIn(2000);
		$(mapSearchDetailArea).hide();
	}
	
	/*****************************************************
	// Driving Direction.
	//****************************************************/
	function GetIndex(MlsNumber){
		for (iDs = 0; iDs < returnedJSON.length; iDs++){
			if (returnedJSON[iDs].MLSNum == MlsNumber)
				return iDs;
		}
	}
	function AddItinerary(MlsNumber){
		var iIndex = GetIndex(MlsNumber);	
		$("#IntineraryOrder").addOption( returnedJSON[iIndex].MLSNum , unescape(returnedJSON[iIndex].PFullAddress) );
		//alert( $("#IntineraryOrder").length);
	}
	function removeDestination(){
		$("#IntineraryOrder").removeOption(/./, true);
	}
	function MoveupItinerary(){
		var oldSelectedValue = $("#IntineraryOrder").selectedValues();
		$("#IntineraryOrder").moveUp( $("#IntineraryOrder").selectedValues());
		$("#IntineraryOrder").selectOptions( oldSelectedValue ,true);
	}
	function MovedownItinerary(){
		var oldSelectedValue = $("#IntineraryOrder").selectedValues();
		$("#IntineraryOrder").moveDown( $("#IntineraryOrder").selectedValues());
		$("#IntineraryOrder").selectOptions( oldSelectedValue ,true);
	}
	function StartDirection()
	{
		if($("#IntineraryOrder").getLength() > 0 && $("#IntineraryOrder").getLength() <20 )
		{
			tb_show('Driving and Directions', DOCUMENT_ROOT+'/POP/DrivingDirection.htm?height=180&amp;width=300');
		} else
		if ($("#IntineraryOrder").getLength() >=20 )
		{
			alert('Maximum 20 properties are in your intinerary to start your driving and directions.');	
		}	
		else{
	    	alert('Please add one or more properties into your intinerary to start your driving and directions.');
		}
	}

	var directionLoaded = true;
	var arrPoints = new Array();	
	function ShowDirections(){
		
		var AddressStart = $('#addressFrom').val();
		if (AddressStart != ''){
/*			$('#DrawingBoxContainer').show();
			$('#DrawingBox').html("Processing your request.<br/>Please wait...");*/
			$("#MapTotalResult").html("<img src='" + DOCUMENT_ROOT + "/img/loadingAnimation.gif'/>&#160;&#160;&#160;&#160;Now Loading...");
			var options = new VERouteOptions();
			options.RouteCallback = Directions_OnLoad;
		
	

//			var arrAddress = $("#IntineraryOrder").allText();

			arrPoints.push(AddressStart);
			var Destinations = document.getElementById("IntineraryOrder");
			for (iA=0;iA<Destinations.options.length;iA++)
			{
				arrPoints.push(Destinations.options[iA].text);
			}
			directionLoaded = false;
			ve_map.GetDirections(arrPoints, options);
			setTimeout("Directions_StillWorking()", 5000);
			setTimeout("Directions_CheckTimeout()", 10000);
		
		}
	}
	
	
	function Directions_StillWorking(){
		if (!directionLoaded){
			$('#MapTotalResult').html("<img src='" + DOCUMENT_ROOT + "/img/loadingAnimation.gif'/>&#160;&#160;&#160;&#160;We are working on your request. Please wait...");
		}
	}
	
	function Directions_CheckTimeout(){
		if (!directionLoaded){
			$('#MapTotalResult').html("We didn't get to process your request. <a href='javascript:StartDrivingDirections()'>Try Again</a>");
			directionLoaded = true;
		}
	}

	        
	function Directions_OnLoad(route){
		// Unroll route
			DestinationCounter = 1;
		   var legs     = route.RouteLegs;
		   var turns    = "Total distance: " + route.Distance.toFixed(1) + " mi\n";
		   var numTurns = 0;
		   var stops = 1;
		   var leg      = null;
		   var newHtml = '<table width="100%"><tr style="background-color:black; color:white;"><td>Steps</td><td>Turns</td><td>Distance</td></tr>';
		   directionLoaded = true;
		   dataSourceDirections = new Array();
			$('#MapTotalResult').html(turns);
			for(var i = 0; i < legs.length; i++)
			{

			   leg = legs[i];
			   var turn = null;
				  
			   for(var j = 0; j < leg.Itinerary.Items.length; j ++)
			   {
				  
				  turn = leg.Itinerary.Items[j];
				  dataSourceDirections.push({Step: turn.Text, Distance: turn.Distance.toFixed(1)});	  
				  newHtml += '<tr>';
				  if (numTurns == 0)
				  {
			        newHtml += '<td>Start</td>';					  
				  newHtml += '<td>' + turn.Text+'</td>';					
				  } else
				  if (turn.Text == 'Arrive')
				  {
			        newHtml += '<td>Stop '+ stops++ + '</td>';					  					  
				    newHtml += '<td>' + turn.Text+' ' + arrPoints[DestinationCounter++] + '</td>';										
				  } else				  
				  {
					newHtml += '<td>' + (numTurns) + '</td>';
				    newHtml += '<td>' + turn.Text+'</td>';					
				  }
				  newHtml += '<td>' + turn.Distance.toFixed(1) + 'mi</td>';
				  newHtml += '</tr>';
				  numTurns++;
			   }
			}
			newHtml += '</table>';
			$('#DrivingDirection').html(newHtml);
			$('#DrivingDirection').show();
			//$('#DrawingBoxContainer').hide();
	}      