ui.calendar.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. /* jQuery Calendar v2.7
  2. Written by Marc Grabanski (m@marcgrabanski.com) and enhanced by Keith Wood (kbwood@iprimus.com.au).
  3. Copyright (c) 2007 Marc Grabanski (http://marcgrabanski.com/code/jquery-calendar)
  4. Dual licensed under the GPL (http://www.gnu.org/licenses/gpl-3.0.txt) and
  5. CC (http://creativecommons.org/licenses/by/3.0/) licenses. "Share or Remix it but please Attribute the authors."
  6. Date: 09-03-2007 */
  7. /* PopUp Calendar manager.
  8. Use the singleton instance of this class, popUpCal, to interact with the calendar.
  9. Settings for (groups of) calendars are maintained in an instance object
  10. (PopUpCalInstance), allowing multiple different settings on the same page. */
  11. function PopUpCal() {
  12. this._nextId = 0; // Next ID for a calendar instance
  13. this._inst = []; // List of instances indexed by ID
  14. this._curInst = null; // The current instance in use
  15. this._disabledInputs = []; // List of calendar inputs that have been disabled
  16. this._popUpShowing = false; // True if the popup calendar is showing , false if not
  17. this._inDialog = false; // True if showing within a "dialog", false if not
  18. this.regional = []; // Available regional settings, indexed by language code
  19. this.regional[''] = { // Default regional settings
  20. clearText: 'Clear', // Display text for clear link
  21. closeText: 'Close', // Display text for close link
  22. prevText: '<Prev', // Display text for previous month link
  23. nextText: 'Next>', // Display text for next month link
  24. currentText: 'Today', // Display text for current month link
  25. dayNames: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Names of days starting at Sunday
  26. monthNames: ['January','February','March','April','May','June',
  27. 'July','August','September','October','November','December'], // Names of months
  28. dateFormat: 'DMY/' // First three are day, month, year in the required order,
  29. // fourth (optional) is the separator, e.g. US would be 'MDY/', ISO would be 'YMD-'
  30. };
  31. this._defaults = { // Global defaults for all the calendar instances
  32. autoPopUp: 'focus', // 'focus' for popup on focus,
  33. // 'button' for trigger button, or 'both' for either
  34. defaultDate: null, // Used when field is blank: actual date,
  35. // +/-number for offset from today, null for today
  36. appendText: '', // Display text following the input box, e.g. showing the format
  37. buttonText: '...', // Text for trigger button
  38. buttonImage: '', // URL for trigger button image
  39. buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
  40. closeAtTop: true, // True to have the clear/close at the top,
  41. // false to have them at the bottom
  42. hideIfNoPrevNext: false, // True to hide next/previous month links
  43. // if not applicable, false to just disable them
  44. changeMonth: true, // True if month can be selected directly, false if only prev/next
  45. changeYear: true, // True if year can be selected directly, false if only prev/next
  46. yearRange: '-10:+10', // Range of years to display in drop-down,
  47. // either relative to current year (-nn:+nn) or absolute (nnnn:nnnn)
  48. firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
  49. changeFirstDay: true, // True to click on day name to change, false to remain as set
  50. showOtherMonths: false, // True to show dates in other months, false to leave blank
  51. minDate: null, // The earliest selectable date, or null for no limit
  52. maxDate: null, // The latest selectable date, or null for no limit
  53. speed: 'medium', // Speed of display/closure
  54. customDate: null, // Function that takes a date and returns an array with
  55. // [0] = true if selectable, false if not,
  56. // [1] = custom CSS class name(s) or '', e.g. popUpCal.noWeekends
  57. fieldSettings: null, // Function that takes an input field and
  58. // returns a set of custom settings for the calendar
  59. onSelect: null // Define a callback function when a date is selected
  60. };
  61. $.extend(this._defaults, this.regional['']);
  62. this._calendarDiv = $('<div id="calendar_div"></div>');
  63. $(document.body).append(this._calendarDiv);
  64. $(document.body).mousedown(this._checkExternalClick);
  65. }
  66. $.extend(PopUpCal.prototype, {
  67. /* Class name added to elements to indicate already configured with a calendar. */
  68. markerClassName: 'hasCalendar',
  69. /* Register a new calendar instance - with custom settings. */
  70. _register: function(inst) {
  71. var id = this._nextId++;
  72. this._inst[id] = inst;
  73. return id;
  74. },
  75. /* Retrieve a particular calendar instance based on its ID. */
  76. _getInst: function(id) {
  77. return this._inst[id] || id;
  78. },
  79. /* Override the default settings for all instances of the calendar.
  80. @param settings object - the new settings to use as defaults (anonymous object)
  81. @return void */
  82. setDefaults: function(settings) {
  83. extendRemove(this._defaults, settings || {});
  84. },
  85. /* Handle keystrokes. */
  86. _doKeyDown: function(e) {
  87. var inst = popUpCal._getInst(this._calId);
  88. if (popUpCal._popUpShowing) {
  89. switch (e.keyCode) {
  90. case 9: popUpCal.hideCalendar(inst, '');
  91. break; // hide on tab out
  92. case 13: popUpCal._selectDate(inst);
  93. break; // select the value on enter
  94. case 27: popUpCal.hideCalendar(inst, inst._get('speed'));
  95. break; // hide on escape
  96. case 33: popUpCal._adjustDate(inst, -1, (e.ctrlKey ? 'Y' : 'M'));
  97. break; // previous month/year on page up/+ ctrl
  98. case 34: popUpCal._adjustDate(inst, +1, (e.ctrlKey ? 'Y' : 'M'));
  99. break; // next month/year on page down/+ ctrl
  100. case 35: if (e.ctrlKey) popUpCal._clearDate(inst);
  101. break; // clear on ctrl+end
  102. case 36: if (e.ctrlKey) popUpCal._gotoToday(inst);
  103. break; // current on ctrl+home
  104. case 37: if (e.ctrlKey) popUpCal._adjustDate(inst, -1, 'D');
  105. break; // -1 day on ctrl+left
  106. case 38: if (e.ctrlKey) popUpCal._adjustDate(inst, -7, 'D');
  107. break; // -1 week on ctrl+up
  108. case 39: if (e.ctrlKey) popUpCal._adjustDate(inst, +1, 'D');
  109. break; // +1 day on ctrl+right
  110. case 40: if (e.ctrlKey) popUpCal._adjustDate(inst, +7, 'D');
  111. break; // +1 week on ctrl+down
  112. }
  113. }
  114. else if (e.keyCode == 36 && e.ctrlKey) { // display the calendar on ctrl+home
  115. popUpCal.showFor(this);
  116. }
  117. },
  118. /* Filter entered characters. */
  119. _doKeyPress: function(e) {
  120. var inst = popUpCal._getInst(this._calId);
  121. var chr = String.fromCharCode(e.charCode == undefined ? e.keyCode : e.charCode);
  122. return (chr < ' ' || chr == inst._get('dateFormat').charAt(3) ||
  123. (chr >= '0' && chr <= '9')); // only allow numbers and separator
  124. },
  125. /* Attach the calendar to an input field. */
  126. _connectCalendar: function(target, inst) {
  127. var input = $(target);
  128. if (this._hasClass(input, this.markerClassName)) {
  129. return;
  130. }
  131. var appendText = inst._get('appendText');
  132. if (appendText) {
  133. input.after('<span class="calendar_append">' + appendText + '</span>');
  134. }
  135. var autoPopUp = inst._get('autoPopUp');
  136. if (autoPopUp == 'focus' || autoPopUp == 'both') { // pop-up calendar when in the marked field
  137. input.focus(this.showFor);
  138. }
  139. if (autoPopUp == 'button' || autoPopUp == 'both') { // pop-up calendar when button clicked
  140. var buttonText = inst._get('buttonText');
  141. var buttonImage = inst._get('buttonImage');
  142. var buttonImageOnly = inst._get('buttonImageOnly');
  143. var trigger = $(buttonImageOnly ? '<img class="calendar_trigger" src="' +
  144. buttonImage + '" alt="' + buttonText + '" title="' + buttonText + '"/>' :
  145. '<button type="button" class="calendar_trigger">' + (buttonImage != '' ?
  146. '<img src="' + buttonImage + '" alt="' + buttonText + '" title="' + buttonText + '"/>' :
  147. buttonText) + '</button>');
  148. input.wrap('<span class="calendar_wrap"></span>').after(trigger);
  149. trigger.click(this.showFor);
  150. }
  151. input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress);
  152. input[0]._calId = inst._id;
  153. },
  154. /* Attach an inline calendar to a div. */
  155. _inlineCalendar: function(target, inst) {
  156. var input = $(target);
  157. if (this._hasClass(input, this.markerClassName)) {
  158. return;
  159. }
  160. input.addClass(this.markerClassName).append(inst._calendarDiv);
  161. input[0]._calId = inst._id;
  162. },
  163. /* Does this element have a particular class? */
  164. _hasClass: function(element, className) {
  165. var classes = element.attr('class');
  166. return (classes && classes.indexOf(className) > -1);
  167. },
  168. /* Pop-up the calendar in a "dialog" box.
  169. @param dateText string - the initial date to display (in the current format)
  170. @param onSelect function - the function(dateText) to call when a date is selected
  171. @param settings object - update the dialog calendar instance's settings (anonymous object)
  172. @param pos int[2] - coordinates for the dialog's position within the screen
  173. leave empty for default (screen centre)
  174. @return void */
  175. dialogCalendar: function(dateText, onSelect, settings, pos) {
  176. var inst = this._dialogInst; // internal instance
  177. if (!inst) {
  178. inst = this._dialogInst = new PopUpCalInstance({}, false);
  179. this._dialogInput = $('<input type="text" size="1" style="position: absolute; top: -100px;"/>');
  180. this._dialogInput.keydown(this._doKeyDown);
  181. $('body').append(this._dialogInput);
  182. this._dialogInput[0]._calId = inst._id;
  183. }
  184. extendRemove(inst._settings, settings || {});
  185. this._dialogInput.val(dateText);
  186. /* Cross Browser Positioning */
  187. if (self.innerHeight) { // all except Explorer
  188. windowWidth = self.innerWidth;
  189. windowHeight = self.innerHeight;
  190. } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
  191. windowWidth = document.documentElement.clientWidth;
  192. windowHeight = document.documentElement.clientHeight;
  193. } else if (document.body) { // other Explorers
  194. windowWidth = document.body.clientWidth;
  195. windowHeight = document.body.clientHeight;
  196. }
  197. this._pos = pos || // should use actual width/height below
  198. [(windowWidth / 2) - 100, (windowHeight / 2) - 100];
  199. // move input on screen for focus, but hidden behind dialog
  200. this._dialogInput.css('left', this._pos[0] + 'px').css('top', this._pos[1] + 'px');
  201. inst._settings.onSelect = onSelect;
  202. this._inDialog = true;
  203. this._calendarDiv.addClass('calendar_dialog');
  204. this.showFor(this._dialogInput[0]);
  205. if ($.blockUI) {
  206. $.blockUI(this._calendarDiv);
  207. }
  208. },
  209. /* Enable the input field(s) for entry.
  210. @param inputs element/object - single input field or jQuery collection of input fields
  211. @return void */
  212. enableFor: function(inputs) {
  213. inputs = (inputs.jquery ? inputs : $(inputs));
  214. inputs.each(function() {
  215. this.disabled = false;
  216. $('../button.calendar_trigger', this).each(function() { this.disabled = false; });
  217. $('../img.calendar_trigger', this).css({opacity:'1.0',cursor:''});
  218. var $this = this;
  219. popUpCal._disabledInputs = $.map(popUpCal._disabledInputs,
  220. function(value) { return (value == $this ? null : value); }); // delete entry
  221. });
  222. },
  223. /* Disable the input field(s) from entry.
  224. @param inputs element/object - single input field or jQuery collection of input fields
  225. @return void */
  226. disableFor: function(inputs) {
  227. inputs = (inputs.jquery ? inputs : $(inputs));
  228. inputs.each(function() {
  229. this.disabled = true;
  230. $('../button.calendar_trigger', this).each(function() { this.disabled = true; });
  231. $('../img.calendar_trigger', this).css({opacity:'0.5',cursor:'default'});
  232. var $this = this;
  233. popUpCal._disabledInputs = $.map(popUpCal._disabledInputs,
  234. function(value) { return (value == $this ? null : value); }); // delete entry
  235. popUpCal._disabledInputs[popUpCal._disabledInputs.length] = this;
  236. });
  237. },
  238. /* Update the settings for a calendar attached to an input field or division.
  239. @param control element - the input field or div/span attached to the calendar or
  240. string - the ID or other jQuery selector of the input field
  241. @param settings object - the new settings to update
  242. @return void */
  243. reconfigureFor: function(control, settings) {
  244. control = (typeof control == 'string' ? $(control)[0] : control);
  245. var inst = this._getInst(control._calId);
  246. if (inst) {
  247. extendRemove(inst._settings, settings || {});
  248. this._updateCalendar(inst);
  249. }
  250. },
  251. /* Set the date for a calendar attached to an input field or division.
  252. @param control element - the input field or div/span attached to the calendar
  253. @param date Date - the new date
  254. @return void */
  255. setDateFor: function(control, date) {
  256. var inst = this._getInst(control._calId);
  257. if (inst) {
  258. inst._setDate(date);
  259. }
  260. },
  261. /* Retrieve the date for a calendar attached to an input field or division.
  262. @param control element - the input field or div/span attached to the calendar
  263. @return Date - the current date */
  264. getDateFor: function(control) {
  265. var inst = this._getInst(control._calId);
  266. return (inst ? inst._getDate() : null);
  267. },
  268. /* Pop-up the calendar for a given input field.
  269. @param target element - the input field attached to the calendar
  270. @return void */
  271. showFor: function(target) {
  272. var input = (target.nodeName && target.nodeName.toLowerCase() == 'input' ? target : this);
  273. if (input.nodeName.toLowerCase() != 'input') { // find from button/image trigger
  274. input = $('input', input.parentNode)[0];
  275. }
  276. if (popUpCal._lastInput == input) { // already here
  277. return;
  278. }
  279. for (var i = 0; i < popUpCal._disabledInputs.length; i++) { // check not disabled
  280. if (popUpCal._disabledInputs[i] == input) {
  281. return;
  282. }
  283. }
  284. var inst = popUpCal._getInst(input._calId);
  285. var fieldSettings = inst._get('fieldSettings');
  286. extendRemove(inst._settings, (fieldSettings ? fieldSettings(input) : {}));
  287. popUpCal.hideCalendar(inst, '');
  288. popUpCal._lastInput = input;
  289. inst._setDateFromField(input);
  290. if (popUpCal._inDialog) { // hide cursor
  291. input.value = '';
  292. }
  293. if (!popUpCal._pos) { // position below input
  294. popUpCal._pos = popUpCal._findPos(input);
  295. popUpCal._pos[1] += input.offsetHeight;
  296. }
  297. inst._calendarDiv.css('position', (popUpCal._inDialog && $.blockUI ? 'static' : 'absolute')).
  298. css('left', popUpCal._pos[0] + 'px').css('top', popUpCal._pos[1] + 'px');
  299. popUpCal._pos = null;
  300. popUpCal._showCalendar(inst);
  301. },
  302. /* Construct and display the calendar. */
  303. _showCalendar: function(id) {
  304. var inst = this._getInst(id);
  305. popUpCal._updateCalendar(inst);
  306. if (!inst._inline) {
  307. var speed = inst._get('speed');
  308. inst._calendarDiv.show(speed, function() {
  309. popUpCal._popUpShowing = true;
  310. popUpCal._afterShow(inst);
  311. });
  312. if (speed == '') {
  313. popUpCal._popUpShowing = true;
  314. popUpCal._afterShow(inst);
  315. }
  316. if (inst._input[0].type != 'hidden') {
  317. inst._input[0].focus();
  318. }
  319. this._curInst = inst;
  320. }
  321. },
  322. /* Generate the calendar content. */
  323. _updateCalendar: function(inst) {
  324. inst._calendarDiv.empty().append(inst._generateCalendar());
  325. if (inst._input && inst._input[0].type != 'hidden') {
  326. inst._input[0].focus();
  327. }
  328. },
  329. /* Tidy up after displaying the calendar. */
  330. _afterShow: function(inst) {
  331. if ($.browser.msie) { // fix IE < 7 select problems
  332. $('#calendar_cover').css({width: inst._calendarDiv[0].offsetWidth + 4,
  333. height: inst._calendarDiv[0].offsetHeight + 4});
  334. }
  335. // re-position on screen if necessary
  336. var calDiv = inst._calendarDiv[0];
  337. var pos = popUpCal._findPos(inst._input[0]);
  338. // Get browser width and X value (IE6+, FF, Safari, Opera)
  339. if( typeof( window.innerWidth ) == 'number' ) {
  340. browserWidth = window.innerWidth;
  341. } else {
  342. browserWidth = document.documentElement.clientWidth;
  343. }
  344. if ( document.documentElement && (document.documentElement.scrollLeft)) {
  345. browserX = document.documentElement.scrollLeft;
  346. } else {
  347. browserX = document.body.scrollLeft;
  348. }
  349. // Reposition calendar if outside the browser window.
  350. if ((calDiv.offsetLeft + calDiv.offsetWidth) >
  351. (browserWidth + browserX) ) {
  352. inst._calendarDiv.css('left', (pos[0] + inst._input[0].offsetWidth - calDiv.offsetWidth) + 'px');
  353. }
  354. // Get browser height and Y value (IE6+, FF, Safari, Opera)
  355. if( typeof( window.innerHeight ) == 'number' ) {
  356. browserHeight = window.innerHeight;
  357. } else {
  358. browserHeight = document.documentElement.clientHeight;
  359. }
  360. if ( document.documentElement && (document.documentElement.scrollTop)) {
  361. browserTopY = document.documentElement.scrollTop;
  362. } else {
  363. browserTopY = document.body.scrollTop;
  364. }
  365. // Reposition calendar if outside the browser window.
  366. if ((calDiv.offsetTop + calDiv.offsetHeight) >
  367. (browserTopY + browserHeight) ) {
  368. inst._calendarDiv.css('top', (pos[1] - calDiv.offsetHeight) + 'px');
  369. }
  370. },
  371. /* Hide the calendar from view.
  372. @param id string/object - the ID of the current calendar instance,
  373. or the instance itself
  374. @param speed string - the speed at which to close the calendar
  375. @return void */
  376. hideCalendar: function(id, speed) {
  377. var inst = this._getInst(id);
  378. if (popUpCal._popUpShowing) {
  379. speed = (speed != null ? speed : inst._get('speed'));
  380. inst._calendarDiv.hide(speed, function() {
  381. popUpCal._tidyDialog(inst);
  382. });
  383. if (speed == '') {
  384. popUpCal._tidyDialog(inst);
  385. }
  386. popUpCal._popUpShowing = false;
  387. popUpCal._lastInput = null;
  388. inst._settings.prompt = null;
  389. if (popUpCal._inDialog) {
  390. popUpCal._dialogInput.css('position', 'absolute').
  391. css('left', '0px').css('top', '-100px');
  392. if ($.blockUI) {
  393. $.unblockUI();
  394. $('body').append(this._calendarDiv);
  395. }
  396. }
  397. popUpCal._inDialog = false;
  398. }
  399. popUpCal._curInst = null;
  400. },
  401. /* Tidy up after a dialog display. */
  402. _tidyDialog: function(inst) {
  403. inst._calendarDiv.removeClass('calendar_dialog');
  404. $('.calendar_prompt', inst._calendarDiv).remove();
  405. },
  406. /* Close calendar if clicked elsewhere. */
  407. _checkExternalClick: function(event) {
  408. if (!popUpCal._curInst) {
  409. return;
  410. }
  411. var target = $(event.target);
  412. if( (target.parents("#calendar_div").length == 0)
  413. && (target.attr('class') != 'calendar_trigger')
  414. && popUpCal._popUpShowing
  415. && !(popUpCal._inDialog && $.blockUI) )
  416. {
  417. popUpCal.hideCalendar(popUpCal._curInst, '');
  418. }
  419. },
  420. /* Adjust one of the date sub-fields. */
  421. _adjustDate: function(id, offset, period) {
  422. var inst = this._getInst(id);
  423. inst._adjustDate(offset, period);
  424. this._updateCalendar(inst);
  425. },
  426. /* Action for current link. */
  427. _gotoToday: function(id) {
  428. var date = new Date();
  429. var inst = this._getInst(id);
  430. inst._selectedDay = date.getDate();
  431. inst._selectedMonth = date.getMonth();
  432. inst._selectedYear = date.getFullYear();
  433. this._adjustDate(inst);
  434. },
  435. /* Action for selecting a new month/year. */
  436. _selectMonthYear: function(id, select, period) {
  437. var inst = this._getInst(id);
  438. inst._selectingMonthYear = false;
  439. inst[period == 'M' ? '_selectedMonth' : '_selectedYear'] =
  440. select.options[select.selectedIndex].value - 0;
  441. this._adjustDate(inst);
  442. },
  443. /* Restore input focus after not changing month/year. */
  444. _clickMonthYear: function(id) {
  445. var inst = this._getInst(id);
  446. if (inst._input && inst._selectingMonthYear && !$.browser.msie) {
  447. inst._input[0].focus();
  448. }
  449. inst._selectingMonthYear = !inst._selectingMonthYear;
  450. },
  451. /* Action for changing the first week day. */
  452. _changeFirstDay: function(id, a) {
  453. var inst = this._getInst(id);
  454. var dayNames = inst._get('dayNames');
  455. var value = a.firstChild.nodeValue;
  456. for (var i = 0; i < 7; i++) {
  457. if (dayNames[i] == value) {
  458. inst._settings.firstDay = i;
  459. break;
  460. }
  461. }
  462. this._updateCalendar(inst);
  463. },
  464. /* Action for selecting a day. */
  465. _selectDay: function(id, td) {
  466. var inst = this._getInst(id);
  467. inst._selectedDay = $("a", td).html();
  468. this._selectDate(id);
  469. },
  470. /* Erase the input field and hide the calendar. */
  471. _clearDate: function(id) {
  472. this._selectDate(id, '');
  473. },
  474. /* Update the input field with the selected date. */
  475. _selectDate: function(id, dateStr) {
  476. var inst = this._getInst(id);
  477. dateStr = (dateStr != null ? dateStr : inst._formatDate());
  478. if (inst._input) {
  479. inst._input.val(dateStr);
  480. }
  481. var onSelect = inst._get('onSelect');
  482. if (onSelect) {
  483. onSelect(dateStr, inst); // trigger custom callback
  484. }
  485. else {
  486. inst._input.trigger('change'); // fire the change event
  487. }
  488. if (inst._inline) {
  489. this._updateCalendar(inst);
  490. }
  491. else {
  492. this.hideCalendar(inst, inst._get('speed'));
  493. }
  494. },
  495. /* Set as customDate function to prevent selection of weekends.
  496. @param date Date - the date to customise
  497. @return [boolean, string] - is this date selectable?, what is its CSS class? */
  498. noWeekends: function(date) {
  499. var day = date.getDay();
  500. return [(day > 0 && day < 6), ''];
  501. },
  502. /* Find an object's position on the screen. */
  503. _findPos: function(obj) {
  504. while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
  505. obj = obj.nextSibling;
  506. }
  507. var curleft = curtop = 0;
  508. if (obj && obj.offsetParent) {
  509. curleft = obj.offsetLeft;
  510. curtop = obj.offsetTop;
  511. while (obj = obj.offsetParent) {
  512. var origcurleft = curleft;
  513. curleft += obj.offsetLeft;
  514. if (curleft < 0) {
  515. curleft = origcurleft;
  516. }
  517. curtop += obj.offsetTop;
  518. }
  519. }
  520. return [curleft,curtop];
  521. }
  522. });
  523. /* Individualised settings for calendars applied to one or more related inputs.
  524. Instances are managed and manipulated through the PopUpCal manager. */
  525. function PopUpCalInstance(settings, inline) {
  526. this._id = popUpCal._register(this);
  527. this._selectedDay = 0;
  528. this._selectedMonth = 0; // 0-11
  529. this._selectedYear = 0; // 4-digit year
  530. this._input = null; // The attached input field
  531. this._inline = inline; // True if showing inline, false if used in a popup
  532. this._calendarDiv = (!inline ? popUpCal._calendarDiv :
  533. $('<div id="calendar_div_' + this._id + '" class="calendar_inline"></div>'));
  534. // customise the calendar object - uses manager defaults if not overridden
  535. this._settings = extendRemove({}, settings || {}); // clone
  536. if (inline) {
  537. this._setDate(this._getDefaultDate());
  538. }
  539. }
  540. $.extend(PopUpCalInstance.prototype, {
  541. /* Get a setting value, defaulting if necessary. */
  542. _get: function(name) {
  543. return (this._settings[name] != null ? this._settings[name] : popUpCal._defaults[name]);
  544. },
  545. /* Parse existing date and initialise calendar. */
  546. _setDateFromField: function(input) {
  547. this._input = $(input);
  548. var dateFormat = this._get('dateFormat');
  549. var currentDate = this._input.val().split(dateFormat.charAt(3));
  550. if (currentDate.length == 3) {
  551. this._currentDay = parseInt(currentDate[dateFormat.indexOf('D')], 10);
  552. this._currentMonth = parseInt(currentDate[dateFormat.indexOf('M')], 10) - 1;
  553. this._currentYear = parseInt(currentDate[dateFormat.indexOf('Y')], 10);
  554. }
  555. else {
  556. var date = this._getDefaultDate();
  557. this._currentDay = date.getDate();
  558. this._currentMonth = date.getMonth();
  559. this._currentYear = date.getFullYear();
  560. }
  561. this._selectedDay = this._currentDay;
  562. this._selectedMonth = this._currentMonth;
  563. this._selectedYear = this._currentYear;
  564. this._adjustDate();
  565. },
  566. /* Retrieve the default date shown on opening. */
  567. _getDefaultDate: function() {
  568. var offsetDate = function(offset) {
  569. var date = new Date();
  570. date.setDate(date.getDate() + offset);
  571. return date;
  572. };
  573. var defaultDate = this._get('defaultDate');
  574. return (defaultDate == null ? new Date() :
  575. (typeof defaultDate == 'number' ? offsetDate(defaultDate) : defaultDate));
  576. },
  577. /* Set the date directly. */
  578. _setDate: function(date) {
  579. this._selectedDay = this._currentDay = date.getDate();
  580. this._selectedMonth = this._currentMonth = date.getMonth();
  581. this._selectedYear = this._currentYear = date.getFullYear();
  582. this._adjustDate();
  583. },
  584. /* Retrieve the date directly. */
  585. _getDate: function() {
  586. return new Date(this._currentYear, this._currentMonth, this._currentDay);
  587. },
  588. /* Generate the HTML for the current state of the calendar. */
  589. _generateCalendar: function() {
  590. var today = new Date();
  591. today = new Date(today.getFullYear(), today.getMonth(), today.getDate()); // clear time
  592. // build the calendar HTML
  593. var controls = '<div class="calendar_control">' +
  594. '<a class="calendar_clear" onclick="popUpCal._clearDate(' + this._id + ');">' +
  595. this._get('clearText') + '</a>' +
  596. '<a class="calendar_close" onclick="popUpCal.hideCalendar(' + this._id + ');">' +
  597. this._get('closeText') + '</a></div>';
  598. var prompt = this._get('prompt');
  599. var closeAtTop = this._get('closeAtTop');
  600. var hideIfNoPrevNext = this._get('hideIfNoPrevNext');
  601. // controls and links
  602. var html = (prompt ? '<div class="calendar_prompt">' + prompt + '</div>' : '') +
  603. (closeAtTop && !this._inline ? controls : '') + '<div class="calendar_links">' +
  604. (this._canAdjustMonth(-1) ? '<a class="calendar_prev" ' +
  605. 'onclick="popUpCal._adjustDate(' + this._id + ', -1, \'M\');">' + this._get('prevText') + '</a>' :
  606. (hideIfNoPrevNext ? '' : '<label class="calendar_prev">' + this._get('prevText') + '</label>')) +
  607. (this._isInRange(today) ? '<a class="calendar_current" ' +
  608. 'onclick="popUpCal._gotoToday(' + this._id + ');">' + this._get('currentText') + '</a>' : '') +
  609. (this._canAdjustMonth(+1) ? '<a class="calendar_next" ' +
  610. 'onclick="popUpCal._adjustDate(' + this._id + ', +1, \'M\');">' + this._get('nextText') + '</a>' :
  611. (hideIfNoPrevNext ? '' : '<label class="calendar_next">' + this._get('nextText') + '</label>')) +
  612. '</div><div class="calendar_header">';
  613. var minDate = this._get('minDate');
  614. var maxDate = this._get('maxDate');
  615. // month selection
  616. var monthNames = this._get('monthNames');
  617. if (!this._get('changeMonth')) {
  618. html += monthNames[this._selectedMonth] + '&nbsp;';
  619. }
  620. else {
  621. var inMinYear = (minDate && minDate.getFullYear() == this._selectedYear);
  622. var inMaxYear = (maxDate && maxDate.getFullYear() == this._selectedYear);
  623. html += '<select class="calendar_newMonth" ' +
  624. 'onchange="popUpCal._selectMonthYear(' + this._id + ', this, \'M\');" ' +
  625. 'onclick="popUpCal._clickMonthYear(' + this._id + ');">';
  626. for (var month = 0; month < 12; month++) {
  627. if ((!inMinYear || month >= minDate.getMonth()) &&
  628. (!inMaxYear || month <= maxDate.getMonth())) {
  629. html += '<option value="' + month + '"' +
  630. (month == this._selectedMonth ? ' selected="selected"' : '') +
  631. '>' + monthNames[month] + '</option>';
  632. }
  633. }
  634. html += '</select>';
  635. }
  636. // year selection
  637. if (!this._get('changeYear')) {
  638. html += this._selectedYear;
  639. }
  640. else {
  641. // determine range of years to display
  642. var years = this._get('yearRange').split(':');
  643. var year = 0;
  644. var endYear = 0;
  645. if (years.length != 2) {
  646. year = this._selectedYear - 10;
  647. endYear = this._selectedYear + 10;
  648. }
  649. else if (years[0].charAt(0) == '+' || years[0].charAt(0) == '-') {
  650. year = this._selectedYear + parseInt(years[0], 10);
  651. endYear = this._selectedYear + parseInt(years[1], 10);
  652. }
  653. else {
  654. year = parseInt(years[0], 10);
  655. endYear = parseInt(years[1], 10);
  656. }
  657. year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
  658. endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
  659. html += '<select class="calendar_newYear" onchange="popUpCal._selectMonthYear(' +
  660. this._id + ', this, \'Y\');" ' + 'onclick="popUpCal._clickMonthYear(' +
  661. this._id + ');">';
  662. for (; year <= endYear; year++) {
  663. html += '<option value="' + year + '"' +
  664. (year == this._selectedYear ? ' selected="selected"' : '') +
  665. '>' + year + '</option>';
  666. }
  667. html += '</select>';
  668. }
  669. html += '</div><table class="calendar" cellpadding="0" cellspacing="0"><thead>' +
  670. '<tr class="calendar_titleRow">';
  671. var firstDay = this._get('firstDay');
  672. var changeFirstDay = this._get('changeFirstDay');
  673. var dayNames = this._get('dayNames');
  674. for (var dow = 0; dow < 7; dow++) { // days of the week
  675. html += '<td>' + (!changeFirstDay ? '' : '<a onclick="popUpCal._changeFirstDay(' +
  676. this._id + ', this);">') + dayNames[(dow + firstDay) % 7] +
  677. (changeFirstDay ? '</a>' : '') + '</td>';
  678. }
  679. html += '</tr></thead><tbody>';
  680. var daysInMonth = this._getDaysInMonth(this._selectedYear, this._selectedMonth);
  681. this._selectedDay = Math.min(this._selectedDay, daysInMonth);
  682. var leadDays = (this._getFirstDayOfMonth(this._selectedYear, this._selectedMonth) - firstDay + 7) % 7;
  683. var currentDate = new Date(this._currentYear, this._currentMonth, this._currentDay);
  684. var selectedDate = new Date(this._selectedYear, this._selectedMonth, this._selectedDay);
  685. var printDate = new Date(this._selectedYear, this._selectedMonth, 1 - leadDays);
  686. var numRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
  687. var customDate = this._get('customDate');
  688. var showOtherMonths = this._get('showOtherMonths');
  689. for (var row = 0; row < numRows; row++) { // create calendar rows
  690. html += '<tr class="calendar_daysRow">';
  691. for (var dow = 0; dow < 7; dow++) { // create calendar days
  692. var customSettings = (customDate ? customDate(printDate) : [true, '']);
  693. var otherMonth = (printDate.getMonth() != this._selectedMonth);
  694. var unselectable = otherMonth || !customSettings[0] ||
  695. (minDate && printDate < minDate) || (maxDate && printDate > maxDate);
  696. html += '<td class="calendar_daysCell' +
  697. ((dow + firstDay + 6) % 7 >= 5 ? ' calendar_weekEndCell' : '') + // highlight weekends
  698. (otherMonth ? ' calendar_otherMonth' : '') + // highlight days from other months
  699. (printDate.getTime() == selectedDate.getTime() ? ' calendar_daysCellOver' : '') + // highlight selected day
  700. (unselectable ? ' calendar_unselectable' : '') + // highlight unselectable days
  701. (otherMonth && !showOtherMonths ? '' : ' ' + customSettings[1] + // highlight custom dates
  702. (printDate.getTime() == currentDate.getTime() ? ' calendar_currentDay' : // highlight current day
  703. (printDate.getTime() == today.getTime() ? ' calendar_today' : ''))) + '"' + // highlight today (if different)
  704. (unselectable ? '' : ' onmouseover="$(this).addClass(\'calendar_daysCellOver\');"' +
  705. ' onmouseout="$(this).removeClass(\'calendar_daysCellOver\');"' +
  706. ' onclick="popUpCal._selectDay(' + this._id + ', this);"') + '>' + // actions
  707. (otherMonth ? (showOtherMonths ? printDate.getDate() : '&nbsp;') : // display for other months
  708. (unselectable ? printDate.getDate() : '<a>' + printDate.getDate() + '</a>')) + '</td>'; // display for this month
  709. printDate.setDate(printDate.getDate() + 1);
  710. }
  711. html += '</tr>';
  712. }
  713. html += '</tbody></table>' + (!closeAtTop && !this._inline ? controls : '') +
  714. '<div style="clear: both;"></div>' + (!$.browser.msie ? '' :
  715. '<!--[if lte IE 6.5]><iframe src="javascript:false;" class="calendar_cover"></iframe><![endif]-->');
  716. return html;
  717. },
  718. /* Adjust one of the date sub-fields. */
  719. _adjustDate: function(offset, period) {
  720. var date = new Date(this._selectedYear + (period == 'Y' ? offset : 0),
  721. this._selectedMonth + (period == 'M' ? offset : 0),
  722. this._selectedDay + (period == 'D' ? offset : 0));
  723. // ensure it is within the bounds set
  724. var minDate = this._get('minDate');
  725. var maxDate = this._get('maxDate');
  726. date = (minDate && date < minDate ? minDate : date);
  727. date = (maxDate && date > maxDate ? maxDate : date);
  728. this._selectedDay = date.getDate();
  729. this._selectedMonth = date.getMonth();
  730. this._selectedYear = date.getFullYear();
  731. },
  732. /* Find the number of days in a given month. */
  733. _getDaysInMonth: function(year, month) {
  734. return 32 - new Date(year, month, 32).getDate();
  735. },
  736. /* Find the day of the week of the first of a month. */
  737. _getFirstDayOfMonth: function(year, month) {
  738. return new Date(year, month, 1).getDay();
  739. },
  740. /* Determines if we should allow a "next/prev" month display change. */
  741. _canAdjustMonth: function(offset) {
  742. var date = new Date(this._selectedYear, this._selectedMonth + offset, 1);
  743. if (offset < 0) {
  744. date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
  745. }
  746. return this._isInRange(date);
  747. },
  748. /* Is the given date in the accepted range? */
  749. _isInRange: function(date) {
  750. var minDate = this._get('minDate');
  751. var maxDate = this._get('maxDate');
  752. return ((!minDate || date >= minDate) && (!maxDate || date <= maxDate));
  753. },
  754. /* Format the given date for display. */
  755. _formatDate: function() {
  756. var day = this._currentDay = this._selectedDay;
  757. var month = this._currentMonth = this._selectedMonth;
  758. var year = this._currentYear = this._selectedYear;
  759. month++; // adjust javascript month
  760. var dateFormat = this._get('dateFormat');
  761. var dateString = '';
  762. for (var i = 0; i < 3; i++) {
  763. dateString += dateFormat.charAt(3) +
  764. (dateFormat.charAt(i) == 'D' ? (day < 10 ? '0' : '') + day :
  765. (dateFormat.charAt(i) == 'M' ? (month < 10 ? '0' : '') + month :
  766. (dateFormat.charAt(i) == 'Y' ? year : '?')));
  767. }
  768. return dateString.substring(dateFormat.charAt(3) ? 1 : 0);
  769. }
  770. });
  771. /* jQuery extend now ignores nulls! */
  772. function extendRemove(target, props) {
  773. $.extend(target, props);
  774. for (var name in props) {
  775. if (props[name] == null) {
  776. target[name] = null;
  777. }
  778. }
  779. return target;
  780. }
  781. /* Attach the calendar to a jQuery selection.
  782. @param settings object - the new settings to use for this calendar instance (anonymous)
  783. @return jQuery object - for chaining further calls */
  784. $.fn.calendar = function(settings) {
  785. return this.each(function() {
  786. // check for settings on the control itself - in namespace 'cal:'
  787. var inlineSettings = null;
  788. for (attrName in popUpCal._defaults) {
  789. var attrValue = this.getAttribute('cal:' + attrName);
  790. if (attrValue) {
  791. inlineSettings = inlineSettings || {};
  792. try {
  793. inlineSettings[attrName] = eval(attrValue);
  794. }
  795. catch (err) {
  796. inlineSettings[attrName] = attrValue;
  797. }
  798. }
  799. }
  800. var nodeName = this.nodeName.toLowerCase();
  801. if (nodeName == 'input') {
  802. var instSettings = (inlineSettings ? $.extend($.extend({}, settings || {}),
  803. inlineSettings || {}) : settings); // clone and customise
  804. var inst = (inst && !inlineSettings ? inst :
  805. new PopUpCalInstance(instSettings, false));
  806. popUpCal._connectCalendar(this, inst);
  807. }
  808. else if (nodeName == 'div' || nodeName == 'span') {
  809. var instSettings = $.extend($.extend({}, settings || {}),
  810. inlineSettings || {}); // clone and customise
  811. var inst = new PopUpCalInstance(instSettings, true);
  812. popUpCal._inlineCalendar(this, inst);
  813. }
  814. });
  815. };
  816. /* Initialise the calendar. */
  817. $(document).ready(function() {
  818. popUpCal = new PopUpCal(); // singleton instance
  819. });