// JavaScript Document

function hov(loc,cls) {
   if(loc.className)
	  loc.className=cls;
}

function cheValidateEntry(req, val, debugElm) {
	// returns a 2-element array: status value and status text
	var r = [0,0];
	var params = 'r=' + req + "&v=" + val;
	cheErrorMsg = '';
	new Ajax.Request('/forms/validation/validate_entry.php', {
	  method: 'get',
	  parameters: params,
	  asynchronous: false,
	  onSuccess: function(transport) {
		  r = transport.responseText.split("|");
		  },
	  onFailure: function(transport) {
		  r = [0, "Ajax failure: " + transport.status];
	  }
	});
	if (debugElm > '') {
		$(debugElm).update(r[0] + " - " + r[1]);
		Element.show(debugElm);
	}
	if (r[0] == 1) {
		Validation.cheError = '';
	} else {
		Validation.cheError = r[1];
	}
	return r[0] == 1;
}

function ohScrollUp() {
	$('OH_scoller').scrollTop -= 12;
	ohCheckButtons();
}

function ohScrollDown () {
	$('OH_scoller').scrollTop += 12;
	ohCheckButtons();
}

function ohCheckButtons() {
	if ($('OH_scoller').scrollTop == 0)
		$('up').setStyle({"background": "url('/newimages/up_inactive.gif')"});
	else
		$('up').setStyle({"background": "url('/newimages/up_active.gif')"});
		
	if ($('OH_scoller').scrollTop >= $('OH_scoller').offsetHeight - 120)
		$('down').setStyle({"background": "url('/newimages/down_inactive.gif')"});
	else
		$('down').setStyle({"background": "url('/newimages/down_active.gif')"});
}

/*=============================
Dynamic select for search boxes
=============================*/
	function dynamicSelect(id1, id2) {
		// Feature test to see if there is enough W3C DOM support
		if (document.getElementById && document.getElementsByTagName) {
			// Obtain references to both select boxes
			var sel1 = document.getElementById(id1);
			var sel2 = document.getElementById(id2);
			// Clone the dynamic select box
			var clone = sel2.cloneNode(true);
			// Obtain references to all cloned options 
			var clonedOptions = clone.getElementsByTagName("option");
			// Onload init: call a generic function to display the related options in the dynamic select box
			refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
			// Onchange of the main select box: call a generic function to display the related options in the dynamic select box
			sel1.onchange = function() {
				refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
			};
		}
	}
	function refreshDynamicSelectOptions(sel1, sel2, clonedOptions) {
		// Delete all options of the dynamic select box
		while (sel2.options.length) {
			sel2.remove(0);
		}
		// Create regular expression objects for "select" and the value of the selected option of the main select box as class names
		var pattern1 = /( |^)(select)( |$)/;
		var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");
		// Iterate through all cloned options
		for (var i = 0; i < clonedOptions.length; i++) {
			// If the classname of a cloned option either equals "select" or equals the value of the selected option of the main select box
			if (clonedOptions[i].className.match(pattern1) || clonedOptions[i].className.match(pattern2)) {
				// Clone the option from the hidden option pool and append it to the dynamic select box
				sel2.appendChild(clonedOptions[i].cloneNode(true));
			}
		}
	}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_nbGroup(event, grpName) { //v6.0
var i,img,nbArr,args=MM_nbGroup.arguments;
  if (event == "init" && args.length > 2) {
	if ((img = MM_findObj(args[2])) != null && !img.MM_init) {
	  img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src;
	  if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array();
	  nbArr[nbArr.length] = img;
	  for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
		if (!img.MM_up) img.MM_up = img.src;
		img.src = img.MM_dn = args[i+1];
		nbArr[nbArr.length] = img;
	} }
  } else if (event == "over") {
	document.MM_nbOver = nbArr = new Array();
	for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) {
	  if (!img.MM_up) img.MM_up = img.src;
	  img.src = (img.MM_dn && args[i+2]) ? args[i+2] : ((args[i+1])?args[i+1] : img.MM_up);
	  nbArr[nbArr.length] = img;
	}
  } else if (event == "out" ) {
	for (i=0; i < document.MM_nbOver.length; i++) { img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; }
  } else if (event == "down") {
	nbArr = document[grpName];
	if (nbArr) for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; }
	document[grpName] = nbArr = new Array();
	for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) {
	  if (!img.MM_up) img.MM_up = img.src;
	  img.src = img.MM_dn = (args[i+1])? args[i+1] : img.MM_up;
	  nbArr[nbArr.length] = img;
  } }
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}


/*======================
Custom formatting for search fields
=======================*/

function cheFormatPrice(box) { 
	var x = box.value;
	var thePrice= cheConvertToNumber(x);
	if(thePrice==0) box.value='';
	else box.value=cheAddCommas(parseInt(thePrice));
} 

function cheAddCommas(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;
}
function cheConvertToNumber(val){
	var x = val + '';
	x = x.replace(/[^0-9.-]/g, ''); // strip non-digit chars
	x = cheStripDuplicateChars(x, '.', 1, 0); // strip excess decimals
	x = cheStripDuplicateChars(x, '-', 0, 1); // strip excess minus signs
	return x; // return value
};

function cheStripDuplicateChars(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 cheSetCustomFieldValue(box,val){
	form = document.myform ;
	thebox = document.getElementById(box);
	thebox.value = val;
};

// Validation for search fields
function fieldVisible(elm) {
	if (!elm.visible()) return false;
	var parents = elm.ancestors();
	for (i=0; i < parents.length; i++) {
		if (!parents[i].visible()) return false;
	}
	return true;
};

function goToSelectedPage(box, prefix, suffix)
{
destination = prefix+box.value+suffix;
if (destination) location.href = destination;
}

function doNothing()
{
}

function cheReportError(request)
{
	alert("Sorry. There was an error. \n" + request );
}


// -------------------------------------------------------------------
// Handle rollovers and logged-in/logged-out images
 // -------------------------------------------------------------------
function reDoRollovers(loggedIn) {
    $$("img.rollover").each(
        function(i) {
			if (fieldVisible(i)) {
			  var os = i.src, ni = document.createElement('img');
			  if (loggedIn) {
				  if (os.indexOf('loggedout') > 0) {
					  os = i.src.replace(/loggedout/, "loggedin");
					  i.src = os;
				  }
			  } else {
				  if (os.indexOf('loggedin') > 0) {
					  os = i.src.replace(/loggedout/, "loggedout");
					  i.src = os;
				  }
			  }
			  $(i).observe('mouseout', function(e){i.src = os;});
			  ni.src = i.src.replace(/(.*)\.(jpg|gif|png)$/i, "$1-rollover.$2");
			  i.observe('mouseover', function(e){i.src = ni.src;});
			}
    });
}

// -------------------------------------------------------------------
//  Miscellaneous functions
 // -------------------------------------------------------------------
function popupUrl(strUrl,loadOnClose) {
		if (loadOnClose === undefined)
			var loadCl = '';
		else
			var loadCl = 'loadPageOnClose:' + loadOnClose;
		if (strUrl.search(/\?/) > 0)
			fbSub = '&fb=1';
		else
			fbSub = '?fb=1';
		parent.fb.start({href:strUrl + fbSub, rev:'controlPos:br height:92% width:970px outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true ' + loadCl});
//		newWindow = window.open(strUrl, 'printPage', 'menubar=no,toolbar=yes,location=no,status=no,scrollbars=yes,resizable=yes,width=680,height=300,left=50,top=50');
	};

function scrollToAnchor(theAnchor) {
	try {
		$(theAnchor).scrollTo();
	} catch(err) {}
}

function toggleVisibility(id, elm1, elm2, textVisible, textHidden) {
	if ( textVisible === undefined )
		textVisible = 'Hide';
	if ( textHidden === undefined )
		textHidden = 'Show';
	if (fieldVisible($(elm2 + id))) {
		Element.hide(elm2 + id);
		$(elm1 + id).update(textHidden);
	} else {
		Element.show(elm2 + id);
		$(elm1 + id).update(textVisible);
	}
}

function deleteMySavedSearch(searchId, boxId) {
    new Ajax.Request("/newsearch/delete_search.php", {
      postBody: $('cheForm').serialize(),
      onSuccess: function(t) { deleteMySavedSearchCompleted(boxId, t.responseText); },
	  onFailure: function(t) { reportError("Ajax Request Failed"); }
    });
}

function deleteMySavedSearchCompleted(boxId, result) {
   	r = result.split("|");
	if (checkAjaxResult(result)) {
		$('dhs_' + boxId).update('');
	} else {
		$('dhs_' + boxId).update('ERROR: ' + r[1] + '.');
		//showPopupBoxAndReload('ERROR: ' + r[1] + '.');
	}
 }
 
function toggleMySavedSearch(searchId, boxId) {
	params = 'intSavedSearchId=' +  searchId + '&box=' +  boxId;
    new Ajax.Request("/newsearch/toggle_saved_search_enabled.php", {
      postBody: params,
      onSuccess: function(t) { toggleMySavedSearchCompleted(searchId, boxId, t.responseText); },
	  onFailure: function(t) { reportError("Ajax Request Failed"); }
    });
}
 
function toggleMySavedSearchCompleted(searchId, boxId, result) {
   	r = result.split("|");
	if (checkAjaxResult(result)) {
		$('dhs_' + boxId).update(r[1]);
	} else {
		showPopupBox('ERROR: ' + r[1] + '.');
	}
 }
 
function updateRating(intId, intLn, intVal, boxId, boxId2) {
	params = 'intId=' +  intId + '&intLn=' +  intLn + '&intVal=' +  intVal;
	new Ajax.Request("/forms/check_for_login.php", {
	  onSuccess: function(t) { 
		if (t.responseText == '') {
			expressLogin();
		} else {
			new Ajax.Request("/newsearch/update_rating.php", {
			  postBody: params,
			  onSuccess: function(t) { 
			  	updateRatingCompleted(boxId, t.responseText);
				if ( boxId2 !== undefined )
					updateRatingCompleted(boxId2, t.responseText);
				if ( boxId == 'drating' ) {
					if (t.responseText == 'OK|') {
						try { $(boxId+'_lnk').update("<a href=\"javascript:;\" onclick=\"updateRating(" + intId + "," + intLn + ",1,'" + boxId + "');\" ><img src=\"http://www.chicagohomeestates.com/newimages/search_add.png\" alt=\"Add To My Properties\" width=\"152\" height=\"67\" class=\"rollover\" /></a>"); } catch(err) {};
						try { $(boxId2+'_lnk').update("<a href=\"javascript:;\" onclick=\"updateRating(" + intId + "," + intLn + ",1,'" + boxId + "');\" >Add&nbsp;To&nbsp;My&nbsp;Properties</a>"); } catch(err) {};
					} else {
						try { $(boxId+'_lnk').update("<a href=\"javascript:;\" onclick=\"updateRating(" + intId + "," + intLn + ",0,'" + boxId + "');\" ><img src=\"http://www.chicagohomeestates.com/newimages/search_remove.png\" alt=\"Remove From My Properties\" width=\"152\" height=\"67\" class=\"rollover\" /></a>"); } catch(err) {};
						try { $(boxId2+'_lnk').update("<a href=\"javascript:;\" onclick=\"updateRating(" + intId + "," + intLn + ",0,'" + boxId + "');\" >Remove&nbsp;From&nbsp;My&nbsp;Properties</a>"); } catch(err) {};
					}
					reDoRollovers(true);
				} else {
					if (t.responseText == 'OK|') {
						try { $(boxId+'_lnk').update("<a href=\"javascript:;\" onclick=\"updateRating(" + intId + "," + intLn + ",1,'" + boxId + "');\" >Add&nbsp;To&nbsp;My&nbsp;Properties</a>"); } catch(err) {};
					} else {
						try { $(boxId+'_lnk').update("<a href=\"javascript:;\" onclick=\"updateRating(" + intId + "," + intLn + ",0,'" + boxId + "');\" >Remove&nbsp;From&nbsp;My&nbsp;Properties</a>"); } catch(err) {};
					}
				}
			  	},
			  onFailure: function(t) { reportError("Ajax Request Failed"); }
			});
		}
	  },
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });
}
 
function updateRatingCompleted(boxId, result) {
   	r = result.split("|");
	if (checkAjaxResult(result)) {
		$(boxId).update(r[1]);
	} else {
		showPopupBox('ERROR: ' + r[1] + '.');
	}
 }
 
function showPopupBox(stat) {
	try {
		$('strPopupStatus').value = stat;
	} catch(err) {};
	parent.fb.start({href:'/lightbox_a.php?r=1&n=popup_box', rev:'controlPos:br type:ajax   height:250 width:350 outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true ' + revParams});
}

function showPopupBoxAndReload(stat) {
	try {
		$('strPopupStatus').value = stat;
	} catch(err) {};
	parent.fb.start({href:'/lightbox_a.php?r=1&n=popup_box', rev:'controlPos:br type:ajax   height:250 width:350 outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true loadPageOnClose:self'});
}

function reportError(stat) {
	if (stat > '') {
	 	$('status_result').update("An error has occurred: " + stat);
	} else {
	 	$('status_result').update("");
	}
	unfreezeUI();
}

  function checkAjaxResult(result) {
   	var r = '';
	var req = '';
	var stat = '';
	r = result.split("|");
	if (r[0] == 'OK') {
		return(true);
	} else if (r[0] == "Redirect") {
		stat = r[2];
		req = '/lightbox_a.php?r=1&n='+r[1];
	} else if (r[0] == "Failure") {
		stat = r[1];
	} else {
		stat = "An error has occurred: " + result;
	}
	if (req > '') {
		parent.fb.start({href:req, rev:'controlPos:br type:ajax   height:50 width:350 outerBorder:1 innerBorder:0 padding:0 pauseOnResize:true'});
	} else {
		showPopupBox(stat);
	}
	return(false);
}


// -------------------------------------------------------------------
// Floatbox default settings
 // -------------------------------------------------------------------
fbPageOptions = {
    theme: 'custom',
	padding: 2,
	panelPadding: 2,
	roundCorners: 'none',
    resizeDuration: 5.5,
    imageFadeDuration: 4.5,
    overlayFadeDuration: 0,
    navType: 'both',
	resizeDuration: 2
};

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function cheFormatDate(box) { 
	var nStr = box.value + '';
	var currentTime = new Date();
	var newDate = '';
	x = nStr.split('/');
	if (x.length == 1) {
		newDate = (currentTime.getMonth() + 1) + '/' + x[0] + '/' + currentTime.getFullYear();
	}
	if (x.length == 2) {
		newDate = x[0] + '/' + x[1] + '/' + currentTime.getFullYear();
	}
	if (x.length == 3) {
		if (x[2].length == 2)
			x[2] = '20' + x[2];
		newDate = x[0] + '/' + x[1] + '/' + x[2];
	}

	box.value=newDate;
} 

function cheFormatTime(box) { 
	var nStr = box.value + '';
	var newTime = '';
	var ampm = '';
	// look for am/pm
	if (nStr.search(/a/i) > 0)
		ampm = 'am';
	if (nStr.search(/p/i) > 0)
		ampm = 'pm';
	nStr = nStr.replace(/[^0-9:]/g, ''); // strip non-time chars
	x = nStr.split(':');
	if (x.length == 1) {
		mm = '00';
	} else {
		mm = x[1];
	}
	hh = parseInt(x[0]);
	if (hh > 12) {
		hh = hh - 12;
		ampm = 'pm';
	}
	if (ampm == '') {
		if ((hh < 9) || (hh > 11)) {
			ampm = 'pm';
		} else {
			ampm = 'am';
		}
	}
	if (mm == '')
		mm = '00';
	if (hh > 0) {
		newTime = '' + hh + ':' + mm + ' ' + ampm;
	}
	box.value = newTime;
} 

function loadInsert(theElm, theReq) {

	var theRequest = "/newsearch/one_result.php";

	new Ajax.Request(theRequest, {
	  onSuccess: function(t) { 
		$(theElm).update(t.responseText);
	  },
	  method: 'post', 
	  parameters: 'srch=' + theReq, 
	  evalScripts: true,
	  onFailure: function(t) { reportError('Ajax request failed') }
	  });

}