var documentLoaded = false;
var G_START_DATE = Date.parse(new Date);
var bIE = (window.navigator.appName == 'Microsoft Internet Explorer');
var appVer = navigator.appVersion.toLowerCase();
var bMozilla = false, bFirefox = false, bNetscape = false, bSafari = false, bAOL = false, bOpera = false;
var orgStyleClassName;
var waitText = 'Wait';

if (appVer.indexOf('firefox') != -1)
	bFirefox = true;
else if (appVer.indexOf('opera') != -1)
	bOpera = true;
else if (appVer.indexOf('netscape') != -1)
	bNetscape = true;
else if (appVer.indexOf('safari') != -1)
	bSafari = true;
else if (appVer.indexOf('aol') != -1)
	bAOL = true;
else
	bMozilla = true;

var hexHash = new Array();
var baseHexHash = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');

function setupHexHash() {
	var counter = 0;
	var basic = new Array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
	for(var i=0;i<16;i++) {
		for(var j=0;j<16;j++) {
			hexHash[counter] = String(basic[i]) + String(basic[j]);
			counter++;
		};
	};
};

// pageOnLoad will be called by the body onload event if
// pageOnLoad is not null, i.e. if the function has been defined
// somewhere in the page body. Use to add custom functionality to
// body onload event.

var pageOnLoad = null;
var genericRollover = null;
var loadedImages = new Array();
var formSubmitStatus = -1;	//-1 = not ready to submit; 0 = disable buttons only no submission; 1 = ready to submit;
var submitFormName = "";
var bLoadCompleted = false;

function documentOnLoad() {
	setupHexHash();
	setupClassList();
	setupDropdownMenus();
	if (typeof(setupSpecialGrades)!='undefined') setupSpecialGrades();
	if (pageOnLoad) pageOnLoad();
	preloadImages();
	bLoadCompleted = true;
}

function preloadImages() {
	var imgs = document.getElementsByTagName('img');
	var img, target;
	for(var i=imgs.length; i-->0;) {
		img = imgs[i].src;
		if(img.indexOf('_off') != -1) {
			target = img.replace('_off.gif','_on.gif');
			loadedImages[target] = new Image();
			loadedImages[target].src = target;
		};
	};
};

function setupDropdownMenus() {
	// teacher dropdowns
	try {
		new tcSlider( 'menuClasses', 'down', '' );
		
		if(typeof(classIdArray)=='undefined') {
			new tcSlider( 'menuTools', 'down', '' );
			new tcSlider( 'menuCopyList', 'right', 'menuTools');
			new tcSlider('menuGradingScales', 'right', 'menuTools');
			new tcSlider('menuGroupsTools', 'right', 'menuTools');
			new tcSlider('menuNotificationsList', 'right', 'menuTools');
			new tcSlider( 'menuReports', 'down', '' );
			new tcSlider( 'menuAttendance', 'right', 'menuReports' );
			new tcSlider( 'menuAssignments', 'right', 'menuReports' );
			new tcSlider( 'menuAudit', 'right', 'menuReports' );
			new tcSlider( 'menuAverages', 'right', 'menuReports' );	
			new tcSlider( 'menuComments', 'right', 'menuReports' );
			new tcSlider( 'menuExportTools', 'right', 'menuTools');
			new tcSlider( 'menuSummary', 'right', 'menuReports');
			new tcSlider( 'menuSchedules', 'right', 'menuReports' );
			new tcSlider('menuVerification', 'right', 'menuReports');
			new tcSlider('menuSchedulesTools', 'right', 'menuTools');
        };
	} catch (ex) { };
	
    // admin dropdowns
	try {
		new tcSlider( 'menuGrades', 'down', '' );
		new tcSlider( 'menuAdminReports', 'down', '' );
		new tcSlider( 'menuAdminReportsAttendance', 'right', 'menuAdminReports' );
		new tcSlider( 'menuAdminReportsGrades', 'right', 'menuAdminReports' );

		new tcSlider( 'menuAdminTools', 'down', '' );
		new tcSlider( 'menuAdminUsers', 'down', '' );
		new tcSlider( 'menuAdminTemplates', 'down', '' );
		new tcSlider( 'menuAdminTemplatesAttendance', 'left', 'menuAdminTemplates' );
		new tcSlider( 'menuAdminTemplatesCalendar', 'left', 'menuAdminTemplates' );
		new tcSlider( 'menuAdminTemplatesDisctrict', 'left', 'menuAdminTemplates' );
		new tcSlider( 'menuAdminTemplatesGrades', 'left', 'menuAdminTemplates' );
		new tcSlider( 'menuAdminTemplatesLessonPlan', 'left', 'menuAdminTemplates' );
		new tcSlider( 'menuAdminTemplatesSchool', 'left', 'menuAdminTemplates' );
		new tcSlider( 'menuAdminTemplatesSubmitGrades', 'left', 'menuAdminTemplates' );
	} catch (ex) { };
	
	// parent dropdowns
	try {
		new tcSlider('menuStudents', 'down', '' );
		if(typeof(studentIdArray)!='undefined') {
			var tmpStudentId;
			for(var i = 0;i<studentIdArray.length;i++)
			{
				tmpStudentId = String(studentIdArray[i]);
				if (document.getElementById('menuStudentClasses' + tmpStudentId + 'Container') != null)
					new tcSlider('menuStudentClasses' + tmpStudentId, 'right', 'menuStudents');
			}
		}
	}
	catch (ex) {};
	// student dropdowns
	try {
		new tcSlider('menuStudentLogin', 'down', '' );
	}
	catch (ex) {};
	
	try {
		var styleSheet = document.styleSheets[0];
		var buttonStyle = bIE ? styleSheet.rules[0].style : styleSheet.cssRules[0].style;
		buttonStyle['backgroundColor'] = '#efefef';
		buttonStyle['backgroundColor'] = '';
		genericRollover = document.getElementById('genericRollover');
	} catch (ex) { };
};
	
function dynamicRollover( id ) {
	var elem = document.getElementById( id );
	
	if( navigator.userAgent.indexOf('Mac') == -1 ) {
		elem.src = elem.src.replace('_off.gif','_on.gif');
	} else {
		try {
			var target = tcSlider.locate( elem );
			elem.src = elem.src.replace('_off.gif','_on.gif');
			genericRollover.style[ 'left' ] = target.x + 'px';
			genericRollover.style[ 'top' ] = target.y + 'px';
			genericRollover.style[ 'visibility' ] = 'visible';
		} catch (ex) { };
	};
};

function dynamicRestore( id ) {
	var elem = document.getElementById( id );
	if( navigator.userAgent.indexOf('Mac') == -1 ) {
		elem.src = elem.src.replace('_on.gif','_off.gif');
	} else {
		try {
			elem.src = elem.src.replace('_on.gif','_off.gif');
			genericRollover.style[ 'visibility' ] = 'hidden';
		} catch (ex) { };
	};
};


function isDisplayNone( elem ) {
	var bDisplayNone = false;
	try {
		if ( elem.style.display == 'none' ) {
			bDisplayNone = true;
		} else {
			if ( elem.parentNode != null )
				bDisplayNone = isDisplayNone( elem.parentNode );
		}
	} catch ( err ) {
		// do nothing
	};
	return bDisplayNone;
} 


function locateFirstTextField(){
	var el, bElNotChosen = true;
	if (eval(document.getElementById('theform'))){
		with (document.getElementById('theform')) {
			for (var i = 0; i < elements.length && bElNotChosen; i++) {
				el = elements[i];
				if ((el.type=='text' || el.type=='textarea') && el.disabled != true && el.readOnly !=true && !isDisplayNone(el) ){
					try {
						elements[i].focus();
						bElNotChosen = false;						
					}catch (x) {
						// do nothing here
					}	
				}
			}
		}	
	} else if (typeof(isGradeAll) != 'undefined' && isGradeAll) {
		var myElements = document.getElementsByTagName('input');
		for (var i = 0; i < myElements.length && bElNotChosen; i++) {
			el = myElements[i];
			if ((el.type=='text' || el.type=='textarea') && el.disabled != true && el.readOnly != true && !isDisplayNone(el)) {
				try {
					el.focus();
					bElNotChosen = false;
				} catch (x) {
					// do nothing here
				}
			}
		}
	}
}
	
// dropdown menu for class button
var classList, bKeepOn = false, bMenuOn = false;
var toolsList, reportsList;

function showDropDown(anElID) {
	if (bMenuOn) {
		bKeepOn = true;
		var anElement = document.getElementById(anElID);
		var list = anElID.split('_')[1];
		var listName = document.getElementById(list).style;
		var y, x, totalLen, dest;
		dest = getOffset(anElement);
		
		if (list == 'classList'){
			y = dest.y + 25;
			x = dest.x;
		}else if (list == 'toolsList'){
			y = dest.y + 50;
			x = dest.x;
			x = (bIE? (x -1) : x);	
		}else if (list == 'reportsList'){
			totalLen = 100;
			y = dest.y + 50;
			x = dest.x - totalLen;
			x = (bIE? (x -1) : x);	
		}				
		turnOn(x, y, listName);
	}
}
function leaveDropDown() {
	bKeepOn = false;
}
function turnOn(x, y, listName) {
	boxSwitch('block', x, y, listName);
}
function turnOff() {
	boxSwitch('none', 0, 0, '');
}
function boxSwitch(displayVal, x, y, listName) {
	if (listName){
		listName.display = displayVal;
		//listName.zIndex = 0;
		listName.left = x;
		listName.top = y;		
	}else{
		if (classList) {
			classList.display = displayVal;
			classList.left = x;
			classList.top = y;
		}
		if (toolsList) {
			toolsList.display = displayVal;
			toolsList.left = x;
			toolsList.top = y;
		}
		if (reportsList) {
			reportsList.display = displayVal;
			reportsList.left = x;
			reportsList.top = y;
		}
	}
}
function testOn() {
	if (bMenuOn) {
		if (!bKeepOn)
			turnOff();
		setTimeout('testOn();',300);
	}
}
function setupClassList() {
	if (bMenuOn) {
		classList = document.getElementById('classList').style;
		toolsList = document.getElementById('toolsList').style;
		reportsList = document.getElementById('reportsList').style;					
		setTimeout('testOn();',300);		
	}			
}

function openWin(url, name, options)
{
	var newwin = window.open(url, name + "_" + aspSessionID, options);
	try { 
		newwin.focus(); 
		return newwin;
	}
	catch (ex) {};
}


function report_card_popup(class_id, uid) {
    url = "/submit_grades/report_card.aspx?class_id=" + class_id + "&uid=" + uid;
    newwin = window.open(url, "report_card_popup", '');
    newwin.focus();
}


function student_profile_popup(uid)
{
    url = "/admin/attendance/parent_info.aspx?uid=" + uid;
    options = "height=300, width=450, scrollbars=yes, resizable=yes, nostatus,top=50,left=50, menubar=yes";
    newwin = window.open(url, "student_profile_popup", options);
    newwin.focus();
}


function assignment_popup(aid) {
	url = '/assignment/popup.asp?aid=' + aid;
	var options = "height=180,width=550, scrollbars=yes, resizable=yes, nostatus,top=50,left=50, menubar=no";
	var optwind = window.open(url, "assignment_popup", options);
	optwind.focus();
}

function grading_template_popup(template_id) {
	url = '/assignment/grading_legend.asp?template_id=' + template_id;
	options = "height=200,width=310, scrollbars=yes, resizable=yes, nostatus,top=50,left=50, menubar=no";
	optwind = window.open(url, "grading_legend", options);
	optwind.focus();
}

function js_trim(str) 
{
	return str.replace(/^\s+/gi, "").replace(/\s+$/gi, "");
}

function isBlank(str) {
	return (String(str).length == 0);
}

function validateList(list, fieldName, fieldLength, checkForSpaces) {
	var strError = '';
	
	if(typeof(checkForSpaces)=='undefined') checkForSpaces = false;
	
	var re = new Array();
	re[0] = new RegExp('[^, ] {1,}[^, ]');
	re[1] = new RegExp('[^,' + (checkForSpaces?' ':'') + ']{' + String(fieldLength+1) + ',}');
	
	if(isBlank(list)) {
		strError += 'At least one ' + fieldName + ' must be entered.\n';
	} else if(checkForSpaces && list.search(re[0])>-1) {
		strError += fieldName + 's must be separated by commas.\n';
	} else if(list.search(re[1])>-1) {
		strError += fieldName + 's must be no longer than ' + fieldLength + ' characters.\n';
	};
	
	return strError;
};


function GetNumDaysInMonth(themonth, theyear)
{
	var numDays;
	
	if (themonth==1 || themonth==3 || themonth==5 || themonth==7 || themonth==8 || themonth==10 || themonth==12)
		numDays = 31;
	else if (themonth == 2) {
		if (theyear % 400 == 0)
			numDays = 29;
		else if (theyear % 100 == 0)
			numDays = 28;
		if (theyear % 4 == 0)
			numDays = 29;
		else
			numDays = 28;
	} else
		numDays = 30;

	return numDays;
}

function RefreshWindow(win)
{
	if (win && !win.closed) {
		if (typeof(dotNetEnvironment) != 'undefined' && dotNetEnvironment && xmlhttp && baseURL)
		{
			if (typeof(win.ResetSessionStartTime) != 'undefined')
			{
				win.ResetSessionStartTime();
				xmlhttp.open('GET', baseURL + '/empty.aspx?sid=' + Math.random(), true);
				xmlhttp.onreadystatechange = function() {
					if (xmlhttp.readyState == 4) {
						if (xmlhttp.status == 200) {
							xmlhttp.open('GET', baseURL + '/empty.asp?sid=' + Math.random(), true);
							xmlhttp.onreadystatechange = function() { };
							xmlhttp.send(null);
						};
					};
				};
				xmlhttp.send(null);
			}
		}
		else
			RefreshWindowClassic(win);
	}
}

function RefreshWindowClassic(win)
{
	if (win && !win.closed && win.document.timeoutForm)
	{	
		win.document.timeoutForm.sessionStartTime.value = Date.parse(new Date);
		var iframe = win.frames['timeoutFrame'];
		try {
			// for Safari
			iframe.document.location.reload();
		} catch (ex) {
			if (iframe.contentDocument)
			{
				iframe.contentDocument.location.reload();
			}
			else
			{
				iframe.document.frames['timeoutFrame'].document.location.reload();
			}
		}
	}
}

function RefreshParent()
{
	RefreshWindow(window.opener);
}


function closeRefreshParent()
{
	RefreshParent();
	if (window.opener && !window.opener.closed)	
		window.opener.focus();	
	window.close();
}


function FormModified() {
  document.getElementById('ismodified').value = 1;
}

function openStudentGrade(uid, class_id, cycle_id){
    var pWindow;
	url = '/assignment/grade.aspx?mode=grade_student&uid=' + uid + '&class_id=' + class_id + '&cycle_list=' + cycle_id;
	
	var modify;
	if (window.main)
		modify = window.main.document.getElementById( 'ismodified' );
	else
		modify = window.document.getElementById( 'ismodified' );
		
	if( modify != null && modify.value != 0 && !confirmMsgWarnChanges2() ) {
		return;
	};
		
	if (typeof(isGradeAll) != 'undefined'){
		pWindow = window.parent.parent;	
	}else{
		isGradeAll = false;
		pWindow = window;	
	}
	pWindow.location = url;
}


function Round(number, decimals)
{
	return Math.round((number + 0.00001) * Math.pow(10, decimals)) / Math.pow(10, decimals);
}


//
//functions for new interface
//
function popup(url, title, wWidth, wHeight){
	var options;
	if (parseInt(wHeight) == 0){
		wHeight = '480';
		wWidth = '540';
	}
	options = 'height=' +wHeight +', width=' + wWidth + ', scrollbars=yes, resizable=yes, nostatus, top=50,left=50, menubar=no';
	
	var optwind = window.open(url, title, options);
	
	optwind.moveTo( window.screen.availHeight, window.screen.availWidth );
	window.focus();
	
	if( gradeAllModifiedCheck() ) {
		optwind.close();
		return;
	};
	try {
		optwind.focus();
		optwind.moveTo( 50, 50 );
	} catch(ex) {}
}

function PopupResetOpener(url, title, wWidth, wHeight, opener, class_id)
{		
	var options;
	var blank_page_url = '/keep_alive.asp';	
	if (parseInt(wHeight) == 0){
		wHeight = '480';
		wWidth = '540';
	}
	options = 'height=' +wHeight +', width=' + wWidth + ', scrollbars=yes, resizable=yes, nostatus, top=50,left=50, menubar=no';
	var optwind, bShortCircuit;
	if 	( 
			( typeof( isGradeAll ) != 'undefined' && isGradeAll ) || 
			( typeof( isGradeAssmt ) != 'undefined' && isGradeAssmt ) || 
			( typeof( isGradeStudent) != 'undefined' && isGradeStudent ) ||
			( typeof( isAttendaceForm) != 'undefined' && isAttendaceForm ) ||
			( typeof( isSubmitGradeForm) != 'undefined' && isSubmitGradeForm) ||
			( typeof( isCheckListCategoryForm) != 'undefined' && isCheckListCategoryForm) ||
			( typeof( isLessonPlanForm) != 'undefined' && isLessonPlanForm) ||
			( typeof( isNickNameForm) != 'undefined' && isNickNameForm)
		) {
		bShortCircuit = false;
		optwind = window.open(blank_page_url, title, options);
	} else {
		bShortCircuit = true;
		optwind = window.open(url, title, options);
	};
	
	if (!bShortCircuit) {
		optwind.moveTo( window.screen.availHeight, window.screen.availWidth );
		window.focus();
	};
	
	if( !bShortCircuit && gradeAllModifiedCheck() ) {
		optwind.close();
		return;
	};
	try
	{	
		if( !bShortCircuit ) optwind.location = url;
		optwind.focus();
		optwind.moveTo( 50, 50 );			
		
		if (js_trim(opener) != '')
		{			
			if (!IsValidOpener(window.location, opener))
			{
				window.location = ResetOpenerUrl(opener, class_id);
			}			
		}
	} catch(ex) {}
}


function IsValidOpener(location, opener)
{
	var assmt = '/assignment/main.asp';
	var asset = '/asset/main.aspx';
	var comment = '/comment/main.aspx?nopopup=1';
	var isValid = true;
	
	switch(opener)
	{
		case 'assmt':
			if (location.toString().indexOf(assmt) == -1)
				isValid = false;			
			break;
		case 'comment':
			if (location.toString().indexOf(comment) == -1)
				isValid = false;
			break;
		case 'checklist':
			if (location.toString().indexOf(asset) == -1)
				isValid = false;
			break;
	}	 
	
	return isValid
}

function ResetOpenerUrl(opener, class_id)
{
	var url = '';
	switch(opener)
	{
		case 'assmt':
			url = '/assignment/main.asp?class_id=' + class_id;
			break;
		case 'comment':
			url = '/comment/main.aspx?nopopup=1&class_id=' + class_id;
			break;
		case 'checklist':
			url = '/asset/main.aspx?class_id=' + class_id;
			break;
	}
	return url;
}

function getPage(URLValue){
	if( gradeAllModifiedCheck() )
		return;
	if( sgTemplateCheck())
		return;
		window.location = URLValue;
}

function getPage2(URLValue, wWidth, wHeight){	
	if (window.opener && !window.opener.closed) {
		window.location = URLValue;
		windowResize(wWidth, wHeight);
	}else{
		popup(URLValue,'',0,0);
	}
}
function gradeAllModifiedCheck() {
	var bTest = false;
	if
		( 
			( typeof( isGradeAll ) != 'undefined' && isGradeAll ) || 
			( typeof( isGradeAssmt ) != 'undefined' && isGradeAssmt ) || 
			( typeof( isGradeStudent) != 'undefined' && isGradeStudent ) ||
			( typeof( isAttendaceForm) != 'undefined' && isAttendaceForm ) ||
			( typeof( isSubmitGradeForm) != 'undefined' && isSubmitGradeForm) ||
			( typeof( isCheckListCategoryForm) != 'undefined' && isCheckListCategoryForm) ||
			( typeof( isLessonPlanForm) != 'undefined' && isLessonPlanForm) ||
			( typeof( isNickNameForm) != 'undefined' && isNickNameForm)
		) 
		{
		var modify;
		//treat differently for Safari 3.0
		if(window.devicePixelRatio) 
		    modify = window.document.getElementById('ismodified');
		else
		    if (window.main)
			    modify = window.main.document.getElementById('ismodified');
		    else
			    modify = window.document.getElementById('ismodified');
			
		if(modify != null && modify.value != 0 && !confirmMsgWarnChanges2()) {
			bTest = true;
		};
	};
	return bTest;
};
function sgTemplateCheck()
{
	if(typeof(isAdminEditingTemplate) != 'undefined' && isAdminEditingTemplate )
	{
		alert("The template is locked. You must click OK or CANCEL to unlock the template before you leave this page.")
		return true;
	}
	return false;
}


function open_seating_chart(class_id)
{
	url = '/seating_chart/main.asp?mode=report&class_id=' + class_id;
	options = "height=580, width=790, scrollbars=yes, resizable=yes, nostatus,top=50,left=50, menubar=yes";
	openWin(url, "popup_reports", options);
}


//maximize a popup window
function maximizeWindow(){
	windowMove(0,0);
	if (document.all) {
		windowResize(screen.availWidth,screen.availHeight, top.window);
	}
	else if (document.layers||document.getElementById) {
		if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth){
			top.window.outerHeight = screen.availHeight;
			top.window.outerWidth = screen.availWidth;
		}
	}	
}	

function button_disabled(){
	//for limitAccess, disable data modification access
	alert('Sorry, your account does not have permission to access this function.');
}

function Coords( x, y ) {
	this.x = x;
	this.y = y;
};

function getCoords( elem ) {
	var x, y;
	
	try {
		var oP = getCoords( elem.offsetParent );
		
		x = elem.offsetLeft + oP.x;
		y = elem.offsetTop + oP.y;
	} catch ( err ) {
		x = 0;
		y = 0;
	};
	
	return new Coords( x, y );
};

function getOffset( elem ) {
	var x = elem.offsetLeft;
	var y = elem.offsetTop;

	if ( elem.offsetParent != null ) {
		var oP = getOffset( elem.offsetParent );
		x += oP.x;
		y += oP.y;
	};
	
	return new Coords( x, y );
};


function windowResize(width, height, win)
{
	if (win == null) win = window;
	
	try
	{ 
		win.resizeTo(width, height + 30);
	}
	catch(err)
	{
		//catch occasional "Access denied" error in IE (bug 3319)
	}
}


function windowMove(x, y, win)
{
	if (win == null) win = window;
	
	try
	{ 
		win.moveTo(x, y);
	}
	catch(err)
	{
		//catch occasional "Access denied" error in IE (bug 3426)
	}
}

function sizeToContent(desireWidth, desireHeight, extraWidth)
{
	var el = document.getElementById("windowBottom");	
	var cWidth, cHeight, width = 0, height = 0, paddingW, paddingH, maxHeight;
	var content = document.getElementById("windowContent");
	maxHeight = 480;
	
	window.resizeTo(800, 700);	
		
	if (bIE)
	{				
		cWidth = document.body.clientWidth;
		cHeight = document.body.clientHeight;
		paddingW = 10;
		paddingH = 0;		
	}
	else
	{
		cWidth = window.innerWidth;
		cHeight = window.innerHeight;
		paddingW = 23;
		paddingH = 18;	
	}
	if (!desireWidth) desireWidth = 0;			
	if (!desireHeight) desireHeight = 0;
	if (!extraWidth) extraWidth = 0;
		
	if (desireWidth > 0)
	{
		width = desireWidth - cWidth;
	}
	else
	{
		if (content)
		{
			width = content.offsetWidth - cWidth;	
			paddingW = 10;
		}
		else
			width = cWidth;
	}
	
	if (desireHeight > 0)
	{
		height = desireHeight - cHeight;
	}
	else
	{
		height = (el.offsetTop - cHeight);		
	}
	
	if ((height + cHeight) > maxHeight) 
	{
		height = maxHeight - cHeight;
	}
	
	if (extraWidth > 0 )
	{
		paddingW = 0;
	}

	width += extraWidth + paddingW;
	height += paddingH;	
	window.resizeBy(width, height);	

	//Work around IE5 bug - see bug 1323
	window.focus();
}

function DisableAllLinks()
{
	var elements = document.getElementsByTagName("a");
	for(i = 0; i < elements.length; i++)
	{
		el = elements[i];
		
		if (el.id != 'print_view_link')
		{
			el.href = '#';
			if (el.clearAttributes) el.clearAttributes();
			el.className = 'nolink';
			el.onclick = DisableEvent;
			el.onmouseover = DisableEvent;
		}
	}
}


function DisableEvent()
{
	return false;
}


function confirm_mail( account, domain, domain_extension ) {
	var addy = account + '@' + domain + '.' + domain_extension;
	
	if( confirm( 'To send an e-mail to ' + addy + ', please click OK.' ) ) {
		window.location = 'mail' + 'to' + ':' + addy;
	};
};


function dateAdd(interval, num_of_days, base)
{
/*	interval is Y, M, D, H, N, S
	num_of_days is amount +/-; 
	base is javascript date object
*/
	switch(interval)
	{
		case "M":
			base.setMonth(base.getMonth() + num_of_days);
			break;
		case "Y":
			base.setFullYear(base.getFullYear() + num_of_days);
			break;
		case "D":
			base.setDate(base.getDate() + num_of_days);
			break;
		case "H":
			base.setHours(base.getHours() + num_of_days);
			break;
		case "N":
			base.setMinutes(base.getMinutes() + num_of_days);
			break;
		case "S":
			base.setSeconds(base.getSeconds() + num_of_days);
			break;
		default:
	}
	return base;
}


function leapYear(theYear) 
{ 
	if ( ((theYear % 4 == 0) && (theYear % 100 != 0)) || (theYear % 400 == 0) ) 
	{ 
		return true; 
	}
	 else 
	{ 
		return false; 
	} 
} 


function getYear(year)
{
	year = year % 100;
	year = ((year < 50) ? (2000 + year) : (1900 + year));
	return year;
}


function isSameDate(date1, date2)
{
	if ((date1.getFullYear() == date2.getFullYear()) && (date1.getMonth() == date2.getMonth()) 
			&& (date1.getDate() == date2.getDate()))
		return true;
	else
		return false;
}


function ReplaceAll(str, look_up_str, replace_str)
{
	while (str.indexOf(look_up_str) != -1)
	{		
		str = str.replace(look_up_str, replace_str);
	}
	
	return str;
}


function ArrayLocate(arr, what)
{
    var f, element;    
    for(f = 0; f < arr.length; f++)
    {		
		element = arr[f];			
		if (element)
		{			
			if (isNaN(element))
			{
				if(element.toString() == what.toString())
					return f;
			}
			else
			{
				if(parseFloat(element) == parseFloat(what))
					return f;
			}
		}				
    }
    return -1;
}


function ArrayDelete(arr, a)
{	
	var new_arr = new Array(), i;
	var index = ArrayLocate(arr, a);		
	if (index > -1)
	{
		for(i = arr.length - 1; i >= 0; i--)
		{
			if (i != index)
				new_arr[new_arr.length] = arr[i];
		}
	}
	else
		new_arr = arr;		
				
	return new_arr;
}

	
function checkPhone(strPhone)
{
	// non-digit characters which are allowed in phone numbers
	var phoneNumberDelimiters = "()- ";
	// characters which are allowed in international phone numbers
	// (a leading + is OK)
	var validWorldPhoneChars = phoneNumberDelimiters + "+";
	// Minimum no of digits in an international phone no.
	var minDigitsInIPhoneNumber = 10;
	var s = stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}


function checkZipCode(strZip)
{
	var zipCodeDelimiters = "-";
	var s = stripCharsInBag(strZip, zipCodeDelimiters);
	return (isInteger(s) && (s.length == 5 || s.length == 9));
}	


function isInteger(s)
{   
	var i;
	for (i = 0; i < s.length; i++)
	{   
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	return true;
}


function stripCharsInBag(s, bag)
{   
	var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++)
	{   
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}


function attendance_legend(code_id) {
	if (parseInt(code_id) == 0)
		url = '/attendance/legend.asp';
	else
		url = '/attendance/sisLegend.asp';
	options = 'height=170, width=290, scrollbars=yes, resizable=yes, nostatus, top=50, left=50, menubar=no';
	newwind = openWin( url, '', options );
}


function confirmBeforePopup(msg, title, url, option)
{
	var blank_page_url = '/keep_alive.asp';
	var optwind = window.open(blank_page_url, title, option);
	
	optwind.moveTo( window.screen.availHeight, window.screen.availWidth );
	window.focus();
	
	if (confirm(msg))
	{
		try
		{	
			optwind.location = url;
			optwind.focus();
			optwind.moveTo( 50, 50 );		
		}
		catch(ex){}
	}
	else
	{
		optwind.close();
		return;
	}
}


function IsEmail(email)
{  
	var pattern = '^[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$';
	var regexp = new RegExp(pattern);
	 
	return regexp.test(email);	
}



function isDate(dValue)
{
	var arrEl, days, month, day, year, today, valid = true, numOfYear = 5;

	today = new Date();
	
	if (String(Date.parse(dValue)) == "NaN")
	{		
		valid = false;
		return valid;
	}
	else
	{
		if (dValue.indexOf("/") == -1)
		{
			valid = false;
			return valid;
		}
		else
		{
			arrEl = dValue.split("/");
			if (arrEl.length != 3)
			{
				valid = false;
				return valid;
			}
			else
			{				
				if (String(parseInt(arrEl[2])) == "NaN" || String(parseInt(arrEl[1])) == "NaN" || String(parseInt(arrEl[0])) == "NaN")
				{
					valid = false;
					return valid;
				}
				
				month = parseInt(arrEl[0], 10);
				day = parseInt(arrEl[1], 10);
				year = parseInt(arrEl[2], 10);
												
				if ((String(year)).length != 4)
				{
					valid = false;
					return valid;
				}
				else
				{
					if (numOfYear > 0)
					{
						if (year > (today.getFullYear() + numOfYear) || year < (today.getFullYear() - numOfYear))
						{
							valid = false;
							return valid;
						}	
					}	
				}				
								
				if (month > 12 || month < 1)
				{
					valid = false;
					return valid;
				}
				else
				{
					days = getDaysInMonth(month, year);										
					if (day > days || day < 1)
					{
						valid = false;
						return valid;
					}
				}
			}
		}
	}
	return valid;
}

//parameter month: 1-12 (Jan - Dec)
function getDaysInMonth(month, year)
{
	var days
	var monthdays = new Array(12);
	monthdays[0]=31;
	monthdays[1]=28;
	monthdays[2]=31;
	monthdays[3]=30;
	monthdays[4]=31;
	monthdays[5]=30;
	monthdays[6]=31;
	monthdays[7]=31;
	monthdays[8]=30;
	monthdays[9]=31;
	monthdays[10]=30;
	monthdays[11]=31;
	
	days = monthdays[month - 1];
	if (leapYear(year) && month == 2)
		days = 29;
	
	return days;
}

//for reports and tools list view
function swapIcon(menu_name, id)
{
	var class_name;
	// = (menu_name == 'tools') ? 'tableTools' : 'tableReports';
	switch(menu_name)
	{
		case 'tools':
			class_name = 'tableTools';
		break
		case 'attendance':
			class_name = 'tableAttendance';
		break
		case 'grades':
			class_name = 'tableGrades';
		break
		case 'users':
			class_name = 'tableUsers';
		break
		case 'templates':
			class_name = 'tableTemplates';
		break
		case 'teacher_desktop':
			class_name = 'tableTeacherDesktop';
		break
		case 'grades':
			class_name = 'tableGrades';
		break
		case 'users':
			class_name = 'tableUsers';
		break
		case 'templates':
			class_name = 'tableTemplates';
		break
		case 'teacher_desktop':
			class_name = 'tableTeacherDesktop';
		break
		case 'student_desktop':
			class_name = 'tableStudentDesktop';
		break
		case 'copy_list':
			class_name = 'tableCopylist'
		break
		case 'copy_list':
			class_name = 'tableCopylist'
		break
		default:
			class_name = 'tableReports';
	}
	var elem = document.getElementById(id);
	if (elem.className == "" && elem.parentElement.className != "") elem = elem.parentElement;
	
	if (String(elem.className).indexOf('On') == -1)
		elem.className = class_name + 'On';
	else
		elem.className = class_name;  
}


function openCalendar(class_id, attendance_date, mode, cycle_id)
{
	var options = "height=150, width=500, scrollbars=no, resizable=no, nostatus, top=100,left=100, menubar=no";
	var url = '/attendance/calendar.asp?class_id=' + class_id + '&selected_date=' + attendance_date + '&mode=' + mode;
	if (parseInt(cycle_id) > 0)
		url += '&cycle_id=' + cycle_id;
		
	openWin(url, 'eSembler_Calendar', options);	
}

//functions for /include/buttons.asp
function buttonHover(elem)
{
    var off_class = 'FormButton', on_class = 'FormButtonHover';
	if(elem.className)
	{
		if (elem.className == off_class)
			elem.className = on_class;
		else
			elem.className = off_class;
    }     
}

function swapButtonText(id) {
    var button = document.getElementById(id);
	if (button)
	{
		if (button.value == 'Wait...')
			button.value = button.name;
		else
			button.value = 'Wait...';
	}
}

function resetButtons(swapTextId)
{
	var buttons = document.getElementsByTagName('input');	
	for(var i = buttons.length - 1; i >= 0; i--)
	{
		if (buttons[i].type.toLowerCase() == 'button')
		{
			buttons[i].disabled = false;
			buttons[i].className = "FormButton";
		}		
	}
	swapButtonText(swapTextId);
}

function buttonSubmit(swapTextId) {
    if (formSubmitStatus != -1)
	{
	    setTimeout('disableButtons();', 5);
		swapButtonText(swapTextId);		
		toSubmitForm();
	}
	
	//return false so that the default submission triggered by ENTER key or SUBMIT button is canceled
	return false;
}

function disableButtons() {
    var buttons = document.getElementsByTagName('input');
    var className = "";
    for (var i = buttons.length - 1; i >= 0; i--) {
        if (buttons[i].type.toLowerCase() == 'button') {
            buttons[i].disabled = true;
            buttons[i].className = getNewButtonClass(buttons[i].value.toLowerCase(), 1) + " FormButtonDisabled";
        }
    }
}

function getNewButtonClass(buttonName, disabled) {
    var disabledText = "";
    if (disabled == 1 || disabled)
        disabledText = "Disabled";
    if (buttonName == 'save')
        return "FormButtonSave" + disabledText;
    else if (buttonName == 'cancel')
        return "FormButtonCancel" + disabledText;
    else if (buttonName == 'save & new')
        return "FormButtonApply" + disabledText;
    else if (buttonName == 'save & grade')
        return "FormButtonGrade" + disabledText;
    else if (buttonName == 'standards')
        return "FormButtonStandards" + disabledText;
    else if (buttonName == 'spelling')
        return "FormButtonSpelling" + disabledText;
    else if (buttonName == 'send')
        return "FormButtonSend" + disabledText;
    else if (buttonName == 'retrieve')
        return "FormButtonRetrieve" + disabledText;
    else if (buttonName == 'copy')
        return "FormButtonCopy" + disabledText;
    else if (buttonName == 'login')
        return "FormButtonLogin" + disabledText;
    else if (buttonName == 'next')
        return "FormButtonNext" + disabledText;
    else if (buttonName == waitText.toLowerCase() + "...")
        return "FormButtonWait";
    else
        return "";
}

function toSubmitForm()
{
	if (formSubmitStatus == 1)
	{
		if (js_trim(submitFormName) != "")
		{
			if (document.forms.item(submitFormName))
				document.forms.item(submitFormName).submit();
		}
		else			
			if (document.theform)
				document.theform.submit();
	}
}

function tableruler()
{
	if (document.getElementById && document.createTextNode)
	{
		var tables, tableClasses, i;
		tables = document.getElementById("ruler");
		if (!tables)
		{
			tables = document.getElementsByTagName('table');
			for (i = tables.length - 1; i >= 0; i--)
			{
				tableClasses = tables[i].className;
				if (tableClasses.indexOf('ruler') != -1)
				{
					changeRowColor(tables[i].rows);
				}
			}
		}
		else
		{
			var trs = tables.getElementsByTagName('tr');
			changeRowColor(trs);
		}
	}
}

function changeRowColor(trs)
{	
	for(var j = trs.length - 1; j >= 0; j--)
	{
		if (trs[j].parentNode.nodeName.toLowerCase() == 'tbody'&& trs[j].className.indexOf('noHighlights') == -1)
		{						
			trs[j].onmouseover = function()
								{
									orgStyleClassName = this.className; 
									this.className = 'ruled'; 
									return false;
								}
			trs[j].onmouseout = function()
								{
									this.className = orgStyleClassName; 
									return false;
								}
		}
	}
}

function averageColors() {
	var args = arguments;
	var length = 0;
	
	var newColor = new Array( 0, 0, 0 );
	var color;
	for(var i=args.length;i-->0;) {
		color = String(args[i]).toUpperCase();
		if (color.length == 7) color = color.substring(1,7);
		if (color.length == 6) {
			newColor[0] += parseInt(color.substring(0,2),16);
			newColor[1] += parseInt(color.substring(2,4),16);
			newColor[2] += parseInt(color.substring(4,6),16);
			length++;
		};
	};
	for(var i=newColor.length;i-->0;) {
		newColor[i] = Math.round(newColor[i] / length);
	};	
	return hexHash[newColor[0]] + hexHash[newColor[1]] + hexHash[newColor[2]];
};

function addEvent(obj, evType, fn) {
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, false);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent('on' + evType, fn);
		return r;
	} else {
		return false;
	};
};

function GetServerUrl()
{
    var baseURL = window.location.protocol + '//' +window.location.hostname;
    var port = window.location.port;
    if (port!= 80 && port != 443 && port.length != 0) baseURL = baseURL + ':' + port;
    return baseURL;
};
// Setup XML HTTP Request object
var xmlhttp=false;

try {
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
	try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (E) {
		xmlhttp = false;
	}
}

if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		xmlhttp=false;
	}
}

if (!xmlhttp && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
	} catch (e) {
		xmlhttp=false;
	}
}

function AlertTime()
{
	var G_START_DATE2 = Date.parse(new Date);
	alert("AlertTime: " + ((G_START_DATE2 - G_START_DATE) / 1000) + " seconds");
}