bootstrap-datepicker.js 30 KB

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