/*
MooCal v0.2 - A simple and easy to use calendar control built upon mooTools
by Chris Martin (http://www.redantdesign.com/) - MIT-style license.

The draw function is modified from a date picker control written by David Kelly
* Copyright 2007 David Kelly for CJD Systems Limited
* version 0.1 - 21st May 2007
* url - http://ng100.cjdsystems.co.uk/moo/dates/DateTimePicker.htm

*/

var MooCal = new Class({
	initialize: function(){
		this.setOptions({
			base: 1,
			x:0,
			y:0,
			calendarClass: "calendar",
			todayClass: "today",
			selectedClass: "selected",
			dayNames: ["Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sun"],
			monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
		});
		this.sqlCompatable = true;
		this.calendarID = null;
		this.visible = false;
		this.displayTimer = 0;
		this.minYear = '2000';
		this.maxYear = '2020';
	},
	showCal: function(ele,value) {
		this.elementID   = ele;
		this.chosenDate = new Date();
		if(value=='' || value == "0000-00-00") {
			var d = new Date();
			value = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();
		}
		if(value.test(' ')) {
			var dat = value.split(' ');
			var parts = dat[0].split('-');
			this.times = dat[1].split(':');
		} else {
			var parts = value.split('-');
		}

		this.chosenDate.setYear(parts[0]);
		var month = new Number(parts[1]);
		this.chosenDate.setMonth(month-1);
		this.chosenDate.setDate(parts[2]);
		this.currentDate = this.chosenDate;
		this.monthAndYear = null;
		var c = $(ele).getCoordinates();
		this.show(c.left,c.top);
	},
	setTimeSelect:function(){
		this.displayTime = true;
	},
	show: function(x, y) {
		if(!this.visible){
			this.calendarID = "calendar_" + Date.parse(new Date());
			this.draw($pick(x, this.options.x), $pick(y, this.options.y));
		}
		this.visible = true;
	},
	hide: function() {
		if(this.visible){
			$(this.calendarID).remove();
			this.visible = false;
			clearTimeout(this.displayTimer);
		}
	},
	setValue: function(d){
		this.currentDate.setDate(d);
		this.chosenDate = this.currentDate;
		var day = this.currentDate.getDate().toString();
		if(day.length == 1) day = '0' + day;
		var month = this.currentDate.getMonth()+1;
		month = month.toString();
		if(month.length == 1) month = '0' + month;


		if(!this.displayTime) {
			$(this.elementID).setProperty("value", this.currentDate.getFullYear() + '-' + month + '-' + day);
			this.hide();
		} else {
			var hrs = this.hoursSelect.value;
			if(this.ampmSelect.value == 'pm' && hrs!=12) {
				var it = new Number(this.hoursSelect.value);
				var hrs =  it+12;
			}
			if(hrs == 12 &&this.ampmSelect.value == 'am') hrs = '00';
			var time = hrs+':'+this.minutesSelect.value+':00';
			$(this.elementID).setProperty("value", this.currentDate.getFullYear() + '-' + month + '-' + day + ' ' + time);
			this.redraw();
		}
	},
	selectDate: function(e,d) {
		new Event(e).stop();
		if($type(d) != "number")return;
		this.setValue(d);
	},
	dispTime: function(){
		var dDate = this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getDate() + " " +  this.currentDate.getFullYear();
		var time = this.hoursSelect.value+':'+this.minutesSelect.value+' '+this.ampmSelect.value;
		this.ct.setHTML(dDate+' '+time);
		this.setValue(this.currentDate.getDate());
	},
	setDates: function(){
		this.lastMonth = new Date(this.currentDate).setMonth(this.currentDate.getMonth() - 1);
		this.nextMonth = new Date(this.currentDate).setMonth(this.currentDate.getMonth() + 1);
		this.lastYear = new Date(this.currentDate).setFullYear(this.currentDate.getFullYear() - 1);
		this.nextYear = new Date(this.currentDate).setFullYear(this.currentDate.getFullYear() + 1);
		this.today = new Date();
	},

	repaint: function(e,d) {
		new Event(e).stop();
		var dateToCheck = new Date(d);
		if(dateToCheck.getFullYear() < this.minYear || dateToCheck.getFullYear() > this.maxYear){
			return;
		}
		this.currentDate = dateToCheck;
		this.setDates();
		this.redraw();
	},

	mouseOver: function() {
		clearTimeout(this.displayTimer);
	},

	mouseOut: function() {
		this.displayTimer = this.hide.delay(500, this);
	},

	draw: function(x, y) {
		var tableContainer, table, thead, tbody, row, td;
		tableContainer = new Element("div",{"class": this.options.calendarClass,"id": this.calendarID,"events": {"mouseover": this.mouseOver.bind(this),"mouseout": this.mouseOut.bind(this)}}).setStyles({"position":"absolute","left": x,"top": y});
		table = new Element("table", {"id": this.calendarID + "-table","class": this.calendarID + "-table"});
		thead = new Element("thead").injectInside(table);

		row = new Element("tr").injectInside(thead);
		new Element("a", {"href":"#","events":{"click": (function(e){ this.repaint(e, this.lastYear); }).bindWithEvent(this)}}).setHTML("&laquo;").injectInside(new Element("th", {"class": this.options.calendarClass + "-yearswitch"}).injectInside(row));
		new Element("a", {"href":"#","events":{"click": (function(e){ this.repaint(e, this.lastMonth); }).bindWithEvent(this)}}).setHTML("&#139;").injectInside(new Element("th", {"class": this.options.calendarClass + "-monthswitch"}).injectInside(row));

		this.monthAndYear = new Element("th", {"colSpan": 3,"class" : this.options.calendarClass + "-monthandyear"}).appendText(this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getFullYear()).injectInside(row);
		new Element("a", {"href":"#","events":{"click": (function(e){ this.repaint(e, this.nextMonth); }).bindWithEvent(this)}}).setHTML("&#155;").injectInside(new Element("th", {"class": this.options.calendarClass + "-monthswitch"}).injectInside(row));
		new Element("a", {"href":"#","events":{"click": (function(e){ this.repaint(e, this.nextYear); }).bindWithEvent(this)}}).setHTML("&raquo;").injectInside(new Element("th", {"class": this.options.calendarClass + "-yearswitch"}).injectInside(row));

		row = new Element("tr").injectInside(thead);
		for (i = 0; i < 7; i++)	{
			new Element("th").appendText(this.options.dayNames[i]).injectInside(row);
		}

		tbody = new Element("tbody").injectInside(table);
		for(r=0;r<6;r++){
			row = new Element("tr").injectInside(tbody);
			for(c=0;c<7;c++){
				td = new Element("td",{'class':'cday'}).injectInside(row);
				new Element("a",{
				"href": "#"
				}).setHTML("&nbsp;").injectInside(td);
			}
		}
		table.injectInside(tableContainer);
		if(this.displayTime) {
			row = new Element('tr',{'class':'cDT'}).injectInside(table);
			td = new Element("td").setProperty('colspan',7).injectInside(row);
			var dDate = this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getDate() + " " +  this.currentDate.getFullYear() + ' 12:00 AM';
			this.ct = new Element('div',{'id':'ct'}).setHTML(dDate).injectInside(td);
			row = new Element('tr',{'class':'timePicker'}).injectInside(table);
			td = new Element("td").setProperty('colspan',7).injectInside(row);
			//setStyles('margin:0px;padding:5px;').setHTML('Time: ');
			this.hoursSelect = new Element('select',{'name':'chours','id':'chours'}).addEvent('change',this.dispTime.bind(this)).injectInside(td);
			var ampm;
			if(this.times) {
				if(this.times[0] == '00') {
					this.times[0] = 12;
					ampm = 'am';
				}
				if(this.times[0] > 12) {
					var ti = new Number(this.times[0]);
					this.times[0] =  ti-12;
					ampm = 'pm';
				} else if(this.times[0] == 12 && ampm!='am') {
					var ampm = 'pm';
				}
			}
			for(i=1;i<=12;i++){
				var hr = new Element('option',{'value':i}).setHTML(i).injectInside(this.hoursSelect);
				if(this.times) {
					if(this.times[0] == i) hr.selected = true;
				}
			}
			this.minutesSelect = new Element('select',{'name':'cminutes','id':'cminutes'}).addEvent('change',this.dispTime.bind(this)).injectInside(td);
			for(h=0;h<=59;h++){
				minute = new String(h);
				if(minute.length < 2) {
					mi = "0"+minute;
				} else mi = minute;
				var min = new Element('option',{'value':mi}).setHTML(mi).injectInside(this.minutesSelect);
				if(this.times) {
					if(this.times[1] == mi) min.selected = true;
				}
			}
			this.ampmSelect = new Element('select',{'name':'campm','id':'campm'}).addEvent('change',this.dispTime.bind(this)).injectInside(td);
			var am = new Element('option',{'value':'am'}).setHTML('AM').injectInside(this.ampmSelect);
			var pm = new Element('option',{'value':'pm'}).setHTML('PM').injectInside(this.ampmSelect);
			if(ampm=='pm') pm.selected = true;
			if(ampm=='am') am.selected = true;
			//holder.injectAfter(table);
		}
		tableContainer.injectInside(document.body);
		this.redraw();
	},
	redraw: function() {
		this.setDates();
		this.monthAndYear.setText(this.options.monthNames[this.currentDate.getMonth()] + " " + this.currentDate.getFullYear());
		var firstDay = new Date(this.currentDate);
		firstDay.setDate(1);

		if (firstDay.getDay() > 0) {
			firstDay.setDate(-firstDay.getDay() + 1);
		}

		var currentDay = new Date(firstDay);
		var today = new Date();
		$ES("tbody a", $(this.calendarID)).each(function(item,i){
			var txt = "&nbsp;";
			if (currentDay.getMonth() == this.currentDate.getMonth()) {
				txt = currentDay.getDate();
			}
			item.removeClass(this.options.todayClass);
			item.getParent().removeClass(this.options.selectedClass);

			item.removeEvents();
			item.addEvent("click", (function(e, day){this.selectDate(e, day);}).bindWithEvent(this, txt));
			item.setHTML(txt);
			if (currentDay.getDate() == today.getDate() && currentDay.getMonth() == today.getMonth() && currentDay.getFullYear() == today.getFullYear()) {
				item.addClass(this.options.todayClass);
			}
			if (currentDay.getMonth() == this.chosenDate.getMonth() &&
			currentDay.getDate() == this.chosenDate.getDate() &&
			currentDay.getMonth() == this.chosenDate.getMonth() &&
			currentDay.getFullYear() == this.chosenDate.getFullYear()) {
				item.getParent().addClass(this.options.selectedClass);
			}
			currentDay.setDate(currentDay.getDate() + 1);
		}.bind(this));
	}
});

MooCal.implement(new Options);
window.addEvent('domready',function(){
	$ES('.dpick',document.body).each(function(item){
		item.addEvent('click',dSelect);
	});
	$ES('.dtpick',document.body).each(function(item){
		item.addEvent('click',dtSelect);
	});
});
var dSelect = function(eve){
	var e = new Event(eve).stop();
	var item = $(e.target);
	var date = item.value;
	var DTCalendar = new MooCal();
	DTCalendar.showCal(item,date);
};
var dtSelect = function(eve){
	var e = new Event(eve).stop();
	var item = $(e.target);
	var date = item.value;
	var DTCalendar = new MooCal();
	DTCalendar.setTimeSelect();
	DTCalendar.showCal(item,date);
};
