
(function($){
	
	/**
	 * This plugin accepts a container which has three selects and a hidden text input field. 
	 * 
	 * The three selects are for the day, month and year of the date, and the script automatically corrects for days in a month, leap years, and 
	 * on each change in the date, fills in the hidden input field in this format: mm/dd/yyyy
	 
	 * @author Stephan Chevalier/Daniel Roberts (http://www.hibe.com)
	 * @class dateSelect
	 * @constructor
	 * @example <pre><code>&lt;fieldset id="facetDOB" &gt;<br />	&lt;g:render template="/shared/dateSelector"/&gt;<br />&lt;/fieldset&gt;</code></pre>
	 * @example var birthday = $j("#facetDOB").dateSelect()
	 * @example $j("#facetDOB").dateSelect().setDate(12, 12, 1986)
	 * @see jQuery.fn.setDate 
	 * @param options {daySelector, monthSelector, yearSelector, fullDate}
	 * @type jQuery
	 *
	 * @cat Plugins/DateSeletc
	 * 
	 */        		
	jQuery.fn.dateSelect = function(options) {
		/**
		* array of days in each month.  0 index represents Feb. during a leap year, so Jan is index 1
		*/
		var daysOfMonth = [
	            		{days : 29},
	            		{days : 31},
	            		{days : 28},
	            		{days : 31},
	            		{days : 30},
	            		{days : 31},
	            		{days : 30},
	            		{days : 31},
	            		{days : 31},
	            		{days : 30},
	            		{days : 31},
	            		{days : 30},
	            		{days : 31}		
	            		]
						
		// Extends the default options with the users parameters
		var opts = $.extend({}, $.dateSelect.defaults, options);
		
		/**
		* this is the init function
		* 
		*@param {String} $this The jquery object passed into the plugin
		*/
		function init($this) {
			//$this is the jquery object passed into the plugin.
			return $this.each(function() {
				//$this is the jquery object of the specific match being iterated at this moment
				$this = $(this);
				var day = $(opts.daySelector, $this);
				var month = $(opts.monthSelector, $this);
				var year = $(opts.yearSelector, $this);
				var fullDate = $(opts.fullDate, $this);
				month.change(function(){setNumDays(day, month, year, fullDate)});
				day.change(function(){setFullDate(day, month, year, fullDate)});
				year.change(function(){setNumDays(day, month, year, fullDate)});
				
			});
		};
		
		/**
		 * setNumDays() determines what month it is and then sets the number of days in the day selector to match 
		 * (i.e. 31 or 30), taking into account leap years
		 * 
		 *@param $day The jquery object representing the date selector
		 *@param $month The jquery object representing the month selector
		 *@param $year the jquery object representing the year selector
		 *@param $fullDate the jquery object representing the hidden full date field that is submitted. 
		 */
		function setNumDays($day, $month, $year, $fullDate){
			if ($month.val() != '') {
				if ($month.val() != 2) { //Any month except February
					resetDays($day, $month);
					//Remove any option with value greater (:gt) than the number of days in the month selected
					$('option:gt(' + (daysOfMonth[$month.val()].days) + ')', $day).remove();
				}
				else { //Februrary logic
					resetDays($day, $month);
					if (validateLeapYear($year.val())) {
						$('option:gt(' + (daysOfMonth[0].days) + ')', $day).remove();
					}
					else{
						$('option:gt(' + (daysOfMonth[$month.val()].days) + ')', $day).remove();
					}
				}
			}			
			setFullDate($day, $month, $year, $fullDate);
		};
		
		/**
		 * resetDays() will compare the current number of options in the day select vs. the number of days 
		 * in the month selected, and will fill the day selector up if any are missing.
		 * 
		 * @param $day The jquery object representing the date selector
		 * @param $month The jquery object representing the month selector
		 */
		function resetDays($day, $month){
			if($month.val() != '') {
				var daysInSelect = $('option', $day).length;
				var daysInMonth = daysOfMonth[$month.val()].days;
				
				if (daysInSelect < daysInMonth){
					for (i = daysInSelect; i <= daysInMonth && i <=31; i++){
						$('<option value="' + i + '">' + i + '</option>').appendTo('option:last', $day);
					}
				}
			}
		};
		
		/**
		 * setFullDate() will take the current date and insert into into the hidden full date field like such month/day/year
		 * 
		 * @param $day The jquery object representing the date selector
		 * @param $month The jquery object representing the month selector
		 * @param $year the jquery object representing the year selector
		 * @param $fullDate the jquery object representing the hidden full date field that is submitted.  
		 */
		function setFullDate($day, $month, $year, $fullDate){
			console.log($year.val());
			console.log($month.val());
			if ($day.val() != '' && $month.val() != '' && $year.val() != '') {
				//birthdate = new Date($year.val(), $month.val(), $day.val());
				//console.log(birthdate);
				//DO NOT change the line below to use date.getMonth(). it causes a bug 
				$fullDate.val(parseInt($month.val()) + '/' + parseInt($day.val()) + '/' + parseInt($year.val()));
			}
			focusToValidate($fullDate);
			
		};
		
		/**
		 * Validates the year against a leap year
		 * 
		 * @param year The integer of the year
		 */
		function validateLeapYear(year){
			if (parseInt(year) % 4 == 0) {
				if (!(year % 100 == 0) || year % 400 == 0){
					return true;
				}
				else {return false;}
			}
			else {return false;}
		}
		
		//Forces the hidden input to validate.
		function focusToValidate(element){
			element.focus();
			element.blur();
		}
		
		return init(this);	;
		
	};
	
	/**
     * @author robertsd
	 * @class dateSelect.setDate
	 * @constructor
	 * Some info about date select
	 */  
	jQuery.fn.setDate = function(day, month, year, options) {
		// Extends the default options with the users parameters
		var opts = $.extend({}, $.dateSelect.defaults, options);
		
		return this.each(function() {
			var $this = $(this);
			$(opts.daySelector, $this).val(day);
			$(opts.monthSelector, $this).val(month);
			$(opts.yearSelector, $this).val(year);;
			$(opts.fullDate, $this).val(month + '/' + day + '/' + year);
		});
	};
	
	jQuery.dateSelect = {
		defaults : {
			daySelector : "#day",
			monthSelector : "#month",
			yearSelector : "#year",
			fullDate : "#birthday"
		}
	};
})(jQuery);
