//
// Calendar visual effect support
//

// TODO: Probably should port this to a prototype extended class

// class constructor
function Calendar(widgetDiv, containerDiv, editControl, dateChangedFn )
{
	this.over_cal = false;
	this.cal_up = false;
	this.dateChangedCB = dateChangedFn;
	
	// contruct encapsulated yui control and associate bits
	this.calWidget = new YAHOO.widget.Calendar(widgetDiv, containerDiv);
	this.editCtrl = document.getElementById(editControl);
	this.containerCtrl = document.getElementById(containerDiv);
	
	// setup initial listeners
	this.calWidget.renderEvent.subscribe(this.setupRenderListeners, this, true);
	this.calWidget.selectEvent.subscribe(this.getDate, this, true);
	YAHOO.util.Event.addListener(this.editCtrl, 'focus', this.showCal, this, true);
	YAHOO.util.Event.addListener(this.editCtrl, 'blur', this.hideCal, this, true);	
}

// listeners that get setup on render (because container div is initially hidden)
Calendar.prototype.setupRenderListeners = function(me)
{
	YAHOO.util.Event.addListener(this.containerCtrl, 'mouseover', this.mouseIn, this, true);
	YAHOO.util.Event.addListener(this.containerCtrl, 'mouseout', this.mouseOut, this, true);
}

// callback for date selection
Calendar.prototype.getDate = function(me)	//type, args, obj)
{
	var calDate = this.calWidget.getSelectedDates()[0];
	this.editCtrl.value = dateToString(calDate);
	this.over_cal = false;	// state hack
	this.hideCal();
	
	// notify the caller if needed
	if( typeof(this.dateChangedCB) == 'function' )
	{
		this.dateChangedCB(calDate);
	}
}

// show the calendar
Calendar.prototype.showCal = function(me)
{
	if( !this.cal_up )
	{
		// get the edit control position and date
		var xy = YAHOO.util.Dom.getXY(this.editCtrl.id);
		var editCtrlStr =
		  (YAHOO.util.Dom.get(this.editCtrl.id).value || '').strip();
		var dateStr = isDateString(editCtrlStr) ? editCtrlStr : '';
	  var date = parseDateString(dateStr) || new Date;
	
		// set the associated calendar date
		var minDate = this.calWidget.cfg.getProperty('mindate');
		this.calWidget.cfg.setProperty('selected', dateStr);
		this.calWidget.cfg.setProperty('pagedate', minDate ? minDate : date, true);
		this.calWidget.render();
			
		YAHOO.util.Dom.setStyle(this.containerCtrl.id, 'display', 'block');
		xy[1] = xy[1] + 20;
		YAHOO.util.Dom.setXY(this.containerCtrl.id, xy);	
		this.cal_up = true;		
	}
}

// hide the calendar
Calendar.prototype.hideCal = function(me)
{
	if( this.cal_up && !this.over_cal )
	{
		YAHOO.util.Dom.setStyle(this.containerCtrl.id, 'display', 'none');
		this.cal_up = false;
	}
}

Calendar.prototype.mouseIn = function(me)
{
	this.over_cal = true;
}

Calendar.prototype.mouseOut = function(me)
{
	this.over_cal = false;
}

Calendar.prototype.setMinDate = function(minDate)
{
	this.calWidget.cfg.setProperty('mindate', minDate, true);
}

Calendar.prototype.setMaxDate = function(maxDate)
{
	this.calWidget.cfg.setProperty('maxdate', maxDate, true);
}