Avail feature updated
[ninja.git] / application / media / js / jquery.datePicker.js
blob77a4da45dcb5456c3020e48aa1e0e1171dbcc51c
1 /**
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.
5 * .
6 * $Id$
7 **/
9 (function($){
11 $.fn.extend({
12 /**
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.
21 * @type jQuery
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.
29 * @example
30 * var testCallback = function($td, thisDate, month, year)
31 * {
32 * if ($td.is('.current-month') && thisDate.getDay() == 4) {
33 * var d = thisDate.getDate();
34 * $td.bind(
35 * 'click',
36 * function()
37 * {
38 * alert('You clicked on ' + d + '/' + (Number(month)+1) + '/' + year);
39 * }
40 * ).addClass('thursday');
41 * } else if (thisDate.getDay() == 5) {
42 * $td.html('Friday the ' + $td.html() + 'th');
43 * }
44 * }
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.
48 **/
49 renderCalendar : function(s)
51 var dc = function(a)
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++) {
61 var weekday = i%7;
62 var day = Date.dayNames[weekday];
63 headRow.append(
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'))
70 .attr(
72 'cellspacing':2
75 .addClass('jCalendar')
76 .append(
77 (s.showHeader != $.dpConst.SHOW_HEADER_NONE ?
78 $(dc('thead'))
79 .append(headRow)
81 dc('thead')
84 var tbody = $(dc('tbody'));
86 var today = (new Date()).zeroTime();
87 today.setHours(12);
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)
102 return function()
104 if (s.hoverClass) {
105 var $this = $(this);
106 if (!s.selectWeek) {
107 $this.addClass(s.hoverClass);
108 } else if (firstDayInBounds && !$this.is('.disabled')) {
109 $this.parent().addClass('activeWeekHover');
114 var unHover = function()
116 if (s.hoverClass) {
117 var $this = $(this);
118 $this.removeClass(s.hoverClass);
119 $this.parent().removeClass('activeWeekHover');
123 var w = 0;
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;
129 var d = $(dc('td'))
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)
138 r.append(d);
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);
147 tbody.append(r);
149 calendarTable.append(tbody);
151 return this.each(
152 function()
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
197 * @type jQuery
198 * @name datePicker
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);
215 return this.each(
216 function()
218 var $this = $(this);
219 var alreadyExists = true;
221 if (!this._dpId) {
222 this._dpId = $.guid++;
223 $.event._dpCache[this._dpId] = new DatePicker(this);
224 alreadyExists = false;
227 if (s.inline) {
228 s.createButton = false;
229 s.displayClose = false;
230 s.closeOnSelect = false;
231 $this.empty();
234 var controller = $.event._dpCache[this._dpId];
236 controller.init(s);
238 if (!alreadyExists && s.createButton) {
239 // create it!
240 controller.button = $('<a href="#" class="dp-choose-date" title="' + $.dpText.TEXT_CHOOSE_DATE + '">' + $.dpText.TEXT_CHOOSE_DATE + '</a>')
241 .bind(
242 'click',
243 function()
245 $this.dpDisplay(this);
246 this.blur();
247 return false;
250 $this.after(controller.button);
253 if (!alreadyExists && $this.is(':text')) {
254 $this
255 .bind(
256 'dateSelected',
257 function(e, selectedDate, $td)
259 this.value = selectedDate.asString();
261 ).bind(
262 'change',
263 function()
265 if (this.value == '') {
266 controller.clearSelected();
267 } else {
268 var d = Date.fromString(this.value);
269 if (d) {
270 controller.setSelected(d, true, true);
275 if (s.clickInput) {
276 $this.bind(
277 'click',
278 function()
280 // The change event doesn't happen until the input loses focus so we need to manually trigger it...
281 $this.trigger('change');
282 $this.dpDisplay();
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
301 * @type jQuery
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).
318 * @type jQuery
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).
335 * @type jQuery
336 * @name dpSetEndDate
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.
351 * @type Array
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]);
363 if (c) {
364 return c.getSelected();
366 return null;
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.
375 * @type jQuery
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.
396 * @type jQuery
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.
413 * @type jQuery
414 * @name dpDisplay
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.
430 * @type jQuery
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
439 * });
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
451 * @type jQuery
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.
469 * @type jQuery
470 * @name dpSetOffset
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.
485 * @type jQuery
486 * @name dpClose
487 * @cat plugins/datePicker
488 * @author Kelvin Luck (http://www.kelvinluck.com/)
490 * @example $('.date-pick')
491 * .datePicker()
492 * .bind(
493 * 'focus',
494 * function()
496 * $(this).dpDisplay();
498 * ).bind(
499 * 'blur',
500 * function()
502 * $(this).dpClose();
504 * );
506 dpClose : function()
508 return _w.call(this, '_closeCalendar', false, this[0]);
511 * Rerenders the date picker's current month (for use with inline calendars and renderCallbacks).
513 * @type jQuery
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)
534 return this.each(
535 function()
537 var c = _getController(this);
538 if (c) {
539 c[f](a1, a2, a3, a4);
545 function DatePicker(ele)
547 this.ele = ele;
549 // initial values...
550 this.displayedMonth = null;
551 this.displayedYear = null;
552 this.startDate = null;
553 this.endDate = 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;
565 this.button = null;
566 this.renderCallback = [];
567 this.selectedDates = {};
568 this.inline = null;
569 this.context = '#dp-popup';
570 this.settings = {};
572 $.extend(
573 DatePicker.prototype,
575 init : function(s)
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;
593 this.settings = s;
594 if (this.inline) {
595 this.context = this.ele;
596 this.display();
599 setStartDate : function(d)
601 if (d) {
602 if (d instanceof Date) {
603 this.startDate = d;
604 } else {
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)
615 if (d) {
616 if (d instanceof Date) {
617 this.endDate = d;
618 } else {
619 this.endDate = Date.fromString(d);
622 if (!this.endDate) {
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)
642 $e = $(this.ele);
643 $e[s ? 'addClass' : 'removeClass']('dp-disabled');
644 if (this.button) {
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) {
656 return;
658 var s = new Date(this.startDate.getTime());
659 s.setDate(1);
660 var e = new Date(this.endDate.getTime());
661 e.setDate(1);
663 var t;
664 if ((!m && !y) || (isNaN(m) && isNaN(y))) {
665 // no month or year passed - default to current month
666 t = new Date().zeroTime();
667 t.setDate(1);
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);
674 } else {
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()) {
680 t = s;
681 } else if (t.getTime() > e.getTime()) {
682 t = e;
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...
699 return;
701 var s = this.settings;
702 if (s.selectWeek)
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...
707 return;
710 if (v == this.isSelected(d)) // this date is already un/selected
712 return;
714 if (this.selectMultiple == false) {
715 this.clearSelected();
716 } else if (v && this.numSelected == this.numSelectable) {
717 // can't select any more dates...
718 return;
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');
726 var $td;
727 $(selectorString, this.context).each(
728 function()
730 if ($(this).data('datePickerDate') == d.asString()) {
731 $td = $(this);
732 if (s.selectWeek)
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');
742 if (dispatchEvents)
744 var s = this.isSelected(d);
745 $e = $(this.ele);
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()
757 var r = [];
758 for(var s in this.selectedDates) {
759 if (this.selectedDates[s] == true) {
760 r.push(Date.fromString(s));
763 return r;
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;
776 var c = this;
777 var $ele = $(eleAlignTo);
778 var eleOffset = $ele.offset();
780 var $createIn;
781 var attrs;
782 var attrsCalendarHolder;
783 var cssRules;
785 if (c.inline) {
786 $createIn = $(this.ele);
787 attrs = {
788 'id' : 'calendar-' + this.ele._dpId,
789 'class' : 'dp-popup dp-popup-inline'
792 $('.dp-popup', $createIn).remove();
793 cssRules = {
795 } else {
796 $createIn = $('body');
797 attrs = {
798 'id' : 'dp-popup',
799 'class' : 'dp-popup'
801 cssRules = {
802 'top' : eleOffset.top + c.verticalOffset,
803 'left' : eleOffset.left + c.horizontalOffset
806 var _checkMouse = function(e)
808 var el = e.target;
809 var cal = $('#dp-popup')[0];
811 while (true){
812 if (el == cal) {
813 return true;
814 } else if (el == document) {
815 c._closeCalendar();
816 return false;
817 } else {
818 el = $(el).parent()[0];
822 this._checkMouse = _checkMouse;
824 c._closeCalendar(true);
825 $(document).bind(
826 'keydown.datepicker',
827 function(event)
829 if (event.keyCode == 27) {
830 c._closeCalendar();
836 if (!c.rememberViewedMonth)
838 var selectedDate = this.getSelected()[0];
839 if (selectedDate) {
840 selectedDate = new Date(selectedDate);
841 this.setDisplayedMonth(selectedDate.getMonth(), selectedDate.getFullYear(), false);
845 $createIn
846 .append(
847 $('<div></div>')
848 .attr(attrs)
849 .css(cssRules)
850 .append(
851 // $('<a href="#" class="selecteee">aaa</a>'),
852 $('<h2></h2>'),
853 $('<div class="dp-nav-prev"></div>')
854 .append(
855 $('<a class="dp-nav-prev-year" href="#" title="' + $.dpText.TEXT_PREV_YEAR + '">&lt;&lt;</a>')
856 .bind(
857 'click',
858 function()
860 return c._displayNewMonth.call(c, this, 0, -1);
863 $('<a class="dp-nav-prev-month" href="#" title="' + $.dpText.TEXT_PREV_MONTH + '">&lt;</a>')
864 .bind(
865 'click',
866 function()
868 return c._displayNewMonth.call(c, this, -1, 0);
872 $('<div class="dp-nav-next"></div>')
873 .append(
874 $('<a class="dp-nav-next-year" href="#" title="' + $.dpText.TEXT_NEXT_YEAR + '">&gt;&gt;</a>')
875 .bind(
876 'click',
877 function()
879 return c._displayNewMonth.call(c, this, 0, 1);
882 $('<a class="dp-nav-next-month" href="#" title="' + $.dpText.TEXT_NEXT_MONTH + '">&gt;</a>')
883 .bind(
884 'click',
885 function()
887 return c._displayNewMonth.call(c, this, 1, 0);
891 $('<div class="dp-calendar"></div>')
893 .bgIframe()
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) {
902 $pop.append(
903 $('<a href="#" id="dp-close">' + $.dpText.TEXT_CLOSE + '</a>')
904 .bind(
905 'click',
906 function()
908 c._closeCalendar();
909 return false;
914 c._renderCalendar();
916 $(this.ele).trigger('dpDisplayed', $pop);
918 if (!c.inline) {
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') {
934 a = [a];
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...
944 $td.bind(
945 'click',
946 function()
948 var $this = $(this);
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) {
954 var ele = c.ele;
955 var found = false;
956 $(':input', ele.form).each(
957 function()
959 if (found) {
960 $(this).focus();
961 return false;
963 if (this == ele) {
964 found = true;
968 } else {
969 c.ele.focus();
971 c._closeCalendar();
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()
989 var c = this;
990 $('td', this.context).each(
991 function()
993 for (var i=0; i<c.renderCallback.length; i++) {
994 $td = $(this);
995 c.renderCallback[i].apply(this, [$td, Date.fromString($td.data('datePickerDate')), c.displayedMonth, c.displayedYear]);
999 return;
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);
1008 ele.blur();
1009 return false;
1011 _rerenderCalendar : function()
1013 this._clearCalendar();
1014 this._renderCalendar();
1016 _renderCalendar : function()
1018 // set the title...
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(
1023 $.extend(
1025 this.settings,
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(
1041 function()
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(
1051 function()
1053 var $this = $(this);
1054 if (Number($this.text()) < d) {
1055 $this.addClass('disabled');
1059 } else {
1060 $('.dp-nav-prev-year', this.context).removeClass('disabled');
1061 $('.dp-nav-prev-month', this.context).removeClass('disabled');
1062 var d = this.startDate.getDate();
1063 if (d > 20) {
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);
1067 sd.addMonths(1);
1068 if (this.displayedYear == sd.getFullYear() && this.displayedMonth == sd.getMonth()) {
1069 $('.dp-calendar td.other-month', this.context).each(
1070 function()
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(
1085 function()
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(
1095 function()
1097 var $this = $(this);
1098 if (Number($this.text()) > d) {
1099 $this.addClass('disabled');
1103 } else {
1104 $('.dp-nav-next-year', this.context).removeClass('disabled');
1105 $('.dp-nav-next-month', this.context).removeClass('disabled');
1106 var d = this.endDate.getDate();
1107 if (d < 13) {
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());
1110 ed.addMonths(-1);
1111 if (this.displayedYear == ed.getFullYear() && this.displayedMonth == ed.getMonth()) {
1112 $('.dp-calendar td.other-month', this.context).each(
1113 function()
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();
1136 if (!programatic) {
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()
1145 // TODO.
1146 $('.dp-calendar td', this.context).unbind();
1147 $('.dp-calendar', this.context).empty();
1152 // static constants
1153 $.dpConst = {
1154 SHOW_HEADER_NONE : 0,
1155 SHOW_HEADER_SHORT : 1,
1156 SHOW_HEADER_LONG : 2,
1157 POS_TOP : 0,
1158 POS_BOTTOM : 1,
1159 POS_LEFT : 0,
1160 POS_RIGHT : 1,
1161 DP_INTERNAL_FOCUS : 'dpInternalFocusTrigger'
1163 // localisable text
1164 $.dpText = {
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'
1173 // version
1174 $.dpVersion = '$Id$';
1176 $.fn.datePicker.defaults = {
1177 month : undefined,
1178 year : undefined,
1179 showHeader : $.dpConst.SHOW_HEADER_SHORT,
1180 startDate : undefined,
1181 endDate : undefined,
1182 inline : false,
1183 renderCallback : null,
1184 createButton : true,
1185 showYearNavigation : true,
1186 closeOnSelect : true,
1187 displayClose : false,
1188 selectMultiple : false,
1189 numSelectable : Number.MAX_VALUE,
1190 clickInput : false,
1191 rememberViewedMonth : true,
1192 selectWeek : false,
1193 verticalPosition : $.dpConst.POS_TOP,
1194 horizontalPosition : $.dpConst.POS_LEFT,
1195 verticalOffset : 0,
1196 horizontalOffset : 0,
1197 hoverClass : 'dp-hover',
1198 autoFocusNextInput : false
1201 function _getController(ele)
1203 if (ele._dpId) return $.event._dpCache[ele._dpId];
1204 return false;
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; };
1214 // clean-up
1215 $(window)
1216 .bind('unload', function() {
1217 var els = $.event._dpCache || [];
1218 for (var i in els) {
1219 $(els[i].ele)._dpDestroy();
1224 })(jQuery);