

//################################## Var declare ###############################################

// whitespace characters
var whitespace = " \t\n\r";

// decimal point character differs by language and culture
var decimalPointDelimiter = ".";

// 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 + "+";

var defaultEmptyOK = false;

var daysInMonth = new Array();
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;
//##############################################################################################

//================== mparseInt(s)=========================================
// Function -- return interger value of the number
// modification of parseInt function as parseInt might not return a valid
// value if the string is prefix will 0
//-------------------------------------------------------------------------
function mparseInt(s){
	for (c=0;c<s.length ;c++ )
	{
		if (s.charAt(c)!='0')
		{
			break;
		}
	}
	if (c==s.length) return 0;
	return parseInt(s.substring(c, s.length)); 
}



//================== isEmpty(s) ===========================================
// Function -- return true if s is empty or null string
//-------------------------------------------------------------------------

function isEmpty(s)
{   
   return ((s == null) || (s.length == 0));
}

//================= isWhitespace (s) ==========================================
// Function -- Returns true if string s is empty or whitespace characters only
//-----------------------------------------------------------------------------

function isWhitespace (s)
{  
    var i;
    // Is s empty?
    if (isEmpty(s)) return true;

    // find a non-whitespace character, return false; else return true.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}


//==================  isInteger (s)===============================================
// Function -- Returns true if all characters in string s are numbers.
// Accepts non-signed integers only. Does not accept floating point, exponential notation, etc.
//-----------------------------------------------------------------------------
function isInteger (s)
{ 
    var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    // find non numberic char return false; else return true.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}

// ================= isDigit (c)==============================================
// Function -- Returns true if character c is a digit
//-----------------------------------------------------------------------------
function isDigit (c)
{   return ((c >= "0") && (c <= "9"));
}


// ================= isFloat (s )============================================
// Function -- return True if string s is an unsigned floating point (real) number. 
// Also returns true for unsigned integers. 
// Does not accept exponential notation.
//-----------------------------------------------------------------------------
function isFloat (s)
{
    var i;
    var seenDecimalPoint = false;

    if (isEmpty(s)) 
       if (isFloat.arguments.length == 1) return defaultEmptyOK;
       else return (isFloat.arguments[1] == true);

    if (s == decimalPointDelimiter) return false;

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);

        if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}

//==================  isIntegerInRange (s, a, b )=============================
// function -- returns true if string s is an integer 
// within the range of integer arguments a and b, inclusive.
//-----------------------------------------------------------------------------
function isIntegerInRange (s, a, b)
{ 
    if (isEmpty(s)) 
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // Catch non-integer strings to avoid creating a NaN below,
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = mparseInt (s);
    return ((num >= a) && (num <= b));
}

//================== checkFloat(s, a, b, sign)===============================
//function -- return true if the numeric is in the format of 
// number(argument 2, argument 3)
// sign is a boolean value to indicate whether it accept '-' value
//---------------------------------------------------------------------------

function checkFloat(s, a, b, sign)
{
        if (isEmpty(s))
           return false;
        if (s.charAt(0)== '-'){
            if (sign) s = s.substring(1);
            else return sign;
        }
        if (! isFloat(s))
		return false;
	if(s.charAt(s.length-1) == decimalPointDelimiter)
		return false;
	var c=0;
	while (c < s.length && (s.charAt(c)!= decimalPointDelimiter)) c++;
	if (c < s.length) 
	{
   		var aDecStr=s.substring(c+1, s.length);
		if (aDecStr.length > b) return false;
	}
	var bDecStr=s.substring(0, c);
	return (bDecStr.length <= a);
}

//================== checkInteger(s, a, sign)=================================
// function -- return true if the number is within the format of number(a)
// sign is a boolean value to indicate whether it accept '-' value
//---------------------------------------------------------------------
function checkInteger(s, a, sign)
{
   if (isEmpty(s))
       return false;
   if (s.charAt(0)== '-'){
	   if (sign) s = s.substring(1);
       else return sign;
    }
	if (!(isInteger (s)))
		return false;
   return (s.length <= a);
}


// ===================== isYear (s)==============================================
// function -- returns true if string s is a valid 
// Year number.  Must be 4 digits only.
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.
//-----------------------------------------------------------------------------
function isYear (s)
{
    if (isEmpty(s)) 
       if (isYear.arguments.length == 1) return defaultEmptyOK;
       else return (isYear.arguments[1] == true);
    if (!isInteger(s)) return false;
    if (s.length == 4)
    {
		yr=mparseInt(s);
        return (yr >= 1500);
    }
    else
      return false;   
}

//===================  isMonth (s)============================================
// function -- returns true if string s is a valid 
// month number between 1 and 12.
//-----------------------------------------------------------------------------
function isMonth (s)
{
    if (isEmpty(s)) 
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}


//==================  isYYYYMM(STRING s)=======================================
// function -- return true if string s is in YYYYMM format ... 
// where YYYY must be after or equal 1500
//-----------------------------------------------------------------------------

function isYYYYMM(s,em)
{
        if (isEmpty(s))
          if (em) return em;
        if (s.length !=6) return false;
	return (isYear(s.substring(0,4)) && isMonth(s.substring(4,6)));
}

//==================== isDDMMYYYY (strDate)==============================
//function -- return true if the date given is a valid date
//-----------------------------------------------------------------------------
function isDDMMYYYY (strDate)
{   
   if (isEmpty(strDate))
      return false;
   if (strDate.length != 8) return false;
   return isDate(strDate.substring(4,8), strDate.substring(2,4),strDate.substring(0,2));
}


//==================  isMMYYYY(STRING s)=======================================
// function -- return true if string strDate is in MMYYYY format ... 
// where YYYY must be after or equal 1500
//-----------------------------------------------------------------------------

function isMMYYYY(strDate)
{
   if (isEmpty(strDate)) return false;
   if (strDate.length !=6) return false;
   return (isYear(strDate.substring(2,6)) && isMonth(strDate.substring(0,2)));
}

//==================== isDate (year, month, day)==============================
//function -- return true if the date given is a valid date
//-----------------------------------------------------------------------------
function isDate (year, month, day)
{   // catch invalid years (4-digit) and invalid months and days.
    if (! (isYear(year) && isMonth(month) && isDay(day, false))) return false;
    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = mparseInt(year);
    var intMonth = mparseInt(month);
    var intDay = mparseInt(day);
    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false;

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;
    return true;
}

// ====================isDate2( date1) ======================================
// function -- retrun true if the given date is a valid date
// This function expects date in the format of dd/mm/yyyy or dd-mm-yyyy
//-----------------------------------------------------------------------------
function isDate2(strDate)
{
   if (strDate.length != 10)
      return false;
   dd1=strDate.substring(0,2);
   mm1=strDate.substring(3,5);
   yy1=strDate.substring(6,10);
   return isDate(yy1, mm1,dd1);
}



//====================== dayInFebruary(year)===========================
// function -- returns number of days in February of that year.
// Given integer argument year,
//-----------------------------------------------------------------------------
function daysInFebruary (year)
{
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return ( ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}


//====================== isDay(s)===================================
//function -- returns true if string s is a valid
//day nmber between 1 and 31
//--------------------------------------------------------------------------
function isDay(s, emptyOK)
{
     if (isEmpty(s))
     if (emptyOK) return emptyOK;
     return isIntegerInRange(s,1,31);
}

//==================  checkB4Date(date1, date2) ===================================
// Function -- return false if date1 is greater than date2
// enforce date1 later than date2 
// date1 and date2 is a String in dd/mm/yyyy format
//---------------------------------------------------------------------------------

function checkB4Date(date1, date2) { 

   var d1 = newDate(date1); 
   var d2 = newDate(date2); 
 // compare the 2 dates 
   if (date2 < date1){
      return false; 
   }
   return true; 
} 


// =====================checkStrLen (s, value)=================================
// function --return true if the string lenght is equal to or smaller than the given value
// use to check the lenght of a text area
//---------------------------------------------------------------------------------
function checkStrLen(s, value) {
  if( s.length <= value )
    return true;
  else
    return false;
}

// ====================checkCurrYr( yyyy, yr) ======================================
// function -- retrue true if the current year - the given number of yr is smaller than the given yr
//---------------------------------------------------------------------------------
function checkCurrYr(yyyy, yr){
	if (!(isYear (yyyy))) return false;
	today = new Date();
	if( mparseInt(yyyy) > (today.getFullYear() - yr) ) 
		return false ;
    return true;
}

// ==================== isTime24(hh, min) ======================================
// function -- return true if it is a valid 24 hr time
//---------------------------------------------------------------------------------
function isTime24(hh, min)
{
      if (isEmpty(hh)) 
        return false;
      if (isEmpty(min)) 
        return false;
      return (isIntegerInRange (hh, 0, 23) && isIntegerInRange (min, 0, 59));
}

// ===================isNotWhitespaceDate(dd, mm, yy)=============================
// function -- return true the date is not empty 
// --------------------------------------------------------------------------------
function isNotWhitespaceDate(dd, mm, yy)
{
   if ( (!(isWhitespace(dd))) && (!(isWhitespace(mm))) && (!(isWhitespace(yy))) )
        return true;
   return false;
}


//===================isProperAlphabetic(argString)======================================
// function -- return ture if the string contain only alphabetic
//------------------------------------------------------------------------------------
function isProperAlphabetic(argString) {
	var alphabets = "abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"

	for(var intI=0; intI<argString.length; intI++)
		if (alphabets.indexOf(argString.charAt(intI)) == -1)
			return false
	
	return true
}

	   
//===================checkb4CurrYear(strYear)======================================
// function -- return ture if the string is before current year
//---------------------------------------------------------------------------------
function checkb4CurrYear(strYear){
	currdate = new Date();
	currYear= currdate.getFullYear();
	if (currYear < parseInt(strYear))
	    return false;
	return true;
}



//===================checkYearRange(strYear)======================================
// function -- return ture if the string is a valid year, and it is greater then
//              or equal to year 2001 but smaller then or equal to current year
//-----------------------------------------------------------------------------

function checkYearRange(strYear){
	if(! isYear(strYear))
		return false;
    if(! checkb4CurrYear(strYear))
		return false;
	return  checkb42001(strYear);

}


//===================btwYearRange(strYear1, strYear2, numYear)======================================
// function -- return ture if stryear1 - stryear2 = numYear
//-----------------------------------------------------------------------------

function btwYearRange(strYear1, strYear2, numYear){
	if(! isYear(strYear1) || ! isYear(strYear2))
		return false;
	if ((parseInt(strYear1) - parseInt(strYear2)) != numYear )
		return false;		
	return true;
}

//===================isLetter (c)======================================
// function -- Returns true if character c is an English letter 
//-----------------------------------------------------------------------------
function isLetter (c){
   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}


//===================isPayRC(strPayRC)======================================
// function -- return ture it is a valid PayRC format XXXX 
//-----------------------------------------------------------------------------

function isPayRC(strPayRC){
   var i;
   if (isWhitespace(strPayRC)) 
      return false;
   if (strPayRC.length != 4 ) return false;
   for (i = 0; i < strPayRC.length; i++) {
        var c = strPayRC.charAt(i);
        if (! (isLetter(c)) )
           return false;
    }
    return true;
}


//===================isPerno(strPerno)======================================
// function -- return ture it is a valid Perno format XNNNNNNNX
//-----------------------------------------------------------------------------

function isPerno(strPerno){
   var i;
   if (isWhitespace(strPerno)) return false;
   if (strPerno.length != 9) return false;
//   if (! isLetter(strPerno.charAt(0))) return false;
//   if (! isLetter(strPerno.charAt(strPerno.length - 1))) return false;
/*
    for (i = 1; i < strPerno.length - 1; i++) {
        var c = strPerno.charAt(i);
        if (! (isDigit(c)) )
           return false;
    }
*/
    return true;
}

//===================isPayRC3Bytes(strPayRC)======================================
// do take note only FS01 n FS20 will use this method, the rest will use isPayRC
// function -- return ture it is a valid PayRC format XXXX 
//-----------------------------------------------------------------------------

function isPayRC3Bytes(strPayRC){
   var i;
   if (isWhitespace(strPayRC)) 
      return false;
   if (strPayRC.length != 3 ) return false;
   for (i = 0; i < strPayRC.length; i++) {
        var c = strPayRC.charAt(i);
        if (! (isLetter(c)) )
           return false;
    }
    return true;
}

// ====================withinMth( String val , int mth) ==========================
// function -- check whether a string value(in mm/yyyy format) 
//             is within the current month and up to 36 mth before. 
//             return false if not fall in the criteria. 
//---------------------------------------------------------------------------------
function withinMth( val , mth){
   mm = val.substring(0,2);
   yyyy = val.substring(3,7);
   if (!(isYear (yyyy))) return false;
   if (!(isMonth(mm))) return false;

   addmth = 0;
   today = new Date();
   cyyyy = today.getFullYear();
   cmm   = today.getMonth() + 1;


   if (mparseInt(yyyy) > cyyyy) return false;
   if (mparseInt(yyyy) == cyyyy)
      if (mparseInt(mm) > cmm) return false;

   if (mparseInt(yyyy) < cyyyy)
      addmth = (cyyyy - mparseInt(yyyy)) * 12;

   if (((cmm + addmth) - mparseInt(mm)) > mth) return false;
    return true;
}


//==================  isMMYYYYFormat(STRING s)=======================================
// function -- return true if string strDate is in mm/yyyy format ... 
// where YYYY must be after or equal 1500
//-----------------------------------------------------------------------------

function isMMYYYYFormat(strDate)
{
   if (isEmpty(strDate)) return false;
   if (strDate.length != 7) return false;
   if (strDate.substring(2,3) != "/") return false;
   return (isYear(strDate.substring(3,7)) && isMonth(strDate.substring(0,2)));
}

//==================  isCurrency(STRING s)=======================================
// function -- return true if string is in currency format
//-----------------------------------------------------------------------------
function isCurrency(strCurr)
{
   locdec = strCurr.indexOf(".");
   if (locdec == -1)
      return isInteger (strCurr);
   else {
      return ((isInteger(strCurr.substr(0,locdec))) && (isInteger(strCurr.substr(locdec + 1,strCurr.length))));
   }
}


//==================  checkNumofDec(STRING s, Int n)=======================================
// function -- return true if string the number of decimal in s is equal to n
//-----------------------------------------------------------------------------
function checkNumofDec(str, n)
{
   locdec = str.indexOf(".");
   if (locdec == -1)
      return isInteger (str);
   else {
      if ((isInteger(str.substr(0,locdec))) && (isInteger(str.substr(locdec + 1,str.length)))) {
         return ((str.substr(locdec + 1,str.length)).length <= n);
      } else 
         return false;
   }
   return false;
}

function popMsg(msg, type) {
	if (type == "1") 
		alert("Please select "+ msg +".");	
	else
		alert("Please provide "+ msg +".");
}

function CheckLength(length) {
	 if (document.f.descTxt.value.length >= length) {
		  alert('You have reached the maximum length of ['+ length+'] characters permitted here.');
		  document.f.descTxt.value = document.f.descTxt.value.substring(0, length-1);
		  return false;                         
	  }
}

function isEmail(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 submitForm(opt, length) {
	var form = document.f
	var selectedArea = f.areaSelect.selectedIndex
	var selectedSubject = f.s.selectedIndex
	var selectedModule = f.m.selectedIndex
	var selectedRequest = f.r.selectedIndex

   if (selectedSubject == "0") {
		popMsg("Subject","1")
	} else if (selectedRequest == "0") {
		popMsg("Request","1")
	} else if (trimString(form.descTxt.value) == "" || form.descTxt.value == null) {
		popMsg("Description")
	} else if (form.descTxt.value.length >= length) {
        alert('Description exceeded 2500 characters.\n');
        form.descTxt.value = form.descTxt.value.substring(0, length-1);
        return false;                         	 
	} else if (trimString(form.nameTxt.value) == "" || form.nameTxt.value == null) {
		popMsg("Name")
	} else if ( (isWhitespace(form.contactTxt.value)) ) {
		popMsg("Contact Number")	
	} else if (! isValidEmail(form.emailTxt.value, true)) {
		popMsg("a valid E-mail")
	} else if (trimString(form.LicNoTxt.value) == "" || form.LicNoTxt.value == null) {
		popMsg("License No./Vendor ID")
	} else if (trimString(form.ClinicNameTxt.value) == "" || form.ClinicNameTxt.value == null) {
		popMsg("Name of Clinic")
   } else {
       if (opt == "s") { //submit
         //f.SubmitRequest.disabled = true;
         //f.action = "helpdeskSubmitMBS.asp";
         f.action = "../submitRequest.aspx";
         f.method = "Post";
         f.submit();
       } else if (opt == "p") { // print
           var showPrint = null;
           showPrint = window.open('./helpdeskPrntMBS.aspx','Print','height=600,width=800,top=40,left=80,toolbar=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no');
       }
	}
}
// Check Contact Number Provided
function checkcontact(){
	var strLen=document.f.contactTxt.value.length

	if (strLen != "")
	{
		//Amended by CWX, AWG06SR0023 Start
		//if (strLen < 5)
		if (strLen < 8 || !allValidPhoneInt(document.f.contactTxt.value))
		//Amended by CWX, AWG06SR0023 End
        {
            //Amended by CWX, AWG06SR0023 Start
			//alert("Contact No. can either be Ext.(5 digits only) or DID (7 digits or more).");
			alert("Contact No. must be valid 8 digits or more.");
			//Amended by CWX, AWG06SR0023 End
            return false;
        } //commented by CWX, AWG06SR0023 Start
		/*else if (strLen > 5 && strLen < 7)
        {
            alert("Contact No. can either be Ext.(5 digits only) or DID (7 digits or more).");
			return false;
        }*/ //commented by CWX, AWG06SR0023 End
	}	
}

// Validation of Email address
function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    }
	
    return true;
}

function allValidChars(email) {
  var parsed = true;
//  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-";
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}

//Added by CWX, AWG06SR0023 Start
function allValidPhoneInt(contact) {
  var parsed = true;
  var validchars = "0123456789";
  for (var i=0; i < contact.length; i++) {
    var letter = contact.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}
//Added by CWX, AWG06SR0023 End

function trimString(str){
    //str = "";
    if(str.charAt(0)==" "){
       str = str.substring(1);
       str = trimString(str);
    }
    if(str.charAt((str.length-1)) == " "){
       str = str.substring(0,(str.length-1));
       str = trimString(str);
    }
    return str;
}