function keyp(e, id)
{
	// if aEvent is null, means the Internet Explorer event model, 
	// so get window.event. 
	var IE5 = false; 
	if (!e) var e = window.event;
	if (e.keyCode)
	{
		IE5= true;
		code = e.keyCode;
	} 
	else if (e.which)
		code = e.which;
	enterid = null;
	if (code == 13)
	{
		if (id == 'datecir')
			enterid = "ci_r";
		else if (id == 'datecor')
			enterid = "co_r";
		else if (id == 'datecil')	
			enterid = "ci_l";
		else if (id == 'datecol')	
			enterid = "co_l";
		document.getElementById(enterid).focus();			
	}
}

function checksubmit()
{
	if ((enterid != null) && (!submitme))
	{
		document.getElementById(enterid).focus();
		enterid = null;
	}
	return submitme;
}

var PBBDatePickers = new Class(
{
	Implements:[Events, Options],
	options:
	{
		onShow:function(datepicker) {datepicker.setStyle('visibility', 'visible');},
		onHide:function(datepicker) {datepicker.setStyle('visibility', 'hidden');},
		presentDay:0,
		presentMonth:0,
		presentYear:2100,		
		showDelay:0,
		hideDelay:0,
		className:null,
		id:null,
		id_checkin:null,		
		id_checkout:null,	
		offsets:{x:0, y:0},		
		dateformat:'d M Y',
		toggle:0,
		days:['Sunday','Monday','Tuesdat','Wednesday','Thursday','Friday','Saturday'],
		days_abbreviate:['Su','M','Tu','W','Th','F','Sa'],
		months:['January','February','March','April','May','June','July','August','September','October','November','December'],
		months_abbreviate:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],		
		weekFirstDay:0,
		visiblity:0
	},
	initialize:function()
	{
		var params=Array.link(arguments,{options:Object.type, elements:$defined});
		this.setOptions(params.options || null);
		this.lock=false;
		this.datepicker=new Element('div').addEvents(
		{
			'mouseover':function() {this.lock=true;}.bind(this),
			'mouseout':function() {this.lock = false;}.bind(this)
		}).inject(document.body);
		if (this.options.className) this.datepicker.addClass(this.options.className);
		var top=new Element('div',{'class':'datepicker-top'}).inject(this.datepicker);
		this.container=new Element('div',{'class':'datepicker'}).inject(this.datepicker);
		var bottom=new Element('div',{'class':'datepicker-bottom'}).inject(this.datepicker);
		this.datepicker.setStyles({position:'absolute',top:0,left:0,visibility:'hidden'});
		if (params.elements) this.attach(params.elements);
	},
	attach:function(elements)
	{
		$$(elements).each(function(element)
		{
			var dateformat=element.retrieve('datepicker:dateformat',element.get('accept'));
			if (!dateformat)
			{
				dateformat=this.options.dateformat;
				element.store('datepicker:dateformat',dateformat);
			}
			var datevalue=element.retrieve('datepicker:datevalue',element.get('value'));
			if (!datevalue)
			{
				datevalue=this.format(new Date(), dateformat);
				element.store('datepicker:datevalue',datevalue);
			}
			element.store('datepicker:current',this.unformat(datevalue,dateformat));
			var inputFocus=element.retrieve('datepicker:focus',this.elementFocus.bindWithEvent(this,element));
			var inputBlur=element.retrieve('datepicker:blur',this.elementBlur.bindWithEvent(this,element));
			element.addEvents({focus:inputFocus,blur:inputBlur});
			element.store('datepicker:native',element.get('accept'));
			element.erase('dateformat');
		}, this);
		return this;
	},
	detach:function(elements)
	{
		$$(elements).each(function(element)
		{
			element.removeEvent('onfocus',element.retrieve('datepicker:focus') || $empty);
			element.removeEvent('onblur',element.retrieve('datepicker:blur') || $empty);
			element.eliminate('datepicker:focus').eliminate('datepicker:blur');
			var original=element.retrieve('datepicker:native');
			if (original) element.set('dateformat',original);
		});
		return this;
	},
	elementFocus:function(event,element)
	{	
		if (this.options.toggle==1)
			this.hide();
		else
		{
			this.el=element;
			if ((this.options.visiblity==0) && (this.options.id != null))
			{		
				var value=document.getElementById(this.options.id).value;
				var current=this.unformat(value,'d M Y');
				this.curFullYear=current[0];
				this.curMonth=current[1];
				this.curDate=current[2];			
				var date=new Date(this.curFullYear,this.curMonth,this.curDate);
				var value=this.format(date,this.el.retrieve('datepicker:dateformat'));
				this.el.store('datepicker:current',Array(this.curFullYear,this.curMonth,this.curDate));
				this.el.set('value',value);
				this.options.visiblity=1;
			}
			else
			{		
				var current=element.retrieve('datepicker:current');
				this.curFullYear=current[0];
				this.curMonth=current[1];
				this.curDate=current[2];			
			}		
			this.build();
			this.show();	
			this.position({page:element.getPosition()});
		}
	},
	elementChange:function()
	{
		var date=new Date(this.curFullYear,this.curMonth,this.curDate);
		var value=this.format(date,this.el.retrieve('datepicker:dateformat'));			
		this.el.store('datepicker:current', Array(this.curFullYear,this.curMonth,this.curDate));
		this.el.set('value',value);				
		if (this.options.id != null)
		{		
			document.getElementById(this.options.id).value=value;
			if (this.options.id==this.options.id_checkin)				
			{
				if (this.options.id_checkout != null)			
				{
					var value2=document.getElementById(this.options.id_checkout).value;
					var arr=value2.split(' ');
					if (arr[2] != null)
					{
						for (i=0; i<12; i++)
						{
							if (arr[1].toLowerCase()==this.options.months_abbreviate[i].toLowerCase())
								break;
						}
						var date2 = new Date(arr[2],i,arr[0]);
						if ((date2.getTime()<date.getTime())||(i==12))
						{
							var date2=new Date(this.curFullYear,this.curMonth,this.curDate+1);
							document.getElementById(this.options.id_checkout).value=this.format(date2,this.el.retrieve('datepicker:dateformat'));
						}
					}
				}
			}
			else if (this.options.id==this.options.id_checkout)
			{
				if (this.options.id_checkin != null)
				{
					var value2=document.getElementById(this.options.id_checkin).value;
					var arr=value2.split(' ');
					if (arr[2] != null)
					{
						for (i=0; i<12; i++)
						{
							if (arr[1].toLowerCase()==this.options.months_abbreviate[i].toLowerCase())
								break;
						}
						var date2 = new Date(arr[2],i,arr[0]);									
						if ((date.getTime()<date2.getTime())||(i==12))
						{
							var date2 = new Date(date2.getFullYear(),date2.getMonth(),date2.getDate()+1);
							document.getElementById(this.options.id_checkout).value=this.format(date2,this.el.retrieve('datepicker:dateformat'));
						}
					}
				}			
			}
		}	
		this.hide();
	},
	elementBlur:function(event)
	{
		if (!this.lock)
			this.hide();	
	},
	position:function(event)
	{
		var size=window.getSize(), scroll=window.getScroll();
		var datepicker={x:this.datepicker.offsetWidth,y:this.datepicker.offsetHeight};
		var props={x:'left',y:'top'};
		for (var z in props)
		{
			var pos=event.page[z]+this.options.offsets[z];
			this.datepicker.setStyle(props[z],pos);
		}
	},
	show:function() {this.fireEvent('show',this.datepicker);},
	hide:function()
	{
		this.datepicker.setStyle('left', -1000);
		this.options.visiblity=0;
		this.options.toggle=0;
		this.fireEvent('hide',this.datepicker);
	},
	build:function()
	{	
		$A(this.container.childNodes).each(Element.dispose);	
		var yearlinks=this.yearlinks().inject(this.container);
		var monthlinks=this.monthlinks().inject(this.container);			
		if (this.curFullYear<this.options.presentYear+2)
			validyear=1;
		else
			validyear=0;
		var month_header_1=this.options.months[this.curMonth]+' '+this.curFullYear;				
		var table_1=new Element('table',{'class':'month1'}).inject(this.container);
		var tcaption_1=this.tcaption(month_header_1).inject(table_1);
		var thead_1=this.thead().inject(table_1);
		var tbody_1=this.tbody(this.curMonth,this.curFullYear,validyear).inject(table_1);		
		if (this.curMonth<11)
		{	
			var month_header_2=this.options.months[this.curMonth+1]+' '+this.curFullYear;
			var table_2=new Element('table',{'class':'month2'}).inject(this.container);
			var tcaption_2=this.tcaption(month_header_2).inject(table_2);
			var thead_2=this.thead().inject(table_2);
			var tbody_2=this.tbody(this.curMonth+1,this.curFullYear,validyear).inject(table_2);
		}
		var btnclose=this.btnclose().inject(this.container);
	},
	navigate:function(type,d)
	{	
		switch (type)
		{
			case 'm':
				this.curMonth=d;
				break;
			case 'y':
				this.curFullYear=d;
				if (d>this.options.presentYear)
					this.curMonth=0;
				else
					this.curMonth=this.options.presentMonth;
				break;
		}
		this.el.store('datepicker:current',Array(this.curFullYear,this.curMonth,this.curDate));
		this.options.toggle=0;
		this.el.focus();
	},
	btnclose:function()
	{			
		var caption=new Element('span',{'class':'btnclose'});
		var close=new Element('a').appendText('CLOSE');
		close.addEvent('click',function() {this.hide();}.bind(this)).inject(caption);
		return caption;
	},		
	yearlinks:function()
	{		
		if (this.curFullYear==this.options.presentYear)
		{
			var p1=new Element('span',{'class':'curyear'}).set('text',this.options.presentYear);
			var p2=new Element('span').set('text',' | ');
			var p3=new Element('span');
			var a=new Element('a').appendText(this.options.presentYear+1);
			a.clone().addEvent('click',function() { this.navigate('y',this.options.presentYear+1);}.bind(this)).inject(p3);			
		}
		else if (this.curFullYear==this.options.presentYear+1)
		{
			var p1=new Element('span');
			var a=new Element('a').appendText(this.options.presentYear);
			a.clone().addEvent('click',function(){ this.navigate('y', this.options.presentYear);}.bind(this)).inject(p1);
			var p2=new Element('span').set('text',' | ');	
			var p3=new Element('span',{'class':'curyear'}).set('text',this.options.presentYear+1);
		}
		else
		{
			var p1=new Element('span');
			var a=new Element('a').appendText(this.options.presentYear);
			a.clone().addEvent('click',function(){this.navigate('y', this.options.presentYear);}.bind(this)).inject(p1);
			var p2=new Element('span').set('text',' | ');	
			var p3=new Element('span');			
			var b=new Element('a').appendText(this.options.presentYear+1);
			b.clone().addEvent('click',function(){this.navigate('y',this.options.presentYear+1); }.bind(this)).inject(p3);			
		}
		var p=new Element('span',{'class':'yearlinks'});		
		p1.inject(p);
		p2.inject(p);			
		p3.inject(p);			
		return p;	
	},	
	monthlinks:function()
	{
		var d0=new Date(this.options.presentYear,this.options.presentMonth,this.options.presentDay);	
		var d1=new Date(this.options.presentYear+1,this.options.presentMonth+1,this.options.presentDay);			
		var today=new Date(d0.getFullYear(),d0.getMonth(),d0.getDate()).getTime();
		var nextyear=new Date(d1.getFullYear(),d1.getMonth(),d1.getDate()).getTime();		
		var table=new Element('table',{'class':'monthlinks'});
		var thead=new Element('tbody');
		var tr=new Element('tr').inject(thead);			
		for (i=0;i<12;i++)
		{
			var date=new Date(this.curFullYear,i+1,0);
			if (date.getTime()>nextyear)
				break;
			else if (date.getTime()<today)
				new Element('td',{'class':'past'}).set('text',this.options.months_abbreviate[i]).inject(tr);
			else if (i == this.curMonth)
				new Element('td',{'class':'curmonth'}).set('text', this.options.months_abbreviate[i]).inject(tr);			
			else
			{
				td=new Element('td').inject(tr);
				var a=new Element('a').appendText(this.options.months_abbreviate[i]);
				a.addEvent('click',function(i) {this.navigate('m', i);}.bind(this,i)).inject(td);				
			}
		}
		thead.inject(table);		
		return table;	
	},
	tcaption:function(txt)
	{
		var caption=new Element('caption').set('text', txt);
		return caption;
	},
	thead:function()
	{
		var thead=new Element('thead');
		var tr=new Element('tr').inject(thead);
		for (i=0;i<7;i++)
			new Element('th').set('text',this.options.days_abbreviate[(this.options.weekFirstDay+i)%7]).inject(tr);	
		return thead;
	},
	tbody:function(Month, FullYear, ValidYear)
	{			
		var d= new Date(FullYear,Month,1);		
		var offset=((d.getDay()-this.options.weekFirstDay)+7) % 7;
		var last=new Date(FullYear,Month+1,0).getDate();
		var prev=new Date(FullYear,Month,0).getDate();
		var v=(this.el.get('value')) ? this.unformat(this.el.get('value'),this.el.retrieve('datepicker:dateformat')) : false;
		var current=new Date(v[0],v[1],v[2]).getTime();		
		var d=new Date(this.options.presentYear,this.options.presentMonth,this.options.presentDay);	
		var today=new Date(d.getFullYear(),d.getMonth(),d.getDate()).getTime();
		var tbody=new Element('tbody');
		for (var i=1;i<43;i++)
		{
			if ((i-1)%7== 0)
				tr=new Element('tr').inject(tbody);
			var td=new Element('td').inject(tr);
			var day=i-offset;
			var date=new Date(FullYear,Month,day);
			if (day<1)
			{
				day='';
				td.addClass('inactive');
			}
			else if (day>last)
			{
				day='';
				td.addClass('inactive');
			}
			else
			{
				if (date.getTime()<today)	
					td.addClass('inactive');
				else if (ValidYear>0)
				{
					if (date.getTime()==current)
						td.addClass('hilite');
					else if (date.getTime()==today)
						td.addClass('today');
					td.addEvents(
					{
						'click':function(day,m)
						{
							this.curMonth=m;
							this.curDate=day;
							this.elementChange();
						}.bind(this,[day,Month]),
						'mouseover':function(td)
						{ 
							td.addClass('hilite'); 
						}.bind(this, td),
						'mouseout':function(td, date)
						{
							if (date.getTime() != current)
								td.removeClass('hilite'); 
						}.bind(this, [td, date])
					}).addClass('active');
				}
			}
			td.set('text',day);
		}	
		return tbody;		
	},
	unformat: function(val,f)
	{
		f=f.escapeRegExp();
		var re=
		{
			d:'([0-9]{2})',
			j:'([0-9]{1,2})',
			D:'(' + this.options.days.map(function(day) { return day.substr(0, 3); }).join('|') + ')',					
			l:'(' + this.options.days.join('|') + ')',
			S:'(st|nd|rd|th)',
			F:'(' + this.options.months.join('|') + ')',
			m:'([0-9]{2})',
			M:'(' + this.options.months.map(function(month) { return month.substr(0, 3); }).join('|') + ')',					
			n:'([0-9]{1,2})',
			Y:'([0-9]{4})',
			y:'([0-9]{2})'
		}
		var arr=[];
		var g='';
		for (var i=0;i<f.length;i++)
		{
			var c=f.charAt(i);
			if (re[c])
			{
				arr.push(c);
				g += re[c];
			}
			else
				g += c;
		}
		var matches=val.match('^'+g+'$');
		var dates=new Array(3);
		dates[0]=-1;
		dates[1]=-1;
		dates[2]=-1;
		if (matches)
		{
			matches=matches.slice(1);
			arr.each(function(c,i)
			{
				i=matches[i];
				switch(c) {
					case 'y':
						i='19'+i;
					case 'Y':
						dates[0]=i.toInt();
						break;
					case 'F':
						i=i.substr(0, 3);
					case 'M':
						i=this.options.months.map(function(month) {return month.substr(0, 3); }).indexOf(i) + 1;
					case 'm':
					case 'n':					
						dates[1]=i.toInt()-1;
						break;
					case 'd':
					case 'j':
						dates[2]=i.toInt();
						break;
				}
			}, this);			
		}
		if (this.options.id==this.options.id_checkout)
		{		
			dates[0]=(dates[0]>=0) ? dates[0]:this.options.presentYear;
			dates[1]=(dates[1]>=0) ? dates[1]:this.options.presentMonth;
			dates[2]=(dates[2]>=0) ? dates[2]:this.options.presentDay+1;
		}
		else
		{		
			dates[0]=(dates[0]>=0) ? dates[0]:this.options.presentYear;
			dates[1]=(dates[1]>=0) ? dates[1]:this.options.presentMonth;
			dates[2]=(dates[2]>=0) ? dates[2]:this.options.presentDay;
		}
		return dates;
	},
	format: function(date,format)
	{
		var str='';
		if (date)
		{
			var j=date.getDate();
      		var w=date.getDay();
			var l=this.options.days[w];
			var n=date.getMonth()+1;
			var f=this.options.months[n-1];
			var y=date.getFullYear()+'';
			
			for (var i=0, len=format.length; i<len; i++)
			{
				var cha=format.charAt(i);
				switch(cha)
				{
					case 'y':
						y=y.substr(2);
					case 'Y':
						str += y;
						break;
					case 'm':
						if (n<10) { n='0'+n;}
					case 'n':
						str += n;
						break;
					case 'M':
						f = f.substr(0, 3);
					case 'F':
						str += f;
						break;
					case 'd':
						if (j<10) {j='0'+j;}
					case 'j':
						str += j;
						break;
					case 'D':
						l = l.substr(0, 3);
					case 'l':
						str += l;
						break;
					case 'N':
						w += 1;
					case 'w':
						str += w;
						break;
					case 'S':
						if (j%10==1 && j != '11') { str += 'st'; }
						else if (j%10 == 2 && j != '12') { str += 'nd'; }
						else if (j%10 == 3 && j != '13') { str += 'rd'; }
						else { str += 'th'; }
						break;
					default:
						str += cha;
				}
			}
		}
	  return str;
	}
});
