
var _console = null;

function debug(msg)
{
// Open a window the first time we are called, or after an existing
// console window has been closed

	if ((_console == null) || (_console.closed)) {
		_console = window.open("","console","width=600,height=300,resizable");
		// Open a document in the window to display plain text
		_console.document.open("text/plain");
	}

	_console.focus(  );                // Make the window visible
	_console.document.writeln(msg);    // Output the message to it
	// Note that we purposely do not call close(  ). Leaving the
	// document open allows us to append to it later.
}
/**
* This is the Cookie() constructor function.
*
* This constructor looks for a cookie with the specified name for the
* current document. If one exists, it parses its value into a set of
* name/value pairs and stores those values as properties of the newly created
* object.
*
* To store new data in the cookie, simply set properties of the Cookie
* object. Avoid properties named "store" and "remove" since these are 
* reserved as method names.
* 
* To save cookie data in the web browser's local store, call store().
* To remove cookie data from the browser's store, call remove().
*
* The static method Cookie.enabled() returns true if cookies are
* enabled and returns false otherwise.
*/

function Cookie(name) {
	this.$name = name;	// Remember the name of this cookie 

	// First, get a list of all cookies that pertain to this document
	// We do this by reading the magic Document.cookie property
	// If there are no cookies, we don't have anything to do 

	var allcookies = document.cookie;
	if (allcookies == "") return;

	// Break the string of all cookies into individual cookie strings
	// Then loop through the cookie strings, looking for our name

	var cookies = allcookies.replace(/ /g, '').split(';');
	var cookie = null;
	for(var i = 0; i < cookies.length; i++) {
		// Does this cookie string begin with the name we want?
		if (cookies[i].substring(0, name.length+1) == (name + "=")) {
			cookie = cookies[i];
			break;
		}
	}

	// If we didn't find a matching cookie, quit now

	if (cookie == null) return;

	// The cookie value is the part after the equals sign

	var cookieval = cookie.substring(name.length+1);

	// Now that we've extracted the value of the named cookie, we
	// must break that value down into individual state variable 
	// names and values. The name/value pairs are separated from each
	// other by ampersands, and the individual names and values are
	// separated from each other by colons. We use the split() method
	// to parse everything.

	var a = cookieval.split('&');	// Break it into an array of name/value pairs
	for(var i=0; i < a.length; i++) // Break each pair into an array
	a[i] = a[i].split(':');

	// Now that we've parsed the cookie value, set all the names and values
	// as properties of this Cookie object. Note that we decode
	// the property value because the store() method encodes it
	
	for(var i = 0; i < a.length; i++) {
		this[a[i][0]] = decodeURIComponent(a[i][1]);
	}
}

/**
* This function is the store() method of the Cookie object.
*
* Arguments:
*
* daysToLive: the lifetime of the cookie, in days. If you set this
* to zero, the cookie will be deleted. If you set it to null, or 
* omit this argument, the cookie will be a session cookie and will
* not be retained when the browser exits. This argument is used to
* set the max-age attribute of the cookie.
* path: the value of the path attribute of the cookie
* domain: the value of the domain attribute of the cookie
* secure: if true, the secure attribute of the cookie will be set
*/

Cookie.prototype.store = function(daysToLive, path, domain, secure) {

	// First, loop through the properties of the Cookie object and
	// put together the value of the cookie. Since cookies use the
	// equals sign and semicolons as separators, we'll use colons
	// and ampersands for the individual state variables we store 
	// within a single cookie value. Note that we encode the value
	// of each property in case it contains punctuation or other
	// illegal characters.

	var cookieval = "";

	for(var prop in this) {
	
		// Ignore properties with names that begin with '$' and also methods
 
		if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function')) 
		continue;
		if (cookieval != "") cookieval += '&';
		cookieval += prop + ':' + encodeURIComponent(this[prop]);
	}

	// Now that we have the value of the cookie, put together the 
	// complete cookie string, which includes the name and the various
	// attributes specified when the Cookie object was created
	
	var cookie = this.$name + '=' + cookieval;
	if (daysToLive || daysToLive == 0) { 
		cookie += "; max-age=" + (daysToLive*24*60*60);
	}

	if (path) cookie += "; path=" + path;
	if (domain) cookie += "; domain=" + domain;
	if (secure) cookie += "; secure";

	// Now store the cookie by setting the magic Document.cookie property
	
	document.cookie = cookie;
}

/**
* This function is the remove() method of the Cookie object; it deletes the
* properties of the object and removes the cookie from the browser's 
* local store.
* 
* The arguments to this function are all optional, but to remove a cookie
* you must pass the same values you passed to store().
*/

Cookie.prototype.remove = function(path, domain, secure) {

	// Delete the properties of the cookie

	for(var prop in this) {
		if (prop.charAt(0) != '$' && typeof this[prop] != 'function') 
		delete this[prop];
	}

	// Then, store the cookie with a lifetime of 0
	
	this.store(0, path, domain, secure);
}

/**
* This static method attempts to determine whether cookies are enabled.
* It returns true if they appear to be enabled and false otherwise.
* A return value of true does not guarantee that cookies actually persist.
* Nonpersistent session cookies may still work even if this method 
* returns false.
*/

Cookie.enabled = function() {

	// Use navigator.cookieEnabled if this browser defines it

	if (navigator.cookieEnabled != undefined) return navigator.cookieEnabled;

	// If we've already cached a value, use that value
	
	if (Cookie.enabled.cache != undefined) return Cookie.enabled.cache;

	// Otherwise, create a test cookie with a lifetime
	
	document.cookie = "testcookie=test; max-age=10000"; // Set cookie

	// Now see if that cookie was saved
	
	var cookies = document.cookie;
	if (cookies.indexOf("testcookie=test") == -1) {
	
		// The cookie was not saved

		return Cookie.enabled.cache = false;
	} else {
	
		// Cookie was saved, so we've got to delete it before returning
	
		document.cookie = "testcookie=test; max-age=0"; // Delete cookie
		return Cookie.enabled.cache = true;
	}
}

/**
* save the property search parameters each time the search button is clicked
*/

// define arrays of form field names

var quick_fields = new Array (
		'search_type'
	,	'town'
	,	'bedrooms'
	,	'minprice'
	,	'maxprice'
	,	'rentalperiod'
	,	'include_sold_stc'
);

var advanced_fields = new Array (
		'search_type'
	,	'town'
	,	'bedrooms'
	,	'minprice'
	,	'maxprice'
	,	'propertytype'
	,	'rentalperiod'
	,	'include_sold_stc'
);

var swap_fields = new Array (
		'minprice'
	,	'maxprice'
);

function save_search(search_form_name) {

	// create the cookie object or load it's data if it already exists

	var cookie = new Cookie(search_form_name);

	if (Cookie.enabled()) {

		// determine which form fields to save

		var form_fields  = new Array;
		if (search_form_name == 'dezrez_quick_search') {
			form_fields = quick_fields;
		} else {
			form_fields = advanced_fields;
		}

		// save required form field selections
	
		for (var n = 0; n < form_fields.length; n++ ) {
			var field_name = form_fields[n];
			if ((search_form_name == 'dezrez_advanced_search') && (field_name == 'town')) {
				search_form = document.getElementById(search_form_name);
				var town_array = new Array;
				town_array  = search_form.town;
				var checked_towns = '';
				for (var m = 0; m < town_array.length; m++ ) {
					var town = town_array[m];
					if (town.checked) {
						if (checked_towns.length) {
							checked_towns = checked_towns + '+';
						}
						checked_towns = checked_towns + town.value;
					}
				}
				// debug('saving ' + field_name + ' = ' + checked_towns);
				cookie[field_name] = checked_towns;
			} else {
				if (field_name == 'rentalperiod') {
					field_value = document[search_form_name].rentalperiod.value;
				} else if (field_name == 'include_sold_stc') {
					field_value = document[search_form_name].include_sold_stc.checked;
				} else {
					var form_elm = document.getElementById(field_name);
					field_value = form_elm.selectedIndex;
				}
				// debug('saving ' + field_name + ' = ' + field_value);
				cookie[field_name] = field_value;
			}
		}

		// save the cooie for 24 hours

		cookie.store(1,'/');

	} else {
		alert("WARNING!\n\nYour browser has cookies disabled\nIt will not be possible to save your search settings");
	}
}

/**
* restore the property search parameters each time a page is loaded
*/

function restore_search(search_form_name) {

	// create the cookie object or load it's data if it already exists

	var cookie = new Cookie(search_form_name);

	// don't do anything if cookie is empty

	if (cookie == null) {
		return;

	// otherwise restore search settings from cookie
	
	} else {

		// determine which form fields to restore

		var form_fields  = new Array;
		if (search_form_name == 'dezrez_quick_search') {
			form_fields = quick_fields;
		} else {
			form_fields = advanced_fields;
		}

		// restore form field selections
	
		for (var n = 0; n < form_fields.length; n++ ) {
			var field_name = form_fields[n];
			if ((search_form_name == 'dezrez_advanced_search') && (field_name == 'town')) {
				var checked_towns = new Array;
				var checked_town_str = cookie[field_name];
				if (checked_town_str) {
					checked_towns = checked_town_str.split('+');
					search_form = document.getElementById(search_form_name);
					town_array  = search_form.town;
					for (var m = 0; m < checked_towns.length; m++ ) {
						var town_code = checked_towns[m];
						for (var p = 0; p < town_array.length; p++ ) {
							var town = town_array[p];
							if (town.value == town_code) {
								town.checked = true;
								// debug('setting ' + town_code + ' to checked');
								break;
							}
						}
					}
				}
			} else {
				var form_elm = document.getElementById(field_name);
				var field_value = cookie[field_name];
				if (field_value) {
					if (field_name == 'rentalperiod') {
						form_elm.value = field_value;
					} else if (field_name == 'include_sold_stc') {
						if (field_value == 'true') { 
							form_elm.checked = true;
						} else {
							form_elm.checked = false;
						}
					} else {
						form_elm.selectedIndex = field_value;
					}
					// debug('restoring ' + field_name + ' = ' + field_value);
				}
			}
		}

		// Check if we need to re-run swap menu

		if (search_form_name == 'dezrez_quick_search') {
			if ( cookie.search_type == 2 ) {
				swap_menu( false, search_form_name );
				for (var n = 0; n < swap_fields.length; n++ ) {
					var form_elm = document.getElementById(swap_fields[n]);
					var field_value = cookie[swap_fields[n]];
					form_elm.selectedIndex = field_value;
				}
			}
		} else {
			if ( cookie.search_type == 1 ) {
				swap_menu( false, search_form_name );
				for (var n = 0; n < swap_fields.length; n++ ) {
					var form_elm = document.getElementById(swap_fields[n]);
					var field_value = cookie[swap_fields[n]];
					form_elm.selectedIndex = field_value;
				}
			}
		}
	}
}
