// Global variables.
var nSelectedRow	= 0;
var nRowOffset		= 0;

// Adjustment of width of tools
var nToolWidthAdjust = 0;

// Offset of height of tools
var nToolHeightOffset = 250;

// Offset of height of tools
var sAreaName = "workingArea";

// popup window
var newWindow = null;
var bOpening = false;

var helpWindow = null;

var agt = navigator.userAgent.toLowerCase();
var bOpera = (agt.indexOf("opera") != -1);
var bIE = !bOpera && (agt.indexOf("msie") > -1);

// Convert int to a fix length string
// Parameters:	vInt		-- The int value
//				vLen		-- The length of result string
//				vFillChar	-- The char that will be filled into string
function intToStr(vInt, vLen, vFillChar)
{
	var vRetVal = "" + vInt;

	if (vLen > 0)
	{
		while (vRetVal.length < vLen)
		{
			vRetVal = vFillChar + vRetVal;
		}
	}

	return vRetVal;
}

// Convert string to an int
function strToInt(vStr)
{
	if (vStr == "")
		return 0;
	else
		return parseInt(vStr, 10);
}

// Convert string to a float
function strToFloat(vStr)
{
	if (vStr == "")
		return 0;
	else
		return parseFloat(vStr);
}

function isValidNumber(s)
{
	var i;
	var hasDecimalPoint = false;

	if (isEmpty(s))
	{
		return false;
	}

	for (i = 0; i < s.length; i++)
	{
	  var c = s.charAt(i);

	  if(!isDigit(c) && !(c=="." && !hasDecimalPoint) && !(i==0 && c=="-"))
	  	return false;

	  if (c==".")
	  	hasDecimalPoint = true;
	}

	return true;
}

function isValidInteger(s)
{
	var i;

	//Empty space is fine for field input
	if (isEmpty(s))
	{
		return true;
	}

	for (i = 0; i < s.length; i++)
	{
	  var c = s.charAt(i);

	  if(!isDigit(c))
	  	return false;
	}

	return true;
}

function getTableBody(vArea)
{
    var updDiv = document.getElementById(vArea);
    //				Table		 TableBody
    return updDiv.childNodes[0].childNodes[0];
}

function deselectRow(vArea, vRow)
{
	if (prvSelectRow(vArea, vRow+nRowOffset, ""))
		nSelectedRow = 0;
}

function selectRow(vArea, vRow)
{
	if (prvSelectRow(vArea, vRow+nRowOffset, COLOR_SELECTED))
	{
		nSelectedRow = vRow;
	}
}

function prvSelectRow(vArea, vRow, vValue)
{
	var myTableBody = getTableBody(vArea);
	if ((vRow == 0) || (vRow >= myTableBody.childNodes.length))
		return false;

	var myRow = myTableBody.childNodes[vRow];
	for (j=0; j<myRow.childNodes.length; j++)
	{
		myRow.childNodes[j].bgColor = vValue;
	}

	return true;
}

function changeSelectRow(vArea, vNewRow, vOldRow)
{
	deselectRow(vArea, vOldRow);

	selectRow(vArea, vNewRow);
}

function onSelectRow(row)
{
	var myTable = document.getElementById("workingTable");
    var aRow = myTable.rows;

    if (nSelectedRow != 0)
    	aRow[nSelectedRow].bgColor = "";

    aRow[row].bgColor = COLOR_SELECTED;
    nSelectedRow = row;
}

function doModal(url,MyWindow,mwidth,mheight, mLeft, mTop)
{
	if(!bOpening && ((newWindow == null) || newWindow.closed))
	{
		bOpening = true;
		if (window.showModelessDialog)
		{
			newWindow = window.showModelessDialog(url,MyWindow,"help:0;resizable:0;status:0;scroll:1;dialogWidth:"+mwidth+"px;dialogHeight:"+mheight+"px;dialogLeft:"+mLeft+"px;dialogTop:"+mTop+"px");
		}
		else
		{
			if(mLeft == null)
				mLeft = 120;

			if(mTop == null)
				mTop = 80;

			newWindow = window.open(url,"","width="+mwidth+"px,height="+mheight+"px,resizable=0,scrollbars=1,statusbar=0,menubar=0,left="+mLeft+"px,top="+mTop+"px");
		}

		newWindow.name = "NewWindow";
		window.setTimeout("bOpening = false;", 1000, "JAVASCRIPT");
		return newWindow;
	}
}

function showHelp(vID)
{
	doModal("NLHelp.jsp?id=" + vID,"PartNineHelp", 400, 200, 350, 260)
}

//This function is used to trim String
function trimString (str) {
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

//Check if the string is empty
function isEmpty(value)
{
	var bEmpty = false;

	if (trimString(value) == "")
		bEmpty = true;

	return bEmpty;
}

//Validate if ID is valid or not. Valid Id has A-Z, a-z, and 0-9 only.
function validateIdFormat(s)
{
	var i;
	for (i = 0; i < s.length; i++)
	{
	  var c = s.charAt(i);

	  //if(!isDigit(c)) return false;
	  if(!isLetter(c) && !isDigit(c))
	  	return false;
	}
	return true;
}

//Validate if User Id is valid or not. Valid Id has A-Z, a-z, 0-9 only.
function validateUserIdFormat(s)
{
	var ok = true;
	var c;
	for (var i=0; i<s.value.length; i++)
	{
		c = "" + s.value.substring(i, i+1);
		if(!isLetter(c) && !isDigit(c))
		{
			ok = false;
			break;
		}
	}

	if (!ok)
	{
		alert(VALIDATE_USERID_FAILURE);

		var temp = "";
		for (var i=0; i<s.value.length; i++)
		{
			c = "" + s.value.substring(i, i+1);
			if(isLetter(c) || isDigit(c))
			{
				temp = temp + c;
			}
		}
		s.value = temp;

		s.focus();
	}
}

function validateMiddleNameFormat(s)
{
	var ok = true;
	var c;
	for (var i=0; i<s.value.length; i++)
	{
		c = "" + s.value.substring(i, i+1);
		if(!isLetter(c) && !isDigit(c) && (c != "-") && (c != "_") && (c != "."))
		{
			ok = false;
			break;
		}
	}

	if (!ok)
	{
		alert(VALIDATE_MIDDLENAME_FAILURE);

		var temp = "";
		for (var i=0; i<s.value.length; i++)
		{
			c = "" + s.value.substring(i, i+1);
			if(isLetter(c) || isDigit(c) || (c == "-") || (c == "_") || (c == "."))
			{
				temp = temp + c;
			}
		}
		s.value = temp;

		s.focus();
	}
}

//Validate if input is valid or not. Valid input has 0-9 only.
function validateDigitFormat(s)
{
	if(isEmpty(s))
	{
		return false;
	}

	var i;
	for (i = 0; i < s.length; i++)
	{
	  var c = s.charAt(i);

	  //if(!isDigit(c)) return false;
	  if(!isDigit(c))
	  	return false;
	}
	return true;
}


// Returns true if character c is an English letter (A .. Z, a..z).
function isLetter (c){
	return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) );
}

// Returns true if character c is a digit between 0 to 9.
function isDigit (c){
	return ((c >= "0") && (c <= "9"));
}

function textLength(s, maxlimit)
{
	  var result = true;
	  if (s.value.length > maxlimit)
	  {
	  	//alert("The maximum length is " + maxlimit);
	  	s.value = s.value.substring(0, maxlimit);
	    result = false;
	  }

	  if (window.event)
	   window.event.returnValue = result;

	  return result;
}

function isValidEmail(str)
{
	// are regular expressions supported?
	var supported = 0;
	if (window.RegExp)
	{
		var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr))
			supported = 1;
	}
	if (!supported)
		return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);

	var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
	var r3 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,20}|[0-9]{1,3})(\\]?)$"); // for aaa@bbb.museum formats

	//return (!r1.test(str) && r2.test(str));
	return (!r1.test(str) && r3.test(str));
}

function replaceString(str, oldStr, newStr)
{
	var sRetVal = "";
	var index = str.indexOf(oldStr);

	while(index != -1)
	{
		sRetVal = sRetVal + str.substring(0, index) + newStr;
		str = str.substring(index + oldStr.length);
		index = str.indexOf(oldStr);
	}

	sRetVal = sRetVal + str;

	return sRetVal;
}

function isValidMultiEmails(str)
{
    var aEmail = new Array();
    var bValidEmail = true;
    var sEmail = replaceString((str), ";", ",");
    aEmail = sEmail.split(",");
    for (var i=0;i<aEmail.length;i++)
    {
        if (!isEmpty(aEmail[i]))
        {
            if (!isValidEmail(aEmail[i]))
            {
                bValidEmail = false;
                break;
            }
        }
    }
    return bValidEmail;
}

function getCookieVal (offset)
{
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
		endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name)
{
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal (j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0)
			break;
	}
	return null;
}

function SetCookie (name, value)
{
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (2 < argc) ? argv[2] : null;
	var path = (3 < argc) ? argv[3] : null;
	var domain = (4 < argc) ? argv[4] : null;
	var secure = (5 < argc) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) +
					 ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
					 ((path == null) ? "" : ("; path=" + path)) +
					 ((domain == null) ? "" : ("; domain=" + domain)) +
					 ((secure == true) ? "; secure" : "");
}

// Use this function instead of "location.reload()"
// The reload() function causes problems when using Java 1.4.1
function reloadPage()
{
	window.top.Working.location.href=window.top.Working.location;
}

// Validate integer number
function validateInteger()
{
	var current = event.srcElement;
	var sStr = current.value;
	var ok = isValidInteger(sStr);

	if (!ok)
	{
		alert(VALIDATE_INTEGER_FAILURE);
		var sNewStr = "";
		for (var i = 0; i < sStr.length; i++)
		{
		  var c = sStr.charAt(i);

		  if(isDigit(c))
		  	sNewStr += c;
		}
		current.value = sNewStr;
		current.focus();
  	}
}

function validateDate(vTime)
{
	var dtTime = new Date(vTime);
	if((((vTime.indexOf(',') == -1) && (vTime.length != 12 || vTime.length != 11)) ||(dtTime == "NaN")) && (!isEmpty(vTime)))
	{
		return false;
	}

	return true;
}

function checkSelection()
{
	var bSelected = false;
	var aAll = document.all;
	var nLength = aAll.length;
	for (var i=0; i<nLength; i++)
	{
		if ((aAll[i].tagName == "INPUT") && (aAll[i].type == "checkbox") && (aAll[i].checked))
		{
		   	bSelected = true;
		   	break;
		}
	}
	return bSelected;
}

// Create a new text area cell.
// Param:	vName			The row/col string name
//			vHeight				The height of the textarea
//			vWidth				The width of the textarea
//			vTitle				Is it title cell?
function newTextArea(vName, vHeight, vWidth, vClassName)
{
	// Create a new cell
	var myCell = document.createElement("TD");

	// Create a new input field
	var myText = document.createElement("TEXTAREA");

	// Set input field attributes.
	myText.setAttribute("className", vClassName);

	myText.setAttribute("name", vName);
	myText.style.width =  vWidth;

	if (vHeight > 0)
		myText.style.height = vHeight;

	// appends the Text Node we created into the cell TD
	myCell.appendChild(myText);

	return myCell;
}

// This method creates a new checkbox cell
// Param: vName		The row/col string name
//		  vChecked			Is the checkboxed default as checked? (true or false)
function newCheckBox(vName, vChecked)
{
	// Create a new cell
	var myCell = document.createElement("TD");

	// Create a new input field
	var myCheckBox = document.createElement("INPUT");
	myCheckBox.setAttribute("name", vName);
	myCheckBox.setAttribute("type", "CHECKBOX");
	myCheckBox.setAttribute("checked", vChecked);

	// appends the Text Node we created into the cell TD
	myCell.appendChild(myCheckBox);

	return myCell;
}

// Get table body
// Param: vArea 		the area of table body
function getTableBody(vArea)
{
    var updDiv = document.getElementById(vArea);
    //				Table		 TableBody
    return updDiv.childNodes[0].childNodes[0];
}

// Validate integer number in a range
function validateIntegerRange(vFrom, vTo)
{
	var current = event.srcElement;
	var sValue = current.value;

	if(!isEmpty(sValue))
	{
		var ok = isValidInteger(sValue);

		if (ok)
		{
			var nValue = strToInt(sValue);
			ok = ((nValue >= vFrom) && (nValue <= vTo))
		}

		if (!ok)
		{
			alert("Invalid entry! Please enter a number between " + vFrom + " and " + vTo + ".");
			current.focus();
			current.select();
	  	}
	}
}

function showHelpForSelectRow()
{
	document.write("<tr><td><i>Single-click a row to select it.</i></td></tr>");
}

// Show school name in auto report
function showSchoolName()
{
	var sSchoolName = window.parent.ReportIndex.sSchoolName;
	document.write("<i>"+sSchoolName+"</i>");
}

// Adjust area's width and height
function onAdjustArea()
{
	var nWinHeight = document.body.clientHeight;
	var nTempHeight = nWinHeight-nToolHeightOffset;
	if (nTempHeight < 0)
		nTempHeight = 0;

	document.getElementById(sAreaName).style.height = nTempHeight;

	// If setting nToolWidthAdjust to 0, don't adjust the width
	if (nToolWidthAdjust > 0)
	{
		var nWinWidth  = document.body.clientWidth;
		var nTempWidth = nWinWidth*nToolWidthAdjust;
		document.getElementById(sAreaName).style.width = nTempWidth;
	}
}

function doPrint()
{
	window.top.Working.focus();
	window.top.Working.print();
}

function onFocusFirstInput()
{
	var oInput = document.getElementById("firstInput");

	if(oInput != null)
		oInput.focus();
}

function showCSS()
{
	if(bIE)
		document.write('<link rel="stylesheet" href="css/main.css" type="text/css">');
	else
		document.write('<link rel="stylesheet" href="css/main.css" type="text/css">');
}

function showCSSForReport()
{
	if(bIE)
		document.write('<link rel="stylesheet" href="../css/main.css" type="text/css">');
	else
		document.write('<link rel="stylesheet" href="../css/main.css" type="text/css">');
}
/*
// aItem is an array obtained from function getElementsByName
function hasDuplicateValues(aItem)
{
	var bRet = false;
	var nItemNum = aItem.length;
	var aItemValue = new Array();
	var nCount = 0;
	for (var i=0; i<nItemNum; i++)
	{
		if(!isEmpty(aItem[i].value))
		{
	  		aItemValue[nCount] = trimString(aItem[i].value);
	  		nCount++;
	  	}
	}

	aItemValue.sort();
	var nItemValueNum = aItemValue.length;
	for (var i=0; i<nItemValueNum - 1; i++)
	{
	  if (aItemValue[i] == aItemValue[i+1])
	  {
	    bRet = true;
	    break;
	  }
	}

	return bRet;
}

function onSelectAll(vInputName, vSelect)
{
	var aAll = document.all;
	var nLength = aAll.length;
	for (var i=0; i<nLength; i++)
	{
		if ((aAll[i].tagName == "INPUT") && (aAll[i].type == vInputName))
		{
		   	aAll[i].checked = vSelect;
		}
	}
}	*/

function expandTreeInLeftFrame(sPage)
{
//	var foldercontent = window.top.Working.AppIndex.document.getElementById(sPage);
	window.top.Working.AppIndex.location.href = "AppLeft.jsp";
//	if (foldercontent != null && typeof(foldercontent) != 'undefined')
//	{
//		foldercontent.childNodes[0].childNodes[0].src="image/Minus.gif";

//		foldercontent.nextSibling.style.display = "";
//	}
}

function onEndEditingTextAreaLength(vLength)
{
	var current = event.srcElement;
	var s	= current.value;
	if(vLength != 0)
	{
		if (s.length > vLength)
		{
			alert("The maximum length of the field is " + vLength + " characters. The data will be truncated.");
			s = s.substr(0, vLength);
			current.value=s;
			return;
		}
	}
}

// Return text with the specified length
// Param: 	s			the text
//			maxlimit	the max limit
function truncate(s, maxlimit)
{
	if (s.value.length > maxlimit)
	{
		s.value = s.value.substring(0, maxlimit);
	}
}

// empyt for toolbar
function onPostInitialization()
{

}

function CountWords (this_field)
{
	var sStr = this_field.value;
	var sStr = trimString(sStr);

	var sCleanedStr = trimString(sStr.replace(/[^A-Za-z0-9''''""""\-*]+/gi, " "));
	var sSplitStr = sCleanedStr.split(" ");
	var nCount = sSplitStr.length;
	var sWordOrWords = "";

	return nCount;
}

function strToArray(vStr, vDelimiter)
{
	var aRet = new Array();
	var nPos = vStr.indexOf(vDelimiter);

	while (nPos != -1)
	{
		if (nPos != 0)
			aRet[aRet.length] = vStr.substring(0, nPos);
		else
			aRet[aRet.length] = "";

		if (vStr.length > nPos+1)
		{
			vStr = vStr.substring(nPos+1);
			nPos = vStr.indexOf(vDelimiter);
		}
		else
		{
			vStr = "";
			nPos = -1;
		}

	}

	if (vStr.length > 0)
		aRet[aRet.length] = vStr;

	return aRet;
}

// Validate the double quotes
// Param: s		the input parameter to be validated
function validateDoubleQuote(s)
{
	if (s.value.indexOf('"') != -1)
	{
		alert("Invalid entry! Double quotes are not allowed.");
		s.disabled = false;

		while (s.value.indexOf('"') != -1)
		{
			s.value = s.value.replace('"', "");
		}

		s.focus();
	}
}

// Validate Quote given the string
// Param: s		the input parameter to be validated
function validateQuotes(s)
{
	if (s.value.indexOf('"') != -1 || s.value.indexOf("'") != -1)
	{
		alert("Invalid entry! Double quote and single quote characters are not allowed.");
		s.disabled = false;

		while (s.value.indexOf("'") != -1)
		{
			s.value = s.value.replace("'", "");
		}

		while (s.value.indexOf('"') != -1)
		{
			s.value = s.value.replace('"', "");
		}

		s.focus();
	}
}

function validateEmailFormat(s)
{
	var ok = true;
	var c;
	for (var i=0; i<s.value.length; i++)
	{
		c = "" + s.value.substring(i, i+1);
		if((c == "\"") || (c == "#") || (c == "%") || (c == "&") || (c == "\\") || (c == "\/"))
		{
			ok = false;
			break;
		}
	}

	if (!ok)
	{
		c = replaceString(c, '"', '\"');
		alert("Invalid entry! The special characters (" + c + ") are not allowed.");

		var temp = "";
		for (var i=0; i<s.value.length; i++)
		{
			c = "" + s.value.substring(i, i+1);
			if((c == "\"") || (c == "#") || (c == "%") || (c == "&") || (c == "\\") || (c == "\/"))
			{
				;
			}
			else
			{
				temp = temp + c;
			}
		}

		s.value = temp;

		s.focus();
	}
}

// Validate if the given parameter is positive number
// Param: c		the input parameter to be evaluated
function isPositiveNumber(c)
{
  	if (isEmpty(c))
	{
    	return true;
	}
	else
	{
		var num = parseFloat(c);

		if (num >= 0)
			return true;
		else
			return false;
	}
}

function isAreaInteger(s,minInt,maxInt)
{
	if (!isValidInteger(s))
	{
		return false;
	}

	if((strToInt(s)>maxInt) || (strToInt(s)<minInt))
	{
	    return false;
	}

	return true;
}

// add by lianying Select All/Clear All row for List page.
function onClickSelectCheckBoxAll(vForm, vId)
{
    if (vForm.sAll.checked == true) {
	    vForm.sAll.checked = false;
    }
	else {
		vForm.sAll.checked = true;
	}
	onSelectAllList(vForm, vId);
}

function onCheckSelectBoxAll(vForm, vId)
{
	if (vId.length > 1) {
		var bClear = false;
      	for (var i=0; i< vId.length; i++) {
			bClear = false;
        	if (vId[i].checked == false) {
				bClear = true;
				break;
        	}
      	}
		if (bClear) {
			vForm.sAll.checked = false;
		}
		else {
			vForm.sAll.checked = true;
		}
    }
}

function onSelectAllList(vForm, vId)
{
	if (vId.length > 1) {
		if (vForm.sAll.checked == true) {
			for (var i=0; i<vId.length; i++) {
				vId[i].checked = true;
			}
		}
		else {
			for (var i=0; i<vId.length; i++) {
				vId[i].checked = false;
			}
		}
	}
}

function showTitlebar(bShow)
{
	if (bShow)
	{
		document.getElementById("Logout").style.display = "";
	}
	else
	{
		document.getElementById("Logout").style.display = "none";
	}
}

function onLogOut(vSrc)
{
	//vSrc.blur();
	if (confirm("Do you really want to log out?")) {
		window.location.href = "Index.jsp?loginout=1";
	}
}

// Hide or Show left window menu.
function onShowLeftMenu()
{
	if (document.getElementById("switchPointMid").innerHTML.indexOf("scroll_right.gif") != -1) {
		document.getElementById("switchPointMid").innerHTML="<img style='cursor : hand;' src='image/scroll_left.gif'>";
		document.getElementById("leftMenu").style.display = "none";
	}
	else {
		document.getElementById("switchPointMid").innerHTML="<img style='cursor : hand;' src='image/scroll_right.gif'>";
		document.getElementById("leftMenu").style.display = "";
	}
}

function mousehover(pobjSrc)
{
	pobjSrc.className = "menuMouseHover";
}


function mouseout(pobjSrc)
{
	pobjSrc.className = "menuMouseOut";
}

function onChangeDate(vObjName)
{	
	var oTime = document.getElementsByName(vObjName)[0];		
	myCalendar.select(oTime, vObjName, DATE_FORMAT_STR, "");
}