var myForm;

var sAreaName = "workingArea";

//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;
}

function validateQuotes(s)
{
	if (s.value.indexOf('"') != -1 || s.value.indexOf("'") != -1)
	{
		alert("Invalid entry! Double quote and single quote 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 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();
	}
}

function textLength(s, maxlimit)
{
	if (s.value.length > maxlimit)
	{
		s.value = s.value.substring(0, maxlimit);
	}
}

// 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);
}

// 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;
}

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;
}

//Validate if the given parameter is a positive integer
//Param: s		the input parameter to be evaluated
function isPositiveInteger(s)
{
	var i;

	if (strToInt(s) <= 0)
	{
		return false;
	}

	for (i = 0; i < s.length; i++)
	{
	  var c = s.charAt(i);

	  if(!isDigit(c))
	  	return false;
	}

	return true;
}

function isNetscape()
{
	if(window.navigator.appName == "Netscape")
		return true;
	else
		return false;
}

//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, "-", "_" and "." 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 != "."))
		{
			ok = false;
			break;
		}
	}

	if (!ok)
	{
		alert("Invalid entry! Only letters, digits, '-', '_' and '.' 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 == "."))
			{
				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 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 doModal(url,MyWindow,mwidth,mheight)
{
    if (window.showModelessDialog)
        {
        var newWindow = window.showModelessDialog(url,MyWindow,"help:0;resizable:1;dialogWidth:"+mwidth+"px;dialogHeight:"+mheight+"px;status:no");

        newWindow.name = "NewWindow";

        return newWindow;
        }
    else
        {
        var newWindow = window.open(url,MyWindow,"toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=1,resizable=1,width=" + mwidth +",height=" + mheight + ",left=10,top=10");

        newWindow.name = "NewWindow";

        return newWindow;
        }
}

//show/hide the search or filter area
//Param	vArea	"" if to hide all
//				"Filter" if to show filter and hide search
//				"Search" if to show search and hide filter
function showHideSearchFilter(vArea)
{
	if(vArea == "")
	{
		document.getElementById("searchFilterArea").style.display = "none";
		document.getElementById("filterArea").style.display = "none";
		document.getElementById("searchArea").style.display = "none";
	}
	else if(vArea == "Filter")
	{
		document.getElementById("searchFilterArea").style.display = "";
		document.getElementById("filterArea").style.display = "";
		document.getElementById("searchArea").style.display = "none";
	}
	else if(vArea == "Search")
	{
		document.getElementById("searchFilterArea").style.display = "";
		document.getElementById("filterArea").style.display = "none";
		document.getElementById("searchArea").style.display = "";
	}
}

//show/hide the filter area
//Param	vArea	"" if to hide filter
//				"Filter" if to show filter
function showHideFilter(vArea)
{
	if(vArea == "")
	{
		document.getElementById("filterArea").style.display = "none";
	}
	else if(vArea == "Filter")
	{
		document.getElementById("filterArea").style.display = "";
	}
}

function doPrint()
{
	alert("For a better printing result, select the Landscape Layout Orientation in the Print dialog box.");
	window.print();
}

// 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 doPrintDivOverflow()
{
	document.getElementById("workingArea").style.overflow = "visible";
	doPrint();
	document.getElementById("workingArea").style.overflow = "auto";
}

// Handles key pressed event.
// Param: 	myfield 	current field
// 			e			event
function onKeyPressed(myfield,e)
{
	var keycode;

	if (window.event)
	{
		keycode = window.event.keyCode;
		editingField = window.event.srcElement;
	}
	else if (e)
	{
		keycode = e.which;
		editingField = e.srcElement;
	}
	else
		return true;

	if (keycode == 13)
	   	return moveToNextCell(myfield);
	else
	{
		//alert(myfield.value.length);
		//setCaretPosition(myfield, myfield.value.length);	
		return true;
	}
}

// Move to focus the next column
// Param: 	myfield	current field
//			offset		the row offset
function moveToNextCell(myfield)
{
	//alert(myfield.id);
	var nRow = strToInt(myfield.id.substr(3));
	var sCol = myfield.id.substr(0, 3);
//alert(nRow + "; "+ sCol);	
	var sNextCellId = sCol + intToStr((nRow+1), 3, "0");
	var oNextCell = document.getElementById(sNextCellId);

	if (oNextCell != null)
	{
		oNextCell.focus();
	}
	else
	{
		myfield.blur();
	}

	return false;
}

function printPartOfPage(elementId, sHeader, sFooter) 
{  
	 var printContent = document.getElementById(elementId);  
	
	 var windowUrl = 'about:blank';  
	 
	 var printWindow = window.open(windowUrl, '_blank', 'resizable=1,scrollbars=1,left=10,top=10,width=800,height=600');  
	 printWindow.document.write(sHeader);
	 printWindow.document.write(printContent.innerHTML);  
	 printWindow.document.write(sFooter);
	
	 printWindow.document.close();  
	
	 printWindow.focus();  
	
	 //printWindow.print();  
	
	// printWindow.close(); 
}  

function getPrintHeader()
{	
	var sRet = '<link rel="stylesheet" href="css/print.css" type="text/css"> ';	
	sRet += '<div class="noprint"><table class=fullcontainer><tr class=toolbar>';
	sRet += '<td colspan=5 width=35%>';
	sRet += '<input type=button class=toolbarButton onClick="window.close();" value="Close">';
	sRet += '&nbsp;&nbsp;&nbsp;<input type=button class=toolbarButton onClick="window.print();" value="Print">';
	sRet += '</td></tr></table></div>';
	
	return sRet;
}	

function setCaretPosition(elem, caretPos) {  
    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}