//<![CDATA[
// Global Variables
var detail_message_offset;
var det_last_tab = '1';

// Animation Constants
var SHOWSIGNINFORMAPPEARDURATION = 1.2;
var SHOWSIGNINFORMHIGHLIGHTDURATION = 2.2;
var PROCESSSIGNINFADEDURATION = 1.2;
var PROCESSSIGNINAPPEARDURATION = 1.2;
var PROCESSSIGNINHIGHLIGHTDURATION = 2.2;
var DETAIL_REQUEST_MORE_INFOAPPEARDURATION = 1.2;
var DETAIL_REQUEST_MORE_INFOHIGHLIGHTDURATION = 2.2;
var DETAIL_REQUEST_MORE_INFO_SENDHIGHLIGHTDURATION = 2.2;
var DETAIL_REQUEST_MORE_INFO_SENDFADEDURATION = 1.2;
var DETAIL_REQUEST_CANCELFADEDURATION = 0.7;
var DETAIL_SCHEDULE_SHOWINGAPPEARDURATION = 1.2;
var DETAIL_SCHEDULE_SHOWINGHIGHLIGHTDURATION = 2.2;
var DETAIL_SCHEDULE_SHOWING_SENDFADEDURATION = 1.2;
var DETAIL_SCHEDULE_SHOWING_SENDHIGHLIGHTDURATION = 2.2;
var DETAIL_EMAIL_LISTINGAPPEARDURATION = 1.2;
var DETAIL_EMAIL_LISTINGHIGHLIGHTDURATION = 2.2;
var DETAIL_EMAIL_LISTING_SENDHIGHLIGHTDURATION = 2.2;
var DETAIL_EMAIL_LISTING_SENDFADEDURATION = 1.2;
var DETAIL_MORTGAGE_CALCULATORAPPEARDURATION = 1.1;
var DETAIL_MORTGAGE_CALCULATORHIGHLIGHTDURATION = 1.8;
var DETAIL_MESSAGE_OFFSET = -24;
var DETAIL_MAIN_CONTAINER_OFFSET = -90;

////////////////////////////////////////////////////////////////////////////////////////////////
// ON LOAD FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////
//dojo.addOnLoad(function() {
Event.observe( window, 'load', function() {	
	addClientOnLoad();
	addOnLoad();
} );


////////////////////////////////////////////////////////////////////////////////////////////////
// SUGGEST REGISTRATION
////////////////////////////////////////////////////////////////////////////////////////////////
// Show an overlay touting the benefits of site registration.  Used to suggest registration (rather than require it).
function showSuggestRegisterOverlay(listingid, mlsregionid, actiontype, whichOverlay) {
	var params = $H({
		requestlistingid: listingid,
		requestmlsregionid: mlsregionid,
		requestactiontype: actiontype,
		initialize: 'true'
		}).toQueryString();
	
	//document.location.href = '/property-search/sist_ajax/' + whichOverlay + '?' + params;
	onClickLightbox('/property-search/sist_ajax/' + whichOverlay + '?' + params, 640, 475)	
	
}

// Switches from the suggestion overlay to the actual sign up form.
function switchFromSuggestToRegister(saveSearch) {
	var requestContainer = $('requestContainer');
	var overlayContainer = $('overlayContainer');
	
	var params = $H({
	requestlistingid: $F('requestlistingid'),
	requestmlsregionid: $F('requestmlsregionid'),
	requestactiontype: $F('requestactiontype')
	}).toQueryString();		
	
	//alert('params: ' + params);
	
	var bindArgs = {
	method: 'post',
	parameters: params,
	onFailure: function(t){
		//alert(t.responseText);
		alert('An error occurred and we could not send your request.  Please try again.');
	},
	onSuccess: function(t){
		overlayContainer.innerHTML = t.responseText;
		$('registerfirstname').focus();
	}
	};	
	
	$('suggestsubmit').value = 'Loading Registration Form...';
	new Ajax.Request('/property-search/sist_ajax/sign_in_register_overlay.asp', bindArgs);	
}

//
// Shows the sign in / register form on a detail page when the site owner requires registration for full access
//
function showSignInRegisterOverlay(listingid, mlsregionid, actionType) {
	var params = $H({
		requestlistingid: listingid,
		requestmlsregionid: mlsregionid,
		requestactiontype: actionType
	}).toQueryString();	
	
	//document.location.href = '/property-search/sist_ajax/sign_in_register_overlay.asp?' + params;
	onClickLightbox('/property-search/sist_ajax/sign_in_register_overlay.asp?' + params, 640, 475)
}

//
// Processes the sign in / register form
//
function processSignInRegisterOverlay() {
	
	var requestContainer = $('requestContainer');
	var signInRegisterContainer = $('signInRegisterContainer');
	var signInRegisterHeader = $('signInRegisterHeader');
	
	var params1 = $H({
	area: $F('area'),
	basement: $F('basement'),
	condoprojectname: $F('condoprojectname'),
	construction: $F('construction'),
	county: $F('county'),
	energy: $F('energy'),
	exterior: $F('exterior'),
	interior: $F('interior'),
	lacreage: $F('lacreage'),
	lbaths: $F('lbaths'),
	lbeds: $F('lbeds'),
	listtypedescrip: $F('listtypedescrip'),
	lprice: $F('lprice'),
	lsqft: $F('lsqft'),
	mage: $F('mage'),
	style: $F('style'),
	subarea: $F('subarea'),
	subdivision: $F('subdivision'),
	uprice: $F('uprice')
	}).toQueryString();		
	//alert('params1: ' + params1);
	
	var params2 = $('frmRegister').serialize();
	//alert('params2: ' + params2);
	
	var params = params1 + "&" + params2;
	//alert('params: ' + params);
	
	//window.location.href = '/pages/sign_in_register_process.asp?' + params;
	
	var bindArgs = {
	method: 'post',
	parameters: params,	
	onFailure: function(t){
		//alert(t.responseText);
		//createCookie('siSignedIn','true',730);
		requestContainer.innerHTML = '';
		closeLightbox();
		return false;
	},
	onSuccess: function(t){
		
		var returnVal = parseFloat(t.responseText);
		
		if (returnVal == -2) {
			$('register_already_taken').style.display = '';
			$('registersubmit').value = 'Register Now';
			return false;
		} else if (returnVal <= 0) {
			$('register_error').style.display = '';
			$('registersubmit').value = 'Register Now';
			return false;
		} else if (returnVal >= 1) {
			signedin = true;
			loggedin = true;
			createCookie('siSignedIn','true',730);
			
			new Ajax.Updater('requestContainer','/property-search/sist_ajax/successful_registration_overlay.asp',{asynchronous:false}); 
			
			//signInRegisterHeader.innerHTML = 'Success! Your Registration Is Complete';		
			//signInRegisterContainer.innerHTML = '<strong>Thank you for registering.</strong><br /><br />';
			//signInRegisterContainer.innerHTML += 'You now enjoy full access to all site search tools.<br /><br />';
			//signInRegisterContainer.innerHTML += '<input type=\"button\" name=\"registerclose\" id=\"registerclose\" value=\"Close\" onclick=\"closeLightbox();\" class=\"button2\" style=\"color: #000000; width: 100px;\" />';
			
			//$('signInRegisterContainer').style.padding = '40px 25px 40px 25px';
			//new Effect.Highlight($('signInRegisterContainer'), {queue: 'end', duration: 8.0, startcolor: highlight_startcolor, endcolor: highlight_endcolor, afterFinish: function() { closeLightbox(); } });
			
			return false;
		}
		
		return false;
	}
	};	
	
	// Validate the form contents before submitting
	var email = IsValidEmail($('registeremail'));
	var emailIsEmpty = IsEmpty($('registeremail'))
	var first = IsEmpty($('registerfirstname'));
	var pass = IsEmpty($('registerpassword'));
	 
	if (!first){
		$('registerfirstname').value = Trim($('registerfirstname'));
		$('registerfirstname').value = ucFirst($('registerfirstname'));
	}
	var last = IsEmpty($('registerlastname'));
	if (!last){
		$('registerlastname').value = Trim($('registerlastname'));
		$('registerlastname').value = ucFirst($('registerlastname'));
	}
	
	// Check to see if this site wants phone number to be a required field (set in si_client.js)
	var phone = true;
	
	if ((require_phone_number == true) || ($F('registerphone') != '')) {
		phone = IsValidPhoneNumber($('registerphone'));
		//alert('phone: ' + phone);
	}

	// if all data is valid, form is processed... else error message is displayed
	if (email && !first && !last && !pass && phone) {
		$('registersubmit').value = 'Submitting...';
		//$('registersubmit').disabled = true;
		new Ajax.Request('/property-search/sist_ajax/sign_in_register_process.asp', bindArgs);
		return false;
	} else if (!phone) {
		alert('Please enter a valid ten digit phone number.');
		$('registerphone').focus();
		return false;		
	} else if (emailIsEmpty || first || last || pass || ((require_phone_number == true) && (!phone))) {
		alert('Please enter all of the required fields.');
		if (first) { $('registerfirstname').focus(); }
		else if (last) { $('registerlastname').focus(); }
		else if (emailIsEmpty) { $('registeremail').focus(); }
		else if (pass) { $('registerpassword').focus(); }
		else if ((require_phone_number == true) && (!phone)) { $('registerphone').focus(); }
		return false;

	} else if (!email) {
		alert('Please enter a valid email address.');
		$('registeremail').focus();
		return false;
	}
	
	return false;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// SIGN IN SEARCH FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Shows the sign in / register form on a detail page when the site owner requires registration for full access
//
function showSignInRegisterForm(mls) {	
	var sign_in = $('sign_in');	
	var detail_container_inner = $('detail_container_inner');
	
	sign_in.innerHTML='<div style="margin-top: 20px; margin-bottom: 40px;  font-size: 12px; font-weight: bold;"><img src="/property-search/res/images/loading_big.gif" align="absmiddle"><strong> Loading. Please wait....</strong></div>';
	sign_in.show();
	detail_container_inner.hide();
	
	var params = $H({
		mls: mls
		}).toQueryString();	
	
	var bindArgs = {
	method: 'get',
	parameters: params,	
	onFailure: function(){
		sign_in.innerHTML='';
		sign_in.hide();
		detail_container_inner.show();
	},
	onSuccess: function(t){
		sign_in.innerHTML=t.responseText;
		new Effect.Appear(sign_in, {queue: 'end', duration: SHOWSIGNINFORMAPPEARDURATION});
		new Effect.Highlight(sign_in, {queue: 'end', duration: SHOWSIGNINFORMHIGHLIGHTDURATION, startcolor: highlight_startcolor, endcolor: highlight_endcolor});						
	}
	};
	
	new Ajax.Request('/property-search/sist_ajax/sign_in_register.asp', bindArgs);	
}
//
// Processes the sign in / register form
//
function processSignInRegister() {
	
	var sign_in = $('sign_in');	
	var detail_container_inner = $('detail_container_inner');	
	var signin_message = $('signin_message');
	
	var params1 = $H({
	area: $F('area'),
	basement: $F('basement'),
	condoprojectname: $F('condoprojectname'),
	construction: $F('construction'),
	county: $F('county'),
	energy: $F('energy'),
	exterior: $F('exterior'),
	interior: $F('interior'),
	lacreage: $F('lacreage'),
	lbaths: $F('lbaths'),
	lbeds: $F('lbeds'),
	listtypedescrip: $F('listtypedescrip'),
	lprice: $F('lprice'),
	lsqft: $F('lsqft'),
	mage: $F('mage'),
	style: $F('style'),
	subarea: $F('subarea'),
	subdivision: $F('subdivision'),
	uprice: $F('uprice')
	}).toQueryString();		
	//alert('params1: ' + params1);
	
	var params2 = $('frmRegister').serialize();
	//alert('params2: ' + params2);
	
	var params = params1 + "&" + params2;
	//alert('params: ' + params);
	//alert('b:');
	//window.location.href = '/property-search/sist_ajax/sign_in_register_process.asp?' + params;
	
	var bindArgs = {
	method: 'post',
	parameters: params,	
	onFailure: function(t){
		//alert(t.responseText);
		//createCookie('siSignedIn','true',730);
		sign_in.innerHTML='';
		$(sign_in).hide();
		$(detail_container_inner).show();
		
		return false;
	},
	onSuccess: function(t){
		
		var returnVal = parseFloat(t.responseText);
		//alert(t.responseText);
		
		if (returnVal == -2) {
			$('register_already_taken').style.display = '';
			$('registersubmit').value = 'Submit';
			$('registersubmit').style.width = '80px';
		} else if (returnVal <= 0) {
			$('register_error').style.display = '';
			$('registersubmit').value = 'Submit';
			$('registersubmit').style.width = '80px';
		} else if (returnVal >= 1) {
			signedin = true;
			loggedin = true;
			createCookie('siSignedIn','true',730);
			signin_message.innerHTML = '<strong>Thank you for registering.</strong>&nbsp;&nbsp;And don\'t forget to save your search to get the new listings you want emailed daily.';
	
			new Effect.Fade(sign_in, {queue: 'end', duration: 0.2});
			new Effect.Appear(detail_container_inner, {queue: 'end', duration: 0.2});
			new Effect.Appear(signin_message, {queue: 'end', duration: 0.2});
			new Effect.ScrollTo(detail_container_inner, {queue: 'end', offset: -40});
			new Effect.Highlight(signin_message, {queue: 'end', duration: 5.0, startcolor: highlight_startcolor, endcolor: highlight_endcolor});
			new Effect.BlindUp(signin_message, {queue: 'end', duration: 0.3});
		}
		
		return false;
	}
	};	
	
	// Validate the form contents before submitting
	var email = IsValidEmail($('registeremail'));
	var emailIsEmpty = IsEmpty($('registeremail'))
	var first = IsEmpty($('registerfirstname'));
	if (!first){
		$('registerfirstname').value = Trim($('registerfirstname'));
		$('registerfirstname').value = ucFirst($('registerfirstname'));
	}
	var last = IsEmpty($('registerlastname'));
	if (!last){
		$('registerlastname').value = Trim($('registerlastname'));
		$('registerlastname').value = ucFirst($('registerlastname'));
	}
	
	// Check to see if this site wants phone number to be a required field (set in si_client.js)
	var phone = true;
	
	if ((require_phone_number == true) || ($F('registerphone') != '')) {
		phone = IsValidPhoneNumber($('registerphone'));
	}
	
	var registerTC = false;
	
	if ($('registerTC').checked == true) { registerTC = true }

	// if all data is valid, form is processed... else error message is displayed
	if (email && !first && !last && phone && registerTC) {
			$('registersubmit').value = 'Processing Info...';
			$('registersubmit').style.width = '145px';	
			new Ajax.Request('/property-search/sist_ajax/sign_in_register_process.asp', bindArgs);
	} else if (!phone) {
		alert('Please enter a valid ten digit phone number.');
		$('registerphone').focus();
		return false;
	} else if (emailIsEmpty || first || last || ((require_phone_number == true) && (!phone))) {
		alert('Please enter all of the required fields.');
		return false;
	} else if (!email) {
		alert('Please enter a valid email address.');
		$('registeremail').focus();
		return false;
	} else if (!registerTC) {
		alert('Please read the Terms and Conditions / Privacy Policy and check the box to proceed.');
		$('registerTC').focus();
		return false;
	}
	
	return false;
}

// Process login of existing user on sign in / register form on sites where client requires registration for full access
function processSignInLogin() {	
	
	var sign_in = $('sign_in');	
	var detail_container_inner = $('detail_container_inner');	
	var signin_message = $('signin_message');
	
	var bindArgs = {
	asynchronous: false,
	method: 'post',
	postBody: 'email=' + $F('signinemail') + '&password=' + $F('signinpassword') + '&remember=' + $F('signinremember') + '&siteid=' + siteid,
	onFailure: function(t){
		//alert(t.responseText);
		alert('An error occurred and we could not send your login request.  Please try again.');
		$('signinloginsubmit').value = 'Login';
		$('signinloginsubmit').style.width = '80px';			
	},		
	onSuccess: function(t){
		var returnVal = parseFloat(t.responseText);
		// Login unsuccessful
		if (returnVal <= 0) { // incorrect username or password
			$('signin_login_incorrect').show();
			$('signinloginsubmit').value = 'Login';
			$('signinloginsubmit').style.width = '80px';				
		} else { 			
			//  set the javascript variables to logged in
			userid = returnVal;
			loggedin = true;
			signedin = true;
			
			createCookie('siSignedIn','true',730);

			// set userid field in form
			if ($('userid')) { $('userid').value = userid }
			
			signin_message.innerHTML = '<strong>Thank you for logging in.</strong>&nbsp;&nbsp;And don\'t forget to save your search to get the new listings you want emailed daily.';
	
			new Effect.Fade(sign_in, {queue: 'end', duration: 0.2});
			new Effect.Appear(detail_container_inner, {queue: 'end', duration: 0.2});
			new Effect.Appear(signin_message, {queue: 'end', duration: 0.2});
			new Effect.ScrollTo(detail_container_inner, {queue: 'end', offset: -40});
			new Effect.Highlight(signin_message, {queue: 'end', duration: 5.0, startcolor: highlight_startcolor, endcolor: highlight_endcolor});
			new Effect.BlindUp(signin_message, {queue: 'end', duration: 0.3});
		}
	}
	};	
	
	// Validate the form contents before submitting
	var email = IsValidEmail($('signinemail'));
	var emailIsEmpty = IsEmpty($('signinemail'))	
	var pass = IsEmpty($('signinpassword'));
	
	if (email && !pass) {	
		$('signinloginsubmit').value = 'Please Wait...';
		$('signinloginsubmit').style.width = '120px';	
		new Ajax.Request('/property-search/sist_ajax/login_process.asp',bindArgs);
	} else if (emailIsEmpty) {
		$('signinloginsubmit').value = 'Login';
		$('signinloginsubmit').style.width = '80px';		
		alert('Please enter your email address.');
		$('signinemail').focus();	
	} else if (!email) {
		$('signinloginsubmit').value = 'Login';
		$('signinloginsubmit').style.width = '80px';		
		alert('Please enter a valid email address.');
		$('signinemail').focus();			
	} else if (pass) {
		$('signinloginsubmit').value = 'Login';
		$('signinloginsubmit').style.width = '80px';		
		alert('Please enter your password.');
		$('signinpassword').focus();	
	}
}

function processOverlaySignInLogin() {	

	var detail_container_inner = $('detail_container_inner');	
	var signin_message = $('signin_message');
	
	var bindArgs = {
	asynchronous: false,
	method: 'post',
	postBody: 'email=' + $F('signinemail') + '&password=' + $F('signinpassword'),
	onFailure: function(t){
		//alert(t.responseText);
		alert('An error occurred and we could not send your login request.  Please try again.');
		$('signinloginsubmit').value = 'Login';
		$('signinloginsubmit').style.width = '80px';	
		
		return false;
	},		
	onSuccess: function(t){
		var returnVal = parseFloat(t.responseText);
		// Login unsuccessful
		if (returnVal <= 0) { // incorrect username or password
			$('signin_login_incorrect').show();
			$('signinloginsubmit').value = 'Login';
			$('signinloginsubmit').style.width = '80px';	
			
			return false;
		} else { 			
			//  set the javascript variables to logged in
			userid = returnVal;
			loggedin = true;
			signedin = true;
			
			createCookie('siSignedIn','true',730);

			// set userid field in form
			if ($('userid')) { $('userid').value = userid }
			
			signin_message.innerHTML = '<strong>Thank you for logging in.</strong>&nbsp;&nbsp;And don\'t forget to save your search to get the new listings you want emailed daily.';
			
			closeLightbox();
			new Effect.Appear(signin_message, {queue: 'end', duration: 0.2});
			new Effect.ScrollTo(detail_container_inner, {queue: 'end', offset: -40});
			new Effect.Highlight(signin_message, {queue: 'end', duration: 5.0, startcolor: highlight_startcolor, endcolor: highlight_endcolor});
			new Effect.BlindUp(signin_message, {queue: 'end', duration: 0.3});
			
			return false;
		}
	}
	};	
	
	// Validate the form contents before submitting
	var email = IsValidEmail($('signinemail'));
	var emailIsEmpty = IsEmpty($('signinemail'))	
	var pass = IsEmpty($('signinpassword'));
	
	if (email && !pass) {	
		$('signinloginsubmit').value = 'Please Wait...';
		$('signinloginsubmit').style.width = '120px';	
		new Ajax.Request('/property-search/sist_ajax/login_process.asp',bindArgs);
	} else if (emailIsEmpty) {
		$('signinloginsubmit').value = 'Login';
		$('signinloginsubmit').style.width = '80px';		
		alert('Please enter your email address.');
		$('signinemail').focus();	
		return false;
	} else if (!email) {
		$('signinloginsubmit').value = 'Login';
		$('signinloginsubmit').style.width = '80px';		
		alert('Please enter a valid email address.');
		$('signinemail').focus();			
		return false;
	} else if (pass) {
		$('signinloginsubmit').value = 'Login';
		$('signinloginsubmit').style.width = '80px';		
		alert('Please enter your password.');
		$('signinpassword').focus();	
		return false;
	}
	
	return false;
}

//
// Allows user to retrieve lost password
//
function retrieveSignInPassword() {
		
	var lost_password_container = $('signin_lost_password_container');
	var orig_contents = lost_password_container.innerHTML;
	
	var params = $H({
		email: $F('signinforgotemail'),
		siteid: siteid
		}).toQueryString();
	
	var bindArgs = {
	method: 'post',
	parameters: params,
	onFailure: function(){
		alert('An error occurred and we could not retrieve your password.  Please try again.');
		$('signinretrievesubmit').value = 'Retrieve Password';
		$('signinretrievesubmit').style.width = '140px';	
	},
	onSuccess: function(t){
		var returnVal = parseFloat(t.responseText);
		if (returnVal == -2) {
			$('signin_retrieve_not_found').show();
			$('signinretrievesubmit').value = 'Retrieve Password';
			$('signinretrievesubmit').style.width = '140px';			
		} else if (returnVal <= 0) {
			$('signin_retrieve_error').show();
			$('signinretrievesubmit').value = 'Retrieve Password';
			$('signinretrievesubmit').style.width = '140px';			
		} else {
			$(lost_password_container).hide();
			$('signin_retrieve_success').show();
			new Effect.Highlight($('signin_retrieve_success'), {queue: 'end', duration: 1.0, startcolor: highlight_startcolor, endcolor: highlight_endcolor});
		}
		
	}
	};	
	
	// Validate the form contents before submitting

	var email = IsValidEmail($('signinforgotemail'));
	
	if (email) {
		$('signinretrievesubmit').value = 'Please Wait...';
		new Ajax.Request('/property-search/sist_ajax/retrieve_password.asp', bindArgs);
	} 
	else {
		alert('Please enter a valid email address.');
		$('signinforgotemail').focus();
	}	
}

function retrieveOverlaySignInPassword() {
		
	var lost_password_container = $('signin_lost_password_container');
	var orig_contents = lost_password_container.innerHTML;
	
	var params = $H({
		email: $F('signinforgotemail'),
		siteid: siteid
		}).toQueryString();
	
	var bindArgs = {
	method: 'post',
	parameters: params,
	onFailure: function(){
		alert('An error occurred and we could not retrieve your password.  Please try again.');
		$('signinretrievesubmit').value = 'Retrieve Password';
		$('signinretrievesubmit').style.width = '140px';	
		
		return false;
	},
	onSuccess: function(t){
		var returnVal = parseFloat(t.responseText);
		if (returnVal == -2) {
			$('signin_retrieve_not_found').show();
			$('signinretrievesubmit').value = 'Retrieve Password';
			$('signinretrievesubmit').style.width = '140px';
			
			return false;
		} else if (returnVal <= 0) {
			$('signin_retrieve_error').show();
			$('signinretrievesubmit').value = 'Retrieve Password';
			$('signinretrievesubmit').style.width = '140px';
			
			return false;
		} else {
			$(lost_password_container).hide();
			$('signin_retrieve_success').show();
			new Effect.Highlight($('signin_retrieve_success'), {queue: 'end', duration: 1.0, startcolor: highlight_startcolor, endcolor: highlight_endcolor});
			
			return false;
		}
		
	}
	};	
	
	// Validate the form contents before submitting

	var email = IsValidEmail($('signinforgotemail'));
	
	if (email) {
		$('signinretrievesubmit').value = 'Please Wait...';
		new Ajax.Request('/property-search/sist_ajax/retrieve_password.asp', bindArgs);
	} 
	else {
		alert('Please enter a valid email address.');
		$('signinforgotemail').focus();
		
		return false;
	}	
	
	return false;
}

//
// Changes tabs on detail page
//
function change_det_tab(tab, site) {
  if (det_last_tab != tab) 
	document.getElementById('det_set_'+det_last_tab).style.display = 'none';
	
  document.getElementById('det_set_'+tab).style.display = 'block';
  det_selected_form = tab;

  document.getElementById('det_tab_'+det_last_tab).className = 'det_tab_inactive';
  document.getElementById('det_tab_'+det_last_tab).style.position = '';
  document.getElementById('det_tab_'+tab).className = 'det_tab_active';
  document.getElementById('det_tab_'+tab).style.position = 'relative';
  det_last_tab = tab;
}
//
// map for detail page tab
//
function mapDetail(lat,lon) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("mapdetail"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(lat,lon), 14);
		map.enableContinuousZoom();

		var point = new GLatLng(lat,lon);	
		baseIcon = new GIcon();
		baseIcon.shadow = "";
		baseIcon.iconSize = new GSize(18, 19);
		baseIcon.shadowSize = new GSize(18, 19);
		baseIcon.iconAnchor = new GPoint(9, 10);
		baseIcon.infoWindowAnchor = new GPoint(9, 7);


		var icon = new GIcon(baseIcon);
		icon.image = "/property-search/res/images/maps/house-main.png";
		var marker = new GMarker(point, icon);

		map.addOverlay(marker);
	}
	else
		write('Sorry, but your browser is not compatible with our maps.');
}
//
// Goes back to Search Results or Map Results from Detail view
//
function backtoSummary(searchType, newoffset, listingid) {
	$('detoffset').value = '';
	$('listingid').value = listingid;
	
	clearTimeout(m_intTimeOut);
	
	// If the user has paged through enough detail listings to be on a different search results page
	// we need to load the new results page into the Search Results and Map Results tabs
	if (newoffset != $('offset').value)
		$('offset').value = newoffset;
	
	full_search(searchType);
}
//
// Page back or forward through detail pages
//
function changeDetailPage(detail_offset, mlsregionid, mls, propaddress) {	
	$('detoffset').value=detail_offset;
	$('listingid').value='';
	if ($F('quicksearchid') != '1') { $('mls').value=''; }
	
	clearTimeout(m_intTimeOut);
	
	full_search_detail(mlsregionid, mls, propaddress);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// SLIDE SHOW FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////
var slideShowSpeed;
var crossFadeDuration;
var	Pic = new Array(); 
var	PicCaption = new Array();
var m_intTimeOut;
var m_intCurrentIndex;
var m_intArrayLen;
var preLoad;
//
// Adjust image size
//
function adjustImageSize() {
	var intStandardWidth = 300;
	var intWidth = 0;
	var intHeight = 0;
	var intPercentDif = 0;
	var intCurrentHeight = 0;
	var intTallestHeight = 0;
	var intCurrentHeight = 0;		
	var objImageArea = document.getElementById('ImageArea');
	
	for (i = 0; i < preLoad.length; i++) {//loop through images
		intHeight = preLoad[i].height; //get unaltered height
		intWidth = preLoad[i].width; //get unaltered width
		intPercentDif = intStandardWidth / intWidth; // make it the right size
		intHeight = intHeight * intPercentDif;
															
		if (intTallestHeight < intHeight)					
			intTallestHeight = intHeight;				
	}
	
	if (intTallestHeight > objImageArea.height)
		objImageArea.height = intTallestHeight + 5;	 //add 5 to avoid popping				
}
//
// Run the slide show
//
function runSlideShow() {
	
	//if there is more than one pic
	if (m_intArrayLen > 1)
		adjustImageSize();
		
	// if there is a SLIDE SHOW
	if (m_intArrayLen > 0) { 				
		m_intCurrentIndex = m_intCurrentIndex + 1;
		
		// reset back
		if (m_intCurrentIndex > (m_intArrayLen-1))
			m_intCurrentIndex = 0;
						
		displaySlide();	
		
		// reset first
		clearTimeout(m_intTimeOut);
		m_intTimeOut = setTimeout('runSlideShow()', slideShowSpeed);
	}
}
//
// Shows the previous slide
//
function showPrevSlide() {
	//if there is more than one pic
	if (m_intArrayLen > 1)
		adjustImageSize();
		
	// if there is a SLIDE SHOW
	if (m_intArrayLen > 0) {
		m_intCurrentIndex = m_intCurrentIndex - 1;
		
		// reset back
		if (m_intCurrentIndex < 0)
			m_intCurrentIndex=(m_intArrayLen-1);
		
		displaySlide();	
		
		// reset first
		clearTimeout(m_intTimeOut); 
	}
}
//
// Shows the next slide
//
function showNextSlide() {
	//if there is more than one pic
	if (m_intArrayLen > 1)
		adjustImageSize();

	// if there is a SLIDE SHOW
	if (m_intArrayLen > 0) {
		m_intCurrentIndex = m_intCurrentIndex + 1;
		
		// reset back
		if (m_intCurrentIndex > (m_intArrayLen-1))
			m_intCurrentIndex=0;
	
		displaySlide();	
		
		// reset first
		clearTimeout(m_intTimeOut);
	}
}
//
// Displays the slide
//
function displaySlide() {
	//if (document.all) {
	//	$('PictureBox').style.filter="blendTrans(duration=2)";
	//	$('PictureBox').style.filter="blendTrans(duration=crossFadeDuration)";
	//	$('PictureBox').filters.blendTrans.Apply();      
	//}
	
	$('PictureBox').src = preLoad[m_intCurrentIndex].src;
	//document.all.SlideShowCaption.InnerText= PicCaption[m_intCurrentIndex];
	
	$('ss_caption').innerHTML = PicCaption[m_intCurrentIndex];
	//window.status= PicCaption[m_intCurrentIndex];
	
	//if (document.all) {
	//	document.PictureBox.filters.blendTrans.Play();
	//}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// DETAIL VIEW: REQUEST MORE INFO FORM FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Request more information from the details page
//
function detail_request_more_info(listingid, mlsregionid) {
	var detail_message = $('detail_message');
	
	var params = $H({
		requestlistingid: listingid,
		requestmlsregionid: mlsregionid
		}).toQueryString();
	
	var bindArgs = {
	method: 'get',
	parameters: params,		
	onFailure: function(){
		alert('An error occurred and we could not retrieve the request more info form.  Please try again.');
	},
	onSuccess: function(t){	
		detail_message.innerHTML=t.responseText;
		new Effect.BlindDown(detail_message, {queue: 'end', duration: DETAIL_REQUEST_MORE_INFOAPPEARDURATION});
		new Effect.ScrollTo(detail_message, {queue: 'end', offset: DETAIL_MESSAGE_OFFSET});
		new Effect.Highlight(detail_message, {queue: 'end', duration: DETAIL_REQUEST_MORE_INFOHIGHLIGHTDURATION, startcolor: highlight_startcolor, endcolor: highlight_endcolor})	
	}
	};
	
	new Ajax.Request('/property-search/sist_ajax/request_more_info.asp', bindArgs);
}
//
// Sends the request more information from the details page
//
function detail_request_more_info_send() {
	var detail_message = $('detail_message');
	
	var params1 = $H({
	area: $F('area'),
	basement: $F('basement'),
	condoprojectname: $F('condoprojectname'),
	construction: $F('construction'),
	county: $F('county'),
	energy: $F('energy'),
	exterior: $F('exterior'),
	interior: $F('interior'),
	lacreage: $F('lacreage'),
	lbaths: $F('lbaths'),
	lbeds: $F('lbeds'),
	listtypedescrip: $F('listtypedescrip'),
	lprice: $F('lprice'),
	lsqft: $F('lsqft'),
	mage: $F('mage'),
	style: $F('style'),
	subarea: $F('subarea'),
	subdivision: $F('subdivision'),
	uprice: $F('uprice')
	}).toQueryString();		
	//alert('params1: ' + params1);
	
	var params2 = $('requestmoreinfo').serialize();
	//alert('params2: ' + params2);
	
	var params = params1 + "&" + params2;	
	
	//window.location.href = '/property-search/sist_ajax/request_more_info.asp?' + params;
	
	var bindArgs = {
	method: 'post',
	parameters: params,
	onFailure: function(t){
		alert('An error occurred and we could not send your request.  Please try again.');
		alert(t.responseText);
		$('requestsubmit').value = 'Submit';
	},
	onSuccess: function(t){
		detail_message.innerHTML='<fieldset><legend>Request More Info about This Listing</legend><strong>' + t.responseText + '</strong></fieldset>';			
		
		new Effect.Highlight(detail_message, {queue: 'end', duration: DETAIL_REQUEST_MORE_INFO_SENDHIGHLIGHTDURATION, startcolor: highlight_startcolor, endcolor: highlight_endcolor});
		new Effect.BlindUp(detail_message, {queue: 'end', duration: DETAIL_REQUEST_MORE_INFO_SENDFADEDURATION});
		new Effect.ScrollTo('detail_top_info', {queue: 'end', offset: DETAIL_MAIN_CONTAINER_OFFSET});		
	}
	};	
	
	// Validate the form contents before submitting
	var name = IsEmpty($('requestName'));
	if (!name) {
		$('requestName').value = ReadableName($('requestName'));
	}
	var email = IsValidEmail($('requestEmail'));
	
	// Check to see if this site wants phone number to be a required field (set in si_client.js)
	var phone = true;
	
	if (require_phone_number) {
		phone = IsValidPhoneNumber($('requestDayPhone'));
	}
	
	// Get the values of the date & time radio buttons in the form.  These start out with none checked to make sure the user
	// 	actively selects one.
	var contactPreference = $RF('requestmoreinfo','requestContactPreference');
	var todPreference = $RF('requestmoreinfo','requestTODPreference');
	
	var bContactPreference = ((contactPreference == '') || (contactPreference == null))
	var btodPreference = ((todPreference == '') || (todPreference == null))
	
	if (!name && email && phone && (!(bContactPreference)) && (!(btodPreference)) ) {	
		$('requestsubmit').value = 'Please Wait...';
		$('requestsubmit').style.width = '125px';	
		new Ajax.Request('/property-search/sist_ajax/request_more_info.asp', bindArgs);
	} else if (name) {
		alert('Please enter your name.');
		$('requestName').focus();
	} else if (!phone) {
		alert('Please enter a valid ten digit phone number.');
		$('requestDayPhone').focus();
	} else if (!email) {
		alert('Please enter a valid email address.');
		$('requestEmail').focus();
	} else	if (bContactPreference) { 
		alert('Please select how you preferred to be contacted.'); 
		$('requestContactPreference1').focus(); 
	} else if (btodPreference) { 
		alert('Please the time of day it\'s best to reach you.'); 
		$('requestTODPreference1').focus(); 
	}
}
//
// Cancels any / all detail request forms
//
function detail_request_cancel() {
	var detail_message = $('detail_message');
	new Effect.BlindUp(detail_message, {queue: 'end', duration: DETAIL_REQUEST_CANCELFADEDURATION});
	new Effect.Fade(detail_message,{ queue: 'end', duration: DETAIL_REQUEST_CANCELFADEDURATION, afterFinish: function() { detail_message.innerHTML = ''; } });
	new Effect.ScrollTo('detail_top_info', {queue: 'end', offset: DETAIL_MAIN_CONTAINER_OFFSET});
}
////////////////////////////////////////////////////////////////////////////////////////////////
// DETAIL VIEW: SHEDULE SHOWING FORM FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Details of the showing schedule
//
function detail_schedule_showing(listingid, mlsregionid) {
	
	var detail_message = $('detail_message');
	
	var params = $H({
		requestlistingid: listingid,
		requestmlsregionid: mlsregionid
		}).toQueryString();
		
	var bindArgs = {
	method: 'get',
	parameters: params,		
	onFailure: function(){
		alert('An error occurred and we could not retrieve the request more info form.  Please try again.');
	},
	onSuccess: function(t){
		detail_message.innerHTML=t.responseText;
		new Effect.BlindDown(detail_message, {queue: 'end', duration: DETAIL_SCHEDULE_SHOWINGAPPEARDURATION});
		new Effect.ScrollTo(detail_message, {queue: 'end', offset: DETAIL_MESSAGE_OFFSET});
		new Effect.Highlight(detail_message, {queue: 'end', duration: DETAIL_SCHEDULE_SHOWINGHIGHLIGHTDURATION, startcolor: highlight_startcolor, endcolor: highlight_endcolor});
	}
	};
	
	new Ajax.Request('/property-search/sist_ajax/schedule_a_showing.asp', bindArgs);
}
//
// Sends the detail showing schedule
//
function detail_schedule_showing_send() {
	var detail_message = $('detail_message');
	
	var params1 = $H({
	area: $F('area'),
	basement: $F('basement'),
	condoprojectname: $F('condoprojectname'),
	construction: $F('construction'),
	county: $F('county'),
	energy: $F('energy'),
	exterior: $F('exterior'),
	interior: $F('interior'),
	lacreage: $F('lacreage'),
	lbaths: $F('lbaths'),
	lbeds: $F('lbeds'),
	listtypedescrip: $F('listtypedescrip'),
	lprice: $F('lprice'),
	lsqft: $F('lsqft'),
	mage: $F('mage'),
	style: $F('style'),
	subarea: $F('subarea'),
	subdivision: $F('subdivision'),
	uprice: $F('uprice')
	}).toQueryString();		
	//alert('params1: ' + params1);
	
	var params2 = $('scheduleashowing').serialize();
	//alert('params2: ' + params2);
	
	var params = params1 + "&" + params2;		
	
	var bindArgs = {
	method: 'post',
	parameters: params,
	onFailure: function(t){
		alert('An error occurred and we could not send your request.  Please try again.');
		alert(t.responseText);
		$('requestsubmit').value = 'Submit';
	},
	onSuccess: function(t){
		detail_message.innerHTML='<fieldset><legend>Schedule a Showing</legend><strong>' + t.responseText + '</strong></fieldset>';			
		
		new Effect.Highlight(detail_message, {queue: 'end', duration: DETAIL_SCHEDULE_SHOWING_SENDHIGHLIGHTDURATION, startcolor: highlight_startcolor, endcolor: highlight_endcolor});
		new Effect.BlindUp(detail_message, {queue: 'end', duration: DETAIL_SCHEDULE_SHOWING_SENDFADEDURATION});
		new Effect.ScrollTo('detail_top_info', {queue: 'end', offset: DETAIL_MAIN_CONTAINER_OFFSET});
	}
	};	
	
	// Validate the form contents before submitting
	var name = IsEmpty($('requestName'));
	if (!name){
		$('requestName').value = Trim($('requestName'));
		$('requestName').value = ReadableName($('requestName'));
	}
	var email = IsValidEmail($('requestEmail'));
	
	// Check to see if this site wants phone number to be a required field (set in si_client.js)
	var phone = true;
	
	if (require_phone_number) {
		phone = IsValidPhoneNumber($('requestDayPhone'));
	}
	
	// Get the values of the date & time radio buttons in the form.  These start out with none checked to make sure the user
	// 	actively selects one.
	var contactPreference = $RF('scheduleashowing','requestContactPreference');
	var todPreference = $RF('scheduleashowing','requestTODPreference');
	var apptDayPreference = $RF('scheduleashowing','requestApptDayPreference');
	var apptTimePreference = $RF('scheduleashowing','requestApptTimePreference');
	
	var bContactPreference = ((contactPreference == '') || (contactPreference == null))
	var btodPreference = ((todPreference == '') || (todPreference == null))
	var bapptDayPreference = ((apptDayPreference == '') || (apptDayPreference == null))
	var bapptTimePreference = ((apptTimePreference == '') || (apptTimePreference == null))
	
	// Processes form
	if (!name && email && phone && (!(bContactPreference)) && (!(btodPreference)) && (!(bapptDayPreference)) && (!(bapptTimePreference)) ) {	
		$('requestsubmit').value = 'Please Wait...';
		$('requestsubmit').style.width = '125px';	
		new Ajax.Request('/property-search/sist_ajax/schedule_a_showing.asp', bindArgs);
	}  else if (name) {
		alert('Please enter your name.');
		$('requestName').focus();
	} else if (!email) {
		alert('Please enter a valid email address.');
		$('requestEmail').focus();
	} else if (!phone) {
		alert('Please enter a valid ten digit phone number.');
		$('requestDayPhone').focus();
	} else	if (bContactPreference) { 
		alert('Please select how you preferred to be contacted.'); 
		$('requestContactPreference1').focus(); 
	} else if (btodPreference) { 
		alert('Please the time of day it\'s best to reach you.'); 
		$('requestTODPreference1').focus(); 
	} else if (bapptDayPreference) { 
		alert('Please select whether you prefer a weekday or weekend.'); 
		$('requestApptDayPreference1').focus(); 
	} else if (bapptTimePreference) { 
		alert('Please select whether you prefer morning, afternoon, or evening.'); 
		$('requestApptTimePreference1').focus(); 
	}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// DETAIL VIEW: EMAIL LISTING FORM FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Loads the email to friend form from the details page
//
function detail_email_listing(listingid, mlsregionid) {
	var detail_message = $('detail_message');
	
	var params = $H({
		requestlistingid: listingid,
		requestmlsregionid: mlsregionid
		}).toQueryString();
	
	var bindArgs = {
	method: 'get',
	parameters: params,		
	onFailure: function(){
		alert('An error occurred and we could not retrieve the request more info form.  Please try again.');
	},
	onSuccess: function(t){
		detail_message.innerHTML=t.responseText;
		new Effect.BlindDown(detail_message, {queue: 'end', duration: DETAIL_EMAIL_LISTINGAPPEARDURATION});
		new Effect.ScrollTo(detail_message, {queue: 'end', offset: DETAIL_MESSAGE_OFFSET});
		new Effect.Highlight(detail_message, {queue: 'end', duration: DETAIL_EMAIL_LISTINGHIGHLIGHTDURATION, startcolor: highlight_startcolor, endcolor: highlight_endcolor});
	}
	};
	
	new Ajax.Request('/property-search/sist_ajax/email_to_friend.asp', bindArgs);
}
//
// Sends the listing details to a friend from the details page
//
function detail_email_listing_send() {
	var detail_message = $('detail_message');
	
	var params = Form.serialize($('emaillisting'));
	
	var bindArgs = {
	method: 'post',
	parameters: params,
	onFailure: function(){
		alert('An error occurred and we could not send your request.  Please try again.');
	},
	onSuccess: function(t){
		detail_message.innerHTML='<fieldset><legend>Email Listing to a Friend</legend><strong>' + t.responseText + '</strong></fieldset>';			
		
		new Effect.Highlight(detail_message, {queue: 'end', duration: DETAIL_EMAIL_LISTING_SENDHIGHLIGHTDURATION, startcolor: highlight_startcolor, endcolor: highlight_endcolor});
		new Effect.BlindUp(detail_message, {queue: 'end', duration: DETAIL_EMAIL_LISTING_SENDFADEDURATION});
		new Effect.ScrollTo('detail_top_info', {queue: 'end', offset: DETAIL_MAIN_CONTAINER_OFFSET});
	}
	};	
	
	// Validate the form contents before submitting
	var reqName = IsEmpty($('requestName'));
	if (!reqName){
		$('requestName').value = Trim($('requestName'));
		$('requestName').value = ReadableName($('requestName'));
	}
	var reqEmail = IsValidEmail($('requestEmail'));
	var recpName = IsEmpty($('recipientName'));
	if (!recpName){
		$('recipientName').value = Trim($('recipientName'));
		$('recipientName').value = ReadableName($('recipientName'));
	}
	var recpEmail = IsValidEmail($('recipientEmail'));
	if ($('requestComments').length > 0)
		$('requestComments').value = Trim($('requestComments'));

	// Processes the request if valid...else focuses invalid fields if possible
	if (!reqName && !recpName && reqEmail && recpEmail) {	
		$('requestsubmit').value = 'Please Wait...';
		$('requestsubmit').style.width = '125px';	
		new Ajax.Request('/property-search/sist_ajax/email_to_friend.asp', bindArgs);
	} 
	else if (!(!reqName && !recpName && reqEmail && recpEmail)) {
		alert('Please enter all of the required fields.');
		return false;
	} 
	else if (!reqEmail) {
		alert('Please enter a valid email address for yourself.');
		$('requestEmail').focus();
	} 
	else if (!recpEmail) {
		alert('Please enter a valid email address for the recipient.');
		$('recipientEmail').focus();		
	}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// DETAIL VIEW: MORTGAGE CALCULATOR FORM FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Loads the mortgage calculator
//
function detail_mortgage_calculator(price) {
	var detail_message = $('detail_message');
	
	var params = $H({
		price: price
		}).toQueryString();
	
	var bindArgs = {
	method: 'get',
	parameters: params,		
	onFailure: function(){
		alert('An error occurred and we could not retrieve the request more info form.  Please try again.');
	},
	onSuccess: function(t){
		detail_message.innerHTML=t.responseText;
		new Effect.BlindDown(detail_message, {queue: 'end', duration: DETAIL_MORTGAGE_CALCULATORAPPEARDURATION});
		new Effect.ScrollTo(detail_message, {queue: 'end', offset: DETAIL_MESSAGE_OFFSET});		
		new Effect.Highlight(detail_message, {queue: 'end', duration: DETAIL_MORTGAGE_CALCULATORHIGHLIGHTDURATION, startcolor: highlight_startcolor, endcolor: highlight_endcolor});
		domortgageCalculate();
	}
	};
	
	new Ajax.Request('/property-search/sist_ajax/mortgage_calculator.asp', bindArgs);
}
//
// Access numbers only as input
//
function numberOnly(e) {
	var charCode = (navigator.appName == "Netscape") ? e.which : e.keyCode
	// status = charCode 
	// see ASCII character value!
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {  
		alert("number only");
		return false;
	}
	return true;
}
//
// clears downpayment value on percentage change
//
function OnPercentChange(){
	document.mortgagecalculator.downpayment.value = "";
}
//
// Clears downpayment percent on downpayment change
//
function OnDownPaymentChange() {
	document.mortgagecalculator.downpaymentpercent.value = "";
}
//
// Returns price with commas inserted
//
function domortgageCalculate() {
	document.mortgagecalculator.price.value = InsertComma(document.mortgagecalculator.price.value);
}
//
// Mortgage calculator function
//
function MakeCurrency() {
	var fPrinc, fDownp, fInter, fPymnt, fPeriod,fPrincVal , fDownpVal;
	var cntr, NumOfPays , MIntrst, Cmpnd, Prncpl, MPayment, Downpymnt;
	var PriceRegExp="^[\\d]+[\\d\,]*[\.]?[\\d]*$";
	var regexpPrice=new RegExp(PriceRegExp);

	fPrinc = CleanNumber(document.mortgagecalculator.price.value);
	if(document.mortgagecalculator.downpaymentpercent.value.length > 0 && document.mortgagecalculator.downpayment.value.length <= 0) {
		fDownpPer = document.mortgagecalculator.downpaymentpercent.value.replace('%','');
		var result3 = regexpPrice.test(fDownpPer);
		if (result3 == false) {
			alert("Please enter a valid percentage for the Down Payment.");
			document.mortgagecalculator.downpaymentpercent.focus();
			return false;
		}
		else {
			if(fDownpPer < 0 || fDownpPer > 100) {
				alert("Please enter a valid percentage between 0% and 100% for the Down Payment.");
				document.mortgagecalculator.downpaymentpercent.focus();
				return false;
			}				
		}
		document.mortgagecalculator.downpayment.value = InsertComma(Math.round(fPrinc * (fDownpPer/100)));
	}
	fDownp = CleanNumber(document.mortgagecalculator.downpayment.value);
	//Netscape returns NaN for call a value of object directly, so I used Options below. -May Zhang
	fInter = document.mortgagecalculator.loanrate.value.replace('%','');
	var result4 = regexpPrice.test(fInter);
	if (result4 == false) {
		alert("Please enter a valid percentage for the Loan Rate.");
		document.mortgagecalculator.loanrate.focus();
		return false;
	}
	else {
		if(fInter < 0 || fInter > 100) {
			alert("Please enter a valid percentage between 0% and 100% for the Loan Rate.");
			document.mortgagecalculator.loanrate.focus();
			return false;
		}				
	}
	fPeriod = parseFloat(document.mortgagecalculator.loanterm.options[document.mortgagecalculator.loanterm.selectedIndex].value);
	fPymnt = document.mortgagecalculator.payments;

	var result1 = regexpPrice.test(fPrinc);
	var result2 = regexpPrice.test(fDownp);

	if (result1 == false) {
		alert("Please enter a valid dollar amount for the price.");
		return false;
	}
	if (result2 == false) {
		alert("Please enter a valid dollar amount for the down payment.");
		return false;
	}
	document.mortgagecalculator.downpaymentpercent.value = Math.round((fDownp / fPrinc) * 10000)/100;
	fPrincVal = CleanNumber(fPrinc);
	fDownpVal = CleanNumber(fDownp);
	Prncpl = fPrincVal.length == 0 ? 0 : parseFloat(fPrincVal);
	Downpymnt = fDownpVal.length == 0 ? 0.2 * parseFloat(Prncpl) : parseFloat(fDownpVal);

	if (Downpymnt > Prncpl) {
		alert("To use this calculator your Principal amount has to be higher than your Downpayment!");
		return;
	}

	Prncpl = Prncpl - Downpymnt ;    /* amount borrowed */
	
	NumOfPays = fPeriod * 12;    /* number of payments in the loan period */
	MIntrst = fInter / 1200 ;   /* Monthly interest */
	Cmpnd = 1 ;  /* compounded interest */
	for (cntr=0; cntr < NumOfPays; cntr++) 
		Cmpnd = Cmpnd * ( 1 + MIntrst );            
	
	MPayment = (Prncpl * Cmpnd * MIntrst)/(Cmpnd - 1);
	if (isNaN(parseInt(MPayment, 10 ))) 
		fPymnt.value = 0;
	else
		fPymnt.value = InsertComma(parseInt(MPayment, 10 ));
}
//
// Inserts commas into passed in currency value
//
function InsertComma(Num) {
	var ret = "";
	var sNum = Num.toString();
	sNum = removeCommas(sNum);
	sNum = addCommas(sNum);
	return sNum;
}
//
// removes commas from dollar amounts
// 
function CleanNumber(Dollar) {
	var nInd
	var strLeft, strRight , strFormat;
	var DLen = Dollar.length;
	nInd = Dollar.indexOf(",",0)
	strLeft = "" ;
	strRight = Dollar.substring(0);
	
	if (nInd == -1) 
		return Dollar;
		
	while (nInd != -1) {
		strLeft = strLeft + strRight.substring(0, nInd  );
		strRight = strRight.substring(nInd + 1);
		nInd = strRight.indexOf(",",0)
	}
           
	strFormat = strLeft + strRight;
	return strFormat;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// CONVERSION AND VALIDATION FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Replaces special characters with HTML equivalent
//
function htmlspecialchars(str) {
    return str.replace(/&/g, "&amp;").replace(/</g,"&lt;").replace(/>/g, "&gt;").replace(/'/g, "&#039;").replace(/"/g, "&quot;");
} 
//
// Validates currency
//
function validateCurrency( strValue)  {
  var objRegExp = /(^\$\d{1,3}(,\d{3})*\.\d{2}$)|(^\(\$\d{1,3}(,\d{3})*\.\d{2}\)$)/;

  return objRegExp.test( strValue );
}
//
// Validates value as numeric
//
function  validateNumeric( strValue ) {
  var objRegExp  =  /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;

  return objRegExp.test(strValue);
}
//
// Validates value as integer
//
function validateInteger( strValue ) {
  var objRegExp  = /(^-?\d\d*$)/;

  return objRegExp.test(strValue);
}
//
// If string is less than four characters, returns true
//
function validateNotlessfour( strValue ) {
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length < 4){
     return true;
   }
   return false;
}
//
// If string is not empty, returns true
//
function validateNotEmpty( strValue ) {
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }
   return false;
}
//
// Validates value to pattern
//
function validateValue( strValue, strMatchPattern ) {
var objRegExp = new RegExp( strMatchPattern);
 return objRegExp.test(strValue);
}
//
// ???
//
function rightTrim( strValue ) {
	var objRegExp = /^([\w\W]*)(\b\s*)$/;

	if(objRegExp.test(strValue))
		strValue = strValue.replace(objRegExp, '$1');
    
  return strValue;
}
//
// ???
//
function leftTrim( strValue ) {
var objRegExp = /^(\s*)(\b[\w\W]*)$/;

      if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}
//
// ???
//
function trimAll( strValue ) {
 var objRegExp = /^(\s*)$/;

    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }

   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}
//
// Removes the currency format
//
function removeCurrency( strValue ) {
  var objRegExp = /\(/;
  var strMinus = '';

  if(objRegExp.test(strValue)){
    strMinus = '-';
  }

  objRegExp = /\)|\(|[,]/g;
  strValue = strValue.replace(objRegExp,'');
  if(strValue.indexOf('$') >= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;
}
//
// Adds the currency format
//
function addCurrency( strValue ) {
  var objRegExp = /-?[0-9]+(\.[0-9]{2})?$/;
	var s = new String(strValue);

    if( objRegExp.test(s)) {
      objRegExp.compile('^-');
      s = addCommas(s);
      if (objRegExp.test(s)){
        s = '($' + s.replace(objRegExp,'') + ')';
      }
      else {
        s = '$' + s;
      }
      return  s;
    }
    else
      return s;
}
//
// Removes currency commas
//
function removeCommas( strValue ) {
  var objRegExp = /,/g; //search for commas globally

  return strValue.replace(objRegExp,'');
}
//
// Adds currency commas
//
function addCommas( strValue ) {
  var objRegExp  = /(-?[0-9]+)([0-9]{3})/;

	var s = new String(strValue);

    while(objRegExp.test(s)) {
       s = s.replace(objRegExp, '$1,$2');
    }
  return s;
}
//
// ???
//
function removeCharacters( strValue, strMatchPattern ) {
 var objRegExp =  new RegExp( strMatchPattern, 'gi' );

  return strValue.replace(objRegExp,'');
}
//]]>