var myPano;
var address;
var camera;
var degreesPerRadian = 180.0 / Math.PI;
var radiansPerDegree = Math.PI / 180.0;
// Returns the bearing in degrees between two points.
// North = 0, East = 90, South = 180, West = 270.
function bearing( from, to ) {
    // See T. Vincenty, Survey Review, 23, No 176, p 88-93,1975.
    // Convert to radians.
    var lat1 = from.latRadians();
    var lon1 = from.lngRadians();
    var lat2 = to.latRadians();
    var lon2 = to.lngRadians();
    // Compute the angle.
    var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ),
        Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * 
        Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
    if ( angle < 0.0 ) angle += Math.PI * 2.0;
    // And convert result to degrees.
    angle = angle * degreesPerRadian;
    angle = angle.toFixed(1);
    return angle;
}
function initialize(lat, lon) 
{
    address = new GLatLng(lat, lon);
    new GStreetviewClient().getNearestPanoramaLatLng(address, CameraLocation);
}
function CameraLocation(result)
{
    if(result)
    {
        camera = result;
        ShowStreetView();
    }
    else 
    {
    	jQuery("#streetViewLink").unbind().addClass("fadeOut").attr("title","Unavailable|Street View is not available for this property.").cluetip({splitTitle: '|'});
    	//alert('There is no street view for this location');        	
    }
}
function ShowStreetView()
{
    var panoramaOptions = { latlng:address, pov:{ yaw:bearing(camera,address) } };
    myPano = new GStreetviewPanorama(document.getElementById("pano"), panoramaOptions);
    GEvent.addListener(myPano, "error", handleNoFlash);
}
function handleNoFlash(errorCode) {
  if (errorCode == FLASH_UNAVAILABLE) {
    alert("Error: Flash doesn't appear to be supported by your browser");
    return;
  }
}  

var nBoundary = null;
var nBoundaryPoints = new Array();
var schoolInfo = new Array();
var soldInfo = new Array();
var route = null;
var overLay = document.createElement("div");
var overviewMap = null;		
var interactiveMap = null;
var iproperty = null;
var soldLoaded = false; 
overLay.id = "mapOverlay";
overLay.style.margin = "0px";
overLay.style.padding = "0px";										
overLay.style.backgroundColor = "white";
overLay.style.filter = "Alpha(Opacity=50)";
overLay.style.MozOpacity = "0.5";
overLay.style.height = "440px";
overLay.style.width = "600px";									
overLay.innerHTML = "<div style=\"margin-top:220px;z-index:2;\"><img src='/HomesCom/Images/busy.gif'/> Loading...</div>";					
overLay.style.position = "absolute";
overLay.style.top = "230px";
overLay.style.left = "153px";
function getNBoundary()
{	
	if (!iproperty)
	{
		jQuery("input[name=localInfo]").removeAttr("disabled");
		return;
	}		
	jQuery("#dDirectionsForm").slideUp();
	interactiveMap.DeleteRoute();
	removeSchoolPins();
	removeSoldPins();
	if (nBoundary)
	{
		nBoundary.Show();
		interactiveMap.SetMapView(nBoundaryPoints);
	}
	else
	{
		jQuery("#mapOverlay").show();
		jQuery("input[name=localInfo]").attr("disabled","disabled");
		var myurl = "/HomesCom/Include/ListingDetail/Map/ajaxNBoundary.cfm";
		var modurl = "latitude=" + iproperty.Latitude + "&longitude=" + iproperty.Longitude;
		
		jQuery.ajax({
			url: myurl,
			data: modurl,
			type: "GET",
			success: function(msg)
			{
				var aResp = msg.split("||");
				if (aResp[0] == 1)
				{
					var longLatList = aResp[1].split(",");
					for (i=0;i<longLatList.length;i++)
					{
						var longLat = longLatList[i].split(" ");
						nBoundaryPoints.push(new VELatLong(longLat[1],longLat[0]));					
					}
					nBoundary = new VEShape(VEShapeType.Polygon,nBoundaryPoints);
					nBoundary.SetLineWidth(2);
					nBoundary.SetLineColor(new VEColor(0,150,100,1.0));
			        nBoundary.SetFillColor(new VEColor(60,179,113,0.75));		        
			        iproperty.SetDescription(aResp[2]);
			        interactiveMap.ShowInfoBox(iproperty);
			        nBoundary.HideIcon();
					interactiveMap.AddShape(nBoundary);
					interactiveMap.SetMapView(nBoundaryPoints);
				
				}
				else
				{
					iproperty.SetDescription(aResp[1]);
				}		
				jQuery("#mapOverlay").hide();
				jQuery("input[name=localInfo]").removeAttr("disabled");
			},
			error: function(msg)
			{
				
			}
		});	
	}	 
}
function getSoldHomes()
{		
		
	interactiveMap.DeleteRoute();
	if (nBoundary)
		nBoundary.Hide();
	removeSchoolPins();	
	jQuery("#streetView").hide();	
	jQuery("#interactiveMap").show();
	jQuery("#prOverview").hide();
	jQuery("#forSale").hide();
	jQuery("#recentlySold").show();
	jQuery("#nearbyHomes").hide();
	jQuery("#schools").hide();
	jQuery(".on").removeClass("on");
	jQuery("#recentlySoldLink").addClass("on");
	jQuery("#interactiveMapLink").addClass("on");
	if (!soldLoaded)
	{
		jQuery("#mapOverlay").show();
		jQuery("input[name=localInfo]").attr("disabled","disabled");
		jQuery("#dDirectionsForm").slideUp();
		var pointArr = new Array();
		var myurl = "/HomesCom/Include/ListingDetail/Map/ajaxSoldHomes.cfm";
		var modurl = "latitude=" + iproperty.Latitude + "&longitude=" + iproperty.Longitude;
		jQuery.ajax({
			url: myurl,
			data: modurl,
			type: "GET",
			success: function(msg)
			{
				var aResp = msg.split("||");
				if (aResp[0] == 1)
				{
					jQuery("#recentlySold").html(aResp[1]);
					var latLongList = aResp[2].split("--");
					for (i=0;i<latLongList.length;i++)
					{					
						var holder = latLongList[i].split("*");
						var pointHolder = new VELatLong(parseFloat(holder[0]),parseFloat(holder[1]));
						pointArr.push(pointHolder);					
						soldInfo[i] = interactiveMap.AddPushpin(pointHolder);
						soldInfo[i].SetTitle("");
						soldInfo[i].SetDescription(holder[2])
						
					}
					interactiveMap.SetMapView(pointArr);				
				}		
				jQuery("#mapOverlay").hide();
				jQuery("input[name=localInfo]").removeAttr("disabled");
				soldLoaded = true;
			},
			error: function(msg)
			{
				
			}
		});	
	}
	else
	{	
		var a = new Array();	
		for (var j=0;j<soldInfo.length;j++)
		{
			soldInfo[j].Show();
			var pointHolder = new VELatLong(soldInfo[j].Latitude,soldInfo[j].Longitude);
			a.push(pointHolder);			
		}
		interactiveMap.SetMapView(a);
	}
}
function getSchools()
{	
	
	jQuery("#streetView").hide();	
	jQuery("#interactiveMap").show();
	jQuery("#prOverview").hide();
	jQuery("#forSale").hide();
	jQuery("#recentlySold").hide();
	jQuery("#nearbyHomes").hide();
	jQuery("#schools").show();
	jQuery(".on").removeClass("on");
	jQuery("#schoolsLink").addClass("on");
	jQuery("#interactiveMapLink").addClass("on");
	jQuery("#mapOverlay").show();
	jQuery("input[name=localInfo]").attr("disabled","disabled");
	var pointArr = new Array();
	jQuery("#dDirectionsForm").slideUp();
	interactiveMap.DeleteRoute();
	if (nBoundary)
		nBoundary.Hide();
	/*for (j=0;j<schoolInfo.length;j++)
	{
		map.DeleteShape(schoolInfo[j]);
	}*/	
	removeSoldPins();
	var myurl = "/HomesCom/Include/ListingDetail/Map/ajaxNSchools.cfm";
	var modurl = "latitude=" + iproperty.Latitude + "&longitude=" + iproperty.Longitude;
	
	if (jQuery("#schoolRadiusSearch"))
		radius = jQuery("#schoolRadiusSearch").val();
	else
		radius = 10;
	modurl += "&radius=" + radius;
	if (jQuery("#schoolTypeSearch"))
		schoolType = jQuery("#schoolTypeSearch").val();
	else
		schoolType = "ALL";
	modurl += "&schoolType=" + schoolType;
	jQuery.ajax({
			url: myurl,
			data: modurl,
			type: "GET",
			success: function(msg)
			{
				var aResp = msg.split("||");
				if (aResp[0] == 1)
				{
					jQuery("#schools").html(aResp[1]);
				}
				var latLongList = aResp[2].split("--");
				for (i=0;i<latLongList.length;i++)
				{					
					var holder = latLongList[i].split(",");
					var pointHolder = new VELatLong(parseFloat(holder[0]),parseFloat(holder[1]));
					var letter = String.fromCharCode("A".charCodeAt(0) + parseInt(i));
					pointArr.push(pointHolder);
					if (i > 8)
						var imageSTR = "/Images/map/pin-school.png";
					else
						var imageSTR = "/Images/map/pin-school" + letter + ".png";
					
					schoolInfo[i] = interactiveMap.AddPushpin(pointHolder);
					schoolInfo[i].SetCustomIcon(imageSTR);
					schoolInfo[i].SetTitle("");
					schoolInfo[i].SetDescription(holder[2])
				}
				interactiveMap.SetMapView(pointArr);
				jQuery("#mapOverlay").hide();
				jQuery("input[name=localInfo]").removeAttr("disabled");						
			},
			error: function(msg)
			{
				
			}
		});		
}
function getDirections()
{	
	jQuery("#mapOverlay").show();
	jQuery("input[name=localInfo]").attr("disabled","disabled");
	locations = new Array(jQuery("#startAddress").val(),jQuery("#endAddress").val());
	var options = new VERouteOptions;
	options.DrawRoute = true;
	options.SetBestMapView = true;
	options.RouteCallback  = ShowTurns;
	options.DistanceUnit = VERouteDistanceUnit.Mile;
	options.ShowDisambiguation = true;
	interactiveMap.GetDirections(locations,options);	
}
function ShowTurns(route)
{
    var turns ="<Br/>";
    turns +="<a href='' id='printDirectionLink' onclick='return getPrintDirections()' target='_blank'>Printable Version<a/>";
	turns += '<table style="margin: 10px 0 0 0;" cellspacing="0" id="mapListingsTable">';
	turns += '<colgroup>';
	turns += '<col id="direction" /><col id="distance" />';
	turns += '</colgroup>';
	turns += '<thead>';
	turns += '<tr><th scope="col">Direction</th><th scope="col">Distance</th></tr>';
	turn += '</thead>';
	turns += '<tbody>';
     
	var legs          = route.RouteLegs;     
	var leg           = null;
	var turnNum       = 0;  // The turn #
	// 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
		var legNum = i + 1;
		turns += "<tr><td colspan='2'>Distance for leg " + legNum + ":</b> " + leg.Distance.toFixed(1) + " miles" +
		"<br/><b>Time for leg "     + legNum + ":</b> " + GetTime(leg.Time) + "<br/><br/></td></tr>";
		
		// 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 ++)
		{
			turnNum++;             
			turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object
			turns += "<tr><td><b>" + turnNum + "</b>\t" + turn.Text + "</td>";
			legDistance    = turn.Distance;
			// So we don't show 0.0 for the arrival
			if(legDistance > 0)
			{
				// Round distances to 1/10ths
				turns += "<td>" + legDistance.toFixed(1) + " miles";
				// Append time if found
				if(turn.Time != null)
				{
					turns += "; " + GetTime(turn.Time);
				}
				turns += ")</td>";
			}
			else
			{
				turns += "<td></td>"
			}
			turns +="</tr>";
		}
		turns += '</tbody></table><div class="divider"></div>';
	}   
	jQuery("#directionDetails").html(turns);
	jQuery("#mapOverlay").hide();
	jQuery("input[name=localInfo]").removeAttr("disabled");
}
function showDirections()
{
	jQuery("#dDirectionsForm").slideDown();
	removeSchoolPins();
	removeSoldPins();
	if (nBoundary)
		nBoundary.Hide();
}
function removeSchoolPins()
{		
	for (j=0;j<schoolInfo.length;j++)
	{
		interactiveMap.DeleteShape(schoolInfo[j]);
	}
}
function removeSoldPins()
{	
	for (j=0;j<soldInfo.length;j++)
	{
		soldInfo[j].Hide();
	}
}
 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");
    }
 }
function getPrintDirections()
{
	var link = "/HomesCom/Include/ListingDetail/Map/PrintDirections.cfm?";
	link += "startAddress=" + escape(jQuery("#startAddress").val()) + "&endAddress=" + escape(jQuery("#endAddress").val());
	jQuery("#printDirectionLink").attr("href",link);
	return true;
}
    