

// 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 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 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;		
	}		
}

//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, "-", "_", or 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) && c != "-" && c != "_")
	  	return false;
	}
	return true;
}

//Validate if User Id is valid or not. Valid Id has A-Z, a-z, 0-9 or @, - or _ 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) && c != "-" && c != "_" && c != "@" && c != "&" && c != ",")
		{
			ok = false;
			break;
		}
	}

	if (!ok)
	{
		alert("Invalid entry! Only letters, digits, '@', '&', ',', '-' or '_' are allowed.");

		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 == "," || 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})(\\]?)$");

	return (!r1.test(str) && r2.test(str));
}

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("Invalid entry! Please enter numbers here.");
		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.indexOf(' ') != 3) || (dtTime == "NaN"))
	{
		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.top.Working.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/Crep.css" type="text/css">');
	else
		document.write('<link rel="stylesheet" href="css/CrepNonIE.css" type="text/css">');
}

function showCSSForReport()
{
	if(bIE)
		document.write('<link rel="stylesheet" href="../css/Crep.css" type="text/css">');
	else
		document.write('<link rel="stylesheet" href="../css/CrepNonIE.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++)
	{
		var oInput = aAll[i];
		if (!oInput.disabled && (oInput.tagName == "INPUT") && (oInput.type == vInputName))
		{
		   	oInput.checked = vSelect;
		}
	}	
}	

function onSelectGroup(vFieldName, vSelect)
{	
	var aInputs = document.getElementsByName(vFieldName);
	var nLength = aInputs.length;	
	for (var i=0; i<nLength; i++)
	{
		var oInput = aInputs[i];
		if (!oInput.disabled)
		{
		   	oInput.checked = vSelect;
		}
	}	
}	

function getCheckedBoxNum()
{
	var nRet = 0;
	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))
		{
		   nRet++;
		}
	}
	return nRet;
}	

// aItem is an array obtained from function getElementsByName
function hasEnteredValue(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))
		{
	  		bRet = true;
	  		break;
	  	}	
	}	
	
	return bRet;
}	

function checkDecimals(s, nMaxDec) 
{
	var bRet = false;
	
	if (!isEmpty(s))
	{	
		if (s.indexOf('.') == -1) s += ".";
		dectext = s.substring(s.indexOf('.')+1, s.length);
		
		if (dectext.length <= nMaxDec)
		{
			bRet = true;
		}
	}
	return bRet;
}

function isValidPositiveNumber(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))
	  	return false;

	  if (c==".")
	  	hasDecimalPoint = true;
	}

	return true;
}

function insertBulletPoint(el)
{
	var ins = "\n·	";
    if (el.setSelectionRange)
    { 	    
        el.value = el.value.substring(0,el.selectionStart) + ins + el.value.substring(el.selectionStart,el.selectionEnd) + el.value.substring(el.selectionEnd,el.value.length); 
    } 
    else if (document.selection && document.selection.createRange) 
    { 	    
        el.focus(); 
        var range = document.selection.createRange(); 
        range.text = range.text + ins; 
    } 
} 

function onAltKeyPressed(myfield,e)
{

	var ctrlPressed = 0;

	altPressed =event.ctrlKey;
	
	var keycode;

	if (window.event)
	{
		keycode = window.event.keyCode;
		altPressed  =event.altKey;
	}
	else if (e)
	{
		keycode = e.which;
		var mString =(e.modifiers+32).toString(2).substring(3,6); 
		altPressed  =(mString.charAt(2)=="1"); 
	}
	else
		return true;

	if (altPressed && keycode == 66) // 'b'
	   	return insertBulletPoint(myfield);
	else
		return true;

}

function onDisplayAll(vInputName, vDisplay)
{	
	var aInputs = document.getElementsByTagName("input");
	var nLength = aInputs.length;	
	for (var i=0; i<nLength; i++)
	{		
		if(aInputs[i].type == vInputName)
		{			
	   		aInputs[i].style.display = "none";	  
	   	}	
	}		
}	

function onResetPos(vInputName)
{
	var aPos = document.getElementsByName(vInputName);
	var nPosNum = aPos.length;
	var nCount = 1;
	for(var i=0;i<nPosNum;i++)
	{
		aPos[i].value = nCount;	
		nCount++;			
	}	
}	

function getInnerTextStr(vInputName)
{
	var sRetVal;
	
	if(document.all)
	{
        sRetVal = document.getElementById(vInputName).innerText;
	} 
	else
	{
		sRetVal = document.getElementById(vInputName).textContent;	    
	}	
	
	return sRetVal;
}	

function getUrlRoot()
{
	var sRetVal = "";	
	var sTempUrl = window.location + "";	
	sRetVal = sTempUrl.substring(0, sTempUrl.indexOf("/Survey/"));

	return sRetVal;
}	

function getUrlRootForLink()
{
	var sRetVal = "&url=";	
	if(!bIE)
	{
		sRetVal += getUrlRoot();
	}

	return sRetVal;
}	

function getSchoolYearList(vStartYear, vEndYear)
{
	var aSchoolYear = new Array();
	var sYears = "";
	if(vStartYear == vEndYear)
	{
		sYears = vStartYear;
		aSchoolYear[0] = sYears;
	}	
	else
	{			
		var nStartYear = strToInt(vStartYear.substring(0,4));
		var nEndYear = strToInt(vEndYear.substring(0,4));
				
		var nTempYear = nStartYear;
		var nCount = 0;
		while (nTempYear < nEndYear)
		{			
			//if(!isEmtpy(sYears))
			//	sYears += ",";
				
			nTempYear = nStartYear + nCount;	
			sYears = nTempYear + " - " + (nTempYear + 1);	
			aSchoolYear[nCount] = sYears;
			nCount++;
		}
	}	
	
	return aSchoolYear;
}

function onChangeDate(vObjName)
{	
	var oTime = document.getElementsByName(vObjName)[0];		
	myCalendar.select(oTime, vObjName, DATE_FORMAT_STR, "");
}

function setElementText(vElemId, vText)
{
	if(document.all)
	{
		document.getElementById(vElemId).innerText = vText;			     
	} 
	else
	{
	    document.getElementById(vElemId).textContent = vText;
	}	
}	
