YAHOO.namespace("example");

/* example */
	var DatePickerObj = function(opts) {
		this.textfield = null;
		this.datepicker = null; // YAHOO.ext.DatePicker object
		this.calID = YAHOO.util.Dom.generateId(0, 'dpobj-dp-');
		this.showDatePicker = null;
		this.config = {
			textfield: null, // id/HTML Element
			showPickerOnFocus: false, // show the picker when the textfield is focused
			outputDateFmt: 'm/d/Y',
			showPicker: null,
			twoDigitYearCutoff: 1980 // null to ignore, otherwise dates before this have 100 years added to them (1904 becomes 2004).
		};

		// initialize our config
		if( typeof opts != 'undefined' ) {
			for( var c in this.config) {
				if( typeof opts[c] != "undefined" ) {
					this.config[c] = opts[c];
				}
			}
		}

	}
	DatePickerObj.prototype.init = function() {
		if( this.config.showPicker ) {
			this.showDatePicker = getEl(this.config.showPicker);
			// add our click handler to show the link
			this.showDatePicker.on('click', this.show, this, true);
		}
		if( this.config.textfield ) {
			this.textfield = getEl(this.config.textfield);
			if( this.config.showPickerOnFocus ) {
				this.textfield.set({autocomplete:'off'}); // work around firefox errors
				this.textfield.on('focus', this.show, this, true);
			}
		}
		this.datepicker = new YAHOO.ext.DatePicker(this.calID);
		
	}
		
	DatePickerObj.prototype.show = function() {
		var selectedDate = new Date();
		var _this = this; // scope our callback appropriately
		var r = { left:0, bottom:0 };
		
		if( this.textfield && this.config.showPickerOnFocus ) {
			r = this.textfield.getRegion();
		} else if( this.showDatePicker ) {
			r = this.showDatePicker.getRegion();
		}

		if( this.textfield && this.textfield.dom.value != '' ) {
			selectedDate = Date.parse(this.textfield.dom.value);
			if( isNaN(selectedDate) ) {
				selectedDate = new Date();
			} else {
				selectedDate = new Date(selectedDate);
				if( this.config.twoDigitYearCutoff && selectedDate.getFullYear() <= this.config.twoDigitYearCutoff ) {
					selectedDate.setFullYear(selectedDate.getFullYear()+100);
				}
			}
		}
		
		this.datepicker.show(r.left, r.bottom, selectedDate, function(selDate) { _this.dateSelectionHandler(selDate); } );
	}
	// override this to deal with other types of elements like select boxes
	DatePickerObj.prototype.dateSelectionHandler = function(selDate) {
		if( this.textfield ) {
			this.textfield.dom.value = selDate.dateFormat(this.config.outputDateFmt);
		}
	}
/* end */


		dateExampleInit = function() {
			YAHOO.example.datepicker = new DatePickerObj({
				textfield:'dateTarget',
				showPicker:'showCal',
				showPickerOnFocus:true
			});
			YAHOO.example.datepicker.init();

		}

		YAHOO.ext.EventManager.onDocumentReady(dateExampleInit);


