var map = null;
var pinID = 1;
var rentalorsale;

function GetMap(lat,lng,zoom,divId)
{
// The following 7 lines of code courtesy of Marc Sutton, found on the MSDN Virtual Earth: Map Control Development forum...
	var ffv = 0;
	var ffn = "Firefox/"
	var ffp = navigator.userAgent.indexOf(ffn);
	if (ffp != -1) ffv = parseFloat(navigator.userAgent.substring(ffp + ffn.length));
	if (ffv >= 1.5) { // If we're using Firefox 1.5 or above override the Virtual Earth drawing functions to use SVG
		Msn.Drawing.Graphic.CreateGraphic=function(f,b) { return new Msn.Drawing.SVGGraphic(f,b) }
	}
		map = new VEMap(divId);
	try {
		map.LoadMap(new VELatLong(lat, lng), zoom ,'r' ,false,VEMapMode.Mode2D);
	} catch(e){
		//alert(e)
	}
}

function GetIndividualMap(lat,lng,type,divId)
{
	GetMap(lat,lng,15,divId)
	if (type=="a")
	{
		map.SetMapStyle(VEMapStyle.Aerial);
	}

	AddHomePagePin(lat,lng);
}

function GetMillsoppsMap(lat,lng,type,divId)
{

	GetMap(lat,lng,12,divId)
	if (type=="a")
	{
		map.SetMapStyle(VEMapStyle.Aerial);
	}
	map.HideDashboard();
	AddHomePagePin(lat,lng);
}

function GetMillsoppsOfficesMap(divId)
{
	GetMap('52.906441','0.8',8,divId)
	map.HideDashboard();
	AddHomePagePin('52.906441','1.089728');
	AddHomePagePin('52.754652','0.394030');
	AddHomePagePin('52.93063','1.302065');
}




function AddHomePagePin(lat,lng)
{
	var pin = new VEPushpin(pinID, new VELatLong(lat,lng), '/images/board.gif','Pin', 'Pin' + pinID);
	VEPushpin.ShowDetailOnMouseOver = false;
	map.AddPushpin(pin);
	pinID++;
}

function onMapClick()
{
	location.href='/search/map-search.htm?rentalorsale=sale';
}



/*
 * Calculate distance (in km) between two points specified by latitude/longitude with Haversine formula
 *
 */
function distHaversine(p1, p2) {
	var R = 6371; // earth's mean radius in km
	var dLat  = p2.lat - p1.lat;
	var dLong = p2.lon - p1.lon;

	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		  Math.cos(p1.lat) * Math.cos(p2.lat) * Math.sin(dLong/2) * Math.sin(dLong/2);
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	var d = R * c;

	return d;
}

/*
 * ditto using law of cosines.
 */
function distCosineLaw(p1, p2) {
	var R = 6371; // earth's mean radius in km
	var d = Math.acos(Math.sin(p1.lat)*Math.sin(p2.lat) +
					Math.cos(p1.lat)*Math.cos(p2.lat)*Math.cos(p2.lon-p1.lon)) * R;
	return d;
}

function llToRad(llDeg) {
	if (!isNaN(llDeg)) return llDeg * Math.PI / 180;  // signed decimal degrees without NSEW

	llDeg = llDeg.replace(/[\s]*$/,'');               // strip trailing whitespace
	var dir = llDeg.slice(-1).toUpperCase();          // compass dir'n
	if (!/[NSEW]/.test(dir)) return NaN;              // check for correct compass direction
	llDeg = llDeg.slice(0,-1);                        // and lose it off the end
	var dms = llDeg.split(/[\s:,°º'\'?\"]/);          // check for separators indicating d/m/s
	if (dms[dms.length-1] == '') dms.length--;        // trailing separator? (see note below)
	switch (dms.length) {                             // convert to decimal degrees...
		case 3:                                         // interpret 3-part result as d/m/s
			var deg = dms[0]/1 + dms[1]/60 + dms[2]/3600; break;
		case 2:                                         // interpret 2-part result as d/m
			var deg = dms[0]/1 + dms[1]/60; break;
		case 1:                                         // non-separated format dddmmss
			if (/[NS]/.test(dir)) llDeg = '0' + llDeg;    // - normalise N/S to 3-digit degrees
			var deg = llDeg.slice(0,3)/1 + llDeg.slice(3,5)/60 + llDeg.slice(5)/3600; break;
		default: return NaN;
	}
	if (/[WS]/.test(dir)) deg = -deg;                 // take west and south as -ve
	return deg * Math.PI / 180;                       // then convert to radians
}



/*
 * LatLong constructor:
 */
function LatLong(degLat, degLong) {
	this.lat = llToRad(degLat);
	this.lon = llToRad(degLong);
}


function generateMarkers(propertiesArray,zoomLevel)
{
	for ( var i=0, len=propertiesArray.length-1; i<len; ++i ){
		propertiesArray[i][2] = false;
	}
	
	var maxDistance;

	if (zoomLevel < 6) {
		maxDistance=100;
	} else if (zoomLevel < 7) {
		maxDistance=50;
	} else if (zoomLevel < 8) {
		maxDistance=20;
	} else if (zoomLevel < 9) {
		maxDistance=10;
	} else if (zoomLevel < 11) {
		maxDistance=5;
	} else if (zoomLevel < 12) {
		maxDistance=2;
	} else if (zoomLevel < 13) {
		maxDistance=0.7;
	} else if (zoomLevel < 14) {
		maxDistance=0.6;
	} else if (zoomLevel < 15) {
		maxDistance=0.4;
	} else if (zoomLevel < 16) {
		maxDistance=0.1;
	} else if (zoomLevel > 15) {
		maxDistance=0.01;
	}
//	alert('zoom level is:' + zoomLevel + ' and maxDistance is' + maxDistance);
	
	var markerCounter=1;
	var markersArray=new Array();
	markersArray.length=0;
	propertiesArrayCopy = propertiesArray;
	for ( var i=0, len=propertiesArrayCopy.length; i<len; ++i ){
		if(propertiesArray[i][2]==false)
		{
			var propertiesWithinRange = 0;
			var totalLat = 0;
			var totalLong = 0;
			var queryString = "";
			for ( var i2=0, len2=propertiesArray.length; i2<len2; ++i2 ){
				if(propertiesArray[i2][2]==false)
				{
					var distance = distCosineLaw(new LatLong(propertiesArray[i][0], propertiesArray[i][1]),new LatLong(propertiesArray[i2][0], propertiesArray[i2][1]));
					if (distance < maxDistance)
					{
						propertiesArray[i2][2] = true;
						propertiesWithinRange++;
						totalLat += propertiesArray[i2][0];
						totalLong += propertiesArray[i2][1];
						queryString += 'property[' + propertiesWithinRange + ']=' + propertiesArray[i2][3] + '&';
					}
				}
			}

			propertiesArray[i][2] = true;
			markersArray[markerCounter] =new Array();
			markersArray[markerCounter][0]=totalLat;
			markersArray[markerCounter][1]=totalLong;
			markersArray[markerCounter][2]=propertiesWithinRange;
			markersArray[markerCounter][3]=queryString;
//			alert('creating markerCounter:' + markerCounter + ' propertiesWithinRange is:' + propertiesWithinRange);
			markerCounter++;
		}
	}

	return markersArray;
}


function PinHover(x, y, id, details)
{
	displayLabel(x, y, id);
	displayButton(x, y, id);
}

function createMarkers(rentalorsearch)
{
	for ( var i=1, len=markersArray.length; i<len; ++i )
	{
		var imageUrl = '/images/board.gif';
		if ((markersArray[i][0]!="") && (markersArray[i][1]!="") && (markersArray[i][2]!=""))
		{

			if (markersArray[i][2]>1)
			{
				imageUrl = '/images/boardmultiple.gif';
			}

			point = new VELatLong((markersArray[i][0]/markersArray[i][2]),(markersArray[i][1]/markersArray[i][2]));
			var pin = new VEPushpin(pinID, point, imageUrl, ''+pinID, 'This is pushpin number ' + pinID);
			VEPushpin.ShowDetailOnMouseOver = false;

			VEPushpin.OnMouseOverCallback = PinHover
			map.AddPushpin(pin);
		}

		pinID++;
	}
}


function hideLabelAndButton()
{
	var the_style = getStyleObject("label");
	if (the_style)
	{
		the_style.visibility = "hidden";
	}
	var the_style = getStyleObject("button");
	if (the_style)
	{
		the_style.visibility = "hidden";
	}
}


function displayLabel(x,y,id)
{
	var xposition = x - 475;
	var yposition = y - 300;

	var the_style = getStyleObject("label");
	if (the_style)
	{
		if (document.layers) 
		{
			the_style.left = xposition;
			the_style.top = yposition;
		}
		else 
		{
			the_style.left = xposition + "px";
			the_style.top = yposition + "px";
		}

		display('label','properties: ' + markersArray[id][2]);
		the_style.visibility = "visible";
	}
}		


function displayButton(x,y,id)
{
	var xposition = x -440;
	var yposition = y - 235;
	var url = markersArray[id][3]+'markerid='+id+'&rentalorsale='+rentalorsale;

	var the_style = getStyleObject("button");
	if (the_style)
	{
		if (document.layers) 
		{
			the_style.left = xposition;
			the_style.top = yposition;
		}
		else 
		{
			the_style.left = xposition + "px";
			the_style.top = yposition + "px";
		}
		display('button','<a href=\"#top\" onClick=\"display(\'ajaxheading\',\'Properties\'); xmlhttpPost(\'/content/mapsearchproperty.php\',\''+url+'\');\" onmouseout=\"hideLabelAndButton()\" onClick=\"hideLabelAndButton()\"><img src=\"/images/button.gif\" alt=\"button\" border=\"0\"></a>');
		the_style.visibility = "visible";
	}
}

function zoomInToMap (lat,lng) {
	map.SetCenterAndZoom(new VELatLong(lat, lng), 17);
}