datepicker.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  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.element = $(element);
  32. this.language = options.language||this.element.data('date-language')||"en";
  33. this.language = this.language in dates ? this.language : this.language.split('-')[0]; //Check if "de-DE" style date is available, if not language should fallback to 2 letter code eg "de"
  34. this.language = this.language in dates ? this.language : "en";
  35. this.isRTL = dates[this.language].rtl||false;
  36. this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||dates[this.language].format||'mm/dd/yyyy');
  37. this.isInline = false;
  38. this.isInput = this.element.is('input');
  39. this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false;
  40. this.hasInput = this.component && this.element.find('input').length;
  41. if(this.component && this.component.length === 0)
  42. this.component = false;
  43. this.forceParse = true;
  44. if ('forceParse' in options) {
  45. this.forceParse = options.forceParse;
  46. } else if ('dateForceParse' in this.element.data()) {
  47. this.forceParse = this.element.data('date-force-parse');
  48. }
  49. this.picker = $(DPGlobal.template);
  50. this._buildEvents();
  51. this._attachEvents();
  52. if(this.isInline) {
  53. this.picker.addClass('datepicker-inline').appendTo(this.element);
  54. } else {
  55. this.picker.addClass('datepicker-dropdown dropdown-menu');
  56. }
  57. if (this.isRTL){
  58. this.picker.addClass('datepicker-rtl');
  59. this.picker.find('.prev i, .next i')
  60. .toggleClass('icon-arrow-left icon-arrow-right');
  61. }
  62. this.autoclose = false;
  63. if ('autoclose' in options) {
  64. this.autoclose = options.autoclose;
  65. } else if ('dateAutoclose' in this.element.data()) {
  66. this.autoclose = this.element.data('date-autoclose');
  67. }
  68. this.keyboardNavigation = true;
  69. if ('keyboardNavigation' in options) {
  70. this.keyboardNavigation = options.keyboardNavigation;
  71. } else if ('dateKeyboardNavigation' in this.element.data()) {
  72. this.keyboardNavigation = this.element.data('date-keyboard-navigation');
  73. }
  74. this.viewMode = this.startViewMode = 0;
  75. switch(options.startView || this.element.data('date-start-view')){
  76. case 2:
  77. case 'decade':
  78. this.viewMode = this.startViewMode = 2;
  79. break;
  80. case 1:
  81. case 'year':
  82. this.viewMode = this.startViewMode = 1;
  83. break;
  84. }
  85. this.minViewMode = options.minViewMode||this.element.data('date-min-view-mode')||0;
  86. if (typeof this.minViewMode === 'string') {
  87. switch (this.minViewMode) {
  88. case 'months':
  89. this.minViewMode = 1;
  90. break;
  91. case 'years':
  92. this.minViewMode = 2;
  93. break;
  94. default:
  95. this.minViewMode = 0;
  96. break;
  97. }
  98. }
  99. this.viewMode = this.startViewMode = Math.max(this.startViewMode, this.minViewMode);
  100. this.todayBtn = (options.todayBtn||this.element.data('date-today-btn')||false);
  101. this.todayHighlight = (options.todayHighlight||this.element.data('date-today-highlight')||false);
  102. this.calendarWeeks = false;
  103. if ('calendarWeeks' in options) {
  104. this.calendarWeeks = options.calendarWeeks;
  105. } else if ('dateCalendarWeeks' in this.element.data()) {
  106. this.calendarWeeks = this.element.data('date-calendar-weeks');
  107. }
  108. if (this.calendarWeeks)
  109. this.picker.find('tfoot th.today')
  110. .attr('colspan', function(i, val){
  111. return parseInt(val) + 1;
  112. });
  113. this._allow_update = false;
  114. this.weekStart = ((options.weekStart||this.element.data('date-weekstart')||dates[this.language].weekStart||0) % 7);
  115. this.weekEnd = ((this.weekStart + 6) % 7);
  116. this.startDate = -Infinity;
  117. this.endDate = Infinity;
  118. this.daysOfWeekDisabled = [];
  119. this.setStartDate(options.startDate||this.element.data('date-startdate'));
  120. this.setEndDate(options.endDate||this.element.data('date-enddate'));
  121. this.setDaysOfWeekDisabled(options.daysOfWeekDisabled||this.element.data('date-days-of-week-disabled'));
  122. this.fillDow();
  123. this.fillMonths();
  124. this._allow_update = true;
  125. this.update();
  126. this.showMode();
  127. if(this.isInline) {
  128. this.show();
  129. }
  130. };
  131. Datepicker.prototype = {
  132. constructor: Datepicker,
  133. _events: [],
  134. _secondaryEvents: [],
  135. _applyEvents: function(evs){
  136. for (var i=0, el, ev; i<evs.length; i++){
  137. el = evs[i][0];
  138. ev = evs[i][1];
  139. el.on(ev);
  140. }
  141. },
  142. _unapplyEvents: function(evs){
  143. for (var i=0, el, ev; i<evs.length; i++){
  144. el = evs[i][0];
  145. ev = evs[i][1];
  146. el.off(ev);
  147. }
  148. },
  149. _buildEvents: function(){
  150. if (this.isInput) { // single input
  151. this._events = [
  152. [this.element, {
  153. focus: $.proxy(this.show, this),
  154. keyup: $.proxy(this.update, this),
  155. keydown: $.proxy(this.keydown, this)
  156. }]
  157. ];
  158. }
  159. else if (this.component && this.hasInput){ // component: input + button
  160. this._events = [
  161. // For components that are not readonly, allow keyboard nav
  162. [this.element.find('input'), {
  163. focus: $.proxy(this.show, this),
  164. keyup: $.proxy(this.update, this),
  165. keydown: $.proxy(this.keydown, this)
  166. }],
  167. [this.component, {
  168. click: $.proxy(this.show, this)
  169. }]
  170. ];
  171. }
  172. else if (this.element.is('div')) { // inline datepicker
  173. this.isInline = true;
  174. }
  175. else {
  176. this._events = [
  177. [this.element, {
  178. click: $.proxy(this.show, this)
  179. }]
  180. ];
  181. }
  182. this._secondaryEvents = [
  183. [this.picker, {
  184. click: $.proxy(this.click, this)
  185. }],
  186. [$(window), {
  187. resize: $.proxy(this.place, this)
  188. }],
  189. [$(document), {
  190. mousedown: $.proxy(function (e) {
  191. // Clicked outside the datepicker, hide it
  192. if ($(e.target).closest('.datepicker.datepicker-inline, .datepicker.datepicker-dropdown').length === 0) {
  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. show: function(e) {
  214. if (!this.isInline)
  215. this.picker.appendTo('body');
  216. this.picker.show();
  217. this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
  218. this.place();
  219. this._attachSecondaryEvents();
  220. if (e) {
  221. e.preventDefault();
  222. }
  223. this.element.trigger({
  224. type: 'show',
  225. date: this.date
  226. });
  227. },
  228. hide: function(e){
  229. if(this.isInline) return;
  230. if (!this.picker.is(':visible')) return;
  231. this.picker.hide().detach();
  232. this._detachSecondaryEvents();
  233. this.viewMode = this.startViewMode;
  234. this.showMode();
  235. if (
  236. this.forceParse &&
  237. (
  238. this.isInput && this.element.val() ||
  239. this.hasInput && this.element.find('input').val()
  240. )
  241. )
  242. this.setValue();
  243. this.element.trigger({
  244. type: 'hide',
  245. date: this.date
  246. });
  247. },
  248. remove: function() {
  249. this.hide();
  250. this._detachEvents();
  251. this._detachSecondaryEvents();
  252. this.picker.remove();
  253. delete this.element.data().datepicker;
  254. if (!this.isInput) {
  255. delete this.element.data().date;
  256. }
  257. },
  258. getDate: function() {
  259. var d = this.getUTCDate();
  260. return new Date(d.getTime() + (d.getTimezoneOffset()*60000));
  261. },
  262. getUTCDate: function() {
  263. return this.date;
  264. },
  265. setDate: function(d) {
  266. this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000)));
  267. },
  268. setUTCDate: function(d) {
  269. this.date = d;
  270. this.setValue();
  271. },
  272. setValue: function() {
  273. var formatted = this.getFormattedDate();
  274. if (!this.isInput) {
  275. if (this.component){
  276. this.element.find('input').val(formatted);
  277. }
  278. this.element.data('date', formatted);
  279. } else {
  280. this.element.val(formatted);
  281. }
  282. },
  283. getFormattedDate: function(format) {
  284. if (format === undefined)
  285. format = this.format;
  286. return DPGlobal.formatDate(this.date, format, this.language);
  287. },
  288. setStartDate: function(startDate){
  289. this.startDate = startDate||-Infinity;
  290. if (this.startDate !== -Infinity) {
  291. this.startDate = DPGlobal.parseDate(this.startDate, this.format, this.language);
  292. }
  293. this.update();
  294. this.updateNavArrows();
  295. },
  296. setEndDate: function(endDate){
  297. this.endDate = endDate||Infinity;
  298. if (this.endDate !== Infinity) {
  299. this.endDate = DPGlobal.parseDate(this.endDate, this.format, this.language);
  300. }
  301. this.update();
  302. this.updateNavArrows();
  303. },
  304. setDaysOfWeekDisabled: function(daysOfWeekDisabled){
  305. this.daysOfWeekDisabled = daysOfWeekDisabled||[];
  306. if (!$.isArray(this.daysOfWeekDisabled)) {
  307. this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/);
  308. }
  309. this.daysOfWeekDisabled = $.map(this.daysOfWeekDisabled, function (d) {
  310. return parseInt(d, 10);
  311. });
  312. this.update();
  313. this.updateNavArrows();
  314. },
  315. place: function(){
  316. if(this.isInline) return;
  317. var zIndex = parseInt(this.element.parents().filter(function() {
  318. return $(this).css('z-index') != 'auto';
  319. }).first().css('z-index'))+10;
  320. var offset = this.component ? this.component.parent().offset() : this.element.offset();
  321. var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true);
  322. this.picker.css({
  323. top: offset.top + height,
  324. left: offset.left,
  325. zIndex: zIndex
  326. });
  327. },
  328. _allow_update: true,
  329. update: function(){
  330. if (!this._allow_update) return;
  331. var date, fromArgs = false;
  332. if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) {
  333. date = arguments[0];
  334. fromArgs = true;
  335. } else {
  336. date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val();
  337. }
  338. this.date = DPGlobal.parseDate(date, this.format, this.language);
  339. if(fromArgs) this.setValue();
  340. if (this.date < this.startDate) {
  341. this.viewDate = new Date(this.startDate);
  342. } else if (this.date > this.endDate) {
  343. this.viewDate = new Date(this.endDate);
  344. } else {
  345. this.viewDate = new Date(this.date);
  346. }
  347. this.fill();
  348. },
  349. fillDow: function(){
  350. var dowCnt = this.weekStart,
  351. html = '<tr>';
  352. if(this.calendarWeeks){
  353. var cell = '<th class="cw">&nbsp;</th>';
  354. html += cell;
  355. this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
  356. }
  357. while (dowCnt < this.weekStart + 7) {
  358. html += '<th class="dow">'+dates[this.language].daysMin[(dowCnt++)%7]+'</th>';
  359. }
  360. html += '</tr>';
  361. this.picker.find('.datepicker-days thead').append(html);
  362. },
  363. fillMonths: function(){
  364. var html = '',
  365. i = 0;
  366. while (i < 12) {
  367. html += '<span class="month">'+dates[this.language].monthsShort[i++]+'</span>';
  368. }
  369. this.picker.find('.datepicker-months td').html(html);
  370. },
  371. fill: function() {
  372. var d = new Date(this.viewDate),
  373. year = d.getUTCFullYear(),
  374. month = d.getUTCMonth(),
  375. startYear = this.startDate !== -Infinity ? this.startDate.getUTCFullYear() : -Infinity,
  376. startMonth = this.startDate !== -Infinity ? this.startDate.getUTCMonth() : -Infinity,
  377. endYear = this.endDate !== Infinity ? this.endDate.getUTCFullYear() : Infinity,
  378. endMonth = this.endDate !== Infinity ? this.endDate.getUTCMonth() : Infinity,
  379. currentDate = this.date && this.date.valueOf(),
  380. today = new Date();
  381. this.picker.find('.datepicker-days thead th.switch')
  382. .text(dates[this.language].months[month]+' '+year);
  383. this.picker.find('tfoot th.today')
  384. .text(dates[this.language].today)
  385. .toggle(this.todayBtn !== false);
  386. this.updateNavArrows();
  387. this.fillMonths();
  388. var prevMonth = UTCDate(year, month-1, 28,0,0,0,0),
  389. day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
  390. prevMonth.setUTCDate(day);
  391. prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7)%7);
  392. var nextMonth = new Date(prevMonth);
  393. nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
  394. nextMonth = nextMonth.valueOf();
  395. var html = [];
  396. var clsName;
  397. while(prevMonth.valueOf() < nextMonth) {
  398. if (prevMonth.getUTCDay() == this.weekStart) {
  399. html.push('<tr>');
  400. if(this.calendarWeeks){
  401. // ISO 8601: First week contains first thursday.
  402. // ISO also states week starts on Monday, but we can be more abstract here.
  403. var
  404. // Start of current week: based on weekstart/current date
  405. ws = new Date(+prevMonth + (this.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
  406. // Thursday of this week
  407. th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
  408. // First Thursday of year, year from thursday
  409. yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
  410. // Calendar week: ms between thursdays, div ms per day, div 7 days
  411. calWeek = (th - yth) / 864e5 / 7 + 1;
  412. html.push('<td class="cw">'+ calWeek +'</td>');
  413. }
  414. }
  415. clsName = '';
  416. if (prevMonth.getUTCFullYear() < year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() < month)) {
  417. clsName += ' old';
  418. } else if (prevMonth.getUTCFullYear() > year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() > month)) {
  419. clsName += ' new';
  420. }
  421. // Compare internal UTC date with local today, not UTC today
  422. if (this.todayHighlight &&
  423. prevMonth.getUTCFullYear() == today.getFullYear() &&
  424. prevMonth.getUTCMonth() == today.getMonth() &&
  425. prevMonth.getUTCDate() == today.getDate()) {
  426. clsName += ' today';
  427. }
  428. if (currentDate && prevMonth.valueOf() == currentDate) {
  429. clsName += ' active';
  430. }
  431. if (prevMonth.valueOf() < this.startDate || prevMonth.valueOf() > this.endDate ||
  432. $.inArray(prevMonth.getUTCDay(), this.daysOfWeekDisabled) !== -1) {
  433. clsName += ' disabled';
  434. }
  435. html.push('<td class="day'+clsName+'">'+prevMonth.getUTCDate() + '</td>');
  436. if (prevMonth.getUTCDay() == this.weekEnd) {
  437. html.push('</tr>');
  438. }
  439. prevMonth.setUTCDate(prevMonth.getUTCDate()+1);
  440. }
  441. this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
  442. var currentYear = this.date && this.date.getUTCFullYear();
  443. var months = this.picker.find('.datepicker-months')
  444. .find('th:eq(1)')
  445. .text(year)
  446. .end()
  447. .find('span').removeClass('active');
  448. if (currentYear && currentYear == year) {
  449. months.eq(this.date.getUTCMonth()).addClass('active');
  450. }
  451. if (year < startYear || year > endYear) {
  452. months.addClass('disabled');
  453. }
  454. if (year == startYear) {
  455. months.slice(0, startMonth).addClass('disabled');
  456. }
  457. if (year == endYear) {
  458. months.slice(endMonth+1).addClass('disabled');
  459. }
  460. html = '';
  461. year = parseInt(year/10, 10) * 10;
  462. var yearCont = this.picker.find('.datepicker-years')
  463. .find('th:eq(1)')
  464. .text(year + '-' + (year + 9))
  465. .end()
  466. .find('td');
  467. year -= 1;
  468. for (var i = -1; i < 11; i++) {
  469. html += '<span class="year'+(i == -1 || i == 10 ? ' old' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>';
  470. year += 1;
  471. }
  472. yearCont.html(html);
  473. },
  474. updateNavArrows: function() {
  475. if (!this._allow_update) return;
  476. var d = new Date(this.viewDate),
  477. year = d.getUTCFullYear(),
  478. month = d.getUTCMonth();
  479. switch (this.viewMode) {
  480. case 0:
  481. if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth()) {
  482. this.picker.find('.prev').css({visibility: 'hidden'});
  483. } else {
  484. this.picker.find('.prev').css({visibility: 'visible'});
  485. }
  486. if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth()) {
  487. this.picker.find('.next').css({visibility: 'hidden'});
  488. } else {
  489. this.picker.find('.next').css({visibility: 'visible'});
  490. }
  491. break;
  492. case 1:
  493. case 2:
  494. if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear()) {
  495. this.picker.find('.prev').css({visibility: 'hidden'});
  496. } else {
  497. this.picker.find('.prev').css({visibility: 'visible'});
  498. }
  499. if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear()) {
  500. this.picker.find('.next').css({visibility: 'hidden'});
  501. } else {
  502. this.picker.find('.next').css({visibility: 'visible'});
  503. }
  504. break;
  505. }
  506. },
  507. click: function(e) {
  508. e.preventDefault();
  509. var target = $(e.target).closest('span, td, th');
  510. if (target.length == 1) {
  511. switch(target[0].nodeName.toLowerCase()) {
  512. case 'th':
  513. switch(target[0].className) {
  514. case 'switch':
  515. this.showMode(1);
  516. break;
  517. case 'prev':
  518. case 'next':
  519. var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1);
  520. switch(this.viewMode){
  521. case 0:
  522. this.viewDate = this.moveMonth(this.viewDate, dir);
  523. break;
  524. case 1:
  525. case 2:
  526. this.viewDate = this.moveYear(this.viewDate, dir);
  527. break;
  528. }
  529. this.fill();
  530. break;
  531. case 'today':
  532. var date = new Date();
  533. date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
  534. this.showMode(-2);
  535. var which = this.todayBtn == 'linked' ? null : 'view';
  536. this._setDate(date, which);
  537. break;
  538. }
  539. break;
  540. case 'span':
  541. if (!target.is('.disabled')) {
  542. this.viewDate.setUTCDate(1);
  543. if (target.is('.month')) {
  544. var day = 1;
  545. var month = target.parent().find('span').index(target);
  546. var year = this.viewDate.getUTCFullYear();
  547. this.viewDate.setUTCMonth(month);
  548. this.element.trigger({
  549. type: 'changeMonth',
  550. date: this.viewDate
  551. });
  552. if ( this.minViewMode == 1 ) {
  553. this._setDate(UTCDate(year, month, day,0,0,0,0));
  554. }
  555. } else {
  556. var year = parseInt(target.text(), 10)||0;
  557. var day = 1;
  558. var month = 0;
  559. this.viewDate.setUTCFullYear(year);
  560. this.element.trigger({
  561. type: 'changeYear',
  562. date: this.viewDate
  563. });
  564. if ( this.minViewMode == 2 ) {
  565. this._setDate(UTCDate(year, month, day,0,0,0,0));
  566. }
  567. }
  568. this.showMode(-1);
  569. this.fill();
  570. }
  571. break;
  572. case 'td':
  573. if (target.is('.day') && !target.is('.disabled')){
  574. var day = parseInt(target.text(), 10)||1;
  575. var year = this.viewDate.getUTCFullYear(),
  576. month = this.viewDate.getUTCMonth();
  577. if (target.is('.old')) {
  578. if (month === 0) {
  579. month = 11;
  580. year -= 1;
  581. } else {
  582. month -= 1;
  583. }
  584. } else if (target.is('.new')) {
  585. if (month == 11) {
  586. month = 0;
  587. year += 1;
  588. } else {
  589. month += 1;
  590. }
  591. }
  592. this._setDate(UTCDate(year, month, day,0,0,0,0));
  593. }
  594. break;
  595. }
  596. }
  597. },
  598. _setDate: function(date, which){
  599. if (!which || which == 'date')
  600. this.date = date;
  601. if (!which || which == 'view')
  602. this.viewDate = date;
  603. this.fill();
  604. this.setValue();
  605. this.element.trigger({
  606. type: 'changeDate',
  607. date: this.date
  608. });
  609. var element;
  610. if (this.isInput) {
  611. element = this.element;
  612. } else if (this.component){
  613. element = this.element.find('input');
  614. }
  615. if (element) {
  616. element.change();
  617. if (this.autoclose && (!which || which == 'date')) {
  618. this.hide();
  619. }
  620. }
  621. },
  622. moveMonth: function(date, dir){
  623. if (!dir) return date;
  624. var new_date = new Date(date.valueOf()),
  625. day = new_date.getUTCDate(),
  626. month = new_date.getUTCMonth(),
  627. mag = Math.abs(dir),
  628. new_month, test;
  629. dir = dir > 0 ? 1 : -1;
  630. if (mag == 1){
  631. test = dir == -1
  632. // If going back one month, make sure month is not current month
  633. // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
  634. ? function(){ return new_date.getUTCMonth() == month; }
  635. // If going forward one month, make sure month is as expected
  636. // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
  637. : function(){ return new_date.getUTCMonth() != new_month; };
  638. new_month = month + dir;
  639. new_date.setUTCMonth(new_month);
  640. // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
  641. if (new_month < 0 || new_month > 11)
  642. new_month = (new_month + 12) % 12;
  643. } else {
  644. // For magnitudes >1, move one month at a time...
  645. for (var i=0; i<mag; i++)
  646. // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
  647. new_date = this.moveMonth(new_date, dir);
  648. // ...then reset the day, keeping it in the new month
  649. new_month = new_date.getUTCMonth();
  650. new_date.setUTCDate(day);
  651. test = function(){ return new_month != new_date.getUTCMonth(); };
  652. }
  653. // Common date-resetting loop -- if date is beyond end of month, make it
  654. // end of month
  655. while (test()){
  656. new_date.setUTCDate(--day);
  657. new_date.setUTCMonth(new_month);
  658. }
  659. return new_date;
  660. },
  661. moveYear: function(date, dir){
  662. return this.moveMonth(date, dir*12);
  663. },
  664. dateWithinRange: function(date){
  665. return date >= this.startDate && date <= this.endDate;
  666. },
  667. keydown: function(e){
  668. if (this.picker.is(':not(:visible)')){
  669. if (e.keyCode == 27) // allow escape to hide and re-show picker
  670. this.show();
  671. return;
  672. }
  673. var dateChanged = false,
  674. dir, day, month,
  675. newDate, newViewDate;
  676. switch(e.keyCode){
  677. case 27: // escape
  678. this.hide();
  679. e.preventDefault();
  680. break;
  681. case 37: // left
  682. case 39: // right
  683. if (!this.keyboardNavigation) break;
  684. dir = e.keyCode == 37 ? -1 : 1;
  685. if (e.ctrlKey){
  686. newDate = this.moveYear(this.date, dir);
  687. newViewDate = this.moveYear(this.viewDate, dir);
  688. } else if (e.shiftKey){
  689. newDate = this.moveMonth(this.date, dir);
  690. newViewDate = this.moveMonth(this.viewDate, dir);
  691. } else {
  692. newDate = new Date(this.date);
  693. newDate.setUTCDate(this.date.getUTCDate() + dir);
  694. newViewDate = new Date(this.viewDate);
  695. newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
  696. }
  697. if (this.dateWithinRange(newDate)){
  698. this.date = newDate;
  699. this.viewDate = newViewDate;
  700. this.setValue();
  701. this.update();
  702. e.preventDefault();
  703. dateChanged = true;
  704. }
  705. break;
  706. case 38: // up
  707. case 40: // down
  708. if (!this.keyboardNavigation) break;
  709. dir = e.keyCode == 38 ? -1 : 1;
  710. if (e.ctrlKey){
  711. newDate = this.moveYear(this.date, dir);
  712. newViewDate = this.moveYear(this.viewDate, dir);
  713. } else if (e.shiftKey){
  714. newDate = this.moveMonth(this.date, dir);
  715. newViewDate = this.moveMonth(this.viewDate, dir);
  716. } else {
  717. newDate = new Date(this.date);
  718. newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
  719. newViewDate = new Date(this.viewDate);
  720. newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
  721. }
  722. if (this.dateWithinRange(newDate)){
  723. this.date = newDate;
  724. this.viewDate = newViewDate;
  725. this.setValue();
  726. this.update();
  727. e.preventDefault();
  728. dateChanged = true;
  729. }
  730. break;
  731. case 13: // enter
  732. this.hide();
  733. e.preventDefault();
  734. break;
  735. case 9: // tab
  736. this.hide();
  737. break;
  738. }
  739. if (dateChanged){
  740. this.element.trigger({
  741. type: 'changeDate',
  742. date: this.date
  743. });
  744. var element;
  745. if (this.isInput) {
  746. element = this.element;
  747. } else if (this.component){
  748. element = this.element.find('input');
  749. }
  750. if (element) {
  751. element.change();
  752. }
  753. }
  754. },
  755. showMode: function(dir) {
  756. if (dir) {
  757. this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
  758. }
  759. /*
  760. vitalets: fixing bug of very special conditions:
  761. jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover.
  762. Method show() does not set display css correctly and datepicker is not shown.
  763. Changed to .css('display', 'block') solve the problem.
  764. See https://github.com/vitalets/x-editable/issues/37
  765. In jquery 1.7.2+ everything works fine.
  766. */
  767. //this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
  768. this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block');
  769. this.updateNavArrows();
  770. }
  771. };
  772. $.fn.datepicker = function ( option ) {
  773. var args = Array.apply(null, arguments);
  774. args.shift();
  775. return this.each(function () {
  776. var $this = $(this),
  777. data = $this.data('datepicker'),
  778. options = typeof option == 'object' && option;
  779. if (!data) {
  780. $this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
  781. }
  782. if (typeof option == 'string' && typeof data[option] == 'function') {
  783. data[option].apply(data, args);
  784. }
  785. });
  786. };
  787. $.fn.datepicker.defaults = {
  788. };
  789. $.fn.datepicker.Constructor = Datepicker;
  790. var dates = $.fn.datepicker.dates = {
  791. en: {
  792. days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
  793. daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  794. daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
  795. months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  796. monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
  797. today: "Today"
  798. }
  799. };
  800. var DPGlobal = {
  801. modes: [
  802. {
  803. clsName: 'days',
  804. navFnc: 'Month',
  805. navStep: 1
  806. },
  807. {
  808. clsName: 'months',
  809. navFnc: 'FullYear',
  810. navStep: 1
  811. },
  812. {
  813. clsName: 'years',
  814. navFnc: 'FullYear',
  815. navStep: 10
  816. }],
  817. isLeapYear: function (year) {
  818. return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
  819. },
  820. getDaysInMonth: function (year, month) {
  821. return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
  822. },
  823. validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
  824. nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
  825. parseFormat: function(format){
  826. // IE treats \0 as a string end in inputs (truncating the value),
  827. // so it's a bad format delimiter, anyway
  828. var separators = format.replace(this.validParts, '\0').split('\0'),
  829. parts = format.match(this.validParts);
  830. if (!separators || !separators.length || !parts || parts.length === 0){
  831. throw new Error("Invalid date format.");
  832. }
  833. return {separators: separators, parts: parts};
  834. },
  835. parseDate: function(date, format, language) {
  836. if (date instanceof Date) return date;
  837. if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) {
  838. var part_re = /([\-+]\d+)([dmwy])/,
  839. parts = date.match(/([\-+]\d+)([dmwy])/g),
  840. part, dir;
  841. date = new Date();
  842. for (var i=0; i<parts.length; i++) {
  843. part = part_re.exec(parts[i]);
  844. dir = parseInt(part[1]);
  845. switch(part[2]){
  846. case 'd':
  847. date.setUTCDate(date.getUTCDate() + dir);
  848. break;
  849. case 'm':
  850. date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
  851. break;
  852. case 'w':
  853. date.setUTCDate(date.getUTCDate() + dir * 7);
  854. break;
  855. case 'y':
  856. date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
  857. break;
  858. }
  859. }
  860. return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
  861. }
  862. var parts = date && date.match(this.nonpunctuation) || [],
  863. date = new Date(),
  864. parsed = {},
  865. setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
  866. setters_map = {
  867. yyyy: function(d,v){ return d.setUTCFullYear(v); },
  868. yy: function(d,v){ return d.setUTCFullYear(2000+v); },
  869. m: function(d,v){
  870. v -= 1;
  871. while (v<0) v += 12;
  872. v %= 12;
  873. d.setUTCMonth(v);
  874. while (d.getUTCMonth() != v)
  875. d.setUTCDate(d.getUTCDate()-1);
  876. return d;
  877. },
  878. d: function(d,v){ return d.setUTCDate(v); }
  879. },
  880. val, filtered, part;
  881. setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
  882. setters_map['dd'] = setters_map['d'];
  883. date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
  884. var fparts = format.parts.slice();
  885. // Remove noop parts
  886. if (parts.length != fparts.length) {
  887. fparts = $(fparts).filter(function(i,p){
  888. return $.inArray(p, setters_order) !== -1;
  889. }).toArray();
  890. }
  891. // Process remainder
  892. if (parts.length == fparts.length) {
  893. for (var i=0, cnt = fparts.length; i < cnt; i++) {
  894. val = parseInt(parts[i], 10);
  895. part = fparts[i];
  896. if (isNaN(val)) {
  897. switch(part) {
  898. case 'MM':
  899. filtered = $(dates[language].months).filter(function(){
  900. var m = this.slice(0, parts[i].length),
  901. p = parts[i].slice(0, m.length);
  902. return m == p;
  903. });
  904. val = $.inArray(filtered[0], dates[language].months) + 1;
  905. break;
  906. case 'M':
  907. filtered = $(dates[language].monthsShort).filter(function(){
  908. var m = this.slice(0, parts[i].length),
  909. p = parts[i].slice(0, m.length);
  910. return m == p;
  911. });
  912. val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
  913. break;
  914. }
  915. }
  916. parsed[part] = val;
  917. }
  918. for (var i=0, s; i<setters_order.length; i++){
  919. s = setters_order[i];
  920. if (s in parsed && !isNaN(parsed[s]))
  921. setters_map[s](date, parsed[s]);
  922. }
  923. }
  924. return date;
  925. },
  926. formatDate: function(date, format, language){
  927. var val = {
  928. d: date.getUTCDate(),
  929. D: dates[language].daysShort[date.getUTCDay()],
  930. DD: dates[language].days[date.getUTCDay()],
  931. m: date.getUTCMonth() + 1,
  932. M: dates[language].monthsShort[date.getUTCMonth()],
  933. MM: dates[language].months[date.getUTCMonth()],
  934. yy: date.getUTCFullYear().toString().substring(2),
  935. yyyy: date.getUTCFullYear()
  936. };
  937. val.dd = (val.d < 10 ? '0' : '') + val.d;
  938. val.mm = (val.m < 10 ? '0' : '') + val.m;
  939. var date = [],
  940. seps = $.extend([], format.separators);
  941. for (var i=0, cnt = format.parts.length; i < cnt; i++) {
  942. if (seps.length)
  943. date.push(seps.shift());
  944. date.push(val[format.parts[i]]);
  945. }
  946. return date.join('');
  947. },
  948. headTemplate: '<thead>'+
  949. '<tr>'+
  950. '<th class="prev"><i class="icon-arrow-left"/></th>'+
  951. '<th colspan="5" class="switch"></th>'+
  952. '<th class="next"><i class="icon-arrow-right"/></th>'+
  953. '</tr>'+
  954. '</thead>',
  955. contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
  956. footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr></tfoot>'
  957. };
  958. DPGlobal.template = '<div class="datepicker">'+
  959. '<div class="datepicker-days">'+
  960. '<table class=" table-condensed">'+
  961. DPGlobal.headTemplate+
  962. '<tbody></tbody>'+
  963. DPGlobal.footTemplate+
  964. '</table>'+
  965. '</div>'+
  966. '<div class="datepicker-months">'+
  967. '<table class="table-condensed">'+
  968. DPGlobal.headTemplate+
  969. DPGlobal.contTemplate+
  970. DPGlobal.footTemplate+
  971. '</table>'+
  972. '</div>'+
  973. '<div class="datepicker-years">'+
  974. '<table class="table-condensed">'+
  975. DPGlobal.headTemplate+
  976. DPGlobal.contTemplate+
  977. DPGlobal.footTemplate+
  978. '</table>'+
  979. '</div>'+
  980. '</div>';
  981. $.fn.datepicker.DPGlobal = DPGlobal;
  982. }( window.jQuery );