/***********************/
// variable declarations
var reWhitespace = /^\s+$/
var reAlphabetic = /^[a-zA-Z]+$/
var reAlphanumeric = /^[a-zA-Z0-9]+$/
var reNumberLetter = /^\d+$/
var reLetterOrDigit = /^([a-zA-Z]|\d)$/
var reSignedInteger = /^(\+|\-)?\d+$/
var reFloat = /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/
var reInteger = /^\d+$/
/***********************
String
***********************/
function isEmpty(s){
	return ((s == null) || (s.length == 0))
}
function isAlphabetic(s){
	if (isEmpty(s) == false)
		return reAlphabetic.test(s);
}
function isAlphaNumeric(s){
	if (isEmpty(s) == false)
		return reAlphanumeric.test(s);
}
function isNumberLetter(s){
	if (isEmpty(s) == false)
  		return reNumberLetter.test(s);
}
function isValidChar(s){
	if(isEmpty(s) == false){
		var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
		var temp;

		for (var i = 0; i < s.length; i++){
			temp = "" + s.substring(i, i+1);
			if (valid.indexOf(temp) == "-1") return false;
		}
		return true;
	}
}
function checkLen(s, len, required){
	if ((required == true) && isEmpty(s) == true)
		return false;
	
	if (s.length > len)
		return false;
	
	return true;
}
function isUserName(s, len, required){
	if (checkLen(s, len, required) == false)
		return false;
	else
		if (isValidChar(s) == false || isAlphabetic(Left(s, 3)) == false)
			return false;
	
	return true;
}
function Left(s, n){
	if (n <= 0)
		return "";
	else if (n > String(s).length)
		return s;
	else
		return String(s).substring(0,n);
}
function Right(s, n){
	if (n <= 0)
		return "";
	else if (n > String(s).length)
		return s;
	else {
		var iLen = String(s).length;
		return String(s).substring(iLen, iLen - n);
	}
}
function LTrim(str){
	var whitespace = new String(" \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1) {
		var j=0, i = s.length;
		while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
			j++;
		s = s.substring(j, i);
	}

	return s;
}
function RTrim(str){
	var whitespace = new String(" \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
		var i = s.length - 1;
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
			i--;
		s = s.substring(0, i+1);
	}

	return s;
}
function Trim(s){
	return RTrim(LTrim(s));
}
function removeBlank(s){
	s.value = Trim(s.value);
}

function stripCharsInBag(s, bag){
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++){
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function stripCharsNotInBag(s, bag){
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++){   
		var c = s.charAt(i);
		if (bag.indexOf(c) != -1) 
			returnString += c;
	}
	return returnString;
}

function reformat(s){
	var arg;
	var sPos = 0;
	var resultString = "";
	for (var i = 1; i < reformat.arguments.length; i++) {
		arg = reformat.arguments[i];
		if (i % 2 == 1) resultString += arg;
		else {
			resultString += s.substring(sPos, sPos + arg);
			sPos += arg;
		}
	}
	return resultString;
}

function Replace(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function

/***********************
Numeric
***********************/
function isNumeric(s){
	if (isEmpty(s) == false)
		if (isNaN(s))
			return false;
		else
			return true;
}
function isPosFloat(s, required, equal){
	if (required == true && isEmpty(s) == true)
		return false;
	if (isEmpty(s) == false){
		var bFloat;
		bFloat = isNaN(s);
		if (bFloat == true)
			return false;
		else{			
			if (equal == 1){//lon hon 0
				if (parseFloat(s) <= 0) 
					return false;
			}
			else{ //cho phep bang 0
				if (parseFloat(s) < 0) 
					return false;
			}
		}
	}

	return true;
}
/*
function isInteger(s){
	if (Left(s, 1) == "+")
		s = Right(s, s.length - 1);
	
	if (isEmpty(s) == false)
		return reInteger.test(s);
}
*/
function isPosInteger(s, required, equal){
	if (required == true && isEmpty(s) == true)
		return false;

	if (isEmpty(s) == false){
		var bInteger;
		
		if (Left(s, 1) == "+")
			s = Right(s, s.length - 1);
		
		bInteger = reInteger.test(s);

		if (bInteger == false)
			return false;
		else 		
			if (equal == 1)//lon hon 0
				if (parseInt(s, 10) <= 0) return false;
			else //cho phep bang 0
				if (parseInt(s, 10) < 0) return false;
	}

	return true;
}

function FormatNumber(num, decimalNum, bolLeadingZero, bolParens, bolCommas){

	if (isPosFloat(num, false) == false) return num;

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))	
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart > 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}

/***********************
Date & Time
***********************/

function DateDiff( start, end, interval, rounding ) {

    var iOut = 0;
    
    // Create 2 error messages, 1 for each argument. 
    var startMsg = "Check the Start Date and End Date\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var bufferA = Date.parse( start ) ;
    var bufferB = Date.parse( end ) ;
    	
    // check that the start parameter is a valid Date. 
    if ( isNaN (bufferA) || isNaN (bufferB) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }
    
    var number = bufferB-bufferA ;
    
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'd': case 'D': 
            iOut = parseInt(number / 86400000) ;
            if(rounding) iOut += parseInt((number % 86400000)/43200001) ;
            break ;
        case 'h': case 'H':
            iOut = parseInt(number / 3600000 ) ;
            if(rounding) iOut += parseInt((number % 3600000)/1800001) ;
            break ;
        case 'm': case 'M':
            iOut = parseInt(number / 60000 ) ;
            if(rounding) iOut += parseInt((number % 60000)/30001) ;
            break ;
        case 's': case 'S':
            iOut = parseInt(number / 1000 ) ;
            if(rounding) iOut += parseInt((number % 1000)/501) ;
            break ;
        default:
        // If we get to here then the interval parameter
        // didn't meet the d,h,m,s criteria.  Handle
        // the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    
    return iOut ;
}


function isDate(s, type, separate, required){
	if (required == true && isEmpty(s) == true){
		return 0;
	}

	if (type > 2) 
		type = 1;

	if (type < 0) 
		type = 0;
	//type:  0: French format: dd/mm/yyyy
	//       1: US format: mm/dd/yyyy

	var i = 0;
	var d, m, y;

	if (type){
		m = s.substr(0,s.indexOf(separate));
		s = s.substr(s.indexOf(separate) + 1);
		d = s.substr(0,s.indexOf(separate));
		y = s.substr(s.indexOf(separate) + 1);
	}
	else{
		d = s.substr(0,s.indexOf(separate));
		s = s.substr(s.indexOf(separate) + 1);
		m = s.substr(0,s.indexOf(separate));
		y = s.substr(s.indexOf(separate) + 1);
	}

	if (isNumberLetter(y) == true && isNumberLetter(m) == true && isNumberLetter(d) == true){
		if (y.length != 4) {
			return 1;
		}

		iDay = parseFloat(d);
		iMon = parseFloat(m);
		iYear = parseFloat(y);

		if (iYear < 1900){
			return 2;
		}

		if ((iDay > 31)||(iDay < 1)){
			return 3;
		}

		if ((iMon > 12)||(iMon < 1)){
			return 4;
		}
	
		if (((iMon == 4)||(iMon == 6)||(iMon == 9)||(iMon == 11))&&(iDay > 30)){
			return 5;
		}

		if (iMon == 2){
			if (iYear%4 == 0){
				if ((iYear%100 != 0)||(iYear%400 == 0)){
					if (iDay > 29){
						return 6;
					}
				}
				else if (iDay > 28){
					return 7;
				}
			}
			else{
				if (iDay > 28){
					return 7;
				}	
			}
		}
	}
	else{
		return 8;
	}

	return -1;
}

function compareDate(date1, date2) {
	var d1 = new Date(date1);
	var d2 = new Date(date2);
	
	var timeleft;
	timeleft = d1.getTime() - d2.getTime();

	if (parseFloat(timeleft) > 0)
		return -1;
	else if (parseFloat(timeleft) < 0)
		return 1;
	else
		return 0;
}

/***********************/
//Email

function isEmail(value) {
	/*
		Email Address's Format: username@subdomain.domain
		Email Address must be include 3 part:
			part 1: username
			part 2: @
			part 3: <domainname[.domainname,...]>.<domainname>
	*/
	if (value==null || value=="")	return true;
	if (value.indexOf(" ")>=0)		return false;

	var state, code, username, domain, amountOfDot, i;
	state = 1; username=''; domain=''; amountOfDot = 0;
	for (i=0; i<value.length; i++) {
		code = value.charAt(i);
		if (state==1) {
			if (	code == "<" || code == ">" 
					|| code == "(" || code == ")"	) return false;
			else if (	code == "@"	)
				if (username == '') return false;
				else state = 3;
			username += code;
		}
		else if (state==3) {
			if (	(code >= "0" && code <= "9")
					|| (code >= "A" && code <= "Z")
					|| (code >= "a" && code <= "z")
					|| code == "_"
					|| code == "-"
				) ;
			else if (code == ".")
				if (domain == '' || domain.charAt(domain.length-1) == '.') return false;
				else amountOfDot++;
			else return false;
			domain += code;
		}
	}
	if (state != 3) return false;
	if (domain == '' || domain.charAt(domain.length-1) == '.') return false;
	if (amountOfDot <1) return false;
	return true;
}
/***********************
         Form
***********************/

function GetRadioButtonValue(param){
	if (param == null)
		return;
	if (param.length >= 2)
		for (i = 0; i < param.length; i++){
			if (param[i].checked)
				return param[i].value;
		}
	else{
		if (param.checked) 
			return param.value;
	}

	return "";
}

function GetCheckBoxsValue(param) {
	var i = 0;
	var str = "";
		
	if (param.length > 0){
		for (i = 0; i < param.length; i++){
			if (param[i].checked){
				if (str == ""){
					str = param[i].value;
				}else{
					str += "," + param[i].value;
				}
			}
		}
	}else{
		if(param.checked){
			str = param.value;
		}
	}
	
	return str;
}
function setPointer(theRow, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    var theCells = null;
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor = theMarkColor;
        }
    }
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()) {
        if (theAction == 'out') {
            newColor = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor = theMarkColor;
        }
    }
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor = (thePointerColor != '')
	                 ? thePointerColor
                     : theDefaultColor;
        }
    } // end 4
    if (newColor) {
        var c = null;
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5
    return true;
} // end of the 'setPointer()' function
function openWindow(url, name, width, height)
{
	var border = 20;
	PWindow = window.open(url, name,'width=' + (width + 2*border) + ',height=' + (height + 2*border)+ ',resizable=yes,scrollbars=yes,toolbar=no,location=no,left='+ border +',top='+border+'');  
	PWindow.focus();
}
