// ----------------------------------------------------------------------------
// function browserDetect: Detect whether the person is using a version 4 Brows
// INPUT: N/A
// OUTPUT: Array of Browser Characteristics
//
function browserDetect()
{
 this.db = (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body? document.body : null;
 this.n = navigator.userAgent.toLowerCase();
 this.op = (window.opera && document.getElementById);
 this.op6 = (this.op && !(this.db && this.db.innerHTML));
 if (this.op && !this.op6) document.onmousedown = new Function('e',
  'if (((e = e || window.event).target || e.srcElement).tagName == "IMAGE") return false;'
 );
 this.ie = this.n.indexOf("msie")!=-1 && document.all && this.db && !this.op;
 this.iemac = this.ie && this.n.indexOf("mac")!=-1;
 this.ie4 = this.ie && !document.getElementById;
 this.n4 = document.layers? true : false;
 this.kq = (this.kqi = this.n.indexOf("konqueror"))>-1 && parseInt(this.n.substring(this.kqi+0x0a))>0x02;
  this.kq_new = this.kq && this.n.substring(this.kqi+0x0a, this.kqi+0x0d)!="3.0";
 this.n6 = !this.op && !this.kq && !this.ie && document.defaultView && typeof document.defaultView.getComputedStyle != "undefined";
 this.n7 = this.n6 && parseInt(this.n.substring((this.n6i = this.n.indexOf('gecko'))+6, this.n6i+0x0c))>200209;
 this.ce = document.captureEvents && document.releaseEvents;
 this.elements = new Array();
}

// ----------------------------------------------------------------------------
// function IsAcceptCookies: Test whether the browser accepts cookies
// INPUT: N/A
// OUTPUT: True or False for if the browser accepts cookies
//
function IsAcceptCookies(){
  var WM_acceptsCookies = false;
  var randomnumber= Math.random();
  document.cookie = 'WM_acceptsCookies=' +randomnumber;// Try to set a cookie.
  if(document.cookie.indexOf('WM_acceptsCookies='+randomnumber) != -1) {
    WM_acceptsCookies = true; 
  }
  return WM_acceptsCookies;
}


// function to limit the length of a textarea for posting to the database
function checkTextAreaLength(myobject,intlength){
   if (myobject.value.length > intlength){
      alert("Please shorten your response to "+intlength+" characters. Thank you!");
      myobject.focus();
   }
}

// function to alert the user if she has left a required field blank
function checkTextNull(x){
   if (x == ""){
      alert("Please fill in the required\ntext! Thank you.");
      return false;
   }
}

var firstwin = true;

// function to open a pop-up window
function openwindow (url,w,h) {
   if (firstwin) { 
      mywin = window.open(url,"help","resizable=yes,status=yes,height="+h+",width="+w+",toolbar=yes,scrollbars=yes");
	  mywin.focus();
      firstwin = false; 
   } else {
      if (mywin.closed == false) {
         mywin.close(); 
      } 
      mywin = window.open(url,"help","resizable=yes,status=yes,height="+h+",width="+w+",toolbar=yes,scrollbars=yes");
  	  mywin.focus();
   }
}

// function to open a pop-up window with a specific title to avoid collisions between two open windows
function openwindow_v2 (url,title,w,h) {
   if (firstwin) { 
      mywin = window.open(url,title,"resizable=yes,status=yes,height="+h+",width="+w+",toolbar=yes,scrollbars=yes");
      firstwin = false; 
   } else {
      if (mywin.closed == false) {
         mywin.close(); 
      } 
      mywin = window.open(url,title,"resizable=yes,status=yes,height="+h+",width="+w+",toolbar=yes,scrollbars=yes");
   }
}
 
// function   
function closewindow() {  
   if (firstwin == false && mywin.closed == false ) { 
      mywin.close();
   } 
}

// function 
function checkemail(x){
   var intPosAt = x.indexOf("\@");
   if (intPosAt > 1) {
      var intPosPeriod = x.indexOf(".");
      if ((intPosAt + 1) > intPosPeriod) {
         alert("Please enter a valid email\naddress! Thank you.");
      }
   } else {
      alert("Please enter a valid email\naddress! Thank you.");
   }
}

// function 
function ReplaceChar(str, strfind, strreplace){
   var newstr=""
   for (var i =0;i <str.length;i++){
      if (str.charAt(i) == strfind){
         newstr = newstr + strreplace
      } else {
         newstr = newstr + str.charAt(i)
      }
   }
   return newstr;
}

// function 
function EnforceTextAreaLength(myobject,intlength){
   if (myobject.value.length > intlength){
      var strtext = myobject.value;
      var str = "";
      for (i = 0; i <= intlength; i++){
         str = str + strtext.charAt(i);
      }
      myobject.value = str;
   }
}

// function 
function confirmlink(msg, url){
   if (confirm(msg)) {
      window.location.href = url;
   }
}

// function 
function confirmdelete(url){
   if (confirm("Are you sure you want to\ndelete this item?")) {
      window.location.href = url;
   }
}

// function 
function confirmexpire(url){
   if (confirm("Selecting expire will\nend date the item to today.\n\nAre you sure you want to\nexpire this entry?")) {
      window.location.href = url;
   }
}

// function 
function currency(anynum) {
   //-- Returns passed number as string in $xxx,xxx.xx format.
   anynum=eval(anynum)
   workNum=Math.abs((Math.round(anynum*100)/100));workStr=""+workNum
   if (workStr.indexOf(".")==-1){workStr+=".00"}
   dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
   pStr=workStr.substr(workStr.indexOf("."))
   while (pStr.length<3){pStr+="0"}

   //--- Adds comma in thousands place.
   if (dNum>=1000) {
      dLen=dStr.length
      dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
   }

   //-- Adds comma in millions place.
   if (dNum>=1000000) {
      dLen=dStr.length
      dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
   }
   retval = dStr + pStr 
   //-- Put numbers in parentheses if negative.
   if (anynum<0) {retval="("+retval+")"}
   return retval
}

// function 
function checkdate(dateStr,strControlName){
   if (dateStr != ''){
      err_msg = isDate(dateStr,strControlName)
      if (err_msg != ''){
         alert(err_msg); 
      }
   }
}

// function 
function checkisvaliddate(dateStr,strControlName){
   if (dateStr != ''){
      err_msg = isDate(dateStr,strControlName)
      if (err_msg != ''){
         alert(err_msg); 
      }
   }
}

// function 
function checkisvaliddateobj(objdate,strControlName){
   if (objdate.value != ''){
      if (objdate.value == 'd' || objdate.value == 'D'){
         var today = new Date();
         objdate.value = eval(today.getMonth()+1)+'/'+today.getDate()+'/'+today.getFullYear();
      } else {
         err_msg = isDate(objdate.value,strControlName)
         if (err_msg != ''){
            alert(err_msg); 
         }
      }
   }
}

// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.
// The function returns true if a valid date, false if not.
// ******************************************************************
// 
function isDate(dateStr,strControlName) {

    //var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var datePat = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?
    var err_msg = "";

    if (matchArray == null) {
        err_msg = " was not entered as mm/dd/yyyy.\nPlease re-enter. Thank you.";
    }
    else{

       month = matchArray[1]; // parse date into variables
       day = matchArray[3];
       year = matchArray[5];
   
       if (month < 1 || month > 12) { // check month range
           err_msg = ": month not between 1 and 12.\nPlease re-enter. Thank you.";
       }
   
       if (day < 1 || day > 31) {
           err_msg = ": day not between 1 and 31.\nPlease re-enter. Thank you.";
       }
   
       if ((month==4 || month==6 || month==9 || month==11) && day==31) {
           err_msg = ": month "+month+" doesn't have 31 days.";
       }
   
       if (month == 2) { // check for february 29th
           var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
           if (day > 29 || (day==29 && !isleap)) {
               err_msg = ": February " + year + " does not have " + day + " days.\nPlease re-enter. Thank you.";
           }
       }
       
    }
    
    if(err_msg != ""){
        err_msg = strControlName + err_msg;
    }
    return err_msg;
}

// function 
function getfiscalyear(strdate){
   gdate = new Date(strdate);
   var intmonth = gdate.getMonth();
   var intday = gdate.getDay();
   var intyear = gdate.getFullYear();

   if (intmonth < 6){
      var strcuryear = intyear.toString().substr(2,2);
      intyear = intyear-1
      var strprevyear = intyear.toString().substr(2,2);
      var fiscalyear = strprevyear + strcuryear;
      //alert(fiscalyear);
   } else {
      var strcuryear = intyear.toString().substr(2,2);
      intyear = intyear+1
      var strnextyear = intyear.toString().substr(2,2);
      var fiscalyear = strcuryear + strnextyear;
      //alert(fiscalyear);
   }
   return fiscalyear;
}

// function checktime: start by looking for AM/PM
//    Then check to make sure that the hour is correct
//    Then check to make sure that the minutes are correct.
function checktime(shour, sminute, sampm){
   //alert(shour + sminute + sampm);
   if (sampm == 'NA'){
      if (shour != '00'){
         alert('Please enter the complete time\nincluding AM/PM. Thank you.');
      } else {
         if (sminute != '00'){
            alert('Please enter the complete time\nincluding AM/PM. Thank you.');
         }
      }
   } else {
      if (shour == '00'){
         alert('Please enter the time.\nThank you.');
      }
   }
}

// function 
function isValidEmail( str ) {
  /* Checks if a given string is a valid email address, based on the following criteria:
     - One or more characters before the "@" 
     - An optional "[", because user@[255.255.255.0] is a valid e-mail 
     - A sequence of letters, numbers, and periods, which are all valid domain or 
     - IP address characters 
     - A period followed by a 2-3 letter suffix 
     - An optional "]" 
  */
  var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
  var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid

  return (!reg1.test(str) && reg2.test(str));
}

function dpuTimeAdd(pinthour, pintminute, pstrampm, pintaddhour, pintaddminute){
   var strreturn = "";
 // step 1: add the times
   var inthour = Number(pinthour) + Number(pintaddhour);
   var intminute = Number(pintminute) + Number(pintaddminute);
   var strampm = pstrampm.toUpperCase();
   
 // step 2: factor minutes by 60
   if(intminute >= 60){
      inthour = inthour + 1;
      intminute = intminute - 60;
   }
   
 // step 3: factor hours by 12
   if(inthour > 12){
      inthour = inthour - 12;
      if(pinthour < 12){
         if(strampm == "AM"){
            strampm == "PM";
         } else {
            strampm == "AM";
         }
      }
   }
   
   strreturn = inthour+':'+intminute+' '+strampm;
   return strreturn;
}

// function 
function dpuTimeSubtract(pinthour, pintminute, pstrampm, pintminushour, pintminusminute){
   var strreturn = "";
 // step 1: add the times
   var inthour = eval("pinthour - pintminushour");
   var intminute = eval("pintminute - pintminusminute");
   var strampm = pstrampm.toUpperCase();
   
 // step 2: factor minutes - 0
   if(intminute < 0){
      inthour = inthour - 1;
      intminute = intminute + 60;
   }

 // step 3: factor hours - 0
   if(inthour <= 0){
      if(inthour < 0){
         if(strampm == "AM"){
            strampm = "PM";
         } else {
            strampm = "AM";
         }
      }
      inthour = inthour + 12;
   }
 
 // step 4: factor AM/PM
   if(pinthour == 12 && inthour < 12){
      if(strampm = "AM"){
         strampm = "PM";
      } else {
         strampm = "AM";
      }
   }

   strreturn = inthour+':'+intminute+' '+strampm;
   return strreturn;
}

// function 
function isnumber(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;
}

// function 
function checkisnumeric(sText, sName){
  if (isnumber(sText.value) == false){
     alert('Please enter only numbers for '+sName+'.\nThank you.');
  }
}

// function 
function isValidTime12Hour(value) {
   var colonCount = 0;
   var hasMeridian = true;

 // Check Length of Time ********************************************************************************
   if (value.length < 6) { return false; }

 // Check for AM/PM  ************************************************************************************
   var ch = value.charAt(value.length-1);
   if ((ch != 'm') && (ch != 'M')) { return false; }
   var ch = value.charAt(value.length-2);
   if ((ch != 'a') && (ch != 'A') && (ch != 'p') && (ch != 'P')) { return false; }
   var ch = value.charAt(value.length-3);
   if ((ch != ' ')) { return false; }
   
 // Check for characters that are not allowed and return false if found *********************************
   for (var i=0; i<value.length; i++) {
      var ch = value.substring(i, i+1);
      if ( (ch < '0') || (ch > '9') ) {
         if ( (ch != ':') && (ch != ' ') && (ch != 'a') && (ch != 'A') 
         && (ch != 'p') && (ch != 'P') && (ch != 'm') && (ch != 'M')) {
            return false;
         }
      }
      if (ch == ':') { colonCount++; }							// Count colons
      if ( (ch == 'p') || (ch == 'P') 
      || (ch == 'a') || (ch == 'A') ) { hasMeridian = true; }	// Check for AM/PM
   }

   if ( (colonCount < 1) || (colonCount > 1) ) { return false; }	// Too many colons
   
// Check for valid hour, minute, and second values *****************************************************
   var hh = value.substring(0, value.indexOf(":"));
   if ( (parseFloat(hh) < 0) || (parseFloat(hh) > 23) ) { return false; }
   if (hasMeridian) {
      if ( (parseFloat(hh) < 1) || (parseFloat(hh) > 12) ) { return false; }
   }
   if (colonCount == 2) {
      var mm = value.substring(value.indexOf(":")+1, value.lastIndexOf(":"));
   } else {
      var mm = value.substring(value.indexOf(":")+1, value.length);
   }
   if ( (parseFloat(mm) < 0) || (parseFloat(mm) > 59) ) { return false; }
   if (colonCount == 2) {
      var ss = value.substring(value.lastIndexOf(":")+1, value.length);
   } else {
      var ss = "00";
   }
   if ( (parseFloat(ss) < 0) || (parseFloat(ss) > 59) ) { return false; }
   return true;
}

// function 
function checkisvalidtime(value, fname){
   if (value != ''){
   if (isValidTime12Hour(value) == false) {
      alert('The '+fname+' you have entered is invalid.\n'
            +'Please enter a valid time.\nThank you.');
      return false;
   } else {
      return true
   }
   }
}

// function 
function isvalidcreditcardnumber(cardtype, cardnumber){
   //alert('cardtype = ' + cardtype + '.\n' +
   //      'cardnumber = ' + cardnumber + '.\n' +
   //      'cardnumber.length = ' + cardnumber.length + '\n' +
   //      'cardnumber.char1 = ' + cardnumber.charAt(0) + '\n');
   var blnreturn = true;
   if (isnumber(cardnumber) == false){
      blnreturn = false;
   }
   if (cardnumber.length != 16) {
      blnreturn = false;
   }
   if (cardtype == 'VISA'){
      if (cardnumber.charAt(0) != '4'){
         blnreturn = false;
      }
   }
   if (cardtype == 'MC'){
      if (cardnumber.charAt(0) != '5'){
         blnreturn = false;
      }
   }
   return blnreturn;
}

// ----------------------------------------------------------------------------
// function autotab: automatically moves the cursor to the next field
// INPUT: Number of Characters in the Current Field to enter before moving,
//        the current field, the next field
// OUTPUT: Cursor is moved to the next field
function autotab(numchars, obj, objnext){
   if (obj.value.length == numchars){
      objnext.focus();
   }
}

// ----------------------------------------------------------------------------
// function putlovtext: automatically enters the text into the LOV field
// INPUT: Name of the ID menu populated with System Registry values
// OUTPUT: Hidden Text field is set in order to write decoded text to DB
function putlovtext(obj){
   var fn = obj.substr(0, obj.length-2)+'TEXT';
   var x = document.myform[obj].options[document.myform[obj].selectedIndex].text;
   document.myform[fn].value = x;
}

// ----------------------------------------------------------------------------
// function putlovtext: automatically enters the text into the LOV field
// INPUT: Name of the ID menu populated with System Registry values
// OUTPUT: Hidden Text field is set in order to write decoded text to DB
function putlovtextmultiline(obj,i){
   var fn = obj.substr(0, obj.length-2)+'TEXT'+i;
   var x = document.myform[obj+i].options[document.myform[obj+i].selectedIndex].text;
   document.myform[fn].value = x;
}

// ----------------------------------------------------------------------------
// function checkisvaliddatetime: check date/time and alert
// INPUT: Value of Field and Name of Field
// OUTPUT: Alert if the datetime is invalid
function checkisvaliddatetime(value,name){
   var arydatetime = value.split(' ');
   var valuedate = arydatetime[0];
   var valuetime = arydatetime[1]+' '+arydatetime[2];
   if (valuedate != ''){
      err_msg = isDate(valuedate,name)
      if (err_msg != ''){
         alert(err_msg); 
      }
   }
   if (isValidTime12Hour(valuetime) == false) {
      alert('The '+name+' you have entered is invalid.\n'
            +'Please enter a valid date and time.\nThank you.');
      return false;
   }
}
