var map;

function GetMap(lat,lng,divId,zoom)
{
	if (document.getElementById(divId)) {
		if (GBrowserIsCompatible()) {
			
			map = new GMap2(document.getElementById(divId));
			map.addControl(new GSmallMapControl());
			map.addControl(new GScaleControl());
			map.setCenter(new GLatLng(lat, lng), zoom);
		}
	}
}


function load_google_map(latitude,longitude,type,divId,zoom) {
	if (document.getElementById(divId)) {
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById(divId));
			map.addControl(new GSmallMapControl());
			map.addControl(new GScaleControl());
			map.setCenter(new GLatLng(latitude, longitude), zoom);

			if (type=="a")
			{
				map.setMapType(G_SATELLITE_MAP);
			}

			var marker = new GMarker(map.getCenter(), getIcon());
			map.addOverlay(marker);

			GEvent.addListener(marker, "click", function() {
				map.setCenter(new GLatLng(latitude, longitude), (map.getZoom()+1))
			});

		}
	}
}

function GetIndividualMap(lat,lng,type,divId)
{
	load_google_map(lat,lng,type,divId,13)
}

function GetMillsoppsOfficesMap(divId)
{
	GetMap("52.87","0.8","contact-us-map",9)

	var point = new GLatLng("52.906441","1.089728");
	var marker = new GMarker(point, getIcon());
	map.addOverlay(marker);

	var point = new GLatLng("52.754652","0.394030");
	var marker = new GMarker(point, getIcon());
	map.addOverlay(marker);

	var point = new GLatLng("52.93063","1.302065");
	var marker = new GMarker(point, getIcon());
	map.addOverlay(marker);
}


/*
 * 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);
}

String.prototype.replaceAll = function(strTarget,strSubString){
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );

	while (intIndexOfMatch != -1){
		strText = strText.replace( strTarget, strSubString )
		intIndexOfMatch = strText.indexOf( strTarget );
	}
	
	return( strText );
}


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=1;
	} else if (zoomLevel < 13) {
		maxDistance=0.8;
	} else if (zoomLevel < 14) {
		maxDistance=0.7;
	} else if (zoomLevel < 15) {
		maxDistance=0.5;
	} else if (zoomLevel < 16) {
		maxDistance=0.1;
	} else if (zoomLevel > 15) {
		maxDistance=0.0001;
	}

//			alert('zoom level is:' + zoomLevel + ' and maxDistance is' + maxDistance);
	
	var markerCounter=0;
	var markersArray=new Array();
	markersArray.length=0;
	propertiesArrayCopy = propertiesArray;
	for ( var i=0, len=propertiesArrayCopy.length-1; i<len; ++i ){
		if(propertiesArray[i][2]==false)
		{
			var propertiesWithinRange = 0;
			var totalLat = 0;
			var totalLong = 0;
			var queryString = "";
			var totalDistance = 0;
			var latMin = 999;
			var latMax = -999;
			var lngMin = 999;
			var lngMax = -999;
			for ( var i2=0, len2=propertiesArray.length-1; 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] + '&';
						totalDistance += distance;
						if(propertiesArray[i2][0]<latMin) latMin = propertiesArray[i2][0];
						if(propertiesArray[i2][0]>latMax) latMax = propertiesArray[i2][0];
						if(propertiesArray[i2][1]<lngMin) lngMin = propertiesArray[i2][1];
						if(propertiesArray[i2][1]>lngMax) lngMax = propertiesArray[i2][1];
					}
				}
			}
			propertiesArray[i][2] = true;
			markersArray[markerCounter] =new Array();
			markersArray[markerCounter][0]=totalLat;
			markersArray[markerCounter][1]=totalLong;
			markersArray[markerCounter][2]=propertiesWithinRange;
			markersArray[markerCounter][3]=queryString;
			markersArray[markerCounter][4]=totalDistance;
			markersArray[markerCounter][5]=latMin;
			markersArray[markerCounter][6]=latMax;
			markersArray[markerCounter][7]=lngMin;
			markersArray[markerCounter][8]=lngMax;

//					alert('creating markerCounter:' + markerCounter + ' propertiesWithinRange is:' + propertiesWithinRange);
			markerCounter++;
		}
	}
//console.log(markersArray);
//console.log("creating markers");

	return markersArray;

}

var gmarkers = [];

function createMarker(point,number,queryString,map,i,rentalorsale)
{
	if (number>1)
	{
		var marker = new GMarker(point,getMutipleIcon());
	} else {
		var marker = new GMarker(point,getIcon());
	}

	GEvent.addListener(marker, "mouseover", function() {
		gPoint = map.fromLatLngToDivPixel(point);
		gPoint2 = map.fromLatLngToDivPixel(map.getCenter());
		displayLabel (gPoint.x+(175-gPoint2.x),gPoint.y+(225-gPoint2.y),i);
	});

	GEvent.addListener(marker, "mouseout", function() {
		hideLabel();
	});

	GEvent.addListener(marker, "click", function() {
		display('ajaxheading','Properties');
		xmlhttpPost('/content/mapsearchproperty.php',queryString+'markerid='+i+'&rentalorsale='+rentalorsale);
	});

	GEvent.addListener(marker, "dblclick", function() {
		map.setCenter(point, (map.getZoom()+1))
	});


	gmarkers[i] = marker;
	return marker;
}

function createHomePageMarker(point,number,queryString,map,i,rentalorsale)
{

//console.log("number of props:"+markersArray[i][2]+ " total distance:"+markersArray[i][4]);

	//action for mutliple icon button
	if((markersArray[i][2]>1) && (markersArray[i][4]==0))
	{
		var marker = new GMarker(point,getIcon());
		GEvent.addListener(marker, "click", function() {
			hideLabel();
		});

		GEvent.addListener(marker, "mouseover", function() {
			hideLabel();
			$.getJSON('/content/quickpropertymultiple.php?',queryString+'markerid='+i, function(json) {
				infoWindowHtml = json;
//				marker.openInfoWindowHtml(json);
				gPoint = map.fromLatLngToDivPixel(point);
				gPoint2 = map.fromLatLngToDivPixel(map.getCenter());
				displayHomePageProperty(gPoint.x+(175-gPoint2.x),gPoint.y+(225-gPoint2.y),infoWindowHtml,true);
			});
//			console.log('/content/quickpropertymultiple.php?',queryString+'markerid='+i+'&callback=?');
		});
	}
	else if (markersArray[i][2]>1)
	{
		var marker = new GMarker(point,getMutipleIcon());
		GEvent.addListener(marker, "click", function() {
			var bounds = new GLatLngBounds; 
			bounds.extend(new GLatLng( markersArray[i][5], markersArray[i][7] )); 
			bounds.extend(new GLatLng( markersArray[i][6], markersArray[i][8] )); 
			map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			hideLabel();
//console.log("Zooming in number of props:"+markersArray[i][2]+ " total distance:"+markersArray[i][4]);
//console.log("querystring:"+markersArray[i][3])
//console.log("markersArray:"+markersArray.length)
//console.log("i:"+i)
		});

		GEvent.addListener(marker, "mouseover", function() {
			hideLabel();
			gPoint = map.fromLatLngToDivPixel(point);
			gPoint2 = map.fromLatLngToDivPixel(map.getCenter());
			displayHomePageLabel (gPoint.x+(175-gPoint2.x),gPoint.y+(225-gPoint2.y),i);
		});

		GEvent.addListener(marker, "mouseout", function() {
			hideLabel();
		});

	} else {
		var marker = new GMarker(point,getIcon());
		GEvent.addListener(marker, "click", function() {
			var url = queryString;
			updatedUrl = url.replaceAll("property[1]=","");
			updatedUrl = updatedUrl.replaceAll("&","");
			updatedUrl = "/properties/"+updatedUrl+".htm";
			hideLabel();
			window.location = updatedUrl;
		});

		GEvent.addListener(marker, "mouseover", function() {
			hideLabel();
			$.getJSON('/content/quickproperty.php?',queryString+'markerid='+i, function(json) {
				infoWindowHtml = json;
//				marker.openInfoWindowHtml(json);
				gPoint = map.fromLatLngToDivPixel(point);
				gPoint2 = map.fromLatLngToDivPixel(map.getCenter());
				displayHomePageProperty(gPoint.x+(175-gPoint2.x),gPoint.y+(225-gPoint2.y),infoWindowHtml,false);
			});

//			displayHomePageProperty(gPoint.x+(175-gPoint2.x),gPoint.y+(225-gPoint2.y),getPropertyQuickData(markersArray[i][5]));
		});
/*
		GEvent.addListener(marker, "mouseout", function() {
			hideLabel();
		});
*/

	}



	GEvent.addListener(marker, "dblclick", function() {
		map.setCenter(point, (map.getZoom()+1))
	});


	gmarkers[i] = marker;
	return marker;
}

/*
function getPropertyQuickData(id)
{
	for ( var i=0, len=propertiesQuickData.length-1; i<len; ++i ){
		if(propertiesQuickData[i][0]==id)
		{
			return propertiesQuickData[i][1];
			alert('FOUND');
		}
		console.log('I:'+i+' '+propertiesQuickData[i][0]);
	}

	return "";
}
*/


function createSimpleMarker(point,number,queryString,map,i)
{
	var marker = new GMarker(point,getIcon());
	return marker;
}

function createStandardMarker(point,number,queryString,map,i)
{
	var marker = new GMarker(point);
	return marker;
}


function hideLabel()
{
	if ( $("#label").length > 0 ) {
		$("#label").css("visibility","hidden");
	}
	if ( $("#propertyLabel").length > 0 ) {
		$("#propertyLabel").css("visibility","hidden");
	}
}


function zoomInToMap(i)
{
	GEvent.trigger(gmarkers[i],"dblclick");
}


function numberOfPropertiesDisplayed(bounds,propertiesArray)
{
	var propertiesUsedCounter = 0;
	var selected = false;
	for ( var i=0, len=propertiesArray.length-1; i<len; ++i ){
		propertyShown = false;
		if ((propertiesArray[i][0]>bounds.getSouthWest().lat()) && (propertiesArray[i][0]<bounds.getNorthEast().lat())) {
			if ((propertiesArray[i][1]>bounds.getSouthWest().lng()) && (propertiesArray[i][1]<bounds.getNorthEast().lng())) {
				propertyShown = true;
			} else {
				//alert('property outside, lat < ' + bounds.getSouthWest().lng() + ' [ ' + propertiesArray[i][1] + ' ] ' + bounds.getNorthEast().lng() + ' > ');
			}
		} else {
			//alert('property outside, lat < ' + bounds.getSouthWest().lat() + ' [ ' + propertiesArray[i][0] + ' ] ' + bounds.getNorthEast().lat() + ' > ');
		}
		if (propertyShown == true) {
			propertiesUsedCounter++;
		}
	}
//			alert('propertiesUsedCounter is:' + propertiesUsedCounter);

	return propertiesUsedCounter;
}


function getIcon()
{
	var icon = new GIcon();
	icon.image = "/images/board.png";
	icon.iconSize = new GSize(31, 23);
	icon.iconAnchor = new GPoint(21, 23);
	icon.shadow = "/images/boardshadow.png";
	icon.shadowSize = new GSize(31, 23);
	icon.infoWindowAnchor = new GPoint(20, 27);
	return icon;
}


function getMutipleIcon()
{
	var icon = new GIcon();
	icon.image = "/images/boardmultiple.png";
	icon.iconSize = new GSize(35, 28);
	icon.iconAnchor = new GPoint(21, 28);
	icon.shadow = "/images/boardshadowmultiple.png";
	icon.shadowSize = new GSize(35, 28);
	return icon;
}

function displayLabel(x,y,id)
{
	var xposition = x - 45;
	var yposition = y - 60;

	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 displayHomePageLabel(x,y,id)
{
	var xposition = x + 25;
	var yposition = y - 95;

	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','click to zoom in on ' + markersArray[id][2] + ' properties');
		the_style.visibility = "visible";
	}
}

function displayHomePageProperty(x,y,content,multiple)
{
	var xposition = x-20;
	var yposition = y-150;

	if(multiple==true)
	{
		$("#propertyLabel").css("height","87px");
		yposition = yposition -25;
	} else {
		$("#propertyLabel").css("height","70px");
	}

	var the_style = getStyleObject("propertyLabel");
	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";
		}

		$("#propertyLabel").html(content);
		the_style.visibility = "visible";

	}
}

function multipleClick(url)
{
	$.getJSON(url, function(json) {
		$("#propertyLabel").html(json);
	});
}