
/*
* Description: library of Form Validator functions 
* 
* This library is called by forms for a variety of both Validation
*   and formatting purposes
* 
*/


// ====== Support Functions =============================
function strip(filter,str){
  var i,curChar;
  var retStr = '';
  var len = str.length;
  for(i=0; i<len; i++) {
    curChar = str.charAt(i);
    
    if(filter.indexOf(curChar) < 0 ) //not in filter, keep it
    retStr += curChar;
  }
  return retStr;
}

function reformat(str){
 var arg;
 var pos = 0;
 var retStr = '';
 var len = reformat.arguments.length;
 for(var i=1; i<len; i++) {
  arg = reformat.arguments[i];
  if(i%2==1)
   retStr += arg;
  else {
   retStr += str.substring(pos, pos + arg);
   pos += arg;
  }
 }
 return retStr;
}

// ======== End Support Functions ======================



// ======== Begin Validation Rules =====================

// is form field empty?
function notEmpty(str){
 if(strip(" \n\r\t",str).length ==0)
  return false;
 else
  return true;
}

// is input an integer(s)
function validateInteger(str){
 str = strip(' ',str);
 //remove leading zeros, if any
 while(str.length > 1 && str.substring(0,1) == '0') {
  str = str.substring(1,str.length);
 }
 var val = parseInt(str);
 if(isNaN(val))
  return false;
 else
  return true;
}

function validateFloat(str){
 str = strip(' ',str);
 //remove leading zeros, if any
 while(str.length > 1 && str.substring(0,1) == '0'){
  str = str.substring(1,str.length);
 }
 var val = parseFloat(str);
 if(isNaN(val))
  return false;
 else
  return true;
}

function validateUSPhone(str){
 str = strip("*() -./_\n\r\t\\",str);
 //if(str.length == 10 || str.length == 7)
 if(str.length == 10)
  return true;
 else
  return false; 
}

function validateDAMPhone(str){
  str = strip("*() -./_\n\r\t\\",str);
  //if(str.length == 10 || str.length == 7)
  if(str.length < 21) {
    return true;
  }
  else {
    return false; 
  }
}

function validateSSN(str){
  str = strip(" -.\n\r\t",str);
  if(isInteger(str) && str.length == 9)
    return true;
  else
    return false;
}

function validateZip(str){
 str = strip("- \n\r\t",str);
 if(isInteger(str)&&(str.length==9 || str.length==5))
  return true;
 else
  return false;
}

function validateCC(str,type){
 str = strip("-./_\n\r\t\\",str);
 if(type=="1")
  if(str.charAt(0)!="4")
   return false;
 if(type=="2")
  if(str.charAt(0)!="5")
   return false;
 if(type=="3")
  if(str.charAt(0)!="6")
   return false;
 if(type=="4")
  if(str.charAt(0)!="3")
   return false;
 if(isInteger(str)&&((str.length==15&&type=="4") || str.length==16))
  return true;
 else
  return false;
}

function validateDate(str){
 var dateVar = new Date(str);
 if(isNaN(dateVar.valueOf()) || (dateVar.valueOf() ==0))
  return false;
 else
  return true;
}

function validateEMail(str){
 str = strip(" \n\r\t",str);
 if(str.indexOf("@")>-1 && str.indexOf(".")>-1)
  return true;
 else
  return false;
}

//check for two fields being equal
function compare(str, str2){
 if(str != str2){
  return false;
 }
 else {
  return true;
 }
}

//check for password length (min 6 - max 32)
function validatePasswordLength(str) {
 if(str.length < 8 || str.length > 32) {
  return false;
 }
 else { 
  return true;
 }
}

//check for UserID length (min 8 - max 64)
function validateUserIDLength(str) {
 if(str.length < 8 || str.length > 64) {
  return false;
 }
 else { 
  return true;
 }
}

//check for valid day 
function validateDayFormat(mStr, dStr, yStr) {
  if ((isInteger(mStr)== false) || 
      (isInteger(dStr)== false) || 
      (isInteger(yStr)== false) ) {
     return false;
  } 
  var mo = parseInt(mStr, 10);
  var da = parseInt(dStr, 10);
  
// needed? 
// strip century if present
// if(yStr.length == 4) {
//   yStr = yStr.substring(2,5);
// }
      
  var ye = parseInt(yStr, 10);

  if (da < 1) { 
    return false; 
  }
  if ((mo == 4) || (mo == 6) || (mo == 9) || (mo == 11)) {
    //it is a 30 day month
    if (da > 30) { 
      return false; 
    }
  } 
  else if (mo == 2) {  
    // it is february (either 28 or 29 depending on leap year)
    if (isLeapYear(ye) == true) { 
      if (da > 29) {
        //leap years have 29 days in february
        return false;
      } 
    } 
    else {
      if (da > 28) {
        //non leap years have 28 days in february
        return false;
      }
    } 
  } 
  else {
    // it is a 31 day month
    if (da > 31) {
      return false;
    }
  }
  // must be valid
  return true;
}


//check for valid month
function validateMonthFormat(str) {
  if (isInteger(str)== false) {
    return false;
  }
  if (isInteger(str)== true) {
    if (str < 1 || str > 12) {
      return false;
    }
  }
  else { 
    return true; 
  }
}

//check for valid year
function validateYearFormat(str) {
  str = strip("-./_\n\r\t\\",str);
  if (isInteger(str) == false) {
    return false;
  }
  
  // check for one or three digits, can't 
  // tell year from that 
  if ((str.length == 1) || (str.length == 3) ) {
    return false;
  }
  
  if (str.length == 4) {
    // check century
    var century = str.substring(0,2);
    
    // if first two digits are not 19 or 20, no good
    if ((century < "19" ) || (century > "20")) {
      return false;
    }
  } 
  return true;
}

//check for valid year and centrury 2000
function validateYearFormat2000(str) {
  str = strip("-./_\n\r\t\\",str);
  if (isInteger(str) == false) {
    return false;
  }
  
  // check for one or three digits, can't 
  // tell year from that 
  if ((str.length == 1) || (str.length == 3) ) {
    return false;
  }
  
  if (str.length == 4) {
    // check century
    var century = str.substring(0,2);
    
    // if first two digits are not 20, no good
    if (century != "20") {
      return false;
    }
  } 
  return true;
}

// expects date in M or MM-D or DD - YY or CCYY
// will strip out hyphens and add leading zeros in month if needed
function parseMonth(dateString) {
  month =  dateString.substring (0, dateString.indexOf ("-"));
  month = formatLeadingZero(month);
  return month;
}

// expects date in M or MM-D or DD - YY or CCYY
// will strip out hyphens and add leading zeros in day if needed
function parseDay(dateString) {  
  day = dateString.substring (dateString.indexOf ("-")+1, dateString.lastIndexOf ("-"));
  day = formatLeadingZero(day);
  return day;
}

// expects date in M or MM-D or DD - YY or CCYY
// will strip out hyphens
function parseYear(dateString) {  
  year = dateString.substring (dateString.lastIndexOf ("-")+1, dateString.length);
  return year;
}

// compare dates, returns 1, -1 or 0
// expecting date in mm-dd-ccyy or mm-dd-yy
function compareDates (value1, value2) {
  var date1, date2;
  var month1, month2;
  var year1, year2;

  month1 = value1.substring (0, value1.indexOf ("-"));
  date1 = value1.substring (value1.indexOf ("-")+1, value1.lastIndexOf ("-"));
  year1 = value1.substring (value1.lastIndexOf ("-")+1, value1.length);

  month2 = value2.substring (0, value2.indexOf ("-"));
  date2 = value2.substring (value2.indexOf ("-")+1, value2.lastIndexOf ("-"));
  year2 = value2.substring (value2.lastIndexOf ("-")+1, value2.length);

  if (year1 > year2) return 1;
  else if (year1 < year2) return -1;
  else if (month1 > month2) return 1;
  else if (month1 < month2) return -1;
  else if (date1 > date2) return 1;
  else if (date1 < date2) return -1;
  else return 0;
}

   
// returns the number of days when comparing today, and a 
// submitted year, month and day
function daysBetween(yr, mo, dy) {
  
  // millisecond values
  var second = 1000; // a second
  var minute = second * 60; // a minute
  var hour = minute * 60; // an hour
  var day = hour * 24; // a day
  var week = day * 7; // a week

  var nDate = new Date(); // current date (local)
  var nTime = nDate.getTime(); // current time (UTC)
  var dTime = Date.UTC(yr, mo - 1, dy); // specified time (UTC)
  var bTime = Math.abs(nTime - dTime)  // time difference
  
  // if submitted date is in the past, add minus sign
  if (nTime > dTime) {
    return "-" + Math.round(bTime / day);
  } else {
    return Math.round(bTime / day);
  }

}


//check for valid year
function validateDateNotNowOrFuture (mStr, dStr, yStr) {

  // get today in proper format
  var d = new Date();
  var mon = d.getMonth() + 1;
  mon = formatLeadingZero(mon.toString());
  var day = d.getDate();
  day = formatLeadingZero(day.toString());
  var year = d.getFullYear();
  var today = mon + day + year;
  
  // passed in date
  var enteredDate = mStr + "/" +  dStr + "/" + yStr;
  var enteredDate = strip("-./_\n\r\t\\",enteredDate);
  
  // if not an int, toss
  if (isInteger(enteredDate)== false) {
    return false;
  }
  
  // if date entered is today or sometime in the future, return false
  if ( (compareDates(today, enteredDate) == 0) ||  
       (compareDates(today, enteredDate) == -1) ) { 
     return false;
  } 
  return true
}  


// better integer check 
function isInteger(str) {
  var isInt = true;
  inputStr = str.toString(); // in case not a string already
  for (var i = 0; i < str.length; i++) {
    var oneChar = str.charAt(i);
    if (oneChar < "0" || oneChar > "9") {
      isInt = false;
      i = str.length; // break out of loop when bad char found
    }
  } 
  return isInt;
}

// check for Leap Year
function isLeapYear(yr) {
  // classic leap year calculation - if the year is:
  // evenly divisible by 4 and not evenly divisible by 100
  // or evenly divisible by 400, then it is a leap year, otherwise not

  if ( ((yr % 4 == 0) && (yr % 100 != 0)) || (yr % 400 == 0) ) {
     return true;
  } 
  else { 
    return false;
  }
} 

//check for valid inquiry Date (3 years in past, any future date)
function validateInquiryDate(str) {
  
  // if not an int, toss
  if (isInteger(str)== false) {
    return false;
  }
  // if an int, check if date is not older than 3 years
  if (isInteger(str)== true) {
    var dt = new Date();
    var yr = dt.getFullYear(); 
    if (str < (yr - 3)) {
      return false;
    }
  }
  else { 
    return true; 
  }
}

/* Function to autotab to next field, used primarily for 3 field dates
   object: The input object (this)
   event: Either 'up' or 'down' depending on the keypress event
   length: Max length of field - tab when input reaches this length
   nextField: input object to get focus after this one
*/


 function TabNextByIndex (field,event,length) {

    // set the default field length
    var fieldLength = 0;

    // if onKeyDown, get the passed in length of the field
    if (event == "down") {	  
      fieldLength = field.value.length;
    }
  	// if onKeyUp, 
    else if (event == "up") {	
      
      // check the field length, and if wrong set it correctly
      if (field.value.length != fieldLength) { 
  			fieldLength = field.value.length; 
      } 
  	  // if the field length is correct
      if (fieldLength == length) {  
        
  		  // loop through all the form field elements
        for (i=0 ; i < field.form.elements.length ; i++)  { 
          // match the current field with it's index
          if (field == field.form.elements[i]) {  
            // if add one to current field index to go to next field
              field.form.elements[++i].focus();
              return;   
          }
  		} 
  	  } 
    }
  }  

   // popup script for public site windows, etc 
   function popUpPublic(url) {
     window.open(url,'pop','left=20,top=20,screenX=0,screenY=0,resizable=1,width=775,height=450,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,copyhistory=no');
    // return false;
   }
   
  // popup script for "kiosk" mode (small window, no menus, address bar, etc.)
  function popUpKiosk(url) {
     window.open(url,'help','left=20,top=20,screenX=0,screenY=0,resizable=1,width=600,height=450,toolbar=no,location=no,directories=no,status=yes,menubar=yes,scrollbars=yes,resizable=yes,copyhistory=no');
    // return false;
   }
   





// check if state abbreviation is a valid state
  var STATES = new Array("AL","AK","AS","AZ","AR","CA","CO","CT",
    "DE","DC","FM","FL","GA","GU","HI","ID","IL","IN","IA","KS",
    "KY","LA","ME","MH","MD","MA","MI","MN","MS","MO","MT","NE",
    "NV","NH","NJ","NM","NY","NC","ND","MP","OH","OK","OR","PW",
    "PA","PR","RI","SC","SD","TN","TX","UT","VT","VI","VA","WA",
    "WV","WI","WY","AE","AA","AE","AE","AE","AP");
   
  function validateStateAbbreviation(str) {  
    var st = str.toUpperCase();
    for (var i = 0; i < STATES.length; i++)
      if (STATES[i] == st) return true;
    return false;
  }


// check for valid Claim Number
function validateClaimNumber(str) {
  // check if integers
  if(isInteger(str)== false) {
    return false;
  } 
  // check if 11 numbers
  if(isInteger(str)== true) {
    if(str.length != 11) {
      return false;
    }
  }
}


// check for valid Claim Number
function validateRiderNumber(str) {
  // should be limited to 
  if(str.length > 6) {
    return false;
  }
}

//============= End Validation Rules ========================



//=============Begin Formatting functions ===================
    
// format day or month with leading zero if single digit
function formatLeadingZero(str) {
 if(str.length == 1 && str > 0 && str < 10) {
  str = 0 + str;
  return str;
 } else {
  return str;
 }
}

function formatPhone(str){
 str = strip("*() -./_\n\r\t\\",str);
 if(str.length==10)
  return reformat(str,"(",3,") ",3,"-",4);
 /*if(str.length==7)
  return reformat(str,"",3,"-",4);
  */
}
function formatSSN(str){
 str = strip(" -.\n\r\t",str);
 // no dashes for IBM
 //return reformat(str,"",3,"-",2,"-",4);
 //return reformat(str,"",3,"-",2,"-",4);
 return str;
}
function formatZip(str){
 str = strip("- \n\r\t",str);
 if(str.length==5)
  return str;
 if(str.length==9)
  return reformat(str,"",5,"-",4);
}
function formatCC(str,type){
 str = strip("-./_\n\r\t\\",str);
 switch(type){
  case "1": 
   return reformat(str,"",4,"-",4,"-",4,"-",4);
   break;
  case "2": 
   return reformat(str,"",4,"-",4,"-",4,"-",4);
   break;
  case "3": 
   return reformat(str,"",4,"-",4,"-",4,"-",4);
   break;
  case "4":
   return reformat(str,"",4,"-",6,"-",5);
 }
}


function formatDate(str,style){
 var dateVar = new Date(str);
 var year = dateVar.getFullYear();
 if(year<10)
  year += 2000;
 if(year<100)
  year += 1900;
 switch(style){
  case "MM/DD/YY":
   return (dateVar.getMonth() + 1) + "/" + dateVar.getDate() + "/" + year;
   break;
  case "DD/MM/YY":
   return dateVar.getDate() + "/" + (dateVar.getMonth() + 1) + "/" + year;
   break;
  case "Month Day, Year":
   return getMonthName(dateVar) + " " + dateVar.getDate() + ", " + year;
   break;
  case "Day, Month Day, Year":
   return getDayName(dateVar) + ", " + getMonthName(dateVar) + " " + dateVar.getDate() + ", " + year;
   break;
  default:
   return (dateVar.getMonth() + 1) + "/" + dateVar.getDate() + "/" + year;
   break;
 }
}

// format 2 digit year
function formatYear(str) {
  str = strip("-./_\n\r\t\\",str);
  if (isInteger(str) == false) {
    return false;
  }
  if(str.length == 2) {
    if(str < 50 ) {
      str = "20" + str;
      return str;
    } 
    if(str >= 50 ) {
      str = "19" + str;
      return str;
    }  
  }
  else {
    return str;
  }
}



