// JavaScript Document

var responseUrl = '/response.cfm';

function init() {

	/* Property Search Autocompleter */
	if ($('psearch')) {
		new Ajax.Autocompleter("psearch", "psearch_choices", responseUrl, {
		parameters: 'action=propSearchAuto', 
		minChars: 1,
		frequency: 0.1,
		indicator: 'psearch_indicator',		
		/*callback: function(input,qryStr) { $('psearch_choices').style.width='175px'; return qryStr; },*/
		afterUpdateElement: function(text,li) { 
				$('psearch').value = li.id;
				//$('psearchForm').submit();
			}
		});
		$('psearch_choices').style.border ='1px solid #013499';
	} //end if
} //end init fuction


/* Global Confirm Logout */
function confirmLogout() {
	if (confirm('Are you sure you want to logout of ISoldMyHouse.com?')) {
		return true;
	} else {
		return false;	
	}
} //end func


/* Account Creation Functions */

function AC_checkSeller(checkBox) {
	if (checkBox.checked) {
		$('bestPhoneRow').style.display = '';
	} else {
		$('bestPhoneRow').style.display = 'none';
	}
} //end func

function AC_checkState(val) {
	if (val == 0) {
		$('countryRow').style.display = '';
	} else {
		$('countryRow').style.display = 'none';
	}
} //end func


function AC_checkPassword(password) {
	var message = '';
	var rating = 0;
	var passwd = password.value;
	
	if (/\s/.test(passwd)) { message = 'No Spaces'; } 
	else if (passwd.length < 6) { message = 'Too Short'; } 
	else if (/^[a-z]*$/.test(passwd) || /^[A-Z]*$/.test(passwd) || /^\d*$/.test(passwd) ) { message = 'Weak'; rating = 1; } 
	else if (/^[a-zA-Z]*$/.test(passwd)) { message = 'Moderate'; rating = 2; } 
	else if (/^[a-zA-Z0-9]*$/.test(passwd)) { message = 'Strong'; rating = 3; } 
	else { message = 'Very Strong'; rating = 4; } 
	
	$('passwordMessage').innerHTML = message;
	if (rating > 0) { 
		$('AC_password').style.borderColor = '';
		return true;
	} else { 
		$('AC_password').style.borderColor = '#cc0000';
		return false;
	}
} //end func

function AC_checkPassword2(password) {
	if (AC_checkPassword($('AC_password')) && password.value == $('AC_password').value) {
		$('password2Message').innerHTML = 'Match';
		$('AC_password2').style.borderColor = '';
		return true;
	} else if (AC_checkPassword($('AC_password')) == false) {
		$('password2Message').innerHTML = '';
		$('AC_password2').style.borderColor = '';
		return false;
	} else {
		$('password2Message').innerHTML = '';
		$('AC_password2').style.borderColor = '#cc0000';
		return false;
	}
} //end func


function AC_checkUsername(username) {
	if (username.value.length > 5) {
		$('AC_usernameOk').value = 0;
		$('usernameMessage').innerHTML = '<img src="/images/common/loading.gif">'; 
		new Ajax.Request(responseUrl, {
		  method: 'post',
		  postBody: 'action=unCheck&username=' + username.value,
		  onSuccess: function(transport) {
			if (transport.responseText == 'true') {
				$('usernameMessage').innerHTML = 'Okay';
				$('AC_username').style.borderColor = '';
				$('AC_usernameOk').value = 1;
			} else {
				$('usernameMessage').innerHTML = 'Username <strong>' + username.value + '</strong> is already in use.';
				$('AC_username').style.borderColor = '#cc0000';
				$('AC_usernameOk').value = 0;
			} //end if-else
		  }
		});
	} else { 
		$('usernameMessage').innerHTML = ''; 
		$('AC_username').style.borderColor = '';
		$('AC_usernameOk').value = 0;
	}//end if

} //end func

function AC_checkEmail(email) {
	if (validEmail(email.value)) {
		//$('AC_emailOk').value = 0;
		
		$('emailMessage').innerHTML = '<img src="/images/common/loading.gif">'; 
		new Ajax.Request(responseUrl, {
		  method: 'post',
		  postBody: 'action=emailCheck&email=' + email.value,
		  onSuccess: function(transport) {
			if (transport.responseText == 'true') {
				$('emailMessage').innerHTML = 'Okay';
				$('AC_email').style.borderColor = '';
				$('AC_emailOk').value = 1;
			} else if(transport.responseText == 'invalid') {
				$('emailMessage').innerHTML = '<strong>' + email.value + '</strong> is not a valid email';
				$('AC_email').style.borderColor = '#cc0000';
				$('AC_emailOk').value = 0;
			} else {
				$('emailMessage').innerHTML = '<strong>' + email.value + '</strong> is already in use. <a href="/account">Login</a>';
				$('AC_email').style.borderColor = '#cc0000';
				$('AC_emailOk').value = 0;
			} //end if-else
		  }
		});
		
	} else { 
		//$('emailMessage').innerHTML = ''; 
		//$('AC_email').style.borderColor = '';
		$('AC_emailOk').value = 0;
	}//end if
} //end func


function SH_checkZipCode(zip) {
	if (zip.value.length == 5) {
		$('SH_zipOk').value = 0;
		$('zipCodeMessage').innerHTML = '&nbsp;<img src="/images/common/loading.gif">'; 
		new Ajax.Request(responseUrl, {
		  method: 'post',
		  postBody: 'action=zipCheck&zipCode=' + zip.value,
		  onSuccess: function(transport) {
			if(transport.responseText == 'invalid') {
				$('zipCodeMessage').innerHTML = '<strong>' + zip.value + '</strong> is not a valid U.S. Zip Code';
				$('SH_zipCode').style.borderColor = '#cc0000';
				$('SH_zipOk').value = 0;
			} else if (transport.responseText != 'error') {
				$('zipCodeMessage').innerHTML = '<strong>' + transport.responseText + '</strong>';
				$('SH_zipCode').style.borderColor = '';
				$('SH_zipOk').value = 1;
			} //end if-else
		  },
		  onFailure: function(e) { alert('fail'); }
		});
	} else { 
		$('zipCodeMessage').innerHTML = ''; 
		$('SH_zipCode').style.borderColor = '';
		$('SH_zipOk').value = 0;
	}//end if
} //end func


/* Validate SH Form */
function SH_checkForm() {
	
	var error = false;
	if ($('SH_zipOk').value == 0) { error = true; $('zipCodeMessage').innerHTML = '<span class="error">Please enter a valid 5 digit U.S. zip code</span>'; }
	//if ($('SH_userAgree').checked == false) { error = true; $('userAgreeMessage').innerHTML = 'You must accept the user agreement to continue'; } else { $('userAgreeMessage').innerHTML = ''; }
		
	// If error, return false
	if (error == true) { return false; } else {	return true; }
} //end function

/* Validate AC Form */
function AC_checkForm() {
	
	var error = false;

	//if ($('AC_usernameOk').value == 0) { error = true; }
	//AC_checkEmail($('AC_email'));
	//if ($('AC_emailOk').value == 0) { error = true; }
	if (trim($('AC_email').value) == '' ||  validEmail($('AC_email').value) == false || $('AC_emailOk').value == 0) { error = true; $('AC_email').style.borderColor = '#cc0000'; $('emailMessage').innerHTML = '<span class="error">Please enter a valid email address</span>'; } else { $('AC_email').style.borderColor = ''; }
	if (AC_checkPassword($('AC_password')) == false) { error = true; }
	if (AC_checkPassword2($('AC_password2')) == false) { error = true; }
	if (trim($('AC_firstName').value).length < 2) { error = true; $('AC_firstName').style.borderColor = '#cc0000'; $('firstNameMessage').innerHTML = 'Please enter your First Name'; } else { $('AC_firstName').style.borderColor = ''; $('firstNameMessage').innerHTML = ''; }
	if (trim($('AC_lastName').value).length < 2) { error = true; $('AC_lastName').style.borderColor = '#cc0000'; $('lastNameMessage').innerHTML = 'Please enter your Last Name'; } else { $('AC_lastName').style.borderColor = ''; $('lastNameMessage').innerHTML = ''; }
	if ($('AC_buy').checked == false && $('AC_sell').checked == false) { error = true; $('typeMessage').innerHTML = 'Please select one option'; } else { $('typeMessage').innerHTML = ''; }
	if (trim($('AC_zipCode').value).length < 5) { error = true; $('AC_zipCode').style.borderColor = '#cc0000'; $('zipCodeMessage').innerHTML = 'Please enter your Zip/Postal Code'; } else { $('AC_zipCode').style.borderColor = ''; $('zipCodeMessage').innerHTML = ''; }
		
	// If error, return false
	if (error == true) { 
		$('formMessage').innerHTML = 'Please check the form above for missing or incomplete information';
		return false; 
	} else {
		$('formMessage').innerHTML = '';
		return true; 
	}
} //end function


/* Validate Account Reset Form */
function AR_checkForm() {
	
	var error = false;

	if (validEmail(trim($('AR_email').value)) == false) { error = true; $('AR_email').style.borderColor = '#cc0000'; $('emailMessage').innerHTML = 'Please enter a valid Email'; } else { $('AR_email').style.borderColor = ''; $('emailMessage').innerHTML = ''; }
	if (trim($('AR_zipCode').value).length < 5) { error = true; $('AR_zipCode').style.borderColor = '#cc0000'; $('zipCodeMessage').innerHTML = 'Please enter your Zip/Postal Code'; } else { $('AR_zipCode').style.borderColor = ''; $('zipCodeMessage').innerHTML = ''; }
		
	// If error, return false
	if (error == true) { return false; } else {	return true; }
} //end function


/* Validate AU Form */
function AU_checkForm() {
	
	var error = false;

	if (trim($('AU_firstName').value).length < 2) { error = true; $('AU_firstName').style.borderColor = '#cc0000'; $('firstNameMessage').innerHTML = 'Please enter your First Name'; } else { $('AU_firstName').style.borderColor = ''; $('firstNameMessage').innerHTML = ''; }
	if (trim($('AU_lastName').value).length < 2) { error = true; $('AU_lastName').style.borderColor = '#cc0000'; $('lastNameMessage').innerHTML = 'Please enter your Last Name'; } else { $('AU_lastName').style.borderColor = ''; $('lastNameMessage').innerHTML = ''; }
	if ($('AU_buy').checked == false && $('AU_sell').checked == false) { error = true; $('typeMessage').innerHTML = 'Please select one option'; } else { $('typeMessage').innerHTML = ''; }
	if (trim($('AU_zipCode').value).length < 5) { error = true; $('AU_zipCode').style.borderColor = '#cc0000'; $('zipCodeMessage').innerHTML = 'Please enter your Zip/Postal Code'; } else { $('AU_zipCode').style.borderColor = ''; $('zipCodeMessage').innerHTML = ''; }
		
	// If error, return false
	if (error == true) { return false; } else {	return true; }
} //end function


/* Validate PU Form */
function PU_checkForm() {

	var error = false;

	if (AC_checkPassword($('AC_password')) == false) { error = true; }
	if (AC_checkPassword2($('AC_password2')) == false) { error = true; }
		
	// If error, return false
	if (error == true) { return false; } else {	return true; }
	
} //end function


/* Validate LM Form */
function LM_checkForm() {
	
	var error = false;
	//if (isNaN(parseInt(trim($('LM_livingSpace').value)))) { error = true; $('LM_livingSpace').style.borderColor = '#cc0000'; $('livingSpaceMessage').innerHTML = 'Please enter a numeric value'; } else { $('LM_livingSpace').style.borderColor = ''; $('livingSpaceMessage').innerHTML = ''; }
	// If error, return false
	if (error == true) { return false; } else {	return true; }
} //end function






function addToPortfolio(adNumber,elem,responseFormat) {
	new Ajax.Request(responseUrl, {
	  method: 'post',
	  postBody: 'action=addPortfolio&ad_number=' + adNumber + '&responseFormat=' + responseFormat + '&element=' + elem,
	  onSuccess: function(transport) {
		if (transport.responseText.split('|')[0] == 'true') {
			$(elem).innerHTML = transport.responseText.split('|')[1];
		} else if (transport.responseText.split('|')[0] == 'false') {
			alert(transport.responseText.split('|')[1]);
		} else {
			alert('The property could not be added');
		} //end if-else
	  },
	  //onException: function(e) { alert(e); },
	  onFailure: function(e) { alert(e.status + ' ' + e.statusText); }
	});
} //end func

function removeFromPortfolio(adNumber,elem,responseFormat) {
	new Ajax.Request(responseUrl, {
	  method: 'post',
	  postBody: 'action=removePortfolio&ad_number=' + adNumber + '&responseFormat=' + responseFormat + '&element=' + elem,
	  onSuccess: function(transport) {
		if (transport.responseText.split('|')[0] == 'true') {
			if (transport.responseText.split('|')[1] == 'remove') {
				$(elem).style.overflow='hidden';
				new Effect.Morph(elem,{style:'height:1px',duration:0.5,afterFinish: function(e) { 
					$(e.element).remove();
					if ($('portfolio_items').childElements().length == 0) { 
						Element.insert('portfolio_items',{'top':'<div class="contentPadding"><strong>YOU HAVE NO LISTINGS IN YOUR PORTFOLIO</strong></div>'});
					}
				}});
			} else {
				$(elem).innerHTML = transport.responseText.split('|')[1];
			}
		} else if (transport.responseText.split('|')[0] == 'false') {
			alert(transport.responseText.split('|')[1]);
		} else {
			alert('The property could not be removed');
		} //end if-else
	  },
	  //onException: function(e) { alert(e); },
	  onFailure: function(e) { alert(e.status + ' ' + e.statusText); }
	});
} //end func





/** Utility Functions **/


/* convertInt */
function convertInt(field) {
	if (trim(field.value) != '') {
		var newVal = trim(field.value).replace(/\D/g,"");
		if (parseInt(newVal)) {
			field.value = parseInt(newVal);
		} else {
			field.value = '';
		} //end if		
	} else {
		field.value = '';
	} //end if	
} //end function

/* convertFloat */
function convertFloat(field,scale) {
	if (trim(field.value) != '') {
		var newVal = trim(field.value).replace(/[^\.\d]/g,"");
		//alert(newVal.toFixed(scale));
		if (parseFloat(newVal)) {
			field.value = parseFloat(newVal).toFixed(scale);
		} else {
			field.value = '';
		} //end if		
	} else {
		field.value = '';
	} //end if	
} //end function

/* Email Validation */
function validEmail(email) {
	invalidChars = " /:,;"
	if (email == "Required") {
		return false
	}
	for (i=0; i<invalidChars.length; i++) {
		badChar = invalidChars.charAt(i)
		if (email.indexOf(badChar,0) != -1) {
			return false
		}
	}
	atPos = email.indexOf("@",1)
	if (atPos == -1) {
		return false
	}
	if (email.indexOf("@",atPos+1) != -1) {
		return false
	}
	periodPos = email.indexOf(".",atPos)
	if (periodPos == -1) {
		return false
	}
	if (periodPos+3 > email.length)	{
		return false
	}
	return true
}


function ltrim(str) {
	while (1) {
		if (str.substring(0, 1) != " ")
		break;
		str = str.substring(1, str.length);
	} //end while
	
	return str;
} //end function


function rtrim(str) {
	while (1) {
		if (str.substring(str.length - 1, str.length) != " ")
		break;
		str = str.substring(0, str.length - 1);
	} //end while
	
	return str;
} //end function


function trim(str) {
	return ltrim(rtrim(str));
} //end function


var hoverOut = false;

function hoverImage(img,state) {
	if (state == true) {
		$('imageZoom').style.display='block';
		$('imageZoom').clonePosition(img);
		$('imageZoom').style.backgroundColor = '#ffffff';
		$('imageZoom').style.opacity=0.0;
		$('imageZoom').style.filter='alpha(opacity=0)';
		$('imageZoom').onmouseout = function() { hoverImage(img,false); }
		//alert(img.title);
		$('imageCaption').style.opacity=0;
		$('imageCaption').style.filter='alpha(opacity=0)';
		
		if ($('imageCaptionText').innerHTML != '' && hoverOut == false) {
			//$('imageCaption').innerHTML = '<div style="background-color:#000000;padding:5px;width:300px;margin:0px auto;">' + $(img).readAttribute("caption") + '</div>';
			//$('imageCaptionText').innerHTML = $(img).readAttribute("caption");
			new Effect.Opacity('imageCaption', {duration:0.3, from:0.0, to:0.7 });	
		}
	} else {
		if ($('imageCaption').style.opacity != 0) {
			hoverOut = true;
			new Effect.Opacity('imageCaption', {duration:0.3, from:0.7, to:0.0, afterFinish: function() {
				//$('imageCaptionText').innerHTML = '';
				$('imageZoom').style.display='none';
				hoverOut = false;
			}});
		} else {
			$('imageCaption').style.opacity=0;
			$('imageCaption').style.filter='alpha(opacity=0)';	
			$('imageZoom').style.display='none';
		} //end if
	}
} //end function

function highlightThumb(img) {
	if (!$(img).hasClassName('selected')) {
		if ($(img) && $(img).style.opacity=='1') {
			$(img).style.opacity='0.5';
			$(img).style.filter='alpha(opacity=50)';
		} else {
			$(img).style.opacity='1';
			$(img).style.filter='alpha(opacity=100)';
		}
	}
} //end function


function selectThumb(img) {
	var currentSelected = $('thumbScroller').getElementsBySelector('.selected');

	if (currentSelected.length > 0 && $(currentSelected[0])) { 
		$(currentSelected[0]).removeClassName('selected');
		$(currentSelected[0]).style.opacity='0.5';
		$(currentSelected[0]).style.filter='alpha(opacity=50)';		
	} //end if

	$(img).addClassName('selected');
	$(img).style.opacity='1';
	$(img).style.filter='alpha(opacity=100)';

	var propSrcDir = $('layer1').src.split('/');
	propSrcDir[propSrcDir.length-1] = $(img).id;
	rotateImg(propSrcDir.join('/') + '.jpg',img);
} //end function


var currentLayer = 2;

function rotateImg(newImg,img) {
	try {
		// Set layer 1
		if (currentLayer == 2) {
			Event.observe('layer1', 'load', function() {
				new Effect.Opacity('imageField2', {duration:0.5, from:1.0, to:0.0, afterFinish: function() { $('imageField2').style.display = 'none'; }});
			});
			$('layer1').src = newImg;
			//$('layer1').setAttribute("caption",img.title);
			$('imageCaptionText').innerHTML = img.title;
			currentLayer = 1;
		
		// Set layer 2
		} else if (currentLayer == 1) {

			Event.observe('layer2', 'load', function() {
				$('imageField2').style.display = ''; 
				new Effect.Opacity('imageField2', {duration:0.5, from:0.0, to:1.0 });
			});
			$('layer2').src = newImg;
			//$('layer2').setAttribute("caption",img.title);
			$('imageCaptionText').innerHTML = img.title;
			currentLayer = 2;
		} //end if
		
	} catch(e) {
		alert('Error: ' + e.description);	
	}

} //end function

var leftScroller = false;
var rightScroller = false;

function scrollThumbLeft(imgCount) {
	var imgCount = imgCount ? imgCount : 1;
	var currentPos = parseInt($('thumbScroller').style.marginLeft);
	
	if (leftScroller == false) {
		if (currentPos > -(imgCount * 121 - 363)) {
			leftScroller = true;
			$('thumbScroller').morph('margin-left:' + (currentPos-363) + 'px;', { duration: 1.0, afterFinish: function() { leftScroller = false; } });// + currentPos-121 + 'px;');
			//if (currentPos >= -363) {
			$('rightScroller').removeClassName('disabled');
			$('rightScroller').title = 'More Photos';
		} else {
			$('leftScroller').addClassName('disabled');
			$('leftScroller').title = '';
		} //end if-else
		//alert(currentPos + ' ' + -(imgCount * 121-363));
		if (currentPos <= -(imgCount * 121-726)) { $('leftScroller').addClassName('disabled'); $('leftScroller').title = ''; }
	} //end if
}

function scrollThumbRight(imgCount) {
	var currentPos = parseInt($('thumbScroller').style.marginLeft);

	if (rightScroller == false) {
		if (currentPos <= -363) {
			rightScroller = true;
			$('thumbScroller').morph('margin-left:' + (currentPos+363) + 'px;', { duration: 1.0, afterFinish: function() { rightScroller = false; } });// + currentPos-121 + 'px;');
			$('leftScroller').removeClassName('disabled');			
			$('leftScroller').title = 'More Photos';
		} else if (currentPos < 0) {
			rightScroller = true;
			$('thumbScroller').morph('margin-left:0px;', { duration: (1-currentPos/363), afterFinish: function() { rightScroller = false; } });// + currentPos-121 + 'px;');
			$('leftScroller').removeClassName('disabled');		
			$('leftScroller').title = 'More Photos';
		} //end if
		
		if (currentPos >= -363) { $('rightScroller').addClassName('disabled'); $('rightScroller').title = ''; }
	} //end if
}


function autoGrow(textarea,minHeight,maxHeight) {
	var minHgt = minHeight ? minHeight:15;
	var maxHgt = maxHeight ? maxHeight:150;

	if ($('textarea_holder') && $(textarea)) {
		$('textarea_holder').style.width=($(textarea).getWidth()-5) + 'px';
		var html = $(textarea).value; /*.replace(/(<|>)/g, '');*/
		html = html.replace(/\n/g, '<br>');
		$('textarea_holder').innerHTML = html;
		if (html == '') {
			$(textarea).style.height=minHgt+'px';
		} else {
			var textHeight = $('textarea_holder').getHeight()+15;
			if (textHeight < minHgt) { textHeight = minHgt; }
			if (textHeight > maxHgt) { textHeight = maxHgt; $(textarea).style.overflow='auto'; } else { $(textarea).style.overflow='hidden'; }
			$(textarea).morph('height:' + (textHeight)+ 'px', { duration:0.3 }); 
		}
	}
}

function rotateSHomes() {
	try {
		if (spotlightHomes.length-1 < shPos) { 
			for (var i=1;i<spotlightHomes.length-1;i++) {
				$('shField' + spotlightHomes[i]).style.display = 'none';
			}
			new Effect.Opacity('shField' + spotlightHomes[spotlightHomes.length-1], {duration:0.5, from:1.0, to:0.0, afterFinish: function() { $('shField' + spotlightHomes[spotlightHomes.length-1]).style.display = 'none'; } });
			shPos = 1; 
		} else {
			$('shField' + spotlightHomes[shPos]).style.opacity = '0';
			$('shField' + spotlightHomes[shPos]).style.filter = 'alpha(opacity=0)';
			$('shField' + spotlightHomes[shPos]).style.display = 'block';
			new Effect.Opacity('shField' + spotlightHomes[shPos], {duration:0.5, from:0.0, to:1.0, afterFinish: function() { } });
			shPos++;
		}
		
	} catch(e) {
		//alert('Error: ' + e.description);	
	}
} //end function