//document.write('<BGSOUND id="BGSOUND_ID" LOOP=1 SRC="jsilence.mid">');

Number.prototype.format= function(d){
	var a,m,m2;
	var rgx = /(\d+)(\d{3})/;
	var d = d || 0;

	if (d){
		a = this.toString().split('.');
		a[1] = a[1] || '0'
		m = Math.pow(10,d)
		m2 = Math.pow(10,-(a[1].length-d))
		a[1] = (Math.round(a[1]*m2)/m).toString().substr(2)
		while (a[1].length < d) 
			a[1] += '0';
	}
 	else 
		a = [Math.round(this).toString()];

	while (rgx.test(a[0])) 
		a[0] = a[0].replace(rgx, '$1' + ',' + '$2');
	return a.join('.')
} 
CSI = {
	ding : function(){
		$('BGSOUND_ID').src = '/wwwroot/lib/csitools/2.0/ding/wav';
	}
	,print : function(str){
		var myWindow = window.open("", "myWindow", "toolbar=no, location=no, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=yes, copyhistory=no, width="+myAjaxBox.clientWidth+", height="+myAjaxBox.clientHeight)
		var myHtml = "<html><body onload='print();window.close();'>" + str + "</body></html>"
		myWindow.document.open()
		window.focus();
		myWindow.document.write(myHtml);
		myWindow.document.close();
	}
	,clearSelection : function(){
		if (document.selection)
			document.selection.clear();
		else if (window.getSelection)
			window.getSelection().removeAllRanges();
	}
	,domMethods : {
		/*getElementsByAttribute : function(attribute,value){
			var a = []
			var t = this;
			var fx = function(){
			
			}
			do {
				if (t.readAttribute(attribute)==value)
					a.push(t);
				
			} while 
			
		}
		,*/
		scrollToView : function(elm){
			var telm = $(elm);
			var pause;
			var left=0;
			var top=0;
			outer:
			do {
				pause = telm;
				inner:
				while (telm && telm.tagName){
					if (telm.getStyle('overflowY')=='scroll')
						break outer;
					if (telm.parentNode == pause.offsetParent)
						break inner;
					telm = $(telm.parentNode);
				}
				left += pause.offsetLeft;
				top += pause.offsetTop;
				telm = $(telm.parentNode);
			} while (telm);
			
			if (telm){
				var x = (top+elm.offsetHeight) - ((telm.offsetHeight/2)+telm.scrollTop);
				if (x>0){
					telm.scrollTop += x;
				}
				else if (top < telm.scrollTop) {
					telm.scrollTop = top;
				}
			}
			return elm;
		}
	}
	,arrayMethods : {
		hasAll : function(val){
			if (typeof(val) == 'number')
				val = [val];
			if (!val.length)
				return false;
			for (var i = 0;i<val.length;i++)
				if (!(personAuths.indexOf(val[i])+1))
					return false;
			return true;
		}
		,uniq : function(property){
			var a = [];
			for (var i=0;i<this.length;i++)
				if (a.indexOf(this[i]) == -1)
					a.push(this[i]);
			return (a.length==this.length) ? this : a;
		}
	}
	,dateMethods : {
		startOfMonth : function(){
			return new Date(this.getFullYear(), this.getMonth(), 1)
		}
		,endOfMonth : function(){
			return new Date(this.getFullYear(), this.getMonth()+1, 0)
		}
		,add : function (sInterval, iNum){
			var d = new Date();
			d.setTime(this.getTime());
			if (sInterval && iNum){
				switch (sInterval.toLowerCase()){
					case "ms":
					case "millisecond":
						d.setMilliseconds(d.getMilliseconds() + iNum);
						break;
					case "s":
					case "second":
						d.setSeconds(d.getSeconds() + iNum);
						break;
					case "mi":
					case "minute":
						d.setMinutes(d.getMinutes() + iNum);
						break;
					case "h":
					case "hour":
						d.setHours(d.getHours() + iNum);
						break;
					case "d":
						d.setDate(d.getDate() + iNum);
						break;
					case "mo":
					case "month":
						d.setMonth(d.getMonth() + iNum);
						break;
					case "y":
						d.setFullYear(d.getFullYear() + iNum);
						break;
				}
				return d;
			}
			else
				return undefined;
		}
	}


	,updPrefs : function (aid,b){    // b = true = Option is on,   b = false = option is off.
		if (!window.aids) 
			return;
		new Ajax.Request('updPersonAttributes.php',{
			parameters : {aid : aid, on : b}
			,onException : function(t,e){alert(e.message)}
		});
		if (b)
			aids.push(aid);
		else
			aids = aids.without(aid);
	}
	
	,isEmpty : function(obj){
		return objToString(obj) == '{}'
	}
	
	
	,iMsgTillCancelled : function(){
		var msgs = [];
		var mtcf;
		var cancelCkBx;
		var button;
		
		return function (aid){
			if (aids.indexOf(aid) > -1){
				return;
			}
			
			var mtcf;
			if (!mtcf){
				mtcf = createForm();
				var b = mtcf.footer.getElementsByTagName('button')[0];
				b.innerHTML = 'OK'
				var cbDiv = mtcf.footer.insertBefore($(document.createElement('div')),b);
				cbDiv.innerHTML = '<input type="checkbox" class="cancel"><span onclick="this.previousSibling.click();" style="cursor:pointer">Don\'t Show this message Again</span>';
				cbDiv.style.lineHeight = '1px'
				cbDiv.style.cssFloat = cbDiv.style.styleFloat = 'left';
				var k = mtcf.cancelCkBx = cbDiv.getElementsByClassName('cancel')[0];
				k.setStyle({position:'relative',top:'3px'});
				mtcf.setTitle('<span style="color:#ff0033;fontWeight:bold">Important Information!</span>')
				cancelCkBx = mtcf.footer.getElementsByTagName('input')[0];
				button = mtcf.footer.getElementsByTagName('button')[0];
				mtcf.onEnterKey = function(){
					if (cancelCkBx.checked)
						CSI.updPrefs(aid,true);
					this.close()
				}
			}
			
			cancelCkBx.checked = false;
			
			if (msgs[aid]){
				mtcf.formBody.innerHTML = msgs[aid];
				setTimeout(function(){mtcf.push().center();button.focus();},170);
			}
			else {
				new Ajax.Request('getMsg.php',{
					parameters : {aid:aid}
					,onSuccess : function(t){
						msgs[aid] = t.responseText;
						mtcf.formBody.innerHTML = t.responseText;
						mtcf.push().center();
						setTimeout(function(){button.focus()},70);
					}
					,onException : function (t,e){alert('Xcept44:'+e.message)}
				})
			}
		}
		return;
	}()
	,jsToPhpDate : function(d){
		return d.getFullYear()+'-'+padZero((d.getMonth()+1),2)+'-'+padZero(d.getDate(),2);
	}
	,formatDate : function (d,optObj){
		optObj = optObj || {};
		var y;
		if (!d || !d.getDate) 
			return '';
		if (optObj.yr2digit){
			y = d.getFullYear().toString().substr(2,2);
		}
		
		else {
			y = d.getFullYear()
		}
		return padZero((d.getMonth()+1),2)+'/'+padZero(d.getDate(),2)+'/'+y
	}
	,formatTime : function (d){
		if (!d || !d.getDate) 
			return '';
		var h = d.getHours()
		var p = (h > 11) ? ' pm' : ' am';
		
		if (h > 12)
			h -= 12;
		if (h == 0)
			h = 12;
		return h+':'+ padZero(d.getMinutes(),2)+p
	}
	,formToPhpDate : function(formDate){
		if (formDate == 'mm/dd/yyyy' || formDate == 'mm/dd/yy' || formDate == "")
			return '';
		var a = formDate.split('/');
		var y;
		if ((y = parseInt(a[2])) < 100){
			if (y > 30)
				y += 1900;
			else
				y+= 2000;
		}
		return y+'-'+padZero(a[0],2)+'-'+padZero(a[1],2);
	}
	,getVisibility : function(elm){
		var v = false;
		var done = false;
		elm = $(elm);
		while (elm && elm.getStyle){  //!elm.readAttribute('visibility'))
			if (elm.getStyle('visibility') == 'hidden' || elm.getStyle('display') == 'none')
				return false
			else if (elm.getStyle('visibility') == 'visible' || elm.getStyle('display') == 'block')
				return true;
			elm = $(elm.parentNode)
		}	
		return true;
	}
	,mouseCoords : function(ev){
		if(ev.pageX || ev.pageY){
			return {x:ev.pageX, y:ev.pageY};
		}
		return {
			x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
			y:ev.clientY + document.body.scrollTop  - document.body.clientTop
		};
	}
	,getMouseOffset : function (target, ev){
		e = ev || window.event;
		var docPos    = CSI.getPosition(target);
		var mousePos  = CSI.mouseCoords(ev);
		return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
	}
		
	,getPosition : function(e){
		var left = 0;
		var top  = 0;
		while (e.offsetParent){
			left += e.offsetLeft;
			top  += e.offsetTop;
			e     = e.offsetParent;
		}
		left += e.offsetLeft;
		top  += e.offsetTop;
		return {x:left, y:top};
	}
	
	,UP_ARROW : '&#9650'
	,DOWN_ARROW : '&#9660'
	,RIGHT_ARROW : '&#9658'
	,LEFT_ARROW : '&#9668'
};

Object.extend(Date.prototype,CSI.dateMethods);
Object.extend(Array.prototype,CSI.arrayMethods);
Element.addMethods(CSI.domMethods);


function getScroll(){
	if (window.pageYOffset) {
		scrollTop = window.pageYOffset;
		scrollLeft = window.pageXOffset;
	}
	else if (document.documentElement && (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
		scrollTop = document.documentElement.scrollTop;
		scrollLeft = document.documentElement.scrollLeft;
	}
	else if (document.body){
		scrollTop = document.body.scrollTop;
		scrollLeft = document.body.scrollLeft;
	}
	
	
	if (window.innerHeight){
		windowHeight = window.innerHeight
		windowWidth = window.innerWidth
	}
	else if (document.documentElement && document.documentElement.clientHeight) {
		windowHeight = document.documentElement.clientHeight
		windowWidth = document.documentElement.clientWidth
	}
	else if (document.body) {
		windowHeight = document.body.clientHeight;
		windowWidth = document.body.clientWidth;
	}
	return {Top:scrollTop,Left:scrollLeft}
}



function padZero(n,totalDigits){
	n=n+'';
	while (n.length<totalDigits)
		n='0'+n
	return n;
}
function formatDate(d){
	if (!d || !d.getDate) 
		return '';
	return padZero((d.getMonth()+1),2)+'/'+padZero(d.getDate(),2)+'/'+d.getFullYear().toString().substr(2,2)
}
function iraStatus(adstatus,expiredate){
	switch (adstatus){
		case 'e':
			return 'Expired';
		case 'w':
			return 'Withdrawn';
		case 's':
			return 'Sold';
		case 'b':
			return 'Backup Offers';
		case 'p':
			return 'Pending';
		case 'c':
			return 'CMA';
		case 't':
			return 'Cancelled';
		case 'a':
			if (expiredate > new Date())
				return 'Active';
			else
				return 'Expired';
	}
	return '';
}
function getElmById(searchStr,elm){
	var returnElm;
	while (elm && !returnElm){
		if (elm.id == searchStr)
			returnElm = elm;
		else if (elm.childNodes.length)
			returnElm = getElmById(searchStr,elm.firstChild);
		elm = elm.nextSibling;
	}
	return returnElm;
}



function CSSRule(cName,styleObj,optObj){
	if (!optObj)
		var optObj = {};
	if(document.styleSheets.length == 0)
		return;
	for (var i=0;i<document.styleSheets.length;i++){
		var cx = document.styleSheets[i].cssRules || document.styleSheets[i].rules
		for (var x=0;x<cx.length;x++){
			if (cx[x].selectorText == cName){
				if (!optObj.insertOnly)
					Object.extend(cx[x].style,styleObj)
				else
					for (var y in styleObj){
						if (!cx[x].style[y])
							cx[x].style[y] = styleObj[y]
					}
				return;
			}
		}
	}
	var s='';
	delim = '';
	for (var i in styleObj){
		if (i == 'cssFloat' || i == 'styleFloat')
			s+= 'float:'+styleObj[i]+';';
		else
			s += i.underscore().dasherize()+':'+styleObj[i]+';';
	}
	var myStyle = document.styleSheets[0];
	//alert(cName)
	if (myStyle.addRule){//ie
		x = myStyle.addRule(cName,s)
	}
	else {
		myStyle.insertRule(cName+'{'+s+'}',  myStyle.cssRules.length-1)
	}

}

function debug(obj){
	var msg=[];
	for (i in obj){
		try {msg[msg.length] = i+':'+obj[i];}
		catch(e) {msg[msg.length] = i+':'}
	}
	if (!window.debugBox){
		debugBox = document.createElement('div')
		debugBox.style.position = 'absolute';
		debugBox.style.top="10px";
		debugBox.style.left="10px";
		debugBox.style.border="1px solid black";
		debugBox.style.height="100px";
		debugBox.style.padding="10px";
		debugBox.style.backgroundColor="lightblue";
		document.body.appendChild(debugBox);
		debugBox.onclick=function(){debugBox.style.visibility="hidden"};
	}
	
	debugBox.innerHTML = msg.join('<br>')
	debugBox.style.visibility='visible';
}
function getElmsByName(searchString,scope){
	var x = scope.all
	var a=[];
	for (var i=0;i<x.length;i++)
		if (x[i].name == searchString)
			a[a.length]=x[i]
	return a
}
function createCookie(name,value,days,mydomain) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else 
		var expires = "";

	if (!mydomain)
		var mydomain = '';
	else
		mydomain = 'domain='+mydomain;
		
	document.cookie = name+"="+value+expires+"; path=/; "+mydomain;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}
//function isDate(a) {
//    return typeof a == 'date';
//}

function wait(millis) {
	date = new Date();
	var curDate = null;

	do { var curDate = new Date(); } 
		while(curDate-date < millis);
} 

function isFunction(a) {
    return typeof a == 'function';
}
function trim(str_var){
	return str_var.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
}
function mainmenu(){
	history.go('http://'+location.host+'/wwwroot/remaint/index.cfm');
	history.go('http://'+location.host+'/remaint/index.cfm');
	history.go('http://'+location.host+'/remaint/');
	setTimeout('window.location = "/wwwroot/remaint/index.cfm"',500);
}
function checklength(obj){
	setTimeout("updateCounter(textarea.value.length)",3);
	//var uselessKeys = /^9|16|17|35|36|37|8|46|91|38|66|39|40$/
	var uselessKeys = /^9|16|35|36|37|8|46|91|38|66|39|40$/
	if (uselessKeys.test(event.keyCode)) {
		return;
	}
	if (!event.keyCode == "17") {
		if (obj.value.length >= obj.maxlength) {
			return false;
		}
	}
}
function updateCounter(used){
	if (!textarea.maxlength)
		textarea.maxlength=textarea.maxLength;

	if (textarea.value.length > textarea.maxlength){
		textarea.value = textarea.value.substring(0,textarea.maxlength)
		used = textarea.maxlength
	}
	_from.innerHTML = 'used '+used+' ';
	_to.innerHTML = ' of '+textarea.maxlength;
}
function init_from_to(obj){
	textarea = obj;
	_from = document.getElementById(textarea.name+'_from');
	_to = document.getElementById(textarea.name+'_to');
	updateCounter(obj.value.length);
}

function testEmails(str){
	str = str.replace(/;/g,',')
	str = str.replace(/ /g,',')
	var r = /,,/;
	while (r.test(str))
		str=str.replace(r,',')
	var a = str.split(',')
	var v = true;
	for (var i=0;i<a.length;i++)
		if (!testEmail(a[i])){
			v = false;
			break;
		}
	return (v) ? str : v
}
function testEmail(str){
	var emailRe = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/
	return emailRe.test(str)
}
CSSRule('.fLink',{cursor:'pointer',color:'blue',textDecoration:'underline'});

// End of CSITools.js                                           //


// start of dates.js by matt kruse:
// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
/// ------------------------------------------------------------------
// These functions use the same 'format' strings as the 
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
//              | NNN (abbr.)        |
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Day of Week  | EE (name)          | E (abbr)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}

// ------------------------------------------------------------------
// isDate ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}

// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1,dateformat1,date2,dateformat2) {
	var d1=getDateFromFormat(date1,dateformat1);
	var d2=getDateFromFormat(date2,dateformat2);
	if (d1==0 || d2==0) {
		return -1;
		}
	else if (d1 > d2 || d1 == d2) {
		return 1;
		}
	return 0;
	}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}
	
// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
	
// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"||token=="NNN"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) { month -= 12; }
						i_val += month_name.length;
						break;
						}
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="EE"||token=="E"){
			for (var i=0; i<DAY_NAMES.length; i++) {
				var day_name=DAY_NAMES[i];
				if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
					}
				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
	}

// ------------------------------------------------------------------
// parseDate( date_string [, prefer_euro_format] )
//
// This function takes a date string and tries to match it to a
// number of possible date formats to get the value. It will try to
// match against the following international formats, in this order:
// y-M-d   MMM d, y   MMM d,y   y-MMM-d   d-MMM-y  MMM d
// M/d/y   M-d-y      M.d.y     MMM-d     M/d      M-d
// d/M/y   d-M-y      d.M.y     d-MMM     d/M      d-M
// A second argument may be passed to instruct the method to search
// for formats like d/M/y (european format) before M/d/y (American).
// Returns a Date object or null if no patterns match.
// ------------------------------------------------------------------
function parseDate(val) {
	var preferEuro=(arguments.length==2)?arguments[1]:false;
	generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');
	monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');
	dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');
	var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
	var d=null;
	for (var i=0; i<checkList.length; i++) {
		var l=window[checkList[i]];
		for (var j=0; j<l.length; j++) {
			d=getDateFromFormat(val,l[j]);
			if (d!=0) { return new Date(d); }
			}
		}
	return null;
	}



/*
					End of dates.js 
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					
					Start of Mybox.js
*/


CSSRule('.theBox',{fontSize:'12px',border:'1px solid black',padding:'6px',position:'absolute',backgroundColor:'#ffffef'});

function createBox(optObj){
	optObj = optObj || {};
	var b = $(document.createElement('div'));
	b.className = 'theBox';
	var par = $(document.createElement('div'));
	par.setStyle({position:'absolute',visibility:'hidden',left:'0px',right:'0px'});
	par.appendChild(b);
	Object.extend(b,boxMethods);
	
	if (optObj.fullScreen){
		b.fullScreen = true;
		optObj.shadowWidth = 0;
	}

	var shadowWidth = (optObj.shadowWidth != undefined) ? optObj.shadowWidth : 5;
	var shadowOpacity = optObj.shadowOpacity || 24;
	b.addShadow(shadowWidth,shadowOpacity);

	if (optObj.insert){
		b.inline = true;
		var elm = $(optObj.insert);
		if(elm.getStyle('position')=='static')
			elm.style.position = 'relative';
		b.parentNode.style.top = b.parentNode.style.left = '0px';
		elm.appendChild(par);
		return b;
	}

	document.body.appendChild(par);
	return b;
}

insertDivReg = function (){
	var dr = [];
	var fx = function(elm){
		var a=[];
		for (var i = 0;i<dr.length;i++){
			if (dr[i].close && (!elm || !$(elm).descendantOf(dr[i])))
				dr[i].close();
			else
				a.push(dr[i])
		}
		dr = a;
	}
	Event.observe(window,'load',function(){
		Event.observe(document,'click',function(ev){
			e = ev || event;
			t = $(e.srcElement || e.target);
			fx(t);
		})
	})
	return function(div){
		if (!div)
			fx();
		else if (dr.indexOf(div)==-1)
			dr.push(div)
	}
}();

boxMethods = {
	show : function(){
		var oThis = this;
		clearTimeout(oThis.showTimeout)
		oThis.showTimeout = window.setTimeout(function(){
			oThis.parentNode.style.visibility = 'visible';
		},25);
		this.positionShadow();
		if (!oThis.inline && !oThis.pushed && !oThis.disableClose){
			setTimeout(function(){insertDivReg(oThis)},50);
		}
		return this;
	}
	,close : function(){
		this.parentNode.style.visibility = 'hidden';
		return this;
	}
	,position : function(elm,optObj){
		var p, jA, kA, i, x, fits, top, otop, ttop, left, oleft, tleft, tElm, eWidth, eHeight, shadow;
		var validPlacements = ['below/right','above/left','above/right','right/top','right/bottom','left/top','left/bottom']

		if (!optObj)
			optObj = {};

		getScroll();
		if (optObj.placement == 'pointer'){
			var x = optObj.event.x || optObj.event.clientX || 0;
			var y = optObj.event.y || optObj.event.clientY || 0;

			if (x>windowWidth/2)
				left = (x-this.offsetWidth)+scrollLeft-3;
			else
				left = x+scrollLeft+3;
				
			if (y>windowHeight/2)
				top = (y-this.offsetHeight)+scrollTop-3;
			else
				top = y+scrollTop+3;
				
			if (y>windowHeight/2 && x>windowWidth/2){
				top-=4;
				left-=4;
			}
				
			top = Math.max(top,0);
			left = Math.max(left,0);
			this.parentNode.style.top = top+'px';
			this.parentNode.style.left = left+'px';
			this.positionShadow()
			return this;
		}
		tElm = elm;
		tleft = ttop = 0;
		while (tElm && tElm.tagName != 'HTML' ){
			ttop += tElm.offsetTop;
			tleft += tElm.offsetLeft;
			tElm = tElm.offsetParent;
		}
		shadow = this.parentNode.getElementsByClassName('vShadow')[0]
		if (shadow){
			eWidth = this.offsetWidth + shadow.offsetWidth 
			eHeight = this.offsetHeight  + shadow.offsetWidth 
		}
		else {
			eWidth = this.offsetWidth 
			eHeight = this.offsetHeight 
		} 
			
		if (optObj.placement == 'below' || optObj.placement == 'above')
			optObj.placement += '/left'
		else if (optObj.placement == 'left' || optObj.placement == 'right')
			optObj.placement += '/top'
		
		if (!optObj.placement || validPlacements.indexOf(optObj.placement) == -1)
			optObj.placement = 'below/left'
		
		var p = optObj.placement.split('/')
		if (p[0] == 'below')
			jA = ['below','above','right','left']
		else if (p[0] == 'above')
			jA = ['above','below','right','left']
		else if (p[0] == 'right')
			jA = ['right','left','below','above']
		else if (p[0] == 'left')
			jA = ['left','right','below','above']
			
		outer_loop:
		for (i=0; i<jA.length; i++){
			if (jA[i] == 'above' || jA[i] == 'below')
				kA = (p[1] == 'left') ? ['left','right'] : ['right','left']
			else
				kA = (p[1] == 'top') ? ['top','bottom'] : ['bottom','top']

				
			if (optObj.cover) {
				if ( jA[i] == 'above') 
					otop = -eHeight;
				else if (jA[i] == 'below')
					otop = 0;
				else if (jA[i] == 'left')
					oleft = -eWidth;
				else if (jA[i] == 'right')
					oleft = elm.offsetWidth;
			}
			else {
				if ( jA[i] == 'above') 
					otop = -eHeight;
				else if (jA[i] == 'below')
					otop = elm.offsetHeight;
				else if (jA[i] == 'left')
					oleft = -eWidth;
				else if (jA[i] == 'right')
					oleft = elm.offsetWidth;
			}
			for (x=0;x<kA.length;x++){
				left = oleft;
				top = otop;
				if (kA[x] == 'left')
					left =  0;
				else if (kA[x] == 'right')
					left = (eWidth - elm.offsetWidth)*-1
				else if (kA[x] == 'top')
					top = 0
				else if (kA[x] == 'bottom')
					top = (eHeight - elm.offsetHeight)*-1
				
				top += ttop;
				left += tleft;
				
				fits = true;
				if (optObj.force)
					break outer_loop;
					
				if (((left + eWidth) - scrollLeft > windowWidth)
				|| ((top + eHeight) - scrollTop > windowHeight)
				|| (top - scrollTop < 0)
				|| (left - scrollLeft < 0)){
					fits = false;
				}
				else
					break outer_loop;
			}
				
		}
		if (!fits){
			for (var i=0;i<jA.length; i++){
				if ( jA[i] == 'above'){
					top = -eHeight+ttop;
					left = scrollLeft;
				}
				else if (jA[i] == 'below'){
					top = elm.offsetHeight+ttop;
					left = scrollLeft;
				}
				else if (jA[i] == 'left'){
					left = -eWidth+tleft;
					top = scrollTop;
				}
				else if (jA[i] == 'right'){
					left = elm.offsetWidth+tleft;
					top = scrollTop;
				}
				
				fits = true;
				if (((left + eWidth) - scrollLeft > windowWidth)
				|| ((top + eHeight) - scrollTop > windowHeight)
				|| (top - scrollTop < 0)
				|| (left - scrollLeft < 0)){
					fits = false;
				}
				else
					break;
			}
		}
		top = Math.max(top,0);
		left = Math.max(left,0);
		this.parentNode.style.top = top+'px';
		this.parentNode.style.left= left+'px';
		this.positionShadow()
		return this;
	}
	,center : function(){
		var par = this.parentNode;
		if (par.style.position != 'absolute')
			return;
		getScroll();
		var divTop = Math.round(scrollTop+((windowHeight - this.offsetHeight)/2))
		var divLeft = Math.round(scrollLeft+((windowWidth - this.offsetWidth)/2))
		par.style.top = Math.max(divTop,0)+'px'
		par.style.left = Math.max(divLeft,0)+'px'

		getScroll();
		if (this.offsetHeight > windowHeight){
			var oThis = this;
			var fHeight = (oThis.footer) ? oThis.footer.offsetHeight : 0;
			oThis.formBody.style.height = (windowHeight - (oThis.hdr.offsetHeight + fHeight + parseInt(oThis.formBody.getStyle('paddingTop')) + parseInt(oThis.formBody.getStyle('paddingBottom')) ) )+'px'
			oThis.formBody.style.overflowY = 'scroll'
		}
		
		this.positionShadow()
		return this
	}
	,addShadow : function(width,opacity){
		if (width==0)
			return this;
		var par = this.parentNode
		var width = width || 3;
		var opacity = opacity || 28;
		var vShadow = $(document.createElement('div'))
		var hShadow = $(document.createElement('div'))
  
  		vShadow.className = 'vShadow';
  		hShadow.className = 'hShadow';
		var bb = parseInt(this.getStyle('borderBottomWidth')) || 0;
		var br = parseInt(this.getStyle('borderRightWidth')) || 0;
		var bt = parseInt(this.getStyle('borderTopWidth')) || 0;
		var bl = parseInt(this.getStyle('borderLeftWidth')) || 0;
  
		vShadow.setStyle({position:'absolute',backgroundColor:'black',opacity:opacity/100,filter:'alpha(opacity='+opacity+')'})
		hShadow.setStyle({overflow:'hidden',position:'absolute',backgroundColor:'black',opacity:opacity/100,filter:'alpha(opacity='+opacity+')'})
		hShadow.style.height = vShadow.style.width = width+'px';
		vShadow.style.top = ((2*width))+'px'
		hShadow.style.left = ((2*width))+'px';
		par.appendChild(vShadow);
		par.appendChild(hShadow);
		return this;
	}
	,positionShadow : function(){
		var shadowWidth = 0;
		if (vShadow = this.parentNode.getElementsByClassName('vShadow')[0]){
			var hShadow = this.parentNode.getElementsByClassName('hShadow')[0]
			shadowWidth = vShadow.offsetWidth;
			
			vShadow.style.height = (((this.offsetHeight)+shadowWidth)-2*shadowWidth)+'px';
			hShadow.style.width = ((this.offsetWidth)-2*shadowWidth)+'px';
			vShadow.style.left = (this.offsetWidth)+'px';
			hShadow.style.top = (this.offsetHeight)+'px';
		}
		if (this.inline){
			var offsetHeight = this.offsetHeight + shadowWidth;
			var offsetWidth = this.offsetWidth + shadowWidth;
			var par = this.parentNode.parentNode;
			var dims = par.getDimensions();
			par.style.height = Math.max(dims.height,offsetHeight)+'px';
			par.style.width = Math.max(dims.width,offsetWidth)+'px';
		}
		return this;
	}
	,adjLeft	: function(v){
		this.parentNode.style.left = (parseInt(this.parentNode.style.left)+v)+'px';
		return this
	}
	,adjTop	: function(v){
		this.parentNode.style.top = (parseInt(this.parentNode.style.top)+v)+'px';
		return this;
	}
}



/*							End of mybox.js
							
							
							
							Start of dmenu.js
*/

CSSRule('.dMenu',{padding:'2px',cursor:'pointer',border:'1px solid #aaa',fontFamily:'tahoma',fontSize:'.7em'});
CSSRule('.dMenu div',{position:'relative',color:'black',padding:'2px 16px 2px 3px',backgroundColor:'white',whiteSpace:'nowrap'});
CSSRule('.dMenu .sel',{color:'white',backgroundColor:'#3B46BF'});
CSSRule('.dMenu span',{position:'absolute',right:'5px',fontSize:'xx-small',paddingTop:'1px'});

if (!window.menuObject)
	menuObject = {};
if (!window.menuObject2)
	menuObject2 = {};

function showMenu(t,str,e){
	t=$(t);
	var o = {};
	if (!menuObject2[str])
		if (menuObject[str])
			menuObject2[str] = createMenu(str,t);
		else {
			alert('no menu')
			return;
		}

	var m = menuObject2[str];
	m.linkElm = t;
	
	if (!t.hasClassName('menuItem') && $(t.parentNode).hasClassName('menuItem')){
		t=$(t.parentNode);
	}
	if (t.hasClassName('menuItem')){
		m.instigator = t;
		m.parentMenu = t.parentNode;
	}
	if (m.parentMenu){
		m.parentMenu.subMenu = m;
		if (!m.parentMenu.horizontal)
			o = {placement:'right'};
	}
	if (m.placement)
		o = {placement:m.placement};
	
	m.show();
	if (m.placement == 'pointer' && e){
		x = e.x || e.clientX
		y = e.y || e.clientY
		o = {placement:'pointer',x:x,y:y}
		m.position(t,o);
	}
	else if (m.placement != 'inline')
		m.position(t,o);
	return m;
}

menuMethods = {
	closeSubMenu : function(){
		var m = this;
		var a = [];
		while (m.subMenu){
			if (a.indexOf(m)>-1){
				alert('error : circular reference')
				return;
			}
			a.push(m)
			if (m.subMenu.selectedItem){
				m.subMenu.selectedItem.removeClassName('sel');
				m.subMenu.selectedItem = null;
			}
			m.subMenu.close()
			m = m.subMenu;
			m.parentMenu.subMenu = null;
		}
	}
	,evaluate : function(){
		var divs = this.getElementsByTagName('div');
		for (var i=0;i<divs.length;i++){
			try {divs[i].disabld = !eval(divs[i].condition)}
			catch(err){divs[i].disabld = true;}
			if (divs[i].disabld)
				divs[i].style.color = 'lightgrey'
			else
				divs[i].style.color = ''
		}
	}
	,setTitle : function(str,styleObj){
		this.titleSpan.innerHTML = str;
		if (styleObj){
			$(this.titleSpan).setStyle(styleObj);
		}
		this.titleSpan.style.display = '';
		return this;
	}
	,onmouseover : function(e){
		var ev = (e) ? e : event;
		var t = $(ev.target || ev.srcElement)
		if (t.className == 'menuItem' && !t.disabld){
			var m = t.parentNode;
			m.selectItem(t);
		}
	}
	,onclick : function(e){
		var ev = (e) ? e : event;
		var t = $(ev.target || ev.srcElement)

		if (!t.hasClassName('menuItem'))
			t=t.parentNode;
		
		if (t.disabld){
			Event.stop(ev);
			return
		}
		
		var controlObj;
		
		if (t.hasClassName('menuItem')){
			var m = t;
			while (!controlObj && m){
				if (m.controlObj)
					controlObj = m.controlObj;
				else if (m.readAttribute && (controlObj = m.readAttribute('controlObj')))
					;
				else if (m == this)
					break;
				else
					m = m.parentNode;
			}
			controlObj = controlObj || {};			
		
			if (typeof(t.fx)=='function'){
				if (typeof (controlObj) == 'string')
					eval ('controlObj = '+ controlObj);
					
				t.fx(ev,controlObj);
			}
			else {
				if (m.autoOpen && m.subMenu){
					m.subMenu.close();
					m.autoOpen = false;
				}
				else{
					showMenu(t,t.fx);
					if (m.horizontal)
						m.autoOpen = true;
				}
			}
		}
	}

	,onmouseenter	:	function(){
		if (this.timeout)
			clearTimeout(this.timeout)
		if (this.instigator && this.parentMenu.selectedItem != this.instigator)
			this.parentMenu.selectItem(this.instigator);
	}
	,selectItem	:	function(t){
		var m = this;
		if (m.selectedItem){
			if (m.selectedItem == t)
				return;
			if (m.subMenu && m.subMenu.instigator == m.selectedItem && !m.autoOpen)
				m.subMenu.timeout = setTimeout(function(){m.closeSubMenu()},700);
			if (m.selectedItem.timeout)
				clearTimeout(m.selectedItem.timeout)
			m.selectedItem.removeClassName('sel')
		}
		t.addClassName('sel')
		m.selectedItem = t;
		if (m.subMenu && m.subMenu.instigator == t && m.subMenu.timeout)
			clearTimeout(m.subMenu.timeout);
			
		if (m.autoOpen){
			m.closeSubMenu()
			if (!t.disabld && typeof(t.fx)=='string')
				showMenu(t,t.fx);
		}
		else if (!m.horizontal && !t.disabld && typeof(t.fx)=='string')
			t.timeout = setTimeout(function(){showMenu(t,t.fx)},700)
	}
}

function createMenu(str,t){
	var optObj = {}
	optObj.shadowOpacity = menuObject[str].shadowOpacity || 24;
	optObj.shadowWidth = (menuObject[str].shadowWidth == undefined) ? 3 : menuObject[str].shadowWidth


	var x = t;
	var z = 0;
	while (x && x.getStyle){
		z = Math.max( x.getStyle('zIndex'),z)
		x = $(x.parentNode);
	}
	
	var box = createBox(optObj)
	box.parentNode.style.zIndex = z+1;
	box.placement = menuObject[str].placement || 'jj';

	
	if (menuObject[str].placement == 'inline'){
		t.appendChild(box.parentNode);
		box.style.position = box.parentNode.style.position = 'relative'
	}


	box.addClassName(menuObject[str].className || 'dMenu');
	box.dMenu = true;
	
	Object.extend(box,menuMethods);
	box.style.padding = '';
	
	box.hideOnClick = menuObject[str].hideOnClick || false;
	
	var d,h,arrow;
	var a;
	
	box.horizontal = !!menuObject[str].horizontal;
	var hideArrows = !!menuObject[str].hideArrows;
	
	arrow = (box.horizontal) ? '&#9660' : '&#9658';
	var left = parseInt(box.getStyle('paddingLeft'));
	var item;
	box.titleSpan = box.appendChild(document.createElement('div'));
	box.titleSpan.style.display='none';
	
	for (var i=0;i<menuObject[str].items.length;i++){
		item = menuObject[str].items[i];
		if (!item.length){
			if (!box.horizontal){
				box.appendChild(document.createElement('hr')).style.width='1px'
				var followhr = true;
			}
		}
		else{
			d = $(document.createElement('div'));
			d.className = 'menuItem';
			try{
				d.disabld = !eval(item[2]);
			}
			catch(err){
				d.disabld = true;
			}
			if (d.disabld)
				d.style.color = 'lightgrey'
			a=[item[0]]
			
			if (typeof(item[1])=='string' && !hideArrows)
				a.push('<span>'+arrow+'</span>');
			d.fx = item[1];
			d.condition = item[2];
			d.innerHTML = a.join('');
			box.appendChild(d)
			if(followhr){
				d.style.marginTop='-7px'
				followhr = false;
			}
			if(box.horizontal){
				d.style.position = 'absolute';
				d.style.left = left+(parseInt(d.getStyle('marginLeft') || 0))+'px';
				left += d.offsetWidth+(parseInt(d.getStyle('marginLeft') || 0))+(parseInt(d.getStyle('marginRight') || 0));
			}
		}
	}
	var hrs = box.getElementsByTagName('hr');
	var width = box.offsetWidth-12;

	for (var i=0;i<hrs.length;i++){
		hrs[i].style.width = width+'px';
		hrs[i].style.marginTop = '-4px'
	}
	if (box.horizontal){
		box.style.width = (left-parseInt(box.getStyle('paddingLeft')))+'px'
		box.style.height = d.offsetHeight+'px';
	}
	menuObject2[str] = box;
	return box;
}


function closeMenu(e){
	var t= $(e.srcElement || e.target);
	var elm = t;
	while (t && !$(t).dMenu && t.tagName != 'BODY'){
		t = $(t.parentNode);
	}

	var ea = [];
	if (t && t.selectedItem && t.selectedItem.subMenu){
		ea.push(t.selectedItem.subMenu)
	}
	
	while (t && t.dMenu && !t.hideOnClick){
		alert(t.innerHTML)
		ea.push(t)
		if (t.parentMenu){
			if (t == t.parentMenu){
				alert('error:circular reference')
				return;
			}
			t=t.instigator.parentNode
		}
		else
			t=null
	}
	var mo = menuObject2;
	var moi;
	for(var i in mo){
		moi = mo[i];
		if (mo.hasOwnProperty(i)){
			if (ea.indexOf(moi) == -1 && elm != moi.linkElm){
				if (moi.placement != 'inline'){
					moi.close();
				}
				moi.autoOpen = false;
				if (moi.selectedItem){
					moi.selectedItem.removeClassName('sel')
					moi.selectedItem = null;
				}
			}
		}
	}
}

Event.observe(window,'load',function(){
	Event.observe(document.body,'click',closeMenu)
})




/*
									End of dmenu.js
									
									
									Start of jsform.js
*/
CSSRule('.formHdr',{backgroundColor:'#eee',borderBottom:'1px solid #666',padding:'8px 24px 8px 8px'});
CSSRule('.jsForm .formBody',{padding:'8px',fontSize:'10px',fontFamily:'verdana'});
CSSRule('.formFooter',{backgroundColor:'#eee',borderTop:'1px solid #666',padding:'8px'});
CSSRule('.jsForm',{padding:'0px'});
CSSRule('.jsForm .icon',{padding:'4px 3px',position:'absolute',top:'6px',cursor:'pointer'});
CSSRule('.jsForm form',{margin:'0px',fontFamily:'Verdana',fontSize:'12px'});
CSSRule('.jsForm .error',{color:'red'});
CSSRule('.jsForm .title',{fontSize:'14px',fontWeight:'bold',whiteSpace:'nowrap'});
CSSRule('.jsForm .formFooter',{textAlign:'right',padding:'3px 8px',whiteSpace:'nowrap',fontSize:'.8em'});
CSSRule('.jsForm button',{backgroundColor:'#016066',color:'#eee'});

CSSRule('.resultsDiv',{padding:'1px',cursor:'pointer',fontSize:'12px',fontFamily:'verdana'});
CSSRule('.resultsDiv td',{padding:'3px 6px',whiteSpace:'nowrap'});
CSSRule('.resultsDiv .odd',{backgroundColor:'#bbb'});
CSSRule('.resultsDiv .highlight',{backgroundColor:'brown',color:'white'});
CSSRule('.msg',{padding:'6px',backgroundColor:'brown',color:'white',fontWeight:'bold',fontSize:'12px'});
CSSRule('.reportForm td',{padding:'0px 12px 0px 0px',whiteSpace:'nowrap',fontSize:'12px'});
CSSRule('.reportForm .noPad',{padding:'0px'});
CSSRule('.reportForm .colHdr',{fontWeight:'bold',whiteSpace:'nowrap'});
CSSRule('.filter',{cursor:'pointer',textDecoration:'underline'});
CSSRule('.notFound',{color:'red',fontSize:'1.2em'});
CSSRule('.b',{fontWeight:'bold'});
CSSRule('.foundText',{backgroundColor:'#007',color:'#ffd'});
/**************************************************************/
	CSI.png =  function(src){
		// returns either a div with a background image(ie <=6.0) or an image everything else
			
		var i = $(document.createElement('img'));
		i.src = src;
		//if (!window.XMLHttpRequest){
		//	var d = $(document.createElement('div'));
			//d.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="/lib/icons/printer.png",sizingMethod="image")';
		//	d.style.height = (i.height+8)+'px';
		//	d.style.width = (i.width+8)+'px';
		//	i = d;
		//}
		i.className = 'icon';
		return i;
	}


function createReport(optObj){
	optObj = optObj || {};
	//optObj.noFooter = true;
	var rpt = createForm(optObj);

	if (!optObj.disablePrint){
		var i;
		i = CSI.png('/wwwroot/lib/icons/printer.png');
		i.title = 'Print Report';
		i.style.right = rpt.rightMargin + 'px'
		i.style.top = '3px'
		rpt.rightMargin += (i.width+6);
		rpt.hdr.appendChild(i);
		Event.observe(i,'click',function(){
			var a = ['<html><body onload="print();window.close();"><center>'];
			if (this.printTitle)
				a.push('<div style="font-size:22px">'+this.printTitle+'</div>');
			
			a.push('<table><tr>');
			for (var i=0;i<this.reportColumnHeadings.length;i++){
				var item = this.reportColumnHeadings[i]
				if (!item.hideOnPrint){
					a.push('<td style="text-decoration:underline">'+item.hdrValue+'</td>')
				}
			}
			var trs = this.formBody.getElementsByTagName('tr');
			for (var j=0;j<trs.length;j++){
				a.push('<tr>');
				var tds = trs[j].childNodes;
				var x = 0;
				for (var i=0;i<this.reportColumnHeadings.length;i++){
					if ( this.reportColumnHeadings[i].filterFx || this.reportColumnHeadings[i].freeFilter)
						x++;
					var item = this.reportColumnHeadings[i];
					if (!item.hideOnPrint){
						a.push('<td class="printCol">'+tds[x].innerHTML+'</td>');
					}
					x++;
				}
				a.push('</tr>');
			}
			a.push('</table></body></html>');
			var printWindow = window.open("", "printWindow", "toolbar=no, location=no, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=yes, copyhistory=no");
			printWindow.document.open()
			window.focus();
			printWindow.document.write(a.join(''));
			printWindow.document.close();
		}.bind(rpt));
	};
	
	if (!optObj.disableExcel){
		var i;
		i = CSI.png('/wwwroot/lib/icons/page_excel.png');
		i.title = 'Download Excel';
		i.style.right = rpt.rightMargin + 'px'
		i.style.top = '3px'
		rpt.rightMargin += (i.width+6);
		rpt.hdr.appendChild(i);
		Event.observe(i,'click',function(){alert('downloading')}.bind(rpt));
	};
	

	var a = ['<table cellspacing=0 cellpadding=0><tr><td><input type="text" '
			,'style="background-color:#fff;color:blue;'
			,'font-weight:bold;'
			,'padding-left:18px;'
			,'background-image:url(\'/wwwroot/lib/icons/zoom.png\');'
			//,'background-repeat:no-repeat"></td><td> '
			,'background-repeat:no-repeat"></td><td style="width:50px;overflow:hidden" class="notFound"> '
			//,'<span style="width:50px;overflow:hidden" class="notFound"></span></td></tr></table>'
			,'</td></tr></table>'
		] 
	rpt.footer.innerHTML = a.join('');
	rpt.searchInput = rpt.footer.getElementsByTagName('input')[0];
	var lastVal = 'tim is good';
	var notFound = rpt.footer.getElementsByClassName('notFound')[0];
	rpt.onEnterKey=function(){};
	var positions, current,val;
	
	var currentHighlighted;
	rpt.highlightFound = function(x){
		if (currentHighlighted)
			currentHighlighted.style.backgroundColor = '';
		currentHighlighted = this.foundItems[x];
		if (currentHighlighted){
			currentHighlighted.style.backgroundColor = '#e20';
			currentHighlighted.scrollToView();
		}
	}
	/*rpt.next = function(){
		if (!found.length)
			return;
		if (current+1 >= found.length){
			if (!confirm('End reached.\nStart over at Beginning?'))
				range.call(this);
			else
				current = 0;
		}
		else
			current++;
		range.call(this);
	}*/
	
	/*rpt.prev = function(){
		if (!found.length)
			return;
		if (!current){
			if (!confirm('Beginning reached.\nStart over from End?'))
				range.call(this);
			else
				current = found.length-1;
		}
		else
			current--;
		range.call(this);
	}*/
	
	/*var range = function(){	
		if (!val || !trim(val).length)
			return;
			
		if (current == undefined) 
			return;
			
		found[current].scrollToView();
		i = current;
		if (document.createRange){ //ff
			var range = document.createRange();
			var textNode = found[i];
			while (textNode.nodeName != '#text')
				textNode = textNode.firstChild;
			range.setStart(textNode, positions[i]);
			range.setEnd(textNode, positions[i]+val.length);
			var s = window.getSelection();
				if(s.rangeCount > 0) s.removeAllRanges();
			s.addRange(range);
		}
		else {
			// asume ie
			//alert(this.searchInput.value)
			var range = document.body.createTextRange();
			range.moveToElementText(found[i])
			this.searchInput.focus();
			range.select();
			//	range.execCommand("Copy");
			//	range.collapse();
			//	range.select();
			//	scroll(0,0)
		}
	}*/
	
	
	
	/*Event.observe(rpt.searchInput,'keydown',function(e,elm){
		if (e.keyCode != 13)
			return;
		this.next();
		e.stop();
	}.bindAsEventListener(rpt,rpt.searchInput));
	*/

	// searchText method .
	rpt.searchText = function(p1){
		if (p1 == 'reset')
			lastVal = '';
		var val = trim(this.searchInput.value);
		if (val == ''){
			notFound.innerHTML = '';
			lastVal = '';
			if (this.findResults){
				var tds = this.formBody.getElementsByTagName('td');
				for (var i=0;i<tds.length;i++){
					if (tds[i].firstChild && tds[i].firstChild.className == 'fLink')
						var item = tds[i].firstChild
					else
						var item = tds[i];
						
					item.innerHTML = (item.innerText != undefined) ? item.innerText : item.textContent;
				}
				this.findResults = 0;
			}
			return this;
		}
			
		if (val == lastVal){
			return this;
		}
		
		lastVal = val;
		var pos;
		var rememberPos;
		var re = new RegExp('\\b'+val,"i")
		var tds = this.formBody.getElementsByTagName('td');
		positions = [];
		this.findResults = 0;
		this.foundItems = [];
		for (var i=0;i<tds.length;i++){
			var item = $(tds[i]);
			if (tds[i].firstChild && tds[i].firstChild.className == 'fLink')
				item = tds[i].firstChild
			
			var innerText = (item.innerText != undefined) ? item.innerText : item.textContent;
			pos = innerText.search(re);
			if (pos+1){
				this.findResults++;
				var wArray = innerText.split('');
				wArray.splice(pos+val.length,0,'</span>')
				wArray.splice(pos,0,'<span class="foundText">')
				//if (item.innerText)
					item.innerHTML = wArray.join('');
				//else
				//	item.textContent = wArray.join('');
	
				this.foundItems.push(item);
				//positions.push(pos);
			}
			else
				item.innerHTML = innerText;
		}

		if (!this.findResults){
			CSI.clearSelection();
			this.searchInput.focus();
			notFound.innerHTML = 'Not Found'
			//setTimeout(function(){this.focus();}.bind(this.searchInput),1150);
		}
		else {
			notFound.innerHTML = this.findResults + ' Matches';
			current = 0;
			//range.call(this);
		}
		this.foundItems = this.formBody.select('span.foundText');
		this.highlightFound(0);
		return this;
	}

	/*Event.observe(rpt.searchInput,'click',function(){
		lastVal = '';
		this.searchText()
	}.bind(rpt));*/
	
	
	Event.observe(rpt.footer.firstChild,'keyup',function(e,elm){
		t = $(e.srcElement || e.target);
		//if (e.keyCode == 40){
		//	return this.next();
		//}
		//if (e.keyCode == 38){
		//	return this.prev();
		//}
		this.searchText(trim(elm.value));
	}.bindAsEventListener(rpt,rpt.footer.getElementsByTagName('input')[0]));
	
	rpt.footer.style.textAlign = 'left';
	rpt.addClassName('reportForm');
	var colHdrs = rpt.hdr.columnHeaders = rpt.hdr.appendChild(document.createElement('div'));
	rpt.hdr.style.paddingBottom = '0px';
	rpt.hdr.columnHeaders.style.paddingTop = '8px';

	var savedCloseMethod = rpt.close;

	
	rpt.close = function(){
		var a = this.getElementsByClassName('arrow');
		for (var i=0;i<a.length;i++)
			a[i].style.visibility = 'hidden';
		savedCloseMethod.call(this);
	}
	
	
	
	colHdrs.innerHTML = CSI.DOWN_ARROW;
	var dArr = colHdrs.innerHTML;
	colHdrs.innerHTML = CSI.UP_ARROW;
	var uArr = colHdrs.innerHTML;
	colHdrs.innerHTML = '';
	Event.observe(colHdrs,'click',function(e){
		var ffi;
		var t = $(e.srcElement || e.target);
		var sortOrder, sortDir;
		if (t.tagName == 'IMG'){
			var colId = t.getAttribute('colId');
			if (cacheColHdrs[colId].freeFilter){
				if (!cacheColHdrs[colId].freeFormatInput){
					ffi = cacheColHdrs[colId].freeFormatInput = createBox()
					ffi.innerHTML = '<div><span class="title"></span><span class="fLink" style="padding:0px 24px 0px 8px">clear</span></div><img style="position:absolute;right:0;top:0;padding:6px" src="/wwwroot/lib/csitools/2.0/close_small.gif"><input type="text" size="30">';
					ffi.parentNode.style.zIndex = parseInt(rpt.parentNode.style.zIndex)+2;
					ffi.titleSpan = ffi.getElementsByTagName('span')[0];
					ffi.input = ffi.getElementsByTagName('input')[0];
					ffi.image = t;
					Event.observe(ffi.getElementsByTagName('img')[0],'click',function(){ffi.close()});
					Event.observe(ffi.getElementsByClassName('fLink')[0],'click',function(){
						ffi.input.value='';
						ffi.input.focus()
						ffi.image.src = "/wwwroot/lib/icons/filterplus.png";
						ffi.image.title = "Set Column Filter";
						ffi.re = null;
						rpt.loadData()
					});
					Event.observe(ffi.input,'keyup', function(e){
						var t = $(e.srcElement || e.target);
						if (trim(t.value)){
							ffi.image.src = "/wwwroot/lib/icons/filterminus.png";
							ffi.image.title = "Modify or Remove Column Filter";
							ffi.re = new RegExp('\\b'+trim(t.value),"i");
						}
						else {
							ffi.image.src = "/wwwroot/lib/icons/filterplus.png";
							ffi.image.title = "Set Column Filter";
							ffi.re = null;
						}
							
						if (e.keyCode==13){
							ffi.close();
						}
						else {
							//if (trim(t.value))
							rpt.loadData();
						}
					}.bindAsEventListener(ffi));
				}
				else {
					ffi = cacheColHdrs[colId].freeFormatInput;
				}
				ffi.titleSpan.innerHTML = 'Filter for  Column: <span class="b">'+cacheColHdrs[colId].hdrValue+'</span>';
				ffi.position(t,{placement:'right/top'}).adjTop(-27).adjLeft(8).show();
				setTimeout(function(){ffi.input.focus()},50);
			}
			else if (cacheColHdrs[colId].filterFx){
				if (!cacheColHdrs[colId].filterOptionsForm){
					var fof = cacheColHdrs[colId].filterOptionsForm = createMultiOptForm();
				}
				else 
					var fof = cacheColHdrs[colId].filterOptionsForm;
				fof.setTitle('Filter for  Column: <span class="b">'+cacheColHdrs[colId].hdrValue+'</span>');
				fof.position(t,{placement:'right/top'}).adjTop(-27).adjLeft(8).show();
				fof.parentNode.style.zIndex = parseInt(rpt.parentNode.style.zIndex)+2;
			}
		}
		if (!(sortOrder = t.getAttribute('sortOrder')))
			return;

		sortDir = t.getAttribute('sortDir') || 'asc';
		
		var arrowSpan = $(t.nextSibling);

		var hdrTD = $(t.parentNode.parentNode.firstChild);
		while (hdrTD){
			if (!hdrTD.hasClassName('noPad'))
				hdrTD.lastChild.style.visibility = 'hidden';
			hdrTD = $(hdrTD.nextSibling);
		}
		
		var so;
		t.nextSibling.style.visibility = 'visible';
		if ((so = t.getAttribute('sortOrder'))==this.sortParms.sortOrder){
			if (this.sortParms.sortDir == 'desc'){
				this.sortParms.sortDir = 'asc';
			}
			else
				this.sortParms.sortDir = 'desc';
		}
		else{
			this.sortParms.sortOrder = so;
			this.sortParms.sortDir = sortDir;
		}
		

		arrowSpan.addClassName('vis');
		arrowSpan.innerHTML = (this.sortParms.sortDir == 'asc') ? uArr : dArr

		this.loadData();
		//listPeople({sortDir:sortDir,sortOrder:sortOrder,controlObj:{teamSeasonId: tx.teamSeasonId}});
	}.bindAsEventListener(rpt));
	
	rpt.syncHdr = function(){
		var h = this.hdr.columnHeaders.getElementsByTagName('tr')[0];
		var b = this.formBody.getElementsByTagName('tr')[0];
		var hc = h.getElementsByTagName('td');
		if (!b) 
			return this;
		
		var bc = b.childNodes;
		//alert(hc.length+':'+bc.length);
		var padding;
		
		for (var i=0;i<bc.length;i++){
			bci = $(bc[i]);
			hci = $(hc[i]);
			padding = parseInt(bci.getStyle('paddingLeft'))+parseInt(bci.getStyle('paddingRight'));
			if (bci.offsetWidth > padding){
				hci.style.width = (bci.offsetWidth-padding-1)+'px';
				//alert(hci.style.width);
			}
		}
		return this;
	}


	//  start of method loadData   //
	
	var cacheDataArray;
	var cacheColHdrs;
		
		
		
		
	rpt.loadData = function(){
		var xs = {};
		return function(dataArray,colHdrs){
			var reload;
			if (dataArray){
				cacheDataArray = dataArray;
				xs = {};
				if (colHdrs)
					cacheColHdrs = colHdrs;
			}
			else {
				reload = true;
				dataArray = cacheDataArray;
				colHdrs = cacheColHdrs;
			}
			if (!colHdrs)
				colHdrs = cacheColHdrs;
				
			if (!colHdrs){
				colHdrs = cacheColHdrs = [];
				for (var i in dataArray[0]){
					if (dataArray[0].hasOwnProperty(i)){
						colHdrs.push({colName:i,hdrValue:i,sortOrder:i})
						if (!colHdrs.sortParms)
							colHdrs.sortParms = {sortOrder:i,sortDir:'asc'}
					}
				}
			}
			if (!colHdrs.sortParms){
				colHdrs.sortParms = {sortOrder:'',sortDir:'asc'}
			}
			rpt.sortParms = colHdrs.sortParms;
			
			var u, filterSpan, tVar='';
			var dl = dataArray.length;
			
			var a = ['<table cellpadding="0" cellspacing="0"><tr>'];
			for (var i=0;i<colHdrs.length;i++){
				var ch=colHdrs[i];
				if (!ch.sortDir)
					ch.sortDir = 'asc';
				
				// count uniq values in column.
				var aUniq=[];
				for (var j =0;j<dl;j++){
					if (aUniq.indexOf(dataArray[j][colHdrs[i].colName])==-1){
						aUniq.push(dataArray[j][colHdrs[i].colName]);
						if (aUniq.length > 1)
							break;
					}	
				}
				
				if (ch.filterFx || ch.freeFilter){
					a.push('<td '+(aUniq.length<2?'style="visibility:hidden"':'')+' class="noPad"><img colId="'+i+'" title="Set Column Filter" src="/wwwroot/lib/icons/filterplus.png"></td>');
				}
				a.push('<td>');
				if (ch.sortOrder && aUniq.length > 1){
					a.push('<span class="colHdr fLink" sortDir="'+ch.sortDir+'" sortOrder="'+ch.sortOrder+'">'+ch.hdrValue+'</span>');
					a.push('<span class="arrow" style="visibility:hidden">'+CSI.DOWN_ARROW+'</span>');
				}
				else
					a.push('<span class="colHdr">'+(ch.hdrValue?ch.hdrValue:'&nbsp;&nbsp;')+'</span><span></span>');
				a.push('</td>');
			}

			if (!reload){
				this.hdr.columnHeaders.innerHTML = a.join('')+'</tr></table>';
			}
	
	
			var sa;
			
			
			if (xs[colHdrs.sortParms.sortOrder]){
				sa = xs[colHdrs.sortParms.sortOrder];
			}
			else {
				sa = xs[colHdrs.sortParms.sortOrder] = function(){
					var sc, sortCols;
					var myArray = [];
					
					for (var i=0;i<dataArray.length;i++){
						myArray.push(dataArray[i]);
					}
	
					sortCols = colHdrs.sortParms.sortOrder;
					sc = sortCols.split(',');
					myArray.sort(function(a,b){
						for (var i=0;i<sc.length;i++){
							if ( parseInt(a[sc[i]]) == a[sc[i]] &&  parseInt(b[sc[i]]) == b[sc[i]] ){
								if (parseInt(a[sc[i]])!=parseInt(b[sc[i]]))
									return parseInt(a[sc[i]])-parseInt(b[sc[i]]);
							}
							else {
								if  (a[sc[i]]<b[sc[i]]){
									return -1
								}
								else if (a[sc[i]]>b[sc[i]]){
									return 1
								}
							}
						}
						return 0;
					});
					return myArray;
				}();
			}
			
			var sa2;
			if (rpt.sortParms.sortDir == 'desc'){
				sa2 = sa.reverse(false);
			}
			else {
				sa2 = sa;
			}
			var fVal, tVal, re, pos, a2;
			outer:
			for (var i in sa2){
				if (sa2.hasOwnProperty(i)){
					a2=[];
					a2.push('<tr>');
					for (var j=0;j< colHdrs.length;j++){
						var item = colHdrs[j];
						re = item.freeFormatInput && item.freeFormatInput.re;
						
						if (item.filterFx || item.freeFilter){//empty column to line up with image in header;	
							a2.push('<td class="noPad">&nbsp;</td>');
						}
					
						a2.push('<td valign="top" nowrap style="padding-bottom:12px">');
						if (item.fx){
							tVal = item.fx(sa2[i])
							if (re && !(tVal.search(re)+1))
								continue outer;
							a2.push(tVal)
						}
						else if (item.colName.match(/Date$/)){
							a2.push(CSI.formatDate(sa2[i][item.colName],{yr2digit:true}));
						}
						else {
							tVal = sa2[i][item.colName] || '';
							if (re && !(tVal.search(re)+1))
								continue outer;
							a2.push(tVal);
						}
						a2.push('</td>');
					}
					a.push(a2.join('')+'</tr>');
				}
			}
			a.push('</table>');

			this.formBody.innerHTML = a.join('');
			var table = this.formBody.getElementsByTagName('table')[0];
			var rows = table.getElementsByTagName('tr');
			var cell, cell2, cells, cells2, padding;
			if (rows[1]){
				cells = $(rows[0]).getElementsByTagName('td');
				cells2 = rows[1].getElementsByTagName('td');
				for (var i=0;i<cells.length;i++){
					cell = $(cells[i]);
					cell2 = $(cells2[i]);
					padding = parseInt(cell.getStyle('paddingLeft'))+parseInt(cell.getStyle('paddingRight'));

					cell2.style.width = (cell.offsetWidth-padding)+'px';
					cell2.width = cell.offsetWidth-padding;
						
				}
			}
			var oThis = this;
			//setTimeout(function(){oThis.syncHdr().positionShadow()},120);
			//alert('a')
			//alert(table.getElementsByTagName('tr')[0].innerHTML+'\n\n'+table.getElementsByTagName('tr')[1].innerHTML)
			table.deleteRow(0);
			//alert(table.parentNode.innerHTML);
			//alert(table.innerHTML)
			this.searchText('reset');
			return this;
		}
	}();
	//  end of  loadData method  //
	return rpt;
}

///            Drag Drop                              ///
var dragObject;
Event.observe(window,'load',function(){
	Event.observe(document.body,'mousemove',function(ev){
		var e = ev || event;
		var mousePos = CSI.mouseCoords(ev);
		if(dragObject){
			dragObject.style.top      = (mousePos.y - mouseOffset.y)+'px';
			dragObject.style.left     = (mousePos.x - mouseOffset.x)+'px';
			//return false;
		}
	});
	Event.observe(document,'mouseup',function(ev){
		dragObject  = null;
		document.body.style.cursor = '';
	});
});



/**************************************************************/
function createMultiOptForm(optObj){
	// extended select multiple checkboxes
	optObj = optObj || {};

	var f = createForm();
	f.footer.innerHTML = '<button>Save</button>';
	Event.observe(f.footer.getElementsByTagName('button')[0],'click',function(){this.onEnterKey()}.bind(f));
	
	Event.observe(f.formBody,'click',function(e){
		var t = $(e.srcElement || e.target);
		if (t.tagName == 'DIV' && t.firstChild.click)
			t.firstChild.click();
		if (t.tagName == 'DIV' || t.tagName == 'INPUT')
			setTimeout(this.refreshSelColor,10);
	}.bindAsEventListener(f))

	f.refreshSelColor = function(){
		var divs = $A(this.formBody.getElementsByTagName('div'));
		for (var i = 0;i<divs.length;i++){
			if (divs[i].firstChild.checked)
				$(divs[i]).addClassName('sel');
			else
				$(divs[i]).removeClassName('sel');
		}
		return this;
	}.bind(f);
	
	return f;
}


function createForm(optObj){
	optObj = optObj || {};
	var box = createBox(optObj);
	box.form = box.appendChild($(document.createElement('form')));
	box.form.onsubmit = function(){return false;};
	box.hdr = box.form.appendChild($(document.createElement('div')));
	box.hdr.className = 'formHdr';
	
	if (!optObj.disableDragDrop){
		Event.observe(box.hdr,'mousedown',function(ev){
			var e = ev || event;
			var t = $(e.srcElement || e.target);
			if (t.hasClassName('fLink') || t.tagName=='IMG')
				return false;
			
			dragObject = box.parentNode;
			mouseOffset = CSI.getMouseOffset(box.parentNode, e);
			document.body.style.cursor = 'move'
		});
	}
	box.titleSpan = box.hdr.appendChild($(document.createElement('span')));
	box.titleSpan.className = 'title';
	

	box.rightMargin = 4;
	if (!optObj.insert && !optObj.disableClose){
		var i = $(document.createElement('img'));
		i.className='icon';
		i.style.right = box.rightMargin+'px';
		i.src = '/wwwroot/lib/csitools/2.0/close_small.gif';
		i.title = "Close";
		box.hdr.appendChild(i);
		box.rightMargin += (i.offsetWidth+6);
		Event.observe(i,'click',function(){this.close()}.bind(box));
	};

	box.addClassName('jsForm');
	box.formBody = box.form.appendChild($(document.createElement('div')));
	box.formBody.className = 'formBody';
	if (box.fullScreen){
		optObj.noFooter = true;

		setTimeout(function(){
			getScroll();
			box.formBody.setStyle({
				height:(windowHeight-(box.hdr.offsetHeight+2))+'px'
				,overflowY:'auto'
			})
		},150)
		box.setStyle({
			 width:windowWidth-2+'px'
		});
	}
	// keepOpen  [ checked | unchecked ]
	Object.extend(box,formMethods);
	
	if (optObj.formMethods)
		Object.extend(box,optObj.formMethods);
	
	if (!optObj.noFooter){
		box.footer = box.appendChild($(document.createElement('div')));
		if (optObj.keepOpen){
			var div = box.footer.appendChild($(document.createElement('div')));
			div.innerHTML = '<input type="checkbox" class="keepOpen" onclick="CSI.updPrefs(2,this.checked);"><span onclick="this.previousSibling.click();" style="cursor:pointer">Keep this form Open</span>';
			div.style.lineHeight = '1px'
			div.style.cssFloat = div.style.styleFloat = 'left';
			var k = box.keepOpenCkBx = div.getElementsByClassName('keepOpen')[0];
			k.setStyle({position:'relative',top:'3px'});
			if (optObj.keepOpen == 'checked'){
				box.keepOpenCkBx.checked=true;
			}
		}
		box.footer.className = 'formFooter';
		box.button = box.footer.appendChild(document.createElement('button'));
		box.button.innerHTML = 'Save';
		Event.observe(box.button,'click',function(){box.onEnterKey()});
	}
										  
	var boxCloseMethod = box.close;


	box.close = function(){
		if (this.pushed){
			popForm(true)
		}
		boxCloseMethod.call(box);
	}

	box.__insert = box.insert;
	
	Event.observe(box,'keydown',box.handleKeys.bindAsEventListener(box));
	return box;
}
formMethods = {
	done : function (){
		if (this.keepOpenCkBx){
			if (this.keepOpenCkBx.parentNode.style.visibility == 'hidden' || !this.keepOpenCkBx.checked ){
				this.close();
			}
			else {
				this.resetVals().focus();
			}
		}
		else {
			this.close();
		}
		return this;
	}
	,setTitle : function(str,styleObj) {
		menuMethods.setTitle.call(this,str,styleObj)
		return this;
		//this.titleSpan.innerHTML = str;
	}
	,resetVals : function(){
		var defaultVal, prompt, ai;
		if (!this.elms)
			this.elms = this.form.getElements();
		var a = this.elms;
		for (var i=0;i<a.length;i++){
			ai = a[i];
			if (ai.autoSuggest)
				ai.searchResults = undefined;
				
			defaultVal =  ai.getAttribute('defaultVal');
			if (ai.type == 'checkbox'){
				ai.checked = (defaultVal == 'checked') ? true : false;
			}
			else {
				ai.style.color = '';
				if (defaultVal)
					ai.value = defaultVal;
				else {
					prompt = ai.getAttribute('prompt');
					if (prompt){
						ai.value=prompt;
						ai.style.color = '#999';
					}
					else
						ai.value = '';
				}
			}
		}
		return this;
	}
	,push	:	function(){
		pushForm(this.parentNode,{opacity:.25})
		this.pushed = true;
		//this.formBody.style.width = (this.offsetWidth+2)+'px';
		if (this.fullScreen){
			this.parentNode.style.top = this.parentNode.style.left = '0px';
		}
		if (this.keepOpenCkBx) {
			this.keepOpenCkBx.checked = (window.aids && aids.indexOf(2) > -1) ? true : false;
		}
		if (this.resultsDiv){
			this.resultsDiv.parentNode.style.zIndex = parseInt(this.parentNode.style.zIndex)+2;
		}
		return this;
	}
	
	
	
	
	
	,finish : function(){
		this.elms = this.form.getElements();
		var myElms = $A(this.elms)
		myElms.push(this.getElementsByTagName('button')[0]);
		
		this.dates = [];
		var popupCalendar = false, prompt;
			
		if (this.form.getElementsByClassName('popupDate').length > 0)
			popupCalendar = true;
		
		for (var i=0;i<myElms.length;i++){
			var elm = $(myElms[i]);
			if (elm.autoSuggest){
				elm.autoSuggest.minSearchChars = elm.autoSuggest.minSearchChars || 
					((typeof(elm.autoSuggest.searchProvider) == 'string') ? 2 : 1);
				Event.observe(elm,'blur',function(){
					this.resultsDiv.close();
				}.bind(this));
				Event.observe(elm,'focus',function(elm){
					if (elm.searchResults)
						this.processMatches(elm);
				}.bind(this,elm));
				// add a resultsDiv
				if (!this.resultsDiv){
					this.resultsDiv = createBox({shadowWidth:3,shadowOpacity:50});
					this.resultsDiv.addClassName('resultsDiv');
					this.resultsDiv.parentForm = this;

					var close = this.close;
					this.close = function(){
						if (this.http && this.http.transport.readyState != 4)
							this.http.transport.abort();
						this.resultsDiv.removeHighlight();
						this.resultsDiv.close();
						close.call(this);
					}
					
					
					Object.extend(this.resultsDiv,resultsDivMethods);
					var cachedShowMethod = this.resultsDiv.show;
					
					this.resultsDiv.show = function(){
						
						this.style.overflow = this.style.height = this.style.width = '' ;
						var elm = this;
						var top = 0;
						getScroll();
						while (elm && elm != 'BODY' && elm != 'HTML'){
							top += elm.offsetTop;
							elm = elm.offsetParent;
						}
						var distanceFromTop = top - scrollTop;
						var distanceFromBottom = windowHeight - distanceFromTop;
						if (this.offsetHeight > distanceFromBottom){
							this.style.height = (distanceFromBottom-17)+'px';
							this.style.width = (this.offsetWidth + 13)+'px'
							this.style.overflow = 'auto';
							this.scrollTop = 0;
						}
				
						return cachedShowMethod.call(this);
					}.bind(this.resultsDiv);
					
					
					
					
					//var ps = this.positionShadow;
					Object.extend(this,searchMethods);
					//this.positionShadow = function(){
					//	ps.call(this);
					//}
					this.resultsDiv.moBound = this.resultsDiv.mouseover.bind(this.resultsDiv);
					Event.observe(this.resultsDiv,'mouseover',this.resultsDiv.moBound)
					
					//Event.observe(this.resultsDiv,'click',this.resultsDiv.on_click.bindAsEventListener(this.resultsDiv))
				}
			}

			if (elm.hasClassName('popupDate') || elm.getAttribute('popupDate')){
				this.dates.push(elm);
				Event.observe(elm,'focus',showCalendarControl.bind(this,elm));
				Event.observe(elm,'click',function(e){showCalendarControl(this);Event.stop(e)}.bindAsEventListener(elm));
				Event.observe(elm,'blur',validateDate.bind(this,elm));
				Event.observe(elm,'change',function(){this.validate='wait'}.bind(elm));
			}
			else {
				if (popupCalendar)
					Event.observe(elm,'focus',hideCalendarControl.bind(this,elm));
			}
			if (prompt = elm.getAttribute('prompt')){
				Event.observe(elm,'blur',function(){
					var prompt = this.getAttribute('prompt');
					if (trim(this.value) == '')
						this.value = prompt;
						
					this.style.color = (this.value==prompt) ? '#999' : '';
						
					//if (this.value == prompt)
						//this.style.color = '#999';
				}.bind(elm));
				Event.observe(elm,'focus',function(){
					var prompt = this.getAttribute('prompt');
					if (trim(this.value) == prompt){
						var oThis = this
						setTimeout(function(){oThis.select()},150);
					}
				}.bind(elm));
				Event.observe(elm,'keyup',function(){
					var prompt = this.getAttribute('prompt');
					if (trim(this.value) == prompt)
						this.style.color = '#999'
					else
						this.style.color = '';
				}.bind(elm));
				if (elm.value == ''){
					elm.value = prompt;
					elm.style.color = '#999';
				}
			}
			if (elm.getAttribute('date'))
				Event.observe(elm,'blur',validateDate.bind(this,elm));
		}
		return this;
	}

	,insert	:	function(elm){
		this.getElementsByClassName('closeImg')[0].style.display='none';
		this.close = function(){return}
		this.__insert(elm);
	}
	
	,onEnterKey		:	function(){ alert('Error!\nMissing onEnterKey callback function.');}
	
	,focus			:	function(){
		var tries = 0;
		var oThis = this;
		if (!this.elms)
			this.elms = this.form.getElements();
		var fx = function(){
			if (!oThis.elms.length){
				return;
			}
			//try {oThis.elms[0].focus()}
			try {oThis.form.focusFirstElement()}
			catch (err) {
				if (tries++ < 5)
					setTimeout(fx,50)
			};
		}
		setTimeout(fx,50);
		return this;
	}
	
	,onkeypress		:	function(e){
		var vChars;
		var ev = (e)?e:event;
		var t = $(ev.srcElement || ev.target);
		var k = ev.keyCode || ev.charCode;
		if (k==9)
			return;
			
		if (vChars = t.getAttribute('vChars'))
			vChars = vChars.split('');
		else
			return k!=13 || t.tagName == 'TEXTAREA';
		if (vChars.indexOf(String.fromCharCode(k))==-1)
			return false
	}
	,reset	: function(){this.form.reset();return this}
	,cursorPos : function (elm){
		
		var i=elm.value.length+1;
		if (elm.createTextRange){
			theCaret = document.selection.createRange().duplicate();
			elm.selectedLength = theCaret.text.length
			while ( theCaret.parentElement() == elm	&& theCaret.move("character",1)==1 ) 
				--i;
		}
		return  i-1
	}
	
	,handleKeys 	:	function(e){
		var t = $(e.srcElement || e.target);
		var k = e.keyCode;
		if (k==13){
			if (t.tagName === 'TEXTAREA')
				return;
			this.onEnterKey(e);
			Event.stop(e);
			return;
		}
		
		if(e.ctrlKey && k != 17)
			if (k == 88 || k == 86 || k==67)
				return;
		
		if (k!=9){
			var digits = t.getAttribute('digits');
			if (digits){
				var a = digits.split('.')
				digits = a[0];
				var decimal = (a.length>1) ? a[1] : 0;
			}
		}
		if (!digits && k!=9)
			return;
			
		//alert(k)
		if (k==39 || k==37 || k==46 || k==8 || k==35 || k==36) //allowed keys
			return;

		t.cursorPos = this.cursorPos(t);
		
		var ta = t.value.split('');
		var d=null;
		
		var a = t.value.split('.')
		
		for (var i=0;i<ta.length;i++){
			if (ta[i]=='.'){
				d=i;
				break;
			}
		}
		if (k!=9){
			if (digits && (a.length==1 || d >= t.cursorPos) && a[0].replace(/,/g,  '').length >= digits && k!=190 && !t.selectedLength){
				Event.stop(e)
				return
			}
			//alert(d+':'+t.cursorPos)
			if (a.length > 1 && decimal && ((d < t.cursorPos && a[1].replace(/,/g,  '').length >= decimal) || k==190)){
				Event.stop(e)
				return
			}
		
			if (!(k >= 48 && k<=57) && !(k >= 96 && k<=105))
				if (!decimal || k!=190){
					Event.stop(e)
					return
				}
		}
		if(k==9){
			var myElms = $A(this.elms)
			var buttons = this.getElementsByTagName('button');
			for (var i =0;i<buttons.length;i++)
				myElms.push(buttons[i]);
				
			if(t==myElms[0] && e.shiftKey)
				var toElm = myElms[myElms.length-1]
			else if (t==myElms[myElms.length-1] && !e.shiftKey)
				var toElm = myElms[0]

			if (toElm){
				CSI.clearSelection();
				toElm.focus();
				if (toElm.select)
					toElm.select();
				Event.stop(e);
			}
		}
	}
}
function createSearchForm(optObj){
	optObj = optObj || {}
	f = createForm(optObj);
	f.formBody.innerHTML = '<span style="display:inline;overflow:auto"><input type=text></span>'
	f.searchInput = f.formBody.getElementsByTagName('input')[0];
	var rsw = optObj.resultsShadowWidth==undefined ? 3 : optObj.resultsShadowWidth;
	var rso = optObj.resultsShadowOpacity==undefined ? 50 : optObj.resultsShadowOpacity;
	f.resultsDiv = createBox({shadowWidth:rsw,shadowOpacity:rso});
	f.resultsDiv.addClassName(optObj.resultsClassName || 'resultsDiv');
	f.resultsDiv.innerHTML = 'aaa';
	f.titleSpan.innerHTML = optObj.Title || 'Search';
	f.resultsDiv.position(f.searchInput).adjLeft(1).adjTop(1);
	f.resultsDiv.parentForm = f;
	f._sf_positionShadow = f.positionShadow;
	f._sf_close = f.close;
	f.resultsDiv._rd_show = f.resultsDiv.show;
	Object.extend(f.resultsDiv,resultsDivMethods);
	Object.extend(f,searchMethods);
	f.resultsDiv.moBound = f.resultsDiv.mouseover.bind(f.resultsDiv);
	Event.observe(f.resultsDiv,'mouseover',f.resultsDiv.moBound)
	
	Event.observe(f.resultsDiv,'click',f.resultsDiv.on_click.bindAsEventListener(f.resultsDiv))

	Event.observe(f.searchInput,'click',function(){
		if (this.searchResults && this.searchResults.length > 0){
			//$('ta').value += 'settimeout;';
			setTimeout(this.resultsDiv.show.bind(this.resultsDiv),25);
		}
	}.bind(f));
	return f;
}





searchMethods = {
	onclick : function(ev){
		e = ev || event;
		t = $(e.srcElement || e.target);
		if (t.autoSuggest && t.searchResults)
			this.processMatches(t);
	}

	,onkeydown: function(ev){
		var e = ev || event;
		if (e.keyCode == 38){	// up arrow
			if (this.resultsDiv.highlighted)
				this.move($(this.resultsDiv.highlighted.previousSibling))
			Event.stop(e);
		}else if (e.keyCode == 40){ 	// down arrow
			if (this.resultsDiv.highlighted)
				this.move($(this.resultsDiv.highlighted.nextSibling))
			Event.stop(e);
		}else if (e.keyCode == 27) {   // esc
			this.resultsDiv.close();
			this.resultsDiv.removeHighlight();
			Event.stop(e);
		}
	}
	,getSearchInput : function(e){
		var t = $(e.srcElement || e.target);
		if (!t.autoSuggest)
			return null;
		return t;
	}
	,onkeyup	: function(ev){
		e = ev || event;
		var searchInput = this.getSearchInput(e);
		if (!searchInput)
			return;
			
		if (searchInput.savedValue && trim(searchInput.savedValue) == trim(searchInput.value))
			return;
		searchInput.savedValue = searchInput.value
		if (searchInput.timeoutId){
			clearTimeout(searchInput.timeoutId);
			searchInput.timeoutId = null;
		}
		var oThis = this;
		if (e.keyCode == 8 || e.keyCode == 32 || (e.keyCode >= 46 && e.keyCode <= 111) || e.keyCode >123){
			if (this.resultsDiv.hasClassName('msg'))
				this.resultsDiv.close();
				
			this.resultsDiv.removeHighlight();
			searchInput.searchResults = null;
			if (searchInput.value.strip().length >= searchInput.autoSuggest.minSearchChars){
				if (typeof(searchInput.autoSuggest.searchProvider) == 'function'){
					searchInput.searchResults = searchInput.autoSuggest.searchProvider();
					this.processMatches(searchInput);
				}
				else if (typeof(searchInput.autoSuggest.searchProvider) == 'string')
					this.timeoutId = setTimeout(function(){
						oThis.search(searchInput);},225);

				if (this.http){
					if (this.http.transport.readyState != 4)
						this.http.transport.abort();
					this.http.transport.readyState == 5;
				}
			}
			else {
				this.resultsDiv.close();
				this.searchResults = null;
			}
		}
					
	}
	,search	: function(searchInput){
		if (this.http){
			this.http.transport.abort();
		}
		var parms = {data:searchInput.value};
		if (this.parameters)
			Object.extend(parms,this.parameters);
			
		this.http = new Ajax.Request(searchInput.autoSuggest.searchProvider+'?data='+this.searchInput.value,{
			parameters:parms
			,method:'post'
			,onSuccess:function(t){eval(t.responseText)}.bind(this)
		})
		this.timeoutId = null;
	}
	,noMatches:function(){
		var rd = this.resultsDiv;
		rd.innerHTML = 'No Matches';
		rd.removeHighlight();
		rd.addClassName('msg').show()
	}
	,highlight : function(i){
		var trs = this.resultsDiv.getElementsByTagName('tr')
		//if (!trs || !trs.length)
		//	return;
		this.resultsDiv.removeHighlight();
		$(trs[i]).addClassName('highlight');
		this.resultsDiv.highlighted = trs[i];
	}
	,move : function(elm){
		if (elm){
			var rd = this.resultsDiv;
			var h = this.resultsDiv.highlighted;
			if (h) 
				h.removeClassName('highlight')
			elm.addClassName('highlight')
			rd.highlighted = elm;
			var table = rd.firstChild;
			if (table.offsetHeight > rd.offsetHeight){
				if (elm.offsetTop+elm.offsetHeight > rd.offsetHeight+rd.scrollTop){
					Event.stopObserving(rd,'mouseover',rd.moBound);
					rd.scrollTop += elm.offsetHeight;
					rd.timeoutId = setTimeout(function(){Event.observe(rd,'mouseover',rd.moBound)},25)
				}
				else
				if (elm.offsetTop < rd.scrollTop){
					Event.stopObserving(this.resultsDiv,'mouseover',this.resultsDiv.moBound)
					rd.scrollTop -= elm.offsetHeight;
					rd.timeoutId = setTimeout(function(){Event.observe(rd,'mouseover',rd.moBound)},25)
				}
			}
		}
	}
	,onEnterKey : function(ev){
		e = ev || event;
		var searchInput = this.getSearchInput(e);
		if (!searchInput)
			return;

		var tries = 0;
		var oThis = this;
		var rd = this.resultsDiv;
		
		if (!rd.highlighted)
			return;
			
		// waitForAjax is only needed if search Provider is an ajax program.  this handles the situation where the user hit 
		// enter before the ajax program displayed.  wait for the response, then select the first result from searchResults;
		if (typeof(searchInput.autoSuggest.searchProvider)=='string'){
			var waitForAjax = function(){
				if (tries++ > 100){
					alert('timed out');
					return;
				}
				if (!oThis.timeoutId && !oThis.http)
					return;
			
				if (oThis.timeoutId || oThis.http.transport.readyState != 4 || oThis.resultsDiv.style.visibility=='hidden'){   // pending Ajax request
					setTimeout(fx,50)
					return;
				}
	
				if ((searchInput.value.length < searchInput.autoSuggest.minSearchChars)
				&& (rd.parentNode.visibility == 'hidden' || rd.hasClassName('msg'))){
					alert('Please enter at least \n'+searchInput.autoSuggest.minSearchChars+' characters to search.')
					return;
				}
				
				if (rd.hasClassName('msg')){
					return;
				}
				
				if (searchInput.autoSuggest.onSelect && rd.highlighted){
					searchInput.autoSuggest.onSelect.call(searchInput,e,rd.highlighted.getAttribute('i'));
					window.clearTimeout(rd.showTimeout)
					setTimeout(function(){rd.close()},25);
				}
			};
			waitForAjax();
			return;
		}
		searchInput.autoSuggest.onSelect.call(searchInput,e,rd.highlighted.getAttribute('i'))
		rd.close();
	}
	,ondblclick : function(){
		if (this.searchResults){
			this.resultsDiv.show();
		}
	}
	,createCells : function(i){  // this function should normally be overwritten
		return '<td>tim is great</td>';
	}
	,processMatches : function(searchInput){
		var sr = searchInput.searchResults;
		var rd = this.resultsDiv;
		if (!sr || !sr.length){
			if (searchInput.autoSuggest.onNoResults)
				searchInput.autoSuggest.onNoResults.call(searchInput);
			else
				rd.close();
			return;
		}
				
		rd.removeClassName('msg')
		var a = ['<table cellspacing=0 cellpadding=0>'];
		for (var i = 0;i<sr.length;i++){
			a.push('<tr i="'+i+'"')
			if (!(i%2))
				a.push(' class="odd"');
			a.push('>'+searchInput.autoSuggest.resultsFilter(sr[i])+'</tr>')
		}
		a.push('</table>');
		rd.innerHTML = a.join('');
		rd.style.width = '';
		var w = rd.offsetWidth;
		var sIw = searchInput.offsetWidth;
		if (w < sIw)
			$(rd.getElementsByTagName('table')[0]).setStyle({width:(sIw-5)+'px'})
		
		rd.onSelect = searchInput.autoSuggest.onSelect.bind(searchInput) || function(){};
		rd.position(searchInput).show();
		this.highlight(0);
	}
}
resultsDivMethods = {
	mouseover : function(ev){
		var e = ev || event;
		t = $(e.srcElement || e.target);
		if (t.tagName == 'TD'){
			var tr = t.parentNode;
			if (tr == this.highlighted)
				return;
			if (this.highlighted)
				this.highlighted.removeClassName('highlight');
			$(tr).addClassName('highlight');
			this.highlighted = tr;
		}
	}
	,removeHighlight : function(){
		if (this.highlighted){
			this.highlighted.removeClassName('highlight');
			this.highlighted = null;
		}
	}
	,onclick : function(e){
		var ev = e || event;
		var t = $(ev.srcElement || ev.target);
		if (this.onSelect && this.highlighted){
			this.onSelect(e,this.highlighted.getAttribute('i'));
		}
	}
}
/*
							End of jsform.js
							
							
							
							
							
							
							
							
							
							
							
							
							
							
							
							Start of pushform.js
*/
pushformVPath = "/wwwroot/lib/csitools/2.0/";
var d = new Date().getTime();
document.write('<iframe name="timiscool" id="testFrame" style="display:none" src="'+pushformVPath+'pushform.html?'+d+'"></iframe>')
//

overlayArray=[];

Event.observe(window,'load',function(){
	Event.observe(document,'keyup',function(e){
		if (e.keyCode == 27){
			if(overlayArray.currentPage >= 0){
				history.go(-1);
				insertDivReg();// calling insert DivReg with no div parameter, will result in all divs being flushed;
			}
		}
	}.bindAsEventListener(this))
})

initScript = '<script>alert(37);par=window.parent;'+
	'if(par.overlay)'+
	'	par.cleanupOverlay(-1);'+
	'if (par.overlayArray && par.overlayArray.reInit){'+
	'	par.overlayArray.reInit()'+
	'}</script>'
	
overlayArray.truncate = function(index){
	for (var i=index;i<overlayArray.length;i++)
		overlayArray.close(i)
}


function pushForm(div, optionsObj){
	optionsObj = optionsObj || {};
	var last=prev=0; 

	truncateOverlayArray();

	getScroll();
	/*if (window.pageYOffset)	{
		  var scrollTop = window.pageYOffset
		  var scrollLeft = window.pageXOffset
	}
	else if (document.documentElement && document.documentElement.scrollTop)	{
		var scrollTop = document.documentElement.scrollTop
		var scrollLeft = document.documentElement.scrollLeft
	}
	else if (document.body){
		  var scrollTop = document.body.scrollTop
		  var scrollLeft = document.body.scrollLeft
	}
	
	if (window.innerHeight){
		var windowHeight = window.innerHeight
		var windowWidth = window.innerWidth
	}
	else if (document.documentElement && document.documentElement.clientHeight)	{
		var windowHeight = document.documentElement.clientHeight
		var windowWidth = document.documentElement.clientWidth
	}
	else if (document.body)	{
		var windowHeight = document.body.clientHeight;
		var windowWidth = document.body.clientWidth;
	}*/
	if (overlayArray.length==0)
		var currentZ = 0;
	else {
		var x = overlayArray.length-1;
		while (overlayArray[x] && !overlayArray[x].style && x > 0)
			x--;
		if (overlayArray[x] && overlayArray[x].style)
			var currentZ = parseInt(overlayArray[x].style.zIndex)
		else
			var currentZ = 0;
	}
	
	if (!window.overlay){
		overlay = document.createElement('div');
		overlay.id = 'overlay';
		overlay.onclick='event.cancelBubble=true';
		overlay.style.position='absolute';
		overlay.style.top='0';
		overlay.style.left='0';
		overlay.style.display='none';
		overlay.style.opacity='.5';
		overlay.style.filter='Alpha(Opacity=50)';
		overlay.style.backgroundColor='black';
		document.body.appendChild(overlay); 
	}
	if (optionsObj.opacity){
		overlay.style.opacity=optionsObj.opacity;
		overlay.style.filter='Alpha(Opacity='+optionsObj.opacity*100+')';
	}
	if (optionsObj.color){
		overlay.style.backgroundColor=optionsObj.color;
	}
	overlay.style.height = Math.max(windowHeight, document.body.scrollHeight)+'px';
	overlay.style.width = Math.max(windowWidth, document.body.scrollWidth)+'px';
	
	last = overlayArray.length
	overlayArray[last]= div;
	
	//alert(last);
	
	div.screenTop = div.saveScreenTop = scrollTop;

	overlayArray.currentPage = last;
	
	div.style.zIndex = currentZ+20;
	
	var divTop = Math.max(scrollTop, Math.round(scrollTop+((windowHeight-div.clientHeight)/2)))
	var divLeft = Math.round(scrollLeft+((windowWidth-div.clientWidth)/2))
	
	div.style.top = Math.max(divTop,0)+'px'
	div.style.left = Math.max(divLeft,0)+'px'

	var newZ = currentZ+10;
	//div.boundHandler = lockWindow.bindAsEventListener(div);
	//writeScript(initScript)
	writeScript(createDivJs(last,newZ));
}

CSI.fixRefresh = function(idx){
	if (!overlayArray.reachedStart){
		overlayArray.close(idx);
		history.back();
	}
}
function createDivJs(x,newZ){
	var a=['<script>;'
	,'	var par=window.parent;'
	,'	var fe, back;'
	,'	var me = '+x+';'
	,'  if (me < par.overlayArray.currentPage) {back = true; };'
	,'	if (par.userClickedRefresh){'
	,'		par.CSI.fixRefresh(me);'
	,'	}else {'
	,'		if(par.overlayArray[me]=="end"){	'
	,'			history.back();	'
	,'		}else if(par.overlayArray[me]=="closed"){	'
	,'			if (back)	{ 	'
	,'				history.back();} '
	,'			else {	'
	,'				history.forward(); }'
	,'		}else if (!par.overlayArray[me]){		'
	,'			par.overlayArray.close(me);	'
	//,'			//par.userClickedRefresh = true;	'
	,'			history.back();	'
	,'		}else{			'
	,'			par.overlay.style.display="";'
	,'			par.overlay.style.zIndex='+newZ+'; '
	,'			par.overlayArray[me].style.visibility="visible";'
	,'			if(par.overlayArray[me].firstChild.focus) par.overlayArray[me].firstChild.focus();'
	,'			par.cleanupOverlay(me);'
	,'		}	'
	,'	}'
	,'</script>'];
	
	return a.join('\n');
}
function createFxJs(x){
	var a=['<script>'
	,'	par=window.parent;'
	,'	var me = '+x+';'
	,'	par.cleanupOverlay(me);'
	,'	if (par.overlayArray.length-1 > me && par.overlayArray[me+1].style && par.overlay.style.display==""){ '
	,'		par.overlay.style.display="none";'
	,'		par.overlayArray[me+1].style.visibility="hidden";'
	,'	}else if (par.overlayArray[me] == "closed"){	'
	,'		par.overlayArray.close(me);	'
	,'		history.go(-1);	'
	,'	}else if (par.overlayArray[me] == "closed"){	'
	,'		par.overlayArray.close(me);	'
	,'		history.forward();	'
	,'	}else if (par.overlayArray.length-1 >= me){ '
	,'		par.overlayArray[me]();'
	,'	};	'
	,'</script>']
	return a.join('');
}

function truncateOverlayArray(){
	if (window.overlayArray && overlayArray.currentPage < overlayArray.length-1){
		overlayArray.splice(overlayArray.currentPage+1,999)
	}
}




function pushF(fx){
	truncateOverlayArray();
	var x = overlayArray.length;
	overlayArray[x]= fx;
	overlayArray.currentPage = x;
	writeScript(createFxJs(x))
}

function writeScript(historyScript){
	if (!window.sessionFrame){
		sessionFrame = $('testFrame');
	}	
	
	var doc = sessionFrame.contentWindow.document;
	if (sessionFrame.contentDocument){
		sessionFrame.src= pushformVPath+'echo.php?data='+historyScript;
	}
	else {
		doc.open();
		doc.write(historyScript)
		doc.close();
	}
}

function popForm(destroy){
	if (destroy){
		overlayArray.close(overlayArray.currentPage);
	}
	history.back();
}

overlayArray.close = function(i){
	turnItOff(i);
	this[i] = 'closed';
}


function turnItOff(ixx){
	var item = overlayArray[ixx];
	
	if (!item)
		return;
	if (item.saveScreenTop)
		scroll(0,item.saveScreenTop);
		
	if (item.style)
		item.style.visibility="hidden";

}

function cleanupOverlay(current){
	overlayArray.currentPage = current;
	if (current == -1){
		turnItOff(0);
		return;
	} 
	
	for (var i = 0;i<overlayArray.length;i++){
		//Event.stopObserving(document.body,'scroll',overlayArray[i].boundHandler)
		//Event.stopObserving(window,'scroll',overlayArray[i].boundHandler)
		
		if (i>current){
			if (overlayArray[i].style){
				overlayArray[i].style.visibility="hidden";
			}
		}
		else if (i==current){
			//alert(i+':'+overlayArray.length)
			if (i+1 < overlayArray.length && overlayArray[i+1].saveScreenTop)
				scroll(0,overlayArray[i+1].saveScreenTop)
			//if (window.parent.isFunction(overlayArray[i].boundHandler)){
			//	Event.observe(document.body,'scroll',overlayArray[i].boundHandler)
			//	Event.observe(window,'scroll',overlayArray[i].boundHandler)
			//}
		}
	}
}

/*
function lockWindow(div){
	if (window.pageYOffset)	{
		  var scrollTop = window.pageYOffset
	}
	else if (document.documentElement && document.documentElement.scrollTop)	{
		var scrollTop = document.documentElement.scrollTop
	}
	else if (document.body)	{
		  var scrollTop = document.body.scrollTop
	}
	
	if (window.innerHeight)	{
		var clientHeight = window.innerHeight-16
	}
	else if (document.documentElement && document.documentElement.clientHeight)	{
		var clientHeight = document.documentElement.clientHeight
	}
	else if (document.body)	{
		var clientHeight = document.body.clientHeight
	}
	
	
	if (clientHeight >= this.offsetHeight){
		//alert(this.clientHeight);
		//alert(clientHeight+':'+this.clientHeight);
		if (scrollTop < this.screenTop){
			if (this.offsetTop+this.offsetHeight > scrollTop+clientHeight){
				scroll(0,this.offsetTop+this.offsetHeight-clientHeight)
				this.screenTop = this.offsetTop+this.offsetHeight-clientHeight
			}
		}
		if (scrollTop > this.screenTop){
			if (scrollTop > this.offsetTop){
				//alert(scrollTop+':'+this.screenTop+':'+this.offsetTop);
				scroll(0,this.offsetTop)
				this.screenTop = this.offsetTop
			}
		}
	}
	else {
		if (scrollTop < this.screenTop){
			if (this.offsetTop > scrollTop){
				scroll(0,this.offsetTop)
				this.screenTop = this.offsetTop
			}
		}
		if (scrollTop > this.screenTop){
			if (this.offsetTop+this.offsetHeight < scrollTop+clientHeight){
				scroll(0,this.offsetTop+this.offsetHeight-clientHeight)
				this.screenTop = this.offsetTop+this.offsetHeight-clientHeight
			}
		}
	}
}
*/



/*
							End of pushform.js
							
							
							
							
							
							
							
							
							
							
							
							
							
							
							
							
							Start of Calendar Control.js
*/
CSSRule('#CalendarControlIFrame', {display:'none',left: '0px', position: 'absolute',top: '0px', height: '250px',width: '250px',zIindex: 99});
CSSRule('#CalendarControl',{position:'absolute',backgroundColor:'#FFF',margin:0,padding:0,display:'none',zIndex: 100});
CSSRule('#CalendarControl table',{fontFamily:'arial, verdana, helvetica, sans-serif',fontSize:'8pt',borderLeft:'1px solid #336',borderRight:'1px solid #336'});
CSSRule('#CalendarControl th',{fontWeight:'normal'});
CSSRule('#CalendarControl th a',{fontWeight:'normal',textDecoration:'none',color:'#FFF',padding:'1px'});
CSSRule('#CalendarControl td',{textAlign:'center'});
CSSRule('#CalendarControl .header',{backgroundColor:'#336'});
CSSRule('#CalendarControl .weekday',{backgroundColor:'#DDD',color:'#000'});
CSSRule('#CalendarControl .weekend',{backgroundColor:'#FFC',color:'#000'});
CSSRule('#CalendarControl .current',{border:'1px solid #339',backgroundColor:'#336',color:'#FFF'});

var tObj = {display:'block',textDecoration:'none',border:'1px solid #FFF',width:'2em'}
CSSRule('#CalendarControl .current',tObj);
CSSRule('#CalendarControl .weekday',tObj);
CSSRule('#CalendarControl .weekend',tObj);

tObj = {border:'1px solid #999',backgroundColor:'#336',color:'#fff'};
CSSRule('#CalendarControl .weekday:hover',tObj);
CSSRule('#CalendarControl .weekend:hover',tObj);
CSSRule('#CalendarControl .current:hover',tObj);

CSSRule('#CalendarControl .previous', {textAlign:'left',padding:'1px 3px 1px 3px',fontSize:'1.4em'});
CSSRule('#CalendarControl .next',{textAlign:'right',padding:'1px 3px 1px 3px',fontSize:'1.4em'});

tObj = {color:'#fff',textDecoration:'none',fontWeight:'bold'};

CSSRule('#CalendarControl .previous a',tObj);
CSSRule('#CalendarControl .next a',tObj);

CSSRule('#CalendarControl .title', {textAlign: 'center',fontWeight: 'bold',color: '#FFF'});

CSSRule('#CalendarControl .empty',{backgroundColor: '#CCC',border: '1px solid #FFF'});

//document.write('<style>@import "/lib/csitools/2.0/calendarcontrol.css";</style>');
Event.observe(window,'load',function(){
	Event.observe(document.body,'click',function(){
		hideCalendarControl()
	})
})

function positionInfo(object) {
  var p_elm = object;

  this.getElementLeft = getElementLeft;
  function getElementLeft() {
    var x = 0;
    var elm;
    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    while (elm != null) {
      x+= elm.offsetLeft;
      elm = elm.offsetParent;
    }
    return parseInt(x);
  }

  this.getElementWidth = getElementWidth;
  function getElementWidth(){
    var elm;
    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    return parseInt(elm.offsetWidth);
  }

  this.getElementRight = getElementRight;
  function getElementRight(){
    return getElementLeft(p_elm) + getElementWidth(p_elm);
  }

  this.getElementTop = getElementTop;
  function getElementTop() {
    var y = 0;
    var elm;
    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    while (elm != null) {
		//alert(elm.tagName+':'+elm.offsetTop)
      y+= elm.offsetTop;
      elm = elm.offsetParent;
    }

	if ((y - document.body.scrollTop) > (document.body.clientHeight/2))
		y = y - (calendar.clientHeight + getElementHeight());
	
    return parseInt(y);
  }

  this.getElementHeight = getElementHeight;
  function getElementHeight(){
    var elm;
    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    return parseInt(elm.offsetHeight);
  }

  this.getElementBottom = getElementBottom;
  function getElementBottom(){
    return getElementTop(p_elm) + getElementHeight(p_elm);
  }
}

function CalendarControl() {

  var calendarId = 'CalendarControl';
  var currentYear = 0;
  var currentMonth = 0;
  var currentDay = 0;

  var selectedYear = 0;
  var selectedMonth = 0;
  var selectedDay = 0;

  var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  var dateField = null;

  /*function getProperty(p_property){
    var p_elm = calendarId;
    var elm = null;

    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    if (elm != null){
      if(elm.style){
        elm = elm.style;
        if(elm[p_property]){
          return elm[p_property];
        } else {
          return null;
        }
      } else {
        return null;
      }
    }
  }*/

  function setElementProperty(p_property, p_value, p_elmId){
    var p_elm = p_elmId;
    var elm = null;

    if(typeof(p_elm) == "object"){
      elm = p_elm;
    } else {
      elm = document.getElementById(p_elm);
    }
    if((elm != null) && (elm.style != null)){
      elm = elm.style;
      elm[ p_property ] = p_value;
    }
  }

  function setProperty(p_property, p_value) {
    setElementProperty(p_property, p_value, calendarId);
  }

  function getDaysInMonth(year, month) {
    return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
  }

  function getDayOfWeek(year, month, day) {
    var date = new Date(year,month-1,day)
    return date.getDay();
  }

  this.clearDate = clearDate;
  function clearDate() {
    dateField.value = '';
    hide();
  }

  this.setFocus = setFocus;
  function setFocus() {
    dateField.focus();
  }

  this.setDate = setDate;
  function setDate(year, month, day) {
    if (dateField) {
      if (month < 10) {month = "0" + month;}
      if (day < 10) {day = "0" + day;}

      var dateString = month+"/"+day+"/"+year;
      dateField.value = dateString;
      setTimeout(hide,25);
    }
    return;
  }

  this.changeMonth = changeMonth;
  function changeMonth(change) {
    currentMonth += change;
    currentDay = 0;
    if(currentMonth > 12) {
      currentMonth = 1;
      currentYear++;
    } else if(currentMonth < 1) {
      currentMonth = 12;
      currentYear--;
    }

    calendar = document.getElementById(calendarId);
    calendar.innerHTML = calendarDrawTable();
  }

  this.changeYear = changeYear;
  function changeYear(change) {
    currentYear += change;
    currentDay = 0;
    calendar = document.getElementById(calendarId);
    calendar.innerHTML = calendarDrawTable();
  }

  function getCurrentYear() {
    var year = new Date().getYear();
    if(year < 1900) year += 1900;
    return year;
  }

  function getCurrentMonth() {
    return new Date().getMonth() + 1;
  } 

  function getCurrentDay() {
    return new Date().getDate();
  }

  function calendarDrawTable() {
	//alert(calendar.required)
    var dayOfMonth = 1;
    var validDay = 0;
    var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
    var daysInMonth = getDaysInMonth(currentYear, currentMonth);
    var css_class = null; //CSS class for each day

    var table = "<table cellspacing='0' cellpadding='0' border='0'>";
    table = table + "<tr class='header'>";

    table += " <td colspan='2' class='previous'>"
	if (notbefore && currentMonth <= notbefore.getMonth()+1 && currentYear <= notbefore.getFullYear())
		table += "<a style='color:#999999'>&lt;</a>"
	else
		table += "<a href='javascript://' onclick='changeCalendarControlMonth(-1);' onDblClick='changeCalendarControlMonth(-1);' ;'>&lt;</a>" //href='javascript:changeCalendarControlMonth(-1)
		
	if (notbefore && (((currentYear - 1) < notbefore.getFullYear()) || ((currentYear - 1) == notbefore.getFullYear() && currentMonth < notbefore.getMonth()+1)))
		table += "<a  style='color:#999999'>&laquo;</a></td>";
	else
		table += "<a href='javascript:changeCalendarControlYear(-1);'>&laquo;</a></td>";

    table += "<td colspan='3' class='title'>" + months[currentMonth-1] + "<br>" + currentYear + "</td>";
	table += "<td colspan='2' class='next'>"
	
	//if (notafter)
		//alert(notafter)
		
	if (notafter && (((currentYear + 1) > notafter.getFullYear()) || ((currentYear + 1) == notafter.getFullYear() && currentMonth > notafter.getMonth()+1)))
	    table = table + "<a style='color:#999999' >&raquo;</a>";
	else
	    table = table + "<a href='javascript:changeCalendarControlYear(1);'>&raquo;</a>";

	if (notafter && (currentMonth >= notafter.getMonth()+1 && currentYear >= notafter.getFullYear()))
		table = table + "  <a style='color:#999999' >&gt;</a></td>";
	else
		table = table + "  <a href='javascript:changeCalendarControlMonth(1);'>&gt;</a></td>";

    table = table + "</tr>";
    table = table + "<tr><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>";

    for(var week=0; week < 6; week++) {
      table = table + "<tr>";
      for(var dayOfWeek=0; dayOfWeek < 7; dayOfWeek++) {
		if(week == 0 && startDayOfWeek == dayOfWeek) {
			validDay = 1;
		} else if (validDay == 1 && dayOfMonth > daysInMonth) {
			validDay = 0;
		}

		if(validDay) {
			if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
				css_class = 'current';
			} else if (dayOfWeek == 0 || dayOfWeek == 6) {
				css_class = 'weekend';
			} else {
				css_class = 'weekday';
			}
			if (notafter && ((currentYear == notafter.getFullYear() && currentMonth == notafter.getMonth()+1 && dayOfMonth > notafter.getDate()))
			|| (notbefore && (currentYear == notbefore.getFullYear() && currentMonth == notbefore.getMonth()+1 && dayOfMonth < notbefore.getDate())))
				table = table + "<td><a class='"+css_class+"' style='color:#999999' >"+dayOfMonth+"</a></td>";
			else
				table = table + "<td><a class='"+css_class+"' href=\"javascript:setCalendarControlDate("+currentYear+","+currentMonth+","+dayOfMonth+")\">"+dayOfMonth+"</a></td>";
			dayOfMonth++;
		} else {
			table = table + "<td class='empty'>&nbsp;</td>";
        }
      }
      table = table + "</tr>";
	}
	if (!dateRequired)
	    table = table + "<tr class='header'><th colspan='7' style='padding: 3px;'><a href='javascript:clearCalendarControl();'>Clear</a> | <a href='javascript:hideCalendarControl();'>Close</a></td></tr>";
	else
	    table = table + "<tr class='header'><th colspan='7' style='padding: 3px;'><a href='javascript:hideCalendarControl();'>Close</a></td></tr>";
    table = table + "</table>";

    return table;
  }

  this.show = show;
  function show(field) {
    can_hide = 0;
	if (field.required)
		dateRequired = true
	else
		dateRequired = false
		
	initAfterBefore(field);

	if (dateField == field) {
		return;
	} 
	else {
		dateField = field;
	}

    if(dateField) {
      try {
        var dateString = new String(dateField.value);
        var dateParts = dateString.split("/");
        
        selectedMonth = parseInt(dateParts[0],10);
        selectedDay = parseInt(dateParts[1],10);
        selectedYear = parseInt(dateParts[2],10);
      } catch(e) {}
    }
	if (selectedYear < 80)
		selectedYear += 2000;
	else if (selectedYear < 100)
		selectedYear += 1900;
	else if (selectedYear < 2099 && selectedYear > 1899)
		;
	else 
		selectedYear = null;
		
    if (!(selectedYear && selectedMonth && selectedDay)) {
      selectedMonth = getCurrentMonth();
      selectedDay = getCurrentDay();
      selectedYear = getCurrentYear();
    }

    currentMonth = selectedMonth;
    currentDay = selectedDay;
    currentYear = selectedYear;

	if (notafter){
		if (currentYear > notafter.getFullYear() || (currentYear == notafter.getFullYear() && currentMonth > notafter.getMonth()+1) || (currentYear == notafter.getFullYear() && currentMonth == notafter.getMonth()+1 && currentDay > notafter.getDate())){
		    currentMonth = notafter.getMonth()+1;
		    currentDay = notafter.getDate();
		    currentYear = notafter.getFullYear();
		}
		if (selectedYear > notafter.getFullYear() || (selectedYear == notafter.getFullYear() && selectedMonth > notafter.getMonth()+1) || (selectedYear == notafter.getFullYear() && selectedMonth == notafter.getMonth()+1 && selectedDay > notafter.getDate())){
		    selectedMonth = notafter.getMonth()+1;
		    selectedDay = notafter.getDate();
		    selectedYear = notafter.getFullYear();
		}
	}
	
	if (notbefore){
		if (currentYear < notbefore.getFullYear() || (currentYear == notbefore.getFullYear() && currentMonth < notbefore.getMonth()+1) || (currentYear == notbefore.getFullYear() && currentMonth == notbefore.getMonth()+1 && currentDay < notbefore.getDate())){
		    currentMonth = notbefore.getMonth()+1;
		    currentDay = notbefore.getDate();
		    currentYear = notbefore.getFullYear();
		}
		if (selectedYear < notbefore.getFullYear() || (selectedYear == notbefore.getFullYear() && selectedMonth < notbefore.getMonth()+1) || (selectedYear == notbefore.getFullYear() && selectedMonth == notbefore.getMonth()+1 && selectedDay < notbefore.getDate())){
		    selectedMonth = notbefore.getMonth()+1;
		    selectedDay = notbefore.getDate();
		    selectedYear = notbefore.getFullYear();
		}
	}
	

    if(document.getElementById){
		calendar = document.getElementById(calendarId);
		calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);
		setProperty('display', 'block');
		
		if (dateField.calendarPositionParent)
			var fieldPos = new positionInfo(dateField.parentNode);
		else
			var fieldPos = new positionInfo(dateField);
			
		var calendarPos = new positionInfo(calendarId);
		
		var x = fieldPos.getElementLeft();
		var y = fieldPos.getElementBottom();
		
		setProperty('left', x + "px");
		setProperty('top', y + "px");
 
      if (document.all) {
        setElementProperty('display', 'block', 'CalendarControlIFrame');
        setElementProperty('left', x + "px", 'CalendarControlIFrame');
        setElementProperty('top', y + "px", 'CalendarControlIFrame');
        setElementProperty('width', calendarPos.getElementWidth() + "px", 'CalendarControlIFrame');
        setElementProperty('height', calendarPos.getElementHeight() + "px", 'CalendarControlIFrame');
      }
    }
  }

  this.hide = hide;
  function hide() {
    if(dateField) {
      setProperty('display', 'none');
      setElementProperty('display', 'none', 'CalendarControlIFrame');
      dateField = null;
    }
  }

  this.visible = visible;
  function visible() {
    return dateField
  }

  this.can_hide = can_hide;
  var can_hide = 0;
}
var calendarControl = new CalendarControl();

function initAfterBefore(field){
	notafter = new Date();
	notbefore = new Date();

	notafter.setFullYear(2079,11,31)
	notafter.setHours(23,59,59,999)

	notbefore.setFullYear(1900,0,1)
	notbefore.setHours(0,0,0,0)

	if (field.notafter = field.getAttribute('notafter')){
		if (document.getElementById(field.notafter)){
			myObj = document.getElementById(field.notafter)
			var dateString = trim(myObj.value)
			if (dateString == '' && myObj.notafter)
				if (!document.getElementById(myObj.notafter))
					dateString = myObj.notafter
		}
		else
			var dateString = field.notafter;
		if (dateString > ' '){
	        var dateParts = dateString.split("/");
			myYear = parseInt(dateParts[2],10);
			if (myYear < 80)
				myYear += 2000;
			else if (myYear < 100)
				myYear += 1900;
			notafter.setFullYear(myYear,parseInt(dateParts[0]-1,10),parseInt(dateParts[1],10))
		}
	}
	
	if (field.notbefore = field.getAttribute('notbefore')){
		if (document.getElementById(field.notbefore))
			var dateString = document.getElementById(field.notbefore).value
		else
			var dateString = field.notbefore;
		if (dateString > ' '){
	        var dateParts = dateString.split("/");
			myYear = parseInt(dateParts[2],10);
			if (myYear < 80)
				myYear += 2000;
			else if (myYear < 100)
				myYear += 1900;
			notbefore.setFullYear(myYear,parseInt(dateParts[0]-1,10),parseInt(dateParts[1],10))
		}
	}
}

function showCalendarControl(textField) {
	calendarControl.show(textField);
}

function clearCalendarControl() {
	myobj = calendarControl.visible();
	calendarControl.clearDate();
	myobj.focus();
	if (myObj.fireEvent)
		myobj.fireEvent("onchange");
}

function hideCalendarControl() {
  if (calendarControl.visible()) {
    calendarControl.hide();
  }
}
function cancelTimeOuts() {
	if (window.myVtimeoutholder) {
		window.clearTimeout(myVtimeoutholder)
	}
}

function setCalendarControlDate(year, month, day) {
	//window.cancelBubble = true;
	var mystring = year + '';
	//year = mystring.substr(2,2)
	myobj = calendarControl.visible();
	myobj.focus();
	calendarControl.setDate(year, month, day);
	if (myobj.fireEvent)
		myobj.fireEvent("onchange");
}

function changeCalendarControlYear(change) {
	if (window.myVtimeoutholder)
		window.clearTimeout(myVtimeoutholder)
	calendarControl.changeYear(change);
	calendarControl.setFocus();
}


function changeCalendarControlMonth(change) {
	if (window.myVtimeoutholder)
		window.clearTimeout(myVtimeoutholder)
	calendarControl.changeMonth(change);
	calendarControl.setFocus();
}

function parseDate(dateString){
	var myDate = new Date();
    var dateParts = dateString.split("/");
	var myYear = parseInt(dateParts[2],10);
	if (myYear < 80)
		myYear += 2000;
	else if (myYear < 100)
		myYear += 1900;
	myDate.setFullYear(myYear,parseInt(dateParts[0]-1,10),parseInt(dateParts[1],10))
	return(myDate);
	
}
function validateDate(fld) {
	if (window.myVtimeoutholder)
		window.clearTimeout(myVtimeoutholder)
	
	if (validateDate.arguments.length > 0){
		gfld = fld;
		myVtimeoutholder = setTimeout("validateDate()",150);
		return;
	}

	if (gfld.style.visibility == 'hidden' || gfld.parentNode.style.visibility == 'hidden'  )
	 	return;
		
	var fld = gfld;

	var prompt = fld.getAttribute('prompt');
	if (prompt && fld.value == prompt)
		var testValue = '';
	else
		var testValue = fld.value;
		


	initAfterBefore(fld);
	
	fld.style.backgroundColor = '';
    var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    var errorMessage = 'Please enter valid date as month, day, and two digit year.\nFormat is mm/dd/yy.\nOr select a valid date from the Calendar.';
	var required = false;
	
	if (fld.required)
		required = true;

	var t = fld;
	while (t.getStyle('visibility')==='inherit'){
		t = $(t.parentNode);
	}
	if (t.getStyle('visibility')!= 'visible')
		return true;

	if (!required && trim(testValue) == ''){
		fld.validate = 'passed';
		return true;
	}

    if (testValue.match(RegExPattern)){
		var secondaryError = false;
		testValue = testValue.replace(/\-/g,"/")
		testValue = testValue.replace(/\./g,"/")
		if (notbefore){
			if (parseDate(testValue) < notbefore){
				errorMessage = 'Date out of Range.\nMust be after '+notbefore
				secondaryError = true;
			}
		}
		if (notafter){
			if (parseDate(testValue) > notafter){
				errorMessage = 'Date out of Range.\nMust be before '+notafter
				secondaryError = true;
			}
		}
		if (!secondaryError){
			fld.validate = 'passed';
	        return true; 
		}
	}
	if (window.submitAction) {
		window.clearTimeout(submitAction)
	}
	if (trim(testValue) == ''){
		errorMessage = 'Date is required.\n' + errorMessage;
	}
	else
		errorMessage = 'Date Formatting error.\n' + errorMessage;
		
	
	fld.style.backgroundColor = "#DE6C74";
	alert(errorMessage);
	fld.validate = 'failed';
	//setTimeout("gfld.focus()",3);
	if (window.myVtimeoutholder)
		window.clearTimeout(myVtimeoutholder)
	return(false)
}
function tabKey(){
	if (event.keyCode == 9)
		hideCalendarControl();
}

document.write("<iframe id='CalendarControlIFrame' src='' frameBorder='1' scrolling='no'></iframe>");
document.write("<div id='CalendarControl' onclick='event.cancelBubble=true' ></div>");

