2 * Copyright (c) 2008 Kelvin Luck (http://www.kelvinluck.com/)
3 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
4 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
13 * Render a calendar table into any matched elements.
15 * @param Object s (optional) Customize your calendars.
16 * @option Number month The month to render (NOTE that months are zero based). Default is today's month.
17 * @option Number year The year to render. Default is today's year.
18 * @option Function renderCallback A reference to a function that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Default is no callback.
19 * @option Number showHeader Whether or not to show the header row, possible values are: $.dpConst.SHOW_HEADER_NONE (no header), $.dpConst.SHOW_HEADER_SHORT (first letter of each day) and $.dpConst.SHOW_HEADER_LONG (full name of each day). Default is $.dpConst.SHOW_HEADER_SHORT.
20 * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
22 * @name renderCalendar
23 * @cat plugins/datePicker
24 * @author Kelvin Luck (http://www.kelvinluck.com/)
26 * @example $('#calendar-me').renderCalendar({month:0, year:2007});
27 * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me.
30 * var testCallback = function($td, thisDate, month, year)
32 * if ($td.is('.current-month') && thisDate.getDay() == 4) {
33 * var d = thisDate.getDate();
38 * alert('You clicked on ' + d + '/' + (Number(month)+1) + '/' + year);
40 * ).addClass('thursday');
41 * } else if (thisDate.getDay() == 5) {
42 * $td.html('Friday the ' + $td.html() + 'th');
45 * $('#calendar-me').renderCalendar({month:0, year:2007, renderCallback:testCallback});
47 * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me. Every Thursday in the current month has a class of "thursday" applied to it, is clickable and shows an alert when clicked. Every Friday on the calendar has the number inside replaced with text.
49 renderCalendar : function(s)
53 return document.createElement(a);
56 s = $.extend({}, $.fn.datePicker.defaults, s);
58 if (s.showHeader != $.dpConst.SHOW_HEADER_NONE) {
59 var headRow = $(dc('tr'));
60 for (var i=Date.firstDayOfWeek; i<Date.firstDayOfWeek+7; i++) {
62 var day = Date.dayNames[weekday];
64 jQuery(dc('th')).attr({'scope':'col', 'abbr':day, 'title':day, 'class':(weekday == 0 || weekday == 6 ? 'weekend' : 'weekday')}).html(s.showHeader == $.dpConst.SHOW_HEADER_SHORT ? day.substr(0, 1) : day)
69 var calendarTable = $(dc('table'))
75 .addClass('jCalendar')
77 (s.showHeader != $.dpConst.SHOW_HEADER_NONE ?
84 var tbody = $(dc('tbody'));
86 var today = (new Date()).zeroTime();
89 var month = s.month == undefined ? today.getMonth() : s.month;
90 var year = s.year || today.getFullYear();
92 var currentDate = (new Date(year, month, 1, 12, 0, 0));
95 var firstDayOffset = Date.firstDayOfWeek - currentDate.getDay() + 1;
96 if (firstDayOffset > 1) firstDayOffset -= 7;
97 var weeksToDraw = Math.ceil(( (-1*firstDayOffset+1) + currentDate.getDaysInMonth() ) /7);
98 currentDate.addDays(firstDayOffset-1);
100 var doHover = function(firstDayInBounds)
107 $this.addClass(s.hoverClass);
108 } else if (firstDayInBounds && !$this.is('.disabled')) {
109 $this.parent().addClass('activeWeekHover');
114 var unHover = function()
118 $this.removeClass(s.hoverClass);
119 $this.parent().removeClass('activeWeekHover');
124 while (w++<weeksToDraw) {
125 var r = jQuery(dc('tr'));
126 var firstDayInBounds = s.dpController ? currentDate > s.dpController.startDate : false;
127 for (var i=0; i<7; i++) {
128 var thisMonth = currentDate.getMonth() == month;
130 .text(currentDate.getDate() + '')
131 .addClass((thisMonth ? 'current-month ' : 'other-month ') +
132 (currentDate.isWeekend() ? 'weekend ' : 'weekday ') +
133 (thisMonth && currentDate.getTime() == today.getTime() ? 'today ' : '')
135 .data('datePickerDate', currentDate.asString())
136 .hover(doHover(firstDayInBounds), unHover)
139 if (s.renderCallback) {
140 s.renderCallback(d, currentDate, month, year);
142 // addDays(1) fails in some locales due to daylight savings. See issue 39.
143 //currentDate.addDays(1);
144 // set the time to midday to avoid any weird timezone issues??
145 currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate()+1, 12, 0, 0);
149 calendarTable.append(tbody);
154 $(this).empty().append(calendarTable);
159 * Create a datePicker associated with each of the matched elements.
161 * The matched element will receive a few custom events with the following signatures:
163 * dateSelected(event, date, $td, status)
164 * Triggered when a date is selected. event is a reference to the event, date is the Date selected, $td is a jquery object wrapped around the TD that was clicked on and status is whether the date was selected (true) or deselected (false)
166 * dpClosed(event, selected)
167 * Triggered when the date picker is closed. event is a reference to the event and selected is an Array containing Date objects.
169 * dpMonthChanged(event, displayedMonth, displayedYear)
170 * Triggered when the month of the popped up calendar is changed. event is a reference to the event, displayedMonth is the number of the month now displayed (zero based) and displayedYear is the year of the month.
172 * dpDisplayed(event, $datePickerDiv)
173 * Triggered when the date picker is created. $datePickerDiv is the div containing the date picker. Use this event to add custom content/ listeners to the popped up date picker.
175 * @param Object s (optional) Customize your date pickers.
176 * @option Number month The month to render when the date picker is opened (NOTE that months are zero based). Default is today's month.
177 * @option Number year The year to render when the date picker is opened. Default is today's year.
178 * @option String|Date startDate The first date date can be selected.
179 * @option String|Date endDate The last date that can be selected.
180 * @option Boolean inline Whether to create the datePicker as inline (e.g. always on the page) or as a model popup. Default is false (== modal popup)
181 * @option Boolean createButton Whether to create a .dp-choose-date anchor directly after the matched element which when clicked will trigger the showing of the date picker. Default is true.
182 * @option Boolean showYearNavigation Whether to display buttons which allow the user to navigate through the months a year at a time. Default is true.
183 * @option Boolean closeOnSelect Whether to close the date picker when a date is selected. Default is true.
184 * @option Boolean displayClose Whether to create a "Close" button within the date picker popup. Default is false.
185 * @option Boolean selectMultiple Whether a user should be able to select multiple dates with this date picker. Default is false.
186 * @option Number numSelectable The maximum number of dates that can be selected where selectMultiple is true. Default is a very high number.
187 * @option Boolean clickInput If the matched element is an input type="text" and this option is true then clicking on the input will cause the date picker to appear.
188 * @option Boolean rememberViewedMonth Whether the datePicker should remember the last viewed month and open on it. If false then the date picker will always open with the month for the first selected date visible.
189 * @option Boolean selectWeek Whether to select a complete week at a time...
190 * @option Number verticalPosition The vertical alignment of the popped up date picker to the matched element. One of $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM. Default is $.dpConst.POS_TOP.
191 * @option Number horizontalPosition The horizontal alignment of the popped up date picker to the matched element. One of $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT.
192 * @option Number verticalOffset The number of pixels offset from the defined verticalPosition of this date picker that it should pop up in. Default in 0.
193 * @option Number horizontalOffset The number of pixels offset from the defined horizontalPosition of this date picker that it should pop up in. Default in 0.
194 * @option (Function|Array) renderCallback A reference to a function (or an array of separate functions) that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Each callback function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year. Default is no callback.
195 * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
196 * @option String autoFocusNextInput Whether focus should be passed onto the next input in the form (true) or remain on this input (false) when a date is selected and the calendar closes
199 * @cat plugins/datePicker
200 * @author Kelvin Luck (http://www.kelvinluck.com/)
202 * @example $('input.date-picker').datePicker();
203 * @desc Creates a date picker button next to all matched input elements. When the button is clicked on the value of the selected date will be placed in the corresponding input (formatted according to Date.format).
205 * @example demo/index.html
206 * @desc See the projects homepage for many more complex examples...
208 datePicker : function(s)
210 if (!$.event._dpCache) $.event._dpCache = [];
212 // initialise the date picker controller with the relevant settings...
213 s = $.extend({}, $.fn.datePicker.defaults, s);
219 var alreadyExists = true;
222 this._dpId = $.event.guid++;
223 $.event._dpCache[this._dpId] = new DatePicker(this);
224 alreadyExists = false;
228 s.createButton = false;
229 s.displayClose = false;
230 s.closeOnSelect = false;
234 var controller = $.event._dpCache[this._dpId];
238 if (!alreadyExists && s.createButton) {
240 controller.button = $('<a href="#" class="dp-choose-date" title="' + $.dpText.TEXT_CHOOSE_DATE + '">' + $.dpText.TEXT_CHOOSE_DATE + '</a>')
245 $this.dpDisplay(this);
250 $this.after(controller.button);
253 if (!alreadyExists && $this.is(':text')) {
257 function(e, selectedDate, $td)
259 this.value = selectedDate.asString();
265 if (this.value == '') {
266 controller.clearSelected();
268 var d = Date.fromString(this.value);
270 controller.setSelected(d, true, true);
280 // The change event doesn't happen until the input loses focus so we need to manually trigger it...
281 $this.trigger('change');
286 var d = Date.fromString(this.value);
287 if (this.value != '' && d) {
288 controller.setSelected(d, true, true);
292 $this.addClass('dp-applied');
298 * Disables or enables this date picker
300 * @param Boolean s Whether to disable (true) or enable (false) this datePicker
302 * @name dpSetDisabled
303 * @cat plugins/datePicker
304 * @author Kelvin Luck (http://www.kelvinluck.com/)
306 * @example $('.date-picker').datePicker();
307 * $('.date-picker').dpSetDisabled(true);
308 * @desc Prevents this date picker from displaying and adds a class of dp-disabled to it (and it's associated button if it has one) for styling purposes. If the matched element is an input field then it will also set the disabled attribute to stop people directly editing the field.
310 dpSetDisabled : function(s)
312 return _w.call(this, 'setDisabled', s);
315 * Updates the first selectable date for any date pickers on any matched elements.
317 * @param String|Date d A Date object or string representing the first selectable date (formatted according to Date.format).
319 * @name dpSetStartDate
320 * @cat plugins/datePicker
321 * @author Kelvin Luck (http://www.kelvinluck.com/)
323 * @example $('.date-picker').datePicker();
324 * $('.date-picker').dpSetStartDate('01/01/2000');
325 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the first selectable date for each of these to the first day of the millenium.
327 dpSetStartDate : function(d)
329 return _w.call(this, 'setStartDate', d);
332 * Updates the last selectable date for any date pickers on any matched elements.
334 * @param String|Date d A Date object or string representing the last selectable date (formatted according to Date.format).
337 * @cat plugins/datePicker
338 * @author Kelvin Luck (http://www.kelvinluck.com/)
340 * @example $('.date-picker').datePicker();
341 * $('.date-picker').dpSetEndDate('01/01/2010');
342 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the last selectable date for each of these to the first Janurary 2010.
344 dpSetEndDate : function(d)
346 return _w.call(this, 'setEndDate', d);
349 * Gets a list of Dates currently selected by this datePicker. This will be an empty array if no dates are currently selected or NULL if there is no datePicker associated with the matched element.
352 * @name dpGetSelected
353 * @cat plugins/datePicker
354 * @author Kelvin Luck (http://www.kelvinluck.com/)
356 * @example $('.date-picker').datePicker();
357 * alert($('.date-picker').dpGetSelected());
358 * @desc Will alert an empty array (as nothing is selected yet)
360 dpGetSelected : function()
362 var c = _getController(this[0]);
364 return c.getSelected();
369 * Selects or deselects a date on any matched element's date pickers. Deselcting is only useful on date pickers where selectMultiple==true. Selecting will only work if the passed date is within the startDate and endDate boundries for a given date picker.
371 * @param String|Date d A Date object or string representing the date you want to select (formatted according to Date.format).
372 * @param Boolean v Whether you want to select (true) or deselect (false) this date. Optional - default = true.
373 * @param Boolean m Whether you want the date picker to open up on the month of this date when it is next opened. Optional - default = true.
374 * @param Boolean e Whether you want the date picker to dispatch events related to this change of selection. Optional - default = true.
376 * @name dpSetSelected
377 * @cat plugins/datePicker
378 * @author Kelvin Luck (http://www.kelvinluck.com/)
380 * @example $('.date-picker').datePicker();
381 * $('.date-picker').dpSetSelected('01/01/2010');
382 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
384 dpSetSelected : function(d, v, m, e)
386 if (v == undefined) v=true;
387 if (m == undefined) m=true;
388 if (e == undefined) e=true;
389 return _w.call(this, 'setSelected', Date.fromString(d), v, m, e);
392 * Sets the month that will be displayed when the date picker is next opened. If the passed month is before startDate then the month containing startDate will be displayed instead. If the passed month is after endDate then the month containing the endDate will be displayed instead.
394 * @param Number m The month you want the date picker to display. Optional - defaults to the currently displayed month.
395 * @param Number y The year you want the date picker to display. Optional - defaults to the currently displayed year.
397 * @name dpSetDisplayedMonth
398 * @cat plugins/datePicker
399 * @author Kelvin Luck (http://www.kelvinluck.com/)
401 * @example $('.date-picker').datePicker();
402 * $('.date-picker').dpSetDisplayedMonth(10, 2008);
403 * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
405 dpSetDisplayedMonth : function(m, y)
407 return _w.call(this, 'setDisplayedMonth', Number(m), Number(y), true);
410 * Displays the date picker associated with the matched elements. Since only one date picker can be displayed at once then the date picker associated with the last matched element will be the one that is displayed.
412 * @param HTMLElement e An element that you want the date picker to pop up relative in position to. Optional - default behaviour is to pop up next to the element associated with this date picker.
415 * @cat plugins/datePicker
416 * @author Kelvin Luck (http://www.kelvinluck.com/)
418 * @example $('#date-picker').datePicker();
419 * $('#date-picker').dpDisplay();
420 * @desc Creates a date picker associated with the element with an id of date-picker and then causes it to pop up.
422 dpDisplay : function(e)
424 return _w.call(this, 'display', e);
427 * Sets a function or array of functions that is called when each TD of the date picker popup is rendered to the page
429 * @param (Function|Array) a A function or an array of functions that are called when each td is rendered. Each function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year.
431 * @name dpSetRenderCallback
432 * @cat plugins/datePicker
433 * @author Kelvin Luck (http://www.kelvinluck.com/)
435 * @example $('#date-picker').datePicker();
436 * $('#date-picker').dpSetRenderCallback(function($td, thisDate, month, year)
438 * // do stuff as each td is rendered dependant on the date in the td and the displayed month and year
440 * @desc Creates a date picker associated with the element with an id of date-picker and then creates a function which is called as each td is rendered when this date picker is displayed.
442 dpSetRenderCallback : function(a)
444 return _w.call(this, 'setRenderCallback', a);
447 * Sets the position that the datePicker will pop up (relative to it's associated element)
449 * @param Number v The vertical alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM
450 * @param Number h The horizontal alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT
452 * @name dpSetPosition
453 * @cat plugins/datePicker
454 * @author Kelvin Luck (http://www.kelvinluck.com/)
456 * @example $('#date-picker').datePicker();
457 * $('#date-picker').dpSetPosition($.dpConst.POS_BOTTOM, $.dpConst.POS_RIGHT);
458 * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be bottom and right aligned to the #date-picker element.
460 dpSetPosition : function(v, h)
462 return _w.call(this, 'setPosition', v, h);
465 * Sets the offset that the popped up date picker will have from it's default position relative to it's associated element (as set by dpSetPosition)
467 * @param Number v The vertical offset of the created date picker.
468 * @param Number h The horizontal offset of the created date picker.
471 * @cat plugins/datePicker
472 * @author Kelvin Luck (http://www.kelvinluck.com/)
474 * @example $('#date-picker').datePicker();
475 * $('#date-picker').dpSetOffset(-20, 200);
476 * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be 20 pixels above and 200 pixels to the right of it's default position.
478 dpSetOffset : function(v, h)
480 return _w.call(this, 'setOffset', v, h);
483 * Closes the open date picker associated with this element.
487 * @cat plugins/datePicker
488 * @author Kelvin Luck (http://www.kelvinluck.com/)
490 * @example $('.date-pick')
496 * $(this).dpDisplay();
508 return _w.call(this, '_closeCalendar', false, this[0]);
511 * Rerenders the date picker's current month (for use with inline calendars and renderCallbacks).
514 * @name dpRerenderCalendar
515 * @cat plugins/datePicker
516 * @author Kelvin Luck (http://www.kelvinluck.com/)
519 dpRerenderCalendar : function()
521 return _w.call(this, '_rerenderCalendar');
523 // private function called on unload to clean up any expandos etc and prevent memory links...
524 _dpDestroy : function()
526 // TODO - implement this?
530 // private internal function to cut down on the amount of code needed where we forward
531 // dp* methods on the jQuery object on to the relevant DatePicker controllers...
532 var _w = function(f, a1, a2, a3, a4)
537 var c = _getController(this);
539 c[f](a1, a2, a3, a4);
545 function DatePicker(ele)
550 this.displayedMonth = null;
551 this.displayedYear = null;
552 this.startDate = null;
554 this.showYearNavigation = null;
555 this.closeOnSelect = null;
556 this.displayClose = null;
557 this.rememberViewedMonth= null;
558 this.selectMultiple = null;
559 this.numSelectable = null;
560 this.numSelected = null;
561 this.verticalPosition = null;
562 this.horizontalPosition = null;
563 this.verticalOffset = null;
564 this.horizontalOffset = null;
566 this.renderCallback = [];
567 this.selectedDates = {};
569 this.context = '#dp-popup';
573 DatePicker.prototype,
577 this.setStartDate(s.startDate);
578 this.setEndDate(s.endDate);
579 this.setDisplayedMonth(Number(s.month), Number(s.year));
580 this.setRenderCallback(s.renderCallback);
581 this.showYearNavigation = s.showYearNavigation;
582 this.closeOnSelect = s.closeOnSelect;
583 this.displayClose = s.displayClose;
584 this.rememberViewedMonth = s.rememberViewedMonth;
585 this.selectMultiple = s.selectMultiple;
586 this.numSelectable = s.selectMultiple ? s.numSelectable : 1;
587 this.numSelected = 0;
588 this.verticalPosition = s.verticalPosition;
589 this.horizontalPosition = s.horizontalPosition;
590 this.hoverClass = s.hoverClass;
591 this.setOffset(s.verticalOffset, s.horizontalOffset);
592 this.inline = s.inline;
595 this.context = this.ele;
599 setStartDate : function(d)
602 if (d instanceof Date) {
605 this.startDate = Date.fromString(d);
608 if (!this.startDate) {
609 this.startDate = (new Date()).zeroTime();
611 this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
613 setEndDate : function(d)
616 if (d instanceof Date) {
619 this.endDate = Date.fromString(d);
623 this.endDate = (new Date('12/31/2999')); // using the JS Date.parse function which expects mm/dd/yyyy
625 if (this.endDate.getTime() < this.startDate.getTime()) {
626 this.endDate = this.startDate;
628 this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
630 setPosition : function(v, h)
632 this.verticalPosition = v;
633 this.horizontalPosition = h;
635 setOffset : function(v, h)
637 this.verticalOffset = parseInt(v) || 0;
638 this.horizontalOffset = parseInt(h) || 0;
640 setDisabled : function(s)
643 $e[s ? 'addClass' : 'removeClass']('dp-disabled');
645 $but = $(this.button);
646 $but[s ? 'addClass' : 'removeClass']('dp-disabled');
647 $but.attr('title', s ? '' : $.dpText.TEXT_CHOOSE_DATE);
649 if ($e.is(':text')) {
650 $e.attr('disabled', s ? 'disabled' : '');
653 setDisplayedMonth : function(m, y, rerender)
655 if (this.startDate == undefined || this.endDate == undefined) {
658 var s = new Date(this.startDate.getTime());
660 var e = new Date(this.endDate.getTime());
664 if ((!m && !y) || (isNaN(m) && isNaN(y))) {
665 // no month or year passed - default to current month
666 t = new Date().zeroTime();
668 } else if (isNaN(m)) {
669 // just year passed in - presume we want the displayedMonth
670 t = new Date(y, this.displayedMonth, 1);
671 } else if (isNaN(y)) {
672 // just month passed in - presume we want the displayedYear
673 t = new Date(this.displayedYear, m, 1);
675 // year and month passed in - that's the date we want!
676 t = new Date(y, m, 1)
678 // check if the desired date is within the range of our defined startDate and endDate
679 if (t.getTime() < s.getTime()) {
681 } else if (t.getTime() > e.getTime()) {
684 var oldMonth = this.displayedMonth;
685 var oldYear = this.displayedYear;
686 this.displayedMonth = t.getMonth();
687 this.displayedYear = t.getFullYear();
689 if (rerender && (this.displayedMonth != oldMonth || this.displayedYear != oldYear))
691 this._rerenderCalendar();
692 $(this.ele).trigger('dpMonthChanged', [this.displayedMonth, this.displayedYear]);
695 setSelected : function(d, v, moveToMonth, dispatchEvents)
697 if (d < this.startDate || d.zeroTime() > this.endDate.zeroTime()) {
698 // Don't allow people to select dates outside range...
701 var s = this.settings;
704 d = d.addDays(- (d.getDay() - Date.firstDayOfWeek + 7) % 7);
705 if (d < this.startDate) // The first day of this week is before the start date so is unselectable...
710 if (v == this.isSelected(d)) // this date is already un/selected
714 if (this.selectMultiple == false) {
715 this.clearSelected();
716 } else if (v && this.numSelected == this.numSelectable) {
717 // can't select any more dates...
720 if (moveToMonth && (this.displayedMonth != d.getMonth() || this.displayedYear != d.getFullYear())) {
721 this.setDisplayedMonth(d.getMonth(), d.getFullYear(), true);
723 this.selectedDates[d.asString()] = v;
724 this.numSelected += v ? 1 : -1;
725 var selectorString = 'td.' + (d.getMonth() == this.displayedMonth ? 'current-month' : 'other-month');
727 $(selectorString, this.context).each(
730 if ($(this).data('datePickerDate') == d.asString()) {
734 $td.parent()[v ? 'addClass' : 'removeClass']('selectedWeek');
736 $td[v ? 'addClass' : 'removeClass']('selected');
740 $('td', this.context).not('.selected')[this.selectMultiple && this.numSelected == this.numSelectable ? 'addClass' : 'removeClass']('unselectable');
744 var s = this.isSelected(d);
746 var dClone = Date.fromString(d.asString());
747 $e.trigger('dateSelected', [dClone, $td, s]);
748 $e.trigger('change');
751 isSelected : function(d)
753 return this.selectedDates[d.asString()];
755 getSelected : function()
758 for(var s in this.selectedDates) {
759 if (this.selectedDates[s] == true) {
760 r.push(Date.fromString(s));
765 clearSelected : function()
767 this.selectedDates = {};
768 this.numSelected = 0;
769 $('td.selected', this.context).removeClass('selected').parent().removeClass('selectedWeek');
771 display : function(eleAlignTo)
773 if ($(this.ele).is('.dp-disabled')) return;
775 eleAlignTo = eleAlignTo || this.ele;
777 var $ele = $(eleAlignTo);
778 var eleOffset = $ele.offset();
782 var attrsCalendarHolder;
786 $createIn = $(this.ele);
788 'id' : 'calendar-' + this.ele._dpId,
789 'class' : 'dp-popup dp-popup-inline'
792 $('.dp-popup', $createIn).remove();
796 $createIn = $('body');
802 'top' : eleOffset.top + c.verticalOffset,
803 'left' : eleOffset.left + c.horizontalOffset
806 var _checkMouse = function(e)
809 var cal = $('#dp-popup')[0];
814 } else if (el == document) {
818 el = $(el).parent()[0];
822 this._checkMouse = _checkMouse;
824 c._closeCalendar(true);
826 'keydown.datepicker',
829 if (event.keyCode == 27) {
836 if (!c.rememberViewedMonth)
838 var selectedDate = this.getSelected()[0];
840 selectedDate = new Date(selectedDate);
841 this.setDisplayedMonth(selectedDate.getMonth(), selectedDate.getFullYear(), false);
851 // $('<a href="#" class="selecteee">aaa</a>'),
853 $('<div class="dp-nav-prev"></div>')
855 $('<a class="dp-nav-prev-year" href="#" title="' + $.dpText.TEXT_PREV_YEAR + '"><<</a>')
860 return c._displayNewMonth.call(c, this, 0, -1);
863 $('<a class="dp-nav-prev-month" href="#" title="' + $.dpText.TEXT_PREV_MONTH + '"><</a>')
868 return c._displayNewMonth.call(c, this, -1, 0);
872 $('<div class="dp-nav-next"></div>')
874 $('<a class="dp-nav-next-year" href="#" title="' + $.dpText.TEXT_NEXT_YEAR + '">>></a>')
879 return c._displayNewMonth.call(c, this, 0, 1);
882 $('<a class="dp-nav-next-month" href="#" title="' + $.dpText.TEXT_NEXT_MONTH + '">></a>')
887 return c._displayNewMonth.call(c, this, 1, 0);
891 $('<div class="dp-calendar"></div>')
896 var $pop = this.inline ? $('.dp-popup', this.context) : $('#dp-popup');
898 if (this.showYearNavigation == false) {
899 $('.dp-nav-prev-year, .dp-nav-next-year', c.context).css('display', 'none');
901 if (this.displayClose) {
903 $('<a href="#" id="dp-close">' + $.dpText.TEXT_CLOSE + '</a>')
916 $(this.ele).trigger('dpDisplayed', $pop);
919 if (this.verticalPosition == $.dpConst.POS_BOTTOM) {
920 $pop.css('top', eleOffset.top + $ele.height() - $pop.height() + c.verticalOffset);
922 if (this.horizontalPosition == $.dpConst.POS_RIGHT) {
923 $pop.css('left', eleOffset.left + $ele.width() - $pop.width() + c.horizontalOffset);
925 // $('.selectee', this.context).focus();
926 $(document).bind('mousedown.datepicker', this._checkMouse);
930 setRenderCallback : function(a)
932 if (a == null) return;
933 if (a && typeof(a) == 'function') {
936 this.renderCallback = this.renderCallback.concat(a);
938 cellRender : function ($td, thisDate, month, year) {
939 var c = this.dpController;
940 var d = new Date(thisDate.getTime());
942 // add our click handlers to deal with it when the days are clicked...
949 if (!$this.is('.disabled')) {
950 c.setSelected(d, !$this.is('.selected') || !c.selectMultiple, false, true);
951 if (c.closeOnSelect) {
952 // Focus the next input in the form…
953 if (c.settings.autoFocusNextInput) {
956 $(':input', ele.form).each(
976 if (c.isSelected(d)) {
977 $td.addClass('selected');
978 if (c.settings.selectWeek)
980 $td.parent().addClass('selectedWeek');
982 } else if (c.selectMultiple && c.numSelected == c.numSelectable) {
983 $td.addClass('unselectable');
987 _applyRenderCallbacks : function()
990 $('td', this.context).each(
993 for (var i=0; i<c.renderCallback.length; i++) {
995 c.renderCallback[i].apply(this, [$td, Date.fromString($td.data('datePickerDate')), c.displayedMonth, c.displayedYear]);
1001 // ele is the clicked button - only proceed if it doesn't have the class disabled...
1002 // m and y are -1, 0 or 1 depending which direction we want to go in...
1003 _displayNewMonth : function(ele, m, y)
1005 if (!$(ele).is('.disabled')) {
1006 this.setDisplayedMonth(this.displayedMonth + m, this.displayedYear + y, true);
1011 _rerenderCalendar : function()
1013 this._clearCalendar();
1014 this._renderCalendar();
1016 _renderCalendar : function()
1019 $('h2', this.context).html((new Date(this.displayedYear, this.displayedMonth, 1)).asString($.dpText.HEADER_FORMAT));
1021 // render the calendar...
1022 $('.dp-calendar', this.context).renderCalendar(
1027 month : this.displayedMonth,
1028 year : this.displayedYear,
1029 renderCallback : this.cellRender,
1030 dpController : this,
1031 hoverClass : this.hoverClass
1035 // update the status of the control buttons and disable dates before startDate or after endDate...
1036 // TODO: When should the year buttons be disabled? When you can't go forward a whole year from where you are or is that annoying?
1037 if (this.displayedYear == this.startDate.getFullYear() && this.displayedMonth == this.startDate.getMonth()) {
1038 $('.dp-nav-prev-year', this.context).addClass('disabled');
1039 $('.dp-nav-prev-month', this.context).addClass('disabled');
1040 $('.dp-calendar td.other-month', this.context).each(
1043 var $this = $(this);
1044 if (Number($this.text()) > 20) {
1045 $this.addClass('disabled');
1049 var d = this.startDate.getDate();
1050 $('.dp-calendar td.current-month', this.context).each(
1053 var $this = $(this);
1054 if (Number($this.text()) < d) {
1055 $this.addClass('disabled');
1060 $('.dp-nav-prev-year', this.context).removeClass('disabled');
1061 $('.dp-nav-prev-month', this.context).removeClass('disabled');
1062 var d = this.startDate.getDate();
1064 // check if the startDate is last month as we might need to add some disabled classes...
1065 var st = this.startDate.getTime();
1066 var sd = new Date(st);
1068 if (this.displayedYear == sd.getFullYear() && this.displayedMonth == sd.getMonth()) {
1069 $('.dp-calendar td.other-month', this.context).each(
1072 var $this = $(this);
1073 if (Date.fromString($this.data('datePickerDate')).getTime() < st) {
1074 $this.addClass('disabled');
1081 if (this.displayedYear == this.endDate.getFullYear() && this.displayedMonth == this.endDate.getMonth()) {
1082 $('.dp-nav-next-year', this.context).addClass('disabled');
1083 $('.dp-nav-next-month', this.context).addClass('disabled');
1084 $('.dp-calendar td.other-month', this.context).each(
1087 var $this = $(this);
1088 if (Number($this.text()) < 14) {
1089 $this.addClass('disabled');
1093 var d = this.endDate.getDate();
1094 $('.dp-calendar td.current-month', this.context).each(
1097 var $this = $(this);
1098 if (Number($this.text()) > d) {
1099 $this.addClass('disabled');
1104 $('.dp-nav-next-year', this.context).removeClass('disabled');
1105 $('.dp-nav-next-month', this.context).removeClass('disabled');
1106 var d = this.endDate.getDate();
1108 // check if the endDate is next month as we might need to add some disabled classes...
1109 var ed = new Date(this.endDate.getTime());
1111 if (this.displayedYear == ed.getFullYear() && this.displayedMonth == ed.getMonth()) {
1112 $('.dp-calendar td.other-month', this.context).each(
1115 var $this = $(this);
1116 var cellDay = Number($this.text());
1117 if (cellDay < 13 && cellDay > d) {
1118 $this.addClass('disabled');
1125 this._applyRenderCallbacks();
1127 _closeCalendar : function(programatic, ele)
1129 if (!ele || ele == this.ele)
1131 $(document).unbind('mousedown.datepicker');
1132 $(document).unbind('keydown.datepicker');
1133 this._clearCalendar();
1134 $('#dp-popup a').unbind();
1135 $('#dp-popup').empty().remove();
1137 $(this.ele).trigger('dpClosed', [this.getSelected()]);
1141 // empties the current dp-calendar div and makes sure that all events are unbound
1142 // and expandos removed to avoid memory leaks...
1143 _clearCalendar : function()
1146 $('.dp-calendar td', this.context).unbind();
1147 $('.dp-calendar', this.context).empty();
1154 SHOW_HEADER_NONE : 0,
1155 SHOW_HEADER_SHORT : 1,
1156 SHOW_HEADER_LONG : 2,
1161 DP_INTERNAL_FOCUS : 'dpInternalFocusTrigger'
1165 TEXT_PREV_YEAR : 'Previous year',
1166 TEXT_PREV_MONTH : 'Previous month',
1167 TEXT_NEXT_YEAR : 'Next year',
1168 TEXT_NEXT_MONTH : 'Next month',
1169 TEXT_CLOSE : 'Close',
1170 TEXT_CHOOSE_DATE : 'Choose date',
1171 HEADER_FORMAT : 'mmmm yyyy'
1174 $.dpVersion = '$Id$';
1176 $.fn.datePicker.defaults = {
1179 showHeader : $.dpConst.SHOW_HEADER_SHORT,
1180 startDate : undefined,
1181 endDate : undefined,
1183 renderCallback : null,
1184 createButton : true,
1185 showYearNavigation : true,
1186 closeOnSelect : true,
1187 displayClose : false,
1188 selectMultiple : false,
1189 numSelectable : Number.MAX_VALUE,
1191 rememberViewedMonth : true,
1193 verticalPosition : $.dpConst.POS_TOP,
1194 horizontalPosition : $.dpConst.POS_LEFT,
1196 horizontalOffset : 0,
1197 hoverClass : 'dp-hover',
1198 autoFocusNextInput : false
1201 function _getController(ele)
1203 if (ele._dpId) return $.event._dpCache[ele._dpId];
1207 // make it so that no error is thrown if bgIframe plugin isn't included (allows you to use conditional
1208 // comments to only include bgIframe where it is needed in IE without breaking this plugin).
1209 if ($.fn.bgIframe == undefined) {
1210 $.fn.bgIframe = function() {return this; };
1216 .bind('unload', function() {
1217 var els = $.event._dpCache || [];
1218 for (var i in els) {
1219 $(els[i].ele)._dpDestroy();