/*
* briz@glyphix.com 20040616
*
* Added onload event handler to:
* -- place cursor in the first form field
* -- auto-submit form when Enter key is pressed
*/
var Wiz = null;

var onloads = new Array();
function bodyOnLoad() {
    for ( var i = 0 ; i < window.onloads.length ; i++ ){
		if(typeof window.onloads[i] == 'function'){
			window.onloads[i]();
		}else{
			eval(window.onloads[i]);
		}
    }
}

init = function() {
    // window.onloads.push(setAutoSubmit);
    window.onloads.push( focusForm );
    bodyOnLoad();
}
window.onload = init;

function setAutoSubmit(){
    FormList = document.getElementsByTagName("form");
    if(FormList){
		for(i = 0; i < FormList.length; i++){
			FormList.item(i).onkeypress = function(){
				if(event.keyCode == 13) this.submit();
			}
		}
    }
}

function focusForm(){
    if( document.forms[0] ){
		var str = "";
		var FieldList = document.forms[0];
		// Set tab order
		x = 1;
		for( i = 0; i < FieldList.length; i++ ){
			if( document.forms[0].elements[i].type != "hidden" && document.forms[0].elements[i].type != "button" ){
				if( elementIsVisible( document.forms[0].elements[i] ) ){
					document.forms[0].elements[i].tabindex = x;
					x++;
				}
			}
		}
		// Focus the first available field
		for( i = 0; i < FieldList.length; i++ ){
			if( (FieldList.elements[i].type == "text") || (FieldList.elements[i].type == "textarea") ){
				document.forms[0].elements[i].select();
				break;
			}else if(FieldList.elements[i].type.toString().charAt(0) == "s"){
				document.forms[0].elements[i].focus();
				break;
			}
		}
    }
}

function execSelect(target){
    if(target){
		eval(target);
    }else{
		return false;
    }
}

function toggleDesc(DivID){
    if(document.getElementById(DivID).style.display=='none'){
		document.getElementById(DivID).style.display='block';
    }else{
		document.getElementById(DivID).style.display='none';
    }
}

function addValue(ToObject,Value){
    for(i=0;i<document.form.length;i++){
		if(document.form[i].name==ToObject){
			document.form[i].value=document.form[i].value + Value;
			document.form[i].focus();
		}
    }

    return 1;
}

function loginSubmit(){
    // alert('hello');
    Form = document.getElementById('LoginForm');
    if(Form.Pass.value && Form.Salt.value){
		var Hashed = MD5(Form.Pass.value + Form.Salt.value);
		URL = "/?Realm=Login&Action=Auth&u=" + MD5(Form.Login.value) + "&p=" + Hashed + "&s=" + Form.Salt.value;
		document.location.href = URL;
    }else{
		alert("Please enter a username and a password.");
    }
    return 1;
}

function toggleSelector(ID){
    if(document.getElementById("Selector_" + ID).checked){
		document.getElementById("Selector_" + ID + "_Row").style.backgroundColor="green";
    }else{
		document.getElementById("Selector_" + ID + "_Row").style.backgroundColor="white";
    }
    return 1;
}

function toggleReportInput(Tracker){
    Controller="Controller_" + Tracker;
    Controlled="Input_" + Tracker;
    if(document.getElementById(Controller).checked){
		document.getElementById(Controlled).disabled=0;
		document.getElementById(Controlled).enabled="true";
    }else if(!document.getElementById(Controller).checked){
		document.getElementById(Controlled).disabled="true";
    }
    return true;
}

function togglePanel(DivID){
    callProcess("Panels","Toggle","PanelName",DivID);
    return toggleDesc(DivID);
}

function toggleFilter(DivID){
	//     callProcess("Panels","ToggleFilter","FilterName",DivID);
    return toggleDesc(DivID);
}

/*
* ToggleID is the id of the field which will be overridden by the form block.
* BlockID is the id of the element containing the form block fields.
*/
function ToggleFormBlock(ToggleID,BlockID){
    toggleDisabled(ToggleID);
    if(document.getElementById(ToggleID).disabled){
		if(document.getElementById(BlockID)){
			document.getElementById(BlockID).style.display="block";
			setBlockFormElementsState(BlockID,"Enable");
		}
    }else{
		if(document.getElementById(BlockID)){
			setBlockFormElementsState(BlockID,"Disable");
			document.getElementById(BlockID).style.display="none";
		}
    }
}

/*
function showBlock(ContainerID,SelectedID,ObjType,DefaultNoneID){
    if(!ObjType){
		ObjType = "div";
    }
    if(!DefaultNoneID){
		DefaultNoneID = "None"
    }
    if(!SelectedID){
		SelectedID = DefaultNoneID;
    }
    Container = document.getElementById(ContainerID);
    ItemList = Container.getElementsByTagName(ObjType);
    if(!ItemList.length){
		alert("No items of type " + ObjType + " were found.");
		return false;
    }
    for(i = 0; i < ItemList.length; i++){
		// Only hide or show if the item has an id attribute
		if(ItemList.item(i).id){
			ItemID = ItemList.item(i).id;
			if(ItemID == SelectedID){
				showElement(ItemID);
				// setBlockFormElementsState(ItemID,"Enable");
			}else{
				hideElement(ItemID);
				// setBlockFormElementsState(ItemID,"Disable");
			}
		}
    }
}
*/

function showBlock(ContainerID,SelectedID,ObjType,DefaultNoneID){
    if(!ObjType){
		ObjType = "div";
    }
    if(!DefaultNoneID){
		DefaultNoneID = "None"
    }
    if(!SelectedID){
		SelectedID = DefaultNoneID;
    }
    var Container = document.getElementById(ContainerID);
    var ItemList = Container.getElementsByTagName(ObjType);
    if(!ItemList.length){
		alert("No items of type " + ObjType + " were found.");
		return false;
    }
    // must declare i in this function in order to scope it correctly
    var i = 0;
    for(i = 0; i < ItemList.length; i++){
		// Only hide or show if the item has an id attribute
		if(ItemList.item(i).id){
		    var ItemID = ItemList.item(i).id;
		    if(typeof(SelectedID) != "string"){
		    	if(inArray(ItemID, SelectedID)){
		    		showElement(ItemID);
		    		setBlockFormElementsState(ItemID,"Enable");
		    	}else{
		    		hideElement(ItemID);
		    		setBlockFormElementsState(ItemID,"Disable");
		    	}
		    }else{
			    if(ItemID == SelectedID){
					showElement(ItemID);
					setBlockFormElementsState(ItemID,"Enable");
			    }else{
					hideElement(ItemID);
					setBlockFormElementsState(ItemID,"Disable");
			    }
		    }
		}
    }
}

function inArray(needle, haystack){
	// must declare i in this function in order to scope it correctly
	var i = 0;
	for(i = 0; i < haystack.length; i++){
		if(haystack[i] == needle){
			return true;
			break;
		}
	}
	return false;
}

function setBlockFormElementsState(BlockID,Action){
    if(!Action){
		Action="Enable";
    }
    if(Action=="Enable"){
		DisabledValue=0;
    }else{
		DisabledValue="true";
    }
    Block=document.getElementById(BlockID);
    if(Block){
		FormStuff=Block.getElementsByTagName("*");
		for(i=0;i<FormStuff.length;i++){
		    if(FormStuff.item(i).nodeName=="INPUT"
				|| FormStuff.item(i).nodeName=="SELECT"
			|| FormStuff.item(i).nodeName=="TEXTAREA"
			|| FormStuff.item(i).nodeName=="BUTTON"){
				FormStuff.item(i).disabled=DisabledValue;
		    }
		}
    }
}

function toggleDisabled(ID){
    if(document.getElementById(ID).disabled){
		document.getElementById(ID).disabled=0;
    }else{
		document.getElementById(ID).disabled="true";
    }
}

function toggleInput(InputID){
    if(document.getElementById(InputID).disabled="true"){
		document.getElementById(InputID).disabled="false";
    }else{
		document.getElementById(InputID).disabled="true";
    }
    return true;
}

function displayElement(Object,State){
    if(!Object){
		alert("No Object in displayElement()");
		return false;
    }
    if(State=="off"){
		DisplayVal="none";
    }else{
		if(document.all){
			// Internet Explorer
			switch(Object.nodeName.toLowerCase()){
				case "img":
					DisplayVal="inline";
					break;
				default:
					DisplayVal="block";
			}
		}else{
			// Mozilla
			switch(Object.nodeName.toLowerCase()){
				case "td":
					DisplayVal="table-cell";
					break;
				case "tr":
					DisplayVal="table-row";
					break;
				case "table":
					DisplayVal="table";
					break;
				case "tbody":
					DisplayVal="table-row-group";
					break;
				case "img":
					DisplayVal="image";
					break;
				default:
					DisplayVal="block";
					break;
			}
		}
    }
    Object.style.display=DisplayVal;
}

function showElement(ElementID){
    theElement = document.getElementById(ElementID);
    theElement.style.display="block";
}

function hideElement(ElementID){
    theElement = document.getElementById(ElementID);
    theElement.style.display="none";
}

function toggleElement(ElementID){
    if(document.getElementById(ElementID).style.display=="none" || document.getElementById(ElementID).style.display==""){
		document.getElementById(ElementID).style.display="block";
    }else{
		document.getElementById(ElementID).style.display="none";
    }
}

function getParentOfType(Obj,desiredType){
    if(!Obj.parentNode){
		return false;
    }
    if(Obj.parentNode.nodeName.toLowerCase()=="body"){
		return false;
    }
    if(Obj.nodeName.toLowerCase()==desiredType){
		return Obj;
    }else{
		return getParentOfType(Obj.parentNode,desiredType);
    }
}

function getParentOfID(Obj,ID){
    if(!Obj.parentNode){
		return false;
    }
    if(Obj.parentNode.nodeName.toLowerCase()=="body"){
		return false;
    }
    if(Obj.id==ID){
		return Obj;
    }else{
		return getParentOfID(Obj.parentNode,ID);
    }
}

function toggleAllRows(Obj,State){
    var TableObj=getParentOfType(Obj,"table");
    if(!TableObj){
		alert("This page does not allow for this function.");
		return false;
    }
    Checks=TableObj.getElementsByTagName("input");
    if(Checks.length){
		for(i=0;i<Checks.length;i++){
			if(Checks[i].type=='checkbox'){
				if(State){
					switch(State.toLowerCase()){
						case "off":
							Checks[i].checked=false;
							break;
						case "on":
							Checks[i].checked=true;
							break;
						default:
							Checks[i].click();
					}
				}else{
					Checks[i].click();
				}
			}
		}
    }else{
		alert("No rows can be checked.");
		return false;
    }
    Obj.blur();
}

function callProcess(MyRealm,MyAction,ToName,ToID){
    CallMe="/?Realm=" + MyRealm + "&Action=" + MyAction;
    if(ToName && ToID){
		CallMe=CallMe + "&" + ToName + "=" + ToID;
    }
    document.getElementById('processFrame').src = CallMe;
    //	alert(CallMe);
    //	history.go(0);
    return true;
}

function closeWizardVerify(){
    alert("Please do NOT close this window until you have completed all Steps.\n\nPlease select this action again to ensure your information is recorded correctly.");
    return false;
}

function startWizard(Realm,Action,LinkType,LinkID){
    var URL = "/?Realm=" + Realm + "&Action=" + Action;
    if(LinkType){
		URL += "&" + LinkType + "=" + LinkID;
    }
    var WindowName = Action + "_Wizard";
	win2top( URL, WindowName, "width=800,height=600,scrolling=yes,scrollbars=yes,status=yes,resize=yes,resizable=yes" );
}

function startRetestWizard(Realm,Action,SiteID,TestID){
    var URL = "/?Realm=" + Realm + "&Action=" + Action + "&SiteID=" + SiteID + "&TestID=" + TestID;
    var WindowName = Action + "_Wizard";
    win2top( URL, WindowName, "width=800,height=600,scrolling=yes,scrollbars=yes,status=yes,resize=yes,resizable=yes" );
}

function startChangeoutRetestWizard(Realm,Action,ChangeoutID,TestID){
    var URL = "/?Realm=" + Realm + "&Action=" + Action + "&ChangeoutID=" + ChangeoutID + "&TestID=" + TestID;
    var WindowName = Action + "_Wizard";
    win2top( URL, WindowName, "width=800,height=600,scrolling=yes,scrollbars=yes,status=yes,resize=yes,resizable=yes" );
}

function startFeedbackWizard(Realm,Action,PageRealm,PageAction){
    var URL = "/?Realm=" + Realm + "&Action=" + Action;
    if(PageRealm){
		URL += "&PageRealm=" + PageRealm + "&PageAction=" + PageAction;
    }
    WindowName = Action + "_Wizard";
    win2top( URL, WindowName, "width=800,height=600,scrolling=yes,scrollbars=yes,status=yes,resize=yes,resizable=yes" );
}

function startChangeoutWizard(Realm,Action,InstallerType,InstallerID,ChangeoutName,ChangeoutID){
    var URL = "/?Realm=" + Realm + "&Action=" + Action + "&InstallerID=" + InstallerID + "&ChangeoutID=" + ChangeoutID;
    WindowName = Action + "_Wizard";
    win2top( URL, WindowName, "width=800,height=600,scrolling=yes,scrollbars=yes,status=yes,resize=yes,resizable=yes" );
}

function popToDoWindow(PlanID){
    var URL = "/?Realm=Plan&Action=ToDoList&PlanID=" + PlanID;
    var WindowName = "ToDo";
    win2top( URL, WindowName, "width=1000,height=700,menubar=yes,scrolling=yes,scrollbars=yes,status=yes,resize=yes,resizable=yes" );
}

function popCompletionWindow(SiteID){
    var URL = "/?Realm=Site&Action=CompletionReport&SiteID=" + SiteID;
    var WindowName = "completion";
    win2top( URL, WindowName, "width=1000,height=700,menubar=yes,scrolling=yes,scrollbars=yes,status=yes,resize=yes,resizable=yes" );
}

function win2top( URL, WindowName, Attributes ) {
    window.Wiz = window.open( URL, WindowName, Attributes );
    if (window.focus) { window.Wiz.focus() }
}

function setMorsel(Morsel){
    Form = document.getElementById("FilterForm");
    Form.Morsel.value = Morsel;
    doPaging();
}

function setChunk(Chunk){
    Form = document.getElementById("FilterForm");
    Form.Morsel.value = 0;
    Form.Chunk.value = Chunk;
    doPaging();
}

function doPaging(){
    Form = document.getElementById("FilterForm");
    Form.submit();
}

function doSort(Column){
    Form = document.getElementById("FilterForm");
    if(Column.length && Form.SortMe){
		if(Form.SortMe.value==Column){
			if(Form.SortOrder.value==0){
				Form.SortOrder.value=1;
			}else{
				Form.SortOrder.value=0;
			}
		}else{
			Form.SortOrder.value=1;
			Form.SortMe.value=Column;
		}
		Form.submit();
    }
}

function popupWizard(URL){
    win2top(URL,"popup","width=700,height=500,location=no,toolbar=no,scrollbars=yes,menubar=no,scrolling=yes,status=no,resize=yes,resizable=yes");
}

/*
* This function parses ampersand-separated name=value argument pairs from
* the query string of the URL. It stores the name=value pairs in
* properties of an object and returns that object.
*/
function getArgs() {
    var args = new Object();
    var query = location.search.substring(1);  		// Get query string.
    var pairs = query.split("&");              		// Break at ampersand.
    for(var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf("=");       		// Look for "name=value".
		if (pos == -1) continue;               		// If not found, skip.
		var argname = pairs[i].substring(0,pos);  	// Extract the name.
		var value = pairs[i].substring(pos+1); 		// Extract the value.
		args[argname] = unescape(value);          	// Store as a property.
    }
    return args;                               		// Return the object.
}

/*
* Recurse up the DOM, returning the parent node of the requested type.
*/
function getParent(Obj,ParentType){
    // briz@glyphix.com 20041221
    // For some reason, this function behaves differently when it"s operating on client-side XML vs. client-side HTML.
    // When in HTML mode, it gets a lot of "Obj has no properties" errors.
    if(!Obj){
		return true;
    }
    // if body, we"re at the top of the tree, return true
    if(Obj.nodeName == "body"){
		return Obj;
    }else{
		if(Obj.nodeName.toLowerCase() == ParentType.toLowerCase()){
			return Obj;
		}else{
			return getParent(Obj.parentNode,ParentType);
		}
    }
}

function setParentClass(Obj,ParentType,Class){
    Parent = getParent(Obj,ParentType);
    if(Parent){
		Parent.className = Class;
    }
}

function failMeasure(Obj){
    var MeasureRow = getParent(Obj,"tr");
    if(MeasureRow){
		var Fail = MeasureRow.getElementsByTagName("input");
		if(Fail.length){
			for(i = 0; i < Fail.length; i++){
				if(Fail.item(i).id == "MeasureFail"){
					Fail.item(i).click();
					break;
				}
			}
		}
    }
}

function passMeasure(Obj){
    var MeasureRow = getParent(Obj,"tr");
    var OK = true;
    if(MeasureRow){
		// get <UL> elements whose class is Required
		var Required = MeasureRow.getElementsByTagName("ul");
		if(Required.length){
			for(i = 0; i < Required.length; i++){
				if(Required.item(i).className == "Required"){
					// get radio buttons contained by the current <UL>
					Bool = Required.item(i).getElementsByTagName("input");
					if(Bool){
						for(x = 0; x < Bool.length; x++){
							// if it's a radio button and its id is "No" and it's checked,
							// then the entire Measure must not be set to Pass.
							if(Bool.item(x).type == "radio" && Bool.item(x).id == "No" && Bool.item(x).checked){
								// alert("A required item is marked No, so cannot set this Measure to passed.");
								OK = false;
								break;
							}
						}
					}
					// if not OK, break the outer loop
					if(!OK){
						break;
					}
				}
			}
		}
		if(OK){
			var Pass = MeasureRow.getElementsByTagName("input");
			if(Pass.length){
				for(i = 0; i < Pass.length; i++){
					if(Pass.item(i).id == "MeasurePass"){
						Pass.item(i).click();
						break;
					}
				}
			}
		}
    }
}

/*
* Recurse up DOM, testing visibility in node tree.
* If an element does not have a style.display attribute, return false.
* An element must have its style.display explicitly set to "none" to return false.
*/
function elementIsVisible(Obj){
    // briz@glyphix.com 20041221
    // For some reason, this function behaves differently when it"s operating on client-side XML vs. client-side HTML.
    // When in HTML mode, it gets a lot of "Obj has no properties" errors.
    if(!Obj){
		return true;
    }
    // if body, we"re at the top of the tree, return true
    if(Obj.nodeName == "body"){
		return true;
    }else{
		if(Obj.style){
			if(Obj.style.display.toLowerCase() == "none"){
				return false;
			}else{
				return elementIsVisible(Obj.parentNode);
			}
		}else{
			return elementIsVisible(Obj.parentNode);
		}
    }
}

function checkForm(){
    var BodyList;
    var DocBody;
    var InputBlocks;
    var CurItem;
    var i=0;
    var ErrorList=0;
    // Check for Pass/Fail radio buttons
    var MeasureResult = document.getElementsByTagName("span");
    if(MeasureResult){
    	for(i = 0; i < MeasureResult.length; i++){
    		if(MeasureResult.item(i).id == "MeasureResult" && elementIsVisible(MeasureResult.item(i))){
	    		Radios = MeasureResult.item(i).getElementsByTagName("input");
	    		if(Radios[0].checked || Radios[1].checked){
	    			setParentClass(MeasureResult.item(i),"td","");
	    			continue;
	    		}
	    		setParentClass(MeasureResult.item(i),"td","MissingData");
	    		alert("A Test on this page requires a Pass / Fail value. It has been marked in bright blue.");
	    		return false;
    		}
    	}
    }
    BodyList = document.getElementsByTagName("body");
    DocBody = BodyList[0];
    InputBlocks = DocBody.getElementsByTagName("li");
    if(InputBlocks.length){
		for(i=0;i<InputBlocks.length;i++){
			CurItem=InputBlocks.item(i);
			/*
			if(InputBlocks.item(i).className){
				alert("elementIsVisible(" + InputBlocks.item(i).className + "): " + (elementIsVisible(InputBlocks.item(i))));
			}
			*/
			if(
				CurItem.id.toLowerCase()=="input"
			&& (CurItem.parentNode.className.toLowerCase()=="required" || CurItem.parentNode.className.toLowerCase()=="error")
			&& elementIsVisible(InputBlocks.item(i))
			){
				CurItem.parentNode.className="Required";
				if(!oneFieldHasValue(CurItem)){
					CurItem.parentNode.className="Error";
					ErrorList++;
				}
			}
		}
		if(ErrorList){
			alert("Please enter all required information. Missing fields have been marked in red.");
			return false;
		}else{
			return true;
		}
    }else{
		return true;
    }
}

function oneFieldHasValue(Obj){
    var i=0;
    var FieldList=Obj.getElementsByTagName("*");
    var FoundField=false;
    if(FieldList.length>0){
		for(i=0;i<FieldList.length;i++){
			if(FieldList.item(i).nodeName.toLowerCase()=="input" || FieldList.item(i).nodeName.toLowerCase()=="select" || FieldList.item(i).nodeName.toLowerCase()=="textarea"){
				// if it"s visible and it"s not a hidden field
				if(FieldList.item(i).type.toLowerCase()!="hidden" && FieldList.item(i).type.toLowerCase()!="button"){
					if(elementIsVisible(FieldList.item(i))){
						FoundField=true;
						if(FieldList.item(i).type.toLowerCase()=="radio" || FieldList.item(i).type.toLowerCase()=="checkbox"){
							if(FieldList.item(i).checked){
								return true;
							}
						}else if(FieldList.item(i).nodeName.toLowerCase()=="select"){
							if(FieldList.item(i).options.length){
								if(FieldList.item(i).options[FieldList.item(i).selectedIndex].value.length>0){
									return true;
								}
							}else if(FieldList.item(i).disabled==true){
								return true;
							}
						}else{
							if(FieldList.item(i).value){
								return true;
							}
						}
					}else{
						continue;
					}
				}else{
					continue
				}
			}else{
				continue;
			}
		}
		// if it made it this far, there"s a required field without a value
		if(FoundField){
			return false;
		}else{
			// found a required field, but it had no value
			return true;
		}
    }else{
		// no fields, return true to not flag as error
		return true;
    }
}

function cleanFieldName(Str){
    reg=/\[|\]/gi;
    return Str.replace(reg,"");
}

function replaceText(Str,FindStr,ReplaceStr){
    rExp=/FindStr/g;
    return Str.replace(rExp,ReplaceStr);
}

function isEmpty(elementID,formID){
    if(!formID){
		theForm=document.forms[0];
    }else{
		theForm=document.getElementById(formID);
    }
    for(e=0; e<theForm.elements.length; e++){
		if (theForm.elements[e].id == elementID){
			theElement = theForm.elements[e];
			if(theElement.type == "radio" || theElement.type == "checkbox"){
				if(theElement.checked){
					return false;
				}
			}else{
				if(theElement.value){
					return false;
				}
			}
		}
    }
    return true;
}

function isBadEmail(elementID){
    checkString=document.getElementById(elementID).value;
    if(checkString.indexOf("@")<0){
		return true;
    }
    if(checkString.indexOf(".")<0){
		return true;
    }
    if(checkString.indexOf(" ") > -1){
		return true;
    }
    var dotParts = checkString.split(".");
    var tld = dotParts.pop();
    if(tld.length < 2){
		return true;
    }
    /* check for invalid characters */
    for(var i = 0; i < checkString.length; i++){
		ch = checkString.substring(i, i + 1);
		if(!((ch >= "A" && ch <= "Z")
			|| (ch >= "a" && ch <= "z")
		|| (ch == "@")
		|| (ch == ".")
		|| (ch == "_")
		|| (ch == "-")
		|| (ch >= "0" && ch <= "9")
		)){
			return true;
		}
    }
    return false;
}

function notAfterToday(cal){
    var date = cal.date;
    var time = date.getTime();
    var now=new Date();
    var nowTime=now.getTime();
    if(time > nowTime){
		alert("Selected date cannot be later than today.");
		cal.params.inputField.value="";
    }
}

function trim(str){
    return str.replace(/^\s*|\s*$/g,"");
}

/*********************************************************/
/********************  ajax wrapper  *********************/
/*********************************************************/

function callAjax( Params, CompleteFunction, FailureFunction ){
    var URL = "/";
	if( !FailureFunction ){
		FailureFunction = "showAjaxError";
	}
    // var myAjax = new Ajax.Request( URL, {method: "get", parameters: Params, onComplete: PostProcess, onFailure: "showAjaxError"} );
    Call = "var myAjax = new Ajax.Request( '" + URL + "', {method: 'get', parameters: '" + Params + "', onComplete: " + CompleteFunction + ", onFailure: " + FailureFunction + "} )";
    eval(Call);
}

function replaceObj( Obj, Params ){
    if(Obj.id){
		var url = "/";
		var myAjax = new Ajax.Updater(
			{success: Obj.id},
			url,
			{method: "get", parameters: Params, onFailure: showAjaxError}
		);
    }
}

function showAjaxError( Result ){
    alert("We were unable to process an AJAX function: " + Result.toSource());
}

/*********************************************************/
/****************  context popup boxes  ******************/
/*********************************************************/

function getRecordActionList( Obj, Realm, LinkType, LinkID ){
	$("RecordAction").style.visibility = "hidden";
	$("RecordAction").innerHTML = null;
	window.RecordCaller = Obj;
	var RecordBox = $("RecordAction");
	var Params = "Realm=Login&Action=ListRecordActions&RealmName=" + Realm + "&RequiredArg=" + LinkType + "&" + LinkType + "=" + LinkID;
	var url = "/";
	var myAjax = new Ajax.Updater(
		{success: RecordBox.id},
		url,
		{method: "get", parameters: Params, evalScripts: true, onComplete: showRecordActionBox, onFailure: showAjaxError}
	);
}

function getRecordInfoBox( Obj, Realm, Action, LinkType, LinkID ){
	$("RecordAction").style.visibility = "hidden";
	$("RecordAction").innerHTML = null;
	window.RecordCaller = Obj;
	var RecordBox = $("RecordAction");
	var Params = "Realm=" + Realm + "&Action=" + Action + "&" + LinkType + "=" + LinkID;
	var url = "/";
	var myAjax = new Ajax.Updater(
		{success: RecordBox.id},
		url,
		{method: "get", parameters: Params, evalScripts: true, onComplete: showRecordInfoBox, onFailure: showAjaxError}
	);
}

function grabComputedStyle(_10){
	if(document.defaultView&&document.defaultView.getComputedStyle){
		return document.defaultView.getComputedStyle(_10,null);
	}else{
		if(_10.currentStyle){
			return _10.currentStyle;
		}else{
			return null;
		}
	}
}
function grabComputedHeight(_11){
	var _12=grabComputedStyle(_11).height;
	if(_12!=null){
		if(_12.indexOf("px")!=-1){
			_12=_12.substring(0,_12.indexOf("px"));
		}
		if(_12=="auto"){
			if(_11.offsetHeight){
				_12=_11.offsetHeight;
			}
		}
	}
	return _12;
}
function getElementOffsetY(_17){
	var _18=0;
	if(_17.offsetTop!=null){
		_18+=_17.offsetTop;
		while(_17.offsetParent){
			_18+=_17.offsetParent.offsetTop;
			_17=_17.offsetParent;
		}
	}
	return _18;
}
function getElementOffsetX(_23){
	return handleElementOffsetX(_23,true);
}
function handleElementOffsetX(_25,_26){
	var _27=0;
	if(_25.offsetLeft!=null){
		_27+=_25.offsetLeft;
		while(_25.offsetParent){
			if(_26&&_25.offsetParent.style.position=="absolute"){
				return _27;
			}else{
				_27+=_25.offsetParent.offsetLeft;
				_25=_25.offsetParent;
			}
		}
	}
	return _27;
}

function showRecordActionBox(){
	return showRecordInfoBox();
	/*
	var Y = getElementOffsetY(window.RecordCaller);
	var X = getElementOffsetX(window.RecordCaller);
	var Height = grabComputedHeight($("RecordAction"));
	$("RecordAction").style.top = (Y - (Height/2)) + "px";
	// $("RecordAction").style.left = (X - 245) + "px";
	$("RecordAction").style.left = (X + 50) + "px";
	// this.correctForYOverrun(_173);
	$("RecordAction").style.visibility = "visible";
	*/
}

function showRecordInfoBox(){
	var firstChild = first_child(window.RecordCaller);
	var secondChild = node_after(firstChild);
	var Y = getElementOffsetY(secondChild);
	var X = getElementOffsetX(secondChild);
	var Height = grabComputedHeight(secondChild);
	$("RecordAction").style.top = (parseInt(Y) + parseInt(Height) - 3) + "px";
	$("RecordAction").style.left = (X - 10) + "px";
	$("RecordAction").style.visibility = "visible";
}

/**
 * Determine whether a node's text content is entirely whitespace.
 *
 * @param nod  A node implementing the |CharacterData| interface (i.e.,
 *             a |Text|, |Comment|, or |CDATASection| node
 * @return     True if all of the text content of |nod| is whitespace,
 *             otherwise false.
 */
function is_all_ws( nod )
{
  // Use ECMA-262 Edition 3 String and RegExp features
  return !(/[^\t\n\r ]/.test(nod.data));
}


/**
 * Determine if a node should be ignored by the iterator functions.
 *
 * @param nod  An object implementing the DOM1 |Node| interface.
 * @return     true if the node is:
 *                1) A |Text| node that is all whitespace
 *                2) A |Comment| node
 *             and otherwise false.
 */

function is_ignorable( nod )
{
  return ( nod.nodeType == 8) || // A comment node
         ( (nod.nodeType == 3) && is_all_ws(nod) ); // a text node, all ws
}

/**
 * Version of |previousSibling| that skips nodes that are entirely
 * whitespace or comments.  (Normally |previousSibling| is a property
 * of all DOM nodes that gives the sibling node, the node that is
 * a child of the same parent, that occurs immediately before the
 * reference node.)
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The closest previous sibling to |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function node_before( sib )
{
  while ((sib = sib.previousSibling)) {
    if (!is_ignorable(sib)) return sib;
  }
  return null;
}

/**
 * Version of |nextSibling| that skips nodes that are entirely
 * whitespace or comments.
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The closest next sibling to |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function node_after( sib )
{
  while ((sib = sib.nextSibling)) {
    if (!is_ignorable(sib)) return sib;
  }
  return null;
}

/**
 * Version of |lastChild| that skips nodes that are entirely
 * whitespace or comments.  (Normally |lastChild| is a property
 * of all DOM nodes that gives the last of the nodes contained
 * directly in the reference node.)
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The last child of |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function last_child( par )
{
  var res=par.lastChild;
  while (res) {
    if (!is_ignorable(res)) return res;
    res = res.previousSibling;
  }
  return null;
}

/**
 * Version of |firstChild| that skips nodes that are entirely
 * whitespace and comments.
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The first child of |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function first_child( par )
{
  var res=par.firstChild;
  while (res) {
    if (!is_ignorable(res)) return res;
    res = res.nextSibling;
  }
  return null;
}

/*********************************************************/
/****************  city / county combo  ******************/
/*********************************************************/

function processCityBlock(){
    // Set CountyList to nothing just in case we have a failure
    $("CountyList").options.length = 0;
    // Populate CountyList
    callAjax("Realm=Misc&Action=CountyList", "processCountyList");
    // Set CityList to nothing
    $("CityList").options.length = 0;
    // Set climate zone display to question marks
    $("CZ").innerHTML = "Select a County / City";
}

function resetCountyCities(){
    $("CZ").innerHTML = "Select a County / City";
    $("LocationCZ").value = "";
    $("SelectedCity").value = "";
    County = $("CountyList").value;
    callAjax("Realm=Misc&Action=CityList&County=" + escape(trim(County)), "processCityList");
}

function setClimateZone(){
    City = $("CityList").value;
    County = $("CountyList").value;
    callAjax("Realm=Misc&Action=CityClimateZone&County=" + escape(trim(County)) + "&City=" + escape(trim(City)), "processClimateZone");
}

function processCountyList(Result){
    if(!Result.responseXML){
		alert("We were unable to obtain a list of Counties.");
		return null;
    }
    var CountyList = Result.responseXML.getElementsByTagName("County");
    $("CountyList").options.length = 0;
    $("CountyList").options[0] = new Option(" ", "");
    for(i = 0; i < CountyList.length; i++){
		CountyName = CountyList.item(i).childNodes[0].nodeValue;
		$("CountyList").options[i + 1] = new Option(CountyName, CountyName);
    }
    // If a city is selected, derive the county, select it and then populate the CityList pulldown
    var SelectedCity = $("SelectedCity").value;
    if(SelectedCity){
		callAjax("Realm=Misc&Action=DeriveCounty&City=" + escape(trim(SelectedCity)), "processCounty");
    }
}

function processCityList(Result){
    if(!Result.responseXML){
		alert("We were unable to obtain a list of Cities.");
		return null;
    }
    var CityList = Result.responseXML.getElementsByTagName("City");
    $("CityList").options.length = 0;
    $("CityList").options[0] = new Option(" ", "");
    for(i = 0; i < CityList.length; i++){
		CityName = CityList.item(i).childNodes[0].nodeValue;
		$("CityList").options[i + 1] = new Option(CityName, CityName);
    }
    // If a city is selected, set the CityList pulldown to that value and then display the climate zone
    var SelectedCity = $("SelectedCity").value;
    if(SelectedCity){
		CityOptions = $("CityList").options;
		for(i = 0; i < CityOptions.length; i++){
			if(CityOptions[i].value == SelectedCity){
				$("CityList").options.selectedIndex = i;
				break;
			}
		}
		County = $("CountyList").value;
		callAjax("Realm=Misc&Action=CityClimateZone&County=" + escape(trim(County)) + "&City=" + escape(trim(SelectedCity)), "processClimateZone");
    }
}

function processCounty(Result){
    if(!Result.responseXML){
		alert("We were unable to determine the County for the selected City.");
		return null;
    }
    var SelectedCounty = Result.responseXML.getElementsByTagName("County");
    var CountyName = SelectedCounty[0].childNodes[0].nodeValue;
    // Check for errors
    if(CountyName.indexOf("ERROR") > -1){
		alert("We could not locate this City (" + $("SelectedCity").value + ") in our database. Please select a County and then choose from the City pulldown.");
		return null;
    }
    // If no errors, select the matching option
    var CountyOptions = $("CountyList").options;
    for(i = 0; i < CountyOptions.length; i++){
		if(CountyOptions[i].value == CountyName){
			$("CountyList").selectedIndex = i;
			break;
		}
    }
    // Now populate the list of cities based ont he matching option
    callAjax("Realm=Misc&Action=CityList&County=" + escape(trim(CountyName)), "processCityList");
}

function processClimateZone(Result){
    var CZ = Result.responseXML.getElementsByTagName("ClimateZone");
    var CZValue = CZ[0].childNodes[0].nodeValue;
    $("CZ").innerHTML = CZValue
    $("LocationCZ").value = CZValue;
    if(CZValue.indexOf("ERROR") > -1){
		alert("We were unable to determine the Climate Zone for the selected City (" + $("SelectedCity").value + "). Please select a County and then choose from the City pulldown.");
		return null;
    }
}

/*********************************************************/
/**************  city / cz lookup by zip  ****************/
/*********************************************************/

function lookupZipInfo( ZipValueID ){
	var Zip = $("ZipSelect").value.substring(0,5);
	if( Zip.length != 5 ){
		return false;
	}
	$(ZipValueID).value = Zip;
	callAjax("Realm=Misc&Action=SearchCityByZip&Zip=" + Zip, "populateZipInfo");
}
function populateZipInfo(Result){
	// blank out the current city value
	$("ZipCity").value = "";
	if(!Result.responseXML){
		// hide the CityHelp div
		$("CityHelp").style.display = "block";
		return null;
	}
	var Info = Result.responseXML.getElementsByTagName("ZipInfo");
	$("ZipCZ").value = Info[0].getAttribute("CZ");
	// fill it with the returned value
	$("ZipCity").value = Info[0].childNodes[0].nodeValue;
	// hide the CityHelp div
	$("CityHelp").style.display = "none";
}

function validateZip( ZipValueID ){
	var Zip = $(ZipValueID).value;
	callAjax("Realm=Misc&Action=SearchCityByZip&Zip=" + escape(Zip), "processValidateZip", "warnInvalidZip");
}
function processValidateZip( Result ){
	if(!Result.responseXML){
		return null;
	}
	var Info = Result.responseXML.getElementsByTagName("ZipInfo");
	if( !Info[0].getAttribute("Code").length ){
		// blank out the current city value
		$("ZipCity").value = "";
		$("ZipCZ").value = Info[0].getAttribute("CZ");
		alert("The zip code for this location is not valid. Please enter a new zip code.");
		return false;
	}
}

function warnInvalidZip( Result ){
	alert("The zip code is not valid: " + Result.toSource());
}

/*********************************************************/
/*******************  scrub warnings  ********************/
/*********************************************************/

function confirmScrubSubscription(SubscriptionID){
    if(confirm("Are you sure? This will scrub this Subscription, all its Members and all their auth keys. Press OK to scrub.")){
		document.location="/?Realm=Subscription&Action=Scrub&SubscriptionID="+SubscriptionID;
    }
}

function confirmScrubOrgChart(MemberID){
    if(confirm("Are you sure? This will scrub this OrgChart record. Press OK to scrub.")){
		document.location="/?Realm=Member&Action=ScrubOrgChart&MemberID="+MemberID;
    }
}

function confirmScrubMember(MemberID){
    if(confirm("Are you sure? This will scrub this Member, all associated OrgChart records and all associated auth keys. Press OK to scrub.")){
		document.location="/?Realm=Member&Action=ScrubMember&MemberID="+MemberID;
    }
}

function confirmResetOrgChart(MemberID){
    if(confirm("Are you sure? This will reset the entire OrgChart, using this Member as the top of the tree. Press OK to reset.")){
		document.location="/?Realm=Member&Action=ResetOrgChart&MemberID="+MemberID;
    }
}

function confirmScrubProject(ProjectID){
    if(confirm("Are you sure? This will scrub this Project, its Plans, any Structures and all associated test data. Press OK to scrub.")){
		document.location="/?Realm=Project&Action=Scrub&ProjectID="+ProjectID;
    }
}

function confirmScrubPlan(PlanID){
    if(confirm("Are you sure? This will scrub this Plan, its data, any Structures and all associated test data. Press OK to scrub.")){
		document.location="/?Realm=Plan&Action=Scrub&PlanID="+PlanID;
    }
}

function confirmReparsePlan(PlanID){
    if(confirm("Are you sure? This will reparse this Plan\"s data from its source file. Press OK to reparse.")){
		document.location="/?Realm=Plan&Action=Reparse&PlanID="+PlanID;
    }
}

function confirmRegenContract(PlanID){
    if(confirm("Are you sure? This will regenerate this plan\"s contract measures based on current plan data. Press OK to regenerate.")){
		document.location="/?Realm=Plan&Action=RegenContract&PlanID="+PlanID;
    }
}

function confirmScrubSite(SiteID){
    if(confirm("Are you sure? This will scrub this Structure and all associated test data. Press OK to scrub.")){
		document.location="/?Realm=Site&Action=ScrubSite&SiteID="+SiteID;
    }
}

function confirmScrubSiteTests(SiteID){
    if(confirm("Are you sure? This will scrub all test data for this Structure. Press OK to scrub.")){
		document.location="/?Realm=Site&Action=ScrubTests&SiteID="+SiteID;
    }
}

function confirmResetLogin(MemberID){
    if(confirm("Are you sure? This will reset this Member\"s Login and Password. Press OK to reset.")){
		document.location="/?Realm=Member&Action=ResetLogin&MemberID="+MemberID;
    }
}

function confirmScrubCourse(CourseID){
    if(confirm("Are you sure? This will scrub this Course and all associated Registrations. Press OK to scrub.")){
		document.location="/?Realm=Course&Action=ScrubCourse&CourseID="+CourseID;
    }
}

function confirmScrubBuilder(BuilderID){
    if(confirm("Are you sure? This will delete this Builder and cannot be undone. Press OK to delete.")){
		document.location="/?Realm=Builder&Action=Scrub&BuilderID="+BuilderID;
    }
}

function confirmScrubInstaller(InstallerID){
    if(confirm("Are you sure? This will delete this Installer and all Alterations associated with it and cannot be undone. Press OK to delete.")){
		document.location="/?Realm=Changeout&Action=ScrubInstaller&InstallerID="+InstallerID;
    }
}

function confirmScrubChangeout(ChangeoutID){
    if(confirm("Are you sure? This will delete this Alteration (and its Homeowner and Tests) and cannot be undone. Press OK to delete.")){
		document.location="/?Realm=Changeout&Action=ScrubChangeout&ChangeoutID="+ChangeoutID;
    }
}

function confirmScrubChangeoutTests(ChangeoutID){
    if(confirm("Are you sure? This will delete this Alteration's Tests and cannot be undone. Press OK to delete.")){
		document.location="/?Realm=Changeout&Action=ScrubTests&ChangeoutID="+ChangeoutID;
    }
}

