FORM_VALIDATION = true;

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

/* ---- Controller function to implement Animation class for window fade ---- **
** qualified as "window.display" or loaded as just "display", use this 				**
** function as a replacement for "alert(str)", ie: "display(str)"							**
** -------------------------------------------------------------------------- */

function display(str, elementID /* optional - switches DIV elements */ ) {
	var displayElement;
	var defaultElement = document.getElementById("MSG_default");
	if(!elementID) displayElement = defaultElement;
	else displayElement = document.getElementById(elementID);
	var msgGraphics = new Animation(displayElement);
	var fadeOutDisplay = function() {
		msgGraphics.fadeElementOpacity(-1, 0, 50);		
		};	
	msgGraphics.fadeElementOpacity(1, 100, 25);	
	displayElement.innerHTML = "<img src='images/visuals/information.gif' class='MSG_information' />"
							 + "<div class='MSG_'><span class='title'>For Your Information</span><br /><br />" + str + "</div>"; 
	setTimeout(fadeOutDisplay, 3000);
	}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	} return [curleft,curtop];
}


/* ---------- Container 'class' : includes UI methods and Form validating methods ------------- */
/* use "Container.setObject(el)" to set any element into the container object (globally within  **
** the instance, OR "Container.Form.setObject(formEl)" to set any form element into the 				**
** Container object's FORM instance (or delegation). Container.UI.* methods are supported by		**
** objects set with the global Container.setObject and those objects share all of the methods		**	
** in each Container.* 'class', whereas Container.Form.setObject objects only support						**
** Container.Form.* methods. this will be the default mechanism for all common JS activity      **
** -------------------------------------------------------------------------------------------- */

var Container = {
	itself: null,	
	setObject: function(element) { this.itself = element; },
	UI: {
		setElementVisual: function() {
			if(!Container.itself) return;
			var element = Container.itself;
			var elUI = Container.itself.style;	
			var state = element.getAttribute("status");
			var destruct = function() { window.eventElementState = element.getAttribute("status"); }
			if(!state || state == "hidden" || state == "static") {
				elUI.visibility = "visible";
				elUI.display = "block";
				element.setAttribute("status", "shown");				
			} else {
				elUI.visibility = "hidden";
				elUI.display = "none";
				element.setAttribute("status", "hidden");
			} destruct();
		}
	},
	Form: {
		itself: null,	
		setObject: function(form) { this.itself = form; },
		validate: function(fields, messages, displayBox, e) {
			var WEB_ID_FORM = document.webIDForm;
			var USE_DISPLAY = false;
			var form = this.itself;
			var messenger = function(m) { alert(m); };
			if(!displayBox) displayBox = "MSG_default";
			if(USE_DISPLAY) messenger = function(m) { display(m, displayBox); };
			if(form == WEB_ID_FORM) {
				if(checkWebID()) {
					form.submit();
				} else {
					cancel(e);
				}	return;
			}
			if(form && fields) {
				if(checkFields()) {
					form.submit();
				} else {
					cancel(e);
				} return;
			}
			function cancel(e) {
				if(!e.preventDefault) {
					e.returnValue = false;
				} else {
					e.preventDefault();
				}
			}
			function checkWebID() {
				var fieldObjectValidity = true;
				var fieldDefaultValue = "Enter Web ID";
				if(!fields) fields = document.webIDForm.agentsStr;
				if(!messages) messages = "You must enter a listing ID number to search for.";
				var fieldObject = fields;
				var message = messages;
				if(fieldObject.value.toLowerCase() == fieldDefaultValue) {
					messenger(message);
					fieldObject.value = "";
					fieldObject.focus();
					fieldObjectValidity = false;
				} return fieldObjectValidity;
			}
			function checkFields() {
				var STRICT_VALIDATION = true;
				var DEFAULT_MSG = "Please make sure the form has been completely filled out.";
				var formValidity = true;
				for(var i = 0; i < fields.length; i++) {
					// loose validation
					if(!form.elements[fields[i]].value) {
						if(!messages || !messages[i] || messages[i] == "") {
							messenger(DEFAULT_MSG); 
							formValidity = false;
						}	else {
							messenger(messages[i]);
						} return;
							formValidity = false;
					} else if(STRICT_VALIDATION) {
						// strict validation - special case for name, phone, and email fields
						if((form.elements[fields[i]].name.toLowerCase() == "phone")
							|| (form.elements[fields[i]].name.toLowerCase() == "dphone")
							|| (form.elements[fields[i]].name.toLowerCase() == "dayphone")) {
							var phoneField = form.elements[fields[i]];
							var wrongNumberLength = "Phone number must be 10 digits long.";
							var alphaNumericNumber = "Phone number must contain only digits.";
							if((phoneField.value.length < 10 || phoneField.value.length > 12)
								|| phoneField.value.length == 11) {
								messenger(wrongNumberLength);
								formValidity = false;
							}	else if(phoneField.value.search(/[a-zA-Z]/i) >= 0) {
								messenger(alphaNumericNumber);
								formValidity = false;
							}
						} else if(form.elements[fields[i]].name.toLowerCase() == "email") {
							var emailField = form.elements[fields[i]];
							var invalidEmailSyntax = "Please enter a valid E-Mail address.";
							if((emailField.value.search(/@/i) == -1)
								|| (emailField.value.search(/\./i) == -1)
								|| (emailField.value.length < 5)) {
								messenger(invalidEmailSyntax);
								formValidity = false;
							}
						}	else if(form.elements[fields[i]].name.toLowerCase() == "name") {
							var nameField = form.elements[fields[i]];
							var invalidFullName = "Please enter your full name.";
							if((nameField.value.search(/\s/i) == -1)
								|| (nameField.value.search(/\w/i) == -1)) {
								messenger(invalidFullName);
								formValidity = false;
							}
						} else if((form.elements[fields[i]].name.toLowerCase() == "zip")
								|| (form.elements[fields[i]].name.toLowerCase() == "billing_zip")) {
							var zipField = form.elements[fields[i]];
							var invalidZipCode = "Please correctly enter your five digit zip code.";
							if((zipField.value.length != 5)
								|| (zipField.value.search(/[a-zA-Z]/i) >= 0)) {
								messenger(invalidZipCode);
								formValidity = false;
							}
						}
					}
				} return formValidity;
			}
		}		
	}
}


/* -------- Menu rollover ---------- */

var Menu = {
	eMenuItem : null,
	eProperties : null,
	onMouseOver : function(element) {
		if(!element) return;
		else setMenuObject();
		this.eProperties.filter = "alpha(opacity=80)";
		this.eProperties.opacity = ".8";	
		function setMenuObject() {
			Menu.eMenuItem = element;
			Menu.eProperties = element.style;
		}
	},
	onMouseOut : function(element) {
		this.eProperties.filter = "alpha(opacity=100)";
		this.eProperties.opacity = "1";	
	}
}


/* -------- generic functions of the "window" object ------- */

function Get_Cookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

function Set_Cookie(name,value,expires,path,domain,secure) {
    document.cookie = name + "=" +escape(value) +
        ( (expires) ? ";expires=" + expires.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") + 
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
}

function Delete_Cookie(name,path,domain) {
    if (Get_Cookie(name)) document.cookie = name + "=" +
       ( (path) ? ";path=" + path : "") +
       ( (domain) ? ";domain=" + domain : "") +
       ";expires=Thu, 01-Jan-70 00:00:01 GMT";
}



function popUp(url, winname, width, height, scroll, resize, status) {
	newWin=window.open(url,winname,'toolbar=0,location=0,directories=0,,menubar=0' 
		+ ',scrollbars='+scroll 
		+ ',resizable='+resize 
		+ ',status=' + status 
		+ ',width=' + width 
		+ ',height='+ height);
	self.name = "mainWin"; 
}


function MM_findObj(n, d) { //v3.0
  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); return x;
}
/* Functions that swaps images. */
function MM_swapImage() { //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];}
}

function MM_swapImgRestore() { //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;
}

/* Functions that handle preload. */
function MM_preloadImages() { //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];}}
}




function removeAB(str_) {
	digits = '0123456789.';
	clr = '';
	for (i=0; i<str_.length; i++) {
		if (digits.indexOf(str_.charAt(i))>-1) {
			clr +=  str_.charAt(i);
		}
	}
	if (clr.length == 0) { clr = "0"; }
	return clr;
}

function removeABC(val, name) {
	newVal = val.replace(/[^\d\.]/g,'')
	document.getElementById(name).value = newVal;
}

function validateField(field,theForm,str,divID)  {
	if (field.value.length == 0) {
		if(!divID) alert(str);
		else display(str, divID);
	} else {
		theForm.submit();
	}
}


function validateForm(field,theForm)  {
	if (field.value == 'Enter Web ID or Agent Name') {
		field.value = "";
	}
	theForm.submit();
}



function formatStreet(str_) {

		//str_ = clearQuotes(str_);
		
		str_ = str_.toUpperCase();
		
		re = '.';
		str_ = str_.replace(re, '') ;
		
		
		re = 'EAST ';
		str_ = str_.replace(re, 'E ') ;
		
		re = 'WEST ';
		str_ = str_.replace(re, 'W ') ;
		
		re = ' STREET';
		str_ = str_.replace(re, ' St.') ;
		
		re = ' ST';
		str_ = str_.replace(re, ' St.') ;
		
		re = 'St.';
		str_ = str_.replace(re, 'ST.') ;
		
		re = ' AVENUE';
		str_ = str_.replace(re, ' Ave.') ;
		
		re = ' AVE';
		str_ = str_.replace(re, ' Ave.') ;
		
		re = ' AV';
		str_ = str_.replace(re, ' Ave.') ;
		
		re = 'Ave.';
		str_ = str_.replace(re, 'AVE.') ;

		re = ' ROAD';
		str_ = str_.replace(re, ' RD') ;
		
		re = ' RD';
		str_ = str_.replace(re, ' RD.') ;

		re = 'FIRST ';
		str_ = str_.replace(re, '1ST ') ;

		re = 'SECOND ';
		str_ = str_.replace(re, '2ND ') ;
		
		re = 'THIRD ';
		str_ = str_.replace(re, '3RD ') ;
		
		re = 'FOURTH ';
		str_ = str_.replace(re, '4TH ') ;

		re = 'FIFTH ';
		str_ = str_.replace(re, '5TH ') ;
		
		re = 'SIXTH ';
		str_ = str_.replace(re, '6TH ') ;

		re = 'SEVENTH ';
		str_ = str_.replace(re, '7TH ') ;

		re = 'EIGHT ';
		str_ = str_.replace(re, '8TH ') ;

		re = 'NINTH ';
		str_ = str_.replace(re, '9TH ') ;
		
		re = 'TENTH ';
		str_ = str_.replace(re, '10TH ') ;

		
		
		return str_;
	}




function formatPhone(Phone,Ext) {

		Phone = Phone.toUpperCase();
		
		digits = '0123456789X';
		clr = '';
		for (i=0; i<Phone.length; i++) {
			if (digits.indexOf(Phone.charAt(i))>-1) {
				clr +=  Phone.charAt(i);
			}
		}
		
		if (Ext>0) {
			n=clr.indexOf('X');
			if (n>-1) {
				document.alertForm.Ext.value = clr.substr(n+1,4);
				clr = clr.replace("X","");
				clr = clr.substr(0,10);
			}		
		}
		
		if (clr.length > 0)
		clr = "(" + clr.substr(0,3) + ") " + clr.substr(3,3) + "-" + clr.substr(6,10);
		
		return(clr);
		
	}
	
	
function toggleDiv(div) {
	if (div.style.display == 'none') div.style.display = 'block'
	else div.style.display = 'none';
}

function sortdropdown(selected) {
	document.location=selected;
}

sfHover = function() {
	var sfEls = document.getElementById("NavigationItem").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}

/*
 *	Register event handlers for window events
 

window.onload = function() {
	
	this.pageContext				= new PageContext();
	this.contentViewer			= document.getElementById("wrapper");
	this.contentView				= this.contentViewer.style;
	
	// we're defining a 'paint' method for 'wrapper' object so it can be called from the
	// onload event or onresize event
	(contentViewer.paint = function() {	
																	
		var ORIGINAL_WIDTH		= document.getElementById('wrapper_width').style.width.replace(/[^\d\.]/g,'');
		var MIN_WIDTH					= 1004;
		var ORIGINAL_HEIGHT		= 800;
		var MIN_HEIGHT				= 400;
		
		if(document.body.className.indexOf('home') > -1) {
			if(pageContext.viewport["width"] < MIN_WIDTH) {
				contentView["width"] = MIN_WIDTH + "px";
			} else if(pageContext.viewport["width"] > ORIGINAL_WIDTH) {
				contentView["width"] = ORIGINAL_WIDTH + "px";
			} else {
				contentView["width"] = pageContext.viewport["width"] + "px";		
			}		
		}
			
	}).call();
	
	// this is used for the menu rollovers in IE 6
	if(document.all&&document.getElementById&&document.getElementById("NavigationItem")) sfHover();
	
};

window.onresize = function() {		
	if(this.pageContext) this.pageContext.update();
	if(this.contentViewer) this.contentViewer.paint();	
};
*/

function UpdateSelectedAreasHiddenField(str_CatIDList) {	
	var catBoxes = document.theForm.cat;
	var areas = str_CatIDList.split(',');	
	
	for(var i = 0; i < catBoxes.length; i++){
		for(var j = 0; j < areas.length; j++){
			if(catBoxes[i].value == areas[j]) {
				catBoxes[i].checked = true;		
				break;
			} 
			else catBoxes[i].checked = false;	
		}
	}				
}

function getPageSize(){
	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function showForm(formId){
	var pageInfo = getPageSize();
	document.getElementById('bLayer').style.top     = '0px';
	document.getElementById('bLayer').style.left    = '0px'; 
	document.getElementById('bLayer').style.width   = pageInfo[0]+'px';
	document.getElementById('bLayer').style.height  = pageInfo[1]+'px';  
	document.getElementById('bLayer').style.display = '';
	dispForm(pageInfo,formId);
}
function dispForm(pageInfo,formId){
	if(formId == "viewAllImages") document.getElementById(formId).style.top = '225px';	
	else document.getElementById(formId).style.top = pageInfo[1] / 3 + 'px';
	document.getElementById(formId).style.left    = (pageInfo[0] - parseInt(document.getElementById(formId).style.width)) / 2 + 'px';
	document.getElementById(formId).style.display = '';
}
function closeForm(formId){
  document.getElementById('bLayer').style.display = 'none';
  document.getElementById(formId).style.display = 'none';
}


function toggleSelectArea(parent,theseAreas,theseBrothers){
	
	//if parent was clicked
	if(parent == 0){		
		var areas = theseAreas.split(',');
		
		if(document.getElementById('subMenu' + areas[0]) == null || document.getElementById('subMenu' + areas[0]).style.display == 'block'){
			
			//if parent was checked before clicking
			if(document.getElementById('areaBox' + areas[0]).checked){
			
				//uncheck all areas
				for(i=0;i<areas.length;i++){
					var area = areas[i];			
					document.getElementById('areaBox' + area).checked = false;
					var areaElement = document.getElementById('area' + area);
					areaElement.style.backgroundImage = "url(images/visuals/areaUnchecked.png)";
					areaElement.style.backgroundRepeat = "no-repeat";
				}
			} 
			//if parent was unchecked
			else {
				
				//check all areas
				for(i=0;i<areas.length;i++){
					var area = areas[i];			
					document.getElementById('areaBox' + area).checked = true;
					var areaElement = document.getElementById('area' + area);
					areaElement.style.backgroundImage = "url(images/visuals/areachecked.png)";
					areaElement.style.backgroundRepeat = "no-repeat";
				}		
			}	
		}
	} 
	
	//if child was clicked
	else {
		
		var brothers = theseBrothers.split(',');
		
		//if child was checked
		if(document.getElementById('areaBox' + theseAreas).checked){
			
			//uncheck both parent and child
			document.getElementById('areaBox' + parent).checked = false;
			document.getElementById('areaBox' + theseAreas).checked = false;
			var areaElement = document.getElementById('area' + parent);
			areaElement.style.backgroundImage = "url(images/visuals/areaUnchecked.png)";
				areaElement.style.backgroundRepeat = "no-repeat";
			var areaElement = document.getElementById('area' + theseAreas);
			areaElement.style.backgroundImage = "url(images/visuals/areaUnchecked.png)";
				areaElement.style.backgroundRepeat = "no-repeat";
		} 
		
		//if child was unchecked
		else {
			
			//check the child
			document.getElementById('areaBox' + theseAreas).checked = true;
			var areaElement = document.getElementById('area' + theseAreas);
			areaElement.style.backgroundImage = "url(images/visuals/areachecked.png)";
				areaElement.style.backgroundRepeat = "no-repeat";
			
			//check brothers
			var allChecked = true;
			
			for(i=0;i<brothers.length;i++){
				var brother = brothers[i];			
				if(document.getElementById('areaBox' + brother).checked == false) allChecked = false;
			}
			
			//if all brothers are checked, check the parent
			if(allChecked){
				document.getElementById('areaBox' + parent).checked = true;
				var areaElement = document.getElementById('area' + parent);
				areaElement.style.backgroundImage = "url(images/visuals/areaChecked.png)";
				areaElement.style.backgroundRepeat = "no-repeat";
			}
			
		}
	}
}

//if checkbox for an area is checked, mark area as selected
function initAreas(){
	for(i=1; i<200; i++){
		if(document.getElementById('areaBox' + i) != null){
			if(document.getElementById('areaBox' + i).checked){
				var areaElement = document.getElementById('area' + i);
				areaElement.style.backgroundImage = "url(images/visuals/areaChecked.png)";
				areaElement.style.backgroundRepeat = "no-repeat";
			}
		}
	}
}

function checkSelectedAreas(myForm){
	var myArray = myForm.cat;
	for ( var i=myArray.length-1; i>=0; --i ){
		if (myArray[i].checked) return true;
	}
	alert ('Please select at least one area to narrow down the results.');
	return false;
}

//OPENS UP POPUPS
function popUpEmail(url,width,height) {
	sealWin=window.open(url,"win1","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width="+width+",height="+height);
	self.name = "mainWin"; 
}

function submitForm(){
	var error = "";
	
	$.each($(".required"), function() { 
		if( $(this).val() == "" || $(this).val() == '$0'){
			def = $(this).attr('def');
			error = error + def + " is a required field.\n";
			$(this).css("border","1px solid red");
		} else if($(this).attr('def') == 'Your full name') {
			thisVal = $(this).val();
			if(thisVal.search(" ") == -1){
				def = $(this).attr('def');
				error = error + def + " needs to consist of both first and last names.\n";
				$(this).css("border","1px solid red");
			}
		} else {
			$(this).css("border","1px solid green");
		}
	});
	
	if( $('#thisForm').attr('page') == 'alerts' ){
		var areasFound = false;
		$.each($("input[name='cat']:checked"), function() { areasFound = true; });
		if(!areasFound) {	error = error + "Select at least one area.\n"; }
	}
	
	if(error != ""){ alert(error); } else { return $('#thisForm').submit(); }
}



function removeComma(str_) {
	digits = '0123456789$';
	clr = '';
	for (i=0; i<str_.length; i++) {
		if (digits.indexOf(str_.charAt(i))>-1) {
			clr +=  str_.charAt(i);
		}
	}
	if (clr.length == 0) { clr = "0"; }
	return clr;
}

function CurrencyFormatted(value){
	var buf = "";
	var sBuf = "";
	var j = 0;
	value = String(value);
	if (value.indexOf(".") > 0) { buf = value.substring(0, value.indexOf(".")); } else { buf = value; }
	if (buf.length%3!=0&&(buf.length/3-1) > 0) { sBuf = buf.substring(0, buf.length%3) + ","; buf = buf.substring(buf.length%3); }
	j = buf.length;
	for (var i = 0; i <(j/3-1); i++) { sBuf = sBuf+buf.substring(0, 3) + ","; buf = buf.substring(3); }
	sBuf = sBuf+buf;
	if (value.indexOf(".") > 0) { value = sBuf + value.substring(value.indexOf("."));} else { value = sBuf; }
	return "$"+value;
}


