/*
+----------------------------------------------------------------------+
| Copyright (c) 2007 Coldwell Banker Funkhouser Realtors               |
+----------------------------------------------------------------------+
| Authors: Matthew Kirkpatrick <matt@cbfunkhouser.com>                 |
+----------------------------------------------------------------------+
 Created:      September 29, 2006
 Last Updated: September 3, 2008
*/
/* BASIC PHP INCLUDE SIMULATOR
*/
php_include = function (locationID, include_file_path, parameters) {

	if (locationID.length > 0) { // simple single or multiple file include

		for (var i = 0; i < locationID.length; i++) {
	
			new Ajax.Updater (
				locationID[i],
				include_file_path[i],
				{
					parameters: parameters[i],
					method: 'post',
					evalScripts: true
				}
			);
	
		}

	} else { // single or multiple file include with div population
	
		for (var i = 0; i < include_file_path.length; i++) {
	
			new Ajax.Request (
				include_file_path[i],
				{
					parameters: parameters[i],
					method: 'post',
					evalScripts: true
				}
			);
	
		}
	}
}

/* CLIENT LOGIN
*/
clientLOGIN = function (x_action, email, pass, extra_pars) {

	var result = new Ajax.Request (
		'/client/files_includes/processors/login.inc.php',
		{
			parameters: 'x_action=' + x_action + '&email=' + email + '&pass=' + pass,
			method: 'post',
			evalScripts: true,
			onSuccess: function (feedback) {
				$('clientLOGINwindow_success').style.display = 'block';
				$('clientLOGINwindow_success').innerHTML = feedback.statusText.substr(0,strpos (feedback.statusText, '#'));
				$('clientLOGINwindow_ajax_success').style.display = 'block';
				new Effect.Fade($('clientLOGINwindow_ajax_success'), {delay: 5, duration: 1.5});
				new Effect.BlindUp($('clientLOGINwindow_ajax_success'), {delay: 5, duration: 1.5});

				// load the clientID
				var clientID = feedback.statusText.substr(strpos (feedback.statusText, '#') + 1, strpos (feedback.statusText, '|'));
				extra_pars.propDetails += 'client_favs|' + feedback.statusText.substr(strpos (feedback.statusText, '|') + 1);
				
				// assigns the found ID to a hidden field for function reference
				$('clientFromLOGINwindow_clientID').value = clientID;
				
				// save the property
				saveProperty (extra_pars.propElemId, extra_pars.favID, extra_pars.propDetails.split(','), clientID);
				
				// close the login screen
				setTimeout("$('clientLOGINwindowBase').style.display	= 'none'", 2000);
				setTimeout("$('clientLOGINwindow').style.display		= 'none'", 2000);
				
			},
			
			onFailure: function (feedback) {
				$('clientLOGINwindow_error').style.display = 'block';
				$('clientLOGINwindow_error').innerHTML = feedback.statusText;
				$('clientLOGINwindow_ajax_failure').style.display = 'block';
				new Effect.Fade($('clientLOGINwindow_ajax_failure'), {delay: 5, duration: 1.5});
				new Effect.BlindUp($('clientLOGINwindow_ajax_failure'), {delay: 5, duration: 1.5});
			}
		}
	);

}

/* CLIENT LOGIN POPUP
*/
clientLOGINpopup = function (propElemId, favID, propDetails) {

	$('clientLOGINwindowBase').style.display	= '';
	$('clientLOGINwindow').style.display		= '';
	
	var propDetailsPars = [];
	for (var i = 0; i < propDetails.length; i++) {
		propDetailsPars[i] = propDetails[i].replace(/, /g,'+'); // cleans up the address (removes the commas)
	}
	
	//populate hidden variables
	$('clientLOGINwindow_propElemId').value		= $(propElemId).id;
	$('clientLOGINwindow_favID').value			= favID;
	$('clientLOGINwindow_propDetails').value	= propDetailsPars;
}

/* SAVE PROPERTY
*/
saveProperty = function (propElemId, favID, propDetails, clientID) {
		
	if (!clientID) { // if the client is not signed in, provide sign in screen.
		
		clientLOGINpopup(propElemId, favID, propDetails);
	
	} else {
	
		if ($(propElemId).id.substr(-3) == '_on') { var save_toggle = "0"; }
			else { var save_toggle = "1"; }
			
		var propDetailsPars = '';
		for (var i = 0; i < propDetails.length; i++) {
			propDetailsPars += '&' + propDetails[i].replace('|', '=');
		}
		propDetailsPars = propDetailsPars.replace(/, /g,'+'); // cleans up the address (removes the commas)
		
		new Ajax.Request(
			'/searching/files_includes/processors/property_tagging.inc.php',
			{
				parameters:		'x_action=save_property' + propDetailsPars,
				method:			'post',
				evalScripts:	true
			}
		);
		
		if (save_toggle == "1") {
			
			$(propElemId).src				= '/files_images/site/button_star_gold.png';
			$(propElemId).id				+= '_on';
			// changes the star on the detail page.
			if ($('button_favorite_' + favID) && $('button_favorite_' + favID) != $(propElemId)) {
				$('button_favorite_' + favID).src	= '/files_images/site/button_star_gold.png';
				$('button_favorite_' + favID).id		+= '_on';
			}

			var previous_HTML				= $('status_toggle_' + favID).innerHTML;
			$('status_toggle_' + favID).innerHTML	= '<strong style="color: #990000;">SAVED!</strong>';
			setTimeout("$('status_toggle_" + favID + "').innerHTML = '" + previous_HTML + "'", 2500);
		
		} else if (save_toggle == "0") {
			
			$(propElemId).src	= '/files_images/site/button_star_gray.png';
			$(propElemId).id	= $(propElemId).id.substr(0, ($(propElemId).id.length) -3);
			// changes the star on the detail page.
			if ($('button_favorite_' + favID + '_on') && $('button_favorite_' + favID + '_on') != $(propElemId)) {
				$('button_favorite_' + favID + '_on').src	= '/files_images/site/button_star_gray.png';
				$('button_favorite_' + favID + '_on').id	= $(propElemId).id.substr(0, ($(propElemId).id.length) -3);
			}

			var previous_HTML	= $('status_toggle_' + favID).innerHTML;
			$('status_toggle_' + favID).innerHTML	= '<strong style="color: #990000;">REMOVED!</strong>';
			setTimeout("$('status_toggle_" + favID + "').innerHTML = '" + previous_HTML + "'", 2500);
		
		}
	} // END: if (clientID)
} // END: function()

/* SUBMIT PROPERTY CONNECT FORM
*/
property_connect_form_submit = function (x_action, my_form, srid, x_property_type, srArrayID) {
	
	for (i = 0; i < $(my_form).elements.length; i++) {
		var my_form_element = $(my_form).elements[i];
		
		$(my_form_element.id).style.border = '1px solid transparent';
		
		// form validation
		if (	my_form_element.value == ' Your First Name' ||
				my_form_element.value == ' Your Last Name' ||
				my_form_element.value == ' Your E-mail Address' ||
				my_form_element.value == " Your Friend's E-mail Address" ||
				trimStr(my_form_element.value) == ''
			) {
			var empty_field_trigger = 1;
			$(my_form_element.id).style.border = '1px solid #bb0000';
		}	
	}
	
	if (empty_field_trigger == 1) {
		alert ('Please help us better assist you by completing the entire form. Thank you!');
		return false;
	}
	
	// hide the form container
	new Effect.BlindUp($('detail_address_title_form_container'), {delay: 0, duration: .5});
	$('connect_' + x_action).style.backgroundImage	= '';
	
	// prep parameters for PHP push
	var pars = '';
	for (var i = 0; i < $(my_form).elements.length; i++) {
		pars += '&' + $(my_form).elements[i].id + '=' + urlencode($(my_form).elements[i].value);
	}
	
	new Ajax.Request (
		'/searching/detail/property_connect/files_includes/processors/connect.inc.php',
		{
			parameters: 'x_action=' + x_action + pars + '&srid=' + srid + '&x_property_type=' + x_property_type + '&srArrayID=' + srArrayID,
			method: 'post',
			evalScripts: true,
			onSuccess: ajax_success_bright,
			onFailure: ajax_failure_bright
		}
	);
	
}

/* SHOW/HIDE PROPERTY CONNECT FORM
*/
property_connect_form = function (show, hide, srid, x_property_type, srArrayID) {
	
	if ($('detail_address_title_form_container').style.display == '' && $('connect_' + show).style.backgroundImage == "url(/files_images/site/nav_property_connect_" + show + "_active.gif)") {
	
		new Effect.BlindUp($('detail_address_title_form_container'), {delay: 0, duration: .5});
		$('connect_' + show).style.backgroundImage				= '';
		
	} else {
	
		// change tabs
		for (var i = 0; i < hide.length; i++) {
			if ($('connect_' + hide[i])) {
				$('connect_' + hide[i]).style.backgroundImage	= '';
			}
		}
		
		$('connect_' + show).style.backgroundImage				= "url('/files_images/site/nav_property_connect_" + show + "_active.gif')";
		new Ajax.Updater (
			'detail_address_title_form_container',
			'/searching/detail/property_connect/index.php',
			{
				parameters: 'connect=' + show + '&srid=' + srid + '&x_property_type=' + x_property_type + '&srArrayID=' + srArrayID,
				method: 'post',
				evalScripts: true
			}
		);
		//new Effect.BlindDown($('detail_address_title_form_container'), {delay: 1, duration: 2});
		setTimeout("$('detail_address_title_form_container').style.display	= ''",500);
	
	}
}

close_property_connent_form = function (hide) {
	new Effect.BlindUp($('detail_address_title_form_container'), {delay: 0, duration: .5});
	// change tabs
	for (var i = 0; i < hide.length; i++) {
		if ($('connect_' + hide[i])) {
			$('connect_' + hide[i]).style.backgroundImage	= '';
		}
	}
}

/* UPDATE AGENT LISTINGS
*/
updateAgentListings = function (divID, default_association, renderer, srArrayID) {
	if (renderer == 'null' || renderer == 'NULL') { renderer = ''; }
	new Ajax.Updater (
		divID,
		'/files_includes/html_renderings/realtor_property' + renderer + '.inc.php',
		{
			parameters: 'default_association=' + default_association + '&srArrayID=' + srArrayID,
			method: 'post',
			evalScripts: true,
			onLoading:		ajax_loading,
			onComplete:		ajax_complete
		}
	);
}

/* UPDATE TOP PROPS ON BLOG
*/
updateTopProps = function (divID, default_association, renderer, srArrayID) {
	if (renderer == 'null' || renderer == 'NULL') { renderer = ''; }
	new Ajax.Updater (
		divID,
		'/files_includes/html_renderings/top_props.inc.php',
		{
			parameters: 'default_association=' + default_association + '&srArrayID=' + srArrayID,
			method: 'post',
			evalScripts: true,
			onLoading:		ajax_loading,
			onComplete:		ajax_complete
		}
	);
}

updateTopPropsAll = function (divID, default_association, renderer, srArrayID, num) {
	if (renderer == 'null' || renderer == 'NULL') { renderer = ''; }
	new Ajax.Updater (
		divID + num,
		'/files_includes/html_renderings/top_props_all.inc.php',
		{
			parameters: 'default_association=' + default_association + '&srArrayID=' + srArrayID,
			method: 'post',
			evalScripts: true,
			onLoading:		ajax_loading,
			onComplete:		ajax_complete
		}
	);
}

/* UPDATE DEFAULT ASSOCIATION
*/
updateDefaultAssociation = function (default_association, code_execution) {
		
		$('loadingDATAwindowBase').style.display	= '';
		$('loadingDATAwindow').style.display		= '';
		
		new Ajax.Request (
			'/files_includes/processors/toggle_association.inc.php',
			{
				parameters:		'default_association=' + default_association,
				method:			'post'
			}
		);
		$('association_updater_span').style.backgroundImage = "url('/files_images/site/toggle_association_" + default_association + ".gif')";

		// execute functions after assciation change
		for (var i = 0; i < code_execution.length; i++) { eval(code_execution[i]); }
		
		setTimeout("$('loadingDATAwindowBase').style.display	= 'none'", 2000);
		setTimeout("$('loadingDATAwindow').style.display		= 'none'", 2000);

}

/*
updateDefaultAssociation = function (default_association) {
		new Ajax.Request (
			'/files_includes/processors/toggle_association.inc.php',
			{
				parameters:		'default_association=' + default_association,
				method:			'post'
			}
		);
		$('association_updater_span').style.backgroundImage = "url('/files_images/site/toggle_association_" + default_association + ".gif')";
}
*/

/* MASTHEAD TOGGLE
Close and open the site masthead
*/
toggleMasthead = function (divID, button1) {
	var myDiv =				$(divID);
	var toggleButton =		$(button1);

	if (myDiv.style.display == '') {
		new Effect.BlindUp(myDiv, {delay: 0, duration: 2});
		toggleButton.style.visibility = 'visible';
		
		new Ajax.Request (
			'/files_includes/processors/close_header.inc.php',
			{
				parameters:		'close_header=1',
				method:			'post'
			}
		);
	} else {
		new Effect.BlindDown(myDiv, {delay: 0, duration: 2});
		toggleButton.style.visibility = 'hidden';

		new Ajax.Request (
			'/files_includes/processors/close_header.inc.php',
			{
				parameters:		'close_header=0',
				method:			'post'
			}
		);
	}
}

/* FIND AN ELEMENT'S ABSOLUTE POSITION
*/
visitBlog = function(url) {
	window.location = url;
}


/* FIND AN ELEMENT'S ABSOLUTE POSITION
*/
getPos = function (obj) {
	var pos = { x: obj.offsetLeft || 0, y: obj.offsetTop || 0 };
	while (obj = obj.offsetParent) {
		pos.x += obj.offsetLeft || 0;
		pos.y += obj.offsetTop || 0;
	}
	return pos;
}

/* SHOW DETAIL JUMP MENU
Activates the jump menu drop-down.

'id' is the element to which you'd like to
'xcor' & 'ycor' are position offset values
*/
showJumpMenu = function(jump_menu, thisElement, xcor, ycor, scrollToValue) {
	var myElement = $(thisElement);
	
	var whereX = getPos(myElement).x;
	var whereY = getPos(myElement).y;
	
	$(jump_menu).style.left =		whereX + (xcor) + 'px';
	$(jump_menu).style.top =		whereY + (ycor) + 'px';

	if ($(jump_menu).style.display == 'block') { $(jump_menu).style.display = 'none'; }
		else { $(jump_menu).style.display = 'block'; }
	
	$(jump_menu).scrollTop += scrollToValue;
}

/* SHOW DETAIL:
Attach this function to any property result item to activate the detail page for that result.
*/
loadPropertyDetail = function (srid, x_property_type, srArrayID) {
	
	var srArrayID = typeof(srArrayID) != 'undefined' ? srArrayID : 1; // sets the default

	$('content').style.display =			'none';
	if($('navL3_container')) { $('navL3_container').style.display = 'none'; }
	$('detail_content').style.display =		'block';

	// LOAD THE DETAIL PAGE
	new Ajax.Updater (
		'detail_content',
		'/searching/detail/files_includes/index.inc.php',
		{
			parameters:		'x_action=detail&srid=' + srid + '&x_property_type=' + x_property_type + '&srArrayID=' + srArrayID,
			method:			'post',
			evalScripts:	true,
			onLoading:		ajax_loading,
			onComplete:		ajax_complete
		}
	);
	
}

/* DETAIL JUMP MENU
Populates the property jump menu on the property detail page
*/
loadJumpMenu = function (srid, x_property_type, srArrayID) {
	srArrayID = typeof(srArrayID) != 'undefined' ? srArrayID : 1; // sets the default
	
	new Ajax.Updater (
	 	$('detailJumpMenu'),
		'/searching/detail/files_includes/index_jump.inc.php',
			{
				parameters:		'srid=' + srid + '&x_property_type=' + x_property_type + '&srArrayID=' + srArrayID,
				method:			'post',
				evalScripts:	true
			}
	);
}

/* AJAX FEEDBACK USAGE:
Place this XHTML where ever you want the error to show up.
<div id="ajax_success" style="display: none;"><div class="feedback" id="success" style="font-size: 9px; padding: 2px;"></div><br /></div>
<div id="ajax_failure" style="display: none;"><div class="feedback" id="error" style="font-size: 9px; padding: 2px;"></div><br /></div>

This is the usage in the ajax statement
new Ajax.Request('./to/some/php/file.php', {parameters: pars, method: 'post', evalScripts: true, onSuccess: ajax_success, onFailure: ajax_failure});

SOMEWHERE INSIDE file.php
if ( conditional TRUE ) { header('HTTP/1.1 200 You successfully blah blah blah!'); }
	else { header('HTTP/1.1 400 Could not update blah blah blah.'); }
*/
ajax_success = function (feedback) {
	$('success').style.display = 'block';
	$('success').innerHTML = feedback.statusText;
	$('ajax_success').style.display = 'block';
	new Effect.Fade($('ajax_success'), {delay: 5, duration: 2.5});
	new Effect.BlindUp($('ajax_success'), {delay: 5, duration: 2.5});
}

ajax_failure = function (feedback) {
	$('error').style.display = 'block';
	$('error').innerHTML = feedback.statusText;
	$('ajax_failure').style.display = 'block';
	new Effect.Fade($('ajax_failure'), {delay: 7, duration: 2.5});
	new Effect.BlindUp($('ajax_failure'), {delay: 7, duration: 2.5});
}

ajax_success_bright = function (feedback) {
	$('success_bright').style.display = 'block';
	$('success_bright').innerHTML = feedback.statusText;
	$('ajax_success').style.display = 'block';
	new Effect.Fade($('ajax_success'), {delay: 5, duration: 2.5});
	new Effect.BlindUp($('ajax_success'), {delay: 5, duration: 2.5});
}

ajax_failure_bright = function (feedback) {
	$('error_bright').style.display = 'block';
	$('error_bright').innerHTML = feedback.statusText;
	$('ajax_failure').style.display = 'block';
	new Effect.Fade($('ajax_failure'), {delay: 7, duration: 2.5});
	new Effect.BlindUp($('ajax_failure'), {delay: 7, duration: 2.5});
}

/* AJAX STATUS:
Place this XHTML where ever you want the error to show up.
<div id="ajax_status" style="display: none;"><img src="/files_images/ajax_status/indicator_000000.gif" alt="Loading . . . Please Wait!" title="Loading . . . Please Wait!" name="ajax_status_img" border="0" id="ajax_status_img" /></div>

This is the usage in the ajax statement
new Ajax.Request('./to/some/php/file.php', {parameters: pars, method: 'post', evalScripts: true, onLoading: ajax_loading, onComplete: ajax_complete});
*/
ajax_loading = function () {
	if ($('ajax_status')) { $('ajax_status').style.display = 'block'; }
}

ajax_complete = function () {
	if ($('ajax_status')) { $('ajax_status').style.display = 'none'; }
}

// HELP FRAME GENERATOR
help_frame_generator = function (findme) {
	var help_frame_data = '<div class="help_frame_container" id="help_frame_container" style="display: none;"></div><div class="help_frame_border" id="help_frame_border"><iframe src="' + findme + 'assistant/index.php" frameborder="0" class="help_frame" id="help_frame"></iframe></div>';
	document.body.insertAdjacentHTML('beforeEnd', help_frame_data);
}

// SUBMIT ON ENTER
submitOnEnter = function (myfield, e) {
	var keycode;
	if (window.event) { keycode = window.event.keyCode; }
		else if (e) { keycode = e.which; }
		else { return true; }
	if (keycode == 13) {
		myfield.form.submit();
		return false;
	}
	else { return true; }
}

// CONFIRM SUBMIT
confirmSubmit = function (msg) {
	var agree = confirm(msg);
	if (agree) { return true; }
		else { return false; }
}

// CONFIRM FORM SUBMIT
confirmFormSubmit = function (form_id, msg) {
	if (document.getElementById) { var	myForm	= document.getElementById(form_id); }
	var agree = confirm(msg);
	if (agree) {
		myForm.submit();
		return false;
	} else { return false; }
}

// UPDATE PARENT
NL_updateParent = function (URL) { //v1.0
  opener.document.location = URL;
}

/* SHOW/HIDE

TODO:
1) MAKE 'id' parameters dynamic (for() loop?)
*/
showhide_l10 = function (id1, id2, id3, id4) {
	if (document.getElementById) {

		if (id1 != 'NULL') { obj1 = document.getElementById(id1); } else { obj1 = ''; }
		if (id2 != 'NULL') { obj2 = document.getElementById(id2); } else { obj2 = ''; }
		if (id3 != 'NULL') { obj3 = document.getElementById(id3); } else { obj3 = ''; }
		if (id4 != 'NULL') { obj4 = document.getElementById(id4); } else { obj4 = ''; }

		if (obj1 != '' && obj1.style.display == "none") { obj1.style.display = ""; }
			else if (obj1 != '' && obj1.style.display == "") { obj1.style.display = "none"; }
		if (obj2 != '' && obj2.style.display == "none") { obj2.style.display = ""; }
			else if (obj2 != '' && obj2.style.display == "") { obj2.style.display = "none"; }
		if (obj3 != '' && obj3.style.display == "none") { obj3.style.display = ""; }
			else if (obj3 != '' && obj3.style.display == "") { obj3.style.display = "none"; }
		if (obj4 != '' && obj4.style.display == "none") { obj4.style.display = ""; }
			else if (obj4 != '' && obj4.style.display == "") { obj4.style.display = "none"; }
	}
}

switchDisplay = function (show, hide) {
	// hide all
	for (var i = 0; i < hide.length; i++) {
		if ($(hide[i])) { $(hide[i]).style.display	= 'none'; }
	}
	// show all
	for (var i = 0; i < show.length; i++) {
		if ($(show[i])) { $(show[i]).style.display	= ''; }
	}

}

/* SEARCH SWITCH

*/
search_switch = function (id, tab_id) {
	address		= $('gst_address');
	mls			= $('gst_mls');
	realtor		= $('gst_realtor');
	
	address_tab	= $('gst_tab_address');
	mls_tab		= $('gst_tab_mls');
	realtor_tab	= $('gst_tab_realtor');

	obj			= $(id);
	obj_tab		= $(tab_id);
	
	address.style.display		= "none";
	mls.style.display			= "none";
	realtor.style.display		= "none";

	address_tab.style.display	= "none";
	mls_tab.style.display		= "none";
	realtor_tab.style.display	= "none";

	obj.style.display			= "";
	obj_tab.style.display		= "";

}

/* TRIM!
*/
trimStr = function (str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}

/**
 * Emulates insertAdjacentHTML(), insertAdjacentText() and 
 * insertAdjacentElement() three functions so they work with Netscape 6/Mozilla
 * by Thor Larholm me@jscript.dk
 */
if (typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement) {
	HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode) {
	  switch (where){
		case 'beforeBegin':
			this.parentNode.insertBefore(parsedNode,this); break;
		case 'afterBegin':
			this.insertBefore(parsedNode,this.firstChild); break;
		case 'beforeEnd':
			this.appendChild(parsedNode); break;
		case 'afterEnd':
			if (this.nextSibling) { this.parentNode.insertBefore(parsedNode,this.nextSibling); }
				else { this.parentNode.appendChild(parsedNode); }
			break;
	  }
	};

	HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr) {
		var r = this.ownerDocument.createRange();
		r.setStartBefore(this);
		var parsedHTML = r.createContextualFragment(htmlStr);
		this.insertAdjacentElement(where,parsedHTML);
	};

	HTMLElement.prototype.insertAdjacentText = function (where,txtStr) {
		var parsedText = document.createTextNode(txtStr);
		this.insertAdjacentElement(where,parsedText);
	};
}

var toQueryComponent = function (input) {
    if (!input.name || input.disabled)
        return "";

    var n = urlencode(input.name);

    switch (input.type) {
    case "text":
    case "password":
    case "submit":
    case "hidden":
        return n + "=" + urlencode(input.value);
    case "textarea":
        // normalize line breaks as CR LF pairs as per RFC 1866
        var v = input.value.split(/\r\n|\r|\n/).join("\r\n");
        return n + "=" + urlencode(v);
    case "checkbox":
    case "radio":
        if (!input.checked)
            return "";
        var v = getRealValue(input);
        if (v === null) v = "on";
        return n + "=" + urlencode(v);
    case "select-one":
    case "select-multiple":
        var nvp = [];
        var opt, i = 0;
        while ((opt = input.options[i++]) != null) {
            if (opt.selected) {
                var v = getRealValue(opt);
                if (v === null) v = opt.text;
                // older versions of IE do not support Array.push
                nvp[nvp.length] = n + "=" + urlencode(v);
            }
        }
        return nvp.join("&");
    default:
        // input types reset, button, image, and file not implemented
        return "";
    }
}

var urlencode = function (str) {
    var v;
    try { v = encodeURIComponent(str); } catch (e) { v = escape(str); }
    //return v.replace(/%20/g,"+");
    return v;
}

var getRealValue = function (input) {
    var attr = input.getAttributeNode("value");
    return (attr && attr.specified) ? input.getAttribute("value") : null;
}

var buildQueryString = function (form) {
    var str = "";
    var element, i = 0;
    while ((element = form.elements[i++]) != null) {
        var qc = toQueryComponent(element);
        if (qc != "") str += "&" + qc;
    }
    return str.substring(1);
}

strpos = function (haystack, needle, offset) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14
    var i = haystack.indexOf(needle, offset); // returns -1
    return i >= 0 ? i : false;
}

//--------------------------------------------------------------------//
//                        MACROMEDIA DEFAULT JS                       //
//--------------------------------------------------------------------//
MM_goToURL = function () { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

MM_preloadImages = function () { //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];}}
}

MM_swapImgRestore = function () { //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;
}

MM_findObj = function (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;
}

MM_swapImage = function () { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

MM_displayStatusMsg = function (msgStr) { //v1.0
  status=msgStr;
  document.MM_returnValue = true;
}

MM_openBrWindow = function (theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

MM_popupMsg = function (msg) { //v1.0
  alert(msg);
}

MM_jumpMenu = function (targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

MM_jumpMenuGo = function (selName,targ,restore){ //v3.0
  var selObj = MM_findObj(selName); if (selObj) MM_jumpMenu(targ,selObj,restore);
}

MM_changeProp = function (objName,x,theProp,theValue) { //v6.0
  var obj = MM_findObj(objName);
  if (obj && (theProp.indexOf("style.")==-1 || obj.style)){
    if (theValue == true || theValue == false)
      eval("obj."+theProp+"="+theValue);
    else eval("obj."+theProp+"='"+theValue+"'");
  }
}
//--------------------------------------------------------------------//


//--------------------------------------------------------------------//
//                        MORTGAGE CALCULATOR                         //
//--------------------------------------------------------------------//

function CheckAllFields(theForm) {

	var errorMsg = '';

	if(!CheckDollarField(theForm.price))

		errorMsg += ' + valid Home Price value\n';

	if(!CheckDollarField(theForm.downpay))

		errorMsg += ' + valid Down Payment dollar value\n';

	if(!CheckFloatField(theForm.downpayperc))

		errorMsg += ' + valid Down Payment percent value\n';

	if(!CheckIntField(theForm.termMonths))

		errorMsg += ' + valid Loan Term in months value (integer)\n';

	if(!CheckFloatField(theForm.termYears))

		errorMsg += ' + valid Loan Term in years value\n';

	if(!CheckFloatField(theForm.intYear))

		errorMsg += ' + valid Annual Interest Rate value\n';



	if(errorMsg == '')

		return true;

	else {

		alert('Please enter:\n' + errorMsg);

		return false;

	}

}





function CheckFloatField(field) {

	var val = field.value;

	if(val.indexOf(".") != -1) {

		while(val.charAt(val.length-1) == "0")

			val = val.substring(0,val.length-1);

		if(val.charAt(val.length-1) == ".")

			val = val.substring(0,val.length-1);

	}



	if("" + parseFloat(val) != val)

		return false;

	else

		return true;

}





function CheckIntField(field) {

	var val = field.value;



	if(isNaN(val))

		return false;

	else {

		field.value = '' + parseInt(val)

		return true;

	}

}





function CheckDollarField(field) {

	var flt = ReadDollarField(field);



	if(isNaN(flt))

		return false;

	else {

		str = FloatToDollarString(flt);

		field.value = str;

		return true;

	}

}





function ReadDollarField(field) {

	var str = field.value;

	if(str.charAt(0) == "$")

		str = str.substring(1, str.length);



	var pos = str.lastIndexOf(",");

	while(pos != -1) {

		str = str.substring(0,pos) + str.substring(pos+1, str.length);

		pos = str.lastIndexOf(",", pos);

	}



	return parseFloat(str);

}





function FloatToDollarString(flt) {

	var str = "" + Math.round(flt)



	pos = str.length;  // str.indexOf(".");

	pos -= 4;

	while(pos >= 0) {

		str = str.substring(0,pos+1) + "," + str.substring(pos+1, str.length);

		pos -= 3;

	}



	return str;

}





function recalcTermMonths(frm) {

	var tYr = parseFloat(frm.termYears.value);

	var tMon = Math.round(tYr * 12.0);

	tYr = parseFloat(tMon) / 12.0;

	frm.termYears.value = "" + tYr;

	frm.termMonths.value = "" + tMon;

}





function recalcTermYears(frm) {

	var tMon = parseInt(frm.termMonths.value);

	var tYr = parseFloat(tMon) / 12.0;

	frm.termYears.value = "" + tYr;

	frm.termMonths.value = "" + tMon;

}





function RecalcMonthlyPay(frm) {

	var Principle  = ReadDollarField(frm.price) - ReadDollarField(frm.downpay);

	var AnnualInt  = parseFloat(frm.intYear.value);

	var MonthlyInt = AnnualInt / (12.0 * 100.0);

	var LenMonths  = parseInt(frm.termMonths.value);



	if(MonthlyInt == 0)

		var MonthlyPay = Principle / LenMonths;

	else

		var MonthlyPay = Principle * ( MonthlyInt / ( 1 - Math.pow((1 + MonthlyInt), -LenMonths) ) );

	MonthlyPay = Math.round(MonthlyPay * 100) / 100;



	frm.payMonth.value = FloatToDollarString(MonthlyPay);

}





function RecalcDownPay(frm) {

	var AnnualInt  = parseFloat(frm.intYear.value);

	var MonthlyInt = AnnualInt / (12.0 * 100.0);

	var LenMonths  = parseInt(frm.termMonths.value);

	var MonthlyPay = ReadDollarField(frm.payMonth);

	var Principle  = ReadDollarField(frm.price) - ReadDollarField(frm.downpay);

	var OldDownPay = ReadDollarField(frm.downpay);

	var EffPrinciple



	if(MonthlyInt == 0)

		EffPrinciple = MonthlyPay * LenMonths;

	else

		EffPrinciple = MonthlyPay * ((1 - Math.pow((1 + MonthlyInt), -LenMonths)) / MonthlyInt);



	var NewDownPay = OldDownPay + (Principle - EffPrinciple);

	frm.downpay.value = "" + NewDownPay;

	CheckDollarField(frm.downpay);



	RecalcDownPayPerc(frm);

	RecalcMonthlyPay(frm);

}





function RecalcDownPayPerc(frm) {

	var HomePrice  = ReadDollarField(frm.price);

	var DownPay = ReadDollarField(frm.downpay);

	var DownPayPerc = 100 * DownPay / HomePrice;



	if(DownPayPerc >= 0  &&  DownPayPerc <= 100) {

		var DownPayPercStr = "" + DownPayPerc;



		var pos = DownPayPercStr.indexOf(".");

		if(DownPayPercStr.length > pos + 4)

			DownPayPercStr = DownPayPercStr.substring(0,pos+4);



		frm.downpayperc.value = DownPayPercStr;

	}

	else if(DownPayPerc < 0) {

		frm.downpayperc.value = "0";

		RecalcDownPayAmount(frm);

	}

	else {

		frm.downpayperc.value = "100";

		RecalcDownPayAmount(frm);

	}

}





function RecalcDownPayAmount(frm) {

	var HomePrice  = ReadDollarField(frm.price);

	var DownPayPerc = parseFloat(frm.downpayperc.value);

	if(DownPayPerc < 0) {

		frm.downpayperc.value = "0";

		RecalcDownPayAmount(frm);

	}

	else if(DownPayPerc > 100) {

		frm.downpayperc.value = "100";

		RecalcDownPayAmount(frm);

	}

	else {

		var DownPay = HomePrice * DownPayPerc / 100;

		DownPay = FloatToDollarString(DownPay);

		frm.downpay.value = "" + DownPay;

	}

}


//--------------------------------------------------------------------//