calendar.js 36 KB

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