
/**
* The new and improved SubmitForm function
* Call this with options for the what you want the form to do
* possible options:
*  : form - the form object to be submitted
*  : target - a target like _blank or _self
*  : action - action URL for the submit
*  : confirm - a confirmation text string
*  : reset - true or false to reset hidden fields
*  : fields - a hash of key/value pairs for fields to be set on the form
*  : redirect - true if you want the form to redirect to the action parameter
*  : entype - encoding type
*/
function SubmitForm(options) {
	if(!options){
		options = [];
	}
	var frm;
	if(!options.form){
		frm = document.forms[0];
	}else{
		frm = options.form;
	}

	if(options.confirm && !confirm(options.confirm)){
		//bail if the confirmation returns false
		return;
	}

	if(options.reset){
		ResetHiddenFields();
	}
	if(options.fields){
		//used to return hidden fields to their original state in case the user hits 'back'
		var savedFields = {};
		for(var fieldName in options.fields){
			var val = options.fields[fieldName];
			var fieldObj = frm.elements[fieldName];
			if (fieldObj) {
				if (fieldObj.options) {
					var selected = false;
					for(var i = 0; i < fieldObj.length; i++) {
						if (fieldObj.options[i].value == val) {
							fieldObj.selectedIndex = i;
							selected = true;
						}
					}
					if (!selected) {
						var option =  new Option('', val);
						fieldObj.options[fieldObj.length] = option;
						fieldObj.selectedIndex = fieldObj.length - 1;
					}
				}
				else {	//AE 10/15/08 add the following block to eliminate dynamic select list/autocomplete items
					if (typeof document.getElementsByName(fieldName+"[]") == "object" && document.getElementsByName(fieldName+"[]") .length) {
						var inputs = document.getElementsByName(fieldName+"[]");
						for (var i=0; i< inputs.length; i++) {
							inputs[i].parentNode.remove(inputs[i]);
						}
						fieldObj = document.createElement("input");
						fieldObj.type = "hidden";
						fieldObj.name = fieldName+"[]";
						fieldObj.value = val;
						frm.appendChild(fieldObj);
						//store the reference to the field object to remove it after the submit
						savedFields[fieldName] = fieldObj;
					}
					else {
						savedFields[fieldName] = fieldObj.value;
						fieldObj.value = val;
					}
				}
			} else {
				if (Object.isArray(val) && (fieldName.endsWith('[]'))) {
					savedFields[fieldName] = [];
					val.each(function iterate(value,index) {
						fieldObj = document.createElement("input");
						fieldObj.type = "hidden";
						fieldObj.name = fieldName;
						fieldObj.value = value;
						frm.appendChild(fieldObj);
						//store the reference to the field object to remove it after the submit
						savedFields[fieldName][index] = fieldObj;
					});
				}
				else {
					fieldObj = document.createElement("input");
					fieldObj.type = "hidden";
					fieldObj.name = fieldName;
					fieldObj.value = val;
					frm.appendChild(fieldObj);
					//store the reference to the field object to remove it after the submit
					savedFields[fieldName] = fieldObj;
				}
			}
		}
	}
	if (typeof ogridEditor == "undefined") {
		ogridEditor = false;
	}
	if(typeof frm.onsubmit == "function" && !frm.onsubmit() &&  !ogridEditor){
		//bail if the onsubmit function returns false
		return;
	}

	if(typeof options.validate == "function" && !options.validate()){
		//bail if the validate function returns false
		return;
	}
	if (options.enctype) {
		var oldEncType = frm.enctype;
		frm.enctype = options.enctype;
		frm.encoding = options.enctype; //stupid IE doesn't play well - we have to set the encoding field instead of enctype
	}
	if(options.target){
		var oldTarget = frm.target;
		frm.target = options.target;
		
		if( Prototype.Browser.WebKit ){	//JR 1/25/2010 - Fixes https://bugs.webkit.org/show_bug.cgi?id=28633
			options.action = ( options.action || window.location.href );
			if( ! /\?/.test(options.action) ){
				options.action += '?';
			}
			options.action += '&webkit=';
			if( window.WebKitSubmitFormSwitch ){
				options.action += '1';
			}
			window.WebKitSubmitFormSwitch = ! window.WebKitSubmitFormSwitch;
		}
	}
	
	if(options.action){
		if(options.redirect){
			frm.SaveAndGo.value = options.action;
		}else{
			var oldAction = frm.action;
			frm.action = options.action;
		}
	}
	
	for (var i = 0; i<window.beforeSubmits.length; i++ ) {
		if (typeof window.beforeSubmits[i] == "function") {
			window.beforeSubmits[i]();
		}
	}
	
	frm.submit();
	
	for (var i = 0; i<window.afterSubmits.length; i++ ) {
		if (typeof window.afterSubmits[i] == "function") {
			window.afterSubmits[i]();
		}
	}
	
	//restor targets and actions post submit
	if(options.target){
		frm.target = oldTarget;
	}
	if(options.action && !options.redirect){
		frm.action = oldAction;
	}
	if (options.enctype) {
		frm.enctype = oldEncType;
	}
	//restore saved field names post submit

	if(options.fields){
		for(var fieldName in savedFields){
			if(Object.isArray(savedFields[fieldName])){
				savedFields[fieldName].each(function clear(element) {
					element.value = "";
				});
			}
			else if(typeof savedFields[fieldName] == "object"){
				//reset the value of a field created on the fly
				savedFields[fieldName].value = "";
			}else{
				frm.elements[fieldName].value = savedFields[fieldName];
			}
		}
	}
}

/**
 * JR 5/25/2010 - Before using this function, please consider using RenderView() or ControllerRequest()
 * @param options
 * @return
 */
function SubmitFormAjax(options) {
	options = options || {};
	var message = options.message || 'Saving...';
	var frm = options.form || document.forms[0];
	var action = options.action || window.location.href;
	var onSuccess = options.onSuccess || Prototype.emptyFunction;
	
	if(options.confirm && !confirm(options.confirm)){
		//bail if the confirmation returns false
		return;
	}

	if(options.reset){
		ResetHiddenFields();
	}
	
	if(typeof options.validate == "function" && !options.validate()){
		//bail if the validate function returns false
		return;
	}
	
	for(var i = 0; i<window.beforeSubmits.length; i++ ) {
		if(typeof window.beforeSubmits[i] == "function") {
			window.beforeSubmits[i]();
		}
	}
	
	if(typeof YUIPopupFormProvider != 'undefined'){
		YUIPopupFormProvider.SetLoadingModalForm(message);
	}
	new Ajax.Request( action, {
		evalJS: false,
		evalJSON: false,
		parameters: Object.extend( Form.serialize(frm, true), options.fields || {} ),
		onSuccess: function onSuccess_SubmitFormAjax(){
			onSuccess();
			if(typeof YUIPopupFormProvider != 'undefined'){
				YUIPopupFormProvider.DisposeModalForm();
			}
		},
		onFailure: function onFailure_SubmitFormAjax(){
			if(typeof YUIPopupFormProvider != 'undefined'){
				YUIPopupFormProvider.SetErrorModalForm();
			}
		},
		onException: function onException_SubmitFormAjax(){
			if(typeof YUIPopupFormProvider != 'undefined'){
				YUIPopupFormProvider.SetErrorModalForm();
			}
		}
	} );
	
	for(var i = 0; i<window.afterSubmits.length; i++ ) {
		if(typeof window.afterSubmits[i] == "function") {
			window.afterSubmits[i]();
		}
	}
}

window.beforeSubmits = [];
window.afterSubmits = [];

/**
 * Override me!
 */
function ResetHiddenFields(){
	
}

/**
 * Insert a hidden form variable (to be used by child document (e.g. iframe)
 * 	workaround for IE not correctly appending nodes into parents objects...
 * added by AE 4/13/09
 */
function InsertHiddenFormVariable(sName,vValue) {
		var oInput = document.createElement('input');
		oInput.type = 'hidden';
		oInput.value = vValue;
		oInput.name = sName;
		oInput.id = sName;
		document.forms[0].appendChild(oInput);
}
function getFormFieldValue(oField) {
	//alert(oField.name + \'=\' + oField.value);
	if((oField.type == "checkbox" || oField.type == "radio") && !oField.checked && typeof oField.value != "undefined"){
		return "";
	}
	return oField.value;
}

function getFormFields() {
	sFields = "";
	for (var i = 0; i < document.forms[0].elements.length; i++) {
		oField = document.forms[0].elements[i];
		if(!oField.name){
			continue;
		}
		sValue = getFormFieldValue(oField);
		if (sValue != "") {
			sFields += encodeURIComponent(oField.name) + "=" + encodeURIComponent(sValue) + "&";
		}
	}
	//JG Added a variable so pages can see if they are from autosave or not
	sFields += "AjaxAutosave=1";
	return sFields;
}

function openRelatedKeywordsWindow(url) {
	var f = document.forms[0].strKey1;
	if(f) {
		if(f.value && f.value.strip()) {
			YUIPopupFormProvider.ShowModalForm('<iframe src="/c/maps/showRelatedKeywords.php?strkey1=' + escape(f.value.strip()) + '" frameborder="0" height="300" width="100%"></iframe>', {
				Header: 'Related Keywords',
				Footer: '<div class="AtlasButtonWrapper"><a class="AtlasButton" href="javascript:YUIPopupFormProvider.HideModalForm();">Done</a></div>',
				height: 300,
				width: 400
			});
		}
		else {
			alert('Enter a term to look up related terms in the thesaurus');
			f.focus();
		}
	}
}

function ClusterOff(){
	document.forms[0].bClusterOff.value=1;
	SubmitForm();
}

function goSummary(sSummaryBy,iID,sNextSummary,sResults) {
	var f=document.forms[0];
	ResetHiddenFields();
	f.results.value='summary';
	if (sResults!='') {
		f.results.value=sResults;
	}

	if (sNextSummary!='') {
		f.SummaryBy.value=sNextSummary;
	}
	if (sSummaryBy!=0) {
		SubmitWithFilterItem(sSummaryBy,iID);
	}
} // goSummary


function goDrillDown(sSummaryBy,iID) {
	var f=document.forms[0];
	ResetHiddenFields();
	switch(sSummaryBy) {
		case 'grade':
		f.SummaryBy.value='subject';
		break;
		case 'subject':
		f.SummaryBy.value='school';
		if (typeof(bIsPLC)!='undefined') {
			f.SummaryBy.value='grade';
		}
		break;
		case 'school':
		if (typeof(bIsPLC)!='undefined') {
			f.SummaryBy.value='grade'; // plc
		} else {
			f.SummaryBy.value='teacher';
		}
		break;
		case 'teacher':
		f.SummaryBy.value='grade';
		break;
		//default:
	}

	// all drilldowns !set
	// FIX: if (f.GradeID.value=='' || f.SubjectID.value=='' || f.SchoolID.value=='') {
	if ( ! ((document.forms[0].elements["lstGrade[]"] && document.forms[0].elements["lstGrade[]"].value!='') &&
	(document.forms[0].elements["lstSubject[]"] && document.forms[0].elements["lstSubject[]"].value!='') &&
	(document.forms[0].elements["lstSchool[]"] && document.forms[0].elements["lstSchool[]"].value!='')	)  ) {
		// advance thru previously set drill-down values
		if (f.SummaryBy.value=='grade' && document.forms[0].elements["lstGrade[]"] && document.forms[0].elements["lstGrade[]"].value!='') {
			f.SummaryBy.value='subject';
		}
		if (f.SummaryBy.value=='subject' && document.forms[0].elements["lstSubject[]"] && document.forms[0].elements["lstSubject[]"].value!='') {
			f.SummaryBy.value='school';
			//alert('now f.SB.v:'+f.SummaryBy.value);
		}
		if (f.SummaryBy.value=='school' && document.forms[0].elements["lstSchool[]"] && document.forms[0].elements["lstSchool[]"].value!='') {
			if (typeof(bIsPLC)!='undefined') {
				f.SummaryBy.value='grade'; // plc
			} else {
				f.SummaryBy.value='teacher';
			}
		}
		if (f.SummaryBy.value=='teacher' && document.forms[0].elements["lstTeacher[]"] && document.forms[0].elements["lstTeacher[]"].value!='') {
			f.SummaryBy.value='grade';
		}
		if (f.SummaryBy.value=='grade' && document.forms[0].elements["lstGrade[]"] && document.forms[0].elements["lstGrade[]"].value!='') {
			f.SummaryBy.value='subject';
		}
		if (f.SummaryBy.value=='subject' && document.forms[0].elements["lstSubject[]"] && document.forms[0].elements["lstSubject[]"].value!='') {
			f.SummaryBy.value='school';
		}
	} // all drilldowns !set
	f.results.value='full';
	if (sSummaryBy!=0) {
		SubmitWithFilterItem(sSummaryBy,iID);
	}
	//f.Page.value=1;//AE this page var removed so remove this erroraneous call...
	//f.submit(); //AE SubmitWithFilterItem now submits form
}

function SubmitWithFilterItem(sSummaryBy,iID) {
	//AE: call UIDynamic selects instead of selectItem
	if ( sSummaryBy=='grade' ) {
		//selectItem('FilterGrades_'+iID,'FilterGrades[]');
		SubmitForm({fields : { "FilterGrades" : [ iID] } } );
	}
	if ( sSummaryBy=='school' ) {
		//selectItem('FilterSchools_'+iID,'FilterSchools[]');
		SubmitForm({fields : { "FilterSchools" : [ iID] } } );
	}
	if ( sSummaryBy=='schooltype' ) {
		//selectItem('FilterSchoolTypes_'+iID,'FilterSchoolTypes[]');
		SubmitForm({fields : { "FilterSchoolTypes" : [ iID] } } );
	}
	if ( sSummaryBy=='subject' ) {
		//selectItem('FilterSubjects_'+iID,'FilterSubjects[]');
		SubmitForm({fields : { "FilterSubjects" : [ iID] } } );
	}
	if ( sSummaryBy=='site' ) {
		//selectItem('FilterSites_'+iID,'FilterSites[]');
		SubmitForm({fields : { "FilterSites" : [ iID] } } );
	}
	if ( sSummaryBy=='teacher' ) {
		//selectItem('FilterTeachers_'+iID,'FilterTeachers[]');
		SubmitForm({fields : { "FilterTeachers" : [ iID] } } );
	}
}

function goReportGraph(sChartType,iSubjectID,iGradeID,iSchoolID,iTeacherID,sSummaryBy) {
	ResetHiddenFields();
	var f = document.forms[0];
	var sOldSummaryBy=f.SummaryBy.value;
	var sOldChartType=f.results.value;

	f.target='_blank';
	f.results.value=sChartType;
	f.SubjectID.value=iSubjectID;
	f.GradeID.value=iGradeID;
	f.SchoolID.value=iSchoolID;
	//f.TeacherID.value=iTeacherID;
	f.SummaryBy.value=sSummaryBy;
	f.submit();
	//reset
	f.target='_self';
	f.SummaryBy.value=sOldSummaryBy;
	f.results.value=sOldChartType;

	return false;
}

function getMouseXY(e){
	var posx = 0,posy = 0;
	if(e == null){
		e = window.event;
	}
	if(e.pageX || e.pageY){
		posx = e.pageX;
		posy = e.pageY;
	} else if(e.clientX || e.clientY){
		if(document.documentElement.scrollTop){
			posx = e.clientX+document.documentElement.scrollLeft;
			posy = e.clientY+document.documentElement.scrollTop;
		} else{
			posx = e.clientX+document.body.scrollLeft;
			posy = e.clientY+document.body.scrollTop;
		}
	}
	return {x: posx, y: posy };
}

//returns the size of the client's screen
function getViewportXY() {
	var myWidth = 0, myHeight = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return { x : myWidth, y : myHeight };
}

//returns how far the client has scrolled x and y for the page
function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return {x :  scrOfX, y : scrOfY };
}

// sets the cursor selection inside a text input or textarea
function setSelection( oElement, iStart, iEnd ){
	if( ! iEnd ){
		iEnd = iStart;
	}
	if( oElement.setSelectionRange ){
		try{
			oElement.setSelectionRange( iStart, iEnd );
		}
		catch( e ){
			return false;
		}
		return true;
	}
	else if( oElement.createTextRange ){
		var range = oElement.createTextRange();
		range.collapse( true );
		range.moveEnd( 'character', iEnd );
		range.moveStart( 'character', iStart );
		range.select();
		
		return true;
	}
	else{
		return false;
	}
}

// inserts text inside a text input or textarea at the cursor location
function insertTextAtCursor( vElement, sText ){
	var oElement = vElement;
	if( typeof oElement == 'string' ){
		oElement = document.getElementById( oElement );
	}
	if( sText ){
		if( oElement.selectionStart || oElement.selectionStart === 0 ){
			var iCursorPosition = oElement.selectionStart;
			var sCurrentText = oElement.value;
			if( sCurrentText.length ){
				var sBeforeText = sCurrentText.substring( 0, iCursorPosition );
				var sAfterText = sCurrentText.substring( iCursorPosition, sCurrentText.length );
				oElement.value = sBeforeText + sText + sAfterText;
			}
			else{
				oElement.value = sText;
			}
			setSelection( oElement, iCursorPosition + sText.length );
			oElement.focus();
		}
		else if( document.selection ){
			oElement.focus();
			var range = document.selection.createRange();
			range.text = sText;
		}
	}
}

function addClass(el, className){
	el.className += ' ' + className;
}

function removeClass(el, className){
	el.className = el.className.replace(className+' ', '');
	el.className = el.className.replace(' '+className, '');
	el.className = el.className.replace(className, '');
}

function swapClass(el, add, remove){
	el.className = el.className.replace(remove, add);
}

//TR 11/18/08
// Wrapper function for replacing the innerHTML of an html tag with the reults of an AJAX call
function ReplaceInnerHTML(sContainerID, sURL, aParameters, sLoadingContent) {
	if (!sLoadingContent) {
		sLoadingContent = GetLoadingContent();
	}
    new Ajax.Updater(sContainerID,
    				 sURL,
    				 {
    					method: 'post',
    					parameters: aParameters,
    					onLoading:function(){
    						$(sContainerID).innerHTML = sLoadingContent;
    					}
    				 }
    				);	
}
function GetLoadingContent(aAttributes) {
	aAttributes = Object.extend({
		'class': 'Loading'
	}, aAttributes || {});
	sAttributes = '';
	$H(aAttributes).each(function(attr){
		sAttributes += ' ' + attr.key + '="' + attr.value + '"';
	});
	return '<div'+sAttributes+'><div class="Spinner"><img src="/common_images/spinner.gif?v=' + ATLAS_VERSION + '"/></div></div>'; 
}
function log(sString) {
}
String.prototype.nl2br = function() {
	return this.replace( /\n/g, "<br />" );
};
String.prototype.br2nl = function() {
	return this.replace( /\<br ?\/?\>\n?/g, "\n" );
};
var aErrorEmailsSent = [];
/*
*	Custom Error handling for Javascript errors
*/
window.onerror = function onerror(msg, errURL, line) {
	// JR 4/22/2010 - only send one notification email per message per page
	for(var i = 0; i < aErrorEmailsSent.length; i++){
		if(aErrorEmailsSent[i] == msg){
			return;
		}
	}
	aErrorEmailsSent.push(msg);
	
	errURL = errURL || window.location.href;
	
	if (typeof Ajax != "undefined") {	//using prototype library
		var sStackTrace = printStackTrace();
		var sLogURL = '/c/error/jsError.php';
		var sForm = '';
		if (typeof document.forms[0] != "undefined") {
			sForm = Form.serialize(document.forms[0]);
		}
		new Ajax.Request(sLogURL, {
			parameters: {'url': errURL, 'msg': msg, 'line': line, 'formVariables': sForm, 'stack[]': sStackTrace}
		});
	}
};

//AE 3/10/09 moved this out of tabldnd.js, to allow drag and drop in embedded pages 
var ATLAS_HANDLER_QUEUE = {
	onmousemoves: [],
	onmouseups: [],
	addHandler: function addHandler(sType, f) {
		switch (sType) {
			case 'onmousemove':
				ATLAS_HANDLER_QUEUE.onmousemoves[ATLAS_HANDLER_QUEUE.onmousemoves.length] = f;
				break;
			case 'onmouseup':
				ATLAS_HANDLER_QUEUE.onmouseups[ATLAS_HANDLER_QUEUE.onmouseups.length] = f;
				break;
			default:
				throw "Can't handle a ".sType;
		}
	},
	init: function init() {
		document.onmousemove = function onmousemove(ev) {
			for (var i = 0; i < ATLAS_HANDLER_QUEUE.onmousemoves.length; i++) {
				f = ATLAS_HANDLER_QUEUE.onmousemoves[i];
				f(ev);
			}
		};
		document.onmouseup = function onmouseup(ev) {
			for (var i = 0; i < ATLAS_HANDLER_QUEUE.onmouseups.length; i++) {
				f = ATLAS_HANDLER_QUEUE.onmouseups[i];
				f(ev);
			}
		};
	}
};

ATLAS_HANDLER_QUEUE.init();

function EvalJavaScript( sJavaScript ){
	// JR 7/16/2009 - IE needs to use execScript to eval in global context
	try{
		if( window.execScript ){
			window.execScript( sJavaScript );
		}
		else{
			window.eval( sJavaScript );
		}
	}
	catch(e){
		window.onerror('EvalJavaScript: ' + e.message, e.lineNumber, sJavaScript);
	}
}

/**
 * Given the Name of a Form Element, this function returns the element's value from any form on the Page.
 * @param string sName
 * @return value
 */
function GetValue( sName ){
	if( sName ){
		var oElementByName = $(sName);
		if( oElementByName ){
			return $F( oElementByName );
		}
		var oElementByForm = $$('form').find( function( form ){
			return form[sName];
		} );
		if( oElementByForm && oElementByForm[sName] ){
			return $F( oElementByForm[sName] );
		}
	}
	return '';
}

/**
 * Toggle Check Boxes state.
 * @param string sCheckBoxesSelector CSS Selector for Check Boxes.
 * @return  boolean bChecked
 */
function toggleCheck( sCheckBoxesSelector ){
	var aCheckBoxes = $$( sCheckBoxesSelector );
	var bChecked = AllCheckBoxesChecked(sCheckBoxesSelector);
	aCheckBoxes.each( function( oCheckBox ){
		oCheckBox.checked = !bChecked;
	} );
	return bChecked;
}
/**
 * Check state of checkboxes
 * @param sCheckBoxesSelector
 * @return boolean
 *  returns true if all are checked
 *  
 */
function AllCheckBoxesChecked(sCheckBoxesSelector) {
	var aCheckBoxes = $$( sCheckBoxesSelector );
	aChecked = aCheckBoxes.select(function( oCheckBox ){
		return oCheckBox.checked;
	});
	return ((aCheckBoxes.length > 0) &&(aCheckBoxes.length == aChecked.length));
	/*return aCheckBoxes.find( function( oCheckBox ){
		return ! oCheckBox.checked;
	} ) ? true : false;*/	
}
/**
 * Button to check all radio buttons and also uncheck all radio buttons
 * @param string sButtonName
 * @return string
 */
function checkAllButtons(sButtonName,sCheckBoxesSelector){
	var button = $(sButtonName);
	if(button){
		if(toggleCheck(sCheckBoxesSelector)){
			button.innerHTML =  "Check All";
		}else{
			button.innerHTML = 'Uncheck All';
		}
	}
}
function SetCheckAllButtonText(sButtonName,sCheckBoxesSelector) {
	var button = $(sButtonName);
	if (button) {
		if(AllCheckBoxesChecked(sCheckBoxesSelector)){
			button.innerHTML = 'Uncheck All';
		}else{
			button.innerHTML =  "Check All";
		}
	}
}

/**
 * Button to change the "checkall" button when the last box is checked/unchecked
 * @param string sButtonName
 * @param string SCheckBoxesSelector
 * @return string
 */
function changeCheckButton(sButtonName,sCheckBoxesSelector){
		var button = $(sButtonName);
		var aCheckBoxes = $$( sCheckBoxesSelector );
		var bChecked = aCheckBoxes.find( function( oCheckBox ){
			return !oCheckBox.checked;
		} ) ? true : false;
		if(button) {
			if(bChecked) {
				button.innerHTML = 'Check All';
			}else{
				button.innerHTML = 'Uncheck All';
			}
		}
		return bChecked;
	} 

/**
 * check Check Boxes states.
 * @param string sCheckBoxesSelector CSS Selector for Check Boxes.
 * @return boolean bChecked
 */
function checkCheckBoxes( sCheckBoxesSelector ){
	var aCheckBoxes = $$( sCheckBoxesSelector );
	var bChecked = aCheckBoxes.find( function( oCheckBox ){
		return oCheckBox.checked;
	} ) ? true : false;
	if(!bChecked) {
		alert('Please check at least one item.');
	}
	return bChecked;
} 

/**
 * pulling from page.php into here
*/
var autoSaveOnUnload = false;
function enableAutoSaveOnUnload(enable){
	autoSaveOnUnload = enable;
	return true;
}
function fieldChanged(e) {
	if (!autoSaveOnUnload) { /*AE 7/21/09 fix bug # 8660 Autosave doesnt save for non RTE site */
		enableAutoSaveOnUnload(true);
	}//AE 10/8/09 move the following if block outside the above if block - autosave wasnt working since this needs to happen after autosave on unload enabled
	if( typeof tinyMCE != "undefined" && tinyMCE.activeEditor && tinyMCE.activeEditor.isDirty() && !(e && e.type=="submit") && typeof customFieldChanged == "function"){
		customFieldChanged();
	}
}


/**
 * UIIframeAutoResize utility
 */
function AutoResizeIFrame_onload( vIframe, iMinHeight, bFromReadyStateChange ){
	var oIframe = $( vIframe );
	iMinHeight = iMinHeight || 0;
	
	if( oIframe ){
		var oIframeDocument = oIframe.contentDocument || oIframe.contentWindow.document;
		if( oIframeDocument ){
			if( ! bFromReadyStateChange ){
				// Reset the iframe's height
				SetIFrameHeight( oIframe, 0 );
			}
			try{
				// Find the height of the internal page [add a few pixels for the scrollbar]
				var iIframeHeight = oIframeDocument.getElementsByTagName( 'body' )[0].scrollHeight + 25;
			}
			catch(e){
				// Set a default value and move on gracefully.
				var iIframeHeight = 150;
			}
			iIframeHeight = Math.max( iMinHeight, iIframeHeight );
			SetIFrameHeight( oIframe, iIframeHeight );
		}
		else if( iMinHeight > 0 ){
			oIframe.height = iMinHeight;
		}
	}
}
function AutoResizeIFrame_onreadystatechange( vIframe, iMinHeight ){
	var oIframe = $( vIframe );
	
	if( oIframe && oIframe.readyState == 'complete' ){
		AutoResizeIFrame_onload.defer( oIframe, iMinHeight, true );
	}
}
function SetIFrameHeight( oIframe, iHeight ){
	Element.setStyle( oIframe, {
		height: iHeight + 'px'
	} );
	oIframe.height = iHeight;
}

/**
 * Stripe all rows inside a table's tbody with oddRow/evenRow.
 * @param var vTable table element
 */
function StripeTable( vTable ){
	var oTable = $( vTable );
	var className = [ 'oddRow', 'evenRow' ];
	Element.childElements( Element.down( oTable, 'tbody' ) ).each( function( tr, index ){
		Element.removeClassName( tr, className[(index+1)%2] );
		Element.addClassName( tr, className[index%2] );
	} );
}

/**
 * Determine whether an email address is valid or not.
 * @param string sEmail Email Address to validate
 * @param boolean bAlert Show javascript alerts?
 * @return boolean
 */
function IsValidEmail( sEmail, bAlert ){
	var emailFilter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	if( ! sEmail ){
		if( bAlert ){
			alert( "Please enter an email address." );
		}
		return false;
	}
	else if( ! emailFilter.test( sEmail ) ){ 
		if( bAlert ){
			alert( "Please enter a valid email address." );
		}
		return false;
	}
	return true;
}

/**
 * Get the View URL for a given class.
 * @param string View Class Name
 * @param object Query Parameters
 * @return string
 */
function GetViewUrl( sViewClass, aParameters ){
	sViewClass = sViewClass || 'View';
	aParameters = aParameters || {};
	var sReturn = '/c/pi/v.php/' + sViewClass.gsub('_', '/');
	if( Object.values(aParameters).length ){
		sReturn += '?' + Object.toQueryString(aParameters);
	}
	return sReturn;
}

aBeforeUnloadCallbacks = [];
/**
 * Adds a function to call before the browser's unload event fires.
 * If fBeforeUnloadCallback returns a result, this result is prompted to the user before they leave the page.
 * @param function fBeforeUnloadCallback
 */
function AddOnBeforeUnload(fBeforeUnloadCallback){
	if(!aBeforeUnloadCallbacks.length){
		window.onbeforeunload = function onbeforeunload(){
			for(var i = 0, result; i < aBeforeUnloadCallbacks.length; i++){
				result = aBeforeUnloadCallbacks[i]();
				if(result){
					return result;
				}
			}
		};
	}
	if(typeof fBeforeUnloadCallback == 'function'){
		aBeforeUnloadCallbacks.push(fBeforeUnloadCallback);
	}
}
