 // -----------------------------------------------------------------------
 // Collection of utility and validation methods.
 // -----------------------------------------------------------------------
  
 var alphaPattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
 var alphanumericPattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
 var numericPattern = "0123456789";
  
 function selectOption(selectobject, v)
 {  
   for (var i=0; i<selectobject.length; i++)
   {
     if (selectobject.options[i].value == v)
     {
       selectobject.selectedIndex = i;
       break;
     }
   }
 }
 
 function selectChecked(radioObj, v)
 {    
    for(var i = 0; i < radioObj.length; i++) 
    {
      if (radioObj[i].value == v)
      {
        radioObj[i].checked = true;
        return;
      }      
    }       
 }
 
 function getCheckedValue(radioObj) 
 {
    if (!radioObj)
        return "";
        
    var radioLength = radioObj.length;
    
    if (radioLength == undefined)
    {
      if (radioObj.checked)
        return radioObj.value;
    }
    else
    {
      for(var i = 0; i < radioLength; i++) 
      {
        if (radioObj[i].checked)
          return radioObj[i].value;
      }
    }
    
    return "";
 }

 // Parmeter 'array' has to be literal 'true' or 'false'.
 
 function getMultipleSelection(obj, array)
 {
    var selected = new Array();
    
    for(j = 0; j < obj.length; j++)    
      if (obj.options[j].selected)        
         selected.push(obj.options[j].value);        
       
    if (array != 'true')    
      return selected.toString();     
    else 
      return selected; 
 } 

 // -----------------------------------------------------------------------
 // Triming functions
 // -----------------------------------------------------------------------
 
 function trim( str)
 {
   if(str==null || str.length==0) { return str; }
   found=false;
   stIdx = 0;
  
   while( str.charAt(stIdx)==" " ) { stIdx++; found=true;}
   endIdx = str.length;
  
   while( str.charAt(endIdx-1)==" " ) { endIdx--; found=true;}
   
   if( endIdx<=stIdx )  
     return "";   
   else
   if( found )  
     return str.substring(stIdx,endIdx);  
   
   return str;  
 }
 
 // Removes leading whitespaces
 function trimLeftWhitespaces( value ) {

    var re = /\s*((\S+\s*)*)/;
    return value.replace(re, "$1");
 }

 // Removes ending whitespaces
 function trimRightWhitespaces( value ) {
    
    var re = /((\s*\S+)*)\s*/;
    return value.replace(re, "$1"); 
 }

 // Removes leading and ending whitespaces
 // \s matches whitespace (short for [\f\n\r\t\v\u00A0\u2028\u2029]).
 // \S matches anything but a whitespace (short for [^\f\n\r\t\v\u00A0\u2028\u2029]).

 function trimWhitespaces( value ) {
    
    return trimLeftWhitespaces(trimRightWhitespaces(value));    
 }

 function trimNum( str)
 { 
   //neg = str.CharAt(0) == '-' ? true : false;
   //if(str.charAt(0) == '+'){ stIdx++;}
   
   str1 = trim(str);
   if(str1==null || str1.length==0) { return str1; }
   found=false;
   stIdx = 0;
   while( str1.charAt(stIdx)=="0" ) { stIdx++; found=true;}
   
   if( found ) 
   {
     if (stIdx < str1.length)  
       str1 = str1.sub(stIdx);
     else 
       str1 = "";
   }
   
   return str1
 }
 
 // -----------------------------------------------------------------------
 // Basic validations
 // -----------------------------------------------------------------------
 
 function isEmpty( str)
 {
    if (str.length == 0)
      return true;
    else
    {     
      s = trim(str);
      
      if (s.length == 0)
        return true;
      else
        return false;
    }
 }
 
 function validatePattern(checkStr, pattern)
 {
   len2 = pattern.length;
   found=true;
   for (i = 0;  found & (i < len);  i++)
   {
      ch = checkStr.charAt(i);
      found = false;
      for (j = 0;  j < len2;  j++)
      {
        if (ch == pattern.charAt(j))
        {
          found = true;
          break;
        } 
      }
   }

   return found 
 }
 
 function isDigits_Only( checkStr )
 {
   if( checkStr==null || (len=checkStr.length)==0 ){return false;}
 
   return validatePattern( checkStr, numericPattern);  
 } 
 
 function isDigits_And( checkStr, pat )
 {
   if( checkStr==null || (len=checkStr.length)==0 ){return false;}
 
   return validatePattern( checkStr, numericPattern+pat);  
 } 
 
 function isAlpha_Only( checkStr )
 {
   if( checkStr==null || (len=checkStr.length)==0 ){return false;}
 
   return validatePattern( checkStr, alphaPattern);  
 }
 
 function isAlpha_And( checkStr, pat )
 {
   if( checkStr==null || (len=checkStr.length)==0 ){return false;}
 
   return validatePattern( checkStr, alphaPattern+pat);  
 }
  
 function isAlphaNum_Only( checkStr )
 {
    if( checkStr==null || (len=checkStr.length)==0 ){return false;}
  
    return validatePattern( checkStr, alphanumericPattern);  
 }
  
 function isAlphaNum_And( checkStr, pat )
 {
    if( checkStr==null || (len=checkStr.length)==0 ){return false;}
  
    return validatePattern( checkStr, alphanumericPattern+pat);  
 }
  
 function validatePosNumber( num, max, scale)
 {
    len = num.length;
    if (len == 0 || 
        !isDigits_And(num,".") ||
        isNaN(num) )
      return (false);

    decIdx = num.lastIndexOf(".");
    
    if( decIdx != -1 &&
        (len-1-decIdx > scale ))
      return false;
          
    if( (num > max) || (num < 0.001) )
      return false;
        
    return true; 
 }
 
 function validateNumber( num, min, max, scale)
 {    
    len = num.length;
    if (len == 0        || 
        !isDigits_And(num,".") ||
        isNaN(num) )    
      return (false);          

    decIdx = num.lastIndexOf(".");
       
    if (decIdx != -1 &&
       (len - 1 - decIdx > scale ))
      return false;    
      
    if( (num > max) || (num < min) )
      return false;
    
    return true; 
 }

 function validateDecimal( num, scale)
 {    
    len = num.length;
    if (len == 0        || 
        !isDigits_And(num,".") ||
        isNaN(num) )    
      return (false);          

    decIdx = num.lastIndexOf(".");
       
    if (decIdx != -1 &&
       (len - 1 - decIdx > scale ))
      return false;
      
    return true;
 }
      
 function AllowNumbersOnly()
 {
    if ((event.keyCode >= 48) && (event.keyCode <= 57))
    { event.returnValue = true; return; }
    else { event.returnValue = false; return; }
 } 
 
 // -----------------------------------------------------------------------
 // End Date validation for today's date - RCK retaining period days
 // -----------------------------------------------------------------------
 function validateEndRP(theForm)
 {
    var cur = trim(theForm.end_date.value);
    var end = new Date(cur);
    
    var dtRP = new Date();
    dtRP.setDate(dtNow.getDate()-365);
    
    if(end > dtRP)
    {
        alert("Ending Date must not exceed today's date - 365 days ");
        theForm.end_date.focus();
        return (false);      
    }
    
    return true;
 }
 // -----------------------------------------------------------------------
 // Start and End Date validation
 // -----------------------------------------------------------------------
 function validateStartEnd(theForm)
{
    var cur = trim(theForm.start_date.value);
    if (!validateDate(cur))
    {
        alert("Please enter valid Beginning Date value as MM/DD/YYYY");
        theForm.start_date.focus();
        return false;
    }
    var start = new Date(cur);
    
    cur = trim(theForm.end_date.value);
    if (!validateDate(cur))
    {
        alert("Please enter valid Ending Date value as MM/DD/YYYY");
        theForm.end_date.focus();
        return false;
    }
    var end = new Date(cur);
    
    if(end < start)
    {
        alert("Ending Date must not be less than Starting Date");
        theForm.start_date.focus();
        return false;    
    }
    
    dtNow = new Date();
    if(end > dtNow)
    {
        alert("Ending Date must not exceed today's date");
        theForm.end_date.focus();
        return (false);      
    }
    
    return true;
}

// Default start date to this day in previous month
function setStartDate(theForm)
{
    dt = parseDate(theForm.start_date.value );
    if (dt == null)
    {     
        dt = new Date();
        year = dt.getFullYear();
        month = dt.getMonth();    // 0 based
        day = dt.getDate();       // 1 based
        
        if (month == 0)
        {
            year = year - 1;
            month = 11;
        }
        else
            month = month - 1;
        
        dt = new Date(year, month, day);
        ds = formatDate(dt, "MM/dd/yyyy");
        theForm.start_date.value = ds;
    }
}

// Default end date to today's date
function setEndDate(theForm)
{
    dt = parseDate(theForm.end_date.value );
    if (dt == null)
    {     
        dt = new Date();    
        ds = formatDate(dt, "MM/dd/yyyy");  
        theForm.end_date.value = ds;
    }
}

 // -----------------------------------------------------------------------
 // Date validation (see CalendarPopup.js)
 // -----------------------------------------------------------------------
 
 function validateDate(date)
 {
   var date1 = new Date(date ); 
   //alert("date1=" + date1)
   if( isNaN(date1) )   
     return false; 
      
   var Date_array = date.split( '/' );
    
   if( Date_array[0].length>2 || 
       Date_array[1].length>2 ||
       Date_array[2].length>4)   
     return false;   
     
   month = date1.getMonth();
   if( Date_array[0] != (month+1) ) { return false; }
 
   year  = date1.getYear();
 
   var yearOk = false
 
   if( isMicrosoft(3) )   
     yearOk = (year >= 2000) && ( year < 2013);    
   else if( isNetscape(3) )   
     yearOk = (year >= 100) && ( year < 113);    
 
   if(!yearOk)
   {
     alert("Year should be a value in range of 2000-2012 ");
     //alert("IGOR, Write it down:\r\n strDate=" + date+"\r\njsDate=" + date1+"\r\n date1.getYear()="+year);
     return false
   } 
  
   return true;
 }
 
 // -------------------------------------------------------------------
 // compareDateToCurrent(date1, dateformat1)
 //
 //   Returns:
 //   1 if date1 is greater than current date
 //   0 if current date is greater than date1 of if they are the same
 //  -1 if either of the dates is in an invalid format
 // -------------------------------------------------------------------

 function compareDateToCurrent(date1,dateformat1)
 {
    var d1=getDateFromFormat(date1,dateformat1);
    
    curDate = new Date();    
    var d2 = curDate.getTime();
    
    if (d1==0 || d2==0) 
      return -1;        
    else if (d1 > d2) 
      return 1;
        
    return 0;
 }

 // -----------------------------------------------------------------------
 // Browser check (see 'browser.js')
 // -----------------------------------------------------------------------

 function isNetscape(v) 
 {
    /*
    ** Check if the browser is Netscape compatible
    **    v  version number
    ** returns  true if Netscape and version equals or greater
    */
    return isBrowser("Netscape", v);
 }
 
 function isMicrosoft(v) 
 {
    /*
    ** Check if the browser is Microsoft Internet Explorer compatible
    **    v  version number
    ** returns  true if MSIE and version equals or greater
    */
    return isBrowser("Microsoft", v);
 }
 
 function isBrowser(b,v) 
 {
    /*
    ** Check if the current browser is compatible
    **  b  browser name
    **  v  version number (if 0 don't check version)
    ** returns true if browser equals and version equals or greater
    */
    browserOk = false;
    versionOk = false;
 
    browserOk = (navigator.appName.indexOf(b) != -1);
    if (v == 0) versionOk = true;
    else  versionOk = (v <= parseInt(navigator.appVersion));
    return browserOk && versionOk;
 }
  
 // -----------------------------------------------------------------------
 // Additional validations - FORMAT functions
 // -----------------------------------------------------------------------
 
 function validateZIP(field) 
 {
   var valid = "0123456789-";
   var hyphencount = 0;
   var msg = "Please enter your 5 or 5+4 digits zip code\r\n in XXXXX or XXXXX-XXXX format.";
  
   if (field.length!=5 && field.length!=10) 
   {
     alert(msg);
     return false;
   }
   
   for (var i=0; i < field.length; i++) 
   {
     temp = "" + field.substring(i, i+1);
     if (temp == "-") hyphencount++;
     if (valid.indexOf(temp) == "-1") 
     {
       alert("Invalid characters in your zip code.\r\n" + msg);
       return false;
     }
   
     if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) 
     {
       alert("Invalid format in your zip code.\r\n" + msg);
       return false;
     }
   }
   
   return true;
 }

 function formatSSN( ssnString )
 {
   var ssn = ssnString.replace(/(-)/g,"")
   if( (ssn.length!=9) || isNaN(ssn) )
   {
     alert("Please enter your 9-digits SSN or TAX id number");
     return "";
   }
  
   return ssn;
 }
  
 function formatSSN_2( ssnString )
 {
   var ssn = ssnString.replace(/(-)/g,"")
   if( (ssn.length!=9) || isNaN(ssn) )
   {
     alert("Please enter your 9-digits SSN or TAX id number");
     return "";
   }
  
   return frmSSN = ssn.substring(0,3) + '-' + ssn.substring(3,5) + '-' + ssn.substr(5)
 }
 
 function formatAsPhone( phString )
 {
    if(phone.length == 10)
      return frmPhone = phone.substring(0,3) + '-' + phone.substring(3,6) + '-' + phone.substr(6);
    else
      return frmPhone;  
 }
  
 function formatPhone( phString )
 {
   var phone = phString.replace(/[\-\(\)]/g,"")

   if( (phone.length!=10) || isNaN(phone) )
   {
     alert("Please enter area code and phone number.\r\n Use '(',')' or '-' as separators");
     return "";
   }
  
   return phone;
 }
 
 function formatFax( faxString )
 {
   var fax = faxString.replace(/[\-\(\)]/g,"")

   if( (fax.length!=10) || isNaN(fax) )
   {
     alert("Please enter area code and fax number.\r\n Use '(',')' or '-' as separators");
     return "";
   }
  
   return fax;
 }
  
 function validateEmail( emString )
 {
   if ( emString==null           || 
        emString.length==0       || 
       !isAlphaNum_And( emString, "-_@.~" ))
   {
      alert("Please enter e-mail address using letters, digits, periods and \'@-~\' characters only. ");
      return false;
   }
   
   return emailCheck (emString);
  
   // return true; 
 }
 
 //
 // CalendarPopup.js has to be referenced to use this function
 //
  
 function formatInputDate(dateField)
 {
   if (!isEmpty(dateField.value))
   {
      var d1 = getDateFromFormat(dateField.value, "MM/dd/yyyy");
      if (d1 != 0)
        dateField.value = formatDate(new Date(d1), value="MM/dd/yyyy");
      else
      {
        alert("Please correct the wrong date format");
        dateField.focus();
      }
   }
 }

 function nothing(){}

 // ------------------------------------------------------------------------------
 // This script and many more are available free online at 
 // The JavaScript Source!! http://javascript.internet.com
 
 // V1.1.3: Sandeep V. Tamhankar (stamhankar@hotmail.com)
 // Original:  Sandeep V. Tamhankar (stamhankar@hotmail.com)
 // Changes:
 // 1.1.4: Fixed a bug where upper ASCII characters (i.e. accented letters
 // international characters) were allowed.
 
 // 1.1.3: Added the restriction to only accept addresses ending in two
 // letters (interpreted to be a country code) or one of the known
 // TLDs (com, net, org, edu, int, mil, gov, arpa), including the
 // new ones (biz, aero, name, coop, info, pro, museum).  One can
 // easily update the list (if ICANN adds even more TLDs in the
 // future) by updating the knownDomsPat variable near the
 // top of the function.  Also, I added a variable at the top
 // of the function that determines whether or not TLDs should be
 // checked at all.  This is good if you are using this function
 // internally (i.e. intranet site) where hostnames don't have to 
 // conform to W3C standards and thus internal organization e-mail
 // addresses don't have to either.
 // Changed some of the logic so that the function will work properly
 // with Netscape 6.
 
 // 1.1.2: Fixed a bug where trailing . in e-mail address was passing
 // (the bug is actually in the weak regexp engine of the browser; I
 // simplified the regexps to make it work).
  
 // 1.1.1: Removed restriction that countries must be preceded by a domain,
 // so abc@host.uk is now legal.  However, there's still the 
 // restriction that an address must end in a two or three letter
 // word.
 
 // 1.1: Rewrote most of the function to conform more closely to RFC 822.
 
 // 1.0: Original
 // 
  
 function emailCheck (emailStr) {
 
 /* The following variable tells the rest of the function whether or not
 to verify that the address ends in a two-letter country or well-known
 TLD.  1 means check it, 0 means don't. */
 
 var checkTLD=0;
 
 /* The following is the list of known TLDs that an e-mail address must end with. */
 
 var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
 
 /* The following pattern is used to check if the entered e-mail address
 fits the user@domain format.  It also is used to separate the username
 from the domain. */
 
 var emailPat=/^(.+)@(.+)$/;
 
 /* The following string represents the pattern for matching all special
 characters.  We don't want to allow special characters in the address. 
 These characters include ( ) < > @ , ; : \ " . [ ] */
 
 var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
 
 /* The following string represents the range of characters allowed in a 
 username or domainname.  It really states which chars aren't allowed.*/
 
 var validChars="\[^\\s" + specialChars + "\]";
 
 /* The following pattern applies if the "user" is a quoted string (in
 which case, there are no rules about which characters are allowed
 and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
 is a legal e-mail address. */
 
 var quotedUser="(\"[^\"]*\")";
 
 /* The following pattern applies for domains that are IP addresses,
 rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
 e-mail address. NOTE: The square brackets are required. */
 
 var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
 
 /* The following string represents an atom (basically a series of non-special characters.) */
 
 var atom=validChars + '+';
 
 /* The following string represents one word in the typical username.
 For example, in john.doe@somewhere.com, john and doe are words.
 Basically, a word is either an atom or quoted string. */
 
 var word="(" + atom + "|" + quotedUser + ")";
 
 // The following pattern describes the structure of the user
 
 var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
 
 /* The following pattern describes the structure of a normal symbolic
 domain, as opposed to ipDomainPat, shown above. */
 
 var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
 
 /* Finally, let's start trying to figure out if the supplied address is valid. */
 
 /* Begin with the coarse pattern to simply break up user@domain into
 different pieces that are easy to analyze. */
 
 var matchArray=emailStr.match(emailPat);
 
 if (matchArray==null) {
 
 /* Too many/few @'s or something; basically, this address doesn't
 even fit the general mould of a valid e-mail address. */
 
 alert("Email address seems incorrect (check @ and .'s)");
 return false;
 }
 var user=matchArray[1];
 var domain=matchArray[2];
 
 // Start by checking that only basic ASCII characters are in the strings (0-127).
 
 for (i=0; i<user.length; i++) {
 if (user.charCodeAt(i)>127) {
 alert("Email username contains invalid characters.");
 return false;
    }
 }
 for (i=0; i<domain.length; i++) {
 if (domain.charCodeAt(i)>127) {
 alert("Email domain name contains invalid characters.");
 return false;
    }
 }
 
 // See if "user" is valid 
 
 if (user.match(userPat)==null) {
 
 // user is not valid
 
 alert("Email username doesn't seem to be valid.");
 return false;
 }
 
 /* if the e-mail address is at an IP address (as opposed to a symbolic
 host name) make sure the IP address is valid. */
 
 var IPArray=domain.match(ipDomainPat);
 if (IPArray!=null) {
 
 // this is an IP address
 
 for (var i=1;i<=4;i++) {
 if (IPArray[i]>255) {
 alert("Email Destination IP address is invalid!");
 return false;
    }
 }
 return true;
 }
 
 // Domain is symbolic name.  Check if it's valid.
  
 var atomPat=new RegExp("^" + atom + "$");
 var domArr=domain.split(".");
 var len=domArr.length;
 for (i=0;i<len;i++) {
 if (domArr[i].search(atomPat)==-1) {
 alert("Email domain name does not seem to be valid.");
 return false;
    }
 }
 
 /* domain name seems valid, but now make sure that it ends in a
 known top-level domain (like com, edu, gov) or a two-letter word,
 representing country (uk, nl), and that there's a hostname preceding 
 the domain or country. */
 
 if (checkTLD && domArr[domArr.length-1].length!=2 && 
 domArr[domArr.length-1].search(knownDomsPat)==-1) {
 alert("Email address must end in a well-known domain or two letter " + "country.");
 return false;
 }
 
 // Make sure there's a host name preceding the domain.
 
 if (len<2) {
 alert("Email address is missing a hostname!");
 return false;
 }
 
 // If we've gotten this far, everything's valid!
 return true;
}
