calendar.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. /*!
  2. * Pikaday
  3. *
  4. * Copyright © 2014 David Bushell | BSD & MIT license | https://github.com/dbushell/Pikaday
  5. */
  6. var pickers = {};
  7. var clLangs = {
  8. ua: {
  9. previousMonth : 'Попередній місяць',
  10. nextMonth : 'Наступний місяць',
  11. months : ['Січень','Лютий','Березень','Квітень','Травень','Червень','Липень','Серпень','Вересень','Жовтень','Листопад','Грудень'],
  12. weekdays : ['Неділя','Понеділок','Вівторок','Середа','Четвер','П’ятниця','Субота'],
  13. weekdaysShort : ['Нд','Пн','Вв','Ср','Чт','Пт','Сб']
  14. },
  15. ru: {
  16. previousMonth : 'Предыдущий месяц',
  17. nextMonth : 'Следующий месяц',
  18. months : ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
  19. weekdays : ['Воскресенье','Понедельник','Вторник','Среда','Четверг','Пятница','Суббота'],
  20. weekdaysShort : ['Вс','Пн','Вт','Ср','Чт','Пт','Сб']
  21. },
  22. en: {
  23. previousMonth : 'Previous Month',
  24. nextMonth : 'Next Month',
  25. months : ['January','February','March','April','May','June','July','August','September','October','November','December'],
  26. weekdays : ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
  27. weekdaysShort : ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
  28. }
  29. };
  30. function getDateParamBySign(date,sign) {
  31. sign = sign.toUpperCase();
  32. var param;
  33. switch(sign) {
  34. case "YYYY":
  35. param = date.getFullYear().toString();break;
  36. case "YY":
  37. param = date.getFullYear().toString().substr(2,2);break;
  38. case "MM":
  39. param = (date.getMonth()+1);
  40. param = (param >= 10) ? param.toString() : ("0"+param.toString());
  41. break;
  42. case "DD":
  43. param = (date.getDate() >= 10) ? date.getDate().toString() : ("0"+date.getDate().toString());
  44. break;
  45. default:
  46. param = date.toDateString();
  47. }
  48. return param;
  49. }
  50. function formatter(date, format) {
  51. date = date || new Date();
  52. format = format || "YYYY-MM-DD";
  53. var signs = format.match(/(Y{2,4})|(M{2})|(D{2})/g);
  54. var params = [];
  55. var reStr = '';
  56. for(var i=0; i<signs.length; ++i) {
  57. params.push(getDateParamBySign(date,signs[i]));
  58. reStr += ((i+1) != signs.length) ? signs[i] + "(.)" : signs[i];
  59. }
  60. var re = new RegExp(reStr,'g');
  61. var delimiters = re.exec(format);
  62. delimiters.splice(0,1);
  63. var value = "";
  64. for(i=0; i<params.length; i++) {
  65. value += ((i+1) != params.length) ? (params[i] + delimiters[i]) : params[i];
  66. }
  67. return value;
  68. }
  69. (function (root, factory)
  70. {
  71. 'use strict';
  72. var moment;
  73. if (typeof exports === 'object') {
  74. // CommonJS module
  75. // Load moment.js as an optional dependency
  76. try { moment = require('moment'); } catch (e) {}
  77. module.exports = factory(moment);
  78. } else if (typeof define === 'function' && define.amd) {
  79. // AMD. Register as an anonymous module.
  80. define(function (req)
  81. {
  82. // Load moment.js as an optional dependency
  83. var id = 'moment';
  84. try { moment = req(id); } catch (e) {}
  85. return factory(moment);
  86. });
  87. } else {
  88. root.Pikaday = factory(root.moment);
  89. }
  90. }(this, function (moment)
  91. {
  92. 'use strict';
  93. /**
  94. * feature detection and helper functions
  95. */
  96. var hasMoment = typeof moment === 'function',
  97. hasEventListeners = !!window.addEventListener,
  98. document = window.document,
  99. sto = window.setTimeout,
  100. addEvent = function(el, e, callback, capture)
  101. {
  102. if (hasEventListeners) {
  103. el.addEventListener(e, callback, !!capture);
  104. } else {
  105. el.attachEvent('on' + e, callback);
  106. }
  107. },
  108. removeEvent = function(el, e, callback, capture)
  109. {
  110. if (hasEventListeners) {
  111. el.removeEventListener(e, callback, !!capture);
  112. } else {
  113. el.detachEvent('on' + e, callback);
  114. }
  115. },
  116. fireEvent = function(el, eventName, data)
  117. {
  118. var ev;
  119. if (document.createEvent) {
  120. ev = document.createEvent('HTMLEvents');
  121. ev.initEvent(eventName, true, false);
  122. ev = extend(ev, data);
  123. el.dispatchEvent(ev);
  124. } else if (document.createEventObject) {
  125. ev = document.createEventObject();
  126. ev = extend(ev, data);
  127. el.fireEvent('on' + eventName, ev);
  128. }
  129. },
  130. trim = function(str)
  131. {
  132. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g,'');
  133. },
  134. hasClass = function(el, cn)
  135. {
  136. return (' ' + el.className + ' ').indexOf(' ' + cn + ' ') !== -1;
  137. },
  138. addClass = function(el, cn)
  139. {
  140. if (!hasClass(el, cn)) {
  141. el.className = (el.className === '') ? cn : el.className + ' ' + cn;
  142. }
  143. },
  144. removeClass = function(el, cn)
  145. {
  146. el.className = trim((' ' + el.className + ' ').replace(' ' + cn + ' ', ' '));
  147. },
  148. isArray = function(obj)
  149. {
  150. return (/Array/).test(Object.prototype.toString.call(obj));
  151. },
  152. isDate = function(obj)
  153. {
  154. return (/Date/).test(Object.prototype.toString.call(obj)) && !isNaN(obj.getTime());
  155. },
  156. isWeekend = function(date)
  157. {
  158. var day = date.getDay();
  159. return day === 0 || day === 6;
  160. },
  161. isLeapYear = function(year)
  162. {
  163. // solution by Matti Virkkunen: http://stackoverflow.com/a/4881951
  164. return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
  165. },
  166. getDaysInMonth = function(year, month)
  167. {
  168. return [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
  169. },
  170. setToStartOfDay = function(date)
  171. {
  172. if (isDate(date)) date.setHours(0,0,0,0);
  173. },
  174. compareDates = function(a,b)
  175. {
  176. // weak date comparison (use setToStartOfDay(date) to ensure correct result)
  177. return a.getTime() === b.getTime();
  178. },
  179. extend = function(to, from, overwrite)
  180. {
  181. var prop, hasProp;
  182. for (prop in from) {
  183. hasProp = to[prop] !== undefined;
  184. if (hasProp && typeof from[prop] === 'object' && from[prop] !== null && from[prop].nodeName === undefined) {
  185. if (isDate(from[prop])) {
  186. if (overwrite) {
  187. to[prop] = new Date(from[prop].getTime());
  188. }
  189. }
  190. else if (isArray(from[prop])) {
  191. if (overwrite) {
  192. to[prop] = from[prop].slice(0);
  193. }
  194. } else {
  195. to[prop] = extend({}, from[prop], overwrite);
  196. }
  197. } else if (overwrite || !hasProp) {
  198. to[prop] = from[prop];
  199. }
  200. }
  201. return to;
  202. },
  203. adjustCalendar = function(calendar) {
  204. if (calendar.month < 0) {
  205. calendar.year -= Math.ceil(Math.abs(calendar.month)/12);
  206. calendar.month += 12;
  207. }
  208. if (calendar.month > 11) {
  209. calendar.year += Math.floor(Math.abs(calendar.month)/12);
  210. calendar.month -= 12;
  211. }
  212. return calendar;
  213. },
  214. /**
  215. * defaults and localisation
  216. */
  217. defaults = {
  218. // bind the picker to a form field
  219. field: null,
  220. // automatically show/hide the picker on `field` focus (default `true` if `field` is set)
  221. bound: undefined,
  222. // position of the datepicker, relative to the field (default to bottom & left)
  223. // ('bottom' & 'left' keywords are not used, 'top' & 'right' are modifier on the bottom/left position)
  224. position: 'bottom left',
  225. // automatically fit in the viewport even if it means repositioning from the position option
  226. reposition: true,
  227. // the default output format for `.toString()` and `field` value
  228. format: 'YYYY-MM-DD',
  229. // the initial date to view when first opened
  230. defaultDate: null,
  231. // make the `defaultDate` the initial selected value
  232. setDefaultDate: false,
  233. // first day of week (0: Sunday, 1: Monday etc)
  234. firstDay: 0,
  235. // the minimum/earliest date that can be selected
  236. minDate: null,
  237. // the maximum/latest date that can be selected
  238. maxDate: null,
  239. // number of years either side, or array of upper/lower range
  240. yearRange: 10,
  241. // show week numbers at head of row
  242. showWeekNumber: false,
  243. // used internally (don't config outside)
  244. minYear: 0,
  245. maxYear: 9999,
  246. minMonth: undefined,
  247. maxMonth: undefined,
  248. startRange: null,
  249. endRange: null,
  250. isRTL: false,
  251. // Additional text to append to the year in the calendar title
  252. yearSuffix: '',
  253. // Render the month after year in the calendar title
  254. showMonthAfterYear: false,
  255. // how many months are visible
  256. numberOfMonths: 1,
  257. // when numberOfMonths is used, this will help you to choose where the main calendar will be (default `left`, can be set to `right`)
  258. // only used for the first display or when a selected date is not visible
  259. mainCalendar: 'left',
  260. // Specify a DOM element to render the calendar in
  261. container: undefined,
  262. // internationalization
  263. i18n: clLangs.en,
  264. // Theme Classname
  265. theme: null,
  266. // callback function
  267. onSelect: null,
  268. onOpen: null,
  269. onClose: null,
  270. onDraw: null
  271. },
  272. /**
  273. * templating functions to abstract HTML rendering
  274. */
  275. renderDayName = function(opts, day, abbr)
  276. {
  277. day += opts.firstDay;
  278. while (day >= 7) {
  279. day -= 7;
  280. }
  281. return abbr ? opts.i18n.weekdaysShort[day] : opts.i18n.weekdays[day];
  282. },
  283. renderDay = function(opts)
  284. {
  285. if (opts.isEmpty) {
  286. return '<td class="is-empty"></td>';
  287. }
  288. var arr = [];
  289. if (opts.isDisabled) {
  290. arr.push('is-disabled');
  291. }
  292. if (opts.isToday) {
  293. arr.push('is-today');
  294. }
  295. if (opts.isSelected) {
  296. arr.push('is-selected');
  297. }
  298. if (opts.isInRange) {
  299. arr.push('is-inrange');
  300. }
  301. if (opts.isStartRange) {
  302. arr.push('is-startrange');
  303. }
  304. if (opts.isEndRange) {
  305. arr.push('is-endrange');
  306. }
  307. return '<td data-day="' + opts.day + '" class="' + arr.join(' ') + '">' +
  308. '<button class="pika-button pika-day" type="button" ' +
  309. 'data-pika-year="' + opts.year + '" data-pika-month="' + opts.month + '" data-pika-day="' + opts.day + '">' +
  310. opts.day +
  311. '</button>' +
  312. '</td>';
  313. },
  314. renderWeek = function (d, m, y) {
  315. // Lifted from http://javascript.about.com/library/blweekyear.htm, lightly modified.
  316. var onejan = new Date(y, 0, 1),
  317. weekNum = Math.ceil((((new Date(y, m, d) - onejan) / 86400000) + onejan.getDay()+1)/7);
  318. return '<td class="pika-week">' + weekNum + '</td>';
  319. },
  320. renderRow = function(days, isRTL)
  321. {
  322. return '<tr>' + (isRTL ? days.reverse() : days).join('') + '</tr>';
  323. },
  324. renderBody = function(rows)
  325. {
  326. return '<tbody>' + rows.join('') + '</tbody>';
  327. },
  328. renderHead = function(opts)
  329. {
  330. var i, arr = [];
  331. if (opts.showWeekNumber) {
  332. arr.push('<th></th>');
  333. }
  334. for (i = 0; i < 7; i++) {
  335. arr.push('<th scope="col"><abbr title="' + renderDayName(opts, i) + '">' + renderDayName(opts, i, true) + '</abbr></th>');
  336. }
  337. return '<thead>' + (opts.isRTL ? arr.reverse() : arr).join('') + '</thead>';
  338. },
  339. renderTitle = function(instance, c, year, month, refYear)
  340. {
  341. var i, j, arr,
  342. opts = instance._o,
  343. isMinYear = year === opts.minYear,
  344. isMaxYear = year === opts.maxYear,
  345. html = '<div class="pika-title">',
  346. monthHtml,
  347. yearHtml,
  348. prev = true,
  349. next = true;
  350. for (arr = [], i = 0; i < 12; i++) {
  351. arr.push('<option value="' + (year === refYear ? i - c : 12 + i - c) + '"' +
  352. (i === month ? ' selected': '') +
  353. ((isMinYear && i < opts.minMonth) || (isMaxYear && i > opts.maxMonth) ? 'disabled' : '') + '>' +
  354. opts.i18n.months[i] + '</option>');
  355. }
  356. monthHtml = '<div class="pika-label">' + opts.i18n.months[month] + '<select class="pika-select pika-select-month" tabindex="-1">' + arr.join('') + '</select></div>';
  357. if (isArray(opts.yearRange)) {
  358. i = opts.yearRange[0];
  359. j = opts.yearRange[1] + 1;
  360. } else {
  361. i = year - opts.yearRange;
  362. j = 1 + year + opts.yearRange;
  363. }
  364. for (arr = []; i < j && i <= opts.maxYear; i++) {
  365. if (i >= opts.minYear) {
  366. arr.push('<option value="' + i + '"' + (i === year ? ' selected': '') + '>' + (i) + '</option>');
  367. }
  368. }
  369. yearHtml = '<div class="pika-label">' + year + opts.yearSuffix + '<select class="pika-select pika-select-year" tabindex="-1">' + arr.join('') + '</select></div>';
  370. if (opts.showMonthAfterYear) {
  371. html += yearHtml + monthHtml;
  372. } else {
  373. html += monthHtml + yearHtml;
  374. }
  375. if (isMinYear && (month === 0 || opts.minMonth >= month)) {
  376. prev = false;
  377. }
  378. if (isMaxYear && (month === 11 || opts.maxMonth <= month)) {
  379. next = false;
  380. }
  381. if (c === 0) {
  382. html += '<button class="pika-prev' + (prev ? '' : ' is-disabled') + '" type="button">' + opts.i18n.previousMonth + '</button>';
  383. }
  384. if (c === (instance._o.numberOfMonths - 1) ) {
  385. html += '<button class="pika-next' + (next ? '' : ' is-disabled') + '" type="button">' + opts.i18n.nextMonth + '</button>';
  386. }
  387. return html += '</div>';
  388. },
  389. renderTable = function(opts, data)
  390. {
  391. return '<table cellpadding="0" cellspacing="0" class="pika-table">' + renderHead(opts) + renderBody(data) + '</table>';
  392. },
  393. /**
  394. * Pikaday constructor
  395. */
  396. Pikaday = function(options)
  397. {
  398. var self = this,
  399. opts = self.config(options);
  400. self._onMouseDown = function(e)
  401. {
  402. if (!self._v) {
  403. return;
  404. }
  405. e = e || window.event;
  406. var target = e.target || e.srcElement;
  407. if (!target) {
  408. return;
  409. }
  410. if (!hasClass(target.parentNode, 'is-disabled')) {
  411. if (hasClass(target, 'pika-button') && !hasClass(target, 'is-empty')) {
  412. self.setDate(new Date(target.getAttribute('data-pika-year'), target.getAttribute('data-pika-month'), target.getAttribute('data-pika-day')));
  413. if (opts.bound) {
  414. sto(function() {
  415. self.hide();
  416. if (opts.field) {
  417. opts.field.blur();
  418. }
  419. }, 100);
  420. }
  421. }
  422. else if (hasClass(target, 'pika-prev')) {
  423. self.prevMonth();
  424. }
  425. else if (hasClass(target, 'pika-next')) {
  426. self.nextMonth();
  427. }
  428. }
  429. if (!hasClass(target, 'pika-select')) {
  430. // if this is touch event prevent mouse events emulation
  431. if (e.preventDefault) {
  432. e.preventDefault();
  433. } else {
  434. e.returnValue = false;
  435. return false;
  436. }
  437. } else {
  438. self._c = true;
  439. }
  440. };
  441. self._onChange = function(e)
  442. {
  443. e = e || window.event;
  444. var target = e.target || e.srcElement;
  445. if (!target) {
  446. return;
  447. }
  448. if (hasClass(target, 'pika-select-month')) {
  449. self.gotoMonth(target.value);
  450. }
  451. else if (hasClass(target, 'pika-select-year')) {
  452. self.gotoYear(target.value);
  453. }
  454. };
  455. self._onInputChange = function(e)
  456. {
  457. var date;
  458. if (e.firedBy === self) {
  459. return;
  460. }
  461. if (hasMoment) {
  462. date = moment(opts.field.value, opts.format);
  463. date = (date && date.isValid()) ? date.toDate() : null;
  464. }
  465. else {
  466. date = new Date(Date.parse(opts.field.value));
  467. }
  468. if (isDate(date)) {
  469. self.setDate(date);
  470. }else {
  471. self.setDate(null);
  472. }
  473. if (!self._v) {
  474. self.show();
  475. }
  476. };
  477. self._onInputFocus = function()
  478. {
  479. self.show();
  480. };
  481. self._onInputClick = function()
  482. {
  483. self.show();
  484. };
  485. self._onInputBlur = function()
  486. {
  487. // IE allows pika div to gain focus; catch blur the input field
  488. var pEl = document.activeElement;
  489. do {
  490. if (hasClass(pEl, 'pika-single')) {
  491. return;
  492. }
  493. }
  494. while ((pEl = pEl.parentNode));
  495. if (!self._c) {
  496. self._b = sto(function() {
  497. self.hide();
  498. }, 50);
  499. }
  500. self._c = false;
  501. };
  502. self._onClick = function(e)
  503. {
  504. e = e || window.event;
  505. var target = e.target || e.srcElement,
  506. pEl = target;
  507. if (!target) {
  508. return;
  509. }
  510. if (!hasEventListeners && hasClass(target, 'pika-select')) {
  511. if (!target.onchange) {
  512. target.setAttribute('onchange', 'return;');
  513. addEvent(target, 'change', self._onChange);
  514. }
  515. }
  516. do {
  517. if (hasClass(pEl, 'pika-single') || pEl === opts.trigger) {
  518. return;
  519. }
  520. }
  521. while ((pEl = pEl.parentNode));
  522. if (self._v && target !== opts.trigger && pEl !== opts.trigger) {
  523. self.hide();
  524. }
  525. };
  526. self.el = document.createElement('div');
  527. self.el.className = 'pika-single' + (opts.isRTL ? ' is-rtl' : '') + (opts.theme ? ' ' + opts.theme : '');
  528. addEvent(self.el, 'mousedown', self._onMouseDown, true);
  529. addEvent(self.el, 'touchend', self._onMouseDown, true);
  530. addEvent(self.el, 'change', self._onChange);
  531. if (opts.field) {
  532. if (opts.container) {
  533. opts.container.appendChild(self.el);
  534. } else if (opts.bound) {
  535. document.body.appendChild(self.el);
  536. } else {
  537. opts.field.parentNode.insertBefore(self.el, opts.field.nextSibling);
  538. }
  539. addEvent(opts.field, 'change', self._onInputChange);
  540. if (!opts.defaultDate) {
  541. if (hasMoment && opts.field.value) {
  542. opts.defaultDate = moment(opts.field.value, opts.format).toDate();
  543. } else {
  544. opts.defaultDate = new Date(Date.parse(opts.field.value));
  545. }
  546. opts.setDefaultDate = true;
  547. }
  548. }
  549. var defDate = opts.defaultDate;
  550. if (isDate(defDate)) {
  551. if (opts.setDefaultDate) {
  552. self.setDate(defDate, true);
  553. } else {
  554. self.gotoDate(defDate);
  555. }
  556. } else {
  557. self.gotoDate(new Date());
  558. }
  559. if (opts.bound) {
  560. this.hide();
  561. self.el.className += ' is-bound';
  562. addEvent(opts.trigger, 'click', self._onInputClick);
  563. addEvent(opts.trigger, 'focus', self._onInputFocus);
  564. addEvent(opts.trigger, 'blur', self._onInputBlur);
  565. } else {
  566. this.show();
  567. }
  568. };
  569. /**
  570. * public Pikaday API
  571. */
  572. Pikaday.prototype = {
  573. /**
  574. * configure functionality
  575. */
  576. config: function(options)
  577. {
  578. if (!this._o) {
  579. this._o = extend({}, defaults, true);
  580. }
  581. var opts = extend(this._o, options, true);
  582. opts.isRTL = !!opts.isRTL;
  583. opts.field = (opts.field && opts.field.nodeName) ? opts.field : null;
  584. opts.theme = (typeof opts.theme) === 'string' && opts.theme ? opts.theme : null;
  585. opts.bound = !!(opts.bound !== undefined ? opts.field && opts.bound : opts.field);
  586. opts.trigger = (opts.trigger && opts.trigger.nodeName) ? opts.trigger : opts.field;
  587. opts.disableWeekends = !!opts.disableWeekends;
  588. opts.disableDayFn = (typeof opts.disableDayFn) === 'function' ? opts.disableDayFn : null;
  589. var nom = parseInt(opts.numberOfMonths, 10) || 1;
  590. opts.numberOfMonths = nom > 4 ? 4 : nom;
  591. if (!isDate(opts.minDate)) {
  592. opts.minDate = false;
  593. }
  594. if (!isDate(opts.maxDate)) {
  595. opts.maxDate = false;
  596. }
  597. if ((opts.minDate && opts.maxDate) && opts.maxDate < opts.minDate) {
  598. opts.maxDate = opts.minDate = false;
  599. }
  600. if (opts.minDate) {
  601. this.setMinDate(opts.minDate);
  602. }
  603. if (opts.maxDate) {
  604. setToStartOfDay(opts.maxDate);
  605. opts.maxYear = opts.maxDate.getFullYear();
  606. opts.maxMonth = opts.maxDate.getMonth();
  607. }
  608. if (isArray(opts.yearRange)) {
  609. var fallback = new Date().getFullYear() - 10;
  610. opts.yearRange[0] = parseInt(opts.yearRange[0], 10) || fallback;
  611. opts.yearRange[1] = parseInt(opts.yearRange[1], 10) || fallback;
  612. } else {
  613. opts.yearRange = Math.abs(parseInt(opts.yearRange, 10)) || defaults.yearRange;
  614. if (opts.yearRange > 100) {
  615. opts.yearRange = 100;
  616. }
  617. }
  618. return opts;
  619. },
  620. /**
  621. * return a formatted string of the current selection (using Moment.js if available or default formatter)
  622. */
  623. toString: function(format) {
  624. return !isDate(this._d) ? '' : (hasMoment) ? moment(this._d).format(format || this._o.format) : formatter(this._d,this._o.format);
  625. },
  626. /**
  627. * return a Moment.js object of the current selection (if available)
  628. */
  629. getMoment: function()
  630. {
  631. return hasMoment ? moment(this._d) : null;
  632. },
  633. /**
  634. * set the current selection from a Moment.js object (if available)
  635. */
  636. setMoment: function(date, preventOnSelect)
  637. {
  638. if (hasMoment && moment.isMoment(date)) {
  639. this.setDate(date.toDate(), preventOnSelect);
  640. }
  641. },
  642. /**
  643. * return a Date object of the current selection
  644. */
  645. getDate: function()
  646. {
  647. return isDate(this._d) ? new Date(this._d.getTime()) : null;
  648. },
  649. /**
  650. * set the current selection
  651. */
  652. setDate: function(date, preventOnSelect)
  653. {
  654. if (!date) {
  655. this._d = null;
  656. if (this._o.field) {
  657. this._o.field.value = '';
  658. fireEvent(this._o.field, 'change', { firedBy: this });
  659. }
  660. return this.draw();
  661. }
  662. if (typeof date === 'string') {
  663. date = new Date(Date.parse(date));
  664. }
  665. if (!isDate(date)) {
  666. return;
  667. }
  668. var min = this._o.minDate,
  669. max = this._o.maxDate;
  670. if (isDate(min) && date < min) {
  671. date = min;
  672. } else if (isDate(max) && date > max) {
  673. date = max;
  674. }
  675. this._d = new Date(date.getTime());
  676. setToStartOfDay(this._d);
  677. this.gotoDate(this._d);
  678. if (this._o.field) {
  679. this._o.field.value = this.toString();
  680. fireEvent(this._o.field, 'change', { firedBy: this });
  681. }
  682. if (!preventOnSelect && typeof this._o.onSelect === 'function') {
  683. this._o.onSelect.call(this, this.getDate());
  684. }
  685. },
  686. /**
  687. * change view to a specific date
  688. */
  689. gotoDate: function(date)
  690. {
  691. var newCalendar = true;
  692. if (!isDate(date)) {
  693. return;
  694. }
  695. if (this.calendars) {
  696. var firstVisibleDate = new Date(this.calendars[0].year, this.calendars[0].month, 1),
  697. lastVisibleDate = new Date(this.calendars[this.calendars.length-1].year, this.calendars[this.calendars.length-1].month, 1),
  698. visibleDate = date.getTime();
  699. // get the end of the month
  700. lastVisibleDate.setMonth(lastVisibleDate.getMonth()+1);
  701. lastVisibleDate.setDate(lastVisibleDate.getDate()-1);
  702. newCalendar = (visibleDate < firstVisibleDate.getTime() || lastVisibleDate.getTime() < visibleDate);
  703. }
  704. if (newCalendar) {
  705. this.calendars = [{
  706. month: date.getMonth(),
  707. year: date.getFullYear()
  708. }];
  709. if (this._o.mainCalendar === 'right') {
  710. this.calendars[0].month += 1 - this._o.numberOfMonths;
  711. }
  712. }
  713. this.adjustCalendars();
  714. },
  715. adjustCalendars: function() {
  716. this.calendars[0] = adjustCalendar(this.calendars[0]);
  717. for (var c = 1; c < this._o.numberOfMonths; c++) {
  718. this.calendars[c] = adjustCalendar({
  719. month: this.calendars[0].month + c,
  720. year: this.calendars[0].year
  721. });
  722. }
  723. this.draw();
  724. },
  725. gotoToday: function()
  726. {
  727. this.gotoDate(new Date());
  728. },
  729. /**
  730. * change view to a specific month (zero-index, e.g. 0: January)
  731. */
  732. gotoMonth: function(month)
  733. {
  734. if (!isNaN(month)) {
  735. this.calendars[0].month = parseInt(month, 10);
  736. this.adjustCalendars();
  737. }
  738. },
  739. nextMonth: function()
  740. {
  741. this.calendars[0].month++;
  742. this.adjustCalendars();
  743. },
  744. prevMonth: function()
  745. {
  746. this.calendars[0].month--;
  747. this.adjustCalendars();
  748. },
  749. /**
  750. * change view to a specific full year (e.g. "2012")
  751. */
  752. gotoYear: function(year)
  753. {
  754. if (!isNaN(year)) {
  755. this.calendars[0].year = parseInt(year, 10);
  756. this.adjustCalendars();
  757. }
  758. },
  759. /**
  760. * change the minDate
  761. */
  762. setMinDate: function(value)
  763. {
  764. setToStartOfDay(value);
  765. this._o.minDate = value;
  766. this._o.minYear = value.getFullYear();
  767. this._o.minMonth = value.getMonth();
  768. },
  769. /**
  770. * change the maxDate
  771. */
  772. setMaxDate: function(value)
  773. {
  774. this._o.maxDate = value;
  775. },
  776. setStartRange: function(value)
  777. {
  778. this._o.startRange = value;
  779. },
  780. setEndRange: function(value)
  781. {
  782. this._o.endRange = value;
  783. },
  784. /**
  785. * refresh the HTML
  786. */
  787. draw: function(force)
  788. {
  789. if (!this._v && !force) {
  790. return;
  791. }
  792. var opts = this._o,
  793. minYear = opts.minYear,
  794. maxYear = opts.maxYear,
  795. minMonth = opts.minMonth,
  796. maxMonth = opts.maxMonth,
  797. html = '';
  798. if (this._y <= minYear) {
  799. this._y = minYear;
  800. if (!isNaN(minMonth) && this._m < minMonth) {
  801. this._m = minMonth;
  802. }
  803. }
  804. if (this._y >= maxYear) {
  805. this._y = maxYear;
  806. if (!isNaN(maxMonth) && this._m > maxMonth) {
  807. this._m = maxMonth;
  808. }
  809. }
  810. for (var c = 0; c < opts.numberOfMonths; c++) {
  811. html += '<div class="pika-lendar">' + renderTitle(this, c, this.calendars[c].year, this.calendars[c].month, this.calendars[0].year) + this.render(this.calendars[c].year, this.calendars[c].month) + '</div>';
  812. }
  813. this.el.innerHTML = html;
  814. if (opts.bound) {
  815. if(opts.field.type !== 'hidden') {
  816. sto(function() {
  817. opts.trigger.focus();
  818. }, 1);
  819. }
  820. }
  821. if (typeof this._o.onDraw === 'function') {
  822. var self = this;
  823. sto(function() {
  824. self._o.onDraw.call(self);
  825. }, 0);
  826. }
  827. },
  828. adjustPosition: function()
  829. {
  830. var field, pEl, width, height, viewportWidth, viewportHeight, scrollTop, left, top, clientRect;
  831. if (this._o.container) return;
  832. this.el.style.position = 'absolute';
  833. field = this._o.trigger;
  834. pEl = field;
  835. width = this.el.offsetWidth;
  836. height = this.el.offsetHeight;
  837. viewportWidth = window.innerWidth || document.documentElement.clientWidth;
  838. viewportHeight = window.innerHeight || document.documentElement.clientHeight;
  839. scrollTop = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
  840. if (typeof field.getBoundingClientRect === 'function') {
  841. clientRect = field.getBoundingClientRect();
  842. left = clientRect.left + window.pageXOffset;
  843. top = clientRect.bottom + window.pageYOffset;
  844. } else {
  845. left = pEl.offsetLeft;
  846. top = pEl.offsetTop + pEl.offsetHeight;
  847. while((pEl = pEl.offsetParent)) {
  848. left += pEl.offsetLeft;
  849. top += pEl.offsetTop;
  850. }
  851. }
  852. // default position is bottom & left
  853. if ((this._o.reposition && left + width > viewportWidth) ||
  854. (
  855. this._o.position.indexOf('right') > -1 &&
  856. left - width + field.offsetWidth > 0
  857. )
  858. ) {
  859. left = left - width + field.offsetWidth;
  860. }
  861. if ((this._o.reposition && top + height > viewportHeight + scrollTop) ||
  862. (
  863. this._o.position.indexOf('top') > -1 &&
  864. top - height - field.offsetHeight > 0
  865. )
  866. ) {
  867. top = top - height - field.offsetHeight;
  868. }
  869. this.el.style.left = left + 'px';
  870. this.el.style.top = top + 'px';
  871. },
  872. /**
  873. * render HTML for a particular month
  874. */
  875. render: function(year, month)
  876. {
  877. var opts = this._o,
  878. now = new Date(),
  879. days = getDaysInMonth(year, month),
  880. before = new Date(year, month, 1).getDay(),
  881. data = [],
  882. row = [];
  883. setToStartOfDay(now);
  884. if (opts.firstDay > 0) {
  885. before -= opts.firstDay;
  886. if (before < 0) {
  887. before += 7;
  888. }
  889. }
  890. var cells = days + before,
  891. after = cells;
  892. while(after > 7) {
  893. after -= 7;
  894. }
  895. cells += 7 - after;
  896. for (var i = 0, r = 0; i < cells; i++)
  897. {
  898. var day = new Date(year, month, 1 + (i - before)),
  899. isSelected = isDate(this._d) ? compareDates(day, this._d) : false,
  900. isToday = compareDates(day, now),
  901. isEmpty = i < before || i >= (days + before),
  902. isStartRange = opts.startRange && compareDates(opts.startRange, day),
  903. isEndRange = opts.endRange && compareDates(opts.endRange, day),
  904. isInRange = opts.startRange && opts.endRange && opts.startRange < day && day < opts.endRange,
  905. isDisabled = (opts.minDate && day < opts.minDate) ||
  906. (opts.maxDate && day > opts.maxDate) ||
  907. (opts.disableWeekends && isWeekend(day)) ||
  908. (opts.disableDayFn && opts.disableDayFn(day)),
  909. dayConfig = {
  910. day: 1 + (i - before),
  911. month: month,
  912. year: year,
  913. isSelected: isSelected,
  914. isToday: isToday,
  915. isDisabled: isDisabled,
  916. isEmpty: isEmpty,
  917. isStartRange: isStartRange,
  918. isEndRange: isEndRange,
  919. isInRange: isInRange
  920. };
  921. row.push(renderDay(dayConfig));
  922. if (++r === 7) {
  923. if (opts.showWeekNumber) {
  924. row.unshift(renderWeek(i - before, month, year));
  925. }
  926. data.push(renderRow(row, opts.isRTL));
  927. row = [];
  928. r = 0;
  929. }
  930. }
  931. return renderTable(opts, data);
  932. },
  933. isVisible: function()
  934. {
  935. return this._v;
  936. },
  937. show: function()
  938. {
  939. if (!this._v) {
  940. removeClass(this.el, 'is-hidden');
  941. this._v = true;
  942. this.draw();
  943. if (this._o.bound) {
  944. addEvent(document, 'click', this._onClick);
  945. this.adjustPosition();
  946. }
  947. if (typeof this._o.onOpen === 'function') {
  948. this._o.onOpen.call(this);
  949. }
  950. }
  951. },
  952. hide: function()
  953. {
  954. var v = this._v;
  955. if (v !== false) {
  956. if (this._o.bound) {
  957. removeEvent(document, 'click', this._onClick);
  958. }
  959. this.el.style.position = 'static'; // reset
  960. this.el.style.left = 'auto';
  961. this.el.style.top = 'auto';
  962. addClass(this.el, 'is-hidden');
  963. this._v = false;
  964. if (v !== undefined && typeof this._o.onClose === 'function') {
  965. this._o.onClose.call(this);
  966. }
  967. }
  968. },
  969. /**
  970. * GAME OVER
  971. */
  972. destroy: function()
  973. {
  974. this.hide();
  975. removeEvent(this.el, 'mousedown', this._onMouseDown, true);
  976. removeEvent(this.el, 'touchend', this._onMouseDown, true);
  977. removeEvent(this.el, 'change', this._onChange);
  978. if (this._o.field) {
  979. removeEvent(this._o.field, 'change', this._onInputChange);
  980. if (this._o.bound) {
  981. removeEvent(this._o.trigger, 'click', this._onInputClick);
  982. removeEvent(this._o.trigger, 'focus', this._onInputFocus);
  983. removeEvent(this._o.trigger, 'blur', this._onInputBlur);
  984. }
  985. }
  986. if (this.el.parentNode) {
  987. this.el.parentNode.removeChild(this.el);
  988. }
  989. }
  990. };
  991. return Pikaday;
  992. }));