var digits = "0123456789";
var lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
var upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var whiteSpace = " \t\n\r";
var decimalPointDelimiter = ".";
var phoneNumberDelimiters = "()- \t";
var validPhoneChars = digits + phoneNumberDelimiters;
var ssnDelimiters = "- \t";
var irsDelimiters = "- \t";
var canDelimiters = "- \t";
var validSsnChars = digits + ssnDelimiters;
var digitsInSocialSecurityNumber = 9;
var digitsInPhoneNumber = 10;
var creditCardDelimiters = " ";
var daysInMonth = Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var childWindow;
var ZIPCodeDelimiters = "-";
var ZIPCodeDelimeter = "-"
var validZIPCodeChars = digits + ZIPCodeDelimiters
var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 9
var digitsInIRS1 = 9
var digitsInIRS2 = 11
var digitsInCAN = 11
var currencyDelimiter = "$,";
var defaultEmptyOK = false
var sessionTimeout = 45; //45;
var timeOutRedirectTo = 'fbtimedout.aspx';
var currentPageLocation = '';
var ISF_APPENDIX_D = '016';
var ISF_PENALTY_AMT = '10000';
var CTB_ISF_PENALTY_AMT = '50000';
var ISF_STB_APPENDIX_D_PORT = '9900'; 
var ISF_CTB_APPENDIX_D_PORT = '9900';
var PRINTING_SAME_TYPE_ERROR_MSG = 'Printing Single Transaction Bonds and Single Transaction ISF Appendix D is not allowed. ';
var CTB_PORT = '9900';

//------------------------------------------------------------------------------
  function hidemenu_all(){
    if (document.getElementById("tblBond").style.visibility != "hidden") document.getElementById("tblBond").style.visibility = "hidden";
    if (document.getElementById("tblQuery").style.visibility != "hidden") document.getElementById("tblQuery").style.visibility = "hidden";
    if (document.getElementById("tblPrint").style.visibility != "hidden") document.getElementById("tblPrint").style.visibility = "hidden";
    if (document.getElementById("tblMaintain").style.visibility != "hidden") document.getElementById("tblMaintain").style.visibility = "hidden";
    if (document.getElementById("tblHelp").style.visibility != "hidden") document.getElementById("tblHelp").style.visibility = "hidden";
    return true;
  }
//------------------------------------------------------------------------------
  function moveover(Id,ImgName){
    document.getElementById(Id).src = "images/" + ImgName;
    return true;
  }
//------------------------------------------------------------------------------
  function moveback(Id,ImgName){
    document.getElementById(Id).src = "images/" + ImgName;
    return true;
  }
//------------------------------------------------------------------------------
  function showmenu(Id){
    hidemenu_all();
    document.getElementById(Id).style.visibility = "visible";
    return true;
  }
//------------------------------------------------------------------------------
  function hidemenu(Id){
    document.getElementById(Id).style.visibility = "hidden";
    return true;
  }
//------------------------------------------------------------------------------
  //function clickIE() {if (document.all) {(message);return false;}}
	//function clickNS(e) {if 
	//(document.layers||(document.getElementById&&!document.all)) {
	//if (e.which==2||e.which==3) {(message);return false;}}}
	//if (document.layers) 
	//{document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
	//else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
	//document.oncontextmenu=new Function("return false")
//------------------------------------------------------------------------------
  function StripWhiteSpace (s) {
    return StripCharsInBag (s, whiteSpace);
  }
//------------------------------------------------------------------------------
  function StripCharsInBag (s, bag) {
    var i;
    var returnString = "";
    if (IsEmpty(s)) return returnString;
    for (i = 0; i < s.length; i++) {   
      var c = s.charAt(i);
      if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
  }
//------------------------------------------------------------------------------
  function IsEmpty(s) {
    return ((s == null) || (s.length == 0));
  }
//------------------------------------------------------------------------------
  function IsFloat (s) {
  var i;
  var seenDecimalPoint = false;
    if (IsEmpty(s)) return false;
    if (s == decimalPointDelimiter) return false;
    var startPos = (s.charAt(0) == "-" || s.charAt(0) == "+") ? 1 : 0;
    for (i = startPos; i < s.length; i++) {   
      var c = s.charAt(i);
      if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
      else if (!(c >= "0" && c <= "9")) return false;
    }
    return true;
  }
//------------------------------------------------------------------------------
  function Reformat (s) {
    var arg;
    var sPos = 0;
    var resultString = "";
    for (var i = 1; i < Reformat.arguments.length; i++) {
      arg = Reformat.arguments[i];
      if (i % 2 == 1) resultString += arg;
      else {
        resultString += s.substring(sPos, sPos + arg);
        sPos += arg;
      }
    }
    return resultString;
  }
//------------------------------------------------------------------------------
  function ReformatSsn (s) {
    return Reformat(s, "", 3, "-", 2, "-", 4);
  }
//------------------------------------------------------------------------------
  function ReformatCan (s) {
    return Reformat(s, "", 6, "-", 5);
  }
//------------------------------------------------------------------------------
  function ReformatIrs (s) {
    if (s.length == 9) return Reformat(s, "", 2, "-", 7); else return Reformat(s, "", 2, "-", 9);
  }
//------------------------------------------------------------------------------
  function IsSsn (s) {
    if (IsEmpty(s)) return false;
    var normalizedSsn = StripCharsInBag(s, ssnDelimiters);
    if (!IsInteger(normalizedSsn) || normalizedSsn.length != digitsInSocialSecurityNumber) return false;
    return true;
  }
//------------------------------------------------------------------------------
  function IsCan (s) {
    if (IsEmpty(s)) return false;
    var normalizedCan = StripCharsInBag(s, canDelimiters);
    if (!IsInteger(normalizedCan) || normalizedCan.length != digitsInCAN) return false;
    return true;
  }
//------------------------------------------------------------------------------
  function IsIrs (s) {
    if (IsEmpty(s)) return false;
    var normalizedIrs = StripCharsInBag(s, irsDelimiters);
    return ((IsInteger(normalizedIrs) && (normalizedIrs.length == digitsInIRS1)) || (IsAlphaNumeric(normalizedIrs) && (normalizedIrs.length == digitsInIRS2)))
  }
//------------------------------------------------------------------------------
  function IsAlphaNumeric (s) {
    var i;
    if (IsEmpty(s)) return false;
    for (i = 0; i < s.length; i++) {
      var c = s.charAt(i);
      if (!((c >= "a" && c <= "z") || (c >= "A" && c <= "Z") || (c >= "0" && c <= "9"))) return false;
    }
    return true;
  }
//------------------------------------------------------------------------------
  function IsCAZip(s) {
    //var objRegExp  = /^([AaBbCcEeGgHhJjKkLlMmNnPpRrSsTtVvXxYy]\d[A-Za-z]\s?\d[A-Za-z]\d)$/;
    var objRegExp  = /^([AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz]\d[A-Za-z]\s?\d[A-Za-z]\d)$/;
    return objRegExp.test(s);
  }
  function IsUSZip(s) {
    var objRegExp  = /^((\d{5}-\d{4})|(\d{5}))$/;
    return objRegExp.test(s);
  }
//------------------------------------------------------------------------------
  function IsInteger (s) {
    var i;
    if (IsEmpty(s)) return false;
    var startPos = (s.charAt(0) == "-" || s.charAt(0) == "+") ? 1 : 0;
    for (i = startPos; i < s.length; i++) {   
      var c = s.charAt(i);
      if (!(c >= "0" && c <= "9")) return false;
    }
    return true;
  }
//------------------------------------------------------------------------------
  function NewWindow(url, width, height) {
    wLeft = screen.width / 2 - width / 2;
    wTop = screen.height / 2 - height / 2;
    if (opener != null && opener.childWindow != null && opener.childWindow.open) {
      opener.childWindow = window.open(url, 'childWindow', 'location=0,toolbar=0,menubar=0,resizable=0,status=1,scrollbars=0,width=' + width + ',height=' + height + ',left=' + wLeft + ',top=' + wTop);
    }
    else if (childWindow != null && childWindow.open) {
      childWindow.close();
      childWindow = window.open(url, 'childWindow', 'location=0,toolbar=0,menubar=0,resizable=0,status=1,scrollbars=0,width=' + width + ',height=' + height + ',left=' + wLeft + ',top=' + wTop);
    }
    else
      childWindow = window.open(url, 'childWindow', 'location=0,toolbar=0,menubar=0,resizable=0,status=1,scrollbars=0,width=' + width + ',height=' + height + ',left=' + wLeft + ',top=' + wTop);
  }
//------------------------------------------------------------------------------
  function FormatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if (isNaN(num)) num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10) cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
      num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    //return (((sign) ? '' : '-') + '$' + num + '.' + cents);
    return (((sign) ? '' : '-') + '$' + num);
  }
//------------------------------------------------------------------------------
  function filterNum(str) {
    re = /\n|\r|\t/g;
    return str.replace(re, "");
  }
//------------------------------------------------------------------------------
    function PrintAndClose(){
      window.print();
      window.close();
    }
//------------------------------------------------------------------------------
  function compareDates(date1,date2, ctrl) {
    var date1_arr = date1.split("/");
    var date2_arr = date2.split("/");
    if (date1_arr[2].length != 4) 
      alert("Please enter year in following format : YYYY");
    else {
      d1 = new Date(date1_arr[2], date1_arr[0], date1_arr[1]);
      d2 = new Date(date2_arr[2], date2_arr[0], date2_arr[1]);
      var diff = d1 - d2;
      if (diff > 0) alert("Warning:Use of a date in the future may be cause for a bond rejection by CBP if CBP receives or processes a post-dated document.");
    }
  }
//------------------------------------------------------------------------------
  function IsDate (month, day, year) {
    var today = new Date();
    if (year == null || year.length == 0) year = "" + today.getYear();
    if (! (IsInteger(year) && (year.length == 2 || year.length == 4) && IsIntegerInRange(month, 1, 12) && IsIntegerInRange (day, 1, 31) ) ) return false;
    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);
    if (intDay > daysInMonth[intMonth - 1]) return false;
    if (intMonth == 2 && intDay > (!(year % 100 == 0) && (year % 4 == 0 || year % 400 == 0) ? 29 : 28)) return false;
    return true;
  }
//------------------------------------------------------------------------------
  function IsIntegerInRange (s, a, b) {
    if (IsEmpty(s)) return false;
    if (!IsInteger(s, false)) return false;
    var num = parseInt (s);
    return ((num >= a) && (num <= b));
  }
//------------------------------------------------------------------------------
	function SetCookie (name, value) {  
	  var argv = SetCookie.arguments;  
	  var argc = SetCookie.arguments.length;  
    var date = new Date();
		//date.setTime(date.getTime()+(days*24*60*60*1000));
		date.setTime(date.getTime()+(2*24*60*60*1000));
		var expires = "; expires=" + date.toGMTString();
	  //var expires = (argc > 2) ? argv[2] : null;  
	  var path = (argc > 3) ? argv[3] : null;  
	  var domain = (argc > 4) ? argv[4] : null;  
	  var secure = (argc > 5) ? argv[5] : false;  
	  document.cookie = name + "=" + escape (value) + expires + 
	  //((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
	  ((path == null) ? "" : ("; path=" + path)) +  
	  ((domain == null) ? "" : ("; domain=" + domain)) +    
	  ((secure == true) ? "; secure" : "");
	}
	function getCookieVal (offset) {  
	  var endstr = document.cookie.indexOf (";", offset);  
	  if (endstr == -1)    
	  endstr = document.cookie.length;  
	  return unescape(document.cookie.substring(offset, endstr));
	}
	function GetCookie (name) {  
	  var arg = name + "=";  
	  var alen = arg.length;  
	  var clen = document.cookie.length;  
	  var i = 0;  
	  while (i < clen) {    
		var j = i + alen;    
		if (document.cookie.substring(i, j) == arg)      
		return getCookieVal (j);    
		i = document.cookie.indexOf(" ", i) + 1;    
		if (i == 0) break;   
	  }  
	  return null;
	}
//------------------------------------------------------------------------------
  function TrimAll(sString) {
    while (sString.substring(0,1) == ' ') sString = sString.substring(1, sString.length);
    while (sString.substring(sString.length-1, sString.length) == ' ') sString = sString.substring(0,sString.length-1);
    return sString;
  }
//------------------------------------------------------------------------------
  function hidemenus() {
	 hidemenu('tblBond');
	 hidemenu('tblQuery');
	 hidemenu('tblPrint');
	 hidemenu('tblMaintain');
	 hidemenu('tblHelp');  
  }
  //------------------------------------------------------------------------------
  function beforeTimeout() {
      currentPageLocation = window.location.href;
      setTimeout('checkSession()', (sessionTimeout - 5) * 60 * 1000);      
  }
  //--------------------------------------------------------------------------------------
  function checkSession() {
      //Pablo Jacome
      //This function tries to keep track of the session on the client and alert user that it is about to expire
      var time = new Date();
      time.setTime(time.getTime() + (5 * 60 * 1000));
      var hour = time.getHours();
      var minute = time.getMinutes();
      var second = time.getSeconds();
      var temp = "" + ((hour > 12) ? hour - 12 : hour);
      if (hour == 0) temp = "12";
      if (temp.length == 1) temp = " " + temp;
      temp += ((minute < 10) ? ":0" : ":") + minute;
      temp += ((second < 10) ? ":0" : ":") + second;
      temp += (hour >= 12) ? " PM" : " AM";
      var msg = 'Your current FastBond session is about to expire. Please, submit the form to save changes. \nFor your security, application sessions automatically end after 45 minutes of inactivity. \nYour session will expire in 5 min. at ' + temp;
      alert(msg);
      /*var flag = confirm(msg);        
      if (flag) {
            //alert(currentPageLocation);
            window.location.href = currentPageLocation;
            window.onload = beforeTimeout;
        } else {
            window.location.href = timeOutRedirectTo;
        }*/
    }
    //---------------------------------------------------------------------------------------
    String.prototype.trim = function() {
	    return this.replace(/^\s+|\s+$/g,"");
    }
    //--------------------------------------------------------------------------------------
    String.prototype.ltrim = function() {
	    return this.replace(/^\s+/,"");
    }
    //--------------------------------------------------------------------------------------
    String.prototype.rtrim = function() {
	    return this.replace(/\s+$/,"");
    }
    //--------------------------------------------------------------------------------------
    function setSelectedIndex(obj, value) {
        for ( var i = 0; i < obj.options.length; i++ ) {
            if ( obj.options[i].value == value ) {
                 obj.options[i].selected = true;
                 return;
            }
        }
    }
    //---------------------------------------------------------------------------------------
    function IsIsfTxnNumber(value){                
         var objRegExp  = /^[A-Za-z0-9\s\-]{3,4}\d{11}$/;
        if (value.length == 15) {
          return objRegExp.test(value);
        } else {
          return false;
        }        
    }
    //----------------------------------------------------------------------------------------
    //--------------------------------------------------------------------------------------
    function resetddl(sid)        
        {
            //This function resets drop down lists
            //Issue: Some pages were having problems when drop down list actions when using back button
            //Solution: Reset all drop down list actions in page
            var el = document.getElementsByTagName('select'); 
            for(i=0;i < el.length; i++)
            {
                var ddl = document.getElementById(el[i].id);
                if (ddl != undefined)
                {
                    if(el[i].id!=sid)
                    {document.getElementById(el[i].id).selectedIndex = 0;}
                }
            }
        }
     //---------------------------------------------------------------------------------------------    
    //--------------------------------------------------------------------------------------
    function resetMultddl(sid)        
        {
            //This function resets drop down lists
            //Issue: Some pages were having problems when drop down list actions when using back button
            //Solution: Reset all drop down list actions in page
            var el = document.getElementsByTagName('select');    
            var len=sid.length   
                        var FoundMatch = false;       
            for(i=0;i < el.length; i++)
            {
                FoundMatch = false; 
                var ddl = document.getElementById(el[i].id);
                if (ddl != undefined)
                {
                    for(j=0;j < len; j++)
                    {
                        //if(el[i].id!=sid[j])
                        //{document.getElementById(el[i].id).selectedIndex = 0;}
                        if(el[i].id==sid[j])
                        {
                            FoundMatch=true
                            break;
                        }
                    }    
                    if(FoundMatch==false)
                       {document.getElementById(el[i].id).selectedIndex = 0;}                    
                }
            }
        }
     //---------------------------------------------------------------------------------------------         
     function isValidUserId(value){
        var regExp = /^[A-Za-z0-9\-\_\.]*$/;
        return regExp.test(value);     
     }   
     //----------------------------------------------------------------------------------------------
     function isValidZip(zip, country)
     {    
        var objRegExp;
        
        if (country == 'MX')
        {
            objRegExp = /^\d{5}$/;
        }        
        
        return objRegExp.test(zip);
     
     }
     //------------------------------------------------------------------------------------------------
     function getCheckedValue(radioObj)
     {
        if(!radioObj)
		    return "";
	    var radioLength = radioObj.length;
	    if(radioLength == undefined)
		    if(radioObj.checked)
			    return radioObj.value;
		    else
			    return "";
	    for(var i = 0; i < radioLength; i++) {
		    if(radioObj[i].checked) {
			    return radioObj[i].value;
		    }
	    }
	    return "";

     }
     //-------------------------------------------------------------------------------------------------
     function formatDate(value) {
        var EffDateLength
        var NewEffDate        
        EffDateLength = value.trim().length;
        var EffDate = value.trim();
        var SlashPosition        
        SlashPosition = value.trim().indexOf('/');
        if (SlashPosition == -1) {
            if (EffDateLength == 8) {
                NewEffDate = value.trim().substring(0, 2) + '/' +
                  value.trim().substring(2, 4) + '/' +
                  value.trim().substring(4, 8);
                  return NewEffDate;
            }
            if (EffDateLength == 6) {
                NewEffDate = value.trim().substring(0, 2) + '/' +
                  value.trim().substring(2, 4) + '/' +
                  '20' +
                  value.trim().substring(4, 6);
                  return NewEffDate;
            }
        }
        if (SlashPosition > 0) {
            if (value.trim().substring(2, 3) == '/' && value.trim().substring(5, 6) == '/') {
                VarYear = value.trim().substring(6)
                if (VarYear.length == 2) {
                    NewEffDate = value.trim().substring(0, 6) +
                  '20' +
                  value.trim().substring(6);
                  return NewEffDate.trim();
                }
            }
        }
        return value;
    }
    //--------------------------------------------------------------------------------------------------
    function isValidDateFormat(value) {
        var regExp = /^\d{2}\/\d{2}\/\d{4}$/;       
       return regExp.test(value);
   }
   //--------------------------------------------------------------------------------------------------
   function isNumeric(value) {       
        var val = value.replace(/\$|\,/g,'');     
        var regExp = /^\d+(\.\d{2})?$/;        
	    return regExp.test(val);
    }
    //---------------------------------------------------------------------------------------------------
    function formatDateOnTheFly(vDateName, vDateValue, e, dateCheck, dateType) {
        // Check browser version
        var isNav4 = false, isNav5 = false, isIE4 = false
        var strSeperator = "/";
        // If you are using any Java validation on the back side you will want to use the / because 
        // Java date validations do not recognize the dash as a valid date separator.
        var vDateType = 3; // Global value for type of date format
        //                1 = mm/dd/yyyy
        //                2 = yyyy/dd/mm  (Unable to do date check at this time)
        //                3 = dd/mm/yyyy
        var vYearType = 4; //Set to 2 or 4 for number of digits in the year for Netscape
        var vYearLength = 2; // Set to 4 if you want to force the user to enter 4 digits for the year before validating.
        var err = 0; // Set the error code to a default of zero
        if (navigator.appName == "Netscape") {
            if (navigator.appVersion < "5") {
                isNav4 = true;
                isNav5 = false;
            }
            else
                if (navigator.appVersion > "4") {
                isNav4 = false;
                isNav5 = true;
            }
        }
        else {
            isIE4 = true;
        }
           
        vDateType = dateType;
        // vDateName = object name
        // vDateValue = value in the field being checked
        // e = event
        // dateCheck 
        // True  = Verify that the vDateValue is a valid date
        // False = Format values being entered into vDateValue only
        // vDateType
        // 1 = mm/dd/yyyy
        // 2 = yyyy/mm/dd
        // 3 = dd/mm/yyyy
        //Enter a tilde sign for the first number and you can check the variable information.
        if (vDateValue == "~") {
            alert("AppVersion = " + navigator.appVersion + " \nNav. 4 Version = " + isNav4 + " \nNav. 5 Version = " + isNav5 + " \nIE Version = " + isIE4 + " \nYear Type = " + vYearType + " \nDate Type = " + vDateType + " \nSeparator = " + strSeperator);
            vDateName.value = "";
            vDateName.focus();
            return true;
        }
        var whichCode = (window.Event) ? e.which : e.keyCode;        
        // Check to see if a seperator is already present.
        // bypass the date if a seperator is present and the length greater than 8
        if (vDateValue.length > 8 && isNav4) {
            if ((vDateValue.indexOf("-") >= 1) || (vDateValue.indexOf("/") >= 1))
                return true;
        }
        //Eliminate all the ASCII codes that are not valid
        var alphaCheck = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-";
        if (alphaCheck.indexOf(vDateValue) >= 1) {
            if (isNav4) {
                vDateName.value = "";
                vDateName.focus();
                vDateName.select();
                return false;
            }
            else {
                vDateName.value = vDateName.value.substr(0, (vDateValue.length - 1));
                return false;
            }
        }
        if (whichCode == 8) //Ignore the Netscape value for backspace. IE has no value
            return false;
        else {
            //Create numeric string values for 0123456789/
            //The codes provided include both keyboard and keypad values
            var strCheck = '13,47,48,49,50,51,52,53,54,55,56,57,58,59,95,96,97,98,99,100,101,102,103,104,105';
            if (strCheck.indexOf(whichCode) != -1) {
                if (isNav4) {
                    if (((vDateValue.length < 6 && dateCheck) || (vDateValue.length == 7 && dateCheck)) && (vDateValue.length >= 1)) {
                        alert("Invalid Date\nPlease Re-Enter");
                        vDateName.value = "";
                        vDateName.focus();
                        vDateName.select();
                        return false;
                    }
                    if (vDateValue.length == 6 && dateCheck) {
                        var mDay = vDateName.value.substr(2, 2);
                        var mMonth = vDateName.value.substr(0, 2);
                        var mYear = vDateName.value.substr(4, 4)
                        //Turn a two digit year into a 4 digit year
                        if (mYear.length == 2 && vYearType == 4) {
                            var mToday = new Date();
                            //If the year is greater than 30 years from now use 19, otherwise use 20
                            var checkYear = mToday.getFullYear() + 30;
                            var mCheckYear = '20' + mYear;
                            if (mCheckYear >= checkYear)
                                mYear = '19' + mYear;
                            else
                                mYear = '20' + mYear;
                        }
                        var vDateValueCheck = mMonth + strSeperator + mDay + strSeperator + mYear;
                        if (!isDateValid(vDateValueCheck)) {
                            alert("Invalid Date\nPlease Re-Enter");
                            vDateName.value = "";
                            vDateName.focus();
                            vDateName.select();
                            return false;
                        }
                        return true;
                    }
                    else {
                        // Reformat the date for validation and set date type to a 1
                        if (vDateValue.length >= 8 && dateCheck) {
                            if (vDateType == 1) // mmddyyyy
                            {
                                var mDay = vDateName.value.substr(2, 2);
                                var mMonth = vDateName.value.substr(0, 2);
                                var mYear = vDateName.value.substr(4, 4)
                                vDateName.value = mMonth + strSeperator + mDay + strSeperator + mYear;
                            }
                            if (vDateType == 2) // yyyymmdd
                            {
                                var mYear = vDateName.value.substr(0, 4)
                                var mMonth = vDateName.value.substr(4, 2);
                                var mDay = vDateName.value.substr(6, 2);
                                vDateName.value = mYear + strSeperator + mMonth + strSeperator + mDay;
                            }
                            if (vDateType == 3) // ddmmyyyy
                            {
                                var mMonth = vDateName.value.substr(2, 2);
                                var mDay = vDateName.value.substr(0, 2);
                                var mYear = vDateName.value.substr(4, 4)
                                vDateName.value = mDay + strSeperator + mMonth + strSeperator + mYear;
                            }
                            //Create a temporary variable for storing the DateType and change
                            //the DateType to a 1 for validation.
                            var vDateTypeTemp = vDateType;
                            vDateType = 1;
                            var vDateValueCheck = mMonth + strSeperator + mDay + strSeperator + mYear;
                            if (!isDateValid(vDateValueCheck)) {
                                alert("Invalid Date\nPlease Re-Enter");
                                vDateType = vDateTypeTemp;
                                vDateName.value = "";
                                vDateName.focus();
                                vDateName.select();
                                return false;
                            }
                            vDateType = vDateTypeTemp;
                            return true;
                        }
                        else {
                            if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >= 1)) {
                                alert("Invalid Date\nPlease Re-Enter");
                                vDateName.value = "";
                                vDateName.focus();
                                vDateName.select();
                                return false;
                            }
                        }
                    }
                }
                else {
                    // Non isNav Check
                    if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >= 1)) {
                        alert("Invalid Date\nPlease Re-Enter");
                        vDateName.value = "";
                        vDateName.focus();
                        return true;
                    }
                    // Reformat date to format that can be validated. mm/dd/yyyy
                    if (vDateValue.length >= 8 && dateCheck) {
                        // Additional date formats can be entered here and parsed out to
                        // a valid date format that the validation routine will recognize.
                        if (vDateType == 1) // mm/dd/yyyy
                        {
                            var mMonth = vDateName.value.substr(0, 2);
                            var mDay = vDateName.value.substr(3, 2);
                            var mYear = vDateName.value.substr(6, 4)
                        }
                        if (vDateType == 2) // yyyy/mm/dd
                        {
                            var mYear = vDateName.value.substr(0, 4)
                            var mMonth = vDateName.value.substr(5, 2);
                            var mDay = vDateName.value.substr(8, 2);
                        }
                        if (vDateType == 3) // dd/mm/yyyy
                        {
                            var mDay = vDateName.value.substr(0, 2);
                            var mMonth = vDateName.value.substr(3, 2);
                            var mYear = vDateName.value.substr(6, 4)
                        }
                        if (vYearLength == 4) {
                            if (mYear.length < 4) {
                                alert("Invalid Date\nPlease Re-Enter");
                                vDateName.value = "";
                                vDateName.focus();
                                return true;
                            }
                        }
                        // Create temp. variable for storing the current vDateType
                        var vDateTypeTemp = vDateType;
                        // Change vDateType to a 1 for standard date format for validation
                        // Type will be changed back when validation is completed.
                        vDateType = 1;
                        // Store reformatted date to new variable for validation.
                        var vDateValueCheck = mMonth + strSeperator + mDay + strSeperator + mYear;
                        if (mYear.length == 2 && vYearType == 4 && dateCheck) {
                            //Turn a two digit year into a 4 digit year
                            var mToday = new Date();
                            //If the year is greater than 30 years from now use 19, otherwise use 20
                            var checkYear = mToday.getFullYear() + 30;
                            var mCheckYear = '20' + mYear;
                            if (mCheckYear >= checkYear)
                                mYear = '19' + mYear;
                            else
                                mYear = '20' + mYear;
                            vDateValueCheck = mMonth + strSeperator + mDay + strSeperator + mYear;
                            // Store the new value back to the field.  This function will
                            // not work with date type of 2 since the year is entered first.
                            if (vDateTypeTemp == 1) // mm/dd/yyyy
                                vDateName.value = mMonth + strSeperator + mDay + strSeperator + mYear;
                            if (vDateTypeTemp == 3) // dd/mm/yyyy
                                vDateName.value = mDay + strSeperator + mMonth + strSeperator + mYear;
                        }
                        if (!isDateValid(vDateValueCheck)) {
                            alert("Invalid Date\nPlease Re-Enter");
                            vDateType = vDateTypeTemp;
                            vDateName.value = "";
                            vDateName.focus();
                            return true;
                        }
                        vDateType = vDateTypeTemp;
                        return true;
                    }
                    else {
                        if (vDateType == 1) {
                            if (vDateValue.length == 2) {
                                vDateName.value = vDateValue + strSeperator;
                            }
                            if (vDateValue.length == 5) {
                                vDateName.value = vDateValue + strSeperator;
                            }
                        }
                        if (vDateType == 2) {
                            if (vDateValue.length == 4) {
                                vDateName.value = vDateValue + strSeperator;
                            }
                            if (vDateValue.length == 7) {
                                vDateName.value = vDateValue + strSeperator;
                            }
                        }
                        if (vDateType == 3) {
                            if (vDateValue.length == 2) {
                                vDateName.value = vDateValue + strSeperator;
                            }
                            if (vDateValue.length == 5) {
                                vDateName.value = vDateValue + strSeperator;
                            }
                        }
                        return true;
                    }
                }
                if (vDateValue.length == 10 && dateCheck) {
                    if (!isDateValid(vDateName)) {
                        // Un-comment the next line of code for debugging the isDateValid() function error messages
                        //alert(err);  
                        alert("Invalid Date\nPlease Re-Enter");
                        vDateName.focus();
                        vDateName.select();
                    }
                }
                return false;
            }
            else {
                // If the value is not in the string return the string minus the last
                // key entered.
                if (isNav4) {
                    vDateName.value = "";
                    vDateName.focus();
                    vDateName.select();
                    return false;
                }
                else {
                    vDateName.value = vDateName.value.substr(0, (vDateValue.length - 1));
                    return false;
                }
            }
        }
    }

    function isDateValid(objName) {
        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;
        strDate = objName;
        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) {
                strDay = strDate.substr(0, 2);
                strMonth = strDate.substr(2, 2);
                strYear = strDate.substr(4);
            }
        }
        //Adjustment for short years entered
        if (strYear.length == 2) {
            strYear = '20' + strYear;
        }
        strTemp = strDay;
        strDay = strMonth;
        strMonth = strTemp;
        intday = parseInt(strDay, 10);
        if (isNaN(intday)) {
            err = 2;
            return false;
        }
        intMonth = parseInt(strMonth, 10);
        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 (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 (isLeapYear(intYear) == true) {
                if (intday > 29) {
                    err = 9;
                    return false;
                }
            }
            else {
                if (intday > 28) {
                    err = 10;
                    return false;
                }
            }
        }
        return true;
    }

    function isLeapYear(intYear) {
        if (intYear % 100 == 0) {
            if (intYear % 400 == 0) {
                return true;
            }
        }
        else {
            if ((intYear % 4) == 0) {
                return true;
            }
        }
        return false;
    }
    //_------------------------------------------------------------------------------
    function setSelectionRange(input, selectionStart, selectionEnd) {
        if (input.setSelectionRange) {
            input.focus();
            input.setSelectionRange(selectionStart, selectionEnd);
        }
        else if (input.createTextRange) {
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', selectionEnd);
            range.moveStart('character', selectionStart);
            range.select();
        }
    }
    //---------------------------------------------------------------------------------------
    function setCaretToPos(input, pos) {
        setSelectionRange(input, pos, pos);
    }
    //---------------------------------------------------------------------------------------
    //Pablo Jacome 11/28/2011
    //This function calculates the number of days between two days
    //references date.js    
    function getElapse(date1, date2) {
        //var d1 = Date.parse(date1);
        //var d2 = Date.parse(date2);
                
        if (date1.compareTo(date2) == 0) {
            return 0;
        } else {
            return Math.ceil((date2 - date1 + 1) / (1000 * 60 * 60 * 24));
        }

    }
    //---------------------------------------------------------------------------------------
    //Pablo Jacome 11/28/2011
    //This function calculates the number of days between two days excluding weekends
    //references date.js
    function getElapseNoWeekends(date1, date2) {
        var d1 = Date.parse(date1.toString('MM/dd/yyyy'));  //Date.parse(date1);
        var d2 = Date.parse(date2.toString('MM/dd/yyyy'));   //Date.parse(date2);
        var count = 0;
        var factor = 1;

        if (d1.compareTo(d2) == 0) return count;

        if (d1.compareTo(d2) > 0) {
            d1 = Date.parse(date2.toString('MM/dd/yyyy'));  //Date.parse(date2);
            d2 = Date.parse(date1.toString('MM/dd/yyyy'));  //Date.parse(date1);
            factor = -1;
        }

        while (true) {
            d1.addDays(1);
            if (!d1.is().sat() && !d1.is().sun()) {
                count++;
            }
            if (d1.compareTo(d2) == 0) break;
        }

        return count * factor;

    }
    //---------------------------------------------------------------------------------------
    //Pablo Jacome 11/28/2011
    //This function calculates the number of weekends between two days
    //references date.js
    function getNumberOfWeekends(date1, date2) {
        var d1 = Date.parse(date1.toString('MM/dd/yyyy'));  //Date.parse(date1);
        var d2 = Date.parse(date2.toString('MM/dd/yyyy')); //Date.parse(date2);
        var count = 0;
        var factor = 1;

        if (d1.compareTo(d2) == 0) return 0; ;

        if (d1.compareTo(d2) > 0) {
            return 0;
            d1 = Date.parse(date2.toString('MM/dd/yyyy'));  //Date.parse(date2);
            d2 = Date.parse(date1.toString('MM/dd/yyyy'));  //Date.parse(date1);
            factor = -1;
        }

        while (true) {
            d1.addDays(1);
            if (d1.is().sat() || d1.is().sun()) {
                count++;
            }
            if (d1.compareTo(d2) == 0) break;
        }

        return count * factor;

    }
