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 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';
}


var ddaccordion={
	
	contentclassname:{}, //object to store corresponding contentclass name based on headerclass

	expandone:function(headerclass, selected){ //PUBLIC function to expand a particular header
		this.toggleone(headerclass, selected, "expand")
	},

	collapseone:function(headerclass, selected){ //PUBLIC function to collapse a particular header
		this.toggleone(headerclass, selected, "collapse")
	},

	expandall:function(headerclass){ //PUBLIC function to expand all headers based on their shared CSS classname
		var $=jQuery
		var $headers=$('.'+headerclass)
		$('.'+this.contentclassname[headerclass]+':hidden').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	collapseall:function(headerclass){ //PUBLIC function to collapse all headers based on their shared CSS classname
		var $=jQuery
		var $headers=$('.'+headerclass)
		$('.'+this.contentclassname[headerclass]+':visible').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	toggleone:function(headerclass, selected, optstate){ //PUBLIC function to expand/ collapse a particular header
		var $=jQuery
		var $targetHeader=$('.'+headerclass).eq(selected)
		var $subcontent=$('.'+this.contentclassname[headerclass]).eq(selected)
		if (typeof optstate=="undefined" || optstate=="expand" && $subcontent.is(":hidden") || optstate=="collapse" && $subcontent.is(":visible"))
			$targetHeader.trigger("evt_accordion")
	},

	expandit:function($targetHeader, $targetContent, config, useractivated, directclick){
		this.transformHeader($targetHeader, config, "expand")
		$targetContent.slideDown(config.animatespeed, function(){
			config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), useractivated)
			if (config.postreveal=="gotourl" && directclick){ //if revealtype is "Go to Header URL upon click", and this is a direct click on the header
				var targetLink=($targetHeader.is("a"))? $targetHeader.get(0) : $targetHeader.find('a:eq(0)').get(0)
				if (targetLink) //if this header is a link
					setTimeout(function(){location=targetLink.href}, 200) //ignore link target, as window.open(targetLink, targetLink.target) doesn't work in FF if popup blocker enabled
			}
		})
	},

	collapseit:function($targetHeader, $targetContent, config, isuseractivated){
		this.transformHeader($targetHeader, config, "collapse")
		$targetContent.slideUp(config.animatespeed, function(){config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), isuseractivated)})
	},

	transformHeader:function($targetHeader, config, state){
		$targetHeader.addClass((state=="expand")? config.cssclass.expand : config.cssclass.collapse) //alternate btw "expand" and "collapse" CSS classes
		.removeClass((state=="expand")? config.cssclass.collapse : config.cssclass.expand)
		if (config.htmlsetting.location=='src'){ //Change header image (assuming header is an image)?
			$targetHeader=($targetHeader.is("img"))? $targetHeader : $targetHeader.find('img').eq(0) //Set target to either header itself, or first image within header
			$targetHeader.attr('src', (state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse) //change header image
		}
		else if (config.htmlsetting.location=="prefix") //if change "prefix" HTML, locate dynamically added ".accordprefix" span tag and change it
			$targetHeader.find('.accordprefix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
		else if (config.htmlsetting.location=="suffix")
			$targetHeader.find('.accordsuffix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
	},

	urlparamselect:function(headerclass){
		var result=window.location.search.match(new RegExp(headerclass+"=((\\d+)(,(\\d+))*)", "i")) //check for "?headerclass=2,3,4" in URL
		if (result!=null)
			result=RegExp.$1.split(',')
		return result //returns null, [index], or [index1,index2,etc], where index are the desired selected header indices
	},

	getCookie:function(Name){ 
		var re=new RegExp(Name+"=[^;]+", "i") //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
			return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	},

	setCookie:function(name, value){
		document.cookie = name + "=" + value + "; path=/"
	},

	init:function(config){
	document.write('<style type="text/css">\n')
	document.write('.'+config.contentclass+'{display: none}\n') //generate CSS to hide contents
	document.write('<\/style>')
	jQuery(document).ready(function($){
		ddaccordion.urlparamselect(config.headerclass)
		var persistedheaders=ddaccordion.getCookie(config.headerclass)
		ddaccordion.contentclassname[config.headerclass]=config.contentclass //remember contentclass name based on headerclass
		config.cssclass={collapse: config.toggleclass[0], expand: config.toggleclass[1]} //store expand and contract CSS classes as object properties
		config.revealtype=config.revealtype || "click"
		config.revealtype=config.revealtype.replace(/mouseover/i, "mouseenter")
		if (config.revealtype=="clickgo"){
			config.postreveal="gotourl" //remember added action
			config.revealtype="click" //overwrite revealtype to "click" keyword
		}
		if (typeof config.togglehtml=="undefined")
			config.htmlsetting={location: "none"}
		else
			config.htmlsetting={location: config.togglehtml[0], collapse: config.togglehtml[1], expand: config.togglehtml[2]} //store HTML settings as object properties
		config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
		config.onopenclose=(typeof config.onopenclose=="undefined")? function(){} : config.onopenclose //attach custom "onopenclose" event handler
		var lastexpanded={} //object to hold reference to last expanded header and content (jquery objects)
		var expandedindices=ddaccordion.urlparamselect(config.headerclass) || ((config.persiststate && persistedheaders!=null)? persistedheaders : config.defaultexpanded)
		if (typeof expandedindices=='string') //test for string value (exception is config.defaultexpanded, which is an array)
			expandedindices=expandedindices.replace(/c/ig, '').split(',') //transform string value to an array (ie: "c1,c2,c3" becomes [1,2,3]
		var $subcontents=$('.'+config["contentclass"])
		if (expandedindices.length==1 && expandedindices[0]=="-1") //check for expandedindices value of [-1], indicating persistence is on and no content expanded
			expandedindices=[]
		if (config["collapseprev"] && expandedindices.length>1) //only allow one content open?
			expandedindices=[expandedindices.pop()] //return last array element as an array (for sake of jQuery.inArray())
		if (config["onemustopen"] && expandedindices.length==0) //if at least one content should be open at all times and none are, open 1st header
			expandedindices=[0]
		$('.'+config["headerclass"]).each(function(index){ //loop through all headers
			if (/(prefix)|(suffix)/i.test(config.htmlsetting.location) && $(this).html()!=""){ //add a SPAN element to header depending on user setting and if header is a container tag
				$('<span class="accordprefix"></span>').prependTo(this)
				$('<span class="accordsuffix"></span>').appendTo(this)
			}
			$(this).attr('headerindex', index+'h') //store position of this header relative to its peers
			$subcontents.eq(index).attr('contentindex', index+'c') //store position of this content relative to its peers
			var $subcontent=$subcontents.eq(index)
			var needle=(typeof expandedindices[0]=="number")? index : index+'' //check for data type within expandedindices array- index should match that type
			if (jQuery.inArray(needle, expandedindices)!=-1){ //check for headers that should be expanded automatically (convert index to string first)
				if (config.animatedefault==false)
					$subcontent.show()
				ddaccordion.expandit($(this), $subcontent, config, false) //Last param sets 'isuseractivated' parameter
				lastexpanded={$header:$(this), $content:$subcontent}
			}  //end check
			else{
				$subcontent.hide()
				config.onopenclose($(this).get(0), parseInt($(this).attr('headerindex')), $subcontent.css('display'), false) //Last Boolean value sets 'isuseractivated' parameter
				ddaccordion.transformHeader($(this), config, "collapse")
			}
		})
		$('.'+config["headerclass"]).bind("evt_accordion", function(e, isdirectclick){ //assign custom event handler that expands/ contacts a header
				var $subcontent=$subcontents.eq(parseInt($(this).attr('headerindex'))) //get subcontent that should be expanded/collapsed
				if ($subcontent.css('display')=="none"){
					ddaccordion.expandit($(this), $subcontent, config, true, isdirectclick) //2nd last param sets 'isuseractivated' parameter
					if (config["collapseprev"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){ //collapse previous content?
						ddaccordion.collapseit(lastexpanded.$header, lastexpanded.$content, config, true) //Last Boolean value sets 'isuseractivated' parameter
					}
					lastexpanded={$header:$(this), $content:$subcontent}
				}
				else if (!config["onemustopen"] || config["onemustopen"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){
					ddaccordion.collapseit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
				}
 		})
		$('.'+config["headerclass"]).bind(config.revealtype, function(){
			if (config.revealtype=="mouseenter"){
				clearTimeout(config.revealdelay)
				var headerindex=parseInt($(this).attr("headerindex"))
				config.revealdelay=setTimeout(function(){ddaccordion.expandone(config["headerclass"], headerindex)}, config.mouseoverdelay || 0)
			}
			else{
				$(this).trigger("evt_accordion", [true])
				return false //cancel default click behavior
			}
		})
		$('.'+config["headerclass"]).bind("mouseleave", function(){
			clearTimeout(config.revealdelay)
		})
		config.oninit($('.'+config["headerclass"]).get(), expandedindices)
		$(window).bind('unload', function(){ //clean up and persist on page unload
			$('.'+config["headerclass"]).unbind()
			var expandedindices=[]
			$('.'+config["contentclass"]+":visible").each(function(index){ //get indices of expanded headers
				expandedindices.push($(this).attr('contentindex'))
			})
			if (config.persiststate==true && $('.'+config["headerclass"]).length>0){ //persist state?
				expandedindices=(expandedindices.length==0)? '-1c' : expandedindices //No contents expanded, indicate that with dummy '-1c' value?
				ddaccordion.setCookie(config.headerclass, expandedindices)
			}
		})
	})
	}
}

ddaccordion.init({
	headerclass: "submenuheader", //Shared CSS class name of headers group
	contentclass: "submenu", //Shared CSS class name of contents group
	revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
	mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
	collapseprev: true, //Collapse previous content (so only one open at any time)? true/false 
	defaultexpanded: [], //index of content(s) open by default [index1, index2, etc] [] denotes no content
	onemustopen: true, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: true, //Should contents open by default be animated into view?
	persiststate: true, //persist state of opened contents within browser session?
	toggleclass: ["", ""], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	togglehtml: ["suffix", "<img src='images/visuals/plus.gif' class='statusicon' />", "<img src='images/visuals/minus.gif' class='statusicon' />"], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
	oninit:function(headers, expandedindices){ //custom code to run when headers have initalized	
	},
	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
	}
})

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";
			}
		}
	}
}