jquery.ui.timepicker.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. /*
  2. * jQuery UI Timepicker 0.2.9
  3. *
  4. * Copyright 2010-2011, Francois Gelinas
  5. * Dual licensed under the MIT or GPL Version 2 licenses.
  6. * http://jquery.org/license
  7. *
  8. * http://fgelinas.com/code/timepicker
  9. *
  10. * Depends:
  11. * jquery.ui.core.js
  12. * jquery.ui.position.js (only if position settngs are used)
  13. *
  14. * Change version 0.1.0 - moved the t-rex up here
  15. *
  16. ____
  17. ___ .-~. /_"-._
  18. `-._~-. / /_ "~o\ :Y
  19. \ \ / : \~x. ` ')
  20. ] Y / | Y< ~-.__j
  21. / ! _.--~T : l l< /.-~
  22. / / ____.--~ . ` l /~\ \<|Y
  23. / / .-~~" /| . ',-~\ \L|
  24. / / / .^ \ Y~Y \.^>/l_ "--'
  25. / Y .-"( . l__ j_j l_/ /~_.-~ .
  26. Y l / \ ) ~~~." / `/"~ / \.__/l_
  27. | \ _.-" ~-{__ l : l._Z~-.___.--~
  28. | ~---~ / ~~"---\_ ' __[>
  29. l . _.^ ___ _>-y~
  30. \ \ . .-~ .-~ ~>--" /
  31. \ ~---" / ./ _.-'
  32. "-.,_____.,_ _.--~\ _.-~
  33. ~~ ( _} -Row
  34. `. ~(
  35. ) \
  36. /,`--'~\--'~\
  37. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  38. ->T-Rex<-
  39. */
  40. (function ($, undefined) {
  41. $.extend($.ui, { timepicker: { version: "0.2.9"} });
  42. var PROP_NAME = 'timepicker';
  43. var tpuuid = new Date().getTime();
  44. /* Time picker manager.
  45. Use the singleton instance of this class, $.timepicker, to interact with the time picker.
  46. Settings for (groups of) time pickers are maintained in an instance object,
  47. allowing multiple different settings on the same page. */
  48. function Timepicker() {
  49. this.debug = true; // Change this to true to start debugging
  50. this._curInst = null; // The current instance in use
  51. this._isInline = false; // true if the instance is displayed inline
  52. this._disabledInputs = []; // List of time picker inputs that have been disabled
  53. this._timepickerShowing = false; // True if the popup picker is showing , false if not
  54. this._inDialog = false; // True if showing within a "dialog", false if not
  55. this._dialogClass = 'ui-timepicker-dialog'; // The name of the dialog marker class
  56. this._mainDivId = 'ui-timepicker-div'; // The ID of the main timepicker division
  57. this._inlineClass = 'ui-timepicker-inline'; // The name of the inline marker class
  58. this._currentClass = 'ui-timepicker-current'; // The name of the current hour / minutes marker class
  59. this._dayOverClass = 'ui-timepicker-days-cell-over'; // The name of the day hover marker class
  60. this.regional = []; // Available regional settings, indexed by language code
  61. this.regional[''] = { // Default regional settings
  62. hourText: 'Hour', // Display text for hours section
  63. minuteText: 'Minute', // Display text for minutes link
  64. amPmText: ['AM', 'PM'], // Display text for AM PM
  65. closeButtonText: 'Done', // Text for the confirmation button (ok button)
  66. nowButtonText: 'Now', // Text for the now button
  67. deselectButtonText: 'Deselect' // Text for the deselect button
  68. };
  69. this._defaults = { // Global defaults for all the time picker instances
  70. showOn: 'focus', // 'focus' for popup on focus,
  71. // 'button' for trigger button, or 'both' for either (not yet implemented)
  72. button: null, // 'button' element that will trigger the timepicker
  73. showAnim: 'fadeIn', // Name of jQuery animation for popup
  74. showOptions: {}, // Options for enhanced animations
  75. appendText: '', // Display text following the input box, e.g. showing the format
  76. beforeShow: null, // Define a callback function executed before the timepicker is shown
  77. onSelect: null, // Define a callback function when a hour / minutes is selected
  78. onClose: null, // Define a callback function when the timepicker is closed
  79. timeSeparator: ':', // The character to use to separate hours and minutes.
  80. periodSeparator: ' ', // The character to use to separate the time from the time period.
  81. showPeriod: false, // Define whether or not to show AM/PM with selected time
  82. showPeriodLabels: true, // Show the AM/PM labels on the left of the time picker
  83. showLeadingZero: true, // Define whether or not to show a leading zero for hours < 10. [true/false]
  84. showMinutesLeadingZero: true, // Define whether or not to show a leading zero for minutes < 10.
  85. altField: '', // Selector for an alternate field to store selected time into
  86. defaultTime: 'now', // Used as default time when input field is empty or for inline timePicker
  87. // (set to 'now' for the current time, '' for no highlighted time)
  88. myPosition: 'left top', // Position of the dialog relative to the input.
  89. // see the position utility for more info : http://jqueryui.com/demos/position/
  90. atPosition: 'left bottom', // Position of the input element to match
  91. // Note : if the position utility is not loaded, the timepicker will attach left top to left bottom
  92. //NEW: 2011-02-03
  93. onHourShow: null, // callback for enabling / disabling on selectable hours ex : function(hour) { return true; }
  94. onMinuteShow: null, // callback for enabling / disabling on time selection ex : function(hour,minute) { return true; }
  95. hours: {
  96. starts: 0, // first displayed hour
  97. ends: 23 // last displayed hour
  98. },
  99. minutes: {
  100. starts: 0, // first displayed minute
  101. ends: 55, // last displayed minute
  102. interval: 5 // interval of displayed minutes
  103. },
  104. rows: 4, // number of rows for the input tables, minimum 2, makes more sense if you use multiple of 2
  105. // 2011-08-05 0.2.4
  106. showHours: true, // display the hours section of the dialog
  107. showMinutes: true, // display the minute section of the dialog
  108. optionalMinutes: false, // optionally parse inputs of whole hours with minutes omitted
  109. // buttons
  110. showCloseButton: false, // shows an OK button to confirm the edit
  111. showNowButton: false, // Shows the 'now' button
  112. showDeselectButton: false // Shows the deselect time button
  113. };
  114. $.extend(this._defaults, this.regional['']);
  115. this.tpDiv = $('<div id="' + this._mainDivId + '" class="ui-timepicker ui-widget ui-helper-clearfix ui-corner-all " style="display: none"></div>');
  116. }
  117. $.extend(Timepicker.prototype, {
  118. /* Class name added to elements to indicate already configured with a time picker. */
  119. markerClassName: 'hasTimepicker',
  120. /* Debug logging (if enabled). */
  121. log: function () {
  122. if (this.debug)
  123. console.log.apply('', arguments);
  124. },
  125. _widgetTimepicker: function () {
  126. return this.tpDiv;
  127. },
  128. /* Override the default settings for all instances of the time picker.
  129. @param settings object - the new settings to use as defaults (anonymous object)
  130. @return the manager object */
  131. setDefaults: function (settings) {
  132. extendRemove(this._defaults, settings || {});
  133. return this;
  134. },
  135. /* Attach the time picker to a jQuery selection.
  136. @param target element - the target input field or division or span
  137. @param settings object - the new settings to use for this time picker instance (anonymous) */
  138. _attachTimepicker: function (target, settings) {
  139. // check for settings on the control itself - in namespace 'time:'
  140. var inlineSettings = null;
  141. for (var attrName in this._defaults) {
  142. var attrValue = target.getAttribute('time:' + attrName);
  143. if (attrValue) {
  144. inlineSettings = inlineSettings || {};
  145. try {
  146. inlineSettings[attrName] = eval(attrValue);
  147. } catch (err) {
  148. inlineSettings[attrName] = attrValue;
  149. }
  150. }
  151. }
  152. var nodeName = target.nodeName.toLowerCase();
  153. var inline = (nodeName == 'div' || nodeName == 'span');
  154. if (!target.id) {
  155. this.uuid += 1;
  156. target.id = 'tp' + this.uuid;
  157. }
  158. var inst = this._newInst($(target), inline);
  159. inst.settings = $.extend({}, settings || {}, inlineSettings || {});
  160. if (nodeName == 'input') {
  161. this._connectTimepicker(target, inst);
  162. // init inst.hours and inst.minutes from the input value
  163. this._setTimeFromField(inst);
  164. } else if (inline) {
  165. this._inlineTimepicker(target, inst);
  166. }
  167. },
  168. /* Create a new instance object. */
  169. _newInst: function (target, inline) {
  170. var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars
  171. return {
  172. id: id, input: target, // associated target
  173. inline: inline, // is timepicker inline or not :
  174. tpDiv: (!inline ? this.tpDiv : // presentation div
  175. $('<div class="' + this._inlineClass + ' ui-timepicker ui-widget ui-helper-clearfix"></div>'))
  176. };
  177. },
  178. /* Attach the time picker to an input field. */
  179. _connectTimepicker: function (target, inst) {
  180. var input = $(target);
  181. inst.append = $([]);
  182. inst.trigger = $([]);
  183. if (input.hasClass(this.markerClassName)) { return; }
  184. this._attachments(input, inst);
  185. input.addClass(this.markerClassName).
  186. keydown(this._doKeyDown).
  187. keyup(this._doKeyUp).
  188. bind("setData.timepicker", function (event, key, value) {
  189. inst.settings[key] = value;
  190. }).
  191. bind("getData.timepicker", function (event, key) {
  192. return this._get(inst, key);
  193. });
  194. $.data(target, PROP_NAME, inst);
  195. },
  196. /* Handle keystrokes. */
  197. _doKeyDown: function (event) {
  198. var inst = $.timepicker._getInst(event.target);
  199. var handled = true;
  200. inst._keyEvent = true;
  201. if ($.timepicker._timepickerShowing) {
  202. switch (event.keyCode) {
  203. case 9: $.timepicker._hideTimepicker();
  204. handled = false;
  205. break; // hide on tab out
  206. case 13:
  207. $.timepicker._updateSelectedValue(inst);
  208. $.timepicker._hideTimepicker();
  209. return false; // don't submit the form
  210. break; // select the value on enter
  211. case 27: $.timepicker._hideTimepicker();
  212. break; // hide on escape
  213. default: handled = false;
  214. }
  215. }
  216. else if (event.keyCode == 36 && event.ctrlKey) { // display the time picker on ctrl+home
  217. $.timepicker._showTimepicker(this);
  218. }
  219. else {
  220. handled = false;
  221. }
  222. if (handled) {
  223. event.preventDefault();
  224. event.stopPropagation();
  225. }
  226. },
  227. /* Update selected time on keyUp */
  228. /* Added verion 0.0.5 */
  229. _doKeyUp: function (event) {
  230. var inst = $.timepicker._getInst(event.target);
  231. $.timepicker._setTimeFromField(inst);
  232. $.timepicker._updateTimepicker(inst);
  233. },
  234. /* Make attachments based on settings. */
  235. _attachments: function (input, inst) {
  236. var appendText = this._get(inst, 'appendText');
  237. var isRTL = this._get(inst, 'isRTL');
  238. if (inst.append) { inst.append.remove(); }
  239. if (appendText) {
  240. inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>');
  241. input[isRTL ? 'before' : 'after'](inst.append);
  242. }
  243. input.unbind('focus.timepicker', this._showTimepicker);
  244. if (inst.trigger) { inst.trigger.remove(); }
  245. var showOn = this._get(inst, 'showOn');
  246. if (showOn == 'focus' || showOn == 'both') { // pop-up time picker when in the marked field
  247. input.bind("focus.timepicker", this._showTimepicker);
  248. }
  249. if (showOn == 'button' || showOn == 'both') { // pop-up time picker when 'button' element is clicked
  250. var button = this._get(inst, 'button');
  251. $(button).bind("click.timepicker", function () {
  252. if ($.timepicker._timepickerShowing && $.timepicker._lastInput == input[0]) { $.timepicker._hideTimepicker(); }
  253. else { $.timepicker._showTimepicker(input[0]); }
  254. return false;
  255. });
  256. }
  257. },
  258. /* Attach an inline time picker to a div. */
  259. _inlineTimepicker: function(target, inst) {
  260. var divSpan = $(target);
  261. if (divSpan.hasClass(this.markerClassName))
  262. return;
  263. divSpan.addClass(this.markerClassName).append(inst.tpDiv).
  264. bind("setData.timepicker", function(event, key, value){
  265. inst.settings[key] = value;
  266. }).bind("getData.timepicker", function(event, key){
  267. return this._get(inst, key);
  268. });
  269. $.data(target, PROP_NAME, inst);
  270. this._setTimeFromField(inst);
  271. this._updateTimepicker(inst);
  272. inst.tpDiv.show();
  273. },
  274. /* Pop-up the time picker for a given input field.
  275. @param input element - the input field attached to the time picker or
  276. event - if triggered by focus */
  277. _showTimepicker: function (input) {
  278. input = input.target || input;
  279. if (input.nodeName.toLowerCase() != 'input') { input = $('input', input.parentNode)[0]; } // find from button/image trigger
  280. if ($.timepicker._isDisabledTimepicker(input) || $.timepicker._lastInput == input) { return; } // already here
  281. // fix v 0.0.8 - close current timepicker before showing another one
  282. $.timepicker._hideTimepicker();
  283. var inst = $.timepicker._getInst(input);
  284. if ($.timepicker._curInst && $.timepicker._curInst != inst) {
  285. $.timepicker._curInst.tpDiv.stop(true, true);
  286. }
  287. var beforeShow = $.timepicker._get(inst, 'beforeShow');
  288. extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
  289. inst.lastVal = null;
  290. $.timepicker._lastInput = input;
  291. $.timepicker._setTimeFromField(inst);
  292. // calculate default position
  293. if ($.timepicker._inDialog) { input.value = ''; } // hide cursor
  294. if (!$.timepicker._pos) { // position below input
  295. $.timepicker._pos = $.timepicker._findPos(input);
  296. $.timepicker._pos[1] += input.offsetHeight; // add the height
  297. }
  298. var isFixed = false;
  299. $(input).parents().each(function () {
  300. isFixed |= $(this).css('position') == 'fixed';
  301. return !isFixed;
  302. });
  303. if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
  304. $.timepicker._pos[0] -= document.documentElement.scrollLeft;
  305. $.timepicker._pos[1] -= document.documentElement.scrollTop;
  306. }
  307. var offset = { left: $.timepicker._pos[0], top: $.timepicker._pos[1] };
  308. $.timepicker._pos = null;
  309. // determine sizing offscreen
  310. inst.tpDiv.css({ position: 'absolute', display: 'block', top: '-1000px' });
  311. $.timepicker._updateTimepicker(inst);
  312. // position with the ui position utility, if loaded
  313. if ( ( ! inst.inline ) && ( typeof $.ui.position == 'object' ) ) {
  314. inst.tpDiv.position({
  315. of: inst.input,
  316. my: $.timepicker._get( inst, 'myPosition' ),
  317. at: $.timepicker._get( inst, 'atPosition' ),
  318. // offset: $( "#offset" ).val(),
  319. // using: using,
  320. collision: 'flip'
  321. });
  322. var offset = inst.tpDiv.offset();
  323. $.timepicker._pos = [offset.top, offset.left];
  324. }
  325. // reset clicked state
  326. inst._hoursClicked = false;
  327. inst._minutesClicked = false;
  328. // fix width for dynamic number of time pickers
  329. // and adjust position before showing
  330. offset = $.timepicker._checkOffset(inst, offset, isFixed);
  331. inst.tpDiv.css({ position: ($.timepicker._inDialog && $.blockUI ?
  332. 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
  333. left: offset.left + 'px', top: offset.top + 'px'
  334. });
  335. if ( ! inst.inline ) {
  336. var showAnim = $.timepicker._get(inst, 'showAnim');
  337. var duration = $.timepicker._get(inst, 'duration');
  338. var postProcess = function () {
  339. $.timepicker._timepickerShowing = true;
  340. var borders = $.timepicker._getBorders(inst.tpDiv);
  341. inst.tpDiv.find('iframe.ui-timepicker-cover'). // IE6- only
  342. css({ left: -borders[0], top: -borders[1],
  343. width: inst.tpDiv.outerWidth(), height: inst.tpDiv.outerHeight()
  344. });
  345. };
  346. // Fixed the zIndex problem for real (I hope) - FG - v 0.2.9
  347. inst.tpDiv.css('zIndex', $.timepicker._getZIndex(input) +1);
  348. if ($.effects && $.effects[showAnim]) {
  349. inst.tpDiv.show(showAnim, $.timepicker._get(inst, 'showOptions'), duration, postProcess);
  350. }
  351. else {
  352. inst.tpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess);
  353. }
  354. if (!showAnim || !duration) { postProcess(); }
  355. if (inst.input.is(':visible') && !inst.input.is(':disabled')) { inst.input.focus(); }
  356. $.timepicker._curInst = inst;
  357. }
  358. },
  359. // This is a copy of the zIndex function of UI core 1.8.??
  360. // Copied in the timepicker to stay backward compatible.
  361. _getZIndex: function (target) {
  362. var elem = $( target ), position, value;
  363. while ( elem.length && elem[ 0 ] !== document ) {
  364. position = elem.css( "position" );
  365. if ( position === "absolute" || position === "relative" || position === "fixed" ) {
  366. value = parseInt( elem.css( "zIndex" ), 10 );
  367. if ( !isNaN( value ) && value !== 0 ) {
  368. return value;
  369. }
  370. }
  371. elem = elem.parent();
  372. }
  373. },
  374. /* Generate the time picker content. */
  375. _updateTimepicker: function (inst) {
  376. inst.tpDiv.empty().append(this._generateHTML(inst));
  377. this._rebindDialogEvents(inst);
  378. },
  379. _rebindDialogEvents: function (inst) {
  380. var borders = $.timepicker._getBorders(inst.tpDiv),
  381. self = this;
  382. inst.tpDiv
  383. .find('iframe.ui-timepicker-cover') // IE6- only
  384. .css({ left: -borders[0], top: -borders[1],
  385. width: inst.tpDiv.outerWidth(), height: inst.tpDiv.outerHeight()
  386. })
  387. .end()
  388. // after the picker html is appended bind the click & double click events (faster in IE this way
  389. // then letting the browser interpret the inline events)
  390. // the binding for the minute cells also exists in _updateMinuteDisplay
  391. .find('.ui-timepicker-minute-cell')
  392. .unbind()
  393. .bind("click", { fromDoubleClick:false }, $.proxy($.timepicker.selectMinutes, this))
  394. .bind("dblclick", { fromDoubleClick:true }, $.proxy($.timepicker.selectMinutes, this))
  395. .end()
  396. .find('.ui-timepicker-hour-cell')
  397. .unbind()
  398. .bind("click", { fromDoubleClick:false }, $.proxy($.timepicker.selectHours, this))
  399. .bind("dblclick", { fromDoubleClick:true }, $.proxy($.timepicker.selectHours, this))
  400. .end()
  401. .find('.ui-timepicker td a')
  402. .unbind()
  403. .bind('mouseout', function () {
  404. $(this).removeClass('ui-state-hover');
  405. if (this.className.indexOf('ui-timepicker-prev') != -1) $(this).removeClass('ui-timepicker-prev-hover');
  406. if (this.className.indexOf('ui-timepicker-next') != -1) $(this).removeClass('ui-timepicker-next-hover');
  407. })
  408. .bind('mouseover', function () {
  409. if ( ! self._isDisabledTimepicker(inst.inline ? inst.tpDiv.parent()[0] : inst.input[0])) {
  410. $(this).parents('.ui-timepicker-calendar').find('a').removeClass('ui-state-hover');
  411. $(this).addClass('ui-state-hover');
  412. if (this.className.indexOf('ui-timepicker-prev') != -1) $(this).addClass('ui-timepicker-prev-hover');
  413. if (this.className.indexOf('ui-timepicker-next') != -1) $(this).addClass('ui-timepicker-next-hover');
  414. }
  415. })
  416. .end()
  417. .find('.' + this._dayOverClass + ' a')
  418. .trigger('mouseover')
  419. .end()
  420. .find('.ui-timepicker-now').bind("click",function(e) {
  421. $.timepicker.selectNow(e);
  422. }).end()
  423. .find('.ui-timepicker-deselect').bind("click",function(e) {
  424. $.timepicker.deselectTime(e);
  425. }).end()
  426. .find('.ui-timepicker-close').bind("click",function(e) {
  427. $.timepicker._hideTimepicker();
  428. }).end();
  429. },
  430. /* Generate the HTML for the current state of the time picker. */
  431. _generateHTML: function (inst) {
  432. var h, m, row, col, html, hoursHtml, minutesHtml = '',
  433. showPeriod = (this._get(inst, 'showPeriod') == true),
  434. showPeriodLabels = (this._get(inst, 'showPeriodLabels') == true),
  435. showLeadingZero = (this._get(inst, 'showLeadingZero') == true),
  436. showHours = (this._get(inst, 'showHours') == true),
  437. showMinutes = (this._get(inst, 'showMinutes') == true),
  438. amPmText = this._get(inst, 'amPmText'),
  439. rows = this._get(inst, 'rows'),
  440. amRows = 0,
  441. pmRows = 0,
  442. amItems = 0,
  443. pmItems = 0,
  444. amFirstRow = 0,
  445. pmFirstRow = 0,
  446. hours = Array(),
  447. hours_options = this._get(inst, 'hours'),
  448. hoursPerRow = null,
  449. hourCounter = 0,
  450. hourLabel = this._get(inst, 'hourText'),
  451. showCloseButton = this._get(inst, 'showCloseButton'),
  452. closeButtonText = this._get(inst, 'closeButtonText'),
  453. showNowButton = this._get(inst, 'showNowButton'),
  454. nowButtonText = this._get(inst, 'nowButtonText'),
  455. showDeselectButton = this._get(inst, 'showDeselectButton'),
  456. deselectButtonText = this._get(inst, 'deselectButtonText'),
  457. showButtonPanel = showCloseButton || showNowButton || showDeselectButton;
  458. // prepare all hours and minutes, makes it easier to distribute by rows
  459. for (h = hours_options.starts; h <= hours_options.ends; h++) {
  460. hours.push (h);
  461. }
  462. hoursPerRow = Math.ceil(hours.length / rows); // always round up
  463. if (showPeriodLabels) {
  464. for (hourCounter = 0; hourCounter < hours.length; hourCounter++) {
  465. if (hours[hourCounter] < 12) {
  466. amItems++;
  467. }
  468. else {
  469. pmItems++;
  470. }
  471. }
  472. hourCounter = 0;
  473. amRows = Math.floor(amItems / hours.length * rows);
  474. pmRows = Math.floor(pmItems / hours.length * rows);
  475. // assign the extra row to the period that is more densly populated
  476. if (rows != amRows + pmRows) {
  477. // Make sure: AM Has Items and either PM Does Not, AM has no rows yet, or AM is more dense
  478. if (amItems && (!pmItems || !amRows || (pmRows && amItems / amRows >= pmItems / pmRows))) {
  479. amRows++;
  480. } else {
  481. pmRows++;
  482. }
  483. }
  484. amFirstRow = Math.min(amRows, 1);
  485. pmFirstRow = amRows + 1;
  486. hoursPerRow = Math.ceil(Math.max(amItems / amRows, pmItems / pmRows));
  487. }
  488. html = '<table class="ui-timepicker-table ui-widget-content ui-corner-all"><tr>';
  489. if (showHours) {
  490. html += '<td class="ui-timepicker-hours">' +
  491. '<div class="ui-timepicker-title ui-widget-header ui-helper-clearfix ui-corner-all">' +
  492. hourLabel +
  493. '</div>' +
  494. '<table class="ui-timepicker">';
  495. for (row = 1; row <= rows; row++) {
  496. html += '<tr>';
  497. // AM
  498. if (row == amFirstRow && showPeriodLabels) {
  499. html += '<th rowspan="' + amRows.toString() + '" class="periods" scope="row">' + amPmText[0] + '</th>';
  500. }
  501. // PM
  502. if (row == pmFirstRow && showPeriodLabels) {
  503. html += '<th rowspan="' + pmRows.toString() + '" class="periods" scope="row">' + amPmText[1] + '</th>';
  504. }
  505. for (col = 1; col <= hoursPerRow; col++) {
  506. if (showPeriodLabels && row < pmFirstRow && hours[hourCounter] >= 12) {
  507. html += this._generateHTMLHourCell(inst, undefined, showPeriod, showLeadingZero);
  508. } else {
  509. html += this._generateHTMLHourCell(inst, hours[hourCounter], showPeriod, showLeadingZero);
  510. hourCounter++;
  511. }
  512. }
  513. html += '</tr>';
  514. }
  515. html += '</tr></table>' + // Close the hours cells table
  516. '</td>'; // Close the Hour td
  517. }
  518. if (showMinutes) {
  519. html += '<td class="ui-timepicker-minutes">';
  520. html += this._generateHTMLMinutes(inst);
  521. html += '</td>';
  522. }
  523. html += '</tr>';
  524. if (showButtonPanel) {
  525. var buttonPanel = '<tr><td colspan="3"><div class="ui-timepicker-buttonpane ui-widget-content">';
  526. if (showNowButton) {
  527. buttonPanel += '<button type="button" class="ui-timepicker-now ui-state-default ui-corner-all" '
  528. + ' data-timepicker-instance-id="#' + inst.id.replace(/\\\\/g,"\\") + '" >'
  529. + nowButtonText + '</button>';
  530. }
  531. if (showDeselectButton) {
  532. buttonPanel += '<button type="button" class="ui-timepicker-deselect ui-state-default ui-corner-all" '
  533. + ' data-timepicker-instance-id="#' + inst.id.replace(/\\\\/g,"\\") + '" >'
  534. + deselectButtonText + '</button>';
  535. }
  536. if (showCloseButton) {
  537. buttonPanel += '<button type="button" class="ui-timepicker-close ui-state-default ui-corner-all" '
  538. + ' data-timepicker-instance-id="#' + inst.id.replace(/\\\\/g,"\\") + '" >'
  539. + closeButtonText + '</button>';
  540. }
  541. html += buttonPanel + '</div></td></tr>';
  542. }
  543. html += '</table>';
  544. /* IE6 IFRAME FIX (taken from datepicker 1.5.3, fixed in 0.1.2 */
  545. html += ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
  546. '<iframe src="javascript:false;" class="ui-timepicker-cover" frameborder="0"></iframe>' : '');
  547. return html;
  548. },
  549. /* Special function that update the minutes selection in currently visible timepicker
  550. * called on hour selection when onMinuteShow is defined */
  551. _updateMinuteDisplay: function (inst) {
  552. var newHtml = this._generateHTMLMinutes(inst);
  553. inst.tpDiv.find('td.ui-timepicker-minutes').html(newHtml);
  554. this._rebindDialogEvents(inst);
  555. // after the picker html is appended bind the click & double click events (faster in IE this way
  556. // then letting the browser interpret the inline events)
  557. // yes I know, duplicate code, sorry
  558. /* .find('.ui-timepicker-minute-cell')
  559. .bind("click", { fromDoubleClick:false }, $.proxy($.timepicker.selectMinutes, this))
  560. .bind("dblclick", { fromDoubleClick:true }, $.proxy($.timepicker.selectMinutes, this));
  561. */
  562. },
  563. /*
  564. * Generate the minutes table
  565. * This is separated from the _generateHTML function because is can be called separately (when hours changes)
  566. */
  567. _generateHTMLMinutes: function (inst) {
  568. var m, row, html = '',
  569. rows = this._get(inst, 'rows'),
  570. minutes = Array(),
  571. minutes_options = this._get(inst, 'minutes'),
  572. minutesPerRow = null,
  573. minuteCounter = 0,
  574. showMinutesLeadingZero = (this._get(inst, 'showMinutesLeadingZero') == true),
  575. onMinuteShow = this._get(inst, 'onMinuteShow'),
  576. minuteLabel = this._get(inst, 'minuteText');
  577. if ( ! minutes_options.starts) {
  578. minutes_options.starts = 0;
  579. }
  580. if ( ! minutes_options.ends) {
  581. minutes_options.ends = 59;
  582. }
  583. for (m = minutes_options.starts; m <= minutes_options.ends; m += minutes_options.interval) {
  584. minutes.push(m);
  585. }
  586. minutesPerRow = Math.round(minutes.length / rows + 0.49); // always round up
  587. /*
  588. * The minutes table
  589. */
  590. // if currently selected minute is not enabled, we have a problem and need to select a new minute.
  591. if (onMinuteShow &&
  592. (onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours , inst.minutes]) == false) ) {
  593. // loop minutes and select first available
  594. for (minuteCounter = 0; minuteCounter < minutes.length; minuteCounter += 1) {
  595. m = minutes[minuteCounter];
  596. if (onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours, m])) {
  597. inst.minutes = m;
  598. break;
  599. }
  600. }
  601. }
  602. html += '<div class="ui-timepicker-title ui-widget-header ui-helper-clearfix ui-corner-all">' +
  603. minuteLabel +
  604. '</div>' +
  605. '<table class="ui-timepicker">';
  606. minuteCounter = 0;
  607. for (row = 1; row <= rows; row++) {
  608. html += '<tr>';
  609. while (minuteCounter < row * minutesPerRow) {
  610. var m = minutes[minuteCounter];
  611. var displayText = '';
  612. if (m !== undefined ) {
  613. displayText = (m < 10) && showMinutesLeadingZero ? "0" + m.toString() : m.toString();
  614. }
  615. html += this._generateHTMLMinuteCell(inst, m, displayText);
  616. minuteCounter++;
  617. }
  618. html += '</tr>';
  619. }
  620. html += '</table>';
  621. return html;
  622. },
  623. /* Generate the content of a "Hour" cell */
  624. _generateHTMLHourCell: function (inst, hour, showPeriod, showLeadingZero) {
  625. var displayHour = hour;
  626. if ((hour > 12) && showPeriod) {
  627. displayHour = hour - 12;
  628. }
  629. if ((displayHour == 0) && showPeriod) {
  630. displayHour = 12;
  631. }
  632. if ((displayHour < 10) && showLeadingZero) {
  633. displayHour = '0' + displayHour;
  634. }
  635. var html = "";
  636. var enabled = true;
  637. var onHourShow = this._get(inst, 'onHourShow'); //custom callback
  638. if (hour == undefined) {
  639. html = '<td><span class="ui-state-default ui-state-disabled">&nbsp;</span></td>';
  640. return html;
  641. }
  642. if (onHourShow) {
  643. enabled = onHourShow.apply((inst.input ? inst.input[0] : null), [hour]);
  644. }
  645. if (enabled) {
  646. html = '<td class="ui-timepicker-hour-cell" data-timepicker-instance-id="#' + inst.id.replace(/\\\\/g,"\\") + '" data-hour="' + hour.toString() + '">' +
  647. '<a class="ui-state-default ' +
  648. (hour == inst.hours ? 'ui-state-active' : '') +
  649. '">' +
  650. displayHour.toString() +
  651. '</a></td>';
  652. }
  653. else {
  654. html =
  655. '<td>' +
  656. '<span class="ui-state-default ui-state-disabled ' +
  657. (hour == inst.hours ? ' ui-state-active ' : ' ') +
  658. '">' +
  659. displayHour.toString() +
  660. '</span>' +
  661. '</td>';
  662. }
  663. return html;
  664. },
  665. /* Generate the content of a "Hour" cell */
  666. _generateHTMLMinuteCell: function (inst, minute, displayText) {
  667. var html = "";
  668. var enabled = true;
  669. var onMinuteShow = this._get(inst, 'onMinuteShow'); //custom callback
  670. if (onMinuteShow) {
  671. //NEW: 2011-02-03 we should give the hour as a parameter as well!
  672. enabled = onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours,minute]); //trigger callback
  673. }
  674. if (minute == undefined) {
  675. html = '<td><span class="ui-state-default ui-state-disabled">&nbsp;</span></td>';
  676. return html;
  677. }
  678. if (enabled) {
  679. html = '<td class="ui-timepicker-minute-cell" data-timepicker-instance-id="#' + inst.id.replace(/\\\\/g,"\\") + '" data-minute="' + minute.toString() + '" >' +
  680. '<a class="ui-state-default ' +
  681. (minute == inst.minutes ? 'ui-state-active' : '') +
  682. '" >' +
  683. displayText +
  684. '</a></td>';
  685. }
  686. else {
  687. html = '<td>' +
  688. '<span class="ui-state-default ui-state-disabled" >' +
  689. displayText +
  690. '</span>' +
  691. '</td>';
  692. }
  693. return html;
  694. },
  695. /* Enable the date picker to a jQuery selection.
  696. @param target element - the target input field or division or span */
  697. _enableTimepicker: function(target) {
  698. var $target = $(target),
  699. target_id = $target.attr('id'),
  700. inst = $.data(target, PROP_NAME);
  701. if (!$target.hasClass(this.markerClassName)) {
  702. return;
  703. }
  704. var nodeName = target.nodeName.toLowerCase();
  705. if (nodeName == 'input') {
  706. target.disabled = false;
  707. inst.trigger.filter('button').
  708. each(function() { this.disabled = false; }).end();
  709. }
  710. else if (nodeName == 'div' || nodeName == 'span') {
  711. var inline = $target.children('.' + this._inlineClass);
  712. inline.children().removeClass('ui-state-disabled');
  713. }
  714. this._disabledInputs = $.map(this._disabledInputs,
  715. function(value) { return (value == target_id ? null : value); }); // delete entry
  716. },
  717. /* Disable the time picker to a jQuery selection.
  718. @param target element - the target input field or division or span */
  719. _disableTimepicker: function(target) {
  720. var $target = $(target);
  721. var inst = $.data(target, PROP_NAME);
  722. if (!$target.hasClass(this.markerClassName)) {
  723. return;
  724. }
  725. var nodeName = target.nodeName.toLowerCase();
  726. if (nodeName == 'input') {
  727. target.disabled = true;
  728. inst.trigger.filter('button').
  729. each(function() { this.disabled = true; }).end();
  730. }
  731. else if (nodeName == 'div' || nodeName == 'span') {
  732. var inline = $target.children('.' + this._inlineClass);
  733. inline.children().addClass('ui-state-disabled');
  734. }
  735. this._disabledInputs = $.map(this._disabledInputs,
  736. function(value) { return (value == target ? null : value); }); // delete entry
  737. this._disabledInputs[this._disabledInputs.length] = $target.attr('id');
  738. },
  739. /* Is the first field in a jQuery collection disabled as a timepicker?
  740. @param target_id element - the target input field or division or span
  741. @return boolean - true if disabled, false if enabled */
  742. _isDisabledTimepicker: function (target_id) {
  743. if ( ! target_id) { return false; }
  744. for (var i = 0; i < this._disabledInputs.length; i++) {
  745. if (this._disabledInputs[i] == target_id) { return true; }
  746. }
  747. return false;
  748. },
  749. /* Check positioning to remain on screen. */
  750. _checkOffset: function (inst, offset, isFixed) {
  751. var tpWidth = inst.tpDiv.outerWidth();
  752. var tpHeight = inst.tpDiv.outerHeight();
  753. var inputWidth = inst.input ? inst.input.outerWidth() : 0;
  754. var inputHeight = inst.input ? inst.input.outerHeight() : 0;
  755. var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft();
  756. var viewHeight = document.documentElement.clientHeight + $(document).scrollTop();
  757. offset.left -= (this._get(inst, 'isRTL') ? (tpWidth - inputWidth) : 0);
  758. offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
  759. offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
  760. // now check if datepicker is showing outside window viewport - move to a better place if so.
  761. offset.left -= Math.min(offset.left, (offset.left + tpWidth > viewWidth && viewWidth > tpWidth) ?
  762. Math.abs(offset.left + tpWidth - viewWidth) : 0);
  763. offset.top -= Math.min(offset.top, (offset.top + tpHeight > viewHeight && viewHeight > tpHeight) ?
  764. Math.abs(tpHeight + inputHeight) : 0);
  765. return offset;
  766. },
  767. /* Find an object's position on the screen. */
  768. _findPos: function (obj) {
  769. var inst = this._getInst(obj);
  770. var isRTL = this._get(inst, 'isRTL');
  771. while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
  772. obj = obj[isRTL ? 'previousSibling' : 'nextSibling'];
  773. }
  774. var position = $(obj).offset();
  775. return [position.left, position.top];
  776. },
  777. /* Retrieve the size of left and top borders for an element.
  778. @param elem (jQuery object) the element of interest
  779. @return (number[2]) the left and top borders */
  780. _getBorders: function (elem) {
  781. var convert = function (value) {
  782. return { thin: 1, medium: 2, thick: 3}[value] || value;
  783. };
  784. return [parseFloat(convert(elem.css('border-left-width'))),
  785. parseFloat(convert(elem.css('border-top-width')))];
  786. },
  787. /* Close time picker if clicked elsewhere. */
  788. _checkExternalClick: function (event) {
  789. if (!$.timepicker._curInst) { return; }
  790. var $target = $(event.target);
  791. if ($target[0].id != $.timepicker._mainDivId &&
  792. $target.parents('#' + $.timepicker._mainDivId).length == 0 &&
  793. !$target.hasClass($.timepicker.markerClassName) &&
  794. !$target.hasClass($.timepicker._triggerClass) &&
  795. $.timepicker._timepickerShowing && !($.timepicker._inDialog && $.blockUI))
  796. $.timepicker._hideTimepicker();
  797. },
  798. /* Hide the time picker from view.
  799. @param input element - the input field attached to the time picker */
  800. _hideTimepicker: function (input) {
  801. var inst = this._curInst;
  802. if (!inst || (input && inst != $.data(input, PROP_NAME))) { return; }
  803. if (this._timepickerShowing) {
  804. var showAnim = this._get(inst, 'showAnim');
  805. var duration = this._get(inst, 'duration');
  806. var postProcess = function () {
  807. $.timepicker._tidyDialog(inst);
  808. this._curInst = null;
  809. };
  810. if ($.effects && $.effects[showAnim]) {
  811. inst.tpDiv.hide(showAnim, $.timepicker._get(inst, 'showOptions'), duration, postProcess);
  812. }
  813. else {
  814. inst.tpDiv[(showAnim == 'slideDown' ? 'slideUp' :
  815. (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess);
  816. }
  817. if (!showAnim) { postProcess(); }
  818. var onClose = this._get(inst, 'onClose');
  819. if (onClose) {
  820. onClose.apply(
  821. (inst.input ? inst.input[0] : null),
  822. [(inst.input ? inst.input.val() : ''), inst]); // trigger custom callback
  823. }
  824. this._timepickerShowing = false;
  825. this._lastInput = null;
  826. if (this._inDialog) {
  827. this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
  828. if ($.blockUI) {
  829. $.unblockUI();
  830. $('body').append(this.tpDiv);
  831. }
  832. }
  833. this._inDialog = false;
  834. }
  835. },
  836. /* Tidy up after a dialog display. */
  837. _tidyDialog: function (inst) {
  838. inst.tpDiv.removeClass(this._dialogClass).unbind('.ui-timepicker');
  839. },
  840. /* Retrieve the instance data for the target control.
  841. @param target element - the target input field or division or span
  842. @return object - the associated instance data
  843. @throws error if a jQuery problem getting data */
  844. _getInst: function (target) {
  845. try {
  846. return $.data(target, PROP_NAME);
  847. }
  848. catch (err) {
  849. throw 'Missing instance data for this timepicker';
  850. }
  851. },
  852. /* Get a setting value, defaulting if necessary. */
  853. _get: function (inst, name) {
  854. return inst.settings[name] !== undefined ?
  855. inst.settings[name] : this._defaults[name];
  856. },
  857. /* Parse existing time and initialise time picker. */
  858. _setTimeFromField: function (inst) {
  859. if (inst.input.val() == inst.lastVal) { return; }
  860. var defaultTime = this._get(inst, 'defaultTime');
  861. var timeToParse = defaultTime == 'now' ? this._getCurrentTimeRounded(inst) : defaultTime;
  862. if ((inst.inline == false) && (inst.input.val() != '')) { timeToParse = inst.input.val() }
  863. if (timeToParse instanceof Date) {
  864. inst.hours = timeToParse.getHours();
  865. inst.minutes = timeToParse.getMinutes();
  866. } else {
  867. var timeVal = inst.lastVal = timeToParse;
  868. if (timeToParse == '') {
  869. inst.hours = -1;
  870. inst.minutes = -1;
  871. } else {
  872. var time = this.parseTime(inst, timeVal);
  873. inst.hours = time.hours;
  874. inst.minutes = time.minutes;
  875. }
  876. }
  877. $.timepicker._updateTimepicker(inst);
  878. },
  879. /* Update or retrieve the settings for an existing time picker.
  880. @param target element - the target input field or division or span
  881. @param name object - the new settings to update or
  882. string - the name of the setting to change or retrieve,
  883. when retrieving also 'all' for all instance settings or
  884. 'defaults' for all global defaults
  885. @param value any - the new value for the setting
  886. (omit if above is an object or to retrieve a value) */
  887. _optionTimepicker: function(target, name, value) {
  888. var inst = this._getInst(target);
  889. if (arguments.length == 2 && typeof name == 'string') {
  890. return (name == 'defaults' ? $.extend({}, $.timepicker._defaults) :
  891. (inst ? (name == 'all' ? $.extend({}, inst.settings) :
  892. this._get(inst, name)) : null));
  893. }
  894. var settings = name || {};
  895. if (typeof name == 'string') {
  896. settings = {};
  897. settings[name] = value;
  898. }
  899. if (inst) {
  900. if (this._curInst == inst) {
  901. this._hideTimepicker();
  902. }
  903. extendRemove(inst.settings, settings);
  904. this._updateTimepicker(inst);
  905. }
  906. },
  907. /* Set the time for a jQuery selection.
  908. @param target element - the target input field or division or span
  909. @param time String - the new time */
  910. _setTimeTimepicker: function(target, time) {
  911. var inst = this._getInst(target);
  912. if (inst) {
  913. this._setTime(inst, time);
  914. this._updateTimepicker(inst);
  915. this._updateAlternate(inst, time);
  916. }
  917. },
  918. /* Set the time directly. */
  919. _setTime: function(inst, time, noChange) {
  920. var origHours = inst.hours;
  921. var origMinutes = inst.minutes;
  922. var time = this.parseTime(inst, time);
  923. inst.hours = time.hours;
  924. inst.minutes = time.minutes;
  925. if ((origHours != inst.hours || origMinutes != inst.minuts) && !noChange) {
  926. inst.input.trigger('change');
  927. }
  928. this._updateTimepicker(inst);
  929. this._updateSelectedValue(inst);
  930. },
  931. /* Return the current time, ready to be parsed, rounded to the closest 5 minute */
  932. _getCurrentTimeRounded: function (inst) {
  933. var currentTime = new Date(),
  934. currentMinutes = currentTime.getMinutes(),
  935. // round to closest 5
  936. adjustedMinutes = Math.round( currentMinutes / 5 ) * 5;
  937. currentTime.setMinutes(adjustedMinutes);
  938. return currentTime;
  939. },
  940. /*
  941. * Parse a time string into hours and minutes
  942. */
  943. parseTime: function (inst, timeVal) {
  944. var retVal = new Object();
  945. retVal.hours = -1;
  946. retVal.minutes = -1;
  947. var timeSeparator = this._get(inst, 'timeSeparator'),
  948. amPmText = this._get(inst, 'amPmText'),
  949. showHours = this._get(inst, 'showHours'),
  950. showMinutes = this._get(inst, 'showMinutes'),
  951. optionalMinutes = this._get(inst, 'optionalMinutes'),
  952. showPeriod = (this._get(inst, 'showPeriod') == true),
  953. p = timeVal.indexOf(timeSeparator);
  954. // check if time separator found
  955. if (p != -1) {
  956. retVal.hours = parseInt(timeVal.substr(0, p), 10);
  957. retVal.minutes = parseInt(timeVal.substr(p + 1), 10);
  958. }
  959. // check for hours only
  960. else if ( (showHours) && ( !showMinutes || optionalMinutes ) ) {
  961. retVal.hours = parseInt(timeVal, 10);
  962. }
  963. // check for minutes only
  964. else if ( ( ! showHours) && (showMinutes) ) {
  965. retVal.minutes = parseInt(timeVal, 10);
  966. }
  967. if (showHours) {
  968. var timeValUpper = timeVal.toUpperCase();
  969. if ((retVal.hours < 12) && (showPeriod) && (timeValUpper.indexOf(amPmText[1].toUpperCase()) != -1)) {
  970. retVal.hours += 12;
  971. }
  972. // fix for 12 AM
  973. if ((retVal.hours == 12) && (showPeriod) && (timeValUpper.indexOf(amPmText[0].toUpperCase()) != -1)) {
  974. retVal.hours = 0;
  975. }
  976. }
  977. return retVal;
  978. },
  979. selectNow: function(e) {
  980. var id = $(e.target).attr("data-timepicker-instance-id"),
  981. $target = $(id),
  982. inst = this._getInst($target[0]);
  983. //if (!inst || (input && inst != $.data(input, PROP_NAME))) { return; }
  984. var currentTime = new Date();
  985. inst.hours = currentTime.getHours();
  986. inst.minutes = currentTime.getMinutes();
  987. this._updateSelectedValue(inst);
  988. this._updateTimepicker(inst);
  989. this._hideTimepicker();
  990. },
  991. deselectTime: function(e) {
  992. var id = $(e.target).attr("data-timepicker-instance-id"),
  993. $target = $(id),
  994. inst = this._getInst($target[0]);
  995. inst.hours = -1;
  996. inst.minutes = -1;
  997. this._updateSelectedValue(inst);
  998. this._hideTimepicker();
  999. },
  1000. selectHours: function (event) {
  1001. var $td = $(event.currentTarget),
  1002. id = $td.attr("data-timepicker-instance-id"),
  1003. newHours = $td.attr("data-hour"),
  1004. fromDoubleClick = event.data.fromDoubleClick,
  1005. $target = $(id),
  1006. inst = this._getInst($target[0]),
  1007. showMinutes = (this._get(inst, 'showMinutes') == true);
  1008. // don't select if disabled
  1009. if ( $.timepicker._isDisabledTimepicker($target.attr('id')) ) { return false }
  1010. $td.parents('.ui-timepicker-hours:first').find('a').removeClass('ui-state-active');
  1011. $td.children('a').addClass('ui-state-active');
  1012. inst.hours = newHours;
  1013. // added for onMinuteShow callback
  1014. var onMinuteShow = this._get(inst, 'onMinuteShow');
  1015. if (onMinuteShow) {
  1016. // this will trigger a callback on selected hour to make sure selected minute is allowed.
  1017. this._updateMinuteDisplay(inst);
  1018. }
  1019. this._updateSelectedValue(inst);
  1020. inst._hoursClicked = true;
  1021. if ((inst._minutesClicked) || (fromDoubleClick) || (showMinutes == false)) {
  1022. $.timepicker._hideTimepicker();
  1023. }
  1024. // return false because if used inline, prevent the url to change to a hashtag
  1025. return false;
  1026. },
  1027. selectMinutes: function (event) {
  1028. var $td = $(event.currentTarget),
  1029. id = $td.attr("data-timepicker-instance-id"),
  1030. newMinutes = $td.attr("data-minute"),
  1031. fromDoubleClick = event.data.fromDoubleClick,
  1032. $target = $(id),
  1033. inst = this._getInst($target[0]),
  1034. showHours = (this._get(inst, 'showHours') == true);
  1035. // don't select if disabled
  1036. if ( $.timepicker._isDisabledTimepicker($target.attr('id')) ) { return false }
  1037. $td.parents('.ui-timepicker-minutes:first').find('a').removeClass('ui-state-active');
  1038. $td.children('a').addClass('ui-state-active');
  1039. inst.minutes = newMinutes;
  1040. this._updateSelectedValue(inst);
  1041. inst._minutesClicked = true;
  1042. if ((inst._hoursClicked) || (fromDoubleClick) || (showHours == false)) {
  1043. $.timepicker._hideTimepicker();
  1044. // return false because if used inline, prevent the url to change to a hashtag
  1045. return false;
  1046. }
  1047. // return false because if used inline, prevent the url to change to a hashtag
  1048. return false;
  1049. },
  1050. _updateSelectedValue: function (inst) {
  1051. var newTime = this._getParsedTime(inst);
  1052. if (inst.input) {
  1053. inst.input.val(newTime);
  1054. inst.input.trigger('change');
  1055. }
  1056. var onSelect = this._get(inst, 'onSelect');
  1057. if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [newTime, inst]); } // trigger custom callback
  1058. this._updateAlternate(inst, newTime);
  1059. return newTime;
  1060. },
  1061. /* this function process selected time and return it parsed according to instance options */
  1062. _getParsedTime: function(inst) {
  1063. if (inst.hours == -1 && inst.minutes == -1) {
  1064. return '';
  1065. }
  1066. if ((inst.hours < 0) || (inst.hours > 23)) { inst.hours = 12; }
  1067. if ((inst.minutes < 0) || (inst.minutes > 59)) { inst.minutes = 0; }
  1068. var period = "",
  1069. showPeriod = (this._get(inst, 'showPeriod') == true),
  1070. showLeadingZero = (this._get(inst, 'showLeadingZero') == true),
  1071. showHours = (this._get(inst, 'showHours') == true),
  1072. showMinutes = (this._get(inst, 'showMinutes') == true),
  1073. optionalMinutes = (this._get(inst, 'optionalMinutes') == true),
  1074. amPmText = this._get(inst, 'amPmText'),
  1075. selectedHours = inst.hours ? inst.hours : 0,
  1076. selectedMinutes = inst.minutes ? inst.minutes : 0,
  1077. displayHours = selectedHours ? selectedHours : 0,
  1078. parsedTime = '';
  1079. if (showPeriod) {
  1080. if (inst.hours == 0) {
  1081. displayHours = 12;
  1082. }
  1083. if (inst.hours < 12) {
  1084. period = amPmText[0];
  1085. }
  1086. else {
  1087. period = amPmText[1];
  1088. if (displayHours > 12) {
  1089. displayHours -= 12;
  1090. }
  1091. }
  1092. }
  1093. var h = displayHours.toString();
  1094. if (showLeadingZero && (displayHours < 10)) { h = '0' + h; }
  1095. var m = selectedMinutes.toString();
  1096. if (selectedMinutes < 10) { m = '0' + m; }
  1097. if (showHours) {
  1098. parsedTime += h;
  1099. }
  1100. if (showHours && showMinutes && (!optionalMinutes || m != 0)) {
  1101. parsedTime += this._get(inst, 'timeSeparator');
  1102. }
  1103. if (showMinutes && (!optionalMinutes || m != 0)) {
  1104. parsedTime += m;
  1105. }
  1106. if (showHours) {
  1107. if (period.length > 0) { parsedTime += this._get(inst, 'periodSeparator') + period; }
  1108. }
  1109. return parsedTime;
  1110. },
  1111. /* Update any alternate field to synchronise with the main field. */
  1112. _updateAlternate: function(inst, newTime) {
  1113. var altField = this._get(inst, 'altField');
  1114. if (altField) { // update alternate field too
  1115. $(altField).each(function(i,e) {
  1116. $(e).val(newTime);
  1117. });
  1118. }
  1119. },
  1120. /* This might look unused but it's called by the $.fn.timepicker function with param getTime */
  1121. /* added v 0.2.3 - gitHub issue #5 - Thanks edanuff */
  1122. _getTimeTimepicker : function(input) {
  1123. var inst = this._getInst(input);
  1124. return this._getParsedTime(inst);
  1125. },
  1126. _getHourTimepicker: function(input) {
  1127. var inst = this._getInst(input);
  1128. if ( inst == undefined) { return -1; }
  1129. return inst.hours;
  1130. },
  1131. _getMinuteTimepicker: function(input) {
  1132. var inst= this._getInst(input);
  1133. if ( inst == undefined) { return -1; }
  1134. return inst.minutes;
  1135. }
  1136. });
  1137. /* Invoke the timepicker functionality.
  1138. @param options string - a command, optionally followed by additional parameters or
  1139. Object - settings for attaching new timepicker functionality
  1140. @return jQuery object */
  1141. $.fn.timepicker = function (options) {
  1142. /* Initialise the time picker. */
  1143. if (!$.timepicker.initialized) {
  1144. $(document).mousedown($.timepicker._checkExternalClick).
  1145. find('body').append($.timepicker.tpDiv);
  1146. $.timepicker.initialized = true;
  1147. }
  1148. var otherArgs = Array.prototype.slice.call(arguments, 1);
  1149. if (typeof options == 'string' && (options == 'getTime' || options == 'getHour' || options == 'getMinute' ))
  1150. return $.timepicker['_' + options + 'Timepicker'].
  1151. apply($.timepicker, [this[0]].concat(otherArgs));
  1152. if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string')
  1153. return $.timepicker['_' + options + 'Timepicker'].
  1154. apply($.timepicker, [this[0]].concat(otherArgs));
  1155. return this.each(function () {
  1156. typeof options == 'string' ?
  1157. $.timepicker['_' + options + 'Timepicker'].
  1158. apply($.timepicker, [this].concat(otherArgs)) :
  1159. $.timepicker._attachTimepicker(this, options);
  1160. });
  1161. };
  1162. /* jQuery extend now ignores nulls! */
  1163. function extendRemove(target, props) {
  1164. $.extend(target, props);
  1165. for (var name in props)
  1166. if (props[name] == null || props[name] == undefined)
  1167. target[name] = props[name];
  1168. return target;
  1169. };
  1170. $.timepicker = new Timepicker(); // singleton instance
  1171. $.timepicker.initialized = false;
  1172. $.timepicker.uuid = new Date().getTime();
  1173. $.timepicker.version = "0.2.9";
  1174. // Workaround for #4055
  1175. // Add another global to avoid noConflict issues with inline event handlers
  1176. window['TP_jQuery_' + tpuuid] = $;
  1177. })(jQuery);