var prevClickTime = 0;

var isIE = (navigator.appName.indexOf("Microsoft") != -1);
var isNS = (navigator.appName.indexOf("Netscape") != -1);
var isFF = (navigator.userAgent.indexOf("Firefox") != -1);
var browserVer = parseInt(navigator.appVersion);

var TimeoutId = null;
var hValidDates = null;

//lbSkipURLCheck --- sometimes the url check causes permission denied errors
// this is caused by multiple frames in a window (iframes)
function fResetTimeout(lbSkipURLCheck) {
    if( TimeoutId != null ) {
        clearTimeout( TimeoutId );
        window.status = "";
        fStartTimeout(lbSkipURLCheck);
    }
}
		
function TEDate() {
}
function isValidDate( InMonth, InDay, InYear ) {
	if( isNaN(parseInt(InYear)) == true )
		return false;
	else if( isNaN(parseInt(InMonth)) == true
		|| parseInt(InMonth) > 12
		|| parseInt(InMonth) <= 0){
		return false;
	}
	else if( isNaN(parseInt(InDay)) == true
		|| parseInt(InDay) <= 0
		|| parseInt(InDay) > 31
		|| (parseInt(InMonth)==2 && parseInt(InDay) > 29) 
		|| (parseInt(InMonth)==2 && parseInt(InDay) > 28 && parseInt(InYear)%4 > 0) 
		|| (parseInt(InMonth)==4 && parseInt(InDay) > 30) 
		|| (parseInt(InMonth)==6 && parseInt(InDay) > 30) 
		|| (parseInt(InMonth)==9 && parseInt(InDay) > 30) 
		|| (parseInt(InMonth)==11 && parseInt(InDay) > 30) 
		){
		return false;
	}
	return true;
}
TEDate.isValidDate = isValidDate;


var userTempID = null
var baseURL = null;
var Module = null;
var bResizeParent = false;
//FireFox's Back-Forward Cache will not load onload functions, but it will run this onpageshow function
function onPageShow() {
  	if( Module!="Parents") {   
	   		var ary = document.getElementsByName("ReportSubmitBtn");
	   		for(var i=0; i<ary.length; i++) {  
				ary[i].disabled=false; 
		   } 
	   if( self.fRefreshStudentSearchObjects !=null){
			fRefreshStudentSearchObjects();
	   }
	}
};  

function fStartTimeout(lbSkipURLCheck){
	try{
		var tempHref = window.location.href;
	}
	catch(e){
		var tempHref = "";
	}
	 
	if( BrowserDetect.browser == "Exlporer" && BrowserDetect.OS=="Mac")
		return;
		
		
	 //do not call timeout when not logged in or on the Logout/AutoLogout page 
	if( lbSkipURLCheck || userTempID>0 
							&& tempHref!= baseURL + "/common/Logout.aspx" 
							&& tempHref!= baseURL + "/common/Timeout.aspx" ){
		//TimeoutId = setTimeout( 'fLogoutWarning( 5 )', 2000 ); 
		// get my local time in HHMM
		var dTimeStamp = new Date();
		var hour = dTimeStamp.getHours();
		if ( hour == 0 )
		    hour = 12;

		if ( hour < 10 )
		    hour = "0" + hour;
		    
		var min = dTimeStamp.getMinutes();
		if( min < 10 )
		    min = "0" + min;
		    
		TemplateStartTime = hour + '' + min;
		    
		document.cookie = 'PageRefreshTime=' + TemplateStartTime + '; path=/';
		//Starts warning at 20 minutes before Server timeout. 15 Recursive calls to update the status bar
		   //Stated time to users is 5 minutes less than actual Server Timeout. 
    	TimeoutId = setTimeout( 'fLogoutWarning( 15 )', ( TemplateTimeoutMin - 20 ) * 60000 );
	}  
} 
            
function _dropPopup() {
    if( self.dropIframe )
		dropIframe();
    if( self.dropPopup )
        dropPopup()
    
    if( parent ) { 
	    if( parent.dropIframe )
			parent.dropIframe();
	    if(parent.dropPopup)
	        parent.dropPopup();
    }
}
function keyPressHandler(e) {
   var kC  = (window.event) ? event.keyCode : e.keyCode;  // MSIE or Firefox?
   var Esc = (window.event) ? 27 : e.DOM_VK_ESCAPE  // MSIE : Firefox
   if(kC==Esc)
        _dropPopup()
}
    
function ClickHandler( e ) {
	var curClickTime = (new Date()).getTime();
	if( (curClickTime-prevClickTime) >= 5000 ) {
		prevClickTime = curClickTime;
		return true;
	}
	else 
		return false;
}

function fLoadTimeoutWarning() {
	return true;
}

function disableFilters(selectedOption ,filterArray){ 
	if(filterArray !=null){   
		for(var i=0; i<filterArray.length;i++){
			if( filterArray[i] == null)
				continue;
			for(var j=0; j<filterArray[i].length; j++){
				if(filterArray[i][j]!= null && i!=selectedOption)
					filterArray[i][j].disabled=true;
			}
		}
		for(var i=0; i<filterArray.length;i++){
			if( filterArray[i] == null)
				continue;
			for(var j=0; j<filterArray[i].length; j++){
				if(filterArray[i][j]!= null && i==selectedOption)
					filterArray[i][j].disabled=false;
			}
		}
	} 
}

function setDisabledByElement(e, ary){
    // we check if length is a number otherwise we know there is only one element and it doesn't need to be disabled
	if(e!=null && isNaN(parseInt(e.length))==false ) {
	     for(var i=e.length-1; i>0; i--)
	     	if(e[i]!=null && e[i].checked)
	     		break;
	    disableFilters(i, ary);
	} 
}

function fLogoutWarning( nRecurses ){
	var cookieTime = readCookie('PageRefreshTime');

	if( cookieTime == TemplateStartTime ) {
		var strMessage = "You are about to log out. You have " + nRecurses + " minutes before being logged out.";
		window.status = strMessage;
		//setTimeout( function() { fAnimateMessage( strMessage, 5 ) }, 200 );
		if( nRecurses > 1 ) 
		    TimeoutId = setTimeout( function() {fLogoutWarning( nRecurses - 1 )}, 6000 );
		else
		    TimeoutId = setTimeout( function() { fLogoutUser() }, 6000 );
	}
	else {
	    window.status = "";
	    //do nothing
	    //fTimerRecalc( cookieTime ); //recalculates the timer
	}
}

function fLogoutUser(){
	var cookieTime = readCookie('PageRefreshTime');
	if( cookieTime == TemplateStartTime ) {
	
    window.status = "You are now logged out...";

    if( bRedirectOnTimeout == true ){
	    //redirect
	    window.location = strServerURL + "/common/Timeout.aspx";
	}
	else {
	//rewrite onsubmit, disable button onsubmit/onclick, disable/change  onsubmit/onclick
	var i = 0;
	var j;
	while( document.forms[i] != null ) {
	    	j = 0;
	    	while( document.forms[i].elements[j] != null ){
	    	    //alert(document.forms[i].elements[j].name);
	    	    if( document.forms[i].elements[j].type != 'textarea' && document.forms[i].elements[j].type != 'text' ) {
	    	    	document.forms[i].elements[j].onclick = null;
	    	    	document.forms[i].elements[j].onsubmit = null;
	    	    	document.forms[i].elements[j].onchange = null;
	    	    	document.forms[i].elements[j].onclick = function(){alert('You have been logged out of TeacherEase and cannot save.');}
	    	    }
	    	    j++;
	    	}
			document.forms[i].onsubmit = null;
			document.forms[i].onsubmit = function(){return false;}
			i++;
		}
		fSessionAbandon();
		alert('You have been inactive for ' + ( TemplateTimeoutMin - 5 ) + ' minutes.  As a security measure,'
			+ ' you have been automatically\r\n logged out of' + ApplicationName + '.'
			+ 'You can NOT save the information on the current page to ' + ApplicationName + '\r\n (because you\'re now logged out). '
			+ 'Print this page (or copy/paste) to make a copy of your latest changes.\r\n\r\n'
			+ 'Please login again to continue using ' + ApplicationName + '.\r\n');

	}
}
else {
	//do nothing
	//fTimerRecalc( cookieTimer );
	}

}

function fSessionAbandon() {
   	try {
		var AjaxRequest = new ActiveXObject("Msxml2.XMLHTTP");	// new IE
	}
	catch (e) {
		try {
			var AjaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); // old IE
		}
		catch (e2) {
			try {
				var AjaxRequest = new XMLHttpRequest();	// Firefox
			}
			catch(e3) {
				var AjaxRequest = null;
			}
		}
	}	// ends Try/Catch block
	if( AjaxRequest != null ) {
		AjaxRequest.open("POST", "/common/SessionAbandon.aspx", true);  // Open a connection to the server
		AjaxRequest.onreadystatechange = function() {}; // Setup a function for the server to run after the ajax submit returns
		AjaxRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		AjaxRequest.send("");
	}	// lObjName !=null
}

function fAnimateMessage( strMessage, nMessageCount ){
    if( nMessageCount == 5 )
        window.status = strMessage;
    else if( nMessageCount == 4 || nMessageCount == 0 )
	    window.status = strMessage + " .";
	else if ( nMessageCount == 3 || nMessageCount == 1 )
	    window.status = strMessage + " . .";
	else if ( nMessageCount == 2 )
	    window.status = strMessage + " . . .";

	nMessageCount -= 1;
	if( nMessageCount >= 0 )
	    setTimeout( function() { fAnimateMessage( strMessage, nMessageCount ) }, 500 );
}

//cookie reader
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function fTimerRecalc( cookieTime ) {

	//example TemplateStartTime 2251, cookieTime was refreshed at 0013(the next day) from diff browser, start timeout in 2300 - 2251 + 0013
	if( cookieTime < TemplateStartTime ) {
	    var overFlowTime = 2300 - TemplateStartTime + cookieTime;
	}
	else {
		if( (cookieTime - TemplateStartTime) <= 15 ) {
		    fLogoutWarning( (cookieTime - TemplateStartTime) );
		}
		else {//your logout time is greater than 15 minutes, give a warning then
			setTimeout( 'fLogoutWarning( 15 )', (cookieTime - TemplateStartTime - 15 ) * 60000 );
		}
		alert(cookieTime - TemplateStartTime );
		TemplateStartTime = cookieTime;

		alert('Recalced timer to: ' + TemplateStartTime);
	}
}

function fDisplayHelp( path ) {
    var width = 1024;
    var height = 650;
    if( window.screen.availWidth < width )
        width = window.screen.availWidth - 5;
    if( window.screen.availHeight < height )
        height = window.screen.availHeight - 5;
    
    // default options
    var strOptions = ",menubar=0,resizable=1,status=0,toolbar=1,location=0"; 
    
    // special options for IE 7.0
    if( navigator.appName.indexOf("Microsoft")!=-1 && navigator.appVersion.indexOf("7.0")!=-1)    
        strOptions = ",menubar=0,resizable=1,status=0,toolbar=0,location=1";
            
    var windowName = window.open( path, "TE_Help", "height=" + height + ",width=" + width + strOptions, false );
}

function spchr_client( str ) {
	if( str != "" && str != null ){
		var strReturn = str.replace(/&/, '&amp;');
		strReturn = strReturn.replace(/\"/, '&quot;');
		strReturn = strReturn.replace(/</, '&lt;');
		strReturn = strReturn.replace(/>/, '&gt;');
		return strReturn;
	}
	else
		return "";
}

function ProcessTime( lTime ) {
	if( typeof lTime=="undefined" || lTime=="" || lTime==null || lTime.search(/[0-1]?[0-9]\:?[0-5][0-9] ?[ap]?m?/)==-1 )
		return null;

	// find hour
	var strHour = "";
	var nMinStartingPosition = -1;
	// the inString has a colon
	if( lTime.search(":") > -1 ) {
		strHour = lTime.substr( 0, lTime.search(":") );
		nMinStartingPosition = lTime.search(":") + 1;
	}
	// the string does NOT have a colon,
	// if the fourth character is a number,
	// then the hour is two characters long
	else if( lTime.length>=4 && lTime.charAt(3).search(/[0-9]/)>-1 ) {
		strHour = lTime.substr( 0, 2 );
		nMinStartingPosition = 2;
	}
	// the hour is only one character long
	else {
		strHour = lTime.substr( 0, 1 );
		nMinStartingPosition = 1;
	}

	// find min, it must be two characters long
	var strMin = lTime.substr( nMinStartingPosition, 2 );

    strHour = parseInt(parseFloat(strHour));
    strMin = parseInt(parseFloat(strMin));
    
	if( isNaN(parseInt(strHour)) || isNaN(parseInt(strMin)) ||
		parseInt(strHour)<1 || parseInt(strHour)>12 ||
		parseInt(strMin)<0 || parseInt(strMin)>59 )
		    return null;

    // find am/pm
	if( lTime.search(/[pP]/) > -1 ) {
	    if( strHour != 12 )
   			strHour += 12;
	}
    else if( lTime.search(/[aA]/) > -1 ) {
        if( strHour == 12 )
        	strHour = 0;
	}
	// if no am/pm entered, guess what it should be for a typical school day
	else if( strHour>=1 && strHour<6 ) {
		strHour += 12;
	}
	strHour = strHour%24;
	
	return new Array( strHour, strMin );

} // ProcessTime()

var menu=function(){
    var TIMER=200,HOVERID,IFRAME;
    function dd( ulid ){
        this.ULID = ulid;
        this.HEADER=[];
        this.DDLIST=[]
    }
	dd.prototype.init=function( ulid, hoverid ){
        IFRAME = document.getElementById("coverup");
        HOVERID=hoverid;
        var w=document.getElementById( ulid );
        var s=w.getElementsByTagName('ul');
		for( var i=0; i < s.length; i++ ){
            var header=s[i].parentNode;
            this.HEADER[i]=header;
            this.DDLIST[i]=s[i];
            header.onmouseover = new Function(this.ULID+'.starttimer('+i+',true)');
            header.onmouseout = new Function(this.ULID+'.starttimer('+i+',false)');
		}
	}
	dd.prototype.starttimer=function(x,f){
	    var ddlist = this.DDLIST[x];
        var header = this.HEADER[x];
        var title = header.getElementsByTagName('a')[0];
        clearTimeout( ddlist.timer )
        if( f ){
            //In TIMER miliseconds, make the list visible
            ddlist.timer = setTimeout(function(){showlist(ddlist, header, true)},TIMER)
	    }
	    else{
	        //Stop the timer.
            ddlist.timer = setTimeout(function(){showlist(ddlist, header, false)},0)
	    }
	    return;
    }
    function showlist(ddlist, header, f){
        var title = header.getElementsByTagName('a')[0];
        if( f ){
            ddlist.style.display='block';
            ddlist.style.overflow='visible';
            ddlist.style.opacity= 1;
            ddlist.style.display= 'block';
            if( title.className.indexOf(HOVERID) != -1 )
                title.className += ' '+HOVERID;
            if( isIE ){
                IFRAME.style.display = "block";
                IFRAME.style.left = (header.offsetLeft-3) + "px";
                IFRAME.style.top = "80px";
                IFRAME.style.width = ddlist.offsetWidth + "px";
                IFRAME.style.height = ddlist.offsetHeight + "px";
            }
        }
        else{
            ddlist.style.overflow='hidden';
            ddlist.style.display= 'none';
            ddlist.style.opacity=0;
            title.className=title.className.replace(' ' + HOVERID,'');
            if( isIE ){
                IFRAME.style.display = "none";
            }
        }
    }
	return{dd:dd}
}();


  
//this function returns "" as succes,
// or a string explaining why it failed.
function jsVerifyDate(objName, bCorrectFormatting, bFourDigitYear, lstrDelimeter) {
	if(lstrDelimeter == null || lstrDelimeter == "")
		lstrDelimeter = "/";
		
	var strDatestyle = "US"; //United States date style
	//var strDatestyle = "EU";  //European date style
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var datefield = objName;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr; 
	var strMonthArray = new Array( "Jan", "Feb", "Mar", "Apr", "May"
				, "Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	strDate = datefield.value;
	if (strDate == null || strDate=="" || strDate.length < 1) {
		return 0;
	}
	
	var booFound = false;
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) {
				return 1;
			}
			else {
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}
			booFound = true; 
		}
	}
	if (booFound == false) {
		if (strDate.length>5) {
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
		}
		else 
			return "date incomplete"
	}
	if (strYear.length == 2) {
		if(isNaN(strYear))
			return 4;
		if( strYear == "19")
			return "year incomplete"
		else if( strYear == "20")
			return "year incomplete"
		else if(parseInt(strYear) > 50)
			strYear = '19' + strYear;
		else
			strYear = '20' + strYear;
	}
	else if(strYear.length == 1 || strYear.length == 3)
		return "year incomplete"
	// US style
	if (strDatestyle == "US") {
		var strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	} 
	
	intday = parseInt(strDay, 10);
	if (isNaN(intday)) { 
		return 2;
	}
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) {
		//if the month is given as a string (NOV) then convert it to a number
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}
		if (isNaN(intMonth)) { 
			return 3;
		}
	}
	intYear = parseInt(strYear, 10);
	if (isNaN(intYear)) { 
		return 4;
	}
	if (intMonth>12 || intMonth<1) { 
		return 5;
	}
	if (intday < 1) { 
		return 8;
	}
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
		return 6;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
		return 7;
	}
	if (intMonth == 2) {
		if (LeapYear(intYear) == true) {
			if (intday > 29) { 
				return 9;
			}
		}
		else {
			if (intday > 28) { 
				return 10;
			}
		}
	}
	var tempDate = new Date(intMonth + "/" + intday + "/" + strYear);
	if( tempDate < new Date("1/1/1900"))
		return "date out of range";
	if(tempDate > new Date("12/31/2099"))
		return "date out of range";
	
	if(bCorrectFormatting){
		if(!bFourDigitYear) 
			strYear = strYear.substr(2);
		if (strDatestyle == "US")
			datefield.value = intMonth + lstrDelimeter + intday + lstrDelimeter + strYear;
		else
			datefield.value = intday + lstrDelimeter + strMonthArray[intMonth-1] + lstrDelimeter + strYear;
	}
	return "";
}
function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) 
			return true;
	}
	else {
		if ((intYear % 4) == 0)
			return true;
	}
	return false;
} 
//  End --> 

function TEIsNumeric(lValue, lbIntegerOnly, lbPositiveOnly, lbAllowZero, lbAllowInfinity, 
                lbAllowScientificNotation, lbAllowHexNotation){
	if(lValue == null || lValue === "" || typeof lValue == "undefined")
		return false;
		
	if(lbIntegerOnly && lValue.indexOf(".")!=-1)
		return false;
	 
	if(lbPositiveOnly && lValue < 0)
		return false;

	if(isNaN( lValue) )
		return false;
		
	if( lbAllowZero===false && lValue==0 )
	   return false;
	
	if( lbAllowInfinity != true && !isFinite(lValue) )
	   return false;
	
    if( lbAllowScientificNotation != true && (lValue+"").indexOf("e") > -1 )
        return false;

    if( lbAllowHexNotation != true && (lValue+"").indexOf("x") > -1 )
        return false;
           
	return true;
}


function findPos(obj) {
	var pos = new Object;
	pos.left = 0;
	pos.top = 0;
	
	if(obj!=null){
		if (obj.offsetParent)	{
			while (obj.offsetParent) {
				pos.left += obj.offsetLeft;
				pos.top  += obj.offsetTop; 
				var bordertop = parseInt(getStyle(obj, "borderTopWidth", "border-top-width"))
				if( isNaN(parseInt( bordertop))==false)
					pos.top += bordertop
				var borderleft = parseInt(getStyle(obj, "borderLeftWidth", "border-left-width"))
				if( isNaN(parseInt( borderleft))==false)
					pos.left += borderleft  
				obj = obj.offsetParent;
				
			};
		}	
		else if (obj.x) {
			pos.left = obj.x;
			pos.top = obj.y;
		};
	}
	return pos;
};

function getScreenSize(){
	var pos = new Object;
	pos.width = 0;
	pos.height = 0; 
	 
	 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	 
	 if (typeof window.innerWidth != 'undefined')
	 {
	      pos.width = window.innerWidth,
	      pos.height = window.innerHeight
	 }
	 
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	
	 else if (typeof document.documentElement != 'undefined'
	     && typeof document.documentElement.clientWidth !=
	     'undefined' && document.documentElement.clientWidth != 0)
	 {
	       pos.width = document.documentElement.clientWidth,
	       pos.height = document.documentElement.clientHeight
	 }
	 
	 // older versions of IE
	 
	 else
	 {
	       pos.width = document.getElementsByTagName('body')[0].clientWidth,
	       pos.height = document.getElementsByTagName('body')[0].clientHeight
	 }
	 return pos;
 }
 
function getScrollOffset() {
    var dim = new Object()
    dim.width = 0
    dim.height = 0;
  
    if (parent.pageYOffset) // all except Explorer
    {
    	dim.width = parent.pageXOffset;
    	dim.height = parent.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop)
    	// Explorer 6 Strict
    {
    	dim.width = document.documentElement.scrollLeft;
    	dim.height = document.documentElement.scrollTop;
    }
    else if (parent &&  parent.document && parent.document.body) // all other Explorers
    {
    	dim.width = parent.document.body.scrollLeft;
    	dim.height = parent.document.body.scrollTop;
    }
    else if(document.body)
    {
    	dim.width = document.body.scrollLeft;
    	dim.height = document.body.scrollTop;
    }
    return dim;
} 

function getPageSize() {
    var dim = new Object()
    dim.width = 0
    dim.height = 0;
     
    if (document.body.scrollHeight > document.body.offsetHeight) 
    	dim.height = document.body.scrollHeight; 
    else
    	dim.height = document.body.offsetHeight;
    	
    if (document.body.scrollWidth > document.body.offsetWidth) 	
    	dim.width = document.body.scrollWidth; 
    else  
    	dim.width = document.body.offsetWidth; 
    
    return dim;
}

function getParentWindowSize() {
  var dim = new Object()
  dim.width = 0
  dim.height = 0;
  if( typeof( parent.window.innerWidth ) == 'number' ) {
    //Non-IE
    dim.width = parent.window.innerWidth;
    dim.height = parent.window.innerHeight;
  } else if( parent.document.documentElement && ( parent.document.documentElement.clientWidth || parent.document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    dim.width = parent.document.documentElement.clientWidth;
    dim.height = parent.document.documentElement.clientHeight;
  } else if( parent.document.body && ( parent.document.body.clientWidth || parent.document.body.clientHeight ) ) {
    //IE 4 compatible
    dim.width = parent.document.body.clientWidth;
    dim.height = parent.document.body.clientHeight;
  }
  return dim;
}

function resizeParent(bAvoidReposition) { 
 	var elem = parent.document.getElementById('edit_popup')
 	if(elem ==null)
 		return;
 	elem.style.display="";
 		
	var windowSize = getParentWindowSize(); 
	var pageSize = getPageSize();   
 		

// 	height += elem.style.paddingTop + elem.style.paddingBottom
	elem.style.height = document.body.offsetHeight + "px";
 	var height = document.body.scrollHeight;
 	if(isIE)
		height += 8;
	elem.style.height = height + "px";  
	
	var width = pageSize.width; 
 	elem.style.width = width + "px";   
	
	if( bAvoidReposition != true){
			// center popup, if it can fit on the entire screen. 
		var top =  (windowSize.height - height )/2       
	 	if(top < 0)
	 		top = 5;
	 	top += parent.document.body.scrollTop;  
		var left = (windowSize.width - width )/2  
	 	if(left < 0)
	 		left = 5; 
		elem.style.top = top  + "px";
		elem.style.left = left + "px";
	} 
	return false;
}
function dropIframe(){
    var popup = document.getElementById("edit_popup");
    if(popup != null && popup.style.display!="none"){
        popup.style.display = 'none'; 
        //resizeParent();
	}
	
    var trans = document.getElementById("edit_trans");
    if(trans != null)
	    trans.style.display = 'none';

	var coverFrame = document.getElementById("edit_coverup");
	if(coverFrame != null)
	    coverFrame.style.display = 'none';
	
	if( isIE )
        window.onresize = '';
}

function addIframe(url){
    fResetTimeout();
    
    //var page = getPageSize();
    var screen = getScreenSize();
    
/*  //there is some way to fix select boxes from showing through the transparent div....for now this is not working  
    var coverFrame = null;
	if(false && BrowserDetect.browser == "Explorer" && BrowserDetect.version == 6){  
    	coverFrame = document.createElement( "iframe" );
		coverFrame.src = "../common/blank.html";
	    coverFrame.setAttribute( 'id', 'edit_coverup' );   
    	coverFrame.className = "coverup" ;   
    	coverFrame.style.zIndex=10;   
	    coverFrame.style.display = ""  
	    coverFrame.style.backgroundColor = "red";
		document.body.appendChild( coverFrame ); 
    }*/
    
    // Create an overlay to darken the area behind the popup
    var new_fade = document.getElementById('edit_trans');
    if( !new_fade ) {
        var new_fade = document.createElement( "div" );
        new_fade.setAttribute( 'id', 'edit_trans' );  
        new_fade.setAttribute( 'class', 'transparency' );
        new_fade.setAttribute( 'className', 'transparency' );
        new_fade.style.display = 'none';  
        document.body.appendChild( new_fade );
    }
   
    //new_fade.style.height = page.height;
    //new_fade.style.width = page.width;   	
    if( isIE ) {  
        window.onresize = resizeTransparency; 
        new_fade.style.height = screen.height;
        new_fade.style.width = screen.width;  
    }      
    else {
        new_fade.style.height = '100%';
        new_fade.style.width = '100%';  
    }
    new_fade.style.display = '';  
	
 	var new_iframe = document.getElementById('edit_popup');
    if( !new_iframe ) {
        new_iframe = document.createElement( "iframe" );
        new_iframe.setAttribute( 'id', 'edit_popup' );
        new_iframe.setAttribute( 'class', 'popup_iframe' );
        new_iframe.setAttribute( 'className', 'popup_iframe' ); 
           
        //new_iframe.style.width = (getScreenSize().width * .8) +"px"
        new_iframe.style.position = 'absolute'; 
        new_iframe.style.display = "none";
        
    //it is best to add the iframe to the page_contents div so that the css is properly inherited
        // add the widget and overlay to the page
        var containerElem = document.getElementById("page_contents");
    	if(containerElem != null && containerElem.tagName!='TABLE') 
    	    containerElem.appendChild( new_iframe ); 
    	else
    	    document.body.appendChild( new_iframe ); 
    }  
	//new_iframe.onresize=resizeParent;
	new_iframe.onkeyup = keyPressHandler;
	new_iframe.setAttribute( 'src', url );
    
	if( document["onkeyup"] == null || document["onkeyup"]  == "")
		document["onkeyup"] = keyPressHandler; 
	
	return new_iframe; 
}

function resizeTransparency() {
    var overlay = document.getElementById('edit_trans');
    if( overlay ) {
        var screen = getScreenSize();
        overlay.style.height = screen.height;
        overlay.style.width = screen.width;          
    } 
}

function getWindowSize() {
  var dim = new Object()
  dim.width = 0
  dim.height = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    dim.width = window.innerWidth;
    dim.height = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    dim.width = document.documentElement.clientWidth;
    dim.height = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    dim.width = document.body.clientWidth;
    dim.height = document.body.clientHeight;
  }
  return dim;
}  
function TEGetAjaxObject( url, argsToPost, onReadyStateChangeFunctionName, lbAsync ) { 
    fResetTimeout(); 
    try { 
        ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");	// new IE 
    }  
    catch (e) { 
        try { 
            ajaxObject = new ActiveXObject("Microsoft.XMLHTTP"); // old IE 
        }  
        catch (e2) { 
            try { 
                ajaxObject = new XMLHttpRequest();	// Firefox   
            }  
            catch(e3) { 
                ajaxObject = null;   
            } 
        } 
    }	// ends Try/Catch block 
    if(lbAsync!=false && lbAsync!=0 ) 
    	lbAsync=true 
    if(!lbAsync && onReadyStateChangeFunctionName != null) 
        alert('do not send in onReadyStateChangeFunctionName when lbAsync is false'); 
    if( ajaxObject != null ) {  
        ajaxObject.open("POST", url, lbAsync );  // Open a connection to the server 
        if(onReadyStateChangeFunctionName != null) 
            ajaxObject.onreadystatechange = onReadyStateChangeFunctionName;  // Setup a function for the server to run after the ajax submit returns      
        ajaxObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');   
        ajaxObject.send(argsToPost);	 
    }// lObjName !=null 
    return ajaxObject; 
}


//lID: The id of your div, if it already exists it will not create anything
//lHTML: What you want to appear in the div
//lWidth: Default is 350. Set in px
//lHeight: Default is 50. Set in px
//lbVisible: Good for creating divs at page load and showing them later on. 
//      Sometimes animated gif might not animate on submitting pages as the image
//      isn't fully loaded when created at page submit.
//lTopOffset: Will place in the middle of the window if not passed in
//lLeftOffset: Will place in the middle of the window if not passes in
//lbShowLoadingIcon: Places a loading icon and your html in a table. You can acheive
//          the same effect by passing in the table an icon and your message as lHTML instead
//NOTE: If you want to add a div at page creation you need to place this function in bodycode as IE
//      will not allow you to dynamically append DOM objects while the DOM tree is being built.
//      Depending on your page setup, you may need to display the image AFTER you submit the page as IE
//      will freeze the animation if it is placed before the submit. ImportExportPictures.aspx has an example...
function popUpDiv( lID, lHTML, lWidth, lHeight, lbVisible, lTopOffset, lLeftOffset, lbShowLoadingIcon ) {
   
	var newdiv = document.getElementById(lID);
	if( newdiv==null ){
	    var newdiv = document.createElement('div');
	    newdiv.setAttribute('id', lID);
	    newdiv.setAttribute( 'class', 'popup_div');
	    newdiv.setAttribute( 'className', 'popup_div'); 

	//it is best to add the popup to the page_contents div so that the css is properly inherited
	    var containerElem = document.getElementById("page_contents"); 
		if(containerElem != null && containerElem.tagName!='TABLE') 
		    containerElem.appendChild( newdiv ); 
		else
		    document.body.appendChild( newdiv ); 
    
    } 
        
    if (lbShowLoadingIcon) {
        newdiv.innerHTML = "<table border=0 cellpadding=3 cellspacing=0 width=100% height=100% ><tr valign=middle>"
            + "<td><img id=img" + lID + " src=\"../images/LoadingAnimatedClearLarge.gif\"></td>"
            + "<td>" + lHTML + "</td></tr></table>";
    }
    else
        newdiv.innerHTML = lHTML;
    
    if( isNaN(parseFloat(lWidth))==false )
        newdiv.style.width = lWidth; 

    if( isNaN(parseFloat(lHeight))==false )
        newdiv.style.height = lHeight; 
        
    var ScrollPos = getScrollOffset();    
    var scrolledX = ScrollPos.width;
    var scrolledY = ScrollPos.height;
    
    // Next, determine the coordinates of the center of browser's window
    var ScreenPos = getScreenSize();
    var centerX = ScreenPos.width;
    var centerY = ScreenPos.height;

    // Xwidth is the width of the div, Yheight is the height of the
    // div passed as arguments to the function:
    newdiv.style.display = '';
    var topoffset = (isNaN(parseFloat(lTopOffset))==false?lTopOffset:scrolledY + (centerY - parseInt(newdiv.offsetHeight)) / 2);
    var leftoffset = (isNaN(parseFloat(lLeftOffset))==false?lLeftOffset:scrolledX + (centerX - parseInt(newdiv.offsetWidth )) / 2);
	if( topoffset < 10 )
		topoffset = 10;
	if( leftoffset < 10 )
		leftoffset = 10;
    if( !lbVisible )
        newdiv.style.display = 'none';
    else
        newdiv.style.display = '';
        
    if( isNaN(parseFloat(topoffset))==false )
        newdiv.style.top = topoffset + 'px';
    if( isNaN(parseFloat(leftoffset))==false )
        newdiv.style.left = leftoffset + 'px';

	if( document["onkeyup"] == null || document["onkeyup"]  == "")
		document["onkeyup"] = keyPressHandler; 
		
    return newdiv;
}

/*
http://www.quirksmode.org/js/detect.html
*/
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: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			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.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function submitForm(f){ 
	if(f.onsubmit==null || f.onsubmit(f)!=false){ 
		f.submit(); 
	}
}


function coverObjectInIframe( obj, id ) {
	if(  BrowserDetect.browser == "Explorer" && parseInt(BrowserDetect.version) == 6){
		if( id == null || typeof id == "undefined" || id=="")
			id = "edit_coverup"
		var cover = document.getElementById(id);
		if( cover == null){
			var cover = document.createElement("iframe");
		    cover.setAttribute( 'id', id );   
	    	cover.className = "coverup" ;   
	    	cover.style.zIndex=10;   
			var containerElem = document.getElementById("page_contents"); 
			if(containerElem != null && containerElem.tagName!='TABLE') 
			    containerElem.appendChild( cover ); 
			else
			    document.body.appendChild( cover ); 
		} 
	    cover.src = "javascript:'<html></html>'";
		var pos = findPos(obj);
		cover.style.top = pos.top + "px";
		cover.style.left = pos.left + "px";
		cover.style.width = obj.offsetWidth + "px";
		cover.style.height = obj.offsetHeight + "px";
		cover.style.display = "block";  
	}
}

var bUsesFloatingHeader = null;

function fBodyOnScroll(e){  
	if(  BrowserDetect.browser == "Explorer" && parseInt(BrowserDetect.version) == 6){
        var cover = document.getElementById("edit_coverup");
		if( cover != null && cover.style.display != "none"){
			cover.style.display = "none";
			cover.style.display = "block";
		}  
	} 
	if( bUsesFloatingHeader == null){
	 	if( document.getElementById("floatingTopButtons")!=null)
	 		bUsesFloatingHeader = true;
	 	else{ 
	 		bUsesFloatingHeader = false;
            for( var z=0;z<aFloatingHeaders.length;z++){
				 if( document.getElementById(aFloatingHeaders[z]) != null)
				 	 bUsesFloatingHeader = true;
			} 
	 	}
	}

 	if( bUsesFloatingHeader ) {
		fMoveFloatingHeader();
    } 
}

var pageName = null;
//the following code is used to implement a table header that will scroll down with the page
//To make a single row on your page a fixed header set that <tr>'s id = floatingHeaderRow
//to set multiple floating header rows (more than 1 table on that page) add those 
	// row ids to the aFloatingHeaders array in an init function
var aFloatingHeaders = new Array("floatingHeaderRow"); 
var lastHeaderString = "";
var hLastPos = {};
var nFloatingHeaderVerticalAdjustment = 0;
var bAdjustForAnchor = true;
function fMoveFloatingHeader(){

		
    var scroll =  getScrollOffset();
	var nMaxWidth = 0;
	var doc = document;
	if( parent.document ) {
		if( parent.document )
			doc = parent.document;
		else if( window.top.document )
			doc = window.top.document
		
		var eParent = doc.getElementById("iframe_body");
		if( eParent != null){
			var parentPos = findPos(eParent);
			scroll.height -= parentPos.top;
			scroll.width -= parentPos.left;
			if( BrowserDetect.browser == "Explorer" )
				parentPos.left += 2;
			if( scroll.width < 0 )
				scroll.width = 0;
		}
		else
			doc = document;
	}
	else
		var eParent = null;
	
	//we only want to bAdjustForAnchor in the very first loading of the page
	var eAnchor = null;
	if( bAdjustForAnchor == true){
		bAdjustForAnchor = false;
		//an anchor tag will be at the very end of the url seperated by a #
		
		try{
			var tempHref = window.location.href;
		}
		catch(e){
			var tempHref = "";
		}
	
		var atemp = tempHref.split("#");
		if( atemp.length == 2){
			//get the name of the anchor element
			var anchorname = atemp[1];
			var etemp = document.getElementsByName(anchorname)
			if( etemp != null && etemp.length > 0)  
				eAnchor = etemp[0]; 
		} 
	}  
		
	if( eParent == null){
		var parentPos = {}
		parentPos.top=0;
		parentPos.left=0;
	} 
	
	var div = doc.getElementById("floatingHeaderFloatingDiv");
	 
	if(  BrowserDetect.browser == "Explorer" && parseInt(BrowserDetect.version) == 6){ 
		var buttons = null;
	}
	else{
		var buttons = document.getElementById("floatingTopButtons");
		if( buttons != null){
			if( hLastPos[ "floatingTopButtons" ] == null)
				var buttonPos = hLastPos[ "floatingTopButtons" ] = findPos(buttons);
			else
				var buttonPos = hLastPos[ "floatingTopButtons" ]  
				
			nMaxWidth = buttons.offsetWidth;
		}
	}	
	var bOneShown = false;
	var strOut = "";
	var curFloaterHeight = 0;
	 
	
	if( buttons!=null && buttonPos.top < scroll.height -  nFloatingHeaderVerticalAdjustment ){ 
		strOut += "<div>" + buttons.innerHTML + "</div>" 
		curFloaterHeight += buttons.offsetHeight + 3; 
	}
	var tbl=null
	var strTable = "";
	if( false ){ //debugging code
		strTable += "<tr><td colspan=100>pageName: " + pageName + "<BR>"
		if(eParent != null)
			strTable +=  "parentPos.top:" + parentPos.top + " ---- parentPos.left:" + parentPos.left + "<br>" 
		strTable += "scroll.height:" + scroll.height + " ---- scroll.width:" + scroll.width + "<br>"
		if( buttons) 
			strTable += "buttonPos.top:" + buttonPos.top + " ---- buttonPos.left:" + buttonPos.left + "<br>"  
		strTable += "</td></tr>";
	}
	for( var z=0;z<aFloatingHeaders.length;z++){
		var lRowID = aFloatingHeaders[z]; 
		var row = document.getElementById(lRowID);
		if(row == null)
			continue;
		tbl = row.offsetParent; 
		if( tbl == null)
			continue;
		var tblWidth = tbl.offsetWidth;
		
		if( hLastPos[ lRowID ] == null)
			var rowPos = hLastPos[ lRowID ] = findPos(tbl);
		else
			var rowPos = hLastPos[ lRowID ] 
		
		if( rowPos.top > scroll.height + curFloaterHeight - nFloatingHeaderVerticalAdjustment  ){
			//if the top of the table is not above the top of the page then hide the floating header and return
			continue;
		}
		else{
			var cell1Height = row.cells[0].offsetHeight;
			if( scroll.height  > rowPos.top + tbl.offsetHeight - cell1Height - curFloaterHeight){
				//its off the bottom 
				continue;
			} 
			//if the div does not exist yet create it
			if( tblWidth > nMaxWidth)
				nMaxWidth = tblWidth;
			
			if( cell1Height > 50 )
				cell1Height = 50
			if( strTable == "")
				strTable = "<table style='text-align:left;margin:0;border-bottom-style:none;width:" + tbl.offsetWidth + "px;' border cellpadding=3 cellspacing=0>"
			var strRow = "<tr id=template_floating_" + lRowID + ">";
			//cycle through each cell for this row and recreate the cells with the correct widths
			for( var i=0;i<row.cells.length;i++){
				var cell = row.cells[i];
				if( cell.style.display =="none" || cell.offsetWidth ==0)
					continue; 
				var strippedWidth = cell.offsetWidth;
				//the offsetWidth = Border + Padding + cellWidth
				// so to calculate the cell width we need to subtract out these extras 
				var paddingLeft = parseInt(getStyle(cell, "paddingLeft", "padding-left"))
				if( isNaN(paddingLeft) ==false)
					strippedWidth -= paddingLeft
					
				var paddingRight = parseInt(getStyle(cell, "paddingRight", "padding-right"))
				if( isNaN(paddingRight) ==false)
					strippedWidth -= paddingRight
							
				//for some reason we only need to use one of the borders.. we chose the right border
				var border = parseInt(getStyle(cell, "borderRightWidth", "border-right-width"))
				if( isNaN(border) ==false)
					strippedWidth -= border 
				
				if( cell.tagName.toString().toLowerCase() == "td")
					var strCell = "<td";
				else
					var strCell = "<th";
				
				if( cell.colSpan != null && cell.colSpan>1)
					strCell += " colspan=" + cell.colSpan + " "
				if( cell.rowSpan != null && cell.rowSpan>1)
					strCell += " rowSpan=" + cell.rowSpan + " "
				
				strCell += " style=\"padding-left:" + paddingLeft + "px;padding-right:" + paddingRight + "px;width:" + strippedWidth + "px;height:" + cell1Height + "px;"
				strCell += "height:" + cell.offsetHeight + "px;" 
				var temp = getStyle( cell, "backgroundImage", "background-image")
				if( temp == "none" || temp=="")
					strCell += "background-image:none;";
				strCell += "\"" 
				if( cell.className != "")
					strCell += " class='" + cell.className + "' " 
			 	/*
			 	if( typeof cell.onclick != "undefined" && cell.onclick!=null){ 
			 		if(BrowserDetect.browser != "Safari") { //Safari does not handle this well
				 		if( cell.onclick.toString().indexOf("fSortTableNow")!=-1) 
					 		strCell += " onclick='" + cell.onclick + "(event);'" 
				 		else 
					 		strCell += " onclick='fSortTableNow(event);'" 
				 	}
			 	}
			 	*/
				strCell += ">"   
				var strTemp = cell.innerHTML ;
				if( strTemp.indexOf("checkbox") != -1 )
					strTemp = "&nbsp;"
				strCell += strTemp
				strCell +=  "</th>";
				strRow += strCell;
			} 
			strTable += strRow + "</tr>"
			curFloaterHeight += cell1Height;
		} 
	}
	if( strTable != ""){ 
		strOut += strTable + "</table>";
	}
	if( curFloaterHeight > 0){ 
		//if adjusting for anchor shift the scroll position appropriately
		if( eAnchor != null){
			var tempPos = findPos( eAnchor);
			document.body.scrollTop = tempPos.top - curFloaterHeight - 6;
			fMoveFloatingHeader(); //now that the scroll has changed restart the function
			return null;
			//  
		}
		
		if( div == null){ 
			var div = doc.createElement("div");
			div.setAttribute("id", "floatingHeaderFloatingDiv");
			div.style.display = 'none'; 
			div.className = "floatingHeaderFloatingDiv"; 
		    var containerElem = doc.getElementById("page_contents");
			if(containerElem != null && containerElem.tagName!='TABLE') 
			    containerElem.appendChild( div ); 
			else
			   	doc.body.appendChild( div );    
		}
		if( tbl == null)
			rowPos = findPos(buttons)
			 
		if(BrowserDetect.browser != "Explorer"){
			if( scroll.width == 0){ 
				var targetTop = 0;
				var targetPosition = "fixed";  
			}
			else{
				var targetTop = scroll.height;
				var targetPosition = "absolute";  
			} 
			//if( parseInt(div.style.top) != parseInt(targetTop)  )
				div.style.top = targetTop; 
			//if( div.style.position != targetPosition )
				div.style.position = targetPosition;
		}
		//if( lastHeaderString != strOut )
			div.innerHTML = strOut;
		lastHeaderString = strOut;
		div.style.left = rowPos.left + parentPos.left;
		div.style.display='block';
		div.style.width = nMaxWidth + "px";
		coverObjectInIframe(div, "floatingDivCoverFrame")	
	}
	else{
		if( div != null){
			div.style.display='none'; 
			var coverFrame = doc.getElementById("floatingDivCoverFrame");
			if(coverFrame != null)
			    coverFrame.style.display = 'none';
		}
	}
	bUsesFloatingHeader = true;
}

 
//getStyle will return the actual style used, not just the ones set 
	//( so if .padding =3, then both paddingLeft and paddingRight have values)
	// or if the element is inheriting the value, its calculated value is returned 
//the difference between styleProp and style2 is that 
	///firefox uses 'padding-left' 
	//while the IE implementation uses 'paddingLeft'
function getStyle(elem,styleProp1, styleProp2)
{
	if (elem.currentStyle)
		var y = elem.currentStyle[styleProp1];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(elem,null).getPropertyValue(styleProp2);
	return y;
}

// Index is the minute. returns equivalent hours based on MO clock
var aAttendanceMinutesToHours = new Array( 0, 0.02, 0.04, 0.05, 0.06, 0.08, 0.10, 0.12, 0.14, 0.15, 0.16, //0-19
											 0.18, 0.20, 0.22, 0.24, 0.25, 0.26, 0.28, 0.30, 0.32, 0.34, //11-20
											 0.35, 0.36, 0.38, 0.40, 0.42, 0.44, 0.45, 0.46, 0.48, 0.50, //21-30
											 0.52, 0.54, 0.55, 0.56, 0.58, 0.60, 0.62, 0.64, 0.65, 0.66, //31-40
											 0.68, 0.70, 0.72, 0.74, 0.75, 0.76, 0.78, 0.80, 0.82, 0.84, //41-50
											 0.85, 0.86, 0.88, 0.90, 0.92, 0.94, 0.95, 0.96, 0.98 //51-59
											 );

// Index is the decimal portion of the hours (e.g. .42 = 42, .05 = 5, etc.). Returns equivalent minutes based on MO clock
var aAttendanceHoursToMinutes = new Array( 0, 0, 1, 1, 2, 3, 4, 4, 5, 5, 6, //0-10
											 6, 7, 7, 8, 9, 10, 10, 11, 11, 12, //11-20
											 12, 13, 13, 14, 15, 16, 16, 17, 17, 18, //21-30
											 18, 19, 19, 20, 21, 22, 22, 23, 23, 24, //31-40
											 24, 25, 25, 26, 27, 28, 28, 29, 29, 30, //41-50
											 30, 31, 31, 32, 33, 34, 34, 35, 35, 36, //51-60
											 36, 37, 37, 38, 39, 40, 40, 41, 41, 42, //61-70
											 42, 43, 43, 44, 45, 46, 46, 47, 47, 48, //71-80
											 48, 49, 49, 50, 51, 52, 52, 53, 53, 54, //81-90
											 54, 55, 55, 56, 57, 58, 58, 59, 59 //91-99
										  );

function fConvertAttendanceMinutesToHours( lMinutes ) {
    if( isNaN(parseInt(lMinutes)) )
		return 0;

	var nHours = Math.floor(lMinutes/60);
	var nIndex = parseInt(lMinutes%60);
	var nDecimalHours = aAttendanceMinutesToHours[nIndex]

	return Math.round((nHours + nDecimalHours)*100)/100
}

function fConvertAttendanceHoursToMinutes( lHours ) {
    if( isNaN(parseFloat(lHours)) )
		return 0;

	var nMinutes = Math.floor(lHours)*60;
	var nIndex = parseInt(Math.round(lHours-Math.floor(lHours)*100)/100*100);
	var nTempMinutes = aAttendanceHoursToMinutes[nIndex]

	return (nMinutes + nTempMinutes)
}

function formatCurrency( lValue ) {
	lValue = lValue.toString().replace(/\$|\,/g,'');
	fValue = parseFloat(lValue);

	blnSign = (fValue == (fValue = Math.abs(fValue)));
	fValue = Math.floor(fValue*100+0.50000000001);
	intCents = fValue%100;
	strCents = intCents.toString();
	fValue = Math.floor(fValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((fValue.length-(1+i))/3); i++)
		fValue = fValue.substring(0,fValue.length-(4*i+3))+','+
		fValue.substring(fValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '$' + fValue + '.' + strCents);
}
var aDaysOfWeek = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var aShortDaysOfWeek = new Array("Sun", "Mon", "Tues", "Wed", "Thu", "Fri", "Sat");
var aAbbrevDayOfWeek = new Array("Su", "M", "Tu", "W", "Th", "F", "Sa");

function getShortDate( inDate, bShowDayOfWeek, lFormat, lDelimiter ) {
	// strip off single quotes if they exist
	if( inDate!=null && isNaN(Date.parse(inDate)) && inDate.toString()!=null &&
		inDate.toString()!="" && inDate.toString().charAt(0)=="'" ) {
		var aTemp = inDate.split("'");
		inDate = aTemp[1];
	}
	if( inDate == null || inDate == "" || isNaN(Date.parse(inDate)) ) {
		return "";
	}
	var newDate = new Date( inDate );
	if( parseInt(newDate.getFullYear()) < 1902)
		return "";
	var strReturn = ""
	
	if( lDelimiter==null || lDelimiter=="" || typeof lDelimiter=="undefined" )
	    lDelimiter = " ";
	
	if( bShowDayOfWeek == true ){
		if(lFormat=="VERYSHORT")
			strReturn+= aShortDaysOfWeek[newDate.getDay()] + lDelimiter;
		else
			strReturn+= aDaysOfWeek[newDate.getDay()] + lDelimiter;
	}
	strReturn+=(newDate.getMonth()+1) + "/" +  newDate.getDate() +"/"
	if(lFormat=="VERYSHORT")
		strReturn+=newDate.getFullYear().toString().substr(2,2)
	else
		strReturn+=newDate.getFullYear();
		
	return strReturn;
}

function fHideCalender(){
	var calendar_widget = document.getElementById('calendar_widget');
	if( calendar_widget != null)
		calendar_widget.style.display = 'none';
}
		
function fDateFieldKeyUp(elem, fOnChange){
	var elemMsg = document.getElementById( "TEDateSpan" + elem.id)
	if( elemMsg == null) { 
		if( elem.value.toLowerCase() == "today")
			return
		jsVerifyDate(elem, true, true, null);
		return;
	}
	else
		elemMsg.style.display = 'none';
	if( elem.value.toString().replace(/ /g, "") == "") {
	    fHideCalender();
	    if( fOnChange!=null )
    	    fOnChange(elem);
		return;
	}
		
	if( elem.value.toLowerCase() == "today"){
		fHideCalender();
		return;
	}
	
	var verifyRet = jsVerifyDate(elem, true, true, null)
	if(  verifyRet != "" ){
		if( parseInt(verifyRet) >=6 && parseInt(verifyRet)<=10){
			elemMsg.style.display = '';
			elemMsg.innerHTML = "Error: Invalid date.";
		}  
		return; //this means it is not a valid date
	}
	
	var temp = getShortDate(elem.value);
	if( temp == "" ){  
		elemMsg.style.display = '';
		elemMsg.innerHTML = "Error: Invalid date."; 
		return; //this means it is not a valid date
	}
	if( hValidDates != null && elemMsg != null){
		if( hValidDates[ temp ] != 1){ 
			elemMsg.style.display = '';
			elemMsg.innerHTML = "Error: Date out of range.";
			return;
		}
	}
	
    fHideCalender();
	if( fOnChange!=null )
    	fOnChange(elem);
}


function fShowDateField(lName, lCurValue, strOnChangeFunction){
		if(lName == null || lName == "")
			lName = "date"; 
				
		if( strOnChangeFunction == null)
			strOnChangeFunction = "";
		else if( strOnChangeFunction != "" && lType != SINGLEINPUT)
			strOnChangeFunction = " onchange='" + strOnChangeFunction + ";' "
			
		// strip off single quotes if they exist
		if( lCurValue!=null && isNaN(Date.parse(lCurValue)) && lCurValue.toString()!=null &&
			lCurValue.toString()!="" && lCurValue.toString().charAt(0)=="'" ) {
			var aTemp = lCurValue.split("'");
			lCurValue = aTemp[1];
		}
		if( lCurValue == null || lCurValue == "" || isNaN(Date.parse(lCurValue)) ) {
			lCurValue = "";
			var targetDate = null;
		}
		else{
			var targetDate = new Date( TEDate.getShortDate(lCurValue) );
			lCurValue = TEDate.getShortDate( lCurValue);
		}
			
		var strOut = "";
		strOut += ("<input type=hidden name='TEDateType" + lName + "' value=1>");
		strOut += ("<span style='white-space:nowrap;'>");
		strOut += ("<input size=8 onkeyup='fDateFieldKeyUp(this );" + strOnChangeFunction + "' onchange='" + strOnChangeFunction + "' type=textbox value='" + lCurValue + "' name=" + lName + " id=" + lName + ">");
		
		strOut += ( "<span tabindex=-1 style='cursor:pointer' onclick='show_calendar_widget(this);' id='date_link' class='calendar-link'><img class=calendar_img tabindex=-1 src='../images/cal.gif' border=0 ></span>" );
		
		strOut += ("</span>");  
		strOut +=  (" <div id='TEDateSpan" + lName + "' style='color:red;display:none;'>" 
			+ "</div>");
		return strOut;
			
}

function SaveToSession( field, value){ 
	//checks are done on the server side to ensure the field is a valid one
	url = "../common/AjaxSaveToSession.aspx"
	argsToPost = "&" + field + "=" + value;
	var tempObj = TEGetAjaxObject(url, argsToPost, null, true);
}

var mainForm = null;

function fSLTRadioClick(){
	var aRadios = document.getElementsByName("where");
	
	for( var i=0;i<aRadios.length;i++){
		var eDiv = document.getElementById("sltDiv" + aRadios[i].value);
		if( eDiv == null)
			continue;
		if( aRadios[i].checked )
			eDiv.style.display = "";
		else
			eDiv.style.display = "none";
	}
	setDisabledByElement( aRadios, whereArray);

}

// This function is called in TEWhoToShow.js
// aWhoArray is defined in that class and is assumed to exist
function template_WTSinit(lForm, lbUseInstructorIDElement){
	if( lForm == null )
		return;
	
	aWhoArray = new Array(7);

	for( var i=0; i<aWhoArray.length;i++ )
		aWhoArray[i] = new Array();
	var j=0; 

    if( lForm.studentsearch ) {
    	aWhoArray[j][0]=(lForm.studentsearch);
    	aWhoArray[j][1]=(lForm.StudentID);
    	j++;
    }
    
    if( lForm.GradeLevelTypeID ) {
        aWhoArray[j][0]=(lForm.GradeLevelTypeID);	
        aWhoArray[j][1]=(lForm.checkAllGradeLevels);
        j++;
    }
    
    if( lForm.HomeroomInstructorID || (lbUseInstructorIDElement && lForm.InstructorID) ) {
        aWhoArray[j][0]=(lForm.HomeroomInstructorID);
        if( lbUseInstructorIDElement )
            aWhoArray[j][0]=(lForm.InstructorID);
        j++;	   
    }
    
    if( lForm.SGID ) {
	   aWhoArray[j][0]=(lForm.SGID);
	   j++;
    }
    
    if( lForm.DEID ) {
	   aWhoArray[j][0]=(lForm.DEID);
	   j++;
    }        
    
    if( lForm.WhoAll ) {
        aWhoArray[j][0]=(lForm.WhoAll);
        j++;
    }
    	
	setDisabledByElement(lForm.who, aWhoArray);
	if( typeof showWhoOption == "function" )
	   showWhoOption();
}

// This function is called in TESchoolLetterTemplate.js
// whereArray is defined in that class and is assumed to exist
function template_SLTinit( lForm, lbHasLetterTemplates ){
	whereArray = new Array(7);
	if( lForm == null )
		return;
		
	for( var i=0; i<whereArray.length;i++ )
		whereArray[i] = new Array();
	var j=1; 
	if( document.getElementById('slt_reporttitle')!=null ) 
		whereArray[j][0]=(lForm.reporttitle); 
 
    if( lForm.mailinglabel ) {
    	whereArray[++j][0]=(lForm.mailinglabel);
    	whereArray[j][1]=(lForm.nrow);
    	whereArray[j][2]=(lForm.ncolumn);
    	whereArray[j][3]=(lForm.bprintorcurrentresident); 
    	whereArray[j][4]=(lForm.bprintparentguardianof); 
    	whereArray[j][5]=(lForm.studentwithnocontacts2);
    }
    
    if( lForm.envelopetype ) {
    	whereArray[++j][0]=(lForm.envelopetype);
    	whereArray[j][1]=(lForm.bprintorcurrentresidentenvelope);
    }
	
	if( lForm.bshowheader)
		whereArray[++j][0]=(lForm.bshowheader); 
	
	if( lbHasLetterTemplates ) {
	    if( lForm.SLTID ) {
    		whereArray[++j][0]=(lForm.SLTID);
    		whereArray[j][1]=(lForm.showheader);
    		whereArray[j][2]=(lForm.changepages);
    		whereArray[j][3]=(lForm.LPP);
    		whereArray[j][4]=(lForm.printhomeroominstructor);
    		whereArray[j][5]=(lForm.studentwithnocontacts);
        }
        if( lForm.SLTID1 ) {
    		whereArray[++j][0]=(lForm.SLTID1);
    		whereArray[j][1]=(lForm.emailcontacts);
    		whereArray[j][2]=(lForm.emailstudent);
    		whereArray[j][3]=(lForm.logemail);
    		whereArray[j][4]=(lForm.previewonly);
        } 
		fCheckDisableLogEmail(lForm.where);
	}
	else
		fSLTRadioClick( ); 
	fChangeLabelLayout(lForm); 
}

function fChangeLabelLayout(lForm){ 
	if( lForm ==  null){
		if( document.addForm != null)
			lForm = document.addForm;
		else if( document.form1 != null)
			lForm = document.form1;
		else 
			return;
	}
	var e = document.getElementById('nrow'); 
	if(e!=null) { 
		for(var i=0;i<e.options.length;i++)  
			e.options[i] = null;  
		var lnRows = aMailingLabelLayouts[ lForm.mailinglabel.value][1]; 
		for(var i=1;i<=lnRows;i++)  
			e.options[i-1] = new Option(i,i);  
	}
	var e = document.getElementById('ncolumn'); 
	if(e!=null) { 
		for(var i=0;i<e.options.length;i++) 
			e.options[i] = null; 
		var lnCols = aMailingLabelLayouts[lForm.mailinglabel.value][0]; 
		for(var i=1;i<=lnCols;i++) 
			e.options[i-1] = new Option(i,i); 
	}
}  

function ParseYear( lValue ) {
    if( lValue!=null && typeof lValue!="undefined" && lValue!="" ) {
        if( lValue.toString().length > 4 )
            return parseInt(lValue.toString().substr(1));
        else
            return parseInt(lValue);
    }
    
    return parseInt(lValue);
}			

function bParseSummer( lValue ) {
    if( lValue!=null && typeof lValue!="undefined" && lValue!="" ) {
        if( lValue.toString().length > 4 )
            return true;
        else
            return false;
    }
    
    return false;
}

function fMakeModal( elem ){ 
    // Create an overlay to darken the area behind the popup
    var new_fade = document.getElementById('edit_trans');
    if( !new_fade ) {
        var new_fade = document.createElement( "div" );
        new_fade.setAttribute( 'id', 'edit_trans' );  
        new_fade.setAttribute( 'class', 'transparency' );
        new_fade.setAttribute( 'className', 'transparency' );
        document.body.appendChild( new_fade );  
    } 
    if( isIE ) {  
        window.onresize = resizeTransparency; 
        new_fade.style.height = screen.height;
        new_fade.style.width = screen.width;  
    }      
    else {
        new_fade.style.height = '100%';
        new_fade.style.width = '100%';  
    }
    new_fade.style.display = '';
    new_fade.style.zIndex = 100;
    elem.style.zIndex = 101;
}

var TE_LastPositionElem = null;
function template_fPositionResults(anchor, bContact){
	if( bContact )
		var results = document.getElementById("contactsearchresults"); 
	else
		var results = document.getElementById("searchresults");
	if( results ){
		if( anchor == null){
			if( bContact )
				anchor = document.getElementById("contactsearch" + curContactIndex);
			else
				anchor = document.getElementById("studentsearch");
		}
		if( TE_LastPositionElem == anchor)
			return;
			
		if( anchor != null){
			var pos = findPos( anchor); 
			pos.top += anchor.offsetHeight + 2;
			results.style.top = pos.top;
			results.style.left = pos.left;
			if( bContact )
				anchor.onkeydown = fHighlightContacts;
			else
				anchor.onkeydown = fHighlightStudents; 
			TE_LastPositionElem = anchor;
		}
	}
}

function fWriteActionLinkHtml( lstrAttributes, lstrClass, lstrLinkText ) {
    var strReturn = "";
    
    // Pass in any CSS classes using lstrClass instead of lstrAttributes so they are appended properly to the default class
    var strClass = "class=\"actionlink"; 
    if( lstrClass != null )
        strClass += " " + lstrClass;
    strClass += "\" ";
    
    if( lstrAttributes == null )
        lstrAttributes = "";
        
    if( lstrLinkText == null || lstrLinkText == "" )
        lstrLinkText = "clear";
        
    strReturn += "<nobr><a " + strClass + lstrAttributes + ">[" + lstrLinkText + "]</a></nobr>";
    
    return strReturn;
}

function TE_fCheckAll( elem, strNameToCheck){
	var aChks = document.getElementsByName( strNameToCheck);
	if( elem == null || aChks==null || aChks.length==0)
		return;
		
	for( var i=0;i<aChks.length;i++){
		try{
			aChks[i].checked = elem.checked;
		}
		catch (e) 
		{}
	}
}
