datepicker.js 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237
  1. ;(function (window, jQuery, undefined) { ;(function () {
  2. var VERSION = '2.2.3',
  3. pluginName = 'datepicker',
  4. autoInitSelector = '.datepicker-here',
  5. jQuerybody, jQuerydatepickersContainer,
  6. containerBuilt = false,
  7. baseTemplate = '' +
  8. '<div class="datepicker">' +
  9. '<i class="datepicker--pointer"></i>' +
  10. '<nav class="datepicker--nav"></nav>' +
  11. '<div class="datepicker--content"></div>' +
  12. '</div>',
  13. defaults = {
  14. classes: '',
  15. inline: false,
  16. language: 'ru',
  17. startDate: new Date(),
  18. firstDay: '',
  19. weekends: [6, 0],
  20. dateFormat: '',
  21. altField: '',
  22. altFieldDateFormat: '@',
  23. toggleSelected: true,
  24. keyboardNav: true,
  25. position: 'bottom left',
  26. offset: 12,
  27. view: 'days',
  28. minView: 'days',
  29. showOtherMonths: true,
  30. selectOtherMonths: true,
  31. moveToOtherMonthsOnSelect: true,
  32. showOtherYears: true,
  33. selectOtherYears: true,
  34. moveToOtherYearsOnSelect: true,
  35. minDate: '',
  36. maxDate: '',
  37. disableNavWhenOutOfRange: true,
  38. multipleDates: false, // Boolean or Number
  39. multipleDatesSeparator: ',',
  40. range: false,
  41. todayButton: false,
  42. clearButton: false,
  43. showEvent: 'focus',
  44. autoClose: false,
  45. // navigation
  46. monthsField: 'monthsShort',
  47. prevHtml: '<svg><path d="M 17,12 l -5,5 l 5,5"></path></svg>',
  48. nextHtml: '<svg><path d="M 14,12 l 5,5 l -5,5"></path></svg>',
  49. navTitles: {
  50. days: 'MM, <i>yyyy</i>',
  51. // days: '<i>yyyy</i>, MM',
  52. months: 'yyyy',
  53. years: 'yyyy1 - yyyy2'
  54. },
  55. // timepicker
  56. timepicker: false,
  57. onlyTimepicker: false,
  58. dateTimeSeparator: ' ',
  59. timeFormat: '',
  60. minHours: 0,
  61. maxHours: 24,
  62. minMinutes: 0,
  63. maxMinutes: 59,
  64. hoursStep: 1,
  65. minutesStep: 1,
  66. // events
  67. onSelect: '',
  68. onShow: '',
  69. onHide: '',
  70. onChangeMonth: '',
  71. onChangeYear: '',
  72. onChangeDecade: '',
  73. onChangeView: '',
  74. onRenderCell: ''
  75. },
  76. hotKeys = {
  77. 'ctrlRight': [17, 39],
  78. 'ctrlUp': [17, 38],
  79. 'ctrlLeft': [17, 37],
  80. 'ctrlDown': [17, 40],
  81. 'shiftRight': [16, 39],
  82. 'shiftUp': [16, 38],
  83. 'shiftLeft': [16, 37],
  84. 'shiftDown': [16, 40],
  85. 'altUp': [18, 38],
  86. 'altRight': [18, 39],
  87. 'altLeft': [18, 37],
  88. 'altDown': [18, 40],
  89. 'ctrlShiftUp': [16, 17, 38]
  90. },
  91. datepicker;
  92. var Datepicker = function (el, options) {
  93. this.el = el;
  94. this.jQueryel = jQuery(el);
  95. this.opts = jQuery.extend(true, {}, defaults, options, this.jQueryel.data());
  96. if (jQuerybody == undefined) {
  97. jQuerybody = jQuery('body');
  98. }
  99. if (!this.opts.startDate) {
  100. this.opts.startDate = new Date();
  101. }
  102. if (this.el.nodeName == 'INPUT') {
  103. this.elIsInput = true;
  104. }
  105. if (this.opts.altField) {
  106. this.jQueryaltField = typeof this.opts.altField == 'string' ? jQuery(this.opts.altField) : this.opts.altField;
  107. }
  108. this.inited = false;
  109. this.visible = false;
  110. this.silent = false; // Need to prevent unnecessary rendering
  111. this.currentDate = this.opts.startDate;
  112. this.currentView = this.opts.view;
  113. this._createShortCuts();
  114. this.selectedDates = [];
  115. this.views = {};
  116. this.keys = [];
  117. this.minRange = '';
  118. this.maxRange = '';
  119. this._prevOnSelectValue = '';
  120. this.init()
  121. };
  122. datepicker = Datepicker;
  123. datepicker.prototype = {
  124. VERSION: VERSION,
  125. viewIndexes: ['days','months', 'years' ],
  126. init: function () {
  127. if (!containerBuilt && !this.opts.inline && this.elIsInput) {
  128. this._buildDatepickersContainer();
  129. }
  130. this._buildBaseHtml();
  131. this._defineLocale(this.opts.language);
  132. this._syncWithMinMaxDates();
  133. if (this.elIsInput) {
  134. if (!this.opts.inline) {
  135. // Set extra classes for proper transitions
  136. this._setPositionClasses(this.opts.position);
  137. this._bindEvents()
  138. }
  139. if (this.opts.keyboardNav && !this.opts.onlyTimepicker) {
  140. this._bindKeyboardEvents();
  141. }
  142. this.jQuerydatepicker.on('mousedown', this._onMouseDownDatepicker.bind(this));
  143. this.jQuerydatepicker.on('mouseup', this._onMouseUpDatepicker.bind(this));
  144. }
  145. if (this.opts.classes) {
  146. this.jQuerydatepicker.addClass(this.opts.classes)
  147. }
  148. if (this.opts.timepicker) {
  149. this.timepicker = new jQuery.fn.datepicker.Timepicker(this, this.opts);
  150. this._bindTimepickerEvents();
  151. }
  152. if (this.opts.onlyTimepicker) {
  153. this.jQuerydatepicker.addClass('-only-timepicker-');
  154. }
  155. this.views[this.currentView] = new jQuery.fn.datepicker.Body(this, this.currentView, this.opts);
  156. this.views[this.currentView].show();
  157. this.nav = new jQuery.fn.datepicker.Navigation(this, this.opts);
  158. this.view = this.currentView;
  159. this.jQueryel.on('clickCell.adp', this._onClickCell.bind(this));
  160. this.jQuerydatepicker.on('mouseenter', '.datepicker--cell', this._onMouseEnterCell.bind(this));
  161. this.jQuerydatepicker.on('mouseleave', '.datepicker--cell', this._onMouseLeaveCell.bind(this));
  162. this.inited = true;
  163. },
  164. _createShortCuts: function () {
  165. this.minDate = this.opts.minDate ? this.opts.minDate : new Date(-8639999913600000);
  166. this.maxDate = this.opts.maxDate ? this.opts.maxDate : new Date(8639999913600000);
  167. },
  168. _bindEvents : function () {
  169. this.jQueryel.on(this.opts.showEvent + '.adp', this._onShowEvent.bind(this));
  170. this.jQueryel.on('mouseup.adp', this._onMouseUpEl.bind(this));
  171. this.jQueryel.on('blur.adp', this._onBlur.bind(this));
  172. this.jQueryel.on('keyup.adp', this._onKeyUpGeneral.bind(this));
  173. jQuery(window).on('resize.adp', this._onResize.bind(this));
  174. jQuery('body').on('mouseup.adp', this._onMouseUpBody.bind(this));
  175. },
  176. _bindKeyboardEvents: function () {
  177. this.jQueryel.on('keydown.adp', this._onKeyDown.bind(this));
  178. this.jQueryel.on('keyup.adp', this._onKeyUp.bind(this));
  179. this.jQueryel.on('hotKey.adp', this._onHotKey.bind(this));
  180. },
  181. _bindTimepickerEvents: function () {
  182. this.jQueryel.on('timeChange.adp', this._onTimeChange.bind(this));
  183. },
  184. isWeekend: function (day) {
  185. return this.opts.weekends.indexOf(day) !== -1;
  186. },
  187. _defineLocale: function (lang) {
  188. if (typeof lang == 'string') {
  189. this.loc = jQuery.fn.datepicker.language[lang];
  190. if (!this.loc) {
  191. console.warn('Can\'t find language "' + lang + '" in Datepicker.language, will use "ru" instead');
  192. this.loc = jQuery.extend(true, {}, jQuery.fn.datepicker.language.ru)
  193. }
  194. this.loc = jQuery.extend(true, {}, jQuery.fn.datepicker.language.ru, jQuery.fn.datepicker.language[lang])
  195. } else {
  196. this.loc = jQuery.extend(true, {}, jQuery.fn.datepicker.language.ru, lang)
  197. }
  198. if (this.opts.dateFormat) {
  199. this.loc.dateFormat = this.opts.dateFormat
  200. }
  201. if (this.opts.timeFormat) {
  202. this.loc.timeFormat = this.opts.timeFormat
  203. }
  204. if (this.opts.firstDay !== '') {
  205. this.loc.firstDay = this.opts.firstDay
  206. }
  207. if (this.opts.timepicker) {
  208. this.loc.dateFormat = [this.loc.dateFormat, this.loc.timeFormat].join(this.opts.dateTimeSeparator);
  209. }
  210. if (this.opts.onlyTimepicker) {
  211. this.loc.dateFormat = this.loc.timeFormat;
  212. }
  213. var boundary = this._getWordBoundaryRegExp;
  214. if (this.loc.timeFormat.match(boundary('aa')) ||
  215. this.loc.timeFormat.match(boundary('AA'))
  216. ) {
  217. this.ampm = true;
  218. }
  219. },
  220. _buildDatepickersContainer: function () {
  221. containerBuilt = true;
  222. jQuerybody.append('<div class="datepickers-container" id="datepickers-container"></div>');
  223. jQuerydatepickersContainer = jQuery('#datepickers-container');
  224. },
  225. _buildBaseHtml: function () {
  226. var jQueryappendTarget,
  227. jQueryinline = jQuery('<div class="datepicker-inline">');
  228. if(this.el.nodeName == 'INPUT') {
  229. if (!this.opts.inline) {
  230. jQueryappendTarget = jQuerydatepickersContainer;
  231. } else {
  232. jQueryappendTarget = jQueryinline.insertAfter(this.jQueryel)
  233. }
  234. } else {
  235. jQueryappendTarget = jQueryinline.appendTo(this.jQueryel)
  236. }
  237. this.jQuerydatepicker = jQuery(baseTemplate).appendTo(jQueryappendTarget);
  238. this.jQuerycontent = jQuery('.datepicker--content', this.jQuerydatepicker);
  239. this.jQuerynav = jQuery('.datepicker--nav', this.jQuerydatepicker);
  240. },
  241. _triggerOnChange: function () {
  242. if (!this.selectedDates.length) {
  243. // Prevent from triggering multiple onSelect callback with same argument (empty string) in IE10-11
  244. if (this._prevOnSelectValue === '') return;
  245. this._prevOnSelectValue = '';
  246. return this.opts.onSelect('', '', this);
  247. }
  248. var selectedDates = this.selectedDates,
  249. parsedSelected = datepicker.getParsedDate(selectedDates[0]),
  250. formattedDates,
  251. _this = this,
  252. dates = new Date(
  253. parsedSelected.year,
  254. parsedSelected.month,
  255. parsedSelected.date,
  256. parsedSelected.hours,
  257. parsedSelected.minutes
  258. );
  259. formattedDates = selectedDates.map(function (date) {
  260. return _this.formatDate(_this.loc.dateFormat, date)
  261. }).join(this.opts.multipleDatesSeparator);
  262. // Create new dates array, to separate it from original selectedDates
  263. if (this.opts.multipleDates || this.opts.range) {
  264. dates = selectedDates.map(function(date) {
  265. var parsedDate = datepicker.getParsedDate(date);
  266. return new Date(
  267. parsedDate.year,
  268. parsedDate.month,
  269. parsedDate.date,
  270. parsedDate.hours,
  271. parsedDate.minutes
  272. );
  273. })
  274. }
  275. this._prevOnSelectValue = formattedDates;
  276. this.opts.onSelect(formattedDates, dates, this);
  277. },
  278. next: function () {
  279. var d = this.parsedDate,
  280. o = this.opts;
  281. switch (this.view) {
  282. case 'days':
  283. this.date = new Date(d.year, d.month + 1, 1);
  284. if (o.onChangeMonth) o.onChangeMonth(this.parsedDate.month, this.parsedDate.year);
  285. break;
  286. case 'months':
  287. this.date = new Date(d.year + 1, d.month, 1);
  288. if (o.onChangeYear) o.onChangeYear(this.parsedDate.year);
  289. break;
  290. case 'years':
  291. this.date = new Date(d.year + 10, 0, 1);
  292. if (o.onChangeDecade) o.onChangeDecade(this.curDecade);
  293. break;
  294. }
  295. },
  296. prev: function () {
  297. var d = this.parsedDate,
  298. o = this.opts;
  299. switch (this.view) {
  300. case 'days':
  301. this.date = new Date(d.year, d.month - 1, 1);
  302. if (o.onChangeMonth) o.onChangeMonth(this.parsedDate.month, this.parsedDate.year);
  303. break;
  304. case 'months':
  305. this.date = new Date(d.year - 1, d.month, 1);
  306. if (o.onChangeYear) o.onChangeYear(this.parsedDate.year);
  307. break;
  308. case 'years':
  309. this.date = new Date(d.year - 10, 0, 1);
  310. if (o.onChangeDecade) o.onChangeDecade(this.curDecade);
  311. break;
  312. }
  313. },
  314. formatDate: function (string, date) {
  315. date = date || this.date;
  316. var result = string,
  317. boundary = this._getWordBoundaryRegExp,
  318. locale = this.loc,
  319. leadingZero = datepicker.getLeadingZeroNum,
  320. decade = datepicker.getDecade(date),
  321. d = datepicker.getParsedDate(date),
  322. fullHours = d.fullHours,
  323. hours = d.hours,
  324. ampm = string.match(boundary('aa')) || string.match(boundary('AA')),
  325. dayPeriod = 'am',
  326. replacer = this._replacer,
  327. validHours;
  328. if (this.opts.timepicker && this.timepicker && ampm) {
  329. validHours = this.timepicker._getValidHoursFromDate(date, ampm);
  330. fullHours = leadingZero(validHours.hours);
  331. hours = validHours.hours;
  332. dayPeriod = validHours.dayPeriod;
  333. }
  334. switch (true) {
  335. case /@/.test(result):
  336. result = result.replace(/@/, date.getTime());
  337. case /aa/.test(result):
  338. result = replacer(result, boundary('aa'), dayPeriod);
  339. case /AA/.test(result):
  340. result = replacer(result, boundary('AA'), dayPeriod.toUpperCase());
  341. case /dd/.test(result):
  342. result = replacer(result, boundary('dd'), d.fullDate);
  343. case /d/.test(result):
  344. result = replacer(result, boundary('d'), d.date);
  345. case /DD/.test(result):
  346. result = replacer(result, boundary('DD'), locale.days[d.day]);
  347. case /D/.test(result):
  348. result = replacer(result, boundary('D'), locale.daysShort[d.day]);
  349. case /mm/.test(result):
  350. result = replacer(result, boundary('mm'), d.fullMonth);
  351. case /m/.test(result):
  352. result = replacer(result, boundary('m'), d.month + 1);
  353. case /MM/.test(result):
  354. result = replacer(result, boundary('MM'), this.loc.months[d.month]);
  355. case /M/.test(result):
  356. result = replacer(result, boundary('M'), locale.monthsShort[d.month]);
  357. case /ii/.test(result):
  358. result = replacer(result, boundary('ii'), d.fullMinutes);
  359. case /i/.test(result):
  360. result = replacer(result, boundary('i'), d.minutes);
  361. case /hh/.test(result):
  362. result = replacer(result, boundary('hh'), fullHours);
  363. case /h/.test(result):
  364. result = replacer(result, boundary('h'), hours);
  365. case /yyyy/.test(result):
  366. result = replacer(result, boundary('yyyy'), d.year);
  367. case /yyyy1/.test(result):
  368. result = replacer(result, boundary('yyyy1'), decade[0]);
  369. case /yyyy2/.test(result):
  370. result = replacer(result, boundary('yyyy2'), decade[1]);
  371. case /yy/.test(result):
  372. result = replacer(result, boundary('yy'), d.year.toString().slice(-2));
  373. }
  374. return result;
  375. },
  376. _replacer: function (str, reg, data) {
  377. return str.replace(reg, function (match, p1,p2,p3) {
  378. return p1 + data + p3;
  379. })
  380. },
  381. _getWordBoundaryRegExp: function (sign) {
  382. var symbols = '\\s|\\.|-|/|\\\\|,|\\jQuery|\\!|\\?|:|;';
  383. return new RegExp('(^|>|' + symbols + ')(' + sign + ')(jQuery|<|' + symbols + ')', 'g');
  384. },
  385. selectDate: function (date) {
  386. var _this = this,
  387. opts = _this.opts,
  388. d = _this.parsedDate,
  389. selectedDates = _this.selectedDates,
  390. len = selectedDates.length,
  391. newDate = '';
  392. if (Array.isArray(date)) {
  393. date.forEach(function (d) {
  394. _this.selectDate(d)
  395. });
  396. return;
  397. }
  398. if (!(date instanceof Date)) return;
  399. this.lastSelectedDate = date;
  400. // Set new time values from Date
  401. if (this.timepicker) {
  402. this.timepicker._setTime(date);
  403. }
  404. // On this step timepicker will set valid values in it's instance
  405. _this._trigger('selectDate', date);
  406. // Set correct time values after timepicker's validation
  407. // Prevent from setting hours or minutes which values are lesser then `min` value or
  408. // greater then `max` value
  409. if (this.timepicker) {
  410. date.setHours(this.timepicker.hours);
  411. date.setMinutes(this.timepicker.minutes)
  412. }
  413. if (_this.view == 'days') {
  414. if (date.getMonth() != d.month && opts.moveToOtherMonthsOnSelect) {
  415. newDate = new Date(date.getFullYear(), date.getMonth(), 1);
  416. }
  417. }
  418. if (_this.view == 'years') {
  419. if (date.getFullYear() != d.year && opts.moveToOtherYearsOnSelect) {
  420. newDate = new Date(date.getFullYear(), 0, 1);
  421. }
  422. }
  423. if (newDate) {
  424. _this.silent = true;
  425. _this.date = newDate;
  426. _this.silent = false;
  427. _this.nav._render()
  428. }
  429. if (opts.multipleDates && !opts.range) { // Set priority to range functionality
  430. if (len === opts.multipleDates) return;
  431. if (!_this._isSelected(date)) {
  432. _this.selectedDates.push(date);
  433. }
  434. } else if (opts.range) {
  435. if (len == 2) {
  436. _this.selectedDates = [date];
  437. _this.minRange = date;
  438. _this.maxRange = '';
  439. } else if (len == 1) {
  440. _this.selectedDates.push(date);
  441. if (!_this.maxRange){
  442. _this.maxRange = date;
  443. } else {
  444. _this.minRange = date;
  445. }
  446. // Swap dates if they were selected via dp.selectDate() and second date was smaller then first
  447. if (datepicker.bigger(_this.maxRange, _this.minRange)) {
  448. _this.maxRange = _this.minRange;
  449. _this.minRange = date;
  450. }
  451. _this.selectedDates = [_this.minRange, _this.maxRange]
  452. } else {
  453. _this.selectedDates = [date];
  454. _this.minRange = date;
  455. }
  456. } else {
  457. _this.selectedDates = [date];
  458. }
  459. _this._setInputValue();
  460. if (opts.onSelect) {
  461. _this._triggerOnChange();
  462. }
  463. if (opts.autoClose && !this.timepickerIsActive) {
  464. if (!opts.multipleDates && !opts.range) {
  465. _this.hide();
  466. } else if (opts.range && _this.selectedDates.length == 2) {
  467. _this.hide();
  468. }
  469. }
  470. _this.views[this.currentView]._render()
  471. },
  472. removeDate: function (date) {
  473. var selected = this.selectedDates,
  474. _this = this;
  475. if (!(date instanceof Date)) return;
  476. return selected.some(function (curDate, i) {
  477. if (datepicker.isSame(curDate, date)) {
  478. selected.splice(i, 1);
  479. if (!_this.selectedDates.length) {
  480. _this.minRange = '';
  481. _this.maxRange = '';
  482. _this.lastSelectedDate = '';
  483. } else {
  484. _this.lastSelectedDate = _this.selectedDates[_this.selectedDates.length - 1];
  485. }
  486. _this.views[_this.currentView]._render();
  487. _this._setInputValue();
  488. if (_this.opts.onSelect) {
  489. _this._triggerOnChange();
  490. }
  491. return true
  492. }
  493. })
  494. },
  495. today: function () {
  496. this.silent = true;
  497. this.view = this.opts.minView;
  498. this.silent = false;
  499. this.date = new Date();
  500. if (this.opts.todayButton instanceof Date) {
  501. this.selectDate(this.opts.todayButton)
  502. }
  503. },
  504. clear: function () {
  505. this.selectedDates = [];
  506. this.minRange = '';
  507. this.maxRange = '';
  508. this.views[this.currentView]._render();
  509. this._setInputValue();
  510. if (this.opts.onSelect) {
  511. this._triggerOnChange()
  512. }
  513. },
  514. /**
  515. * Updates datepicker options
  516. * @param {String|Object} param - parameter's name to update. If object then it will extend current options
  517. * @param {String|Number|Object} [value] - new param value
  518. */
  519. update: function (param, value) {
  520. var len = arguments.length,
  521. lastSelectedDate = this.lastSelectedDate;
  522. if (len == 2) {
  523. this.opts[param] = value;
  524. } else if (len == 1 && typeof param == 'object') {
  525. this.opts = jQuery.extend(true, this.opts, param)
  526. }
  527. this._createShortCuts();
  528. this._syncWithMinMaxDates();
  529. this._defineLocale(this.opts.language);
  530. this.nav._addButtonsIfNeed();
  531. if (!this.opts.onlyTimepicker) this.nav._render();
  532. this.views[this.currentView]._render();
  533. if (this.elIsInput && !this.opts.inline) {
  534. this._setPositionClasses(this.opts.position);
  535. if (this.visible) {
  536. this.setPosition(this.opts.position)
  537. }
  538. }
  539. if (this.opts.classes) {
  540. this.jQuerydatepicker.addClass(this.opts.classes)
  541. }
  542. if (this.opts.onlyTimepicker) {
  543. this.jQuerydatepicker.addClass('-only-timepicker-');
  544. }
  545. if (this.opts.timepicker) {
  546. if (lastSelectedDate) this.timepicker._handleDate(lastSelectedDate);
  547. this.timepicker._updateRanges();
  548. this.timepicker._updateCurrentTime();
  549. // Change hours and minutes if it's values have been changed through min/max hours/minutes
  550. if (lastSelectedDate) {
  551. lastSelectedDate.setHours(this.timepicker.hours);
  552. lastSelectedDate.setMinutes(this.timepicker.minutes);
  553. }
  554. }
  555. this._setInputValue();
  556. return this;
  557. },
  558. _syncWithMinMaxDates: function () {
  559. var curTime = this.date.getTime();
  560. this.silent = true;
  561. if (this.minTime > curTime) {
  562. this.date = this.minDate;
  563. }
  564. if (this.maxTime < curTime) {
  565. this.date = this.maxDate;
  566. }
  567. this.silent = false;
  568. },
  569. _isSelected: function (checkDate, cellType) {
  570. var res = false;
  571. this.selectedDates.some(function (date) {
  572. if (datepicker.isSame(date, checkDate, cellType)) {
  573. res = date;
  574. return true;
  575. }
  576. });
  577. return res;
  578. },
  579. _setInputValue: function () {
  580. var _this = this,
  581. opts = _this.opts,
  582. format = _this.loc.dateFormat,
  583. altFormat = opts.altFieldDateFormat,
  584. value = _this.selectedDates.map(function (date) {
  585. return _this.formatDate(format, date)
  586. }),
  587. altValues;
  588. if (opts.altField && _this.jQueryaltField.length) {
  589. altValues = this.selectedDates.map(function (date) {
  590. return _this.formatDate(altFormat, date)
  591. });
  592. altValues = altValues.join(this.opts.multipleDatesSeparator);
  593. this.jQueryaltField.val(altValues);
  594. }
  595. value = value.join(this.opts.multipleDatesSeparator);
  596. this.jQueryel.val(value)
  597. },
  598. /**
  599. * Check if date is between minDate and maxDate
  600. * @param date {object} - date object
  601. * @param type {string} - cell type
  602. * @returns {boolean}
  603. * @private
  604. */
  605. _isInRange: function (date, type) {
  606. var time = date.getTime(),
  607. d = datepicker.getParsedDate(date),
  608. min = datepicker.getParsedDate(this.minDate),
  609. max = datepicker.getParsedDate(this.maxDate),
  610. dMinTime = new Date(d.year, d.month, min.date).getTime(),
  611. dMaxTime = new Date(d.year, d.month, max.date).getTime(),
  612. types = {
  613. day: time >= this.minTime && time <= this.maxTime,
  614. month: dMinTime >= this.minTime && dMaxTime <= this.maxTime,
  615. year: d.year >= min.year && d.year <= max.year
  616. };
  617. return type ? types[type] : types.day
  618. },
  619. _getDimensions: function (jQueryel) {
  620. var offset = jQueryel.offset();
  621. return {
  622. width: jQueryel.outerWidth(),
  623. height: jQueryel.outerHeight(),
  624. left: offset.left,
  625. top: offset.top
  626. }
  627. },
  628. _getDateFromCell: function (cell) {
  629. var curDate = this.parsedDate,
  630. year = cell.data('year') || curDate.year,
  631. month = cell.data('month') == undefined ? curDate.month : cell.data('month'),
  632. date = cell.data('date') || 1;
  633. return new Date(year, month, date);
  634. },
  635. _setPositionClasses: function (pos) {
  636. pos = pos.split(' ');
  637. var main = pos[0],
  638. sec = pos[1],
  639. classes = 'datepicker -' + main + '-' + sec + '- -from-' + main + '-';
  640. if (this.visible) classes += ' active';
  641. this.jQuerydatepicker
  642. .removeAttr('class')
  643. .addClass(classes);
  644. },
  645. setPosition: function (position) {
  646. position = position || this.opts.position;
  647. var dims = this._getDimensions(this.jQueryel),
  648. selfDims = this._getDimensions(this.jQuerydatepicker),
  649. pos = position.split(' '),
  650. top, left,
  651. offset = this.opts.offset,
  652. main = pos[0],
  653. secondary = pos[1];
  654. switch (main) {
  655. case 'top':
  656. top = dims.top - selfDims.height - offset;
  657. break;
  658. case 'right':
  659. left = dims.left + dims.width + offset;
  660. break;
  661. case 'bottom':
  662. top = dims.top + dims.height + offset;
  663. break;
  664. case 'left':
  665. left = dims.left - selfDims.width - offset;
  666. break;
  667. }
  668. switch(secondary) {
  669. case 'top':
  670. top = dims.top;
  671. break;
  672. case 'right':
  673. left = dims.left + dims.width - selfDims.width;
  674. break;
  675. case 'bottom':
  676. top = dims.top + dims.height - selfDims.height;
  677. break;
  678. case 'left':
  679. left = dims.left;
  680. break;
  681. case 'center':
  682. if (/left|right/.test(main)) {
  683. top = dims.top + dims.height/2 - selfDims.height/2;
  684. } else {
  685. left = dims.left + dims.width/2 - selfDims.width/2;
  686. }
  687. }
  688. this.jQuerydatepicker
  689. .css({
  690. left: left,
  691. top: top
  692. })
  693. },
  694. show: function () {
  695. var onShow = this.opts.onShow;
  696. this.setPosition(this.opts.position);
  697. this.jQuerydatepicker.addClass('active');
  698. this.visible = true;
  699. if (onShow) {
  700. this._bindVisionEvents(onShow)
  701. }
  702. },
  703. hide: function () {
  704. var onHide = this.opts.onHide;
  705. this.jQuerydatepicker
  706. .removeClass('active')
  707. .css({
  708. left: '-100000px'
  709. });
  710. this.focused = '';
  711. this.keys = [];
  712. this.inFocus = false;
  713. this.visible = false;
  714. this.jQueryel.blur();
  715. if (onHide) {
  716. this._bindVisionEvents(onHide)
  717. }
  718. },
  719. down: function (date) {
  720. this._changeView(date, 'down');
  721. },
  722. up: function (date) {
  723. this._changeView(date, 'up');
  724. },
  725. _bindVisionEvents: function (event) {
  726. this.jQuerydatepicker.off('transitionend.dp');
  727. event(this, false);
  728. this.jQuerydatepicker.one('transitionend.dp', event.bind(this, this, true))
  729. },
  730. _changeView: function (date, dir) {
  731. date = date || this.focused || this.date;
  732. var nextView = dir == 'up' ? this.viewIndex + 1 : this.viewIndex - 1;
  733. if (nextView > 2) nextView = 2;
  734. if (nextView < 0) nextView = 0;
  735. this.silent = true;
  736. this.date = new Date(date.getFullYear(), date.getMonth(), 1);
  737. this.silent = false;
  738. this.view = this.viewIndexes[nextView];
  739. },
  740. _handleHotKey: function (key) {
  741. var date = datepicker.getParsedDate(this._getFocusedDate()),
  742. focusedParsed,
  743. o = this.opts,
  744. newDate,
  745. totalDaysInNextMonth,
  746. monthChanged = false,
  747. yearChanged = false,
  748. decadeChanged = false,
  749. y = date.year,
  750. m = date.month,
  751. d = date.date;
  752. switch (key) {
  753. case 'ctrlRight':
  754. case 'ctrlUp':
  755. m += 1;
  756. monthChanged = true;
  757. break;
  758. case 'ctrlLeft':
  759. case 'ctrlDown':
  760. m -= 1;
  761. monthChanged = true;
  762. break;
  763. case 'shiftRight':
  764. case 'shiftUp':
  765. yearChanged = true;
  766. y += 1;
  767. break;
  768. case 'shiftLeft':
  769. case 'shiftDown':
  770. yearChanged = true;
  771. y -= 1;
  772. break;
  773. case 'altRight':
  774. case 'altUp':
  775. decadeChanged = true;
  776. y += 10;
  777. break;
  778. case 'altLeft':
  779. case 'altDown':
  780. decadeChanged = true;
  781. y -= 10;
  782. break;
  783. case 'ctrlShiftUp':
  784. this.up();
  785. break;
  786. }
  787. totalDaysInNextMonth = datepicker.getDaysCount(new Date(y,m));
  788. newDate = new Date(y,m,d);
  789. // If next month has less days than current, set date to total days in that month
  790. if (totalDaysInNextMonth < d) d = totalDaysInNextMonth;
  791. // Check if newDate is in valid range
  792. if (newDate.getTime() < this.minTime) {
  793. newDate = this.minDate;
  794. } else if (newDate.getTime() > this.maxTime) {
  795. newDate = this.maxDate;
  796. }
  797. this.focused = newDate;
  798. focusedParsed = datepicker.getParsedDate(newDate);
  799. if (monthChanged && o.onChangeMonth) {
  800. o.onChangeMonth(focusedParsed.month, focusedParsed.year)
  801. }
  802. if (yearChanged && o.onChangeYear) {
  803. o.onChangeYear(focusedParsed.year)
  804. }
  805. if (decadeChanged && o.onChangeDecade) {
  806. o.onChangeDecade(this.curDecade)
  807. }
  808. },
  809. _registerKey: function (key) {
  810. var exists = this.keys.some(function (curKey) {
  811. return curKey == key;
  812. });
  813. if (!exists) {
  814. this.keys.push(key)
  815. }
  816. },
  817. _unRegisterKey: function (key) {
  818. var index = this.keys.indexOf(key);
  819. this.keys.splice(index, 1);
  820. },
  821. _isHotKeyPressed: function () {
  822. var currentHotKey,
  823. found = false,
  824. _this = this,
  825. pressedKeys = this.keys.sort();
  826. for (var hotKey in hotKeys) {
  827. currentHotKey = hotKeys[hotKey];
  828. if (pressedKeys.length != currentHotKey.length) continue;
  829. if (currentHotKey.every(function (key, i) { return key == pressedKeys[i]})) {
  830. _this._trigger('hotKey', hotKey);
  831. found = true;
  832. }
  833. }
  834. return found;
  835. },
  836. _trigger: function (event, args) {
  837. this.jQueryel.trigger(event, args)
  838. },
  839. _focusNextCell: function (keyCode, type) {
  840. type = type || this.cellType;
  841. var date = datepicker.getParsedDate(this._getFocusedDate()),
  842. y = date.year,
  843. m = date.month,
  844. d = date.date;
  845. if (this._isHotKeyPressed()){
  846. return;
  847. }
  848. switch(keyCode) {
  849. case 37: // left
  850. type == 'day' ? (d -= 1) : '';
  851. type == 'month' ? (m -= 1) : '';
  852. type == 'year' ? (y -= 1) : '';
  853. break;
  854. case 38: // up
  855. type == 'day' ? (d -= 7) : '';
  856. type == 'month' ? (m -= 3) : '';
  857. type == 'year' ? (y -= 4) : '';
  858. break;
  859. case 39: // right
  860. type == 'day' ? (d += 1) : '';
  861. type == 'month' ? (m += 1) : '';
  862. type == 'year' ? (y += 1) : '';
  863. break;
  864. case 40: // down
  865. type == 'day' ? (d += 7) : '';
  866. type == 'month' ? (m += 3) : '';
  867. type == 'year' ? (y += 4) : '';
  868. break;
  869. }
  870. var nd = new Date(y,m,d);
  871. if (nd.getTime() < this.minTime) {
  872. nd = this.minDate;
  873. } else if (nd.getTime() > this.maxTime) {
  874. nd = this.maxDate;
  875. }
  876. this.focused = nd;
  877. },
  878. _getFocusedDate: function () {
  879. var focused = this.focused || this.selectedDates[this.selectedDates.length - 1],
  880. d = this.parsedDate;
  881. if (!focused) {
  882. switch (this.view) {
  883. case 'days':
  884. focused = new Date(d.year, d.month, new Date().getDate());
  885. break;
  886. case 'months':
  887. focused = new Date(d.year, d.month, 1);
  888. break;
  889. case 'years':
  890. focused = new Date(d.year, 0, 1);
  891. break;
  892. }
  893. }
  894. return focused;
  895. },
  896. _getCell: function (date, type) {
  897. type = type || this.cellType;
  898. var d = datepicker.getParsedDate(date),
  899. selector = '.datepicker--cell[data-year="' + d.year + '"]',
  900. jQuerycell;
  901. switch (type) {
  902. case 'month':
  903. selector = '[data-month="' + d.month + '"]';
  904. break;
  905. case 'day':
  906. selector += '[data-month="' + d.month + '"][data-date="' + d.date + '"]';
  907. break;
  908. }
  909. jQuerycell = this.views[this.currentView].jQueryel.find(selector);
  910. return jQuerycell.length ? jQuerycell : jQuery('');
  911. },
  912. destroy: function () {
  913. var _this = this;
  914. _this.jQueryel
  915. .off('.adp')
  916. .data('datepicker', '');
  917. _this.selectedDates = [];
  918. _this.focused = '';
  919. _this.views = {};
  920. _this.keys = [];
  921. _this.minRange = '';
  922. _this.maxRange = '';
  923. if (_this.opts.inline || !_this.elIsInput) {
  924. _this.jQuerydatepicker.closest('.datepicker-inline').remove();
  925. } else {
  926. _this.jQuerydatepicker.remove();
  927. }
  928. },
  929. _handleAlreadySelectedDates: function (alreadySelected, selectedDate) {
  930. if (this.opts.range) {
  931. if (!this.opts.toggleSelected) {
  932. // Add possibility to select same date when range is true
  933. if (this.selectedDates.length != 2) {
  934. this._trigger('clickCell', selectedDate);
  935. }
  936. } else {
  937. this.removeDate(selectedDate);
  938. }
  939. } else if (this.opts.toggleSelected){
  940. this.removeDate(selectedDate);
  941. }
  942. // Change last selected date to be able to change time when clicking on this cell
  943. if (!this.opts.toggleSelected) {
  944. this.lastSelectedDate = alreadySelected;
  945. if (this.opts.timepicker) {
  946. this.timepicker._setTime(alreadySelected);
  947. this.timepicker.update();
  948. }
  949. }
  950. },
  951. _onShowEvent: function (e) {
  952. if (!this.visible) {
  953. this.show();
  954. }
  955. },
  956. _onBlur: function () {
  957. if (!this.inFocus && this.visible) {
  958. this.hide();
  959. }
  960. },
  961. _onMouseDownDatepicker: function (e) {
  962. this.inFocus = true;
  963. },
  964. _onMouseUpDatepicker: function (e) {
  965. this.inFocus = false;
  966. e.originalEvent.inFocus = true;
  967. if (!e.originalEvent.timepickerFocus) this.jQueryel.focus();
  968. },
  969. _onKeyUpGeneral: function (e) {
  970. var val = this.jQueryel.val();
  971. if (!val) {
  972. this.clear();
  973. }
  974. },
  975. _onResize: function () {
  976. if (this.visible) {
  977. this.setPosition();
  978. }
  979. },
  980. _onMouseUpBody: function (e) {
  981. if (e.originalEvent.inFocus) return;
  982. if (this.visible && !this.inFocus) {
  983. this.hide();
  984. }
  985. },
  986. _onMouseUpEl: function (e) {
  987. e.originalEvent.inFocus = true;
  988. setTimeout(this._onKeyUpGeneral.bind(this),4);
  989. },
  990. _onKeyDown: function (e) {
  991. var code = e.which;
  992. this._registerKey(code);
  993. // Arrows
  994. if (code >= 37 && code <= 40) {
  995. e.preventDefault();
  996. this._focusNextCell(code);
  997. }
  998. // Enter
  999. if (code == 13) {
  1000. if (this.focused) {
  1001. if (this._getCell(this.focused).hasClass('-disabled-')) return;
  1002. if (this.view != this.opts.minView) {
  1003. this.down()
  1004. } else {
  1005. var alreadySelected = this._isSelected(this.focused, this.cellType);
  1006. if (!alreadySelected) {
  1007. if (this.timepicker) {
  1008. this.focused.setHours(this.timepicker.hours);
  1009. this.focused.setMinutes(this.timepicker.minutes);
  1010. }
  1011. this.selectDate(this.focused);
  1012. return;
  1013. }
  1014. this._handleAlreadySelectedDates(alreadySelected, this.focused)
  1015. }
  1016. }
  1017. }
  1018. // Esc
  1019. if (code == 27) {
  1020. this.hide();
  1021. }
  1022. },
  1023. _onKeyUp: function (e) {
  1024. var code = e.which;
  1025. this._unRegisterKey(code);
  1026. },
  1027. _onHotKey: function (e, hotKey) {
  1028. this._handleHotKey(hotKey);
  1029. },
  1030. _onMouseEnterCell: function (e) {
  1031. var jQuerycell = jQuery(e.target).closest('.datepicker--cell'),
  1032. date = this._getDateFromCell(jQuerycell);
  1033. // Prevent from unnecessary rendering and setting new currentDate
  1034. this.silent = true;
  1035. if (this.focused) {
  1036. this.focused = ''
  1037. }
  1038. jQuerycell.addClass('-focus-');
  1039. this.focused = date;
  1040. this.silent = false;
  1041. if (this.opts.range && this.selectedDates.length == 1) {
  1042. this.minRange = this.selectedDates[0];
  1043. this.maxRange = '';
  1044. if (datepicker.less(this.minRange, this.focused)) {
  1045. this.maxRange = this.minRange;
  1046. this.minRange = '';
  1047. }
  1048. this.views[this.currentView]._update();
  1049. }
  1050. },
  1051. _onMouseLeaveCell: function (e) {
  1052. var jQuerycell = jQuery(e.target).closest('.datepicker--cell');
  1053. jQuerycell.removeClass('-focus-');
  1054. this.silent = true;
  1055. this.focused = '';
  1056. this.silent = false;
  1057. },
  1058. _onTimeChange: function (e, h, m) {
  1059. var date = new Date(),
  1060. selectedDates = this.selectedDates,
  1061. selected = false;
  1062. if (selectedDates.length) {
  1063. selected = true;
  1064. date = this.lastSelectedDate;
  1065. }
  1066. date.setHours(h);
  1067. date.setMinutes(m);
  1068. if (!selected && !this._getCell(date).hasClass('-disabled-')) {
  1069. this.selectDate(date);
  1070. } else {
  1071. this._setInputValue();
  1072. if (this.opts.onSelect) {
  1073. this._triggerOnChange();
  1074. }
  1075. }
  1076. },
  1077. _onClickCell: function (e, date) {
  1078. if (this.timepicker) {
  1079. date.setHours(this.timepicker.hours);
  1080. date.setMinutes(this.timepicker.minutes);
  1081. }
  1082. this.selectDate(date);
  1083. },
  1084. set focused(val) {
  1085. if (!val && this.focused) {
  1086. var jQuerycell = this._getCell(this.focused);
  1087. if (jQuerycell.length) {
  1088. jQuerycell.removeClass('-focus-')
  1089. }
  1090. }
  1091. this._focused = val;
  1092. if (this.opts.range && this.selectedDates.length == 1) {
  1093. this.minRange = this.selectedDates[0];
  1094. this.maxRange = '';
  1095. if (datepicker.less(this.minRange, this._focused)) {
  1096. this.maxRange = this.minRange;
  1097. this.minRange = '';
  1098. }
  1099. }
  1100. if (this.silent) return;
  1101. this.date = val;
  1102. },
  1103. get focused() {
  1104. return this._focused;
  1105. },
  1106. get parsedDate() {
  1107. return datepicker.getParsedDate(this.date);
  1108. },
  1109. set date (val) {
  1110. if (!(val instanceof Date)) return;
  1111. this.currentDate = val;
  1112. if (this.inited && !this.silent) {
  1113. this.views[this.view]._render();
  1114. this.nav._render();
  1115. if (this.visible && this.elIsInput) {
  1116. this.setPosition();
  1117. }
  1118. }
  1119. return val;
  1120. },
  1121. get date () {
  1122. return this.currentDate
  1123. },
  1124. set view (val) {
  1125. this.viewIndex = this.viewIndexes.indexOf(val);
  1126. if (this.viewIndex < 0) {
  1127. return;
  1128. }
  1129. this.prevView = this.currentView;
  1130. this.currentView = val;
  1131. if (this.inited) {
  1132. if (!this.views[val]) {
  1133. this.views[val] = new jQuery.fn.datepicker.Body(this, val, this.opts)
  1134. } else {
  1135. this.views[val]._render();
  1136. }
  1137. this.views[this.prevView].hide();
  1138. this.views[val].show();
  1139. this.nav._render();
  1140. if (this.opts.onChangeView) {
  1141. this.opts.onChangeView(val)
  1142. }
  1143. if (this.elIsInput && this.visible) this.setPosition();
  1144. }
  1145. return val
  1146. },
  1147. get view() {
  1148. return this.currentView;
  1149. },
  1150. get cellType() {
  1151. return this.view.substring(0, this.view.length - 1)
  1152. },
  1153. get minTime() {
  1154. var min = datepicker.getParsedDate(this.minDate);
  1155. return new Date(min.year, min.month, min.date).getTime()
  1156. },
  1157. get maxTime() {
  1158. var max = datepicker.getParsedDate(this.maxDate);
  1159. return new Date(max.year, max.month, max.date).getTime()
  1160. },
  1161. get curDecade() {
  1162. return datepicker.getDecade(this.date)
  1163. }
  1164. };
  1165. // Utils
  1166. // -------------------------------------------------
  1167. datepicker.getDaysCount = function (date) {
  1168. return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
  1169. };
  1170. datepicker.getParsedDate = function (date) {
  1171. return {
  1172. year: date.getFullYear(),
  1173. month: date.getMonth(),
  1174. fullMonth: (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1, // One based
  1175. date: date.getDate(),
  1176. fullDate: date.getDate() < 10 ? '0' + date.getDate() : date.getDate(),
  1177. day: date.getDay(),
  1178. hours: date.getHours(),
  1179. fullHours: date.getHours() < 10 ? '0' + date.getHours() : date.getHours() ,
  1180. minutes: date.getMinutes(),
  1181. fullMinutes: date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  1182. }
  1183. };
  1184. datepicker.getDecade = function (date) {
  1185. var firstYear = Math.floor(date.getFullYear() / 10) * 10;
  1186. return [firstYear, firstYear + 9];
  1187. };
  1188. datepicker.template = function (str, data) {
  1189. return str.replace(/#\{([\w]+)\}/g, function (source, match) {
  1190. if (data[match] || data[match] === 0) {
  1191. return data[match]
  1192. }
  1193. });
  1194. };
  1195. datepicker.isSame = function (date1, date2, type) {
  1196. if (!date1 || !date2) return false;
  1197. var d1 = datepicker.getParsedDate(date1),
  1198. d2 = datepicker.getParsedDate(date2),
  1199. _type = type ? type : 'day',
  1200. conditions = {
  1201. day: d1.date == d2.date && d1.month == d2.month && d1.year == d2.year,
  1202. month: d1.month == d2.month && d1.year == d2.year,
  1203. year: d1.year == d2.year
  1204. };
  1205. return conditions[_type];
  1206. };
  1207. datepicker.less = function (dateCompareTo, date, type) {
  1208. if (!dateCompareTo || !date) return false;
  1209. return date.getTime() < dateCompareTo.getTime();
  1210. };
  1211. datepicker.bigger = function (dateCompareTo, date, type) {
  1212. if (!dateCompareTo || !date) return false;
  1213. return date.getTime() > dateCompareTo.getTime();
  1214. };
  1215. datepicker.getLeadingZeroNum = function (num) {
  1216. return parseInt(num) < 10 ? '0' + num : num;
  1217. };
  1218. /**
  1219. * Returns copy of date with hours and minutes equals to 0
  1220. * @param date {Date}
  1221. */
  1222. datepicker.resetTime = function (date) {
  1223. if (typeof date != 'object') return;
  1224. date = datepicker.getParsedDate(date);
  1225. return new Date(date.year, date.month, date.date)
  1226. };
  1227. jQuery.fn.datepicker = function ( options ) {
  1228. return this.each(function () {
  1229. if (!jQuery.data(this, pluginName)) {
  1230. jQuery.data(this, pluginName,
  1231. new Datepicker( this, options ));
  1232. } else {
  1233. var _this = jQuery.data(this, pluginName);
  1234. _this.opts = jQuery.extend(true, _this.opts, options);
  1235. _this.update();
  1236. }
  1237. });
  1238. };
  1239. jQuery.fn.datepicker.Constructor = Datepicker;
  1240. jQuery.fn.datepicker.language = {
  1241. ru: {
  1242. days: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
  1243. daysShort: ['Вос','Пон','Вто','Сре','Чет','Пят','Суб'],
  1244. daysMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
  1245. months: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
  1246. monthsShort: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'],
  1247. today: 'Сегодня',
  1248. clear: 'Очистить',
  1249. dateFormat: 'dd.mm.yyyy',
  1250. timeFormat: 'hh:ii',
  1251. firstDay: 1
  1252. }
  1253. };
  1254. jQuery(function () {
  1255. jQuery(autoInitSelector).datepicker();
  1256. })
  1257. })();
  1258. ;(function () {
  1259. var templates = {
  1260. days:'' +
  1261. '<div class="datepicker--days datepicker--body">' +
  1262. '<div class="datepicker--days-names"></div>' +
  1263. '<div class="datepicker--cells datepicker--cells-days"></div>' +
  1264. '</div>',
  1265. months: '' +
  1266. '<div class="datepicker--months datepicker--body">' +
  1267. '<div class="datepicker--cells datepicker--cells-months"></div>' +
  1268. '</div>',
  1269. years: '' +
  1270. '<div class="datepicker--years datepicker--body">' +
  1271. '<div class="datepicker--cells datepicker--cells-years"></div>' +
  1272. '</div>'
  1273. },
  1274. datepicker = jQuery.fn.datepicker,
  1275. dp = datepicker.Constructor;
  1276. datepicker.Body = function (d, type, opts) {
  1277. this.d = d;
  1278. this.type = type;
  1279. this.opts = opts;
  1280. this.jQueryel = jQuery('');
  1281. if (this.opts.onlyTimepicker) return;
  1282. this.init();
  1283. };
  1284. datepicker.Body.prototype = {
  1285. init: function () {
  1286. this._buildBaseHtml();
  1287. this._render();
  1288. this._bindEvents();
  1289. },
  1290. _bindEvents: function () {
  1291. this.jQueryel.on('click', '.datepicker--cell', jQuery.proxy(this._onClickCell, this));
  1292. },
  1293. _buildBaseHtml: function () {
  1294. this.jQueryel = jQuery(templates[this.type]).appendTo(this.d.jQuerycontent);
  1295. this.jQuerynames = jQuery('.datepicker--days-names', this.jQueryel);
  1296. this.jQuerycells = jQuery('.datepicker--cells', this.jQueryel);
  1297. },
  1298. _getDayNamesHtml: function (firstDay, curDay, html, i) {
  1299. curDay = curDay != undefined ? curDay : firstDay;
  1300. html = html ? html : '';
  1301. i = i != undefined ? i : 0;
  1302. if (i > 7) return html;
  1303. if (curDay == 7) return this._getDayNamesHtml(firstDay, 0, html, ++i);
  1304. html += '<div class="datepicker--day-name' + (this.d.isWeekend(curDay) ? " -weekend-" : "") + '">' + this.d.loc.daysMin[curDay] + '</div>';
  1305. return this._getDayNamesHtml(firstDay, ++curDay, html, ++i);
  1306. },
  1307. _getCellContents: function (date, type) {
  1308. var classes = "datepicker--cell datepicker--cell-" + type,
  1309. currentDate = new Date(),
  1310. parent = this.d,
  1311. minRange = dp.resetTime(parent.minRange),
  1312. maxRange = dp.resetTime(parent.maxRange),
  1313. opts = parent.opts,
  1314. d = dp.getParsedDate(date),
  1315. render = {},
  1316. html = d.date;
  1317. switch (type) {
  1318. case 'day':
  1319. if (parent.isWeekend(d.day)) classes += " -weekend-";
  1320. if (d.month != this.d.parsedDate.month) {
  1321. classes += " -other-month-";
  1322. if (!opts.selectOtherMonths) {
  1323. classes += " -disabled-";
  1324. }
  1325. if (!opts.showOtherMonths) html = '';
  1326. }
  1327. break;
  1328. case 'month':
  1329. html = parent.loc[parent.opts.monthsField][d.month];
  1330. break;
  1331. case 'year':
  1332. var decade = parent.curDecade;
  1333. html = d.year;
  1334. if (d.year < decade[0] || d.year > decade[1]) {
  1335. classes += ' -other-decade-';
  1336. if (!opts.selectOtherYears) {
  1337. classes += " -disabled-";
  1338. }
  1339. if (!opts.showOtherYears) html = '';
  1340. }
  1341. break;
  1342. }
  1343. if (opts.onRenderCell) {
  1344. render = opts.onRenderCell(date, type) || {};
  1345. html = render.html ? render.html : html;
  1346. classes += render.classes ? ' ' + render.classes : '';
  1347. }
  1348. if (opts.range) {
  1349. if (dp.isSame(minRange, date, type)) classes += ' -range-from-';
  1350. if (dp.isSame(maxRange, date, type)) classes += ' -range-to-';
  1351. if (parent.selectedDates.length == 1 && parent.focused) {
  1352. if (
  1353. (dp.bigger(minRange, date) && dp.less(parent.focused, date)) ||
  1354. (dp.less(maxRange, date) && dp.bigger(parent.focused, date)))
  1355. {
  1356. classes += ' -in-range-'
  1357. }
  1358. if (dp.less(maxRange, date) && dp.isSame(parent.focused, date)) {
  1359. classes += ' -range-from-'
  1360. }
  1361. if (dp.bigger(minRange, date) && dp.isSame(parent.focused, date)) {
  1362. classes += ' -range-to-'
  1363. }
  1364. } else if (parent.selectedDates.length == 2) {
  1365. if (dp.bigger(minRange, date) && dp.less(maxRange, date)) {
  1366. classes += ' -in-range-'
  1367. }
  1368. }
  1369. }
  1370. if (dp.isSame(currentDate, date, type)) classes += ' -current-';
  1371. if (parent.focused && dp.isSame(date, parent.focused, type)) classes += ' -focus-';
  1372. if (parent._isSelected(date, type)) classes += ' -selected-';
  1373. if (!parent._isInRange(date, type) || render.disabled) classes += ' -disabled-';
  1374. return {
  1375. html: html,
  1376. classes: classes
  1377. }
  1378. },
  1379. /**
  1380. * Calculates days number to render. Generates days html and returns it.
  1381. * @param {object} date - Date object
  1382. * @returns {string}
  1383. * @private
  1384. */
  1385. _getDaysHtml: function (date) {
  1386. var totalMonthDays = dp.getDaysCount(date),
  1387. firstMonthDay = new Date(date.getFullYear(), date.getMonth(), 1).getDay(),
  1388. lastMonthDay = new Date(date.getFullYear(), date.getMonth(), totalMonthDays).getDay(),
  1389. daysFromPevMonth = firstMonthDay - this.d.loc.firstDay,
  1390. daysFromNextMonth = 6 - lastMonthDay + this.d.loc.firstDay;
  1391. daysFromPevMonth = daysFromPevMonth < 0 ? daysFromPevMonth + 7 : daysFromPevMonth;
  1392. daysFromNextMonth = daysFromNextMonth > 6 ? daysFromNextMonth - 7 : daysFromNextMonth;
  1393. var startDayIndex = -daysFromPevMonth + 1,
  1394. m, y,
  1395. html = '';
  1396. for (var i = startDayIndex, max = totalMonthDays + daysFromNextMonth; i <= max; i++) {
  1397. y = date.getFullYear();
  1398. m = date.getMonth();
  1399. html += this._getDayHtml(new Date(y, m, i))
  1400. }
  1401. return html;
  1402. },
  1403. _getDayHtml: function (date) {
  1404. var content = this._getCellContents(date, 'day');
  1405. return '<div class="' + content.classes + '" ' +
  1406. 'data-date="' + date.getDate() + '" ' +
  1407. 'data-month="' + date.getMonth() + '" ' +
  1408. 'data-year="' + date.getFullYear() + '">' + content.html + '</div>';
  1409. },
  1410. /**
  1411. * Generates months html
  1412. * @param {object} date - date instance
  1413. * @returns {string}
  1414. * @private
  1415. */
  1416. _getMonthsHtml: function (date) {
  1417. var html = '',
  1418. d = dp.getParsedDate(date),
  1419. i = 0;
  1420. while(i < 12) {
  1421. html += this._getMonthHtml(new Date(d.year, i));
  1422. i++
  1423. }
  1424. return html;
  1425. },
  1426. _getMonthHtml: function (date) {
  1427. var content = this._getCellContents(date, 'month');
  1428. return '<div class="' + content.classes + '" data-month="' + date.getMonth() + '">' + content.html + '</div>'
  1429. },
  1430. _getYearsHtml: function (date) {
  1431. var d = dp.getParsedDate(date),
  1432. decade = dp.getDecade(date),
  1433. firstYear = decade[0] - 1,
  1434. html = '',
  1435. i = firstYear;
  1436. for (i; i <= decade[1] + 1; i++) {
  1437. html += this._getYearHtml(new Date(i , 0));
  1438. }
  1439. return html;
  1440. },
  1441. _getYearHtml: function (date) {
  1442. var content = this._getCellContents(date, 'year');
  1443. return '<div class="' + content.classes + '" data-year="' + date.getFullYear() + '">' + content.html + '</div>'
  1444. },
  1445. _renderTypes: {
  1446. days: function () {
  1447. var dayNames = this._getDayNamesHtml(this.d.loc.firstDay),
  1448. days = this._getDaysHtml(this.d.currentDate);
  1449. this.jQuerycells.html(days);
  1450. this.jQuerynames.html(dayNames)
  1451. },
  1452. months: function () {
  1453. var html = this._getMonthsHtml(this.d.currentDate);
  1454. this.jQuerycells.html(html)
  1455. },
  1456. years: function () {
  1457. var html = this._getYearsHtml(this.d.currentDate);
  1458. this.jQuerycells.html(html)
  1459. }
  1460. },
  1461. _render: function () {
  1462. if (this.opts.onlyTimepicker) return;
  1463. this._renderTypes[this.type].bind(this)();
  1464. },
  1465. _update: function () {
  1466. var jQuerycells = jQuery('.datepicker--cell', this.jQuerycells),
  1467. _this = this,
  1468. classes,
  1469. jQuerycell,
  1470. date;
  1471. jQuerycells.each(function (cell, i) {
  1472. jQuerycell = jQuery(this);
  1473. date = _this.d._getDateFromCell(jQuery(this));
  1474. classes = _this._getCellContents(date, _this.d.cellType);
  1475. jQuerycell.attr('class',classes.classes)
  1476. });
  1477. },
  1478. show: function () {
  1479. if (this.opts.onlyTimepicker) return;
  1480. this.jQueryel.addClass('active');
  1481. this.acitve = true;
  1482. },
  1483. hide: function () {
  1484. this.jQueryel.removeClass('active');
  1485. this.active = false;
  1486. },
  1487. // Events
  1488. // -------------------------------------------------
  1489. _handleClick: function (el) {
  1490. var date = el.data('date') || 1,
  1491. month = el.data('month') || 0,
  1492. year = el.data('year') || this.d.parsedDate.year,
  1493. dp = this.d;
  1494. // Change view if min view does not reach yet
  1495. if (dp.view != this.opts.minView) {
  1496. dp.down(new Date(year, month, date));
  1497. return;
  1498. }
  1499. // Select date if min view is reached
  1500. var selectedDate = new Date(year, month, date),
  1501. alreadySelected = this.d._isSelected(selectedDate, this.d.cellType);
  1502. if (!alreadySelected) {
  1503. dp._trigger('clickCell', selectedDate);
  1504. return;
  1505. }
  1506. dp._handleAlreadySelectedDates.bind(dp, alreadySelected, selectedDate)();
  1507. },
  1508. _onClickCell: function (e) {
  1509. var jQueryel = jQuery(e.target).closest('.datepicker--cell');
  1510. if (jQueryel.hasClass('-disabled-')) return;
  1511. this._handleClick.bind(this)(jQueryel);
  1512. }
  1513. };
  1514. })();
  1515. ;(function () {
  1516. var template = '' +
  1517. '<div class="datepicker--nav-action" data-action="prev">#{prevHtml}</div>' +
  1518. '<div class="datepicker--nav-title">#{title}</div>' +
  1519. '<div class="datepicker--nav-action" data-action="next">#{nextHtml}</div>',
  1520. buttonsContainerTemplate = '<div class="datepicker--buttons"></div>',
  1521. button = '<span class="datepicker--button" data-action="#{action}">#{label}</span>',
  1522. datepicker = jQuery.fn.datepicker,
  1523. dp = datepicker.Constructor;
  1524. datepicker.Navigation = function (d, opts) {
  1525. this.d = d;
  1526. this.opts = opts;
  1527. this.jQuerybuttonsContainer = '';
  1528. this.init();
  1529. };
  1530. datepicker.Navigation.prototype = {
  1531. init: function () {
  1532. this._buildBaseHtml();
  1533. this._bindEvents();
  1534. },
  1535. _bindEvents: function () {
  1536. this.d.jQuerynav.on('click', '.datepicker--nav-action', jQuery.proxy(this._onClickNavButton, this));
  1537. this.d.jQuerynav.on('click', '.datepicker--nav-title', jQuery.proxy(this._onClickNavTitle, this));
  1538. this.d.jQuerydatepicker.on('click', '.datepicker--button', jQuery.proxy(this._onClickNavButton, this));
  1539. },
  1540. _buildBaseHtml: function () {
  1541. if (!this.opts.onlyTimepicker) {
  1542. this._render();
  1543. }
  1544. this._addButtonsIfNeed();
  1545. },
  1546. _addButtonsIfNeed: function () {
  1547. if (this.opts.todayButton) {
  1548. this._addButton('today')
  1549. }
  1550. if (this.opts.clearButton) {
  1551. this._addButton('clear')
  1552. }
  1553. },
  1554. _render: function () {
  1555. var title = this._getTitle(this.d.currentDate),
  1556. html = dp.template(template, jQuery.extend({title: title}, this.opts));
  1557. this.d.jQuerynav.html(html);
  1558. if (this.d.view == 'years') {
  1559. jQuery('.datepicker--nav-title', this.d.jQuerynav).addClass('-disabled-');
  1560. }
  1561. this.setNavStatus();
  1562. },
  1563. _getTitle: function (date) {
  1564. return this.d.formatDate(this.opts.navTitles[this.d.view], date)
  1565. },
  1566. _addButton: function (type) {
  1567. if (!this.jQuerybuttonsContainer.length) {
  1568. this._addButtonsContainer();
  1569. }
  1570. var data = {
  1571. action: type,
  1572. label: this.d.loc[type]
  1573. },
  1574. html = dp.template(button, data);
  1575. if (jQuery('[data-action=' + type + ']', this.jQuerybuttonsContainer).length) return;
  1576. this.jQuerybuttonsContainer.append(html);
  1577. },
  1578. _addButtonsContainer: function () {
  1579. this.d.jQuerydatepicker.append(buttonsContainerTemplate);
  1580. this.jQuerybuttonsContainer = jQuery('.datepicker--buttons', this.d.jQuerydatepicker);
  1581. },
  1582. setNavStatus: function () {
  1583. if (!(this.opts.minDate || this.opts.maxDate) || !this.opts.disableNavWhenOutOfRange) return;
  1584. var date = this.d.parsedDate,
  1585. m = date.month,
  1586. y = date.year,
  1587. d = date.date;
  1588. switch (this.d.view) {
  1589. case 'days':
  1590. if (!this.d._isInRange(new Date(y, m-1, 1), 'month')) {
  1591. this._disableNav('prev')
  1592. }
  1593. if (!this.d._isInRange(new Date(y, m+1, 1), 'month')) {
  1594. this._disableNav('next')
  1595. }
  1596. break;
  1597. case 'months':
  1598. if (!this.d._isInRange(new Date(y-1, m, d), 'year')) {
  1599. this._disableNav('prev')
  1600. }
  1601. if (!this.d._isInRange(new Date(y+1, m, d), 'year')) {
  1602. this._disableNav('next')
  1603. }
  1604. break;
  1605. case 'years':
  1606. var decade = dp.getDecade(this.d.date);
  1607. if (!this.d._isInRange(new Date(decade[0] - 1, 0, 1), 'year')) {
  1608. this._disableNav('prev')
  1609. }
  1610. if (!this.d._isInRange(new Date(decade[1] + 1, 0, 1), 'year')) {
  1611. this._disableNav('next')
  1612. }
  1613. break;
  1614. }
  1615. },
  1616. _disableNav: function (nav) {
  1617. jQuery('[data-action="' + nav + '"]', this.d.jQuerynav).addClass('-disabled-')
  1618. },
  1619. _activateNav: function (nav) {
  1620. jQuery('[data-action="' + nav + '"]', this.d.jQuerynav).removeClass('-disabled-')
  1621. },
  1622. _onClickNavButton: function (e) {
  1623. var jQueryel = jQuery(e.target).closest('[data-action]'),
  1624. action = jQueryel.data('action');
  1625. this.d[action]();
  1626. },
  1627. _onClickNavTitle: function (e) {
  1628. if (jQuery(e.target).hasClass('-disabled-')) return;
  1629. if (this.d.view == 'days') {
  1630. return this.d.view = 'months'
  1631. }
  1632. this.d.view = 'years';
  1633. }
  1634. }
  1635. })();
  1636. ;(function () {
  1637. var template = '<div class="datepicker--time">' +
  1638. '<div class="datepicker--time-current">' +
  1639. ' <span class="datepicker--time-current-hours">#{hourVisible}</span>' +
  1640. ' <span class="datepicker--time-current-colon">:</span>' +
  1641. ' <span class="datepicker--time-current-minutes">#{minValue}</span>' +
  1642. '</div>' +
  1643. '<div class="datepicker--time-sliders">' +
  1644. ' <div class="datepicker--time-row">' +
  1645. ' <input type="range" name="hours" value="#{hourValue}" min="#{hourMin}" max="#{hourMax}" step="#{hourStep}"/>' +
  1646. ' </div>' +
  1647. ' <div class="datepicker--time-row">' +
  1648. ' <input type="range" name="minutes" value="#{minValue}" min="#{minMin}" max="#{minMax}" step="#{minStep}"/>' +
  1649. ' </div>' +
  1650. '</div>' +
  1651. '</div>',
  1652. datepicker = jQuery.fn.datepicker,
  1653. dp = datepicker.Constructor;
  1654. datepicker.Timepicker = function (inst, opts) {
  1655. this.d = inst;
  1656. this.opts = opts;
  1657. this.init();
  1658. };
  1659. datepicker.Timepicker.prototype = {
  1660. init: function () {
  1661. var input = 'input';
  1662. this._setTime(this.d.date);
  1663. this._buildHTML();
  1664. if (navigator.userAgent.match(/trident/gi)) {
  1665. input = 'change';
  1666. }
  1667. this.d.jQueryel.on('selectDate', this._onSelectDate.bind(this));
  1668. this.jQueryranges.on(input, this._onChangeRange.bind(this));
  1669. this.jQueryranges.on('mouseup', this._onMouseUpRange.bind(this));
  1670. this.jQueryranges.on('mousemove focus ', this._onMouseEnterRange.bind(this));
  1671. this.jQueryranges.on('mouseout blur', this._onMouseOutRange.bind(this));
  1672. },
  1673. _setTime: function (date) {
  1674. var _date = dp.getParsedDate(date);
  1675. this._handleDate(date);
  1676. this.hours = _date.hours < this.minHours ? this.minHours : _date.hours;
  1677. this.minutes = _date.minutes < this.minMinutes ? this.minMinutes : _date.minutes;
  1678. },
  1679. /**
  1680. * Sets minHours and minMinutes from date (usually it's a minDate)
  1681. * Also changes minMinutes if current hours are bigger then @date hours
  1682. * @param date {Date}
  1683. * @private
  1684. */
  1685. _setMinTimeFromDate: function (date) {
  1686. this.minHours = date.getHours();
  1687. this.minMinutes = date.getMinutes();
  1688. // If, for example, min hours are 10, and current hours are 12,
  1689. // update minMinutes to default value, to be able to choose whole range of values
  1690. if (this.d.lastSelectedDate) {
  1691. if (this.d.lastSelectedDate.getHours() > date.getHours()) {
  1692. this.minMinutes = this.opts.minMinutes;
  1693. }
  1694. }
  1695. },
  1696. _setMaxTimeFromDate: function (date) {
  1697. this.maxHours = date.getHours();
  1698. this.maxMinutes = date.getMinutes();
  1699. if (this.d.lastSelectedDate) {
  1700. if (this.d.lastSelectedDate.getHours() < date.getHours()) {
  1701. this.maxMinutes = this.opts.maxMinutes;
  1702. }
  1703. }
  1704. },
  1705. _setDefaultMinMaxTime: function () {
  1706. var maxHours = 23,
  1707. maxMinutes = 59,
  1708. opts = this.opts;
  1709. this.minHours = opts.minHours < 0 || opts.minHours > maxHours ? 0 : opts.minHours;
  1710. this.minMinutes = opts.minMinutes < 0 || opts.minMinutes > maxMinutes ? 0 : opts.minMinutes;
  1711. this.maxHours = opts.maxHours < 0 || opts.maxHours > maxHours ? maxHours : opts.maxHours;
  1712. this.maxMinutes = opts.maxMinutes < 0 || opts.maxMinutes > maxMinutes ? maxMinutes : opts.maxMinutes;
  1713. },
  1714. /**
  1715. * Looks for min/max hours/minutes and if current values
  1716. * are out of range sets valid values.
  1717. * @private
  1718. */
  1719. _validateHoursMinutes: function (date) {
  1720. if (this.hours < this.minHours) {
  1721. this.hours = this.minHours;
  1722. } else if (this.hours > this.maxHours) {
  1723. this.hours = this.maxHours;
  1724. }
  1725. if (this.minutes < this.minMinutes) {
  1726. this.minutes = this.minMinutes;
  1727. } else if (this.minutes > this.maxMinutes) {
  1728. this.minutes = this.maxMinutes;
  1729. }
  1730. },
  1731. _buildHTML: function () {
  1732. var lz = dp.getLeadingZeroNum,
  1733. data = {
  1734. hourMin: this.minHours,
  1735. hourMax: lz(this.maxHours),
  1736. hourStep: this.opts.hoursStep,
  1737. hourValue: this.hours,
  1738. hourVisible: lz(this.displayHours),
  1739. minMin: this.minMinutes,
  1740. minMax: lz(this.maxMinutes),
  1741. minStep: this.opts.minutesStep,
  1742. minValue: lz(this.minutes)
  1743. },
  1744. _template = dp.template(template, data);
  1745. this.jQuerytimepicker = jQuery(_template).appendTo(this.d.jQuerydatepicker);
  1746. this.jQueryranges = jQuery('[type="range"]', this.jQuerytimepicker);
  1747. this.jQueryhours = jQuery('[name="hours"]', this.jQuerytimepicker);
  1748. this.jQueryminutes = jQuery('[name="minutes"]', this.jQuerytimepicker);
  1749. this.jQueryhoursText = jQuery('.datepicker--time-current-hours', this.jQuerytimepicker);
  1750. this.jQueryminutesText = jQuery('.datepicker--time-current-minutes', this.jQuerytimepicker);
  1751. if (this.d.ampm) {
  1752. this.jQueryampm = jQuery('<span class="datepicker--time-current-ampm">')
  1753. .appendTo(jQuery('.datepicker--time-current', this.jQuerytimepicker))
  1754. .html(this.dayPeriod);
  1755. this.jQuerytimepicker.addClass('-am-pm-');
  1756. }
  1757. },
  1758. _updateCurrentTime: function () {
  1759. var h = dp.getLeadingZeroNum(this.displayHours),
  1760. m = dp.getLeadingZeroNum(this.minutes);
  1761. this.jQueryhoursText.html(h);
  1762. this.jQueryminutesText.html(m);
  1763. if (this.d.ampm) {
  1764. this.jQueryampm.html(this.dayPeriod);
  1765. }
  1766. },
  1767. _updateRanges: function () {
  1768. this.jQueryhours.attr({
  1769. min: this.minHours,
  1770. max: this.maxHours
  1771. }).val(this.hours);
  1772. this.jQueryminutes.attr({
  1773. min: this.minMinutes,
  1774. max: this.maxMinutes
  1775. }).val(this.minutes)
  1776. },
  1777. /**
  1778. * Sets minHours, minMinutes etc. from date. If date is not passed, than sets
  1779. * values from options
  1780. * @param [date] {object} - Date object, to get values from
  1781. * @private
  1782. */
  1783. _handleDate: function (date) {
  1784. this._setDefaultMinMaxTime();
  1785. if (date) {
  1786. if (dp.isSame(date, this.d.opts.minDate)) {
  1787. this._setMinTimeFromDate(this.d.opts.minDate);
  1788. } else if (dp.isSame(date, this.d.opts.maxDate)) {
  1789. this._setMaxTimeFromDate(this.d.opts.maxDate);
  1790. }
  1791. }
  1792. this._validateHoursMinutes(date);
  1793. },
  1794. update: function () {
  1795. this._updateRanges();
  1796. this._updateCurrentTime();
  1797. },
  1798. /**
  1799. * Calculates valid hour value to display in text input and datepicker's body.
  1800. * @param date {Date|Number} - date or hours
  1801. * @param [ampm] {Boolean} - 12 hours mode
  1802. * @returns {{hours: *, dayPeriod: string}}
  1803. * @private
  1804. */
  1805. _getValidHoursFromDate: function (date, ampm) {
  1806. var d = date,
  1807. hours = date;
  1808. if (date instanceof Date) {
  1809. d = dp.getParsedDate(date);
  1810. hours = d.hours;
  1811. }
  1812. var _ampm = ampm || this.d.ampm,
  1813. dayPeriod = 'am';
  1814. if (_ampm) {
  1815. switch(true) {
  1816. case hours == 0:
  1817. hours = 12;
  1818. break;
  1819. case hours == 12:
  1820. dayPeriod = 'pm';
  1821. break;
  1822. case hours > 11:
  1823. hours = hours - 12;
  1824. dayPeriod = 'pm';
  1825. break;
  1826. default:
  1827. break;
  1828. }
  1829. }
  1830. return {
  1831. hours: hours,
  1832. dayPeriod: dayPeriod
  1833. }
  1834. },
  1835. set hours (val) {
  1836. this._hours = val;
  1837. var displayHours = this._getValidHoursFromDate(val);
  1838. this.displayHours = displayHours.hours;
  1839. this.dayPeriod = displayHours.dayPeriod;
  1840. },
  1841. get hours() {
  1842. return this._hours;
  1843. },
  1844. // Events
  1845. // -------------------------------------------------
  1846. _onChangeRange: function (e) {
  1847. var jQuerytarget = jQuery(e.target),
  1848. name = jQuerytarget.attr('name');
  1849. this.d.timepickerIsActive = true;
  1850. this[name] = jQuerytarget.val();
  1851. this._updateCurrentTime();
  1852. this.d._trigger('timeChange', [this.hours, this.minutes]);
  1853. this._handleDate(this.d.lastSelectedDate);
  1854. this.update()
  1855. },
  1856. _onSelectDate: function (e, data) {
  1857. this._handleDate(data);
  1858. this.update();
  1859. },
  1860. _onMouseEnterRange: function (e) {
  1861. var name = jQuery(e.target).attr('name');
  1862. jQuery('.datepicker--time-current-' + name, this.jQuerytimepicker).addClass('-focus-');
  1863. },
  1864. _onMouseOutRange: function (e) {
  1865. var name = jQuery(e.target).attr('name');
  1866. if (this.d.inFocus) return; // Prevent removing focus when mouse out of range slider
  1867. jQuery('.datepicker--time-current-' + name, this.jQuerytimepicker).removeClass('-focus-');
  1868. },
  1869. _onMouseUpRange: function (e) {
  1870. this.d.timepickerIsActive = false;
  1871. }
  1872. };
  1873. })();
  1874. })(window,jQuery);