bootstrap-datepicker.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. /* =========================================================
  2. * bootstrap-datepicker.js
  3. * http://www.eyecon.ro/bootstrap-datepicker
  4. * =========================================================
  5. * Copyright 2012 Stefan Petre
  6. * Improvements by Andrew Rowls
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. * ========================================================= */
  20. !function( $ ) {
  21. function UTCDate(){
  22. return new Date(Date.UTC.apply(Date, arguments));
  23. }
  24. function UTCToday(){
  25. var today = new Date();
  26. return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
  27. }
  28. // Picker object
  29. var Datepicker = function(element, options) {
  30. var that = this;
  31. this._process_options(options);
  32. this.element = $(element);
  33. this.isInline = false;
  34. this.isInput = this.element.is('input');
  35. this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false;
  36. this.hasInput = this.component && this.element.find('input').length;
  37. if(this.component && this.component.length === 0)
  38. this.component = false;
  39. this.picker = $(DPGlobal.template);
  40. this._buildEvents();
  41. this._attachEvents();
  42. if(this.isInline) {
  43. this.picker.addClass('datepicker-inline').appendTo(this.element);
  44. } else {
  45. this.picker.addClass('datepicker-dropdown dropdown-menu');
  46. }
  47. if (this.o.rtl){
  48. this.picker.addClass('datepicker-rtl');
  49. this.picker.find('.prev i, .next i')
  50. .toggleClass('icon-arrow-left icon-arrow-right');
  51. }
  52. this.viewMode = this.o.startView;
  53. if (this.o.calendarWeeks)
  54. this.picker.find('tfoot th.today')
  55. .attr('colspan', function(i, val){
  56. return parseInt(val) + 1;
  57. });
  58. this._allow_update = false;
  59. this.setStartDate(this.o.startDate);
  60. this.setEndDate(this.o.endDate);
  61. this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);
  62. this.fillDow();
  63. this.fillMonths();
  64. this._allow_update = true;
  65. this.update();
  66. this.showMode();
  67. if(this.isInline) {
  68. this.show();
  69. }
  70. };
  71. Datepicker.prototype = {
  72. constructor: Datepicker,
  73. _process_options: function(opts){
  74. // Store raw options for reference
  75. this._o = $.extend({}, this._o, opts);
  76. // Processed options
  77. var o = this.o = $.extend({}, this._o);
  78. // Check if "de-DE" style date is available, if not language should
  79. // fallback to 2 letter code eg "de"
  80. var lang = o.language;
  81. if (!dates[lang]) {
  82. lang = lang.split('-')[0];
  83. if (!dates[lang])
  84. lang = $.fn.datepicker.defaults.language;
  85. }
  86. o.language = lang;
  87. switch(o.startView){
  88. case 2:
  89. case 'decade':
  90. o.startView = 2;
  91. break;
  92. case 1:
  93. case 'year':
  94. o.startView = 1;
  95. break;
  96. default:
  97. o.startView = 0;
  98. }
  99. switch (o.minViewMode) {
  100. case 1:
  101. case 'months':
  102. o.minViewMode = 1;
  103. break;
  104. case 2:
  105. case 'years':
  106. o.minViewMode = 2;
  107. break;
  108. default:
  109. o.minViewMode = 0;
  110. }
  111. o.startView = Math.max(o.startView, o.minViewMode);
  112. o.weekStart %= 7;
  113. o.weekEnd = ((o.weekStart + 6) % 7);
  114. var format = DPGlobal.parseFormat(o.format)
  115. if (o.startDate !== -Infinity) {
  116. o.startDate = DPGlobal.parseDate(o.startDate, format, o.language);
  117. }
  118. if (o.endDate !== Infinity) {
  119. o.endDate = DPGlobal.parseDate(o.endDate, format, o.language);
  120. }
  121. o.daysOfWeekDisabled = o.daysOfWeekDisabled||[];
  122. if (!$.isArray(o.daysOfWeekDisabled))
  123. o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/);
  124. o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) {
  125. return parseInt(d, 10);
  126. });
  127. },
  128. _events: [],
  129. _secondaryEvents: [],
  130. _applyEvents: function(evs){
  131. for (var i=0, el, ev; i<evs.length; i++){
  132. el = evs[i][0];
  133. ev = evs[i][1];
  134. el.on(ev);
  135. }
  136. },
  137. _unapplyEvents: function(evs){
  138. for (var i=0, el, ev; i<evs.length; i++){
  139. el = evs[i][0];
  140. ev = evs[i][1];
  141. el.off(ev);
  142. }
  143. },
  144. _buildEvents: function(){
  145. if (this.isInput) { // single input
  146. this._events = [
  147. [this.element, {
  148. focus: $.proxy(this.show, this),
  149. keyup: $.proxy(this.update, this),
  150. keydown: $.proxy(this.keydown, this)
  151. }]
  152. ];
  153. }
  154. else if (this.component && this.hasInput){ // component: input + button
  155. this._events = [
  156. // For components that are not readonly, allow keyboard nav
  157. [this.element.find('input'), {
  158. focus: $.proxy(this.show, this),
  159. keyup: $.proxy(this.update, this),
  160. keydown: $.proxy(this.keydown, this)
  161. }],
  162. [this.component, {
  163. click: $.proxy(this.show, this)
  164. }]
  165. ];
  166. }
  167. else if (this.element.is('div')) { // inline datepicker
  168. this.isInline = true;
  169. }
  170. else {
  171. this._events = [
  172. [this.element, {
  173. click: $.proxy(this.show, this)
  174. }]
  175. ];
  176. }
  177. this._secondaryEvents = [
  178. [this.picker, {
  179. click: $.proxy(this.click, this)
  180. }],
  181. [$(window), {
  182. resize: $.proxy(this.place, this)
  183. }],
  184. [$(document), {
  185. mousedown: $.proxy(function (e) {
  186. // Clicked outside the datepicker, hide it
  187. if (!(
  188. this.element.is(e.target) ||
  189. this.element.find(e.target).size() ||
  190. this.picker.is(e.target) ||
  191. this.picker.find(e.target).size()
  192. )) {
  193. this.hide();
  194. }
  195. }, this)
  196. }]
  197. ];
  198. },
  199. _attachEvents: function(){
  200. this._detachEvents();
  201. this._applyEvents(this._events);
  202. },
  203. _detachEvents: function(){
  204. this._unapplyEvents(this._events);
  205. },
  206. _attachSecondaryEvents: function(){
  207. this._detachSecondaryEvents();
  208. this._applyEvents(this._secondaryEvents);
  209. },
  210. _detachSecondaryEvents: function(){
  211. this._unapplyEvents(this._secondaryEvents);
  212. },
  213. _trigger: function(event, altdate){
  214. var date = altdate || this.date,
  215. local_date = new Date(date.getTime() + (date.getTimezoneOffset()*60000));
  216. this.element.trigger({
  217. type: event,
  218. date: local_date,
  219. format: $.proxy(function(altformat){
  220. var format = altformat || this.o.format;
  221. return DPGlobal.formatDate(date, format, this.language);
  222. }, this)
  223. });
  224. },
  225. show: function(e) {
  226. if (!this.isInline)
  227. this.picker.appendTo('body');
  228. this.picker.show();
  229. this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
  230. this.place();
  231. this._attachSecondaryEvents();
  232. if (e) {
  233. e.preventDefault();
  234. }
  235. this._trigger('show');
  236. },
  237. hide: function(e){
  238. if(this.isInline) return;
  239. if (!this.picker.is(':visible')) return;
  240. this.picker.hide().detach();
  241. this._detachSecondaryEvents();
  242. this.viewMode = this.o.startView;
  243. this.showMode();
  244. if (
  245. this.o.forceParse &&
  246. (
  247. this.isInput && this.element.val() ||
  248. this.hasInput && this.element.find('input').val()
  249. )
  250. )
  251. this.setValue();
  252. this._trigger('hide');
  253. },
  254. remove: function() {
  255. this.hide();
  256. this._detachEvents();
  257. this._detachSecondaryEvents();
  258. this.picker.remove();
  259. delete this.element.data().datepicker;
  260. if (!this.isInput) {
  261. delete this.element.data().date;
  262. }
  263. },
  264. getDate: function() {
  265. var d = this.getUTCDate();
  266. return new Date(d.getTime() + (d.getTimezoneOffset()*60000));
  267. },
  268. getUTCDate: function() {
  269. return this.date;
  270. },
  271. setDate: function(d) {
  272. this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000)));
  273. },
  274. setUTCDate: function(d) {
  275. this.date = d;
  276. this.setValue();
  277. },
  278. setValue: function() {
  279. var formatted = this.getFormattedDate();
  280. if (!this.isInput) {
  281. if (this.component){
  282. this.element.find('input').val(formatted);
  283. }
  284. } else {
  285. this.element.val(formatted);
  286. }
  287. },
  288. getFormattedDate: function(format) {
  289. if (format === undefined)
  290. format = this.o.format;
  291. return DPGlobal.formatDate(this.date, format, this.o.language);
  292. },
  293. setStartDate: function(startDate){
  294. this._process_options({startDate: startDate});
  295. this.update();
  296. this.updateNavArrows();
  297. },
  298. setEndDate: function(endDate){
  299. this._process_options({endDate: endDate});
  300. this.update();
  301. this.updateNavArrows();
  302. },
  303. setDaysOfWeekDisabled: function(daysOfWeekDisabled){
  304. this._process_options({daysOfWeekDisabled: daysOfWeekDisabled});
  305. this.update();
  306. this.updateNavArrows();
  307. },
  308. place: function(){
  309. if(this.isInline) return;
  310. var zIndex = parseInt(this.element.parents().filter(function() {
  311. return $(this).css('z-index') != 'auto';
  312. }).first().css('z-index'))+10;
  313. var offset = this.component ? this.component.parent().offset() : this.element.offset();
  314. var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true);
  315. this.picker.css({
  316. top: offset.top + height,
  317. left: offset.left,
  318. zIndex: zIndex
  319. });
  320. },
  321. _allow_update: true,
  322. update: function(){
  323. if (!this._allow_update) return;
  324. var date, fromArgs = false;
  325. if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) {
  326. date = arguments[0];
  327. fromArgs = true;
  328. } else {
  329. date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val();
  330. delete this.element.data().date;
  331. }
  332. this.date = DPGlobal.parseDate(date, this.o.format, this.o.language);
  333. if(fromArgs) this.setValue();
  334. if (this.date < this.o.startDate) {
  335. this.viewDate = new Date(this.o.startDate);
  336. } else if (this.date > this.o.endDate) {
  337. this.viewDate = new Date(this.o.endDate);
  338. } else {
  339. this.viewDate = new Date(this.date);
  340. }
  341. this.fill();
  342. },
  343. fillDow: function(){
  344. var dowCnt = this.o.weekStart,
  345. html = '<tr>';
  346. if(this.o.calendarWeeks){
  347. var cell = '<th class="cw">&nbsp;</th>';
  348. html += cell;
  349. this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
  350. }
  351. while (dowCnt < this.o.weekStart + 7) {
  352. html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>';
  353. }
  354. html += '</tr>';
  355. this.picker.find('.datepicker-days thead').append(html);
  356. },
  357. fillMonths: function(){
  358. var html = '',
  359. i = 0;
  360. while (i < 12) {
  361. html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>';
  362. }
  363. this.picker.find('.datepicker-months td').html(html);
  364. },
  365. setRange: function(range){
  366. if (!range || !range.length)
  367. delete this.range;
  368. else
  369. this.range = $.map(range, function(d){ return d.valueOf(); });
  370. this.fill();
  371. },
  372. getClassNames: function(date){
  373. var cls = [],
  374. year = this.viewDate.getUTCFullYear(),
  375. month = this.viewDate.getUTCMonth(),
  376. currentDate = this.date.valueOf(),
  377. today = new Date();
  378. if (date.getUTCFullYear() < year || (date.getUTCFullYear() == year && date.getUTCMonth() < month)) {
  379. cls.push('old');
  380. } else if (date.getUTCFullYear() > year || (date.getUTCFullYear() == year && date.getUTCMonth() > month)) {
  381. cls.push('new');
  382. }
  383. // Compare internal UTC date with local today, not UTC today
  384. if (this.o.todayHighlight &&
  385. date.getUTCFullYear() == today.getFullYear() &&
  386. date.getUTCMonth() == today.getMonth() &&
  387. date.getUTCDate() == today.getDate()) {
  388. cls.push('today');
  389. }
  390. if (currentDate && date.valueOf() == currentDate) {
  391. cls.push('active');
  392. }
  393. if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate ||
  394. $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) {
  395. cls.push('disabled');
  396. }
  397. if (this.range){
  398. if (date > this.range[0] && date < this.range[this.range.length-1]){
  399. cls.push('range');
  400. }
  401. if ($.inArray(date.valueOf(), this.range) != -1){
  402. cls.push('selected');
  403. }
  404. }
  405. return cls;
  406. },
  407. fill: function() {
  408. var d = new Date(this.viewDate),
  409. year = d.getUTCFullYear(),
  410. month = d.getUTCMonth(),
  411. startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
  412. startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
  413. endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
  414. endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
  415. currentDate = this.date && this.date.valueOf(),
  416. tooltip;
  417. this.picker.find('.datepicker-days thead th.datepicker-switch')
  418. .text(dates[this.o.language].months[month]+' '+year);
  419. this.picker.find('tfoot th.today')
  420. .text(dates[this.o.language].today)
  421. .toggle(this.o.todayBtn !== false);
  422. this.picker.find('tfoot th.clear')
  423. .text(dates[this.o.language].clear)
  424. .toggle(this.o.clearBtn !== false);
  425. this.updateNavArrows();
  426. this.fillMonths();
  427. var prevMonth = UTCDate(year, month-1, 28,0,0,0,0),
  428. day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
  429. prevMonth.setUTCDate(day);
  430. prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7);
  431. var nextMonth = new Date(prevMonth);
  432. nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
  433. nextMonth = nextMonth.valueOf();
  434. var html = [];
  435. var clsName;
  436. while(prevMonth.valueOf() < nextMonth) {
  437. if (prevMonth.getUTCDay() == this.o.weekStart) {
  438. html.push('<tr>');
  439. if(this.o.calendarWeeks){
  440. // ISO 8601: First week contains first thursday.
  441. // ISO also states week starts on Monday, but we can be more abstract here.
  442. var
  443. // Start of current week: based on weekstart/current date
  444. ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
  445. // Thursday of this week
  446. th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
  447. // First Thursday of year, year from thursday
  448. yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
  449. // Calendar week: ms between thursdays, div ms per day, div 7 days
  450. calWeek = (th - yth) / 864e5 / 7 + 1;
  451. html.push('<td class="cw">'+ calWeek +'</td>');
  452. }
  453. }
  454. clsName = this.getClassNames(prevMonth);
  455. clsName.push('day');
  456. var before = this.o.beforeShowDay(prevMonth);
  457. if (before === undefined)
  458. before = {};
  459. else if (typeof(before) === 'boolean')
  460. before = {enabled: before};
  461. else if (typeof(before) === 'string')
  462. before = {classes: before};
  463. if (before.enabled === false)
  464. clsName.push('disabled');
  465. if (before.classes)
  466. clsName = clsName.concat(before.classes.split(/\s+/));
  467. if (before.tooltip)
  468. tooltip = before.tooltip;
  469. clsName = $.unique(clsName);
  470. html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>');
  471. if (prevMonth.getUTCDay() == this.o.weekEnd) {
  472. html.push('</tr>');
  473. }
  474. prevMonth.setUTCDate(prevMonth.getUTCDate()+1);
  475. }
  476. this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
  477. var currentYear = this.date && this.date.getUTCFullYear();
  478. var months = this.picker.find('.datepicker-months')
  479. .find('th:eq(1)')
  480. .text(year)
  481. .end()
  482. .find('span').removeClass('active');
  483. if (currentYear && currentYear == year) {
  484. months.eq(this.date.getUTCMonth()).addClass('active');
  485. }
  486. if (year < startYear || year > endYear) {
  487. months.addClass('disabled');
  488. }
  489. if (year == startYear) {
  490. months.slice(0, startMonth).addClass('disabled');
  491. }
  492. if (year == endYear) {
  493. months.slice(endMonth+1).addClass('disabled');
  494. }
  495. html = '';
  496. year = parseInt(year/10, 10) * 10;
  497. var yearCont = this.picker.find('.datepicker-years')
  498. .find('th:eq(1)')
  499. .text(year + '-' + (year + 9))
  500. .end()
  501. .find('td');
  502. year -= 1;
  503. for (var i = -1; i < 11; i++) {
  504. html += '<span class="year'+(i == -1 ? ' old' : i == 10 ? ' new' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>';
  505. year += 1;
  506. }
  507. yearCont.html(html);
  508. },
  509. updateNavArrows: function() {
  510. if (!this._allow_update) return;
  511. var d = new Date(this.viewDate),
  512. year = d.getUTCFullYear(),
  513. month = d.getUTCMonth();
  514. switch (this.viewMode) {
  515. case 0:
  516. if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) {
  517. this.picker.find('.prev').css({visibility: 'hidden'});
  518. } else {
  519. this.picker.find('.prev').css({visibility: 'visible'});
  520. }
  521. if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) {
  522. this.picker.find('.next').css({visibility: 'hidden'});
  523. } else {
  524. this.picker.find('.next').css({visibility: 'visible'});
  525. }
  526. break;
  527. case 1:
  528. case 2:
  529. if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) {
  530. this.picker.find('.prev').css({visibility: 'hidden'});
  531. } else {
  532. this.picker.find('.prev').css({visibility: 'visible'});
  533. }
  534. if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) {
  535. this.picker.find('.next').css({visibility: 'hidden'});
  536. } else {
  537. this.picker.find('.next').css({visibility: 'visible'});
  538. }
  539. break;
  540. }
  541. },
  542. click: function(e) {
  543. e.preventDefault();
  544. var target = $(e.target).closest('span, td, th');
  545. if (target.length == 1) {
  546. switch(target[0].nodeName.toLowerCase()) {
  547. case 'th':
  548. switch(target[0].className) {
  549. case 'datepicker-switch':
  550. this.showMode(1);
  551. break;
  552. case 'prev':
  553. case 'next':
  554. var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1);
  555. switch(this.viewMode){
  556. case 0:
  557. this.viewDate = this.moveMonth(this.viewDate, dir);
  558. break;
  559. case 1:
  560. case 2:
  561. this.viewDate = this.moveYear(this.viewDate, dir);
  562. break;
  563. }
  564. this.fill();
  565. break;
  566. case 'today':
  567. var date = new Date();
  568. date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
  569. this.showMode(-2);
  570. var which = this.o.todayBtn == 'linked' ? null : 'view';
  571. this._setDate(date, which);
  572. break;
  573. case 'clear':
  574. if (this.isInput)
  575. this.element.val("");
  576. else
  577. this.element.find('input').val("");
  578. this.update();
  579. if (this.o.autoclose)
  580. this.hide();
  581. break;
  582. }
  583. break;
  584. case 'span':
  585. if (!target.is('.disabled')) {
  586. this.viewDate.setUTCDate(1);
  587. if (target.is('.month')) {
  588. var day = 1;
  589. var month = target.parent().find('span').index(target);
  590. var year = this.viewDate.getUTCFullYear();
  591. this.viewDate.setUTCMonth(month);
  592. this._trigger('changeMonth', this.viewDate);
  593. if (this.o.minViewMode === 1) {
  594. this._setDate(UTCDate(year, month, day,0,0,0,0));
  595. }
  596. } else {
  597. var year = parseInt(target.text(), 10)||0;
  598. var day = 1;
  599. var month = 0;
  600. this.viewDate.setUTCFullYear(year);
  601. this._trigger('changeYear', this.viewDate);
  602. if (this.o.minViewMode === 2) {
  603. this._setDate(UTCDate(year, month, day,0,0,0,0));
  604. }
  605. }
  606. this.showMode(-1);
  607. this.fill();
  608. }
  609. break;
  610. case 'td':
  611. if (target.is('.day') && !target.is('.disabled')){
  612. var day = parseInt(target.text(), 10)||1;
  613. var year = this.viewDate.getUTCFullYear(),
  614. month = this.viewDate.getUTCMonth();
  615. if (target.is('.old')) {
  616. if (month === 0) {
  617. month = 11;
  618. year -= 1;
  619. } else {
  620. month -= 1;
  621. }
  622. } else if (target.is('.new')) {
  623. if (month == 11) {
  624. month = 0;
  625. year += 1;
  626. } else {
  627. month += 1;
  628. }
  629. }
  630. this._setDate(UTCDate(year, month, day,0,0,0,0));
  631. }
  632. break;
  633. }
  634. }
  635. },
  636. _setDate: function(date, which){
  637. if (!which || which == 'date')
  638. this.date = new Date(date);
  639. if (!which || which == 'view')
  640. this.viewDate = new Date(date);
  641. this.fill();
  642. this.setValue();
  643. this._trigger('changeDate');
  644. var element;
  645. if (this.isInput) {
  646. element = this.element;
  647. } else if (this.component){
  648. element = this.element.find('input');
  649. }
  650. if (element) {
  651. element.change();
  652. if (this.o.autoclose && (!which || which == 'date')) {
  653. this.hide();
  654. }
  655. }
  656. },
  657. moveMonth: function(date, dir){
  658. if (!dir) return date;
  659. var new_date = new Date(date.valueOf()),
  660. day = new_date.getUTCDate(),
  661. month = new_date.getUTCMonth(),
  662. mag = Math.abs(dir),
  663. new_month, test;
  664. dir = dir > 0 ? 1 : -1;
  665. if (mag == 1){
  666. test = dir == -1
  667. // If going back one month, make sure month is not current month
  668. // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
  669. ? function(){ return new_date.getUTCMonth() == month; }
  670. // If going forward one month, make sure month is as expected
  671. // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
  672. : function(){ return new_date.getUTCMonth() != new_month; };
  673. new_month = month + dir;
  674. new_date.setUTCMonth(new_month);
  675. // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
  676. if (new_month < 0 || new_month > 11)
  677. new_month = (new_month + 12) % 12;
  678. } else {
  679. // For magnitudes >1, move one month at a time...
  680. for (var i=0; i<mag; i++)
  681. // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
  682. new_date = this.moveMonth(new_date, dir);
  683. // ...then reset the day, keeping it in the new month
  684. new_month = new_date.getUTCMonth();
  685. new_date.setUTCDate(day);
  686. test = function(){ return new_month != new_date.getUTCMonth(); };
  687. }
  688. // Common date-resetting loop -- if date is beyond end of month, make it
  689. // end of month
  690. while (test()){
  691. new_date.setUTCDate(--day);
  692. new_date.setUTCMonth(new_month);
  693. }
  694. return new_date;
  695. },
  696. moveYear: function(date, dir){
  697. return this.moveMonth(date, dir*12);
  698. },
  699. dateWithinRange: function(date){
  700. return date >= this.o.startDate && date <= this.o.endDate;
  701. },
  702. keydown: function(e){
  703. if (this.picker.is(':not(:visible)')){
  704. if (e.keyCode == 27) // allow escape to hide and re-show picker
  705. this.show();
  706. return;
  707. }
  708. var dateChanged = false,
  709. dir, day, month,
  710. newDate, newViewDate;
  711. switch(e.keyCode){
  712. case 27: // escape
  713. this.hide();
  714. e.preventDefault();
  715. break;
  716. case 37: // left
  717. case 39: // right
  718. if (!this.o.keyboardNavigation) break;
  719. dir = e.keyCode == 37 ? -1 : 1;
  720. if (e.ctrlKey){
  721. newDate = this.moveYear(this.date, dir);
  722. newViewDate = this.moveYear(this.viewDate, dir);
  723. } else if (e.shiftKey){
  724. newDate = this.moveMonth(this.date, dir);
  725. newViewDate = this.moveMonth(this.viewDate, dir);
  726. } else {
  727. newDate = new Date(this.date);
  728. newDate.setUTCDate(this.date.getUTCDate() + dir);
  729. newViewDate = new Date(this.viewDate);
  730. newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
  731. }
  732. if (this.dateWithinRange(newDate)){
  733. this.date = newDate;
  734. this.viewDate = newViewDate;
  735. this.setValue();
  736. this.update();
  737. e.preventDefault();
  738. dateChanged = true;
  739. }
  740. break;
  741. case 38: // up
  742. case 40: // down
  743. if (!this.o.keyboardNavigation) break;
  744. dir = e.keyCode == 38 ? -1 : 1;
  745. if (e.ctrlKey){
  746. newDate = this.moveYear(this.date, dir);
  747. newViewDate = this.moveYear(this.viewDate, dir);
  748. } else if (e.shiftKey){
  749. newDate = this.moveMonth(this.date, dir);
  750. newViewDate = this.moveMonth(this.viewDate, dir);
  751. } else {
  752. newDate = new Date(this.date);
  753. newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
  754. newViewDate = new Date(this.viewDate);
  755. newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
  756. }
  757. if (this.dateWithinRange(newDate)){
  758. this.date = newDate;
  759. this.viewDate = newViewDate;
  760. this.setValue();
  761. this.update();
  762. e.preventDefault();
  763. dateChanged = true;
  764. }
  765. break;
  766. case 13: // enter
  767. this.hide();
  768. e.preventDefault();
  769. break;
  770. case 9: // tab
  771. this.hide();
  772. break;
  773. }
  774. if (dateChanged){
  775. this._trigger('changeDate');
  776. var element;
  777. if (this.isInput) {
  778. element = this.element;
  779. } else if (this.component){
  780. element = this.element.find('input');
  781. }
  782. if (element) {
  783. element.change();
  784. }
  785. }
  786. },
  787. showMode: function(dir) {
  788. if (dir) {
  789. this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir));
  790. }
  791. /*
  792. vitalets: fixing bug of very special conditions:
  793. jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover.
  794. Method show() does not set display css correctly and datepicker is not shown.
  795. Changed to .css('display', 'block') solve the problem.
  796. See https://github.com/vitalets/x-editable/issues/37
  797. In jquery 1.7.2+ everything works fine.
  798. */
  799. //this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
  800. this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block');
  801. this.updateNavArrows();
  802. }
  803. };
  804. var DateRangePicker = function(element, options){
  805. this.element = $(element);
  806. this.inputs = $.map(options.inputs, function(i){ return i.jquery ? i[0] : i; });
  807. delete options.inputs;
  808. $(this.inputs)
  809. .datepicker(options)
  810. .bind('changeDate', $.proxy(this.dateUpdated, this));
  811. this.pickers = $.map(this.inputs, function(i){ return $(i).data('datepicker'); });
  812. this.updateDates();
  813. };
  814. DateRangePicker.prototype = {
  815. updateDates: function(){
  816. this.dates = $.map(this.pickers, function(i){ return i.date; });
  817. this.updateRanges();
  818. },
  819. updateRanges: function(){
  820. var range = $.map(this.dates, function(d){ return d.valueOf(); });
  821. $.each(this.pickers, function(i, p){
  822. p.setRange(range);
  823. });
  824. },
  825. dateUpdated: function(e){
  826. var dp = $(e.target).data('datepicker'),
  827. new_date = dp.getUTCDate(),
  828. i = $.inArray(e.target, this.inputs),
  829. l = this.inputs.length;
  830. if (i == -1) return;
  831. if (new_date < this.dates[i]){
  832. // Date being moved earlier/left
  833. while (i>=0 && new_date < this.dates[i]){
  834. this.pickers[i--].setUTCDate(new_date);
  835. }
  836. }
  837. else if (new_date > this.dates[i]){
  838. // Date being moved later/right
  839. while (i<l && new_date > this.dates[i]){
  840. this.pickers[i++].setUTCDate(new_date);
  841. }
  842. }
  843. this.updateDates();
  844. },
  845. remove: function(){
  846. $.map(this.pickers, function(p){ p.remove(); });
  847. delete this.element.data().datepicker;
  848. }
  849. };
  850. function opts_from_el(el, prefix){
  851. // Derive options from element data-attrs
  852. var data = $(el).data(),
  853. out = {}, inkey,
  854. replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'),
  855. prefix = new RegExp('^' + prefix.toLowerCase());
  856. for (var key in data)
  857. if (prefix.test(key)){
  858. inkey = key.replace(replace, function(_,a){ return a.toLowerCase(); });
  859. out[inkey] = data[key];
  860. }
  861. return out;
  862. }
  863. function opts_from_locale(lang){
  864. // Derive options from locale plugins
  865. var out = {};
  866. // Check if "de-DE" style date is available, if not language should
  867. // fallback to 2 letter code eg "de"
  868. if (!dates[lang]) {
  869. lang = lang.split('-')[0]
  870. if (!dates[lang])
  871. return;
  872. }
  873. var d = dates[lang];
  874. $.each($.fn.datepicker.locale_opts, function(i,k){
  875. if (k in d)
  876. out[k] = d[k];
  877. });
  878. return out;
  879. }
  880. var old = $.fn.datepicker;
  881. $.fn.datepicker = function ( option ) {
  882. var args = Array.apply(null, arguments);
  883. args.shift();
  884. var internal_return,
  885. this_return;
  886. this.each(function () {
  887. var $this = $(this),
  888. data = $this.data('datepicker'),
  889. options = typeof option == 'object' && option;
  890. if (!data) {
  891. var elopts = opts_from_el(this, 'date'),
  892. // Preliminary otions
  893. xopts = $.extend({}, $.fn.datepicker.defaults, elopts, options),
  894. locopts = opts_from_locale(xopts.language),
  895. // Options priority: js args, data-attrs, locales, defaults
  896. opts = $.extend({}, $.fn.datepicker.defaults, locopts, elopts, options);
  897. if ($this.is('.input-daterange') || opts.inputs){
  898. var ropts = {
  899. inputs: opts.inputs || $this.find('input').toArray()
  900. };
  901. $this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts))));
  902. }
  903. else{
  904. $this.data('datepicker', (data = new Datepicker(this, opts)));
  905. }
  906. }
  907. if (typeof option == 'string' && typeof data[option] == 'function') {
  908. internal_return = data[option].apply(data, args);
  909. if (internal_return !== undefined)
  910. return false;
  911. }
  912. });
  913. if (internal_return !== undefined)
  914. return internal_return;
  915. else
  916. return this;
  917. };
  918. $.fn.datepicker.defaults = {
  919. autoclose: false,
  920. beforeShowDay: $.noop,
  921. calendarWeeks: false,
  922. clearBtn: false,
  923. daysOfWeekDisabled: [],
  924. endDate: Infinity,
  925. forceParse: true,
  926. format: 'mm/dd/yyyy',
  927. keyboardNavigation: true,
  928. language: 'en',
  929. minViewMode: 0,
  930. rtl: false,
  931. startDate: -Infinity,
  932. startView: 0,
  933. todayBtn: false,
  934. todayHighlight: false,
  935. weekStart: 0
  936. };
  937. $.fn.datepicker.locale_opts = [
  938. 'format',
  939. 'rtl',
  940. 'weekStart'
  941. ];
  942. $.fn.datepicker.Constructor = Datepicker;
  943. var dates = $.fn.datepicker.dates = {
  944. en: {
  945. days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
  946. daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  947. daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
  948. months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  949. monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
  950. today: "Today",
  951. clear: "Clear"
  952. }
  953. };
  954. var DPGlobal = {
  955. modes: [
  956. {
  957. clsName: 'days',
  958. navFnc: 'Month',
  959. navStep: 1
  960. },
  961. {
  962. clsName: 'months',
  963. navFnc: 'FullYear',
  964. navStep: 1
  965. },
  966. {
  967. clsName: 'years',
  968. navFnc: 'FullYear',
  969. navStep: 10
  970. }],
  971. isLeapYear: function (year) {
  972. return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
  973. },
  974. getDaysInMonth: function (year, month) {
  975. return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
  976. },
  977. validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
  978. nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
  979. parseFormat: function(format){
  980. // IE treats \0 as a string end in inputs (truncating the value),
  981. // so it's a bad format delimiter, anyway
  982. var separators = format.replace(this.validParts, '\0').split('\0'),
  983. parts = format.match(this.validParts);
  984. if (!separators || !separators.length || !parts || parts.length === 0){
  985. throw new Error("Invalid date format.");
  986. }
  987. return {separators: separators, parts: parts};
  988. },
  989. parseDate: function(date, format, language) {
  990. if (date instanceof Date) return date;
  991. if (typeof format === 'string')
  992. format = DPGlobal.parseFormat(format);
  993. if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) {
  994. var part_re = /([\-+]\d+)([dmwy])/,
  995. parts = date.match(/([\-+]\d+)([dmwy])/g),
  996. part, dir;
  997. date = new Date();
  998. for (var i=0; i<parts.length; i++) {
  999. part = part_re.exec(parts[i]);
  1000. dir = parseInt(part[1]);
  1001. switch(part[2]){
  1002. case 'd':
  1003. date.setUTCDate(date.getUTCDate() + dir);
  1004. break;
  1005. case 'm':
  1006. date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
  1007. break;
  1008. case 'w':
  1009. date.setUTCDate(date.getUTCDate() + dir * 7);
  1010. break;
  1011. case 'y':
  1012. date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
  1013. break;
  1014. }
  1015. }
  1016. return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
  1017. }
  1018. var parts = date && date.match(this.nonpunctuation) || [],
  1019. date = new Date(),
  1020. parsed = {},
  1021. setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
  1022. setters_map = {
  1023. yyyy: function(d,v){ return d.setUTCFullYear(v); },
  1024. yy: function(d,v){ return d.setUTCFullYear(2000+v); },
  1025. m: function(d,v){
  1026. v -= 1;
  1027. while (v<0) v += 12;
  1028. v %= 12;
  1029. d.setUTCMonth(v);
  1030. while (d.getUTCMonth() != v)
  1031. d.setUTCDate(d.getUTCDate()-1);
  1032. return d;
  1033. },
  1034. d: function(d,v){ return d.setUTCDate(v); }
  1035. },
  1036. val, filtered, part;
  1037. setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
  1038. setters_map['dd'] = setters_map['d'];
  1039. date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
  1040. var fparts = format.parts.slice();
  1041. // Remove noop parts
  1042. if (parts.length != fparts.length) {
  1043. fparts = $(fparts).filter(function(i,p){
  1044. return $.inArray(p, setters_order) !== -1;
  1045. }).toArray();
  1046. }
  1047. // Process remainder
  1048. if (parts.length == fparts.length) {
  1049. for (var i=0, cnt = fparts.length; i < cnt; i++) {
  1050. val = parseInt(parts[i], 10);
  1051. part = fparts[i];
  1052. if (isNaN(val)) {
  1053. switch(part) {
  1054. case 'MM':
  1055. filtered = $(dates[language].months).filter(function(){
  1056. var m = this.slice(0, parts[i].length),
  1057. p = parts[i].slice(0, m.length);
  1058. return m == p;
  1059. });
  1060. val = $.inArray(filtered[0], dates[language].months) + 1;
  1061. break;
  1062. case 'M':
  1063. filtered = $(dates[language].monthsShort).filter(function(){
  1064. var m = this.slice(0, parts[i].length),
  1065. p = parts[i].slice(0, m.length);
  1066. return m == p;
  1067. });
  1068. val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
  1069. break;
  1070. }
  1071. }
  1072. parsed[part] = val;
  1073. }
  1074. for (var i=0, s; i<setters_order.length; i++){
  1075. s = setters_order[i];
  1076. if (s in parsed && !isNaN(parsed[s]))
  1077. setters_map[s](date, parsed[s]);
  1078. }
  1079. }
  1080. return date;
  1081. },
  1082. formatDate: function(date, format, language){
  1083. if (typeof format === 'string')
  1084. format = DPGlobal.parseFormat(format);
  1085. var val = {
  1086. d: date.getUTCDate(),
  1087. D: dates[language].daysShort[date.getUTCDay()],
  1088. DD: dates[language].days[date.getUTCDay()],
  1089. m: date.getUTCMonth() + 1,
  1090. M: dates[language].monthsShort[date.getUTCMonth()],
  1091. MM: dates[language].months[date.getUTCMonth()],
  1092. yy: date.getUTCFullYear().toString().substring(2),
  1093. yyyy: date.getUTCFullYear()
  1094. };
  1095. val.dd = (val.d < 10 ? '0' : '') + val.d;
  1096. val.mm = (val.m < 10 ? '0' : '') + val.m;
  1097. var date = [],
  1098. seps = $.extend([], format.separators);
  1099. for (var i=0, cnt = format.parts.length; i <= cnt; i++) {
  1100. if (seps.length)
  1101. date.push(seps.shift());
  1102. date.push(val[format.parts[i]]);
  1103. }
  1104. return date.join('');
  1105. },
  1106. headTemplate: '<thead>'+
  1107. '<tr>'+
  1108. '<th class="prev"><i class="icon-angle-left"/></th>'+
  1109. '<th colspan="5" class="datepicker-switch"></th>'+
  1110. '<th class="next"><i class="icon-angle-right"/></th>'+
  1111. '</tr>'+
  1112. '</thead>',
  1113. contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
  1114. footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>'
  1115. };
  1116. DPGlobal.template = '<div class="datepicker">'+
  1117. '<div class="datepicker-days">'+
  1118. '<table class=" table-condensed">'+
  1119. DPGlobal.headTemplate+
  1120. '<tbody></tbody>'+
  1121. DPGlobal.footTemplate+
  1122. '</table>'+
  1123. '</div>'+
  1124. '<div class="datepicker-months">'+
  1125. '<table class="table-condensed">'+
  1126. DPGlobal.headTemplate+
  1127. DPGlobal.contTemplate+
  1128. DPGlobal.footTemplate+
  1129. '</table>'+
  1130. '</div>'+
  1131. '<div class="datepicker-years">'+
  1132. '<table class="table-condensed">'+
  1133. DPGlobal.headTemplate+
  1134. DPGlobal.contTemplate+
  1135. DPGlobal.footTemplate+
  1136. '</table>'+
  1137. '</div>'+
  1138. '</div>';
  1139. $.fn.datepicker.DPGlobal = DPGlobal;
  1140. /* DATEPICKER NO CONFLICT
  1141. * =================== */
  1142. $.fn.datepicker.noConflict = function(){
  1143. $.fn.datepicker = old;
  1144. return this;
  1145. };
  1146. /* DATEPICKER DATA-API
  1147. * ================== */
  1148. $(document).on(
  1149. 'focus.datepicker.data-api click.datepicker.data-api',
  1150. '[data-provide="datepicker"]',
  1151. function(e){
  1152. var $this = $(this);
  1153. if ($this.data('datepicker')) return;
  1154. e.preventDefault();
  1155. // component click requires us to explicitly show it
  1156. $this.datepicker('show');
  1157. }
  1158. );
  1159. $(function(){
  1160. $('[data-provide="datepicker-inline"]').datepicker();
  1161. });
  1162. }( window.jQuery );