You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2035 lines
56 KiB

  1. /*!
  2. * Datepicker for Bootstrap v1.8.0 (https://github.com/uxsolutions/bootstrap-datepicker)
  3. *
  4. * Licensed under the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0)
  5. */
  6. (function(factory){
  7. if (typeof define === 'function' && define.amd) {
  8. define(['jquery'], factory);
  9. } else if (typeof exports === 'object') {
  10. factory(require('jquery'));
  11. } else {
  12. factory(jQuery);
  13. }
  14. }(function($, undefined){
  15. function UTCDate(){
  16. return new Date(Date.UTC.apply(Date, arguments));
  17. }
  18. function UTCToday(){
  19. var today = new Date();
  20. return UTCDate(today.getFullYear(), today.getMonth(), today.getDate());
  21. }
  22. function isUTCEquals(date1, date2) {
  23. return (
  24. date1.getUTCFullYear() === date2.getUTCFullYear() &&
  25. date1.getUTCMonth() === date2.getUTCMonth() &&
  26. date1.getUTCDate() === date2.getUTCDate()
  27. );
  28. }
  29. function alias(method, deprecationMsg){
  30. return function(){
  31. if (deprecationMsg !== undefined) {
  32. $.fn.datepicker.deprecated(deprecationMsg);
  33. }
  34. return this[method].apply(this, arguments);
  35. };
  36. }
  37. function isValidDate(d) {
  38. return d && !isNaN(d.getTime());
  39. }
  40. var DateArray = (function(){
  41. var extras = {
  42. get: function(i){
  43. return this.slice(i)[0];
  44. },
  45. contains: function(d){
  46. // Array.indexOf is not cross-browser;
  47. // $.inArray doesn't work with Dates
  48. var val = d && d.valueOf();
  49. for (var i=0, l=this.length; i < l; i++)
  50. // Use date arithmetic to allow dates with different times to match
  51. if (0 <= this[i].valueOf() - val && this[i].valueOf() - val < 1000*60*60*24)
  52. return i;
  53. return -1;
  54. },
  55. remove: function(i){
  56. this.splice(i,1);
  57. },
  58. replace: function(new_array){
  59. if (!new_array)
  60. return;
  61. if (!$.isArray(new_array))
  62. new_array = [new_array];
  63. this.clear();
  64. this.push.apply(this, new_array);
  65. },
  66. clear: function(){
  67. this.length = 0;
  68. },
  69. copy: function(){
  70. var a = new DateArray();
  71. a.replace(this);
  72. return a;
  73. }
  74. };
  75. return function(){
  76. var a = [];
  77. a.push.apply(a, arguments);
  78. $.extend(a, extras);
  79. return a;
  80. };
  81. })();
  82. // Picker object
  83. var Datepicker = function(element, options){
  84. $.data(element, 'datepicker', this);
  85. this._process_options(options);
  86. this.dates = new DateArray();
  87. this.viewDate = this.o.defaultViewDate;
  88. this.focusDate = null;
  89. this.element = $(element);
  90. this.isInput = this.element.is('input');
  91. this.inputField = this.isInput ? this.element : this.element.find('input');
  92. this.component = this.element.hasClass('date') ? this.element.find('.add-on, .input-group-addon, .btn') : false;
  93. if (this.component && this.component.length === 0)
  94. this.component = false;
  95. this.isInline = !this.component && this.element.is('div');
  96. this.picker = $(DPGlobal.template);
  97. // Checking templates and inserting
  98. if (this._check_template(this.o.templates.leftArrow)) {
  99. this.picker.find('.prev').html(this.o.templates.leftArrow);
  100. }
  101. if (this._check_template(this.o.templates.rightArrow)) {
  102. this.picker.find('.next').html(this.o.templates.rightArrow);
  103. }
  104. this._buildEvents();
  105. this._attachEvents();
  106. if (this.isInline){
  107. this.picker.addClass('datepicker-inline').appendTo(this.element);
  108. }
  109. else {
  110. this.picker.addClass('datepicker-dropdown dropdown-menu');
  111. }
  112. if (this.o.rtl){
  113. this.picker.addClass('datepicker-rtl');
  114. }
  115. if (this.o.calendarWeeks) {
  116. this.picker.find('.datepicker-days .datepicker-switch, thead .datepicker-title, tfoot .today, tfoot .clear')
  117. .attr('colspan', function(i, val){
  118. return Number(val) + 1;
  119. });
  120. }
  121. this._process_options({
  122. startDate: this._o.startDate,
  123. endDate: this._o.endDate,
  124. daysOfWeekDisabled: this.o.daysOfWeekDisabled,
  125. daysOfWeekHighlighted: this.o.daysOfWeekHighlighted,
  126. datesDisabled: this.o.datesDisabled
  127. });
  128. this._allow_update = false;
  129. this.setViewMode(this.o.startView);
  130. this._allow_update = true;
  131. this.fillDow();
  132. this.fillMonths();
  133. this.update();
  134. if (this.isInline){
  135. this.show();
  136. }
  137. };
  138. Datepicker.prototype = {
  139. constructor: Datepicker,
  140. _resolveViewName: function(view){
  141. $.each(DPGlobal.viewModes, function(i, viewMode){
  142. if (view === i || $.inArray(view, viewMode.names) !== -1){
  143. view = i;
  144. return false;
  145. }
  146. });
  147. return view;
  148. },
  149. _resolveDaysOfWeek: function(daysOfWeek){
  150. if (!$.isArray(daysOfWeek))
  151. daysOfWeek = daysOfWeek.split(/[,\s]*/);
  152. return $.map(daysOfWeek, Number);
  153. },
  154. _check_template: function(tmp){
  155. try {
  156. // If empty
  157. if (tmp === undefined || tmp === "") {
  158. return false;
  159. }
  160. // If no html, everything ok
  161. if ((tmp.match(/[<>]/g) || []).length <= 0) {
  162. return true;
  163. }
  164. // Checking if html is fine
  165. var jDom = $(tmp);
  166. return jDom.length > 0;
  167. }
  168. catch (ex) {
  169. return false;
  170. }
  171. },
  172. _process_options: function(opts){
  173. // Store raw options for reference
  174. this._o = $.extend({}, this._o, opts);
  175. // Processed options
  176. var o = this.o = $.extend({}, this._o);
  177. // Check if "de-DE" style date is available, if not language should
  178. // fallback to 2 letter code eg "de"
  179. var lang = o.language;
  180. if (!dates[lang]){
  181. lang = lang.split('-')[0];
  182. if (!dates[lang])
  183. lang = defaults.language;
  184. }
  185. o.language = lang;
  186. // Retrieve view index from any aliases
  187. o.startView = this._resolveViewName(o.startView);
  188. o.minViewMode = this._resolveViewName(o.minViewMode);
  189. o.maxViewMode = this._resolveViewName(o.maxViewMode);
  190. // Check view is between min and max
  191. o.startView = Math.max(this.o.minViewMode, Math.min(this.o.maxViewMode, o.startView));
  192. // true, false, or Number > 0
  193. if (o.multidate !== true){
  194. o.multidate = Number(o.multidate) || false;
  195. if (o.multidate !== false)
  196. o.multidate = Math.max(0, o.multidate);
  197. }
  198. o.multidateSeparator = String(o.multidateSeparator);
  199. o.weekStart %= 7;
  200. o.weekEnd = (o.weekStart + 6) % 7;
  201. var format = DPGlobal.parseFormat(o.format);
  202. if (o.startDate !== -Infinity){
  203. if (!!o.startDate){
  204. if (o.startDate instanceof Date)
  205. o.startDate = this._local_to_utc(this._zero_time(o.startDate));
  206. else
  207. o.startDate = DPGlobal.parseDate(o.startDate, format, o.language, o.assumeNearbyYear);
  208. }
  209. else {
  210. o.startDate = -Infinity;
  211. }
  212. }
  213. if (o.endDate !== Infinity){
  214. if (!!o.endDate){
  215. if (o.endDate instanceof Date)
  216. o.endDate = this._local_to_utc(this._zero_time(o.endDate));
  217. else
  218. o.endDate = DPGlobal.parseDate(o.endDate, format, o.language, o.assumeNearbyYear);
  219. }
  220. else {
  221. o.endDate = Infinity;
  222. }
  223. }
  224. o.daysOfWeekDisabled = this._resolveDaysOfWeek(o.daysOfWeekDisabled||[]);
  225. o.daysOfWeekHighlighted = this._resolveDaysOfWeek(o.daysOfWeekHighlighted||[]);
  226. o.datesDisabled = o.datesDisabled||[];
  227. if (!$.isArray(o.datesDisabled)) {
  228. o.datesDisabled = o.datesDisabled.split(',');
  229. }
  230. o.datesDisabled = $.map(o.datesDisabled, function(d){
  231. return DPGlobal.parseDate(d, format, o.language, o.assumeNearbyYear);
  232. });
  233. var plc = String(o.orientation).toLowerCase().split(/\s+/g),
  234. _plc = o.orientation.toLowerCase();
  235. plc = $.grep(plc, function(word){
  236. return /^auto|left|right|top|bottom$/.test(word);
  237. });
  238. o.orientation = {x: 'auto', y: 'auto'};
  239. if (!_plc || _plc === 'auto')
  240. ; // no action
  241. else if (plc.length === 1){
  242. switch (plc[0]){
  243. case 'top':
  244. case 'bottom':
  245. o.orientation.y = plc[0];
  246. break;
  247. case 'left':
  248. case 'right':
  249. o.orientation.x = plc[0];
  250. break;
  251. }
  252. }
  253. else {
  254. _plc = $.grep(plc, function(word){
  255. return /^left|right$/.test(word);
  256. });
  257. o.orientation.x = _plc[0] || 'auto';
  258. _plc = $.grep(plc, function(word){
  259. return /^top|bottom$/.test(word);
  260. });
  261. o.orientation.y = _plc[0] || 'auto';
  262. }
  263. if (o.defaultViewDate instanceof Date || typeof o.defaultViewDate === 'string') {
  264. o.defaultViewDate = DPGlobal.parseDate(o.defaultViewDate, format, o.language, o.assumeNearbyYear);
  265. } else if (o.defaultViewDate) {
  266. var year = o.defaultViewDate.year || new Date().getFullYear();
  267. var month = o.defaultViewDate.month || 0;
  268. var day = o.defaultViewDate.day || 1;
  269. o.defaultViewDate = UTCDate(year, month, day);
  270. } else {
  271. o.defaultViewDate = UTCToday();
  272. }
  273. },
  274. _events: [],
  275. _secondaryEvents: [],
  276. _applyEvents: function(evs){
  277. for (var i=0, el, ch, ev; i < evs.length; i++){
  278. el = evs[i][0];
  279. if (evs[i].length === 2){
  280. ch = undefined;
  281. ev = evs[i][1];
  282. } else if (evs[i].length === 3){
  283. ch = evs[i][1];
  284. ev = evs[i][2];
  285. }
  286. el.on(ev, ch);
  287. }
  288. },
  289. _unapplyEvents: function(evs){
  290. for (var i=0, el, ev, ch; i < evs.length; i++){
  291. el = evs[i][0];
  292. if (evs[i].length === 2){
  293. ch = undefined;
  294. ev = evs[i][1];
  295. } else if (evs[i].length === 3){
  296. ch = evs[i][1];
  297. ev = evs[i][2];
  298. }
  299. el.off(ev, ch);
  300. }
  301. },
  302. _buildEvents: function(){
  303. var events = {
  304. keyup: $.proxy(function(e){
  305. if ($.inArray(e.keyCode, [27, 37, 39, 38, 40, 32, 13, 9]) === -1)
  306. this.update();
  307. }, this),
  308. keydown: $.proxy(this.keydown, this),
  309. paste: $.proxy(this.paste, this)
  310. };
  311. if (this.o.showOnFocus === true) {
  312. events.focus = $.proxy(this.show, this);
  313. }
  314. if (this.isInput) { // single input
  315. this._events = [
  316. [this.element, events]
  317. ];
  318. }
  319. // component: input + button
  320. else if (this.component && this.inputField.length) {
  321. this._events = [
  322. // For components that are not readonly, allow keyboard nav
  323. [this.inputField, events],
  324. [this.component, {
  325. click: $.proxy(this.show, this)
  326. }]
  327. ];
  328. }
  329. else {
  330. this._events = [
  331. [this.element, {
  332. click: $.proxy(this.show, this),
  333. keydown: $.proxy(this.keydown, this)
  334. }]
  335. ];
  336. }
  337. this._events.push(
  338. // Component: listen for blur on element descendants
  339. [this.element, '*', {
  340. blur: $.proxy(function(e){
  341. this._focused_from = e.target;
  342. }, this)
  343. }],
  344. // Input: listen for blur on element
  345. [this.element, {
  346. blur: $.proxy(function(e){
  347. this._focused_from = e.target;
  348. }, this)
  349. }]
  350. );
  351. if (this.o.immediateUpdates) {
  352. // Trigger input updates immediately on changed year/month
  353. this._events.push([this.element, {
  354. 'changeYear changeMonth': $.proxy(function(e){
  355. this.update(e.date);
  356. }, this)
  357. }]);
  358. }
  359. this._secondaryEvents = [
  360. [this.picker, {
  361. click: $.proxy(this.click, this)
  362. }],
  363. [this.picker, '.prev, .next', {
  364. click: $.proxy(this.navArrowsClick, this)
  365. }],
  366. [this.picker, '.day:not(.disabled)', {
  367. click: $.proxy(this.dayCellClick, this)
  368. }],
  369. [$(window), {
  370. resize: $.proxy(this.place, this)
  371. }],
  372. [$(document), {
  373. 'mousedown touchstart': $.proxy(function(e){
  374. // Clicked outside the datepicker, hide it
  375. if (!(
  376. this.element.is(e.target) ||
  377. this.element.find(e.target).length ||
  378. this.picker.is(e.target) ||
  379. this.picker.find(e.target).length ||
  380. this.isInline
  381. )){
  382. this.hide();
  383. }
  384. }, this)
  385. }]
  386. ];
  387. },
  388. _attachEvents: function(){
  389. this._detachEvents();
  390. this._applyEvents(this._events);
  391. },
  392. _detachEvents: function(){
  393. this._unapplyEvents(this._events);
  394. },
  395. _attachSecondaryEvents: function(){
  396. this._detachSecondaryEvents();
  397. this._applyEvents(this._secondaryEvents);
  398. },
  399. _detachSecondaryEvents: function(){
  400. this._unapplyEvents(this._secondaryEvents);
  401. },
  402. _trigger: function(event, altdate){
  403. var date = altdate || this.dates.get(-1),
  404. local_date = this._utc_to_local(date);
  405. this.element.trigger({
  406. type: event,
  407. date: local_date,
  408. viewMode: this.viewMode,
  409. dates: $.map(this.dates, this._utc_to_local),
  410. format: $.proxy(function(ix, format){
  411. if (arguments.length === 0){
  412. ix = this.dates.length - 1;
  413. format = this.o.format;
  414. } else if (typeof ix === 'string'){
  415. format = ix;
  416. ix = this.dates.length - 1;
  417. }
  418. format = format || this.o.format;
  419. var date = this.dates.get(ix);
  420. return DPGlobal.formatDate(date, format, this.o.language);
  421. }, this)
  422. });
  423. },
  424. show: function(){
  425. if (this.inputField.prop('disabled') || (this.inputField.prop('readonly') && this.o.enableOnReadonly === false))
  426. return;
  427. if (!this.isInline)
  428. this.picker.appendTo(this.o.container);
  429. this.place();
  430. this.picker.show();
  431. this._attachSecondaryEvents();
  432. this._trigger('show');
  433. if ((window.navigator.msMaxTouchPoints || 'ontouchstart' in document) && this.o.disableTouchKeyboard) {
  434. $(this.element).blur();
  435. }
  436. return this;
  437. },
  438. hide: function(){
  439. if (this.isInline || !this.picker.is(':visible'))
  440. return this;
  441. this.focusDate = null;
  442. this.picker.hide().detach();
  443. this._detachSecondaryEvents();
  444. this.setViewMode(this.o.startView);
  445. if (this.o.forceParse && this.inputField.val())
  446. this.setValue();
  447. this._trigger('hide');
  448. return this;
  449. },
  450. destroy: function(){
  451. this.hide();
  452. this._detachEvents();
  453. this._detachSecondaryEvents();
  454. this.picker.remove();
  455. delete this.element.data().datepicker;
  456. if (!this.isInput){
  457. delete this.element.data().date;
  458. }
  459. return this;
  460. },
  461. paste: function(e){
  462. var dateString;
  463. if (e.originalEvent.clipboardData && e.originalEvent.clipboardData.types
  464. && $.inArray('text/plain', e.originalEvent.clipboardData.types) !== -1) {
  465. dateString = e.originalEvent.clipboardData.getData('text/plain');
  466. } else if (window.clipboardData) {
  467. dateString = window.clipboardData.getData('Text');
  468. } else {
  469. return;
  470. }
  471. this.setDate(dateString);
  472. this.update();
  473. e.preventDefault();
  474. },
  475. _utc_to_local: function(utc){
  476. if (!utc) {
  477. return utc;
  478. }
  479. var local = new Date(utc.getTime() + (utc.getTimezoneOffset() * 60000));
  480. if (local.getTimezoneOffset() !== utc.getTimezoneOffset()) {
  481. local = new Date(utc.getTime() + (local.getTimezoneOffset() * 60000));
  482. }
  483. return local;
  484. },
  485. _local_to_utc: function(local){
  486. return local && new Date(local.getTime() - (local.getTimezoneOffset()*60000));
  487. },
  488. _zero_time: function(local){
  489. return local && new Date(local.getFullYear(), local.getMonth(), local.getDate());
  490. },
  491. _zero_utc_time: function(utc){
  492. return utc && UTCDate(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate());
  493. },
  494. getDates: function(){
  495. return $.map(this.dates, this._utc_to_local);
  496. },
  497. getUTCDates: function(){
  498. return $.map(this.dates, function(d){
  499. return new Date(d);
  500. });
  501. },
  502. getDate: function(){
  503. return this._utc_to_local(this.getUTCDate());
  504. },
  505. getUTCDate: function(){
  506. var selected_date = this.dates.get(-1);
  507. if (selected_date !== undefined) {
  508. return new Date(selected_date);
  509. } else {
  510. return null;
  511. }
  512. },
  513. clearDates: function(){
  514. this.inputField.val('');
  515. this.update();
  516. this._trigger('changeDate');
  517. if (this.o.autoclose) {
  518. this.hide();
  519. }
  520. },
  521. setDates: function(){
  522. var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
  523. this.update.apply(this, args);
  524. this._trigger('changeDate');
  525. this.setValue();
  526. return this;
  527. },
  528. setUTCDates: function(){
  529. var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
  530. this.setDates.apply(this, $.map(args, this._utc_to_local));
  531. return this;
  532. },
  533. setDate: alias('setDates'),
  534. setUTCDate: alias('setUTCDates'),
  535. remove: alias('destroy', 'Method `remove` is deprecated and will be removed in version 2.0. Use `destroy` instead'),
  536. setValue: function(){
  537. var formatted = this.getFormattedDate();
  538. this.inputField.val(formatted);
  539. return this;
  540. },
  541. getFormattedDate: function(format){
  542. if (format === undefined)
  543. format = this.o.format;
  544. var lang = this.o.language;
  545. return $.map(this.dates, function(d){
  546. return DPGlobal.formatDate(d, format, lang);
  547. }).join(this.o.multidateSeparator);
  548. },
  549. getStartDate: function(){
  550. return this.o.startDate;
  551. },
  552. setStartDate: function(startDate){
  553. this._process_options({startDate: startDate});
  554. this.update();
  555. this.updateNavArrows();
  556. return this;
  557. },
  558. getEndDate: function(){
  559. return this.o.endDate;
  560. },
  561. setEndDate: function(endDate){
  562. this._process_options({endDate: endDate});
  563. this.update();
  564. this.updateNavArrows();
  565. return this;
  566. },
  567. setDaysOfWeekDisabled: function(daysOfWeekDisabled){
  568. this._process_options({daysOfWeekDisabled: daysOfWeekDisabled});
  569. this.update();
  570. return this;
  571. },
  572. setDaysOfWeekHighlighted: function(daysOfWeekHighlighted){
  573. this._process_options({daysOfWeekHighlighted: daysOfWeekHighlighted});
  574. this.update();
  575. return this;
  576. },
  577. setDatesDisabled: function(datesDisabled){
  578. this._process_options({datesDisabled: datesDisabled});
  579. this.update();
  580. return this;
  581. },
  582. place: function(){
  583. if (this.isInline)
  584. return this;
  585. var calendarWidth = this.picker.outerWidth(),
  586. calendarHeight = this.picker.outerHeight(),
  587. visualPadding = 10,
  588. container = $(this.o.container),
  589. windowWidth = container.width(),
  590. scrollTop = this.o.container === 'body' ? $(document).scrollTop() : container.scrollTop(),
  591. appendOffset = container.offset();
  592. var parentsZindex = [0];
  593. this.element.parents().each(function(){
  594. var itemZIndex = $(this).css('z-index');
  595. if (itemZIndex !== 'auto' && Number(itemZIndex) !== 0) parentsZindex.push(Number(itemZIndex));
  596. });
  597. var zIndex = Math.max.apply(Math, parentsZindex) + this.o.zIndexOffset;
  598. var offset = this.component ? this.component.parent().offset() : this.element.offset();
  599. var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(false);
  600. var width = this.component ? this.component.outerWidth(true) : this.element.outerWidth(false);
  601. var left = offset.left - appendOffset.left;
  602. var top = offset.top - appendOffset.top;
  603. if (this.o.container !== 'body') {
  604. top += scrollTop;
  605. }
  606. this.picker.removeClass(
  607. 'datepicker-orient-top datepicker-orient-bottom '+
  608. 'datepicker-orient-right datepicker-orient-left'
  609. );
  610. if (this.o.orientation.x !== 'auto'){
  611. this.picker.addClass('datepicker-orient-' + this.o.orientation.x);
  612. if (this.o.orientation.x === 'right')
  613. left -= calendarWidth - width;
  614. }
  615. // auto x orientation is best-placement: if it crosses a window
  616. // edge, fudge it sideways
  617. else {
  618. if (offset.left < 0) {
  619. // component is outside the window on the left side. Move it into visible range
  620. this.picker.addClass('datepicker-orient-left');
  621. left -= offset.left - visualPadding;
  622. } else if (left + calendarWidth > windowWidth) {
  623. // the calendar passes the widow right edge. Align it to component right side
  624. this.picker.addClass('datepicker-orient-right');
  625. left += width - calendarWidth;
  626. } else {
  627. if (this.o.rtl) {
  628. // Default to right
  629. this.picker.addClass('datepicker-orient-right');
  630. } else {
  631. // Default to left
  632. this.picker.addClass('datepicker-orient-left');
  633. }
  634. }
  635. }
  636. // auto y orientation is best-situation: top or bottom, no fudging,
  637. // decision based on which shows more of the calendar
  638. var yorient = this.o.orientation.y,
  639. top_overflow;
  640. if (yorient === 'auto'){
  641. top_overflow = -scrollTop + top - calendarHeight;
  642. yorient = top_overflow < 0 ? 'bottom' : 'top';
  643. }
  644. this.picker.addClass('datepicker-orient-' + yorient);
  645. if (yorient === 'top')
  646. top -= calendarHeight + parseInt(this.picker.css('padding-top'));
  647. else
  648. top += height;
  649. if (this.o.rtl) {
  650. var right = windowWidth - (left + width);
  651. this.picker.css({
  652. top: top,
  653. right: right,
  654. zIndex: zIndex
  655. });
  656. } else {
  657. this.picker.css({
  658. top: top,
  659. left: left,
  660. zIndex: zIndex
  661. });
  662. }
  663. return this;
  664. },
  665. _allow_update: true,
  666. update: function(){
  667. if (!this._allow_update)
  668. return this;
  669. var oldDates = this.dates.copy(),
  670. dates = [],
  671. fromArgs = false;
  672. if (arguments.length){
  673. $.each(arguments, $.proxy(function(i, date){
  674. if (date instanceof Date)
  675. date = this._local_to_utc(date);
  676. dates.push(date);
  677. }, this));
  678. fromArgs = true;
  679. } else {
  680. dates = this.isInput
  681. ? this.element.val()
  682. : this.element.data('date') || this.inputField.val();
  683. if (dates && this.o.multidate)
  684. dates = dates.split(this.o.multidateSeparator);
  685. else
  686. dates = [dates];
  687. delete this.element.data().date;
  688. }
  689. dates = $.map(dates, $.proxy(function(date){
  690. return DPGlobal.parseDate(date, this.o.format, this.o.language, this.o.assumeNearbyYear);
  691. }, this));
  692. dates = $.grep(dates, $.proxy(function(date){
  693. return (
  694. !this.dateWithinRange(date) ||
  695. !date
  696. );
  697. }, this), true);
  698. this.dates.replace(dates);
  699. if (this.o.updateViewDate) {
  700. if (this.dates.length)
  701. this.viewDate = new Date(this.dates.get(-1));
  702. else if (this.viewDate < this.o.startDate)
  703. this.viewDate = new Date(this.o.startDate);
  704. else if (this.viewDate > this.o.endDate)
  705. this.viewDate = new Date(this.o.endDate);
  706. else
  707. this.viewDate = this.o.defaultViewDate;
  708. }
  709. if (fromArgs){
  710. // setting date by clicking
  711. this.setValue();
  712. this.element.change();
  713. }
  714. else if (this.dates.length){
  715. // setting date by typing
  716. if (String(oldDates) !== String(this.dates) && fromArgs) {
  717. this._trigger('changeDate');
  718. this.element.change();
  719. }
  720. }
  721. if (!this.dates.length && oldDates.length) {
  722. this._trigger('clearDate');
  723. this.element.change();
  724. }
  725. this.fill();
  726. return this;
  727. },
  728. fillDow: function(){
  729. if (this.o.showWeekDays) {
  730. var dowCnt = this.o.weekStart,
  731. html = '<tr>';
  732. if (this.o.calendarWeeks){
  733. html += '<th class="cw">&#160;</th>';
  734. }
  735. while (dowCnt < this.o.weekStart + 7){
  736. html += '<th class="dow';
  737. if ($.inArray(dowCnt, this.o.daysOfWeekDisabled) !== -1)
  738. html += ' disabled';
  739. html += '">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>';
  740. }
  741. html += '</tr>';
  742. this.picker.find('.datepicker-days thead').append(html);
  743. }
  744. },
  745. fillMonths: function(){
  746. var localDate = this._utc_to_local(this.viewDate);
  747. var html = '';
  748. var focused;
  749. for (var i = 0; i < 12; i++){
  750. focused = localDate && localDate.getMonth() === i ? ' focused' : '';
  751. html += '<span class="month' + focused + '">' + dates[this.o.language].monthsShort[i] + '</span>';
  752. }
  753. this.picker.find('.datepicker-months td').html(html);
  754. },
  755. setRange: function(range){
  756. if (!range || !range.length)
  757. delete this.range;
  758. else
  759. this.range = $.map(range, function(d){
  760. return d.valueOf();
  761. });
  762. this.fill();
  763. },
  764. getClassNames: function(date){
  765. var cls = [],
  766. year = this.viewDate.getUTCFullYear(),
  767. month = this.viewDate.getUTCMonth(),
  768. today = UTCToday();
  769. if (date.getUTCFullYear() < year || (date.getUTCFullYear() === year && date.getUTCMonth() < month)){
  770. cls.push('old');
  771. } else if (date.getUTCFullYear() > year || (date.getUTCFullYear() === year && date.getUTCMonth() > month)){
  772. cls.push('new');
  773. }
  774. if (this.focusDate && date.valueOf() === this.focusDate.valueOf())
  775. cls.push('focused');
  776. // Compare internal UTC date with UTC today, not local today
  777. if (this.o.todayHighlight && isUTCEquals(date, today)) {
  778. cls.push('today');
  779. }
  780. if (this.dates.contains(date) !== -1)
  781. cls.push('active');
  782. if (!this.dateWithinRange(date)){
  783. cls.push('disabled');
  784. }
  785. if (this.dateIsDisabled(date)){
  786. cls.push('disabled', 'disabled-date');
  787. }
  788. if ($.inArray(date.getUTCDay(), this.o.daysOfWeekHighlighted) !== -1){
  789. cls.push('highlighted');
  790. }
  791. if (this.range){
  792. if (date > this.range[0] && date < this.range[this.range.length-1]){
  793. cls.push('range');
  794. }
  795. if ($.inArray(date.valueOf(), this.range) !== -1){
  796. cls.push('selected');
  797. }
  798. if (date.valueOf() === this.range[0]){
  799. cls.push('range-start');
  800. }
  801. if (date.valueOf() === this.range[this.range.length-1]){
  802. cls.push('range-end');
  803. }
  804. }
  805. return cls;
  806. },
  807. _fill_yearsView: function(selector, cssClass, factor, year, startYear, endYear, beforeFn){
  808. var html = '';
  809. var step = factor / 10;
  810. var view = this.picker.find(selector);
  811. var startVal = Math.floor(year / factor) * factor;
  812. var endVal = startVal + step * 9;
  813. var focusedVal = Math.floor(this.viewDate.getFullYear() / step) * step;
  814. var selected = $.map(this.dates, function(d){
  815. return Math.floor(d.getUTCFullYear() / step) * step;
  816. });
  817. var classes, tooltip, before;
  818. for (var currVal = startVal - step; currVal <= endVal + step; currVal += step) {
  819. classes = [cssClass];
  820. tooltip = null;
  821. if (currVal === startVal - step) {
  822. classes.push('old');
  823. } else if (currVal === endVal + step) {
  824. classes.push('new');
  825. }
  826. if ($.inArray(currVal, selected) !== -1) {
  827. classes.push('active');
  828. }
  829. if (currVal < startYear || currVal > endYear) {
  830. classes.push('disabled');
  831. }
  832. if (currVal === focusedVal) {
  833. classes.push('focused');
  834. }
  835. if (beforeFn !== $.noop) {
  836. before = beforeFn(new Date(currVal, 0, 1));
  837. if (before === undefined) {
  838. before = {};
  839. } else if (typeof before === 'boolean') {
  840. before = {enabled: before};
  841. } else if (typeof before === 'string') {
  842. before = {classes: before};
  843. }
  844. if (before.enabled === false) {
  845. classes.push('disabled');
  846. }
  847. if (before.classes) {
  848. classes = classes.concat(before.classes.split(/\s+/));
  849. }
  850. if (before.tooltip) {
  851. tooltip = before.tooltip;
  852. }
  853. }
  854. html += '<span class="' + classes.join(' ') + '"' + (tooltip ? ' title="' + tooltip + '"' : '') + '>' + currVal + '</span>';
  855. }
  856. view.find('.datepicker-switch').text(startVal + '-' + endVal);
  857. view.find('td').html(html);
  858. },
  859. fill: function(){
  860. var d = new Date(this.viewDate),
  861. year = d.getUTCFullYear(),
  862. month = d.getUTCMonth(),
  863. startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
  864. startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
  865. endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
  866. endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
  867. todaytxt = dates[this.o.language].today || dates['en'].today || '',
  868. cleartxt = dates[this.o.language].clear || dates['en'].clear || '',
  869. titleFormat = dates[this.o.language].titleFormat || dates['en'].titleFormat,
  870. tooltip,
  871. before;
  872. if (isNaN(year) || isNaN(month))
  873. return;
  874. this.picker.find('.datepicker-days .datepicker-switch')
  875. .text(DPGlobal.formatDate(d, titleFormat, this.o.language));
  876. this.picker.find('tfoot .today')
  877. .text(todaytxt)
  878. .css('display', this.o.todayBtn === true || this.o.todayBtn === 'linked' ? 'table-cell' : 'none');
  879. this.picker.find('tfoot .clear')
  880. .text(cleartxt)
  881. .css('display', this.o.clearBtn === true ? 'table-cell' : 'none');
  882. this.picker.find('thead .datepicker-title')
  883. .text(this.o.title)
  884. .css('display', typeof this.o.title === 'string' && this.o.title !== '' ? 'table-cell' : 'none');
  885. this.updateNavArrows();
  886. this.fillMonths();
  887. var prevMonth = UTCDate(year, month, 0),
  888. day = prevMonth.getUTCDate();
  889. prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7);
  890. var nextMonth = new Date(prevMonth);
  891. if (prevMonth.getUTCFullYear() < 100){
  892. nextMonth.setUTCFullYear(prevMonth.getUTCFullYear());
  893. }
  894. nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
  895. nextMonth = nextMonth.valueOf();
  896. var html = [];
  897. var weekDay, clsName;
  898. while (prevMonth.valueOf() < nextMonth){
  899. weekDay = prevMonth.getUTCDay();
  900. if (weekDay === this.o.weekStart){
  901. html.push('<tr>');
  902. if (this.o.calendarWeeks){
  903. // ISO 8601: First week contains first thursday.
  904. // ISO also states week starts on Monday, but we can be more abstract here.
  905. var
  906. // Start of current week: based on weekstart/current date
  907. ws = new Date(+prevMonth + (this.o.weekStart - weekDay - 7) % 7 * 864e5),
  908. // Thursday of this week
  909. th = new Date(Number(ws) + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
  910. // First Thursday of year, year from thursday
  911. yth = new Date(Number(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay()) % 7 * 864e5),
  912. // Calendar week: ms between thursdays, div ms per day, div 7 days
  913. calWeek = (th - yth) / 864e5 / 7 + 1;
  914. html.push('<td class="cw">'+ calWeek +'</td>');
  915. }
  916. }
  917. clsName = this.getClassNames(prevMonth);
  918. clsName.push('day');
  919. var content = prevMonth.getUTCDate();
  920. if (this.o.beforeShowDay !== $.noop){
  921. before = this.o.beforeShowDay(this._utc_to_local(prevMonth));
  922. if (before === undefined)
  923. before = {};
  924. else if (typeof before === 'boolean')
  925. before = {enabled: before};
  926. else if (typeof before === 'string')
  927. before = {classes: before};
  928. if (before.enabled === false)
  929. clsName.push('disabled');
  930. if (before.classes)
  931. clsName = clsName.concat(before.classes.split(/\s+/));
  932. if (before.tooltip)
  933. tooltip = before.tooltip;
  934. if (before.content)
  935. content = before.content;
  936. }
  937. //Check if uniqueSort exists (supported by jquery >=1.12 and >=2.2)
  938. //Fallback to unique function for older jquery versions
  939. if ($.isFunction($.uniqueSort)) {
  940. clsName = $.uniqueSort(clsName);
  941. } else {
  942. clsName = $.unique(clsName);
  943. }
  944. html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + ' data-date="' + prevMonth.getTime().toString() + '">' + content + '</td>');
  945. tooltip = null;
  946. if (weekDay === this.o.weekEnd){
  947. html.push('</tr>');
  948. }
  949. prevMonth.setUTCDate(prevMonth.getUTCDate() + 1);
  950. }
  951. this.picker.find('.datepicker-days tbody').html(html.join(''));
  952. var monthsTitle = dates[this.o.language].monthsTitle || dates['en'].monthsTitle || 'Months';
  953. var months = this.picker.find('.datepicker-months')
  954. .find('.datepicker-switch')
  955. .text(this.o.maxViewMode < 2 ? monthsTitle : year)
  956. .end()
  957. .find('tbody span').removeClass('active');
  958. $.each(this.dates, function(i, d){
  959. if (d.getUTCFullYear() === year)
  960. months.eq(d.getUTCMonth()).addClass('active');
  961. });
  962. if (year < startYear || year > endYear){
  963. months.addClass('disabled');
  964. }
  965. if (year === startYear){
  966. months.slice(0, startMonth).addClass('disabled');
  967. }
  968. if (year === endYear){
  969. months.slice(endMonth+1).addClass('disabled');
  970. }
  971. if (this.o.beforeShowMonth !== $.noop){
  972. var that = this;
  973. $.each(months, function(i, month){
  974. var moDate = new Date(year, i, 1);
  975. var before = that.o.beforeShowMonth(moDate);
  976. if (before === undefined)
  977. before = {};
  978. else if (typeof before === 'boolean')
  979. before = {enabled: before};
  980. else if (typeof before === 'string')
  981. before = {classes: before};
  982. if (before.enabled === false && !$(month).hasClass('disabled'))
  983. $(month).addClass('disabled');
  984. if (before.classes)
  985. $(month).addClass(before.classes);
  986. if (before.tooltip)
  987. $(month).prop('title', before.tooltip);
  988. });
  989. }
  990. // Generating decade/years picker
  991. this._fill_yearsView(
  992. '.datepicker-years',
  993. 'year',
  994. 10,
  995. year,
  996. startYear,
  997. endYear,
  998. this.o.beforeShowYear
  999. );
  1000. // Generating century/decades picker
  1001. this._fill_yearsView(
  1002. '.datepicker-decades',
  1003. 'decade',
  1004. 100,
  1005. year,
  1006. startYear,
  1007. endYear,
  1008. this.o.beforeShowDecade
  1009. );
  1010. // Generating millennium/centuries picker
  1011. this._fill_yearsView(
  1012. '.datepicker-centuries',
  1013. 'century',
  1014. 1000,
  1015. year,
  1016. startYear,
  1017. endYear,
  1018. this.o.beforeShowCentury
  1019. );
  1020. },
  1021. updateNavArrows: function(){
  1022. if (!this._allow_update)
  1023. return;
  1024. var d = new Date(this.viewDate),
  1025. year = d.getUTCFullYear(),
  1026. month = d.getUTCMonth(),
  1027. startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
  1028. startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
  1029. endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
  1030. endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
  1031. prevIsDisabled,
  1032. nextIsDisabled,
  1033. factor = 1;
  1034. switch (this.viewMode){
  1035. case 4:
  1036. factor *= 10;
  1037. /* falls through */
  1038. case 3:
  1039. factor *= 10;
  1040. /* falls through */
  1041. case 2:
  1042. factor *= 10;
  1043. /* falls through */
  1044. case 1:
  1045. prevIsDisabled = Math.floor(year / factor) * factor < startYear;
  1046. nextIsDisabled = Math.floor(year / factor) * factor + factor > endYear;
  1047. break;
  1048. case 0:
  1049. prevIsDisabled = year <= startYear && month < startMonth;
  1050. nextIsDisabled = year >= endYear && month > endMonth;
  1051. break;
  1052. }
  1053. this.picker.find('.prev').toggleClass('disabled', prevIsDisabled);
  1054. this.picker.find('.next').toggleClass('disabled', nextIsDisabled);
  1055. },
  1056. click: function(e){
  1057. e.preventDefault();
  1058. e.stopPropagation();
  1059. var target, dir, day, year, month;
  1060. target = $(e.target);
  1061. // Clicked on the switch
  1062. if (target.hasClass('datepicker-switch') && this.viewMode !== this.o.maxViewMode){
  1063. this.setViewMode(this.viewMode + 1);
  1064. }
  1065. // Clicked on today button
  1066. if (target.hasClass('today') && !target.hasClass('day')){
  1067. this.setViewMode(0);
  1068. this._setDate(UTCToday(), this.o.todayBtn === 'linked' ? null : 'view');
  1069. }
  1070. // Clicked on clear button
  1071. if (target.hasClass('clear')){
  1072. this.clearDates();
  1073. }
  1074. if (!target.hasClass('disabled')){
  1075. // Clicked on a month, year, decade, century
  1076. if (target.hasClass('month')
  1077. || target.hasClass('year')
  1078. || target.hasClass('decade')
  1079. || target.hasClass('century')) {
  1080. this.viewDate.setUTCDate(1);
  1081. day = 1;
  1082. if (this.viewMode === 1){
  1083. month = target.parent().find('span').index(target);
  1084. year = this.viewDate.getUTCFullYear();
  1085. this.viewDate.setUTCMonth(month);
  1086. } else {
  1087. month = 0;
  1088. year = Number(target.text());
  1089. this.viewDate.setUTCFullYear(year);
  1090. }
  1091. this._trigger(DPGlobal.viewModes[this.viewMode - 1].e, this.viewDate);
  1092. if (this.viewMode === this.o.minViewMode){
  1093. this._setDate(UTCDate(year, month, day));
  1094. } else {
  1095. this.setViewMode(this.viewMode - 1);
  1096. this.fill();
  1097. }
  1098. }
  1099. }
  1100. if (this.picker.is(':visible') && this._focused_from){
  1101. this._focused_from.focus();
  1102. }
  1103. delete this._focused_from;
  1104. },
  1105. dayCellClick: function(e){
  1106. var $target = $(e.currentTarget);
  1107. var timestamp = $target.data('date');
  1108. var date = new Date(timestamp);
  1109. if (this.o.updateViewDate) {
  1110. if (date.getUTCFullYear() !== this.viewDate.getUTCFullYear()) {
  1111. this._trigger('changeYear', this.viewDate);
  1112. }
  1113. if (date.getUTCMonth() !== this.viewDate.getUTCMonth()) {
  1114. this._trigger('changeMonth', this.viewDate);
  1115. }
  1116. }
  1117. this._setDate(date);
  1118. },
  1119. // Clicked on prev or next
  1120. navArrowsClick: function(e){
  1121. var $target = $(e.currentTarget);
  1122. var dir = $target.hasClass('prev') ? -1 : 1;
  1123. if (this.viewMode !== 0){
  1124. dir *= DPGlobal.viewModes[this.viewMode].navStep * 12;
  1125. }
  1126. this.viewDate = this.moveMonth(this.viewDate, dir);
  1127. this._trigger(DPGlobal.viewModes[this.viewMode].e, this.viewDate);
  1128. this.fill();
  1129. },
  1130. _toggle_multidate: function(date){
  1131. var ix = this.dates.contains(date);
  1132. if (!date){
  1133. this.dates.clear();
  1134. }
  1135. if (ix !== -1){
  1136. if (this.o.multidate === true || this.o.multidate > 1 || this.o.toggleActive){
  1137. this.dates.remove(ix);
  1138. }
  1139. } else if (this.o.multidate === false) {
  1140. this.dates.clear();
  1141. this.dates.push(date);
  1142. }
  1143. else {
  1144. this.dates.push(date);
  1145. }
  1146. if (typeof this.o.multidate === 'number')
  1147. while (this.dates.length > this.o.multidate)
  1148. this.dates.remove(0);
  1149. },
  1150. _setDate: function(date, which){
  1151. if (!which || which === 'date')
  1152. this._toggle_multidate(date && new Date(date));
  1153. if ((!which && this.o.updateViewDate) || which === 'view')
  1154. this.viewDate = date && new Date(date);
  1155. this.fill();
  1156. this.setValue();
  1157. if (!which || which !== 'view') {
  1158. this._trigger('changeDate');
  1159. }
  1160. this.inputField.trigger('change');
  1161. if (this.o.autoclose && (!which || which === 'date')){
  1162. this.hide();
  1163. }
  1164. },
  1165. moveDay: function(date, dir){
  1166. var newDate = new Date(date);
  1167. newDate.setUTCDate(date.getUTCDate() + dir);
  1168. return newDate;
  1169. },
  1170. moveWeek: function(date, dir){
  1171. return this.moveDay(date, dir * 7);
  1172. },
  1173. moveMonth: function(date, dir){
  1174. if (!isValidDate(date))
  1175. return this.o.defaultViewDate;
  1176. if (!dir)
  1177. return date;
  1178. var new_date = new Date(date.valueOf()),
  1179. day = new_date.getUTCDate(),
  1180. month = new_date.getUTCMonth(),
  1181. mag = Math.abs(dir),
  1182. new_month, test;
  1183. dir = dir > 0 ? 1 : -1;
  1184. if (mag === 1){
  1185. test = dir === -1
  1186. // If going back one month, make sure month is not current month
  1187. // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
  1188. ? function(){
  1189. return new_date.getUTCMonth() === month;
  1190. }
  1191. // If going forward one month, make sure month is as expected
  1192. // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
  1193. : function(){
  1194. return new_date.getUTCMonth() !== new_month;
  1195. };
  1196. new_month = month + dir;
  1197. new_date.setUTCMonth(new_month);
  1198. // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
  1199. new_month = (new_month + 12) % 12;
  1200. }
  1201. else {
  1202. // For magnitudes >1, move one month at a time...
  1203. for (var i=0; i < mag; i++)
  1204. // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
  1205. new_date = this.moveMonth(new_date, dir);
  1206. // ...then reset the day, keeping it in the new month
  1207. new_month = new_date.getUTCMonth();
  1208. new_date.setUTCDate(day);
  1209. test = function(){
  1210. return new_month !== new_date.getUTCMonth();
  1211. };
  1212. }
  1213. // Common date-resetting loop -- if date is beyond end of month, make it
  1214. // end of month
  1215. while (test()){
  1216. new_date.setUTCDate(--day);
  1217. new_date.setUTCMonth(new_month);
  1218. }
  1219. return new_date;
  1220. },
  1221. moveYear: function(date, dir){
  1222. return this.moveMonth(date, dir*12);
  1223. },
  1224. moveAvailableDate: function(date, dir, fn){
  1225. do {
  1226. date = this[fn](date, dir);
  1227. if (!this.dateWithinRange(date))
  1228. return false;
  1229. fn = 'moveDay';
  1230. }
  1231. while (this.dateIsDisabled(date));
  1232. return date;
  1233. },
  1234. weekOfDateIsDisabled: function(date){
  1235. return $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1;
  1236. },
  1237. dateIsDisabled: function(date){
  1238. return (
  1239. this.weekOfDateIsDisabled(date) ||
  1240. $.grep(this.o.datesDisabled, function(d){
  1241. return isUTCEquals(date, d);
  1242. }).length > 0
  1243. );
  1244. },
  1245. dateWithinRange: function(date){
  1246. return date >= this.o.startDate && date <= this.o.endDate;
  1247. },
  1248. keydown: function(e){
  1249. if (!this.picker.is(':visible')){
  1250. if (e.keyCode === 40 || e.keyCode === 27) { // allow down to re-show picker
  1251. this.show();
  1252. e.stopPropagation();
  1253. }
  1254. return;
  1255. }
  1256. var dateChanged = false,
  1257. dir, newViewDate,
  1258. focusDate = this.focusDate || this.viewDate;
  1259. switch (e.keyCode){
  1260. case 27: // escape
  1261. if (this.focusDate){
  1262. this.focusDate = null;
  1263. this.viewDate = this.dates.get(-1) || this.viewDate;
  1264. this.fill();
  1265. }
  1266. else
  1267. this.hide();
  1268. e.preventDefault();
  1269. e.stopPropagation();
  1270. break;
  1271. case 37: // left
  1272. case 38: // up
  1273. case 39: // right
  1274. case 40: // down
  1275. if (!this.o.keyboardNavigation || this.o.daysOfWeekDisabled.length === 7)
  1276. break;
  1277. dir = e.keyCode === 37 || e.keyCode === 38 ? -1 : 1;
  1278. if (this.viewMode === 0) {
  1279. if (e.ctrlKey){
  1280. newViewDate = this.moveAvailableDate(focusDate, dir, 'moveYear');
  1281. if (newViewDate)
  1282. this._trigger('changeYear', this.viewDate);
  1283. } else if (e.shiftKey){
  1284. newViewDate = this.moveAvailableDate(focusDate, dir, 'moveMonth');
  1285. if (newViewDate)
  1286. this._trigger('changeMonth', this.viewDate);
  1287. } else if (e.keyCode === 37 || e.keyCode === 39){
  1288. newViewDate = this.moveAvailableDate(focusDate, dir, 'moveDay');
  1289. } else if (!this.weekOfDateIsDisabled(focusDate)){
  1290. newViewDate = this.moveAvailableDate(focusDate, dir, 'moveWeek');
  1291. }
  1292. } else if (this.viewMode === 1) {
  1293. if (e.keyCode === 38 || e.keyCode === 40) {
  1294. dir = dir * 4;
  1295. }
  1296. newViewDate = this.moveAvailableDate(focusDate, dir, 'moveMonth');
  1297. } else if (this.viewMode === 2) {
  1298. if (e.keyCode === 38 || e.keyCode === 40) {
  1299. dir = dir * 4;
  1300. }
  1301. newViewDate = this.moveAvailableDate(focusDate, dir, 'moveYear');
  1302. }
  1303. if (newViewDate){
  1304. this.focusDate = this.viewDate = newViewDate;
  1305. this.setValue();
  1306. this.fill();
  1307. e.preventDefault();
  1308. }
  1309. break;
  1310. case 13: // enter
  1311. if (!this.o.forceParse)
  1312. break;
  1313. focusDate = this.focusDate || this.dates.get(-1) || this.viewDate;
  1314. if (this.o.keyboardNavigation) {
  1315. this._toggle_multidate(focusDate);
  1316. dateChanged = true;
  1317. }
  1318. this.focusDate = null;
  1319. this.viewDate = this.dates.get(-1) || this.viewDate;
  1320. this.setValue();
  1321. this.fill();
  1322. if (this.picker.is(':visible')){
  1323. e.preventDefault();
  1324. e.stopPropagation();
  1325. if (this.o.autoclose)
  1326. this.hide();
  1327. }
  1328. break;
  1329. case 9: // tab
  1330. this.focusDate = null;
  1331. this.viewDate = this.dates.get(-1) || this.viewDate;
  1332. this.fill();
  1333. this.hide();
  1334. break;
  1335. }
  1336. if (dateChanged){
  1337. if (this.dates.length)
  1338. this._trigger('changeDate');
  1339. else
  1340. this._trigger('clearDate');
  1341. this.inputField.trigger('change');
  1342. }
  1343. },
  1344. setViewMode: function(viewMode){
  1345. this.viewMode = viewMode;
  1346. this.picker
  1347. .children('div')
  1348. .hide()
  1349. .filter('.datepicker-' + DPGlobal.viewModes[this.viewMode].clsName)
  1350. .show();
  1351. this.updateNavArrows();
  1352. this._trigger('changeViewMode', new Date(this.viewDate));
  1353. }
  1354. };
  1355. var DateRangePicker = function(element, options){
  1356. $.data(element, 'datepicker', this);
  1357. this.element = $(element);
  1358. this.inputs = $.map(options.inputs, function(i){
  1359. return i.jquery ? i[0] : i;
  1360. });
  1361. delete options.inputs;
  1362. this.keepEmptyValues = options.keepEmptyValues;
  1363. delete options.keepEmptyValues;
  1364. datepickerPlugin.call($(this.inputs), options)
  1365. .on('changeDate', $.proxy(this.dateUpdated, this));
  1366. this.pickers = $.map(this.inputs, function(i){
  1367. return $.data(i, 'datepicker');
  1368. });
  1369. this.updateDates();
  1370. };
  1371. DateRangePicker.prototype = {
  1372. updateDates: function(){
  1373. this.dates = $.map(this.pickers, function(i){
  1374. return i.getUTCDate();
  1375. });
  1376. this.updateRanges();
  1377. },
  1378. updateRanges: function(){
  1379. var range = $.map(this.dates, function(d){
  1380. return d.valueOf();
  1381. });
  1382. $.each(this.pickers, function(i, p){
  1383. p.setRange(range);
  1384. });
  1385. },
  1386. clearDates: function(){
  1387. $.each(this.pickers, function(i, p){
  1388. p.clearDates();
  1389. });
  1390. },
  1391. dateUpdated: function(e){
  1392. // `this.updating` is a workaround for preventing infinite recursion
  1393. // between `changeDate` triggering and `setUTCDate` calling. Until
  1394. // there is a better mechanism.
  1395. if (this.updating)
  1396. return;
  1397. this.updating = true;
  1398. var dp = $.data(e.target, 'datepicker');
  1399. if (dp === undefined) {
  1400. return;
  1401. }
  1402. var new_date = dp.getUTCDate(),
  1403. keep_empty_values = this.keepEmptyValues,
  1404. i = $.inArray(e.target, this.inputs),
  1405. j = i - 1,
  1406. k = i + 1,
  1407. l = this.inputs.length;
  1408. if (i === -1)
  1409. return;
  1410. $.each(this.pickers, function(i, p){
  1411. if (!p.getUTCDate() && (p === dp || !keep_empty_values))
  1412. p.setUTCDate(new_date);
  1413. });
  1414. if (new_date < this.dates[j]){
  1415. // Date being moved earlier/left
  1416. while (j >= 0 && new_date < this.dates[j]){
  1417. this.pickers[j--].setUTCDate(new_date);
  1418. }
  1419. } else if (new_date > this.dates[k]){
  1420. // Date being moved later/right
  1421. while (k < l && new_date > this.dates[k]){
  1422. this.pickers[k++].setUTCDate(new_date);
  1423. }
  1424. }
  1425. this.updateDates();
  1426. delete this.updating;
  1427. },
  1428. destroy: function(){
  1429. $.map(this.pickers, function(p){ p.destroy(); });
  1430. $(this.inputs).off('changeDate', this.dateUpdated);
  1431. delete this.element.data().datepicker;
  1432. },
  1433. remove: alias('destroy', 'Method `remove` is deprecated and will be removed in version 2.0. Use `destroy` instead')
  1434. };
  1435. function opts_from_el(el, prefix){
  1436. // Derive options from element data-attrs
  1437. var data = $(el).data(),
  1438. out = {}, inkey,
  1439. replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])');
  1440. prefix = new RegExp('^' + prefix.toLowerCase());
  1441. function re_lower(_,a){
  1442. return a.toLowerCase();
  1443. }
  1444. for (var key in data)
  1445. if (prefix.test(key)){
  1446. inkey = key.replace(replace, re_lower);
  1447. out[inkey] = data[key];
  1448. }
  1449. return out;
  1450. }
  1451. function opts_from_locale(lang){
  1452. // Derive options from locale plugins
  1453. var out = {};
  1454. // Check if "de-DE" style date is available, if not language should
  1455. // fallback to 2 letter code eg "de"
  1456. if (!dates[lang]){
  1457. lang = lang.split('-')[0];
  1458. if (!dates[lang])
  1459. return;
  1460. }
  1461. var d = dates[lang];
  1462. $.each(locale_opts, function(i,k){
  1463. if (k in d)
  1464. out[k] = d[k];
  1465. });
  1466. return out;
  1467. }
  1468. var old = $.fn.datepicker;
  1469. var datepickerPlugin = function(option){
  1470. var args = Array.apply(null, arguments);
  1471. args.shift();
  1472. var internal_return;
  1473. this.each(function(){
  1474. var $this = $(this),
  1475. data = $this.data('datepicker'),
  1476. options = typeof option === 'object' && option;
  1477. if (!data){
  1478. var elopts = opts_from_el(this, 'date'),
  1479. // Preliminary otions
  1480. xopts = $.extend({}, defaults, elopts, options),
  1481. locopts = opts_from_locale(xopts.language),
  1482. // Options priority: js args, data-attrs, locales, defaults
  1483. opts = $.extend({}, defaults, locopts, elopts, options);
  1484. if ($this.hasClass('input-daterange') || opts.inputs){
  1485. $.extend(opts, {
  1486. inputs: opts.inputs || $this.find('input').toArray()
  1487. });
  1488. data = new DateRangePicker(this, opts);
  1489. }
  1490. else {
  1491. data = new Datepicker(this, opts);
  1492. }
  1493. $this.data('datepicker', data);
  1494. }
  1495. if (typeof option === 'string' && typeof data[option] === 'function'){
  1496. internal_return = data[option].apply(data, args);
  1497. }
  1498. });
  1499. if (
  1500. internal_return === undefined ||
  1501. internal_return instanceof Datepicker ||
  1502. internal_return instanceof DateRangePicker
  1503. )
  1504. return this;
  1505. if (this.length > 1)
  1506. throw new Error('Using only allowed for the collection of a single element (' + option + ' function)');
  1507. else
  1508. return internal_return;
  1509. };
  1510. $.fn.datepicker = datepickerPlugin;
  1511. var defaults = $.fn.datepicker.defaults = {
  1512. assumeNearbyYear: false,
  1513. autoclose: false,
  1514. beforeShowDay: $.noop,
  1515. beforeShowMonth: $.noop,
  1516. beforeShowYear: $.noop,
  1517. beforeShowDecade: $.noop,
  1518. beforeShowCentury: $.noop,
  1519. calendarWeeks: false,
  1520. clearBtn: false,
  1521. toggleActive: false,
  1522. daysOfWeekDisabled: [],
  1523. daysOfWeekHighlighted: [],
  1524. datesDisabled: [],
  1525. endDate: Infinity,
  1526. forceParse: true,
  1527. format: 'mm/dd/yyyy',
  1528. keepEmptyValues: false,
  1529. keyboardNavigation: true,
  1530. language: 'en',
  1531. minViewMode: 0,
  1532. maxViewMode: 4,
  1533. multidate: false,
  1534. multidateSeparator: ',',
  1535. orientation: "auto",
  1536. rtl: false,
  1537. startDate: -Infinity,
  1538. startView: 0,
  1539. todayBtn: false,
  1540. todayHighlight: false,
  1541. updateViewDate: true,
  1542. weekStart: 0,
  1543. disableTouchKeyboard: false,
  1544. enableOnReadonly: true,
  1545. showOnFocus: true,
  1546. zIndexOffset: 10,
  1547. container: 'body',
  1548. immediateUpdates: false,
  1549. title: '',
  1550. templates: {
  1551. leftArrow: '&#x00AB;',
  1552. rightArrow: '&#x00BB;'
  1553. },
  1554. showWeekDays: true
  1555. };
  1556. var locale_opts = $.fn.datepicker.locale_opts = [
  1557. 'format',
  1558. 'rtl',
  1559. 'weekStart'
  1560. ];
  1561. $.fn.datepicker.Constructor = Datepicker;
  1562. var dates = $.fn.datepicker.dates = {
  1563. en: {
  1564. days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  1565. daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  1566. daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
  1567. months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  1568. monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
  1569. today: "Today",
  1570. clear: "Clear",
  1571. titleFormat: "MM yyyy"
  1572. }
  1573. };
  1574. var DPGlobal = {
  1575. viewModes: [
  1576. {
  1577. names: ['days', 'month'],
  1578. clsName: 'days',
  1579. e: 'changeMonth'
  1580. },
  1581. {
  1582. names: ['months', 'year'],
  1583. clsName: 'months',
  1584. e: 'changeYear',
  1585. navStep: 1
  1586. },
  1587. {
  1588. names: ['years', 'decade'],
  1589. clsName: 'years',
  1590. e: 'changeDecade',
  1591. navStep: 10
  1592. },
  1593. {
  1594. names: ['decades', 'century'],
  1595. clsName: 'decades',
  1596. e: 'changeCentury',
  1597. navStep: 100
  1598. },
  1599. {
  1600. names: ['centuries', 'millennium'],
  1601. clsName: 'centuries',
  1602. e: 'changeMillennium',
  1603. navStep: 1000
  1604. }
  1605. ],
  1606. validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
  1607. nonpunctuation: /[^ -\/:-@\u5e74\u6708\u65e5\[-`{-~\t\n\r]+/g,
  1608. parseFormat: function(format){
  1609. if (typeof format.toValue === 'function' && typeof format.toDisplay === 'function')
  1610. return format;
  1611. // IE treats \0 as a string end in inputs (truncating the value),
  1612. // so it's a bad format delimiter, anyway
  1613. var separators = format.replace(this.validParts, '\0').split('\0'),
  1614. parts = format.match(this.validParts);
  1615. if (!separators || !separators.length || !parts || parts.length === 0){
  1616. throw new Error("Invalid date format.");
  1617. }
  1618. return {separators: separators, parts: parts};
  1619. },
  1620. parseDate: function(date, format, language, assumeNearby){
  1621. if (!date)
  1622. return undefined;
  1623. if (date instanceof Date)
  1624. return date;
  1625. if (typeof format === 'string')
  1626. format = DPGlobal.parseFormat(format);
  1627. if (format.toValue)
  1628. return format.toValue(date, format, language);
  1629. var fn_map = {
  1630. d: 'moveDay',
  1631. m: 'moveMonth',
  1632. w: 'moveWeek',
  1633. y: 'moveYear'
  1634. },
  1635. dateAliases = {
  1636. yesterday: '-1d',
  1637. today: '+0d',
  1638. tomorrow: '+1d'
  1639. },
  1640. parts, part, dir, i, fn;
  1641. if (date in dateAliases){
  1642. date = dateAliases[date];
  1643. }
  1644. if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/i.test(date)){
  1645. parts = date.match(/([\-+]\d+)([dmwy])/gi);
  1646. date = new Date();
  1647. for (i=0; i < parts.length; i++){
  1648. part = parts[i].match(/([\-+]\d+)([dmwy])/i);
  1649. dir = Number(part[1]);
  1650. fn = fn_map[part[2].toLowerCase()];
  1651. date = Datepicker.prototype[fn](date, dir);
  1652. }
  1653. return Datepicker.prototype._zero_utc_time(date);
  1654. }
  1655. parts = date && date.match(this.nonpunctuation) || [];
  1656. function applyNearbyYear(year, threshold){
  1657. if (threshold === true)
  1658. threshold = 10;
  1659. // if year is 2 digits or less, than the user most likely is trying to get a recent century
  1660. if (year < 100){
  1661. year += 2000;
  1662. // if the new year is more than threshold years in advance, use last century
  1663. if (year > ((new Date()).getFullYear()+threshold)){
  1664. year -= 100;
  1665. }
  1666. }
  1667. return year;
  1668. }
  1669. var parsed = {},
  1670. setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
  1671. setters_map = {
  1672. yyyy: function(d,v){
  1673. return d.setUTCFullYear(assumeNearby ? applyNearbyYear(v, assumeNearby) : v);
  1674. },
  1675. m: function(d,v){
  1676. if (isNaN(d))
  1677. return d;
  1678. v -= 1;
  1679. while (v < 0) v += 12;
  1680. v %= 12;
  1681. d.setUTCMonth(v);
  1682. while (d.getUTCMonth() !== v)
  1683. d.setUTCDate(d.getUTCDate()-1);
  1684. return d;
  1685. },
  1686. d: function(d,v){
  1687. return d.setUTCDate(v);
  1688. }
  1689. },
  1690. val, filtered;
  1691. setters_map['yy'] = setters_map['yyyy'];
  1692. setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
  1693. setters_map['dd'] = setters_map['d'];
  1694. date = UTCToday();
  1695. var fparts = format.parts.slice();
  1696. // Remove noop parts
  1697. if (parts.length !== fparts.length){
  1698. fparts = $(fparts).filter(function(i,p){
  1699. return $.inArray(p, setters_order) !== -1;
  1700. }).toArray();
  1701. }
  1702. // Process remainder
  1703. function match_part(){
  1704. var m = this.slice(0, parts[i].length),
  1705. p = parts[i].slice(0, m.length);
  1706. return m.toLowerCase() === p.toLowerCase();
  1707. }
  1708. if (parts.length === fparts.length){
  1709. var cnt;
  1710. for (i=0, cnt = fparts.length; i < cnt; i++){
  1711. val = parseInt(parts[i], 10);
  1712. part = fparts[i];
  1713. if (isNaN(val)){
  1714. switch (part){
  1715. case 'MM':
  1716. filtered = $(dates[language].months).filter(match_part);
  1717. val = $.inArray(filtered[0], dates[language].months) + 1;
  1718. break;
  1719. case 'M':
  1720. filtered = $(dates[language].monthsShort).filter(match_part);
  1721. val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
  1722. break;
  1723. }
  1724. }
  1725. parsed[part] = val;
  1726. }
  1727. var _date, s;
  1728. for (i=0; i < setters_order.length; i++){
  1729. s = setters_order[i];
  1730. if (s in parsed && !isNaN(parsed[s])){
  1731. _date = new Date(date);
  1732. setters_map[s](_date, parsed[s]);
  1733. if (!isNaN(_date))
  1734. date = _date;
  1735. }
  1736. }
  1737. }
  1738. return date;
  1739. },
  1740. formatDate: function(date, format, language){
  1741. if (!date)
  1742. return '';
  1743. if (typeof format === 'string')
  1744. format = DPGlobal.parseFormat(format);
  1745. if (format.toDisplay)
  1746. return format.toDisplay(date, format, language);
  1747. var val = {
  1748. d: date.getUTCDate(),
  1749. D: dates[language].daysShort[date.getUTCDay()],
  1750. DD: dates[language].days[date.getUTCDay()],
  1751. m: date.getUTCMonth() + 1,
  1752. M: dates[language].monthsShort[date.getUTCMonth()],
  1753. MM: dates[language].months[date.getUTCMonth()],
  1754. yy: date.getUTCFullYear().toString().substring(2),
  1755. yyyy: date.getUTCFullYear()
  1756. };
  1757. val.dd = (val.d < 10 ? '0' : '') + val.d;
  1758. val.mm = (val.m < 10 ? '0' : '') + val.m;
  1759. date = [];
  1760. var seps = $.extend([], format.separators);
  1761. for (var i=0, cnt = format.parts.length; i <= cnt; i++){
  1762. if (seps.length)
  1763. date.push(seps.shift());
  1764. date.push(val[format.parts[i]]);
  1765. }
  1766. return date.join('');
  1767. },
  1768. headTemplate: '<thead>'+
  1769. '<tr>'+
  1770. '<th colspan="7" class="datepicker-title"></th>'+
  1771. '</tr>'+
  1772. '<tr>'+
  1773. '<th class="prev">'+defaults.templates.leftArrow+'</th>'+
  1774. '<th colspan="5" class="datepicker-switch"></th>'+
  1775. '<th class="next">'+defaults.templates.rightArrow+'</th>'+
  1776. '</tr>'+
  1777. '</thead>',
  1778. contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
  1779. footTemplate: '<tfoot>'+
  1780. '<tr>'+
  1781. '<th colspan="7" class="today"></th>'+
  1782. '</tr>'+
  1783. '<tr>'+
  1784. '<th colspan="7" class="clear"></th>'+
  1785. '</tr>'+
  1786. '</tfoot>'
  1787. };
  1788. DPGlobal.template = '<div class="datepicker">'+
  1789. '<div class="datepicker-days">'+
  1790. '<table class="table-condensed">'+
  1791. DPGlobal.headTemplate+
  1792. '<tbody></tbody>'+
  1793. DPGlobal.footTemplate+
  1794. '</table>'+
  1795. '</div>'+
  1796. '<div class="datepicker-months">'+
  1797. '<table class="table-condensed">'+
  1798. DPGlobal.headTemplate+
  1799. DPGlobal.contTemplate+
  1800. DPGlobal.footTemplate+
  1801. '</table>'+
  1802. '</div>'+
  1803. '<div class="datepicker-years">'+
  1804. '<table class="table-condensed">'+
  1805. DPGlobal.headTemplate+
  1806. DPGlobal.contTemplate+
  1807. DPGlobal.footTemplate+
  1808. '</table>'+
  1809. '</div>'+
  1810. '<div class="datepicker-decades">'+
  1811. '<table class="table-condensed">'+
  1812. DPGlobal.headTemplate+
  1813. DPGlobal.contTemplate+
  1814. DPGlobal.footTemplate+
  1815. '</table>'+
  1816. '</div>'+
  1817. '<div class="datepicker-centuries">'+
  1818. '<table class="table-condensed">'+
  1819. DPGlobal.headTemplate+
  1820. DPGlobal.contTemplate+
  1821. DPGlobal.footTemplate+
  1822. '</table>'+
  1823. '</div>'+
  1824. '</div>';
  1825. $.fn.datepicker.DPGlobal = DPGlobal;
  1826. /* DATEPICKER NO CONFLICT
  1827. * =================== */
  1828. $.fn.datepicker.noConflict = function(){
  1829. $.fn.datepicker = old;
  1830. return this;
  1831. };
  1832. /* DATEPICKER VERSION
  1833. * =================== */
  1834. $.fn.datepicker.version = '1.8.0';
  1835. $.fn.datepicker.deprecated = function(msg){
  1836. var console = window.console;
  1837. if (console && console.warn) {
  1838. console.warn('DEPRECATED: ' + msg);
  1839. }
  1840. };
  1841. /* DATEPICKER DATA-API
  1842. * ================== */
  1843. $(document).on(
  1844. 'focus.datepicker.data-api click.datepicker.data-api',
  1845. '[data-provide="datepicker"]',
  1846. function(e){
  1847. var $this = $(this);
  1848. if ($this.data('datepicker'))
  1849. return;
  1850. e.preventDefault();
  1851. // component click requires us to explicitly show it
  1852. datepickerPlugin.call($this, 'show');
  1853. }
  1854. );
  1855. $(function(){
  1856. datepickerPlugin.call($('[data-provide="datepicker-inline"]'));
  1857. });
  1858. }));