/** @file webapp.js
* @author Michael Snow
* @version 1.0
* @date 11/2008
* @brief This file contains site wide javascript functions.
* @bug
* @warning
*/
//*****************************************************************************************************//

/** trim
*  \brief Removes the leading and trailing whitespaces from a string
*  \param str - The string to trim
*  \return The string without leading and trailing whitespace
*/
function trim(str) {
	return str.replace(/^\s+|\s+$/g,'');
}

/** checkNumber
*  \brief Determines if the input variable is a number
*  \param value - The variable to determine if a number
*  \return boolean - true if a number, otherwise false
*/
function checkNumber(value) {
	var check = true;
	//check that all characters are digits or .
	for(var i=0;i < value.length; ++i) {
		var new_key = value.charAt(i); //cycle through characters
		// If its a bad char, return false and exit for loop
		if(((new_key < "0") || (new_key > "9")) && !(new_key == ".")) {
			check = false;
			break;
		}
	}
	return check;
}

/** highlight
*  \brief For an input field, turns the background color to yellow, to highlight the field's focus
*  \param myID - The id of the form field to be converted
*/
function highlight(myID) {
	document.getElementById(myID).style.backgroundColor='yellow';
}

/** normal
*  \brief For an input field, turns the background color to white, when the field loses focus
*  \param myID - The id of the form field to be converted
*/
function normal(myID) {
	document.getElementById(myID).style.backgroundColor='white';
}

/** CheckMaxLength
*  \brief For an input field, checks the string length and compares to a pre determined value set in this function
*  \param field - The id of the form field to be checked
*  \return Boolean - true if max length not reached, otherwise false plus an alert message stating max length reached
*/
function CheckMaxLength(field) {
	var fieldId = field.getAttribute('id');
	var maxLength = 0;
	/*
		Add custom textarea fields here
	if(fieldId == "Description")
		maxLength = 300;
	*/

	if(field.value.length > maxLength) {
		field.value = field.value.substring(0, maxLength - 1);
		alert("You have reached the maximum allowable characters for this field. You will need to remove text to add more.");
		return false;
	} else {
		return true;
	}
}

/** setTimeInterval
*  \brief Sets a timer variable for use in the functions fade and animateFade below, the amount of time the fade process takes to accomplish.
*  \param val - An amount of time, input
*/
function setTimeInterval(val) {
    TimeToFade = val;
}

/** fade
*  \brief Determines the fadestate for the HTML form element that is to be faded in or faded out and calls animateFade, the process to accomplish the fade
*  \param eid - the id of the HTML form element to fade
*/
function fade(eid) {
	var element = document.getElementById(eid);
	if(element == null)
		return;
	
	if(element.FadeState == null) {
		if(element.style.opacity == null 
			|| element.style.opacity == '' 
			|| element.style.opacity == '1') {
			element.FadeState = 2;
		} else {
			element.FadeState = -2;
		}
	}

	if(element.FadeState == 1 || element.FadeState == -1) {
		element.FadeState = element.FadeState == 1 ? -1 : 1;
		element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
	} else {
		element.FadeState = element.FadeState == 2 ? -1 : 1;
		element.FadeTimeLeft = TimeToFade;
		setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "')", 33);
	}
}

/** fade
*  \brief Using the HTML style property opacity, gives an HTML form element the apparance of fading in or fading out, this is done so recursively
*  \param lastTick - Counter variable to keep track of the amount of time has elapsed
*  \param eid - the id of the HTML form element to fade
*/
function animateFade(lastTick, eid) {
	var curTick = new Date().getTime();
	var elapsedTicks = curTick - lastTick;
	var element = document.getElementById(eid);
	
	if(element.FadeTimeLeft <= elapsedTicks) {
		element.style.opacity = element.FadeState == 1 ? '1' : '0';
		element.style.filter = 'alpha(opacity = ' + (element.FadeState == 1 ? '100' : '0') + ')';
		element.FadeState = element.FadeState == 1 ? 2 : -2;
		return;
	}
	
	element.FadeTimeLeft -= elapsedTicks;
	var newOpVal = element.FadeTimeLeft/TimeToFade;
	if(element.FadeState == 1)
		newOpVal = 1 - newOpVal;
	
	element.style.opacity = newOpVal;
	element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
	setTimeout("animateFade(" + curTick + ",'" + eid + "')", 33);
}

/** modifyForm
*  \brief Clears, Enables and Disables form fields and buttons.
*  \param formIdent - name of form to modify
*  \param modifyType - determines how to modify form, either clear, enable or disable, clear will clear field value, enable will
*	enable the form field and set its background color to white, and disable will disable the form field and set its background
*   color to gray.
*  \param skipSelect - Array that determines name of fields to not modify.
*/
function modifyForm(formIdent, modifyType, skipSelect)
{
	var form, elements, i, elm; 
	var found = false;
	// Get the form field
	form = document.getElementById 
	? document.getElementById(formIdent) 
	: document.forms[formIdent];

	if(document.getElementsByTagName) {
		// Processing if an HTML input form field
		elements = form.getElementsByTagName('input');
		for(i=0, elm; elm=elements.item(i++); ) {
			// Determines if element is in skip list, if so no further processing necessary on this element
			for(j=0; j < skipSelect.length; j++) {
				if(elm.name == skipSelect[j]) {
					found = true;
					j = skipSelect.length;
				}
			}
			if(elm.getAttribute('type') == "text" && !found) {
				if(modifyType == 'clear') {
					elm.value = '';
				} else if(modifyType == 'enable') {
					elm.disabled = false;
					elm.style.backgroundColor = '#FFFFFF';
					elm.style.color = '#000000';
					if(elm.getAttribute('readonly') == 'readonly' || elm.getAttribute('readonly') == true) {
						elm.style.backgroundColor = '#DFE1BC';
						elm.style.color = '#666666';
					}
				} else if(modifyType == 'disable') {
					elm.disabled = true;
					elm.style.backgroundColor = '#E2E2E2';
				} else if(modifyType == 'readonly') {
					elm.disabled = true;
					elm.readonly = true;
					elm.style.backgroundColor = '#DFE1BC';
					elm.style.color = '#666666';
				}
			} else if(elm.getAttribute('type') == "hidden" && !found) {
				if(modifyType == 'clear') {
					// No action, hidden fields are left intact at all times
				} else if(modifyType == 'enable') {
					elm.disabled = false;
				} else if(modifyType == 'disable') {
					elm.disabled = true;
				}
			} else if(elm.getAttribute('type') == "button" && !found) {
				if(modifyType == 'clear') {
					// No action, button values are left intact at all times
				} else if(modifyType == 'enable') {
					elm.disabled = false;
				} else if(modifyType == 'disable') {
					elm.disabled = true;
				} else if(modifyType == 'readonly') {
					elm.disabled = true;
				}
			} else if(elm.getAttribute('type') == "radio" && !found) {
				if(modifyType == 'clear') {
					elm.checked = false;
				} else if(modifyType == 'enable') {
					elm.disabled = false;
				} else if(modifyType == 'disable') {
					elm.disabled = true;
				}
			} else if(elm.getAttribute('type') == "checkbox" && !found) {
				if(modifyType == 'clear') {
					elm.checked = false;
				} else if(modifyType == 'enable') {
					elm.disabled = false;
				} else if(modifyType == 'disable') {
					elm.disabled = true;
					elm.checked = false;
				} else if(modifyType == 'readonly') {
					elm.disabled = true;
				}
			}
			found = false;
		}
		// Processing if an HTML textarea form field
		elements = form.getElementsByTagName('textarea');
		for(i=0, elm; elm=elements.item(i++); ) {
			// Determines if element is in skip list, if so no further processing necessary on this element
			for(j=0; j < skipSelect.length; j++) {
				if(elm.name == skipSelect[j]) {
					found = true;
					j = skipSelect.length;
				}
			}
			if(!found) {
				if(modifyType == 'clear') {
					elm.value = '';
				} else if(modifyType == 'enable') {
					elm.disabled = false;
					elm.style.backgroundColor = '#FFFFFF';
					elm.style.color = '#000000';
					if(elm.getAttribute('readonly') == 'readonly' || elm.getAttribute('readonly') == true) {
						elm.style.backgroundColor = '#DFE1BC';	
						elm.style.color = '#666666';
					}
				} else if(modifyType == 'disable') {
					elm.disabled = true;
					elm.style.backgroundColor = '#E2E2E2';
				} else if(modifyType == 'readonly') {
					elm.disabled = true;
					elm.readonly = true;
					elm.style.backgroundColor = '#DFE1BC';
					elm.style.color = '#666666';
				}
			}
			found = false;
		}
		// Processing if an HTML select form field
		elements = form.getElementsByTagName('select');
		for(i=0, elm; elm=elements.item(i++); ) {
			// Determines if element is in skip list, if so no further processing necessary on this element
			for(j=0; j < skipSelect.length; j++) {
				if(elm.name == skipSelect[j]) {
					found = true;
					j = skipSelect.length;
				}
			}
			if(!found) {
				if(modifyType == 'clear') {
					elm.innerHTML = '';
				} else if(modifyType == 'enable') {
					elm.disabled = false;
					elm.style.backgroundColor = '#FFFFFF';
					elm.style.color = '#000000';
					if(elm.getAttribute('readonly') == 'readonly' || elm.getAttribute('readonly') == true) {
						elm.style.backgroundColor = '#DFE1BC';	
						elm.style.color = '#666666';
					}
				} else if(modifyType == 'disable') {
					elm.disabled = true;
					elm.style.backgroundColor = '#E2E2E2';
				} else if(modifyType == 'readonly') {
					elm.disabled = true;
					elm.readonly = true;
					elm.style.backgroundColor = '#DFE1BC';
					elm.style.color = '#666666';
				}
			}
			found = false;
		}
		found = false;
	}
}

function display_form(z) {
	if(z['success']) {
		var form, elements, i, elm;
		form = document.getElementById 
		? document.getElementById(z['formIdent'])
		: document.forms[z['formIdent']];

		if(document.getElementsByTagName) {
			elements = form.getElementsByTagName('input');
			for(i=0,elm; elm=elements.item(i++); ) {
				if(elm.getAttribute('type') == "text") {
					document.getElementById(elm.id).value = decodeURIComponent(unescape(z['output'][elm.id]));
				}
				if(elm.getAttribute('type') == "checkbox") {
					if(z['output'][elm.id] == 1)
						document.getElementById(elm.id).checked = true;
					else
						document.getElementById(elm.id).checked = false;
				}
			}

			elements = form.getElementsByTagName('textarea');
			for(i=0,elm; elm=elements.item(i++); ) {
				document.getElementById(elm.id).value = decodeURIComponent(unescape(z['output'][elm.id]));
			}
		}
	} else {
		document.getElementById(z['msgLocation']).innerHTML = "<br />" + z['msg'] + "<br />";
	}
}

function getFormElements(formIdent) {
	var form, elements, i, elm;
	form = document.getElementById 
	? document.getElementById(formIdent)
	: document.forms[formIdent];

	var selected = new Array();
	var index = 0;
	if(document.getElementsByTagName) {
		elements = form.getElementsByTagName('input');
		for(i=0,elm; elm=elements.item(i++); ) {
			if(elm.getAttribute('type') == "text") {
				selected[index] = new Object;
				selected[index].value = encodeURIComponent(escape(trim(document.getElementById(elm.id).value)));
				selected[index].key = elm.id;
				index++;				
			}
			if(elm.getAttribute('type') == "checkbox") {
				selected[index] = new Object;
				if(elm.checked == true)
					selected[index].value = 1;
				else
					selected[index].value = 0;
				selected[index].key = elm.id;
				index++;				
			}
		}

		elements = form.getElementsByTagName('select');
		for(i=0,elm; elm=elements.item(i++); ) {
			selected[index] = new Object;
			selected[index].value = encodeURIComponent(escape(trim(document.getElementById(elm.id).value)));
			selected[index].key = elm.id;
			index++;				
		}

		elements = form.getElementsByTagName('textarea');
		for(i=0,elm; elm=elements.item(i++); ) {
			selected[index] = new Object;
			selected[index].value = encodeURIComponent(escape(trim(document.getElementById(elm.id).value)));
			selected[index].key = elm.id;
			index++;				
		}
	}

	var indexes = new Array();
	var str_array = '';
	var key = '';
	var value = '';
	for(var item in selected) {
		str_array += selected[item].key + "," + selected[item].value + ",";
	}

	var str_length = str_array.length;
	str_array = trim(str_array.substring(0, str_length-1));

	return str_array;
}

/** msieversion
*  \brief Determines if browser is a version of IE and which version or another non-IE browser
*  \return If an IE browser, returns the version number, otherwise returns 0
*/
function msieversion() {
	var ua = window.navigator.userAgent;
	var msie = ua.indexOf("MSIE");
	
	if (msie > 0) // If Internet Explorer, return version number
		return parseInt(ua.substring(msie+5, ua.indexOf(".", msie)));
	else // If another browser, return 0
		return 0;
}

/** build_select
*  \brief Redisplays an arbitray HTML select form field after an AJAX call and modifies a few of its properties
*  \param z - An array of all the elements that make up an HTML select form field, and a message to display to a user
*/
function build_select(z) {
	if(msieversion() == 0) { // NON-IE Browser
		document.getElementById(z['formElm']).innerHTML = unescape(z['options']);
	} else {
		document.getElementById(z['formElm']+'DIV').innerHTML = unescape(z['openTag'] + z['options'] + z['closeTag']);
	}
	document.getElementById(z['formElm']).disabled = false;
	document.getElementById(z['formElm']).style.backgroundColor = '#FFFFFF';
	document.getElementById(z['formElm']).style.color = '#000000';
	if(document.getElementById(z['formElm']+'Mod')) {
		document.getElementById(z['formElm']+'Mod').disabled = false;
	}
	if(document.getElementById(z['EmailFormElm'])) {
		document.getElementById(z['EmailFormElm']).innerHTML = z['EmailList'];
	}
	document.getElementById(z['msgLocation']).innerHTML = z['msg'];
}

/** build_select_readonly
*  \brief Redisplays an arbitray HTML select form field after an AJAX call and modifies a few of its properties, but it is to be displayed as
*  readonly, so the field is not enabled.
*  \param z - An array of all the elements that make up an HTML select form field, and a message to display to a user
*/
function build_select_readonly(z) {
	if(msieversion() == 0) { // NON-IE Browser
		document.getElementById(z['formElm']).innerHTML = decodeURIComponent(unescape(z['options']));
	} else {
		document.getElementById(z['formElm']+'DIV').innerHTML = decodeURIComponent(unescape(z['openTag'] + z['options'] + z['closeTag']));
	}
	document.getElementById(z['formElm']).style.backgroundColor = '#DFE1BC';
	document.getElementById(z['formElm']).style.color = '#666666';
	document.getElementById(z['msgLocation']).innerHTML = z['msg'];
}

/** build_select_parent
*  \brief Redisplays an arbitray HTML select form field after an AJAX call from a modal window and modifies a few of its properties
*  \param z - An array of all the elements that make up an HTML select form field, and a message to display to a user
*/
function build_select_parent(z) {
	if(msieversion() == 0) { // NON-IE Browser
		parent.document.getElementById(z['formElm']).innerHTML = decodeURIComponent(unescape(z['options']));
	} else {
		parent.document.getElementById(z['formElm']+'DIV').innerHTML = decodeURIComponent(unescape(z['openTag'] + z['options'] + z['closeTag']));
	}
	parent.document.getElementById(z['formElm']).disabled = false;
	parent.document.getElementById(z['formElm']).style.backgroundColor = '#FFFFFF';
	if(parent.document.getElementById(z['formElm']+'Mod')) {
		parent.document.getElementById(z['formElm']+'Mod').disabled = false;
	}
	parent.document.getElementById(z['msgLocation']).innerHTML = z['msg'];
}

/** fill_textarea
*  \brief Displays the text for an arbitray HTML textarea form field after an AJAX call
*  \param z - An array containing the text to display in an HTML textarea form field
*/
function fill_textarea(z) {
	document.getElementById(z['formElm']).value = decodeURIComponent(unescape(z['value']));
}

/** checkPhone
*  \brief While a user is entering in a phone number, this function will switch the focus to the next field once
*  the correct number of numbers are added to each field. This function is used for both forms on this page. If
*  there are multiple phone fields on a page, change the name and modify this function to add those
*  \param id - The id of the HTML form field being modified
*/
function checkPhone(id) {
	if(checkNumber(document.getElementById(id).value)) {
		if(id == 'Num1') {
			if(document.getElementById(id).value.length == 3) {
				if(id == 'Num1') {
					document.getElementById('Num2').focus();
				}
			}
		} else if(id == 'Num2') {
			if(document.getElementById(id).value.length == 3) {
				if(id == 'Num2') {
					document.getElementById('Num3').focus();
				}
			}
		}
	}
}

/** select_text
*  \brief Highlights the text in a text box to easily replace with new text
*  \param id - The id of the HTML form field being modified
*/
function select_text(id) {
	document.getElementById(id).select();
}

/** getSelected
*  \brief Determines which options in a multiple select box or multiple checkboxes are selected
*  \param id - The id of the HTML form field being modified
*  \return - An array containing the index and value of the selected options
*/
function getSelected(id) {
	var selected = new Array();
	var index = 0;
	for(var intLoop = 0; intLoop < id.length; intLoop++) {
		if((id[intLoop].selected) || (id[intLoop].checked)) {
			index = selected.length;
			selected[index] = new Object;
			selected[index].value = id[intLoop].text;
			selected[index].index = id[intLoop].value; //intLoop;
		}
	}
	return selected;
}

function getOptionsIndex(id, value) {
	var index = 0;
	var element = document.getElementById(id);
	for(var i=0;i<element.options.length;i++) {
		if(element.options[i].value == value) {
			index = i;
			//element.options[i].selected = true;
			i = element.options.length;
		}
	}
	return index;
}

function clearSajaxMsg() {
	document.getElementById('SajaxMsg').innerHTML = '';
	document.getElementById('SajaxMsg').style.display='none';
}
