OBJ_INNERHTML = 1;
var OBJ_VALUE = 2;
var OBJ_RETURN_VAL = 3;
var isError = false;
var isComplete = false;

// Creates the HTTP Object
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
} 

// Instantiates the HTTP Object and assigns as a global var
var http = createRequestObject();

//Sends the request to the server and updates the appropriate object
function sendRequest(serverPage, objID, type, callBack) {
	isError = false;
	http.open("GET", serverPage);
	http.onreadystatechange = function() {
		if (http.readyState == 4 && http.status == 200) {
			if (OBJ_VALUE == type) {
				if (isErrorResponse(trim(http.responseText))) {
					alert("Error Completing Transaction");
					isError = true;
				} else {
					var obj = document.getElementById(objID);
					obj.value = trim(http.responseText);
				}
			} else if (OBJ_INNERHTML == type) {
				var obj = document.getElementById(objID);
				obj.innerHTML = trim(http.responseText);
			} else if (OBJ_RETURN_VAL == type) {
				//this.call(callBack);
				
				callBack.call(this, http.responseText);
			} 
		} else if (http.readyState == 4 && http.status != 200) {
			alert("Error Completing Transaction");
			isError = true;
		}
	};
	
	http.send(null);
}

// Loops though form elements and creates a GET URL
function sendFormRequest(theForm, objID, type, callBack) {
	var url = theForm.action + "?1=1";
	for (var i=0; i< theForm.elements.length; i++) {
		if(theForm.elements[i].name.length > 0) {
			url += "&" + theForm.elements[i].name + "=" + theForm.elements[i].value;
		}
	}
	
	sendRequest(url, objID, type,callBack);
}

function changeFontSize(size) {
	var url = window.location.href;
	url = url.replace(/[&]?fontSize=[0-9]/g, "");
	if (url.indexOf("#") > 0) url = url.substring(0, url.indexOf("#"));
	url += (url.indexOf("?") > 0) ? "&" : "?";
	window.location = url + "fontSize=" + size;
}

function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
			anchor.target = "_blank";
	}
}
window.onload = externalLinks;

//simple URL parameter getter method.
function getURLParam(strParamName) {
	var strReturn = "";
	var strHref = window.location.href;
	if (strHref.indexOf("?") > -1 ) {
		var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
		var aQueryString = strQueryString.split("&");
		for (var iParam = 0; iParam < aQueryString.length; iParam++ ) {
			if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ) {
				var aParam = aQueryString[iParam].split("=");
				strReturn = aParam[1];
				break;
			}
		}
	}
	return unescape(strReturn);
} 

// Checks to ensure all values are filled out and submits the form
function submitElement(theForm, message) {
	if (checkVals(theForm, message)) {
		theForm.submit();
	} else {
		return false;
	}
}

// Checks to ensure all values are filled out and submits the form
function submitContact(theForm, message, commJS) {
	var cs = theForm.collectionStatement;
	if (cs != null)	{
		if (cs.checked == false) {
			alert(commJS);
			return false;
		}
	}
	
	cs = theForm.orgConsentStatement;
	if (cs != null) {
		if (cs.checked == false) {
			alert(commJS);
			return false;
		}
	}
	
	if (checkVals(theForm, message)) {
		//require a valid email address if this field is present on the form (and required)
		try {
			if (theForm.pfl_EMAIL_ADDRESS_TXT != null 
					&& theForm.pfl_EMAIL_ADDRESS_TXT.id.length > 0 
					&& !checkEmail(theForm.pfl_EMAIL_ADDRESS_TXT.value)) {
				alert(message + " \"" + theForm.pfl_EMAIL_ADDRESS_TXT.id.replace(/_/g, " ") + "\"");
				return false;
			}
		} catch (Err) {}
		
		theForm.submit();
	} else {
		return false;
	}
}

// Checks to ensure all values are filled out and submits the form
// owned by REGISTRATION module
// TODO: add JS validation to fields based on attribute, validation=""
function submitRegistration(theForm, message, commJS, passwordJS) {
	if (!checkVals(theForm, message)) return false;
	
	var passwd = theForm.elements["Password"];
	if (passwd != null) {
		var passwd2 = theForm.elements["PasswordConfirm"];
		if (passwd2 == null || passwd.value == "" || passwd.value != passwd2.value) {
			alert(passwordJS);
			return false;
		}
	}
	
	var cs = theForm.elements["COMMCONSENTFLG"];
	if (cs != null)	{
		if (cs.checked == false) {
			alert(commJS);
			return false;
		}
	} else {
		cs = theForm.elements["COLLECTIONFLG"];
		if (cs != null)	{
			if (cs.checked == false) {
				alert(commJS);
				return false;
			}
		}
	}
	
	theForm.submit();
}

// Checks the Form Elements that have an ID and makes sure the field 
//has data associated
var skipIds = Array();
	skipIds["COMMCONSENTFLG"] = 0;
	skipIds["Password"] = 0;
	skipIds["PasswordConfirm"] = 0;
function checkVals(theForm, message) {
	for (i=0; i < theForm.elements.length; i++) {
		var promptUser = false;
		node = theForm.elements[i];
		
		if (node.id != null && node.id != "") {
			//this test allows checkVals to bypass certain form fields, allowing the parent 
			//method to do other things with them
			if (node.id in skipIds) continue;
			
			// Check the radio buttons for a value selected
			if (node.type == "radio" || node.type == "checkbox") {
				fields = theForm[node.name];
				radioSet = false;
				
				// If there is only one element to the radio button, check it
				// like a normal field otherwise loop the elements
				if (fields.length == undefined) {
					radioSet = (fields.checked);
				} else {
					for (j=0; j < fields.length; j++) {
						if (fields[j].checked) {
							radioSet = true;
							break;
						}
					}
				}
				
				promptUser = (!radioSet);
				
			} else {
				promptUser = (node.value == null || node.value == "");
			}
			
			// Display a message to the user that required elements are not filled out
			if (promptUser) {
				var fieldNm = node.id.replace(/_/g, " ");  //replace word separators
				fieldNm = fieldNm.replace(/<[^>]*>/g," "); //strip HTML
				fieldNm = fieldNm.replace(/&nbsp;/g," ");  //strip &nbsp;
				
				alert(message + " \"" + fieldNm + "\"");
				node.focus();
				return false;
			}
		}
	}
	
	return true;
}

// Shows and hides the appropriate elements.
// theEle - <a> tag which has the call to this method.  Can usually use
//          The word "this" in the call
// which - element to hide/show.  Usually document.getElementById(val)
function toggleElement(theEle) {
	var which = fetch_object(theEle);
	if (which.style.display == "none")	{
		which.style.display = "";
	} else {
		which.style.display = "none";
	}
}
function toggleElementCtrl(theEle, showIt) {
	var which = fetch_object(theEle);
	if (showIt)	{
		which.style.display = "";
	} else {
		which.style.display = "none";
	}
}

// same as admin JS toggleView function
function toggleView(theEle, which) {
	if (which.style.display == "none")	{
		which.style.display = "";
		document.getElementById(theEle.id).innerHTML = "-";
	} else {
		which.style.display = "none";
		document.getElementById(theEle.id).innerHTML = "+";
	}
}

function leaveSite(site) {
	leaveSite(site,false);
}
function leaveSite(site,newWindow) {
	var notice = "This link will take you to a Web site to which this Privacy Policy does not apply. You are solely responsible for your interactions with that Web site. Press OK to continue.";
	if (confirm(notice)) {
		if (newWindow) window.open(site,"_blank");
		else window.location = site;
	}
}

/* Opens the site in a new window with low control */
function openSite(site,width,height,style) {
	var newWindow = window.open(site,'mywindow');
}

/* Opens the site in a new window with high control */
function openContent(site,width,height,style) {
	var newWindow = window.open(site,'mywindow','width=' + width + ',height=' + height + ',menubar=' + style + ',status=no,scrollbars=yes');
}

/* Opens the site in a new window with total control */
function openContent(site,name,style) {
	if (name == null) name = "mywindow";
	var newWindow = window.open(site, name, style);
}

/* email validator */
function checkEmail(str) {
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;
	return (filter.test(str));  //returns true if valid, false if not
}

//returns number-only equivellent of string passed (strips all non-numerics)
function parseInteger(field) {
	var length1 = field.length;
	var val = "";
	for (i=0; i < length1; i++) {
		val = field.charCodeAt(i);
		if (!(val > 47 && val < 58)) {
			field = field.replace(field.charAt(i), "");
			i = i - 1;
			length1 = length1 - 1;
		}
	}
	return field;
}

// function to emulate document.getElementById
function fetch_object(idname) {
	if (document.getElementById) {
		return document.getElementById(idname);
	
	} else if (document.all) {
		return document.all[idname];
	
	} else if (document.layers) {
		return document.layers[idname];

	} else {
		return null;
	}
}

function searchSite(form, msg) {
	var data = form.searchData.value;
	form.elements['searchField'].value = data;
	if (data == "") {
		alert(msg);
	} else {
		form.submit();
	}
}

// displays the current section of the docuemnt and turns the others off
function changePage(pageNum, numPages) {
	for (i=1; i <= numPages; i++)	{
		var id = "page" + i;
		try {
			var obj = fetch_object(id);
			if (i == pageNum) {
				obj.style.display="block";
			} else {
				obj.style.display="none";
			}
		} catch (err) {}
	}
}

// Shows and hides the appropriate elements.
// theEle - <a> tag which has the call to this method.  Can usually use
//          The word "this" in the call
// which - element to hide/show.  Usually document.getElementById(val)
function toggleMapElement(disp, theEle, show, hide) {
	var which = fetch_object(theEle);
	if (which.style.display == "none")	{
		document.getElementById(disp.id).innerHTML = hide;
		which.style.display = "";
	} else {
		which.style.display = "none";
		document.getElementById(disp.id).innerHTML = show;
	}
}

// Assigns the selected ambiguity to the form
function assignAmb(theForm, type, addr, city, state, zip) {
	theForm[type + "Address"].value = addr;
	theForm[type + "City"].value = city;
	theForm[type + "StateProvince"].value = state;
	theForm[type + "PostalCode"].value = zip;
}

// Assigns a specific lat/long
function assignLatLong(theForm, type, latitude, longitude) {
	if (theForm.useMapLoc.checked) {
		theForm[type + "Latitude"].value = latitude;
		theForm[type + "Longitude"].value = longitude;
	} else {
		theForm[type + "Latitude"].value = "";
		theForm[type + "Longitude"].value = "";
	}
}

// Checks or unchecks boxes in the supplied ele
function checkAllBoxes(ele, on, otherEle) {
	if (ele.length == null) ele.checked = on;
	
	for(i=0; i < ele.length; i++) {
		ele[i].checked = on;
	}
	
	if (otherEle != null) {
		otherEle.checked = on;
		showOptOutOther(otherEle.checked);
	}

}
function showOptOutOther(boolChecked) {
	var otherBox = document.getElementById("optOutOther");
	if (boolChecked) {
		otherBox.style.visibility = "hidden";	
		otherBox.style.display = "none";		
	} else {
		otherBox.style.visibility = "visible";
		otherBox.style.display = "block";				
	}
}


// Checks or unchecks boxes in the supplied ele
function toggleAllBoxes(ele) {
	for(i=0; i < ele.length; i++) {
		if(ele[i].checked) {
			ele[i].checked = false;
		} else {
			ele[i].checked = true;
		}
	}

}

// Checks a string value to determine if it is
// formatted as a valid date.
function isDate(sDate) {

	if (! Date.parse(sDate)) {
		return false;
	} else {
		return true;
	}
	
}

// Parses a string into a slash-pattern date and validates the month/day/year ranges.
// Accommodates a date string in 'slashed' (MM/DD/YYYY) or non-slashed (MMDDYYYY).
// format.  Returns either a zero-length String or the valid date in slash-pattern (MM/DD/YYYY)
// formatted String.
function parseDate(inDate) {
	
	var returnedDate = '';
	var dateLength = inDate.length;

	if (dateLength < 6 || dateLength > 10) {
		return returnedDate;
	}
		
	var firstSlash = inDate.indexOf('/');
	var lastSlash = 0;
	var month = 0;
	var day = 0;
	var year = 0;
	
	if (firstSlash > 0) {
		
		lastSlash = inDate.lastIndexOf('/');
		month = parseInt(inDate.substr(0,firstSlash));
		day = parseInt(inDate.substring((firstSlash + 1),lastSlash));
		year = parseInt(inDate.substring(lastSlash + 1));
		
	} else {
		
		switch(dateLength) {
			case(6):
				month = parseInt(inDate.substr(0,1));
				day = parseInt(inDate.substr(1,1));
				break;
			case(7):
				month = parseInt(inDate.substr(0,2));
				day = parseInt(inDate.substr(2,1));
				break;
			case(8):
				month = parseInt(inDate.substr(0,2));
				day = parseInt(inDate.substr(2,2));
				break;
		}
		
		year = parseInt(inDate.substring((dateLength - 4)));
			
	}
	
	if (isNaN(year) || (year < 1970) || (year > 2100)) {
		return returnedDate;
	}
	
	if (isNaN(month) || (month < 1) || (month > 12)) {
		return returnedDate;
	}
	
	var leapYear = false;
	
	if (year % 4 == 0) {
		if (year % 100 == 0) {
			if (year % 400 == 0) {
				leapYear = true;
			}
		} else {
			leapYear = true;
		} 
	}
	
	if (isNaN(day) || (day < 1)) {
		return returnedDate; 
	} else {
		switch(month) {
			case(1):
			case(3):
			case(5):
			case(7):
			case(8):
			case(10):
			case(12):
				if (day > 31) {
					return returnedDate;
				}
				break;
			case(4):
			case(6):
			case(9):
			case(11):
				if (day > 30) {
					return returnedDate;
				}
				break;
			case(2):
				if (leapYear && (day > 29)) {
					return returnedDate;
				} else {
					if (day > 28) {
						return returnedDate;
					}
				}
				break;
		}
	}	
	
	returnedDate = month + "/" + day + "/" + year;
	return returnedDate;
	
}

// Looks up the appropriate style and gets the background color
function getColor(val) {
	var color = "";
	var mysheet=document.styleSheets[0];
	var rules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
	var totalrules=mysheet.cssRules? mysheet.cssRules.length : mysheet.rules.length;
	
	for (i=0; i < totalrules; i++) {
		var myText = rules[i].selectorText.toLowerCase();
		if (myText.indexOf(val.toLowerCase()) > -1) color = rules[i].style.backgroundColor;
	}
	
	return(color);
}

// refresh state select list based on country code
function refreshStateList(theForm, actionId, country, type, callBack) {
	var url = "/sb/json?1=1&actionId=${actionId}&countryCode=" + country + "&listType=" + type;
	sendRequest(url, null, OBJ_RETURN_VAL, callBack);
}

//email-a-friend form expandability
var lastRow = 2;
var fileNum = 1;
function addRecipient(context, name, email, ele, rowNo) {
	tempNm = name;
	tempEmail = email;
	if (name.indexOf('apos') > -1) {
		tempNm = name.replace('apos','&#39;');
	}
	if (email.indexOf('apos') > -1) {
		tempEmail = email.replace('apos','&#39;');
	}
	fileNum = rowNo-1;
	var newRowId = "row-" + rowNo;
	var row = ele.insertRow(rowNo);
		row.id = newRowId;
		row.className = "smallRow";
	var cell1 = row.insertCell(0);
		cell1.innerHTML = tempNm + ":"; //name label
		cell1.className ="sForm";
	var cell2 = row.insertCell(1);
		cell2.innerHTML = "&nbsp;"; //spacer
	var cell3 = row.insertCell(2);
		cell3.innerHTML = "<input type='text' name='rcptNm' class='emailFriendField'/>"; //name field
		cell3.className ="form-ele";
	var cell4 = row.insertCell(3);
		cell4.innerHTML = "&nbsp;"; //spacer
	var cell5 = row.insertCell(4);
		cell5.innerHTML = tempEmail + ":"; //email label
		cell5.className ="sForm";
	var cell6 = row.insertCell(5);
		cell6.innerHTML = "&nbsp;"; //spacer
	var cell7 = row.insertCell(6);
		cell7.innerHTML = "<input type='text' name='rcptEml' class='emailFriendField'/>"; //email field
		cell7.className ="form-ele";
	var cell8 = row.insertCell(7);
		cell8.innerHTML = "<a style=\"font-weight:bold; text-decoration:none;\" href=\"javascript:removeRecipient(fetch_object('emailTable'),'" + newRowId + "');\">X</a>"; //delete icon
	return;
}
function removeRecipient(ele, rowId) {
	for (x=0; ele.rows[x] != null; x++) {
		if (ele.rows[x].id == rowId) {
			ele.deleteRow(x);
			lastRow--;
			break;
		}
	}
	return;
}

//Email-a-Friend form VERTICAL expansion
var lastRowVertical = 4;
var fileNumVertical = 1;
function addRecipientVertical(context, name, email, ele, rowNo) {
	tempNm = name;
	tempEmail = email;
	if (name.indexOf('apos') > -1) {
		tempNm = name.replace('apos','&#39;');
	}
	if (email.indexOf('apos') > -1) {
		tempEmail = email.replace('apos','&#39;');
	}
	fileNumVertical++;
	var newRowId = "row-" + rowNo;
	var row = ele.insertRow(rowNo);
		row.id = newRowId;
		row.className = "smallRow";
	var cell1 = row.insertCell(0);
		cell1.innerHTML = tempNm + ":"; //name label
		cell1.className ="sForm";
	var cell2 = row.insertCell(1);
		cell2.innerHTML = "&nbsp;"; //spacer
	var cell3 = row.insertCell(2);
		cell3.innerHTML = "<input type='text' name='rcptNm' class='emailFriendField'/>"; //name field
		cell3.className ="form-ele";
	var cell4 = row.insertCell(3);
		cell4.innerHTML = "<a style=\"font-weight:bold; text-decoration:none;\" href=\"javascript:removeRecipientVertical(fetch_object('emailTable'),'" + newRowId + "');\">X</a>"; //delete icon
		rowNo++;
		lastRowVertical++;
		newRowId = "row-" + rowNo;
	var row1 = ele.insertRow(rowNo);
		row1.id = newRowId;
		row1.className="smallRow";
	var cell1 = row1.insertCell(0);
		cell1.innerHTML = tempEmail + ":"; //email label
		cell1.className ="sForm";
	var cell2 = row1.insertCell(1);
		cell2.innerHTML = "&nbsp;"; //spacer
	var cell3 = row1.insertCell(2);
		cell3.innerHTML = "<input type='text' name='rcptEml' class='emailFriendField'/>"; //email field
		cell3.className ="form-ele";
	var cell4 = row1.insertCell(3);
		cell4.innerHTML = "&nbsp;"; //spacer
	return;
	lastRowVertical++;
}

//Email-a-Friend form VERTICAL recipient removal
function removeRecipientVertical(ele, rowId) {
	for (x=0; ele.rows[x] != null; x++) {
		if (ele.rows[x].id == rowId) {
			for (y=0; y<2; y++) {
				ele.deleteRow(x);
				lastRowVertical--;
			}
			break;
		}
	}
	return;
}

//Clears form fields, including select lists.
// Based on example from http://www.javascript-coder.com/javascript-form/javascript-reset-form.htm
function clearForm(theForm) {
	var ele = theForm.elements;
	
	for (i = 0; i < ele.length; i++) {
		var eleType = ele[i].type.toLowerCase();
		
		switch(eleType) {
			case "text":
			case "textarea":
				ele[i].value = "";
				break;
			
			case "radio":
			case "checkbox":
				if (ele[i].checked) {
					ele[i].checked = false;
				}
				break;
				
			case "select-one":
			case "select-multi":
				ele[i].selectedIndex = -1;
				break;
				
			default:
				break;
		}
	}
}

/* PSP site graphical menu support */
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/* allows for multiple functions to be executed upon window.onload without conflict
- author: Simon Willison; http://simonwillison.net/ */
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

