// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================


/* SOURCE FILE: selectbox.js */

// HISTORY
// ------------------------------------------------------------------
// June 12, 2003: Modified up and down functions to support more than
//                one selected option
/*
DESCRIPTION: These are general functions to deal with and manipulate
select boxes. Also see the OptionTransfer library to more easily 
handle transferring options between two lists

COMPATABILITY: These are fairly basic functions - they should work on
all browsers that support Javascript.
*/


// -------------------------------------------------------------------
// hasOptions(obj)
//  Utility function to determine if a select object has an options array
// -------------------------------------------------------------------
function hasOptions(obj) {
	if (obj!=null && obj.options!=null) { return true; }
	return false;
	}

// -------------------------------------------------------------------
// selectUnselectMatchingOptions(select_object,regex,select/unselect,true/false)
//  This is a general function used by the select functions below, to
//  avoid code duplication
// -------------------------------------------------------------------
function selectUnselectMatchingOptions(obj,regex,which,only) {
	if (window.RegExp) {
		if (which == "select") {
			var selected1=true;
			var selected2=false;
			}
		else if (which == "unselect") {
			var selected1=false;
			var selected2=true;
			}
		else {
			return;
			}
		var re = new RegExp(regex);
		if (!hasOptions(obj)) { return; }
		for (var i=0; i<obj.options.length; i++) {
			if (re.test(obj.options[i].text)) {
				obj.options[i].selected = selected1;
				}
			else {
				if (only == true) {
					obj.options[i].selected = selected2;
					}
				}
			}
		}
	}
		
// -------------------------------------------------------------------
// selectMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Currently-selected options will not be changed.
// -------------------------------------------------------------------
function selectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",false);
	}
// -------------------------------------------------------------------
// selectOnlyMatchingOptions(select_object,regex)
//  This function selects all options that match the regular expression
//  passed in. Selected options that don't match will be un-selected.
// -------------------------------------------------------------------
function selectOnlyMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"select",true);
	}
// -------------------------------------------------------------------
// unSelectMatchingOptions(select_object,regex)
//  This function Unselects all options that match the regular expression
//  passed in. 
// -------------------------------------------------------------------
function unSelectMatchingOptions(obj,regex) {
	selectUnselectMatchingOptions(obj,regex,"unselect",false);
	}
	
// -------------------------------------------------------------------
// sortSelect(select_object)
//   Pass this function a SELECT object and the options will be sorted
//   by their text (display) values
// -------------------------------------------------------------------
function sortSelect(obj) {
	var o = new Array();
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
		}
	if (o.length==0) { return; }
	o = o.sort( 
		function(a,b) { 
			if ((a.text+"") < (b.text+"")) { return -1; }
			if ((a.text+"") > (b.text+"")) { return 1; }
			return 0;
			} 
		);

	for (var i=0; i<o.length; i++) {
		obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
		}
	}

// -------------------------------------------------------------------
// selectAllOptions(select_object)
//  This function takes a select box and selects all options (in a 
//  multiple select object). This is used when passing values between
//  two select boxes. Select all options in the right box before 
//  submitting the form so the values will be sent to the server.
// -------------------------------------------------------------------
function selectAllOptions(obj) {
	if (!hasOptions(obj)) { return; }
	for (var i=0; i<obj.options.length; i++) {
		obj.options[i].selected = true;
		}
	}
	
// -------------------------------------------------------------------
// moveSelectedOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  This function moves options between select boxes. Works best with
//  multi-select boxes to create the common Windows control effect.
//  Passes all selected values from the first object to the second
//  object and re-sorts each box.
//  If a third argument of 'false' is passed, then the lists are not
//  sorted after the move.
//  If a fourth string argument is passed, this will function as a
//  Regular Expression to match against the TEXT or the options. If 
//  the text of an option matches the pattern, it will NOT be moved.
//  It will be treated as an unmoveable option.
//  You can also put this into the <SELECT> object as follows:
//    onDblClick="moveSelectedOptions(this,this.form.target)
//  This way, when the user double-clicks on a value in one box, it
//  will be transferred to the other (in browsers that support the 
//  onDblClick() event handler).
// -------------------------------------------------------------------
function moveSelectedOptions(from,to) {
	// Unselect matching options, if required
	if (arguments.length>3) {
		var regex = arguments[3];
		if (regex != "") {
			unSelectMatchingOptions(from,regex);
			}
		}
	// Move them over
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
			to.options[index] = new Option( o.text, o.value, false, false);
			}
		}
	// Delete them from original
	for (var i=(from.options.length-1); i>=0; i--) {
		var o = from.options[i];
		if (o.selected) {
			from.options[i] = null;
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(from);
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}

// -------------------------------------------------------------------
// copySelectedOptions(select_object,select_object[,autosort(true/false)])
//  This function copies options between select boxes instead of 
//  moving items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copySelectedOptions(from,to) {
	var options = new Object();
	if (hasOptions(to)) {
		for (var i=0; i<to.options.length; i++) {
			options[to.options[i].value] = to.options[i].text;
			}
		}
	if (!hasOptions(from)) { return; }
	for (var i=0; i<from.options.length; i++) {
		var o = from.options[i];
		if (o.selected) {
			if (options[o.value] == null || options[o.value] == "undefined" || options[o.value]!=o.text) {
				if (!hasOptions(to)) { var index = 0; } else { var index=to.options.length; }
				to.options[index] = new Option( o.text, o.value, false, false);
				}
			}
		}
	if ((arguments.length<3) || (arguments[2]==true)) {
		sortSelect(to);
		}
	from.selectedIndex = -1;
	to.selectedIndex = -1;
	}

// -------------------------------------------------------------------
// moveAllOptions(select_object,select_object[,autosort(true/false)[,regex]])
//  Move all options from one select box to another.
// -------------------------------------------------------------------
function moveAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		moveSelectedOptions(from,to);
		}
	else if (arguments.length==3) {
		moveSelectedOptions(from,to,arguments[2]);
		}
	else if (arguments.length==4) {
		moveSelectedOptions(from,to,arguments[2],arguments[3]);
		}
	}

// -------------------------------------------------------------------
// copyAllOptions(select_object,select_object[,autosort(true/false)])
//  Copy all options from one select box to another, instead of
//  removing items. Duplicates in the target list are not allowed.
// -------------------------------------------------------------------
function copyAllOptions(from,to) {
	selectAllOptions(from);
	if (arguments.length==2) {
		copySelectedOptions(from,to);
		}
	else if (arguments.length==3) {
		copySelectedOptions(from,to,arguments[2]);
		}
	}

// -------------------------------------------------------------------
// swapOptions(select_object,option1,option2)
//  Swap positions of two options in a select list
// -------------------------------------------------------------------
function swapOptions(obj,i,j) {
	var o = obj.options;
	var i_selected = o[i].selected;
	var j_selected = o[j].selected;
	var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
	o[i] = temp2;
	o[j] = temp;
	o[i].selected = j_selected;
	o[j].selected = i_selected;
	}
	
// -------------------------------------------------------------------
// moveOptionUp(select_object)
//  Move selected option in a select list up one
// -------------------------------------------------------------------
function moveOptionUp(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=0; i<obj.options.length; i++) {
		if (obj.options[i].selected) {
			if (i != 0 && !obj.options[i-1].selected) {
				swapOptions(obj,i,i-1);
				obj.options[i-1].selected = true;
				}
			}
		}
	}

// -------------------------------------------------------------------
// moveOptionDown(select_object)
//  Move selected option in a select list down one
// -------------------------------------------------------------------
function moveOptionDown(obj) {
	if (!hasOptions(obj)) { return; }
	for (i=obj.options.length-1; i>=0; i--) {
		if (obj.options[i].selected) {
			if (i != (obj.options.length-1) && ! obj.options[i+1].selected) {
				swapOptions(obj,i,i+1);
				obj.options[i+1].selected = true;
				}
			}
		}
	}

// -------------------------------------------------------------------
// removeSelectedOptions(select_object)
//  Remove all selected options from a list
//  (Thanks to Gene Ninestein)
// -------------------------------------------------------------------
function removeSelectedOptions(from) { 
	if (!hasOptions(from)) { return; }
	for (var i=(from.options.length-1); i>=0; i--) { 
		var o=from.options[i]; 
		if (o.selected) { 
			from.options[i] = null; 
			} 
		} 
	from.selectedIndex = -1; 
	} 

// -------------------------------------------------------------------
// removeAllOptions(select_object)
//  Remove all options from a list
// -------------------------------------------------------------------
function removeAllOptions(from) { 
	if (!hasOptions(from)) { return; }
	for (var i=(from.options.length-1); i>=0; i--) { 
		from.options[i] = null; 
		} 
	from.selectedIndex = -1; 
	} 

// -------------------------------------------------------------------
// addOption(select_object,display_text,value,selected)
//  Add an option to a list
// -------------------------------------------------------------------
function addOption(obj,text,value,selected) {
	if (obj!=null && obj.options!=null) {
		obj.options[obj.options.length] = new Option(text, value, false, selected);
		}
	}


/* SOURCE FILE: OptionTransfer.js */

/* 
OptionTransfer.js
Last Modified: 7/12/2004

DESCRIPTION: This widget is used to easily and quickly create an interface
where the user can transfer choices from one select box to another. For
example, when selecting which columns to show or hide in search results.
This object adds value by automatically storing the values that were added
or removed from each list, as well as the state of the final list. 

COMPATABILITY: Should work on all Javascript-compliant browsers.

USAGE:
// Create a new OptionTransfer object. Pass it the field names of the left
// select box and the right select box.
var ot = new OptionTransfer("from","to");

// Optionally tell the lists whether or not to auto-sort when options are 
// moved. By default, the lists will be sorted.
ot.setAutoSort(true);

// Optionally set the delimiter to be used to separate values that are
// stored in hidden fields for the added and removed options, as well as
// final state of the lists. Defaults to a comma.
ot.setDelimiter("|");

// You can set a regular expression for option texts which are _not_ allowed to
// be transferred in either direction
ot.setStaticOptionRegex("static");

// These functions assign the form fields which will store the state of
// the lists. Each one is optional, so you can pick to only store the
// new options which were transferred to the right list, for example.
// Each function takes the name of a HIDDEN or TEXT input field.

// Store list of options removed from left list into an input field
ot.saveRemovedLeftOptions("removedLeft");
// Store list of options removed from right list into an input field
ot.saveRemovedRightOptions("removedRight");
// Store list of options added to left list into an input field
ot.saveAddedLeftOptions("addedLeft");
// Store list of options radded to right list into an input field
ot.saveAddedRightOptions("addedRight");
// Store all options existing in the left list into an input field
ot.saveNewLeftOptions("newLeft");
// Store all options existing in the right list into an input field
ot.saveNewRightOptions("newRight");

// IMPORTANT: This step is required for the OptionTransfer object to work
// correctly.
// Add a call to the BODY onLoad="" tag of the page, and pass a reference to
// the form which contains the select boxes and input fields.
BODY onLoad="ot.init(document.forms[0])"

// ADDING ACTIONS INTO YOUR PAGE
// Finally, add calls to the object to move options back and forth, either
// from links in your page or from double-clicking the options themselves.
// See example page, and use the following methods:
ot.transferRight();
ot.transferAllRight();
ot.transferLeft();
ot.transferAllLeft();


NOTES:
1) Requires the functions in selectbox.js

*/ 
function OT_transferLeft() { moveSelectedOptions(this.right,this.left,this.autoSort,this.staticOptionRegex); this.upd(); }
function OT_transferRight() { moveSelectedOptions(this.left,this.right,this.autoSort,this.staticOptionRegex); this.upd(); }
function OT_transferAllLeft() { moveAllOptions(this.right,this.left,this.autoSort,this.staticOptionRegex); this.upd(); }
function OT_transferAllRight() { moveAllOptions(this.left,this.right,this.autoSort,this.staticOptionRegex); this.upd(); }
function OT_saveRemovedLeftOptions(f) { this.removedLeftField = f; }
function OT_saveRemovedRightOptions(f) { this.removedRightField = f; }
function OT_saveAddedLeftOptions(f) { this.addedLeftField = f; }
function OT_saveAddedRightOptions(f) { this.addedRightField = f; }
function OT_saveNewLeftOptions(f) { this.newLeftField = f; }
function OT_saveNewRightOptions(f) { this.newRightField = f; }
function OT_update() {
	var removedLeft = new Object();
	var removedRight = new Object();
	var addedLeft = new Object();
	var addedRight = new Object();
	var newLeft = new Object();
	var newRight = new Object();
	for (var i=0;i<this.left.options.length;i++) {
		var o=this.left.options[i];
		newLeft[o.value]=1;
		if (typeof(this.originalLeftValues[o.value])=="undefined") {
			addedLeft[o.value]=1;
			removedRight[o.value]=1;
			}
		}
	for (var i=0;i<this.right.options.length;i++) {
		var o=this.right.options[i];
		newRight[o.value]=1;
		if (typeof(this.originalRightValues[o.value])=="undefined") {
			addedRight[o.value]=1;
			removedLeft[o.value]=1;
			}
		}
	if (this.removedLeftField!=null) { this.removedLeftField.value = OT_join(removedLeft,this.delimiter); }
	if (this.removedRightField!=null) { this.removedRightField.value = OT_join(removedRight,this.delimiter); }
	if (this.addedLeftField!=null) { this.addedLeftField.value = OT_join(addedLeft,this.delimiter); }
	if (this.addedRightField!=null) { this.addedRightField.value = OT_join(addedRight,this.delimiter); }
	if (this.newLeftField!=null) { this.newLeftField.value = OT_join(newLeft,this.delimiter); }
	if (this.newRightField!=null) { $(this.newRightField).value = OT_join(newRight,this.delimiter); }
	}
function OT_join(o,delimiter) {
	var val; var str="";
	for(val in o){
		if (str.length>0) { str=str+delimiter; }
		str=str+val;
		}
	return str;
	}
function OT_setDelimiter(val) { this.delimiter=val; }
function OT_setLeftSet(val) { this.leftSet=val; }
function OT_setAutoSort(val) { this.autoSort=val; }
function OT_setStaticOptionRegex(val) { this.staticOptionRegex=val; }
function OT_init(theform) {
	this.form = theform;
	if(!theform[this.left]){return false;}
	if(!theform[this.right]){return false;}
	this.left=theform[this.left];
	this.right=theform[this.right];
	for(var i=0;i<this.left.options.length;i++) {
		this.originalLeftValues[this.left.options[i].value]=1;
		}
	for(var i=0;i<this.right.options.length;i++) {
		this.originalRightValues[this.right.options[i].value]=1;
		}
	if(this.removedLeftField!=null) { this.removedLeftField=theform[this.removedLeftField]; }
	if(this.removedRightField!=null) { this.removedRightField=theform[this.removedRightField]; }
	if(this.addedLeftField!=null) { this.addedLeftField=theform[this.addedLeftField]; }
	if(this.addedRightField!=null) { this.addedRightField=theform[this.addedRightField]; }
	if(this.newLeftField!=null) { this.newLeftField=theform[this.newLeftField]; }
	if(this.newRightField!=null) { this.newRightField=theform[this.newRightField]; }
	this.upd();
	}
// -------------------------------------------------------------------
// OptionTransfer()
//  This is the object interface.
// -------------------------------------------------------------------
function OptionTransfer(l,r) {
	this.form = null;
	this.left=l;
	this.right=r;
	this.autoSort=true;
	this.delimiter=",";
	this.leftSet="";
	this.staticOptionRegex = "";
	this.originalLeftValues = new Object();
	this.originalRightValues = new Object();
	this.removedLeftField = null;
	this.removedRightField = null;
	this.addedLeftField = null;
	this.addedRightField = null;
	this.newLeftField = null;
	this.newRightField = null;
	this.transferLeft=OT_transferLeft;
	this.transferRight=OT_transferRight;
	this.transferAllLeft=OT_transferAllLeft;
	this.transferAllRight=OT_transferAllRight;
	this.populateLeft=OT_populateLeft;
	this.populateRight=OT_populateRight;
	this.saveRemovedLeftOptions=OT_saveRemovedLeftOptions;
	this.saveRemovedRightOptions=OT_saveRemovedRightOptions;
	this.saveAddedLeftOptions=OT_saveAddedLeftOptions;
	this.saveAddedRightOptions=OT_saveAddedRightOptions;
	this.saveNewLeftOptions=OT_saveNewLeftOptions;
	this.saveNewRightOptions=OT_saveNewRightOptions;
	this.setDelimiter=OT_setDelimiter;
	this.setLeftSet=OT_setLeftSet;
	this.setAutoSort=OT_setAutoSort;
	this.setStaticOptionRegex=OT_setStaticOptionRegex;
	this.init=OT_init;
	this.upd=OT_update;
//	this.SelectThisTab=OT_SelectThisTab;
	}

// -------------------------------------------------------------------
// populateLeft()
//  Populate the left select box with a subset of all areas
// -------------------------------------------------------------------
function OT_populateLeft(f) {	
	if (hasOptions(this.left)) {
		removeAllOptions(this.left);
	}
	var oleft='sbtn-'+this.leftSet;
	var nleft='sbtn-'+f;
	var codes= eval('codes'+f);
	var found;
	for (var i=0; i< codes.length; i++) {
		found = false;
		for (var j=0; j<this.right.options.length; j++) {
			if (this.right.options[j].text == areaMaster[codes[i]]) {
				found = true;
			}
		}
		if (!found) {
			if (!hasOptions(this.left)) { var index = 0; } else { var index=this.left.options.length; }
			this.left.options[index] = new Option( areaMaster[codes[i]], codes[i], false, false);
		}
	}
	this.setLeftSet(f);
	this.upd();
	try {
		$(nleft).addClassName('sbtn2-asel');
		$(nleft).removeClassName('sbtn2-a');
	} catch(err) {}
	try {
		$(oleft).addClassName('sbtn2-a');
		$(oleft).removeClassName('sbtn2-asel');
	} catch(err) {}
}

// -------------------------------------------------------------------
// populateRightt()
//  Populate the right select box with values provided in a + delimted string
// -------------------------------------------------------------------
function OT_populateRight(s) {	
	if (hasOptions(this.right)) {
		removeAllOptions(this.right);
	}
	if ($(s).value > "") {
	var myCodes=$(s).value.split("+");
		for (var i=0; i< myCodes.length; i++) {
			if (!hasOptions(this.right)) { var myIndex = 0; } else { var myIndex=this.right.options.length; }
			this.right.options[myIndex] = new Option( areaMaster[myCodes[i]], myCodes[i], false, false);
		}
	}
	this.upd();
}

// -------------------------------------------------------------------
// Zip specific functions (we use a text input field on the left
// -------------------------------------------------------------------
function transferZipRight() {	
	if ($('LeftListInput').value > "") {
		var codes=$('LeftListInput').value.split(",");
		var result="";
		for (var i=0; i< codes.length; i++) {
			codes[i] = codes[i] + '';
			codes[i] = codes[i].replace(/[^0-9]/g, ''); // strip non-digit chars
			if (codes[i] > 9999 && codes[i] < 100000) {
				if (!hasOptions(opt3.right)) { var index = 0; } else { var index=opt3.right.options.length; }
				opt3.right.options[index] = new Option( codes[i], codes[i], false, false);
			} else { result += codes[i] + ""; }
		}
	}
	opt3.upd();
	if (result > "") {
		$('LeftListInput').value = result;
		$('zip_error_message').innerHTML = "Invalid zip code";
	} else {
		$('LeftListInput').value = "";
		$('zip_error_message').innerHTML = "";
	}
}

function popupBox(msg) {
}

// -------------------------------------------------------------------
// Utility functions
// -------------------------------------------------------------------

function reloadLoginArea() {
    new Ajax.Request("/forms/reload_login.php", {
      postBody: $('search_form').serialize(),
      onSuccess: function(t) { $("header_content_right").update( t.responseText);  }
    });
}

function showForm() {
    forms[this].show();  
    addlinks[this].hide();  
    
  }

function hideForm() {
    forms[this].hide();    
    addlinks[this].show();  
  }

function showVT(url) {
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			parent.fb.start({href:url, rev:'controlPos:br height:98% width:92% outerBorder:1 innerBorder:0 padding:10 pauseOnResize:true enableDragResize:true'});
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
}

function requestShowing(listingId) {
	var baId = '';
	try {
		baId = $('intBrandingAgentId').value;
	} catch(err) {}

	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText != 'SITE') {
			expressLogin();
		} else {
//			parent.fb.start({href:'/lightbox_a.php?r=0&n=request_showing&' + listingId, rev:'controlPos:br type:ajax   height:600 width:700 outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true'});
			parent.fb.start({href:'/request_showing.phtml?fb=1&intListingId=' + listingId + '&intBrandingAgentId=' + baId, rev:'controlPos:br height:550 width:600 outerBorder:1 innerBorder:0 padding:0 autoFitOther:true pauseOnResize:true enableDragResize:true'});
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
}

function sendListingToFriend(listingId) {
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			parent.fb.start({href:'/send_listing_to_friend.phtml?fb=1&intListingId=' + listingId, rev:'controlPos:br height:450 width:690 outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true enableDragResize:true'});
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
}

function sendListingToClient(listingId) {
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
	  	var visitorType = t.responseText;
		if ((visitorType != 'AGENT') && (visitorType != 'ADMIN')) {
			expressLogin();
		} else {
			parent.fb.start({href:'/send_listing_to_client.phtml?fb=1&intListingId=' + listingId, rev:'controlPos:br height:450 width:690 outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true enableDragResize:true'});
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
}

function showMapLink(url) {
	parent.fb.start({href:url, rev:'controlPos:br height:92% width:92% outerBorder:1 innerBorder:0 padding:10 pauseOnResize:true enableDragResize:true'});
}

function requestMoreInfo(listingId) {
	var baId = '';
	try {
		baId = $('intBrandingAgentId').value;
	} catch(err) {}

	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText != 'SITE') {
			expressLogin();
		} else {
//			parent.fb.start({href:'/lightbox_a.php?r=0&n=request_showing&' + listingId, rev:'controlPos:br type:ajax   height:600 width:700 outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true'});
			parent.fb.start({href:'/request_more_info.phtml?fb=1&intListingId=' + listingId + '&intBrandingAgentId=' + baId, rev:'controlPos:br height:550 width:600 outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true enableDragResize:true'});
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
}

function showPreviousPurchasePrice(listingId) {
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			parent.fb.start({href:'/show_previous_purchase_price.phtml?fb=1&intListingId=' + listingId, rev:'controlPos:br height:120 width:300 outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true enableDragResize:true'});
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
}



// -------------------------------------------------------------------
// Dreamhome locator functions
// -------------------------------------------------------------------
function updateDhl(msg, val) {
	// Re-display Dreamhome locator
var req = "/forms/reload_dhl.php";
	if (val =='') {
		val = 0;
	}
	req += '?id=' + val;
	new Ajax.Request(req, {
	  postBody: $('search_form').serialize(),
	  onSuccess: function(t) { $("dhlOptions").update( t.responseText); fb.anchors.length = 0; fb.tagAnchors(document);},
	  onFailure: function(t) {  reportError("Ajax Request Failed"); }
	});
}

  function saveSearch() {
	if (fieldVisible($("dhlOptions"))) {
		new Ajax.Request("/newsearch/save_search.php", {
		  postBody: $('search_form').serialize(),
		  onSuccess: function(t) { saveSearchCompleted(t.responseText); },
		  onFailure: function(t) {  reportError("Ajax Request Failed"); }
		  });
	} else {
		new Ajax.Request("/forms/check_for_login.php", {
		  onSuccess: function(t) { 
		  	if (t.responseText == '') {
				expressLogin();
			} else {
				saveSearchPopup();
			}
		  },
		  onFailure: function(t) { reportError('Ajax request failed') }
		  });
	}
  }
  
  function saveSearchCompleted(result) {
  	r = result.split("|");
	if (checkAjaxResult(result)) {
		updateDhl(r[1], r[2]);
		showPopupBox(r[1]);
	}
 }

function saveSearchPopup() {
	// display a floatbox for Dreamhome locator. When complted, expressLogin will call expressLoginCompleted. If the user closes the box, nothing will happen.
	var id = '';
	var id = $('intSavedSearchId').serialize();
	parent.fb.start({href:'/lightbox_a.php?r=0&n=save_search_popup&' + id, rev:'controlPos:br type:ajax   height:250 width:220 outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true'});
}

  function saveSearchPopupCompleted() {
		var p =  $('search_form').serialize(false);
		var q = $('cheForm').serialize();
		new Ajax.Request("/newsearch/save_search.php", {
		  postBody: p + '&' + q,
		  onSuccess: function(t) { saveSearchCompleted(t.responseText); },
		  onFailure: function(t) {  reportError("Ajax Request Failed"); }
		  });
 }

function deleteSearch() {
    new Ajax.Request("/newsearch/delete_search.php", {
      postBody: $('search_form').serialize(),
      onSuccess: function(t) { deleteSearchCompleted(t.responseText); },
	  onFailure: function(t) { reportError("Ajax Request Failed"); }
    });
}

  function deleteSearchCompleted(result) {
   	r = result.split("|");
	if (checkAjaxResult(result)) {
		updateDhl('','');
		showPopupBox(r[1]);
	}
 }
 
 function Morgcal() { 
Element.show("MortResults");
var LoanAmount = convertToNumber('LoanAmount');
var DownPayment = convertToNumber('LoanAmount') * convertToNumber('DownPayment') / 100;
var AnnualInterestRate = convertToNumber('InterestRate')/100 ;
var Years= convertToNumber('NumberOfYears') ;
var MonthRate=AnnualInterestRate/12 ;
var NumPayments=Years*12 ;
var Prin=LoanAmount-DownPayment ;
var MonthPayment=Math.floor((Prin*MonthRate)/(1-Math.pow((1+MonthRate),(-1*NumPayments)))*100)/100 ;
var MonthlyTax=convertToNumber('Taxes')/12;
var MonthlyAssessment = convertToNumber('Assessment')*1;
var TotalPayment=MonthPayment+MonthlyTax+MonthlyAssessment;
$('DownPmt').innerHTML = (addCommas(DownPayment.toFixed(0)));
$('Prin').innerHTML = (addCommas(Prin.toFixed(0)));
$('MonthlyPayment').innerHTML = (addCommas(MonthPayment.toFixed(0)));
$('MonthlyAssessment').innerHTML = (addCommas(MonthlyAssessment.toFixed(0)));
$('MonthlyTax').innerHTML = (addCommas(MonthlyTax.toFixed(0)));
$('MonthlyTotal').innerHTML = (addCommas(TotalPayment.toFixed(0)));
} 

function convertToNumber(box){
var val = 0;
try { val=$(box).value; } catch(err) { reportError("convertToNumber failed for field " + box + 'ERROR: ' + err); }
//val=$(box).value;
val = val.replace(/[^0-9.-]/g, ''); // strip non-digit chars
val = stripDuplicateChars(val, '.', 1, 0); // strip excess decimals
val = stripDuplicateChars(val, '-', 0, 1); // strip excess minus signs
$(box).value=addCommas(val);
return val; // return value
}

function stripDuplicateChars(str, strip, n, s){
var count=0; var stripped=str.substring(0, s); var chr;
for (var i=s; i<str.length; i++){ chr = str.substring(i, i+1);
if (chr == strip){ count++; if (count<n+1){ stripped = stripped +
chr;}}
else {stripped = stripped + chr;}} return stripped;
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

// -------------------------------------------------------------------
// Express login (without leaving the search page)
// -------------------------------------------------------------------
function expressLogin() {
	// display a floatbox for express login. When complted, expressLogin will call expressLoginCompleted. If the user closes the box, nothing will happen.
	parent.fb.loadAnchor('/lightbox_a.php?r=1&n=express_login', 'controlPos:br type:ajax   height:300 width:350 outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true');
}

function expressLoginConfirm() {
    new Ajax.Request("/forms/express_login_confirm.php", {
      postBody: $('cheForm').serialize(),
      onSuccess: function(t) { expressLoginCompleted(t.responseText); },
	  onFailure: function(t) {  reportError("Ajax Request Failed"); }
    });
}

function expressLoginCompleted(result) {
	if (checkAjaxResult(result)) {
		reloadLoginArea();
		updateDhl('',0);
		if ($('strSearchQualifier').value == 'H') {
			showOpenHouses();
		}
		//reDoRollovers(true);
		goToReportPage($("strPageSelection").value, false);
		showPopupBox("Login successful.");
	}
}


// -------------------------------------------------------------------
// Listing display
// -------------------------------------------------------------------
function getListing(resultNum, addlParams) {
	freezeUI();
	$('intResultNum').value = resultNum;
    new Ajax.Request("/newsearch/get_listing.php?l=" + resultNum, {
      postBody: $('search_form').serialize() + addlParams,
      onSuccess: function(t) { showListingResult(t.responseText); },
	  onFailure: function(t) { reportError("Ajax Request Failed"); }
    });
  }

function getMlsListing(resultNum, addlParams) {
	freezeUI();
	$('intResultNum').value = resultNum;
    new Ajax.Request("/newsearch/get_listing.php?mls=" + resultNum, {
      postBody: $('search_form').serialize() + addlParams,
      onSuccess: function(t) { showListingResult(t.responseText); },
	  onFailure: function(t) { reportError("Ajax Request Failed"); }
    });
  }

function showListingResult(result) {
	//var json = result.evalJSON();
	//$('listing-result').update(json.re1);
	$('listing-result').update(result);
	reportError("");
	reDoRollovers(true);
	fb.anchors.length = 0;
	fb.tagAnchors(document);
	unfreezeUI();
}



// -------------------------------------------------------------------
// Main Search functions
// -------------------------------------------------------------------
function changeSortOptions(t) {
	var newSortOpt = t.value;
	$('strOrderBy').value = newSortOpt;
	$('strOrderBy1').value = newSortOpt;
	$('strOrderBy2').value = newSortOpt;
	$('strPageSelection').value = '1';
	if ($(t).identify() != "strOrderBy") goToReportPage(1);
}
function changeLimitOptions(t) {
	var newSortOpt = t.value;
	var oldSortOpt;
	if ($(t).identify() == "intLimit") oldSortOpt = $('intLimit1').value;
	else $oldSortOpt = $('intLimit2').value;
	$('intLimit').value = newSortOpt;
	$('intLimit1').value = newSortOpt;
	$('intLimit2').value = newSortOpt;
	$('strPageSelection').value = '1';
	if ($(t).identify() != "intLimit") goToReportPage(1);
}
function goToReportPage(pageNum,addHis) {
	if ( addHis === undefined )
		var addToHis = true;
	else
		var addToHis = addHis;
	if (pageNum < 1) {
		pageNum = 1;
	}
	$("strPageSelection").value = pageNum;
	if (addToHis)
		addToHistory("goToPage", pageNum);
	doSearch(false);
}
  //do fancy javascript search
  
  function freezeUI() {
 	Element.show("ui2");
	Element.hide("ui1");
  }
  
  function unfreezeUI() {
 	Element.show("ui1");
	Element.hide("ui2");
  }
  
  function doSearch(addHis) {
	if ( addHis === undefined )
		var addToHis = true;
	else
		var addToHis = addHis;
	prepareForSearch();
 // 	$("search-result").innerHTML = "Please wait...";
	Element.hide("search-forms");
	Element.hide("listing-results");
	Element.show("search-results");
    freezeUI(); 
	
	var theRequest = "/newsearch/results.php";
	if ($('strSearchQualifier').value == 'S')
		theRequest = "/newsearch/results_sold.php";

	new Ajax.Request(theRequest, {
	  onSuccess: function(t) { 
		$('search-result').update(t.responseText);
		if (addToHis)
			addToHistory("showListing", resultNum);
		unfreezeUI();
	  },
	  method: 'post', 
	  parameters: $('search_form').serialize(), 
	  evalScripts: true,
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
 }

  function startSearch() {
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			goToReportPage(1);
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
  }

function goToReportPage(pageNum,addHis) {
	if ( addHis === undefined )
		var addToHis = true;
	else
		var addToHis = addHis;
	if (pageNum < 1) {
		pageNum = 1;
	}
	$("strPageSelection").value = pageNum;
	if (addToHis)
		addToHistory("goToPage", pageNum);
	doSearch(false);
}
  function refineSearch(addHis) {
	if ( addHis === undefined )
		var addToHis = true;
	else
		var addToHis = addHis;
	Element.hide("search-results");
	Element.hide("listing-results");
	Element.show("search-forms");
	$('strPageSelection').value = '1';
	$('blnFirstSearch').value = 1;
	if (addToHis)
		addToHistory("refineSearch", null);
  }

  function showResults(addHis) {
	if ( addHis === undefined )
		var addToHis = true;
	else
		var addToHis = addHis;
	Element.hide("listing-results");
	Element.hide("search-forms");
	Element.show("search-results");
	if (addToHis)
		addToHistory("showResults", null);
  }

  function showListing(resultNum,addHis) {
	if ( addHis === undefined )
		var addToHis = true;
	else
		var addToHis = addHis;
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			Element.hide("search-forms");
			Element.hide("search-results");
			Element.show("listing-results");
			getListing(resultNum);
			if (addToHis)
				addToHistory("showListing", resultNum);
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
  }

  function showOhListing(resultNum,addHis) {
	if ( addHis === undefined )
		var addToHis = true;
	else
		var addToHis = addHis;
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			Element.hide("search-forms");
			Element.hide("search-results");
			Element.show("listing-results");
			getListing(resultNum, '&printOhSchedule=1');
			if (addToHis)
				addToHistory("showOhListing", resultNum);
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
  }
 
  function showMlsListing(resultNum,addHis) {
	if ( addHis === undefined )
		var addToHis = true;
	else
		var addToHis = addHis;
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			Element.hide("search-forms");
			Element.hide("search-results");
			Element.show("listing-results");
			getMlsListing(resultNum);
			if (addToHis)
				addToHistory("showMlsListing", resultNum);
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
  }

function UncheckCondoMain(box) { 
form = document.myform ;
if (box.checked) {form.intPtCondo.checked=false;};
} 
function UncheckCondoDetail(box) { 
form = document.myform ;
if (box.checked) {
form.intPtLoft.checked=false;
form.intPtPenthouse.checked=false;
form.intPtHighrise.checked=false;
form.intPtStudio.checked=false;
form.intPtDuplex.checked=false;}
} 


// -------------------------------------------------------------------
// Ajax history handling
// -------------------------------------------------------------------
function addToHistory(newLocation, 
                       historyData) {
 $('status_result').update('');
 newLocation = newLocation + "-" + dhtmlHistoryCount++;
	dhtmlHistory.add(newLocation, historyData);
//	$('status_resulth').update("Adding to history: "
//        + "<br>newLocation="+newLocation
//        + "<br>historyData="+historyData);
//	$('status_result').update(dhtmlHistoryChangeCount);
}

function historyChange(newLocation, historyData) {
//	$('status_result').update(dhtmlHistoryChangeCount++ + "A history change has occurred: "
//		+ "<br>newLocation="+newLocation
//		+ "<br>historyData="+historyData);
//	$('status_resulth').update(dhtmlHistoryCount);
	if ( newLocation > '' ) {
		var loc = newLocation.split('-');
		switch(loc[0]) { 
				case "doSearch": 
					rePopulateForm(historyData); 
					doSearch(false);
					break; 
				case "goToPage": 
					goToReportPage(historyData, false); 
					//doSearch();
					break; 
				case "showListing": 
					showListing(historyData, false); 
					//doSearch();
					break; 
				case "refineSearch": 
					refineSearch(false); 
					//doSearch();
					break; 
				case "showResults": 
					showResults(false); 
					//doSearch();
					break; 
		} 
	} else {
		window.location.reload();
	}
}

function rePopulateForm(theData) {
	var js = new Object();
	var x = theData.split('&');
	var y;
	var z = 'rePopulateForm:<br>';
	for (var i = 0; i < x.length - 1; i++) {
		if( x[i] > '' ) {
			y = x[i].split('=');
			js[y[0]] = y[1];
			z += y[0] + " = " + y[1] + '<br>';
		}
//		try { $(y[0]).update(y[1]); } catch(err) {}
//		try { $(y[0]).value = y[1]; } catch(err) {}
	}
//	$('status_result').update(z);
}

function showOpenHouses() {
	new Ajax.Request("/newsearch/show_open_houses.php", {
	  onSuccess: function(t) { 
		try {
			$('open_house_results').update(t.responseText);
		} catch(err) {};
		},
	  onFailure: function(t) { reportError("Ajax Request Failed"); }
	});
}
 
function addOpenHouse(intLn, dtOhDate) {
	params = 'intLn=' +  intLn + '&dtOhDate=' +  dtOhDate;
	try {
		$('open_house_results').scrollTo();
	} catch(err) {};
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			new Ajax.Request("/newsearch/add_open_house.php", {
			  postBody: params,
			  onSuccess: function(t) { 
			  	changeOpenHouseCompleted(t.responseText);
			  	},
			  onFailure: function(t) { reportError("Ajax Request Failed"); }
			});
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
}
 
function removeOpenHouse(intId) {
	params = 'intId=' +  intId;
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			new Ajax.Request("/newsearch/remove_open_house.php", {
			  postBody: params,
			  onSuccess: function(t) { 
			  	changeOpenHouseCompleted(t.responseText);
			  	},
			  onFailure: function(t) { reportError("Ajax Request Failed"); }
			});
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
}
 
function moveOpenHouse(intId, startNum) {
	params = 'intId=' +  intId + '&startNum=' + startNum;
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			new Ajax.Request("/newsearch/move_open_house.php", {
			  postBody: params,
			  onSuccess: function(t) { 
			  	changeOpenHouseCompleted(t.responseText);
			  	},
			  onFailure: function(t) { reportError("Ajax Request Failed"); }
			});
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
}
 
function changeOpenHouseCompleted(result) {
   	r = result.split("|");
	if (checkAjaxResult(result)) {
		showOpenHouses();
	} else {
		showPopupBox('ERROR: ' + r[1] + '.');
	}
 }
 
function myOhSearch() {
	Element.hide("search-forms");
	Element.hide("listing-results");
	Element.show("search-results");
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			var theRequest = "/newsearch/results.php";
			new Ajax.Request(theRequest, {
			  onSuccess: function(t) { 
				$('search-result').update(t.responseText);
				addToHistory("myOhSearch", null);
			  },
			  method: 'post', 
			  parameters: $('search_form').serialize() + '&printOhSchedule=1', 
			  evalScripts: true,
			  onFailure: function(t) { reportError('Ajax request failed') }
			  });
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
};

function doAdvSearch() {
	$('search_form').action = "/real_estate_search/r";
	if ($('strNeighborhodAreas').value > '') {
		$('strCity').value = '';
	}
	$('strAreaSearchTerm').value = $('strNeighborhodAreas').value;
	$('search_form').submit();
}

function setCustomFieldValue(box,val){
$(box).value = val;
};
