var isIE;
if(navigator.appName == "Netscape")
{
	isIE = false;
}
else
{
	isIE = true;
}

var agent = navigator.userAgent.toLowerCase();
var windowHeight=(screen.height<= 600 && agent.indexOf("mac")==-1)?500:657;
var sh = screen.availHeight - (screen.availHeight/2);
var sw = screen.availWidth - (screen.availWidth/2);

function AddDays(dateStr, numDays)
{
	var returnDate = new Date(dateStr);
	returnDate.setTime(returnDate.getTime()+60000*60*24*numDays);
	return returnDate;
}
	
function ViewDetail()
{
	winPopup.height = 600;
	winPopup.width = 780;
	winPopup.top = screen.availHeight - (screen.availHeight/2) -(winPopup.height/2);
	winPopup.left = screen.availWidth - (screen.availWidth/2) -(winPopup.width/2);
	winPopup.url = "PropertyDetail.aspx";
	winPopup.open();
}

function GetArgs(s)
{
	//returns name/value objects from a querystring
	var args = new Object()
	if(s.indexOf("?") == -1)
		var query = s;
	else
		var query = s.substring(s.indexOf("?")+1);
	var pairs = query.split("&");
	
	for(var i=0;i<pairs.length;i++)
	{
		var pos = pairs[i].indexOf("=");
		if (pos == -1) continue;
		var argname = pairs[i].substring(0,pos).toLowerCase();
		var value = pairs[i].substring(pos+1);
		args[argname] = unescape(value);
	}
	return args;
}

var visibleDivs = new Array();

function PrintMe()
{
	
	//Get any DIVs that may exist on page
	var arrDivs = document.getElementsByTagName("div");
	
	//if the page to be printed has DIVs, the following code will hide them.
	if(arrDivs.length > 0)
	{
		var j = 0
		for(i = 0; i < arrDivs.length; i++)
		{
			var div = arrDivs[i];
			if((div.style.visibility == "visible") && (div.id.indexOf("pnl") < 0))
			{
				visibleDivs[j] = div;
				visibleDivs[j].style.visibility = "hidden";
				j++; 
			}
		}
	}
	
	//Prints the contents of the frmData window.
	window.parent.frames["frmData"].focus();
	window.parent.frames["frmData"].print();
	
	//If there were DIVs that were hidden, they will now be restored.
	if(arrDivs.length > 0)
	{
		setTimeout('RestoreDivs()',6000);
	}
}
	
function RestoreDivs()
{
	for(k=0; k< visibleDivs.length; k++)
	{
		visibleDivs[k].style.visibility = "visible";
	}
}

function setCookie(name, value, expires)
{
	document.cookie = name + "=" + escape(value) + "; path=/" + 
	((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
	
function getCookie(name)
{
	var cookieName = name + "=";
	var objCookie = document.cookie;
	var cookieStart;
	var cookieEnd;
	if(objCookie.length > 0)
	{
		cookieStart = objCookie.indexOf(cookieName);
		if(cookieStart != -1)
		{
			cookieStart += cookieName.length;
			cookieEnd = objCookie.indexOf(";",cookieStart);
			if(cookieEnd == -1)
			{
				cookieEnd = objCookie.length;
			}
			return unescape(objCookie.substring(cookieStart,cookieEnd));
		}
	}
	return null;
}

function GetMonthlyPayment(amount,rate,term,type)
{
	var IsValid = true;
	
	if(isNaN(amount) || amount.length == 0)
	{
		alert("The mortgage amount that you entered is not numeric. Please enter a numeric value.");
		IsValid = false;
	}
	
	if(isNaN(rate))
	{
		alert("The interest rate that you entered is not numeric. Please enter a numeric value.");
		IsValid = false;
	}
	
	if(isNaN(term))
	{
		alert("The loan term that you entered is not numeric. Please enter a numeric value.");
		IsValid = false;
	}
		
	if(IsValid)
	{
		if(parseFloat(rate) >= 0.01 && parseFloat(rate) <= 99.99)
		{
			var totalPayments = parseInt(term) * 12;
			var monthlyInterest =  rate/1200;
			var principal = parseFloat(amount);
			var num = Math.pow(1 + monthlyInterest, totalPayments);
			
			var monthly = 0.00;
			
			if(type == 'PI')
				monthly = principal * monthlyInterest * num / (num - 1);
			else
				monthly = principal * monthlyInterest;
	
			return formatCurrency(monthly);
		}
		else
		{
			alert("The interest rate must be a number between 0 and 100.");
			return "Error";
		}
	}
}

function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
}

function SetDropDown(dropDown, values)
{
	var v = "[" + values.replace(",","],[") + "]";
	
	for(var i=0; i<dropDown.length; i++)
	{
		if(v.indexOf("[" + dropDown[i].value + "]")>-1)
		{
			dropDown[i].selected = true;
		}
	}
}

function finOptions(downPayment,downPercent,rate,term,type)
{
	this.downPayment = downPayment;
	this.downPercent = downPercent;
	this.rate = rate;
	this.term = term;
	this.type = type;
}

function GetFinOptionsFromCookie()
{
	var val = getCookie("finOptions");
	if(val!=null)
	{
		var a = val.split(",");
		return new finOptions(a[0],a[1],a[2],a[3],a[4]);
	}
	else
	{
		return null;
	}
}	

function IsValidEmailAddress(strAddress)
{
	//Author: Dave Duran (dave.duran@soniceagle.com)
	//Credit: Peter-Paul Koch http://www.xs4all.nl/~ppk/
	//returns true if strAddress is a valid email address user@domain.
	//does not support friendly names i.e. "Joe User <joe@domain.com>"
	strAddress = strAddress.replace(/^\s+/,'').replace(/\s+$/,'');
	var reFilter = /^([a-zA-Z0-9_\.\-\'])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return (reFilter.test(strAddress));
}

function trim(str)
{
   return str.replace(/^\s*|\s*$/g,"");
}

// ------------------ BEGIN POPUP CODE --------------------

	// popup window object, set properties (e.g. url, width, height) and then open it
	// it will cascade closing of children popups when you leave the current screen
	function noError()
	{
		// ignore this error - use to avoid permission denied errors when crossing http/https windows
		// may leave some windows open in this circumstance
		return true;
	}
	var oldErrorHandler = window.onerror
	window.onerror = noError

	// keep and array of windows on the original opener 
	// we use this only to count the total windows to give them a unique windowname
	// without the unique name we will end up closing the wrong windows
	try
	{
		var popups = window.opener.getPopups();
	}
	catch (e)
	{ 
		var popups = new Array();
	}
	window.onerror = oldErrorHandler	
	// myChildren holds the windows that this window (may be a second or third level popup) has opened
	myChildren = new Array();

	function getPopups()
	{
		// function called by child popup to get back to opener's list of popups
		return popups
	}

	function popupWindow()
	{
		this.fullscreen = "no"
		this.toolbar= "no";
		this.status= "no"
		this.menubar = "no"
		this.scrollbars = "yes"
		this.resizable="yes"
		this.directories="no"
		this.location="no"
		this.width="300"
		this.height="400"
		this.top="100"
		this.left="100"
		this.url ="";
		this.open = function (fNew) 
		{	
		// remove any closed child windows from the array
			count = myChildren.length;
			for (var i=0; i<count; i++)
			{
				if (myChildren[myChildren.length-1].closed)
					myChildren.slice(myChildren.length-1, 1);
			}
										
			var fNeeded = true;
			if ( (myChildren.length > 0) && !fNew  ) 
			{
				// resuse an existing popup (the last one created)
				if(!myChildren[myChildren.length - 1].closed)
				{
					myChildren[myChildren.length - 1].location = this.url;
					myChildren[myChildren.length - 1].resizeTo(this.width,this.height);					
					myChildren[myChildren.length - 1].focus();					
					fNeeded = false;
				}
			} 
			
			// need to create (not reuse) a new popup
			if (fNeeded)
			{
				// MUST have a unique name
				this.windowname = "wPopup" + popups.length
				if ((this.height > 500) && (screen.height <= 600) && (agent.indexOf("mac")==-1)) this.height = 500;
				// create the window and add it to the myChildren array
				if (this.url.indexOf('http') == -1)
					this.url = 'http://' + window.location.hostname + this.url;
				myChildren[myChildren.length] = window.open(this.url ,this.windowname,
					'fullscreen=' + this.fullscreen + 
					',toolbar=' + this.toolbar + 
					',status=' + this.status + 
					',menubar=' + this.menubar + 
					',scrollbars=' + this.scrollbars + 
					',resizable=' + this.resizable +  
					',directories=' + this.directories + 
					',location=' + this.location +
					',width=' + this.width + 
					',top=' + this.top +
					',left=' + this.left + 
					',height=' + this.height)
				// also add it to the opener array so we have an accurate count
				popups[popups.length] = myChildren[myChildren.length -1];
				// every window will take care of closing its children
				window.onunload = this.close;
				if(myChildren[myChildren.length -1])
				{
					myChildren[myChildren.length -1].focus();				
					this.pWindow = myChildren[myChildren.length -1];
				}
			}
		}		
		this.close = function()
		{
			// go through the children - newest to oldest and close
			count = myChildren.length;
			for (var i=0; i<count; i++)
			{
				if (myChildren[myChildren.length - 1]  && !myChildren[myChildren.length-1].closed)
					myChildren[myChildren.length-1].close();
				if (myChildren.length > 0)
					myChildren = myChildren.slice(0, myChildren.length-1);
			}
		}		
	}
	var winPopup = new popupWindow();
	
	// ------------------ END POPUP CODE --------------------
	

	function possiblePhone(sender, args)
	{
		if (args)
		{
			var reg = /[\D]+/i;
			var str = args.Value;
			str = str.replace(reg, "");
			args.IsValid = str.length > 6;
		} else
			args.IsValid = true;		
	}
	
	function formatPhone(field)
	{
		field.value = trim(field.value);
		var ov = field.value;
		var v = "";
		var x = -1;

		// is this phone number 'escaped' by a leading plus?
		if (0 < ov.length && '+' != ov.charAt(0)) { // format it
			// count number of digits
			var n = 0;

			if ('1' == ov.charAt(0))
			{
				// skip it
				ov = ov.substring(1, ov.length);
			}

			for (i = 0; i < ov.length; i++)
			{
				var ch = ov.charAt(i);

				// build up formatted number
				if (ch >= '0' && ch <= '9')
				{
					if (n == 0)
						v += "(";
					else if (n == 3)
						v += ") ";
					else if (n == 6)
						v += "-";

					v += ch;
					n++;
				}

				// check for extension type section;
				// are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?
				if (! (ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')')
				{
					x = i;
					break;
				}
			}

			// add the extension
			if (x >= 0)
				v += " " + ov.substring(x, ov.length);

			// if we recognize the number, then format it
			if (n == 10 && v.length <= 40)
				field.value = v;
		}

		return true;
	}
function showPhotoTour(mlsID,classID,listingID)
{
	if(document.getElementById("propPhoto").src.indexOf("map.aspx") == -1)
		isMap = "no";
	else
		isMap = "yes";
		
	window.open('/Search/PhotoTour.aspx?mlsID=' + mlsID + '&classID=' + classID + '&listingID=' + listingID + '&isMap=' + isMap,'PhotoTour','fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=yes,resizable=yes,directories=no,location=no,width=800,height=600');
}

function SetMasterTableWidth()
{
	var masterTable = document.getElementById("masterTable");
	if (!masterTable) masterTable = document.getElementById("tblMaster");
	try
	{
		masterTable.width=parent.masterWidth
	}
	catch(e)
	{
		// we aren't in a sonic eagle frameset - just fill the window
		if (masterTable)
			masterTable.width = "100%";
	}
}
function ShowTitle() 
{
	try 
	{
		parent.window.document.title = window.document.title;
	}
	catch(e)
	{}
} 	