/**
 * Calendar widget.
 * 
 * Takes an input fields as element.
 * 
 * ----
 * 
 * LICENCE
 * 
 * This work is licensed under Creative Commons Attribution-Share Alike 3.0 (Germany).
 * For details on this licence visit http://creativecommons.org/licenses/by-sa/3.0/de/
 * 
 * All rights reserved
 * 
 * @author Jakob Hohlfeld | http://www.netronaut.de
 * @copyright 2010 by Jakob Hohlfeld
 * 
 */
var NetronautUI_Widgets_InputDate = new Class
({
	Extends: NetronautUI_Widget,
	
	calendar: null,
	date: new Date(),
	
	initialize: function ( el, options ) {
		this.parent(el, options);
		
		// add calendar
		this.calendar = new NetronautUI_Widgets_Calendar().setLimit({from:new Date()});
		var win = new NetronautUI_Window(this.calendar, {positionOnTarget:{position:'centerBottom',edge:'centerTop'}, autoClose:true});
		
		win.dom.hitarea.push(this.dom.el);
		this.dom.hitarea.extend(win.dom.hitarea);
		win.increaseZIndex();
		
		// events
		this.dom.el.addEvent('focus', function(event){
			var date = Date.parse(this.dom.el.value);
			this.calendar.gotoDate(date);
			win.open(event);
			this.dom.el.select();
		}.bind(this)).addEvent('change', function(event){
			var date = Date.parse(this.dom.el.value);
			if(isNaN(date.getTime())) {
				date = new Date();
			}
			this.fireEvent('change');
			this.update(date);
			this.fireEvent('update', date);
			win.close();
		}.bind(this));
		this.calendar.addEvent('select', function(date){
			this.fireEvent('select', date);
			this.update(date);
			this.fireEvent('update', date);
			win.close();
		}.bind(this));
	},
	
	/**
	 * Update the widget.
	 * 
	 * @param Date date
	 */
	update: function ( date ) {
		this.date = date;
		this.calendar.setDate(date);
		this.dom.el.value = date.format('short_date');
	}
})
