// JavaScript Document
//function adds onload events. allows for multiple events to be loaded.
//cross browser compatiable
if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

function addOnloadEvent(fnc) {
  if ( typeof window.addEventListener != "undefined" )
    window.addEventListener( "load", fnc, false );
  else if ( typeof window.attachEvent != "undefined" ) {
    window.attachEvent( "onload", fnc );
  }
  else {
    if ( window.onload != null ) {
      var oldOnload = window.onload;
      window.onload = function ( e ) {
        oldOnload( e );
        window[fnc]();
      };
    }
    else 
      window.onload = fnc;
  }
}

//function adds an event listner to an element
//cross browser compatiable
function addListnert(element, method, fnc) {
	if ( typeof window.addEventListener != "undefined") {
		element.addEventListener(method, fnc, false );
	} else if (typeof window.attachEvent != "undefined") {
		method = checkAeMethod(method);
		element.attachEvent(method, fnc);
	}
}

//function switches out the method names that work for addEventListner and pops in the attachEvent methods
function checkAeMethod(method) {
	switch(method) {
		case 'load':
			method = 'onload';
			break;
		case 'change':
			method = 'onchange';
			break;
		case 'click':
			method = 'onclick';
			break;
		case 'blur':
			method = 'onblur';
			break;
		case 'focus':
			method = 'onfocus';
			break;
		case 'mouseover':
			method = 'onmouseover';
			break;
	}
	
	return method;
}

//function to open popup window
function openPopUp(loc){
	var win = window.open(loc,"popup","width=600,height=600,resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no");
}

function openNewWin(loc){
	var win = window.open(loc,"popup","width=780,height=590,resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no");
}

function closeWindow() {
	window.close();
}

/**
* Function to close window
* add to onload event to listen for link press
*/
function closePop(){
	var popUp = document.getElementById('closeWin');
	
	popUp.onclick = function(){
		window.close();
	}
}

/**
* listen for Back button actions
* removes javascript from html 
*/
function back_button(){
	var backBtn = document.getElementById('backBtn');
	
	backBtn.onclick = function (){
		history.go(-1);
	}
}

/**
* Function designed to update footer text when information is added or removed from the page through javascript
*/
function update_footer(){
	var footer = document.getElementById('footer');
	var footer_content = footer.innerHTML;
	footer.innerHTML = "";
	footer.innerHTML = footer_content;
}

/**
* Function designed to return a 5 digit random string. used to name popup windows
*/
function randomString(len) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = len;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}


/**
* Function to trigger print in both ie and firefox
*/
function printit(){
	var printW = document.getElementById('printWindow');
	
	printW.onclick = function(){
		if (window.print) {
		    window.print();  
		} else {
		    var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
			document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
		    WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box    WebBrowser1.outerHTML = "";  
		}
	}
}


/** 
* utc_date()
* This function takes a date that is formatted mm/dd/yyyy to UTC miliseconds for easy compairison
*
* @example 
*			var date   = "03/21/2006";
*			return utc_date(date);         //returns 1191369600000
* @param Integer date
* @return Integer
* @access public 
*/ 
function utc_date(date){
	dates = date.split('/');
	var humDate = new Date(Date.UTC(dates[2], dates[0]-1, dates[1], 0, 0, 0));
	return humDate.getTime();
}



/** 
* trimString()
* This function removes the whitespace before and after a given string
*
* @example 
*			var string   = "       this is a test            ";
*			return trimString(string);                                    //returns "this is a test"
* @param String str
* @return String
* @access public 
*/ 
function trimString (str) {
	str = str.replace( /^\s+/g, "" );			// strip leading
	return str.replace( /\s+$/g, "" );				// strip trailing
} 


function resetForm(id){
	document.forms[id].reset;
}


function handleEnter (event, form) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

	if (( 13 == keyCode ) && ( document.activeElement.nodeName != 'TEXTAREA' )) {
		submitForm(form);	
	}
}



function popWinTemp(url, rel){
	
	var scrW = screen.availWidth;
    var scrH = screen.availHeight;
		
	switch(rel){
		case 'popup' || 'email' || (rel.search(/form/gi) > -1):
			var pW = 600;
			var pH = 500;
			scrX = (scrW - pW - 10) * .5;
			scrY = (scrH - pH - 30) * .5;
			
			var windowAttributes = "width=" + pW + ",height=" + pH + ",left=" + scrX + ",top=" + scrY + ",screenX=" + scrX + ",screenY=" + scrY;
			windowAttributes += ",resizable=no,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no";
			winName = 'popup';
			
			if(rel == "email") {
			  	winName = 'email';
			} else if(rel.search(/form/gi) > -1) {
				winName = "form";
			}
			break;
		case 'erl':
			var windowAttributes = "width=789,height=540,left=0,top=0,screenX=0,screenY=0";
			windowAttributes += ",resizable=no,scrollbars=no,toolbar=no,location=no,directories=no,status=no,menubar=no";
			linkDest += "?studentID="+studentID;
			var winName = "popup";
			break;
		case 'full':
			var windowAttributes = "left=0,top=0,screenX=0,screenY=0";
			windowAttributes += ",resizable=yes,scrollbars=yes,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes";
			var winName = "full";
			break; 
	}
	
	window.open(url, winName, windowAttributes);
}



var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

/** the following Trim functions were taken from http://www.apriori-it.co.uk/Trim.asp */
function Trim(TRIM_VALUE){
	if(TRIM_VALUE.length < 1){
		return"";
	}
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	if(TRIM_VALUE==""){
		return "";
	}
	else{
		return TRIM_VALUE;
	}
}

function RTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0){
		return"";
	}
	var iTemp = v_length -1;
	
	while(iTemp > -1){
		if(VALUE.charAt(iTemp) == w_space){
		}
		else{
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}
		iTemp = iTemp-1;	
	} //End While
	return strTemp;

} //End Function

function LTrim(VALUE){
	var w_space = String.fromCharCode(32);
	if(v_length < 1){
		return"";
	}
	var v_length = VALUE.length;
	var strTemp = "";
	
	var iTemp = 0;
	
	while(iTemp < v_length){
		if(VALUE.charAt(iTemp) == w_space){
		}
		else{
			strTemp = VALUE.substring(iTemp,v_length);
			break;
		}
		iTemp = iTemp + 1;
	} //End While
	return strTemp;
} //End Function


onload = function(){
	popupWindows();
	if(document.getElementById('printWindow')) printit();
	if(document.getElementById('closeWin')) closePop();
	if(document.getElementById('backBtn')) back_button();
	
	//work around for mozilla based browsers, will set the variable used to determine the element that has focus
	if (typeof document.activeElement == "undefined") {
		document.addEventListener("focus", function(event) { document.activeElement = event.target; }, true);
	}
}

//function is used to make <select> boxes disabled
function toggleSelect (select) {	
  if (!select.disabled) {
    select.disabled = true;
    if (!document.all && !document.getElementById) {
      select.oldOnFocus = 
        select.onfocus ? select.onfocus : null;
      select.onfocus = skip;
    }
  }
  else {
    select.disabled = false;
    if (!document.all && !document.getElementById) {
      select.onfocus = select.oldOnFocus;
    }
  }
}

//function disable form elemnet or enables it depending on its state
function disableIt(obj) {
	obj.disabled = !(obj.disabled);
	var z = (obj.disabled) ? 'disabled' : 'enabled';
	//alert(obj.type + ' now ' + z);
}

//function test if the object it is passed exists.
function testIsValidObject(objToTest) {
	if (null == objToTest) {
		return false;
	}
	if ("undefined" == typeof(objToTest) ) {
		return false;
	}
	return true;
}

/*
 * The following functions are used to hide / show an element on a page.
 */
function getStyleObject(objectId) {
	// checkW3C DOM, then MSIE 4, then NN 4.
	//
	if(document.getElementById && document.getElementById(objectId)) {
		return document.getElementById(objectId).style;
	} else if (document.all && document.all(objectId)) {  
		return document.all(objectId).style;
	} else if (document.layers && document.layers[objectId]) { 
		return document.layers[objectId];
	} else {
		return false;
	}
}

function changeObjectDisplay(objectId, newVisibility) {
	// first get the object's stylesheet
	var styleObject = getStyleObject(objectId);
	
	// then if we find an object, set its visibility as requested
	//
	if (styleObject) {
		styleObject.display = newVisibility;
		return true;
	} else {
		return false;
	}
}

function verifyObjectDisplay(objectId, value) {
	
	if ((value == true) || (value != '' && value != " " && value != 'none')) {
		changeObjectDisplay(objectId, 'block');
	} else {
		changeObjectDisplay(objectId, 'none');
	}
}

/**
 * function receives a radio button object and returns the checked value.
 */
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function CreateXmlHttp() {
	var xmlhttp = false;
	if (typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	} else {
        /*@cc_on
        @if (@_jscript_version >= 5)
            try {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (E) {
                    xmlhttp = false;
                }
            }
        @end @*/
    }
	return xmlhttp;
}