//***************************************************
// Removes leading and trailing blanks from a string
//
//***************************************************
function Trim(InString)
{
while(InString.length > 0 && InString.substring(0,1) == " ")
   {
   InString = InString.substring(1,InString.length)
   }

while(InString.length > 0 && InString.substring(InString.length-1,InString.length) == " ")
   {
   InString = InString.substring(0,InString.length-1)
   }
return InString
}

//***************************************************
// Insert commas into a  number at an interval of three eg 1234567
// becomes 1,234,567.  Also can set the number of decimal points
//
//***************************************************
function insertCommas(number, dec) {
   number = '' + number
   dec = '' + dec

   x = number.indexOf(".")
   y = number.length
   if (x > 0) {
      decimal = true
      prefix = number.substring(0,x)
      postfix = number.substring(x+1, y)
   }
   else {
      decimal = false
      prefix = number
      postfix = ''
   }

   if (prefix.length > 3) {
      var mod = prefix.length % 3
      var output = (mod > 0 ? (prefix.substring(0,mod)) : '')
      for (i=0 ; i < Math.floor(prefix.length / 3) ; i++) {
         if ((mod == 0) && (i == 0))
            output+= prefix.substring(mod + 3 * i,mod + 3 * i + 3)
         else
            output+= ',' + prefix.substring(mod + 3 * i,mod + 3 * i + 3)

      }
   }
   else {
      output = prefix
   }

   if (decimal == true || dec > 0) {
      if (postfix.length > 0) {
         len = postfix.length
      }
      else {
         len = 0
      }

      while (len < dec) {
         postfix = postfix + '0'
	 len = len + 1
      }

      if (len > dec) {
         postfix = postfix.substring(0,dec)
      }

      number = output + '.' + postfix
   }
   else {
      number = output
   }

   return number

}

//***************************************************
// remove the commas from a number
//
//***************************************************
function removeCommas(InString) {
        var re = /,/g
        InString = InString.value.replace(re,"")
	return InString.value
}

//***************************************************
// Subtract a number of days from a date - Requires a date object as inDate.
//
//***************************************************
function subDays(inDate, noDays) {
   inDate = new Date(inDate)
   noDays = '' + noDays
   outDate = new Date()

   days = new Array(12)
      days[0] = 31
      days[1] = 28
      days[2] = 31
      days[3] = 30
      days[4] = 31
      days[5] = 30
      days[6] = 31
      days[7] = 31
      days[8] = 30
      days[9] = 31
      days[10] = 30
      days[11] = 31

   day = inDate.getDate()
   month = inDate.getMonth()
   year = inDate.getFullYear()

   day = day - noDays
   if (day == 0) {
      month = month - 1
      if (month == 0) {
         year = year - 1
         month = 11
         day = 31
      }
      else {
         if (month == 2) {
            if (year % 4 == 0) {
               days[1] = 29
            }
         }
      }
   }

   outDate.setFullYear(year, month, day)
   return outDate
}

//***************************************************
// Returns a date in DD/MM/YYYY (8 long)format eg if today = 1/1/2000 returns 01012000
//
//***************************************************
function formatDate(inDate) {
  var date = new Date(inDate)

  day = '' + today.getDate()
  if (day.length == 1) {
    day = '0' + day.tostring
  }

  month = today.getMonth() + 1
  monthStr = '' + month
  if (monthStr.length == 1) {
    monthStr = '0' + monthStr
  }
  year = '' + today.getFullYear()

  x = 1
  if (today.getDay() == 1) {
    x = 3
  }

  outDate = day + monthStr + year
  return outDate
}

//***************************************************
// the next function parses a date in the format DD/MM/YYYY
// and returns a Date object - 'NULL' if invalid
//
//***************************************************
function parseDate(IDate) {
  err = 0
  day = 0
  month = 0
  year = 0
  i = IDate.indexOf('/')
  if (i > 0) {
    day = IDate.slice(0, i)
  }

  j = IDate.indexOf('/', i+1)
  if (j > 0) {
    month = IDate.slice(i+1, j)
  }
  year = IDate.slice(j+1)


  //basic error checking
  if (month<1 || month>12 || isNaN(month)) err = 1
  if (day<1 || day>31 || isNaN(day)) err = 1
  if (isNaN(year)) {
    err = 1
  }
  else {
    x=parseInt(year/1)
    if (x <= 39) {
      year = x + 2000
    }
    else {
      if (x > 39 && x < 1000) {
        year = x + 1900
      }
    }
  }


  //***************************************************
  //advanced error checking
  //
  //***************************************************

  //***************************************************
  // months with 30 days
  //
  //***************************************************
  if (month==4 || month==6 || month==9 || month==11){
    if (day==31) err=1
  }

  // february, leap year
  if (month==2){
    // feb
    var g=parseInt(year/4)
    if (isNaN(g)) {
      err=1
    }

    if (day>29) err=1
    if (day == 29) {
      if ((year/4)!=parseInt(year/4)) err=1

	  if ((year/100) == parseInt(year/100)) {
	    if ((year/1000) != parseInt(year/1000)) {
	      err=1;
		}
	  }

    }
  }

  if (err != 1) {
    month = month - 1
    ODate = new Date(year, month, day)
    return ODate
  }
  else {
    return 'NULL'
  }
} // End Parse Date. 

//****************************************************************************
function futureDate( theDate) {
	var selectedDate = parseDate( theDate ).getTime() ;
	var theDateNow = new Date().getTime();
	if( selectedDate > theDateNow ) {
		return true;
	}
	else {
		return false;
	}
}

//***************************************************
// This function just parses the Card type into what is expected by the CheckCC function
// and calls that.
//
//***************************************************
function CheckCC2(CC_Num, CC_Type) {
	type2 = "";
	if (CC_Type == "VS") {
		type2 = "Visa"
	}

	if (CC_Type == "AX") {
		type2 = "American Express"
	}

	if (CC_Type == "BC") {
		type2 = "Bank Card"
	}

	if (CC_Type == "DC") {
		type2 = "Diners Club"
	}

	if (CC_Type == "MC") {
		type2 = "Master Card"
	}

	return CheckCC(CC_Num, type2);
}

<!-- JavaScript by ADI Associates, Inc. - public domain 1999
// ---------------------------------------------------------------------
function CheckCC(CC_Num,CC_Type)
  // ---------------------------------------------------------------------
  {
//  CC_Num = CC_Num.substring(1,CC_Num.length);
//  CC_Type = CC_Type.substring(1,CC_Type.length);
  // ---------------------------------------------------------------------
  // CCN_digits stores just the digits from the Credit Card Number
  // ---------------------------------------------------------------------
  var CCN_digits = ""

  // ---------------------------------------------------------------------
  // get the digits from the entered Card Number
  // Note - the isNaN (Not a Number) function is not used
  // because it is not supported by JavaScript 1.0
  // ---------------------------------------------------------------------

  for (var i = 0; i < CC_Num.length; i++)
    {
    if ((CC_Num.charAt(i) == "0") ||
        (CC_Num.charAt(i) == "1") ||
        (CC_Num.charAt(i) == "2") ||
        (CC_Num.charAt(i) == "3") ||
        (CC_Num.charAt(i) == "4") ||
        (CC_Num.charAt(i) == "5") ||
        (CC_Num.charAt(i) == "6") ||
        (CC_Num.charAt(i) == "7") ||
        (CC_Num.charAt(i) == "8") ||
        (CC_Num.charAt(i) == "9"))
      {
      CCN_digits = CCN_digits + CC_Num.charAt(i);
    }
    else {
    }

  }

  // ---------------------------------------------------------------------
  // validcard is the true/false indicator for a valid card
  //  - it is returned to the calling routine.
  // ---------------------------------------------------------------------
  var validcard = false;

  // ---------------------------------------------------------------------
  // msgind is used to communicate the type of alert to
  // post in case of a problem
  //    1=invalid prefix (prefix does not match card type)
  //    2=invalid number of digits in card number
  //        for the card type selected
  // ---------------------------------------------------------------------
  var msgind = 0;

  // ---------------------------------------------------------------------
  // Check the card for having a valid prefix and number of
  // digits (length) for the card type.
  // Note - the if, else if construct was used here because
  // switch/case is not supported by JavaScript 1.0
  // ---------------------------------------------------------------------
  // VALID LENGTH AND PREFIX VALUES
  // ---------------------------------------------------------------------
  //        	AMEX	Diners		Master		Visa	Bank Card
  //                                    Card
  //
  // LENGTHS	15	   14		16		13/16	16

  // PREFIXES	34 & 37	   36 & 38	51 - 55		4	56105 and 56022

  if (CC_Type == "American Express")
    if (CCN_digits.length == 15)
      if ((CCN_digits.substring (0, 2) == "34") ||
          (CCN_digits.substring (0, 2) == "37"))
        validcard = true;
      else
        msgind = 1;
    else
      msgind = 2;
  else if (CC_Type == "Bank Card")
    if (CCN_digits.length == 16)
      if ((CCN_digits.substring (0, 5) == "56105") ||
          (CCN_digits.substring (0, 5) == "56022"))
        validcard = true;
      else
        msgind = 1;
    else
      msgind = 2;
  else if (CC_Type == "Diners Club")
    if (CCN_digits.length == 14)
      if ((CCN_digits.substring (0, 2) == "36") ||
          (CCN_digits.substring (0, 2) == "38"))
        validcard = true;
      else
        msgind = 1;
    else
      msgind = 2;
  else if (CC_Type == "Master Card")
    if (CCN_digits.length == 16)
      if ((CCN_digits.substring (0, 2) >= "51") &&
          (CCN_digits.substring (0, 2) <= "55") &&
          (CCN_digits != "5454545454545454"))
        validcard = true;
      else
        msgind = 1;
    else
      msgind = 2;
  else if (CC_Type == "Visa")
    if ((CCN_digits.length == 16) ||
        (CCN_digits.length == 13))
      if (CCN_digits.substring (0, 1) == "4" && CCN_digits != "4242424242424242")
        validcard = true;
      else
        msgind = 1;
    else
      msgind = 2;
  else
    // ---------------------------------------------------------------------
    // Invalid card type - this should be impossible to reach as
    // long  as all valid card types are in the list above....
    // ---------------------------------------------------------------------
    alert ("Sorry, "+ CC_Type + " is not currently being accepted - please contact us by phone or email.");

  if (CC_Num.indexOf(" ") >= 0) {
    validcard = false;
    msgind = 3;
  }

  if (!validcard)
    {
    if (msgind == 1)
      // ---------------------------------------------------------------------
      //            Invalid prefix
      // ---------------------------------------------------------------------
      alert ("The Card Number ("+CC_Num + ") and the Card Type (" + CC_Type + ") do not match.");
    else if (msgind == 2)
      // ---------------------------------------------------------------------
      //            Invalid number of digits (length)
      // ---------------------------------------------------------------------
      alert ("The Card Number ("+CC_Num + ") is not the right length for the Card Type (" + CC_Type + ").");
    else if (msgind == 3)
      // ---------------------------------------------------------------------
      //            Space in the number not allowed
      // ---------------------------------------------------------------------
      alert ("The Card Number ("+ CC_Num + ") is invalid.  Please remove the spaces");
   }
   if (!validcard)
     return (validcard);

   // ---------------------------------------------------------------------
   // Perform the mod10 check sum routine on the
   //  digits in the card number
   //    1) Go through the Credit Card Number digits, starting on
   //        the RIGHT.
   //            If the position is odd
   //                 add the digit to the checksum tally.
   //            If the position is even
   //                 multiply the digit by 2
   //                 if the result is greater than 9
   //                     divide the result by 10
   //                     and add the remainder
   //                         to the checksum tally
   //                     add 1 to the checksum tally
   //                 if the result is 9 or less
   //                     add the result to the checksum tally
   //        Repeat for each digit.
   //    2) Divide the checksum tally by 10
   //    3) If there is a remainder
   //                     the Credit Card Number is not valid.
   // ---------------------------------------------------------------------
   var CheckSum = 0;
   // ---------------------------------------------------------------------
   // for loop to look at the Credit Card Number
   // ---------------------------------------------------------------------
   for (var x = 1; x <= CCN_digits.length; x++)
     {
     // ---------------------------------------------------------------------
     // x is subtracted from the length of the CCN
     // to point at the digits from RIGHT to LEFT
     // ---------------------------------------------------------------------
     var CurrentDigit = CCN_digits.charAt
     (CCN_digits.length - x);
     if (x % 2 == 0)
       {
       // ---------------------------------------------------------------------
       // even position in credit card number
       // (2nd, 4th, etc. from RIGHT of Credit Card Number)
       // ---------------------------------------------------------------------
       var WorkDigit = CurrentDigit * 2;
       if (WorkDigit > 9)
         {
         CheckSum = CheckSum + (1 - 0);
         CheckSum = CheckSum + (WorkDigit % 10);
       }
       else
         {
         CheckSum = CheckSum + (WorkDigit - 0);
       }
     }
     else
       {
       // ---------------------------------------------------------------------
       // odd position in credit card number
       // (1st, 3rd, etc. from RIGHT of Credit Card Number)
       // ---------------------------------------------------------------------
       CheckSum = CheckSum + (CurrentDigit - 0);
     }
   }
   // ---------------------------------------------------------------------
   // end for loop
   // ---------------------------------------------------------------------
   if (CheckSum % 10)
     {
     // ---------------------------------------------------------------------
     // The CheckSum does not divide evenly by 10
     // ---------------------------------------------------------------------
     validcard = false;
     alert ("I'm sorry, the Card Number ("+ CC_Num +") is not correct - perhaps there is a typo or two numbers are reversed?");
   }
   return (validcard);
}
// ---------------------------------------------------------------------
// end function
// ---------------------------------------------------------------------
//-->


//***************************************************
// Checks the syntax of the email address passed and returns true or false
//
//***************************************************
function checkMail(email)
{
    var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (filter.test(email)) return true;
    else {
		return false;
	}
}

//***************************************************
// Displays Image in individual window
// use in conjunction with anchor
// eg <a href="javascript:ShowImage('/image/path/image.jpg')">
//
//***************************************************
function ShowImage(ImageToDisplay)
{
    ShowWindow=window.open("","","height=600,width=900,scrollbars,resizable=yes")
    ShowWindow.document.write("<HTML><HEAD><TITLE>BoysTown Lotteries</title></head>")
    ShowWindow.document.write("<body bgcolor='WHITE' text='BLACK' onBlur='window.close()'>")
    ShowWindow.document.write("<center><font face='Verdana, Lucida Sans, Arial' size='1'>Right click on the picture to save it<br>")
    ShowWindow.document.write("<center>Close the window after viewing<br></font>")
    ShowWindow.document.write("<img src=",ImageToDisplay , "></center></body></head></html>")
}

//***************************************************
/*
	This function highlights (read Bolds) the text
	inside the associated Label tag and rests
	the text in all other labels for the same group
	of radiobuttons.

	To call this function just add on onClick event like so
	<input type='radio' name='button' id='button1' onclick='highlightRadioButton(this);'/>

	You also need a label that is associated via the "for" attribute
	with an "id" that is the same as the "id" + "Label"

	So for the radioButton defined above we would have
	<label id= 'button1Label' for='button1'> Label for button 1</label>
*/
function highlightRadioButton(radioButton) {
	// get the array of radiobuttone with the passed in name
	var buttons = document.getElementsByName(radioButton.name);
	// If we got some radio buttons
	if (buttons) {
		// and there is a list of them
		if (buttons.length) {
			// loop through them and make them all normal
			for (i = 0; i < buttons.length; i++) {
				var label = document.getElementById(buttons[i].id + 'Label');
				label.style.fontWeight = 'normal';
			}
		}
	}

	// now just highlight the clicked one
	// get the id
	var id = radioButton.id;
	// and if it's checked
	if (document.getElementById(id).checked) {
		// highlight the associated label
		var label = document.getElementById(id + 'Label');
		label.style.fontWeight = "bold";
	}
}

/*
	function addHoverToolTip
	Add a dojo/dijit hovertooltip to an element.
 */
function addHoverToolTip(hoverObjId, url) {
//	if (typeof(dijit) != 'undefined' && dijit.showTooltip) {
	if (typeof(dijit) != 'undefined' && dijit.showTooltip) {
		var	hoverObj = dojo.byId(hoverObjId);
		dojo.addOnLoad(function () {buildHoverToolTip(hoverObj,url)});
	} else {
		var	hoverObj = dojo.byId(hoverObjId);
		hoverObj.title = hoverObj.title + " Unable to show hover tooltip. Dojo libraries have not been included.";
	}
}

/*
	function buildHoverToolTip
	Build the dojo/dijit hovertooltip so that it gets the tooltip info
	from a url
 */
 // assume the tooltip should be displayed
var dispTT = true;
function buildHoverToolTip(hoverObj, url) {
	// id of the object we are hovering over
	var connectTo = hoverObj.id;
	// build the tooltip with 'Loading. . .' as the content
	// and connect it to the hoverObj

	// now for the magic = We change the contents of the tooltip by connecting
	// the mouseover event to get the contents from the passed url
	var objId = hoverObj.id;

	hoverObj.hf = function () {
		// only do it once - we don't need to get the contents twice
		var dijitId = objId + "Tooltip";
		if (!dijit.byId(dijitId)) {
			// Tooltip hover started - create it
			dispTT = true;
			console.log("Creating Tooltip");
			dojo.xhrGet({
				url: url,
				load: function(response, ioArgs) {
					console.log("Tooltip contents retrieved");
					var ttNode = new dijit.Tooltip({label: response, connectId: [connectTo], showDelay: 500, id: dijitId});
					// Still hovering then open it
					// it's possible that the user stopeed hovering 
					// in which case the "onmouseout" event below would have
					// executed, but our Tooltip has already been created
					// so only display it if dispTT is still ok with it
					if (dispTT) {
						console.log("Showing Tooltip " + dijitId);
						ttNode.open();
					}
					return response;
				},
				error: function(response, ioArgs) {
					// if we couldn't get in 3 seconds just show nothing
					// The server may be busy and the user can just try again
					return response;
				},
				timeout: 3000,
				handleAs: 'text'
			});
		} else {
				console.log("Tooltip already exists");
		}
	};

	dojo.connect(hoverObj, 'onmouseover', function() {hoverObj.hfId = setTimeout("dojo.byId('" + objId +"').hf()", 500);});
	dojo.connect(hoverObj, 'onmouseout', function() {clearTimeout(hoverObj.hfId); dispTT = false; });

}

function hideHoverToolTip(objId) {
	var dijitId = objId + "Tooltip";
	var tt = dijit.byId(dijitId);
	if (tt) {
		tt.close();
	}
}


// This function is used by the buildMultiStaffSelectGenerator PHP function.
// this function is called when a selection is made form a user select
// that is part of div that allows a person to select multiple users
// the select object that invked this method is passed
// and the root name for this select
function multiStaffSelected( selectBox , fieldName ) {

	var lastIndex = 1;
	var anyEmpty = false;

	// check all the selects in the Div - if the are no empty ones then add one to the end of the list
	while( dijit.byId( fieldName + lastIndex ) ) {
		if ( dijit.byId( fieldName + lastIndex ).getValue() == ""	) {
			anyEmpty = true;
		}
		lastIndex = lastIndex + 1;
	}

	if (anyEmpty == false) {

		var newName = fieldName + lastIndex;
		var newUserSelect = document.createElement("select");
		newUserSelect.id = newName;
		newUserSelect.name = newName;

		// append a break
		var msDiv = dojo.byId(fieldName + "MSD");
		var brElement = document.createElement("br");
		msDiv.appendChild(brElement);

		// copy the selectBox
		msDiv.appendChild(newUserSelect);

		var params="({'name': '" 
			+ newName 
			+ "', 'autoComplete': false, 'store': " 
			+ fieldName 
			+ "Store, 'class':'multiUserSelect', 'queryExpr': '*${0}*'})";
		params = eval(params);
		var newSel = new dijit.form.FilteringSelect(params, newUserSelect);
		newSel.focus();
		dojo.connect(newSel, "onBlur", function () {
			if (newSel.value == "" || !newSel.value) {newSel.setDisplayedValue("");}});
		newSel.connect(newSel, "onChange", function () {multiStaffSelected(dojo.byId(newName), fieldName);});
	}
} // end userSelect function.



//****************************************************************
function isValidTime(timeStr) {
	// Checks if time is in HH:MM:SS AM/PM format.
	// The seconds and AM/PM are optional.

	var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

	var matchArray = timeStr.match(timePat);
	if (matchArray == null) {
		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) {
		return false;
	}
	if (hour <= 12 && ampm == null) {
//		alert("hour: " + hour);
//		return false;
	}
	if  (hour > 12 && ampm != null) {
//			alert("hour > ");
			return false;
	}
	if (minute<0 || minute > 59) {
//		alert("min");
		return false;
	}
	if (second != null && (second < 0 || second > 59)) {
//		alert("sec");
		return false;
	}
	return true;
} // end isValidTime




// Determine the value of a radio button.
function checkedValue(parmBtn) {
	btn = document.getElementsByName(parmBtn);
	var cnt = -1;
	for (var i=btn.length-1; i > -1; i--) {
		if (btn[i].checked) {cnt = i; i = -1;}
	}
	if (cnt > -1) return btn[cnt].value;
	else return null;
} // end valButton
	
