YAHOO.namespace("LP.form.CalendarWithSelects");

YAHOO.LP.form.CalendarWithSelects = function(dayFieldId, monthFieldId, yearFieldId, triggerId, calendarId, calendarContainerId, calendarCfg){
	
	this.dayField = document.getElementById(dayFieldId);
	this.monthField = document.getElementById(monthFieldId);
	this.yearField = document.getElementById(yearFieldId);
	this.trigger = document.getElementById(triggerId);
	this.calendarContainer = document.getElementById(calendarContainerId);
	//alert(monthFieldId);
	if(null == calendarCfg){
		calendarCfg = {close:true}
	}
	
	this.calendar = new YAHOO.widget.Calendar(calendarId,calendarContainerId, 
												calendarCfg);
	this.calendar.selectEvent.subscribe(this.handleSelect, this, true);
	//set the default calendar page to "01/1974"
	this.calendar.cfg.setProperty("pagedate", "01/1974");
	this.calendar.render();

	YAHOO.util.Event.addListener([monthFieldId,dayFieldId,yearFieldId], "change", this.updateCal, this, true);
	YAHOO.util.Event.addListener(triggerId, "click", this.showCal, this, true);
};

YAHOO.LP.form.CalendarWithSelects.prototype = {

	handleSelect : function(type,args,obj){
		var dates = args[0]; 
		var date = dates[0];
		
		var year = date[0];
		var month = date[1];
		var day = date[2];

		this.monthField.selectedIndex = month;
		this.dayField.selectedIndex = day;
		
		for (var y=0;y<this.yearField.options.length;y++) {
			if (this.yearField.options[y].value == year) {
				this.yearField.selectedIndex = y;
				break;
			}
		}
		this.calendar.hide();
	},
	
	updateCal : function(){
		// additional argument to parseInt indicates that the number is base-10 
		// otherwise JS tries to be clever and screws up with 08 and 09
		var month = parseInt(this.monthField.options[this.monthField.selectedIndex].value, 10);
		var day = parseInt(this.dayField.options[this.dayField.selectedIndex].value, 10);
		var year = parseInt(this.yearField.options[this.yearField.selectedIndex].value, 10);
		
    
    	// assume the default date of 01/01/1974 if none of the date components are selected
		if (isNaN(month) ) {
			month = 1;
		}
		if (isNaN(day)) {
			day = 1;
		} 
		if (isNaN(year)) {
			year = 1974;
		}
			
		var date = month + "/" + day + "/" + year;
		this.calendar.cfg.setProperty("pagedate", month + "/" + year);
		this.calendar.render();
		  
	},
	
	showCal : function(){
		this.calendar.show();
		var pos = YAHOO.util.Dom.getXY(this.trigger); 
		YAHOO.util.Dom.setXY(this.calendarContainer, pos);
	}
};

