var map;
var xAdjustment = 5;
var yAdjustment = 50;
var defaultZoom = 13;
var baseLat;
var baseLng;
var markerTitle;
var bounds;
var defaultBounds = new Array();
var currentBounds = new Array();
var mapMoveHandler = false;
var showDetails = false;
var jsonUrl = "/json/location/properties.php"; // The server-side script
var imageLoading = "/images/ajax-loader.gif";
var overlayBgColor = '#000';		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
var overlayOpacity = 0.2;		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
var pageLimit = 50;
var sw;
var ne;
var markers = new Array();
var currentMarkerId;
var highlightMarker;
var highlightId;
var message = new Array();
var postMessage = new Array();

// ====== set up marker mouseover tooltip div ======
var tooltip = document.createElement("div");
var titletip = document.createElement("div");
tooltip.style.visibility="hidden";

function loadTabbedMap(currentBlock){
	if (document.getElementById('map'))
	{
		if (GBrowserIsCompatible()) {
			markers = new Array();
			currentMarkerId = null;
			highlightMarker = null;
			highlightId = null;

			map = new GMap2(document.getElementById("map"));
			map.addControl(new GSmallMapControl());
			map.setCenter(new GLatLng(0,0),0);

			bounds = new GLatLngBounds();
			switch(currentBlock)
			{
				case "hotel":
				case "cottage":
					for (i=0; i<properties[currentBlock].length; i++)
					{
						if (properties[currentBlock][i].propertyType.propertyTypeName ==currentBlock) markers[i] = createMarker(currentBlock, i, false);
					}

					document.getElementById("map").appendChild(tooltip);
					for (i=0; i<locationList.length; i++)
					{
						createTownMarker(i);
					}

					if(currentBounds[currentBlock]!=undefined) bounds = currentBounds[currentBlock];
					sw = bounds.getSouthWest();
					ne = bounds.getNorthEast();

					if(sw.lng()==180 && ne.lng()==-180){
						map.setCenter(new GLatLng(baseLat,baseLng),0);
						map.setZoom(defaultZoom);
						bounds = map.getBounds();
					}
					else {
						map.setZoom(map.getBoundsZoomLevel(bounds));
						map.setCenter(bounds.getCenter());
					}
					if (defaultBounds[currentBlock]===undefined) defaultBounds[currentBlock] = bounds;

					currentBounds[currentBlock] = bounds;

					doMaxItems();

					mapMoveHandler = GEvent.addListener(map, "moveend", function() {
						updateProperties();
					});
					for (i=0; i<properties[currentBlock].length; i++)
					{
						if ( markers[i]!=null) map.removeOverlay( markers[i]);
						if (properties[currentBlock][i].propertyType.propertyTypeName ==currentBlock) markers[i] = createMarker(currentBlock, i, false);
					}
					break;    
				case "extra":
				case "tourist":
					//hide map....
					break;    
			}
		}
	}
}

function loadSimpleMap(currentBlock){
	if (document.getElementById('map'))
	{
		if (GBrowserIsCompatible()) {
			mapLoaded = true;
			markers = new Array();
			currentMarkerId = null;
			highlightMarker = null;
			highlightId = null;

			map = new GMap2(document.getElementById("map"));
			map.addControl(new GSmallMapControl());
			map.setCenter(new GLatLng(baseLat,baseLng),defaultZoom);

			bounds = map.getBounds();
			currentBounds[currentBlock] = bounds;

			updateProperties();

			mapMoveHandler = GEvent.addListener(map, "moveend", function() {
				updateProperties();
			});
		}
	}
}

function doMaxItems(){
	var maxItems = document.getElementById("maxItems");
	if (maxItems!=null)
	{
		if (properties[currentBlock].length>=50)
		{
			maxItems.innerHTML = "SHOWING MAXIMUM NUMBER OF PROPERTIES. <br/>PLEASE ZOOM IN FOR MORE PROPERTY DETAILS";
			maxItems.style.visibility = "visible";
		}
		else if (properties[currentBlock].length<1)
		{
			maxItems.innerHTML = "NO PROPERTIES FOUND. <br/>PLEASE ZOOM OUT FOR MORE PROPERTY DETAILS";
			maxItems.style.visibility = "visible";
		}
		else {
			maxItems.innerHTML = "";
			maxItems.style.visibility = "hidden";
		}
	}
}

function loadPropertyMap(lat, lng, iconName, name) {
	if (document.getElementById('map'))
	{
		baseLat = lat;
		baseLng = lng;
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("map"));
			map.addControl(new GSmallMapControl());
			map.setCenter(new GLatLng(lat,lng),0);

			map.setZoom(defaultZoom);
			var point = new GLatLng(lat, lng);

			var icon = new GIcon();
			icon.image = '/images/icons/'+iconName+'_small.png';
			icon.iconSize = new GSize(24, 24);
			icon.iconAnchor = new GPoint(12, 12);
			icon.infoWindowAnchor = new GPoint(0, 0);

			opts = { 
			  "icon": icon,
			  "clickable": false
			};
			var marker = new LabeledMarker(point, opts);

			map.addOverlay(marker);
		}
	}
}

function createMarker(arrayType, arrayId, isHighlight)
{
	var point = new GLatLng(properties[arrayType][arrayId].latitude, properties[arrayType][arrayId].longitude);
	bounds.extend(point);

	var imageToUse = '/images/icons/'+properties[arrayType][arrayId].propertyType.propertyTypeName+'.png';
	if (isHighlight) imageToUse = '/images/icons/'+properties[arrayType][arrayId].propertyType.propertyTypeName+'_highlight.png';

	var icon = new GIcon();
	icon.image = imageToUse;
	icon.iconSize = new GSize(41, 24);
	icon.iconAnchor = new GPoint(20, 12);
	icon.infoWindowAnchor = new GPoint(25, 7);

	opts = { 
		  "icon": icon,
		  "clickable": true,
		  "labelText": (arrayId+1),
		  "labelOffset": new GSize(0, -8),
		  "zIndexProcess": orderOfCreation
	};

	function orderOfCreation(marker, b){
		if (isHighlight) return 1000;
		return (marker.importance);
	}

	var marker = new LabeledMarker(point, opts);
	marker.importance = properties[currentBlock].length*5 - arrayId;
	if (isHighlight) marker.importance = 1000;

	GEvent.addListener(marker, "click", function() {
		window.location=properties[arrayType][arrayId].localUrl;
	});

	GEvent.addListener(marker, "mouseover", function() {
		displayLabel (arrayType, arrayId);
	});

	GEvent.addListener(marker, "mouseout", function() {
		hideLabel(arrayType, arrayId);
	});

	map.addOverlay(marker);

	marker.div_.style.zIndex = marker.importance;
	return marker;
}

function createTownMarker(arrayId)
{
	var point = new GLatLng(locationList[arrayId].latitude, locationList[arrayId].longitude);
	bounds.extend(point);

	var icon = new GIcon();
	icon.image = '/images/icons/dot.png';
	icon.iconSize = new GSize(10, 10);
	icon.iconAnchor = new GPoint(0, 0);
	icon.infoWindowAnchor = new GPoint(0, 0);

	opts = { 
	  "icon": icon,
	  "clickable": true,
	  "zIndexProcess": orderOfCreation
	};

	function orderOfCreation(marker, b){
		return (marker.importance);
	}

	var marker = new LabeledMarker(point, opts);
	marker.importance = 750+arrayId;
	
	marker.tooltip = '<div class="tooltip">Click to see properties in '+locationList[arrayId].name+'<\/div>';

	GEvent.addListener(marker, "click", function() {
		window.location=locationList[arrayId].url;
	});

	//  ======  The new marker "mouseover" and "mouseout" listeners  ======
	GEvent.addListener(marker, "mouseover", function() {
		showTooltip(marker);
	});    
	
	GEvent.addListener(marker, "mouseout", function() {
		tooltip.style.visibility="hidden"
	});        

	map.addOverlay(marker);
}

function createTitleMarker()
{
	var point = new GLatLng(baseLat, baseLng);

	var icon = new GIcon();
	icon.image = '/images/icons/dot.png';
	icon.iconSize = new GSize(10, 10);
	icon.iconAnchor = new GPoint(0, 0);
	icon.infoWindowAnchor = new GPoint(0, 0);

	opts = { 
	  "icon": icon,
	  "zIndexProcess": orderOfCreation
	};

	function orderOfCreation(marker, b){
		return (marker.importance);
	}

	var marker = new LabeledMarker(point, opts);
	marker.importance = 1200;
	
	marker.titletip = '<div class="titletip">'+markerTitle+'<\/div>';

	map.addOverlay(marker);

	document.getElementById("map").appendChild(titletip);

	titletip.innerHTML = marker.titletip;

	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(320, 320)); 
	pos.apply(titletip);
	var width = titletip.offsetWidth/2;
	var xoffset = offset.x - point.x - width
	if (xoffset<0) xoffset = 0;
	if (offset.x - point.x + width > 500)
	{
		xoffset = 500-width;
	}
	var yoffset = - offset.y + point.y;
	if (yoffset>300) yoffset = yoffset - 50;
	else yoffset = yoffset+10;

	pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(xoffset, yoffset)); 
	pos.apply(titletip);
}

function displayLabel(arrayType, arrayId)
{
	if (arrayId != highlightId)
	{
		if (highlightMarker!=null) map.removeOverlay(highlightMarker);
		if (currentMarkerId!=null) markers[currentMarkerId] = createMarker(currentBlock, currentMarkerId, false);
		highlightMarker = null;
		currentMarkerId = null;
	}

	var property = properties[arrayType][arrayId];
	var propertyElement = document.getElementById(property.propertyType.propertyTypeName+"_property_number_"+property.position);
	propertyElement.style.backgroundColor = '#F1E7B1';
	var propertyDetailsElement = document.getElementById("property_details");
	if ($("#property_details").is(":hidden")) {
		$("#property_details").slideDown("slow");
	}
	propertyDetailsElement.innerHTML = propertyElement.innerHTML;
}

function show_on_map(arrayType, arrayId){
	if (arrayId != highlightId || highlightMarker==null){
		displayLabel(arrayType, arrayId);
		hideLabel(arrayType, arrayId);

		marker = markers[arrayId];
		map.removeOverlay(marker);
		currentMarkerId = arrayId;

		highlightMarker = createMarker(arrayType, arrayId, true);
		highlightId = arrayId;
	}
}

function hideLabel(arrayType, arrayId)
{
	var propertyElement = document.getElementById(properties[arrayType][arrayId].propertyType.propertyTypeName+"_property_number_"+(properties[arrayType][arrayId].position));
	propertyElement.style.backgroundColor = '';
}

// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a side_bar mouseover
function showTooltip(marker) {
	tooltip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var width = tooltip.offsetWidth/2;
	var xoffset = offset.x - point.x - width
	if (xoffset<0) xoffset = 0;
	if (offset.x - point.x + width > 500)
	{
		xoffset = 500-width;
	}
	var yoffset = - offset.y + point.y;
	if (yoffset>300) yoffset = yoffset - 50;
	else yoffset = yoffset+10;
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(xoffset, yoffset)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
}

function resetMap()
{
	var addHandler = false;
	if (mapMoveHandler)
	{
		addHandler = true;
		GEvent.removeListener(mapMoveHandler);
	}
	map.setZoom(map.getBoundsZoomLevel(defaultBounds[currentBlock]));
	map.setCenter(defaultBounds[currentBlock].getCenter());
	if (addHandler)
	{
		updateProperties();
		mapMoveHandler = GEvent.addListener(map, "moveend", function() {
			updateProperties();
		});
	}
}

function resetPropertyMap()
{
	var addHandler = false;
	map.setCenter(new GLatLng(baseLat,baseLng),defaultZoom);
}

function updateProperties()
{
	var allPropertiesElement = document.getElementById(blockToShow);
	allPropertiesElement.innerHTML = "";
	_set_loading_interface();
	$("#loading_information").show();
	$("#property_details").hide();
	map.clearOverlays();
	if (isDateSet) startAvailabilityRequest();
	else displayProperties();
}

function _set_loading_interface() {
	// Apply the HTML markup into body tag
	$('#map-area').append('<div id="map-loading"><div id="property-loading">LOADING PROPERTY INFORMATION<a href="#" id="property-loading-link"><img src="' + imageLoading + '"></a></div></div>');	
	// Get page sizes
	var arrPageSizes = ___getPageSize();
	// Style overlay and show it
	$('#map-loading-overlay').css({
		backgroundColor:	overlayBgColor,
		opacity:			overlayOpacity,
		width:				arrPageSizes[0],
		height:				arrPageSizes[1]
	}).fadeIn();
/*
	// Get page scroll
	var arrPageScroll = ___getPageScroll();
	// Calculate top and left offset for the map-loading div object and show it
	$('#map-loading').css({
		top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
		left:	arrPageScroll[0]
	}).show();
	// If window was resized, calculate the new overlay dimensions
	$(window).resize(function() {
		// Get page sizes
		var arrPageSizes = ___getPageSize();
		// Style overlay and show it
		$('#map-loading-overlay').css({
			width:		arrPageSizes[0],
			height:		arrPageSizes[1]
		});
		// Get page scroll
		var arrPageScroll = ___getPageScroll();
		// Calculate top and left offset for the map-loading div object and show it
		$('#map-loading').css({
			top:	arrPageScroll[1] + (arrPageSizes[3] / 10),
			left:	arrPageScroll[0]
		});
	});
*/
}

function displayProperties(){
	message[currentBlock] = "";
	postMessage[currentBlock] = "";
	propertyCount=0;
	bounds = map.getBounds();
	currentBounds[currentBlock] = bounds;
	sw = bounds.getSouthWest();
	ne = bounds.getNorthEast();
	var currentTime = new Date();
	properties[currentBlock] =  new Array();
	orderBy = "dist";
	if (document.getElementById('orderBy') != null) orderBy = document.getElementById('orderBy').value;
	var qs = "action=search_map&swlat="+sw.lat()+"&swlng="+sw.lng()+"&nelat="+ne.lat()+"&nelng="+ne.lng()+"&propertytype="+currentBlock+"&baseLat="+baseLat+"&baseLng="+baseLng+"&orderBy="+orderBy+"&pageLimit="+pageLimit+"&clean="+currentTime.getTime();
	doAjaxRun("ajax", handleHttpResponse, qs);
}

function getCurrentProperties(){
	blockToShow = currentBlock + "_information";
	for (var blockName in propertyList)
	{
		message[blockName] = "<h2>Featured "+townName+" "+blockName+"s";
		postMessage[blockName] = "";
		if (propertyList[blockName].length>0)
		{
			message[blockName] += "<button class=\"form_button\" onclick=\"showAllProperties(); return false;\" type=\"submit\" style=\"margin-left:80px;\">Show more "+townName+" "+blockName+"s</button>";
			postMessage[blockName] = "<button class=\"form_button\" onclick=\"showAllProperties(); return false;\" type=\"submit\">Show more "+townName+" "+blockName+"s</button>";
			var currentTime = new Date();

			var q="";
			for(var i=0;i < propertyList[blockName].length;i++) {
				if (i>0) q += ",";
				q += propertyList[blockName][i];
			}
			var qs = "action=specific_properties&propertyList="+q+"&propertytype="+blockName+"&baseLat="+baseLat+"&baseLng="+baseLng+"&orderBy="+orderBy+"&clean="+currentTime.getTime();
			doAjaxRun("ajax", handleCurrentProperyResponse, qs);
		}
		else {
			properties[blockName] = new Array();
		}
		message[blockName] += "</h2>";
	}

}

function handleCurrentProperyResponse(json){
	properties[json.propertytype] =  new Array();
	properties[json.propertytype] =  json.properties;
	doShowBlocks = true;
	for (var blockName in propertyList)
	{
		if (properties[blockName]==null) doShowBlocks = false;
	}
	if(doShowBlocks){
		updatePropertyPrices();
		showBlocks();
	}
}

function showAllProperties(){
	var allPropertiesElement = document.getElementById(blockToShow);
	allPropertiesElement.innerHTML = "";
	_set_loading_interface();
	$("#loading_information").show();
	$("#property_details").hide();
	mapLoaded = false;
	currentBounds[currentBlock] = null;
	message[currentBlock] = "";
	postMessage[currentBlock] = "";
	propertyCount=0;
	var currentTime = new Date();
	properties[currentBlock] =  new Array();
	orderBy = "dist";
	if (document.getElementById('orderBy') != null) orderBy = document.getElementById('orderBy').value;
	var qs = "action=search_location&locId="+locId+"&propertytype="+currentBlock+"&baseLat="+baseLat+"&baseLng="+baseLng+"&orderBy="+orderBy+"&pageLimit="+pageLimit+"&clean="+currentTime.getTime();
	doAjaxRun("ajax", handleHttpResponse, qs);
}

function handleHttpResponse(json){
			properties[currentBlock] =  properties[currentBlock].concat(json.properties);

			var allPropertiesElement = document.getElementById(blockToShow);
			var html = "";
			
			allPropertiesElement.innerHTML = getPropertiesHtml(currentBlock);
			if (message[currentBlock]!=null && message[currentBlock]!="") $("#message_area_"+currentBlock).show();

			doMaxItems();

			for (i=0; i<locationList.length; i++)
			{
				createTownMarker(i);
			}
			if(markerTitle!='' && markerTitle!=undefined){
				createTitleMarker();
			}
			var finishLoading = true;
			var html="";
			if (isDateSet && mapLoaded)
			{
				var distributorId = json.distributorId;
				distributorDetails[distributorId].currentCallCount = parseInt(distributorDetails[distributorId].currentCallCount)+parseInt(distributorDetails[distributorId].maxDistributorCall);
				if (distributorDetails[distributorId].currentCallCount<parseInt(distributorDetails[distributorId].numberOfProperties) && properties[currentBlock].length < pageLimit)
				{
					distributorDetails[distributorId].searchComplete = false;
					finishLoading = false;
					makeAvailabilityRequest(distributorId);
				}
				else {
					distributorDetails[distributorId].searchComplete = true;
				}
				for ( var i in distributorDetails )
				{
					if(!distributorDetails[i].searchComplete) finishLoading = false;
				}
			}
			reOrderProperties();
			if (finishLoading) _finish_loading();
}

function getCurrencyCodeHtml(currency){
	switch(currency)
	{
		case "GBP":
			currency = "&#163;"
			break;    
		case "USD":
			currency = "&#36;"
			break;    
		case "EUR":
			currency = "&#128;"
			break;
		default:
			currency = currency+" ";
	}
	return currency;
}

function getPropertiesHtml(block){
	var html = "<div id=\"message_area_"+block+"\">"+message[block]+"</div>";

	for (i=0; i<properties[block].length; i++)
	{
		var property = properties[block][i];
		html += "<div id=\""+property.propertyType.propertyTypeName+"_property_number_"+(i+1)+"\" class=\"property_information\">";
		html += getPropertyHtml(property, block);
		html += "</div>";
	}
	if (postMessage[block]!=null && postMessage[block]!="") html += "<div id=\"post_message_area_"+block+"\">"+postMessage[block]+"</div>";
	html += "<br class=\"clear\"/>";
	return html;
}

function getPropertyHtml(property, block){
	var html = "<div class=\"property-photo\">";
	html += "	<a title=\"hotel : "+property.name+"\" href=\""+property.localUrl+"\" rel=\"nofollow\" target=\"_property\">";
	html += "		<img class=\"property\" height=\"125\" width=\"125\" alt=\""+property.name+"\" src=\""+property.thumbnail+"\"/>";
	html += "	</a>";
	html += "</div>";
	html += "<div class=\"property-copy\">";
	html += "	<div class=\"property-info\">";
	html += "		<a title=\"hotel : "+property.name+"\" href=\""+property.localUrl+"\" target=\"_property\">";
	html += "			<div class=\"name\">";
	html += "				<h3>"+property.name+"</h3>";
	html += "			</div>";
	if(property.discount!="" && property.discount!=0 && property.discount!=null) html += "			<span class=\"discount\">"+property.discount+"% discount</span>";
	if (property.rating>0)
	{
		html += "<div class=\"star-rating-area\">";
		html += "	<div class=\"star-rating-simple\">";
		for(j=0; j<5; j++){
			if(property.rating>j) html += "<div class=\"star\"><span class=\"on\">"+j+"</span></div>";
			else if(property.rating==j) html += "<div class=\"star\"><span class=\"on\" style=\"width: 0%;\">"+j+"</span></div>";
			else html += "<div class=\"star\"><span class=\"off\">"+j+"</span></div>";
		}
		html += "	</div>";
		html += "</div>";
	}

	html += "		</a>";
	html += "		<div class=\"type_icon "+property.propertyType.propertyTypeName+"_icon\"><p>"+property.position+"</p></div>";
	html += "		<div class=\"show-on-map\"><a href=\"#\" onclick=\"show_on_map('"+property.propertyType.propertyTypeName+"', "+(property.position-1)+");\"><img alt=\"show on map\" src=\"/images/icons/show-on-map.png\"/></a></div>";
	html += "		<br class=\"clear\">";
	html += "	</div>";
	html += "	<div class=\"property-text\">";
	html += "		<div class=\"property-address-area\">";
	var addressToDisplay = "";
	if(property.address.address1!='') addressToDisplay += property.address.address1+", ";
	if(property.address.address2!='') addressToDisplay += property.address.address2+", ";
	if(property.address.address3!='') addressToDisplay += property.address.address3+", ";
	addressToDisplay += property.address.town;
	if(property.address.county!='') addressToDisplay += ", "+property.address.county;
	addressToDisplay += " "+property.address.postcode;
	property.addressToDisplay = addressToDisplay;

	html += "			<p class=\"address\">"+property.addressToDisplay+"</p>";
	if(property.distance!="" && property.distance!=null){
		html += "			<p class=\"property-distance\">Distance: "+property.distance+"miles from ";
		if (postMessage[block]!="" && postMessage[block]!=null) html += townName+".</p>";
		else html += "the centre of the map.</p>";
	}
	html += "			<br class=\"clear\">";
	html += "		</div>";
	html += "		<p class=\"description\">"+property.shortDescription;
	html += "			<a title=\"hotel : "+property.name+"\" href=\""+property.localUrl+"\" target=\"_property\"> more </a>";
	html += "		</p>";

	var commentsHtml = "";
	for ( var i in property.comments){
		var comment = property.comments[i];
		if (comment.commentContent!='')
		{
			commentsHtml += "<p class=\"comments\">"+comment.commentContent+"</p>";
		}
		if (comment.best!='')
		{
			commentsHtml += "<p class=\"best\">"+comment.best+"</p>";
		}
		if (comment.worst!='')
		{
			commentsHtml += "<p class=\"worst\">"+comment.worst+"<p/>";
		}
	}
	if (commentsHtml!="")
	{
		html += "<p><strong>Reviewer comments</strong></p>"+commentsHtml;
	}

	var currency = property.currency;
	currencyHtml = getCurrencyCodeHtml(currency);
	var convertedPriceHtml = "";
	var guidePrice = parseFloat(property.guidePrice);
	if (currency!=currentCurrency && currency!="")
	{
		if (rateObject[currency]!=0 && rateObject[currency]!=null)
		{
			convertedPriceHtml = " <span class=\"converted\">(approximately "+getCurrencyCodeHtml(currentCurrency)+Math.ceil(getConvertedPrice(currency, currentCurrency, property.guidePrice))+")</span>";
		}
	}
	html += "		<p class=\"guideprice\"> Guide Price: <span>"+currencyHtml+guidePrice.toFixed(2)+convertedPriceHtml+"</span>";
	if (isDateSet && distributorDetails.length > 0) html += " price quoted is for the duration of your stay";
	if(property.discount!="" && property.discount!=0 && property.discount!=null) html += " and includes a discount of "+property.discount+"% ";
	if (property.message!="" && property.message!=null) html += "		<br/><span class=\"message\">"+property.message+"</span>";
	if((property.rooms!="" && property.rooms!=null && property.rooms!=0) || (property.sleeps!="" && property.sleeps!=null && property.sleeps!=0) || (property.time!="" && property.time!=null)){
		html += "<br>";
		if (property.time!="" && property.time!=null) html += "	Property start date: "+property.time+" ";
		if (property.rooms!="" && property.rooms!=null && property.rooms!=0) html += "Number of bedrooms: "+property.rooms+" ";
		if (property.sleeps!="" && property.sleeps!=null && property.sleeps!=0){
			html += "Property sleeps up to: "+property.sleeps;
			if (property.sleeps>1) html += " people";
			else html += " person";
		}
	}

	html += "	</p>";
	html += "<div class=\"recommend\"><a href=\"/recommendahotel.php?propertyId="+property.propertyId+"&distributorId="+property.distributorId+"\" target=\"_recommend\"><img src=\"/images/recommend.gif\"/></a></div>";
	html += "</div>";
	html += "</div>";
	html += "<br class=\"clear\"/>";
	return html;
}
/**
 * Availability Functions....
 *
 */
var maxResultSet = 50;
var distributorDetails = new Array();
var startYear;
var startMonth;
var startDay;
var endYear;
var endMonth;
var endDay;
var numberOfNights;
var numberOfPeople;
var orderBy;
var propertyCount = 0;

function startAvailabilityRequest(){
	dateSelected();
	var count=0;
	propertyCount=0;
	properties[currentBlock] = new Array();

	startYear = document.getElementById('checkIn_MonthYear').value.substring(0,4);
	startMonth = document.getElementById('checkIn_MonthYear').value.substring(5,7);
	startDay = document.getElementById('checkIn_Day').value;
	if (parseInt(startDay)<10) startDay = "0"+startDay;

	endYear = document.getElementById('checkOut_MonthYear').value.substring(0,4);
	endMonth = document.getElementById('checkOut_MonthYear').value.substring(5,7);
	endDay = document.getElementById('checkOut_Day').value;
	if (parseInt(endDay)<10) endDay = "0"+endDay;

	orderBy = "dist";
	if (document.getElementById('orderBy') != null) orderBy = document.getElementById('orderBy').value;

	numberOfNights = document.getElementById('numberOfNights').value;
	numberOfPeople = document.getElementById('numberOfPeople').value;

	bounds = map.getBounds();
	currentBounds[currentBlock] = bounds;
	sw = bounds.getSouthWest();
	ne = bounds.getNorthEast();
	var currentTime = new Date();
	var qs = "action=get_distributor_list&swlat="+sw.lat()+"&swlng="+sw.lng()+"&nelat="+ne.lat()+"&nelng="+ne.lng()+"&propertytype="+currentBlock+"&baseLat="+baseLat+"&baseLng="+baseLng+"&orderBy="+orderBy+"&clean="+currentTime.getTime();
	doAjaxRun("ajax", getDistributorListJson, qs);

	var startDate = parseDate(startYear+"-"+startMonth+"-"+startDay);
	var endDate = parseDate(endYear+"-"+endMonth+"-"+endDay);
	message[currentBlock] = "Showing available properties for arrival on "+formatDate(startDate,"EE d MMM yyyy")+" and departure on "+formatDate(endDate,"EE d MMM yyyy");
}

function makeAvailabilityRequest(distributorId){
	var currentTime = new Date();
	var qs = "action=get_availability&distributorId="+distributorId+"&startYear="+startYear+"&startMonth="+startMonth+"&startDay="+startDay+"&endYear="+endYear+"&endMonth="+endMonth+"&endDay="+endDay+"&swlat="+sw.lat()+"&swlng="+sw.lng()+"&nelat="+ne.lat()+"&nelng="+ne.lng()+"&propertytype="+currentBlock+"&baseLat="+baseLat+"&baseLng="+baseLng+"&orderBy="+orderBy+"&numberOfNights="+numberOfNights+"&numberOfPeople="+numberOfPeople+"&offset="+distributorDetails[distributorId].currentCallCount+"&limit="+distributorDetails[distributorId].maxDistributorCall+"&clean="+currentTime.getTime();
	doAjaxRun("ajax"+distributorId, handleHttpResponse, qs);
}

function getDistributorListJson(json){
	distributorDetails = new Array();
	var count = 0;
	for ( var i in json.distributorCounts ){
		count++;
		var currentDistributor = json.distributorCounts[i];
		var distributorId = currentDistributor.distributorId;
		currentDistributor.currentCallCount = 0;
		currentDistributor.searchComplete = false;
		propertyCount += parseInt(currentDistributor.numberOfProperties);

		distributorDetails[distributorId] = currentDistributor;
		makeAvailabilityRequest(distributorId);
	}
	if (count==0){
		var maxItems = document.getElementById("maxItems");
		maxItems.innerHTML = "NO PROPERTIES FOUND. <br/>PLEASE ZOOM OUT FOR MORE PROPERTY DETAILS";
		maxItems.style.visibility = "visible";
		_finish_loading();
	}
}


/**
 * Remove map loading HTML markup
 *
 */
function _finish_loading() {
	$('#map-loading').remove();
}

/**
 / THIRD FUNCTION
 * getPageSize() by quirksmode.com
 *
 * @return Array Return an array with page width, height and window width, height
 */
function ___getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};
/**
 / THIRD FUNCTION
 * getPageScroll() by quirksmode.com
 *
 * @return Array Return an array with x,y page scroll values.
 */
function ___getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
};

function doAjaxRun(domain, callback, qs){
	$.getJSON("http://"+domain+".world-stay.com"+jsonUrl+"?"+qs+"&callback=?", callback);
//console.log("http://"+domain+".world-stay.com"+jsonUrl+"?"+qs+"&callback=?");
}