var Atom = {};  // Declare Atom namespace
Atom.Debug = {};  // Declare Atom namespace
var Vreb = {};  // Declare Vreb namespace
Vreb.OH = {};  // Declare Vreb.OH namespace
//AtomVreb.warn = function (msg) {
//	alert(msg);
//}


var strOpenHouseAjaxProvider = '/buying/open_house_app.code.php';

// Mozilla stores the line number in the lineNumber property and Opera appends
// it to the message property.
window.onerror = function (err, file, line) {
	var s_ERROR = "";

	s_ERROR += 'The following error occured:\n';
	s_ERROR += 'Error [' + err + ']\n';
	s_ERROR += 'File  [' + file + ']\n';
	s_ERROR += 'Line  [' + line + ']\n';
	/*
	 for (var i in err) {
	 s_ERROR += i + ' = ' + err[i] +'\n';
	 };
	 */

	if (window.onerror.caller === null) {
		s_ERROR += 'CallLevel was called from the top level\n';
	}
	else {
		s_ERROR += 'CallLevel was called by another function.' + window.onerror.caller;
	}
	alert(s_ERROR);
	return true;
};


Vreb.OH.pre_select_do_search_count_waiting = 0;
Vreb.OH.s_loading_html = '<img src="/images/ajax-loader-0.gif" alt="Loading data">';


// ############################################################################
// Function: new_window()
// Purpose:  create and populate a new window with a url
// Inputs:
// Returns:
// Modifies:
// ############################################################################
function new_window() {
}

function show_popup() {
}

function pre_select_set_defaults() {
}

Vreb.OH.pre_select_add_handlers = function () {
	//debugit('Vreb.OH.pre_select_add_handlers');
	var aryMapLinks = $A($$('#pnlPsWhereMap area'));
	var aryWhereCheckboxes = $$('#pnlPsWhere input.cbx');
	var aryWhereLabels = $A($$('#pnlPsWhere label.lblPsWhere'));

	var aryWhenCheckboxes = $$('#pnlPsWhen input.cbx');
	var aryWhenLabels = $A($$('#pnlPsWhen label.lblPsWhen'));

	var aryWhatCheckboxes = $$('#pnlPsWhat input.cbx');
	var aryWhatLabels = $A($$('#pnlPsWhat label.lblPsWhat'));

	// --------------------------------------------------------------------------
	// Set all Where Checkboxes to unchecked except for the Where=Any Checkbox
	// --------------------------------------------------------------------------
	aryWhereCheckboxes.each(function (item) {
		item.checked = false;
	});
	aryWhereLabels.invoke('removeClassName', 'cbxLblChecked');
	$("lblPsWhereZZ").addClassName('cbxLblChecked');
	$("cbxPsWhereZZ").checked = true;


	// --------------------------------------------------------------------------
	// Add event handler for clicks on "Where" areas on the image map
	// --------------------------------------------------------------------------
	aryMapLinks.each(function (item) {
		var strMapAreaId = item.id;
		$(strMapAreaId).observe(
			'click',
			function (e) {
				//debugit("-------------------------");
				//debugit("MAP Clicked:" + strMapAreaId);

				var intLength = strMapAreaId.length;
				var strDistrictId = strMapAreaId.substring(intLength - 2, intLength);


				//debugit("strDistrictId:" + strDistrictId);
				//toggleWhereCheckbox(strDistrictId);
				var cbxPsWhere = $("cbxPsWhere" + strDistrictId);
				var lblPsWhere = $("lblPsWhere" + strDistrictId);

				if (!cbxPsWhere) {
					alert(strMapAreaId + " does not exist on the page!");
					return false;
					//return;
				}


				if (cbxPsWhere.disabled) {
					lblPsWhere.removeClassName('cbxLblChecked');
					return true;
					//return;
				}

				if (strDistrictId == "ZZ") {

					if (cbxPsWhere.checked) {
						//debugit(cbxPsWhere.id + " is checked");
						cbxPsWhere.checked = false;
						lblPsWhere.removeClassName('cbxLblChecked');
					}
					else {
						//debugit(cbxPsWhere.id + " is not checked");
						aryWhereCheckboxes.each(function (item) {
							item.checked = false;
						});
						aryWhereLabels.invoke('removeClassName', 'cbxLblChecked');
						cbxPsWhere.checked = true;
						lblPsWhere.addClassName('cbxLblChecked');
					}

					Vreb.OH.pre_select_do_search_count();

					return true;
					//return;
				}

				$("lblPsWhereZZ").removeClassName('cbxLblChecked');
				$("cbxPsWhereZZ").checked = false;


				if (cbxPsWhere.checked) {
					cbxPsWhere.checked = false;
					lblPsWhere.removeClassName('cbxLblChecked');
				}
				else {
					cbxPsWhere.checked = true;
					lblPsWhere.addClassName('cbxLblChecked');
				}


				Vreb.OH.pre_select_do_search_count();

				return true;
				//return;

			}
		);
		//debugit(strMapAreaId);


	});

	// --------------------------------------------------------------------------
	// Add event handler for clicks on "Where" checkbox
	// --------------------------------------------------------------------------
	aryWhereCheckboxes.each(
		function (item) {

			var strWhereCheckboxId = item.id;
			$(strWhereCheckboxId).observe(
				'click',
				function (e) {
					//debugit("-------------------------");
					//debugit("Checkbox Clicked:" + strWhereCheckboxId);
					var intLength = strWhereCheckboxId.length;
					var strDistrictId = strWhereCheckboxId.substring(intLength - 2, intLength);
					//debugit("strDistrictId:" + strDistrictId);
					//debugit("strDistrictId2:" + strDistrictId2);
					var cbxPsWhere = $("cbxPsWhere" + strDistrictId);
					var lblPsWhere = $("lblPsWhere" + strDistrictId);

					if (cbxPsWhere.disabled) {
						lblPsWhere.removeClassName('cbxLblChecked');
						return true;
						//return;
					}

					// --------------------------------------------------------------------
					// When the user has clicked on the "Any" label, we want to remove the
					// checks from all other districts and remove the checked class from
					// their corresponding labels
					// --------------------------------------------------------------------
					if (strDistrictId == "ZZ") {
						if (cbxPsWhere.checked) {
							//debugit(cbxPsWhere.id + " is checked");
							aryWhereCheckboxes.each(function (item) {
								item.checked = false;
							});
							aryWhereLabels.invoke('removeClassName', 'cbxLblChecked');
							lblPsWhere.addClassName('cbxLblChecked');
							cbxPsWhere.checked = true;
						}
						else {
							//debugit(cbxPsWhere.id + " is not checked");
							lblPsWhere.removeClassName('cbxLblChecked');
						}
						Vreb.OH.pre_select_do_search_count();
						return true;
					}

					$("lblPsWhereZZ").removeClassName('cbxLblChecked');
					$("cbxPsWhereZZ").checked = false;

					if (cbxPsWhere.checked) {
						//debugit(cbxPsWhere.id + " is checked");
						lblPsWhere.addClassName('cbxLblChecked');
					}
					else {
						//debugit(cbxPsWhere.id + " is not checked");
						lblPsWhere.removeClassName('cbxLblChecked');
					}

					Vreb.OH.pre_select_do_search_count();

					return true;

				}
			);
		}
	);

	// --------------------------------------------------------------------------
	// Add event handler for clicks on "When" checkbox
	// --------------------------------------------------------------------------
	aryWhenCheckboxes.each(
		function (item) {
			var strWhenCheckboxId = item.id;
			$(strWhenCheckboxId).observe(
				'click',
				function (e) {
					//debugit("-------------------------");
					//debugit("WHEN Checkbox Clicked:" + strWhenCheckboxId);
					var intLength = strWhenCheckboxId.length;
					var intDateNumber = strWhenCheckboxId.substring(intLength - 1, intLength);
					//debugit("intDateNumber:" + intDateNumber);

					var cbxPsWhen = $("cbxPsWhen" + intDateNumber);
					var lblPsWhen = $("lblPsWhen" + intDateNumber);

					if (cbxPsWhen.disabled) {
						lblPsWhen.removeClassName('cbxLblChecked');
						return true;
						//return;
					}


					// --------------------------------------------------------------------
					// When the user has clicked on the "Any" label, we want to remove the
					// checks from all other dates and remove the checked class from
					// their corresponding labels
					// --------------------------------------------------------------------
					if (intDateNumber == "0") {
						if (cbxPsWhen.checked) {
							//debugit(cbxPsWhen.id + " is checked");
							aryWhenCheckboxes.each(function (item) {
								item.checked = false;
							});
							aryWhenLabels.invoke('removeClassName', 'cbxLblChecked');
							lblPsWhen.addClassName('cbxLblChecked');
							cbxPsWhen.checked = true;
						}
						else {
							//debugit(cbxPsWhen.id + " is not checked");
							lblPsWhen.removeClassName('cbxLblChecked');
						}
						Vreb.OH.pre_select_do_search_count();
						return true;
					}

					// --------------------------------------------------------------------
					// When the user has clicked on the "Any" label, we want to remove the
					// checks from all other dates and remove the checked class from
					// their corresponding labels
					// --------------------------------------------------------------------
					else if (intDateNumber == "8") {
						if (cbxPsWhen.checked) {
							//debugit(cbxPsWhen.id + " is checked");
							aryWhenCheckboxes.each(function (item) {
								item.checked = false;
							});
							aryWhenLabels.invoke('removeClassName', 'cbxLblChecked');
							lblPsWhen.addClassName('cbxLblChecked');
							cbxPsWhen.checked = true;
						}
						else {
							//debugit(cbxPsWhen.id + " is not checked");
							lblPsWhen.removeClassName('cbxLblChecked');
						}
						Vreb.OH.pre_select_do_search_count();
						return true;
					}

					else {
						$("lblPsWhen8").removeClassName('cbxLblChecked');
						$("cbxPsWhen8").checked = false;
						$("lblPsWhen0").removeClassName('cbxLblChecked');
						$("cbxPsWhen0").checked = false;
					}


					if (cbxPsWhen.checked) {
						//debugit(cbxPsWhen.id + " is checked");
						lblPsWhen.addClassName('cbxLblChecked');
					}
					else {
						//debugit(cbxPsWhen.id + " is not checked");
						lblPsWhen.removeClassName('cbxLblChecked');
					}

					Vreb.OH.pre_select_do_search_count();

					return true;

				}
			);
		}
	);


	// --------------------------------------------------------------------------
	// Add event handler for clicks on "What" checkbox
	// --------------------------------------------------------------------------
	aryWhatCheckboxes.each(
		function (item) {
			var strWhatCheckboxId = item.id;
			$(strWhatCheckboxId).observe(
				'click',
				function (e) {
					//debugit("-------------------------");
					//debugit("WHAT Checkbox Clicked:" + strWhatCheckboxId);
					var intLength = strWhatCheckboxId.length;
					var strListingType = strWhatCheckboxId.substring(9, intLength);
					//debugit("strListingType:" + strListingType);

					var cbxPsWhat = $("cbxPsWhat" + strListingType);
					var lblPsWhat = $("lblPsWhat" + strListingType);

					if (cbxPsWhat.disabled) {
						lblPsWhat.removeClassName('cbxLblChecked');
						return true;
						//return;
					}


					// --------------------------------------------------------------------
					// When the user has clicked on the "Any" label, we want to remove the
					// checks from all other dates and remove the checked class from
					// their corresponding labels
					// --------------------------------------------------------------------
					if (strListingType == "ZZ") {
						if (cbxPsWhat.checked) {
							//debugit(cbxPsWhat.id + " is checked");
							aryWhatCheckboxes.each(function (item) {
								item.checked = false;
							});
							aryWhatLabels.invoke('removeClassName', 'cbxLblChecked');
							lblPsWhat.addClassName('cbxLblChecked');
							cbxPsWhat.checked = true;
						}
						else {
							//debugit(cbxPsWhat.id + " is not checked");
							lblPsWhat.removeClassName('cbxLblChecked');
						}
						Vreb.OH.pre_select_do_search_count();
						return true;
					}

					else {
						$("lblPsWhatZZ").removeClassName('cbxLblChecked');
						$("cbxPsWhatZZ").checked = false;
					}

					if (cbxPsWhat.checked) {
						//debugit(cbxPsWhat.id + " is checked");
						lblPsWhat.addClassName('cbxLblChecked');
					}
					else {
						//debugit(cbxPsWhat.id + " is not checked");
						lblPsWhat.removeClassName('cbxLblChecked');
					}

					Vreb.OH.pre_select_do_search_count();

					return true;

				}
			);
		}
	);

	// --------------------------------------------------------------------------
	// Add event handler for change and blur on selPriceTo
	// --------------------------------------------------------------------------
	//var objSelPriceTo = $('selPriceTo');
	$('selPriceTo').observe(
		'change',
		function (e) {
			//debugit("-------------------------");
			var objSelPriceFrom = $('selPriceFrom');
			var objSelPriceTo = $('selPriceTo');
			var intPriceFrom = parseInt(objSelPriceFrom.value, 10);
			var intPriceTo = parseInt(objSelPriceTo.value, 10);
			while ((intPriceTo > 0) && (intPriceFrom > 0) && (intPriceFrom >= intPriceTo )) {
				objSelPriceFrom.selectedIndex = objSelPriceFrom.selectedIndex - 1;
				intPriceFrom = parseInt(objSelPriceFrom.value, 10);
				intPriceTo = parseInt(objSelPriceTo.value, 10);
			}
			Vreb.OH.pre_select_do_search_count();
		}
	);

	// --------------------------------------------------------------------------
	// Add event handler for change and blur on selPriceFrom
	// --------------------------------------------------------------------------
	//var objSelPriceFrom = $('selPriceFrom');
	$('selPriceFrom').observe(
		'change',
		function (e) {
			//debugit("-------------------------");
			var objSelPriceFrom = $('selPriceFrom');
			var objSelPriceTo = $('selPriceTo');
			var intPriceFrom = parseInt(objSelPriceFrom.value, 10);
			var intPriceTo = parseInt(objSelPriceTo.value, 10);
			//debugit("selPriceFrom Changed:" + intPriceFrom);
			//debugit("selPriceFrom   Index:" + objSelPriceFrom.selectedIndex);
			//debugit("selPriceTo value:" + intPriceTo);
			while ((intPriceTo > 0) && (intPriceFrom > 0) && (intPriceTo <= intPriceFrom)) {
				//debugit("TO: (" + intPriceTo + ") LESSS/EQ  FROM: (" + intPriceFrom + ")");
				intPriceFrom = parseInt(objSelPriceFrom.value, 10);
				intPriceTo = parseInt(objSelPriceTo.value, 10);
				objSelPriceTo.selectedIndex = objSelPriceTo.selectedIndex + 1;
				//debugit("selPriceFrom NOW:" + objSelPriceFrom.value);
				//debugit("selPriceTo NOW:" + objSelPriceTo.value);
			}
			Vreb.OH.pre_select_do_search_count();
		}
	);

	// --------------------------------------------------------------------------
	// Add event handler for change and blur on selBedrooms
	// --------------------------------------------------------------------------
	//var objSelBedrooms = $('selBedrooms');
	$('selBedrooms').observe(
		'change',
		function (e) {
			//debugit("-------------------------");
			//debugit("selBedrooms Changed:" + objSelBedrooms.value);
			//debugit("selBedrooms   Index:" + objSelBedrooms.selectedIndex);
			Vreb.OH.pre_select_do_search_count();
		}
	);


	// --------------------------------------------------------------------------
	// Add event handler for change and blur on selBathrooms
	// --------------------------------------------------------------------------
	//var objSelBathrooms = $('selBathrooms');
	$('selBathrooms').observe(
		'change',
		function (e) {
			//debugit("-------------------------");
			//debugit("selBathrooms Changed:" + objSelBathrooms.value);
			//debugit("selBathrooms   Index:" + objSelBathrooms.selectedIndex);
			Vreb.OH.pre_select_do_search_count();
		}
	);


	// --------------------------------------------------------------------------
	// Add event handler for key events on txtMLS
	// --------------------------------------------------------------------------
	//var txtMLS = $('txtMLS');
	$('txtMLS').observe(
		'keyup',
		function (e) {
			// remove all characters except numbers, spaces, comma and semi-colon
			this.value = this.value.replace(/[^0-9;, ]+/g, ' ');
			this.value = this.value.replace(/\s+/g, ' ');
			this.value = this.value.replace(/^\s+/g, '');

			aValid = pre_select_mls_text_clean();

			// If the user pressed the enter key in the text area, we validate the input and if ok, we submit the frm
			if (aValid.length > 0) {
				if ((e.keyCode === 13)) {
					$('frmPreSelect').submit();
					return false;
				}
				//else {
				//}
			}
			Vreb.OH.pre_select_do_search_count();
		}
	);


}

/**
 *
 */
function pre_select_mls_text_clean() {
	// if the string is empty or in range we are going to validate the input
	var mls = $('txtMLS').value.split(/[^\d]/g);
	mls2 = Array();


	mls.each(function (item, index) {
		debug.info("mls2.item " + item);
		item = parseInt(item, 10);
		if ((item >= Vreb.OH.MlsMin) && (item <= Vreb.OH.MlsMax)) {
			debug.info("(item >= Vreb.OH.MlsMin) " + (item >= Vreb.OH.MlsMin));
			debug.info("(item <= Vreb.OH.MlsMax) " + (item <= Vreb.OH.MlsMax));
			mls2.push(item);
		}
	});
	debug.info("mls2.length " + mls2.length);
	debug.info("Vreb.OH.MlsMax " + Vreb.OH.MlsMax);
	debug.info("Vreb.OH.MlsMin " + Vreb.OH.MlsMin);

	//mls2.each(function (item, index) {
	//	debug.info("mls2.item[" + index + "] " + item);
	//});
	//debug.info("mls2.length " + mls2.length);
	debug.info("mls2[" + mls2 + "]");
	return mls2;
}

function pre_select_where_change_list() {
}

function pre_select_where_change_map() {
}

function pre_select_date_change() {
}

function pre_select_property_type_change() {
}

function pre_select_price_from_change() {
}

function pre_select_price_to_change() {
}

Atom.Debug.debugClear = function () {
	$('pnlDebug').update("");
}

function debugit(strMessage) {
	return;
	$('pnlDebug').update($('pnlDebug').innerHTML + '<br>' + strMessage);
}

function toggleWhereCheckbox(strDistrictId) {
	var cbxWhere = $("where-" + strDistrictId);
	var lblWhere = $("lbl-where-" + strDistrictId);

	if (cbxWhere.checked) {
		cbxWhere.checked = false;
		lblWhere.removeClassName('cbxLblChecked');
	}
	else {
		cbxWhere.checked = true;
		lblWhere.addClassName('cbxLblChecked');
	}
}

function pre_select_remove_handlers() {
}

function pre_select_summary_update() {
}

function pre_select_get_search_criteria() {
}

Vreb.OH.gatherPreselectFormData = function () {
	//debugit('gatherPreselectFormData');
	var h_params = $('frmPreSelect').serialize(true);
	h_params['mode'] = '99';
	return h_params;
}

function gatherResultSelectionFormData() {
	//debugit('gatherResultSelectionFormData');
	var h_params = $('frmRsResults').serialize(true);
	h_params['mode'] = '4';
	return h_params;
}


/**
 *
 */
Vreb.OH.pre_select_do_search_count = function () {

	Vreb.OH.pre_select_do_search_count_waiting++;

	if (Vreb.OH.pre_select_do_search_count_waiting > 1) {
		//debugit("Already running pre_select_do_search_count");
		return;
	}


	$('lblExpectedResultCount').update(Vreb.OH.s_loading_html);


	new Ajax.Updater(
		{ success:'lblExpectedResultCount', failure:'pnlPreSelectSummaryFail' },
		strOpenHouseAjaxProvider,
		{
			method:'post',
			EvalScripts:true,
			parameters:Vreb.OH.gatherPreselectFormData(),
			onSuccess:function (transport) {
				//debugit("onSuccess:pre_select_do_search_count");
				//pre_select_do_search_count_waiting--;
			},
			onFailure:function (transport) {
				//debugit("onFailure:pre_select_do_search_count");
				//pre_select_do_search_count_waiting--;
			},
			onComplete:function () {
				//debugit("onComplete:pre_select_do_search_count");
				Vreb.OH.pre_select_do_search_count_waiting--;
				//debugit("onComplete:pre_select_do_search_count_waiting = " + pre_select_do_search_count_waiting);
				if (Vreb.OH.pre_select_do_search_count_waiting > 0) {
					Vreb.OH.pre_select_do_search_count_waiting = 0;
					Vreb.OH.pre_select_do_search_count();
				}
			}
		}
	);

}

Vreb.OH.results_add_select_handlers = function () {

	//debugit("--------------------------------------------------------------------------------");
	//debugit("results_add_select_handlers()");
	//debugit("--------------------------------------------------------------------------------");


	var aryCheckboxes = $$('#pnlOhResults .tblRecord input.cbx');


	var lnkOhAddAll = $('pnlOhResultsSummaryAddAll');
	var lnkOhRemoveAll = $('pnlOhResultsSummaryRemoveAll');


	if (lnkOhAddAll !== null) {
		// --------------------------------------------------------------------------
		// Add event handler for clicks on "Open House Add All" link
		// --------------------------------------------------------------------------
		$(lnkOhAddAll).observe(
			'click',
			function (e) {
				//debugit("-------------------------");
				//debugit("lnkOhAddAll Clicked:" + lnkOhAddAll.innerHTML);
				// --------------------------------------------------------------------------
				// Handles clicks on "Add All nn" linkButton
				// --------------------------------------------------------------------------
				var aryCheckboxes = $$('#pnlOhResults .tblRecord input.cbx');
				aryCheckboxes.each(
					function (item) {
						var strOhidCheckboxId = item.id;
						var intOhID = $(strOhidCheckboxId).value;
						//debugit("intOhID:" + intOhID);
						if ($(strOhidCheckboxId).checked === false) {
							$(strOhidCheckboxId).checked = true;
							Vreb.OH.setOpenHouseSelected(intOhID);
						}
					}
				);


			}
		);

	}


	// --------------------------------------------------------------------------
	// Add event handler for clicks on "Open House Remove All" link
	// --------------------------------------------------------------------------
	if (lnkOhAddAll !== null) {
		$(lnkOhRemoveAll).observe(
			'click',
			function (e) {
				//debugit("-------------------------");
				//debugit("lnkOhRemoveAll Clicked:" + lnkOhRemoveAll.innerHTML);


				// --------------------------------------------------------------------------
				// Handles clicks on "Remove All nn" linkButton
				// --------------------------------------------------------------------------
				var aryCheckboxes = $$('#pnlOhResults .tblRecord input.cbx');
				aryCheckboxes.each(
					function (item) {
						var strOhidCheckboxId = item.id;
						var intOhID = $(strOhidCheckboxId).value;
						//debugit("intOhID:" + intOhID);
						if ($(strOhidCheckboxId).checked === true) {
							$(strOhidCheckboxId).checked = false;
							Vreb.OH.setOpenHouseDeSelected(intOhID);
						}
					}
				);


			}
		);
	}


	// --------------------------------------------------------------------------
	// Add event handler for clicks on "Open House Select" checkbox
	// --------------------------------------------------------------------------
	aryCheckboxes.each(
		function (item) {
			var strOhidCheckboxId = item.id;
			//debugit("Adding Listener for " + item.id);
			$(strOhidCheckboxId).observe(
				'click',
				function (e) {
					//debugit("-------------------------");
					//debugit("Open House Select Checkbox Clicked:" + strOhidCheckboxId);
					var intOhID = $(strOhidCheckboxId).value;
					//debugit("intOhID:" + intOhID);

					if ($(strOhidCheckboxId).checked) {
						//debugit($(strOhidCheckboxId).value + " is checked");
						Vreb.OH.setOpenHouseSelected(intOhID);
					}
					else {
						//debugit($(strOhidCheckboxId).id + " is not checked");
						Vreb.OH.setOpenHouseDeSelected(intOhID);
					}
				}
			);
		}
	);
}

/**
 * @param intOhId
 */
Vreb.OH.setOpenHouseDeSelected = function (intOhId) {
	new Ajax.Updater(
		{ success:'pnlDebug', failure:'pnlOhError' },
		strOpenHouseAjaxProvider,
		{
			method:'post',
			evalScripts:true,
			parameters:{
				'mode':11,
				'ohid':intOhId
			}
		}
	);

	Vreb.OH.setOpenHouseSelectedCount();

	var intOpenHouseSelectedCountTotal = parseInt($('spnOpenHouseSelectedCountTotal').innerHTML, 10);
	$('spnOpenHouseSelectedCountTotal').update(intOpenHouseSelectedCountTotal - 1);

	if ((intOpenHouseSelectedCountTotal - 1) < 1) {
		$('btnPrint').disable();
		$('btnPrint').addClassName("disabled");

		$('btnSend').disable();
		$('btnSend').addClassName("disabled");
	}

}

Vreb.OH.setOpenHouseSelected = function (intOhId) {
	//debugit("setOpenHouseSelected");
	new Ajax.Updater(
		{ success:'pnlDebug', failure:'pnlOhError' },
		strOpenHouseAjaxProvider,
		{
			method:'post',
			evalScripts:true,
			parameters:{
				'mode':10,
				'ohid':intOhId
			}
		}
	);

	Vreb.OH.setOpenHouseSelectedCount();

	var intOpenHouseSelectedCountTotal = parseInt($('spnOpenHouseSelectedCountTotal').innerHTML, 10);
	$('spnOpenHouseSelectedCountTotal').update(intOpenHouseSelectedCountTotal + 1);
	$('btnPrint').enable();
	$('btnPrint').removeClassName("disabled");
	$('btnSend').enable();
	$('btnSend').removeClassName("disabled");

}

Vreb.OH.setOpenHouseSelectedCount = function () {
	var aryCheckboxes = $$('#pnlOhResults .tblRecord input.cbx');
	var iChecked = 0;
	aryCheckboxes.each(function (item) {
		if (item.checked) {
			iChecked++;
		}
	});
	var spnOpenHouseSelectedCount = $('spnOpenHouseSelectedCount');
	//debugit("aryCheckboxes.length" + iChecked);
	spnOpenHouseSelectedCount.update(iChecked);
}

function results_remove_select_handlers() {
}

function results_add_pagination_handlers() {
}

Vreb.OH.results_add_view_handlers = function () {


	// --------------------------------------------------------------------------
	// Add event handler for clicks on "Open House Select" checkbox
	// --------------------------------------------------------------------------
	var aryRadioNames = $A(Array('radResFormatListTop', 'radResFormatThumbTop', 'radResFormatListBottom', 'radResFormatThumbBottom'));
	// --------------------------------------------------------------------------
	// Add event handler for clicks on "Sort Headers"
	// --------------------------------------------------------------------------
	aryRadioNames.each(
		function (strFormatRadioButtonId) {
			//debugit("Adding Listener for " + strFormatRadioButtonId);
			if ($(strFormatRadioButtonId) !== null) {
				$($(strFormatRadioButtonId)).observe(
					'click',
					function (event) {
						//debugit("-------------------------");
						//debugit("radResFormatListTop Radio Clicked:" + strFormatRadioButtonId);
						var objRadioButton = Event.element(event);


						var strDisplayMode = $('display_mode').value;
						//debugit("strDisplayMode:" + strDisplayMode);
						var intMode = (strDisplayMode == 'print') ? 44 : 48;


						var strRadioButtonId = objRadioButton.id;
						var strFormatSelected = objRadioButton.value;


						if (strFormatSelected == 'thumb') {
							$('radResFormatThumbTop').checked = true;
							$('radResFormatThumbBottom').checked = true;
						}
						else {
							$('radResFormatListTop').checked = true;
							$('radResFormatListBottom').checked = true;
						}

						//debugit("strRadioButtonId:" + strRadioButtonId);
						//debugit("strFormatSelected:" + strFormatSelected);


						var aryUrlAndQuery = document.URL.split('?');
						var strUrlBase = aryUrlAndQuery[0];
						var strNewUrl = strUrlBase + '?mode=' + intMode + '&format=' + strFormatSelected;

						//debugit("strUrlBase:" + strUrlBase);
						//debugit("strNewUrl:" + strNewUrl);


						//return;

						window.location.href = strNewUrl;

						return;

					}
				);
			}


		}
	);

}

function result_selection_changed() {
}

Vreb.OH.results_add_action_handlers = function () {

	var btnResults = $('btnResults');
	// --------------------------------------------------------------------------
	// Add event handler for clicks on "btnResults"
	// --------------------------------------------------------------------------

	if (btnResults !== null) {
		//debugit("Adding Listener for btnResults");
		btnResults.observe(
			'click',
			function (event) {
				//debugit("-------------------------");
				//debugit("btnResults Clicked:");
				//debugit("btnResults Clicked:");
				var aryUrlAndQuery = document.URL.split('?');
				var strUrlBase = aryUrlAndQuery[0];
				var strNewUrl = strUrlBase + '?mode=48&results=1'; // MODE_RESULTS_VIEW
				//debugit("strUrlBase:" + strUrlBase);
				//debugit("strNewUrl:" + strNewUrl);
				window.location.href = strNewUrl;
				return;
			}
		);

	}

	// --------------------------------------------------------------------------
	// Add event handler for clicks on "btnSend"
	// --------------------------------------------------------------------------
	var btnSend = $('btnSend');
	if (btnSend !== null) {
		//debugit("Adding Listener for btnSend");

		btnSend.observe(
			'click',
			function (event) {
				//debugit("-------------------------");
				//debugit("btnSend Clicked:");
				//debugit("btnSend Clicked:Save Selections");
				$('pnlOhResultsSend').show();
				$('pnlOhEmailControls').show();
				$('pnlOhEmailStatus').update("");
				$('pnlOhEmailStatus').hide();
				return;

			}
		);

	}


	// --------------------------------------------------------------------------
	// Add event handler for clicks on "btnSendEmail"
	// --------------------------------------------------------------------------
	var btnSendEmail = $('btnSendEmail');
	if (btnSendEmail !== null) {
		//debugit("Adding Listener for btnSendEmail");

		btnSendEmail.observe(
			'click',
			function (event) {
				//debugit("-------------------------");
				//debugit("btnSendEmail Clicked:");

				var strErrors = "";

				if (!is_valid_email($('txtEmailFrom').value)) {
					strErrors += "Email From: " + $('txtEmailFrom').value + " is not a valid email address.\n";
				}
				if (!is_valid_email($('txtEmailTo').value)) {
					strErrors += "Email To: " + $('txtEmailTo').value + " is not a valid email address.\n";
				}
				if (strErrors !== "") {
					alert(strErrors);
					return false;
				}

				//debugit("txtEmailFrom:" + $('txtEmailFrom').value);
				//debugit("txtEmailTo:" + $('txtEmailTo').value);


				$('pnlOhEmailControls').hide();
				$('pnlOhEmailStatus').show();
				$('pnlOhEmailStatus').update("<p>" + Vreb.OH.s_loading_html + "Sending email.... please wait.</p>");

				new Ajax.Updater(
					{ success:'pnlOhEmailStatus', failure:'pnlOhEmailStatus' },
					strOpenHouseAjaxProvider,
					{
						method:'post',
						evalScripts:true,
						parameters:{
							'mode':13, // MODE_SEND
							'from':$('txtEmailFrom').value,
							'to':$('txtEmailTo').value
						}
					}
				);

				return true;


			}
		);

	}

}

function results_remove_action_handlers() {
}

Vreb.OH.results_add_sort_handlers = function () {

	//debugit("--------------------------------------------------------------------------------");
	//debugit("results_add_sort_handlers()");
	//debugit("--------------------------------------------------------------------------------");


	var btnSort = $('btnSort');

	if (btnSort !== null) {
		btnSort.observe(
			'click',
			function (event) {

				var hashParams = $H({});


				var arySelectSortControls2 = $$('#pnlOhResultsSummarySort select');
				//alert("arySelectSortControls2.length " + arySelectSortControls2.length);

				arySelectSortControls2.each(
					function (objSelectControl) {
						var strSortControl = objSelectControl.id;
						var strSortValue1 = objSelectControl.value;
						var strSortName1 = objSelectControl.name;
						var strSortNumber = strSortName1.substring(strSortName1.length - 1, strSortName1.length);
						/*
						 //debugit("------------------------------------------------------------");
						 */
						if (!strSortValue1.match(/^(Address|Price|Bedrooms|Bathrooms|Mls|MapArea|LotSize|SizeUnFin|SizeFin|PropertyType|YearBuilt|DateTimes)-([ad])$/)) {
							//debugit("Nothing to do for " + strSortValue1);
							return;
						}

						var strSortField1 = strSortValue1.substring(0, strSortValue1.length - 2);
						var strSortDir = strSortValue1.substring(strSortValue1.length - 1, strSortValue1.length);

						/*
						 //debugit("strSortControl:" + strSortControl);
						 //debugit("strSortValue1:" + strSortValue1);
						 //debugit("strSortName1:" + strSortName1);
						 //debugit("strSortField1:" + strSortField1);
						 //debugit("strSortDir:" + strSortDir);
						 //debugit("strSortNumber:" + strSortNumber);
						 */

						// 15/10/2009 1:41:28 PM apugh
						// Backwards compatibility changes in Prototype 1.6

						//hashParams['sort'+strSortNumber] = strSortField1;
						//hashParams['dir'+strSortNumber] = strSortDir;

						hashParams.set('sort' + strSortNumber, strSortField1);
						hashParams.set('dir' + strSortNumber, strSortDir);

					}
				);


				var aryUrlAndQuery = document.URL.split('?');
				var strUrlBase = aryUrlAndQuery[0];
				var strNewUrl = strUrlBase + '?mode=43&' + (hashParams.toQueryString());


				/*
				 //debugit("hashParams:" + hashParams);
				 //debugit("hashParams.toQueryString():" + hashParams.toQueryString());
				 //debugit("strUrlBase:" + strUrlBase);
				 //debugit("strNewUrl:" + strNewUrl);
				 */
				window.location.href = strNewUrl;

				return;


			}
		);

	}

	var aryHeaderDivs = $$('#pnlOhResults .tblHeader div');

	// --------------------------------------------------------------------------
	// Add event handler for clicks on "Sort Headers"
	// --------------------------------------------------------------------------
	aryHeaderDivs.each(
		function (item) {
			var strHeaderId = item.id;
			$(strHeaderId).observe(
				'click',
				function (e) {

					//debugit("-------------------------");

					var objHeaderDiv = $(strHeaderId);

					//debugit("Header Clicked:" + strHeaderId);
					var strHeaderName = strHeaderId.substring(9, strHeaderId.length);
					//debugit("strHeaderName:" + strHeaderName);


					if (!strHeaderName.match(/^(Address|Price|Bedrooms|Bathrooms|Mls|MapArea|LotSize|SizeUnFin|SizeFin|PropertyType|YearBuilt|DateTimes)$/)) {
						//debugit("Nothing to do for " + strHeaderName);
						return;
					}


					var aryUrlAndQuery = document.URL.split('?');
					var strUrlBase = aryUrlAndQuery[0];
					var strNewUrl = strUrlBase + '?mode=43&sort=' + strHeaderName;


					//debugit("strUrlBase:" + strUrlBase);
					//debugit("strNewUrl:" + strNewUrl);
					window.location.href = strNewUrl;

					return;


				}
			);
		}
	);


}

Vreb.OH.results_add_image_control_handler = function () {

	//debugit("--------------------------------------------------------------------------------");
	//debugit("results_add_image_control_handler()");
	//debugit("--------------------------------------------------------------------------------");

	var aryImageControllers = $$('#pnlOhResults .thumbPhoto .btnPhotoNav');
	//debugit("aryImageControllers = " + aryImageControllers);

	// --------------------------------------------------------------------------
	// Add event handler for clicks on "Sort Headers"
	// --------------------------------------------------------------------------
	aryImageControllers.each(
		function (item) {
			var strImageControllerId = item.id;
			$(strImageControllerId).observe(
				'click',
				function (e) {

					//debugit("-------------------------");

					var objHeaderDiv = $(strImageControllerId);

					//debugit("Button Clicked:" + strImageControllerId);


					// ------------------------------------------------------------------
					// Extract the open house id from the id of the id of the image
					// controller
					// ------------------------------------------------------------------
					var intOhid = parseInt(strImageControllerId.substring(7, strImageControllerId.length), 10);
					//debugit("intOhid:" + intOhid);

					// ------------------------------------------------------------------
					// Create a reference to the image object
					// ------------------------------------------------------------------
					var objImage = $('photo' + intOhid);
					//debugit("objImage:" + objImage);
					var strSrc = objImage.src;
					//debugit("strSrc:" + strSrc);
					//var aryMatches = strSrc.match(/(\d+)\.jpg/);
					//debugit("aryMatches:" + aryMatches);
					//var strImgNum = aryMatches[0];
					//debugit("strImgNum:" + strImgNum);


					var strImgNum = parseInt($('photoNum' + intOhid).innerHTML, 10);
					var strImgCount = parseInt($('photoCount' + intOhid).innerHTML, 10);
					//debugit("strImgNum:" + strImgNum);
					//debugit("strImgCount:" + strImgCount);


					var numIncrement = strImageControllerId.match(/Next/) ? 1 : -1;


					var strImgNumNew = parseInt(strImgNum + numIncrement, 10);
					//debugit("strImgNumNew:" + strImgNumNew);

					var strSrcNew = strSrc.replace(/(\d+)\.jpg/, strImgNumNew + '.jpg');
					//debugit("strSrcNew:" + strSrcNew);

					objImage.src = strSrcNew;

					$('photoNum' + intOhid).update(strImgNumNew);

					//debugit("strImgNumNew == 1:" + (strImgNumNew == 1));
					//debugit("strImgNumNew == strImgCount:" + (strImgNumNew == strImgCount));

					if (strImgNumNew == 1) {
						$('btnPrev' + intOhid).disable();
					}
					else {
						$('btnPrev' + intOhid).enable();
					}

					if (strImgNumNew == strImgCount) {
						$('btnNext' + intOhid).disable();
					}
					else {
						$('btnNext' + intOhid).enable();
					}

				}
			);
		}
	);

}

Vreb.OH.results_add_external_link_handlers = function () {

	//debugit("--------------------------------------------------------------------------------");
	//debugit("results_add_external_link_handlers()");
	//debugit("--------------------------------------------------------------------------------");
	$$('#pnlOhApplication a.external').each(
		function (objLink) {
			objLink.setAttribute('target', 'external');
			objLink.removeClassName('external');
		}
	);

	$$('#map img').each(
		function (objImage) {
			if (objImage.readAttribute('alt') === null) {
				objImage.setAttribute('alt', '');
			}
		}
	);

}

function results_remove_sort_handlers() {
}

function do_search_sort() {
}

function results_add_print_single_handlers() {
}

function results_remove_print_single_handlers() {
}

function is_valid_email(strEmail) {
	var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return(filter.test(strEmail));
}

function feedback_form_toggle() {
	$('pnlFeedback').toggle();
	$('pnlFeedbackForm').show();
	$('pnlFeedbackStatus').update("");
	$('txtName').value = "";
	$('txtEmail').value = "";
	$('txtComment').innerText = "";
	//$('txtComment').update("");
}

function feedback_form_post() {
	var s_sending_html = '<img src="/images/ajax-loader-0.gif" alt="Sending Email"><span>Sending Email:</span>';
	var strErrors = "";

	// ------------------------------------------------------------------------
	// Validate that comment is present
	// ------------------------------------------------------------------------
	if ($F('txtComment') === "") {
		strErrors += "-- A Comment is required to send the feedback form\n";
	}
	// ------------------------------------------------------------------------
	// Validate the email address is valid if provided
	// ------------------------------------------------------------------------
	if ($F('txtEmail') !== "") {
		if (is_valid_email($F('txtEmail')) === false) {
			strErrors += '-- This is not a valid email address\n';
		}
	}
	// ------------------------------------------------------------------------
	// Notify of errors if any
	// ------------------------------------------------------------------------
	if (strErrors !== "") {
		alert('The following error(s) occurred:\n' + strErrors);
		return;
	}
	// ------------------------------------------------------------------------
	// Display Ajax Loader
	// ------------------------------------------------------------------------
	$('pnlFeedbackStatus').update(s_sending_html);
	$('pnlFeedbackStatus').show();
	// ------------------------------------------------------------------------
	// Hide the form
	// ------------------------------------------------------------------------
	$('pnlFeedbackForm').hide();

	// ------------------------------------------------------------------------
	// Make the request
	// ------------------------------------------------------------------------
	new Ajax.Request(
		strOpenHouseAjaxProvider,
		{
			method:'post',
			EvalScripts:true,
			parameters:{
				'mode':55,
				'name':$F('txtName'),
				'email':$F('txtEmail'),
				'comment':$F('txtComment')
			},
			onSuccess:function (transport) {
				//alert("onSuccess");
				$('txtName').value = "";
				$('txtEmail').value = "";
				$('txtComment').update("");
				$('pnlFeedbackForm').hide();
				var strResponse = transport.responseText;
				$('pnlFeedbackStatus').update(strResponse);
				$('pnlFeedbackStatus').show();
				setTimeout(function () {
					$('pnlFeedback').hide();
				}, 4000);
			},
			onFailure:function (transport) {
				alert("onFailure");
				$('pnlFeedbackStatus').update(transport.responseText);
				$('pnlFeedbackStatus').show();
				$('pnlFeedbackForm').show();
			}
		}
	);
}

