/**
 * datepicker.js - MooTools Datepicker class
 * @version 1.12
 * 
 * by MonkeyPhysics.com
 *
 * Source/Documentation available at:
 * http://www.monkeyphysics.com/mootools/script/2/datepicker
 * 
 * --
 * 
 * Smoothly animating, very configurable and easy to install.
 * No Ajax, pure Javascript. 4 skins available out of the box.
 * 
 * --
 *
 * Some Rights Reserved
 * http://creativecommons.org/licenses/by-sa/3.0/
 * 
 */

var DatePicker = new Class({
	
	Implements: Options,
	
	// working date, which we will keep modifying to render the calendars
	d: '',
	
	// just so that we need not request it over and over
	today: '',
	
	// current user-choice in date object format
	choice: null, 
	
	// size of body, used to animate the sliding
	bodysize: {}, 
	
	// to check availability of next/previous buttons
	limit: {}, 
	
	// element references:
	attachTo: null,    // selector for target inputs
	picker: null,      // main datepicker container
	pickerContent: null, // main datepicker content
	slider: null,      // slider that contains both oldContents and newContents, used to animate between 2 different views
	oldContents: null, // used in animating from-view to new-view
	newContents: null, // used in animating from-view to new-view
	input: null,       // original input element (used for input/output)
	visual: null,      // visible input (used for rendering)
	arrSelectMonths: null, // month selector array
	
	options: { 
		pickerClass: 'clsDatepicker',
		updateGlobalDateFields : function(){},
		calendarId: 'calendar',
		days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
		months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
		dayShort: 3,
		monthShort: 3,
		startDay: 1, // Sunday (0) through Saturday (6) - be aware that this may affect your layout, since the days on the right might have a different margin
		format: 'd-m-Y',
		allowEmpty: false,
		inputOutputFormat: 'd-m-Y', // default to unix timestamp
		animationDuration: 250,
		useFadeInOut: !Browser.Engine.trident, // dont animate fade-in/fade-out for IE
		positionOffset: { x: 0, y: 0 },
		startDate: null, //  { date: '[date-string]', format: '[date-string-interpretation-format]' }
		minDate: null, // { date: '[date-string]', format: '[date-string-interpretation-format]' }
		maxDate: null, // same as minDate
		debug: false,
		toggleElement: null,
		nrOfMonths: 2,
		
		// and some event hooks:
		onShow: $empty,   // triggered when the datepicker pops up
		onClose: $empty,  // triggered after the datepicker is closed (destroyed)
		onSelect: $empty  // triggered when a date is selected
	},
	
	initialize: function(attachTo, options) {
		this.attachTo = attachTo;
		this.setOptions(options).attach();
		if ($chk(this.options.startDate)) this.options.startDate = this.unformat(this.options.startDate.date, this.options.startDate.format);
		if ($chk(this.options.minDate)) this.options.minDate = this.unformat(this.options.minDate.date, this.options.minDate.format);
		if ($chk(this.options.maxDate)) this.options.maxDate = this.unformat(this.options.maxDate.date, this.options.maxDate.format);
		document.addEvent('mousedown', this.close.bind(this));
	},
	
	attach: function() {
		// toggle the datepicker through a separate element?
		if ($chk(this.options.toggleElement)) {
			var toggler = $(this.options.toggleElement);
			document.addEvents({
				'keydown': function(e) {
					if (e.key == "tab") {
						this.close(null, true);
					}
				}.bind(this)
			});
		};
		
		// attach functionality to the input	
		var item = $(this.attachTo);
		
		// never double attach
		if (item.retrieve('datepicker'))
			return;
		
		// determine starting value(s)
		if ($chk(item.get('value'))) {
			var init_clone_val = this.format(new Date(this.unformat(item.get('value'), this.options.inputOutputFormat)), this.options.format);
		} else if (!this.options.allowEmpty) {
			var init_clone_val = this.format(new Date(), this.options.format);
		} else {
			var init_clone_val = '';
		}
		
		
		// create clone
		var display = item.getStyle('display');
		var clone = item
			.setStyle('display', this.options.debug ? display : 'none')
			.store('datepicker', true) // to prevent double attachment...
			.clone()
			.store('datepicker', true) // ...even for the clone (!)
			.removeProperty('name')    // secure clean (form)submission
			.setStyle('display', display)
			.set('value', init_clone_val)
			.inject(item, 'after');
			
		// events
		if ($chk(this.options.toggleElement)){
			$(this.options.toggleElement)
				.setStyle('cursor', 'pointer')
				.addEvents({
					'click': function(e) {
						this.onFocus(item, clone);
					}.bind(this)
				});
			clone.addEvents({
				'blur': function() {
					item.set('value', clone.get('value'));
				}
			});
		} else {
			clone.addEvents({
				'keydown': function(e) {
					if (this.options.allowEmpty && (e.key == "delete" || e.key == "backspace")) {
						item.set('value', '');
						e.target.set('value', '');
						this.close(null, true);
					} else if (e.key == "tab") {
						this.close(null, true);
					} else {
						e.stop();
					}
				}.bind(this),
				'focus': function(e) {
					this.onFocus(item, clone);
				}.bind(this)
			});
		}
	},
	
	onFocus: function(original_input, visual_input) {
		var init_visual_date;
		var toggler = $(this.options.toggleElement);
		d = toggler.getCoordinates();
		if ($chk(original_input.get('value'))) {
			init_visual_date = this.unformat(original_input.get('value'), this.options.inputOutputFormat).valueOf();
		} else {
			init_visual_date = $chk(this.options.startDate)?this.options.startDate:new Date();
		}
		
		this.show({ left: d.left + this.options.positionOffset.x, top: d.top + d.height + this.options.positionOffset.y }, init_visual_date);
		this.input = original_input;
		this.visual = visual_input;
		this.options.onShow();
	},
	
	show: function(position, timestamp) {
		if ($chk(timestamp)) {
			this.d = new Date(timestamp);
		} else if ($chk(this.options.startDate)) {
			this.d = new Date(this.options.startDate.getTime());
		} else {
			this.d = new Date();
		}
		this.today = $chk(this.options.startDate)?new Date(this.options.startDate.getTime()):new Date();
		this.choice = new Date(this.d.getTime());
		this.mode = 'month';
		this.render();
		this.picker.setStyles(position);
	},
	
	render: function(fx) {
		if (!$chk(this.picker)) {
			this.constructPicker();
		} else {
			// swap contents so we can fill the newContents again and animate
			var o = this.oldContents;
			this.oldContents = this.newContents;
			this.newContents = o;
			this.newContents.empty();
		}
		
		// remember current working date
		var xStartDate = new Date(this.d.getTime());
		
		// intially assume both left and right are allowed
		this.limit = { right: false, left: false };
		
		this.renderMonth(0);
			
		this.pickerContent.getElement('.previous').setStyle('visibility', this.limit.left ? 'hidden' : 'visible');
		this.pickerContent.getElement('.next').setStyle('visibility', this.limit.right ? 'hidden' : 'visible');
		
		// restore working date
		this.d = xStartDate;
		
		// if ever the opacity is set to '0' it was only to have us fade it in here
		// refer to the constructPicker() function, which instantiates the picker at opacity 0 when fading is desired
		if (this.picker.getStyle('opacity') == 0) {
			this.picker.tween('opacity', 0, 1);
		}
		
		// animate
		if ($chk(fx)) this.fx(fx);
	},
	
	fx: function(fx) {
		if (fx == 'right') {
			this.oldContents.setStyles({ left: 0, opacity: 1 });
			this.newContents.setStyles({ left: this.bodysize.x/2, opacity: 1 });
			this.slider.setStyle('left', 0).tween('left', 0, (-this.bodysize.x/2));
		} else if (fx == 'left') {
			this.oldContents.setStyles({ left: this.bodysize.x/2, opacity: 1 });
			this.newContents.setStyles({ left: 0, opacity: 1 });
			this.slider.setStyle('left', (-this.bodysize.x / 2)).tween('left', (-this.bodysize.x / 2),0);
		} else if (fx == 'fade') {
			this.slider.setStyle('left', 0);
			this.oldContents.setStyle('left', 0).set('tween', { duration: this.options.animationDuration / 2 }).tween('opacity', 1, 0);
			this.newContents.setStyles({ opacity: 0, left: 0}).set('tween', { duration: this.options.animationDuration }).tween('opacity', 0, 1);
		}
	},
	
	constructPicker: function() {
		this.picker = new Element('div', { 'id': this.options.calendarId, 'class': this.options.pickerClass }).inject(document.body);
		this.pickerContent = new Element('div', { 'class': 'content' }).inject(this.picker);
		if (this.options.useFadeInOut) {
			this.picker.setStyle('opacity', 0).set('tween', { duration: this.options.animationDuration });
		}
		
		var h = new Element('div', { 'class': 'header' }).inject(this.pickerContent);
		var titlecontainer = new Element('div', { 'class': 'title' }).inject(h);
		new Element('div', { 'class': 'previous' }).addEvent('click', this.previous.bind(this)).set('html', '&#171;').inject(h);
		new Element('div', { 'class': 'next' }).addEvent('click', this.next.bind(this)).set('html', '&#187;').inject(h);
		new Element('div', { 'class': 'closeButton' }).addEvent('click', this.close.bindWithEvent(this, true)).set('text', '[x]').inject(h);
		
		this.arrSelectMonths = new Array();
		var arrSelectDivs = new Array();
		
		var tmpTime = this.options.startDate.getTime();
		var stopTime = this.options.maxDate.getTime();
		for(var monthCount=0; monthCount<this.options.nrOfMonths; monthCount++){
			arrSelectDivs[monthCount] =	new Element('div', {'class': 'titleText' }).inject(titlecontainer);
			this.arrSelectMonths[monthCount] = new Element('select', {'class': 'clsCalendarSelectMonth' }).addEvent('change', this.updateSelectedMonth).inject(arrSelectDivs[monthCount]);
			this.arrSelectMonths[monthCount].store('counter',monthCount);
			this.arrSelectMonths[monthCount].store('daypicker',this);
			
			/* reset time */
			this.options.startDate.setTime(tmpTime);
			this.options.startDate.setDate(1);

			/* set next calendars a month ahead */
			this.options.startDate.setMonth(this.options.startDate.getMonth() + monthCount);
						
			stopTime = this.options.maxDate.getTime();
			this.options.maxDate.setDate(1);
			this.options.maxDate.setMonth((this.options.maxDate.getMonth() - (this.options.nrOfMonths-1)) + monthCount);

			while(this.options.startDate.getTime() <= this.options.maxDate.getTime()){
			
				new Element('option', { 'value':this.format(this.options.startDate,'d-m-Y') }).set('text', this.format(this.options.startDate,'M \'y')).inject(this.arrSelectMonths[monthCount]);
				this.options.startDate.setMonth(this.options.startDate.getMonth() + 1);
				
			}
			this.options.maxDate.setTime(stopTime);
		}
		/* and reset the time again */
		this.options.startDate.setTime(tmpTime);

		var b = new Element('div', { 'class': 'body' }).inject(this.pickerContent);
		this.bodysize = b.getSize();
		this.slider = new Element('div', { styles: { position: 'absolute', top: 0, left: 0, width: 1.5 * this.bodysize.x, height: this.bodysize.y }})
					.set('tween', { duration: this.options.animationDuration, transition: Fx.Transitions.Quad.easeInOut }).inject(b);
		this.oldContents = new Element('div', { styles: { position: 'absolute', top: 0, left: this.bodysize.x, width: this.bodysize.x, height: this.bodysize.y }}).inject(this.slider);
		this.newContents = new Element('div', { styles: { position: 'absolute', top: 0, left: 0, width: this.bodysize.x, height: this.bodysize.y }}).inject(this.slider);
		
		var monthWidth = Math.floor(this.bodysize.x/this.options.nrOfMonths);
		for(var monthCount=0; monthCount<this.options.nrOfMonths; monthCount++){
			arrSelectDivs[monthCount].setStyle('width',''+(monthWidth-45)+'px');
			arrSelectDivs[monthCount].setStyle('position','absolute');
			if(monthCount == 0){
				arrSelectDivs[monthCount].setStyle('left',''+((monthCount*monthWidth)+25)+'px');
			} else {
				arrSelectDivs[monthCount].setStyle('left',''+((monthCount*monthWidth)+5)+'px');
			}			
		}
	},	
	
	renderMonth: function(intBuildMonth) {
		
		/* the case the dates are on the last month we may show */
		var tmpTime = this.options.maxDate.getTime();
		this.options.maxDate.setDate(1);
		if(intBuildMonth == (this.options.nrOfMonths - 2) && this.d.getTime() > this.options.maxDate.getTime()){
			this.d.setMonth(this.d.getMonth()-1);			
		}
		this.options.maxDate.setTime(tmpTime);
		
		var month = this.d.getMonth();
		var dayFormat = '01-'+this.format(this.d,'m-Y');
		for(var i=0; i<this.arrSelectMonths[intBuildMonth].options.length; i++){
			var element = $(this.arrSelectMonths[intBuildMonth].options[i]);
			if(element.getProperty('value') == dayFormat){
				element.setProperty('selected','selected');
			} else {
				element.removeProperty('selected');
			}
		}
		this.d.setDate(1);
		while (this.d.getDay() != this.options.startDay) {
			this.d.setDate(this.d.getDate() - 1);
		}
		
		var container = new Element('div', {'style':'position:absolute !important; top:0px; left:'+(intBuildMonth*(this.bodysize.x/this.options.nrOfMonths))+'px;', 'class': 'days' }).inject(this.newContents);
		var titles = new Element('div', { 'class': 'titles'}).inject(container);
		var d, i, classes, e, weekcontainer;

		for (d = this.options.startDay; d < (this.options.startDay + 7); d++) {
			new Element('div', { 'class': 'title day day' + (d % 7) }).set('text', this.options.days[(d % 7)].substring(0,this.options.dayShort)).inject(titles);
		}
		
		var available = false;
		var t = this.today.toDateString();
		var currentChoice = this.choice.toDateString();
		
		for (i = 0; i < 42; i++) {
			classes = [];
			classes.push('day');
			classes.push('day'+this.d.getDay());
			if (this.d.toDateString() == t) classes.push('today');
			if (this.d.toDateString() == currentChoice) classes.push('selected');
			if (this.d.getMonth() != month) classes.push('otherMonth');
			
			if (i % 7 == 0) {
				weekcontainer = new Element('div', { 'class': 'week week'+(Math.floor(i/7)) }).inject(container);
			}
			
			e = new Element('div', { 'class': classes.join(' ') }).set('text', this.d.getDate()).inject(weekcontainer);
			if (this.limited('date')) {
				e.addClass('unavailable');
			} else {
				e.store('date',new Date(this.d.getTime()));
				e.store('datepicker',this);
				e.addEvent('click', function(e) {
					this.retrieve('datepicker').select(this.retrieve('date'));
				});
			}
			if (this.limited('monthLeft')) {
				this.limit.left = true;
			} 
			if(this.limited('monthRight')) {
				this.limit.right = true;
			}
			this.d.setDate(this.d.getDate() + 1);
		}
		if(intBuildMonth < (this.options.nrOfMonths-1)){
			this.renderMonth((intBuildMonth+1));
		}
	},
	limited: function(type) {
		var cs = $chk(this.options.minDate);
		var ce = $chk(this.options.maxDate);
		if (!cs && !ce) return false;
		
		switch (type) {
			case 'year':
				return (cs && this.d.getFullYear() < this.options.minDate.getFullYear()) || (ce && this.d.getFullYear() > this.options.maxDate.getFullYear());
				
			case 'month':
				// todo: there has got to be an easier way...?
				var ms = ('' + this.d.getFullYear() + this.leadZero(this.d.getMonth())).toInt();
				return cs && ms < ('' + this.options.minDate.getFullYear() + this.leadZero(this.options.minDate.getMonth())).toInt()
					|| ce && ms > ('' + this.options.maxDate.getFullYear() + this.leadZero(this.options.maxDate.getMonth())).toInt()
			
			case 'monthLeft':
				var ms = ('' + this.d.getFullYear() + this.leadZero(this.d.getMonth())).toInt();
				return cs && ms < ('' + this.options.minDate.getFullYear() + this.leadZero(this.options.minDate.getMonth())).toInt()
			
			case 'monthRight':
				var ms = ('' + this.d.getFullYear() + this.leadZero(this.d.getMonth())).toInt();
				return ce && ms > ('' + this.options.maxDate.getFullYear() + this.leadZero(this.options.maxDate.getMonth())).toInt()
				
					
			case 'date':
				return (cs && this.d < this.options.minDate) || (ce && this.d > this.options.maxDate);
		}
	},
		
	previous: function() {
		this.d.setMonth(this.d.getMonth() - 1);
		this.render('left');
	},
	
	next: function() {
		this.d.setMonth(this.d.getMonth() + 1);
		this.render('right');
	},
	
	close: function(e, force) {
		if (!$(this.picker)) return;
		var clickOutside = ($chk(e) && e.target != this.picker && !this.picker.hasChild(e.target) && e.target != this.visual);
		if (force || clickOutside) {
			if (this.options.useFadeInOut) {
				this.picker.set('tween', { duration: this.options.animationDuration / 2, onComplete: this.destroy.bind(this) }).tween('opacity', 1, 0);
			} else {
				this.destroy();
			}
		}
	},
	
	destroy: function() {
		this.picker.destroy();
		this.picker = null;
		this.options.onClose();
	},
	
	select: function(d) {
		this.input.set('value', this.format(d, 'd-m-Y'));
		this.visual.set('value', this.format(d, 'd-m-Y'));
		this.options.onSelect();
		this.options.updateGlobalDateFields(this.format(d, 'j-n-Y'));
		this.close(null, true);
	},
	
	leadZero: function(v) {
		return parseInt(v) < 10 ? '0'+v : v;
	},

	stripZero: function(v) {
		v = ''+v;
		return (v.charAt(0) == '0')?v.charAt(1):v;
	},
	
	updateSelectedMonth: function(){
		var counter = this.retrieve('counter');
		var daypicker = this.retrieve('daypicker');
		daypicker.setStartMonthYear(counter);
	},
	
	setStartMonthYear: function(c){
		var oldTime = this.d.getTime();
		this.d = this.unformat(this.arrSelectMonths[0].options[this.arrSelectMonths[c].selectedIndex].value,'d-m-Y');
		if(this.d.getTime() > oldTime){
			this.render('right');
		} else if(this.d.getTime() < oldTime){
			this.render('left');
		}
	},
	
	format: function(t, format) {
		var f = '';
		var h = t.getHours();
		var m = t.getMonth();
		
		for (var i = 0; i < format.length; i++) {
			switch(format.charAt(i)) {
				case '\\': i++; f+= format.charAt(i); break;
				case 'y': f += (t.getFullYear()+'').substring(2,4); break
				case 'Y': f += t.getFullYear(); break;
				case 'm': f += this.leadZero(m + 1); break;
				case 'n': f += (m + 1); break;
				case 'M': f += this.options.months[m].substring(0,this.options.monthShort); break;
				case 'F': f += this.options.months[m]; break;
				case 'd': f += this.leadZero(t.getDate()); break;
				case 'j': f += t.getDate(); break;
				case 'D': f += this.options.days[t.getDay()].substring(0,this.options.dayShort); break;
				case 'l': f += this.options.days[t.getDay()]; break;
				case 'G': f += h; break;
				case 'H': f += this.leadZero(h); break;
				case 'g': f += (h % 12 ? h % 12 : 12); break;
				case 'h': f += this.leadZero(h % 12 ? h % 12 : 12); break;
				case 'a': f += (h > 11 ? 'pm' : 'am'); break;
				case 'A': f += (h > 11 ? 'PM' : 'AM'); break;
				case 'i': f += this.leadZero(t.getMinutes()); break;
				case 's': f += this.leadZero(t.getSeconds()); break;
				case 'U': f += Math.floor(t.valueOf() / 1000); break;
				default:  f += format.charAt(i);
			}
		}
		return f;
	},
	
	unformat: function(t, format) {
		var d = new Date();
		var a = {};
		var c, m;
		
		for (var i = 0; i < format.length; i++) {
			c = format.charAt(i);
			switch(c) {
				case '\\': r = null; i++; break;
				case 'y': r = '[0-9]{2}'; break;
				case 'Y': r = '[0-9]{4}'; break;
				case 'm': r = '0[1-9]|1[012]'; break;
				case 'n': r = '[1-9]|1[012]'; break;
				case 'M': r = '[A-Za-z]{'+this.options.monthShort+'}'; break;
				case 'F': r = '[A-Za-z]+'; break;
				case 'd': r = '0[1-9]|[12][0-9]|3[01]'; break;
				case 'j': r = '[1-9]|[12][0-9]|3[01]'; break;
				case 'D': r = '[A-Za-z]{'+this.options.dayShort+'}'; break;
				case 'l': r = '[A-Za-z]+'; break;
				case 'G': 
				case 'H': 
				case 'g': 
				case 'h': r = '[0-9]{1,2}'; break;
				case 'a': r = '(am|pm)'; break;
				case 'A': r = '(AM|PM)'; break;
				case 'i': 
				case 's': r = '[012345][0-9]'; break;
				case 'U': r = '-?[0-9]+$'; break;
				default:  r = null;
			}
			
			if ($chk(r)) {
				m = t.match('^'+r);
				if ($chk(m)) {
					a[c] = m[0];
					t = t.substring(a[c].length);
				} else {
					if (this.options.debug) alert("Fatal Error in DatePicker\n\nUnexpected format at: '"+t+"' expected format character '"+c+"' (pattern '"+r+"')");
					return d;
				}
			} else {
				t = t.substring(1);
			}
		}
		/*
		for (c in a) {
			var v = a[c];
			switch(c) {
				case 'y': d.setFullYear(v < 30 ? 2000 + v.toInt() : 1900 + v.toInt()); break; // assume between 1930 - 2029
				case 'Y': d.setFullYear(v); break;
				case 'm':
				case 'n': d.setMonth(v - 1); break;
				// FALL THROUGH NOTICE! "M" has no break, because "v" now is the full month (eg. 'February'), which will work with the next format "F":
				case 'M': v = this.options.months.filter(function(item, index) { return item.substring(0,this.options.monthShort) == v }.bind(this))[0];
				case 'F': d.setMonth(this.options.months.indexOf(v)); break;
				case 'd':
				case 'j': d.setDate(v); break;
				case 'G': 
				case 'H': d.setHours(v); break;
				case 'g': 
				case 'h': if (a['a'] == 'pm' || a['A'] == 'PM') { d.setHours(v == 12 ? 0 : v.toInt() + 12); } else { d.setHours(v); } break;
				case 'i': d.setMinutes(v); break;
				case 's': d.setSeconds(v); break;
				case 'U': d = new Date(v.toInt() * 1000);
			}
		};*/
		var year  = ((a['Y'] != null)?a['Y']:(2000 + a['y'].toInt()));
		var month = parseInt(this.stripZero((a['m'] != null)?a['m']:a['n']))-1;
		var day   = this.stripZero((a['d'] != null)?a['d']:a['j']);
		var time  = (a['U'] != null)?a['U']:false;
		if(time !== false){
			d = new Date(time);
		} else {
			d = new Date(year,month,day);
		}
		return d;
	}
});