var sectionValidationCallbacks = new Array;

function registerCallback(func){
  sectionValidationCallbacks.push(func);
}

function confirm_message(message, postUrl) {
  if (confirm(message)) {
    window.location=postUrl;
  }
}

function getNumber(input) {
  var number = 0;
  cleanText(input, ",$ ");
  var v = parseFloat(input.value);
  if (!isNaN(v)) {
    number = v;
  }
  return number;
}

function isValidFormat(inStr,fiormat) {

  if (inStr)
  {
    var str;
  
    str = inStr;
    str.toUpperCase();
  
    if (str.length != format.length) {
      return false;
    }
  
    for (i = 0; i < format.length; i++) {
       if (format.charAt(i) == '9') {
         if (str.charAt(i) < '0' || str.charAt(i) > '9') {
           return false;
         }
       } else if (format.charAt(i) == 'A') {
         if (!((str.charAt(i) >= '0' && str.charAt(i) <= '9') || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'))) {
           return false;
         }
       } else if (format.charAt(i) == 'L') {
         if (!(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')) {
           return false;
         }
       } else if (format.charAt(i) != str.charAt(i)) {
         return false;
       } 
    }
  }
  else
    return false;
  return true;

}

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);
  if(str == "") {
    return true;
  }
  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 confirm_delete(postUrl) {
  message = "Are you sure you want to delete this record?";
  confirm_message(message, postUrl);
}

function cleanText(input,filteredValues) {
  if (input && filteredValues)
  {
    s = input.value;
    
    if (s)
    {
      var i;
      var returnString = "";
      for (i = 0; i < s.length; i++) {  // Search through string and append to unfiltered values to returnString.
        var c = s.charAt(i);
        if (filteredValues.indexOf(c) == -1) returnString += c;
      }
      input.value = returnString;
    }
  }
}

function isblank(s) {
    if ( null == s) 
    {
      return true;
    }
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

function formatZip(zip) {

  if (zip)
  {
    if (zip.length == 5) {
       return zip;
    }
  
    var returnZip = "";
    
    returnZip = zip.substr(0,5);
    returnZip += "-";
    returnZip += zip.substr(5);
    return returnZip;
  }
}

function isValidZip(input) {
  if (input)
  {
    cleanText(input, "-()/ ");
    var z = input.value;
    var r1 = new RegExp("[0-9]{5}(-[0-9]{4})?");
    if (!r1.test(z)) {
      return false;
    }
    if ((z.length != 5) && (z.length != 9)) {
      return false;
    }
  }
  else
  {
    return false;
  }
    
  return true;
}

function formatSsn(ssn) {
    if (ssn)
    {
      var returnSsn = "";
    
      returnSsn = ssn.substr(0,3);
      returnSsn += "-";
      returnSsn += ssn.substr(3,2);
      returnSsn += "-";
      returnSsn += ssn.substr(5,4);
    
      return returnSsn;
    }
    else return "";
}

function isValidSsn(input) {
  if (input)
  {
    cleanText(input, "- ");
    
    var v = input.value;
    var r1 = new RegExp("^[0-9]*$");
    if (!r1.test(v)) {
      return false;
    }
    if (v.length != 9) {
      return false;
    }
    return true;
  }
  else return false;
}


function formatPhone(phoneNumber) {
  if( phoneNumber.length > 0 )
  {
    var returnPhone = phoneNumber.substr(0,3);
    var idx = 0;
    
    returnPhone += " ";
    returnPhone += phoneNumber.substr(3,3);
    returnPhone += " ";
    returnPhone += phoneNumber.substr(6,4);
    return returnPhone;
  }else{
    return phoneNumber;
  }
}


function isValidPhone(input) {
  if( input.value.length == 0 ) {
    return true;
  }
  if (input) 
  {
    cleanText(input, "-/ ");
    
    var v = input.value;
    var r1 = new RegExp("^[0-9]*$");
    if (!r1.test(v)) {
      return false;
    }
    if (v.length != 10 ) {       
      return false;
    }
    return true;
  }
  else return false;
}

function isValidNumeric(input) {
    var v = input.value;
    var r1 = new RegExp("^[0-9]*$");
    if (!r1.test(input)) {
      return false;
    }
  return true;
}

function isValidTime(input) {
  var r1 = new RegExp("^[0-9]{1,2}:[0-9]{2}\\s[aApP][mM]$");
  if (!r1.test(input)) {
    return false;
  }
  result = input.match(/[0-9]{1,2}/g);
  hours = parseInt(result[0], 10);
  minutes = parseInt(result[1], 10);
  if(hours > 12 || hours < 1) {
    return false;
  }
  if(minutes > 59) {
    return false;
  }
  return true;
}

function check_date(objName) {
  if (!objName)
    return false;
    
  var strDatestyle = "US"; //United States date style
  //var strDatestyle = "EU";  //European date style
  var strDate;
  var strDateArray;
  var strDay;
  var strMonth;
  var strYear;
  var intDay;
  var intMonth;
  var intYear;
  var booFound = false;
  var datefield = objName;
  var strSeparatorArray = new Array("-"," ","/",".");
  var intElementNr;
  var err = 0;
  var strMonthArray = new Array(12);
  strMonthArray[0] = "Jan";
  strMonthArray[1] = "Feb";
  strMonthArray[2] = "Mar";
  strMonthArray[3] = "Apr";
  strMonthArray[4] = "May";
  strMonthArray[5] = "Jun";
  strMonthArray[6] = "Jul";
  strMonthArray[7] = "Aug";
  strMonthArray[8] = "Sep";
  strMonthArray[9] = "Oct";
  strMonthArray[10] = "Nov";
  strMonthArray[11] = "Dec";
  strDate = datefield.value;
  if (strDate.length < 1) {
    return true;
  }
  for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
    if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
      strDateArray = strDate.split(strSeparatorArray[intElementNr]);
      if (strDateArray.length != 3) {
        err = 1;
        return false;
      } else {
        strDay = strDateArray[0];
        strMonth = strDateArray[1];
        strYear = strDateArray[2];
      }
      booFound = true;
    }
  }
  if (booFound == false) {
    if (strDate.length == 5) {
      strDate = '0' + strDate;
    }
    if (strDate.length>5) {
      strDay = strDate.substr(0, 2);
      strMonth = strDate.substr(2, 2);
      strYear = strDate.substr(4);
    } else {
      err = 9;
      return false;
    }
  }
  if (strYear.length == 2) {
    var intTwoYear = parseInt(strYear);
    if (intTwoYear < 20) {
      strYear = '20' + strYear;
    } else {
      strYear = '19' + strYear;
    }
  }
  // US style
  if (strDatestyle == "US") {
    strTemp = strDay;
    strDay = strMonth;
    strMonth = strTemp;
  }
  intDay = parseInt(strDay, 10);
//  if( intDay < 10 ) {
//    if("0"+intDay != strDay) {
//      return false;
//    }
//  }
//  else {
//    if( ""+intDay != strDay) {
//      return false;
//    }
//  }
  if (isNaN(intDay)) {
    err = 2;
    return false;
  }
  intMonth = parseInt(strMonth, 10);
//  if( intMonth < 10) {
//    if( "0"+intMonth != strMonth) {
//      return false;
//    }
//  else
//    if( ""+intMonth != strMonth) {
//      return false;
//    }
//  }
  if (isNaN(intMonth)) {
    for (i = 0;i<12;i++) {
      if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
        intMonth = i+1;
        strMonth = strMonthArray[i];
        i = 12;
       }
    }
    if (isNaN(intMonth)) {
      err = 3;
      return false;
     }
  }
  intYear = parseInt(strYear, 10);
  if( ""+intYear != strYear) {
    return false;
  }
  if (isNaN(intYear)) {
    err = 4;
    return false;
  }
  if (intMonth>12 || intMonth<1) {
    err = 5;
    return false;
  }
  if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intDay > 31 || intDay < 1)) {
    err = 6;
    return false;
  }
  if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30 || intDay < 1)) {
    err = 7;
    return false;
  }
  if (intMonth == 2) {
    if (intDay < 1) {
      err = 8;
      return false;
    }
    if (LeapYear(intYear) == true) {
      if (intDay > 29) {
        err = 9;
        return false;
      }
    }
    else {
      if (intDay > 28) {
        err = 10;
        return false;
      }
    }
  }
  if (strDatestyle == "US") {
    datefield.value = intMonth + "/" + intDay+"/" + strYear;
  }
  else {
    datefield.value = intDay + " " + strMonthArray[intMonth-1] + " " + strYear;
  }
  return true;
}
function LeapYear(intYear) {
    if (intYear % 100 == 0) {
      if (intYear % 400 == 0) { return true; }
    }
    else {
      if ((intYear % 4) == 0) { return true; }
    }
    return false;
}

function doDateCheck(from, to) {
  if (from && to)
  {
    var errors = ""
    if (Date.parse(from.value) > Date.parse(to.value)) {
      if (from.value == "" || to.value == "") 
        errors = "Both dates must be entered.";
      else 
        errors = "To date must occur after the from date.";
    }
  }
  else
    errors = "Both dates must be entered.";
    
  return errors;
}


function checkMinMax(e, v) {
   var errors = "";
   if (((e.min != null) && (v < e.min)) || 
      ((e.max != null) && (v > e.max))) {
      errors += e.label + " must be a number";
      if (e.min != null) 
        errors += " that is greater than or equal to " + e.min;

      if (e.max != null && e.min != null) 
        errors += " and less than or equal to " + e.max;
      else if (e.max != null)
        errors += " that is less than or equal to " + e.max;

      errors += ".\n";
   }

   return errors;
}

function makeFieldNormal(e) 
{
  if (e)
    e.style.backgroundColor="#FFFFFF";
}

function makeFieldInError(e) 
{  
  if (e) {
    e.style.backgroundColor="#FFFFCC";
  }
}

// This is the function that performs form verification. It is invoked
// from the onsubmit event handler. The handler should return whatever
// value this function returns.
function validate(f) {
    var msg;
    var empty_fields = "";
    var errors = "";
    
    if ( !f.length )
    {
      // no form to validate
      return true;
    }

    // Loop through the elements of the form, looking for all 
    // text and textarea elements that don't have an "optional" property
    // defined. Then, check for fields that are empty and make a list of them.
    // Also, if any of these elements have a "min" or a "max" property defined,
    // verify that they are numbers and in the right range.
    // If the element has a "numeric" property defined, verify that
    // it is a number, but don't check its range.
    // Put together error messages for fields that are wrong.
    for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];
        var errorMsg = null;
        if ((e.type == "text") || (e.type == "textarea") || e.type=="select-one" || e.type == "password" || e.type == "file") 
        {
            if ( e.label == null ) {
              label = document.getElementById(e.name + ".label");
              if(label) {
                if(e.id.indexOf("required") > -1) {
                  e.label = label.innerHTML.substring(2, label.innerHTML.length);
                }
                else {
                  e.label = label.innerHTML;
                }
              }
              else {
                if( e.attributes.getNamedItem('label') ) {
                  e.label = e.attributes.getNamedItem('label').nodeValue;
                }
                else {
                  e.label = e.name;
                }
              }
            }

            if (e.type == "select-one" && e.selectedIndex == -1) {
               if (e.id.indexOf("required") > -1) {
                  makeFieldNormal(e);
                  empty_fields += "\n          " + e.label;
                  makeFieldInError(e);
               }
               continue;
            }

            makeFieldNormal(e);
            cleanText(e, '"&'); // don't allow double quote character

            if ( e.id.indexOf("required") > -1 )
            {
              // first check if the field is empty
              if ((e.value == null) || (e.value == "") || isblank(e.value)) 
              {
                  empty_fields += "\n          " + e.label;
                  makeFieldInError(e);
                  continue;
              }
            }
            
            if ( (e.id.indexOf( "email" ) > -1) && !isValidEmail(e.value) ) 
            {
               errors += "- " + e.label + " is an invalid email address. \n";
               makeFieldInError(e);
            }

            if ( e.id.indexOf( "phone" ) > -1 ) 
            {
              if (isValidPhone(e)) 
              {
                 e.value = formatPhone(e.value);
              } 
              else 
              {
                errors += "- " + e.label + " is an invalid phone number.  Phone numbers must be 10 digits.\n";
                makeFieldInError(e);
              }
            }

            if ( e.id.indexOf( "zip" ) > -1 )
            {
              if (isValidZip(e)) 
              {
                 e.value = formatZip(e.value);
              } 
              else 
              {
                errors += "- " + e.label + " is an invalid zip code.  Zip Codes must be either 5 or 9 digits.\n";
                makeFieldInError(e);
              }
            }

            if ( e.id.indexOf( "date" ) > -1 ) {
              if (!check_date(e)) {
                errors += "- " + e.label + " is an invalid date.  Please use MM/DD/YYYY format.\n";
                makeFieldInError(e);
              }
            }

            if ( e.id.indexOf( "ssn" ) > -1 ) {
              if (isValidSsn(e)) {
                 e.value = formatSsn(e.value);
              } else {
                errors += "- " + e.label + " is invalid.  Please enter in 999-99-9999 format.\n";
                makeFieldInError(e);
              }
            }

            if ( e.id.indexOf( "correctformat" ) > -1 ) {
              if (!isValidFormat(e.value, e.format)) {
                errors += "- " + e.label + " is invalid.  Please enter in " + e.format + " format.\n";
                makeFieldInError(e);
              }
            }
              
            if ( e.id.indexOf( "year" ) > -1 ) {
               e.integer=true;
               if (e.min) {
               } else {
                 e.min=1900;
               }
               if (e.max) {
               } else {
                 e.max=2050;
               }
            }

            if ( e.id.indexOf( "number" ) > -1 ) {
//                cleanText(e, ",$ ");
                var v = parseFloat(e.value);
                if (isNaN(v)) {
                    errors += "- The field " + e.label + " must be a number.\n";
                    makeFieldInError(e);
                } else {
                  e.value = v;
                  errorMsg = checkMinMax(e, v);
                  if (errorMsg) {
                     errors+=errorMsg;
                     makeFieldInError(e);
                  }
                }
            }

            if ( e.id.indexOf( "integer" ) > -1 ) {
                cleanText(e, ", ");
                var v = parseInt(e.value);
                if (isNaN(v)) {
                    errors += "- The field " + e.label + " must be an integer.\n";
                    makeFieldInError(e);
                } else {
                  e.value = v;
                  errorMsg = checkMinMax(e, v);
                  if (errorMsg) {
                     errors+=errorMsg;
                     makeFieldInError(e);
                  }
                }
            }
            
            if ( (e.id.indexOf( "numeric" ) > -1) && !isValidNumeric(e.value) ) 
            {
               errors += "- " + e.label + " contains non-numeric characters. \n";
               makeFieldInError(e);
            }
            if(e.value != ""){
	            if ( (e.id.indexOf( "time" ) > -1) && !isValidTime(e.value) ) 
	            {
	               errors += "- " + e.label + " is an invalid time. \n";
	               makeFieldInError(e);
	            }
			}
        }
        
        <!-- this code has been added specifically for the HR training application Shailaja 05/11/04 -->
               
        if ( (e.type == 'checkbox') && (e.name == 'mandatoryChk')) {
         if (e.checked) {
            
            var e2 = f.department;                                    
            if ( (e2.value == "") || (e2.value == null) || (isblank(e2.value)) ) 
            {
               empty_fields += "\n          " + e2.label;
               makeFieldInError(e2);
            }
            
          }
        }        
        
        if ( e.id.indexOf( "text" ) > -1 ) {                                    
            var v = e.value;                                
            var r1 = new RegExp("^[a-zA-Z0-9][a-zA-Z0-9_\-]+");
            if (!r1.test(v)) {
               errors += "- The field '" + e.label + "' must be a Text starting with letters(a-z,A-Z). Can include digits and underscore in between.\n";
               makeFieldInError(e);                           
            }
        }        
        
        <!--  end -->
               
               
        if (e.validator) {
           errorMsg = e.validator(e,errors);
           if (errorMsg) {
              errors+=errorMsg;
              makeFieldInError(e);
           }
        }
    }

    if(sectionValidationCallbacks.length > 0) {
      for(i=0; i<sectionValidationCallbacks.length; i++) {
        errors += sectionValidationCallbacks[i](f);
      }
    }
    
    // Now, if there were any errors, display the messages, and
    // return false to prevent the form from being submitted. 
    // Otherwise return true.
    if (!empty_fields && !errors) return true;

    msg  = "______________________________________________________\n\n"
    msg += "The form was not submitted because of the following error(s).\n";
    msg += "Please correct these error(s) and re-submit.\n";
    msg += "______________________________________________________\n\n"

    if (empty_fields) {
        msg += "- The following required field(s) are empty:" 
                + empty_fields + "\n";
        if (errors) msg += "\n";
    }
    msg += errors;
    alert(msg);
    return false;
}

