// javascript used by advsearch.asp for googlemap functionality.

var show_debugging = false; 
var map_intro_closed = false; 
var map;
var saved_lat, saved_lng, saved_zoom = '';
var DEFAULT_ZOOM = 7;
var DEFAULT_LAT = 50.7;
var DEFAULT_LNG = -3.8;
var MAPSTATE_COOKIE = 'advsgmapstate';

function hhgmap_initialize() {
	
   if (show_debugging)
	{
	document.getElementById("debug_info").style.display = 'block';
	document.getElementById("debug_info").innerHTML = '<p><b>Debugging Information</b><br/></p>';
	}  
	
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("googleMap"));
			
		map.addMapType(G_PHYSICAL_MAP)
					
		var mapState = hhgmap_getCookie(MAPSTATE_COOKIE);
		if (mapState.length > 1) {
			hhgmap_loadMapStateFromCookie();	
		}
		else {
			map.setCenter(new GLatLng(DEFAULT_LAT, DEFAULT_LNG), DEFAULT_ZOOM);
		}

		map.addControl(new GSmallMapControl());
		
		var bottomRight = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(82,4));
		map.addControl(new GMapTypeControl(), bottomRight);
		// map.addControl(new GOverviewMapControl());
		map.enableScrollWheelZoom();
								
		// Save map state to cookie whenever map changes...
		// GEvent.addListener(map,"moveend", function(){saveMapStateToCookie();});	
		
		// Ensure map returns to original position when info windows are closed...
		GEvent.addListener(map,"infowindowclose",function(){map.returnToSavedPosition()});
		
		
		hhgmap_populateMap();
	}
	
}


function hhgmap_populateMap() {
	hhgmap_loadMarkers();
}

function hhgmap_refreshMarkers() {
	map.clearOverlays();
	hhgmap_populateMap();
}
		

function hhgmap_createMarker(point,label,placeid,placename,arrprops) {

	var myIcon = new GIcon(G_DEFAULT_ICON);
	//myIcon.image = "images/maps/red_marker.png";
	//myIcon.iconSize = new GSize(12, 20);
	//myIcon.iconAnchor = new GPoint((12 / 2), (20 - 2));
	
	//myIcon.image = "images/misc/throb_3.gif";
	//myIcon.iconSize = new GSize(5, 5);
	//myIcon.iconAnchor = new GPoint((5 / 2), (5 - 2));
	
	myIcon.image = "images/misc/throb_2.gif";
	myIcon.iconSize = new GSize(7, 7);
	myIcon.iconAnchor = new GPoint((7 / 2), (7 - 2));
	myIcon.infoWindowAnchor = new GPoint(1,5);
			
	myIcon.shadow = "";

	var marker = new GMarker(point, {icon:myIcon, title:label});
			
	// GEvent.addListener(marker, "click", function() {
	//  marker.openInfoWindowHtml(html,{maxWidth:350});
	// });
	
	GEvent.addListener(marker, "click", function() {
		hhgmap_showPopUpHTML(marker,placeid,placename,arrprops)
	});
							
	return marker;
}
	
function hhgmap_showPopUpHTML(marker,placeid,placename,arrprops){
							
	var request = GXmlHttp.create();
	var dataUrl = "wsfeeds/WS_DataRequestHandler.asp?hh_affid=1&hh_wskey=JNZFRVKWQP&hh_action=PROPSEARCH&hh_output=xml&hh_itemspp=999&hh_inc_descs=N&hh_proprefs=" + arrprops.join(",");	
   
	if (show_debugging)
	  {document.getElementById("debug_info").innerHTML = document.getElementById("debug_info").innerHTML
	  + '<p><b>dataURL</b> = ' + dataUrl + '</p>';}  

	request.open("GET", dataUrl, true);
	request.onreadystatechange = function() {
		if (request.readyState == 4) {
										
			// Get rid of annoying ColdFusion warning if necessary.
			var responseTextCleaned = request.responseText.replace(/<META NAME="ColdFusionMXEdition" CONTENT="ColdFusion DevNet Edition - Not for Production Use.">/,"");  
			
			 if (show_debugging)
			  {document.getElementById("debug_info").innerHTML = '<p><b>XML Cleaned Response...</b><br/><xmp>' + responseTextCleaned + '</xmp></p>';}   
							
			var xmlDoc = GXml.parse(responseTextCleaned);
							
			//	obtain the array of markers and loop through it
			var properties = xmlDoc.documentElement.getElementsByTagName("entry");
							
			var html, prop_ref, propdets_link, prop_sleeps, prop_bedrooms, prop_bathrooms, prop_stars, prop_description, prop_image = '';
			var prop_smoking, prop_pets, prop_minprice, prop_comments, propcomments_link = '';
			var centerLatLng = '';
			var results_link = 'advresults.asp?pl_id=' + placeid;

			if (show_debugging)
			  {document.getElementById("debug_info").innerHTML = document.getElementById("debug_info").innerHTML  
			  + '<p><b>Number of properties in XML...</b><br/><xmp>' + properties.length + '</xmp></p>';}

			var props_html = ['<div class="gmap_popup_hdr gen9">'];
			props_html.push('Holiday cottages in ' + placename + ' (' + properties.length + ')<br/>');
			props_html.push('<a href="' + results_link + '">View more detailed holiday cottage list</a>');
			props_html.push('</div>');
			
			props_html.push('<div class="gmap_popup_list">');
			props_html.push('<table border="0" cellpadding="2" cellspacing="0" width="371px">');
						
			// iterate properties data and build up html for pop-up info box.
			for (var x = 0; x < properties.length; x++) {
													  
				prop_ref = GXml.value(properties[x].getElementsByTagName("propRef")[0]);
				prop_sleeps = GXml.value(properties[x].getElementsByTagName("propSleeps")[0]);
				prop_bedrooms = GXml.value(properties[x].getElementsByTagName("propBedrooms")[0]);
				prop_bathrooms = GXml.value(properties[x].getElementsByTagName("propBathrooms")[0]);
				prop_stars = GXml.value(properties[x].getElementsByTagName("propStars")[0]);
				prop_image = GXml.value(properties[x].getElementsByTagName("webPropPhotoMediumURL")[0]);
				// prop_description = GXml.value(properties[x].getElementsByTagName("propDesc")[0]);
				prop_smoking = GXml.value(properties[x].getElementsByTagName("propSmokingAllowed")[0]);
				prop_pets = GXml.value(properties[x].getElementsByTagName("propPetsAllowed")[0]);
				prop_minprice = GXml.value(properties[x].getElementsByTagName("propMinPrice")[0]);
				prop_comments = GXml.value(properties[x].getElementsByTagName("propCommentsCount")[0]);
				
				propdets_link = 'property.asp?ref=' + prop_ref;
				propcomments_link = 'javascript:pc=window.open(\'property_comments.asp?pref=' + prop_ref + '\',\'comments\',\'height=500,width=650,scrollbars=yes,resize=yes\');pc.focus()';
				
				props_html.push('<tr valign="top" align="left" class="gen9">');
				props_html.push('<td><a href="' + propdets_link + '"><img src="' + prop_image + '" width="140" alt="Property photo" border="0"></a></td>');
				props_html.push('<td>');
				props_html.push('  <table border="0" cellpadding="1" cellspacing="0" width="230px">');
				props_html.push('    <tr class="gen9">');
				props_html.push('      <td colspan="2" align="left">');
				props_html.push('        <a href="' + propdets_link + '">' + prop_ref + '</a>&nbsp;&nbsp;&nbsp;');
				props_html.push('        <img src="images/misc/stars_' + prop_stars + '.gif"/>');
				props_html.push('      </td>');
				props_html.push('      <td colspan="2" align="right">');
				if (prop_comments == 0) {
				  props_html.push('        Comments (' + prop_comments + ')');
				}
				else {
				  props_html.push('        <a href="' + propcomments_link + '">Comments (' + prop_comments + ')</a>');
				}
				props_html.push('      </td>');
				props_html.push('    </tr>');
				props_html.push('    <tr class="gen9">');
				props_html.push('      <td align="left">');
				props_html.push('        Sleeps:');
				props_html.push('      </td>');
				props_html.push('      <td align="right">');
				props_html.push('          ' + prop_sleeps);
				props_html.push('      </td>');
				props_html.push('      <td colspan="2" rowspan="3" align="right">');
				if (prop_pets == 'N') {
				  props_html.push('        <img src="images/misc/nopets.gif" height="36" width="28" alt="No pets"/>');
				}
				else {
				  props_html.push('        <img src="images/misc/yespets.jpg" height="36" width="28" alt="Pets may be allowed"/>');
				}
				if (prop_smoking == 'N') {
				  props_html.push('        <img src="images/misc/nosmoking.gif" height="36" width="36" alt="No smoking"/>');
				}
				props_html.push('      </td>');
				props_html.push('    </tr>');
				props_html.push('    <tr class="gen9">');
				props_html.push('      <td align="left">');
				props_html.push('        Bedrooms:');
				props_html.push('      </td>');
				props_html.push('      <td align="right">');
				props_html.push('          ' + prop_bedrooms);
				props_html.push('      </td>');
				props_html.push('    </tr>');
				props_html.push('    <tr class="gen9">');
				props_html.push('      <td align="left">');
				props_html.push('        Bathrooms:');
				props_html.push('      </td>');
				props_html.push('      <td align="right">');
				props_html.push('          ' + prop_bathrooms);
				props_html.push('      </td>');
				props_html.push('    </tr>');
				props_html.push('    <tr class="gen9">');
				props_html.push('      <td colspan="4" align="left">');
				props_html.push('        Prices from <a href="' + propdets_link + '">£' + prop_minprice + '</a>');
				props_html.push('      </td>');
				props_html.push('    </tr>');
				props_html.push('  </table>');
				props_html.push('</td>');
				props_html.push('</tr>');
				
				// props_html.push('<tr valign="top" align="left" class="gen9">');
				// props_html.push('  <td colspan="2">' + prop_description);
				// props_html.push('  </td>');
									
				props_html.push('<tr valign="top" align="left" class="gen9">');
				props_html.push('  <td colspan="2">');
				props_html.push('    <table border="0" cellpadding="1" cellspacing="0">');
				props_html.push('      <tr>');
				props_html.push('        <td><div class="inlinebutton"><a href="' + propdets_link +'" title="See the full details of this property">Details</a></div></td>');
				props_html.push('        <td><div class="inlinebutton"><a href="availability_fullpage.asp?pref=' + prop_ref +'" title="See the latest availability for this property">Availability</a></div></td>');
				props_html.push('      </tr>');
				props_html.push('    </table>');
				props_html.push('    <hr/>');
				props_html.push('  </td>');
				props_html.push('</tr>');
				
			}
				
			props_html.push('</table>');
			props_html.push('</div>');
						
			html = props_html.join("");
									
			// Save current Map position so we can revert to it when info window is closed...	
			map.savePosition();	

			// Additional map state variables that are used in finalize function
			centerLatLng = map.getCenter();
			saved_zoom = map.getZoom();
			saved_lat = centerLatLng.lat();
			saved_lng = centerLatLng.lng();
										
			marker.openInfoWindowHtml(html,{maxWidth:400});  // This will cause the map position to move
								
		}
	}
	request.send(null);
		
}

function hhgmap_btnPlotOnClick() {
	progress_update();
	map.setCenter(new GLatLng(DEFAULT_LAT, DEFAULT_LNG), DEFAULT_ZOOM);
	return true;
}

function hhgmap_btnResetOnClick() {
	progress_update();
	map.setCenter(new GLatLng(DEFAULT_LAT, DEFAULT_LNG), DEFAULT_ZOOM);
	return true;
}


function hhgmap_saveMapStateToCookie() {

	var mapzoom=map.getZoom();
	
	var mapcenter=map.getCenter();
	var maplat=mapcenter.lat();
	var maplng=mapcenter.lng();
	
	var cookiestring=maplat+"_"+maplng+"_"+mapzoom;
	
	// var exp = new Date();     
	// exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 3));     //set it 3 days ahead
	var exp = null;  // Create a transient/Session Cookie
	
	hhgmap_setCookie(MAPSTATE_COOKIE,cookiestring, exp);
}


function hhgmap_loadMapStateFromCookie()	{
	var loadedstring = hhgmap_getCookie(MAPSTATE_COOKIE);
	var splitstr = loadedstring.split("_");
	
	map.setCenter(new GLatLng(parseFloat(splitstr[0]), parseFloat(splitstr[1])), parseFloat(splitstr[2]));
}

function hhgmap_setCookie(name, value, expires) {
	document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}

function hhgmap_getCookie(c_name) {
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}


function hhgmap_finalize() {

	// if the infowindow is currently displayed then we need to set the map state back to how it was prior to it being displayed...
	var infoWindow = map.getInfoWindow();
	if (!infoWindow.isHidden()) {
		map.setCenter(new GLatLng(saved_lat, saved_lng), saved_zoom);
	}	

	hhgmap_saveMapStateToCookie();  // Save map state to session cookie.
	
	GUnload();  // Googlemaps unload.

}
			
