var _childWin;
var _showWait = true;
var _appPathRootUninit = 'UNINIT';
var _appPathRoot = _appPathRoot || _appPathRootUninit;
var wide=screen.width;
var high=screen.height;
//DOM Utility functions:
function $endsWith(id) {
	return Element.select(document.body, '[id$="' + id + '"]').first();
}
function resz(win) 
{
win.moveTo(0,0);
win.resizeTo(screen.width,screen.height);
}
function $submit(formName) {
    var frm = document.forms[formName];
    if(frm) {
        frm.submit();
    }
}
function applyAppPathModifier(path) {
	if(_appPathRoot.charAt(_appPathRoot.length-1) == '/') {
		_appPathRoot = _appPathRoot.substring(0,_appPathRoot.length-1);
	}
	
	if(_appPathRoot == _appPathRootUninit) {
		alert('Application root [_appPathRoot] not set.');
		_appPathRoot = 'http://www.recls.com';
	}
	if(path.charAt(0) == '~') {
		return _appPathRoot + path.substring(1,path.length);
	}
	return path;
}

function deleteRow(sender) {
	if(sender == null) {
		alert("Row could not be deleted (deleteRow.1)");
		return;
	}
	
	var tr = findParentRow(sender)
	if(tr == null) {
		alert("Row not found (deleteRow.2)");
		return;
	}
	
	tr.removeNode(true);
	return false;
}

function addRow(elem,templateId) {
	var tr = findParentRow(elem);
	var template = document.getElementById(templateId);
	var newRow = template.cloneNode(true);
	newRow.style.display = "block";
	var nextRow = tr.nextSibling;
	if(nextRow != null) {
		tr.parentNode.insertBefore(newRow,nextRow);
	}
	else {
		tr.parentNode.appendChild(newRow);
	}
	return false;
}

function findParentRow(e) {
	var current = e;
	
	while(current && current.tagName != "TR") {
		current = current.parentNode;
	}
		
	return current;
}

function findNextRow(tr) {
	return findNextTagName(tr,"TR");
}

function findNextTagName(element,tagName) {
	var current = element.nextSibling;
	
	while(current && current.tagName != tagName) {
		current = current.nextSibling;
	}
	
	return current;
}

function getFormField(frm,controlName,fieldName) {
	var newFieldName;
	var element;
	
	if(controlName != null && controlName.length > 0) {
		// .NET 2.0 naming
		newFieldName = controlName + "$" + fieldName;
		element = frm[newFieldName];
		
		if(element == null) {
			// .NET 1.1 naming
			newFieldName = controlName + ":" + fieldName;
			element = frm[newFieldName];
		}
	}
	else {
		newFieldName = fieldName;
		element = frm[newFieldName];
	}
	
	return element;
}

function $uc(namingContainerId,id) {
	var prefix = namingContainerId ? namingContainerId + "_" : "";
	var element = document.getElementById(prefix + id);
	if(element == null && prefix.length > 0) {
		// if we didn't find the element, fall back to no prefix
		element = document.getElementById(id);
	}
	return element;
}

function getBasicId(namingContainerId,id) {
	var containerIdLength = namingContainerId ? namingContainerId.length : 0;
	var beginningOfId = containerIdLength + 1;
	return id.substring(beginningOfId);
}


//MISC FUNCTIONS
function syncCombos(cboClicked) {
	cboClicked = $(cboClicked);
	var body = $(document.body);
	cboFrom = body.select('select[id$="cboFromPrice"]').first();
	cboTo = body.select('select[id$="cboToPrice"]').first();
	
	var divLinks = $('divLinks');
	if(divLinks) {
		divLinks.style.display = "none";
		$('divLinks2').style.display = "none";
	}
	
	//if(!cboClicked) return;
	//if(!cboFrom) return;
	//if(!cboTo) return;
	
	if(cboClicked.selectedIndex == 0) {
		if(cboClicked == cboTo) return;
			cboTo.selectedIndex = 0;
			return;
		}
		if(cboClicked == cboFrom && cboClicked.selectedIndex == cboClicked.options.length - 1) {
			cboTo.selectedIndex = 0;
			return;
		}
		if(cboClicked == cboFrom && cboTo.selectedIndex == 0) {
			return ;
		}
		if(cboClicked == cboTo && cboFrom.selectedIndex == 0) {
			cboFrom.selectedIndex = 1;
			return;
		}
		var fromPrice = parseFloat(cboFrom.options[cboFrom.selectedIndex].value);
		var toPrice = parseFloat(cboTo.options[cboTo.selectedIndex].value);
		while(toPrice <= fromPrice) {
		cboTo.selectedIndex++;
		fromPrice = parseFloat(cboFrom.options[cboFrom.selectedIndex].value);
		toPrice = parseFloat(cboTo.options[cboTo.selectedIndex].value);
	}
}


function editAttachments(mlsId, mlsType) {
	var url = applyAppPathModifier("~/EditAttachments.aspx?mlsId=" + mlsId + "&mlsType=" + mlsType);
	window.open(url, "", "top=20,left=20");
}

//CLASS SIZE
function Size(left, top, width, height) {
	this.Left = left;
	this.Top = top;
	this.Width = width;
	this.Height = height;
	this.toString = function(separator) {
		var arr = new Array();
		var i = 0;
		
		arr[i++] = "left=" + this.Left;
		arr[i++] = "top=" + this.Top;
		arr[i++] = "width=" + this.Width;
		arr[i++] = "height=" + this.Height;
		
		if(!separator) {
			separator = ",";
		}
		
		return arr.join(separator);
	}
}

function getCenteredSize(width, height) {
	var screenWidth = document.body.offsetWidth;
	var screenHeight = document.body.offsetHeight;
	var left = window.screenLeft + (screenWidth / 2) - (width / 2);
	var top = window.screenTop + (screenHeight / 2) - (height / 2) - 30;
	
	return new Size(left, top, width, height);
}

function openGoodFaithDialog(mlsId, address, price, taxes, abbreviated) {
	var query = new Array();
	var i = 0;
	
	query[i++] = "mlsId=" + mlsId;
	query[i++] = "address=" + escape(address);
	query[i++] = "price=" + price;
	query[i++] = "taxes=" + taxes;
	query[i++] = "abbreviated=" + abbreviated;
	
	var url = applyAppPathModifier("~/HomeOwnershipOptions.aspx?" + query.join("&"));
	var size = getCenteredSize(350, 480);
	var features = size.toString(",") + ",menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no";
	var win = window.open(url, "_blank", features);
	return false;
}


function ko() {
	if(_childWin != null) {
		_childWin.close();
	}
}


function saveCheck(chk) {
	if(!document.all) {
		return
	}
	if(!chk.checked) {
		return;
	}
	var span = chk.parentElement;
	for(var i=0;i<span.children.length;i++) {
		if(span.children[i].tagName == "LABEL") {
			span.children[i].innerHTML = "Save Preferences";
		}
	}
}


function page(i) {
	_showWait = false;
	document.forms[0].hidPaging.value = i;
	//document.forms[0].action = 'search.aspx' + location.search + '#results';
	document.forms[0].submit()
	//document.getElementById("cmdSearch").click();
}

function getListingCount() {
	var err;
	var myForm = document.forms[0]
	try {
		myForm.hidChangedTown.value = (window.event.srcElement.name == "cboTownList") ? "Y" : ""
	}
	catch(err) {
		//noop
	}
	myForm.action = "/listingCount.aspx";
	myForm.target = getAvailIFrame();
	window.setTimeout("rs()",10)
}


function rs() {
	if(document.getElementById("divSearchBox") !=  null) {
		var myForm = document.forms[0]
		myForm.submit();
		myForm.target = "";
		myForm.action = ""
		document.getElementById("listingCount").innerHTML = "Updating..."
	}
}


function getAvailIFrame() {
	for(var i=1;i<11;i++) {
		var strID = "iframe"+i
		var iframe = document.getElementById(strID)
		if(iframe.readyState == "complete") {
			return iframe.id
		}
	}
}


function callBack(s,elems,midls,highs) {
	var myForm = document.forms[0]
	window.clearTimeout(propsTimer)
	intPropsCount = 0
	document.getElementById("listingCount").innerHTML = s;
	if(elems.length !=0) {
		reBuildCombo(myForm.cboElem,elems)
	}
	if(midls.length !=0) {
		reBuildCombo(myForm.cboMidl,midls)
	}
	if(highs.length != 0) {
		reBuildCombo(myForm.cboHigh,highs)
	}
}


var intPropsCount = 0
var propsTimer
function propsWait() {
	if(intPropsCount==0) {
		document.getElementById("listingCount").innerHTML = "."
	}
	else {
		document.getElementById("listingCount").innerHTML += "."
	}
	intPropsCount = (intPropsCount==5) ? 0 : intPropsCount + 1
}


function reBuildCombo(cbo,strItems) {
	var a = strItems.split("~")
	cbo.length = 1
	for(var i=0;i<a.length-1;i++) {
		if(a[i].length != 0) {
			cbo.options[cbo.options.length] = new Option(a[i],a[i])
		}
	}
}

var intCurrentWait = 4;
var ShowWaitTimeout;

function toggleCombos(state) {
	var combos = document.body.getElementsByTagName("SELECT")
	for(var i=0;i<combos.length;i++) {
		var combo = combos[i];
		combos[i].style.visibility = state;
	}
}


function ShowWaiting(msg) {
	//toggleCombos('hidden')
	
	var waitText = document.getElementById('waitText');
	if(waitText) waitText.innerHTML = msg;
	
	var pleaseWait = document.getElementById('pleaseWait');
	if(pleaseWait) pleaseWait.style.display = '';
	
	var pageBody = document.getElementById('pageBody');
	if(pageBody) pageBody.style.display = 'none';
}

function HideWaiting() {
	document.getElementById("pleaseWait").style.display = "none";
	//toggleCombos("visible")
	document.getElementById("pageBody").style.display = "";
	window.clearTimeout(ShowWaitTimeout);
}

function listingDetail(id,url) {
	ko()
	
	if(location.host.toLowerCase().indexOf('sharonlockwood') > -1)
	{
    // temp fix for sharonlockwood.com 1/09/2008 1:58 pm   mitch @ 870 743-2947
      //url=applyAppPathModifier("~/detail.aspx?cls=" + id); returns missing  _appPathRoot error
	  url="http://www.recls.com/Detail.aspx?cls="+ id; //static
	}else
	url = url || applyAppPathModifier("~/detail.aspx?cls=" + id);

	_childWin = window.open(url, "listingDetail", "resizable=yes,scrollbars=yes,toolbar=no")
	if(location.host.toLowerCase().indexOf('sharonlockwood') < 0) //avoid "access denied" error from 
	{                                                             // sharonlockwood.com running window
	  resz(_childWin);                                            //  resize script from this server.
	}	  
	
	if(_childWin == null) {
		alert('Your browser has a pop-up blocker enabled.\n\nPlease set it to allow popup windows for this site.');
		return false;
	}

	_childWin.focus()
}

// called from sharon's site (maybe?)
function showMlsDetail(id) {
	return listingDetail(id);
}

function floor(number) {
  return Math.floor(number*Math.pow(10,2))/Math.pow(10,2);
}

function dosum() {
  var mi = document.forms[0].txtMCInt.value / 1200;
  var base = 1;
  var mbase = 1 + mi;
  for (i=0; i<document.forms[0].txtMCYrs.value * 12; i++)
  {
    base = base * mbase
  }
  document.all.lblMCPrinPlusInt.innerHTML = FormatCurrency(floor(document.forms[0].txtMCLoanAmt.value * mi / ( 1 - (1/base))),2,true,false,true)
  document.all.lblMCMonthlyTax.innerHTML = FormatCurrency(floor(document.forms[0].txtMCAnnualTax.value / 12),2,true,false,true)
  document.all.lblMCMonthlyIns.innerHTML = FormatCurrency(floor(document.forms[0].txtMCAnnualIns.value / 12),2,true,false,true)
  var dasum = document.forms[0].txtMCLoanAmt.value * mi / ( 1 - (1/base)) +
        document.forms[0].txtMCAnnualTax.value / 12 + 
        document.forms[0].txtMCAnnualIns.value / 12;
  document.all.lblMCTotalPmt.innerHTML = FormatCurrency(floor(dasum),2,true,false,true);
}


function changeAmt(val) {
    var pct = parseFloat(val)
    var price = document.getElementById("lblPrice").innerText.replace(/[^\d]/g,"")
    document.forms[0].txtMCLoanAmt.value = pct * price
}

function FormatCurrency(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
{
	var tmpStr = FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas).toString();

	if (tmpStr.indexOf("(") != -1 || tmpStr.indexOf("-") != -1) 
	{
		if (tmpStr.charAt(0) == "(")
			tmpStr = "($"  + tmpStr.substring(1,tmpStr.length);
		else if (tmpStr.charAt(0) == "-")
			tmpStr = "-$" + tmpStr.substring(1,tmpStr.length);
			
		return tmpStr;
	}
	else
        {
		
		return "$" + tmpStr;		
		
        }
}

function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
{ 

  	if (isNaN(parseInt(num))) 
  		return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		
	
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))	
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;	
	
	var tmpNumStr = tmpNum.toString();

	if (decimalNum == 2) {      //only works for 2 decimal places (currency)	    
	    if (tmpNumStr.indexOf(".") == -1)
	    	tmpNumStr = tmpNumStr + ".00";
	    else if (tmpNumStr.length - tmpNumStr.indexOf(".") == 1)
	           tmpNumStr = tmpNumStr + "00";
	    else if (tmpNumStr.length - tmpNumStr.indexOf(".") == 2)
	           tmpNumStr = tmpNumStr + "0";
         }


	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	if (bolCommas && (num >= 1000 || num <= -1000)) 
	{
		tmpNumStr = iSign == 1 ? tmpNumStr : tmpNumStr.substr(1)
			
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) 
		{
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
		tmpNumStr = iSign == 1 ? tmpNumStr : "-" + tmpNumStr
	}
	
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;
}

var reImg = /[^\/]+\.jpg[\d\D]*/
function showImg(id) {
    document.getElementById("lrgImg").src = document.getElementById("lrgImg").src.replace(reImg,id)
}

function showImage(path) {
	var img = document.getElementById("lrgImg");
	img.src = path;
	return false;
}

function deleteRental(link,id) {

	while(link.tagName != "TR") {
		link = link.parentNode
	}
	link.style.backgroundColor = "#FFFFCC"
	if(window.confirm("Are you sure you want to delete this listing?")) {
		document.forms[0].hidID.value = id
		document.forms[0].action = applyAppPathModifier("~/deleterental.aspx")
		document.forms[0].method = "post"
		document.forms[0].submit()
	}
	else {
		link.style.backgroundColor = ""
	}
}


function editRental(id) {
	var df = document.forms[0]
	if(id == null) {
		df.hidID.value = "NEW"
	}
	else {
		df.hidID.value = id
	}
	df.action = applyAppPathModifier("~/EditRental.aspx");
	df.method = "post"
	df.submit()
}

var reUSPhone 
var reNonDigits = /\D/g
var reDigits = /\d{7}|\d{10,11}/
var rePhone = /(\d{3})(\d{4})/
var reFullPhone = /(\d{3})(\d{3})(\d{4})/

function formatPhone(field) {
	var s = field.value
	s = s.replace(reNonDigits,"")
	if(reDigits.test(s)) {
		if(s.substr(0,1) == "1") {
			 s = s.substr(1)
		}
		if(s.length==7) {
			field.value = "(479) " + s.replace(rePhone,"$1-$2")
		}
		else {
			field.value = s.replace(reFullPhone,"($1) $2-$3")
		}
	}
	
}

function confirmDelete(title,elem) {
	if(elem.selectedIndex && elem.selectedIndex < 0) {
		alert("No " + title + " is selected.  Please select one and try again.");
		return false;
	}	
	
	var prevClass = elem.className;
	elem.className = "yellowSelect";
	
	if(confirm("Are you sure that you want to delete the selected " + title + "?")) {
		return true;
	}
	else {
		elem.className = prevClass;
		return false;
	}
}