bootstrap-datepicker.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672
  1. /* =========================================================
  2. * bootstrap-datepicker.js
  3. * Repo: https://github.com/eternicode/bootstrap-datepicker/
  4. * Demo: http://eternicode.github.io/bootstrap-datepicker/
  5. * Docs: http://bootstrap-datepicker.readthedocs.org/
  6. * Forked from http://www.eyecon.ro/bootstrap-datepicker
  7. * =========================================================
  8. * Started by Stefan Petre; improvements by Andrew Rowls + contributors
  9. *
  10. * Licensed under the Apache License, Version 2.0 (the "License");
  11. * you may not use this file except in compliance with the License.
  12. * You may obtain a copy of the License at
  13. *
  14. * http://www.apache.org/licenses/LICENSE-2.0
  15. *
  16. * Unless required by applicable law or agreed to in writing, software
  17. * distributed under the License is distributed on an "AS IS" BASIS,
  18. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. * See the License for the specific language governing permissions and
  20. * limitations under the License.
  21. * ========================================================= */
  22. (function($, undefined){
  23. var $window = $(window);
  24. function UTCDate(){
  25. return new Date(Date.UTC.apply(Date, arguments));
  26. }
  27. function UTCToday(){
  28. var today = new Date();
  29. return UTCDate(today.getFullYear(), today.getMonth(), today.getDate());
  30. }
  31. function alias(method){
  32. return function(){
  33. return this[method].apply(this, arguments);
  34. };
  35. }
  36. var DateArray = (function(){
  37. var extras = {
  38. get: function(i){
  39. return this.slice(i)[0];
  40. },
  41. contains: function(d){
  42. // Array.indexOf is not cross-browser;
  43. // $.inArray doesn't work with Dates
  44. var val = d && d.valueOf();
  45. for (var i=0, l=this.length; i < l; i++)
  46. if (this[i].valueOf() === val)
  47. return i;
  48. return -1;
  49. },
  50. remove: function(i){
  51. this.splice(i,1);
  52. },
  53. replace: function(new_array){
  54. if (!new_array)
  55. return;
  56. if (!$.isArray(new_array))
  57. new_array = [new_array];
  58. this.clear();
  59. this.push.apply(this, new_array);
  60. },
  61. clear: function(){
  62. this.splice(0);
  63. },
  64. copy: function(){
  65. var a = new DateArray();
  66. a.replace(this);
  67. return a;
  68. }
  69. };
  70. return function(){
  71. var a = [];
  72. a.push.apply(a, arguments);
  73. $.extend(a, extras);
  74. return a;
  75. };
  76. })();
  77. // Picker object
  78. var Datepicker = function(element, options){
  79. this.dates = new DateArray();
  80. this.viewDate = UTCToday();
  81. this.focusDate = null;
  82. this._process_options(options);
  83. this.element = $(element);
  84. this.isInline = false;
  85. this.isInput = this.element.is('input');
  86. this.component = this.element.is('.date') ? this.element.find('.add-on, .input-group-addon, .btn') : false;
  87. this.hasInput = this.component && this.element.find('input').length;
  88. if (this.component && this.component.length === 0)
  89. this.component = false;
  90. this.picker = $(DPGlobal.template);
  91. this._buildEvents();
  92. this._attachEvents();
  93. if (this.isInline){
  94. this.picker.addClass('datepicker-inline').appendTo(this.element);
  95. }
  96. else {
  97. this.picker.addClass('datepicker-dropdown dropdown-menu');
  98. }
  99. if (this.o.rtl){
  100. this.picker.addClass('datepicker-rtl');
  101. }
  102. this.viewMode = this.o.startView;
  103. if (this.o.calendarWeeks)
  104. this.picker.find('tfoot th.today')
  105. .attr('colspan', function(i, val){
  106. return parseInt(val) + 1;
  107. });
  108. this._allow_update = false;
  109. this.setStartDate(this._o.startDate);
  110. this.setEndDate(this._o.endDate);
  111. this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);
  112. this.fillDow();
  113. this.fillMonths();
  114. this._allow_update = true;
  115. this.update();
  116. this.showMode();
  117. if (this.isInline){
  118. this.show();
  119. }
  120. };
  121. Datepicker.prototype = {
  122. constructor: Datepicker,
  123. _process_options: function(opts){
  124. // Store raw options for reference
  125. this._o = $.extend({}, this._o, opts);
  126. // Processed options
  127. var o = this.o = $.extend({}, this._o);
  128. // Check if "de-DE" style date is available, if not language should
  129. // fallback to 2 letter code eg "de"
  130. var lang = o.language;
  131. if (!dates[lang]){
  132. lang = lang.split('-')[0];
  133. if (!dates[lang])
  134. lang = defaults.language;
  135. }
  136. o.language = lang;
  137. switch (o.startView){
  138. case 2:
  139. case 'decade':
  140. o.startView = 2;
  141. break;
  142. case 1:
  143. case 'year':
  144. o.startView = 1;
  145. break;
  146. default:
  147. o.startView = 0;
  148. }
  149. switch (o.minViewMode){
  150. case 1:
  151. case 'months':
  152. o.minViewMode = 1;
  153. break;
  154. case 2:
  155. case 'years':
  156. o.minViewMode = 2;
  157. break;
  158. default:
  159. o.minViewMode = 0;
  160. }
  161. o.startView = Math.max(o.startView, o.minViewMode);
  162. // true, false, or Number > 0
  163. if (o.multidate !== true){
  164. o.multidate = Number(o.multidate) || false;
  165. if (o.multidate !== false)
  166. o.multidate = Math.max(0, o.multidate);
  167. else
  168. o.multidate = 1;
  169. }
  170. o.multidateSeparator = String(o.multidateSeparator);
  171. o.weekStart %= 7;
  172. o.weekEnd = ((o.weekStart + 6) % 7);
  173. var format = DPGlobal.parseFormat(o.format);
  174. if (o.startDate !== -Infinity){
  175. if (!!o.startDate){
  176. if (o.startDate instanceof Date)
  177. o.startDate = this._local_to_utc(this._zero_time(o.startDate));
  178. else
  179. o.startDate = DPGlobal.parseDate(o.startDate, format, o.language);
  180. }
  181. else {
  182. o.startDate = -Infinity;
  183. }
  184. }
  185. if (o.endDate !== Infinity){
  186. if (!!o.endDate){
  187. if (o.endDate instanceof Date)
  188. o.endDate = this._local_to_utc(this._zero_time(o.endDate));
  189. else
  190. o.endDate = DPGlobal.parseDate(o.endDate, format, o.language);
  191. }
  192. else {
  193. o.endDate = Infinity;
  194. }
  195. }
  196. o.daysOfWeekDisabled = o.daysOfWeekDisabled||[];
  197. if (!$.isArray(o.daysOfWeekDisabled))
  198. o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/);
  199. o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function(d){
  200. return parseInt(d, 10);
  201. });
  202. var plc = String(o.orientation).toLowerCase().split(/\s+/g),
  203. _plc = o.orientation.toLowerCase();
  204. plc = $.grep(plc, function(word){
  205. return (/^auto|left|right|top|bottom$/).test(word);
  206. });
  207. o.orientation = {x: 'auto', y: 'auto'};
  208. if (!_plc || _plc === 'auto')
  209. ; // no action
  210. else if (plc.length === 1){
  211. switch (plc[0]){
  212. case 'top':
  213. case 'bottom':
  214. o.orientation.y = plc[0];
  215. break;
  216. case 'left':
  217. case 'right':
  218. o.orientation.x = plc[0];
  219. break;
  220. }
  221. }
  222. else {
  223. _plc = $.grep(plc, function(word){
  224. return (/^left|right$/).test(word);
  225. });
  226. o.orientation.x = _plc[0] || 'auto';
  227. _plc = $.grep(plc, function(word){
  228. return (/^top|bottom$/).test(word);
  229. });
  230. o.orientation.y = _plc[0] || 'auto';
  231. }
  232. },
  233. _events: [],
  234. _secondaryEvents: [],
  235. _applyEvents: function(evs){
  236. for (var i=0, el, ch, ev; i < evs.length; i++){
  237. el = evs[i][0];
  238. if (evs[i].length === 2){
  239. ch = undefined;
  240. ev = evs[i][1];
  241. }
  242. else if (evs[i].length === 3){
  243. ch = evs[i][1];
  244. ev = evs[i][2];
  245. }
  246. el.on(ev, ch);
  247. }
  248. },
  249. _unapplyEvents: function(evs){
  250. for (var i=0, el, ev, ch; i < evs.length; i++){
  251. el = evs[i][0];
  252. if (evs[i].length === 2){
  253. ch = undefined;
  254. ev = evs[i][1];
  255. }
  256. else if (evs[i].length === 3){
  257. ch = evs[i][1];
  258. ev = evs[i][2];
  259. }
  260. el.off(ev, ch);
  261. }
  262. },
  263. _buildEvents: function(){
  264. if (this.isInput){ // single input
  265. this._events = [
  266. [this.element, {
  267. focus: $.proxy(this.show, this),
  268. keyup: $.proxy(function(e){
  269. if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1)
  270. this.update();
  271. }, this),
  272. keydown: $.proxy(this.keydown, this)
  273. }]
  274. ];
  275. }
  276. else if (this.component && this.hasInput){ // component: input + button
  277. this._events = [
  278. // For components that are not readonly, allow keyboard nav
  279. [this.element.find('input'), {
  280. focus: $.proxy(this.show, this),
  281. keyup: $.proxy(function(e){
  282. if ($.inArray(e.keyCode, [27,37,39,38,40,32,13,9]) === -1)
  283. this.update();
  284. }, this),
  285. keydown: $.proxy(this.keydown, this)
  286. }],
  287. [this.component, {
  288. click: $.proxy(this.show, this)
  289. }]
  290. ];
  291. }
  292. else if (this.element.is('div')){ // inline datepicker
  293. this.isInline = true;
  294. }
  295. else {
  296. this._events = [
  297. [this.element, {
  298. click: $.proxy(this.show, this)
  299. }]
  300. ];
  301. }
  302. this._events.push(
  303. // Component: listen for blur on element descendants
  304. [this.element, '*', {
  305. blur: $.proxy(function(e){
  306. this._focused_from = e.target;
  307. }, this)
  308. }],
  309. // Input: listen for blur on element
  310. [this.element, {
  311. blur: $.proxy(function(e){
  312. this._focused_from = e.target;
  313. }, this)
  314. }]
  315. );
  316. this._secondaryEvents = [
  317. [this.picker, {
  318. click: $.proxy(this.click, this)
  319. }],
  320. [$(window), {
  321. resize: $.proxy(this.place, this)
  322. }],
  323. [$(document), {
  324. 'mousedown touchstart': $.proxy(function(e){
  325. // Clicked outside the datepicker, hide it
  326. if (!(
  327. this.element.is(e.target) ||
  328. this.element.find(e.target).length ||
  329. this.picker.is(e.target) ||
  330. this.picker.find(e.target).length
  331. )){
  332. this.hide();
  333. }
  334. }, this)
  335. }]
  336. ];
  337. },
  338. _attachEvents: function(){
  339. this._detachEvents();
  340. this._applyEvents(this._events);
  341. },
  342. _detachEvents: function(){
  343. this._unapplyEvents(this._events);
  344. },
  345. _attachSecondaryEvents: function(){
  346. this._detachSecondaryEvents();
  347. this._applyEvents(this._secondaryEvents);
  348. },
  349. _detachSecondaryEvents: function(){
  350. this._unapplyEvents(this._secondaryEvents);
  351. },
  352. _trigger: function(event, altdate){
  353. var date = altdate || this.dates.get(-1),
  354. local_date = this._utc_to_local(date);
  355. this.element.trigger({
  356. type: event,
  357. date: local_date,
  358. dates: $.map(this.dates, this._utc_to_local),
  359. format: $.proxy(function(ix, format){
  360. if (arguments.length === 0){
  361. ix = this.dates.length - 1;
  362. format = this.o.format;
  363. }
  364. else if (typeof ix === 'string'){
  365. format = ix;
  366. ix = this.dates.length - 1;
  367. }
  368. format = format || this.o.format;
  369. var date = this.dates.get(ix);
  370. return DPGlobal.formatDate(date, format, this.o.language);
  371. }, this)
  372. });
  373. },
  374. show: function(){
  375. if (!this.isInline)
  376. this.picker.appendTo('body');
  377. this.picker.show();
  378. this.place();
  379. this._attachSecondaryEvents();
  380. this._trigger('show');
  381. },
  382. hide: function(){
  383. if (this.isInline)
  384. return;
  385. if (!this.picker.is(':visible'))
  386. return;
  387. this.focusDate = null;
  388. this.picker.hide().detach();
  389. this._detachSecondaryEvents();
  390. this.viewMode = this.o.startView;
  391. this.showMode();
  392. if (
  393. this.o.forceParse &&
  394. (
  395. this.isInput && this.element.val() ||
  396. this.hasInput && this.element.find('input').val()
  397. )
  398. )
  399. this.setValue();
  400. this._trigger('hide');
  401. },
  402. remove: function(){
  403. this.hide();
  404. this._detachEvents();
  405. this._detachSecondaryEvents();
  406. this.picker.remove();
  407. delete this.element.data().datepicker;
  408. if (!this.isInput){
  409. delete this.element.data().date;
  410. }
  411. },
  412. _utc_to_local: function(utc){
  413. return utc && new Date(utc.getTime() + (utc.getTimezoneOffset()*60000));
  414. },
  415. _local_to_utc: function(local){
  416. return local && new Date(local.getTime() - (local.getTimezoneOffset()*60000));
  417. },
  418. _zero_time: function(local){
  419. return local && new Date(local.getFullYear(), local.getMonth(), local.getDate());
  420. },
  421. _zero_utc_time: function(utc){
  422. return utc && new Date(Date.UTC(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate()));
  423. },
  424. getDates: function(){
  425. return $.map(this.dates, this._utc_to_local);
  426. },
  427. getUTCDates: function(){
  428. return $.map(this.dates, function(d){
  429. return new Date(d);
  430. });
  431. },
  432. getDate: function(){
  433. return this._utc_to_local(this.getUTCDate());
  434. },
  435. getUTCDate: function(){
  436. return new Date(this.dates.get(-1));
  437. },
  438. setDates: function(){
  439. var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
  440. this.update.apply(this, args);
  441. this._trigger('changeDate');
  442. this.setValue();
  443. },
  444. setUTCDates: function(){
  445. var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
  446. this.update.apply(this, $.map(args, this._utc_to_local));
  447. this._trigger('changeDate');
  448. this.setValue();
  449. },
  450. setDate: alias('setDates'),
  451. setUTCDate: alias('setUTCDates'),
  452. setValue: function(){
  453. var formatted = this.getFormattedDate();
  454. if (!this.isInput){
  455. if (this.component){
  456. this.element.find('input').val(formatted).change();
  457. }
  458. }
  459. else {
  460. this.element.val(formatted).change();
  461. }
  462. },
  463. getFormattedDate: function(format){
  464. if (format === undefined)
  465. format = this.o.format;
  466. var lang = this.o.language;
  467. return $.map(this.dates, function(d){
  468. return DPGlobal.formatDate(d, format, lang);
  469. }).join(this.o.multidateSeparator);
  470. },
  471. setStartDate: function(startDate){
  472. this._process_options({startDate: startDate});
  473. this.update();
  474. this.updateNavArrows();
  475. },
  476. setEndDate: function(endDate){
  477. this._process_options({endDate: endDate});
  478. this.update();
  479. this.updateNavArrows();
  480. },
  481. setDaysOfWeekDisabled: function(daysOfWeekDisabled){
  482. this._process_options({daysOfWeekDisabled: daysOfWeekDisabled});
  483. this.update();
  484. this.updateNavArrows();
  485. },
  486. place: function(){
  487. if (this.isInline)
  488. return;
  489. var calendarWidth = this.picker.outerWidth(),
  490. calendarHeight = this.picker.outerHeight(),
  491. visualPadding = 10,
  492. windowWidth = $window.width(),
  493. windowHeight = $window.height(),
  494. scrollTop = $window.scrollTop();
  495. var zIndex = parseInt(this.element.parents().filter(function(){
  496. return $(this).css('z-index') !== 'auto';
  497. }).first().css('z-index'))+10;
  498. var offset = this.component ? this.component.parent().offset() : this.element.offset();
  499. var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(false);
  500. var width = this.component ? this.component.outerWidth(true) : this.element.outerWidth(false);
  501. var left = offset.left,
  502. top = offset.top;
  503. this.picker.removeClass(
  504. 'datepicker-orient-top datepicker-orient-bottom '+
  505. 'datepicker-orient-right datepicker-orient-left'
  506. );
  507. if (this.o.orientation.x !== 'auto'){
  508. this.picker.addClass('datepicker-orient-' + this.o.orientation.x);
  509. if (this.o.orientation.x === 'right')
  510. left -= calendarWidth - width;
  511. }
  512. // auto x orientation is best-placement: if it crosses a window
  513. // edge, fudge it sideways
  514. else {
  515. // Default to left
  516. this.picker.addClass('datepicker-orient-left');
  517. if (offset.left < 0)
  518. left -= offset.left - visualPadding;
  519. else if (offset.left + calendarWidth > windowWidth)
  520. left = windowWidth - calendarWidth - visualPadding;
  521. }
  522. // auto y orientation is best-situation: top or bottom, no fudging,
  523. // decision based on which shows more of the calendar
  524. var yorient = this.o.orientation.y,
  525. top_overflow, bottom_overflow;
  526. if (yorient === 'auto'){
  527. top_overflow = -scrollTop + offset.top - calendarHeight;
  528. bottom_overflow = scrollTop + windowHeight - (offset.top + height + calendarHeight);
  529. if (Math.max(top_overflow, bottom_overflow) === bottom_overflow)
  530. yorient = 'top';
  531. else
  532. yorient = 'bottom';
  533. }
  534. this.picker.addClass('datepicker-orient-' + yorient);
  535. if (yorient === 'top')
  536. top += height;
  537. else
  538. top -= calendarHeight + parseInt(this.picker.css('padding-top'));
  539. this.picker.css({
  540. top: top,
  541. left: left,
  542. zIndex: zIndex
  543. });
  544. },
  545. _allow_update: true,
  546. update: function(){
  547. if (!this._allow_update)
  548. return;
  549. var oldDates = this.dates.copy(),
  550. dates = [],
  551. fromArgs = false;
  552. if (arguments.length){
  553. $.each(arguments, $.proxy(function(i, date){
  554. if (date instanceof Date)
  555. date = this._local_to_utc(date);
  556. dates.push(date);
  557. }, this));
  558. fromArgs = true;
  559. }
  560. else {
  561. dates = this.isInput
  562. ? this.element.val()
  563. : this.element.data('date') || this.element.find('input').val();
  564. if (dates && this.o.multidate)
  565. dates = dates.split(this.o.multidateSeparator);
  566. else
  567. dates = [dates];
  568. delete this.element.data().date;
  569. }
  570. dates = $.map(dates, $.proxy(function(date){
  571. return DPGlobal.parseDate(date, this.o.format, this.o.language);
  572. }, this));
  573. dates = $.grep(dates, $.proxy(function(date){
  574. return (
  575. date < this.o.startDate ||
  576. date > this.o.endDate ||
  577. !date
  578. );
  579. }, this), true);
  580. this.dates.replace(dates);
  581. if (this.dates.length)
  582. this.viewDate = new Date(this.dates.get(-1));
  583. else if (this.viewDate < this.o.startDate)
  584. this.viewDate = new Date(this.o.startDate);
  585. else if (this.viewDate > this.o.endDate)
  586. this.viewDate = new Date(this.o.endDate);
  587. if (fromArgs){
  588. // setting date by clicking
  589. this.setValue();
  590. }
  591. else if (dates.length){
  592. // setting date by typing
  593. if (String(oldDates) !== String(this.dates))
  594. this._trigger('changeDate');
  595. }
  596. if (!this.dates.length && oldDates.length)
  597. this._trigger('clearDate');
  598. this.fill();
  599. },
  600. fillDow: function(){
  601. var dowCnt = this.o.weekStart,
  602. html = '<tr>';
  603. if (this.o.calendarWeeks){
  604. var cell = '<th class="cw">&nbsp;</th>';
  605. html += cell;
  606. this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
  607. }
  608. while (dowCnt < this.o.weekStart + 7){
  609. html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>';
  610. }
  611. html += '</tr>';
  612. this.picker.find('.datepicker-days thead').append(html);
  613. },
  614. fillMonths: function(){
  615. var html = '',
  616. i = 0;
  617. while (i < 12){
  618. html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>';
  619. }
  620. this.picker.find('.datepicker-months td').html(html);
  621. },
  622. setRange: function(range){
  623. if (!range || !range.length)
  624. delete this.range;
  625. else
  626. this.range = $.map(range, function(d){
  627. return d.valueOf();
  628. });
  629. this.fill();
  630. },
  631. getClassNames: function(date){
  632. var cls = [],
  633. year = this.viewDate.getUTCFullYear(),
  634. month = this.viewDate.getUTCMonth(),
  635. today = new Date();
  636. if (date.getUTCFullYear() < year || (date.getUTCFullYear() === year && date.getUTCMonth() < month)){
  637. cls.push('old');
  638. }
  639. else if (date.getUTCFullYear() > year || (date.getUTCFullYear() === year && date.getUTCMonth() > month)){
  640. cls.push('new');
  641. }
  642. if (this.focusDate && date.valueOf() === this.focusDate.valueOf())
  643. cls.push('focused');
  644. // Compare internal UTC date with local today, not UTC today
  645. if (this.o.todayHighlight &&
  646. date.getUTCFullYear() === today.getFullYear() &&
  647. date.getUTCMonth() === today.getMonth() &&
  648. date.getUTCDate() === today.getDate()){
  649. cls.push('today');
  650. }
  651. if (this.dates.contains(date) !== -1)
  652. cls.push('active');
  653. if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate ||
  654. $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1){
  655. cls.push('disabled');
  656. }
  657. if (this.range){
  658. if (date > this.range[0] && date < this.range[this.range.length-1]){
  659. cls.push('range');
  660. }
  661. if ($.inArray(date.valueOf(), this.range) !== -1){
  662. cls.push('selected');
  663. }
  664. }
  665. return cls;
  666. },
  667. fill: function(){
  668. var d = new Date(this.viewDate),
  669. year = d.getUTCFullYear(),
  670. month = d.getUTCMonth(),
  671. startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
  672. startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
  673. endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
  674. endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
  675. todaytxt = dates[this.o.language].today || dates['en'].today || '',
  676. cleartxt = dates[this.o.language].clear || dates['en'].clear || '',
  677. tooltip;
  678. this.picker.find('.datepicker-days thead th.datepicker-switch')
  679. .text(dates[this.o.language].months[month]+' '+year);
  680. this.picker.find('tfoot th.today')
  681. .text(todaytxt)
  682. .toggle(this.o.todayBtn !== false);
  683. this.picker.find('tfoot th.clear')
  684. .text(cleartxt)
  685. .toggle(this.o.clearBtn !== false);
  686. this.updateNavArrows();
  687. this.fillMonths();
  688. var prevMonth = UTCDate(year, month-1, 28),
  689. day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
  690. prevMonth.setUTCDate(day);
  691. prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7);
  692. var nextMonth = new Date(prevMonth);
  693. nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
  694. nextMonth = nextMonth.valueOf();
  695. var html = [];
  696. var clsName;
  697. while (prevMonth.valueOf() < nextMonth){
  698. if (prevMonth.getUTCDay() === this.o.weekStart){
  699. html.push('<tr>');
  700. if (this.o.calendarWeeks){
  701. // ISO 8601: First week contains first thursday.
  702. // ISO also states week starts on Monday, but we can be more abstract here.
  703. var
  704. // Start of current week: based on weekstart/current date
  705. ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
  706. // Thursday of this week
  707. th = new Date(Number(ws) + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
  708. // First Thursday of year, year from thursday
  709. yth = new Date(Number(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5),
  710. // Calendar week: ms between thursdays, div ms per day, div 7 days
  711. calWeek = (th - yth) / 864e5 / 7 + 1;
  712. html.push('<td class="cw">'+ calWeek +'</td>');
  713. }
  714. }
  715. clsName = this.getClassNames(prevMonth);
  716. clsName.push('day');
  717. if (this.o.beforeShowDay !== $.noop){
  718. var before = this.o.beforeShowDay(this._utc_to_local(prevMonth));
  719. if (before === undefined)
  720. before = {};
  721. else if (typeof(before) === 'boolean')
  722. before = {enabled: before};
  723. else if (typeof(before) === 'string')
  724. before = {classes: before};
  725. if (before.enabled === false)
  726. clsName.push('disabled');
  727. if (before.classes)
  728. clsName = clsName.concat(before.classes.split(/\s+/));
  729. if (before.tooltip)
  730. tooltip = before.tooltip;
  731. }
  732. clsName = $.unique(clsName);
  733. html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>');
  734. if (prevMonth.getUTCDay() === this.o.weekEnd){
  735. html.push('</tr>');
  736. }
  737. prevMonth.setUTCDate(prevMonth.getUTCDate()+1);
  738. }
  739. this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
  740. var months = this.picker.find('.datepicker-months')
  741. .find('th:eq(1)')
  742. .text(year)
  743. .end()
  744. .find('span').removeClass('active');
  745. $.each(this.dates, function(i, d){
  746. if (d.getUTCFullYear() === year)
  747. months.eq(d.getUTCMonth()).addClass('active');
  748. });
  749. if (year < startYear || year > endYear){
  750. months.addClass('disabled');
  751. }
  752. if (year === startYear){
  753. months.slice(0, startMonth).addClass('disabled');
  754. }
  755. if (year === endYear){
  756. months.slice(endMonth+1).addClass('disabled');
  757. }
  758. html = '';
  759. year = parseInt(year/10, 10) * 10;
  760. var yearCont = this.picker.find('.datepicker-years')
  761. .find('th:eq(1)')
  762. .text(year + '-' + (year + 9))
  763. .end()
  764. .find('td');
  765. year -= 1;
  766. var years = $.map(this.dates, function(d){
  767. return d.getUTCFullYear();
  768. }),
  769. classes;
  770. for (var i = -1; i < 11; i++){
  771. classes = ['year'];
  772. if (i === -1)
  773. classes.push('old');
  774. else if (i === 10)
  775. classes.push('new');
  776. if ($.inArray(year, years) !== -1)
  777. classes.push('active');
  778. if (year < startYear || year > endYear)
  779. classes.push('disabled');
  780. html += '<span class="' + classes.join(' ') + '">'+year+'</span>';
  781. year += 1;
  782. }
  783. yearCont.html(html);
  784. },
  785. updateNavArrows: function(){
  786. if (!this._allow_update)
  787. return;
  788. var d = new Date(this.viewDate),
  789. year = d.getUTCFullYear(),
  790. month = d.getUTCMonth();
  791. switch (this.viewMode){
  792. case 0:
  793. if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()){
  794. this.picker.find('.prev').css({visibility: 'hidden'});
  795. }
  796. else {
  797. this.picker.find('.prev').css({visibility: 'visible'});
  798. }
  799. if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()){
  800. this.picker.find('.next').css({visibility: 'hidden'});
  801. }
  802. else {
  803. this.picker.find('.next').css({visibility: 'visible'});
  804. }
  805. break;
  806. case 1:
  807. case 2:
  808. if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()){
  809. this.picker.find('.prev').css({visibility: 'hidden'});
  810. }
  811. else {
  812. this.picker.find('.prev').css({visibility: 'visible'});
  813. }
  814. if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()){
  815. this.picker.find('.next').css({visibility: 'hidden'});
  816. }
  817. else {
  818. this.picker.find('.next').css({visibility: 'visible'});
  819. }
  820. break;
  821. }
  822. },
  823. click: function(e){
  824. e.preventDefault();
  825. var target = $(e.target).closest('span, td, th'),
  826. year, month, day;
  827. if (target.length === 1){
  828. switch (target[0].nodeName.toLowerCase()){
  829. case 'th':
  830. switch (target[0].className){
  831. case 'datepicker-switch':
  832. this.showMode(1);
  833. break;
  834. case 'prev':
  835. case 'next':
  836. var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1);
  837. switch (this.viewMode){
  838. case 0:
  839. this.viewDate = this.moveMonth(this.viewDate, dir);
  840. this._trigger('changeMonth', this.viewDate);
  841. break;
  842. case 1:
  843. case 2:
  844. this.viewDate = this.moveYear(this.viewDate, dir);
  845. if (this.viewMode === 1)
  846. this._trigger('changeYear', this.viewDate);
  847. break;
  848. }
  849. this.fill();
  850. break;
  851. case 'today':
  852. var date = new Date();
  853. date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
  854. this.showMode(-2);
  855. var which = this.o.todayBtn === 'linked' ? null : 'view';
  856. this._setDate(date, which);
  857. break;
  858. case 'clear':
  859. var element;
  860. if (this.isInput)
  861. element = this.element;
  862. else if (this.component)
  863. element = this.element.find('input');
  864. if (element)
  865. element.val("").change();
  866. this.update();
  867. this._trigger('changeDate');
  868. if (this.o.autoclose)
  869. this.hide();
  870. break;
  871. }
  872. break;
  873. case 'span':
  874. if (!target.is('.disabled')){
  875. this.viewDate.setUTCDate(1);
  876. if (target.is('.month')){
  877. day = 1;
  878. month = target.parent().find('span').index(target);
  879. year = this.viewDate.getUTCFullYear();
  880. this.viewDate.setUTCMonth(month);
  881. this._trigger('changeMonth', this.viewDate);
  882. if (this.o.minViewMode === 1){
  883. this._setDate(UTCDate(year, month, day));
  884. }
  885. }
  886. else {
  887. day = 1;
  888. month = 0;
  889. year = parseInt(target.text(), 10)||0;
  890. this.viewDate.setUTCFullYear(year);
  891. this._trigger('changeYear', this.viewDate);
  892. if (this.o.minViewMode === 2){
  893. this._setDate(UTCDate(year, month, day));
  894. }
  895. }
  896. this.showMode(-1);
  897. this.fill();
  898. }
  899. break;
  900. case 'td':
  901. if (target.is('.day') && !target.is('.disabled')){
  902. day = parseInt(target.text(), 10)||1;
  903. year = this.viewDate.getUTCFullYear();
  904. month = this.viewDate.getUTCMonth();
  905. if (target.is('.old')){
  906. if (month === 0){
  907. month = 11;
  908. year -= 1;
  909. }
  910. else {
  911. month -= 1;
  912. }
  913. }
  914. else if (target.is('.new')){
  915. if (month === 11){
  916. month = 0;
  917. year += 1;
  918. }
  919. else {
  920. month += 1;
  921. }
  922. }
  923. this._setDate(UTCDate(year, month, day));
  924. }
  925. break;
  926. }
  927. }
  928. if (this.picker.is(':visible') && this._focused_from){
  929. $(this._focused_from).focus();
  930. }
  931. delete this._focused_from;
  932. },
  933. _toggle_multidate: function(date){
  934. var ix = this.dates.contains(date);
  935. if (!date){
  936. this.dates.clear();
  937. }
  938. else if (ix !== -1){
  939. this.dates.remove(ix);
  940. }
  941. else {
  942. this.dates.push(date);
  943. }
  944. if (typeof this.o.multidate === 'number')
  945. while (this.dates.length > this.o.multidate)
  946. this.dates.remove(0);
  947. },
  948. _setDate: function(date, which){
  949. if (!which || which === 'date')
  950. this._toggle_multidate(date && new Date(date));
  951. if (!which || which === 'view')
  952. this.viewDate = date && new Date(date);
  953. this.fill();
  954. this.setValue();
  955. this._trigger('changeDate');
  956. var element;
  957. if (this.isInput){
  958. element = this.element;
  959. }
  960. else if (this.component){
  961. element = this.element.find('input');
  962. }
  963. if (element){
  964. element.change();
  965. }
  966. if (this.o.autoclose && (!which || which === 'date')){
  967. this.hide();
  968. }
  969. },
  970. moveMonth: function(date, dir){
  971. if (!date)
  972. return undefined;
  973. if (!dir)
  974. return date;
  975. var new_date = new Date(date.valueOf()),
  976. day = new_date.getUTCDate(),
  977. month = new_date.getUTCMonth(),
  978. mag = Math.abs(dir),
  979. new_month, test;
  980. dir = dir > 0 ? 1 : -1;
  981. if (mag === 1){
  982. test = dir === -1
  983. // If going back one month, make sure month is not current month
  984. // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
  985. ? function(){
  986. return new_date.getUTCMonth() === month;
  987. }
  988. // If going forward one month, make sure month is as expected
  989. // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
  990. : function(){
  991. return new_date.getUTCMonth() !== new_month;
  992. };
  993. new_month = month + dir;
  994. new_date.setUTCMonth(new_month);
  995. // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
  996. if (new_month < 0 || new_month > 11)
  997. new_month = (new_month + 12) % 12;
  998. }
  999. else {
  1000. // For magnitudes >1, move one month at a time...
  1001. for (var i=0; i < mag; i++)
  1002. // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
  1003. new_date = this.moveMonth(new_date, dir);
  1004. // ...then reset the day, keeping it in the new month
  1005. new_month = new_date.getUTCMonth();
  1006. new_date.setUTCDate(day);
  1007. test = function(){
  1008. return new_month !== new_date.getUTCMonth();
  1009. };
  1010. }
  1011. // Common date-resetting loop -- if date is beyond end of month, make it
  1012. // end of month
  1013. while (test()){
  1014. new_date.setUTCDate(--day);
  1015. new_date.setUTCMonth(new_month);
  1016. }
  1017. return new_date;
  1018. },
  1019. moveYear: function(date, dir){
  1020. return this.moveMonth(date, dir*12);
  1021. },
  1022. dateWithinRange: function(date){
  1023. return date >= this.o.startDate && date <= this.o.endDate;
  1024. },
  1025. keydown: function(e){
  1026. if (this.picker.is(':not(:visible)')){
  1027. if (e.keyCode === 27) // allow escape to hide and re-show picker
  1028. this.show();
  1029. return;
  1030. }
  1031. var dateChanged = false,
  1032. dir, newDate, newViewDate,
  1033. focusDate = this.focusDate || this.viewDate;
  1034. switch (e.keyCode){
  1035. case 27: // escape
  1036. if (this.focusDate){
  1037. this.focusDate = null;
  1038. this.viewDate = this.dates.get(-1) || this.viewDate;
  1039. this.fill();
  1040. }
  1041. else
  1042. this.hide();
  1043. e.preventDefault();
  1044. break;
  1045. case 37: // left
  1046. case 39: // right
  1047. if (!this.o.keyboardNavigation)
  1048. break;
  1049. dir = e.keyCode === 37 ? -1 : 1;
  1050. if (e.ctrlKey){
  1051. newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
  1052. newViewDate = this.moveYear(focusDate, dir);
  1053. this._trigger('changeYear', this.viewDate);
  1054. }
  1055. else if (e.shiftKey){
  1056. newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
  1057. newViewDate = this.moveMonth(focusDate, dir);
  1058. this._trigger('changeMonth', this.viewDate);
  1059. }
  1060. else {
  1061. newDate = new Date(this.dates.get(-1) || UTCToday());
  1062. newDate.setUTCDate(newDate.getUTCDate() + dir);
  1063. newViewDate = new Date(focusDate);
  1064. newViewDate.setUTCDate(focusDate.getUTCDate() + dir);
  1065. }
  1066. if (this.dateWithinRange(newDate)){
  1067. this.focusDate = this.viewDate = newViewDate;
  1068. this.setValue();
  1069. this.fill();
  1070. e.preventDefault();
  1071. }
  1072. break;
  1073. case 38: // up
  1074. case 40: // down
  1075. if (!this.o.keyboardNavigation)
  1076. break;
  1077. dir = e.keyCode === 38 ? -1 : 1;
  1078. if (e.ctrlKey){
  1079. newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
  1080. newViewDate = this.moveYear(focusDate, dir);
  1081. this._trigger('changeYear', this.viewDate);
  1082. }
  1083. else if (e.shiftKey){
  1084. newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
  1085. newViewDate = this.moveMonth(focusDate, dir);
  1086. this._trigger('changeMonth', this.viewDate);
  1087. }
  1088. else {
  1089. newDate = new Date(this.dates.get(-1) || UTCToday());
  1090. newDate.setUTCDate(newDate.getUTCDate() + dir * 7);
  1091. newViewDate = new Date(focusDate);
  1092. newViewDate.setUTCDate(focusDate.getUTCDate() + dir * 7);
  1093. }
  1094. if (this.dateWithinRange(newDate)){
  1095. this.focusDate = this.viewDate = newViewDate;
  1096. this.setValue();
  1097. this.fill();
  1098. e.preventDefault();
  1099. }
  1100. break;
  1101. case 32: // spacebar
  1102. // Spacebar is used in manually typing dates in some formats.
  1103. // As such, its behavior should not be hijacked.
  1104. break;
  1105. case 13: // enter
  1106. focusDate = this.focusDate || this.dates.get(-1) || this.viewDate;
  1107. this._toggle_multidate(focusDate);
  1108. dateChanged = true;
  1109. this.focusDate = null;
  1110. this.viewDate = this.dates.get(-1) || this.viewDate;
  1111. this.setValue();
  1112. this.fill();
  1113. if (this.picker.is(':visible')){
  1114. e.preventDefault();
  1115. if (this.o.autoclose)
  1116. this.hide();
  1117. }
  1118. break;
  1119. case 9: // tab
  1120. this.focusDate = null;
  1121. this.viewDate = this.dates.get(-1) || this.viewDate;
  1122. this.fill();
  1123. this.hide();
  1124. break;
  1125. }
  1126. if (dateChanged){
  1127. if (this.dates.length)
  1128. this._trigger('changeDate');
  1129. else
  1130. this._trigger('clearDate');
  1131. var element;
  1132. if (this.isInput){
  1133. element = this.element;
  1134. }
  1135. else if (this.component){
  1136. element = this.element.find('input');
  1137. }
  1138. if (element){
  1139. element.change();
  1140. }
  1141. }
  1142. },
  1143. showMode: function(dir){
  1144. if (dir){
  1145. this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir));
  1146. }
  1147. this.picker
  1148. .find('>div')
  1149. .hide()
  1150. .filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName)
  1151. .css('display', 'block');
  1152. this.updateNavArrows();
  1153. }
  1154. };
  1155. var DateRangePicker = function(element, options){
  1156. this.element = $(element);
  1157. this.inputs = $.map(options.inputs, function(i){
  1158. return i.jquery ? i[0] : i;
  1159. });
  1160. delete options.inputs;
  1161. $(this.inputs)
  1162. .datepicker(options)
  1163. .bind('changeDate', $.proxy(this.dateUpdated, this));
  1164. this.pickers = $.map(this.inputs, function(i){
  1165. return $(i).data('datepicker');
  1166. });
  1167. this.updateDates();
  1168. };
  1169. DateRangePicker.prototype = {
  1170. updateDates: function(){
  1171. this.dates = $.map(this.pickers, function(i){
  1172. return i.getUTCDate();
  1173. });
  1174. this.updateRanges();
  1175. },
  1176. updateRanges: function(){
  1177. var range = $.map(this.dates, function(d){
  1178. return d.valueOf();
  1179. });
  1180. $.each(this.pickers, function(i, p){
  1181. p.setRange(range);
  1182. });
  1183. },
  1184. dateUpdated: function(e){
  1185. // `this.updating` is a workaround for preventing infinite recursion
  1186. // between `changeDate` triggering and `setUTCDate` calling. Until
  1187. // there is a better mechanism.
  1188. if (this.updating)
  1189. return;
  1190. this.updating = true;
  1191. var dp = $(e.target).data('datepicker'),
  1192. new_date = dp.getUTCDate(),
  1193. i = $.inArray(e.target, this.inputs),
  1194. l = this.inputs.length;
  1195. if (i === -1)
  1196. return;
  1197. $.each(this.pickers, function(i, p){
  1198. if (!p.getUTCDate())
  1199. p.setUTCDate(new_date);
  1200. });
  1201. if (new_date < this.dates[i]){
  1202. // Date being moved earlier/left
  1203. while (i >= 0 && new_date < this.dates[i]){
  1204. this.pickers[i--].setUTCDate(new_date);
  1205. }
  1206. }
  1207. else if (new_date > this.dates[i]){
  1208. // Date being moved later/right
  1209. while (i < l && new_date > this.dates[i]){
  1210. this.pickers[i++].setUTCDate(new_date);
  1211. }
  1212. }
  1213. this.updateDates();
  1214. delete this.updating;
  1215. },
  1216. remove: function(){
  1217. $.map(this.pickers, function(p){ p.remove(); });
  1218. delete this.element.data().datepicker;
  1219. }
  1220. };
  1221. function opts_from_el(el, prefix){
  1222. // Derive options from element data-attrs
  1223. var data = $(el).data(),
  1224. out = {}, inkey,
  1225. replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])');
  1226. prefix = new RegExp('^' + prefix.toLowerCase());
  1227. function re_lower(_,a){
  1228. return a.toLowerCase();
  1229. }
  1230. for (var key in data)
  1231. if (prefix.test(key)){
  1232. inkey = key.replace(replace, re_lower);
  1233. out[inkey] = data[key];
  1234. }
  1235. return out;
  1236. }
  1237. function opts_from_locale(lang){
  1238. // Derive options from locale plugins
  1239. var out = {};
  1240. // Check if "de-DE" style date is available, if not language should
  1241. // fallback to 2 letter code eg "de"
  1242. if (!dates[lang]){
  1243. lang = lang.split('-')[0];
  1244. if (!dates[lang])
  1245. return;
  1246. }
  1247. var d = dates[lang];
  1248. $.each(locale_opts, function(i,k){
  1249. if (k in d)
  1250. out[k] = d[k];
  1251. });
  1252. return out;
  1253. }
  1254. var old = $.fn.datepicker;
  1255. $.fn.datepicker = function(option){
  1256. var args = Array.apply(null, arguments);
  1257. args.shift();
  1258. var internal_return;
  1259. this.each(function(){
  1260. var $this = $(this),
  1261. data = $this.data('datepicker'),
  1262. options = typeof option === 'object' && option;
  1263. if (!data){
  1264. var elopts = opts_from_el(this, 'date'),
  1265. // Preliminary otions
  1266. xopts = $.extend({}, defaults, elopts, options),
  1267. locopts = opts_from_locale(xopts.language),
  1268. // Options priority: js args, data-attrs, locales, defaults
  1269. opts = $.extend({}, defaults, locopts, elopts, options);
  1270. if ($this.is('.input-daterange') || opts.inputs){
  1271. var ropts = {
  1272. inputs: opts.inputs || $this.find('input').toArray()
  1273. };
  1274. $this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts))));
  1275. }
  1276. else {
  1277. $this.data('datepicker', (data = new Datepicker(this, opts)));
  1278. }
  1279. }
  1280. if (typeof option === 'string' && typeof data[option] === 'function'){
  1281. internal_return = data[option].apply(data, args);
  1282. if (internal_return !== undefined)
  1283. return false;
  1284. }
  1285. });
  1286. if (internal_return !== undefined)
  1287. return internal_return;
  1288. else
  1289. return this;
  1290. };
  1291. var defaults = $.fn.datepicker.defaults = {
  1292. autoclose: false,
  1293. beforeShowDay: $.noop,
  1294. calendarWeeks: false,
  1295. clearBtn: false,
  1296. daysOfWeekDisabled: [],
  1297. endDate: Infinity,
  1298. forceParse: true,
  1299. format: 'mm/dd/yyyy',
  1300. keyboardNavigation: true,
  1301. language: 'en',
  1302. minViewMode: 0,
  1303. multidate: false,
  1304. multidateSeparator: ',',
  1305. orientation: "auto",
  1306. rtl: false,
  1307. startDate: -Infinity,
  1308. startView: 0,
  1309. todayBtn: false,
  1310. todayHighlight: false,
  1311. weekStart: 0
  1312. };
  1313. var locale_opts = $.fn.datepicker.locale_opts = [
  1314. 'format',
  1315. 'rtl',
  1316. 'weekStart'
  1317. ];
  1318. $.fn.datepicker.Constructor = Datepicker;
  1319. var dates = $.fn.datepicker.dates = {
  1320. en: {
  1321. days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
  1322. daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  1323. daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
  1324. months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  1325. monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
  1326. today: "Today",
  1327. clear: "Clear"
  1328. }
  1329. };
  1330. var DPGlobal = {
  1331. modes: [
  1332. {
  1333. clsName: 'days',
  1334. navFnc: 'Month',
  1335. navStep: 1
  1336. },
  1337. {
  1338. clsName: 'months',
  1339. navFnc: 'FullYear',
  1340. navStep: 1
  1341. },
  1342. {
  1343. clsName: 'years',
  1344. navFnc: 'FullYear',
  1345. navStep: 10
  1346. }],
  1347. isLeapYear: function(year){
  1348. return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
  1349. },
  1350. getDaysInMonth: function(year, month){
  1351. return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
  1352. },
  1353. validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
  1354. nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
  1355. parseFormat: function(format){
  1356. // IE treats \0 as a string end in inputs (truncating the value),
  1357. // so it's a bad format delimiter, anyway
  1358. var separators = format.replace(this.validParts, '\0').split('\0'),
  1359. parts = format.match(this.validParts);
  1360. if (!separators || !separators.length || !parts || parts.length === 0){
  1361. throw new Error("Invalid date format.");
  1362. }
  1363. return {separators: separators, parts: parts};
  1364. },
  1365. parseDate: function(date, format, language){
  1366. if (!date)
  1367. return undefined;
  1368. if (date instanceof Date)
  1369. return date;
  1370. if (typeof format === 'string')
  1371. format = DPGlobal.parseFormat(format);
  1372. var part_re = /([\-+]\d+)([dmwy])/,
  1373. parts = date.match(/([\-+]\d+)([dmwy])/g),
  1374. part, dir, i;
  1375. if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)){
  1376. date = new Date();
  1377. for (i=0; i < parts.length; i++){
  1378. part = part_re.exec(parts[i]);
  1379. dir = parseInt(part[1]);
  1380. switch (part[2]){
  1381. case 'd':
  1382. date.setUTCDate(date.getUTCDate() + dir);
  1383. break;
  1384. case 'm':
  1385. date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
  1386. break;
  1387. case 'w':
  1388. date.setUTCDate(date.getUTCDate() + dir * 7);
  1389. break;
  1390. case 'y':
  1391. date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
  1392. break;
  1393. }
  1394. }
  1395. return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
  1396. }
  1397. parts = date && date.match(this.nonpunctuation) || [];
  1398. date = new Date();
  1399. var parsed = {},
  1400. setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
  1401. setters_map = {
  1402. yyyy: function(d,v){
  1403. return d.setUTCFullYear(v);
  1404. },
  1405. yy: function(d,v){
  1406. return d.setUTCFullYear(2000+v);
  1407. },
  1408. m: function(d,v){
  1409. if (isNaN(d))
  1410. return d;
  1411. v -= 1;
  1412. while (v < 0) v += 12;
  1413. v %= 12;
  1414. d.setUTCMonth(v);
  1415. while (d.getUTCMonth() !== v)
  1416. d.setUTCDate(d.getUTCDate()-1);
  1417. return d;
  1418. },
  1419. d: function(d,v){
  1420. return d.setUTCDate(v);
  1421. }
  1422. },
  1423. val, filtered;
  1424. setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
  1425. setters_map['dd'] = setters_map['d'];
  1426. date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
  1427. var fparts = format.parts.slice();
  1428. // Remove noop parts
  1429. if (parts.length !== fparts.length){
  1430. fparts = $(fparts).filter(function(i,p){
  1431. return $.inArray(p, setters_order) !== -1;
  1432. }).toArray();
  1433. }
  1434. // Process remainder
  1435. function match_part(){
  1436. var m = this.slice(0, parts[i].length),
  1437. p = parts[i].slice(0, m.length);
  1438. return m === p;
  1439. }
  1440. if (parts.length === fparts.length){
  1441. var cnt;
  1442. for (i=0, cnt = fparts.length; i < cnt; i++){
  1443. val = parseInt(parts[i], 10);
  1444. part = fparts[i];
  1445. if (isNaN(val)){
  1446. switch (part){
  1447. case 'MM':
  1448. filtered = $(dates[language].months).filter(match_part);
  1449. val = $.inArray(filtered[0], dates[language].months) + 1;
  1450. break;
  1451. case 'M':
  1452. filtered = $(dates[language].monthsShort).filter(match_part);
  1453. val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
  1454. break;
  1455. }
  1456. }
  1457. parsed[part] = val;
  1458. }
  1459. var _date, s;
  1460. for (i=0; i < setters_order.length; i++){
  1461. s = setters_order[i];
  1462. if (s in parsed && !isNaN(parsed[s])){
  1463. _date = new Date(date);
  1464. setters_map[s](_date, parsed[s]);
  1465. if (!isNaN(_date))
  1466. date = _date;
  1467. }
  1468. }
  1469. }
  1470. return date;
  1471. },
  1472. formatDate: function(date, format, language){
  1473. if (!date)
  1474. return '';
  1475. if (typeof format === 'string')
  1476. format = DPGlobal.parseFormat(format);
  1477. var val = {
  1478. d: date.getUTCDate(),
  1479. D: dates[language].daysShort[date.getUTCDay()],
  1480. DD: dates[language].days[date.getUTCDay()],
  1481. m: date.getUTCMonth() + 1,
  1482. M: dates[language].monthsShort[date.getUTCMonth()],
  1483. MM: dates[language].months[date.getUTCMonth()],
  1484. yy: date.getUTCFullYear().toString().substring(2),
  1485. yyyy: date.getUTCFullYear()
  1486. };
  1487. val.dd = (val.d < 10 ? '0' : '') + val.d;
  1488. val.mm = (val.m < 10 ? '0' : '') + val.m;
  1489. date = [];
  1490. var seps = $.extend([], format.separators);
  1491. for (var i=0, cnt = format.parts.length; i <= cnt; i++){
  1492. if (seps.length)
  1493. date.push(seps.shift());
  1494. date.push(val[format.parts[i]]);
  1495. }
  1496. return date.join('');
  1497. },
  1498. headTemplate: '<thead>'+
  1499. '<tr>'+
  1500. '<th class="prev">&laquo;</th>'+
  1501. '<th colspan="5" class="datepicker-switch"></th>'+
  1502. '<th class="next">&raquo;</th>'+
  1503. '</tr>'+
  1504. '</thead>',
  1505. contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
  1506. footTemplate: '<tfoot>'+
  1507. '<tr>'+
  1508. '<th colspan="7" class="today"></th>'+
  1509. '</tr>'+
  1510. '<tr>'+
  1511. '<th colspan="7" class="clear"></th>'+
  1512. '</tr>'+
  1513. '</tfoot>'
  1514. };
  1515. DPGlobal.template = '<div class="datepicker">'+
  1516. '<div class="datepicker-days">'+
  1517. '<table class=" table-condensed">'+
  1518. DPGlobal.headTemplate+
  1519. '<tbody></tbody>'+
  1520. DPGlobal.footTemplate+
  1521. '</table>'+
  1522. '</div>'+
  1523. '<div class="datepicker-months">'+
  1524. '<table class="table-condensed">'+
  1525. DPGlobal.headTemplate+
  1526. DPGlobal.contTemplate+
  1527. DPGlobal.footTemplate+
  1528. '</table>'+
  1529. '</div>'+
  1530. '<div class="datepicker-years">'+
  1531. '<table class="table-condensed">'+
  1532. DPGlobal.headTemplate+
  1533. DPGlobal.contTemplate+
  1534. DPGlobal.footTemplate+
  1535. '</table>'+
  1536. '</div>'+
  1537. '</div>';
  1538. $.fn.datepicker.DPGlobal = DPGlobal;
  1539. /* DATEPICKER NO CONFLICT
  1540. * =================== */
  1541. $.fn.datepicker.noConflict = function(){
  1542. $.fn.datepicker = old;
  1543. return this;
  1544. };
  1545. /* DATEPICKER DATA-API
  1546. * ================== */
  1547. $(document).on(
  1548. 'focus.datepicker.data-api click.datepicker.data-api',
  1549. '[data-provide="datepicker"]',
  1550. function(e){
  1551. var $this = $(this);
  1552. if ($this.data('datepicker'))
  1553. return;
  1554. e.preventDefault();
  1555. // component click requires us to explicitly show it
  1556. $this.datepicker('show');
  1557. }
  1558. );
  1559. $(function(){
  1560. $('[data-provide="datepicker-inline"]').datepicker();
  1561. });
  1562. }(window.jQuery));