/*************************************************************************************************/
/* Date / Time Functions.                                                                        */
/*************************************************************************************************/

function getMonthName(i)
{
  var theMonths = new Array('January','February','March','April','May','June','July','August','September','October','November','December') ;
  return theMonths[i] ;
}

function getDayName(i)
{
  var theDays   = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday') ;
  return theDays[i] ;
}

function dateDiff(str,datepart)
{
  //Parameter 'str' must be a valid JavaScript date time value, ie: 'August,31,2003'.
  //Parameter 'datepart' should be 'days' or 'years', which ever format you wish returned.

  var dateNow    = new Date() ;
  var targetDate = new Date(str) ;

  //Find date difference in milliseconds
  var diff = dateNow.getTime() - targetDate.getTime() ;

  //Convert difference from milliseconds to days
  diffDays = Math.abs(Math.floor(diff / (1000 * 60 * 60 * 24))) ;

  //Convert difference from milliseconds to years
  diffYears = Math.abs(Math.floor(diff / (1000 * 60 * 60 * 24 * 365.2425))) ;

  if (datepart=='days')
  {
    return diffDays ;
  }
  else
  {
    return diffYears ;
  }
}

function findDaysOfMonth()
{
  //Find number of days in each month
  var i = 0;
  this[i++] = 0;  //Initialize
  this[i++] = 31; //January
  this[i++] = 29; //February
  this[i++] = 31; //March
  this[i++] = 30; //April
  this[i++] = 31; //May
  this[i++] = 30; //June
  this[i++] = 31; //July
  this[i++] = 31; //August
  this[i++] = 30; //September
  this[i++] = 31; //October
  this[i++] = 30; //November
  this[i  ] = 31; //December
  this.length = i;
}

function howOld(mm,dd,yy)
{
  //DOB
  var monthArray = new findDaysOfMonth();
  var birthYear  = parseInt(yy);         // Year of birth (4 digits)
  var birthMonth = parseInt(mm);         // Month of birth (1-12)
  var birthDate  = parseInt(dd);         // Date of birth (1-31)
  var ageMonths  = 0;                      // Age in Months

  //Check for invalid DOB
  //if (monthArray[birthMonth] < birthDate || birthDate < 1) return -1;

  //Current Date
  var newDate    = new Date();             // Get current date
  var thisYear   = newDate.getFullYear();  // Get year of current
  var thisMonth  = newDate.getMonth() + 1; // Get month of current
  var thisDate   = newDate.getDate();    // Get date of current

  var age = thisYear - birthYear;

  //Had birthday yet?
  if ((thisMonth < birthMonth) || (birthMonth == thisMonth && thisDate < birthDate)) age -- ;


  // Calculate age in months if less than 1 year old
  if (age < 1)
  {
  if (thisYear == birthYear)
  {
    ageMonths = thisMonth - birthMonth ;
    }

  if (thisYear > birthYear)
  {
    ageMonths = 12 - birthMonth + thisMonth ;
    }

    //Had "Monthly Birthday" yet?
    if (thisDate < birthDate)
    {
      ageMonths = ageMonths - 1 ;
    }

    if (ageMonths == 1)
    {
    //Only one month old? Drop the "s" from "months "
      age = ageMonths + " month" ;
    }
    else age = ageMonths + " months " ;
  }
  else
  {
    if (age == 1)
    {
      age = age + " year " ;
    }

    if (age > 1)
    {
    age = age + " years " ;
    }
  }

  return age;
}

// End How Old -->

//Opens a mini window
function openWin(URL)
{
  aWindow = window.open(URL,"thewindow","height=425,width=550,location=no,scrollbars=yes,screenX=0,screenY=0,left=0,top=0,menubars=no,toolbars=no,resizable=no");
}

//page redirect
function redirect(URL)
{
  window.location=URL ;
}

/*************************************************************************************************/

//Current time, updated every second.
function theClock()
{
  if (!document.layers && !document.all)
  return;

  var newTime    = new Date();
  var theHours   = newTime.getHours();
  var theMinutes = newTime.getMinutes();
  var theSeconds = newTime.getSeconds();
  var AmOrPm     = "AM";

  if (theHours >= 12)
  {
    AmOrPm = "PM";
    theHours = theHours - 12;
  }

  if (theHours == 0)
  {
    theHours = 12;
  }

  if (theMinutes <= 9)
  {
    theMinutes = "0" + theMinutes;
  }

  if (theSeconds <= 9)
  {
    theSeconds = "0" + theSeconds;
  }

  theTime = theHours + ":" + theMinutes + ":" + theSeconds + " " + AmOrPm ;

  if (document.layers)
  {
    document.layers.clock.document.write(theTime);
    document.layers.clock.document.close();
  }
  else if (document.all)
  {
    clock.innerHTML = theTime ;
  }

  setTimeout("theClock()", 1000)

}

/*************************************************************************************************/

// Time of Day Greeting
function Greeting()
{
  var newTime    = new Date();
  var theHours   = newTime.getHours();
  var Greeting   = "Good Morning!";

  if (theHours >= 12)
  {
    Greeting = "Good Afternoon!";
    if (theHours >= 17)
    {
      Greeting = "Good Evening!"
    }
  }
  return Greeting ;
}

/*************************************************************************************************/

//Formats current date in Day, Month Day of Month, Year format (ie: Monday, January 13, 2003)
function getCurrentDate()
{

  var thisDate = new Date() ;

  var curYear  = thisDate.getFullYear() ;
  var curMonth = getMonthName(thisDate.getMonth()) ;
  var curDate  = thisDate.getDate() ;
  var curDay   = getDayName(thisDate.getDay()) ;

  var dateNow = curDay + ", " + curMonth + " " + curDate + ", " + curYear ;

  return dateNow ;
}

/*************************************************************************************************/

// Declaring valid date character, minimum year and maximum year
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 validEmail(checkEmail)
{
  if ((checkEmail.indexOf('@') < 0) || ((checkEmail.charAt(checkEmail.length-4) != '.') && (checkEmail.charAt(checkEmail.length-3) != '.'))) 
  {
    return false ;
  }  
  return true ;
}

//Remove character list in bag from string s, return new string.
function compress(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++)
  {
    if (i==4 || i==6 || i==9 || i==11)
    {
      this[i] = 30 ;
    }

  if (i==2) ;
    {
      this[i] = 29 ;
    }

  if (i==1 || i==3 || i==5 || i==7 || i==8 || i==10 || i==12)
  {
    this[i] = 31 ;
  }
  }

  return this ;
}

/*************************************************************************************************/

function isDate(dtStr, label)
{
  if (dtStr == "")
  {
    return true ;
  }

  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 <= 3; i++)
  {
    if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1) ;
  }

  month=parseInt(strMonth) ;
  day=parseInt(strDay) ;
  year=parseInt(strYr) ;

  if (pos1==-1 || pos2==-1)
  {
    alert("The date format should be : mm/dd/yyyy for " + label) ;
    return false ;
  }

  if (strMonth.length<1 || month<1 || month>12)
  {
    alert("Please enter a valid month for " + label) ;
    return false ;
  }

  if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
  {
    alert("Please enter a valid day for " + label) ;
    return false ;
  }

  if (strYear.length != 4 || year==0 || year<minYear || year>maxYear)
  {
    alert("Please enter a valid 4 digit year between " + minYear + " and " + maxYear + " for " + label) ;
    return false ;
  }

  if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(compress(dtStr, dtCh))==false)
  {
    alert("Please enter a valid date for " + label) ;
    return false ;
  }

  return true ;
}

/*************************************************************************************************/

//Return the selected value of a radio button group
function radioValue(radioGroup)
{
  radio = radioGroup;
  for (i=0; i < radio.length; i++)
  {
    if (radio[i].checked)
    {
      return radio[i].value ;
    }
  }
  //No value selected
  return undefined ;
}

/*************************************************************************************************/
//Enable Single Check Boxes
function enableCheckBox(checkbox)
{
    checkbox.disabled = false ;
}

/*************************************************************************************************/
//Disable Single Check Boxes
function disableCheckBox(checkbox)
{
    checkbox.disabled = true ;
    checkbox.checked  = false ;
}

/*************************************************************************************************/
//Enable Radio Buttons
function enableRadio(radioGroup)
{
  radio = radioGroup ;

  for (i=0; i < radio.length; i++)
  {
    radio[i].disabled = false ;
  }
}

/*************************************************************************************************/
//Disable Radio Buttons
function disableRadio(radioGroup)
{
  radio = radioGroup;

  for (i=0; i < radio.length; i++)
  {
    radio[i].disabled = true ;
    radio[i].checked  = false ;
  }
}

/*************************************************************************************************/
//Enable other form elements (select, textbox, password)
function enable(element)
{
  //Enable element and set color to white
  element.disabled = false ;
  element.style.backgroundColor= "#FFFFFF" ;
}

/*************************************************************************************************/
//Disable other form elements (select, textbox, password)
function disable(element)
{
  //Disable element and set color to gray
  element.disabled = true ;
  element.style.backgroundColor= "#CCCCCC" ;
}

/*************************************************************************************************/

//Make sure string only contains characters in allowed.
function isValid(source, allowed)
{
  for (var i=0; i< source.length; i++)
  {
    if (allowed.indexOf(source.charAt(i)) == -1)
    {
      return false;
    }
  }
  return true ;
}
/*************************************************************************************************/

function checkMissing(field, label)
{
  if ((field == " ") || (field==""))
  {
    alert("Please enter a value for " + label) ;
    return false ;
  }
  return true ;
}

/*************************************************************************************************/
//Strip leading and trailing spaces from string.
function trim(sInString)
{
  // strip leading spaces
  sInString = sInString.replace( /^\s+/g, "" ) ;

  // strip trailing spaces
  return sInString.replace( /\s+$/g, "" ) ;
}

/*************************************************************************************************/
//Validate phone number :  All numeric, correct length
function validPhone(areacode, prefix, suffix, label)
{
  if ((isNaN(areacode)) || (areacode.length != 3))
  {
    alert("Invalid " + label + ". Please enter a valid areacode.") ;
    return false ;
  }

  if (isNaN(prefix) || prefix.length != 3)
  {
    alert("Invalid " + label + ". Please enter a valid prefix.") ;  
    return false ;
  }

  if (isNaN(suffix) || suffix.length != 4)
  {
    alert("Invalid " + label + ". Please enter a valid suffix.") ;
    return false ;
  }
  else
  {
    return true ;
  }
}

/*************************************************************************************************/

//Remove character list in bag from source, return new string.
function compress(source, 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 < source.length; i++)
  {
    var c = source.charAt(i);
    if (bag.indexOf(c) == -1) returnString += c;
  }

  return returnString;
}

/*************************************************************************************************/

//Strip leading and trailing spaces from source.
function trim(source)
{
  // strip leading spaces
  source = source.replace( /^\s+/g, "" ) ;

  // strip trailing spaces
  return source.replace( /\s+$/g, "" ) ;
}

/*************************************************************************************************/

//Strip leading spaces from source.
function ltrim(source)
{
  // strip leading spaces
  return source.replace( /^\s+/g, "" ) ;
}

/*************************************************************************************************/

//Strip trailing spaces from source.
function rtrim(source)
{
  // strip trailing spaces
  return source.replace( /\s+$/g, "" ) ;
}

/*************************************************************************************************/

function replaceStr(source, target, replacement)
{
  if (target == replacement)
  {
    return source ;
  }

  var newString = source ;

  while (newString.indexOf(target) > -1)
  {
    pos = newString.indexOf(target) ;
    newString = newString.substring(0, pos) + replacement + newString.substring((pos + target.length), newString.length) ;
  }

  return newString ;
}

function replaceDoubleQuotes(theForm)
{
  for (var i=0; i<theForm.elements.length; i++)
  {
    if (theForm.elements[i].type == 'text' || theForm.elements[i].type == 'hidden' || theForm.elements[i].type == 'textarea')
        {
          theForm.elements[i].value = replaceStr(theForm.elements[i].value, '"', "'") ;
        }
  }  
}
/*************************************************************************************************/

//Format Money as Integer.
function formatAsInt(string)
{
  string.value = compress(string.value, '$') ;
}

/*************************************************************************************************/

//Format number as U.S. Money.
function formatAsMoney(string)
{
  if (!isValid(string.value, '$.0123456789- '))
  {
    alert ("Field contains invalid characters.\nOnly numbers, dollar signs, minus signs, and decimals are allowed in this field") ;
    string.focus() ;
  }
  else
  {
    if ((trim(string.value) == '') || (compress(string.value, '$.0') == ''))
    {
      string.value = '$0.00' ;
    }

    else
    {
      var newStr = compress(string.value, '$ ') ;

      //Deal with decimal portion of number.
      var decPos = newStr.indexOf(".") ;

      if (decPos == -1)
      {
        var decimal = '.00' ;
        decPos = newStr.length ;
      }
      else
      {
        var decimal = trim(newStr.substring(decPos, newStr.length)) ;
      }
      var decimalPortion = decimal.substring(1,decimal.length) ;

      decimalPortion = compress(decimalPortion, '.') ;

      decimal = '.' + decimalPortion ;

      //Make sure decimal is two digits long.
      while (decimal.length < 3)
      {
        decimal = decimal + '0' ;
      }

      //Truncate Decimal to 2 digits
      if (decimal.length > 3)
      {
        decimal = decimal.substring(0,3) ;
      }

      //Deal with integer portion of number.
      var dollars = newStr.substring(0, decPos) ;

      while (dollars.indexOf("0") == 0)
      {
        dollars = dollars.substring(1, dollars.length) ;
      }

      if (dollars == '')
      {
        dollars = '0' ;
      }

      string.value = '$' + dollars + decimal ;
    }
  }
}

/*************************************************************************************************/

//Create a Random Number between 1 and maxnum
function createRandomNumber(maxnum)
{
  //Make sure required length is a number greater than zero.
  if ((maxnum < 1) || (isNaN(maxnum)))
  {
    alert ("Maximum Number must be a digit (1-9).") ;
    return " ";
  }

  //Create random number.
  var rand_num = Math.floor(Math.random() * maxnum) + 1 ;

  //Return random number.
  return rand_num ;
}

/*************************************************************************************************/

//Create a password reqLen characters long, mixed alpha and numeric.
function createPassword(reqLen)
{
  /* Enter the characters used to build password in an Array. The letters 'L', 'O', and 'I' as well as the
     numbers '0' and '1' have been removed because they are easily confused. Also, numeric values have been
     repeated so you are as likely to get a number as a letter.
  */

  alphaArray = new Array ;
  alphaArray[0]  = 'A' ;
  alphaArray[1]  = 'B' ;
  alphaArray[2]  = 'C' ;
  alphaArray[3]  = 'D' ;
  alphaArray[4]  = 'E' ;
  alphaArray[5]  = 'F' ;
  alphaArray[6]  = 'G' ;
  alphaArray[7]  = 'H' ;
  alphaArray[8]  = 'J' ;
  alphaArray[9]  = 'K' ;
  alphaArray[10] = 'M' ;
  alphaArray[11] = 'N' ;
  alphaArray[12] = 'P' ;
  alphaArray[13] = 'Q' ;
  alphaArray[14] = 'R' ;
  alphaArray[15] = 'S' ;
  alphaArray[16] = 'T' ;
  alphaArray[17] = 'U' ;
  alphaArray[18] = 'V' ;
  alphaArray[19] = 'W' ;
  alphaArray[20] = 'X' ;
  alphaArray[21] = 'Y' ;
  alphaArray[22] = 'Z' ;
  alphaArray[23] = '2' ;
  alphaArray[24] = '3' ;
  alphaArray[25] = '4' ;
  alphaArray[26] = '5' ;
  alphaArray[27] = '6' ;
  alphaArray[28] = '7' ;
  alphaArray[29] = '8' ;
  alphaArray[30] = '9' ;
  alphaArray[31] = '2' ;
  alphaArray[32] = '3' ;
  alphaArray[33] = '4' ;
  alphaArray[34] = '5' ;
  alphaArray[35] = '6' ;
  alphaArray[36] = '7' ;
  alphaArray[37] = '8' ;
  alphaArray[38] = '9' ;
  alphaArray[39] = '2' ;
  alphaArray[40] = '3' ;
  alphaArray[41] = '4' ;
  alphaArray[41] = '5' ;
  alphaArray[41] = '6' ;
  alphaArray[41] = '7' ;
  alphaArray[41] = '8' ;

  //Make sure desired length is a number greater than zero.
  if ((reqLen < 1) || (isNaN(reqLen)))
  {
    alert ("Desired Password Length must be a digit > 0.") ;
    return ;
  }

  //Create variable to hold password string.
  var password = '' ;

  //Iterate thru alphaArray, building password one character at a time until password is desired length.
  while (password.length < reqLen)
  {
    //Generate Random Number between 0 and the length of the alphaArray
    var i = Math.floor(Math.random() * alphaArray.length) ;

    //Next character in password is a random index in the array.
    password = password + alphaArray[i] ;
  }

  //Return the completed password.
  return password ;

}
