var prevClickTime = 0;
var template_bPopup = false;
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 hValidDates = null;

var Module = null;
var ApplicationName = '';

var userTempID = null
var baseURL = null;
var bResizeParent = false;
var bErrorLogged = false; // only log an error if one has not already been logged (one error per page)

function TEUtils() {
}
TEUtils.TE_ACTIVE = 1;
TEUtils.TE_INACTIVE = 0;
TEUtils.TE_FUTURE = 2;

function template_IsEnrolledInDateRange( lStartDate, lEndDate, lEntryDate, lExitDate, lbExclusiveExitDate ) {
    var bEnrolled = true;                
        
    if( isInt(Date.parse(lEndDate)) ) {    
        if( isInt(Date.parse(lEntryDate)) && new Date(lEntryDate) > new Date(lEndDate) )
            bEnrolled = false;                
    }
    
    if( bEnrolled && isInt(Date.parse(lStartDate)) ) {
        if( isInt(Date.parse(lExitDate)) && 
            (!lbExclusiveExitDate && new Date(lExitDate) < new Date(lStartDate)) ||
            (lbExclusiveExitDate && new Date(lExitDate) <= new Date(lStartDate)) )
            bEnrolled = false;
    }

    return bEnrolled;
} 

function template_IsEntryDateBefore( lDate, lEntryDate ) {
    return template_IsEnrolledInDateRange(null, lDate, lEntryDate, null, false);
}  

function template_IsExitDateAfter( lDate, lExitDate, lbExclusiveExitDate ) {
    return template_IsEnrolledInDateRange(lDate, null, null, lExitDate, lbExclusiveExitDate);
}  

function template_bEnrollmentsOverlap( ldEntry1, ldExit1, ldEntry2, ldExit2, lbExclusiveExitDate ) {
    var bOverlap = ((!isInt(Date.parse(ldExit2)) || !isInt(Date.parse(ldEntry1)) || ( (!lbExclusiveExitDate && (new Date(ldEntry1).valueOf())<=(new Date(ldExit2).valueOf()) )
        || (lbExclusiveExitDate && (new Date(ldEntry1).valueOf())<(new Date(ldExit2).valueOf()) ) ) )
        &&
        ( !isInt(Date.parse(ldEntry2)) || !isInt(Date.parse(ldExit1)) || ( (!lbExclusiveExitDate && (new Date(ldExit1).valueOf())>=(new Date(ldEntry2).valueOf()) )
        || (lbExclusiveExitDate && (new Date(ldExit1).valueOf())>(new Date(ldEntry2).valueOf()) ) ) ) );

    return bOverlap;
}

function getEnrollmentStatus( lCompareDate, lEntryElem, lExitElem, lbExclusiveExitDate ) {
    var dCompareDate = new Date(lCompareDate);
    var dEntryDate = lEntryElem.value;
    if( dEntryDate != "" )
        dEntryDate = new Date(dEntryDate);
    var dExitDate = lExitElem.value;
    if( dExitDate != "" )
        dExitDate = new Date(dExitDate);
    var nReturn = null;
    if( !template_IsEntryDateBefore(dCompareDate, dEntryDate) )
        nReturn = TEUtils.TE_FUTURE;
    else if( !template_IsExitDateAfter(dCompareDate, dExitDate, lbExclusiveExitDate) )
        nReturn = TEUtils.TE_INACTIVE;
    else
        nReturn = TEUtils.TE_ACTIVE;
    return nReturn;
}

function getEnrollmentStatusDescription( lCompareDate, lEntryElem, lExitElem, lbExclusiveExitDate ) {
    var strReturn = "";
    var lEnrollmentStatus = getEnrollmentStatus( lCompareDate, lEntryElem, lExitElem, lbExclusiveExitDate );
    if( lEnrollmentStatus == TEUtils.TE_ACTIVE )
        strReturn = "Active";
    else if( lEnrollmentStatus == TEUtils.TE_INACTIVE )
        strReturn = "Inactive";
    else if( lEnrollmentStatus == TEUtils.TE_FUTURE )
        strReturn = "Future";
    
    return strReturn;
}
		
function TEDate() {
}
function isValidDate( InMonth, InDay, InYear, strInDate ) {
    if( strInDate ) {
        var aDate = strInDate.split("/");
        if( aDate.length != 3 )
            return false
        InMonth = aDate[0];
        InDay = aDate[1];
        InYear = aDate[2];
    }
    
	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;
TEDate.getShortDate = getShortDate; 

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;
}

//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();
	   }
	  } 
	var ePopup = TEPopup_GetObj("te_floadpopup");
	if( ePopup != null)
		ePopup.Close();
}

function _dropPopup(lbEscKey) {
	for (var id in hTEPopup) { 
		var obj = hTEPopup[id];
		
		if ( obj == null)
			continue;
		
		// Temporary code to prevent sessiontimeout from being closed.
		// The fix is to use .Close() instead of _dropPopup everywhere so this entire code block can be removed.
        if( obj.PopupID() == "sessiontimeoutdisplay" )
            continue;
            	
        if( !lbEscKey || (lbEscKey && obj.bCloseOnEsc()) )
            obj.Close();
        else if( lbEscKey && !obj.bCloseOnEsc() )
            obj.Hide();
	}
    if( self.dropIframe )
		dropIframe();
    if( self.dropPopup )
        dropPopup();
    
    if( parent && parent!=self ) {
	    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(true)
}
    
function ClickHandler( e ) {
	var curClickTime = (new Date()).getTime();
	if( (curClickTime-prevClickTime) >= 5000 ) {
		prevClickTime = curClickTime;
		return true;
	}
	else 
		return false;
}

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 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(/&/g, '&amp;');
		strReturn = strReturn.replace(/\"/g, '&quot;');
		strReturn = strReturn.replace(/</g, '&lt;');
		strReturn = strReturn.replace(/>/g, '&gt;');
		strReturn = strReturn.replace(/'/g,"&#39;")
		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 isInt( lValue ) {
    return TEIsNumeric(lValue, true, false, true, false, false, false);
}
function isPositiveInt( lValue ) {
    return TEIsNumeric(lValue, true, true, true, false, false, false);
}
function isFloat( lValue ) {
    return TEIsNumeric(lValue, false, false, true, false, false, false);
}
function isPositiveFloat( lValue ) {
    return TEIsNumeric(lValue, false, true, true, false, false, false);
}

function isDate( lValue ) {
    return isInt(Date.parse(lValue));
}

function TEIsNumeric(lValue, lbIntegerOnly, lbPositiveOnly, lbAllowZero, lbAllowInfinity, 
                lbAllowScientificNotation, lbAllowHexNotation){
	if(lValue == null || lValue === "" || typeof lValue == "undefined")
		return false;

	if( lValue.toString().indexOf(" ")!=-1)
	   return false;
    
	if(lbIntegerOnly && lValue.toString().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+"").toString().indexOf("e") > -1 )
        return false;

    if( lbAllowHexNotation != true && (lValue+"").toString().indexOf("x") > -1 )
        return false;
           
	return true;
}

// Check to see if an HTML element has a value
function template_HasValue( eElem ) {
    var bReturn = false;
    
    if( eElem ) {
        var strTag = eElem.tagName;
        if( strTag == "SELECT" && eElem.selectedIndex > -1 && (eElem.selectedIndex > 0 || (eElem.selectedIndex == 0 && eElem.value !== "" && eElem.value != "null")) ) bReturn = true;
        else if( strTag == "TEXTAREA" && eElem.value !== "" ) bReturn = true;
        else if( strTag == "INPUT" ) {
            var strType = eElem.type;
            if( (strType == "text" || strType == "password" || strType == "hidden" || strType == "file") && eElem.value !== "" ) bReturn = true;
            else if( (strType == "checkbox" || strType == "radio") && eElem.checked ) bReturn = true;
        }
    }
    
    return bReturn;
}

// If the bottom button row is pushed off the bottom of the page, show the top button row
function template_ShowTopButtonRow() {
    var eTopButtonRow = document.getElementById("template_topbuttonrow");
    
    if( eTopButtonRow ) {
        var eBottomButtonRow = document.getElementById("template_bottombuttonrow");
        
        if( eBottomButtonRow ) {
            // This might need to be tweaked for loading the page in an IFrame
            var oScreenSize = getScreenSize(); 
            var oBottomButtonRowPos = findPos(eBottomButtonRow);
            var nBottomButtonRowBottom = oBottomButtonRowPos.top + eBottomButtonRow.offsetHeight;
            
            eTopButtonRow.style.display = (nBottomButtonRowBottom > oScreenSize.height ? "inline" : "none");
        }
    }
}

// Get an element's bounding box with or without the margins included
// Note: Includes padding and border
function template_GetBoundingBox( lElem, lbExcludeMargin ) {
    var oReturn = null;
    
    if( lElem ) {
        oReturn = {};
        oReturn.height = template_GetElementHeight(lElem, lbExcludeMargin);
        oReturn.width = template_GetElementWidth(lElem, lbExcludeMargin);
    }
    
    return oReturn;
}

// Get an element's height with or without the margins included
// Note: Includes padding and border
function template_GetElementHeight( lElem, lbExcludeMargin ) {
    var nReturn = null;
    
    if( lElem ) {
        nReturn = lElem.offsetHeight;
        if( !lbExcludeMargin ) {
            var nMarginTop = getStyle(lElem, "marginTop", "margin-top");
            var nMarginBottom = getStyle(lElem, "marginBottom", "margin-bottom");
            
            if( isInt(nMarginTop) ) nReturn += nMarginTop;
            if( isInt(nMarginBottom) ) nReturn += nMarginBottom;
            
            // IE displays margins with a 1px difference
            if( isIE && (isInt(nMarginTop) || isInt(nMarginBottom)) ) nReturn += 1;
        }            
    }
    
    return nReturn
}

// Get an element's width with or without the margins included
// Note: Includes padding and border
function template_GetElementWidth( lElem, lbExcludeMargin ) {
    var nReturn = null;
    
    if( lElem ) {
        nReturn = lElem.offsetWidth;
        if( !lbExcludeMargin ) {
            var nMarginLeft = getStyle(lElem, "marginLeft", "margin-left");
            var nMarginRight = getStyle(lElem, "marginRight", "margin-right");
            
            if( isInt(nMarginLeft) ) nReturn += nMarginLeft;
            if( isInt(nMarginRight) ) nReturn += nMarginRight;
            
            // IE displays margins with a 1px difference
            if( isIE && (isInt(nMarginLeft) || isInt(nMarginRight)) ) nReturn += 1;
        }
    }
    
    return nReturn
}

function findPos(obj, bExcludeBorderAdjust) {
	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;
                if( bExcludeBorderAdjust != true ) { 
    				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
                }
                else
                    pos.left -= 1;  // Not sure why, but offsetLeft is too big by one pixel (cross-browser confirmed)
				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;
  
    var lParent = (window ? window : parent);
    if (lParent.pageYOffset) // all except Explorer
    {
    	dim.width = lParent.pageXOffset;
    	dim.height = lParent.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop)
    	// Explorer 6 Strict
    {
    	dim.width = document.documentElement.scrollLeft;
    	dim.height = document.documentElement.scrollTop;
    }
    else if (lParent &&  lParent.document && lParent.document.body) // all other Explorers
    {
    	dim.width = lParent.document.body.scrollLeft;
    	dim.height = lParent.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 template_HasScrollBars() {
    var oReturn = {};
    oReturn.horizontal = false;
    oReturn.vertical = false;
    
    oReturn.vertical = document.body.scrollHeight > document.body.clientHeight;
    oReturn.horizontal = document.body.scrollWidth > document.body.clientWidth;
    
    // Check the overflow properties for "auto" and "visible" values
    // When the overflow properties are set otherwise no scroll bars will appear regardless of the difference in height/width
    var cStyle = document.body.currentStyle || window.getComputedStyle(document.body, "");
        
    oReturn.vertical = (oReturn.vertical && 
                           ( cStyle.overflow == "visible" 
                          || cStyle.overflowY == "visible"
                          || (oReturn.vertical && cStyle.overflow == "auto")
                          || (oReturn.vertical && cStyle.overflowY == "auto")));
                          
    oReturn.horizontal = (oReturn.horizontal && 
                           ( cStyle.overflow == "visible" 
                          || cStyle.overflowX == "visible"
                          || (oReturn.vertical && cStyle.overflow == "auto")
                          || (oReturn.vertical && cStyle.overflowX == "auto")));                              
   
    return oReturn;
}

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';
}

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 ); 
    }*/
    
 	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 ); 
    }  
    
    fMakeModal(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 template_ResizeIFrame( lstrFrameID ) {
    var eIFrame = document.getElementById(lstrFrameID);
    if( !eIFrame )
        return;
    
    eIFrame.style.display = "inline";
    
	if (eIFrame.contentDocument && eIFrame.contentDocument.body.offsetHeight){ //ns6 syntax
        eIFrame.style.height = eIFrame.contentDocument.body.offsetHeight;
        //for some reason the offsetHeight isn't being correctly set until it's height is set once
        eIFrame.style.height = eIFrame.contentDocument.body.offsetHeight;
    }
    else if (eIFrame.Document && eIFrame.Document.body.scrollHeight) //ie5+ syntax
        eIFrame.style.height = eIFrame.Document.body.scrollHeight;

    var nNewHeight = -1;
    var nCurrentHeight = 0;
    
	if( eIFrame.contentDocument ) {
        if( eIFrame.contentDocument.body.offsetHeight ) { //ns6 syntax
            nCurrentHeight = eIFrame.contentDocument.body.offsetHeight;
            if( nCurrentHeight > nNewHeight ) nNewHeight = nCurrentHeight;
        }
        if( eIFrame.contentDocument.body.scrollHeight ) {
            nCurrentHeight = eIFrame.contentDocument.body.scrollHeight;
            if( nCurrentHeight > nNewHeight ) nNewHeight = nCurrentHeight;
        }
        if( eIFrame.contentDocument.documentElement.offsetHeight ) {
            nCurrentHeight = eIFrame.contentDocument.documentElement.offsetHeight;
            if( nCurrentHeight > nNewHeight ) nNewHeight = nCurrentHeight;
        }
	}

    if( eIFrame.Document ) {
        if( eIFrame.Document.body.scrollHeight ) {
            nCurrentHeight = eIFrame.Document.body.scrollHeight;
            if( nCurrentHeight > nNewHeight ) nNewHeight = nCurrentHeight;
        }
        if( eIFrame.Document.documentElement.scrollHeight ) {
            nCurrentHeight = eIFrame.Document.documentElement.scrollHeight;
            if( nCurrentHeight > nNewHeight ) nNewHeight = nCurrentHeight;
        }
    }
	
	if( nNewHeight > -1 )
		eIFrame.style.height = nNewHeight + (isIE?15:0);
}

function resizeTransparency() {
    var overlay = document.getElementById('edit_trans');
    if( overlay ) {
        var screen = getScreenSize();
        overlay.style.height = screen.height + 2 + "px";
        overlay.style.width =  (screen.width) + 1 + "px"; // the addition px causes scroll bars in IE 
    } 
    else if( isIE ) 
        template_removeEventListener(window, "onresize", resizeTransparency);
}

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, lbGET ) { 
    //fResetTimeout(); this function does not always exist (bTab mode on student single view - automated add/drop) 
    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(lbGET ? "GET" : "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; 
}

// Return an error code depending on the status of the ajax object.
function template_AjaxErrorCode( lAjaxObject ) {
    // 0 = no error
    // 1 = ajax object not supplied    
    // 2 = readystate != 4 (Not ready to look for errors yet)    
    // 3 = status != http code 200
    // 4 = error processing ajax request (Usually an error on the ajax page)
    var nReturn = 0;
    if( !lAjaxObject )
        nReturn = 1;
    else if( lAjaxObject.readyState != 4 )
        nReturn = 2;
    else if( lAjaxObject.status != 200 )
        nReturn = 3;
    else if( lAjaxObject.responseText.indexOf("TE_Error") > -1 )
        nReturn = 4;
    
    return nReturn;
}

//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;
template_addEventListener(window, "resize", fMoveFloatingHeader);
function fMoveFloatingHeader(){
    if( !bUsesFloatingHeader )
        return;
        
    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)
}

// Use this function for entering currency values into an input
// It will strip out the dollar sign and commas
function formatInputCurrency( lValue ) {
    return formatCurrency(lValue, true).replace(/,/g, "");
}

function formatCurrency( lValue, lbHideDollarSign ) {
    if( !TEIsNumeric(lValue, false, false, true) )
        return "";
	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)?'':'-') + (lbHideDollarSign ? '' : '$') + 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 getShortTime( inDate ) {
	if( inDate == null || inDate == "" || isNaN(Date.parse(inDate)) ) {
		return "";
	}
	
	var newDate = new Date( inDate );
	
	var strAMPM = "am";
	if( newDate.getHours() >= 12 )
		strAMPM = "pm";
		
	var strMins;
	if( newDate.getMinutes() < 10 )
		strMins = "0" + newDate.getMinutes();
	else
		strMins = newDate.getMinutes();
		
	if( newDate.getHours() == 0 )
		return "12:" + strMins + strAMPM;
	else if( newDate.getHours() <= 12 )
		return newDate.getHours() + ":" + strMins + strAMPM;
	else
		return (newDate.getHours()-12) + ":" + strMins + strAMPM;
}
		
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, lUnrestricted){
	var eMsg = document.getElementsByName("TEDateSpan" + elem.id );
	var eDateObjs = document.getElementsByName(elem.name);
	if( eMsg.length == eDateObjs.length ) {
	    var nElementIndex = 0;
    	for( ; nElementIndex<eDateObjs.length; nElementIndex++ ) {
    	   if( eDateObjs[nElementIndex] == elem )
    	       break;
    	}
    	var elemMsg = eMsg[nElementIndex];
    }
    else
        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();
		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 = "<br>Error: Invalid date.";
		}  
		return; //this means it is not a valid date
	}
	
	var temp = getShortDate(elem.value);
	if( temp == "" ){  
		elemMsg.style.display = '';
		elemMsg.innerHTML = "<br>Error: Invalid date."; 
		return; //this means it is not a valid date
	}
	if( hValidDates != null && elemMsg != null && !lUnrestricted){
		if( hValidDates[ temp ] != 1){ 
			elemMsg.style.display = '';
			elemMsg.innerHTML = "<br>Error: Date out of range.";
			return;
		}
	}
	
    fHideCalender();
	if( fOnChange!=null )
    	fOnChange(elem);
}


function fShowDateField(lName, lCurValue, strOnChangeFunction, lType){
		if(lName == null || lName == "")
			lName = "date"; 
				
        if( lType == null || lType == "" )
            lType = SINGLEINPUT;
            
		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( getShortDate(lCurValue) );
			lCurValue = getShortDate( lCurValue);
		}
			
		var strOut = "";
		strOut += ("<input type=hidden name='TEDateType" + lName + "' value=1>");
		strOut += ("<span style='white-space:nowrap;'>");
		strOut += ("<input size=8 "	
            + " onfocus='this.select();' "
            + " onclick='show_calendar_widget(this);' "
			+ " 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 +=  (" <span id='TEDateSpan" + lName + "' style='color:red;display:none;'>" 
			+ "</span>");
		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);

}

function template_RecipientChange( e ) {
    var eRecipient = document.getElementById("recipientoptions");
    if( eRecipient != null ) {
        if( e.value == "ANONYMOUS" )
            eRecipient.style.display = 'none';
        else
            eRecipient.style.display = '';
    }
}

// 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.InstructorID0 || (lbUseInstructorIDElement && lForm.InstructorID) ) {
        aWhoArray[j][0]=(lForm.InstructorID0);
        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 TETimeFrame.js
// aTimeframeArray is defined in that class and is assumed to exist
function template_TimeFrameInit(lForm){
	if( lForm == null )
		return;
	
	aTimeframeArray = new Array(5);

	for( var i=0; i<aTimeframeArray.length;i++ )
		aTimeframeArray[i] = new Array();
	var j=0; 

    j++;
    if( lForm.gpid ) {
    	aTimeframeArray[j][0]=(lForm.gpid);
        j++;        
    }
    
    if( lForm.month ) {
        aTimeframeArray[j][0]=(lForm.month);	
        j++;
    }
    
    
    if( lForm.week ) {
        aTimeframeArray[j][0]=(lForm.week);
        j++;	   
    }
    
    
    if( lForm.startdate ) {
	   aTimeframeArray[j][0]=(lForm.startdate);
	   aTimeframeArray[j][1]=(lForm.enddate);
       j++;
    }    
    	
	setDisabledByElement(lForm.timeframe, aTimeframeArray);
	if( typeof fTE_TimeframeChanged == "function" )
	   fTE_TimeframeChanged();
}

// 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( );

    var tempE = document.getElementById("contactinformation");
    if(tempE != null)
        template_RecipientChange(tempE);
	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); 
	}
}  
    
// Fills a select list with options.  Clears the select list's options before filling it.
function template_WriteSelectListOptions(eElem, aValues, aText, lValue) {
    if( eElem && eElem.type && eElem.type.search("select") > -1 && aValues.length == aText.length ) {
        eElem.options.length = 0;
        for( var i = 0; i < aValues.length; i++ ) {
            TE_addOption(eElem, aText[i], aValues[i], lValue);
        }
    }
}

function TE_addOption( eSel, strText, strValue, lValue ){
	var newOption = new Option(); 
	
	if( strText == "" )
	   strText = "\u00a0"; // creates an &nbsp; instead of an empty node, which will keep the select list the same height as if it had text in it
	var theText=document.createTextNode(strText);
	newOption.appendChild(theText);
	newOption.setAttribute("value",strValue);
	
	eSel.appendChild( newOption);
	
	if( lValue && lValue.toString() == strValue.toString() )  
		newOption.selected = true; 
	   
	return newOption;
}
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( "iframe" );
        new_fade.setAttribute( 'id', 'edit_trans' );  
        new_fade.setAttribute( 'class', 'transparency' );
        new_fade.setAttribute( 'className', 'transparency' );
        new_fade.src = "../common/blank.html";
        document.body.appendChild( new_fade );  
    } 
    if( isIE ) {  
        template_addEventListener(window, "resize", resizeTransparency);
        var screen = getScreenSize();
        new_fade.style.height = screen.height + 2 + "px";
        new_fade.style.width = (screen.width) + 1 + "px"; // the addition px causes scroll bars in IE
    }      
    else {
        new_fade.style.height = '100%';
        new_fade.style.width = '100%';  
    }
    new_fade.style.borderWidth = "0px";
    new_fade.style.display = '';
    
    nTEPopupZIndex += 2;
    elem.style.zIndex = nTEPopupZIndex;
    new_fade.style.zIndex = elem.style.zIndex-1;
}

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 template_fPositionGenericResults(anchor){
    TE_LastPositionElem = null;
	var results = document.getElementById(anchor.id + "results");
	if( results ){
		if( anchor == null){
			anchor = document.getElementById("search");
		}
		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;
			anchor.onkeydown = search_fHighlight; 
			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 = "";
        
    // IE doesn't like links without hrefs
    if( lstrAttributes.toString().toLowerCase().indexOf("href") == -1 )
        lstrAttributes += " href=\"javascript:void(0)\"";
                        
    if( lstrLinkText == null || lstrLinkText == "" )
        lstrLinkText = "clear";
        
    strReturn += "<nobr><a " + strClass + lstrAttributes + ">[" + lstrLinkText + "]</a></nobr>";
    
    return strReturn;
}

function template_getSelectedRadioButton(aElem, lbReturnValue) {
    var eReturn = null;
    
    if( aElem!=null && aElem.length ) {
        for( var i = 0; i < aElem.length && !eReturn; i++ ) {
            if( aElem[i] && aElem[i].checked ){        
                eReturn = aElem[i];
            }
        }
    }
    if( lbReturnValue && eReturn != null)
    	return eReturn.value;
    return eReturn;
}       
function TE_AtLeastOneChecked(  strNameToCheck ,lbIncludeDisabled){
	var aChks = document.getElementsByName( strNameToCheck);
	if( aChks==null || aChks.length==0)
		return;
		
	for( var i=0;i<aChks.length;i++){
		if( aChks[i].checked && (lbIncludeDisabled || aChks[i].disabled==false ) )
			return true; 
	}  
	return false;
}
 
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) 
		{}
	}
}
 
function fLoadPopup(strString, bModal, bShowCloseButton) { 
	
	var ePopup = TEPopup_GetObj("te_floadpopup");
	if (!ePopup)
		ePopup = new TEPopup("te_floadpopup");
	else
		ePopup.Close();
	ePopup.Title(strString);
	var strHTML = "<table class=template><tr>"
		+ "<td valign=center>"
		+ "<img src='../images/LoadingAnimatedClearLarge.gif'>"
		+ "</td><td valign=center style='padding-left:15px;'>Please wait... </td>"
		+ "</tr></table>"
	ePopup.HTML( strHTML);
	if(bModal== true || bModal == null || typeof bModal == "undefined")
		ePopup.bModal(true);
	else	
		ePopup.bModal(false); 
	ePopup.bShowXButton (bShowCloseButton);
	ePopup.Buttons("");
	ePopup.Width(300)
	ePopup.Draw();
	return ePopup;
} 

function fShowDeleteConfirm(strString, bModal, bShowCloseButton, strURL, nHeight, nWidth) {

	var ePopup = TEPopup_GetObj("te_fShowDeleteConfirmation");
	if (!ePopup)
		ePopup = new TEPopup("te_fShowDeleteConfirmation");

	ePopup.Title("Delete");
	var strHTML = strString
        + "<br><br><input type=Submit class=button name=Submit value=\"Delete\" onClick=\"window.location='" + strURL + "'\">&nbsp;"
        + "<input type=button class=button name=Back value=\"Cancel\" onClick=\"_dropPopup()\">";
	ePopup.HTML( strHTML);
	if(bModal== true || bModal == null || typeof bModal == "undefined")
		ePopup.bModal(true);
	else
		ePopup.bModal(false);
	ePopup.bShowXButton (bShowCloseButton);
	ePopup.Buttons("");
	ePopup.Height( nHeight )
	ePopup.Width( nWidth )
	ePopup.Draw();
	return ePopup;
}
// Creates a text input with the appropriate key handler.  Returns the new element.
function template_createTextInput( lName, lType ) {
    var eElem = document.createElement("input");
    if( lType != "password" && lName != "email" ) {
        eElem.type = "text";
        KeyHandling_Attach_Process_KeyDown(eElem);
    }
    else {
        eElem.type = "password";
        KeyHandling_Attach_Dont_Bubble_Backspace(eElem);
    }
    eElem.name = lName;
    return eElem;
}

// Creates a text area with the appropriate key handler.  Returns the new element.
function template_createTextArea() {
    var eElem = document.createElement("textarea");
    KeyHandling_Attach_Dont_Bubble_Backspace(eElem);
    return eElem;
}


// Appends an event listener to an element.  Allows multiple functions to be called per event.
function template_addEventListener(lElem, lstrEvent, lFunction) { 
    if( lElem.addEventListener ) //DOM method for binding an event
        lElem.addEventListener(lstrEvent, lFunction, false);
    else if( lElem.attachEvent ) //IE exclusive method for binding an event
        lElem.attachEvent("on" + lstrEvent, lFunction);
} 

// Removes an event listener to an element.  The parameters must exactly match the addEventListener call.
function template_removeEventListener(lElem, lstrEvent, lFunction) {                
    if( lElem.removeEventListener ) //DOM method for binding an event
        lElem.removeEventListener(lstrEvent, lFunction, false);
    else if( lElem.detachEvent ) //IE exclusive method for binding an event
        lElem.detachEvent("on" + lstrEvent, lFunction);
} 

// Disable text selection for an element
function template_toggleTextSelection(element, bEnable) {
	if( element ) {
	    if( bEnable ) {
    		if( typeof element.onselectstart != "undefined" ) //IE
    			element.onselectstart = function(){return true};
    		else if( typeof element.style.MozUserSelect != "undefined" ) //Firefox
    			element.style.MozUserSelect = "";
    
    		element.style.cursor = "auto";
	    }
	    else {
    		if( typeof element.onselectstart != "undefined" ) //IE
    			element.onselectstart = function(){return false};
    		else if( typeof element.style.MozUserSelect != "undefined" ) //Firefox
    			element.style.MozUserSelect = "none";
    
    		element.style.cursor = "default";
        }
	}
}
		
function VerifyMultiSelect( lID ) {
    var eElem = document.getElementById(lID);
    var bSelected = false;
    if( eElem ) {
        for( var i=0; i<eElem.length && !bSelected; i++ ) {
            if( eElem.options[i].selected )
                bSelected = true;
        }
    }
    
    return bSelected;
}

function fTE_ChangeLanguage(e) {
    var bSpanish = e.options[e.selectedIndex].value;
    window.location="main.aspx?bspan=" + bSpanish;
}

function fTE_ShowLanguageSelect( lbSpanish ) {
	var elem = document.getElementById("TE_ChangeLanguageDiv");
	var bSpanish = lbSpanish;
    if( elem != null){   
		var strSelect =  "<select id=language onchange='fTE_ChangeLanguage(this)'>"
            + "<option " + (bSpanish==0? "selected ": "") + "value=0>English</option>"
            + "<option " + (bSpanish==1? "selected ": "") + "value=1>Espa&ntilde;ol</option>"
            + "</select>";
            
        elem.style.verticalAlign = "top"; 
		elem.innerHTML = "<b>Language:</b> " + strSelect;
		elem.style.top = "37px";
	}
}

function fTE_ChangeInstructor() {
	document.body.style.cursor = "wait";
	var elem = document.getElementById("TE_ChangeSchoolDiv");
	if( elem != null){   
		var url = '../common/AJAXGetChangeInstructorSelector.aspx'
		var ajaxObject = TEGetAjaxObject(url, null,  null, false ) 
		var strRet =  ajaxObject.responseText;
		if (strRet == -2)
			alert("Cannot change instructors from this location.")
		else {
			elem.style.verticalAlign = "top"; 
			elem.innerHTML = "<b>Instructor:</b> " + strRet
			elem.style.top = "2px";
		}
	}
	document.body.style.cursor = "";
}

function fTE_ChangeSchool() {
	document.body.style.cursor = "wait";
	var elem = document.getElementById("TE_ChangeSchoolDiv");
	if( elem != null){  
		var args = "&LicenseModuleToCheck=" + LicenseModuleToCheck 
			+ "&AdminPermissionToCheck=" + AdminPermissionToCheck
		var url = '../common/AJAXGetChangeSchoolSelector.aspx'
		var ajaxObject = TEGetAjaxObject(url, args,  null, false ) 
		var strRet =  ajaxObject.responseText;
		if (strRet == -2)
			alert("Cannot change schools from this location.")
		else {
			elem.style.verticalAlign = "top"; 
			elem.innerHTML = "<span style='font-weight:bold;'>School:</span> " + strRet 
			elem.style.top = "2px";
		}
	}
	document.body.style.cursor = "";
}
function fTE_OnChangeInstructor(elem) {
	document.body.style.cursor = "wait";    
	var args = "&InstructorID=" + elem.value;
	var url = '../common/AJAXInstructorGotoResponse.aspx'
	var ajaxObject = TEGetAjaxObject(url, args,  null, false )
	
	
	document.body.style.cursor = "";
	var strRet =  ajaxObject.responseText;  
	if( strRet == -2)
		alert("Cannot change instructors from this location.")	
	else{
		var newURL = window.location.protocol + "//" + window.location.host + "" + window.location.pathname;
	/*	alert(window.location.protocol + "\r\n"
			+ window.location.host + "\r\n"
			+ window.location.pathname + "\r\n"
			+ newURL);
	*/
		newURL += "?" + addToQS(null, true);
		//if( confirm("reload?") )
			window.location.replace( newURL);
		}
}

function fTE_OnChangeSchool(elem) {
	document.body.style.cursor = "wait";
	var strError = "";
	if( elem.value == -1)
		strError = ("Insufficient permissions to view this page for the specified school.") 
	else if( elem.value == -3)
		strError = ("Selected school does not have the appropriate module.")
	if( strError != ""){
		alert(strError)
		document.body.style.cursor = "";
		return false;
	}
		
	var args = "&SchoolID=" + elem.value;
	var url = '../common/AJAXSchoolGotoResponse.aspx'
	var ajaxObject = TEGetAjaxObject(url, args,  null, false )
	
	
	var strRet =  ajaxObject.responseText;  
	if( strRet == -2)
		alert("Cannot change schools from this location.")	
	else{
		var newURL = window.location.protocol + "//" + window.location.host + "" + window.location.pathname;
	/*	alert(window.location.protocol + "\r\n"
			+ window.location.host + "\r\n"
			+ window.location.pathname + "\r\n"
			+ newURL);
	*/
		newURL += "?" + addToQS(null, true);
		//if( confirm("reload?") )
			window.location.replace( newURL);
	}
}

function addToQS( hNameValuePairs, lbStripAllIDs ){ 
	if( hNameValuePairs ==null)
		hNameValuePairs = {};
		
	var query = window.location.search.substring(1);
	var strRet = "";
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) { 
		if( vars[i] == null || vars[i] == "")
			continue;
		var pair = vars[i].split("=");
		if (hNameValuePairs[pair[0].toLowerCase()] != null)
			continue;
		else if (lbStripAllIDs && pair[0].substring(pair[0].length - 2).toLowerCase() == "id")
			strRet += "";
		else
			strRet += "&" + pair[0] + "=" + pair[1];
	}
	for (var field in hNameValuePairs) {
		strRet += "&" + field + "=" + hNameValuePairs[ field ]
	}
	return strRet;
}
function fRefreshPage(hNumValuePairs, lbRedirect) {
	//lbRedirect = true will cause the back button to include

	var newURL = window.location.protocol + "//" + window.location.host + "" + window.location.pathname
	newURL += "?" + addToQS(hNumValuePairs, false); 
	//if( confirm( newURL) ) 
	if( !lbRedirect)
		window.location.replace(newURL);
	else
		window.location = newURL
}

function fTE_TimeframeChanged() {
	var aRadios = document.getElementsByName("timeframe");
	for (var i = 0; i < aRadios.length; i++) {
		var cur = aRadios[i];
		var elem = document.getElementById( cur.value);
		if (elem != null) {
			elem.style.display = cur.checked ? "" : "none";
		}
	}
}


//TIME PICKERS


function fTimePickerChanged(){
	if( timerElem == null)
		return;
	
	timerElem.value = document.getElementById("te_timepicker_hour").value
		+ ":" + document.getElementById("te_timepicker_minute").value
		+ " " 
		+ (document.getElementById("te_timepicker_am").selectedIndex == 0?"AM":"PM")
} 

var aTimeElemsFocused = {};
function fTimePickerFocused( elem, lbShowPicker ){ 
	aTimeElemsFocused[ elem.id.toLowerCase() ] = true;
	if( lbShowPicker )
		fShowTimePicker(elem);
}
function fWaitToHideTimePicker(){
	for( var id in aTimeElemsFocused){ 
		if( aTimeElemsFocused[ id.toLowerCase() ] != null ){ 
			return;
		}
	} 
	if (timerPopup != null){
		timerPopup.Close();
		timerPopup = null;
	}
}
function fTimePickerLostFocus( elem, lbIsBaseTextBox){  
	if( lbIsBaseTextBox ){ 
		bForcedClosed = false;
	}
	aTimeElemsFocused[ elem.id.toLowerCase() ] = null;
	setTimeout( 'fWaitToHideTimePicker()', 250 );
}
var timerPopup = null;
var timerElem = null;
var bForcedClosed = false;
function fShowTimePicker(elem, lbReturnIfInvalid){
	timerElem = elem;
	if( bForcedClosed ) { 
		timerElem.focus();
		if (timerPopup != null)
			timerPopup.Close();	
		return;
	} 
	if (timerPopup == null)
		timerPopup = new TEPopup("te_timepicker");  
	var lMinuteInterval = parseInt( elem.getAttribute("timerinterval") ); 
	
	if( !TEIsNumeric( lMinuteInterval, true) )
		lMinuteInterval = 1;
		 
	var strHTML = "";
	var aTemp = ProcessTime(elem.value);
	if( aTemp == null){
		if( lbReturnIfInvalid )
			return;
		var dNow = new Date()
		var strNow = getShortTime(dNow) 
		aTemp = ProcessTime( strNow );
	}
	var hr = parseInt( aTemp[0] );
	var bAm = true;
	if( hr == 12){ 
		bAm = false;
	}
	else if(  hr > 12){ 
		bAm = false;
		hr -= 12
	}
	else if( hr == 0)
		hr = 12;
	
	strHTML = "<div onmousedown='fTimePickerFocused(this);' onmouseup='fTimePickerLostFocus(this);' id=te_pickerdiv style='vertical-align:top;white-space:nowrap;padding:0;margin:0;'  >"
	
	
	var strSelStyle = " style='font-size:11px; margin:0;padding:0;' "
	var strSelFunctions = " onfocus='fTimePickerFocused(this);' onblur='fTimePickerLostFocus(this);'  onchange='fTimePickerChanged()'"
	strHTML += "<select " + strSelStyle + strSelFunctions + " id=te_timepicker_hour >"
	for( var i=1 ; i<=12;i++){
		var str = i;
		strHTML += "<option value=" + str
			+ ( i==hr ? " selected ":"")
			+ ">" + str + "</option>";
	}
	strHTML += "</select>";
	strHTML += "<b>:</b>"
	
	if( lMinuteInterval == 60 ){
		strHTML += "<b>00</b><input type=hidden id=te_timepicker_minute value='00'>"
	}
	else{
		
		strHTML += "<select " + strSelStyle + strSelFunctions + " id=te_timepicker_minute >"
		var bSelected = false;
		for( var i=0 ; i<=59;i+=lMinuteInterval){
			var str = i;
			if(str < 10)
				str = "0" + i;
			strHTML += "<option value=" + str;
			if( !bSelected){
				if( i == aTemp[1] || i + lMinuteInterval >aTemp[1] ){
					strHTML +=  " selected ";
					bSelected = true;
				}
			}
			strHTML +=  ">" + str + "</option>";
		}
		strHTML += "</select>";
	}
	strHTML += "&nbsp;<select " + strSelStyle + strSelFunctions + " id=te_timepicker_am >" 
		strHTML += "<option value=1" 
			+ ( bAm ? " selected ":"")
			+ ">AM</option>";
		strHTML += "<option value=0" 
			+ ( !bAm ? " selected ":"")
			+ ">PM</option>";
	strHTML += "</select>"
	 
	strHTML += "&nbsp;&nbsp;<a style='text-decoration: none;font-weight:normal;font-size:11px' href=\"javascript:bForcedClosed=true;fTimePickerChanged();fShowTimePicker(timerElem);\">set</a>"
	strHTML += "&nbsp;&nbsp;<img style='margin:0;padding:0;' src='../images/close.gif' onclick=\"bForcedClosed=true;fShowTimePicker(timerElem);\">"
	strHTML += "</div>"; 
	timerPopup.HTML( strHTML); 
	timerPopup.Height(25);
	timerPopup.bDraggable(false);
	timerPopup.Width(185);
	timerPopup.Anchor( "RLB"); //bottom  
	timerPopup.AnchorElem( elem);
	timerPopup.AnchorPaddingVert(2);
	timerPopup.AnchorPaddingHoriz(5); 
	timerPopup.Draw(); 
	
	var popupElem = timerPopup.Elem(); 
	template_addEventListener(popupElem, "mousedown", fTimePickerMouseDown)
	template_addEventListener(popupElem, "mouseup", fTimePickerMouseUp ); 
	//*/
}
var elemDown = null;
function fTimePickerMouseDown(e){ 
	e = e || window.event
	var targ = e.target || e.srcElement; 
	if( targ.tagName == "DIV" || targ.tagName == "TD"
		|| targ.tagName == "B" || targ.tagName == "TABLE"){
		elemDown = targ;
		if( elemDown.id == null)
			elemDown.id = "temp";
		fTimePickerFocused( elemDown );
	} 
}
function fTimePickerMouseUp(){
	if( elemDown != null){  
		timerElem.focus();
		fTimePickerChanged();
		fTimePickerLostFocus( elemDown );
		fTimePickerFocused( timerElem );
		elemDown = null;
	}
} 
function fTimePickerTextboxChanged( elem ){ 
	var strHTML = "";
	var aTemp = ProcessTime(elem.value);
	if( aTemp == null) 
		return; 
	var hr = parseInt( aTemp[0] );
	var bAm = true;
	if( hr == 12){ 
		bAm = false;
	}
	else if(  hr > 12){ 
		bAm = false;
		hr -= 12
	}
	else if( hr == 0)
		hr = 12;
		
	var min = aTemp[1];
	if( min<10)
		min = "0" + min;
	
	elem.value = hr + ":" + min + ( bAm?" AM":" PM")
}

function fShowTimePickerField( id, value, interval, lbDontBubbleBackspace){
	if( !TEIsNumeric( interval, true ) )
		interval = 1;
	if( value != null && typeof value != "undefined")
		value = getShortTime( value );
	
	if( ProcessTime( value ) == null)
		value = "";
	return "<input type=textbox id=" + id
		+ " size=8 "
		+ " value='" + value + "'"
		+ " name=" + id
		+ " timerinterval='" + interval + "' "
		+ " onkeyup='fShowTimePicker(this, true);'"
		+ " onchange='fTimePickerTextboxChanged(this );'"
		+ (lbDontBubbleBackspace ? " onkeydown='dont_bubble_backspace();' ":"")
		+ " onfocus='fTimePickerFocused(this, true);'"
		+ " onblur='fTimePickerLostFocus(this, true);'>"
}    
   
function te_bParseSummer( lValue ) {
    if( lValue!=null && typeof lValue!="undefined" && lValue!="" ) {
        if( lValue.toString().length > 4 )
            return true;
        else
            return false;
    }
    
    return false;
}
function te_ParseYear( lValue ) {
    if( isNaN(parseInt(lValue)) == false ) {
        if( lValue.toString().length > 4 )
            return parseInt(lValue.toString().substr(1));
        else
            return parseInt(lValue);
    }
    
    return null;
}
function getYearRange( lValue ) {
	return getDisplayYear(lValue, "SHORT");
}                            
function getDisplayYear( lValue, lFormat){
    var baseYear = te_ParseYear(lValue);
    if( baseYear == null)    
    	return "";
    
	str = baseYear.toString(); 
	
	var nextYear = baseYear +1;
	if( lFormat == "SHORT")
		str +=  "-" + nextYear.toString().substr(2);
	else
		str +=  " - " + nextYear.toString();
	  
	if( te_bParseSummer( lValue) ) 	
		str += " Summer";
	return str;
}
  
function template_onload(){
    template_ShowTopButtonRow();
}

function jsVerifyTime( eStartTime, eEndTime, lbRequired, lbHighlightErrors, lStartTimeLabel, lEndTimeLabel){    
	var errorColor = "yellow";
	var strRet = "";
	var aStartTime = null;
	var aEndTime = null;
	if( lStartTimeLabel == null || lStartTimeLabel == "" || typeof lStartTimeLabel == "undefined"){
		if( eEndTime == null)
			lStartTimeLabel="Time";
		else
			lStartTimeLabel = "Start time";
	}
	if( lEndTimeLabel == null || lEndTimeLabel == "" || typeof lEndTimeLabel == "undefined"){
		lEndTimeLabel = "End time";
	} 
	
	if( eStartTime != null){
		eStartTime.style.backgroundColor = "";
		aStartTime = ProcessTime( eStartTime.value  )
		if( aStartTime == null ){
			if( eStartTime.value == "" && lbRequired){
				strRet += lStartTimeLabel + " must be supplied. \r\n";
			}
			else if( eStartTime.value != "")
				strRet += lStartTimeLabel + " has an invalid time format. \r\n";
			if( strRet != "" && lbHighlightErrors)
				eStartTime.style.backgroundColor = errorColor 
		} 
		else
			bHasStart = true;
	}
	
	if( eEndTime != null){
		eEndTime.style.backgroundColor = "";
		var temp = "";            
		aEndTime = ProcessTime( eEndTime.value  )
		if( aEndTime == null ){ 
			if( eEndTime.value == "" && lbRequired)
				temp += lEndTimeLabel + " must be supplied. \r\n";
			else if( eEndTime.value != "")
				temp += lEndTimeLabel + " has an invalid time format. \r\n";
			if( temp != "" && lbHighlightErrors){
				eEndTime.style.backgroundColor = errorColor
				strRet += temp;
			} 
		} 
		else	
			bHasEnd = true;
	}
	
	if( strRet == "" && aStartTime!=null && aEndTime != null){
		var dStart = new Date(2000, 1, 1, aStartTime[0], aStartTime[1] );
		var dEnd = new Date(2000, 1, 1, aEndTime[0], aEndTime[1] );  
		if( dEnd < dStart ){
			strRet += lEndTimeLabel + " must be after the " + lStartTimeLabel.toLowerCase() + ". \r\n";
			if( lbHighlightErrors){
				eStartTime.style.backgroundColor = errorColor
				eEndTime.style.backgroundColor = errorColor
			}
		}
	}
	
	return strRet; 
}
  
var template_hVerifyMessages = {};
var aVerifyFunctions = [];
var template_aWarningFunctions = [];
function template_verify( lForm ){
	var strError = "";
	var strWarning = "";
	var bReturn = true;

	for( var i = 0; i < aVerifyFunctions.length && bReturn; i++ ) {
		var ret = aVerifyFunctions[i].apply();
        // Return false to override the automatic verify messages (useful if you want to create a custom confirm dialog etc)
		if( ret === false )
			bReturn = false;		
		else if( ret != "" && !template_hVerifyMessages[ret] ) {
	    	strError += ret;
	    	template_hVerifyMessages[ret] = true;
	    }
	}
	
	if( bReturn ) {
        if( typeof verify == "function") {
            var eForm = document.addForm ? document.addForm : document.form1;
            var ret = verify(eForm, strError);
            // Return false to override the automatic verify messages (useful if you want to create a custom confirm dialog etc)
    		if( ret === false )
    			bReturn = false;
    		else if( ret === true)
    			ret = "";
    	    
            if ( ret != "" )
    	       strError += ret;
        }
    }
    	
    if( bReturn ) {
        for( var i = 0; i < template_aWarningFunctions.length; i++ ) {
            var ret = template_aWarningFunctions[i].apply();
    		if( ret != "" && !template_hVerifyMessages[ret] ) {
    	    	strWarning += ret;
    	    	template_hVerifyMessages[ret] = true;
    	    }        
        }
        
    	if( strError != "" || strWarning != "" ) {
    	    var strMessage = "";
    	    
    	    if( strError != "" && bReturn ) {
                if( strWarning != "" ) 
                    strMessage += "Errors:\r\n";
                strMessage += strError;
    	    }
    	    
    	    if( strWarning != "" ) {
                if( strError != "" && bReturn )
                    strMessage += "\r\nWarnings:\r\n";
                strMessage += strWarning;
    	    }
    	    
    	    if( strError != "" && bReturn ) {
                alert(strMessage)
                bReturn = false;
            }
            else {
                strMessage += "\r\n\r\n"
                            + "Click OK to continue or Cancel to go back and make changes.";
                bReturn = window.confirm(strMessage);
            }
    	}
    }
	
	template_hVerifyMessages = {};
	return bReturn;
}

function TEClassStats_fShowRoster(lClassID, lbActive, strArgs){
	if (strArgs==null)
		strArgs="";
	
	// Drop existing loading popup
	var LoadingPopup = TEPopup_GetObj("te_floadpopup");
	if (LoadingPopup!=null)
		LoadingPopup.Close();	
	
	if (window.location != window.parent.location)
		var offset = parent.getScrollOffset();
	else
		var offset = getScrollOffset();		
	
	// Check if there is an existing rosters popup. If yes, replace html in it.
	// Otherwise, start new loading popup.
	var RostersPopup = TEPopup_GetObj("rosterspopup");
	if (RostersPopup!=null) {
		var strHTML = "<table class=template><tr>"
			+ "<td>"
			+ "<img src='../images/LoadingAnimatedClearLarge.gif'>"
			+ "</td><td valign=top style='padding-left:15px;'>Please&nbsp;wait... </td>"
			+ "</tr></table>"
		RostersPopup.Buttons("");
		RostersPopup.HTML(strHTML);
		if (RostersPopup.Top()+150<offset.height || RostersPopup.Top()>offset.height-50) {
			if (window.location != window.parent.location)
				RostersPopup.Top(offset.height - 150);
			else
				RostersPopup.Top(offset.height + 50);
		}
		RostersPopup.Reposition();
	} else {	
		// Start a Loading Popup
		var LoadingPopup = fLoadPopup("", false, false);
		if (window.location != window.parent.location)
			LoadingPopup.Top(offset.height - 150);
		else
			LoadingPopup.Top(offset.height + 50);
		LoadingPopup.Left(offset.width + 575);
		LoadingPopup.Reposition();
	}
	
	var argsToPost = "classid=" + lClassID + "&bactive=" + lbActive + strArgs;
	var ajaxObject = null;
    ajaxObject = TEGetAjaxObject( "/common/ClassStatsRostersAjax.aspx", argsToPost, TEClassStats_onRostersReturn );	
}

function TEClassStats_onRostersReturn() {
    
    if(ajaxObject != null && ajaxObject.readyState == 4
        && ajaxObject.status == 200) {
        
		var LoadingPopup = TEPopup_GetObj("te_floadpopup");
		if (LoadingPopup!=null)
			LoadingPopup.Close();

		var RostersPopup = TEPopup_GetObj("rosterspopup");
		nTEPopupZIndex = nTEPopupZIndex++;
		var bFoundRostersPopup = false;
		if (RostersPopup!=null) 
			bFoundRostersPopup = true;
		
		if (!bFoundRostersPopup) {
			if (window.location != window.parent.location)
				var offset = parent.getScrollOffset();
			else
				var offset = getScrollOffset();
				
			var RostersPopup = new TEPopup("rosterspopup");
            RostersPopup.bResizeWidthToFit(true);			
			RostersPopup.bDraggable(true);
			RostersPopup.bModal(false);
			if (window.location != window.parent.location)
				RostersPopup.Top(offset.height - 150);
			else
				RostersPopup.Top(offset.height + 50);
			RostersPopup.Left(offset.width + 575);
		}
		RostersPopup.Title("Rosters");
		RostersPopup.HTML(ajaxObject.responseText);
		if (!bFoundRostersPopup)
			RostersPopup.Draw();
		RostersPopup.ResizeToFit();
		RostersPopup.Reposition();
		
		if( parent && parent.fResizeIFrame)
			parent.fResizeIFrame("iframe_body");
		
        ajaxObject = null;
    } 
    return;
}

function VerifyMandatory( lstrInternalName, lstrExternalName ){                       
	var aElems = document.getElementsByName( lstrInternalName);
	var strRet = "";
    for( var i=0;i<aElems.length;i++){
		var elem = aElems[i];    
		if( elem == null || typeof elem.value == "undefined")
			continue;
		var bIsNull = false;
		var type = elem.type.toLowerCase();    
		if( type== "radio"){
			if( template_getSelectedRadioButton( aElems) == null)
				bIsNull = true;
		}
		else if( type == "text"){
			if( elem.value == "" || elem.value == null)
				bIsNull = true;
		}
		if( bIsNull ){
			strRet += lstrExternalName + " must be entered. \r\n"; 
		} 
		if( strRet != "")
			break;
	}
	return strRet;
}
function VerifyNumber( lstrInternalName, lstrExternalName, lbAllowNull, lbAllowFloat){
	var aElems = document.getElementsByName( lstrInternalName);
	var strRet = "";
	for( var i in aElems){
		var elem = aElems[i];
		if( elem == null || typeof elem.value == "undefined")
			continue;
		if( elem.value == "" ){
			if( !lbAllowNull)
				strRet += lstrExternalName + " must be entered. \r\n"; 
		} 
		else{
			if( !isFloat(elem.value) )
				strRet += lstrExternalName + " must be a number.   \r\n"; 
			else if( !lbAllowFloat && !isInt(elem.value) ){
				strRet += lstrExternalName + " must be a number. \r\n"; 
			}
		}
		if( strRet != "")
			break;
	}
	return strRet;
} 

function TEClassStats_fChangedFilters(lClassID, lbActive) {
	var strArgs="";
	if (document.getElementById("TEClassStats_gender").options[1].selected==true)
		strArgs+="&bfemale=0";
	else if (document.getElementById("TEClassStats_gender").options[2].selected==true)
		strArgs+="&bfemale=1";
	else if (document.getElementById("TEClassStats_gender").options[3].selected==true)
		strArgs+="&bunassigned=1";
	if (document.getElementById("TEClassStats_iep").options[1].selected==true)
		strArgs+="&bhasiep=1";
	else if (document.getElementById("TEClassStats_iep").options[2].selected==true)
		strArgs+="&bhasiep=0";
	TEClassStats_fShowRoster(lClassID, lbActive, strArgs);
}

function fUpdateAge() {
    var eAge = document.getElementById("Age");
    
    if( !eAge )
        return;
        
    var eMonth = document.getElementById("Month");
    var eDay = document.getElementById("Day");
    var eYear = document.getElementById("Year");
    var eBirthDate = document.getElementById("BirthDate");
    
    if( eBirthDate || (eMonth && eDay && eYear) ) {
        var studentbirthdate = null;
        var bIsValidDate = false;
        
        if( !eBirthDate ) {
        	var MonthIndex = eMonth.selectedIndex;
        	var DayIndex = eDay.selectedIndex;
        	var YearIndex = eYear.selectedIndex;
        	
        	if ( MonthIndex==0 || DayIndex==0 || YearIndex==0 ) 
                eAge.innerHTML = "";
        	else {
        	    studentbirthdate = new Date(eYear.value, eMonth.value - 1, eDay.value);
        	    bIsValidDate = isValidDate(eMonth.value - 1, eDay.value, eYear.value);
        	}
        }
        else if( template_HasValue(eBirthDate) ) {
            studentbirthdate = new Date(eBirthDate.value);
            bIsValidDate = isValidDate(null, null, null, eBirthDate.value);
        }

        if( bIsValidDate ) {
    		var currentdate = new Date();
    		var years = currentdate.getYear() - studentbirthdate.getYear();
    		if (currentdate.getMonth() < studentbirthdate.getMonth())
    			years -= 1;
    		else if (currentdate.getMonth() == studentbirthdate.getMonth() && currentdate.getDate() < studentbirthdate.getDate())
    			years -= 1;
    		if (years > 1900)
    			years -= 1900;
    		var months = currentdate.getMonth() - studentbirthdate.getMonth();
    		if (currentdate.getDate() < studentbirthdate.getDate())
    			months -=1;
    		if (months < 0)
    			months += 12;
            
            eAge.innerHTML = "(" + years + "y" + " " + months + "m)";    	
        }	
    }
    else 
        eAge.innerHTML = "";
}

// Initializes TEPopup in SchedulingStudentNew.aspx and SchedulingStudentAuto.aspx
function SchedulingStudentNew_fCreatePopup( strID, strTitle, strHTML, strType ) {
	
	// Initialization
	var ePopup = new TEPopup( strID );
	ePopup.bResizeWidthToFit(true); 
	ePopup.Title(strTitle);
	ePopup.HTML(strHTML);
	ePopup.Draw();
	
	// Hide some elements by default
	var eClassIDs = ePopup.FindElement("classids");
	if (eClassIDs.innerHTML!=null)
		var aClassIDs = eClassIDs.innerHTML.split(",");	
	else
		var aClassIDs = new Array();
	for( var i in aClassIDs){
		var eSec = ePopup.FindElement(aClassIDs[i] +  "_section");
		var eIns = ePopup.FindElement(aClassIDs[i] + "_ins");
		var eTeam = ePopup.FindElement(aClassIDs[i] + "_team");
		var eGenderStats = ePopup.FindElement(aClassIDs[i] + "_classstatsgender");
		var eIEPStats = ePopup.FindElement(aClassIDs[i] + "_classstatsiep");
		var eDropAddLink = ePopup.FindElement(aClassIDs[i] + "_dropaddlink");
		if (eSec != null)
			eSec.style.display="none";
		if (strType=="CurrentSchedule" && eIns!=null)
			eIns.style.display="none";
		if (eTeam != null)
			eTeam.style.display="none";
		if (eGenderStats != null)
			eGenderStats.style.display="none";
		if (eIEPStats != null)
			eIEPStats.style.display="none";
		if (eDropAddLink != null)
			eDropAddLink.style.display="none";
	}

	// Resize and position
	ePopup.ResizeToFit();
	if (window.location!=window.parent.location) {
		var windowsize = getParentWindowSize();
		var offset = window.parent.getScrollOffset();
		var pagesize = window.parent.getPageSize();
	}
	if (strType=="CurrentSchedule") {
		ePopup.Anchor("TR");
		ePopup.Reposition();
		ePopup.Anchor("");
	}
	else if (strType=="AllSectionsBL") {
		ePopup.Anchor("BL");
		ePopup.Reposition();
		ePopup.Anchor("");
		if (window.location!=window.parent.location)
			ePopup.Bottom(pagesize.height - windowsize.height - offset.height);
	} else {
		ePopup.Anchor("BR");
		ePopup.Reposition();
		ePopup.Anchor("");
		if (window.location!=window.parent.location)
			ePopup.Bottom(pagesize.height - windowsize.height - offset.height);
	}
	
	if( parent && parent.fResizeIFrame)
		parent.fResizeIFrame("iframe_body");	
}

function SchedulingStudentNew_fTogglePopupShowHide( lPopupID ) {
	var ePopup = TEPopup_GetObj( lPopupID );
	if (ePopup==null)
		return;
	var bCurrentSchedulePopup = true;
	if (lPopupID!="currentschedulepopup" && lPopupID!="enrolledPopup")
		bCurrentSchedulePopup = false;
	var eClassIDs = ePopup.FindElement("classids");
	var aClassIDs = eClassIDs.innerHTML.split(",");
	var eStatus = ePopup.FindElement("showhidestatus");
	var bShow = eStatus.innerHTML.indexOf("show") > -1;
	for (var i in aClassIDs) {
		var eSec = ePopup.FindElement(aClassIDs[i] +  "_section");
		var eIns = ePopup.FindElement(aClassIDs[i]  + "_ins");
		var eTeam = ePopup.FindElement(aClassIDs[i]  + "_team");
		var eGenderStats = ePopup.FindElement(aClassIDs[i]  + "_classstatsgender");
		var eIEPStats = ePopup.FindElement(aClassIDs[i]  + "_classstatsiep");
		var eDropAddLink = ePopup.FindElement(aClassIDs[i] + "_dropaddlink");
		if (bShow) {
			if (eSec!=null)
				eSec.style.display='';
			if (eIns!=null)
				eIns.style.display='';
			if (eTeam!=null)
				eTeam.style.display='';
			if (eGenderStats!=null)
				eGenderStats.style.display='';
			if (eIEPStats!=null)
				eIEPStats.style.display='';
			if (eDropAddLink!=null)
				eDropAddLink.style.display='';
		} else {
			if (eSec!=null)
				eSec.style.display="none";
			if (eIns!=null && bCurrentSchedulePopup)
				eIns.style.display="none";
			if (eTeam!=null)
				eTeam.style.display="none";
			if (eGenderStats!=null)
				eGenderStats.style.display="none";
			if (eIEPStats!=null)
				eIEPStats.style.display="none";
			if (eDropAddLink!=null)
				eDropAddLink.style.display="none";
		}
	}
	if (bShow)
		eStatus.innerHTML = eStatus.innerHTML.replace("show","hide");
	else
		eStatus.innerHTML = eStatus.innerHTML.replace("hide","show");
		
	ePopup.ResizeToFit();
	ePopup.Reposition();
	if( parent && parent.fResizeIFrame)
		parent.fResizeIFrame("iframe_body");	
}

function SchedulingStudentNew_fTogglePopupShowHideAllTeams( lPopupID, lStudentTeamID ) {
	var ePopup = TEPopup_GetObj( lPopupID );
	if (ePopup==null)
		return;
	var eStatus = ePopup.FindElement("teamsshowhidestatus");
	var bShowAllTeams = eStatus.innerHTML.indexOf("show") > -1;
	var eStrErrorRow = ePopup.FindElement("strerrorrow");
	var eShowDetailsLink = ePopup.FindElement("showhidestatus");
	var eClassIDs = ePopup.FindElement("classids");
	var aClassIDs = eClassIDs.innerHTML.split(",");
	for (var i in aClassIDs) {
		var bFoundStudentTeamID = false
		var eClassTeams = ePopup.FindElement(aClassIDs[i] + "_teamids");
		if (eClassTeams != null && eClassTeams.innerHTML != "") {
			var strClassTeams = eClassTeams.innerHTML;
			var aClassTeams = strClassTeams.split(",");
			for (var j in aClassTeams) {
				if(lStudentTeamID == aClassTeams[j]) {
					bFoundStudentTeamID = true;
					break;
				}
			}
		} else
			bFoundStudentTeamID = true;
		if (!bFoundStudentTeamID) {
			var eClassRow = ePopup.FindElement(aClassIDs[i] + "_class");
			if (eClassRow!=null) {
				if  (bShowAllTeams)
					eClassRow.style.display="";
				else
					eClassRow.style.display="none";
			}
		}
	}
	if (bShowAllTeams) {
		eStatus.innerHTML=eStatus.innerHTML.replace("show all","hide other");
		if (eStrErrorRow != null) {
			eStrErrorRow.style.display="none";
			if (eShowDetailsLink != null)
				eShowDetailsLink.style.display="";
		}
	}
	else {
		eStatus.innerHTML=eStatus.innerHTML.replace("hide other","show all");
		if (eStrErrorRow != null) {
			eStrErrorRow.style.display="";
			if (eShowDetailsLink != null)
				eShowDetailsLink.style.display="none";	
		}
	}
	
	ePopup.ResizeToFit();
	ePopup.Reposition();
	if( parent && parent.fResizeIFrame)
		parent.fResizeIFrame("iframe_body");	
}

function fShowCourseAllSections( lCourseID, lStudentID ) {
	// Drop existing loading popup
	var eLoadingPopup = TEPopup_GetObj("te_floadpopup");
	if (eLoadingPopup!=null)
		eLoadingPopup.Close();

	var eSectionsPopup = TEPopup_GetObj(lCourseID + "_sectionspopup");
	if (eSectionsPopup != null)
		return;	
		
	// Start a Loading Popup
	var eLoadingPopup = fLoadPopup("", false, false);
	eLoadingPopup.Anchor("BR");
	eLoadingPopup.Reposition();
	eLoadingPopup.Anchor("");
	if (window.location!=window.parent.location) {
		var windowsize = getParentWindowSize();
		var offset = window.parent.getScrollOffset();
		var pagesize = window.parent.getPageSize();
		eLoadingPopup.Bottom(pagesize.height - windowsize.height - offset.height);	
	}
	
	var argsToPost = "courseid=" + lCourseID;
	if (lStudentID!=null)
		argsToPost += "&studentid=" + lStudentID;
	var ajaxObject = null;
    ajaxObject = TEGetAjaxObject( "/schooladmins/SchedulingStudentNewAjaxGetCourseSections.aspx", argsToPost, onShowCourseAllSectionsReturn );		
}

function onShowCourseAllSectionsReturn() {
	if(ajaxObject != null && ajaxObject.readyState == 4
		&& ajaxObject.status == 200) {
		
		var eLoadingPopup = TEPopup_GetObj("te_floadpopup");
		if (eLoadingPopup!=null)
			eLoadingPopup.Close();			
		
		var aAjaxResponse = ajaxObject.responseText.split("__");
		
		var eSectionsPopup = TEPopup_GetObj(aAjaxResponse[0] + "_sectionspopup");
		if (eSectionsPopup != null)
			return;
		
		var strPopupID = aAjaxResponse[0] + "_sectionspopup";
		var strPopupTitle = "All Sections of " + aAjaxResponse[1];
		var strPopupHTML = aAjaxResponse[2];
		
		SchedulingStudentNew_fCreatePopup( strPopupID, strPopupTitle, strPopupHTML, "" );
		
		ajaxObject = null;
    }
    return;
}

function fShowStudentCourseRequests(lStudentID) {
	// Drop existing loading popup
	var eLoadingPopup = TEPopup_GetObj("te_floadpopup");
	if (eLoadingPopup!=null)
		eLoadingPopup.Close();

	var ePopup = TEPopup_GetObj("studentcourserequests");
	if (ePopup!=null)
		return;	
	
	// Start a Loading Popup
	var eLoadingPopup = fLoadPopup("", false, false);
	eLoadingPopup.Anchor("TR");
	eLoadingPopup.Reposition();
	eLoadingPopup.Anchor("");
	
	var ajaxObject = null
	ajaxObject = TEGetAjaxObject( "/common/CourseRequestView.aspx?bTab=1&bPopup=1&StudentID=" + lStudentID, "", onShowStudentCourseRequestsReturn);
}

function template_ArrayContains( lArray, lValue){
	for( var i=0;lArray != null && i<lArray.length;i++)
		if( lArray[i] == lValue)
			return true;
	return false;
}

function onShowStudentCourseRequestsReturn() {
	if(ajaxObject != null && ajaxObject.readyState == 4
		&& ajaxObject.status == 200) {
		
		var eLoadingPopup = TEPopup_GetObj("te_floadpopup");
		if (eLoadingPopup!=null)
			eLoadingPopup.Close();			
		
		var strAjaxResponse = ajaxObject.responseText;		
		
		ePopup = new TEPopup("studentcourserequests");
		ePopup.bResizeWidthToFit(true); 
		ePopup.Title("Course Requests");
		ePopup.HTML(strAjaxResponse);
		ePopup.Draw();
		ePopup.Anchor("TR");
		ePopup.Reposition();
		ePopup.Anchor("");	
		
		ajaxObject = null;
	}
	return;
}


function template_fClearList( e ){ 
	while (e.firstChild) {
	e.removeChild(e.firstChild);
	} 
}

function template_ErrorHandler( lsMessage, lsURL, lnLineNumber ) {
    if( !bErrorLogged && lsURL &&
        (lsURL.indexOf("teacherease.com") > -1 || lsURL.indexOf("schoolinsight.com") > -1 || lsURL.indexOf("common-goal.com") > -1) ) {
        var sArgsToPost = "message=" + escape(lsMessage)
                        + "&url=" + escape(lsURL)
                        + "&linenumber=" + lnLineNumber
                        ;
        var ajaxObject = TEGetAjaxObject("../common/AJAXJavascriptErrorHandler.aspx", sArgsToPost, null, true, false );
        bErrorLogged = true;
    }
    return false;
}

// The window parameter is only needed when attempting to select text from an element inside an iframe.
function template_SelectElementText( lElem, lWindow ) {
    lWindow = lWindow || window;
    var eDocument = lWindow.document;
    var oSelection = null;
    var oRange = null;
    
    if( lWindow.getSelection && eDocument.createRange ) {
        oSelection = lWindow.getSelection();
        oRange = eDocument.createRange();
        oRange.selectNodeContents(lElem);
        oSelection.removeAllRanges();
        oSelection.addRange(oRange);
    } 
    else if( eDocument.body.createTextRange ) {
        oRange = eDocument.body.createTextRange();
        oRange.moveToElementText(lElem);
        oRange.select();
    }
}

function TEPREnumeratedListItem_Draw( lbCircle, lbIsImage, lDescription, i ){
			//THIS FUNCTION IS duplicated in TEPREnumeratedListItem
	if( lbIsImage ) {      
		var strClass = "pr_container_container PREnumeratedList_imgs";                            
		var val = "<img class='noEdge' src='../images/preli_" + lDescription + ".png'>"
		//	+ "<div class='noEdge'>" + lDescription + "</div>";
	}
	else{
		var strClass = "pr_container_container PREnumeratedList";                            
		var val = lDescription;
	}  
	var events = " onmouseover='fMouseOver(" + i + ");' onmouseout='fMouseOut(" + i + ");' onclick='fClick(" + i + ");' " 
	var str = "<div " + events + " style='cursor:pointer;' class='" + strClass + "' id='itemdiv_" + i + "' >"
 
	if( lbIsImage ){
		var circleClass = "circle_stretch_large";
		var circleSize = 30;
	}
	else if( val!=null && val.toString().length > 1 ){ 
		var circleClass = "circle_stretch_medium";
		var circleSize = 30;
	}
	else  {
		var circleClass = "circle_stretch_small"; 
		var circleSize = 30;
	}
	if(  lbCircle )
		str += "<div class=pr_container><img id='preli_img' "
			+ "class=" + circleClass
			+ " src='../images/preli_circle" + circleSize + ".png'></div>"
					 
	str += "<span class='noEdge' id='listitem_" + i + "'>" + val + "</span>" 
	str += "</div>";
	return str;
} 

function PRELI_CheckAll( elem_clicked, lbIsImage  ){ 
	var curElem = elem_clicked.nextSibling;
	while( curElem != null){
		if( curElem.id == "prEnumeratedListContainer")
			break;
		curElem = curElem.nextSibling;
	}
	if( curElem == null)
		return;
	
	var bCheckAll = 1;
	if( elem_clicked.innerHTML.indexOf("check all") != -1){
		elem_clicked.innerHTML = "<a class=actionlink href='javascript:;'>clear all</a>"; 
	}
	else{
		bCheckAll = 0;
		elem_clicked.innerHTML = "<a class=actionlink href='javascript:;'>check all</a>";
	}
	for( var i=0;i<curElem.rows.length;i++){
		var row = curElem.rows[i];
		for( var j=0; j<row.cells.length;j++){
			var cell = row.cells[j]; 
			
			var innerTbl = cell.getElementsByTagName( "table" )[0]; 
			if( innerTbl == null)
				continue;
				
			for( var z=0;z<innerTbl.rows[0].cells.length;z++){ 
				PRELI_Click( innerTbl.rows[0].cells[z].firstChild, bCheckAll, lbIsImage);
			}
		}
	}
}
function PRELI_Click( elem_clicked, lbCheck, lbIsImage){  
	var chkElem = null;
	if(elem_clicked.getElementsByTagName == null)
		return;
		
	var aElems = elem_clicked.getElementsByTagName("input");
	for( var i =0;i<aElems.length;i++){ 
		if( aElems[i].type == "checkbox" && aElems[i].name.indexOf("preld") >= 0 ){
			chkElem = aElems[i];                                                   
			break;
		}
	}
	if( lbCheck ==null && chkElem == null)
		return;  
		                
	if( lbCheck == null )
		lbCheck =  !chkElem.checked;
	        
	var nShiftTotal = 0;	
	if( lbCheck ){
		if( chkElem != null){
			if( !chkElem.checked )
				nShiftTotal++;
			chkElem.checked = true;
		}	 
		if( typeof elem_clicked.firstChild.tagName == "undefined" || elem_clicked.firstChild.tagName.toLowerCase() != "div"){
			var newDiv = document.createElement("div");
			newDiv.className = "pr_container";
			
			if(  typeof elem_clicked.firstChild.tagName == "undefined" )
				var val = elem_clicked.innerHTML;
			else
				var val = elem_clicked.firstChild.innerHTML;
			if( lbIsImage ){
				var circleClass = "circle_stretch_large";
				var circleSize = 30;
			}
			else if( val!=null && val.toString().length > 1 ){ 
				var circleClass = "circle_stretch_medium";
				var circleSize = "22x40";
			}
			else  {
				var circleClass = "circle_stretch_small"; 
				var circleSize = 18;
			}  
			newDiv.innerHTML = "<img id='preli_img' "
					+ "class=" + circleClass
					+ " src='../images/preli_Circle" + circleSize + ".png'>"
			elem_clicked.insertBefore( newDiv, elem_clicked.firstChild);
		}
	}
	else{
		if( chkElem != null){
			if( chkElem.checked )
				nShiftTotal--;
			chkElem.checked = false;
		}      
		if( typeof elem_clicked.firstChild.tagName != "undefined" && elem_clicked.firstChild.tagName.toLowerCase() == "div")       
				elem_clicked.removeChild( elem_clicked.firstChild ); 
	}
	if( nShiftTotal != 0){
	    var parent = elem_clicked
	    var nTables = 0;
	    while(parent != null && nTables < 2){
	    	parent = parent.parentNode;
	    	if(parent!=null && parent.tagName.toLowerCase() == "table")
	    		nTables++;
	    }
	    if( parent == null)
	    	return;
	    var lastrow = parent.rows[ parent.rows.length-1];
	    var cell = lastrow.cells[0];
	    
	    var span = cell.getElementsByTagName("span")[0];
		if( span == null || span.id != "prelli_count")
			return;
		var curCount = parseInt( span.innerHTML);
		span.innerHTML = curCount + nShiftTotal;
	}
}

function template_SortDates(a,b) {
    if( a[0]=="null" && a[1]==1 )
        return 1;
    else if( a[0]=="null" && a[1]==0 )
        return 0;
    if( b[0]=="null" && b[1]==1 )
        return 0;
    else if( b[0]=="null" && b[1]==0 )
        return 1;
    else if( a[0].valueOf()==b[0].valueOf() )
        return a[1]==1;
    return a[0].valueOf()>b[0].valueOf();
}

function template_OverlappingEnrollmentError( lState, laEntryDate, laExitDate, laCalendarID, laHSID, laServingScoolID, laFTE, laMaxPresentCredit, lbExclusiveExitDate, lbShowAttendanceInHours) {
    var bDayLengthError = false;
    var bHomeSchoolError = false;
    var bServingSchoolError = false;
    var bCalendarError = false;
    var bSetCalendarError = false;
    var bEntryDateError = false;
    var errString = "";
    
    //clean the data
    for( var i=0; i<laEntryDate.length; i++ ) {
        if( Date.parse( laEntryDate[i] ) )
            laEntryDate[i] = new Date( laEntryDate[i] );
        else
            laEntryDate[i] = "null";
            
        if( Date.parse( laExitDate[i] ) )
            laExitDate[i] = new Date( laExitDate[i] );
        else
            laExitDate[i] = "null";
    }
    
        
    for( var i=0; i<laEntryDate.length; i++ ) {
        if( bSetCalendarError==false && laCalendarID[i]=="null" ) {
            bSetCalendarError = true;
    	    errString += "Please select a calendar for each enrollment.\r\n";
    	    break;
    	}
    	var dEntry1 = laEntryDate[i];
    	var dExit1 = laExitDate[i];
    	if( bEntryDateError==false && dEntry1!="null" && dExit1!="null" && dEntry1.valueOf()>dExit1.valueOf() ) {
        	errString += "The Entry Date cannot be later than the Exit Date.\r\n";
        	bEntryDateError = true;
        }

        for( var j=0; j<laEntryDate.length; j++ ) {
            if( j==i )
                continue;
        	var dEntry2 = laEntryDate[j];
        	var dExit2 = laExitDate[j];
            var overlap = template_bEnrollmentsOverlap(dEntry1, dExit1, dEntry2, dExit2, lbExclusiveExitDate);
            if( overlap ) {
                if( !bHomeSchoolError && laHSID.length>0 && laHSID[i]!=laHSID[j]) {
                    errString += "Sorry, enrollments with overlapping entry/exit dates cannot have different home schools.\r\n";
                    bHomeSchoolError = true;
                }
                if( !bServingSchoolError && laServingScoolID.length>0 && laServingScoolID[i]==laServingScoolID[j] ) {
                    errString += "Sorry, enrollments with overlapping entry/exit dates cannot have the same serving school.\r\n";
                    bServingSchoolError = true;
                }
                if( !bCalendarError && laCalendarID.length>0 && laCalendarID[i]!=laCalendarID[j]) {
                    errString += "Sorry, enrollments with overlapping entry/exit dates cannot have different calendars.\r\n";
                    bCalendarError = true;
                }
            }
        }
    }
    
    //Create a timeline of entry/exit dates
    var aDates = new Array();
    var hDates = {};
    var nDay = 1000 * 60 * 60 * 24;
    for( var i=0; i<laEntryDate.length; i++ ) {
        if( laEntryDate[i]=="null" && hDates["enull"]==null) {
            var aTmp = new Array();
            aTmp.push("null");
            aTmp.push( 0 );
            aDates.push(aTmp);
            hDates["enull"] = 1;
        }
        else if( laEntryDate[i]!="null" && hDates["e" + laEntryDate[i]]==null ) {
            var aTmp = new Array();
            aTmp.push( new Date(laEntryDate[i]) );
            aTmp.push( 0 );
            aDates.push( aTmp );
            hDates["e" + laEntryDate[i]] = 1;
        }
        
        if( laExitDate[i]=="null" && hDates["xnull"]==null ) {
            var aTmp = new Array();
            aTmp.push("null");
            aTmp.push( 1 );
            aDates.push(aTmp);
            hDates["xnull"] = 1;
        }
        else if( laExitDate[i]!="null" && hDates["x" + laExitDate[i]]==null ) {
            var aTmp = new Array();
            var dTmp = new Date( laExitDate[i] );
            if( lbExclusiveExitDate )
                dTmp = new Date( dTmp.valueOf() - nDay );
            aTmp.push( dTmp );
            aTmp.push( 1 );
            aDates.push( aTmp );
            hDates["x" + laExitDate[i]] = 1;
        }
    }
    aDates.sort( template_SortDates );
    var aEntryDate = new Array();
    var aExitDate = new Array();
    
    /*Build a list of date ranges to verify we are either 1 or .5
    Here is an example of input (Note: The following enrollments should result in an error)
    9/14/2011-null .7
    9/14/2011-9/18/2011 .3
    9/20/2011-null .2
    9/20/2011-null .1
    We'll create the following timeline of entry/exit dates
    9/14/2011 0
    9/18/2011 1
    9/20/2011 0
    null 1
    From the timeline, produce another set of date ranges that need to be inspected, results below using timeline from above...
    9/14/2011-9/18/2011
    9/19/2011-9/19/2011 (note this is dead space that wouldn't have been caught with straight range comparison)
    9/20/2011-null
    
    Use the following algorithm on the time line to produce the date ranges to check
    1. When i is an entry date
        a. Set the start of the date range to i
        b. When i+1 is an entry date set the end of the date range to the day before i+1
        Example: i=9/14/2011, i+1=9/15/2011 creates a range of 9/14/2011-9/14/2011
        c. When i+1 is an exit date set the end of the date range to i+1
        Example: i=9/14/2011, i+1=9/15/2011 creates a range of 9/14/2011-9/15/2011
    2. When i is an exit date
        a. If i+1 is an entry date that is one day later then we do not create a date range as it will get
            created in another case.
        Example. i=9/19/2011, i+1=9/20/2011
        b. If i+1 is an exit date
            I. set the start of the date range to the day after i
            II. Set the end of the date range to i+1
            Example. i=9/16/2011, i+1=9/17/2011 will create a date range to check of
                9/17/2011-9/17/2011
    */
    for( var i=0; i+1<aDates.length; i++ ) {
        if( aDates[i][1] == 0 ) {
            aEntryDate.push( aDates[i][0] );
        }
        else {
            var dTmp = new Date( aDates[i][0].valueOf() + nDay );
            if( aDates[i+1][1] == 0 && aDates[i+1][0].valueOf()==dTmp.valueOf() )
                continue;
            aEntryDate.push( dTmp );
        }
        
        if( aDates[i+1][1] == 0 ) {
            var dTmp = new Date( aDates[i+1][0].valueOf() - nDay );
            aExitDate.push( dTmp );
        }
        else {
                aExitDate.push( aDates[i+1][0] );
        }
    }

    //Compare the fte lengths from the date ranges created off of the timeline
    for( var i=0; i<aEntryDate.length; i++ ) {
        var dEntry1 = aEntryDate[i];
        var dExit1 = aExitDate[i];
        var aOverlappingSet = new Array();
        for( var j=0; j<laEntryDate.length; j++ ) {
            var dEntry2 = laEntryDate[j];
            var dExit2 = laExitDate[j];
            var overlap = template_bEnrollmentsOverlap(dEntry1, dExit1, dEntry2, dExit2, lbExclusiveExitDate);
            if( overlap ) {
                if( aOverlappingSet.length > 0 ) {
                    var bFoundSet = false;
                    for( var m=0; m<aOverlappingSet.length; m++ ) {
                        var bSetOverlap = true;
                        for( var k=0; k<aOverlappingSet[m].length; k++ ) {
                            var dEntry3 = laEntryDate[aOverlappingSet[m][k]];
                            var dExit3 = laExitDate[aOverlappingSet[m][k]];
                            bSetOverlap = template_bEnrollmentsOverlap(dEntry2, dExit2, dEntry3, dExit3, lbExclusiveExitDate);
                            if( !bSetOverlap )
                                break;
                        }
                        
                        if( bSetOverlap ) {
                            aOverlappingSet[m].push( j );
                            bFoundSet = true;
                        }
                    }
                    
                    if( !bFoundSet ) {
                        var aTmp = new Array();
                        aTmp.push( j );
                        aOverlappingSet.push( aTmp );
                    }
                }
                else {
                    var aTmp = new Array();
                    aTmp.push( j );
                    aOverlappingSet.push( aTmp );
                }
            }
        }
 
        for( var b=0; b<aOverlappingSet.length; b++ ) {
            var fCurrentDayLength = 0;
            var fMaxPresentCredit = 0;

            for( var g=0; g<aOverlappingSet[b].length; g++ ) {
                var nFTEIndex = aOverlappingSet[b][g];
                fCurrentDayLength += Number(laFTE[nFTEIndex]);
                fMaxPresentCredit += Number(laMaxPresentCredit[nFTEIndex]);
            }

            fCurrentDayLength = fCurrentDayLength.toFixed(2);
            fMaxPresentCredit = fMaxPresentCredit.toFixed(2);

            if( aOverlappingSet[b].length == 1 && (fCurrentDayLength <= 0 || fCurrentDayLength > 1) )
                errString = "Sorry, an Enrollment's FTE cannot be greater than 1 or less than or equal to 0";
			else if( !bDayLengthError ) {
				if( lState == "IL" || lState == "MO") {
					if( fCurrentDayLength <= 0 || fCurrentDayLength > 1 ) {
					    errString += "Sorry, Length of Day for enrollments with overlapping entry/exit dates must be greater than 0 and less than or equal to 1.\r\n";
					    bDayLengthError = true;
				    }
				}
				else {
					if( fCurrentDayLength!=1 && fCurrentDayLength!=.5 ) {
	                	errString += "Sorry, Length of Day for enrollments with overlapping entry/exit dates must equal 0.5 or 1.\r\n";
	                	bDayLengthError = true;
					}
				}
				if( fMaxPresentCredit > 1 && !bDayLengthError ) {
				    errString += "Sorry, Max Present Credit for enrollments with overlapping entry/exit dates must be greater than 0 and less than or equal to 1.\r\n";
	                bDayLengthError = true;
				}
            }
        }    
    }
    
    return errString;
}

// Values are stored using \r\n, but depending on the browser a textarea will use \r, \n, or \r\n.
// This function will convert a value using \r or \n to use \r\n for purposes of counting the number
// of characters in a textarea.
function template_FixTextAreaNewLine( strValue ) {
    // Uses the same \r\n newline, so skip this case.
    if( strValue.indexOf("\r\n") != -1 ) {}
    // Uses \r, so add a \n.
    else if( strValue.indexOf("\r") != -1 )
        strValue = strValue.replace(/\r/g, "\r\n");
    // Uses \n, so add a \r. 
    else if( strValue.indexOf("\n") != -1 )
        strValue = strValue.replace(/\n/g, "\r\n");
 
    return strValue;
}

//THE AJAX transcript functions are used by CourseRequest related pages to show a popup of the students grades
function template_AjaxTanscriptModeChanged( lStudentID, eSel){
    fShowTranscript( lStudentID, eSel.value);
}
var transcriptAjax = null;
function fShowTranscript( lStudentID, lMode, lAddToQS ){ 
    if( lMode != "failedTracks" && lMode != "allTracks" && lMode != "transcript" )
        lMode = "transcript"
	var ePopup = TEPopup_GetObj("te_transcript");
	if (!ePopup)
		ePopup = new TEPopup("te_transcript"); 
	ePopup.Title("Transcript Summary");      
	var strHTML = "<table class=template><tr>"
		+ "<td>"
		+ "<img src='../images/LoadingAnimatedClearLarge.gif'>"
		+ "</td><td valign=top style='padding-left:15px;'>Please&nbsp;wait... </td>"
		+ "</tr></table>"
    
	ePopup.HTML( strHTML );  
	ePopup.bShowXButton (true);
	ePopup.Buttons("");  
        ePopup.Width(200);   
        ePopup.AnchorPaddingVert(5);
        ePopup.AnchorPaddingHoriz(5);
	ePopup.Draw();      
		ePopup.SetPositionFromAnchor("TR");
    if( lAddToQS == null || typeof lAddToQS == "undfined")
        lAddToQS = "";
    var strArgs = "&StudentID=" + lStudentID    
        + "&Mode=" + lMode
        + lAddToQS;
    /*if( lSubjectTypeID != null)
        strArgs += "SubjectTypeID=" + lSubjectTypeID
    if( laCourseIDs != null)
        strArgs += "aCourseID=" + laCourseIDs.toString();*/
    var url = "../common/AJAXStudentTranscript.aspx";
    transcriptAjax = TEGetAjaxObject( url, strArgs, fAjaxTranscriptReturn );
}
function fAjaxTranscriptReturn(){
    if(transcriptAjax != null && transcriptAjax.readyState == 4
        && transcriptAjax.status == 200) {
        
		var ePopup = TEPopup_GetObj("te_transcript"); 
    	if (!ePopup)
    		ePopup = new TEPopup("te_transcript");  
		ePopup.HTML(transcriptAjax.responseText);   
        ePopup.Draw();    
        ePopup.bResizeWidthToFit(true)
		ePopup.ResizeToFit();
		ePopup.SetPositionFromAnchor("TR");
		if( parent && parent.fResizeIFrame)
			parent.fResizeIFrame("iframe_body");
		
        transcriptAjax = null;
    }
}

function template_fGotoInstructorAttendanceViewAll() {
	var dDate = new Date();
	var strTime = getShortTime( "1/1/2000 " + dDate.getHours() + ":" + dDate.getMinutes() );

	window.location = "/instructors/AttendanceViewAll.aspx?Time=" + strTime;
}

