// Trim(s)
// LTrim(s)
// RTrim(s)
// filterNumeric()
// validateControls()
// ForceMoney(object,objName)
// todaysDate()
// UCase(fld)
// disableControls(disable)
// CheckStartDate(BeginDate, EndDate)
// CheckDateFormat(obj)
// IsInt(theValue)
// isNumeric(strN)
// SetStatus(Status, Pointer)
// GetDate(obj)
// UpdateCheckBox(checkBox, field) - Removed by someone
// UpdateCheckboxField(checkBox, field)
// TabClick(Tab)
// DateInputValidate(startDate, startTime, endDate, endTime )
// CheckTimeFormat(timeStr)
// isWhitespace(s)
// isEmpty(s)
// setSpacer(spc)
// ToFmt(x)
// Money(objField)
// fmtF(w,d)
// Credit Card Check.
// FormatMoney(ctl, val)

/* Public Variables */
var bClearCardInfo;

function ShowDiv(which){
	if (which=="Contents"){
		window.Processing.style.display = "none";
		window.Saving.style.display = "none";
		window.Loading.style.display = "none";
		window.Contents.style.display = "";
	}
	if (which=="Processing"){
		window.Contents.style.display = "none";
		window.Saving.style.display = "none";
		window.Loading.style.display = "none";
		window.Processing.style.display = "";
	}
	if (which=="Saving"){
		window.Contents.style.display = "none";
		window.Processing.style.display = "none";
		window.Loading.style.display = "none";
		window.Saving.style.display = "";
	}
	if (which=="Loading"){
		window.Contents.style.display = "none";
		window.Processing.style.display = "none";
		window.Saving.style.display = "none";
		window.Loading.style.display = "";
	}

}

function Trim(s) {
  s = s.replace(/^\s+/, "");    // LTrim
  s = s.replace(/\s+$/, "");    // RTrim
  return(s);
}
function LTrim(s) {
  s = s.replace(/^\s+/, "");    // LTrim
  return(s);
}
function RTrim(s) {
  s = s.replace(/\s+$/, "");    // RTrim
  return(s);
}

function filterNumeric() {

	switch (window.event.keyCode) {
	    case 189://negative sign
	        break;
		case 8: //Backspace
			break;
		case 9: //Tab
			break;
		case 13: //Enter
			break;
		case 37: //Left arrow
			break;
		case 39: //Right arrow
			break;
		case 46: //Delete
			break; 
        case 190: //.
            break;
        case 110: //.
            break;  
		default:
			if (window.event.keyCode < 48 || (window.event.keyCode > 57 && window.event.keyCode < 96) || window.event.keyCode > 105 )
				window.event.returnValue = false;
	}
}

function validateControls() {

	var required = document.thisForm.RequiredFields.value
	
  for (var i=0; i<document.thisForm.elements.length; i++){
		var e = document.thisForm.elements[i];
		var FieldName = e.name;
		
		if (required.indexOf(FieldName + ",") >= 0) {
			if	(e.value == ""){
				alert("Input in this field is required.");
				e.focus();
				return false;
			}		
			else {
				switch (FieldName.charAt(2).toUpperCase()){
					case "N": 
						if(!isNumeric(e.value)){
				      alert("" +e.name+" must be a number");
				      e.focus();
				      return false;
				     }
						break;
				  case "C":
						break;
					case "D":
						if(!CheckDateFormat(e)){
				      e.focus();
				      return false;
				     }
				   break;
				   default:
				}			
			}
		}
  }
  return true;
}

function ForceMoney(objField, FieldName) {
	var strField = new String(objField.value);
	
	if (isWhitespace(strField)) return true;

	var i = 0;

	for (i = 0; i < strField.length; i++)
		if ((strField.charAt(i) < '0' || strField.charAt(i) > '9') && (strField.charAt(i) != '.')) {
			alert(FieldName + " must be a valid numeric entry.  Please do not use commas or dollar signs or any non-numeric symbols.");
			objField.focus();
			return false;
		}
	Money(objField);
	return true;
}


function Money(objField){
  var a = new ToFmt(objField.value);
  objField.value=a.fmtF(9,2);
}
 
function ToFmt(x){
 this.x=x;
 this.fmtF = fmtF;
 this.spacer="";
 this.setSpacer=setSpacer;
} 

function todaysDate() {
  var d, s = '';
  d = new Date();
  s += (d.getMonth() + 1) + "/";
  s += d.getDate() + "/";
  s += (d.getYear() + '').substring(2,4);
  return(s);
}

function UCase(fld) {
 fld.value=fld.value.toUpperCase();
}

function disableControls(disable) {

  for (var i=0;i<document.thisForm.elements.length;i++){
		var e = document.thisForm.elements[i];
		var type = e.type;
		if (type == "checkbox" || type == "text" || type == "textarea" || type == "radio" || type.substring(0,6) == "select" || type == "password")
		    e.disabled = disable;
  }
  //Handle controls that should not be disabled
//  if (top.topFrame.thisForm.CurrentItem.value == 'Hotel') 
		//thisForm.SPNBKFMRM.disabled = (thisForm.chkspnbkfmrmflg.checked);
}


function LocaleDate(inDate) {
  var s = '';
  var d = new Date(inDate);
  s += (d.getMonth() + 1) + "/";
  s += d.getDate() + "/";
  s += (d.getYear() + '').substring(2,4);
  return(s);
}

function CheckStartDate(BeginDate, EndDate){
  
  var d1 = new Date(BeginDate);
  var d2 = new Date(EndDate);

	if (d1.getYear() < 50)
		d1.setYear(d1.getYear() + 2000)
	
	if (d2.getYear() < 50)
		d2.setYear(d2.getYear() + 2000)

  if (d1.getTime() > d2.getTime())
		return 1;
  else
		return 0;
}

function CheckDateFormat(obj){

	var month, day, year, sep1, sep2, i, pos, count;
	
	if (obj.value == "") {return true;}
	
	count = 0
	
	while (pos != -1) {
		pos = obj.value.indexOf("/", i+1);
		i = pos;		
		if (i != -1) {
			count++;
			if (count == 1)
				sep1 = pos
		
			if (count == 2)
				sep2 = pos
		}
	}
	
	if (count > 2 || count < 2) {
		alert("Date format incorrect. Please use mm/dd/yy");
		return false;
	}
	
	month = obj.value.substring(0, sep1)
	day   = obj.value.substring((sep1+1),sep2) ;
	year  = obj.value.substring((sep2+1));	
	
	if (IsInt(month)){
		if (month < 1 || month > 12){
			alert("Month is out of acceptable range.");
			return false;	
		}
	}
	else {
		alert("Month must be a number.");
		return false;
	}
	
	if (IsInt(day)){
		if (day < 1 || day > 31){
			alert("Day is out of acceptable range.");
			return false;	
		}
    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
			alert("Month "+month+" doesn't have 31 days!")
			return false;
		}

		if (month == 2) { 
			if (year.length == 2)
				var true_year=parseInt(year)+2000;
			else
				true_year=year;
			
			var isleap = (true_year % 4 == 0 && (true_year % 100 != 0 || true_year % 400 == 0));
			
			if (day>29 || (day==29 && !isleap)) {
				alert("February " + year + " doesn't have " + day + " days!");
				return false;
			}
		}
	}
	else {
		alert("Day must be a number.");
		return false;
	}

	if (year.length % 2 != 0){
		alert("Year must be 2 or 4 characters.");
		return false;
	}
	
	if (IsInt(year)){
		if (year.length == 2){
			if (year < 00 || year > 99){
				alert("Year is out of acceptable range.");
				return false;	
			}
		}
		
		if (year.length == 4){
			if (year < 0000 || year > 2099){
				alert("Year is out of acceptable range.");
				return false;	
			}
		}
	}
	else {
		alert("Year must be a number.");
		return false;
	}
	return true
}

function IsInt(theValue){

	var newValue = theValue;
	var newLength = newValue.length
	var aChar;
	for (var i = 0; i != newLength; i++){
		aChar = newValue.substring(i, i + 1);
		if (aChar != "-")
			if (aChar < "0" || aChar > "9")  return false;
	}
	return true;
}

function isNumeric(strN)
{
  var checkOK = "0123456789.-";
  var decPoints = 0;

  for (i = 0;  i < strN.length;  i++){
    ch = strN.charAt(i);
    for (j = 0;  j < checkOK.length;  j++)
        if (ch == checkOK.charAt(j))
          break;
    if (j == checkOK.length) {
          return false;
          break;
           }
    if (ch == ".") {
          decPoints++;
           }
     }
  if (decPoints>1)
    {return false;}
    
  return (true);
}

function SetStatus(Status, Pointer) {
	window.status = Status;
	document.body.style.cursor = Pointer; 
}


function GetDate(obj) {
	var retVal = window.showModalDialog("CCalendar.asp?WCI=Calendar",0,"status:no;help:no;dialogWidth:300px;dialogHeight:250px");
	if (typeof(retVal) == "undefined" || retVal == "Cancel")
		return 1;
	obj.value = retVal;
	return 0;
}

function UpdateCheckboxField(checkBox, field) {
	field.value = ((checkBox.checked == true) ? 1:0);
}

function TabClick(Tab) {
	//Make sure the page is loaded
	if (window.PageLoaded.value == "No") {
		alert("Please wait until the page has finished loading.");
		return;
	}
	
	//Call the Save function
	//if (!Save())
	//	return; //Don't switch tabs if the save validation fails
	
	//Reset all tabs
	for (var i=1;i<(window.TabStrip.cells.length + 1);i++) {
		document.all["Tab" + i].style.backgroundColor = "#FFFFFF";
		document.all["Tab" + i].style.color = "#003366";
		window["spn" + i].style.display = "none";
	}
	document.all["Tab" + Tab].style.backgroundColor = "#6699CC";
	document.all["Tab" + Tab].style.color = "#FFFFFF";
	window.CurrentTab.value = Tab;
	window["spn" + Tab].style.display = "";
}


function DateInputValidate(startDate, startTime, endDate, endTime ) {
	date1 = new Date();
	date2 = new Date();
	diff  = new Date();
	if (CheckDateFormat(startDate) && CheckTimeFormat(startTime.value)) {
		date1temp = new Date(startDate.value + " " + startTime.value);
		date1.setTime(date1temp.getTime());
	}
	else return false; 

	if (CheckDateFormat(endDate) && CheckTimeFormat(endTime.value)) { 
		date2temp = new Date(endDate.value + " " + endTime.value);
		date2.setTime(date2temp.getTime());
	}
	else return false; 

	diff.setTime(date1.getTime() - date2.getTime());
	timediff = diff.getTime();
  if (timediff<=0){
		//alert ("Input validated.");
    return true;
	}
	else {
		//alert ("End time can't be earlier than start time");
    return false;
	}
}

function CheckTimeFormat(timeStr) {

	if (timeStr == "")
		return;
		
	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;
	var matchArray = timeStr.match(timePat);     

	if (matchArray == null) {
		alert("Time is not in a valid format.");
		return false;
	}

	hour   = matchArray[1];
	minute = matchArray[2];
	second = matchArray[4];
	ampm   = matchArray[6];

	if (second=="") { second = null; }
	if (ampm=="") { ampm = null }

	if (hour < 0  || hour > 23) {
		alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
		return false;
	}

	if (hour <= 12 && ampm == null) {
		if (confirm("Please indicate the time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
			alert("You must specify AM or PM.");
			return false;
   	}
	}

	if  (hour > 12 && ampm != null) {
		alert("You can't specify AM or PM for military time.");
		return false;
	}

	if (minute < 0 || minute > 59) {
		alert ("Minute must be between 0 and 59.");
		return false;
	}

	if (second != null && (second < 0 || second > 59)) {
		alert ("Second must be between 0 and 59.");
		return false;
	}
	return true;
}

function isWhitespace(s) {
	var i;

  // Is s empty?
  if (isEmpty(s)) return true;

  // Search through string's characters one by one
  // until we find a non-whitespace character.
  // When we do, return false; if we don't, return true.

	
  for (i = 0; i < s.length; i++) {   
		// Check that current character isn't whitespace.
		var c = s.charAt(i);

		if (whitespace.indexOf(c) == -1) 
			return false;
  }

  // All characters are whitespace.
  return true;
}

function isEmpty(s) {
	return ((s == null) || (s.length == 0))
}

function setSpacer(spc){
 var spc;
 this.spacer=spc;
 return this.spacer;
}

function fmtF(w,d){

 // fmtF: formats in a style similar to Fortran's Fw.d, where w is the
 // width of the field and d is the number of figures after the decimal
 // point. 
 // The result is aligned to the right of the field.  The default
 // padding character is a space " ". This can be modified using the 
 // setSpacer(string) method of ToFmt. 
 // If the result will not fit in the field , the field will be returned
 // containing w asterisks.
 var width=w;
 var dpls=d;
 var lt1=false;
 var len=this.x.toString().length;
 var junk;
 var res="";
// First check for valid format request
 if ( width < (dpls+2)){
  window.alert("Illegal format specified : w = " + d +
               " w = " + d +
                "\nUsage: [ToFmt].fmtF(w,d)" +
                "\nWidth (w) of field must be greater or equal to the number " +
                "\nof digits to the right of the decimal point (d) + 2");
  junk = filljunk(width);
  return junk;
 }
// Work with absolute value
 var absx=Math.abs(this.x);
// Nasty fix to deal with numbers < 1 and problems with leading zeros!
 if ((absx < 1) && (absx > 0)){
  lt1 = true;
  absx+=10;
 }
// Get postion of decimal point
 var pt_pos = absx.toString().indexOf(".");
 if ( pt_pos == -1){
  res+= absx;
  res+= ".";
  for (var i = 0; i < dpls; i++){
   res += 0;
  }  
 }
 else{
  res = Math.round(absx * Math.pow(10,dpls));
  res=res.toString();
  if (res.length == 
      Math.round(Math.floor(absx * Math.pow(10,dpls))).toString().length){ 
   res = res.substring(0,pt_pos) + "." + 
         res.substring(pt_pos,res.length);
  }
  else{
   pt_pos++;
   res = res.substring(0,pt_pos) + "." + 
          res.substring(pt_pos,res.length);
  } 
// Remove leading 1 from  numbers < 1 (Nasty fix!)
  if (lt1) {
   res=res.substring(1,res.length);
  }
 }
 // Final formatting statements
 // Reinsert - sign for negative numbers
 if (this.x < 0)res = "-"+res;
 // Check whether the result fits in the width of the field specified
 if (res.length > width){
  res=filljunk(width);
 }
 // If necessary, pad from the left with the spacer string
 else if (res.length < width){
  var res_bl="";
  for (var i = 0; i < (width - res.length); i++){
   res_bl += this.spacer ;
  } 
  res = res_bl + res;
 }
 return res;
}


//Credit Card Check.

var Cards = new makeArray(8);
Cards[0] = new CardType("MC", "51,52,53,54,55", "16");
var MC = Cards[0];
Cards[1] = new CardType("VI", "4", "13,16");
var VI = Cards[1];
Cards[2] = new CardType("AX", "34,37", "15");
var AX = Cards[2];
Cards[3] = new CardType("DN", "30,36,38", "14");
var DN = Cards[3];
Cards[4] = new CardType("DS", "6011", "16");
var DS = Cards[4];
Cards[5] = new CardType("ER", "2014,2149", "15");
var ER = Cards[5];
Cards[6] = new CardType("JC", "3088,3096,3112,3158,3337,3528", "16");
var JC = Cards[6];
var LuhnCheckSum = Cards[7] = new CardType();


function CheckCardNumber(cdNo,cdType,cdExp) {
var tmpyear;
var tmpmonth;

if (cdNo.value.length == 0 && cdExp.value.length == 0) {
return true;
}
if (cdNo.value.length == 0) {
alert("Please enter a Card Number.");
cdNo.focus();
return false;
}

if (cdExp.value.length == 0) {
alert("Please enter the Expiration Year.");
cdExp.focus();
return false;
}

if (cdType.value == "") {
alert("Please select a valid credit card type.");
cdType.focus();
return false;
}

tmpyear = cdExp.value.substr(2,2);
tmpmonth = cdExp.value.substr(0,2);

if (tmpyear > 96)
    tmpyear = "19" + temyear;
else if (tmpyear < 21)
    tmpyear = "20" + tmpyear;
else {
    alert("The Expiration Year is not valid.");
    cdExp.focus();
    return false;
}

if ( cdExp.value.substr(2,2).length == 0 || tmpmonth > 12 || tmpmonth < 1 )  {
    alert("The Expiration month is not valid.");
    cdExp.focus();
    return false;
}

if (!(new CardType()).isExpiryDate(tmpyear, tmpmonth)) {
alert("This card has already expired.");
return false;
}

card = cdType.options[cdType.selectedIndex].value;
var retval = eval(card + ".checkCardNumber(\"" + cdNo.value + "\", " + tmpyear + ", " + tmpmonth + ");");
cardname = "";
if (retval)
     {return true;   }
else {
    for (var n = 0; n < Cards.size; n++) {
      if (Cards[n].checkCardNumber(cdNo.value, tmpyear, tmpmonth)) {
         cardname = Cards[n].getCardType(); 
         break;
         }
     }
if (cardname.length > 0) {
     alert("The credit card number and type do not match.");
}
else {
     if(confirm("Your credit card info is incorrect. Click OK to continue, Cancel to change your card information.")){
			  bClearCardInfo = true;
        return true;
     }
		 	  bClearCardInfo = false;
				cdNo.focus(); 
     }
  }
}


function CardType() {
var n;
var argv = CardType.arguments;
var argc = CardType.arguments.length;

this.objname = "object CardType";

var tmpcardtype = (argc > 0) ? argv[0] : "CardObject";
var tmprules = (argc > 1) ? argv[1] : "0,1,2,3,4,5,6,7,8,9";
var tmplen = (argc > 2) ? argv[2] : "13,14,15,16,19";

this.setCardNumber = setCardNumber;  // set CardNumber method.
this.setCardType = setCardType;  // setCardType method.
this.setLen = setLen;  // setLen method.
this.setRules = setRules;  // setRules method.
this.setExpiryDate = setExpiryDate;  // setExpiryDate method.

this.setCardType(tmpcardtype);
this.setLen(tmplen);
this.setRules(tmprules);
if (argc > 4)
this.setExpiryDate(argv[3], argv[4]);

this.checkCardNumber = checkCardNumber;  // checkCardNumber method.
this.getExpiryDate = getExpiryDate;  // getExpiryDate method.
this.getCardType = getCardType;  // getCardType method.
this.isCardNumber = isCardNumber;  // isCardNumber method.
this.isExpiryDate = isExpiryDate;  // isExpiryDate method.
this.luhnCheck = luhnCheck;// luhnCheck method.
return this;
}

function checkCardNumber() {
var argv = checkCardNumber.arguments;
var argc = checkCardNumber.arguments.length;
var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;
var year = (argc > 1) ? argv[1] : this.year;
var month = (argc > 2) ? argv[2] : this.month;

this.setCardNumber(cardnumber);
this.setExpiryDate(year, month);

if (!this.isCardNumber())
return false;
if (!this.isExpiryDate())
return false;

return true;
}
function getCardType() {
return this.cardtype;
}
function getExpiryDate() {
return this.month + "/" + this.year;
}
function isCardNumber() {
var argv = isCardNumber.arguments;
var argc = isCardNumber.arguments.length;
var cardnumber = (argc > 0) ? argv[0] : this.cardnumber;
if (!this.luhnCheck())
return false;

for (var n = 0; n < this.len.size; n++)
if (cardnumber.toString().length == this.len[n]) {
for (var m = 0; m < this.rules.size; m++) {
var headdigit = cardnumber.substring(0, this.rules[m].toString().length);
if (headdigit == this.rules[m])
return true;
}
return false;
}
return false;
}

function isExpiryDate() {
var argv = isExpiryDate.arguments;
var argc = isExpiryDate.arguments.length;

year = argc > 0 ? argv[0] : this.year;
month = argc > 1 ? argv[1] : this.month;

if (!isNum(year+""))
return false;
if (!isNum(month+""))
return false;
today = new Date();
expiry = new Date(year, month);
if (today.getTime() > expiry.getTime())
return false;
else
return true;
}

function isNum(argvalue) {
argvalue = argvalue.toString();

if (argvalue.length == 0)
return false;

for (var n = 0; n < argvalue.length; n++)
if (argvalue.substring(n, n+1) < "0" || argvalue.substring(n, n+1) > "9")
return false;

return true;
}

function luhnCheck() {
var argv = luhnCheck.arguments;
var argc = luhnCheck.arguments.length;

var CardNumber = argc > 0 ? argv[0] : this.cardnumber;

if (! isNum(CardNumber)) {
return false;
  }

var no_digit = CardNumber.length;
var oddoeven = no_digit & 1;
var sum = 0;

for (var count = 0; count < no_digit; count++) {
var digit = parseInt(CardNumber.charAt(count));
if (!((count & 1) ^ oddoeven)) {
digit *= 2;
if (digit > 9)
digit -= 9;
}
sum += digit;
}
if (sum % 10 == 0)
return true;
else
return false;
}

function makeArray(size) {
this.size = size;
return this;
}

function setCardNumber(cardnumber) {
this.cardnumber = cardnumber;
return this;
}

function setCardType(cardtype) {
this.cardtype = cardtype;
return this;
}

function setExpiryDate(year, month) {
this.year = year;
this.month = month;
return this;
}


function setLen(len) {
// Create the len array.
if (len.length == 0 || len == null)
len = "13,14,15,16,19";

var tmplen = len;
n = 1;
while (tmplen.indexOf(",") != -1) {
tmplen = tmplen.substring(tmplen.indexOf(",") + 1, tmplen.length);
n++;
}
this.len = new makeArray(n);
n = 0;
while (len.indexOf(",") != -1) {
var tmpstr = len.substring(0, len.indexOf(","));
this.len[n] = tmpstr;
len = len.substring(len.indexOf(",") + 1, len.length);
n++;
}
this.len[n] = len;
return this;
}
function setRules(rules) {
// Create the rules array.
if (rules.length == 0 || rules == null)
rules = "0,1,2,3,4,5,6,7,8,9";
  
var tmprules = rules;
n = 1;
while (tmprules.indexOf(",") != -1) {
tmprules = tmprules.substring(tmprules.indexOf(",") + 1, tmprules.length);
n++;
}
this.rules = new makeArray(n);
n = 0;
while (rules.indexOf(",") != -1) {
var tmpstr = rules.substring(0, rules.indexOf(","));
this.rules[n] = tmpstr;
rules = rules.substring(rules.indexOf(",") + 1, rules.length);
n++;
}
this.rules[n] = rules;
return this;
}

function FormatMoney(ctl, val) {

	var tmp = "";
	
  if (val == "") {
	ctl.value = "0.00";
	}
	else {
	
  val -= 0;
  val = (Math.round(val*100))/100;
  tmp = (val == Math.floor(val)) ? val + '.00' : ( (val*10 == Math.floor(val*10)) ? val + '0' : val);

  if (isNaN(tmp)) {
		alert("Please enter a valid number");
		ctl.value = "";
		ctl.focus();
	}		
	else
		ctl.value = tmp;
}

}
