var dtCh= "/";
var minYear=1900;
var maxYear=2100;
function isInteger(s){
    var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

//
function showpageinwawindow(url)
{
    window.open(url,"wa");
}

//
function ValidatorTrim(s) {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return (m == null) ? "" : m[1];
}

//
function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

//
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 );
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
        if (i==2) {this[i] = 29}
   } 
   return this
}

function ddmmmyyyyToJsdate(datestr)
{
	var retarray = datestr.split("-");
	var arrMonth = new Object();
	arrMonth["Jan"] = {value:"01",text:"January"};
	arrMonth["Feb"] = {value:"02",text:"February"};
	arrMonth["Mar"] = {value:"03",text:"March"};
	arrMonth["Apr"] = {value:"04",text:"April"};
	arrMonth["May"] = {value:"05",text:"May"};
	arrMonth["Jun"] = {value:"06",text:"June"};
	arrMonth["Jul"] = {value:"07",text:"July"};
	arrMonth["Aug"] = {value:"08",text:"August"};
	arrMonth["Sep"] = {value:"09",text:"September"};
	arrMonth["Oct"] = {value:"10",text:"October"};
	arrMonth["Nov"] = {value:"11",text:"November"};
	arrMonth["Dec"] = {value:"12",text:"December"};
	var month = arrMonth[retarray[1]];
	return(month.value + "/" + retarray[0] + "/" + retarray[2]);
}

function compare2Dates(date1,date2)
{
    // assumes that dates are in the format YYYY-MM-DD
    varDate = date1.split("-");
    day = trimSpaces(varDate[2]); 
    month = trimSpaces(varDate[1]); 
    year = trimSpaces(varDate[0]); 
    d1 = new Date(year,month-1,day).getTime();

    varDate = date2.split("-");
    day = trimSpaces(varDate[2]); 
    month = trimSpaces(varDate[1]); 
    year = trimSpaces(varDate[0]);
    d2 = new Date(year,month-1,day).getTime();
     
    if (d1==0 || d2==0)
    {
        return -1;
    }
    else if (d1 > d2) 
    {
        return 1;
    }
    else if (d1 == d2) 
    {
        return 2;
    }
    return 0;
}

function isDate(dtStr){
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strMonth=dtStr.substring(0,pos1)
    var strDay=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)

    strYr=strYear
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    for (var i = 1; i <= 2; i++) {
        if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
    }
    var month=parseInt(strMonth)
    var day=parseInt(strDay)
    var year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
        return false
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        return false
    }
    if (strMonth.length<1 || month<1 || month>12){
        return false
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        return false
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        return false
    }
return true
}

function checkEmail(strng)
{
    
    var error = "";
    var emailFilter=/^.+@.+\..{2,4}$/;
    if (strng == "") 
        {
        error = "You didn't enter an email-address.\n";
        }
    
    else if (!(emailFilter.test(strng))) 
        { 
        error = "Please enter a valid email address.\n";
        }
    var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/;
    if (strng.match(illegalChars))
        {
        error = "The email address contains illegal characters.\n";
        }
    return error;
}

function checkPassword (strng) 
{
    var error = "";
    var illegalChars = /[\W_]/; 
    if (strng == "") 
    {
        error = "You didn't enter password.\n";
    }
    
    if ((strng.length < 4) || (strng.length > 15)) 
    {
        error = "The password is of wrong length(valid length 4-15 chars).\n";
    }
    else if (illegalChars.test(strng)) 
    {
        error = "The password contains illegal characters.\n";
    }
    return error;
}

function chkselectedids(formname,objname)
{
    var chkflg,strmessageid,url,returl;
    strmessageid="";
    chkflg=false;
    for(j=0; j<document.forms.length;j++)
    {
        if(document.forms[j].name==formname)
        {
            for (i=0;i<document.forms[j].elements.length;i++)
            {
                if (document.forms[j].elements[i].name==objname) 
                {
                    if (document.forms[j].elements[i].checked)
                    {                           
                        chkflg=true;
                        break;
                    }
                }
            }           
        }   
    }
    return chkflg;  
}

function fnShowHint(form,hintid)  {

    window.open("itHelp.php?page="+form+"&context="+hintid, "Help", "statusbar=0, toolbar=0, menubar=0, scrollbar=0, resizable=0, height=400, width=400");
}

function isAlphabetic(val) {
    
    if (val.match(/^[a-zA-Z]+$/)) {
        return true;
    }
    else {
        return false;
    }   
}

function IsNumericValue(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }


// check to see if input is alphanumeric
function isAlphaNumeric(val) {
    
    if (val.match(/^[a-zA-Z0-9]+$/)) {
        return true;
    }
    else {
        return false;
    }
}

function removeSpaces(string) {
   var newString = '';
   for (var i = 0; i < string.length; i++) {
      if (string.charAt(i) != ' ') newString += string.charAt(i);
   }
   return newString;
}

//function to open in custom window
function openWindow(url,window_name,winWidth,winHeight,fscroll,resize) {
    sWidth = screen.availWidth;
    sHeight = screen.availHeight;
    
    sLeft = (sWidth - winWidth) / 2;
    sTop = (sHeight - winHeight) / 2;
    if(fscroll == '') {fscroll = 0}
    if(resize == '') {resize = 'no'}
    
    window.open(url,window_name,"width=" + winWidth + ",height=" + winHeight + ",top=" + sTop + ",left=" + sLeft + ",toolbar=0,menubar=0,status=0,scrollbars=" + fscroll + ",resizable="+resize);
}

// Checks the first occurance of spaces and removes them
function trimSpaces(stringValue) {
    for(i = 0; i < stringValue.length; i++) {
        if(stringValue.charAt(i) != " ") {
            break;
        }
    }
    if(i > 0) {
        stringValue = stringValue.substring(i);
    }
    
    // Checks the last occurance of spaces and removes them
    strLength = stringValue.length - 1;
    for(i = strLength; i >= 0; i--) {
        if(stringValue.charAt(i) != " ") {
            break;
        }
    }
    if(i < strLength) {
        stringValue = stringValue.substring(0, i + 1);
    }
    
    // Returns the string after removing leading and trailing spaces.
    return stringValue;
}
function Trim(TXT)
{
    return TXT.replace(/(^\s+)|(\s+$)/g,"");
}

//function to compare dates
/*
        0 - date1 less than date2
        1 - date1 greater than date2
        2 - date1 =  date2
        -1 - not valid dates
*/
function compareDates(date1,date2)
{
    // assumes that dates are in the format YYYY-MM-DD
    
    varDate = date1.split("-");
    day = trimSpaces(varDate[2]); 
    month = trimSpaces(varDate[1]); 
    year = trimSpaces(varDate[0]); 
    d1 = new Date(year,month-1,day).getTime();

    varDate = date2.split("-");
    day = trimSpaces(varDate[2]); 
    month = trimSpaces(varDate[1]); 
    year = trimSpaces(varDate[0]);
    d2 = new Date(year,month-1,day).getTime();
     
    if (d1==0 || d2==0)
    {
        return -1;
    }
    else if (d1 > d2) 
    {
        return 1;
    }
    else if (d1 == d2) 
    {
        return 2;
    }
    return 0;
}

//function limitText used to limit text in a textarea
function limitText(field,maxlimit,remark) {
    if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
    }
    else {
        if(remark) {
            remark.value = maxlimit - field.value.length;
        }
    }   
}

function isValidIPAddress(ipaddr) {
       var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
       if (re.test(ipaddr)) {
          var parts = ipaddr.split(".");
          if (parseInt(parseFloat(parts[0])) == 0) { return false; }
          for (var i=0; i<parts.length; i++) {
             if (parseInt(parseFloat(parts[i])) > 255) { return false; }
          }
          return true;
       } else {
          return false;
       }
    }

function dateTimeDiff( 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 DtDiff(date1, date2) {
   dte1 = new Date(Date.parse(date1));
   dte2 = new Date(Date.parse(date2));

    if (isNaN (dte1) || isNaN (dte2) ) {
        alert("Invalid date parameters") ;
        return null ;
    }


   diff = Math.abs(dte1.getTime() - dte2.getTime());

    days = 0;
    hours = 0;
    minutes = 0;
    seconds = 0;
  if((diff % 86400000) > 0)
   {
       rest = (diff % 86400000);
       days = (diff - rest) / 86400000;
       
       if((rest % 3600000) > 0 )
       {
           rest1 = (rest % 3600000);
           hours = (rest - rest1) / 3600000;
     

           if((rest1 % 60000) > 0 )
           {
               rest2 = (rest1 % 60000);
               minutes = (rest1 - rest2) / 60000;
               seconds = rest2/1000;
           }else{
               minutes = rest1 / 60000;
           }
      }else{
           hours = rest / 3600000;
       }
   }else{
       days = diff / 86400000;
    }

    var retarray = new Array(4);
    retarray[0]= days;
    retarray[1]= hours;
    retarray[2]= minutes;
    retarray[3]= seconds;
    return retarray;
}




//Convert the date in "YYYY-MM-DD" to "MM/DD/YYYY"
function changeDateformat(datestr) {
    var retarray = datestr.split("-");
    return(retarray[1] + "/" +  retarray[2] + "/" + retarray[0]);
}


//convert ddm-mmm-yyyy To yyyy-mm-dd;
function ddmmmyyyyToDBdate(datestr) {
    var retarray = datestr.split("-");
    var arrMonth = new Object();
    arrMonth["Jan"] = {value:"01",text:"January"};
    arrMonth["Feb"] = {value:"02",text:"February"};
    arrMonth["Mar"] = {value:"03",text:"March"};
    arrMonth["Apr"] = {value:"04",text:"April"};
    arrMonth["May"] = {value:"05",text:"May"};
    arrMonth["Jun"] = {value:"06",text:"June"};
    arrMonth["Jul"] = {value:"07",text:"July"};
    arrMonth["Aug"] = {value:"08",text:"August"};
    arrMonth["Sep"] = {value:"09",text:"September"};
    arrMonth["Oct"] = {value:"10",text:"October"};
    arrMonth["Nov"] = {value:"11",text:"November"};
    arrMonth["Dec"] = {value:"12",text:"December"};
    var month = arrMonth[retarray[1]];
    return(retarray[2] + "-" + month.value + "-" + retarray[0]);
}


function printSetup(pageName) {
    var arrPageName = new Array('im') ;
    var flag = 0;
    
    for(var i=0; i < arrPageName.length; i++) {
        if(arrPageName[i] == pageName) {
            flag = 1;
            break;
        }
    }
    
    if (flag == 0) return false;
    hideMe();
    var a = document.all.item("noPrint");

    if (a!=null) {
        if (a.length!=null) {
            for (i=0; i< a.length; i++) {
                a(i).style.display = window.event.type == "beforeprint" ? "none" :"inline";
            }
        } 
        else { 
            a.style.display = window.event.type == "beforeprint" ? "none" :"inline";
        }
    }

    if( window.event.type == "afterprint") {
        var hidemenu = readCookie("hidemenu");
        if (hidemenu == 1 && document.getElementById("sideMenu"))
        {
            hideMe();
        }
        else {
            showMe();
        }
    }
} 

function roundNumber(val,precision) {
    var newVal = Math.round(val*Math.pow(10,precision))/Math.pow(10,precision);
    return newVal ;
}

//function:minuteToHM - convert minute to hour:minute
function minuteToHM(minute) {
    var sign = "";
    if(minute < 0) {
        sign = "-";
    }   

    var minute = parseInt(Math.abs(minute));

    var hour = parseInt(minute/60);
    var fract = minute % 60;
    var hh = hour;
    var mm = Math.floor(fract);

    if (hh <= 9) hh = "0"+hh ;
    if (mm <= 9) mm = "0"+mm ;
    
    return sign+hh+":"+mm ; 
}

// functions used for auto complete drop down
var keyTime, keyStr = '', lastKey;
var agt=navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));

function setSelection(element)
{
  
  if(is_ie)
  {
    var currentKey = unescape('%' + window.event.keyCode.toString(16)).toLowerCase();
    var idx, currentSIdx = element.selectedIndex;
    var newTime = new Date().getTime();
    if(keyTime != null && newTime - keyTime < 500) // if two keys were pressed between 0.3 seconds (can be customized), do type-ahead
    {
      keyStr += currentKey;
      idx = findIdx(element);
    }
    else // unfortunately we seem to have to handle default browser behavior too
    {
      keyStr = currentKey;
      var selectFirst = true;
      if(keyStr == lastKey)
      {
        idx = currentSIdx + 1;
        if(idx < element.options.length && element.options[idx].text.charAt(0) == lastKey)
          selectFirst = false;
      }
      if(selectFirst) idx = findIdx(element);
      lastKey = currentKey;
    }
    if(idx >= 0)
    {
        element.options[currentSIdx].selected = false;
        element.options[idx].selected = true;
    }
  }
  
}

function findIdx(element)
{
  var idx = -1, len = keyStr.length;
  for(var i = 1; i < element.options.length; i++)
  {
    var str = element.options[i].text.toLowerCase();
    str = str.substring(0, len); 
    if(keyStr == str) { idx = i; break }
  }
  return idx;
}

function setTime()
{
  keyTime = new Date().getTime();
  return false;
}


//Convert the date in "MM/DD/YYYY HH:MM:SS" to "DD-MMM-YYYY HH:MM:SS"
function jsDateToMydate(datestr) {
    var m_names = new Array("", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov","Dec");
    var retarray = datestr.split("/");
    return(retarray[1] + "-" +  m_names[parseInt(retarray[0])] + "-" + retarray[2]);
}

// allows only numeric
function numericOnly(e) {
    if(window.event) {
        key = e.keyCode; // for IE, e.keyCode or window.event.keyCode can be used
    }
    else if(e.which) {
        key = e.which; // netscape
    }
    else {
        return true;// no event, so pass through
    }
    
    if( ((key>45) && (key<58)) || (key == 8) ) {
        return true; 
    }
    else {
        return false;
    }
    
}

// to set focus on default control
function setFocus() {
    var frm = document.forms[0];
    if(frm) { 
        for(i=0; i < frm.elements.length; i++) {
            if(frm.elements[i].type == "text" || frm.elements[i].type == "password" || frm.elements[i].type == "textarea" || frm.elements[i].type == "button" || frm.elements[i].type == "select-one" ){
                if(frm.elements[i].disabled == false) {
                    frm.elements[i].focus();
                    return true;
                }           
            }
        }
    }
                                             
}

//  check for valid numeric strings 
function IsNumeric(strString)   
{
    var testExp = /^\d+\.?\d*$/ ;
    
    if(testExp.test(strString)) {
        return true;
    }
    else {
        false;
    }   
    
}

// functions used for auto complete drop down
var keyTime, keyStr = '', lastKey;
var agt=navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));

function setSelection(element)
{
  
  if(is_ie)
  {
    
    var currentKey = unescape('%' + window.event.keyCode.toString(16)).toLowerCase();
    var idx, currentSIdx = element.selectedIndex;
    var newTime = new Date().getTime();
    if(keyTime != null && newTime - keyTime < 500) // if two keys were pressed between 0.3 seconds (can be customized), do type-ahead
    {
      keyStr += currentKey;
      idx = findIdx(element);
    }
    else // unfortunately we seem to have to handle default browser behavior too
    {
      keyStr = currentKey;
      var selectFirst = true;
      if(keyStr == lastKey)
      {
        idx = currentSIdx + 1;
        if(idx < element.options.length && element.options[idx].text.charAt(0) == lastKey)
          selectFirst = false;
      }
      if(selectFirst) idx = findIdx(element);
      lastKey = currentKey;
    }
    if(idx >= 0)
    {
        element.options[currentSIdx].selected = false;
        element.options[idx].selected = true;
    }
  }
  
}

function findIdx(element)
{
  var idx = -1, len = keyStr.length;
  for(var i = 1; i < element.options.length; i++)
  {
    var str = element.options[i].text.toLowerCase();
    str = str.substring(0, len); 
    if(keyStr == str) { idx = i; break }
  }
  return idx;
}

function setTime()
{
  keyTime = new Date().getTime();
  return false;
}

function Left(str, n){
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0,n);
}
//function to open in custom window
function openWindow(url,window_name,winWidth,winHeight,fscroll,resize) {
	sWidth = screen.availWidth;
	sHeight = screen.availHeight;
	sLeft = (sWidth - winWidth) / 2;
	sTop = (sHeight - winHeight) / 2;
	if(fscroll == '') {fscroll = 0}
	if(resize == '') {resize = 'no'}
	window.open(url,window_name,"width=" + winWidth + ",height=" + winHeight + ",top=" + sTop + ",left=" + sLeft + ",toolbar=0,menubar=0,status=0,scrollbars=" + fscroll + ",resizable="+resize);
}

function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}


