var Calendar = require ('./calendar');

module.exports = new Class
({
	Extends: Htk.Field
	,Tag: 'htk-date-chooser'

	,format: _('%a, %e %b %Y')
	,calendar: null
	,ignoreCalendarChange: false
	
	,render: function ()
	{
		var node = this.createRoot ('div');
		node.className = 'htk-date-chooser';
		
		this.label = this.createElement ('span');
		this.node.appendChild (this.label);

		this.setEditable (this._editable);
	}

	,putValue: function (value)
	{
		var dateString;

		if (value instanceof Date)
			dateString = Vn.Date.strftime (value, this.format);
		else
			dateString = '';

		Vn.Node.setText (this.label, dateString);
	}

	,setEditable: function (editable)
	{
		Vn.Node.remove (this.label);
		
		if (this.calendar)
		{
			this.node.removeChild (this.button);
		
			this.calendar.disconnectByInstance (this);
			this.calendar = null;
		}

		if (editable && !this.calendar)
		{
			this.button = this.createElement ('button');
			this.button.className = 'input';
			this.button.title = _('ChangeDate');
			this.button.addEventListener ('click', this._onClick.bind (this));
			this.button.appendChild (this.label);
			this.node.appendChild (this.button);
		
			this.calendar = new Calendar ();
			this.calendar.on ('changed', this._onCalendarChange.bind (this));
			
			this.popup = new Htk.Popup ();
			this.popup.child = this.calendar;
		}
		else if (!editable)
			this.node.appendChild (this.label);
	}

	,_onCalendarChange: function (calendar)
	{
		if (this.ignoreCalendarChange)
			return;
	
		this.popup.hide ();
		
		var newDate = calendar.value;
		this.putValue (newDate);
		this.valueChanged (newDate);
	}

	,_onClick: function (event)
	{
		this.ignoreCalendarChange = true;
		this.calendar.value = this._value;
		this.calendar.goToSelectedMonth ();
		this.ignoreCalendarChange = false;

		this.popup.show (this.button);
	}
});