/*
http://skipbinsonline.com.au/system/request.js
http://skipbinsonline.com.au/system/3rdparty/JasonsDateInputCalendar/calendarDateInput.js
http://skipbinsonline.com.au/system/3rdparty/autosuggest/js/bsn.AutoSuggest_2.1.3.js
http://skipbinsonline.com.au/system/templates/default/resources/instantquote.js
*/
	var currentTime = new Date();
	var month = currentTime.getMonth()+1;
	var day = currentTime.getDate();
	var year = currentTime.getFullYear();
	
	function strReplace(search, replace, string){
		return string.split(search).join(replace);
	}
	function IsNumeric(input)
	{
	   return (input - 0) == input && input.length > 0;
	}

	function eftnotification(days){
		var BinSize = document.getElementById('BinSize');
		var InstantQuoteRight = document.getElementById('InstantQuoteRight');

		if (BinSize.selectedIndex != 0 && InstantQuoteRight.innerHTML.indexOf('EFT Payments')==-1){
			InstantQuoteRight.innerHTML = strReplace("br", "span", InstantQuoteRight.innerHTML);
			InstantQuoteRight.innerHTML = "<br /><br />" + InstantQuoteRight.innerHTML +  '<font color="#008000"><b>Reminder - EFT Payments</b> available <u>only</u> for skip bins booked with a <b>delivery date</b> '+days+' business days in advance.</font>';
		}
	}
	
	function submitQuote(URL){
		InstantQuote = document.getElementById('instantquote');	

		Input = InstantQuote.postcode.value;
		
		//Validate Blank Input
		if ( Input.length == 0 ){
			alert("Please enter a suburb or postcode.");
			return false;
		}
		
		// CHeck Bin Size & Waste Cats
		if ( document.getElementById("WasteCategory").selectedIndex == 0 ){
			alert("Please select a Waste Type.");
			return false;
		}
		
		//Convert to URL-SAFE
		if ( Input.search(', ') != -1  ){
			PostCode = Input.split(', ')[1];
			Suburb = Input.split(', ')[0];
		}else{
			PostCode = Input;
			Suburb = Input;
		}

		PostCode	= strReplace(' ', '-', (PostCode));
		Suburb		= strReplace(' ', '-', (Suburb));
		
		//Validate Selection
		if ( Input.search(', ') == -1){
			/** If no proper suburb, postcode selection - check if a postcode **/
			if ( is_numeric(Input) ){
				InstantQuote.action =	URL + 'bin-options/' +
									InstantQuote.category[InstantQuote.category.selectedIndex].value + '/' +
									PostCode + '/';
			}else{
				/** If not a postcode, forward to find-a-bin/ **/
				InstantQuote.action =	URL + 'find-a-bin/';
			}
		}else{
			InstantQuote.action =	URL + 'bin-options/' +
								InstantQuote.category[InstantQuote.category.selectedIndex].value + '/' +
								PostCode + '/' + Suburb + '/';
		}
		
		InstantQuote.submit();
		return false;
	}

	function setOpacity( objectID, value ) {
		object = document.getElementById(objectID);
		object.style.opacity = value / 10;
		object.style.filter = 'alpha(opacity=' + value * 10 + ')';
	}

	function fadeInMyPopup(objectID) {
		for( var i = 0 ; i <= 100 ; i++ )
			setTimeout( 'setOpacity("' + objectID + '",' + (i / 10) + ')' , 3 * i );
	}

	function fadeOutMyPopup(objectID) {
		for( var i = 0 ; i <= 100 ; i++ ) {
			setTimeout( 'setOpacity("' +objectID+ '",' + (10 - i / 10) + ')' , 8 * i );
		}

		setTimeout('closeMyPopup('+object+')', 800 );
	}

	function closeMyPopup(objectID) {
		object = document.getElementById(objectID);
		object.style.display = "none"
	}

	function fireMyPopup(objectID) {
		object = document.getElementById(objectID);
		
		setOpacity( objectID, 0 );
		object.style.display = "block";
		fadeInMyPopup(objectID);
	}
	
	function displayWasteDesc( Position ){
		Div = document.getElementById(Position);
		Field = document.getElementById("WasteCategory");

		Category = Field[Field.selectedIndex].value;

		if ( Category.value = '' ) return false;

		if ( Position == 'InstantQuoteLeft' ){
			Div.style.left = '30px'; 
			Div.style.width = '325px'; 
		}else{
			Div.style.padding = '10px';
			Div.style.left = '655px'; 
			Div.style.width = '325px'; 
		}
		Div.innerHTML = document.getElementById("waste_"+Category).innerHTML;
		fireMyPopup(Position);
	}

	function displayBinSize(Position, ImageDir){
		Field = document.getElementById("BinSize");
		BinSize = Field[Field.selectedIndex].value;

		if ( BinSize.value = '' ) return false;

		document.getElementById(Position).style.left = '655px'; 
		document.getElementById(Position).innerHTML = "<br /><br /><br /><br /><center><b>"+BinSize+" Cubic Metres Skip Bin</b><br /><img class='InlinePopupImg' src='"+ ImageDir + BinSize + "%20metre.gif' />"

		fireMyPopup(Position);
	}
	function is_numeric (mixed_var) {
		return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
	}
	
	function resetInstantQuote(){
		document.getElementById("WasteCategory").selectedIndex=0;
		BinSizeElement = document.getElementById("BinSize");
		BinSizeElement.selectedIndex=0;
		BinSizeElement[0].text="Select a Bin Size";
		BinSizeElement.readonly=true;
	}
	
	function loadBinSizeOptions(BaseURL, PostcodeID, WasteCatID, BinSizeID){
		var Postcode = document.getElementById(PostcodeID);
		var WasteCat = document.getElementById(WasteCatID);
		var BinSizeField = document.getElementById(BinSizeID);

		// Lockout Bin Options		
		BinSizeField.disabled = true;
		BinSizeField[0].text = "Loading..."
		BinSizeField[BinSizeField.selectedIndex].text = "Loading..."
	
		RemoteUpdateSelect(BaseURL + "system/availablebinsizes.php?category=" + WasteCat[WasteCat.selectedIndex].value + "&postcode=" + Postcode.value, BinSizeField, "Select a Bin Size");
	}
	
	function RemoteUpdateSelect(URL, Element, Default)
	{
	
		var xmlhttp;
		if (window.XMLHttpRequest)
		  {// code for IE7+, Firefox, Chrome, Opera, Safari
		  xmlhttp=new XMLHttpRequest();
		  }
		else
		  {// code for IE6, IE5
		  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		xmlhttp.onreadystatechange=function()
		  {
		  if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				ReturnData = xmlhttp.responseText;
				if (ReturnData == 'nobins'){
					Element.length=1;
					Element[0].text = "No Available Bins"
					Element[0].value = ""
					return true;
				}
				
				ReturnData = ReturnData.split("|");
				
				Element.length=1;
				Element.length = ReturnData.length + 1;
				

				Element[0].text = Default;
				Element[0].value = "";

				
				for(o=0; o < ReturnData.length; o++){
					Element[o+1].text = ReturnData[o] + " cubic metres";
					Element[o+1].value = ReturnData[o];
				}
				
				Element.disabled = false;
			}
		  }
		xmlhttp.open("GET", URL, true);
		xmlhttp.send();
	}
/**
 *  author:Timothy Groves - http://www.brandspankingnew.net
 *version:1.2 - 2006-11-17
 *              1.3 - 2006-12-04
 *              2.0 - 2007-02-07
 *              2.1.1 - 2007-04-13
 *              2.1.2 - 2007-07-07
 *              2.1.3 - 2007-07-19
 *
 */
if (typeof(bsn) == "undefined")
_b = bsn = {};
if (typeof(_b.Autosuggest) == "undefined")
_b.Autosuggest = {};
else
alert("Autosuggest is already set!");
_b.AutoSuggest = function (id, param)
{
// no DOM - give up!
//
if (!document.getElementById)
return 0;




// get field via DOM
//
this.fld = _b.DOM.gE(id);
if (!this.fld)
return 0;




// init variables
//
this.sInp = "";
this.nInpC = 0;
this.aSug = [];
this.iHigh = 0;




// parameters object
//
this.oP = param ? param : {};

// defaults
//
var k, def = {minchars:1, meth:"get", varname:"input", className:"autosuggest", timeout:2500, delay:500, offsety:-5, shownoresults: true, noresults: "No results!", maxheight: 250, cache: true, maxentries: 25, divwidth:"100%"};
for (k in def)
{
if (typeof(this.oP[k]) != typeof(def[k]))
this.oP[k] = def[k];
}


// set keyup handler for field
// and prevent autocomplete from client
//
var p = this;

// NOTE: not using addEventListener because UpArrow fired twice in Safari
//_b.DOM.addEvent( this.fld, 'keyup', function(ev){ return pointer.onKeyPress(ev); } );

this.fld.onkeypress = function(ev){ return p.onKeyPress(ev); };
this.fld.onkeyup = function(ev){ return p.onKeyUp(ev); };

this.fld.setAttribute("autocomplete","off");
};
_b.AutoSuggest.prototype.onKeyPress = function(ev)
{

var key = (window.event) ? window.event.keyCode : ev.keyCode;
// set responses to keydown events in the field
// this allows the user to use the arrow keys to scroll through the results
// ESCAPE clears the list
// TAB sets the current highlighted value
//
var RETURN = 13;
var TAB = 9;
var ESC = 27;

var bubble = 1;
switch(key)
{
case RETURN:
this.setHighlightedValue();
bubble = 0;
break;
case ESC:
this.clearSuggestions();
break;
}
return bubble;
};
_b.AutoSuggest.prototype.onKeyUp = function(ev)
{
var key = (window.event) ? window.event.keyCode : ev.keyCode;

// set responses to keydown events in the field
// this allows the user to use the arrow keys to scroll through the results
// ESCAPE clears the list
// TAB sets the current highlighted value
//
var ARRUP = 38;
var ARRDN = 40;

var bubble = 1;
switch(key)
{
case ARRUP:
this.changeHighlight(key);
bubble = 0;
break;
case ARRDN:
this.changeHighlight(key);
bubble = 0;
break;


default:
this.getSuggestions(this.fld.value);
}
return bubble;

};
_b.AutoSuggest.prototype.getSuggestions = function (val)
{

// if input stays the same, do nothing
//
if (val == this.sInp)
return 0;


// kill list
//
_b.DOM.remE(this.idAs);


this.sInp = val;


// input length is less than the min required to trigger a request
// do nothing
//
if (val.length < this.oP.minchars)
{
this.aSug = [];
this.nInpC = val.length;
return 0;
}




var ol = this.nInpC; // old length
this.nInpC = val.length ? val.length : 0;



// if caching enabled, and user is typing (ie. length of input is increasing)
// filter results out of aSuggestions from last request
//
var l = this.aSug.length;
if (this.nInpC > ol && l && l<this.oP.maxentries && this.oP.cache)
{
var arr = [];
for (var i=0;i<l;i++)
{
if (this.aSug[i].value.substr(0,val.length).toLowerCase() == val.toLowerCase())
arr.push( this.aSug[i] );
}
this.aSug = arr;

this.createList(this.aSug);



return false;
}
else
// do new request
//
{
var pointer = this;
var input = this.sInp;
clearTimeout(this.ajID);
this.ajID = setTimeout( function() { pointer.doAjaxRequest(input) }, this.oP.delay );
}
return false;
};
_b.AutoSuggest.prototype.doAjaxRequest = function (input)
{
// check that saved input is still the value of the field
//
if (input != this.fld.value)
return false;


var pointer = this;


// create ajax request
//
if (typeof(this.oP.script) == "function")
var url = this.oP.script(encodeURIComponent(this.sInp));
else
var url = this.oP.script+this.oP.varname+"="+encodeURIComponent(this.sInp);

if (!url)
return false;

var meth = this.oP.meth;
var input = this.sInp;

var onSuccessFunc = function (req) { pointer.setSuggestions(req, input) };
var onErrorFunc = function (status) {  };
var myAjax = new _b.Ajax();
myAjax.makeRequest( url, meth, onSuccessFunc, onErrorFunc );
};
_b.AutoSuggest.prototype.setSuggestions = function (req, input)
{
// if field input no longer matches what was passed to the request
// don't show the suggestions
//
if (input != this.fld.value)
return false;


this.aSug = [];


if (this.oP.json)
{
var jsondata = eval('(' + req.responseText + ')');

for (var i=0;i<jsondata.results.length;i++)
{
this.aSug.push(  { 'id':jsondata.results[i].id, 'value':jsondata.results[i].value, 'info':jsondata.results[i].info }  );
}
}
else
{
var xml = req.responseXML;

// traverse xml
//
var results = xml.getElementsByTagName('results')[0].childNodes;
for (var i=0;i<results.length;i++)
{
if (results[i].hasChildNodes())
this.aSug.push(  { 'id':results[i].getAttribute('id'), 'value':results[i].childNodes[0].nodeValue, 'info':results[i].getAttribute('info') }  );
}

}

this.idAs = "as_"+this.fld.id;

this.createList(this.aSug);
};
_b.AutoSuggest.prototype.createList = function(arr)
{
var pointer = this;




// get rid of old list
// and clear the list removal timeout
//
_b.DOM.remE(this.idAs);
this.killTimeout();


// if no results, and shownoresults is false, do nothing
//
if (arr.length == 0 && !this.oP.shownoresults)
return false;


// create holding div
//
var div = _b.DOM.cE("div", {id:this.idAs, className:this.oP.className});

var hcorner = _b.DOM.cE("div", {className:"as_corner"});
var hbar = _b.DOM.cE("div", {className:"as_bar"});
var header = _b.DOM.cE("div", {className:"as_header"});
header.appendChild(hcorner);
header.appendChild(hbar);
div.appendChild(header);




// create and populate ul
//
var ul = _b.DOM.cE("ul", {id:"as_ul"});




// loop throught arr of suggestions
// creating an LI element for each suggestion
//
for (var i=0;i<arr.length;i++)
{
// format output with the input enclosed in a EM element
// (as HTML, not DOM)
//
var val = arr[i].value;
var st = val.toLowerCase().indexOf( this.sInp.toLowerCase() );
var output = val.substring(0,st) + "<em>" + val.substring(st, st+this.sInp.length) + "</em>" + val.substring(st+this.sInp.length);


var span = _b.DOM.cE("span", {}, output, true);
if (arr[i].info != "")
{
var br= _b.DOM.cE("br", {});
span.appendChild(br);
var small= _b.DOM.cE("small", {}, arr[i].info);
span.appendChild(small);
}

var a = _b.DOM.cE("a", { href:"#" });

var tl = _b.DOM.cE("span", {className:"tl"}, " ");
var tr = _b.DOM.cE("span", {className:"tr"}, " ");
a.appendChild(tl);
a.appendChild(tr);

a.appendChild(span);

a.name = i+1;
a.onclick = function () { pointer.setHighlightedValue(); return false; };
a.onmouseover = function () { pointer.setHighlight(this.name); };

var li = _b.DOM.cE(  "li", {}, a  );

ul.appendChild( li );
}


// no results
//
if (arr.length == 0 && this.oP.shownoresults)
{
var li = _b.DOM.cE(  "li", {className:"as_warning"}, this.oP.noresults  );
ul.appendChild( li );
}


div.appendChild( ul );


var fcorner = _b.DOM.cE("div", {className:"as_corner"});
var fbar = _b.DOM.cE("div", {className:"as_bar"});
var footer = _b.DOM.cE("div", {className:"as_footer"});
footer.appendChild(fcorner);
footer.appendChild(fbar);
div.appendChild(footer);



// get position of target textfield
// position holding div below it
// set width of holding div to width of field
//
var pos = _b.DOM.getPos(this.fld);

div.style.left = pos.x + "px";
div.style.top = ( pos.y + this.fld.offsetHeight + this.oP.offsety ) + "px";
if ( this.oP.divwidth == "100%" ){
div.style.width = this.fld.offsetWidth + "px";
}else{
div.style.width = this.oP.divwidth;
}


// set mouseover functions for div
// when mouse pointer leaves div, set a timeout to remove the list after an interval
// when mouse enters div, kill the timeout so the list won't be removed
//
div.onmouseover = function(){ pointer.killTimeout() };
div.onmouseout = function(){ pointer.resetTimeout() };
// add DIV to document
//
document.getElementsByTagName("body")[0].appendChild(div);



// currently no item is highlighted
//
this.iHigh = 0;






// remove list after an interval
//
var pointer = this;
this.toID = setTimeout(function () { pointer.clearSuggestions() }, this.oP.timeout);
};
_b.AutoSuggest.prototype.changeHighlight = function(key)
{
var list = _b.DOM.gE("as_ul");
if (!list)
return false;

var n;
if (key == 40)
n = this.iHigh + 1;
else if (key == 38)
n = this.iHigh - 1;


if (n > list.childNodes.length)
n = list.childNodes.length;
if (n < 1)
n = 1;


this.setHighlight(n);
};
_b.AutoSuggest.prototype.setHighlight = function(n)
{
var list = _b.DOM.gE("as_ul");
if (!list)
return false;

if (this.iHigh > 0)
this.clearHighlight();

this.iHigh = Number(n);

list.childNodes[this.iHigh-1].className = "as_highlight";
this.killTimeout();
};
_b.AutoSuggest.prototype.clearHighlight = function()
{
var list = _b.DOM.gE("as_ul");
if (!list)
return false;

if (this.iHigh > 0)
{
list.childNodes[this.iHigh-1].className = "";
this.iHigh = 0;
}
};
_b.AutoSuggest.prototype.setHighlightedValue = function ()
{
if (this.iHigh)
{
this.sInp = this.fld.value = this.aSug[ this.iHigh-1 ].value;

// move cursor to end of input (safari)
//
this.fld.focus();
if (this.fld.selectionStart)
this.fld.setSelectionRange(this.sInp.length, this.sInp.length);

this.clearSuggestions();

// pass selected object to callback function, if exists
//
if (typeof(this.oP.callback) == "function")
this.oP.callback( this.aSug[this.iHigh-1] );
}
};
_b.AutoSuggest.prototype.killTimeout = function()
{
clearTimeout(this.toID);
};
_b.AutoSuggest.prototype.resetTimeout = function()
{
clearTimeout(this.toID);
var pointer = this;
this.toID = setTimeout(function () { pointer.clearSuggestions() }, 1000);
};
_b.AutoSuggest.prototype.clearSuggestions = function ()
{

this.killTimeout();

var ele = _b.DOM.gE(this.idAs);
var pointer = this;
if (ele)
{
var fade = new _b.Fader(ele,1,0,250,function () { _b.DOM.remE(pointer.idAs) });
}
};
// AJAX PROTOTYPE _____________________________________________
if (typeof(_b.Ajax) == "undefined")
_b.Ajax = {};
_b.Ajax = function ()
{
this.req = {};
this.isIE = false;
};
_b.Ajax.prototype.makeRequest = function (url, meth, onComp, onErr)
{

if (meth != "POST")
meth = "GET";

this.onComplete = onComp;
this.onError = onErr;

var pointer = this;

// branch for native XMLHttpRequest object
if (window.XMLHttpRequest)
{
this.req = new XMLHttpRequest();
this.req.onreadystatechange = function () { pointer.processReqChange() };
this.req.open("GET", url, true); //
this.req.send(null);
// branch for IE/Windows ActiveX version
}
else if (window.ActiveXObject)
{
this.req = new ActiveXObject("Microsoft.XMLHTTP");
if (this.req)
{
this.req.onreadystatechange = function () { pointer.processReqChange() };
this.req.open(meth, url, true);
this.req.send();
}
}
};
_b.Ajax.prototype.processReqChange = function()
{

// only if req shows "loaded"
if (this.req.readyState == 4) {
// only if "OK"
if (this.req.status == 200)
{
this.onComplete( this.req );
} else {
this.onError( this.req.status );
}
}
};
// DOM PROTOTYPE _____________________________________________
if (typeof(_b.DOM) == "undefined")
_b.DOM = {};
/* create element */
_b.DOM.cE = function ( type, attr, cont, html )
{
var ne = document.createElement( type );
if (!ne)
return 0;

for (var a in attr)
ne[a] = attr[a];

var t = typeof(cont);

if (t == "string" && !html)
ne.appendChild( document.createTextNode(cont) );
else if (t == "string" && html)
ne.innerHTML = cont;
else if (t == "object")
ne.appendChild( cont );
return ne;
};
/* get element */
_b.DOM.gE = function ( e )
{
var t=typeof(e);
if (t == "undefined")
return 0;
else if (t == "string")
{
var re = document.getElementById( e );
if (!re)
return 0;
else if (typeof(re.appendChild) != "undefined" )
return re;
else
return 0;
}
else if (typeof(e.appendChild) != "undefined")
return e;
else
return 0;
};
/* remove element */
_b.DOM.remE = function ( ele )
{
var e = this.gE(ele);

if (!e)
return 0;
else if (e.parentNode.removeChild(e))
return true;
else
return 0;
};
/* get position */
_b.DOM.getPos = function ( e )
{
var e = this.gE(e);
var obj = e;
var curleft = 0;
if (obj.offsetParent)
{
while (obj.offsetParent)
{
curleft += obj.offsetLeft;
obj = obj.offsetParent;
}
}
else if (obj.x)
curleft += obj.x;

var obj = e;

var curtop = 0;
if (obj.offsetParent)
{
while (obj.offsetParent)
{
curtop += obj.offsetTop;
obj = obj.offsetParent;
}
}
else if (obj.y)
curtop += obj.y;
return {x:curleft, y:curtop};
};
// FADER PROTOTYPE _____________________________________________
if (typeof(_b.Fader) == "undefined")
_b.Fader = {};
_b.Fader = function (ele, from, to, fadetime, callback)
{
if (!ele)
return 0;

this.e = ele;

this.from = from;
this.to = to;

this.cb = callback;

this.nDur = fadetime;

this.nInt = 50;
this.nTime = 0;

var p = this;
this.nID = setInterval(function() { p._fade() }, this.nInt);
};
_b.Fader.prototype._fade = function()
{
this.nTime += this.nInt;

var ieop = Math.round( this._tween(this.nTime, this.from, this.to, this.nDur) * 100 );
var op = ieop / 100;

if (this.e.filters) // internet explorer
{
try
{
this.e.filters.item("DXImageTransform.Microsoft.Alpha").opacity = ieop;
} catch (e) { 
// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
this.e.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+ieop+')';
}
}
else // other browsers
{
this.e.style.opacity = op;
}


if (this.nTime == this.nDur)
{
clearInterval( this.nID );
if (this.cb != undefined)
this.cb();
}
};
_b.Fader.prototype._tween = function(t,b,c,d)
{
return b + ( (c-b) * (t/d) );
};
/***********************************************
 Fool-Proof Date Input Script with DHTML Calendar
 by Jason Moon - http://calendar.moonscript.com/dateinput.cfm
 ************************************************/
// Customizable variables
var DefaultDateFormat = 'DD/MM/YYYY'; // If no date format is supplied, this will be used instead
var HideWait = 3; // Number of seconds before the calendar will disappear
var Y2kPivotPoint = 76; // 2-digit years before this point will be created in the 21st century
var UnselectedMonthText = ''; // Text to display in the 1st month list item when the date isn't required
var FontSize = 11; // In pixels
var FontFamily = 'Tahoma';
var CellWidth = 18;
var CellHeight = 16;
var ImageURL = 'calendar.jpg';
var NextURL = 'next.gif';
var PrevURL = 'prev.gif';
var CalBGColor = 'white';
var TopRowBGColor = 'buttonface';
var DayBGColor = 'lightgrey';
// Global variables
var ZCounter = 100;
var Today = new Date();
var WeekDays = new Array('S','M','T','W','T','F','S');
var MonthDays = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var MonthNames = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
// Write out the stylesheet definition for the calendar
with (document) {
   writeln('<style>');
   writeln('td.calendarDateInput {letter-spacing:normal;line-height:normal;font-family:' + FontFamily + ',Sans-Serif;font-size:' + FontSize + 'px;}');
   writeln('select.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('input.calendarDateInput {letter-spacing:.06em;font-family:Verdana,Sans-Serif;font-size:11px;}');
   writeln('</style>');
}
// Only allows certain keys to be used in the date field
function YearDigitsOnly(e) {
   var KeyCode = (e.keyCode) ? e.keyCode : e.which;
   return ((KeyCode == 8) // backspace
        || (KeyCode == 9) // tab
        || (KeyCode == 37) // left arrow
        || (KeyCode == 39) // right arrow
        || (KeyCode == 46) // delete
        || ((KeyCode > 47) && (KeyCode < 58)) // 0 - 9
   );
}
// Gets the absolute pixel position of the supplied element
function GetTagPixels(StartTag, Direction) {
   var PixelAmt = (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   while ((StartTag.tagName != 'BODY') && (StartTag.tagName != 'HTML')) {
      StartTag = StartTag.offsetParent;
      PixelAmt += (Direction == 'LEFT') ? StartTag.offsetLeft : StartTag.offsetTop;
   }
   return PixelAmt;
}
// Is the specified select-list behind the calendar?
function BehindCal(SelectList, CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY) {
   var ListLeftX = GetTagPixels(SelectList, 'LEFT');
   var ListRightX = ListLeftX + SelectList.offsetWidth;
   var ListBottomY = ListTopY + SelectList.offsetHeight;
   return (((ListTopY < CalBottomY) && (ListBottomY > CalTopY)) && ((ListLeftX < CalRightX) && (ListRightX > CalLeftX)));
}
// For IE, hides any select-lists that are behind the calendar
function FixSelectLists(Over) {
   if (navigator.appName == 'Microsoft Internet Explorer') {
      var CalDiv = this.getCalendar();
      var CalLeftX = CalDiv.offsetLeft;
      var CalRightX = CalLeftX + CalDiv.offsetWidth;
      var CalTopY = CalDiv.offsetTop;
      var CalBottomY = CalTopY + (CellHeight * 9);
      var FoundCalInput = false;
      formLoop :
      for (var j=this.formNumber;j<document.forms.length;j++) {
         for (var i=0;i<document.forms[j].elements.length;i++) {
            if (typeof document.forms[j].elements[i].type == 'string') {
               if ((document.forms[j].elements[i].type == 'hidden') && (document.forms[j].elements[i].name == this.hiddenFieldName)) {
                  FoundCalInput = true;
                  i += 3; // 3 elements between the 1st hidden field and the last year input field
               }
               if (FoundCalInput) {
                  if (document.forms[j].elements[i].type.substr(0,6) == 'select') {
                     ListTopY = GetTagPixels(document.forms[j].elements[i], 'TOP');
                     if (ListTopY < CalBottomY) {
                        if (BehindCal(document.forms[j].elements[i], CalLeftX, CalRightX, CalTopY, CalBottomY, ListTopY)) {
                           document.forms[j].elements[i].style.visibility = (Over) ? 'hidden' : 'visible';
                        }
                     }
                     else break formLoop;
                  }
               }
            }
         }
      }
   }
}
// Displays a message in the status bar when hovering over the calendar days
function DayCellHover(Cell, Over, Color, HoveredDay) {
   Cell.style.backgroundColor = (Over) ? DayBGColor : Color;
   if (Over) {
      if ((this.yearValue == Today.getFullYear()) && (this.monthIndex == Today.getMonth()) && (HoveredDay == Today.getDate())) self.status = 'Click to select today';
      else {
         var Suffix = HoveredDay.toString();
         switch (Suffix.substr(Suffix.length - 1, 1)) {
            case '1' : Suffix += (HoveredDay == 11) ? 'th' : 'st'; break;
            case '2' : Suffix += (HoveredDay == 12) ? 'th' : 'nd'; break;
            case '3' : Suffix += (HoveredDay == 13) ? 'th' : 'rd'; break;
            default : Suffix += 'th'; break;
         }
         self.status = 'Click to select ' + this.monthName + ' ' + Suffix;
      }
   }
   else self.status = '';
   return true;
}
// Sets the form elements after a day has been picked from the calendar
function PickDisplayDay(ClickedDay) {
   this.show();
   var MonthList = this.getMonthList();
   var DayList = this.getDayList();
   var YearField = this.getYearField();
   FixDayList(DayList, GetDayCount(this.displayed.yearValue, this.displayed.monthIndex));
   // Select the month and day in the lists
   for (var i=0;i<MonthList.length;i++) {
      if (MonthList.options[i].value == this.displayed.monthIndex) MonthList.options[i].selected = true;
   }
   for (var j=1;j<=DayList.length;j++) {
      if (j == ClickedDay) DayList.options[j-1].selected = true;
   }
   this.setPicked(this.displayed.yearValue, this.displayed.monthIndex, ClickedDay);
   // Change the year, if necessary
   YearField.value = this.picked.yearPad;
   YearField.defaultValue = YearField.value;
}
// Builds the HTML for the calendar days
function BuildCalendarDays() {
   var Rows = 5;
   if (((this.displayed.dayCount == 31) && (this.displayed.firstDay > 4)) || ((this.displayed.dayCount == 30) && (this.displayed.firstDay == 6))) Rows = 6;
   else if ((this.displayed.dayCount == 28) && (this.displayed.firstDay == 0)) Rows = 4;
   var HTML = '<table width="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1" style="cursor:default">';
   for (var j=0;j<Rows;j++) {
      HTML += '<tr>';
      for (var i=1;i<=7;i++) {
         Day = (j * 7) + (i - this.displayed.firstDay);
         if ((Day >= 1) && (Day <= this.displayed.dayCount)) {
            if ((this.displayed.yearValue == this.picked.yearValue) && (this.displayed.monthIndex == this.picked.monthIndex) && (Day == this.picked.day)) {
               TextStyle = 'color:white;font-weight:bold;'
               BackColor = DayBGColor;
            }
            else {
               TextStyle = 'color:black;'
               BackColor = CalBGColor;
            }
            if ((this.displayed.yearValue == Today.getFullYear()) && (this.displayed.monthIndex == Today.getMonth()) && (Day == Today.getDate())) TextStyle += 'border:1px solid darkred;padding:0px;';
            HTML += '<td align="center" class="calendarDateInput" style="cursor:default;height:' + CellHeight + ';width:' + CellWidth + ';' + TextStyle + ';background-color:' + BackColor + '" onClick="' + this.objName + '.pickDay(' + Day + ')" onMouseOver="return ' + this.objName + '.displayed.dayHover(this,true,\'' + BackColor + '\',' + Day + ')" onMouseOut="return ' + this.objName + '.displayed.dayHover(this,false,\'' + BackColor + '\')">' + Day + '</td>';
         }
         else HTML += '<td class="calendarDateInput" style="height:' + CellHeight + '">&nbsp;</td>';
      }
      HTML += '</tr>';
   }
   return HTML += '</table>';
}
// Determines which century to use (20th or 21st) when dealing with 2-digit years
function GetGoodYear(YearDigits) {
   if (YearDigits.length == 4) return YearDigits;
   else {
      var Millennium = (YearDigits < Y2kPivotPoint) ? 2000 : 1900;
      return Millennium + parseInt(YearDigits,10);
   }
}
// Returns the number of days in a month (handles leap-years)
function GetDayCount(SomeYear, SomeMonth) {
   return ((SomeMonth == 1) && ((SomeYear % 400 == 0) || ((SomeYear % 4 == 0) && (SomeYear % 100 != 0)))) ? 29 : MonthDays[SomeMonth];
}
// Highlights the buttons
function VirtualButton(Cell, ButtonDown) {
   if (ButtonDown) {
      Cell.style.borderLeft = 'buttonshadow 1px solid';
      Cell.style.borderTop = 'buttonshadow 1px solid';
      Cell.style.borderBottom = 'buttonhighlight 1px solid';
      Cell.style.borderRight = 'buttonhighlight 1px solid';
   }
   else {
      Cell.style.borderLeft = 'buttonhighlight 1px solid';
      Cell.style.borderTop = 'buttonhighlight 1px solid';
      Cell.style.borderBottom = 'buttonshadow 1px solid';
      Cell.style.borderRight = 'buttonshadow 1px solid';
   }
}
// Mouse-over for the previous/next month buttons
function NeighborHover(Cell, Over, DateObj) {
   if (Over) {
      VirtualButton(Cell, false);
      self.status = 'Click to view ' + DateObj.fullName;
   }
   else {
      Cell.style.border = 'buttonface 1px solid';
      self.status = '';
   }
   return true;
}
// Adds/removes days from the day list, depending on the month/year
function FixDayList(DayList, NewDays) {
   var DayPick = DayList.selectedIndex + 1;
   if (NewDays != DayList.length) {
      var OldSize = DayList.length;
      for (var k=Math.min(NewDays,OldSize);k<Math.max(NewDays,OldSize);k++) {
         (k >= NewDays) ? DayList.options[NewDays] = null : DayList.options[k] = new Option(k+1, k+1);
      }
      DayPick = Math.min(DayPick, NewDays);
      DayList.options[DayPick-1].selected = true;
   }
   return DayPick;
}
// Resets the year to its previous valid value when something invalid is entered
function FixYearInput(YearField) {
   var YearRE = new RegExp('\\d{' + YearField.defaultValue.length + '}');
   if (!YearRE.test(YearField.value)) YearField.value = YearField.defaultValue;
}
// Displays a message in the status bar when hovering over the calendar icon
function CalIconHover(Over) {
   var Message = (this.isShowing()) ? 'hide' : 'show';
   self.status = (Over) ? 'Click to ' + Message + ' the calendar' : '';
   return true;
}
// Starts the timer over from scratch
function CalTimerReset() {
   eval('clearTimeout(' + this.timerID + ')');
   eval(this.timerID + '=setTimeout(\'' + this.objName + '.show()\',' + (HideWait * 1000) + ')');
}
// The timer for the calendar
function DoTimer(CancelTimer) {
   if (CancelTimer) eval('clearTimeout(' + this.timerID + ')');
   else {
      eval(this.timerID + '=null');
      this.resetTimer();
   }
}
// Show or hide the calendar
function ShowCalendar() {
   if (this.isShowing()) {
      var StopTimer = true;
      this.getCalendar().style.zIndex = --ZCounter;
      this.getCalendar().style.visibility = 'hidden';
      this.fixSelects(false);
   }
   else {
      var StopTimer = false;
      this.fixSelects(true);
      this.getCalendar().style.zIndex = ++ZCounter;
      this.getCalendar().style.visibility = 'visible';
   }
   this.handleTimer(StopTimer);
   self.status = '';
}
// Hides the input elements when the "blank" month is selected
function SetElementStatus(Hide) {
   this.getDayList().style.visibility = (Hide) ? 'hidden' : 'visible';
   this.getYearField().style.visibility = (Hide) ? 'hidden' : 'visible';
   this.getCalendarLink().style.visibility = (Hide) ? 'hidden' : 'visible';
}
// Sets the date, based on the month selected
function CheckMonthChange(MonthList) {
   var DayList = this.getDayList();
   if (MonthList.options[MonthList.selectedIndex].value == '') {
      DayList.selectedIndex = 0;
      this.hideElements(true);
      this.setHidden('');
   }
   else {
      this.hideElements(false);
      if (this.isShowing()) {
         this.resetTimer(); // Gives the user more time to view the calendar with the newly-selected month
         this.getCalendar().style.zIndex = ++ZCounter; // Make sure this calendar is on top of any other calendars
      }
      var DayPick = FixDayList(DayList, GetDayCount(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value));
      this.setPicked(this.picked.yearValue, MonthList.options[MonthList.selectedIndex].value, DayPick);
   }
}
// Sets the date, based on the day selected
function CheckDayChange(DayList) {
   if (this.isShowing()) this.show();
   this.setPicked(this.picked.yearValue, this.picked.monthIndex, DayList.selectedIndex+1);
}
// Changes the date when a valid year has been entered
function CheckYearInput(YearField) {
   if ((YearField.value.length == YearField.defaultValue.length) && (YearField.defaultValue != YearField.value)) {
      if (this.isShowing()) {
         this.resetTimer(); // Gives the user more time to view the calendar with the newly-entered year
         this.getCalendar().style.zIndex = ++ZCounter; // Make sure this calendar is on top of any other calendars
      }
      var NewYear = GetGoodYear(YearField.value);
      var MonthList = this.getMonthList();
      var NewDay = FixDayList(this.getDayList(), GetDayCount(NewYear, this.picked.monthIndex));
      this.setPicked(NewYear, this.picked.monthIndex, NewDay);
      YearField.defaultValue = YearField.value;
   }
}
// Holds characteristics about a date
function dateObject() {
   if (Function.call) { // Used when 'call' method of the Function object is supported
      var ParentObject = this;
      var ArgumentStart = 0;
   }
   else { // Used with 'call' method of the Function object is NOT supported
      var ParentObject = arguments[0];
      var ArgumentStart = 1;
   }
   ParentObject.date = (arguments.length == (ArgumentStart+1)) ? new Date(arguments[ArgumentStart+0]) : new Date(arguments[ArgumentStart+0], arguments[ArgumentStart+1], arguments[ArgumentStart+2]);
   ParentObject.yearValue = ParentObject.date.getFullYear();
   ParentObject.monthIndex = ParentObject.date.getMonth();
   ParentObject.monthName = MonthNames[ParentObject.monthIndex];
   ParentObject.fullName = ParentObject.monthName + ' ' + ParentObject.yearValue;
   ParentObject.day = ParentObject.date.getDate();
   ParentObject.dayCount = GetDayCount(ParentObject.yearValue, ParentObject.monthIndex);
   var FirstDate = new Date(ParentObject.yearValue, ParentObject.monthIndex, 1);
   ParentObject.firstDay = FirstDate.getDay();
}
// Keeps track of the date that goes into the hidden field
function storedMonthObject(DateFormat, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.yearPad = this.yearValue.toString();
   this.monthPad = (this.monthIndex < 9) ? '0' + String(this.monthIndex + 1) : this.monthIndex + 1;
   this.dayPad = (this.day < 10) ? '0' + this.day.toString() : this.day;
   this.monthShort = this.monthName.substr(0,3).toUpperCase();
   // Formats the year with 2 digits instead of 4
   if (DateFormat.indexOf('YYYY') == -1) this.yearPad = this.yearPad.substr(2);
   // Define the date-part delimiter
   if (DateFormat.indexOf('/') >= 0) var Delimiter = '/';
   else if (DateFormat.indexOf('-') >= 0) var Delimiter = '-';
   else var Delimiter = '';
   // Determine the order of the months and days
   if (/DD?.?((MON)|(MM?M?))/.test(DateFormat)) {
      this.formatted = this.dayPad + Delimiter;
      this.formatted += (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
   }
   else if (/((MON)|(MM?M?))?.?DD?/.test(DateFormat)) {
      this.formatted = (RegExp.$1.length == 3) ? this.monthShort : this.monthPad;
      this.formatted += Delimiter + this.dayPad;
   }
   // Either prepend or append the year to the formatted date
   this.formatted = (DateFormat.substr(0,2) == 'YY') ? this.yearPad + Delimiter + this.formatted : this.formatted + Delimiter + this.yearPad;
}
// Object for the current displayed month
function displayMonthObject(ParentObject, DateYear, DateMonth, DateDay) {
   (Function.call) ? dateObject.call(this, DateYear, DateMonth, DateDay) : dateObject(this, DateYear, DateMonth, DateDay);
   this.displayID = ParentObject.hiddenFieldName + '_Current_ID';
   this.getDisplay = new Function('return document.getElementById(this.displayID)');
   this.dayHover = DayCellHover;
   this.goCurrent = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(Today.getFullYear(),Today.getMonth());');
   if (ParentObject.formNumber >= 0) this.getDisplay().innerHTML = this.fullName;
}
// Object for the previous/next buttons
function neighborMonthObject(ParentObject, IDText, DateMS) {
   (Function.call) ? dateObject.call(this, DateMS) : dateObject(this, DateMS);
   this.buttonID = ParentObject.hiddenFieldName + '_' + IDText + '_ID';
   this.hover = new Function('C','O','NeighborHover(C,O,this)');
   this.getButton = new Function('return document.getElementById(this.buttonID)');
   this.go = new Function(ParentObject.objName + '.getCalendar().style.zIndex=++ZCounter;' + ParentObject.objName + '.setDisplayed(this.yearValue,this.monthIndex);');
   if (ParentObject.formNumber >= 0) this.getButton().title = this.monthName;
}
// Sets the currently-displayed month object
function SetDisplayedMonth(DispYear, DispMonth) {
   this.displayed = new displayMonthObject(this, DispYear, DispMonth, 1);
   // Creates the previous and next month objects
   this.previous = new neighborMonthObject(this, 'Previous', this.displayed.date.getTime() - 86400000);
   this.next = new neighborMonthObject(this, 'Next', this.displayed.date.getTime() + (86400000 * (this.displayed.dayCount + 1)));
   // Creates the HTML for the calendar
   if (this.formNumber >= 0) this.getDayTable().innerHTML = this.buildCalendar();
}
// Sets the current selected date
function SetPickedMonth(PickedYear, PickedMonth, PickedDay) {
   this.picked = new storedMonthObject(this.format, PickedYear, PickedMonth, PickedDay);
   this.setHidden(this.picked.formatted);
   this.setDisplayed(PickedYear, PickedMonth);
}
// The calendar object
function calendarObject(DateName, DateFormat, DefaultDate) {
   /* Properties */
   this.hiddenFieldName = DateName;
   this.monthListID = DateName + '_Month_ID';
   this.dayListID = DateName + '_Day_ID';
   this.yearFieldID = DateName + '_Year_ID';
   this.monthDisplayID = DateName + '_Current_ID';
   this.calendarID = DateName + '_ID';
   this.dayTableID = DateName + '_DayTable_ID';
   this.calendarLinkID = this.calendarID + '_Link';
   this.timerID = this.calendarID + '_Timer';
   this.objName = DateName + '_Object';
   this.format = DateFormat;
   this.formNumber = -1;
   this.picked = null;
   this.displayed = null;
   this.previous = null;
   this.next = null;
   /* Methods */
   this.setPicked = SetPickedMonth;
   this.setDisplayed = SetDisplayedMonth;
   this.checkYear = CheckYearInput;
   this.fixYear = FixYearInput;
   this.changeMonth = CheckMonthChange;
   this.changeDay = CheckDayChange;
   this.resetTimer = CalTimerReset;
   this.hideElements = SetElementStatus;
   this.show = ShowCalendar;
   this.handleTimer = DoTimer;
   this.iconHover = CalIconHover;
   this.buildCalendar = BuildCalendarDays;
   this.pickDay = PickDisplayDay;
   this.fixSelects = FixSelectLists;
   this.setHidden = new Function('D','if (this.formNumber >= 0) this.getHiddenField().value=D');
   // Returns a reference to these elements
   this.getHiddenField = new Function('return document.forms[this.formNumber].elements[this.hiddenFieldName]');
   this.getMonthList = new Function('return document.getElementById(this.monthListID)');
   this.getDayList = new Function('return document.getElementById(this.dayListID)');
   this.getYearField = new Function('return document.getElementById(this.yearFieldID)');
   this.getCalendar = new Function('return document.getElementById(this.calendarID)');
   this.getDayTable = new Function('return document.getElementById(this.dayTableID)');
   this.getCalendarLink = new Function('return document.getElementById(this.calendarLinkID)');
   this.getMonthDisplay = new Function('return document.getElementById(this.monthDisplayID)');
   this.isShowing = new Function('return !(this.getCalendar().style.visibility != \'visible\')');
   /* Constructor */
   // Functions used only by the constructor
   function getMonthIndex(MonthAbbr) { // Returns the index (0-11) of the supplied month abbreviation
      for (var MonPos=0;MonPos<MonthNames.length;MonPos++) {
         if (MonthNames[MonPos].substr(0,3).toUpperCase() == MonthAbbr.toUpperCase()) break;
      }
      return MonPos;
   }
   function SetGoodDate(CalObj, Notify) { // Notifies the user about their bad default date, and sets the current system date
      CalObj.setPicked(Today.getFullYear(), Today.getMonth(), Today.getDate());
      if (Notify) alert('WARNING: The supplied date is not in valid \'' + DateFormat + '\' format: ' + DefaultDate + '.\nTherefore, the current system date will be used instead: ' + CalObj.picked.formatted);
   }
   // Main part of the constructor
   if (DefaultDate != '') {
      if ((this.format == 'YYYYMMDD') && (/^(\d{4})(\d{2})(\d{2})$/.test(DefaultDate))) this.setPicked(RegExp.$1, parseInt(RegExp.$2,10)-1, RegExp.$3);
      else {
         // Get the year
         if ((this.format.substr(0,2) == 'YY') && (/^(\d{2,4})(-|\/)/.test(DefaultDate))) { // Year is at the beginning
            var YearPart = GetGoodYear(RegExp.$1);
            // Determine the order of the months and days
            if (/(-|\/)(\w{1,3})(-|\/)(\w{1,3})$/.test(DefaultDate)) {
               var MidPart = RegExp.$2;
               var EndPart = RegExp.$4;
               if (/D$/.test(this.format)) { // Ends with days
                  var DayPart = EndPart;
                  var MonthPart = MidPart;
               }
               else {
                  var DayPart = MidPart;
                  var MonthPart = EndPart;
               }
               MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
               this.setPicked(YearPart, MonthPart, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else if (/(-|\/)(\d{2,4})$/.test(DefaultDate)) { // Year is at the end
            var YearPart = GetGoodYear(RegExp.$2);
            // Determine the order of the months and days
            if (/^(\w{1,3})(-|\/)(\w{1,3})(-|\/)/.test(DefaultDate)) {
               if (this.format.substr(0,1) == 'D') { // Starts with days
                  var DayPart = RegExp.$1;
                  var MonthPart = RegExp.$3;
               }
               else { // Starts with months
                  var MonthPart = RegExp.$1;
                  var DayPart = RegExp.$3;
               }
               MonthPart = (/\d{1,2}/i.test(MonthPart)) ? parseInt(MonthPart,10)-1 : getMonthIndex(MonthPart);
               this.setPicked(YearPart, MonthPart, DayPart);
            }
            else SetGoodDate(this, true);
         }
         else SetGoodDate(this, true);
      }
   }
}
var calObjectID;
function writeoutln( data ){
if ( document.getElementById(calObjectID) != undefined ){
document.getElementById(calObjectID).innerHTML = document.getElementById(calObjectID).innerHTML + data;
}else{
document.writeln(data);
}
}
// Main function that creates the form elements
function DateInput(DateName, Required, DateFormat, DefaultDate) {
   if (arguments.length == 0) document.writeln('<span style="color:red;font-size:' + FontSize + 'px;font-family:' + FontFamily + ';">ERROR: Missing required parameter in call to \'DateInput\': [name of hidden date field].</span>');
   else {
      // Handle DateFormat
      if (arguments.length < 3) { // The format wasn't passed in, so use default
         DateFormat = DefaultDateFormat;
         if (arguments.length < 2) Required = false;
      }
      else if (/^(Y{2,4}(-|\/)?)?((MON)|(MM?M?)|(DD?))(-|\/)?((MON)|(MM?M?)|(DD?))((-|\/)Y{2,4})?$/i.test(DateFormat)) DateFormat = DateFormat.toUpperCase();
      else { // Passed-in DateFormat was invalid, use default format instead
         var AlertMessage = 'WARNING: The supplied date format for the \'' + DateName + '\' field is not valid: ' + DateFormat + '\nTherefore, the default date format will be used instead: ' + DefaultDateFormat;
         DateFormat = DefaultDateFormat;
         if (arguments.length == 4) { // DefaultDate was passed in with an invalid date format
            var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
            AlertMessage += '\n\nThe supplied date (' + DefaultDate + ') cannot be interpreted with the invalid format.\nTherefore, the current system date will be used instead: ' + CurrentDate.formatted;
            DefaultDate = CurrentDate.formatted;
         }
         alert(AlertMessage);
      }
      // Define the current date if it wasn't set already
      if (!CurrentDate) var CurrentDate = new storedMonthObject(DateFormat, Today.getFullYear(), Today.getMonth(), Today.getDate());
      // Handle DefaultDate
      if (arguments.length < 4) { // The date wasn't passed in
         DefaultDate = (Required) ? CurrentDate.formatted : ''; // If required, use today's date
      }
      // Creates the calendar object!
      eval(DateName + '_Object=new calendarObject(\'' + DateName + '\',\'' + DateFormat + '\',\'' + DefaultDate + '\')');
      // Determine initial viewable state of day, year, and calendar icon
      if ((Required) || (arguments.length == 4)) {
         var InitialStatus = '';
         var InitialDate = eval(DateName + '_Object.picked.formatted');
      }
      else {
         var InitialStatus = ' style="visibility:hidden"';
         var InitialDate = '';
         eval(DateName + '_Object.setPicked(' + Today.getFullYear() + ',' + Today.getMonth() + ',' + Today.getDate() + ')');
      }
      // Create the form elements
      with (document) {
         writeoutln('<input type="hidden" name="' + DateName + '" value="' + InitialDate + '">');
         // Find this form number
         for (var f=0;f<forms.length;f++) {
            for (var e=0;e<forms[f].elements.length;e++) {
               if (typeof forms[f].elements[e].type == 'string') {
                  if ((forms[f].elements[e].type == 'hidden') && (forms[f].elements[e].name == DateName)) {
                     eval(DateName + '_Object.formNumber='+f);
                     break;
                  }
               }
            }
         }
         writeoutln('<table cellpadding="0" cellspacing="2"><tr>' + String.fromCharCode(13) + '<td valign="middle">');
         writeoutln('<select' + InitialStatus + ' class="calendarDateInput" id="' + DateName + '_Day_ID" onChange="' + DateName + '_Object.changeDay(this)">');
         for (var j=1;j<=eval(DateName + '_Object.picked.dayCount');j++) {
            DaySelected = ((DefaultDate != '') && (eval(DateName + '_Object.picked.day') == j)) ? ' selected' : '';
            writeoutln('<option' + DaySelected + '>' + j + '</option>');
         }
         writeoutln('</select>' + String.fromCharCode(13) + '</td>' + String.fromCharCode(13) + '<td valign="middle">');
 
 
         writeoutln('<select class="calendarDateInput" id="' + DateName + '_Month_ID" onChange="' + DateName + '_Object.changeMonth(this)">');
         if (!Required) {
            var NoneSelected = (DefaultDate == '') ? ' selected' : '';
            writeoutln('<option value=""' + NoneSelected + '>' + UnselectedMonthText + '</option>');
         }
         for (var i=0;i<12;i++) {
            MonthSelected = ((DefaultDate != '') && (eval(DateName + '_Object.picked.monthIndex') == i)) ? ' selected' : '';
            writeoutln('<option value="' + i + '"' + MonthSelected + '>' + MonthNames[i].substr(0,3) + '</option>');
         }
         writeoutln('</select>' + String.fromCharCode(13) + '</td>' + String.fromCharCode(13) + '<td valign="middle">');
         writeoutln('<input' + InitialStatus + ' class="calendarDateInput" type="text" id="' + DateName + '_Year_ID" size="' + eval(DateName + '_Object.picked.yearPad.length') + '" maxlength="' + eval(DateName + '_Object.picked.yearPad.length') + '" title="Year" value="' + eval(DateName + '_Object.picked.yearPad') + '" onKeyPress="return YearDigitsOnly(window.event)" onKeyUp="' + DateName + '_Object.checkYear(this)" onBlur="' + DateName + '_Object.fixYear(this)">');
         writeoutln('<td valign="middle">' + String.fromCharCode(13) + '<a' + InitialStatus + ' id="' + DateName + '_ID_Link" href="javascript:' + DateName + '_Object.show()" onMouseOver="return ' + DateName + '_Object.iconHover(true)" onMouseOut="return ' + DateName + '_Object.iconHover(false)"><img src="' + ImageURL + '" align="baseline" title="Calendar" border="0"></a>&nbsp;');
         writeoutln('<span id="' + DateName + '_ID" style="position:absolute;visibility:hidden;width:' + (CellWidth * 7) + 'px;background-color:' + CalBGColor + ';border:1px solid dimgray;" onMouseOver="' + DateName + '_Object.handleTimer(true)" onMouseOut="' + DateName + '_Object.handleTimer(false)">');
         writeoutln('<table width="' + (CellWidth * 7) + '" cellspacing="0" cellpadding="1">' + String.fromCharCode(13) + '<tr style="background-color:' + TopRowBGColor + ';">');
         writeoutln('<td id="' + DateName + '_Previous_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CellHeight + '" onClick="' + DateName + '_Object.previous.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + DateName + '_Object.previous.hover(this,true)" onMouseOut="return ' + DateName + '_Object.previous.hover(this,false)" title="' + eval(DateName + '_Object.previous.monthName') + '"><img src="' + PrevURL + '"></td>');
         writeoutln('<td id="' + DateName + '_Current_ID" style="cursor:pointer" align="center" class="calendarDateInput" style="height:' + CellHeight + '" colspan="5" onClick="' + DateName + '_Object.displayed.goCurrent()" onMouseOver="self.status=\'Click to view ' + CurrentDate.fullName + '\';return true;" onMouseOut="self.status=\'\';return true;" title="Show Current Month">' + eval(DateName + '_Object.displayed.fullName') + '</td>');
         writeoutln('<td id="' + DateName + '_Next_ID" style="cursor:default" align="center" class="calendarDateInput" style="height:' + CellHeight + '" onClick="' + DateName + '_Object.next.go()" onMouseDown="VirtualButton(this,true)" onMouseUp="VirtualButton(this,false)" onMouseOver="return ' + DateName + '_Object.next.hover(this,true)" onMouseOut="return ' + DateName + '_Object.next.hover(this,false)" title="' + eval(DateName + '_Object.next.monthName') + '"><img src="' + NextURL + '"></td></tr>' + String.fromCharCode(13) + '<tr>');
         for (var w=0;w<7;w++) writeoutln('<td width="' + CellWidth + '" align="center" class="calendarDateInput" style="height:' + CellHeight + ';width:' + CellWidth + ';font-weight:bold;border-top:1px solid dimgray;border-bottom:1px solid dimgray;">' + WeekDays[w] + '</td>');
         writeoutln('</tr>' + String.fromCharCode(13) + '</table>' + String.fromCharCode(13) + '<span id="' + DateName + '_DayTable_ID">' + eval(DateName + '_Object.buildCalendar()') + '</span>' + String.fromCharCode(13) + '</span>' + String.fromCharCode(13) + '</td>' + String.fromCharCode(13) + '</tr>' + String.fromCharCode(13) + '</table>');
      }
   }
}
var AJAXObjectID;
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == 'Microsoft Internet Explorer'){
        ro = new ActiveXObject('Microsoft.XMLHTTP');
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}
var http = createRequestObject();
function AJAXRequest(url, objectID) {
AJAXObjectID = objectID;
    http.open('get', url);
    http.onreadystatechange = handleResponse;
    http.send(null);
}
function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;

if ( document.getElementById( AJAXObjectID ) != undefined ){
document.getElementById( AJAXObjectID ).innerHTML = response;
}
    }
}



/*****************************
CHRISTMAS FLASHING
******************************/
var xmasflashswitch=0;
function xmasflash(){
	if ( document.getElementById("xmasflashdiv") != null ){
		if ( xmasflashswitch == 0 ){
			document.getElementById("xmasflashdiv").style.color="#006892";
			xmasflashswitch=1;
		}else{
			document.getElementById("xmasflashdiv").style.color="#77AA00";
			xmasflashswitch=0;
		}
	}
	
	setTimeout("xmasflash()", 1000);
}

