bootstrap-datetimepicker.js 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552
  1. /*! version : 4.17.37
  2. =========================================================
  3. bootstrap-datetimejs
  4. https://github.com/Eonasdan/bootstrap-datetimepicker
  5. Copyright (c) 2015 Jonathan Peterson
  6. =========================================================
  7. */
  8. /*
  9. The MIT License (MIT)
  10. Copyright (c) 2015 Jonathan Peterson
  11. Permission is hereby granted, free of charge, to any person obtaining a copy
  12. of this software and associated documentation files (the "Software"), to deal
  13. in the Software without restriction, including without limitation the rights
  14. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. copies of the Software, and to permit persons to whom the Software is
  16. furnished to do so, subject to the following conditions:
  17. The above copyright notice and this permission notice shall be included in
  18. all copies or substantial portions of the Software.
  19. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. THE SOFTWARE.
  26. */
  27. /*global define:false */
  28. /*global exports:false */
  29. /*global require:false */
  30. /*global jQuery:false */
  31. /*global moment:false */
  32. (function (factory) {
  33. 'use strict';
  34. if (typeof define === 'function' && define.amd) {
  35. // AMD is used - Register as an anonymous module.
  36. define(['jquery', 'moment'], factory);
  37. } else if (typeof exports === 'object') {
  38. factory(require('jquery'), require('moment'));
  39. } else {
  40. // Neither AMD nor CommonJS used. Use global variables.
  41. if (typeof jQuery === 'undefined') {
  42. throw 'bootstrap-datetimepicker requires jQuery to be loaded first';
  43. }
  44. if (typeof moment === 'undefined') {
  45. throw 'bootstrap-datetimepicker requires Moment.js to be loaded first';
  46. }
  47. factory(jQuery, moment);
  48. }
  49. }(function ($, moment) {
  50. 'use strict';
  51. if (!moment) {
  52. throw new Error('bootstrap-datetimepicker requires Moment.js to be loaded first');
  53. }
  54. var dateTimePicker = function (element, options) {
  55. var picker = {},
  56. date,
  57. viewDate,
  58. unset = true,
  59. input,
  60. component = false,
  61. widget = false,
  62. use24Hours,
  63. minViewModeNumber = 0,
  64. actualFormat,
  65. parseFormats,
  66. currentViewMode,
  67. datePickerModes = [
  68. {
  69. clsName: 'days',
  70. navFnc: 'M',
  71. navStep: 1
  72. },
  73. {
  74. clsName: 'months',
  75. navFnc: 'y',
  76. navStep: 1
  77. },
  78. {
  79. clsName: 'years',
  80. navFnc: 'y',
  81. navStep: 10
  82. },
  83. {
  84. clsName: 'decades',
  85. navFnc: 'y',
  86. navStep: 100
  87. }
  88. ],
  89. viewModes = ['days', 'months', 'years', 'decades'],
  90. verticalModes = ['top', 'bottom', 'auto'],
  91. horizontalModes = ['left', 'right', 'auto'],
  92. toolbarPlacements = ['default', 'top', 'bottom'],
  93. keyMap = {
  94. 'up': 38,
  95. 38: 'up',
  96. 'down': 40,
  97. 40: 'down',
  98. 'left': 37,
  99. 37: 'left',
  100. 'right': 39,
  101. 39: 'right',
  102. 'tab': 9,
  103. 9: 'tab',
  104. 'escape': 27,
  105. 27: 'escape',
  106. 'enter': 13,
  107. 13: 'enter',
  108. 'pageUp': 33,
  109. 33: 'pageUp',
  110. 'pageDown': 34,
  111. 34: 'pageDown',
  112. 'shift': 16,
  113. 16: 'shift',
  114. 'control': 17,
  115. 17: 'control',
  116. 'space': 32,
  117. 32: 'space',
  118. 't': 84,
  119. 84: 't',
  120. 'delete': 46,
  121. 46: 'delete'
  122. },
  123. keyState = {},
  124. /********************************************************************************
  125. *
  126. * Private functions
  127. *
  128. ********************************************************************************/
  129. getMoment = function (d) {
  130. var tzEnabled = false,
  131. returnMoment,
  132. currentZoneOffset,
  133. incomingZoneOffset,
  134. timeZoneIndicator,
  135. dateWithTimeZoneInfo;
  136. if (moment.tz !== undefined && options.timeZone !== undefined && options.timeZone !== null && options.timeZone !== '') {
  137. tzEnabled = true;
  138. }
  139. if (d === undefined || d === null) {
  140. if (tzEnabled) {
  141. returnMoment = moment().tz(options.timeZone).startOf('d');
  142. } else {
  143. returnMoment = moment().startOf('d');
  144. }
  145. } else {
  146. if (tzEnabled) {
  147. currentZoneOffset = moment().tz(options.timeZone).utcOffset();
  148. incomingZoneOffset = moment(d, parseFormats, options.useStrict).utcOffset();
  149. if (incomingZoneOffset !== currentZoneOffset) {
  150. timeZoneIndicator = moment().tz(options.timeZone).format('Z');
  151. dateWithTimeZoneInfo = moment(d, parseFormats, options.useStrict).format('YYYY-MM-DD[T]HH:mm:ss') + timeZoneIndicator;
  152. returnMoment = moment(dateWithTimeZoneInfo, parseFormats, options.useStrict).tz(options.timeZone);
  153. } else {
  154. returnMoment = moment(d, parseFormats, options.useStrict).tz(options.timeZone);
  155. }
  156. } else {
  157. returnMoment = moment(d, parseFormats, options.useStrict);
  158. }
  159. }
  160. return returnMoment;
  161. },
  162. isEnabled = function (granularity) {
  163. if (typeof granularity !== 'string' || granularity.length > 1) {
  164. throw new TypeError('isEnabled expects a single character string parameter');
  165. }
  166. switch (granularity) {
  167. case 'y':
  168. return actualFormat.indexOf('Y') !== -1;
  169. case 'M':
  170. return actualFormat.indexOf('M') !== -1;
  171. case 'd':
  172. return actualFormat.toLowerCase().indexOf('d') !== -1;
  173. case 'h':
  174. case 'H':
  175. return actualFormat.toLowerCase().indexOf('h') !== -1;
  176. case 'm':
  177. return actualFormat.indexOf('m') !== -1;
  178. case 's':
  179. return actualFormat.indexOf('s') !== -1;
  180. default:
  181. return false;
  182. }
  183. },
  184. hasTime = function () {
  185. return (isEnabled('h') || isEnabled('m') || isEnabled('s'));
  186. },
  187. hasDate = function () {
  188. return (isEnabled('y') || isEnabled('M') || isEnabled('d'));
  189. },
  190. getDatePickerTemplate = function () {
  191. var headTemplate = $('<thead>')
  192. .append($('<tr>')
  193. .append($('<th>').addClass('prev').attr('data-action', 'previous')
  194. .append($('<span>').addClass(options.icons.previous))
  195. )
  196. .append($('<th>').addClass('picker-switch').attr('data-action', 'pickerSwitch').attr('colspan', (options.calendarWeeks ? '6' : '5')))
  197. .append($('<th>').addClass('next').attr('data-action', 'next')
  198. .append($('<span>').addClass(options.icons.next))
  199. )
  200. ),
  201. contTemplate = $('<tbody>')
  202. .append($('<tr>')
  203. .append($('<td>').attr('colspan', (options.calendarWeeks ? '8' : '7')))
  204. );
  205. return [
  206. $('<div>').addClass('datepicker-days')
  207. .append($('<table>').addClass('table-condensed')
  208. .append(headTemplate)
  209. .append($('<tbody>'))
  210. ),
  211. $('<div>').addClass('datepicker-months')
  212. .append($('<table>').addClass('table-condensed')
  213. .append(headTemplate.clone())
  214. .append(contTemplate.clone())
  215. ),
  216. $('<div>').addClass('datepicker-years')
  217. .append($('<table>').addClass('table-condensed')
  218. .append(headTemplate.clone())
  219. .append(contTemplate.clone())
  220. ),
  221. $('<div>').addClass('datepicker-decades')
  222. .append($('<table>').addClass('table-condensed')
  223. .append(headTemplate.clone())
  224. .append(contTemplate.clone())
  225. )
  226. ];
  227. },
  228. getTimePickerMainTemplate = function () {
  229. var topRow = $('<tr>'),
  230. middleRow = $('<tr>'),
  231. bottomRow = $('<tr>');
  232. if (isEnabled('h')) {
  233. topRow.append($('<td>')
  234. .append($('<a>').attr({href: '#', tabindex: '-1', 'title': options.tooltips.incrementHour}).addClass('btn').attr('data-action', 'incrementHours')
  235. .append($('<span>').addClass(options.icons.up))));
  236. middleRow.append($('<td>')
  237. .append($('<span>').addClass('timepicker-hour').attr({'data-time-component':'hours', 'title': options.tooltips.pickHour}).attr('data-action', 'showHours')));
  238. bottomRow.append($('<td>')
  239. .append($('<a>').attr({href: '#', tabindex: '-1', 'title': options.tooltips.decrementHour}).addClass('btn').attr('data-action', 'decrementHours')
  240. .append($('<span>').addClass(options.icons.down))));
  241. }
  242. if (isEnabled('m')) {
  243. if (isEnabled('h')) {
  244. topRow.append($('<td>').addClass('separator'));
  245. middleRow.append($('<td>').addClass('separator').html(':'));
  246. bottomRow.append($('<td>').addClass('separator'));
  247. }
  248. topRow.append($('<td>')
  249. .append($('<a>').attr({href: '#', tabindex: '-1', 'title': options.tooltips.incrementMinute}).addClass('btn').attr('data-action', 'incrementMinutes')
  250. .append($('<span>').addClass(options.icons.up))));
  251. middleRow.append($('<td>')
  252. .append($('<span>').addClass('timepicker-minute').attr({'data-time-component': 'minutes', 'title': options.tooltips.pickMinute}).attr('data-action', 'showMinutes')));
  253. bottomRow.append($('<td>')
  254. .append($('<a>').attr({href: '#', tabindex: '-1', 'title': options.tooltips.decrementMinute}).addClass('btn').attr('data-action', 'decrementMinutes')
  255. .append($('<span>').addClass(options.icons.down))));
  256. }
  257. if (isEnabled('s')) {
  258. if (isEnabled('m')) {
  259. topRow.append($('<td>').addClass('separator'));
  260. middleRow.append($('<td>').addClass('separator').html(':'));
  261. bottomRow.append($('<td>').addClass('separator'));
  262. }
  263. topRow.append($('<td>')
  264. .append($('<a>').attr({href: '#', tabindex: '-1', 'title': options.tooltips.incrementSecond}).addClass('btn').attr('data-action', 'incrementSeconds')
  265. .append($('<span>').addClass(options.icons.up))));
  266. middleRow.append($('<td>')
  267. .append($('<span>').addClass('timepicker-second').attr({'data-time-component': 'seconds', 'title': options.tooltips.pickSecond}).attr('data-action', 'showSeconds')));
  268. bottomRow.append($('<td>')
  269. .append($('<a>').attr({href: '#', tabindex: '-1', 'title': options.tooltips.decrementSecond}).addClass('btn').attr('data-action', 'decrementSeconds')
  270. .append($('<span>').addClass(options.icons.down))));
  271. }
  272. if (!use24Hours) {
  273. topRow.append($('<td>').addClass('separator'));
  274. middleRow.append($('<td>')
  275. .append($('<button>').addClass('btn btn-primary').attr({'data-action': 'togglePeriod', tabindex: '-1', 'title': options.tooltips.togglePeriod})));
  276. bottomRow.append($('<td>').addClass('separator'));
  277. }
  278. return $('<div>').addClass('timepicker-picker')
  279. .append($('<table>').addClass('table-condensed')
  280. .append([topRow, middleRow, bottomRow]));
  281. },
  282. getTimePickerTemplate = function () {
  283. var hoursView = $('<div>').addClass('timepicker-hours')
  284. .append($('<table>').addClass('table-condensed')),
  285. minutesView = $('<div>').addClass('timepicker-minutes')
  286. .append($('<table>').addClass('table-condensed')),
  287. secondsView = $('<div>').addClass('timepicker-seconds')
  288. .append($('<table>').addClass('table-condensed')),
  289. ret = [getTimePickerMainTemplate()];
  290. if (isEnabled('h')) {
  291. ret.push(hoursView);
  292. }
  293. if (isEnabled('m')) {
  294. ret.push(minutesView);
  295. }
  296. if (isEnabled('s')) {
  297. ret.push(secondsView);
  298. }
  299. return ret;
  300. },
  301. getToolbar = function () {
  302. var row = [];
  303. if (options.showTodayButton) {
  304. row.push($('<td>').append($('<a>').attr({'data-action':'today', 'title': options.tooltips.today}).append($('<span>').addClass(options.icons.today))));
  305. }
  306. if (!options.sideBySide && hasDate() && hasTime()) {
  307. row.push($('<td>').append($('<a>').attr({'data-action':'togglePicker', 'title': options.tooltips.selectTime}).append($('<span>').addClass(options.icons.time))));
  308. }
  309. if (options.showClear) {
  310. row.push($('<td>').append($('<a>').attr({'data-action':'clear', 'title': options.tooltips.clear}).append($('<span>').addClass(options.icons.clear))));
  311. }
  312. if (options.showClose) {
  313. row.push($('<td>').append($('<a>').attr({'data-action':'close', 'title': options.tooltips.close}).append($('<span>').addClass(options.icons.close))));
  314. }
  315. return $('<table>').addClass('table-condensed').append($('<tbody>').append($('<tr>').append(row)));
  316. },
  317. getTemplate = function () {
  318. var template = $('<div>').addClass('bootstrap-datetimepicker-widget dropdown-menu'),
  319. dateView = $('<div>').addClass('datepicker').append(getDatePickerTemplate()),
  320. timeView = $('<div>').addClass('timepicker').append(getTimePickerTemplate()),
  321. content = $('<ul>').addClass('list-unstyled'),
  322. toolbar = $('<li>').addClass('picker-switch' + (options.collapse ? ' accordion-toggle' : '')).append(getToolbar());
  323. if (options.inline) {
  324. template.removeClass('dropdown-menu');
  325. }
  326. if (use24Hours) {
  327. template.addClass('usetwentyfour');
  328. }
  329. if (isEnabled('s') && !use24Hours) {
  330. template.addClass('wider');
  331. }
  332. if (options.sideBySide && hasDate() && hasTime()) {
  333. template.addClass('timepicker-sbs');
  334. if (options.toolbarPlacement === 'top') {
  335. template.append(toolbar);
  336. }
  337. template.append(
  338. $('<div>').addClass('row')
  339. .append(dateView.addClass('col-md-6'))
  340. .append(timeView.addClass('col-md-6'))
  341. );
  342. if (options.toolbarPlacement === 'bottom') {
  343. template.append(toolbar);
  344. }
  345. return template;
  346. }
  347. if (options.toolbarPlacement === 'top') {
  348. content.append(toolbar);
  349. }
  350. if (hasDate()) {
  351. content.append($('<li>').addClass((options.collapse && hasTime() ? 'collapse in' : '')).append(dateView));
  352. }
  353. if (options.toolbarPlacement === 'default') {
  354. content.append(toolbar);
  355. }
  356. if (hasTime()) {
  357. content.append($('<li>').addClass((options.collapse && hasDate() ? 'collapse' : '')).append(timeView));
  358. }
  359. if (options.toolbarPlacement === 'bottom') {
  360. content.append(toolbar);
  361. }
  362. return template.append(content);
  363. },
  364. dataToOptions = function () {
  365. var eData,
  366. dataOptions = {};
  367. if (element.is('input') || options.inline) {
  368. eData = element.data();
  369. } else {
  370. eData = element.find('input').data();
  371. }
  372. if (eData.dateOptions && eData.dateOptions instanceof Object) {
  373. dataOptions = $.extend(true, dataOptions, eData.dateOptions);
  374. }
  375. $.each(options, function (key) {
  376. var attributeName = 'date' + key.charAt(0).toUpperCase() + key.slice(1);
  377. if (eData[attributeName] !== undefined) {
  378. dataOptions[key] = eData[attributeName];
  379. }
  380. });
  381. return dataOptions;
  382. },
  383. place = function () {
  384. var position = (component || element).position(),
  385. offset = (component || element).offset(),
  386. vertical = options.widgetPositioning.vertical,
  387. horizontal = options.widgetPositioning.horizontal,
  388. parent;
  389. if (options.widgetParent) {
  390. parent = options.widgetParent.append(widget);
  391. } else if (element.is('input')) {
  392. parent = element.after(widget).parent();
  393. } else if (options.inline) {
  394. parent = element.append(widget);
  395. return;
  396. } else {
  397. parent = element;
  398. element.children().first().after(widget);
  399. }
  400. // Top and bottom logic
  401. if (vertical === 'auto') {
  402. if (offset.top + widget.height() * 1.5 >= $(window).height() + $(window).scrollTop() &&
  403. widget.height() + element.outerHeight() < offset.top) {
  404. vertical = 'top';
  405. } else {
  406. vertical = 'bottom';
  407. }
  408. }
  409. // Left and right logic
  410. if (horizontal === 'auto') {
  411. if (parent.width() < offset.left + widget.outerWidth() / 2 &&
  412. offset.left + widget.outerWidth() > $(window).width()) {
  413. horizontal = 'right';
  414. } else {
  415. horizontal = 'left';
  416. }
  417. }
  418. if (vertical === 'top') {
  419. widget.addClass('top').removeClass('bottom');
  420. } else {
  421. widget.addClass('bottom').removeClass('top');
  422. }
  423. if (horizontal === 'right') {
  424. widget.addClass('pull-right');
  425. } else {
  426. widget.removeClass('pull-right');
  427. }
  428. // find the first parent element that has a relative css positioning
  429. if (parent.css('position') !== 'relative') {
  430. parent = parent.parents().filter(function () {
  431. return $(this).css('position') === 'relative';
  432. }).first();
  433. }
  434. if (parent.length === 0) {
  435. throw new Error('datetimepicker component should be placed within a relative positioned container');
  436. }
  437. widget.css({
  438. top: vertical === 'top' ? 'auto' : position.top + element.outerHeight(),
  439. bottom: vertical === 'top' ? position.top + element.outerHeight() : 'auto',
  440. left: horizontal === 'left' ? (parent === element ? 0 : position.left) : 'auto',
  441. right: horizontal === 'left' ? 'auto' : parent.outerWidth() - element.outerWidth() - (parent === element ? 0 : position.left)
  442. });
  443. },
  444. notifyEvent = function (e) {
  445. if (e.type === 'dp.change' && ((e.date && e.date.isSame(e.oldDate)) || (!e.date && !e.oldDate))) {
  446. return;
  447. }
  448. element.trigger(e);
  449. },
  450. viewUpdate = function (e) {
  451. if (e === 'y') {
  452. e = 'YYYY';
  453. }
  454. notifyEvent({
  455. type: 'dp.update',
  456. change: e,
  457. viewDate: viewDate.clone()
  458. });
  459. },
  460. showMode = function (dir) {
  461. if (!widget) {
  462. return;
  463. }
  464. if (dir) {
  465. currentViewMode = Math.max(minViewModeNumber, Math.min(3, currentViewMode + dir));
  466. }
  467. widget.find('.datepicker > div').hide().filter('.datepicker-' + datePickerModes[currentViewMode].clsName).show();
  468. },
  469. fillDow = function () {
  470. var row = $('<tr>'),
  471. currentDate = viewDate.clone().startOf('w').startOf('d');
  472. if (options.calendarWeeks === true) {
  473. row.append($('<th>').addClass('cw').text('#'));
  474. }
  475. while (currentDate.isBefore(viewDate.clone().endOf('w'))) {
  476. row.append($('<th>').addClass('dow').text(currentDate.format('dd')));
  477. currentDate.add(1, 'd');
  478. }
  479. widget.find('.datepicker-days thead').append(row);
  480. },
  481. isInDisabledDates = function (testDate) {
  482. return options.disabledDates[testDate.format('YYYY-MM-DD')] === true;
  483. },
  484. isInEnabledDates = function (testDate) {
  485. return options.enabledDates[testDate.format('YYYY-MM-DD')] === true;
  486. },
  487. isInDisabledHours = function (testDate) {
  488. return options.disabledHours[testDate.format('H')] === true;
  489. },
  490. isInEnabledHours = function (testDate) {
  491. return options.enabledHours[testDate.format('H')] === true;
  492. },
  493. isValid = function (targetMoment, granularity) {
  494. if (!targetMoment.isValid()) {
  495. return false;
  496. }
  497. if (options.disabledDates && granularity === 'd' && isInDisabledDates(targetMoment)) {
  498. return false;
  499. }
  500. if (options.enabledDates && granularity === 'd' && !isInEnabledDates(targetMoment)) {
  501. return false;
  502. }
  503. if (options.minDate && targetMoment.isBefore(options.minDate, granularity)) {
  504. return false;
  505. }
  506. if (options.maxDate && targetMoment.isAfter(options.maxDate, granularity)) {
  507. return false;
  508. }
  509. if (options.daysOfWeekDisabled && granularity === 'd' && options.daysOfWeekDisabled.indexOf(targetMoment.day()) !== -1) {
  510. return false;
  511. }
  512. if (options.disabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && isInDisabledHours(targetMoment)) {
  513. return false;
  514. }
  515. if (options.enabledHours && (granularity === 'h' || granularity === 'm' || granularity === 's') && !isInEnabledHours(targetMoment)) {
  516. return false;
  517. }
  518. if (options.disabledTimeIntervals && (granularity === 'h' || granularity === 'm' || granularity === 's')) {
  519. var found = false;
  520. $.each(options.disabledTimeIntervals, function () {
  521. if (targetMoment.isBetween(this[0], this[1])) {
  522. found = true;
  523. return false;
  524. }
  525. });
  526. if (found) {
  527. return false;
  528. }
  529. }
  530. return true;
  531. },
  532. fillMonths = function () {
  533. var spans = [],
  534. monthsShort = viewDate.clone().startOf('y').startOf('d');
  535. while (monthsShort.isSame(viewDate, 'y')) {
  536. spans.push($('<span>').attr('data-action', 'selectMonth').addClass('month').text(monthsShort.format('MMM')));
  537. monthsShort.add(1, 'M');
  538. }
  539. widget.find('.datepicker-months td').empty().append(spans);
  540. },
  541. updateMonths = function () {
  542. var monthsView = widget.find('.datepicker-months'),
  543. monthsViewHeader = monthsView.find('th'),
  544. months = monthsView.find('tbody').find('span');
  545. monthsViewHeader.eq(0).find('span').attr('title', options.tooltips.prevYear);
  546. monthsViewHeader.eq(1).attr('title', options.tooltips.selectYear);
  547. monthsViewHeader.eq(2).find('span').attr('title', options.tooltips.nextYear);
  548. monthsView.find('.disabled').removeClass('disabled');
  549. if (!isValid(viewDate.clone().subtract(1, 'y'), 'y')) {
  550. monthsViewHeader.eq(0).addClass('disabled');
  551. }
  552. monthsViewHeader.eq(1).text(viewDate.year());
  553. if (!isValid(viewDate.clone().add(1, 'y'), 'y')) {
  554. monthsViewHeader.eq(2).addClass('disabled');
  555. }
  556. months.removeClass('active');
  557. if (date.isSame(viewDate, 'y') && !unset) {
  558. months.eq(date.month()).addClass('active');
  559. }
  560. months.each(function (index) {
  561. if (!isValid(viewDate.clone().month(index), 'M')) {
  562. $(this).addClass('disabled');
  563. }
  564. });
  565. },
  566. updateYears = function () {
  567. var yearsView = widget.find('.datepicker-years'),
  568. yearsViewHeader = yearsView.find('th'),
  569. startYear = viewDate.clone().subtract(5, 'y'),
  570. endYear = viewDate.clone().add(6, 'y'),
  571. html = '';
  572. yearsViewHeader.eq(0).find('span').attr('title', options.tooltips.prevDecade);
  573. yearsViewHeader.eq(1).attr('title', options.tooltips.selectDecade);
  574. yearsViewHeader.eq(2).find('span').attr('title', options.tooltips.nextDecade);
  575. yearsView.find('.disabled').removeClass('disabled');
  576. if (options.minDate && options.minDate.isAfter(startYear, 'y')) {
  577. yearsViewHeader.eq(0).addClass('disabled');
  578. }
  579. yearsViewHeader.eq(1).text(startYear.year() + '-' + endYear.year());
  580. if (options.maxDate && options.maxDate.isBefore(endYear, 'y')) {
  581. yearsViewHeader.eq(2).addClass('disabled');
  582. }
  583. while (!startYear.isAfter(endYear, 'y')) {
  584. html += '<span data-action="selectYear" class="year' + (startYear.isSame(date, 'y') && !unset ? ' active' : '') + (!isValid(startYear, 'y') ? ' disabled' : '') + '">' + startYear.year() + '</span>';
  585. startYear.add(1, 'y');
  586. }
  587. yearsView.find('td').html(html);
  588. },
  589. updateDecades = function () {
  590. var decadesView = widget.find('.datepicker-decades'),
  591. decadesViewHeader = decadesView.find('th'),
  592. startDecade = moment({y: viewDate.year() - (viewDate.year() % 100) - 1}),
  593. endDecade = startDecade.clone().add(100, 'y'),
  594. startedAt = startDecade.clone(),
  595. html = '';
  596. decadesViewHeader.eq(0).find('span').attr('title', options.tooltips.prevCentury);
  597. decadesViewHeader.eq(2).find('span').attr('title', options.tooltips.nextCentury);
  598. decadesView.find('.disabled').removeClass('disabled');
  599. if (startDecade.isSame(moment({y: 1900})) || (options.minDate && options.minDate.isAfter(startDecade, 'y'))) {
  600. decadesViewHeader.eq(0).addClass('disabled');
  601. }
  602. decadesViewHeader.eq(1).text(startDecade.year() + '-' + endDecade.year());
  603. if (startDecade.isSame(moment({y: 2000})) || (options.maxDate && options.maxDate.isBefore(endDecade, 'y'))) {
  604. decadesViewHeader.eq(2).addClass('disabled');
  605. }
  606. while (!startDecade.isAfter(endDecade, 'y')) {
  607. html += '<span data-action="selectDecade" class="decade' + (startDecade.isSame(date, 'y') ? ' active' : '') +
  608. (!isValid(startDecade, 'y') ? ' disabled' : '') + '" data-selection="' + (startDecade.year() + 6) + '">' + (startDecade.year() + 1) + ' - ' + (startDecade.year() + 12) + '</span>';
  609. startDecade.add(12, 'y');
  610. }
  611. html += '<span></span><span></span><span></span>'; //push the dangling block over, at least this way it's even
  612. decadesView.find('td').html(html);
  613. decadesViewHeader.eq(1).text((startedAt.year() + 1) + '-' + (startDecade.year()));
  614. },
  615. fillDate = function () {
  616. var daysView = widget.find('.datepicker-days'),
  617. daysViewHeader = daysView.find('th'),
  618. currentDate,
  619. html = [],
  620. row,
  621. clsName,
  622. i;
  623. if (!hasDate()) {
  624. return;
  625. }
  626. daysViewHeader.eq(0).find('span').attr('title', options.tooltips.prevMonth);
  627. daysViewHeader.eq(1).attr('title', options.tooltips.selectMonth);
  628. daysViewHeader.eq(2).find('span').attr('title', options.tooltips.nextMonth);
  629. daysView.find('.disabled').removeClass('disabled');
  630. daysViewHeader.eq(1).text(viewDate.format(options.dayViewHeaderFormat));
  631. if (!isValid(viewDate.clone().subtract(1, 'M'), 'M')) {
  632. daysViewHeader.eq(0).addClass('disabled');
  633. }
  634. if (!isValid(viewDate.clone().add(1, 'M'), 'M')) {
  635. daysViewHeader.eq(2).addClass('disabled');
  636. }
  637. currentDate = viewDate.clone().startOf('M').startOf('w').startOf('d');
  638. for (i = 0; i < 42; i++) { //always display 42 days (should show 6 weeks)
  639. if (currentDate.weekday() === 0) {
  640. row = $('<tr>');
  641. if (options.calendarWeeks) {
  642. row.append('<td class="cw">' + currentDate.week() + '</td>');
  643. }
  644. html.push(row);
  645. }
  646. clsName = '';
  647. if (currentDate.isBefore(viewDate, 'M')) {
  648. clsName += ' old';
  649. }
  650. if (currentDate.isAfter(viewDate, 'M')) {
  651. clsName += ' new';
  652. }
  653. if (currentDate.isSame(date, 'd') && !unset) {
  654. clsName += ' active';
  655. }
  656. if (!isValid(currentDate, 'd')) {
  657. clsName += ' disabled';
  658. }
  659. if (currentDate.isSame(getMoment(), 'd')) {
  660. clsName += ' today';
  661. }
  662. if (currentDate.day() === 0 || currentDate.day() === 6) {
  663. clsName += ' weekend';
  664. }
  665. row.append('<td data-action="selectDay" data-day="' + currentDate.format('L') + '" class="day' + clsName + '">' + currentDate.date() + '</td>');
  666. currentDate.add(1, 'd');
  667. }
  668. daysView.find('tbody').empty().append(html);
  669. updateMonths();
  670. updateYears();
  671. updateDecades();
  672. },
  673. fillHours = function () {
  674. var table = widget.find('.timepicker-hours table'),
  675. currentHour = viewDate.clone().startOf('d'),
  676. html = [],
  677. row = $('<tr>');
  678. if (viewDate.hour() > 11 && !use24Hours) {
  679. currentHour.hour(12);
  680. }
  681. while (currentHour.isSame(viewDate, 'd') && (use24Hours || (viewDate.hour() < 12 && currentHour.hour() < 12) || viewDate.hour() > 11)) {
  682. if (currentHour.hour() % 4 === 0) {
  683. row = $('<tr>');
  684. html.push(row);
  685. }
  686. row.append('<td data-action="selectHour" class="hour' + (!isValid(currentHour, 'h') ? ' disabled' : '') + '">' + currentHour.format(use24Hours ? 'HH' : 'hh') + '</td>');
  687. currentHour.add(1, 'h');
  688. }
  689. table.empty().append(html);
  690. },
  691. fillMinutes = function () {
  692. var table = widget.find('.timepicker-minutes table'),
  693. currentMinute = viewDate.clone().startOf('h'),
  694. html = [],
  695. row = $('<tr>'),
  696. step = options.stepping === 1 ? 5 : options.stepping;
  697. while (viewDate.isSame(currentMinute, 'h')) {
  698. if (currentMinute.minute() % (step * 4) === 0) {
  699. row = $('<tr>');
  700. html.push(row);
  701. }
  702. row.append('<td data-action="selectMinute" class="minute' + (!isValid(currentMinute, 'm') ? ' disabled' : '') + '">' + currentMinute.format('mm') + '</td>');
  703. currentMinute.add(step, 'm');
  704. }
  705. table.empty().append(html);
  706. },
  707. fillSeconds = function () {
  708. var table = widget.find('.timepicker-seconds table'),
  709. currentSecond = viewDate.clone().startOf('m'),
  710. html = [],
  711. row = $('<tr>');
  712. while (viewDate.isSame(currentSecond, 'm')) {
  713. if (currentSecond.second() % 20 === 0) {
  714. row = $('<tr>');
  715. html.push(row);
  716. }
  717. row.append('<td data-action="selectSecond" class="second' + (!isValid(currentSecond, 's') ? ' disabled' : '') + '">' + currentSecond.format('ss') + '</td>');
  718. currentSecond.add(5, 's');
  719. }
  720. table.empty().append(html);
  721. },
  722. fillTime = function () {
  723. var toggle, newDate, timeComponents = widget.find('.timepicker span[data-time-component]');
  724. if (!use24Hours) {
  725. toggle = widget.find('.timepicker [data-action=togglePeriod]');
  726. newDate = date.clone().add((date.hours() >= 12) ? -12 : 12, 'h');
  727. toggle.text(date.format('A'));
  728. if (isValid(newDate, 'h')) {
  729. toggle.removeClass('disabled');
  730. } else {
  731. toggle.addClass('disabled');
  732. }
  733. }
  734. timeComponents.filter('[data-time-component=hours]').text(date.format(use24Hours ? 'HH' : 'hh'));
  735. timeComponents.filter('[data-time-component=minutes]').text(date.format('mm'));
  736. timeComponents.filter('[data-time-component=seconds]').text(date.format('ss'));
  737. fillHours();
  738. fillMinutes();
  739. fillSeconds();
  740. },
  741. update = function () {
  742. if (!widget) {
  743. return;
  744. }
  745. fillDate();
  746. fillTime();
  747. },
  748. setValue = function (targetMoment) {
  749. var oldDate = unset ? null : date;
  750. // case of calling setValue(null or false)
  751. if (!targetMoment) {
  752. unset = true;
  753. input.val('');
  754. element.data('date', '');
  755. notifyEvent({
  756. type: 'dp.change',
  757. date: false,
  758. oldDate: oldDate
  759. });
  760. update();
  761. return;
  762. }
  763. targetMoment = targetMoment.clone().locale(options.locale);
  764. if (options.stepping !== 1) {
  765. targetMoment.minutes((Math.round(targetMoment.minutes() / options.stepping) * options.stepping) % 60).seconds(0);
  766. }
  767. if (isValid(targetMoment)) {
  768. date = targetMoment;
  769. viewDate = date.clone();
  770. input.val(date.format(actualFormat));
  771. element.data('date', date.format(actualFormat));
  772. unset = false;
  773. update();
  774. notifyEvent({
  775. type: 'dp.change',
  776. date: date.clone(),
  777. oldDate: oldDate
  778. });
  779. } else {
  780. if (!options.keepInvalid) {
  781. input.val(unset ? '' : date.format(actualFormat));
  782. }
  783. notifyEvent({
  784. type: 'dp.error',
  785. date: targetMoment
  786. });
  787. }
  788. },
  789. hide = function () {
  790. ///<summary>Hides the widget. Possibly will emit dp.hide</summary>
  791. var transitioning = false;
  792. if (!widget) {
  793. return picker;
  794. }
  795. // Ignore event if in the middle of a picker transition
  796. widget.find('.collapse').each(function () {
  797. var collapseData = $(this).data('collapse');
  798. if (collapseData && collapseData.transitioning) {
  799. transitioning = true;
  800. return false;
  801. }
  802. return true;
  803. });
  804. if (transitioning) {
  805. return picker;
  806. }
  807. if (component && component.hasClass('btn')) {
  808. component.toggleClass('active');
  809. }
  810. widget.hide();
  811. $(window).off('resize', place);
  812. widget.off('click', '[data-action]');
  813. widget.off('mousedown', false);
  814. widget.remove();
  815. widget = false;
  816. notifyEvent({
  817. type: 'dp.hide',
  818. date: date.clone()
  819. });
  820. input.blur();
  821. return picker;
  822. },
  823. clear = function () {
  824. setValue(null);
  825. },
  826. /********************************************************************************
  827. *
  828. * Widget UI interaction functions
  829. *
  830. ********************************************************************************/
  831. actions = {
  832. next: function () {
  833. var navFnc = datePickerModes[currentViewMode].navFnc;
  834. viewDate.add(datePickerModes[currentViewMode].navStep, navFnc);
  835. fillDate();
  836. viewUpdate(navFnc);
  837. },
  838. previous: function () {
  839. var navFnc = datePickerModes[currentViewMode].navFnc;
  840. viewDate.subtract(datePickerModes[currentViewMode].navStep, navFnc);
  841. fillDate();
  842. viewUpdate(navFnc);
  843. },
  844. pickerSwitch: function () {
  845. showMode(1);
  846. },
  847. selectMonth: function (e) {
  848. var month = $(e.target).closest('tbody').find('span').index($(e.target));
  849. viewDate.month(month);
  850. if (currentViewMode === minViewModeNumber) {
  851. setValue(date.clone().year(viewDate.year()).month(viewDate.month()));
  852. if (!options.inline) {
  853. hide();
  854. }
  855. } else {
  856. showMode(-1);
  857. fillDate();
  858. }
  859. viewUpdate('M');
  860. },
  861. selectYear: function (e) {
  862. var year = parseInt($(e.target).text(), 10) || 0;
  863. viewDate.year(year);
  864. if (currentViewMode === minViewModeNumber) {
  865. setValue(date.clone().year(viewDate.year()));
  866. if (!options.inline) {
  867. hide();
  868. }
  869. } else {
  870. showMode(-1);
  871. fillDate();
  872. }
  873. viewUpdate('YYYY');
  874. },
  875. selectDecade: function (e) {
  876. var year = parseInt($(e.target).data('selection'), 10) || 0;
  877. viewDate.year(year);
  878. if (currentViewMode === minViewModeNumber) {
  879. setValue(date.clone().year(viewDate.year()));
  880. if (!options.inline) {
  881. hide();
  882. }
  883. } else {
  884. showMode(-1);
  885. fillDate();
  886. }
  887. viewUpdate('YYYY');
  888. },
  889. selectDay: function (e) {
  890. var day = viewDate.clone();
  891. if ($(e.target).is('.old')) {
  892. day.subtract(1, 'M');
  893. }
  894. if ($(e.target).is('.new')) {
  895. day.add(1, 'M');
  896. }
  897. setValue(day.date(parseInt($(e.target).text(), 10)));
  898. if (!hasTime() && !options.keepOpen && !options.inline) {
  899. hide();
  900. }
  901. },
  902. incrementHours: function () {
  903. var newDate = date.clone().add(1, 'h');
  904. if (isValid(newDate, 'h')) {
  905. setValue(newDate);
  906. }
  907. },
  908. incrementMinutes: function () {
  909. var newDate = date.clone().add(options.stepping, 'm');
  910. if (isValid(newDate, 'm')) {
  911. setValue(newDate);
  912. }
  913. },
  914. incrementSeconds: function () {
  915. var newDate = date.clone().add(1, 's');
  916. if (isValid(newDate, 's')) {
  917. setValue(newDate);
  918. }
  919. },
  920. decrementHours: function () {
  921. var newDate = date.clone().subtract(1, 'h');
  922. if (isValid(newDate, 'h')) {
  923. setValue(newDate);
  924. }
  925. },
  926. decrementMinutes: function () {
  927. var newDate = date.clone().subtract(options.stepping, 'm');
  928. if (isValid(newDate, 'm')) {
  929. setValue(newDate);
  930. }
  931. },
  932. decrementSeconds: function () {
  933. var newDate = date.clone().subtract(1, 's');
  934. if (isValid(newDate, 's')) {
  935. setValue(newDate);
  936. }
  937. },
  938. togglePeriod: function () {
  939. setValue(date.clone().add((date.hours() >= 12) ? -12 : 12, 'h'));
  940. },
  941. togglePicker: function (e) {
  942. var $this = $(e.target),
  943. $parent = $this.closest('ul'),
  944. expanded = $parent.find('.in'),
  945. closed = $parent.find('.collapse:not(.in)'),
  946. collapseData;
  947. if (expanded && expanded.length) {
  948. collapseData = expanded.data('collapse');
  949. if (collapseData && collapseData.transitioning) {
  950. return;
  951. }
  952. if (expanded.collapse) { // if collapse plugin is available through bootstrap.js then use it
  953. expanded.collapse('hide');
  954. closed.collapse('show');
  955. } else { // otherwise just toggle in class on the two views
  956. expanded.removeClass('in');
  957. closed.addClass('in');
  958. }
  959. if ($this.is('span')) {
  960. $this.toggleClass(options.icons.time + ' ' + options.icons.date);
  961. } else {
  962. $this.find('span').toggleClass(options.icons.time + ' ' + options.icons.date);
  963. }
  964. // NOTE: uncomment if toggled state will be restored in show()
  965. //if (component) {
  966. // component.find('span').toggleClass(options.icons.time + ' ' + options.icons.date);
  967. //}
  968. }
  969. },
  970. showPicker: function () {
  971. widget.find('.timepicker > div:not(.timepicker-picker)').hide();
  972. widget.find('.timepicker .timepicker-picker').show();
  973. },
  974. showHours: function () {
  975. widget.find('.timepicker .timepicker-picker').hide();
  976. widget.find('.timepicker .timepicker-hours').show();
  977. },
  978. showMinutes: function () {
  979. widget.find('.timepicker .timepicker-picker').hide();
  980. widget.find('.timepicker .timepicker-minutes').show();
  981. },
  982. showSeconds: function () {
  983. widget.find('.timepicker .timepicker-picker').hide();
  984. widget.find('.timepicker .timepicker-seconds').show();
  985. },
  986. selectHour: function (e) {
  987. var hour = parseInt($(e.target).text(), 10);
  988. if (!use24Hours) {
  989. if (date.hours() >= 12) {
  990. if (hour !== 12) {
  991. hour += 12;
  992. }
  993. } else {
  994. if (hour === 12) {
  995. hour = 0;
  996. }
  997. }
  998. }
  999. setValue(date.clone().hours(hour));
  1000. actions.showPicker.call(picker);
  1001. },
  1002. selectMinute: function (e) {
  1003. setValue(date.clone().minutes(parseInt($(e.target).text(), 10)));
  1004. actions.showPicker.call(picker);
  1005. },
  1006. selectSecond: function (e) {
  1007. setValue(date.clone().seconds(parseInt($(e.target).text(), 10)));
  1008. actions.showPicker.call(picker);
  1009. },
  1010. clear: clear,
  1011. today: function () {
  1012. var todaysDate = getMoment();
  1013. if (isValid(todaysDate, 'd')) {
  1014. setValue(todaysDate);
  1015. }
  1016. },
  1017. close: hide
  1018. },
  1019. doAction = function (e) {
  1020. if ($(e.currentTarget).is('.disabled')) {
  1021. return false;
  1022. }
  1023. actions[$(e.currentTarget).data('action')].apply(picker, arguments);
  1024. return false;
  1025. },
  1026. show = function () {
  1027. ///<summary>Shows the widget. Possibly will emit dp.show and dp.change</summary>
  1028. var currentMoment,
  1029. useCurrentGranularity = {
  1030. 'year': function (m) {
  1031. return m.month(0).date(1).hours(0).seconds(0).minutes(0);
  1032. },
  1033. 'month': function (m) {
  1034. return m.date(1).hours(0).seconds(0).minutes(0);
  1035. },
  1036. 'day': function (m) {
  1037. return m.hours(0).seconds(0).minutes(0);
  1038. },
  1039. 'hour': function (m) {
  1040. return m.seconds(0).minutes(0);
  1041. },
  1042. 'minute': function (m) {
  1043. return m.seconds(0);
  1044. }
  1045. };
  1046. if (input.prop('disabled') || (!options.ignoreReadonly && input.prop('readonly')) || widget) {
  1047. return picker;
  1048. }
  1049. if (input.val() !== undefined && input.val().trim().length !== 0) {
  1050. setValue(parseInputDate(input.val().trim()));
  1051. } else if (options.useCurrent && unset && ((input.is('input') && input.val().trim().length === 0) || options.inline)) {
  1052. currentMoment = getMoment();
  1053. if (typeof options.useCurrent === 'string') {
  1054. currentMoment = useCurrentGranularity[options.useCurrent](currentMoment);
  1055. }
  1056. setValue(currentMoment);
  1057. }
  1058. widget = getTemplate();
  1059. fillDow();
  1060. fillMonths();
  1061. widget.find('.timepicker-hours').hide();
  1062. widget.find('.timepicker-minutes').hide();
  1063. widget.find('.timepicker-seconds').hide();
  1064. update();
  1065. showMode();
  1066. $(window).on('resize', place);
  1067. widget.on('click', '[data-action]', doAction); // this handles clicks on the widget
  1068. widget.on('mousedown', false);
  1069. if (component && component.hasClass('btn')) {
  1070. component.toggleClass('active');
  1071. }
  1072. widget.show();
  1073. place();
  1074. if (options.focusOnShow && !input.is(':focus')) {
  1075. input.focus();
  1076. }
  1077. notifyEvent({
  1078. type: 'dp.show'
  1079. });
  1080. return picker;
  1081. },
  1082. toggle = function () {
  1083. /// <summary>Shows or hides the widget</summary>
  1084. return (widget ? hide() : show());
  1085. },
  1086. parseInputDate = function (inputDate) {
  1087. if (options.parseInputDate === undefined) {
  1088. if (moment.isMoment(inputDate) || inputDate instanceof Date) {
  1089. inputDate = moment(inputDate);
  1090. } else {
  1091. inputDate = getMoment(inputDate);
  1092. }
  1093. } else {
  1094. inputDate = options.parseInputDate(inputDate);
  1095. }
  1096. inputDate.locale(options.locale);
  1097. return inputDate;
  1098. },
  1099. keydown = function (e) {
  1100. var handler = null,
  1101. index,
  1102. index2,
  1103. pressedKeys = [],
  1104. pressedModifiers = {},
  1105. currentKey = e.which,
  1106. keyBindKeys,
  1107. allModifiersPressed,
  1108. pressed = 'p';
  1109. keyState[currentKey] = pressed;
  1110. for (index in keyState) {
  1111. if (keyState.hasOwnProperty(index) && keyState[index] === pressed) {
  1112. pressedKeys.push(index);
  1113. if (parseInt(index, 10) !== currentKey) {
  1114. pressedModifiers[index] = true;
  1115. }
  1116. }
  1117. }
  1118. for (index in options.keyBinds) {
  1119. if (options.keyBinds.hasOwnProperty(index) && typeof (options.keyBinds[index]) === 'function') {
  1120. keyBindKeys = index.split(' ');
  1121. if (keyBindKeys.length === pressedKeys.length && keyMap[currentKey] === keyBindKeys[keyBindKeys.length - 1]) {
  1122. allModifiersPressed = true;
  1123. for (index2 = keyBindKeys.length - 2; index2 >= 0; index2--) {
  1124. if (!(keyMap[keyBindKeys[index2]] in pressedModifiers)) {
  1125. allModifiersPressed = false;
  1126. break;
  1127. }
  1128. }
  1129. if (allModifiersPressed) {
  1130. handler = options.keyBinds[index];
  1131. break;
  1132. }
  1133. }
  1134. }
  1135. }
  1136. if (handler) {
  1137. handler.call(picker, widget);
  1138. e.stopPropagation();
  1139. e.preventDefault();
  1140. }
  1141. },
  1142. keyup = function (e) {
  1143. keyState[e.which] = 'r';
  1144. e.stopPropagation();
  1145. e.preventDefault();
  1146. },
  1147. change = function (e) {
  1148. var val = $(e.target).val().trim(),
  1149. parsedDate = val ? parseInputDate(val) : null;
  1150. setValue(parsedDate);
  1151. e.stopImmediatePropagation();
  1152. return false;
  1153. },
  1154. attachDatePickerElementEvents = function () {
  1155. input.on({
  1156. 'change': change,
  1157. 'blur': options.debug ? '' : hide,
  1158. 'keydown': keydown,
  1159. 'keyup': keyup,
  1160. 'focus': options.allowInputToggle ? show : ''
  1161. });
  1162. if (element.is('input')) {
  1163. input.on({
  1164. 'focus': show
  1165. });
  1166. } else if (component) {
  1167. component.on('click', toggle);
  1168. component.on('mousedown', false);
  1169. }
  1170. },
  1171. detachDatePickerElementEvents = function () {
  1172. input.off({
  1173. 'change': change,
  1174. 'blur': blur,
  1175. 'keydown': keydown,
  1176. 'keyup': keyup,
  1177. 'focus': options.allowInputToggle ? hide : ''
  1178. });
  1179. if (element.is('input')) {
  1180. input.off({
  1181. 'focus': show
  1182. });
  1183. } else if (component) {
  1184. component.off('click', toggle);
  1185. component.off('mousedown', false);
  1186. }
  1187. },
  1188. indexGivenDates = function (givenDatesArray) {
  1189. // Store given enabledDates and disabledDates as keys.
  1190. // This way we can check their existence in O(1) time instead of looping through whole array.
  1191. // (for example: options.enabledDates['2014-02-27'] === true)
  1192. var givenDatesIndexed = {};
  1193. $.each(givenDatesArray, function () {
  1194. var dDate = parseInputDate(this);
  1195. if (dDate.isValid()) {
  1196. givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true;
  1197. }
  1198. });
  1199. return (Object.keys(givenDatesIndexed).length) ? givenDatesIndexed : false;
  1200. },
  1201. indexGivenHours = function (givenHoursArray) {
  1202. // Store given enabledHours and disabledHours as keys.
  1203. // This way we can check their existence in O(1) time instead of looping through whole array.
  1204. // (for example: options.enabledHours['2014-02-27'] === true)
  1205. var givenHoursIndexed = {};
  1206. $.each(givenHoursArray, function () {
  1207. givenHoursIndexed[this] = true;
  1208. });
  1209. return (Object.keys(givenHoursIndexed).length) ? givenHoursIndexed : false;
  1210. },
  1211. initFormatting = function () {
  1212. var format = options.format || 'L LT';
  1213. actualFormat = format.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput) {
  1214. var newinput = date.localeData().longDateFormat(formatInput) || formatInput;
  1215. return newinput.replace(/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, function (formatInput2) { //temp fix for #740
  1216. return date.localeData().longDateFormat(formatInput2) || formatInput2;
  1217. });
  1218. });
  1219. parseFormats = options.extraFormats ? options.extraFormats.slice() : [];
  1220. if (parseFormats.indexOf(format) < 0 && parseFormats.indexOf(actualFormat) < 0) {
  1221. parseFormats.push(actualFormat);
  1222. }
  1223. use24Hours = (actualFormat.toLowerCase().indexOf('a') < 1 && actualFormat.replace(/\[.*?\]/g, '').indexOf('h') < 1);
  1224. if (isEnabled('y')) {
  1225. minViewModeNumber = 2;
  1226. }
  1227. if (isEnabled('M')) {
  1228. minViewModeNumber = 1;
  1229. }
  1230. if (isEnabled('d')) {
  1231. minViewModeNumber = 0;
  1232. }
  1233. currentViewMode = Math.max(minViewModeNumber, currentViewMode);
  1234. if (!unset) {
  1235. setValue(date);
  1236. }
  1237. };
  1238. /********************************************************************************
  1239. *
  1240. * Public API functions
  1241. * =====================
  1242. *
  1243. * Important: Do not expose direct references to private objects or the options
  1244. * object to the outer world. Always return a clone when returning values or make
  1245. * a clone when setting a private variable.
  1246. *
  1247. ********************************************************************************/
  1248. picker.destroy = function () {
  1249. ///<summary>Destroys the widget and removes all attached event listeners</summary>
  1250. hide();
  1251. detachDatePickerElementEvents();
  1252. element.removeData('DateTimePicker');
  1253. element.removeData('date');
  1254. };
  1255. picker.toggle = toggle;
  1256. picker.show = show;
  1257. picker.hide = hide;
  1258. picker.disable = function () {
  1259. ///<summary>Disables the input element, the component is attached to, by adding a disabled="true" attribute to it.
  1260. ///If the widget was visible before that call it is hidden. Possibly emits dp.hide</summary>
  1261. hide();
  1262. if (component && component.hasClass('btn')) {
  1263. component.addClass('disabled');
  1264. }
  1265. input.prop('disabled', true);
  1266. return picker;
  1267. };
  1268. picker.enable = function () {
  1269. ///<summary>Enables the input element, the component is attached to, by removing disabled attribute from it.</summary>
  1270. if (component && component.hasClass('btn')) {
  1271. component.removeClass('disabled');
  1272. }
  1273. input.prop('disabled', false);
  1274. return picker;
  1275. };
  1276. picker.ignoreReadonly = function (ignoreReadonly) {
  1277. if (arguments.length === 0) {
  1278. return options.ignoreReadonly;
  1279. }
  1280. if (typeof ignoreReadonly !== 'boolean') {
  1281. throw new TypeError('ignoreReadonly () expects a boolean parameter');
  1282. }
  1283. options.ignoreReadonly = ignoreReadonly;
  1284. return picker;
  1285. };
  1286. picker.options = function (newOptions) {
  1287. if (arguments.length === 0) {
  1288. return $.extend(true, {}, options);
  1289. }
  1290. if (!(newOptions instanceof Object)) {
  1291. throw new TypeError('options() options parameter should be an object');
  1292. }
  1293. $.extend(true, options, newOptions);
  1294. $.each(options, function (key, value) {
  1295. if (picker[key] !== undefined) {
  1296. picker[key](value);
  1297. } else {
  1298. throw new TypeError('option ' + key + ' is not recognized!');
  1299. }
  1300. });
  1301. return picker;
  1302. };
  1303. picker.date = function (newDate) {
  1304. ///<signature helpKeyword="$.fn.datetimepicker.date">
  1305. ///<summary>Returns the component's model current date, a moment object or null if not set.</summary>
  1306. ///<returns type="Moment">date.clone()</returns>
  1307. ///</signature>
  1308. ///<signature>
  1309. ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary>
  1310. ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, Date, moment, null parameter.</param>
  1311. ///</signature>
  1312. if (arguments.length === 0) {
  1313. if (unset) {
  1314. return null;
  1315. }
  1316. return date.clone();
  1317. }
  1318. if (newDate !== null && typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
  1319. throw new TypeError('date() parameter must be one of [null, string, moment or Date]');
  1320. }
  1321. setValue(newDate === null ? null : parseInputDate(newDate));
  1322. return picker;
  1323. };
  1324. picker.format = function (newFormat) {
  1325. ///<summary>test su</summary>
  1326. ///<param name="newFormat">info about para</param>
  1327. ///<returns type="string|boolean">returns foo</returns>
  1328. if (arguments.length === 0) {
  1329. return options.format;
  1330. }
  1331. if ((typeof newFormat !== 'string') && ((typeof newFormat !== 'boolean') || (newFormat !== false))) {
  1332. throw new TypeError('format() expects a sting or boolean:false parameter ' + newFormat);
  1333. }
  1334. options.format = newFormat;
  1335. if (actualFormat) {
  1336. initFormatting(); // reinit formatting
  1337. }
  1338. return picker;
  1339. };
  1340. picker.timeZone = function (newZone) {
  1341. if (arguments.length === 0) {
  1342. return options.timeZone;
  1343. }
  1344. options.timeZone = newZone;
  1345. return picker;
  1346. };
  1347. picker.dayViewHeaderFormat = function (newFormat) {
  1348. if (arguments.length === 0) {
  1349. return options.dayViewHeaderFormat;
  1350. }
  1351. if (typeof newFormat !== 'string') {
  1352. throw new TypeError('dayViewHeaderFormat() expects a string parameter');
  1353. }
  1354. options.dayViewHeaderFormat = newFormat;
  1355. return picker;
  1356. };
  1357. picker.extraFormats = function (formats) {
  1358. if (arguments.length === 0) {
  1359. return options.extraFormats;
  1360. }
  1361. if (formats !== false && !(formats instanceof Array)) {
  1362. throw new TypeError('extraFormats() expects an array or false parameter');
  1363. }
  1364. options.extraFormats = formats;
  1365. if (parseFormats) {
  1366. initFormatting(); // reinit formatting
  1367. }
  1368. return picker;
  1369. };
  1370. picker.disabledDates = function (dates) {
  1371. ///<signature helpKeyword="$.fn.datetimepicker.disabledDates">
  1372. ///<summary>Returns an array with the currently set disabled dates on the component.</summary>
  1373. ///<returns type="array">options.disabledDates</returns>
  1374. ///</signature>
  1375. ///<signature>
  1376. ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
  1377. ///options.enabledDates if such exist.</summary>
  1378. ///<param name="dates" locid="$.fn.datetimepicker.disabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
  1379. ///</signature>
  1380. if (arguments.length === 0) {
  1381. return (options.disabledDates ? $.extend({}, options.disabledDates) : options.disabledDates);
  1382. }
  1383. if (!dates) {
  1384. options.disabledDates = false;
  1385. update();
  1386. return picker;
  1387. }
  1388. if (!(dates instanceof Array)) {
  1389. throw new TypeError('disabledDates() expects an array parameter');
  1390. }
  1391. options.disabledDates = indexGivenDates(dates);
  1392. options.enabledDates = false;
  1393. update();
  1394. return picker;
  1395. };
  1396. picker.enabledDates = function (dates) {
  1397. ///<signature helpKeyword="$.fn.datetimepicker.enabledDates">
  1398. ///<summary>Returns an array with the currently set enabled dates on the component.</summary>
  1399. ///<returns type="array">options.enabledDates</returns>
  1400. ///</signature>
  1401. ///<signature>
  1402. ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledDates if such exist.</summary>
  1403. ///<param name="dates" locid="$.fn.datetimepicker.enabledDates_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
  1404. ///</signature>
  1405. if (arguments.length === 0) {
  1406. return (options.enabledDates ? $.extend({}, options.enabledDates) : options.enabledDates);
  1407. }
  1408. if (!dates) {
  1409. options.enabledDates = false;
  1410. update();
  1411. return picker;
  1412. }
  1413. if (!(dates instanceof Array)) {
  1414. throw new TypeError('enabledDates() expects an array parameter');
  1415. }
  1416. options.enabledDates = indexGivenDates(dates);
  1417. options.disabledDates = false;
  1418. update();
  1419. return picker;
  1420. };
  1421. picker.daysOfWeekDisabled = function (daysOfWeekDisabled) {
  1422. if (arguments.length === 0) {
  1423. return options.daysOfWeekDisabled.splice(0);
  1424. }
  1425. if ((typeof daysOfWeekDisabled === 'boolean') && !daysOfWeekDisabled) {
  1426. options.daysOfWeekDisabled = false;
  1427. update();
  1428. return picker;
  1429. }
  1430. if (!(daysOfWeekDisabled instanceof Array)) {
  1431. throw new TypeError('daysOfWeekDisabled() expects an array parameter');
  1432. }
  1433. options.daysOfWeekDisabled = daysOfWeekDisabled.reduce(function (previousValue, currentValue) {
  1434. currentValue = parseInt(currentValue, 10);
  1435. if (currentValue > 6 || currentValue < 0 || isNaN(currentValue)) {
  1436. return previousValue;
  1437. }
  1438. if (previousValue.indexOf(currentValue) === -1) {
  1439. previousValue.push(currentValue);
  1440. }
  1441. return previousValue;
  1442. }, []).sort();
  1443. if (options.useCurrent && !options.keepInvalid) {
  1444. var tries = 0;
  1445. while (!isValid(date, 'd')) {
  1446. date.add(1, 'd');
  1447. if (tries === 7) {
  1448. throw 'Tried 7 times to find a valid date';
  1449. }
  1450. tries++;
  1451. }
  1452. setValue(date);
  1453. }
  1454. update();
  1455. return picker;
  1456. };
  1457. picker.maxDate = function (maxDate) {
  1458. if (arguments.length === 0) {
  1459. return options.maxDate ? options.maxDate.clone() : options.maxDate;
  1460. }
  1461. if ((typeof maxDate === 'boolean') && maxDate === false) {
  1462. options.maxDate = false;
  1463. update();
  1464. return picker;
  1465. }
  1466. if (typeof maxDate === 'string') {
  1467. if (maxDate === 'now' || maxDate === 'moment') {
  1468. maxDate = getMoment();
  1469. }
  1470. }
  1471. var parsedDate = parseInputDate(maxDate);
  1472. if (!parsedDate.isValid()) {
  1473. throw new TypeError('maxDate() Could not parse date parameter: ' + maxDate);
  1474. }
  1475. if (options.minDate && parsedDate.isBefore(options.minDate)) {
  1476. throw new TypeError('maxDate() date parameter is before options.minDate: ' + parsedDate.format(actualFormat));
  1477. }
  1478. options.maxDate = parsedDate;
  1479. if (options.useCurrent && !options.keepInvalid && date.isAfter(maxDate)) {
  1480. setValue(options.maxDate);
  1481. }
  1482. if (viewDate.isAfter(parsedDate)) {
  1483. viewDate = parsedDate.clone().subtract(options.stepping, 'm');
  1484. }
  1485. update();
  1486. return picker;
  1487. };
  1488. picker.minDate = function (minDate) {
  1489. if (arguments.length === 0) {
  1490. return options.minDate ? options.minDate.clone() : options.minDate;
  1491. }
  1492. if ((typeof minDate === 'boolean') && minDate === false) {
  1493. options.minDate = false;
  1494. update();
  1495. return picker;
  1496. }
  1497. if (typeof minDate === 'string') {
  1498. if (minDate === 'now' || minDate === 'moment') {
  1499. minDate = getMoment();
  1500. }
  1501. }
  1502. var parsedDate = parseInputDate(minDate);
  1503. if (!parsedDate.isValid()) {
  1504. throw new TypeError('minDate() Could not parse date parameter: ' + minDate);
  1505. }
  1506. if (options.maxDate && parsedDate.isAfter(options.maxDate)) {
  1507. throw new TypeError('minDate() date parameter is after options.maxDate: ' + parsedDate.format(actualFormat));
  1508. }
  1509. options.minDate = parsedDate;
  1510. if (options.useCurrent && !options.keepInvalid && date.isBefore(minDate)) {
  1511. setValue(options.minDate);
  1512. }
  1513. if (viewDate.isBefore(parsedDate)) {
  1514. viewDate = parsedDate.clone().add(options.stepping, 'm');
  1515. }
  1516. update();
  1517. return picker;
  1518. };
  1519. picker.defaultDate = function (defaultDate) {
  1520. ///<signature helpKeyword="$.fn.datetimepicker.defaultDate">
  1521. ///<summary>Returns a moment with the options.defaultDate option configuration or false if not set</summary>
  1522. ///<returns type="Moment">date.clone()</returns>
  1523. ///</signature>
  1524. ///<signature>
  1525. ///<summary>Will set the picker's inital date. If a boolean:false value is passed the options.defaultDate parameter is cleared.</summary>
  1526. ///<param name="defaultDate" locid="$.fn.datetimepicker.defaultDate_p:defaultDate">Takes a string, Date, moment, boolean:false</param>
  1527. ///</signature>
  1528. if (arguments.length === 0) {
  1529. return options.defaultDate ? options.defaultDate.clone() : options.defaultDate;
  1530. }
  1531. if (!defaultDate) {
  1532. options.defaultDate = false;
  1533. return picker;
  1534. }
  1535. if (typeof defaultDate === 'string') {
  1536. if (defaultDate === 'now' || defaultDate === 'moment') {
  1537. defaultDate = getMoment();
  1538. }
  1539. }
  1540. var parsedDate = parseInputDate(defaultDate);
  1541. if (!parsedDate.isValid()) {
  1542. throw new TypeError('defaultDate() Could not parse date parameter: ' + defaultDate);
  1543. }
  1544. if (!isValid(parsedDate)) {
  1545. throw new TypeError('defaultDate() date passed is invalid according to component setup validations');
  1546. }
  1547. options.defaultDate = parsedDate;
  1548. if ((options.defaultDate && options.inline) || input.val().trim() === '') {
  1549. setValue(options.defaultDate);
  1550. }
  1551. return picker;
  1552. };
  1553. picker.locale = function (locale) {
  1554. if (arguments.length === 0) {
  1555. return options.locale;
  1556. }
  1557. if (!moment.localeData(locale)) {
  1558. throw new TypeError('locale() locale ' + locale + ' is not loaded from moment locales!');
  1559. }
  1560. options.locale = locale;
  1561. date.locale(options.locale);
  1562. viewDate.locale(options.locale);
  1563. if (actualFormat) {
  1564. initFormatting(); // reinit formatting
  1565. }
  1566. if (widget) {
  1567. hide();
  1568. show();
  1569. }
  1570. return picker;
  1571. };
  1572. picker.stepping = function (stepping) {
  1573. if (arguments.length === 0) {
  1574. return options.stepping;
  1575. }
  1576. stepping = parseInt(stepping, 10);
  1577. if (isNaN(stepping) || stepping < 1) {
  1578. stepping = 1;
  1579. }
  1580. options.stepping = stepping;
  1581. return picker;
  1582. };
  1583. picker.useCurrent = function (useCurrent) {
  1584. var useCurrentOptions = ['year', 'month', 'day', 'hour', 'minute'];
  1585. if (arguments.length === 0) {
  1586. return options.useCurrent;
  1587. }
  1588. if ((typeof useCurrent !== 'boolean') && (typeof useCurrent !== 'string')) {
  1589. throw new TypeError('useCurrent() expects a boolean or string parameter');
  1590. }
  1591. if (typeof useCurrent === 'string' && useCurrentOptions.indexOf(useCurrent.toLowerCase()) === -1) {
  1592. throw new TypeError('useCurrent() expects a string parameter of ' + useCurrentOptions.join(', '));
  1593. }
  1594. options.useCurrent = useCurrent;
  1595. return picker;
  1596. };
  1597. picker.collapse = function (collapse) {
  1598. if (arguments.length === 0) {
  1599. return options.collapse;
  1600. }
  1601. if (typeof collapse !== 'boolean') {
  1602. throw new TypeError('collapse() expects a boolean parameter');
  1603. }
  1604. if (options.collapse === collapse) {
  1605. return picker;
  1606. }
  1607. options.collapse = collapse;
  1608. if (widget) {
  1609. hide();
  1610. show();
  1611. }
  1612. return picker;
  1613. };
  1614. picker.icons = function (icons) {
  1615. if (arguments.length === 0) {
  1616. return $.extend({}, options.icons);
  1617. }
  1618. if (!(icons instanceof Object)) {
  1619. throw new TypeError('icons() expects parameter to be an Object');
  1620. }
  1621. $.extend(options.icons, icons);
  1622. if (widget) {
  1623. hide();
  1624. show();
  1625. }
  1626. return picker;
  1627. };
  1628. picker.tooltips = function (tooltips) {
  1629. if (arguments.length === 0) {
  1630. return $.extend({}, options.tooltips);
  1631. }
  1632. if (!(tooltips instanceof Object)) {
  1633. throw new TypeError('tooltips() expects parameter to be an Object');
  1634. }
  1635. $.extend(options.tooltips, tooltips);
  1636. if (widget) {
  1637. hide();
  1638. show();
  1639. }
  1640. return picker;
  1641. };
  1642. picker.useStrict = function (useStrict) {
  1643. if (arguments.length === 0) {
  1644. return options.useStrict;
  1645. }
  1646. if (typeof useStrict !== 'boolean') {
  1647. throw new TypeError('useStrict() expects a boolean parameter');
  1648. }
  1649. options.useStrict = useStrict;
  1650. return picker;
  1651. };
  1652. picker.sideBySide = function (sideBySide) {
  1653. if (arguments.length === 0) {
  1654. return options.sideBySide;
  1655. }
  1656. if (typeof sideBySide !== 'boolean') {
  1657. throw new TypeError('sideBySide() expects a boolean parameter');
  1658. }
  1659. options.sideBySide = sideBySide;
  1660. if (widget) {
  1661. hide();
  1662. show();
  1663. }
  1664. return picker;
  1665. };
  1666. picker.viewMode = function (viewMode) {
  1667. if (arguments.length === 0) {
  1668. return options.viewMode;
  1669. }
  1670. if (typeof viewMode !== 'string') {
  1671. throw new TypeError('viewMode() expects a string parameter');
  1672. }
  1673. if (viewModes.indexOf(viewMode) === -1) {
  1674. throw new TypeError('viewMode() parameter must be one of (' + viewModes.join(', ') + ') value');
  1675. }
  1676. options.viewMode = viewMode;
  1677. currentViewMode = Math.max(viewModes.indexOf(viewMode), minViewModeNumber);
  1678. showMode();
  1679. return picker;
  1680. };
  1681. picker.toolbarPlacement = function (toolbarPlacement) {
  1682. if (arguments.length === 0) {
  1683. return options.toolbarPlacement;
  1684. }
  1685. if (typeof toolbarPlacement !== 'string') {
  1686. throw new TypeError('toolbarPlacement() expects a string parameter');
  1687. }
  1688. if (toolbarPlacements.indexOf(toolbarPlacement) === -1) {
  1689. throw new TypeError('toolbarPlacement() parameter must be one of (' + toolbarPlacements.join(', ') + ') value');
  1690. }
  1691. options.toolbarPlacement = toolbarPlacement;
  1692. if (widget) {
  1693. hide();
  1694. show();
  1695. }
  1696. return picker;
  1697. };
  1698. picker.widgetPositioning = function (widgetPositioning) {
  1699. if (arguments.length === 0) {
  1700. return $.extend({}, options.widgetPositioning);
  1701. }
  1702. if (({}).toString.call(widgetPositioning) !== '[object Object]') {
  1703. throw new TypeError('widgetPositioning() expects an object variable');
  1704. }
  1705. if (widgetPositioning.horizontal) {
  1706. if (typeof widgetPositioning.horizontal !== 'string') {
  1707. throw new TypeError('widgetPositioning() horizontal variable must be a string');
  1708. }
  1709. widgetPositioning.horizontal = widgetPositioning.horizontal.toLowerCase();
  1710. if (horizontalModes.indexOf(widgetPositioning.horizontal) === -1) {
  1711. throw new TypeError('widgetPositioning() expects horizontal parameter to be one of (' + horizontalModes.join(', ') + ')');
  1712. }
  1713. options.widgetPositioning.horizontal = widgetPositioning.horizontal;
  1714. }
  1715. if (widgetPositioning.vertical) {
  1716. if (typeof widgetPositioning.vertical !== 'string') {
  1717. throw new TypeError('widgetPositioning() vertical variable must be a string');
  1718. }
  1719. widgetPositioning.vertical = widgetPositioning.vertical.toLowerCase();
  1720. if (verticalModes.indexOf(widgetPositioning.vertical) === -1) {
  1721. throw new TypeError('widgetPositioning() expects vertical parameter to be one of (' + verticalModes.join(', ') + ')');
  1722. }
  1723. options.widgetPositioning.vertical = widgetPositioning.vertical;
  1724. }
  1725. update();
  1726. return picker;
  1727. };
  1728. picker.calendarWeeks = function (calendarWeeks) {
  1729. if (arguments.length === 0) {
  1730. return options.calendarWeeks;
  1731. }
  1732. if (typeof calendarWeeks !== 'boolean') {
  1733. throw new TypeError('calendarWeeks() expects parameter to be a boolean value');
  1734. }
  1735. options.calendarWeeks = calendarWeeks;
  1736. update();
  1737. return picker;
  1738. };
  1739. picker.showTodayButton = function (showTodayButton) {
  1740. if (arguments.length === 0) {
  1741. return options.showTodayButton;
  1742. }
  1743. if (typeof showTodayButton !== 'boolean') {
  1744. throw new TypeError('showTodayButton() expects a boolean parameter');
  1745. }
  1746. options.showTodayButton = showTodayButton;
  1747. if (widget) {
  1748. hide();
  1749. show();
  1750. }
  1751. return picker;
  1752. };
  1753. picker.showClear = function (showClear) {
  1754. if (arguments.length === 0) {
  1755. return options.showClear;
  1756. }
  1757. if (typeof showClear !== 'boolean') {
  1758. throw new TypeError('showClear() expects a boolean parameter');
  1759. }
  1760. options.showClear = showClear;
  1761. if (widget) {
  1762. hide();
  1763. show();
  1764. }
  1765. return picker;
  1766. };
  1767. picker.widgetParent = function (widgetParent) {
  1768. if (arguments.length === 0) {
  1769. return options.widgetParent;
  1770. }
  1771. if (typeof widgetParent === 'string') {
  1772. widgetParent = $(widgetParent);
  1773. }
  1774. if (widgetParent !== null && (typeof widgetParent !== 'string' && !(widgetParent instanceof $))) {
  1775. throw new TypeError('widgetParent() expects a string or a jQuery object parameter');
  1776. }
  1777. options.widgetParent = widgetParent;
  1778. if (widget) {
  1779. hide();
  1780. show();
  1781. }
  1782. return picker;
  1783. };
  1784. picker.keepOpen = function (keepOpen) {
  1785. if (arguments.length === 0) {
  1786. return options.keepOpen;
  1787. }
  1788. if (typeof keepOpen !== 'boolean') {
  1789. throw new TypeError('keepOpen() expects a boolean parameter');
  1790. }
  1791. options.keepOpen = keepOpen;
  1792. return picker;
  1793. };
  1794. picker.focusOnShow = function (focusOnShow) {
  1795. if (arguments.length === 0) {
  1796. return options.focusOnShow;
  1797. }
  1798. if (typeof focusOnShow !== 'boolean') {
  1799. throw new TypeError('focusOnShow() expects a boolean parameter');
  1800. }
  1801. options.focusOnShow = focusOnShow;
  1802. return picker;
  1803. };
  1804. picker.inline = function (inline) {
  1805. if (arguments.length === 0) {
  1806. return options.inline;
  1807. }
  1808. if (typeof inline !== 'boolean') {
  1809. throw new TypeError('inline() expects a boolean parameter');
  1810. }
  1811. options.inline = inline;
  1812. return picker;
  1813. };
  1814. picker.clear = function () {
  1815. clear();
  1816. return picker;
  1817. };
  1818. picker.keyBinds = function (keyBinds) {
  1819. options.keyBinds = keyBinds;
  1820. return picker;
  1821. };
  1822. picker.getMoment = function (d) {
  1823. return getMoment(d);
  1824. };
  1825. picker.debug = function (debug) {
  1826. if (typeof debug !== 'boolean') {
  1827. throw new TypeError('debug() expects a boolean parameter');
  1828. }
  1829. options.debug = debug;
  1830. return picker;
  1831. };
  1832. picker.allowInputToggle = function (allowInputToggle) {
  1833. if (arguments.length === 0) {
  1834. return options.allowInputToggle;
  1835. }
  1836. if (typeof allowInputToggle !== 'boolean') {
  1837. throw new TypeError('allowInputToggle() expects a boolean parameter');
  1838. }
  1839. options.allowInputToggle = allowInputToggle;
  1840. return picker;
  1841. };
  1842. picker.showClose = function (showClose) {
  1843. if (arguments.length === 0) {
  1844. return options.showClose;
  1845. }
  1846. if (typeof showClose !== 'boolean') {
  1847. throw new TypeError('showClose() expects a boolean parameter');
  1848. }
  1849. options.showClose = showClose;
  1850. return picker;
  1851. };
  1852. picker.keepInvalid = function (keepInvalid) {
  1853. if (arguments.length === 0) {
  1854. return options.keepInvalid;
  1855. }
  1856. if (typeof keepInvalid !== 'boolean') {
  1857. throw new TypeError('keepInvalid() expects a boolean parameter');
  1858. }
  1859. options.keepInvalid = keepInvalid;
  1860. return picker;
  1861. };
  1862. picker.datepickerInput = function (datepickerInput) {
  1863. if (arguments.length === 0) {
  1864. return options.datepickerInput;
  1865. }
  1866. if (typeof datepickerInput !== 'string') {
  1867. throw new TypeError('datepickerInput() expects a string parameter');
  1868. }
  1869. options.datepickerInput = datepickerInput;
  1870. return picker;
  1871. };
  1872. picker.parseInputDate = function (parseInputDate) {
  1873. if (arguments.length === 0) {
  1874. return options.parseInputDate;
  1875. }
  1876. if (typeof parseInputDate !== 'function') {
  1877. throw new TypeError('parseInputDate() sholud be as function');
  1878. }
  1879. options.parseInputDate = parseInputDate;
  1880. return picker;
  1881. };
  1882. picker.disabledTimeIntervals = function (disabledTimeIntervals) {
  1883. ///<signature helpKeyword="$.fn.datetimepicker.disabledTimeIntervals">
  1884. ///<summary>Returns an array with the currently set disabled dates on the component.</summary>
  1885. ///<returns type="array">options.disabledTimeIntervals</returns>
  1886. ///</signature>
  1887. ///<signature>
  1888. ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
  1889. ///options.enabledDates if such exist.</summary>
  1890. ///<param name="dates" locid="$.fn.datetimepicker.disabledTimeIntervals_p:dates">Takes an [ string or Date or moment ] of values and allows the user to select only from those days.</param>
  1891. ///</signature>
  1892. if (arguments.length === 0) {
  1893. return (options.disabledTimeIntervals ? $.extend({}, options.disabledTimeIntervals) : options.disabledTimeIntervals);
  1894. }
  1895. if (!disabledTimeIntervals) {
  1896. options.disabledTimeIntervals = false;
  1897. update();
  1898. return picker;
  1899. }
  1900. if (!(disabledTimeIntervals instanceof Array)) {
  1901. throw new TypeError('disabledTimeIntervals() expects an array parameter');
  1902. }
  1903. options.disabledTimeIntervals = disabledTimeIntervals;
  1904. update();
  1905. return picker;
  1906. };
  1907. picker.disabledHours = function (hours) {
  1908. ///<signature helpKeyword="$.fn.datetimepicker.disabledHours">
  1909. ///<summary>Returns an array with the currently set disabled hours on the component.</summary>
  1910. ///<returns type="array">options.disabledHours</returns>
  1911. ///</signature>
  1912. ///<signature>
  1913. ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of
  1914. ///options.enabledHours if such exist.</summary>
  1915. ///<param name="hours" locid="$.fn.datetimepicker.disabledHours_p:hours">Takes an [ int ] of values and disallows the user to select only from those hours.</param>
  1916. ///</signature>
  1917. if (arguments.length === 0) {
  1918. return (options.disabledHours ? $.extend({}, options.disabledHours) : options.disabledHours);
  1919. }
  1920. if (!hours) {
  1921. options.disabledHours = false;
  1922. update();
  1923. return picker;
  1924. }
  1925. if (!(hours instanceof Array)) {
  1926. throw new TypeError('disabledHours() expects an array parameter');
  1927. }
  1928. options.disabledHours = indexGivenHours(hours);
  1929. options.enabledHours = false;
  1930. if (options.useCurrent && !options.keepInvalid) {
  1931. var tries = 0;
  1932. while (!isValid(date, 'h')) {
  1933. date.add(1, 'h');
  1934. if (tries === 24) {
  1935. throw 'Tried 24 times to find a valid date';
  1936. }
  1937. tries++;
  1938. }
  1939. setValue(date);
  1940. }
  1941. update();
  1942. return picker;
  1943. };
  1944. picker.enabledHours = function (hours) {
  1945. ///<signature helpKeyword="$.fn.datetimepicker.enabledHours">
  1946. ///<summary>Returns an array with the currently set enabled hours on the component.</summary>
  1947. ///<returns type="array">options.enabledHours</returns>
  1948. ///</signature>
  1949. ///<signature>
  1950. ///<summary>Setting this takes precedence over options.minDate, options.maxDate configuration. Also calling this function removes the configuration of options.disabledHours if such exist.</summary>
  1951. ///<param name="hours" locid="$.fn.datetimepicker.enabledHours_p:hours">Takes an [ int ] of values and allows the user to select only from those hours.</param>
  1952. ///</signature>
  1953. if (arguments.length === 0) {
  1954. return (options.enabledHours ? $.extend({}, options.enabledHours) : options.enabledHours);
  1955. }
  1956. if (!hours) {
  1957. options.enabledHours = false;
  1958. update();
  1959. return picker;
  1960. }
  1961. if (!(hours instanceof Array)) {
  1962. throw new TypeError('enabledHours() expects an array parameter');
  1963. }
  1964. options.enabledHours = indexGivenHours(hours);
  1965. options.disabledHours = false;
  1966. if (options.useCurrent && !options.keepInvalid) {
  1967. var tries = 0;
  1968. while (!isValid(date, 'h')) {
  1969. date.add(1, 'h');
  1970. if (tries === 24) {
  1971. throw 'Tried 24 times to find a valid date';
  1972. }
  1973. tries++;
  1974. }
  1975. setValue(date);
  1976. }
  1977. update();
  1978. return picker;
  1979. };
  1980. picker.viewDate = function (newDate) {
  1981. ///<signature helpKeyword="$.fn.datetimepicker.viewDate">
  1982. ///<summary>Returns the component's model current viewDate, a moment object or null if not set.</summary>
  1983. ///<returns type="Moment">viewDate.clone()</returns>
  1984. ///</signature>
  1985. ///<signature>
  1986. ///<summary>Sets the components model current moment to it. Passing a null value unsets the components model current moment. Parsing of the newDate parameter is made using moment library with the options.format and options.useStrict components configuration.</summary>
  1987. ///<param name="newDate" locid="$.fn.datetimepicker.date_p:newDate">Takes string, viewDate, moment, null parameter.</param>
  1988. ///</signature>
  1989. if (arguments.length === 0) {
  1990. return viewDate.clone();
  1991. }
  1992. if (!newDate) {
  1993. viewDate = date.clone();
  1994. return picker;
  1995. }
  1996. if (typeof newDate !== 'string' && !moment.isMoment(newDate) && !(newDate instanceof Date)) {
  1997. throw new TypeError('viewDate() parameter must be one of [string, moment or Date]');
  1998. }
  1999. viewDate = parseInputDate(newDate);
  2000. viewUpdate();
  2001. return picker;
  2002. };
  2003. // initializing element and component attributes
  2004. if (element.is('input')) {
  2005. input = element;
  2006. } else {
  2007. input = element.find(options.datepickerInput);
  2008. if (input.size() === 0) {
  2009. input = element.find('input');
  2010. } else if (!input.is('input')) {
  2011. throw new Error('CSS class "' + options.datepickerInput + '" cannot be applied to non input element');
  2012. }
  2013. }
  2014. if (element.hasClass('input-group')) {
  2015. // in case there is more then one 'input-group-addon' Issue #48
  2016. if (element.find('.datepickerbutton').size() === 0) {
  2017. component = element.find('.input-group-addon');
  2018. } else {
  2019. component = element.find('.datepickerbutton');
  2020. }
  2021. }
  2022. if (!options.inline && !input.is('input')) {
  2023. throw new Error('Could not initialize DateTimePicker without an input element');
  2024. }
  2025. // Set defaults for date here now instead of in var declaration
  2026. date = getMoment();
  2027. viewDate = date.clone();
  2028. $.extend(true, options, dataToOptions());
  2029. picker.options(options);
  2030. initFormatting();
  2031. attachDatePickerElementEvents();
  2032. if (input.prop('disabled')) {
  2033. picker.disable();
  2034. }
  2035. if (input.is('input') && input.val().trim().length !== 0) {
  2036. setValue(parseInputDate(input.val().trim()));
  2037. }
  2038. else if (options.defaultDate && input.attr('placeholder') === undefined) {
  2039. setValue(options.defaultDate);
  2040. }
  2041. if (options.inline) {
  2042. show();
  2043. }
  2044. return picker;
  2045. };
  2046. /********************************************************************************
  2047. *
  2048. * jQuery plugin constructor and defaults object
  2049. *
  2050. ********************************************************************************/
  2051. $.fn.datetimepicker = function (options) {
  2052. return this.each(function () {
  2053. var $this = $(this);
  2054. if (!$this.data('DateTimePicker')) {
  2055. // create a private copy of the defaults object
  2056. options = $.extend(true, {}, $.fn.datetimepicker.defaults, options);
  2057. $this.data('DateTimePicker', dateTimePicker($this, options));
  2058. }
  2059. });
  2060. };
  2061. $.fn.datetimepicker.defaults = {
  2062. timeZone: 'Etc/UTC',
  2063. format: false,
  2064. dayViewHeaderFormat: 'MMMM YYYY',
  2065. extraFormats: false,
  2066. stepping: 1,
  2067. minDate: false,
  2068. maxDate: false,
  2069. useCurrent: true,
  2070. collapse: true,
  2071. locale: moment.locale(),
  2072. defaultDate: false,
  2073. disabledDates: false,
  2074. enabledDates: false,
  2075. icons: {
  2076. time: 'mdi mdi-clock',
  2077. date: 'mdi mdi-calendar',
  2078. up: 'mdi mdi-chevron-up',
  2079. down: 'mdi mdi-chevron-down',
  2080. previous: 'mdi mdi-chevron-left',
  2081. next: 'mdi mdi-chevron-right',
  2082. today: 'mdi mdi-crosshairs-gps',
  2083. clear: 'mdi mdi-delete',
  2084. close: 'mdi mdi-close'
  2085. },
  2086. tooltips: {
  2087. today: 'Go to today',
  2088. clear: 'Clear selection',
  2089. close: 'Close the picker',
  2090. selectMonth: 'Select Month',
  2091. prevMonth: 'Previous Month',
  2092. nextMonth: 'Next Month',
  2093. selectYear: 'Select Year',
  2094. prevYear: 'Previous Year',
  2095. nextYear: 'Next Year',
  2096. selectDecade: 'Select Decade',
  2097. prevDecade: 'Previous Decade',
  2098. nextDecade: 'Next Decade',
  2099. prevCentury: 'Previous Century',
  2100. nextCentury: 'Next Century',
  2101. pickHour: 'Pick Hour',
  2102. incrementHour: 'Increment Hour',
  2103. decrementHour: 'Decrement Hour',
  2104. pickMinute: 'Pick Minute',
  2105. incrementMinute: 'Increment Minute',
  2106. decrementMinute: 'Decrement Minute',
  2107. pickSecond: 'Pick Second',
  2108. incrementSecond: 'Increment Second',
  2109. decrementSecond: 'Decrement Second',
  2110. togglePeriod: 'Toggle Period',
  2111. selectTime: 'Select Time'
  2112. },
  2113. useStrict: false,
  2114. sideBySide: false,
  2115. daysOfWeekDisabled: false,
  2116. calendarWeeks: false,
  2117. viewMode: 'days',
  2118. toolbarPlacement: 'default',
  2119. showTodayButton: false,
  2120. showClear: false,
  2121. showClose: false,
  2122. widgetPositioning: {
  2123. horizontal: 'auto',
  2124. vertical: 'auto'
  2125. },
  2126. widgetParent: null,
  2127. ignoreReadonly: false,
  2128. keepOpen: false,
  2129. focusOnShow: true,
  2130. inline: false,
  2131. keepInvalid: false,
  2132. datepickerInput: '.datepickerinput',
  2133. keyBinds: {
  2134. up: function (widget) {
  2135. if (!widget) {
  2136. return;
  2137. }
  2138. var d = this.date() || this.getMoment();
  2139. if (widget.find('.datepicker').is(':visible')) {
  2140. this.date(d.clone().subtract(7, 'd'));
  2141. } else {
  2142. this.date(d.clone().add(this.stepping(), 'm'));
  2143. }
  2144. },
  2145. down: function (widget) {
  2146. if (!widget) {
  2147. this.show();
  2148. return;
  2149. }
  2150. var d = this.date() || this.getMoment();
  2151. if (widget.find('.datepicker').is(':visible')) {
  2152. this.date(d.clone().add(7, 'd'));
  2153. } else {
  2154. this.date(d.clone().subtract(this.stepping(), 'm'));
  2155. }
  2156. },
  2157. 'control up': function (widget) {
  2158. if (!widget) {
  2159. return;
  2160. }
  2161. var d = this.date() || this.getMoment();
  2162. if (widget.find('.datepicker').is(':visible')) {
  2163. this.date(d.clone().subtract(1, 'y'));
  2164. } else {
  2165. this.date(d.clone().add(1, 'h'));
  2166. }
  2167. },
  2168. 'control down': function (widget) {
  2169. if (!widget) {
  2170. return;
  2171. }
  2172. var d = this.date() || this.getMoment();
  2173. if (widget.find('.datepicker').is(':visible')) {
  2174. this.date(d.clone().add(1, 'y'));
  2175. } else {
  2176. this.date(d.clone().subtract(1, 'h'));
  2177. }
  2178. },
  2179. left: function (widget) {
  2180. if (!widget) {
  2181. return;
  2182. }
  2183. var d = this.date() || this.getMoment();
  2184. if (widget.find('.datepicker').is(':visible')) {
  2185. this.date(d.clone().subtract(1, 'd'));
  2186. }
  2187. },
  2188. right: function (widget) {
  2189. if (!widget) {
  2190. return;
  2191. }
  2192. var d = this.date() || this.getMoment();
  2193. if (widget.find('.datepicker').is(':visible')) {
  2194. this.date(d.clone().add(1, 'd'));
  2195. }
  2196. },
  2197. pageUp: function (widget) {
  2198. if (!widget) {
  2199. return;
  2200. }
  2201. var d = this.date() || this.getMoment();
  2202. if (widget.find('.datepicker').is(':visible')) {
  2203. this.date(d.clone().subtract(1, 'M'));
  2204. }
  2205. },
  2206. pageDown: function (widget) {
  2207. if (!widget) {
  2208. return;
  2209. }
  2210. var d = this.date() || this.getMoment();
  2211. if (widget.find('.datepicker').is(':visible')) {
  2212. this.date(d.clone().add(1, 'M'));
  2213. }
  2214. },
  2215. enter: function () {
  2216. this.hide();
  2217. },
  2218. escape: function () {
  2219. this.hide();
  2220. },
  2221. //tab: function (widget) { //this break the flow of the form. disabling for now
  2222. // var toggle = widget.find('.picker-switch a[data-action="togglePicker"]');
  2223. // if(toggle.length > 0) toggle.click();
  2224. //},
  2225. 'control space': function (widget) {
  2226. if (widget.find('.timepicker').is(':visible')) {
  2227. widget.find('.btn[data-action="togglePeriod"]').click();
  2228. }
  2229. },
  2230. t: function () {
  2231. this.date(this.getMoment());
  2232. },
  2233. 'delete': function () {
  2234. this.clear();
  2235. }
  2236. },
  2237. debug: false,
  2238. allowInputToggle: false,
  2239. disabledTimeIntervals: false,
  2240. disabledHours: false,
  2241. enabledHours: false,
  2242. viewDate: false
  2243. };
  2244. }));