var today = new Date();
var day   = today.getDate();
var month = today.getMonth();
var year  = today.getFullYear();
var skipValidation = false;
// Various form-related functions in alphabetical order //
//-----------------------------------------------------------------//
// Add Mask information to the Date to MM/DD/YY or MM/DD/YYYY      //
//-----------------------------------------------------------------//

function dateMask(field,format){
	var t_dt, t_mm, t_dd, t_yyyy, t_field;
    var date_format = 'mm/dd/yyyy';
    if (arguments.length > 1) {
    	date_format = format;
     }

	if( field=='[object]' || field=='[object HTMLInputElement]' ) { t_field = field.value } else { t_field = field }
	if(t_field != "") {
		t_dt = isDate(t_field, "/");
		if (t_dt != null) { t_field = t_dt; }
		else { 
			t_mm = t_field.substr(0,2);t_dd = t_field.substr(2,2);t_yyyy = t_field.substr(4);
			if( isNaN(t_mm) == false && isNaN(t_dd) == false && isNaN(t_yyyy) == false ) { 
				t_dt = t_mm + "/" + t_dd + "/" + t_yyyy;t_dt = isDate(t_dt, "/");
				if( t_dt != null ) { t_field = t_dt; } }
			}
	}
	if( field.value ) { field.value = t_field } else { return t_field }
}

function displayCalendar(calendar_name)
    {
    var winCalendar        
    popupWindow(calendar_name,'winCalendar', 'toolbar=no,menu=no,resizable=yes,width=250,height=260');
    }

function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"||token=="NNN"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) { month -= 12; }
						i_val += month_name.length;
						break;
						}
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="EE"||token=="E"){
			for (var i=0; i<DAY_NAMES.length; i++) {
				var day_name=DAY_NAMES[i];
				if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
					}
				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (mm==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((mm==4)||(mm==6)||(mm==9)||(mm==11)) {
		if (date > 30) { return 0; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
	}
	
// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}
	
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function stripSpecialChars(field, flag){
     var tempStr = "";
     var suffix = "";
     var temp2Str = field.value;temp2Str = temp2Str.toUpperCase()
	 if( flag  ) { if( isNaN(flag) ) { var lc_Flag = flag.toLowerCase(); } }
     var leng =  temp2Str.length, t_dt = null;

	if( field.value != "" ) {
		if( lc_Flag == "date" || flag == 1 ) {
			t_dt = isDate(field.value, '');
			if( t_dt != null ) { field.value = t_dt; } }
        else
           {
		   if( lc_Flag == "phone" || flag == 2 ) 
            {
	    	 for (var i = 0; i < leng; i++) 
              {
                var keep = false
		        if (tempStr.length < 10)
                  {
		         if (temp2Str.charAt(i) >= "0" && temp2Str.charAt(i) <= "9")
                    tempStr = tempStr + temp2Str.charAt(i); 
                  }
		        else
                  {
                   if (suffix != "" || temp2Str.charAt(i) != " ") // Drop leading blanks in the suffix
                     suffix = suffix + temp2Str.charAt(i); 
                  }				 
              }
              field.value = tempStr + " " + suffix;
            }
		else {
	    	for (var i = 0; i < leng; i++) {
		        if (((temp2Str.charAt(i) >= "0") && (temp2Str.charAt(i) <= "9")) ||
		           ((temp2Str.charAt(i) >= "A") && (temp2Str.charAt(i) <= "Z"))) {
				 tempStr = tempStr + temp2Str.charAt(i); }
 	      	}
  		    field.value = tempStr; }
         }
	}
}
function stripSpecialChars_Str(value){
  re = /\$|,|@|#|~|`|\%|\*|\^|\&|\(|\)|\+|\=|\[|\-|\_|\ |\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$|\./g;
          // remove special characters like "$" and "," etc...
  return value.replace(re, "");
}

function trimBlanks(field, trim_type){
 var leading = false;
 var trailing = false;
 var embedded = "";
 switch (trim_type.toLowerCase()){
   case "leadingspaces":
     leading = true;
     break;
   case "trailingspaces": 
     trailing = true;
     break;
   case "leading+trailing": 
     leading = true;
     trailing = true;
     break;
   case "allspaces": 
     leading = true;
     trailing = true;
     embedded = " ";
     break;
   case "multiembedded": 
     leading = true;
     trailing = true;
     embedded = "  ";
     break;
   default : alert('Invalid trim option passed to trimBlanks function: "'+trim_type+'"');
  }
   var retValue = field.value;
   var ch = retValue.substring(0, 1);
   if (leading){
     while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
     }
   }
   if (trailing){
     ch = retValue.substring(retValue.length-1, retValue.length);
     while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
     }
   }
   if (embedded > ""){
     while (retValue.indexOf(embedded) != -1) { // look for spaces within the string
        retValue = retValue.substring(0, retValue.indexOf(embedded)) + retValue.substring(retValue.indexOf(embedded)+1, retValue.length); // Again, there are spaces in each of the strings
     }
   }
   return retValue; // Return the trimmed string back to the user
} // End of "trimBlanks" function

function trimSpaces(arg) {
  return (arg.replace(/^\W+/,'')).replace(/\W+$/,'');
}

function changeCase(field, case_type){
 switch (case_type.toLowerCase()){
   case "tolower":
     return field.value.toLowerCase();
   case "toupper":
     return field.value.toUpperCase();
   case "tomixed": 
     break; // See Below
   default : alert('Invalid case change option passed to changeCase function: "'+case_type+'"');
  }
   var makeUpper = true;
   var retValue = "";
   for(var i = 0; i<=field.value.length; i++ ) {
     if (makeUpper) {
	  makeUpper = false;	
	  retValue += field.value.charAt(i).toUpperCase();
      }
     else {
	  retValue += field.value.charAt(i);
     }
     if (field.value.charAt(i) == " ") {
     	makeUpper = true;
     }
   }
   return retValue; // Return the trimmed string back to the user
} // End of "changeCase" function
function checkEmailAddress(field,label) {
// Note: The next expression must be all on one line...
//       allow no spaces, linefeeds, or carriage returns!
var goodEmail = field.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
return (goodEmail ? '' : 'Invalid email address, must be in the form name@domain.xxx');
}
function checkCanadianPostalCode(field,label) {
// Note: This is for Canadian postal codes (AnAnAn)
var goodCode = field.value.match(/^\s*[a-ceghj-npr-tvxy]\d[a-z](\s)?\d[a-z]\d\s*$/i);
return (goodCode ? '' : 'Invalid Canadian Postal Code, must be in the form LnLnLn (alternating Letters and Numbers). Note that some letters look like numbers, for example the letter O looks like the number zero.');
}
function checkPhoneNumber(field,label) {
  return (countDigits(field.value) > 9 ? '' : 'Phone numbers must contain at least 10 digits');
}
function checkCreditCardNumber(field,label) {
  return (countDigits(field.value) > 15 ? '' : 'Credit Card numbers must contain at least 16 digits');
}
function checkNumeric(field,label) {
  return (isNumeric(field.value) ? '' : 'Invalid number');
}
function checkRequiredRadioButton(field,label) {
var myOption = -1;
var rlen = (typeof(field.length) == 'undefined' ? 1 : field.name);
if (rlen == 1){ // Single radio buttons don't create collection
	  if (field.checked) {
	    myOption = 1;	
	    }
}
else {
	for (var i = field.length - 1; i > -1; i--) {
	  if (field[i].checked) {
	    myOption = i;	
	    }
	}
}
if (myOption == -1) {
  var nameprop = (typeof(field.name) == 'undefined' ? '' : field.name);
  if (nameprop == '') {
	nameprop = (label == '' ? '' : label);
  }
  return 'One ' + nameprop + ' option must be chosen';
}
}
function checkDate(field,label,format) {
   var date_format = 'm/d/yyyy';
   if (arguments.length > 2) {
    	date_format = format;
     }
  return (isDate(field.value,date_format) ? '' : 'Invalid Date');
}
function countDigits(text) {
var digits = 0;
for(var i = 0; i<=text.length; i++ ) {
  if (text.charAt(i) >= '0' && text.charAt(i) <= '9') {
	digits++;	
     }
}
return digits;
}
function checkDisallowItem1(field,label) {
  var field_label = (label > '' ? ' for ' + label : '');
  return (field.selectedIndex == 0 ? 'Please select a valid entry' + field_label : '');	
}
function isNumeric(string) {
    if (!string) return false;
    var Chars = ".-+0123456789";

    for (var i = 0; i < string.length; i++) {
       if (Chars.indexOf(string.charAt(i)) == -1)
          return false;
    }
    return true;
} 
function formatPhone(field,focus) {
	if (focus) {
	  field.value = stripSpecialChars_Str(field.value);
	}
	else {
		var temp = stripSpecialChars_Str(field.value);
		if (temp > '') {
			field.value = '(' + temp.substr(0,3) + ') ' + temp.substr(3,3) + '-' + temp.substr(6,4);
		    if (temp.length > 10) {
				field.value +=  ' ' + temp.substr(10)
			}
		}
	}
}

function formatCanadianPostalCode(field,focus) {
	if (focus) {
	  field.value = stripSpecialChars_Str(field.value);
	}
	else {
		var temp = stripSpecialChars_Str(field.value);
		if (temp > '') {
			temp = temp.toUpperCase();
			field.value = temp.substr(0,3) + ' ' + temp.substr(3,3);
		}
	}
}
function setSurrogate(field,surrogate) {
	surrogate.value =  (field.checked ? 'checked' : 'unchecked');
  }
function db_navigate($what,where,frm) {
  frm[$what+'_navto'].value = where; 
  frm.button_pressed.value = $what+'_navigate'; 
  skipValidation = true;
  frm.submit();
  }
function default_date_format() {
  return 'mm/dd/yyyy';
  }
