var moveableObj = null;
var offsetX = 0;
var offsetY = 0;
var popupZIndex = 15;
var disabler;
var disablerZIndex = 5;
var enableMove = false;
var isModal = false;


// These Events are triggers onload
initEmail();

// Adds onblur event to verify valid email addresses
function initEmail()
{
	var email = document.getElementById("Email");
	
	if (email != null)
	{
		email.onblur = function()
		{
			if (this.value != "")
			{
				if (this.value.indexOf("@") == -1 || this.value.indexOf(".") == -1)
				{
					this.value = "";
				}
			}
		}
	}
}

function submitOnce(e)
{
  
	if(typeof(window.IsSubmited)=="undefined" )
	{
	     window.IsSubmited = true;
		 return true; // IE style
	}else{
	    //alert("Order processing in progress...");
		if (e && e.preventDefault)
				e.preventDefault(); // DOM style
		 return false; // IE style
	}
}

function toggleInputBoxVisibility() {

	//if (document.forms.name == "savePlanForm")
	//{
		//selectBox = getEl("PlanFolder");
		selectBox = document.forms['savePlanForm'].PlanFolder;
		newFolderDiv = getEl("newFolderContainer");		
				
		var index = selectBox.selectedIndex	;
		
		if ("0" == selectBox.options[index].value)
		{
			newFolderDiv.style.display = "block";
			//alert("block");
			//inputBox.style.visibility = "visible";
			//newFolderLabel.style.visibility = "visible";
		}
		else
		{
			newFolderDiv.style.display = "none";
			//alert("");
			//inputBox.style.visibility = "hidden";
			//newFolderLabel.style.visibility = "hidden";
		}
	//}
}

function toggleRows(tbl){

	var foundationCheck = getEl('foundationBit');
	
	if (foundationCheck != null)
	{
		if (foundationCheck.value == 'true')
		{
			var len = getEl(tbl).rows.length;
			var inputFirst = getEl("ImportantExtra-206");
			
			if(inputFirst)
			{
				var vStyle = (inputFirst.checked)? "none":"";
				var inputEls = getElsByName("ImportantExtra");
				
				if (vStyle == "none") {
					for (i=1; i < inputEls.length; i++)
					{
						inputEls[i].checked = false;
						inputEls[i].disabled = true;
					}
				}
				else if (vStyle == "") {
					for (i=1; i < inputEls.length; i++)
					{
						inputEls[i].disabled = false;
					}
				}

				for(i=2; i< len; i++) {
					getEl(tbl).rows[i].style.display = vStyle;		
				}
			}
		}
	}	
}


/* function togglePrevPaging(e)
{
	var prevSetItem = document.getElementsByTagName("li");
	
	for(i=0; i<prevSetItem.length; i++) {
		
		if(prevSetItem[i].className == '')
		{
		}
		else if(prevSetItem[i].className == "prevSetHide" && prevSetItem[i].className != "prevSetShow")
		{
			prevSetItem[i].className = 'prevSetShow';
		}
		else if(prevSetItem[i].className == "prevSetShow")
		{
			prevSetItem[i].className = 'prevSetHide';
		}
		else
		{
		}	
	}
} */

/* function toggleNextPaging(e)
{
	var nextSetItem = document.getElementsByTagName("li");
	
	for(i=0; i<nextSetItem.length; i++) {
		
		if(nextSetItem[i].className == '')
		{
		}
		else if(nextSetItem[i].className == "nextSetHide" && nextSetItem[i].className != "nextSetShow")
		{
			nextSetItem[i].className = 'nextSetShow';
		}
		else if(nextSetItem[i].className == "nextSetShow")
		{
			nextSetItem[i].className = 'nextSetHide';
		}
		else
		{
		}	
	}
} */


function SubmitForm()
{
	var theForm = document.forms['affiliateSignupForm'];
	if (!theForm.spam.checked)
	{
		alert('You must agree not to use the eplans affiliate program for the purpose of sending unsolicited email in order to sign up. If you agree to these terms, please check the box.');
		theForm.spam.focus();
		return false;
	}
	if (!theForm.agree.checked)
	{
		alert('You must confirm that you have read the affiliate agreement in order to sign up. If you agree to the terms of the agreement, please check the box.');
		theForm.agree.focus();
		return false;
	}
	theForm.submit();
}

function toggle_disclosure (e) {
  
  if (!e) {
    e = window.event;
  }
  
  var button = e.target;
  if (!button) {
    button = e.srcElement;
  }
  
  var suffix = button.id.split("_")[0];
  
  if (document.getElementById) {
    var group = getEl(suffix + "_group");
    var searchButtonTop = getEl("show-results-top");
    
    if (group.style.display == "block") {
      group.style.display = "none";
      var newButtonSrc = button.src.replace(/icon-\w+\.gif/, "icon-more.gif");
      button.src = newButtonSrc;
      isSearchFormExpanded = false;
      if (null != searchButtonTop) {
		searchButtonTop.style.display = "none";
	  }
    }
    else {
      group.style.display = "block";
      var newButtonSrc = button.src.replace(/icon-\w+\.gif/, "icon-fewer.gif");
      button.src = newButtonSrc;
      isSearchFormExpanded = true;
      if (null != searchButtonTop) {
		searchButtonTop.style.display = "inline";
	  }
    }
    
  }
}


function flipImages() { 

 var imgs = document.getElementsByTagName("img")

for (var i=0; i<imgs.length; i++) {
  if  (imgs[i].className == 'flipp')  {
    if (imgs[i].filters) {
		if (!imgs[i].filters.fliph)
		imgs[i].style.filter += ' fliph()';
		else
		imgs[i].filters.fliph.enabled = !imgs[i].filters.fliph.enabled;
	}

}
}
	
}

function flipffox(){

	var imgs = document.getElementsByTagName("img");
	if (imgs.length > 0){
    if (imgs[0].filters) {
	return true;
}
}
	return false;
}


function clearSearch_click()
{
	var formControl = getEl("PlanSearchForm");
	var formLen = formControl.length;
	var i;
	for(i = 0; i < formLen; i++)
	{
		var currCntrl = formControl[i];
        if (currCntrl.type == "select-one" && currCntrl.selectedIndex != 0)
		{
			currCntrl.selectedIndex = 0;
			selectPlanType(null);
		}
		else if(currCntrl.id == "MinSqft" || currCntrl.id == "MinWidth" || currCntrl.id == "MinDepth")
		{
			currCntrl.value = "Min";
		}
		else if(currCntrl.id == "MaxSqft" || currCntrl.id == "MaxWidth" || currCntrl.id == "MaxDepth")
		{
			currCntrl.value = "Max";
		}
		else if(currCntrl.type == "checkbox")
		{
			currCntrl.checked = false;
		}
		else if(currCntrl.type == "radio")
		{
			currCntrl.checked = false;
		}		
	}
	ResetCostToBuildType();
}
function ResetCostToBuildType()
{
    $("#CostToBuildType").attr('checked','checked');
    $("#SelectMinCostToBuild").val('00');
    $("#SelectMaxCostToBuild").val('10000000');
    $("#SelectMinCostToBuild" ).removeAttr('disabled'); 
    $("#SelectMaxCostToBuild" ).removeAttr('disabled');
    $("#MinCostToBuild").attr('value','enter Min');
    $("#MaxCostToBuild").attr('value','enter Max');
    $("#MinCostToBuild").attr('disabled', 'disabled');
    $("#MaxCostToBuild").attr('disabled', 'disabled');		    
			 
	return false;	 
}

function toggleClass(element) {
	element.className = (element.className == "active") ? "" : "active";
}

function resizeIframe() {
	if (parent == window) return false;
	var ifrmWin = parent.frames["featuredPlan"];
	if (ifrmWin) {
		var ifrm;
		if (parent.window.document.getElementById) {
			ifrm = parent.window.document.getElementById("featuredPlan");
		}
		else {
			if (parent.window.document.all) {
				ifrm = parent.window.document.all["featuredPlan"];
			}
		}
		if (ifrm) {
			ifrm.style.height = "auto"; 
			ifrm.style.height = getHeight() + "px";
		}
	}
}

function resizeIframeDialog() {
	if (parent == window) {return false};
	
	var ifrm;
	
	if (parent.window.document.getElementById) {
		ifrm = parent.window.document.getElementById("dialogWin");
	}
	else if (parent.window.document.all) {
			ifrm = parent.window.document.all["dialogWin"];
	}
	
	if (parent && parent.setDialogTitle) {
		parent.setDialogTitle(document.title);
	}
	
	//The below script was overriding the dimensions set in showdialog	
	/*
	if (ifrm) {
		ifrm.style.height = "auto"; 
		ifrm.style.height = getHeight() + "px";
		ifrm.style.width = "auto";
		ifrm.style.width = getWidth() + "px";
		
	}*/

}

function getHeight() {
	var height = 0;
	if (document.height) {
		height = document.height;
	}
	else {
		if (document.body) {
			var sh = (document.body.scrollHeight) ? document.body.scrollHeight : 0;
			var oh = (document.body.offsetHeight) ? document.body.offsetHeight : 0;
			height = (sh > oh) ? sh : oh;
		}
	}
	return height;
}

function getWidth() {
	var width = 0;
	if (document.width) {
		width = document.width;
	}
	else {
		if (document.body) {
			var sh = (document.body.scrollWidth) ? document.body.scrollWidth : 0;
			var oh = (document.body.offsetWidth) ? document.body.offsetWidth : 0;
			width = (sh > oh) ? sh : oh;
		}
	}
	return width;
}

function toggleCostToBuild() {
	var elem = document.getElementById ("costToBuild");
	if (elem) {
		if (elem.style.display == "block") {
			elem.style.display = "none";
		}
		else {
			elem.style.display = "block";
		}		
	}
}

	
function showDialog(url)
{
	var dialog = document.getElementById ("dialog");	
	moveableObj = dialog;
	var w = 330;
	var h = 400;
	
	if (url.indexOf('newsletter') != -1) {
		w = 300;
		h = popUpHeight;
	}
	if (url.indexOf('thankyou') != -1) {
		w = 300;
		h = 200;
	}
	if (url.indexOf('login-dialog') != -1) {
		w = 568;
		h = 320;
	}
	if (url.indexOf('HelpLarge') != -1) {
		w = 500;
		h = 500;
	}
	else if (url.indexOf('help') != -1) {
		w = 300;
		h = 300;
	}

	var eplansIframe = parent.frames["eplans"];
	
	if(eplansIframe)
	{	
		positionFromLeftEdge(dialog, w, h)
	}
	else if(w > 300)
	{
		positionFromBottomLeftCenterWell(dialog, w, h);
	}
	else
	{
		positionCenter(dialog);
	}
	
	setDialogTitle("Loading...")
	
	dialog.style.display = "block";
	dialog.style.width = w + 'px';
	
	var ifrm;

	if (document.getElementById) {
		ifrm = document.getElementById("dialogWin");
	}
	else if (document.all) {
		ifrm = document.all["dialogWin"];
	}
	
	if (ifrm)
	{
		ifrm.src = url;	
		ifrm.style.height = h + 'px';
		ifrm.style.width = w + 'px';
	}
	
	if (!isModal) {negotiateSelects(moveableObj, true, false)};
}


function hideDialog()
{
	var ifrmWin = window.frames["dialogWin"];
	
	var dialog = getEl ("dialog");
	hideDialogEl(dialog);
}

function hideDialogEl(dialog)
{
	if (!dialog) {
		alert("No dialog");
		return;
	}
	
	var dialogBody = document.getElementById("dialogBody");
	
	dialog.style.display = "none";
	
	moveableObj = dialog;
	
	if (!isModal) negotiateSelects(moveableObj, true, false);
}

function hideParentDialog()
{
	var dialog = getParentEl("dialog");
	hideDialogEl(dialog);	
}


function setDialogTitle(title)
{
	var dlgTitle;	
	
	if (document.getElementById) {
		dlgTitle = top.document.getElementById("dialogTitle");
	}
	else if (document.all) {
		dlgTitle = document.all["dialogTitle"];
	}
	
	if (dlgTitle)
	{
		dlgTitle.innerHTML = title;
	}
}

function positionFromLeftEdge(el, width, height)
{
	var eplansIframe = parent.document.getElementById("eplans");
	var centerWell = document.getElementById("centerwell");
	var parentScrollTopPx = getParentScrollTop();
	var topPx = 0;
	
	el.style.left = (centerWell.offsetLeft + getScrollLeft()) + 'px';
		
	if(parentScrollTopPx <= eplansIframe.offsetTop)
	{
		topPx = eplansIframe.offsetTop + 10;
	}
	else if((parentScrollTopPx + height) > (eplansIframe.offsetTop + eplansIframe.clientHeight))
	{
		topPx = eplansIframe.clientHeight - height - 80;
	}
	else
	{
		topPx = parentScrollTopPx - 80;		
	}

	el.style.top = topPx + 'px';
}

function positionFromBottomLeftCenterWell(el, width, height)
{
	var centerWidth = 0;
	var leftWidth = 0;
	
	var centerWell = document.getElementById("centerwell");
	var leftWell = document.getElementById("leftwell");
	
	if (leftWell) 
	{
		leftWidth = leftWell.offsetWidth;
	}
	
	if (centerWell) 
	{
		centerWidth = centerWell.offsetWidth;
	}
	

	var relWidth = centerWidth + leftWidth;
	
	el.style.left = (relWidth - width - 20 + getScrollLeft()) + 'px';
	el.style.top = (getScreenHeight() - height - 60 + getScrollTop()) + 'px';
}

function positionCenter(el) {
	el.style.top = (getScrollTop() + 100) + 'px';
	el.style.left = ((screen.availWidth / 3.5) + getScrollLeft()) + 'px';
}

function getScrollTop() {
	if (document.documentElement && document.documentElement.scrollTop)
	{
		return document.documentElement.scrollTop;
	}
	else if (document.body)
	{
		return document.body.scrollTop;
	}
	else if (window.pageYOffset)
	{
		return window.pageYOffset;
	}
}

function getParentScrollTop()
{
	if (parent.document.documentElement && parent.document.documentElement.scrollTop)
	{
		return parent.document.documentElement.scrollTop;
	}
	else if (parent.document.body)
	{
		return parent.document.body.scrollTop;
	}
	else if (parent.window.pageYOffset)
	{
		return parent.window.pageYOffset;
	}
}

function getScrollLeft() {
	if (document.documentElement && document.documentElement.scrollLeft)
		return document.documentElement.scrollLeft;
	else if (document.body)
		return document.body.scrollLeft;
	else if (window.pageXOffset)
		return window.pageXOffset;
}


function getScreenWidth() {
	if (document.documentElement && document.documentElement.clientWidth)
		return document.documentElement.clientWidth;
	else if (document.body)
		return document.body.clientWidth;
}


function getScreenHeight() {
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	else if (document.body)
		return document.body.clientHeight;
}


function getOffsetWidth(el) {
	if (el)
	var width = el.offsetWidth;
	return width;
	
}


function getOffsetHeight(el) {
	if (el)
	var height = el.offsetHeight;
	return height;
}

function getOffsetLeft(el) {
	var left = 0;
	var curEl = el;
	while (curEl != null) {
		left += curEl.offsetLeft;
		curEl = curEl.offsetParent;
	}
	return left;
}


function getOffsetTop(el) {
	var top = 0;
	var curEl = el;
	while (curEl != null) {
		top += curEl.offsetTop;
		curEl = curEl.offsetParent;
	}
	return top;
}


function getOffsetX(el)
{
	if (el.offsetX) return el.offsetX;
	if (el.layerX) return el.layerX;
	return 0;
}


function getOffsetY(el)
{
	if (el.offsetY) return el.offsetY;
	if (el.layerY) return el.layerY;
	return 0;
}


function getParentElement(el)
{
	if (el && el.parentNode) return el.parentNode;
	if (el && el.parentElement) return el.parentElement;
	return null;
}

function getFormElements(el)
{
	if (typeof(el.form) != "undefined") 
	{ 
		return el.form.elements;
	}
	else 
	{
		if(document.forms[0] != undefined)
		{
			return document.forms[0].elements;
		}
		else
		{
			return null;
		}
	}
}

function getEl(id) {
	var obj;
	if (document.getElementById) {
		obj = document.getElementById(id);
	} else if (document.all) {
		obj = eval("document.all." + id);
	} 
	return obj;
}

function getElsByName(name) {
	var obj;
	if (document.getElementsByName) {
		obj = document.getElementsByName(name);
	}
	return obj;
}

function getParentEl(id)
{
	var element;
	if (parent.window.document.getElementById) 
	{
		element = parent.window.document.getElementById(id);
	}
	else 
	{
		if (parent.window.document.all) 
		{
			element = parent.window.document.all[id];
		}
	}
	return element;
}

function getRadioVal(name) {
	var els = getElsByName(name);
	if (els) {
		for (var i=0; i<els.length; i++) {
			if (els[i] && els[i].checked) {
				return els[i].value;
			}
		}
	}
	return null;
}

function hasNumericValue(el) {
	return (el && el.value != '' && !isNaN(el.value));
}

function getFloatValue(el, defaultVal) {
	if (el && hasNumericValue(el)) {
		return parseFloat(el.value);
	}
	else {
		return parseFloat(defaultVal);
	}
}

function getCurrencyValue(el) {
	return parseFloat(getFloatValue(el, 0.00).toFixed(2));
}

function getCurrencyDisplay(el) {
	return formatCurrency(getCurrencyValue(el));
}

function formatCurrency(val) {
	var formattedVal = val.toString();
	if (formattedVal.indexOf('.') < 0) formattedVal += '.00';
	return '$' + formatComma(formattedVal);
}

function formatComma(val) {
	var vals = val.toString().split('.', 2);
	var wholePart = vals[0];
	var decimalPart = vals[1];
	if (typeof(decimalPart) != 'undefined' && decimalPart != '') {
		if (wholePart.length > 3) {
			return formatComma(wholePart.substring(0, wholePart.length - 3)) + ',' + wholePart.substring(wholePart.length - 3) + '.' + decimalPart;
		}
		else {
			return wholePart + '.' + decimalPart;
		}
	}
	else {
		if (wholePart.length > 3) {
			return formatComma(wholePart.substring(0, wholePart.length - 3)) + ',' + wholePart.substring(wholePart.length - 3);
		}
		else {
			return wholePart;
		}
	}
}



var bLoaded = true;

function downDialog(e) {
	if (!e) {
		e = event;
	}
	enableMove = true;
	offsetX = getOffsetX(e);
	offsetY = getOffsetY(e);
	
	var tg = (e.target) ? e.target : e.srcElement;

	moveableObj = selectDialog(tg);
	return false;
}


function selectDialog(el) {
	if (el && el.onmousedown == downDialog) return el;
	else if (el) return (selectDialog(getParentElement(el)));
	return moveableObj;
}


function upDialog(e) {
	if (!e) {
		e = event;
	}
	enableMove = false;
	return false;
}


function moveDialog(e) {
	if (!e) {
	 e = event;
	}
	if (enableMove && moveableObj) {
		moveableObj.style.top = e.clientY + getScrollTop() - offsetY + 'px';
		moveableObj.style.left = e.clientX + getScrollLeft() - offsetX + 'px';
		if (!isModal) negotiateSelects(moveableObj, true, false);
	}
	return false;
}

function negotiateSelects(topEl, activate, keepHidden) {
	negotiateElements('select', topEl, activate, keepHidden);
}


function negotiateElements(tagName, topEl, activate, keepHidden) {
	var allEls = document.getElementsByTagName(tagName);
	for (var i=0; i<allEls.length; i++) {
		if (activate) {
			if (topEl != allEls[i]) {
				if (checkOverlap(topEl, allEls[i])) {
					hideEl(allEls[i]);
				}
				else {
					if (!keepHidden) showEl(allEls[i]);
				}
			}
		}
		else {
			showEl(allEls[i]);
		}
	}
}


function checkOverlap(topEl, bottomEl) {
	var dims1 = getDimensions(topEl);
	var dims2 = getDimensions(bottomEl);
	if (overlap(dims1, dims2)) {
		return true;
	}
	else {
		return false;
	}
}


function getDimensions(el) {
	var points = new Array();	
	points[0] = getOffsetLeft(el);					//left
	points[1] = points[0] + getOffsetWidth(el);		//right
	points[2] = getOffsetTop(el);					//top
	points[3] = points[2] + getOffsetHeight(el);	//bottom
	return points;
}


function overlap(dims1, dims2) {
	if (((dims1[0] > dims2[0] && 
		  dims1[1] > dims2[0] && 
		  dims1[0] > dims2[1] && 
		  dims1[1] > dims2[1]) ||
		 (dims1[0] < dims2[0] && 
		  dims1[1] < dims2[0] && 
		  dims1[0] < dims2[1] && 
		  dims1[1] < dims2[1])) ||
	    ((dims1[2] > dims2[2] &&
		  dims1[3] > dims2[2] &&
		  dims1[2] > dims2[3] &&
		  dims1[3] > dims2[3]) ||
		 (dims1[2] < dims2[2] &&
		  dims1[3] < dims2[2] &&
		  dims1[2] < dims2[3] &&
		  dims1[3] < dims2[3]))) {
			return false;	
	}
	else {
		return true;
	}
}


function showEl(obj) {
	if ((obj == null) || (!bLoaded)) return;
	if (document.getElementById) {
		obj.style.visibility = "visible";
	} else if (document.all) {
		obj.style.visibility = "visible";
	} 
}


function hideEl(obj) {
	if ((obj == null) || (!bLoaded)) return;
	if (document.getElementById) {
		obj.style.visibility = "hidden";
	} else if (document.all) {
		obj.style.visibility = "hidden";
	} 
}


function refreshParent() {
	if (parent == window) {return false;}
		
	parent.location = parent.location;
}

function setParentUrl(url) {
	if (parent == window) {return false;}
		
	parent.location = url;
}

// ESCAPE dismisses dialog
function handleHotKey(e) {
	if (!e) {e = event;}
	
	var key = (e.keyCode) ? e.keyCode : e.which;
	
	if (key == 27) { 
		hideDialog();
	}
}

function selectPlanType(e) 
{
	var elem;
	var elemName;
	var elemType;
	var elemValue;
	var elemLabel;
 
	if (!top.document.PlanSearchForm) { return; }

	var formElements = top.document.PlanSearchForm.elements;	
  var selectBox = top.document.PlanSearchForm.PlanType;

 	if (null == formElements || null == selectBox)
	{
		alert("no form");
		return;
	}  

	var index = selectBox.selectedIndex;

	for (var i = 0; i < formElements.length; i++) 
	{
		formElements[i].disabled = false;
		
		if (("Amenities" == formElements[i].name || "Styles" == formElements[i].name)) 
		{
			formElements[i].parentNode.parentNode.style.display = "block";
		}
	}
	
	var group;
	var button;
	
	if (document.getElementById) 
	{
		group = document.getElementById ("search_group");
		button = document.getElementById ("search_button");				
	}
	
	if ("House" == selectBox.options[index].value) 
	{		
		for (var i = 0; i < formElements.length; i++) 
		{
			elem = formElements[i];
			elemName = formElements[i].name;
			elemType = formElements[i].type;
			
			elem.disabled = false;
		}
		
		if (button)
		{
			var newButtonSrc = button.src.replace(/icon-\w+\.gif/, "icon-more.gif");
			button.src = newButtonSrc;
			button.style.cursor = "pointer"
			
			if (isSearchFormExpanded == true) 
			{
				if (group.style.display == "block") 
				{
					group.style.display = "none";
					var newButtonSrc = button.src.replace(/icon-\w+\.gif/, "icon-more.gif");
					button.src = newButtonSrc;
				}
				else 
				{
					group.style.display = "block";
					var newButtonSrc = button.src.replace(/icon-\w+\.gif/, "icon-more.gif");
					button.src = newButtonSrc;
				}
			}
		}
	}
	
	else if ("Garage" == selectBox.options[index].value) 
	{
		for (var i = 0; i < formElements.length; i++) 
		{
			elem = formElements[i];
			elemName = formElements[i].name;
			elemType = formElements[i].type;
			elemValue = formElements[i].value;
			
			if ("select-one" == elemType || "button" == elemType || "submit" == elemType) 
			{
				continue;
			}
			
			if ("Amenities" == elemName || "Styles" == elemName) 
			{
					elem.disabled = true;
			}
		}
		
		if (button)
		{
			if(group)
				group.style.display = "none";
			
			var newButtonSrc = button.src.replace(/icon-\w+\.gif/, "icon-blank.gif");
			button.src = newButtonSrc;
			button.style.cursor = "none";
			button.style.cursor = "auto";	
		}		
	}	
	
	else if ("Project" == selectBox[index].value) 
	{
		for (var i = 0; i < formElements.length; i++) 
		{
			var elem = formElements[i];
			var elemName = formElements[i].name;
			var elemType = formElements[i].type;
			var elemValue = formElements[i].value;

			if ("select-one" == elemType || "button" == elemType || "submit" == elemType) 
			{
				continue;
			}

			if ("Styles,Amenities,Bedrooms,Bathrooms,Stories,GarageBays".indexOf(elemName) != -1) 
			{
				elem.disabled = true;
			}
		}
		
		if (button)
		{
			if(group)
				group.style.display = "none";
			var newButtonSrc = button.src.replace(/icon-\w+\.gif/, "icon-blank.gif");
			button.src = newButtonSrc;
			button.style.cursor = "none";
			button.style.cursor = "auto";
		}
	}
	
	else if ("Landscapes" == selectBox[index].value) 
	{
		for (var i = 0; i < formElements.length; i++) 
		{
			var elem = formElements[i];
			var elemName = formElements[i].name;
			var elemType = formElements[i].type;
			var elemValue = formElements[i].value;

			if ("button" == elemType || "submit" == elemType) 
			{
				continue;
			}

			if ("MinSqft,MaxSqft,Styles,Amenities,Bedrooms,Bathrooms,Stories,GarageBays,minAvgCostToBuild,maxAvgCostToBuild,AdditionalUseid".indexOf(elemName) != -1) 
			{
				elem.disabled = true;
			}
			
			if ("Amenities" == elemName || "Styles" == elemName) 
			{
					elem.parentNode.parentNode.style.display = "none";
			}
		}
	}
	
	else if ("Deck" == selectBox[index].value) 
	{
		for (var i = 0; i < formElements.length; i++) 
		{
			var elem = formElements[i];
			var elemName = formElements[i].name;
			var elemType = formElements[i].type;
			var elemValue = formElements[i].value;

			if ("button" == elemType || "submit" == elemType) {
				continue;
			}

			if ("MinSqft,MaxSqft,Amenities,Bedrooms,Bathrooms,Stories,GarageBays,minAvgCostToBuild,maxAvgCostToBuild,AdditionalUseid".indexOf(elemName) != -1) 
			{
				elem.disabled = true;
			}
			
			if ("Amenities" == elemName || "Styles" == elemName) 
			{
					elem.parentNode.parentNode.style.display = "none";
			}
		}
	}
	
	else 
	{
		for (var i = 0; i < formElements.length; i++) 
		{
			var elem = formElements[i];
			var elemType = formElements[i].type;
			
			if ("select-one" == elemType || "button" == elemType || "submit" == elemType) 
			{
				continue;
			}
		}
	}
}


function validateAddToCart() {
	var message = '';
	var planProduct		= getRadioVal('PlanProduct');
	var foundationType	= getRadioVal('DesignOption');
	var zipCode			= getEl('zipCode');
	var foundationCheck = getEl('foundationBit');
	
	if (planProduct == null) {
		message += 'You must make a plan selection.\n';
	}
	
	if (foundationCheck != null)
	{
		if (foundationCheck.value == 'true')
		{
			if (foundationType == null) 
			{
				message += 'You must select a foundation type.\n';
			}
		}
	}	
	
	if (zipCode.value == '') 
	{
		message += 'You must enter a ZIP code.';
	}
	
	if (message != '') 
	{
		alert(message);
		return false;
	}
	
	return true;
}


function updateTotals() 
{
	var elSubtotalDisplay			= getEl('Subtotal-Display');
	var elSubtotal					= getEl('Subtotal');
	var elSubtotalRebateDisplay		= getEl('Subtotal-Rebate-Display');
	var elSubtotalRebate			= getEl('Subtotal-Rebate');
	var elPlanProducts				= getElsByName('PlanProduct');
	var elPlanOptions				= getElsByName('PlanOption');
	var elExtras					= getElsByName('ImportantExtra');
	var subtotal					= 0.00;
	var rebate						= 0.00;
	
	subtotal += getTotals(elPlanProducts, 'PlanProduct-', '-Value');
	subtotal += getTotals(elPlanOptions, 'PlanOption-', '-Value');
	subtotal += getTotals(elExtras, 'ImportantExtra-', '-Value');

	try 
	{
		if (null == indyMacRebate) 
		{
			indyMacRebate = 0;
		}
	}
	catch (e) 
	{
		indyMacRebate = 0;
	}
	
	
	rebate = subtotal - indyMacRebate;
	
	if (rebate < 0)
	{
		rebate = 0;
	}

	subtotal = subtotal.toFixed(2);
	rebate = rebate.toFixed(2);
	
	if (elSubtotalDisplay) 
	{
		elSubtotalDisplay.innerHTML = formatCurrency(subtotal);
	}
	
	if (elSubtotal) 
	{
		elSubtotal.value = subtotal;
	}
	
	if (elSubtotalRebateDisplay) 
	{
		elSubtotalRebateDisplay.innerHTML = formatCurrency(rebate);
	}
	
	if (elSubtotalRebate) 
	{
		elSubtotalRebate.value = rebate;
	}
}


function getTotals(els, idPrefix, idSuffix) {
	var total = 0;
	if (els) {
		var el;
		var elQty;
		for (var i=0; i<els.length; i++) {
			if (els[i].checked) {
				el = getEl(idPrefix + els[i].value + idSuffix);
				if (hasNumericValue(el)) {
					var elQty = getEl(idPrefix + els[i].value + '-Quantity');
					if (hasNumericValue(elQty) 
						&& ((idPrefix + els[i].value + '-Quantity') != 'PlanOption-157-Quantity') 
						&& ((idPrefix + els[i].value + '-Quantity') != 'PlanOption-164-Quantity') 
						&& ((idPrefix + els[i].value + '-Quantity') != 'PlanOption-174-Quantity')) {	//HACK: Ignore Mirror Reverse
						total += getCurrencyValue(el) * getCurrencyValue(elQty, 1);
					}
					else {
						total += getCurrencyValue(el);
					}
				}
			}
		}
	}
	return parseFloat(total);
}

function updateShipping() {
	var elShippingDisplay	= getEl('Shipping-Display');
	var elShipping			= getEl('Shipping');
	var shippingMethod		= getRadioVal('ShippingMethod');
	var elShippingPrice		= getEl('ShippingMethod-' + shippingMethod);
	var shippingPrice		= getCurrencyValue(elShippingPrice, 0.00);
	
	if (elShippingDisplay) {
		elShippingDisplay.innerHTML = formatCurrency(shippingPrice);
	}
	if (elShipping) {
		elShipping.value = shippingPrice;
	}
	
	updateOrderTotals();	
}

function updateOrderTotals() {
	var elTotalDisplay			= getEl('Total-Display');
	var elTotal					= getEl('Total');
	var elTotalRebateDisplay	= getEl('Total-Rebate-Display');
	var elTotalRebate			= getEl('Total-Rebate');
	
	var elSubtotal				= getEl('Subtotal');
	var elSubtotalRebate		= getEl('Subtotal-Rebate');
	
	var elDiscount				= getEl('Discount');
	var elShipping				= getEl('Shipping');
	var elTax					= getEl('Tax');
	
	var total					= 0.00;
	var totalRebate				= 0.00;
	
	var subtotal				= getCurrencyValue(elSubtotal, 0.00);
	var subtotalRebate			= getCurrencyValue(elSubtotalRebate, 0.00);
	
	var discount				= getCurrencyValue(elDiscount, 0.00);
	var shipping				= getCurrencyValue(elShipping, 0.00);
	var tax						= getCurrencyValue(elTax, 0.00);
	
	total = subtotal - discount + shipping + tax;
	totalRebate = subtotalRebate - discount + shipping + tax;
	
	total = total.toFixed(2);
	totalRebate = totalRebate.toFixed(2);
	
	if (elTotalDisplay) {
		elTotalDisplay.innerHTML = formatCurrency(total);
	}
	if (elTotal) {
		elTotal.value = total;
	}
	if (elTotalRebateDisplay) {
		elTotalRebateDisplay.innerHTML = formatCurrency(totalRebate);
	}
	if (elTotalRebate) {
		elTotalRebate.value = totalRebate;
	}
}

function PlanFolder_change() {
//PlanFolder is the PlanFolder dropdown on the save-plan-dialog-form.xml XForm.
	folderDropDown = getEl("PlanFolder");
	createFolderTxtBox = getEl("NewPlanFolderName");

	if(folderDropDown.value == "0")
	{
		//Value of "0" means that 'Create New folder' was selected from the dropdown,
		//so we need to allow the user to enter a new folder's name. 
		createFolderTxtBox.disabled = false;
	}
	else
	{
		//User has selected an existing folder, so we don't new to show the 'New folder name' textbox.
		createFolderTxtBox.disabled = true;
	}
}

function newsletterSignup_onSubmit()
{
	var emailBox = getEl('email');
	var hdnEmailBox = getEl('hdnEmail');
	var hdnEmail = hdnEmailBox.value;
	var EmailAddress=emailBox.value;
	
	var EmailPattern = /^[A-Za-z0-9 @_.-]*$/;
	if(emailBox && emailBox.value == '')
	{
		alert("Please enter an email address");
		return false;
	}
	else if(!EmailPattern.test(EmailAddress))
	{
		alert("Please enter a valid email address");
		return false;
	}
	else if(!/^[^@]+@{1}[^@]+\.{1}[^@.]+$/.test(EmailAddress))
	{
		alert("Please enter a valid email address to receive our Featured House Plan of the Week.");
		return false;
	}
	else if ( hdnEmailBox && hdnEmail != "" && hdnEmail != EmailAddress )
	{
		alert("Entered email address not matching with Your registered email address. Please re-enter.");
		return false;
	}
	
}
function loginsignup_onSubmit()
{
	var emailBox = getEl('username');
	var pwdBox = getEl('password');
	var EmailAddress=emailBox.value;
	var EmailPattern = /^[A-Za-z0-9 @_.-]*$/;
	if(emailBox && emailBox.value == '')
	{
		alert("Please enter username");
		return false;
	}
	else if(!EmailPattern.test(EmailAddress))
	{
		alert("Please enter a valid email address");
		return false;
	}
	else if(!/^[^@]+@{1}[^@]+\.{1}[^@.]+$/.test(EmailAddress))
	{
		alert("Please enter a valid email address to receive our Featured House Plan of the Week.");
		return false;
	}
	//else
	//{
	//	top.setTimeout('top.hideDialog()', 1000);
	//	return true;
	//}
	if(pwdBox && pwdBox.value == '')
	{
		alert("Please enter password");
		return false;
	}
	//else
	//{
	//	top.setTimeout('top.hideDialog()', 1000);
	//	return true;
	//}
	
	
}
//comparePlansFormSubmit() function checks to make sure at least 2 plans have been selected to compare
//before displaying submitting and displaying the comparePlans page (it doesn't make sense to compare plans
//when only one plan has been selected to compare).
function comparePlansFormSubmit()
{
	var planCheckboxes = getElsByName("Alias");
	var numberChecked = 0;
	
	for(i = 0; i < planCheckboxes.length; i++)
	{
		if(planCheckboxes[i].checked == true)
		{
			numberChecked++;
		}
	}
	
	if(numberChecked > 1)
	{
		return true;
	}
	else
	{
		alert("Please check the checkbox for at least 2 plans before clicking 'Compare'.");
		return false;
	}
}


// -- Added by LSI For US581--//
//var addressForm = getEl("checkoutPaymentForm");
//if(addressForm!=null)
//{
//	$(document).ready(OnAddressingAndPaymentDocumentReady);
//}
//function OnAddressingAndPaymentDocumentReady()
//{
//	var control=$("#ShipToStateProvince");
//	if(control != null || control!='')
//	{
//		$("#ShipToStateProvince").change(function(event)
//			{
//				GetShippingMethods();
//			});
//	}
//}



//var shoppingcartId=1;
//function GetShippingMethods()
//{
//		
//		var st="";
//		var anum=/(^[0-9a-zA-Z,]+$)/;
//		var elems = document.getElementById("checkoutPaymentForm").elements;
//		
//		
//		var SCartID=getEl("ShoppingCartID");
//		
//		for(var e=0;e< elems.length;e++)
//		{
//			if(elems[e].name!="" && elems[e].name!="undefined")
//			{
//				if(elems[e].id.indexOf('BillTo', 0) == 0 || elems[e].id.indexOf('ShipTo', 0) == 0)
//				{
//					if(elems[e].type=="select-one")
//					{
//						if(st!=""){st+="&"}
//							st += elems[e].name + "=" + elems[e].options[elems[e].selectedIndex].value;
//					}
//					else
//					{
//						if(st!=""){st+="&"}
//							st += elems[e].name + "=" + elems[e].value;
//					}
//				}
//			}
//		}
//		if(SCartID.value !='')
//		{
//			shoppingcartId=SCartID.value;
//			st=st+'&CartID='+SCartID.value;
//		}
//		else
//		{
//			st=st+'&CartID='+shoppingcartId;
//		}
//		//alert(SiteRoot);
//		SiteRoot=SiteRoot.replace('http://','https://');
//		//alert(SiteRoot);
//		var dhsUrl = SiteRoot + "ajax/get-shipping-methods.hwx";
//		$.post(dhsUrl, st,
//							function(data)
//							{
//								document.getElementById('shipping-method-div').innerHTML = data;
//								// on shipto state change : Tax calculated values updated at cart subtotal area
//								document.getElementById("Subtotal-Display").innerHTML = '$' + document.getElementById("Subtotal").value;
//								//Shipping value will return empty when shiping methods changed or not selected or free
//								if(document.getElementById("Shipping").value =="")
//								{
//								    document.getElementById("Shipping-Display").innerHTML = '$0.00'
//								}
//								else
//								{
//								    document.getElementById("Shipping-Display").innerHTML = '$' + document.getElementById("Shipping").value;
//								}
//								document.getElementById("Tax-Display").innerHTML = '$' + document.getElementById("Tax").value;
//								document.getElementById("Total-Display").innerHTML = '$' + document.getElementById("Total").value;
//							}
//			);
//}
//----  --//
//function sameAsBillingClick(e)
//{
//	if(!getEl("SameAsBilling").checked)
//	{
//		var addressForm = getEl("checkoutPaymentForm");
//		var formLen = addressForm.length;
//		var currEl;
//		var currShipToElId;
//		var currShipToEl;
//		var i;

//		for(i = 0; i < formLen; i++)
//		{
//			currEl = addressForm[i];
//			if(currEl.id.indexOf('BillTo', 0) == 0)
//			{
//				currShipToElId = currEl.id.replace(/BillTo/, 'ShipTo');
//				currShipToEl = getEl(currShipToElId);	
//				currShipToEl.value = '';
//			} 
//		}
//	}
//	else
//	{
//		var addressForm = getEl("checkoutPaymentForm");
//		var formLen = addressForm.length;
//		var currEl;
//		var currShipToElId;
//		var currShipToEl;
//		var i;
//		
//		for(i = 0; i < formLen; i++)
//		{
//			currEl = addressForm[i];
//			if(currEl.id.indexOf('BillTo', 0) == 0)
//			{
//				currShipToElId = currEl.id.replace(/BillTo/, 'ShipTo');
//				currShipToEl = getEl(currShipToElId);	
//				currShipToEl.value = currEl.value;
//			} 
//		}
//		GetShippingMethods();
//	}	
//}

function phoneKeyUpMask(e)
{
	if (!e) {
		e = event;
	}

	var control = (e.target) ? e.target : e.srcElement;

	var delimLocs = new Array('3', '7');
	var delim = '-';
	var i;
	var j;
	var currVal = control.value;
	
	for(i = 0; i < delimLocs.length; i++)
	{
		for(j=0; j <currVal.length; j++)
		{
			if(j == delimLocs[i])
			{
				if(currVal.substring(j, j+1) != delim)
				{
					currVal = currVal.substring(0, j) + delim + currVal.substring(j, currVal.length);
				}
			}
		}
	}
	
	control.value = currVal;
}

function checkoutAgreementSubmitClick()
{
	var agreementBox = getEl("AcceptsAgreement");
	
	if(!agreementBox.checked)
	{
		alert("You must check the box to accept the terms and conditions to proceed.");
		return false;
	}
	else
	{
		return true;
	}
}
//function ValidatePaymentSubmitClick()
//{
//	var crdNum=getEl("CardNumber");
//	var cardnumber=crdNum.value;
//	var verifNum=getEl("VerificationNumber");
//	var verificationnumber=verifNum.value;
//	var regExp = /\s+/g;
//	cardnumber=cardnumber.replace(regExp,'');
//	crdNum.value=cardnumber.replace(/-/g,'');
//	verificationnumber=verificationnumber.replace(regExp,'');
//	verifNum.value=verificationnumber.replace(/-/g,'');
//	var agreementBox = getEl("rdTermsAndConditions");
//	if(!agreementBox.checked)
//	{
//		alert("You must check the check box to accept the terms and conditions to proceed.");
//		return false;
//	}
//	else
//	{
//		return true;
//	}
//	
//}
function initForm (controlId, signal, functionHandler) {

	var formControl = null;
	
	if (document == controlId) {
		formControl = document;
	}
	
	if ("window" == controlId) {
		formControl = window;
	}
	
	if ("PlanType" == controlId && top.document.PlanSearchForm) {
		formControl = top.document.PlanSearchForm.PlanType
	}
	
	if (null == formControl) {	
		if (document.getElementById) {
			formControl = document.getElementById(controlId);
		}
		else if (top.document.all) {
			formControl = document.all[controlId];
		}
	}
	
	// abort since there is nothing to attach
	if (!formControl) {
		return;
	}

  if (document.addEventListener) {
      formControl.addEventListener(signal, functionHandler, true);
  }
  else if (document.attachEvent) {
      formControl.attachEvent("on" + signal, functionHandler);
  }
  else if (document.all) {
		var sigHandler = eval(formControl + ".on" + signal)
		sigHandler = functionHandler;
  }
}


function loadReverse() 
{
	var rev=getEl("reverse");
	
	if (rev)
	{
		if (!flipffox()) {
			rev.style.display = 'none';
		}
	}
}

function getCookie (cookiename) {
	var val = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );
 
	if (val)
	{
		return unescape(val[1]);
	}
	else
	{
		return null;
	}
}

function softLogout(softLogoutSpace, url)
{
	var el = getEl(softLogoutSpace);
	if (el)
	{
		el.innerHTML = '<iframe src=\"' + url + '\" style=\"width:0px;height:0px;\"></iframe>';
		pauseExecution(3000);
	}
}

function pauseExecution(milliseconds)
{
	date = new Date();
	var curDate = null;
	do 
	{ 
		curDate = new Date(); 
	}
	while((curDate - date) < milliseconds);
} 

function softLogoutCookie() 
{
	var expires = new Date().setTime(0);
	
	setCookie ("WebnizCookie", "anonymous", expires, "/", "");
	setCookie ("WebnizUserCookie", "anonymous", expires, "/", "");
	
	if (document.cookie.indexOf ("WebnizCookie") != -1 || document.cookie.indexOf ("WebnizUserCookie") != -1) 
	{
		return true;
	}
	else 
	{
		return false;
	}
}


function setCookie (cname, cval, cexpires, cpath, cdomain) 
{

	var cookieStr = cname + "=" + cval + ";"
	
	if (cexpires)
	{
		cookieStr = cookieStr + "expires=" + cexpires + ";"
	}
	
	if (cpath)
	{
		cookieStr = cookieStr + "path=" + cpath + ";"
	}
	
	if (cdomain)
	{
		cookieStr = cookieStr + "domain=" + cdomain + ";"
	}
	
	document.cookie = cookieStr;
}


function autoShowDialog(idString)
{
	var el = getEl(idString);

	if (el != null && self == top && top.location.href.indexOf('Action.Save') != -1) 
	{
		var reUriInJavaScript = /.*'([^']*)'.*/i
		var href = el.getAttribute("href");
		var uri = href.replace(reUriInJavaScript, "$1");
		
		showDialog(uri);
	}
}


function setTopFormButton() 
{
	var searchButtonTop = getEl("show-results-top");
	var moreButton = getEl("search_button")
	
	if (searchButtonTop && moreButton && moreButton.src.indexOf("icon-more.gif") != -1) 
	{
		searchButtonTop.style.display = "none";
    } 
}


/* state variables */
var isSearchFormExpanded = false;

	$(document).ready(
						function()
						{




	if (top == self)
	{

		//LSI commented this. The button click now transfers the control to a new tab page 'Advanced Search' rather than showing the criteria in the same page.
		//initForm("search_button", "click", toggle_disclosure); 
		initForm("PlanType", "change", selectPlanType);
		// Synchronize the form with it's initial state
		selectPlanType(null); 
	
		//Set homepage plans top search button
		setTopFormButton();
	
		//initForm("dialog", "mousedown", downDialog);
		//initForm("dialog", "mouseup", upDialog);
		//initForm(document, "mousemove", moveDialog);
		//initForm(document, "mouseup", upDialog);
		initForm(document, "keypress", handleHotKey);	
		//initForm("SameAsBilling", "click", sameAsBillingClick);
		//initForm("BillToPhone", "keyup", phoneKeyUpMask);
		//initForm("BillToFax", "keyup", phoneKeyUpMask);
		//initForm("ShipToPhone", "keyup", phoneKeyUpMask);
		//initForm("ShipToFax", "keyup", phoneKeyUpMask);
		//initForm("prevEll", "click", togglePrevPaging);
		//initForm("nextEll", "click", toggleNextPaging);
		//initForm("prevEll2", "click", togglePrevPaging);
		//initForm("nextEll2", "click", toggleNextPaging);
		initForm("checkoutPaymentForm", "submit", submitOnce);
	}
	else 
	{
		initForm("PlanFolder", "change", PlanFolder_change);
	}

	if (getEl("PlanFolder") != null) 
	{
		PlanFolder_change();
	}

	if (getEl('add-to-cart-submit') != null || getEl('edit-cart-submit') != null)  
	{
	    //LSI: For DE773 in Iteration15
		//updateTotals();
	}

	if (typeof(updateShipping) != 'undefined') 
	{
		updateShipping();
	}

	autoShowDialog("save-plan-action");
	autoShowDialog("save-search-action");


	loadReverse();

});

//
// browse-collections
//
// FUNCTIONALITY THAT CONTROLS THE "BROWSE COLLECTIONS" SLIDER MENU AT THE TOP OF THE PAGE.
//
var BrowseCollectionsMenuControl;
var ArchStylesMenuControl;

//
// FUNCTION: OnBrowseCollectionsReady
//
// INVOKED WHEN THE DOCUMENT IS READY.
// CONFIGURES THE BROWSE COLLECTIONS SLIDER CONTROL AT THE TOP OF THE PAGE.
//
function OnBrowseCollectionsReady ()
{
	ConfigureBrowseCollectionsMenu();
	ConfigureArchStylesMenu();
}


//
// FUNCTION: ConfigureBrowseCollectionsMenu
//
// CREATES AND CONFIGURES THE BROWSE COLLECTIONS MENU.
//
function ConfigureBrowseCollectionsMenu ()
{
	BrowseCollectionsMenuControl = CreateBrowseCollectionsStyleMenu();
	//BrowseCollectionsMenuControl.InitializeMenu();
	$("#BrowseCurtain").click(function(){ArchStylesMenuControl.HideMenu();ShowBrowseCollectionsMenu();return false;});
	$("#BrowseCollectionsCloseButtonLinkTop").click(function(){HideBrowseCollectionsMenu(); return false;});
	$("#BrowseCollectionsCloseButtonLinkBottom").click(function(){HideBrowseCollectionsMenu(); return false;});
}


//
// FUNCTION: CreateBrowseCollectionsStyleMenu
//
// CREATES THE BROWSE COLLECTIONS MENU.
//
function CreateBrowseCollectionsStyleMenu ()
{
	//
	// MENU SYSTEM INITIALIZATION
	//
	//this.TabElement = $("#showBrowse");
	//this.MenuElement = $("#collections");
	
	//this.IsOpen = false;
	//this.UserIsInMenu = false;
	
	//
	// THESE ARE GLOBALLY DEFINED ELEMENTS THAT WE WANT TO HIDE ACROSS ALL PAGES.
	// IF THIS BECOMES UNMANAGEABLE THEN INDIVIDUAL PAGES WILL HAVE TO OVERRIDE THIS PROPERTY AND LIST THEIR OWN SHINE THROUGH ELEMENTS.
	// FOR RIGHT NOW WE ONLY HAVE 5 CONTROLS THAT SHINE THROUGH.  NO BIG DEAL.
	//
	this.ShineThroughElements = ["#PlanType", "#StateProvince", "#toppagerShow", "#toppagerSortColumn","#Proximity","#CategorySelect"];
	
	this.OpenSpeed = 300;
	this.CloseSpeed = 300;
	this.DelayUntilClose = 750;
	
	//
	// METHOD DEFINITIONS
	//
	//this.InitializeMenu = IntitializeBrowseCollectionsMenu;
	this.ShowMenu = ShowBrowseCollectionsMenu;
	this.HideMenu = HideBrowseCollectionsMenu;
	this.DisableMenu = DisableBrowseCollectionsMenu;
	this.OnMouseClick = OnBrowseCollectionsMouseClick;
	//this.OnMouseOut = OnBrowseCollectionsMouseOut;
	//this.OnMouseIn = OnBrowseCollectionsMouseIn;
	
	//
	// DONE.
	//
	return this;
}


//
// FUNCTION: IntitializeBrowseCollectionsMenu
//
// INITIALIZES AND CONFIGURES THE BROWSE COLLECTIONS MENU AND TAB.
//
function IntitializeBrowseCollectionsMenu ()
{
	//
	// CONFIGURE THE TAB ELEMENT.
	//
	//$(TabElement).hover(this.OnMouseClick);
	
	//
	// CONFIGURE THE MENU ELEMENT.
	//
	//$(MenuElement).hover(this.OnMouseIn, this.OnMouseOut);
}


//
// FUNCTION: OnBrowseCollectionsMouseOut
//
// CLOSES THE BROWSE COLLECTIONS MENU IF THE USER MOUSES OUT OF THE MENU AND STAYS OUT OF THE MENU FOR MORE THAN DelayUntilClose MILLISECONDS.
//
function OnBrowseCollectionsMouseOut ()
{
	BrowseCollectionsMenuControl.UserIsInMenu = false;
	window.setTimeout(function(){if (!BrowseCollectionsMenuControl.UserIsInMenu) BrowseCollectionsMenuControl.HideMenu();}, BrowseCollectionsMenuControl.DelayUntilClose);
}


//
// FUNCTION: OnBrowseCollectionsMouseIn
//
// OPENS THE BROWSE COLLECTIONS MENU IF IT IS NOT OPEN ALREADY.
//
function OnBrowseCollectionsMouseIn ()
{
	BrowseCollectionsMenuControl.UserIsInMenu = true;
	
	if (!BrowseCollectionsMenuControl.IsOpen)
		BrowseCollectionsMenuControl.ShowMenu();
}


//
// FUNCTION: OnBrowseCollectionsMouseClick
//
// OPENS THE BROWSE COLLECTIONS MENU IF IT IS NOT OPEN ALREADY.
//
function OnBrowseCollectionsMouseClick ()
{
	BrowseCollectionsMenuControl.UserIsInMenu = true;
	
	if (!BrowseCollectionsMenuControl.IsOpen)
		BrowseCollectionsMenuControl.ShowMenu();
}


//
// FUNCTION: HideBrowseCollectionsMenu
//
// HIDES THE BROWSE COLLECTIONS MENU.
//
function HideBrowseCollectionsMenu()
{
	//
	// HIDE THE FOLLOWING ELEMENTS SO THEY DON'T "SHINE THROUGH" THE BROWSE COLLECTIONS MENU.
	// THIS DEFECT IS EVIDENT IN INTERNET EXPLORER 6.
	//
	for (var i = 0; i < ShineThroughElements.length; i++)
		$(ShineThroughElements[i]).css("visibility", "visible");
	//
	// HIDE THE BROWSE COLLECTIONS MENU.
	//
	$("#collections").hide();

	//
	// THE MENU IS CLOSED.
	//
	BrowseCollectionsMenuControl.IsOpen  = false;
}


//
// FUNCTION: ShowBrowseCollectionsMenu
//
// SHOWS THE BROWSE COLLECTIONS MENU.
//
function ShowBrowseCollectionsMenu()
{
	//
	// HIDE THE FOLLOWING ELEMENTS SO THEY DON'T "SHINE THROUGH" THE BROWSE COLLECTIONS MENU.
	// THIS DEFECT IS EVIDENT IN INTERNET EXPLORER 6.
	//
	for (var i = 0; i < ShineThroughElements.length; i++)
		$(ShineThroughElements[i]).css("visibility", "hidden");

	//
	// OPEN THE BROWSE COLLECTIONS MENU WITH THE SPECIFIED ANIMATION.
	//
	$("#architecturalstyles").hide();
	$("#collections").fadeIn(OpenSpeed);
	
	//
	// THE MENU IS OPEN.
	//
	BrowseCollectionsMenuControl.IsOpen  = true;
}


//
// FUNCTION: DisableBrowseCollectionsMenu
//
// DISABLES THE BROWSE COLLECTIONS MENU FOR PAGES AND APPLICATIONS WHERE IT SHOULD NOT APPEAR.
//
function DisableBrowseCollectionsMenu ()
{
	//
	// "UNCONFIGURE" THE TAB ELEMENT.
	//
	//$(TabElement).unbind();
	
	//
	// "UNCONFIGURE" THE MENU ELEMENT.
	//
	//$(MenuElement).unbind();

}



//
// FUNCTION: ConfigureArchStyles
//
// CREATES AND CONFIGURES THE ARCHITECTURAL STYLES MENU.
//
function ConfigureArchStylesMenu()
{
	ArchStylesMenuControl = CreateArchStylesMenu();
	ArchStylesMenuControl.InitializeMenu();
	$("#StylesCurtain").click(function(){HideBrowseCollectionsMenu();ArchStylesMenuControl.ShowMenu ();return false;});
	$("#ArchStylesCloseButtonLinkTop").click(function(){ArchStylesMenuControl.HideMenu(); return false;});
	$("#ArchStylesCloseButtonLinkBottom").click(function(){ArchStylesMenuControl.HideMenu(); return false;});
}


//
// FUNCTION: CreateArchStylesMenu
//
// CREATES THE ARCHITECTURAL STYLES MENU.
//
function CreateArchStylesMenu ()
{
	//
	// MENU SYSTEM INITIALIZATION
	//
	//this.TabElement = $("#showArch");
	//this.MenuElement = $("#architecturalstyles");
	
	this.IsOpen = false;
	this.UserIsInMenu = false;
	
	//
	// THESE ARE GLOBALLY DEFINED ELEMENTS THAT WE WANT TO HIDE ACROSS ALL PAGES.
	// IF THIS BECOMES UNMANAGEABLE THEN INDIVIDUAL PAGES WILL HAVE TO OVERRIDE THIS PROPERTY AND LIST THEIR OWN SHINE THROUGH ELEMENTS.
	// FOR RIGHT NOW WE ONLY HAVE 5 CONTROLS THAT SHINE THROUGH.  NO BIG DEAL.
	//
	//this.ShineThroughElements = ["#toppagerShow", "#toppagerSortColumn", "#toppagerRange"];
	
	this.OpenSpeed = 300;
	this.CloseSpeed = 300;
	this.DelayUntilClose = 750;
	
	//
	// METHOD DEFINITIONS
	//
	this.InitializeMenu = IntitializeArchStylesMenu;
	this.ShowMenu = ShowArchStylesMenu;
	this.HideMenu = HideArchStylesMenu;
	this.DisableMenu = DisableArchStylesMenu;
	this.OnMouseClick = OnArchStylesMouseClick;
	//this.OnMouseOut = OnArchStylesMouseOut;
	//this.OnMouseIn = OnArchStylesMouseIn;
	
	//
	// DONE.
	//
	return this;
}


//
// FUNCTION: IntitializeArchStylesMenu
//
// INITIALIZES AND CONFIGURES THE ARCH STYLES MENU AND TAB.
//
function IntitializeArchStylesMenu ()
{
	//
	// CONFIGURE THE TAB ELEMENT.
	//
	//$(TabElement).hover(this.OnMouseIn, this.OnMouseOut);
	
	//
	// CONFIGURE THE MENU ELEMENT.
	//
	//$(MenuElement).hover(this.OnMouseIn, this.OnMouseOut);
}


//
// FUNCTION: OnBrowseCollectionsMouseOut
//
// CLOSES THE BROWSE COLLECTIONS MENU IF THE USER MOUSES OUT OF THE MENU AND STAYS OUT OF THE MENU FOR MORE THAN DelayUntilClose MILLISECONDS.
//
function OnArchStylesMouseOut ()
{
	ArchStylesMenuControl.UserIsInMenu = false;
	window.setTimeout(function(){if (!ArchStylesMenuControl.UserIsInMenu) ArchStylesMenuControl.HideMenu();}, ArchStylesMenuControl.DelayUntilClose);
}


//
// FUNCTION: OnArchStylesMouseIn
//
// OPENS THE ARCH STYLE MENU IF IT IS NOT OPEN ALREADY.
//
function OnArchStylesMouseIn ()
{
	ArchStylesMenuControl.UserIsInMenu = true;
	
	if (!ArchStylesMenuControl.IsOpen)
		ArchStylesMenuControl.ShowMenu();
}

//
// FUNCTION: OnArchStylesMouseClick
//
// OPENS THE ARCH STYLE MENU IF IT IS NOT OPEN ALREADY.
//
function OnArchStylesMouseClick ()
{
	ArchStylesMenuControl.UserIsInMenu = true;
	
	if (!ArchStylesMenuControl.IsOpen)
		ArchStylesMenuControl.ShowMenu();
}


//
// FUNCTION: HideArchStylesMenu
//
// HIDES THE ARCH STYLES MENU.
//
function HideArchStylesMenu ()
{
	//
	// HIDE THE FOLLOWING ELEMENTS SO THEY DON'T "SHINE THROUGH" THE ARCH COLLECTIONS MENU.
	// THIS DEFECT IS EVIDENT IN INTERNET EXPLORER 6.
	//["#toppagerShow", "#toppagerSortColumn", "#toppagerRange"];
	//for (var i = 0; i < ShineThroughElements.length; i++)
	//{
		$("#StateProvince").css("visibility", "visible");
		$("#toppagerShow").css("visibility", "visible");
		$("#toppagerSortColumn").css("visibility", "visible");
		$("#toppagerRange").css("visibility", "visible");
		$("#Proximity").css("visibility", "visible");
		$("#CategorySelect").css("visibility", "visible");
	//	alert(ShineThroughElements[i]);
	//}

	//
	// HIDE THE BROWSE COLLECTIONS MENU.
	//
	$("#architecturalstyles").hide();

	//
	// THE MENU IS CLOSED.
	//
	ArchStylesMenuControl.IsOpen  = false;
}


//
// FUNCTION: ShowArchStylesMenu
//
// SHOWS THE ARCH STYLES MENU.
//
function ShowArchStylesMenu ()
{
	//
	// HIDE THE FOLLOWING ELEMENTS SO THEY DON'T "SHINE THROUGH" THE ARCH STYLES MENU.
	// THIS DEFECT IS EVIDENT IN INTERNET EXPLORER 6.
	//
	//for (var i = 0; i < ShineThroughElements.length; i++)
	//{
	//	$(ShineThroughElements[i]).css("visibility", "hidden");
	//	alert(ShineThroughElements[i]);
	//}
	$("#StateProvince").css("visibility", "hidden");
	$("#toppagerShow").css("visibility", "hidden");
	$("#toppagerSortColumn").css("visibility", "hidden");
	$("#toppagerRange").css("visibility", "hidden");
	$("#Proximity").css("visibility", "hidden");
	$("#CategorySelect").css("visibility", "hidden");
	//
	// OPEN THE BROWSE COLLECTIONS MENU WITH THE SPECIFIED ANIMATION.
	//
	$("#architecturalstyles").fadeIn(OpenSpeed);
	
	//
	// THE MENU IS OPEN.
	//
	ArchStylesMenuControl.IsOpen  = true;
}


//
// FUNCTION: DisableArchStylesMenu
//
// DISABLES THE ARCH STYLES MENU FOR PAGES AND APPLICATIONS WHERE IT SHOULD NOT APPEAR.
//
function DisableArchStylesMenu ()
{
	//
	// "UNCONFIGURE" THE TAB ELEMENT.
	//
	$(TabElement).unbind();
	
	//
	// "UNCONFIGURE" THE MENU ELEMENT.
	//
	$(MenuElement).unbind();

}

//
// JAVASCRIPT LOGIC FOR Permalink - LSI Group.
//
function post2Url(url)
{
	var ThisUrl = location.protocol + "//" + location.hostname + location.pathname;

	var QPos = ThisUrl.indexOf("/Q/");
	var paramStr='';
	if( QPos > 0 )
	{
		 paramStr = ThisUrl.substr(QPos+3);
		paramStr = paramStr.replace("/", "&").replace(/\./g, "=");
	}
	
	tf1 = document.getElementById('permalinkForm');
	tf1.action = url;
	tf1.submit();
}

//
// FUNCTION: GetFeaturedPlan
//
// INVOKED WHEN THE DOCUMENT READY EVENT FIRES.
//
function GetFeaturedPlan ()
{
	var dhsUrl = "";

	var ThisUrl = location.protocol + "//" + location.hostname + location.pathname;
	var hwxPos = ThisUrl.indexOf(".hwx");
		
	if( hwxPos > 0 )
	  ThisUrl = ThisUrl.substr(0,hwxPos);

	hwxPos = ThisUrl.lastIndexOf("/");
	ThisUrl = ThisUrl.substr(0,hwxPos);

	var dhsUrl = ThisUrl.toString() + "/plan-of-the-week.hwx";
	
	$(document).ready(
						function()
						{
							$.post(dhsUrl, { name: "John", time: "2pm" },
									function(data)
									{
										$("div[@id=featuredPlanDiv]").each(function()
																			{
																				this.innerHTML= data ;
																				//this.innerHTML= "<h2>" + data + "</h2>";
																			}
																		);
									}
								   );
						}
					);
}

function GetFeaturedPlans (url)
{
	$(document).ready(
						function()
						{
							$.post(url, { name: "John", time: "2pm" },
									function(data)
									{
										$("div[@id=featuredPlanDiv]").each(function()
																			{
																				this.innerHTML= data ;
																				//this.innerHTML= "<h2>" + data + "</h2>";
																			}
																		);
									}
								   );
						}
					);
}

//
// JAVASCRIPT LOGIC FOR PLAN COUNTER FUNCTIONALITY - LSI Group.
//

	//function to call the ajax handler, to execute the getPlanCount() function in the webNiz AjaxContent.cs
	function updatePlanCount()
	{
	            ///get plan on sale counter
	            ///
	                   //    var plansUrl = SiteRoot + "ajax/plansonsale.hwx";
	                   //    var stg = "";
					       //$.ajax({type: "POST",
					                //url: plansUrl,
					                //data: stg,
					                //success: 
									$(document).ready(function(msg)
					                {
						                    //var pscnt =$('getplanonsalecount/PlansonsaleCount', msg).text();
											var pscnt =0;
						                    if (Number(pscnt)==0)
						                    {
						                        $("#PlansOnSale1").attr('disabled', 'disabled');
						                    }
						                    else
						                    {
						                        $("#PlansOnSale1").removeAttr('disabled');
						                    }
						            }
					            
			                    );
         SelectCostToBuildType(); 	            
	            ///	
	
		var dhsUrl = SiteRoot + "ajax/getplancount.hwx";
		
		//collect the selected inputs in the PlanSearchForm and prepare the query string to send to the ajaxHandler
		var st="";
		var anum=/(^[0-9a-zA-Z,]+$)/;
		var elems = document.getElementById("PlanSearchForm").elements;
		for(var e=0;e< elems.length;e++)
		{
		
			if(elems[e].name!="" && elems[e].name!="undefined")
			{
				if((elems[e].type=="checkbox"||elems[e].type=="radio")&&(elems[e].checked==true))
				{
					if(st!=""){st+="&"}
						st += elems[e].name + "=" + elems[e].value;
						 
				}
				if(elems[e].type=="text")
				{
					if(st!=""){st+="&"}
					
					var st1 = elems[e].value
					if(st1.length>6)
					{
					    st1 = st1.toUpperCase();
					    if (st1=='ENTER MIN')
					    {
					        st1 = '0';
					    }
					    else if (st1=='ENTER MAX')
					    {
					        st1 = '0';
					    }
					    else if ((elems[e].name == "MinCostToBuild") || (elems[e].name == "MaxCostToBuild"))
					    { 
					        st1 = st1;
					    }
					    else
					    {
					     	st = 'Error';
						    break;
						}
					}
		            st1 = st1.toUpperCase();
					
					if (st1=='MIN' || st1 =='MAX' || st1 == '')
					{
					}
					else if (st1=='ENTER MIN' )
					{
					    st1 = '0';
					}
					else if (st1=='ENTER MAX')
					{
					    st1 = '0';
					}
					else
					{  
						if(anum.test(st1))
						{
							st1 = st1.replace(/[^0-9]/g,'');
							
							if( st1.length == 0 )
							{
								st1 = '';
							}
							else
							{
								var num = Number(st1);
								if( num < 0 || num > 999999 )
								{   
					                if ((elems[e].name == "MinCostToBuild") || (elems[e].name == "MaxCostToBuild"))
					                { 
					                    st1 = st1;
					                }
					                else
					                {
					     	            st = 'Error';
						                break;
						            }
									 
								}
								else 
								{ 
									st1 = num.toString(); 
								}
							}							 
						}
						else
						{
							st = 'Error';
							break;
						}
					}

					st += elems[e].name + "=" + st1;
					 
				}
				if(elems[e].type=="select-one")
				{ 
					if(st!=""){st+="&"}
					st += elems[e].name + "=" + elems[e].options[elems[e].selectedIndex].value;
				}				 
			}
		}
		if(st=='Error')
		{
			$("div[@id=plansCount]").each(function(){
				this.innerHTML= "<h2>0</h2>";
			});
		}
		else
		{ 
			st=st+'&show-results=Search';
			//and finally call the ajaxHandler through the ajax Post call
			//and update the plansCount on the page with the planCount returned
			$.ajax({type: "POST",
					url: dhsUrl,
					data: st,
					success: function(msg){
						var pcnt =$('getplancount/PlanCount', msg).text();
						$("div[@id=plansCount]").each(function(){
							this.innerHTML= "<h2>" + pcnt + "</h2>";
						});
						$("span[@class=warningBlock]",document.forms["PlanSearchForm"]).each(function(){
								this.innerHTML= "";
						});
					}
			});
		}
		 
	}
 		
function SelectCostToBuildType()
{
    $("#MinCostToBuild").attr('disabled', 'disabled');
    $("#MaxCostToBuild").attr('disabled', 'disabled');            
    var elems = document.getElementById("PlanSearchForm").elements;
	for(var e=0;e< elems.length;e++)
	{
		if(elems[e].name=="CostToBuildType" && elems[e].name!="undefined")
		{
			if((elems[e].type=="radio")&&(elems[e].checked==true))
			{
				if (elems[e].value == '1')
				{
				    $("#MinCostToBuild").attr('value','enter Min');
                    $("#MaxCostToBuild").attr('value','enter Max');
                    $("#MinCostToBuild").attr('disabled', 'disabled');
                    $("#MaxCostToBuild").attr('disabled', 'disabled');
                    $("#SelectMinCostToBuild" ).removeAttr('disabled'); 
                    $("#SelectMaxCostToBuild" ).removeAttr('disabled');
				}
				else
				{
				    $("#MinCostToBuild" ).removeAttr('disabled');
                    $("#MaxCostToBuild" ).removeAttr('disabled');                                         
                    $("#SelectMinCostToBuild").val('00');
                    $("#SelectMaxCostToBuild").val('10000000');
                    $("#SelectMinCostToBuild").attr('disabled', 'disabled'); 
                    $("#SelectMaxCostToBuild").attr('disabled', 'disabled');
                }
                if($("#MinCostToBuild").val().toUpperCase()!='ENTER MIN')
	            {
	                validatecosttobuildtextboxes($("#MinCostToBuild"));
	            }
	            if($("#MaxCostToBuild").val().toUpperCase()!='ENTER MAX')
                {
                    validatecosttobuildtextboxes($("#MaxCostToBuild"));
                }
                if($("#MinCostToBuild").val().length > 9  || $("#MaxCostToBuild").val().length > 9 )
                {
                    alert(" Please enter valid minimum value and maximum value for Cost To Build. \n Value must be integer(0-9) and length should be less than 10.");
                    $("#MinCostToBuild").attr('value','enter Min');
                    $("#MaxCostToBuild").attr('value','enter Max');
                    return false;
                }
			}
			else
			{
                $("#MinCostToBuild").attr('disabled', 'disabled');
                $("#MaxCostToBuild").attr('disabled', 'disabled');
			}
		}		
	}
	
	if ( (Number($("#SelectMinCostToBuild").val()) > Number($("#SelectMaxCostToBuild").val())) && (Number($("#SelectMaxCostToBuild").val())>0))
    {
        alert(" Please select valid minimum value and maximum value for Cost To Build. \n Min Value should be less than Max Value.");
        $("#SelectMinCostToBuild").val('00');
        $("#SelectMaxCostToBuild").val('10000000');
        return false;
    }
    if ( (Number($("#MinCostToBuild").val()) > Number($("#MaxCostToBuild").val())) && (Number($("#MaxCostToBuild").val()>0)))
    {
        alert(" Please enter valid minimum value and maximum value for Cost To Build. \n Min Value should be less than Max Value. \n Value must be integer(0-9) and length should be less than 10.");
        $("#MinCostToBuild").attr('value','enter Min');
        $("#MaxCostToBuild").attr('value','enter Max');
        return false;
    }
    
}

function validatecosttobuildtextboxes(textBox)
{
    var validNum='0123456789';
	var tbvalue = textBox.val();
	//alert(tbvalue);
    for(i =0 ; i< tbvalue.length; i++)
	{
	    if(validNum.indexOf(tbvalue.charAt(i)) <= -1 )
	    {
		    textBox.attr('value','0');
		}
	}
}

//
// FUNCTION: OnPlanCounterDocumentReady
//
// INVOKED WHEN THE DOCUMENT READY EVENT FIRES.
//
function OnPlanCounterDocumentReady ()
{
	var dhsUrl = "";
	function readCookie(name)
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++)
		{
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	//when the page rendering completed, the code below is executed
	//and planCounter gets into action right away
	$(document).ready(function(){
	
		//Add the onClick event functions to the checkBox, Radio and Text inputs in the PlanSearchForm
		//so that, updatePlanCount function can be called for each of these inputs when the user changes selection
		$("input",document.forms["PlanSearchForm"]).each(function(){
			if(this.type=="checkbox"||this.type=="radio"){
				this.onclick =updatePlanCount;
			}
			if(this.type=="text")
			{
				this.onblur =updatePlanCount;
			}
		});
		$("select[@name=PlanType]").each(function(){
			this.onchange =updatePlanCount;
		});
		$("select[@name=SelectMinCostToBuild]").each(function(){
			this.onchange =updatePlanCount;
		});
		$("select[@name=SelectMaxCostToBuild]").each(function(){
			this.onchange =updatePlanCount;
		});


		//$(PlanSearchForm).each(function(){
		//	updatePlanCount();
		//});
		
		//when the PlanSearchForm is rendered on screen,
		//call the function to update the page with appropriate value
		$("form[@id=PlanSearchForm]").each(function(){
			updatePlanCount();
		});		
		
	});
}

// from plansearch.xsl
//
//
// EXTRACT THE SEARCH ID PARAMETER FROM THE URL.
//
function ExtractParamFromUrl (paramName)
{
	var currentUrl = decodeURI(document.URL);
	//
	// GET THE PART OF THE URL AFTER THE Q, THEN SPLIT IT USING THE /.
	//
	var paramValuePairArray = currentUrl.split('/Q/')[1].split('/');
					
	var arrayCount = 0;
				
	for(arrayCount = 0; arrayCount < paramValuePairArray.length; arrayCount++)
	{
		var nameValuePair = paramValuePairArray[arrayCount];
			
		if (nameValuePair.length > 0)
		{
			var nameValue = nameValuePair.split('.');
			if (nameValue.length > 1)
			{
				var currentParamName = nameValue[0];
				var currentParamValue = nameValue[1];
							
				if (currentParamName == paramName)
					return currentParamValue;
			}					
		}	
	}
					
	return null;
}
// removed this affiliate script here and added it in refferdetect.js -- LSI
//	var scriptLoc = 'http://www.myaffiliateprogram.com/u/eplans/rep.asp';
//	
//	var kbId = 0;
//	var qryString = window.location.search.substring(1);
//	var imgdata = '';
//	var subdata = '';

//	if (qryString.length > 0)
//	{
//		var pairs = qryString.split('&');
//								
//		for(var i = 0; i < pairs.length; i++)
//		{
//			var pairs2 = pairs[i].split('=');
//			
//			switch(pairs2[0].toLowerCase())
//			{
//				case 'kbid':
//					kbId = pairs2[1];
//					break;
//				case 'clearcookie':
//					if (pairs2[1] == 1)
//					{
//						DeleteCookie("kbid");
//					}
//					break;
//				case 'img':
//					imgdata = pairs2[1];
//					break;
//				case 'sub':
//					subdata = pairs2[1];
//					break;
//			}
//		} //end for
//	}//end if

//	if (GetCookie("kbid") == null)
//	{
//		if (kbId != 0)
//		{
//			var img = new Image();
//			var url = scriptLoc + '?id=' + kbId;
//			if (imgdata != '')
//			{
//				url += '&img=' + imgdata
//			}

//			if (subdata != '')
//			{
//				url += '&sub=' + subdata
//			}

//			img.src = url;
//			
//			//SetCookie("kbid", kbId, 1);
//		}
//	}//end if
//	
//	function getCookieVal (offset) 
//	{
//		var endstr = document.cookie.indexOf (";", offset);
//		if (endstr == -1)
//			endstr = document.cookie.length;

//		return unescape(document.cookie.substring(offset, endstr));
//	}

//	function GetCookie (name) 
//	{
//		var arg = name + "=";
//		var alen = arg.length;
//		var clen = document.cookie.length;
//		var i = 0;
//		
//		while (i < clen) 
//		{
//			var j = i + alen;
//			if (document.cookie.substring(i, j) == arg)
//				return getCookieVal (j);
//			
//			i = document.cookie.indexOf(" ", i) + 1;

//			if (i == 0) break; 
//		}
//		
//		return null;
//	}

//	function WriteCookie (name, value, expires) 
//	{
//		var argv = SetCookie.arguments;
//		var argc = SetCookie.arguments.length;
//		var path = (argc > 3) ? argv[3] : null;
//		var domain = (argc > 4) ? argv[4] : null;
//		var secure = (argc > 5) ? argv[5] : false;
//		
//		var cookie = name + "=" + escape(value) +
//			((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
//			((path == null) ? "" : ("; path=" + path)) +
//			((domain == null) ? "" : ("; domain=" + domain)) +
//			((secure == true) ? "; secure" : "");
//		
//		document.cookie = cookie;
//	}

//	function DeleteCookie (name) 
//	{
//		var exp = new Date();
//		exp.setTime (exp.getTime() - 1000000000);  // This cookie is history (changed -1 to make it previous time)
//		var cval = GetCookie (name);
//		document.cookie =name + "=" + cval + "; expires=" + exp.toGMTString();
//	}

//	function SetCookie(name, value, expiredays)
//	{
//		var expdate = new Date(); 
//		expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * expiredays)); 
//		WriteCookie(name, value, expdate);  
//	}



