jquery-ui-timepicker-addon.js 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103
  1. /*
  2. * jQuery timepicker addon
  3. * By: Trent Richardson [http://trentrichardson.com]
  4. * Version 1.3
  5. * Last Modified: 05/05/2013
  6. *
  7. * Copyright 2013 Trent Richardson
  8. * You may use this project under MIT or GPL licenses.
  9. * http://trentrichardson.com/Impromptu/GPL-LICENSE.txt
  10. * http://trentrichardson.com/Impromptu/MIT-LICENSE.txt
  11. */
  12. /*jslint evil: true, white: false, undef: false, nomen: false */
  13. (function($) {
  14. /*
  15. * Lets not redefine timepicker, Prevent "Uncaught RangeError: Maximum call stack size exceeded"
  16. */
  17. $.ui.timepicker = $.ui.timepicker || {};
  18. if ($.ui.timepicker.version) {
  19. return;
  20. }
  21. /*
  22. * Extend jQueryUI, get it started with our version number
  23. */
  24. $.extend($.ui, {
  25. timepicker: {
  26. version: "1.3"
  27. }
  28. });
  29. /*
  30. * Timepicker manager.
  31. * Use the singleton instance of this class, $.timepicker, to interact with the time picker.
  32. * Settings for (groups of) time pickers are maintained in an instance object,
  33. * allowing multiple different settings on the same page.
  34. */
  35. var Timepicker = function() {
  36. this.regional = []; // Available regional settings, indexed by language code
  37. this.regional[''] = { // Default regional settings
  38. currentText: 'Now',
  39. closeText: 'Done',
  40. amNames: ['AM', 'A'],
  41. pmNames: ['PM', 'P'],
  42. timeFormat: 'HH:mm',
  43. timeSuffix: '',
  44. timeOnlyTitle: 'Choose Time',
  45. timeText: 'Time',
  46. hourText: 'Hour',
  47. minuteText: 'Minute',
  48. secondText: 'Second',
  49. millisecText: 'Millisecond',
  50. microsecText: 'Microsecond',
  51. timezoneText: 'Time Zone',
  52. isRTL: false
  53. };
  54. this._defaults = { // Global defaults for all the datetime picker instances
  55. showButtonPanel: true,
  56. timeOnly: false,
  57. showHour: null,
  58. showMinute: null,
  59. showSecond: null,
  60. showMillisec: null,
  61. showMicrosec: null,
  62. showTimezone: null,
  63. showTime: true,
  64. stepHour: 1,
  65. stepMinute: 1,
  66. stepSecond: 1,
  67. stepMillisec: 1,
  68. stepMicrosec: 1,
  69. hour: 0,
  70. minute: 0,
  71. second: 0,
  72. millisec: 0,
  73. microsec: 0,
  74. timezone: null,
  75. hourMin: 0,
  76. minuteMin: 0,
  77. secondMin: 0,
  78. millisecMin: 0,
  79. microsecMin: 0,
  80. hourMax: 23,
  81. minuteMax: 59,
  82. secondMax: 59,
  83. millisecMax: 999,
  84. microsecMax: 999,
  85. minDateTime: null,
  86. maxDateTime: null,
  87. onSelect: null,
  88. hourGrid: 0,
  89. minuteGrid: 0,
  90. secondGrid: 0,
  91. millisecGrid: 0,
  92. microsecGrid: 0,
  93. alwaysSetTime: true,
  94. separator: ' ',
  95. altFieldTimeOnly: true,
  96. altTimeFormat: null,
  97. altSeparator: null,
  98. altTimeSuffix: null,
  99. pickerTimeFormat: null,
  100. pickerTimeSuffix: null,
  101. showTimepicker: true,
  102. timezoneList: null,
  103. addSliderAccess: false,
  104. sliderAccessArgs: null,
  105. controlType: 'slider',
  106. defaultValue: null,
  107. parse: 'strict'
  108. };
  109. $.extend(this._defaults, this.regional['']);
  110. };
  111. $.extend(Timepicker.prototype, {
  112. $input: null,
  113. $altInput: null,
  114. $timeObj: null,
  115. inst: null,
  116. hour_slider: null,
  117. minute_slider: null,
  118. second_slider: null,
  119. millisec_slider: null,
  120. microsec_slider: null,
  121. timezone_select: null,
  122. hour: 0,
  123. minute: 0,
  124. second: 0,
  125. millisec: 0,
  126. microsec: 0,
  127. timezone: null,
  128. hourMinOriginal: null,
  129. minuteMinOriginal: null,
  130. secondMinOriginal: null,
  131. millisecMinOriginal: null,
  132. microsecMinOriginal: null,
  133. hourMaxOriginal: null,
  134. minuteMaxOriginal: null,
  135. secondMaxOriginal: null,
  136. millisecMaxOriginal: null,
  137. microsecMaxOriginal: null,
  138. ampm: '',
  139. formattedDate: '',
  140. formattedTime: '',
  141. formattedDateTime: '',
  142. timezoneList: null,
  143. units: ['hour','minute','second','millisec', 'microsec'],
  144. support: {},
  145. control: null,
  146. /*
  147. * Override the default settings for all instances of the time picker.
  148. * @param settings object - the new settings to use as defaults (anonymous object)
  149. * @return the manager object
  150. */
  151. setDefaults: function(settings) {
  152. extendRemove(this._defaults, settings || {});
  153. return this;
  154. },
  155. /*
  156. * Create a new Timepicker instance
  157. */
  158. _newInst: function($input, o) {
  159. var tp_inst = new Timepicker(),
  160. inlineSettings = {},
  161. fns = {},
  162. overrides, i;
  163. for (var attrName in this._defaults) {
  164. if(this._defaults.hasOwnProperty(attrName)){
  165. var attrValue = $input.attr('time:' + attrName);
  166. if (attrValue) {
  167. try {
  168. inlineSettings[attrName] = eval(attrValue);
  169. } catch (err) {
  170. inlineSettings[attrName] = attrValue;
  171. }
  172. }
  173. }
  174. }
  175. overrides = {
  176. beforeShow: function (input, dp_inst) {
  177. if ($.isFunction(tp_inst._defaults.evnts.beforeShow)) {
  178. return tp_inst._defaults.evnts.beforeShow.call($input[0], input, dp_inst, tp_inst);
  179. }
  180. },
  181. onChangeMonthYear: function (year, month, dp_inst) {
  182. // Update the time as well : this prevents the time from disappearing from the $input field.
  183. tp_inst._updateDateTime(dp_inst);
  184. if ($.isFunction(tp_inst._defaults.evnts.onChangeMonthYear)) {
  185. tp_inst._defaults.evnts.onChangeMonthYear.call($input[0], year, month, dp_inst, tp_inst);
  186. }
  187. },
  188. onClose: function (dateText, dp_inst) {
  189. if (tp_inst.timeDefined === true && $input.val() !== '') {
  190. tp_inst._updateDateTime(dp_inst);
  191. }
  192. if ($.isFunction(tp_inst._defaults.evnts.onClose)) {
  193. tp_inst._defaults.evnts.onClose.call($input[0], dateText, dp_inst, tp_inst);
  194. }
  195. }
  196. };
  197. for (i in overrides) {
  198. if (overrides.hasOwnProperty(i)) {
  199. fns[i] = o[i] || null;
  200. }
  201. }
  202. tp_inst._defaults = $.extend({}, this._defaults, inlineSettings, o, overrides, {
  203. evnts:fns,
  204. timepicker: tp_inst // add timepicker as a property of datepicker: $.datepicker._get(dp_inst, 'timepicker');
  205. });
  206. tp_inst.amNames = $.map(tp_inst._defaults.amNames, function(val) {
  207. return val.toUpperCase();
  208. });
  209. tp_inst.pmNames = $.map(tp_inst._defaults.pmNames, function(val) {
  210. return val.toUpperCase();
  211. });
  212. // detect which units are supported
  213. tp_inst.support = detectSupport(
  214. tp_inst._defaults.timeFormat +
  215. (tp_inst._defaults.pickerTimeFormat? tp_inst._defaults.pickerTimeFormat:'') +
  216. (tp_inst._defaults.altTimeFormat? tp_inst._defaults.altTimeFormat:''));
  217. // controlType is string - key to our this._controls
  218. if(typeof(tp_inst._defaults.controlType) === 'string'){
  219. if(tp_inst._defaults.controlType == 'slider' && typeof(jQuery.ui.slider) === 'undefined'){
  220. tp_inst._defaults.controlType = 'select';
  221. }
  222. tp_inst.control = tp_inst._controls[tp_inst._defaults.controlType];
  223. }
  224. // controlType is an object and must implement create, options, value methods
  225. else{
  226. tp_inst.control = tp_inst._defaults.controlType;
  227. }
  228. // prep the timezone options
  229. var timezoneList = [-720,-660,-600,-570,-540,-480,-420,-360,-300,-270,-240,-210,-180,-120,-60,
  230. 0,60,120,180,210,240,270,300,330,345,360,390,420,480,525,540,570,600,630,660,690,720,765,780,840];
  231. if (tp_inst._defaults.timezoneList !== null) {
  232. timezoneList = tp_inst._defaults.timezoneList;
  233. }
  234. var tzl=timezoneList.length,tzi=0,tzv=null;
  235. if (tzl > 0 && typeof timezoneList[0] !== 'object') {
  236. for(; tzi<tzl; tzi++){
  237. tzv = timezoneList[tzi];
  238. timezoneList[tzi] = { value: tzv, label: $.timepicker.timezoneOffsetString(tzv, tp_inst.support.iso8601) };
  239. }
  240. }
  241. tp_inst._defaults.timezoneList = timezoneList;
  242. // set the default units
  243. tp_inst.timezone = tp_inst._defaults.timezone !== null? $.timepicker.timezoneOffsetNumber(tp_inst._defaults.timezone) :
  244. ((new Date()).getTimezoneOffset()*-1);
  245. tp_inst.hour = tp_inst._defaults.hour < tp_inst._defaults.hourMin? tp_inst._defaults.hourMin :
  246. tp_inst._defaults.hour > tp_inst._defaults.hourMax? tp_inst._defaults.hourMax : tp_inst._defaults.hour;
  247. tp_inst.minute = tp_inst._defaults.minute < tp_inst._defaults.minuteMin? tp_inst._defaults.minuteMin :
  248. tp_inst._defaults.minute > tp_inst._defaults.minuteMax? tp_inst._defaults.minuteMax : tp_inst._defaults.minute;
  249. tp_inst.second = tp_inst._defaults.second < tp_inst._defaults.secondMin? tp_inst._defaults.secondMin :
  250. tp_inst._defaults.second > tp_inst._defaults.secondMax? tp_inst._defaults.secondMax : tp_inst._defaults.second;
  251. tp_inst.millisec = tp_inst._defaults.millisec < tp_inst._defaults.millisecMin? tp_inst._defaults.millisecMin :
  252. tp_inst._defaults.millisec > tp_inst._defaults.millisecMax? tp_inst._defaults.millisecMax : tp_inst._defaults.millisec;
  253. tp_inst.microsec = tp_inst._defaults.microsec < tp_inst._defaults.microsecMin? tp_inst._defaults.microsecMin :
  254. tp_inst._defaults.microsec > tp_inst._defaults.microsecMax? tp_inst._defaults.microsecMax : tp_inst._defaults.microsec;
  255. tp_inst.ampm = '';
  256. tp_inst.$input = $input;
  257. if (o.altField) {
  258. tp_inst.$altInput = $(o.altField).css({
  259. cursor: 'pointer'
  260. }).focus(function() {
  261. $input.trigger("focus");
  262. });
  263. }
  264. if (tp_inst._defaults.minDate === 0 || tp_inst._defaults.minDateTime === 0) {
  265. tp_inst._defaults.minDate = new Date();
  266. }
  267. if (tp_inst._defaults.maxDate === 0 || tp_inst._defaults.maxDateTime === 0) {
  268. tp_inst._defaults.maxDate = new Date();
  269. }
  270. // datepicker needs minDate/maxDate, timepicker needs minDateTime/maxDateTime..
  271. if (tp_inst._defaults.minDate !== undefined && tp_inst._defaults.minDate instanceof Date) {
  272. tp_inst._defaults.minDateTime = new Date(tp_inst._defaults.minDate.getTime());
  273. }
  274. if (tp_inst._defaults.minDateTime !== undefined && tp_inst._defaults.minDateTime instanceof Date) {
  275. tp_inst._defaults.minDate = new Date(tp_inst._defaults.minDateTime.getTime());
  276. }
  277. if (tp_inst._defaults.maxDate !== undefined && tp_inst._defaults.maxDate instanceof Date) {
  278. tp_inst._defaults.maxDateTime = new Date(tp_inst._defaults.maxDate.getTime());
  279. }
  280. if (tp_inst._defaults.maxDateTime !== undefined && tp_inst._defaults.maxDateTime instanceof Date) {
  281. tp_inst._defaults.maxDate = new Date(tp_inst._defaults.maxDateTime.getTime());
  282. }
  283. tp_inst.$input.bind('focus', function() {
  284. tp_inst._onFocus();
  285. });
  286. return tp_inst;
  287. },
  288. /*
  289. * add our sliders to the calendar
  290. */
  291. _addTimePicker: function(dp_inst) {
  292. var currDT = (this.$altInput && this._defaults.altFieldTimeOnly) ? this.$input.val() + ' ' + this.$altInput.val() : this.$input.val();
  293. this.timeDefined = this._parseTime(currDT);
  294. this._limitMinMaxDateTime(dp_inst, false);
  295. this._injectTimePicker();
  296. },
  297. /*
  298. * parse the time string from input value or _setTime
  299. */
  300. _parseTime: function(timeString, withDate) {
  301. if (!this.inst) {
  302. this.inst = $.datepicker._getInst(this.$input[0]);
  303. }
  304. if (withDate || !this._defaults.timeOnly) {
  305. var dp_dateFormat = $.datepicker._get(this.inst, 'dateFormat');
  306. try {
  307. var parseRes = parseDateTimeInternal(dp_dateFormat, this._defaults.timeFormat, timeString, $.datepicker._getFormatConfig(this.inst), this._defaults);
  308. if (!parseRes.timeObj) {
  309. return false;
  310. }
  311. $.extend(this, parseRes.timeObj);
  312. } catch (err) {
  313. $.timepicker.log("Error parsing the date/time string: " + err +
  314. "\ndate/time string = " + timeString +
  315. "\ntimeFormat = " + this._defaults.timeFormat +
  316. "\ndateFormat = " + dp_dateFormat);
  317. return false;
  318. }
  319. return true;
  320. } else {
  321. var timeObj = $.datepicker.parseTime(this._defaults.timeFormat, timeString, this._defaults);
  322. if (!timeObj) {
  323. return false;
  324. }
  325. $.extend(this, timeObj);
  326. return true;
  327. }
  328. },
  329. /*
  330. * generate and inject html for timepicker into ui datepicker
  331. */
  332. _injectTimePicker: function() {
  333. var $dp = this.inst.dpDiv,
  334. o = this.inst.settings,
  335. tp_inst = this,
  336. litem = '',
  337. uitem = '',
  338. show = null,
  339. max = {},
  340. gridSize = {},
  341. size = null,
  342. i=0,
  343. l=0;
  344. // Prevent displaying twice
  345. if ($dp.find("div.ui-timepicker-div").length === 0 && o.showTimepicker) {
  346. var noDisplay = ' style="display:none;"',
  347. html = '<div class="ui-timepicker-div'+ (o.isRTL? ' ui-timepicker-rtl' : '') +'"><dl>' + '<dt class="ui_tpicker_time_label"' + ((o.showTime) ? '' : noDisplay) + '>' + o.timeText + '</dt>' +
  348. '<dd class="ui_tpicker_time"' + ((o.showTime) ? '' : noDisplay) + '></dd>';
  349. // Create the markup
  350. for(i=0,l=this.units.length; i<l; i++){
  351. litem = this.units[i];
  352. uitem = litem.substr(0,1).toUpperCase() + litem.substr(1);
  353. show = o['show'+uitem] !== null? o['show'+uitem] : this.support[litem];
  354. // Added by Peter Medeiros:
  355. // - Figure out what the hour/minute/second max should be based on the step values.
  356. // - Example: if stepMinute is 15, then minMax is 45.
  357. max[litem] = parseInt((o[litem+'Max'] - ((o[litem+'Max'] - o[litem+'Min']) % o['step'+uitem])), 10);
  358. gridSize[litem] = 0;
  359. html += '<dt class="ui_tpicker_'+ litem +'_label"' + (show ? '' : noDisplay) + '>' + o[litem +'Text'] + '</dt>' +
  360. '<dd class="ui_tpicker_'+ litem +'"><div class="ui_tpicker_'+ litem +'_slider"' + (show ? '' : noDisplay) + '></div>';
  361. if (show && o[litem+'Grid'] > 0) {
  362. html += '<div style="padding-left: 1px"><table class="ui-tpicker-grid-label"><tr>';
  363. if(litem == 'hour'){
  364. for (var h = o[litem+'Min']; h <= max[litem]; h += parseInt(o[litem+'Grid'], 10)) {
  365. gridSize[litem]++;
  366. var tmph = $.datepicker.formatTime(this.support.ampm? 'hht':'HH', {hour:h}, o);
  367. html += '<td data-for="'+litem+'">' + tmph + '</td>';
  368. }
  369. }
  370. else{
  371. for (var m = o[litem+'Min']; m <= max[litem]; m += parseInt(o[litem+'Grid'], 10)) {
  372. gridSize[litem]++;
  373. html += '<td data-for="'+litem+'">' + ((m < 10) ? '0' : '') + m + '</td>';
  374. }
  375. }
  376. html += '</tr></table></div>';
  377. }
  378. html += '</dd>';
  379. }
  380. // Timezone
  381. var showTz = o.showTimezone !== null? o.showTimezone : this.support.timezone;
  382. html += '<dt class="ui_tpicker_timezone_label"' + (showTz ? '' : noDisplay) + '>' + o.timezoneText + '</dt>';
  383. html += '<dd class="ui_tpicker_timezone" ' + (showTz ? '' : noDisplay) + '></dd>';
  384. // Create the elements from string
  385. html += '</dl></div>';
  386. var $tp = $(html);
  387. // if we only want time picker...
  388. if (o.timeOnly === true) {
  389. $tp.prepend('<div class="ui-widget-header ui-helper-clearfix ui-corner-all">' + '<div class="ui-datepicker-title">' + o.timeOnlyTitle + '</div>' + '</div>');
  390. $dp.find('.ui-datepicker-header, .ui-datepicker-calendar').hide();
  391. }
  392. // add sliders, adjust grids, add events
  393. for(i=0,l=tp_inst.units.length; i<l; i++){
  394. litem = tp_inst.units[i];
  395. uitem = litem.substr(0,1).toUpperCase() + litem.substr(1);
  396. show = o['show'+uitem] !== null? o['show'+uitem] : this.support[litem];
  397. // add the slider
  398. tp_inst[litem+'_slider'] = tp_inst.control.create(tp_inst, $tp.find('.ui_tpicker_'+litem+'_slider'), litem, tp_inst[litem], o[litem+'Min'], max[litem], o['step'+uitem]);
  399. // adjust the grid and add click event
  400. if (show && o[litem+'Grid'] > 0) {
  401. size = 100 * gridSize[litem] * o[litem+'Grid'] / (max[litem] - o[litem+'Min']);
  402. $tp.find('.ui_tpicker_'+litem+' table').css({
  403. width: size + "%",
  404. marginLeft: o.isRTL? '0' : ((size / (-2 * gridSize[litem])) + "%"),
  405. marginRight: o.isRTL? ((size / (-2 * gridSize[litem])) + "%") : '0',
  406. borderCollapse: 'collapse'
  407. }).find("td").click(function(e){
  408. var $t = $(this),
  409. h = $t.html(),
  410. n = parseInt(h.replace(/[^0-9]/g),10),
  411. ap = h.replace(/[^apm]/ig),
  412. f = $t.data('for'); // loses scope, so we use data-for
  413. if(f == 'hour'){
  414. if(ap.indexOf('p') !== -1 && n < 12){
  415. n += 12;
  416. }
  417. else{
  418. if(ap.indexOf('a') !== -1 && n === 12){
  419. n = 0;
  420. }
  421. }
  422. }
  423. tp_inst.control.value(tp_inst, tp_inst[f+'_slider'], litem, n);
  424. tp_inst._onTimeChange();
  425. tp_inst._onSelectHandler();
  426. }).css({
  427. cursor: 'pointer',
  428. width: (100 / gridSize[litem]) + '%',
  429. textAlign: 'center',
  430. overflow: 'hidden'
  431. });
  432. } // end if grid > 0
  433. } // end for loop
  434. // Add timezone options
  435. this.timezone_select = $tp.find('.ui_tpicker_timezone').append('<select></select>').find("select");
  436. $.fn.append.apply(this.timezone_select,
  437. $.map(o.timezoneList, function(val, idx) {
  438. return $("<option />").val(typeof val == "object" ? val.value : val).text(typeof val == "object" ? val.label : val);
  439. }));
  440. if (typeof(this.timezone) != "undefined" && this.timezone !== null && this.timezone !== "") {
  441. var local_timezone = (new Date(this.inst.selectedYear, this.inst.selectedMonth, this.inst.selectedDay, 12)).getTimezoneOffset()*-1;
  442. if (local_timezone == this.timezone) {
  443. selectLocalTimezone(tp_inst);
  444. } else {
  445. this.timezone_select.val(this.timezone);
  446. }
  447. } else {
  448. if (typeof(this.hour) != "undefined" && this.hour !== null && this.hour !== "") {
  449. this.timezone_select.val(o.timezone);
  450. } else {
  451. selectLocalTimezone(tp_inst);
  452. }
  453. }
  454. this.timezone_select.change(function() {
  455. tp_inst._onTimeChange();
  456. tp_inst._onSelectHandler();
  457. });
  458. // End timezone options
  459. // inject timepicker into datepicker
  460. var $buttonPanel = $dp.find('.ui-datepicker-buttonpane');
  461. if ($buttonPanel.length) {
  462. $buttonPanel.before($tp);
  463. } else {
  464. $dp.append($tp);
  465. }
  466. this.$timeObj = $tp.find('.ui_tpicker_time');
  467. if (this.inst !== null) {
  468. var timeDefined = this.timeDefined;
  469. this._onTimeChange();
  470. this.timeDefined = timeDefined;
  471. }
  472. // slideAccess integration: http://trentrichardson.com/2011/11/11/jquery-ui-sliders-and-touch-accessibility/
  473. if (this._defaults.addSliderAccess) {
  474. var sliderAccessArgs = this._defaults.sliderAccessArgs,
  475. rtl = this._defaults.isRTL;
  476. sliderAccessArgs.isRTL = rtl;
  477. setTimeout(function() { // fix for inline mode
  478. if ($tp.find('.ui-slider-access').length === 0) {
  479. $tp.find('.ui-slider:visible').sliderAccess(sliderAccessArgs);
  480. // fix any grids since sliders are shorter
  481. var sliderAccessWidth = $tp.find('.ui-slider-access:eq(0)').outerWidth(true);
  482. if (sliderAccessWidth) {
  483. $tp.find('table:visible').each(function() {
  484. var $g = $(this),
  485. oldWidth = $g.outerWidth(),
  486. oldMarginLeft = $g.css(rtl? 'marginRight':'marginLeft').toString().replace('%', ''),
  487. newWidth = oldWidth - sliderAccessWidth,
  488. newMarginLeft = ((oldMarginLeft * newWidth) / oldWidth) + '%',
  489. css = { width: newWidth, marginRight: 0, marginLeft: 0 };
  490. css[rtl? 'marginRight':'marginLeft'] = newMarginLeft;
  491. $g.css(css);
  492. });
  493. }
  494. }
  495. }, 10);
  496. }
  497. // end slideAccess integration
  498. }
  499. },
  500. /*
  501. * This function tries to limit the ability to go outside the
  502. * min/max date range
  503. */
  504. _limitMinMaxDateTime: function(dp_inst, adjustSliders) {
  505. var o = this._defaults,
  506. dp_date = new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay);
  507. if (!this._defaults.showTimepicker) {
  508. return;
  509. } // No time so nothing to check here
  510. if ($.datepicker._get(dp_inst, 'minDateTime') !== null && $.datepicker._get(dp_inst, 'minDateTime') !== undefined && dp_date) {
  511. var minDateTime = $.datepicker._get(dp_inst, 'minDateTime'),
  512. minDateTimeDate = new Date(minDateTime.getFullYear(), minDateTime.getMonth(), minDateTime.getDate(), 0, 0, 0, 0);
  513. if (this.hourMinOriginal === null || this.minuteMinOriginal === null || this.secondMinOriginal === null || this.millisecMinOriginal === null || this.microsecMinOriginal === null) {
  514. this.hourMinOriginal = o.hourMin;
  515. this.minuteMinOriginal = o.minuteMin;
  516. this.secondMinOriginal = o.secondMin;
  517. this.millisecMinOriginal = o.millisecMin;
  518. this.microsecMinOriginal = o.microsecMin;
  519. }
  520. if (dp_inst.settings.timeOnly || minDateTimeDate.getTime() == dp_date.getTime()) {
  521. this._defaults.hourMin = minDateTime.getHours();
  522. if (this.hour <= this._defaults.hourMin) {
  523. this.hour = this._defaults.hourMin;
  524. this._defaults.minuteMin = minDateTime.getMinutes();
  525. if (this.minute <= this._defaults.minuteMin) {
  526. this.minute = this._defaults.minuteMin;
  527. this._defaults.secondMin = minDateTime.getSeconds();
  528. if (this.second <= this._defaults.secondMin) {
  529. this.second = this._defaults.secondMin;
  530. this._defaults.millisecMin = minDateTime.getMilliseconds();
  531. if(this.millisec <= this._defaults.millisecMin) {
  532. this.millisec = this._defaults.millisecMin;
  533. this._defaults.microsecMin = minDateTime.getMicroseconds();
  534. } else {
  535. if (this.microsec < this._defaults.microsecMin) {
  536. this.microsec = this._defaults.microsecMin;
  537. }
  538. this._defaults.microsecMin = this.microsecMinOriginal;
  539. }
  540. } else {
  541. this._defaults.millisecMin = this.millisecMinOriginal;
  542. this._defaults.microsecMin = this.microsecMinOriginal;
  543. }
  544. } else {
  545. this._defaults.secondMin = this.secondMinOriginal;
  546. this._defaults.millisecMin = this.millisecMinOriginal;
  547. this._defaults.microsecMin = this.microsecMinOriginal;
  548. }
  549. } else {
  550. this._defaults.minuteMin = this.minuteMinOriginal;
  551. this._defaults.secondMin = this.secondMinOriginal;
  552. this._defaults.millisecMin = this.millisecMinOriginal;
  553. this._defaults.microsecMin = this.microsecMinOriginal;
  554. }
  555. } else {
  556. this._defaults.hourMin = this.hourMinOriginal;
  557. this._defaults.minuteMin = this.minuteMinOriginal;
  558. this._defaults.secondMin = this.secondMinOriginal;
  559. this._defaults.millisecMin = this.millisecMinOriginal;
  560. this._defaults.microsecMin = this.microsecMinOriginal;
  561. }
  562. }
  563. if ($.datepicker._get(dp_inst, 'maxDateTime') !== null && $.datepicker._get(dp_inst, 'maxDateTime') !== undefined && dp_date) {
  564. var maxDateTime = $.datepicker._get(dp_inst, 'maxDateTime'),
  565. maxDateTimeDate = new Date(maxDateTime.getFullYear(), maxDateTime.getMonth(), maxDateTime.getDate(), 0, 0, 0, 0);
  566. if (this.hourMaxOriginal === null || this.minuteMaxOriginal === null || this.secondMaxOriginal === null || this.millisecMaxOriginal === null) {
  567. this.hourMaxOriginal = o.hourMax;
  568. this.minuteMaxOriginal = o.minuteMax;
  569. this.secondMaxOriginal = o.secondMax;
  570. this.millisecMaxOriginal = o.millisecMax;
  571. this.microsecMaxOriginal = o.microsecMax;
  572. }
  573. if (dp_inst.settings.timeOnly || maxDateTimeDate.getTime() == dp_date.getTime()) {
  574. this._defaults.hourMax = maxDateTime.getHours();
  575. if (this.hour >= this._defaults.hourMax) {
  576. this.hour = this._defaults.hourMax;
  577. this._defaults.minuteMax = maxDateTime.getMinutes();
  578. if (this.minute >= this._defaults.minuteMax) {
  579. this.minute = this._defaults.minuteMax;
  580. this._defaults.secondMax = maxDateTime.getSeconds();
  581. if (this.second >= this._defaults.secondMax) {
  582. this.second = this._defaults.secondMax;
  583. this._defaults.millisecMax = maxDateTime.getMilliseconds();
  584. if (this.millisec >= this._defaults.millisecMax) {
  585. this.millisec = this._defaults.millisecMax;
  586. this._defaults.microsecMax = maxDateTime.getMicroseconds();
  587. } else {
  588. if (this.microsec > this._defaults.microsecMax) {
  589. this.microsec = this._defaults.microsecMax;
  590. }
  591. this._defaults.microsecMax = this.microsecMaxOriginal;
  592. }
  593. } else {
  594. this._defaults.millisecMax = this.millisecMaxOriginal;
  595. this._defaults.microsecMax = this.microsecMaxOriginal;
  596. }
  597. } else {
  598. this._defaults.secondMax = this.secondMaxOriginal;
  599. this._defaults.millisecMax = this.millisecMaxOriginal;
  600. this._defaults.microsecMax = this.microsecMaxOriginal;
  601. }
  602. } else {
  603. this._defaults.minuteMax = this.minuteMaxOriginal;
  604. this._defaults.secondMax = this.secondMaxOriginal;
  605. this._defaults.millisecMax = this.millisecMaxOriginal;
  606. this._defaults.microsecMax = this.microsecMaxOriginal;
  607. }
  608. } else {
  609. this._defaults.hourMax = this.hourMaxOriginal;
  610. this._defaults.minuteMax = this.minuteMaxOriginal;
  611. this._defaults.secondMax = this.secondMaxOriginal;
  612. this._defaults.millisecMax = this.millisecMaxOriginal;
  613. this._defaults.microsecMax = this.microsecMaxOriginal;
  614. }
  615. }
  616. if (adjustSliders !== undefined && adjustSliders === true) {
  617. var hourMax = parseInt((this._defaults.hourMax - ((this._defaults.hourMax - this._defaults.hourMin) % this._defaults.stepHour)), 10),
  618. minMax = parseInt((this._defaults.minuteMax - ((this._defaults.minuteMax - this._defaults.minuteMin) % this._defaults.stepMinute)), 10),
  619. secMax = parseInt((this._defaults.secondMax - ((this._defaults.secondMax - this._defaults.secondMin) % this._defaults.stepSecond)), 10),
  620. millisecMax = parseInt((this._defaults.millisecMax - ((this._defaults.millisecMax - this._defaults.millisecMin) % this._defaults.stepMillisec)), 10);
  621. microsecMax = parseInt((this._defaults.microsecMax - ((this._defaults.microsecMax - this._defaults.microsecMin) % this._defaults.stepMicrosec)), 10);
  622. if (this.hour_slider) {
  623. this.control.options(this, this.hour_slider, 'hour', { min: this._defaults.hourMin, max: hourMax });
  624. this.control.value(this, this.hour_slider, 'hour', this.hour - (this.hour % this._defaults.stepHour));
  625. }
  626. if (this.minute_slider) {
  627. this.control.options(this, this.minute_slider, 'minute', { min: this._defaults.minuteMin, max: minMax });
  628. this.control.value(this, this.minute_slider, 'minute', this.minute - (this.minute % this._defaults.stepMinute));
  629. }
  630. if (this.second_slider) {
  631. this.control.options(this, this.second_slider, 'second', { min: this._defaults.secondMin, max: secMax });
  632. this.control.value(this, this.second_slider, 'second', this.second - (this.second % this._defaults.stepSecond));
  633. }
  634. if (this.millisec_slider) {
  635. this.control.options(this, this.millisec_slider, 'millisec', { min: this._defaults.millisecMin, max: millisecMax });
  636. this.control.value(this, this.millisec_slider, 'millisec', this.millisec - (this.millisec % this._defaults.stepMillisec));
  637. }
  638. if (this.microsec_slider) {
  639. this.control.options(this, this.microsec_slider, 'microsec', { min: this._defaults.microsecMin, max: microsecMax });
  640. this.control.value(this, this.microsec_slider, 'microsec', this.microsec - (this.microsec % this._defaults.stepMicrosec));
  641. }
  642. }
  643. },
  644. /*
  645. * when a slider moves, set the internal time...
  646. * on time change is also called when the time is updated in the text field
  647. */
  648. _onTimeChange: function() {
  649. var hour = (this.hour_slider) ? this.control.value(this, this.hour_slider, 'hour') : false,
  650. minute = (this.minute_slider) ? this.control.value(this, this.minute_slider, 'minute') : false,
  651. second = (this.second_slider) ? this.control.value(this, this.second_slider, 'second') : false,
  652. millisec = (this.millisec_slider) ? this.control.value(this, this.millisec_slider, 'millisec') : false,
  653. microsec = (this.microsec_slider) ? this.control.value(this, this.microsec_slider, 'microsec') : false,
  654. timezone = (this.timezone_select) ? this.timezone_select.val() : false,
  655. o = this._defaults,
  656. pickerTimeFormat = o.pickerTimeFormat || o.timeFormat,
  657. pickerTimeSuffix = o.pickerTimeSuffix || o.timeSuffix;
  658. if (typeof(hour) == 'object') {
  659. hour = false;
  660. }
  661. if (typeof(minute) == 'object') {
  662. minute = false;
  663. }
  664. if (typeof(second) == 'object') {
  665. second = false;
  666. }
  667. if (typeof(millisec) == 'object') {
  668. millisec = false;
  669. }
  670. if (typeof(microsec) == 'object') {
  671. microsec = false;
  672. }
  673. if (typeof(timezone) == 'object') {
  674. timezone = false;
  675. }
  676. if (hour !== false) {
  677. hour = parseInt(hour, 10);
  678. }
  679. if (minute !== false) {
  680. minute = parseInt(minute, 10);
  681. }
  682. if (second !== false) {
  683. second = parseInt(second, 10);
  684. }
  685. if (millisec !== false) {
  686. millisec = parseInt(millisec, 10);
  687. }
  688. if (microsec !== false) {
  689. microsec = parseInt(microsec, 10);
  690. }
  691. var ampm = o[hour < 12 ? 'amNames' : 'pmNames'][0];
  692. // If the update was done in the input field, the input field should not be updated.
  693. // If the update was done using the sliders, update the input field.
  694. var hasChanged = (hour != this.hour || minute != this.minute || second != this.second || millisec != this.millisec || microsec != this.microsec
  695. || (this.ampm.length > 0 && (hour < 12) != ($.inArray(this.ampm.toUpperCase(), this.amNames) !== -1))
  696. || (this.timezone !== null && timezone != this.timezone));
  697. if (hasChanged) {
  698. if (hour !== false) {
  699. this.hour = hour;
  700. }
  701. if (minute !== false) {
  702. this.minute = minute;
  703. }
  704. if (second !== false) {
  705. this.second = second;
  706. }
  707. if (millisec !== false) {
  708. this.millisec = millisec;
  709. }
  710. if (microsec !== false) {
  711. this.microsec = microsec;
  712. }
  713. if (timezone !== false) {
  714. this.timezone = timezone;
  715. }
  716. if (!this.inst) {
  717. this.inst = $.datepicker._getInst(this.$input[0]);
  718. }
  719. this._limitMinMaxDateTime(this.inst, true);
  720. }
  721. if (this.support.ampm) {
  722. this.ampm = ampm;
  723. }
  724. // Updates the time within the timepicker
  725. this.formattedTime = $.datepicker.formatTime(o.timeFormat, this, o);
  726. if (this.$timeObj) {
  727. if(pickerTimeFormat === o.timeFormat){
  728. this.$timeObj.text(this.formattedTime + pickerTimeSuffix);
  729. }
  730. else{
  731. this.$timeObj.text($.datepicker.formatTime(pickerTimeFormat, this, o) + pickerTimeSuffix);
  732. }
  733. }
  734. this.timeDefined = true;
  735. if (hasChanged) {
  736. this._updateDateTime();
  737. }
  738. },
  739. /*
  740. * call custom onSelect.
  741. * bind to sliders slidestop, and grid click.
  742. */
  743. _onSelectHandler: function() {
  744. var onSelect = this._defaults.onSelect || this.inst.settings.onSelect;
  745. var inputEl = this.$input ? this.$input[0] : null;
  746. if (onSelect && inputEl) {
  747. onSelect.apply(inputEl, [this.formattedDateTime, this]);
  748. }
  749. },
  750. /*
  751. * update our input with the new date time..
  752. */
  753. _updateDateTime: function(dp_inst) {
  754. dp_inst = this.inst || dp_inst;
  755. var dt = $.datepicker._daylightSavingAdjust(new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay)),
  756. dateFmt = $.datepicker._get(dp_inst, 'dateFormat'),
  757. formatCfg = $.datepicker._getFormatConfig(dp_inst),
  758. timeAvailable = dt !== null && this.timeDefined;
  759. this.formattedDate = $.datepicker.formatDate(dateFmt, (dt === null ? new Date() : dt), formatCfg);
  760. var formattedDateTime = this.formattedDate;
  761. // if a slider was changed but datepicker doesn't have a value yet, set it
  762. if(dp_inst.lastVal===""){
  763. dp_inst.currentYear=dp_inst.selectedYear;
  764. dp_inst.currentMonth=dp_inst.selectedMonth;
  765. dp_inst.currentDay=dp_inst.selectedDay;
  766. }
  767. /*
  768. * remove following lines to force every changes in date picker to change the input value
  769. * Bug descriptions: when an input field has a default value, and click on the field to pop up the date picker.
  770. * If the user manually empty the value in the input field, the date picker will never change selected value.
  771. */
  772. //if (dp_inst.lastVal !== undefined && (dp_inst.lastVal.length > 0 && this.$input.val().length === 0)) {
  773. // return;
  774. //}
  775. if (this._defaults.timeOnly === true) {
  776. formattedDateTime = this.formattedTime;
  777. } else if (this._defaults.timeOnly !== true && (this._defaults.alwaysSetTime || timeAvailable)) {
  778. formattedDateTime += this._defaults.separator + this.formattedTime + this._defaults.timeSuffix;
  779. }
  780. this.formattedDateTime = formattedDateTime;
  781. if (!this._defaults.showTimepicker) {
  782. this.$input.val(this.formattedDate);
  783. } else if (this.$altInput && this._defaults.timeOnly === false && this._defaults.altFieldTimeOnly === true) {
  784. this.$altInput.val(this.formattedTime);
  785. this.$input.val(this.formattedDate);
  786. } else if (this.$altInput) {
  787. this.$input.val(formattedDateTime);
  788. var altFormattedDateTime = '',
  789. altSeparator = this._defaults.altSeparator ? this._defaults.altSeparator : this._defaults.separator,
  790. altTimeSuffix = this._defaults.altTimeSuffix ? this._defaults.altTimeSuffix : this._defaults.timeSuffix;
  791. if(!this._defaults.timeOnly){
  792. if (this._defaults.altFormat){
  793. altFormattedDateTime = $.datepicker.formatDate(this._defaults.altFormat, (dt === null ? new Date() : dt), formatCfg);
  794. }
  795. else{
  796. altFormattedDateTime = this.formattedDate;
  797. }
  798. if (altFormattedDateTime){
  799. altFormattedDateTime += altSeparator;
  800. }
  801. }
  802. if(this._defaults.altTimeFormat){
  803. altFormattedDateTime += $.datepicker.formatTime(this._defaults.altTimeFormat, this, this._defaults) + altTimeSuffix;
  804. }
  805. else{
  806. altFormattedDateTime += this.formattedTime + altTimeSuffix;
  807. }
  808. this.$altInput.val(altFormattedDateTime);
  809. } else {
  810. this.$input.val(formattedDateTime);
  811. }
  812. this.$input.trigger("change");
  813. },
  814. _onFocus: function() {
  815. if (!this.$input.val() && this._defaults.defaultValue) {
  816. this.$input.val(this._defaults.defaultValue);
  817. var inst = $.datepicker._getInst(this.$input.get(0)),
  818. tp_inst = $.datepicker._get(inst, 'timepicker');
  819. if (tp_inst) {
  820. if (tp_inst._defaults.timeOnly && (inst.input.val() != inst.lastVal)) {
  821. try {
  822. $.datepicker._updateDatepicker(inst);
  823. } catch (err) {
  824. $.timepicker.log(err);
  825. }
  826. }
  827. }
  828. }
  829. },
  830. /*
  831. * Small abstraction to control types
  832. * We can add more, just be sure to follow the pattern: create, options, value
  833. */
  834. _controls: {
  835. // slider methods
  836. slider: {
  837. create: function(tp_inst, obj, unit, val, min, max, step){
  838. var rtl = tp_inst._defaults.isRTL; // if rtl go -60->0 instead of 0->60
  839. return obj.prop('slide', null).slider({
  840. orientation: "horizontal",
  841. value: rtl? val*-1 : val,
  842. min: rtl? max*-1 : min,
  843. max: rtl? min*-1 : max,
  844. step: step,
  845. slide: function(event, ui) {
  846. tp_inst.control.value(tp_inst, $(this), unit, rtl? ui.value*-1:ui.value);
  847. tp_inst._onTimeChange();
  848. },
  849. stop: function(event, ui) {
  850. tp_inst._onSelectHandler();
  851. }
  852. });
  853. },
  854. options: function(tp_inst, obj, unit, opts, val){
  855. if(tp_inst._defaults.isRTL){
  856. if(typeof(opts) == 'string'){
  857. if(opts == 'min' || opts == 'max'){
  858. if(val !== undefined){
  859. return obj.slider(opts, val*-1);
  860. }
  861. return Math.abs(obj.slider(opts));
  862. }
  863. return obj.slider(opts);
  864. }
  865. var min = opts.min,
  866. max = opts.max;
  867. opts.min = opts.max = null;
  868. if(min !== undefined){
  869. opts.max = min * -1;
  870. }
  871. if(max !== undefined){
  872. opts.min = max * -1;
  873. }
  874. return obj.slider(opts);
  875. }
  876. if(typeof(opts) == 'string' && val !== undefined){
  877. return obj.slider(opts, val);
  878. }
  879. return obj.slider(opts);
  880. },
  881. value: function(tp_inst, obj, unit, val){
  882. if(tp_inst._defaults.isRTL){
  883. if(val !== undefined){
  884. return obj.slider('value', val*-1);
  885. }
  886. return Math.abs(obj.slider('value'));
  887. }
  888. if(val !== undefined){
  889. return obj.slider('value', val);
  890. }
  891. return obj.slider('value');
  892. }
  893. },
  894. // select methods
  895. select: {
  896. create: function(tp_inst, obj, unit, val, min, max, step){
  897. var sel = '<select class="ui-timepicker-select" data-unit="'+ unit +'" data-min="'+ min +'" data-max="'+ max +'" data-step="'+ step +'">',
  898. format = tp_inst._defaults.pickerTimeFormat || tp_inst._defaults.timeFormat;
  899. for(var i=min; i<=max; i+=step){
  900. sel += '<option value="'+ i +'"'+ (i==val? ' selected':'') +'>';
  901. if(unit == 'hour'){
  902. sel += $.datepicker.formatTime($.trim(format.replace(/[^ht ]/ig,'')), {hour:i}, tp_inst._defaults);
  903. }
  904. else if(unit == 'millisec' || unit == 'microsec' || i >= 10){ sel += i; }
  905. else {sel += '0'+ i.toString(); }
  906. sel += '</option>';
  907. }
  908. sel += '</select>';
  909. obj.children('select').remove();
  910. $(sel).appendTo(obj).change(function(e){
  911. tp_inst._onTimeChange();
  912. tp_inst._onSelectHandler();
  913. });
  914. return obj;
  915. },
  916. options: function(tp_inst, obj, unit, opts, val){
  917. var o = {},
  918. $t = obj.children('select');
  919. if(typeof(opts) == 'string'){
  920. if(val === undefined){
  921. return $t.data(opts);
  922. }
  923. o[opts] = val;
  924. }
  925. else{ o = opts; }
  926. return tp_inst.control.create(tp_inst, obj, $t.data('unit'), $t.val(), o.min || $t.data('min'), o.max || $t.data('max'), o.step || $t.data('step'));
  927. },
  928. value: function(tp_inst, obj, unit, val){
  929. var $t = obj.children('select');
  930. if(val !== undefined){
  931. return $t.val(val);
  932. }
  933. return $t.val();
  934. }
  935. }
  936. } // end _controls
  937. });
  938. $.fn.extend({
  939. /*
  940. * shorthand just to use timepicker..
  941. */
  942. timepicker: function(o) {
  943. o = o || {};
  944. var tmp_args = Array.prototype.slice.call(arguments);
  945. if (typeof o == 'object') {
  946. tmp_args[0] = $.extend(o, {
  947. timeOnly: true
  948. });
  949. }
  950. return $(this).each(function() {
  951. $.fn.datetimepicker.apply($(this), tmp_args);
  952. });
  953. },
  954. /*
  955. * extend timepicker to datepicker
  956. */
  957. datetimepicker: function(o) {
  958. o = o || {};
  959. var tmp_args = arguments;
  960. if (typeof(o) == 'string') {
  961. if (o == 'getDate') {
  962. return $.fn.datepicker.apply($(this[0]), tmp_args);
  963. } else {
  964. return this.each(function() {
  965. var $t = $(this);
  966. $t.datepicker.apply($t, tmp_args);
  967. });
  968. }
  969. } else {
  970. return this.each(function() {
  971. var $t = $(this);
  972. $t.datepicker($.timepicker._newInst($t, o)._defaults);
  973. });
  974. }
  975. }
  976. });
  977. /*
  978. * Public Utility to parse date and time
  979. */
  980. $.datepicker.parseDateTime = function(dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings) {
  981. var parseRes = parseDateTimeInternal(dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings);
  982. if (parseRes.timeObj) {
  983. var t = parseRes.timeObj;
  984. parseRes.date.setHours(t.hour, t.minute, t.second, t.millisec);
  985. parseRex.date.setMicroseconds(t.microsec);
  986. }
  987. return parseRes.date;
  988. };
  989. /*
  990. * Public utility to parse time
  991. */
  992. $.datepicker.parseTime = function(timeFormat, timeString, options) {
  993. var o = extendRemove(extendRemove({}, $.timepicker._defaults), options || {}),
  994. iso8601 = (timeFormat.replace(/\'.*?\'/g,'').indexOf('Z') !== -1);
  995. // Strict parse requires the timeString to match the timeFormat exactly
  996. var strictParse = function(f, s, o){
  997. // pattern for standard and localized AM/PM markers
  998. var getPatternAmpm = function(amNames, pmNames) {
  999. var markers = [];
  1000. if (amNames) {
  1001. $.merge(markers, amNames);
  1002. }
  1003. if (pmNames) {
  1004. $.merge(markers, pmNames);
  1005. }
  1006. markers = $.map(markers, function(val) {
  1007. return val.replace(/[.*+?|()\[\]{}\\]/g, '\\$&');
  1008. });
  1009. return '(' + markers.join('|') + ')?';
  1010. };
  1011. // figure out position of time elements.. cause js cant do named captures
  1012. var getFormatPositions = function(timeFormat) {
  1013. var finds = timeFormat.toLowerCase().match(/(h{1,2}|m{1,2}|s{1,2}|l{1}|c{1}|t{1,2}|z|'.*?')/g),
  1014. orders = {
  1015. h: -1,
  1016. m: -1,
  1017. s: -1,
  1018. l: -1,
  1019. c: -1,
  1020. t: -1,
  1021. z: -1
  1022. };
  1023. if (finds) {
  1024. for (var i = 0; i < finds.length; i++) {
  1025. if (orders[finds[i].toString().charAt(0)] == -1) {
  1026. orders[finds[i].toString().charAt(0)] = i + 1;
  1027. }
  1028. }
  1029. }
  1030. return orders;
  1031. };
  1032. var regstr = '^' + f.toString()
  1033. .replace(/([hH]{1,2}|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g, function (match) {
  1034. var ml = match.length;
  1035. switch (match.charAt(0).toLowerCase()) {
  1036. case 'h': return ml === 1? '(\\d?\\d)':'(\\d{'+ml+'})';
  1037. case 'm': return ml === 1? '(\\d?\\d)':'(\\d{'+ml+'})';
  1038. case 's': return ml === 1? '(\\d?\\d)':'(\\d{'+ml+'})';
  1039. case 'l': return '(\\d?\\d?\\d)';
  1040. case 'c': return '(\\d?\\d?\\d)';
  1041. case 'z': return '(z|[-+]\\d\\d:?\\d\\d|\\S+)?';
  1042. case 't': return getPatternAmpm(o.amNames, o.pmNames);
  1043. default: // literal escaped in quotes
  1044. return '(' + match.replace(/\'/g, "").replace(/(\.|\$|\^|\\|\/|\(|\)|\[|\]|\?|\+|\*)/g, function (m) { return "\\" + m; }) + ')?';
  1045. }
  1046. })
  1047. .replace(/\s/g, '\\s?') +
  1048. o.timeSuffix + '$',
  1049. order = getFormatPositions(f),
  1050. ampm = '',
  1051. treg;
  1052. treg = s.match(new RegExp(regstr, 'i'));
  1053. var resTime = {
  1054. hour: 0,
  1055. minute: 0,
  1056. second: 0,
  1057. millisec: 0,
  1058. microsec: 0
  1059. };
  1060. if (treg) {
  1061. if (order.t !== -1) {
  1062. if (treg[order.t] === undefined || treg[order.t].length === 0) {
  1063. ampm = '';
  1064. resTime.ampm = '';
  1065. } else {
  1066. ampm = $.inArray(treg[order.t].toUpperCase(), o.amNames) !== -1 ? 'AM' : 'PM';
  1067. resTime.ampm = o[ampm == 'AM' ? 'amNames' : 'pmNames'][0];
  1068. }
  1069. }
  1070. if (order.h !== -1) {
  1071. if (ampm == 'AM' && treg[order.h] == '12') {
  1072. resTime.hour = 0; // 12am = 0 hour
  1073. } else {
  1074. if (ampm == 'PM' && treg[order.h] != '12') {
  1075. resTime.hour = parseInt(treg[order.h], 10) + 12; // 12pm = 12 hour, any other pm = hour + 12
  1076. } else {
  1077. resTime.hour = Number(treg[order.h]);
  1078. }
  1079. }
  1080. }
  1081. if (order.m !== -1) {
  1082. resTime.minute = Number(treg[order.m]);
  1083. }
  1084. if (order.s !== -1) {
  1085. resTime.second = Number(treg[order.s]);
  1086. }
  1087. if (order.l !== -1) {
  1088. resTime.millisec = Number(treg[order.l]);
  1089. }
  1090. if (order.c !== -1) {
  1091. resTime.microsec = Number(treg[order.c]);
  1092. }
  1093. if (order.z !== -1 && treg[order.z] !== undefined) {
  1094. resTime.timezone = $.timepicker.timezoneOffsetNumber(treg[order.z]);
  1095. }
  1096. return resTime;
  1097. }
  1098. return false;
  1099. };// end strictParse
  1100. // First try JS Date, if that fails, use strictParse
  1101. var looseParse = function(f,s,o){
  1102. try{
  1103. var d = new Date('2012-01-01 '+ s);
  1104. if(isNaN(d.getTime())){
  1105. d = new Date('2012-01-01T'+ s);
  1106. if(isNaN(d.getTime())){
  1107. d = new Date('01/01/2012 '+ s);
  1108. if(isNaN(d.getTime())){
  1109. throw "Unable to parse time with native Date: "+ s;
  1110. }
  1111. }
  1112. }
  1113. return {
  1114. hour: d.getHours(),
  1115. minute: d.getMinutes(),
  1116. second: d.getSeconds(),
  1117. millisec: d.getMilliseconds(),
  1118. microsec: d.getMicroseconds(),
  1119. timezone: d.getTimezoneOffset()*-1
  1120. };
  1121. }
  1122. catch(err){
  1123. try{
  1124. return strictParse(f,s,o);
  1125. }
  1126. catch(err2){
  1127. $.timepicker.log("Unable to parse \ntimeString: "+ s +"\ntimeFormat: "+ f);
  1128. }
  1129. }
  1130. return false;
  1131. }; // end looseParse
  1132. if(typeof o.parse === "function"){
  1133. return o.parse(timeFormat, timeString, o);
  1134. }
  1135. if(o.parse === 'loose'){
  1136. return looseParse(timeFormat, timeString, o);
  1137. }
  1138. return strictParse(timeFormat, timeString, o);
  1139. };
  1140. /*
  1141. * Public utility to format the time
  1142. * format = string format of the time
  1143. * time = a {}, not a Date() for timezones
  1144. * options = essentially the regional[].. amNames, pmNames, ampm
  1145. */
  1146. $.datepicker.formatTime = function(format, time, options) {
  1147. options = options || {};
  1148. options = $.extend({}, $.timepicker._defaults, options);
  1149. time = $.extend({
  1150. hour: 0,
  1151. minute: 0,
  1152. second: 0,
  1153. millisec: 0,
  1154. timezone: 0
  1155. }, time);
  1156. var tmptime = format,
  1157. ampmName = options.amNames[0],
  1158. hour = parseInt(time.hour, 10);
  1159. if (hour > 11) {
  1160. ampmName = options.pmNames[0];
  1161. }
  1162. tmptime = tmptime.replace(/(?:HH?|hh?|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|('.*?'|".*?"))/g, function(match) {
  1163. switch (match) {
  1164. case 'HH':
  1165. return ('0' + hour).slice(-2);
  1166. case 'H':
  1167. return hour;
  1168. case 'hh':
  1169. return ('0' + convert24to12(hour)).slice(-2);
  1170. case 'h':
  1171. return convert24to12(hour);
  1172. case 'mm':
  1173. return ('0' + time.minute).slice(-2);
  1174. case 'm':
  1175. return time.minute;
  1176. case 'ss':
  1177. return ('0' + time.second).slice(-2);
  1178. case 's':
  1179. return time.second;
  1180. case 'l':
  1181. return ('00' + time.millisec).slice(-3);
  1182. case 'c':
  1183. return ('00' + time.microsec).slice(-3);
  1184. case 'z':
  1185. return $.timepicker.timezoneOffsetString(time.timezone === null? options.timezone : time.timezone, false);
  1186. case 'Z':
  1187. return $.timepicker.timezoneOffsetString(time.timezone === null? options.timezone : time.timezone, true);
  1188. case 'T':
  1189. return ampmName.charAt(0).toUpperCase();
  1190. case 'TT':
  1191. return ampmName.toUpperCase();
  1192. case 't':
  1193. return ampmName.charAt(0).toLowerCase();
  1194. case 'tt':
  1195. return ampmName.toLowerCase();
  1196. default:
  1197. return match.replace(/\'/g, "") || "'";
  1198. }
  1199. });
  1200. tmptime = $.trim(tmptime);
  1201. return tmptime;
  1202. };
  1203. /*
  1204. * the bad hack :/ override datepicker so it doesnt close on select
  1205. // inspired: http://stackoverflow.com/questions/1252512/jquery-datepicker-prevent-closing-picker-when-clicking-a-date/1762378#1762378
  1206. */
  1207. $.datepicker._base_selectDate = $.datepicker._selectDate;
  1208. $.datepicker._selectDate = function(id, dateStr) {
  1209. var inst = this._getInst($(id)[0]),
  1210. tp_inst = this._get(inst, 'timepicker');
  1211. if (tp_inst) {
  1212. tp_inst._limitMinMaxDateTime(inst, true);
  1213. inst.inline = inst.stay_open = true;
  1214. //This way the onSelect handler called from calendarpicker get the full dateTime
  1215. this._base_selectDate(id, dateStr);
  1216. inst.inline = inst.stay_open = false;
  1217. this._notifyChange(inst);
  1218. this._updateDatepicker(inst);
  1219. } else {
  1220. this._base_selectDate(id, dateStr);
  1221. }
  1222. };
  1223. /*
  1224. * second bad hack :/ override datepicker so it triggers an event when changing the input field
  1225. * and does not redraw the datepicker on every selectDate event
  1226. */
  1227. $.datepicker._base_updateDatepicker = $.datepicker._updateDatepicker;
  1228. $.datepicker._updateDatepicker = function(inst) {
  1229. // don't popup the datepicker if there is another instance already opened
  1230. var input = inst.input[0];
  1231. if ($.datepicker._curInst && $.datepicker._curInst != inst && $.datepicker._datepickerShowing && $.datepicker._lastInput != input) {
  1232. return;
  1233. }
  1234. if (typeof(inst.stay_open) !== 'boolean' || inst.stay_open === false) {
  1235. this._base_updateDatepicker(inst);
  1236. // Reload the time control when changing something in the input text field.
  1237. var tp_inst = this._get(inst, 'timepicker');
  1238. if (tp_inst) {
  1239. tp_inst._addTimePicker(inst);
  1240. }
  1241. }
  1242. };
  1243. /*
  1244. * third bad hack :/ override datepicker so it allows spaces and colon in the input field
  1245. */
  1246. $.datepicker._base_doKeyPress = $.datepicker._doKeyPress;
  1247. $.datepicker._doKeyPress = function(event) {
  1248. var inst = $.datepicker._getInst(event.target),
  1249. tp_inst = $.datepicker._get(inst, 'timepicker');
  1250. if (tp_inst) {
  1251. if ($.datepicker._get(inst, 'constrainInput')) {
  1252. var ampm = tp_inst.support.ampm,
  1253. tz = tp_inst._defaults.showTimezone !== null? tp_inst._defaults.showTimezone : tp_inst.support.timezone,
  1254. dateChars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')),
  1255. datetimeChars = tp_inst._defaults.timeFormat.toString()
  1256. .replace(/[hms]/g, '')
  1257. .replace(/TT/g, ampm ? 'APM' : '')
  1258. .replace(/Tt/g, ampm ? 'AaPpMm' : '')
  1259. .replace(/tT/g, ampm ? 'AaPpMm' : '')
  1260. .replace(/T/g, ampm ? 'AP' : '')
  1261. .replace(/tt/g, ampm ? 'apm' : '')
  1262. .replace(/t/g, ampm ? 'ap' : '') +
  1263. " " + tp_inst._defaults.separator +
  1264. tp_inst._defaults.timeSuffix +
  1265. (tz ? tp_inst._defaults.timezoneList.join('') : '') +
  1266. (tp_inst._defaults.amNames.join('')) + (tp_inst._defaults.pmNames.join('')) +
  1267. dateChars,
  1268. chr = String.fromCharCode(event.charCode === undefined ? event.keyCode : event.charCode);
  1269. return event.ctrlKey || (chr < ' ' || !dateChars || datetimeChars.indexOf(chr) > -1);
  1270. }
  1271. }
  1272. return $.datepicker._base_doKeyPress(event);
  1273. };
  1274. /*
  1275. * Fourth bad hack :/ override _updateAlternate function used in inline mode to init altField
  1276. */
  1277. $.datepicker._base_updateAlternate = $.datepicker._updateAlternate;
  1278. /* Update any alternate field to synchronise with the main field. */
  1279. $.datepicker._updateAlternate = function(inst) {
  1280. var tp_inst = this._get(inst, 'timepicker');
  1281. if(tp_inst){
  1282. var altField = tp_inst._defaults.altField;
  1283. if (altField) { // update alternate field too
  1284. var altFormat = tp_inst._defaults.altFormat || tp_inst._defaults.dateFormat,
  1285. date = this._getDate(inst),
  1286. formatCfg = $.datepicker._getFormatConfig(inst),
  1287. altFormattedDateTime = '',
  1288. altSeparator = tp_inst._defaults.altSeparator ? tp_inst._defaults.altSeparator : tp_inst._defaults.separator,
  1289. altTimeSuffix = tp_inst._defaults.altTimeSuffix ? tp_inst._defaults.altTimeSuffix : tp_inst._defaults.timeSuffix,
  1290. altTimeFormat = tp_inst._defaults.altTimeFormat !== null ? tp_inst._defaults.altTimeFormat : tp_inst._defaults.timeFormat;
  1291. altFormattedDateTime += $.datepicker.formatTime(altTimeFormat, tp_inst, tp_inst._defaults) + altTimeSuffix;
  1292. if(!tp_inst._defaults.timeOnly && !tp_inst._defaults.altFieldTimeOnly && date !== null){
  1293. if(tp_inst._defaults.altFormat){
  1294. altFormattedDateTime = $.datepicker.formatDate(tp_inst._defaults.altFormat, date, formatCfg) + altSeparator + altFormattedDateTime;
  1295. }
  1296. else{
  1297. altFormattedDateTime = tp_inst.formattedDate + altSeparator + altFormattedDateTime;
  1298. }
  1299. }
  1300. $(altField).val(altFormattedDateTime);
  1301. }
  1302. }
  1303. else{
  1304. $.datepicker._base_updateAlternate(inst);
  1305. }
  1306. };
  1307. /*
  1308. * Override key up event to sync manual input changes.
  1309. */
  1310. $.datepicker._base_doKeyUp = $.datepicker._doKeyUp;
  1311. $.datepicker._doKeyUp = function(event) {
  1312. var inst = $.datepicker._getInst(event.target),
  1313. tp_inst = $.datepicker._get(inst, 'timepicker');
  1314. if (tp_inst) {
  1315. if (tp_inst._defaults.timeOnly && (inst.input.val() != inst.lastVal)) {
  1316. try {
  1317. $.datepicker._updateDatepicker(inst);
  1318. } catch (err) {
  1319. $.timepicker.log(err);
  1320. }
  1321. }
  1322. }
  1323. return $.datepicker._base_doKeyUp(event);
  1324. };
  1325. /*
  1326. * override "Today" button to also grab the time.
  1327. */
  1328. $.datepicker._base_gotoToday = $.datepicker._gotoToday;
  1329. $.datepicker._gotoToday = function(id) {
  1330. var inst = this._getInst($(id)[0]),
  1331. $dp = inst.dpDiv;
  1332. this._base_gotoToday(id);
  1333. var tp_inst = this._get(inst, 'timepicker');
  1334. selectLocalTimezone(tp_inst);
  1335. var now = new Date();
  1336. this._setTime(inst, now);
  1337. $('.ui-datepicker-today', $dp).click();
  1338. };
  1339. /*
  1340. * Disable & enable the Time in the datetimepicker
  1341. */
  1342. $.datepicker._disableTimepickerDatepicker = function(target) {
  1343. var inst = this._getInst(target);
  1344. if (!inst) {
  1345. return;
  1346. }
  1347. var tp_inst = this._get(inst, 'timepicker');
  1348. $(target).datepicker('getDate'); // Init selected[Year|Month|Day]
  1349. if (tp_inst) {
  1350. tp_inst._defaults.showTimepicker = false;
  1351. tp_inst._updateDateTime(inst);
  1352. }
  1353. };
  1354. $.datepicker._enableTimepickerDatepicker = function(target) {
  1355. var inst = this._getInst(target);
  1356. if (!inst) {
  1357. return;
  1358. }
  1359. var tp_inst = this._get(inst, 'timepicker');
  1360. $(target).datepicker('getDate'); // Init selected[Year|Month|Day]
  1361. if (tp_inst) {
  1362. tp_inst._defaults.showTimepicker = true;
  1363. tp_inst._addTimePicker(inst); // Could be disabled on page load
  1364. tp_inst._updateDateTime(inst);
  1365. }
  1366. };
  1367. /*
  1368. * Create our own set time function
  1369. */
  1370. $.datepicker._setTime = function(inst, date) {
  1371. var tp_inst = this._get(inst, 'timepicker');
  1372. if (tp_inst) {
  1373. var defaults = tp_inst._defaults;
  1374. // calling _setTime with no date sets time to defaults
  1375. tp_inst.hour = date ? date.getHours() : defaults.hour;
  1376. tp_inst.minute = date ? date.getMinutes() : defaults.minute;
  1377. tp_inst.second = date ? date.getSeconds() : defaults.second;
  1378. tp_inst.millisec = date ? date.getMilliseconds() : defaults.millisec;
  1379. tp_inst.microsec = date ? date.getMicroseconds() : defaults.microsec;
  1380. //check if within min/max times..
  1381. tp_inst._limitMinMaxDateTime(inst, true);
  1382. tp_inst._onTimeChange();
  1383. tp_inst._updateDateTime(inst);
  1384. }
  1385. };
  1386. /*
  1387. * Create new public method to set only time, callable as $().datepicker('setTime', date)
  1388. */
  1389. $.datepicker._setTimeDatepicker = function(target, date, withDate) {
  1390. var inst = this._getInst(target);
  1391. if (!inst) {
  1392. return;
  1393. }
  1394. var tp_inst = this._get(inst, 'timepicker');
  1395. if (tp_inst) {
  1396. this._setDateFromField(inst);
  1397. var tp_date;
  1398. if (date) {
  1399. if (typeof date == "string") {
  1400. tp_inst._parseTime(date, withDate);
  1401. tp_date = new Date();
  1402. tp_date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec);
  1403. tp_date.setMicroseconds(tp_inst.microsec);
  1404. } else {
  1405. tp_date = new Date(date.getTime());
  1406. }
  1407. if (tp_date.toString() == 'Invalid Date') {
  1408. tp_date = undefined;
  1409. }
  1410. this._setTime(inst, tp_date);
  1411. }
  1412. }
  1413. };
  1414. /*
  1415. * override setDate() to allow setting time too within Date object
  1416. */
  1417. $.datepicker._base_setDateDatepicker = $.datepicker._setDateDatepicker;
  1418. $.datepicker._setDateDatepicker = function(target, date) {
  1419. var inst = this._getInst(target);
  1420. if (!inst) {
  1421. return;
  1422. }
  1423. var tp_inst = this._get(inst, 'timepicker'),
  1424. tp_date = (date instanceof Date) ? new Date(date.getTime()) : date;
  1425. // This is important if you are using the timezone option, javascript's Date
  1426. // object will only return the timezone offset for the current locale, so we
  1427. // adjust it accordingly. If not using timezone option this won't matter..
  1428. // If a timezone is different in tp, keep the timezone as is
  1429. if(tp_inst && tp_inst.timezone != null){
  1430. date = $.timepicker.timezoneAdjust(date, tp_inst.timezone);
  1431. tp_date = $.timepicker.timezoneAdjust(tp_date, tp_inst.timezone);
  1432. }
  1433. this._updateDatepicker(inst);
  1434. this._base_setDateDatepicker.apply(this, arguments);
  1435. this._setTimeDatepicker(target, tp_date, true);
  1436. };
  1437. /*
  1438. * override getDate() to allow getting time too within Date object
  1439. */
  1440. $.datepicker._base_getDateDatepicker = $.datepicker._getDateDatepicker;
  1441. $.datepicker._getDateDatepicker = function(target, noDefault) {
  1442. var inst = this._getInst(target);
  1443. if (!inst) {
  1444. return;
  1445. }
  1446. var tp_inst = this._get(inst, 'timepicker');
  1447. if (tp_inst) {
  1448. // if it hasn't yet been defined, grab from field
  1449. if(inst.lastVal === undefined){
  1450. this._setDateFromField(inst, noDefault);
  1451. }
  1452. var date = this._getDate(inst);
  1453. if (date && tp_inst._parseTime($(target).val(), tp_inst.timeOnly)) {
  1454. date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec);
  1455. date.setMicroseconds(tp_inst.microsec);
  1456. // This is important if you are using the timezone option, javascript's Date
  1457. // object will only return the timezone offset for the current locale, so we
  1458. // adjust it accordingly. If not using timezone option this won't matter..
  1459. if(tp_inst.timezone != null){
  1460. date = $.timepicker.timezoneAdjust(date, tp_inst.timezone);
  1461. }
  1462. }
  1463. return date;
  1464. }
  1465. return this._base_getDateDatepicker(target, noDefault);
  1466. };
  1467. /*
  1468. * override parseDate() because UI 1.8.14 throws an error about "Extra characters"
  1469. * An option in datapicker to ignore extra format characters would be nicer.
  1470. */
  1471. $.datepicker._base_parseDate = $.datepicker.parseDate;
  1472. $.datepicker.parseDate = function(format, value, settings) {
  1473. var date;
  1474. try {
  1475. date = this._base_parseDate(format, value, settings);
  1476. } catch (err) {
  1477. // Hack! The error message ends with a colon, a space, and
  1478. // the "extra" characters. We rely on that instead of
  1479. // attempting to perfectly reproduce the parsing algorithm.
  1480. if (err.indexOf(":") >= 0) {
  1481. date = this._base_parseDate(format, value.substring(0,value.length-(err.length-err.indexOf(':')-2)), settings);
  1482. $.timepicker.log("Error parsing the date string: " + err + "\ndate string = " + value + "\ndate format = " + format);
  1483. } else {
  1484. throw err;
  1485. }
  1486. }
  1487. return date;
  1488. };
  1489. /*
  1490. * override formatDate to set date with time to the input
  1491. */
  1492. $.datepicker._base_formatDate = $.datepicker._formatDate;
  1493. $.datepicker._formatDate = function(inst, day, month, year) {
  1494. var tp_inst = this._get(inst, 'timepicker');
  1495. if (tp_inst) {
  1496. tp_inst._updateDateTime(inst);
  1497. return tp_inst.$input.val();
  1498. }
  1499. return this._base_formatDate(inst);
  1500. };
  1501. /*
  1502. * override options setter to add time to maxDate(Time) and minDate(Time). MaxDate
  1503. */
  1504. $.datepicker._base_optionDatepicker = $.datepicker._optionDatepicker;
  1505. $.datepicker._optionDatepicker = function(target, name, value) {
  1506. var inst = this._getInst(target),
  1507. name_clone;
  1508. if (!inst) {
  1509. return null;
  1510. }
  1511. var tp_inst = this._get(inst, 'timepicker');
  1512. if (tp_inst) {
  1513. var min = null,
  1514. max = null,
  1515. onselect = null,
  1516. overrides = tp_inst._defaults.evnts,
  1517. fns = {},
  1518. prop;
  1519. if (typeof name == 'string') { // if min/max was set with the string
  1520. if (name === 'minDate' || name === 'minDateTime') {
  1521. min = value;
  1522. } else if (name === 'maxDate' || name === 'maxDateTime') {
  1523. max = value;
  1524. } else if (name === 'onSelect') {
  1525. onselect = value;
  1526. } else if (overrides.hasOwnProperty(name)) {
  1527. if (typeof (value) === 'undefined') {
  1528. return overrides[name];
  1529. }
  1530. fns[name] = value;
  1531. name_clone = {}; //empty results in exiting function after overrides updated
  1532. }
  1533. } else if (typeof name == 'object') { //if min/max was set with the JSON
  1534. if (name.minDate) {
  1535. min = name.minDate;
  1536. } else if (name.minDateTime) {
  1537. min = name.minDateTime;
  1538. } else if (name.maxDate) {
  1539. max = name.maxDate;
  1540. } else if (name.maxDateTime) {
  1541. max = name.maxDateTime;
  1542. }
  1543. for (prop in overrides) {
  1544. if (overrides.hasOwnProperty(prop) && name[prop]) {
  1545. fns[prop] = name[prop];
  1546. }
  1547. }
  1548. }
  1549. for (prop in fns) {
  1550. if (fns.hasOwnProperty(prop)) {
  1551. overrides[prop] = fns[prop];
  1552. if (!name_clone) { name_clone = $.extend({}, name);}
  1553. delete name_clone[prop];
  1554. }
  1555. }
  1556. if (name_clone && isEmptyObject(name_clone)) { return; }
  1557. if (min) { //if min was set
  1558. if (min === 0) {
  1559. min = new Date();
  1560. } else {
  1561. min = new Date(min);
  1562. }
  1563. tp_inst._defaults.minDate = min;
  1564. tp_inst._defaults.minDateTime = min;
  1565. } else if (max) { //if max was set
  1566. if (max === 0) {
  1567. max = new Date();
  1568. } else {
  1569. max = new Date(max);
  1570. }
  1571. tp_inst._defaults.maxDate = max;
  1572. tp_inst._defaults.maxDateTime = max;
  1573. } else if (onselect) {
  1574. tp_inst._defaults.onSelect = onselect;
  1575. }
  1576. }
  1577. if (value === undefined) {
  1578. return this._base_optionDatepicker.call($.datepicker, target, name);
  1579. }
  1580. return this._base_optionDatepicker.call($.datepicker, target, name_clone || name, value);
  1581. };
  1582. /*
  1583. * jQuery isEmptyObject does not check hasOwnProperty - if someone has added to the object prototype,
  1584. * it will return false for all objects
  1585. */
  1586. var isEmptyObject = function(obj) {
  1587. var prop;
  1588. for (prop in obj) {
  1589. if (obj.hasOwnProperty(obj)) {
  1590. return false;
  1591. }
  1592. }
  1593. return true;
  1594. };
  1595. /*
  1596. * jQuery extend now ignores nulls!
  1597. */
  1598. var extendRemove = function(target, props) {
  1599. $.extend(target, props);
  1600. for (var name in props) {
  1601. if (props[name] === null || props[name] === undefined) {
  1602. target[name] = props[name];
  1603. }
  1604. }
  1605. return target;
  1606. };
  1607. /*
  1608. * Determine by the time format which units are supported
  1609. * Returns an object of booleans for each unit
  1610. */
  1611. var detectSupport = function(timeFormat){
  1612. var tf = timeFormat.replace(/\'.*?\'/g,'').toLowerCase(), // removes literals
  1613. isIn = function(f, t){ // does the format contain the token?
  1614. return f.indexOf(t) !== -1? true:false;
  1615. };
  1616. return {
  1617. hour: isIn(tf,'h'),
  1618. minute: isIn(tf,'m'),
  1619. second: isIn(tf,'s'),
  1620. millisec: isIn(tf,'l'),
  1621. microsec: isIn(tf,'c'),
  1622. timezone: isIn(tf,'z'),
  1623. ampm: isIn('t') && isIn(timeFormat,'h'),
  1624. iso8601: isIn(timeFormat, 'Z')
  1625. };
  1626. };
  1627. /*
  1628. * Converts 24 hour format into 12 hour
  1629. * Returns 12 hour without leading 0
  1630. */
  1631. var convert24to12 = function(hour) {
  1632. if (hour > 12) {
  1633. hour = hour - 12;
  1634. }
  1635. if (hour === 0) {
  1636. hour = 12;
  1637. }
  1638. return String(hour);
  1639. };
  1640. /*
  1641. * Splits datetime string into date ans time substrings.
  1642. * Throws exception when date can't be parsed
  1643. * Returns [dateString, timeString]
  1644. */
  1645. var splitDateTime = function(dateFormat, dateTimeString, dateSettings, timeSettings) {
  1646. try {
  1647. // The idea is to get the number separator occurances in datetime and the time format requested (since time has
  1648. // fewer unknowns, mostly numbers and am/pm). We will use the time pattern to split.
  1649. var separator = timeSettings && timeSettings.separator ? timeSettings.separator : $.timepicker._defaults.separator,
  1650. format = timeSettings && timeSettings.timeFormat ? timeSettings.timeFormat : $.timepicker._defaults.timeFormat,
  1651. timeParts = format.split(separator), // how many occurances of separator may be in our format?
  1652. timePartsLen = timeParts.length,
  1653. allParts = dateTimeString.split(separator),
  1654. allPartsLen = allParts.length;
  1655. if (allPartsLen > 1) {
  1656. return [
  1657. allParts.splice(0,allPartsLen-timePartsLen).join(separator),
  1658. allParts.splice(0,timePartsLen).join(separator)
  1659. ];
  1660. }
  1661. } catch (err) {
  1662. $.timepicker.log('Could not split the date from the time. Please check the following datetimepicker options' +
  1663. "\nthrown error: " + err +
  1664. "\ndateTimeString" + dateTimeString +
  1665. "\ndateFormat = " + dateFormat +
  1666. "\nseparator = " + timeSettings.separator +
  1667. "\ntimeFormat = " + timeSettings.timeFormat);
  1668. if (err.indexOf(":") >= 0) {
  1669. // Hack! The error message ends with a colon, a space, and
  1670. // the "extra" characters. We rely on that instead of
  1671. // attempting to perfectly reproduce the parsing algorithm.
  1672. var dateStringLength = dateTimeString.length - (err.length - err.indexOf(':') - 2),
  1673. timeString = dateTimeString.substring(dateStringLength);
  1674. return [$.trim(dateTimeString.substring(0, dateStringLength)), $.trim(dateTimeString.substring(dateStringLength))];
  1675. } else {
  1676. throw err;
  1677. }
  1678. }
  1679. return [dateTimeString, ''];
  1680. };
  1681. /*
  1682. * Internal function to parse datetime interval
  1683. * Returns: {date: Date, timeObj: Object}, where
  1684. * date - parsed date without time (type Date)
  1685. * timeObj = {hour: , minute: , second: , millisec: , microsec: } - parsed time. Optional
  1686. */
  1687. var parseDateTimeInternal = function(dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings) {
  1688. var date;
  1689. var splitRes = splitDateTime(dateFormat, dateTimeString, dateSettings, timeSettings);
  1690. date = $.datepicker._base_parseDate(dateFormat, splitRes[0], dateSettings);
  1691. if (splitRes[1] !== '') {
  1692. var timeString = splitRes[1],
  1693. parsedTime = $.datepicker.parseTime(timeFormat, timeString, timeSettings);
  1694. if (parsedTime === null) {
  1695. throw 'Wrong time format';
  1696. }
  1697. return {
  1698. date: date,
  1699. timeObj: parsedTime
  1700. };
  1701. } else {
  1702. return {
  1703. date: date
  1704. };
  1705. }
  1706. };
  1707. /*
  1708. * Internal function to set timezone_select to the local timezone
  1709. */
  1710. var selectLocalTimezone = function(tp_inst, date) {
  1711. if (tp_inst && tp_inst.timezone_select) {
  1712. var now = typeof date !== 'undefined' ? date : new Date();
  1713. tp_inst.timezone_select.val(now.getTimezoneOffset()*-1);
  1714. }
  1715. };
  1716. /*
  1717. * Create a Singleton Insance
  1718. */
  1719. $.timepicker = new Timepicker();
  1720. /**
  1721. * Get the timezone offset as string from a date object (eg '+0530' for UTC+5.5)
  1722. * @param number if not a number this value is returned
  1723. * @param boolean if true formats in accordance to iso8601 "+12:45"
  1724. * @return string
  1725. */
  1726. $.timepicker.timezoneOffsetString = function(tzMinutes, iso8601) {
  1727. if(isNaN(tzMinutes) || tzMinutes > 840){
  1728. return tzMinutes;
  1729. }
  1730. var off = tzMinutes,
  1731. minutes = off % 60,
  1732. hours = (off - minutes) / 60,
  1733. iso = iso8601? ':':'',
  1734. tz = (off >= 0 ? '+' : '-') + ('0' + (hours * 101).toString()).slice(-2) + iso + ('0' + (minutes * 101).toString()).slice(-2);
  1735. if(tz == '+00:00'){
  1736. return 'Z';
  1737. }
  1738. return tz;
  1739. };
  1740. /**
  1741. * Get the number in minutes that represents a timezone string
  1742. * @param string formated like "+0500", "-1245"
  1743. * @return number
  1744. */
  1745. $.timepicker.timezoneOffsetNumber = function(tzString) {
  1746. tzString = tzString.toString().replace(':',''); // excuse any iso8601, end up with "+1245"
  1747. if(tzString.toUpperCase() === 'Z'){ // if iso8601 with Z, its 0 minute offset
  1748. return 0;
  1749. }
  1750. if(!/^(\-|\+)\d{4}$/.test(tzString)){ // possibly a user defined tz, so just give it back
  1751. return tzString;
  1752. }
  1753. return ((tzString.substr(0,1) =='-'? -1 : 1) * // plus or minus
  1754. ((parseInt(tzString.substr(1,2),10)*60) + // hours (converted to minutes)
  1755. parseInt(tzString.substr(3,2),10))); // minutes
  1756. };
  1757. /**
  1758. * No way to set timezone in js Date, so we must adjust the minutes to compensate. (think setDate, getDate)
  1759. * @param date
  1760. * @param string formated like "+0500", "-1245"
  1761. * @return date
  1762. */
  1763. $.timepicker.timezoneAdjust = function(date, toTimezone) {
  1764. var toTz = $.timepicker.timezoneOffsetNumber(toTimezone);
  1765. if(!isNaN(toTz)){
  1766. var currTz = date.getTimezoneOffset()*-1,
  1767. diff = currTz - toTz; // difference in minutes
  1768. date.setMinutes(date.getMinutes()+diff);
  1769. }
  1770. return date;
  1771. };
  1772. /**
  1773. * Calls `timepicker()` on the `startTime` and `endTime` elements, and configures them to
  1774. * enforce date range limits.
  1775. * n.b. The input value must be correctly formatted (reformatting is not supported)
  1776. * @param Element startTime
  1777. * @param Element endTime
  1778. * @param obj options Options for the timepicker() call
  1779. * @return jQuery
  1780. */
  1781. $.timepicker.timeRange = function(startTime, endTime, options) {
  1782. return $.timepicker.handleRange('timepicker', startTime, endTime, options);
  1783. };
  1784. /**
  1785. * Calls `datetimepicker` on the `startTime` and `endTime` elements, and configures them to
  1786. * enforce date range limits.
  1787. * @param Element startTime
  1788. * @param Element endTime
  1789. * @param obj options Options for the `timepicker()` call. Also supports `reformat`,
  1790. * a boolean value that can be used to reformat the input values to the `dateFormat`.
  1791. * @param string method Can be used to specify the type of picker to be added
  1792. * @return jQuery
  1793. */
  1794. $.timepicker.datetimeRange = function(startTime, endTime, options) {
  1795. $.timepicker.handleRange('datetimepicker', startTime, endTime, options);
  1796. };
  1797. /**
  1798. * Calls `method` on the `startTime` and `endTime` elements, and configures them to
  1799. * enforce date range limits.
  1800. * @param Element startTime
  1801. * @param Element endTime
  1802. * @param obj options Options for the `timepicker()` call. Also supports `reformat`,
  1803. * a boolean value that can be used to reformat the input values to the `dateFormat`.
  1804. * @return jQuery
  1805. */
  1806. $.timepicker.dateRange = function(startTime, endTime, options) {
  1807. $.timepicker.handleRange('datepicker', startTime, endTime, options);
  1808. };
  1809. /**
  1810. * Calls `method` on the `startTime` and `endTime` elements, and configures them to
  1811. * enforce date range limits.
  1812. * @param string method Can be used to specify the type of picker to be added
  1813. * @param Element startTime
  1814. * @param Element endTime
  1815. * @param obj options Options for the `timepicker()` call. Also supports `reformat`,
  1816. * a boolean value that can be used to reformat the input values to the `dateFormat`.
  1817. * @return jQuery
  1818. */
  1819. $.timepicker.handleRange = function(method, startTime, endTime, options) {
  1820. options = $.extend({}, {
  1821. minInterval: 0, // min allowed interval in milliseconds
  1822. maxInterval: 0, // max allowed interval in milliseconds
  1823. start: {}, // options for start picker
  1824. end: {} // options for end picker
  1825. }, options);
  1826. $.fn[method].call(startTime, $.extend({
  1827. onClose: function(dateText, inst) {
  1828. checkDates($(this), endTime);
  1829. },
  1830. onSelect: function(selectedDateTime) {
  1831. selected($(this), endTime, 'minDate');
  1832. }
  1833. }, options, options.start));
  1834. $.fn[method].call(endTime, $.extend({
  1835. onClose: function(dateText, inst) {
  1836. checkDates($(this), startTime);
  1837. },
  1838. onSelect: function(selectedDateTime) {
  1839. selected($(this), startTime, 'maxDate');
  1840. }
  1841. }, options, options.end));
  1842. checkDates(startTime, endTime);
  1843. selected(startTime, endTime, 'minDate');
  1844. selected(endTime, startTime, 'maxDate');
  1845. function checkDates(changed, other) {
  1846. var startdt = startTime[method]('getDate'),
  1847. enddt = endTime[method]('getDate'),
  1848. changeddt = changed[method]('getDate');
  1849. if(startdt !== null){
  1850. var minDate = new Date(startdt.getTime()),
  1851. maxDate = new Date(startdt.getTime());
  1852. minDate.setMilliseconds(minDate.getMilliseconds() + options.minInterval);
  1853. maxDate.setMilliseconds(maxDate.getMilliseconds() + options.maxInterval);
  1854. if(options.minInterval > 0 && minDate > enddt){ // minInterval check
  1855. endTime[method]('setDate',minDate);
  1856. }
  1857. else if(options.maxInterval > 0 && maxDate < enddt){ // max interval check
  1858. endTime[method]('setDate',maxDate);
  1859. }
  1860. else if (startdt > enddt) {
  1861. other[method]('setDate',changeddt);
  1862. }
  1863. }
  1864. }
  1865. function selected(changed, other, option) {
  1866. if (!changed.val()) {
  1867. return;
  1868. }
  1869. var date = changed[method].call(changed, 'getDate');
  1870. if(date !== null && options.minInterval > 0){
  1871. if(option == 'minDate'){
  1872. date.setMilliseconds(date.getMilliseconds() + options.minInterval);
  1873. }
  1874. if(option == 'maxDate'){
  1875. date.setMilliseconds(date.getMilliseconds() - options.minInterval);
  1876. }
  1877. }
  1878. if (date.getTime) {
  1879. other[method].call(other, 'option', option, date);
  1880. }
  1881. }
  1882. return $([startTime.get(0), endTime.get(0)]);
  1883. };
  1884. /**
  1885. * Log error or data to the console during error or debugging
  1886. * @param Object err pass any type object to log to the console during error or debugging
  1887. * @return void
  1888. */
  1889. $.timepicker.log = function(err){
  1890. if(window.console){
  1891. console.log(err);
  1892. }
  1893. };
  1894. /*
  1895. * Rough microsecond support
  1896. */
  1897. if(!Date.prototype.getMicroseconds){
  1898. Date.microseconds = 0;
  1899. Date.prototype.getMicroseconds = function(){ return this.microseconds; };
  1900. Date.prototype.setMicroseconds = function(m){ this.microseconds = m; return this; };
  1901. }
  1902. /*
  1903. * Keep up with the version
  1904. */
  1905. $.timepicker.version = "1.3";
  1906. })(jQuery);