/***************************************************
*
* AJAX for Welsh Cottages shortlist Implementation
*
* Support Scripts - called via HttpRequest
*
*		fee_add.php
*		fee_remove.php
*		fee_to_top.php
*		fee_clear.php
*
****************************************************/

// location of the server-side scripts for manipulating this session's shortlist
var httpPath = "/scripts/";

// turns verbose debugging mode on/off
var verbose = false;

// Install crossbrowser support for getElementById
//
// If browser has no getElementById then create one for it using the technology it does support...
//
if(!document.getElementById)
{
	if(document.all) 
	{
	document.getElementById=
		function()
		{
			if (typeof document.all[arguments[0]] != "undefined")
				return document.all[arguments[0]]
			else
				return null
		}
	}
	else if(document.layers)
	{
		document.getElementById=
		function()
		{
			if (typeof document[arguments[0]] != "undefined")
				return document[arguments[0]]
			else
				return null
		}
	}
}

/**
 * for debugging
 */
function _alert(str)
{
	if (verbose == true) alert(str);	
}

/**
 * for a checkbox, or array of checkboxes returns true only if at least one is checked
 * !!! JavaScirpt NOT as cool as PHP when dealing with arrays from form !!!
 */
function validateDates(fromAvailability)
{
	//var dates = document.forms[fromAvailability].elements['dates[]']
	var dates = fromAvailability.elements['dates[]']
	if (dates.length)
	{
	for (i=0; i<dates.length; i++)
	{
	  if (dates[i].checked) return true;
	} 
	} 
	else
	{
	if (dates) return dates.checked;
	}
	return false;
}


/**
 * Generic function to get an XMLHttpRequest object
 */
function getRequester()
{  
	// try all possible browser styles for getting an http request object...
	var xmlHttp;
	try
	{    
		// Firefox, Opera 8.0+, Safari AND now IE 7
		xmlHttp=new XMLHttpRequest();
		_alert("Got a NATIVE XMLHttpRequest Object!")
	}
	catch (e)
	{    
		// Internet Explorer 
		try
		{      
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      
			_alert("Got an ActiveXObject XMLHttpRequest Object!")
		}
		catch (e)
		{      
			try
			{ 
				// Old, old style
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");        
				_alert("Got a very old style IExplorer 5ish XMLHttpRequest Object!")
			}
			catch (e)
			{        
				alert("Sorry but your browser does not support AJAX! No shortlist available."); 
				return false;  
			}
		}
	}
	return xmlHttp;
}

/**
 *	Checks ref for validity, returns true if it is INVALID
 */
function invalid(ref)
{
	var pat = /\d\d\d/;
	var str = (String)(ref);
	return (str.search(pat) == -1);
}

function parseResponse(response)
{
	var exp = new RegExp(/([0-9]*),([0-9,'']*)/);	
	var matches = response.match(exp);
	if (matches[1] == "undefined") {matches[1] = 0;}
	if (matches[2] == "undefined") {matches[2] = "";}
	_alert("From response " + response + " Extracted count " + matches[1] + " and list " + matches[2] + " from " + matches[0]);
	
	return matches;
}

/**
* Given a property ref, adds it to the shortlist for this session by issuing an XMLHttpRequest
* to the server and getting it to run fee_add.php
* 
*	callerId		<= the Id of the 'add to shortlist button' that was clicked
*	ref				<= ref of the property for which the button was clicked
*	lastsearch		<= search string that created the current page
*
*/
function add_to_shortlist(callerId, ref, lastsearch, mailtoURL)
{  
	if (invalid(ref)) return false;
	
	// get an XMLHttpRequest object
	var xmlHttp = getRequester();
	if (!xmlHttp) return false;

	var clicked = document.getElementById(callerId);
	if (clicked.innerHTML=="[Shortlist]")
	{
		clicked.innerHTML = "[View&nbsp;Shortlist]"

		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				// split response text into count and list parts
				_alert("In Response With =" + xmlHttp.responseText);
				
				var res = parseResponse(xmlHttp.responseText);
				var count = res[1];
				var list = res[2];
				
				_alert("RESPONSE=" + res);
				
				// first update the counter for number of entries in shortlist
				doCount(count);
				
				// now update the email list
				el = document.getElementById("emailshortlist"); 
				if (el != null)
				{
					if (list != "")
					{
						var href = mailtoURL + "%26mailshortlist=" + list;
						el.href = href;
					}
				} else {
					// NOT really a problem as wel may be on the search page NOT the shortlist page!
					_alert("CANT FIND emailshortlist!");				
				}
			}
		}

		xmlHttp.open("GET", httpPath + "fee_add.php?propref=" + ref, true);
		_alert("About to GET: " + httpPath + "fee_add.php?propref=" + ref);
		xmlHttp.send(null);
		_alert("SUCCESS - but still awaiting response"); 
	}
	else
	{
		// NOT [Shortlist] so this is a call to view the shortlist...
		//window.location.search = lastsearch + "&showshortlist=1";
		// !!! TO DO !!!
		// THIS IS A TEMPORARY IMPLEMENTATION - need a generic solution...
		//window.location.search = lastsearch;
		
		window.location = "/search/pty_shorts.php";
	}
	return false;	
}

/**
 * remove propref from the shortlist by calling server fee_remove.php
 * 
 * also makes the target disappear from the page
 */
function remove_from_shortlist(callerId, ref, lastsearch, mailtoURL, targetOrder)
{  
	if (invalid(ref)) return false;
	
	// get an XMLHttpRequest object
	var xmlHttp = getRequester();
	if (!xmlHttp) return false;
	
	var clicked = document.getElementById(callerId);
	if (clicked.innerHTML=="[Remove]")
	{
		// remove the whole property listing from current page
		var targetId = "wrap_" + targetOrder;
		var target = document.getElementById(targetId);
		target.style.display = 'none';
		
		// callback to display new count
		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				// split response text into count and list parts
				var res = parseResponse(xmlHttp.responseText);
				var count = res[1];
				var list = res[2];
				
				// first update the counter for number of entries in shortlist
				doCount(count);
				
				// now update the email list
				el = document.getElementById("emailshortlist"); 
				if (el != null)
				{
					if (list != "")
					{
						var href = mailtoURL + "%26mailshortlist=" + list;
						el.href = href;
					}
				} else _alert("CANT FIND emailshortlist!");				
			}
		}
		
		xmlHttp.open("GET",httpPath + "fee_remove.php?propref=" + ref, true);
		_alert("About to GET: " + httpPath + "fee_remove.php?propref=" + ref);
		xmlHttp.send(null); 
		_alert("SUCCESS"); 
	}	
	return false;	
}

function doCount(count)
{
	// the original one...
	el = document.getElementById("numshortlist"); 
	if (el != null)
	{
		el.innerHTML=count;
	} 
	else _alert("CANT FIND numshortlist!");
	
	// now any others that have been added by PW - max of 20 cos thats our pagination limit
	for (i=0; i<=20; i++)
	{
		el = document.getElementById("numshortlist" + i); 
		if (el != null)
		{
			el.innerHTML=count;
		} 
		else return //alert("CANT FIND numshortlist" + i);
	}
	return;
}
/**
 * move to top of shortlist
 *
 * also moves element to the top of the page
 */
function to_top_shortlist(callerId, ref, lastsearch, mailtoURL, targetOrder)
{ 
	if (invalid(ref)) return false;
	
	var xmlHttp = getRequester();
	if (!xmlHttp) return false;
	
	var clicked = document.getElementById(callerId);
	if (clicked.innerHTML=="[I Like It!]")
	{
		var targetId = "wrap_" + targetOrder;
		var target = document.getElementById(targetId);
		// 'lost' the id=m div from mainsite! So use the id=w which seems to have replaced it
		//var parent = document.getElementById("m");
		var parent = document.getElementById("w");
		
		var top = document.getElementById("top_of_list");
		if (parent && top && target) 
		{
			// Do some gymnastics 
			// - move the element to Before top_of_list placeholder
			// - then put the placeholder before the target!
			parent.removeChild(target);
			parent.insertBefore(target, top);
			parent.removeChild(top);
			parent.insertBefore(top, target);
		}
		
		xmlHttp.onreadystatechange=function()
		{
			if(xmlHttp.readyState==4)
			{
				// split response text into count and list parts
				var res = parseResponse(xmlHttp.responseText);
				var count = res[1];
				var list = res[2];
				
				// first update the counter for number of entries in shortlist
				doCount(count);
				
				// now update the email list
				el = document.getElementById("emailshortlist"); 
				if (el != null)
				{
					if (list != "")
					{
						var href = mailtoURL + "%26mailshortlist=" + list;
						el.href = href;
					}
				} else _alert("CANT FIND emailshortlist!");				
			}
		}

		xmlHttp.open("GET",httpPath + "fee_to_top.php?propref="+ref, true);
		_alert("About to GET: " + httpPath + "fee_to_top.php?propref=" + ref);
		xmlHttp.send(null); 
		_alert("SUCCESS");
	} 
	return false;
}

/**
 * call on server to clear the shortlist
 * then follow the link OR use location:
 */
function clear_shortlist(lastsearch)
{
	var xmlHttp = getRequester();
	if (!xmlHttp) return false;
	
				var count = 0;
				var list = "";
				
				// first update the counter for number of entries in shortlist
				doCount(count);
				
				// now update the email list
				el = document.getElementById("emailshortlist"); 
				if (el != null)
				{
					el.href = "";
				} else _alert("CANT FIND emailshortlist!");				
			
	
	_alert("About to open GET: " + httpPath + "fee_clear.php");
	xmlHttp.open("GET",httpPath + "fee_clear.php", true);
	_alert("SUCCESS");
	xmlHttp.send(null); 

	// !!! trying this...
	//window.location.search = lastsearch;
	window.location = lastsearch;
	return false;
}

/**
 * no server actions, just return browser to the search page
 * use lastsearch to ensure shortlisted properties are preserved
 *
 * NB I was going to use the lastsearch parameter but don't need to 
 * as we can use window.location.search
 *
 */
function go_back(lastsearch)
{
	// !!! trying this...
	//window.location.search = lastsearch;
	window.location = lastsearch;
	return false;
	
	// ========================================================================NAH!
	
	// now we want to relocate the browser to the full search results page
	// so remove the search parameter BUT NOT the maillist parameter
	var shortexp = new RegExp("(&)?showshortlist=[0-9]*","g");
	//var mailexp = new RegExp("(&)?mailshortlist=[0-9,]*", "g");
	var search = window.location.search;
	search = search.replace(shortexp, "");
	//search = search.replace(mailexp, "");

	_alert("going back to search = " + search);
	
	window.location.search = search;
	
	return false;
}
