PageRenderTime 62ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/public/javascripts/rails_admin/jquery.ui.timepicker.js

https://github.com/rjacoby/rails_admin
JavaScript | 964 lines | 685 code | 118 blank | 161 comment | 213 complexity | be4a7e60952a7b5c343522c6ec36e160 MD5 | raw file
  1. /*
  2. * jQuery UI Timepicker 0.0.8
  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
  9. *
  10. * Depends:
  11. * jquery.ui.core.js
  12. */
  13. /*
  14. * As it is a timepicker, I inspired most of the code from the datepicker
  15. * Francois Gelinas - Nov 2010
  16. *
  17. * Release 0.0.2 - Jan 6, 2011
  18. * Updated to include common display options for USA users
  19. * Stephen Commisso - Jan 2011
  20. *
  21. * release 0.0.3 - Jan 8, 2011
  22. * Re-added a display:none on the main div (fix a small empty div visible at the bottom of the page before timepicker is called) (Thanks Gertjan van Roekel)
  23. * Fixed a problem where the timepicker was never displayed with jquery ui 1.8.7 css,
  24. * the problem was the class ui-helper-hidden-accessible, witch I removed.
  25. * Thanks Alexander Fietz and StackOverflow : http://stackoverflow.com/questions/4522274/jquery-timepicker-and-jqueryui-1-8-7-conflict
  26. *
  27. * Release 0.0.4 - jan 10, 2011
  28. * changed showLeadingZero to affect only hours, added showMinutesLeadingZero for minutes display
  29. * Removed width:100% for tables in css
  30. *
  31. * Release 0.0.5 - Jan 18, 2011
  32. * Now updating time picker selected value when manually typing in the text field (thanks Rasmus Schultz)
  33. * Fixed : with showPeriod: true and showLeadingZero: true, PM hours did not show leading zeros (thanks Chandler May)
  34. * Fixed : with showPeriod: true and showLeadingZero: true, Selecting 12 AM shows as 00 AM in the input field, also parsing 12AM did not work correctly (thanks Rasmus Schultz)
  35. *
  36. * Release 0.0.6 - Jan 19, 2011
  37. * Added standard "change" event being triggered on the input when the content changes. (Thanks Rasmus Schultz)
  38. * Added support for inline timePicker, attached to div or span
  39. * Added altField that receive the parsed time value when selected time changes
  40. * Added defaultTime value to use when input field is missing (inline) or input value is empty
  41. * if defaultTime is missing, current time is used
  42. *
  43. * Release 0.0.7 - Fev 10, 2011
  44. * Added function to set time after initialisation :$('#timepicker').timepicker('setTime',newTime);
  45. * Added support for disabled period of time : onHourShow and onMinuteShow (thanks Rene Felgenträger)
  46. *
  47. * Release 0.0.8 - Fev 17, 2011
  48. * Fixed close event not triggered when switching to another input with time picker (thanks Stuart Gregg)
  49. *
  50. */
  51. (function ($, undefined) {
  52. $.extend($.ui, { timepicker: { version: "0.0.8"} });
  53. var PROP_NAME = 'timepicker';
  54. var tpuuid = new Date().getTime();
  55. /* Time picker manager.
  56. Use the singleton instance of this class, $.timepicker, to interact with the time picker.
  57. Settings for (groups of) time pickers are maintained in an instance object,
  58. allowing multiple different settings on the same page. */
  59. function Timepicker() {
  60. this.debug = true; // Change this to true to start debugging
  61. this._curInst = null; // The current instance in use
  62. this._isInline = false; // true if the instance is displayed inline
  63. this._disabledInputs = []; // List of time picker inputs that have been disabled
  64. this._timepickerShowing = false; // True if the popup picker is showing , false if not
  65. this._inDialog = false; // True if showing within a "dialog", false if not
  66. this._dialogClass = 'ui-timepicker-dialog'; // The name of the dialog marker class
  67. this._mainDivId = 'ui-timepicker-div'; // The ID of the main timepicker division
  68. this._inlineClass = 'ui-timepicker-inline'; // The name of the inline marker class
  69. this._currentClass = 'ui-timepicker-current'; // The name of the current hour / minutes marker class
  70. this._dayOverClass = 'ui-timepicker-days-cell-over'; // The name of the day hover marker class
  71. this.regional = []; // Available regional settings, indexed by language code
  72. this.regional[''] = { // Default regional settings
  73. hourText: 'Hour', // Display text for hours section
  74. minuteText: 'Minute', // Display text for minutes link
  75. amPmText: ['AM', 'PM'] // Display text for AM PM
  76. };
  77. this._defaults = { // Global defaults for all the time picker instances
  78. showOn: 'focus', // 'focus' for popup on focus,
  79. // 'button' for trigger button, or 'both' for either (not yet implemented)
  80. showAnim: 'fadeIn', // Name of jQuery animation for popup
  81. showOptions: {}, // Options for enhanced animations
  82. appendText: '', // Display text following the input box, e.g. showing the format
  83. onSelect: null, // Define a callback function when a hour / minutes is selected
  84. onClose: null, // Define a callback function when the timepicker is closed
  85. timeSeparator: ':', // The caracter to use to separate hours and minutes.
  86. showPeriod: false, // Define whether or not to show AM/PM with selected time
  87. showLeadingZero: true, // Define whether or not to show a leading zero for hours < 10. [true/false]
  88. showMinutesLeadingZero: true, // Define whether or not to show a leading zero for minutes < 10.
  89. altField: '', // Selector for an alternate field to store selected time into
  90. defaultTime: '', // Used as default time when input field is empty or for inline timePicker
  91. //NEW: 2011-02-03
  92. onHourShow: null, // callback for enabling / disabling on selectable hours ex : function(hour) { return true; }
  93. onMinuteShow: null // callback for enabling / disabling on time selection ex : function(hour,minute) { return true; }
  94. };
  95. $.extend(this._defaults, this.regional['']);
  96. this.tpDiv = $('<div id="' + this._mainDivId + '" class="ui-timepicker ui-widget ui-helper-clearfix ui-corner-all " style="display: none"></div>');
  97. }
  98. $.extend(Timepicker.prototype, {
  99. /* Class name added to elements to indicate already configured with a time picker. */
  100. markerClassName: 'hasTimepicker',
  101. /* Debug logging (if enabled). */
  102. log: function () {
  103. if (this.debug)
  104. console.log.apply('', arguments);
  105. },
  106. // TODO rename to "widget" when switching to widget factory
  107. _widgetTimepicker: function () {
  108. return this.tpDiv;
  109. },
  110. /* Override the default settings for all instances of the time picker.
  111. @param settings object - the new settings to use as defaults (anonymous object)
  112. @return the manager object */
  113. setDefaults: function (settings) {
  114. extendRemove(this._defaults, settings || {});
  115. return this;
  116. },
  117. /* Attach the time picker to a jQuery selection.
  118. @param target element - the target input field or division or span
  119. @param settings object - the new settings to use for this time picker instance (anonymous) */
  120. _attachTimepicker: function (target, settings) {
  121. // check for settings on the control itself - in namespace 'time:'
  122. var inlineSettings = null;
  123. for (var attrName in this._defaults) {
  124. var attrValue = target.getAttribute('time:' + attrName);
  125. if (attrValue) {
  126. inlineSettings = inlineSettings || {};
  127. try {
  128. inlineSettings[attrName] = eval(attrValue);
  129. } catch (err) {
  130. inlineSettings[attrName] = attrValue;
  131. }
  132. }
  133. }
  134. var nodeName = target.nodeName.toLowerCase();
  135. var inline = (nodeName == 'div' || nodeName == 'span');
  136. if (!target.id) {
  137. this.uuid += 1;
  138. target.id = 'tp' + this.uuid;
  139. }
  140. var inst = this._newInst($(target), inline);
  141. inst.settings = $.extend({}, settings || {}, inlineSettings || {});
  142. if (nodeName == 'input') {
  143. this._connectTimepicker(target, inst);
  144. } else if (inline) {
  145. this._inlineTimepicker(target, inst);
  146. }
  147. },
  148. /* Create a new instance object. */
  149. _newInst: function (target, inline) {
  150. var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars
  151. return { id: id, input: target, // associated target
  152. selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
  153. drawMonth: 0, drawYear: 0, // month being drawn
  154. inline: inline, // is timepicker inline or not :
  155. tpDiv: (!inline ? this.tpDiv : // presentation div
  156. $('<div class="' + this._inlineClass + ' ui-timepicker ui-widget ui-helper-clearfix"></div>'))
  157. };
  158. },
  159. /* Attach the time picker to an input field. */
  160. _connectTimepicker: function (target, inst) {
  161. var input = $(target);
  162. inst.append = $([]);
  163. inst.trigger = $([]);
  164. if (input.hasClass(this.markerClassName)) { return; }
  165. this._attachments(input, inst);
  166. input.addClass(this.markerClassName).
  167. keydown(this._doKeyDown).
  168. keyup(this._doKeyUp).
  169. bind("setData.timepicker", function (event, key, value) {
  170. inst.settings[key] = value;
  171. }).
  172. bind("getData.timepicker", function (event, key) {
  173. return this._get(inst, key);
  174. });
  175. //this._autoSize(inst);
  176. $.data(target, PROP_NAME, inst);
  177. },
  178. /* Handle keystrokes. */
  179. _doKeyDown: function (event) {
  180. var inst = $.timepicker._getInst(event.target);
  181. var handled = true;
  182. inst._keyEvent = true;
  183. if ($.timepicker._timepickerShowing) {
  184. switch (event.keyCode) {
  185. case 9: $.timepicker._hideTimepicker();
  186. handled = false;
  187. break; // hide on tab out
  188. case 27: $.timepicker._hideTimepicker();
  189. break; // hide on escape
  190. default: handled = false;
  191. }
  192. }
  193. else if (event.keyCode == 36 && event.ctrlKey) { // display the time picker on ctrl+home
  194. $.timepicker._showTimepicker(this);
  195. }
  196. else {
  197. handled = false;
  198. }
  199. if (handled) {
  200. event.preventDefault();
  201. event.stopPropagation();
  202. }
  203. },
  204. /* Update selected time on keyUp */
  205. /* Added verion 0.0.5 */
  206. _doKeyUp: function (event) {
  207. var inst = $.timepicker._getInst(event.target);
  208. $.timepicker._setTimeFromField(inst);
  209. $.timepicker._updateTimepicker(inst);
  210. },
  211. /* Make attachments based on settings. */
  212. _attachments: function (input, inst) {
  213. var appendText = this._get(inst, 'appendText');
  214. var isRTL = this._get(inst, 'isRTL');
  215. if (inst.append) { inst.append.remove(); }
  216. if (appendText) {
  217. inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>');
  218. input[isRTL ? 'before' : 'after'](inst.append);
  219. }
  220. input.unbind('focus', this._showTimepicker);
  221. if (inst.trigger) { inst.trigger.remove(); }
  222. var showOn = this._get(inst, 'showOn');
  223. if (showOn == 'focus' || showOn == 'both') { // pop-up time picker when in the marked field
  224. input.focus(this._showTimepicker);
  225. }
  226. if (showOn == 'button' || showOn == 'both') { // pop-up time picker when button clicked
  227. var buttonText = this._get(inst, 'buttonText');
  228. var buttonImage = this._get(inst, 'buttonImage');
  229. inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
  230. $('<img/>').addClass(this._triggerClass).
  231. attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
  232. $('<button type="button"></button>').addClass(this._triggerClass).
  233. html(buttonImage == '' ? buttonText : $('<img/>').attr(
  234. { src: buttonImage, alt: buttonText, title: buttonText })));
  235. input[isRTL ? 'before' : 'after'](inst.trigger);
  236. inst.trigger.click(function () {
  237. if ($.timepicker._timepickerShowing && $.timepicker._lastInput == input[0]) { $.timepicker._hideTimepicker(); }
  238. else { $.timepicker._showTimepicker(input[0]); }
  239. return false;
  240. });
  241. }
  242. },
  243. /* Attach an inline time picker to a div. */
  244. _inlineTimepicker: function(target, inst) {
  245. var divSpan = $(target);
  246. if (divSpan.hasClass(this.markerClassName))
  247. return;
  248. divSpan.addClass(this.markerClassName).append(inst.tpDiv).
  249. bind("setData.timepicker", function(event, key, value){
  250. inst.settings[key] = value;
  251. }).bind("getData.timepicker", function(event, key){
  252. return this._get(inst, key);
  253. });
  254. $.data(target, PROP_NAME, inst);
  255. this._setTimeFromField(inst);
  256. this._updateTimepicker(inst);
  257. inst.tpDiv.show();
  258. },
  259. /* Pop-up the time picker for a given input field.
  260. @param input element - the input field attached to the time picker or
  261. event - if triggered by focus */
  262. _showTimepicker: function (input) {
  263. input = input.target || input;
  264. if (input.nodeName.toLowerCase() != 'input') { input = $('input', input.parentNode)[0]; } // find from button/image trigger
  265. if ($.timepicker._isDisabledTimepicker(input) || $.timepicker._lastInput == input) { return; } // already here
  266. // fix v 0.0.8 - close current timepicker before showing another one
  267. $.timepicker._hideTimepicker();
  268. var inst = $.timepicker._getInst(input);
  269. if ($.timepicker._curInst && $.timepicker._curInst != inst) {
  270. $.timepicker._curInst.tpDiv.stop(true, true);
  271. }
  272. var beforeShow = $.timepicker._get(inst, 'beforeShow');
  273. extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
  274. inst.lastVal = null;
  275. $.timepicker._lastInput = input;
  276. $.timepicker._setTimeFromField(inst);
  277. if ($.timepicker._inDialog) { input.value = ''; } // hide cursor
  278. if (!$.timepicker._pos) { // position below input
  279. $.timepicker._pos = $.timepicker._findPos(input);
  280. $.timepicker._pos[1] += input.offsetHeight; // add the height
  281. }
  282. var isFixed = false;
  283. $(input).parents().each(function () {
  284. isFixed |= $(this).css('position') == 'fixed';
  285. return !isFixed;
  286. });
  287. if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
  288. $.timepicker._pos[0] -= document.documentElement.scrollLeft;
  289. $.timepicker._pos[1] -= document.documentElement.scrollTop;
  290. }
  291. var offset = { left: $.timepicker._pos[0], top: $.timepicker._pos[1] };
  292. $.timepicker._pos = null;
  293. // determine sizing offscreen
  294. inst.tpDiv.css({ position: 'absolute', display: 'block', top: '-1000px' });
  295. $.timepicker._updateTimepicker(inst);
  296. // reset clicked state
  297. inst._hoursClicked = false;
  298. inst._minutesClicked = false;
  299. // fix width for dynamic number of time pickers
  300. // and adjust position before showing
  301. offset = $.timepicker._checkOffset(inst, offset, isFixed);
  302. inst.tpDiv.css({ position: ($.timepicker._inDialog && $.blockUI ?
  303. 'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
  304. left: offset.left + 'px', top: offset.top + 'px'
  305. });
  306. if (!inst.inline) {
  307. var showAnim = $.timepicker._get(inst, 'showAnim');
  308. var duration = $.timepicker._get(inst, 'duration');
  309. var postProcess = function () {
  310. $.timepicker._timepickerShowing = true;
  311. var borders = $.timepicker._getBorders(inst.tpDiv);
  312. inst.tpDiv.find('iframe.ui-timepicker-cover'). // IE6- only
  313. css({ left: -borders[0], top: -borders[1],
  314. width: inst.tpDiv.outerWidth(), height: inst.tpDiv.outerHeight()
  315. });
  316. };
  317. inst.tpDiv.zIndex($(input).zIndex() + 1);
  318. if ($.effects && $.effects[showAnim]) {
  319. inst.tpDiv.show(showAnim, $.timepicker._get(inst, 'showOptions'), duration, postProcess);
  320. }
  321. else {
  322. inst.tpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess);
  323. }
  324. if (!showAnim || !duration) { postProcess(); }
  325. if (inst.input.is(':visible') && !inst.input.is(':disabled')) { inst.input.focus(); }
  326. $.timepicker._curInst = inst;
  327. }
  328. },
  329. /* Generate the time picker content. */
  330. _updateTimepicker: function (inst) {
  331. var self = this;
  332. var borders = $.timepicker._getBorders(inst.tpDiv);
  333. inst.tpDiv.empty().append(this._generateHTML(inst))
  334. .find('iframe.ui-timepicker-cover') // IE6- only
  335. .css({ left: -borders[0], top: -borders[1],
  336. width: inst.tpDiv.outerWidth(), height: inst.tpDiv.outerHeight()
  337. })
  338. .end()
  339. .find('.ui-timepicker td a')
  340. .bind('mouseout', function () {
  341. $(this).removeClass('ui-state-hover');
  342. if (this.className.indexOf('ui-timepicker-prev') != -1) $(this).removeClass('ui-timepicker-prev-hover');
  343. if (this.className.indexOf('ui-timepicker-next') != -1) $(this).removeClass('ui-timepicker-next-hover');
  344. })
  345. .bind('mouseover', function () {
  346. if (!self._isDisabledTimepicker(inst.inline ? inst.tpDiv.parent()[0] : inst.input[0])) {
  347. $(this).parents('.ui-timepicker-calendar').find('a').removeClass('ui-state-hover');
  348. $(this).addClass('ui-state-hover');
  349. if (this.className.indexOf('ui-timepicker-prev') != -1) $(this).addClass('ui-timepicker-prev-hover');
  350. if (this.className.indexOf('ui-timepicker-next') != -1) $(this).addClass('ui-timepicker-next-hover');
  351. }
  352. })
  353. .end()
  354. .find('.' + this._dayOverClass + ' a')
  355. .trigger('mouseover')
  356. .end();
  357. },
  358. /* Generate the HTML for the current state of the date picker. */
  359. _generateHTML: function (inst) {
  360. var h, m, html = '';
  361. var showPeriod = (this._get(inst, 'showPeriod') == true);
  362. var showLeadingZero = (this._get(inst, 'showLeadingZero') == true);
  363. var amPmText = this._get(inst, 'amPmText');
  364. html = '<table class="ui-timepicker-table ui-widget-content ui-corner-all"><tr>' +
  365. '<td class="ui-timepicker-hours">' +
  366. '<div class="ui-timepicker-title ui-widget-header ui-helper-clearfix ui-corner-all">' +
  367. this._get(inst, 'hourText') +
  368. '</div>' +
  369. '<table class="ui-timepicker">';
  370. // AM
  371. html += '<tr><th rowspan="2" class="periods">' + amPmText[0] + '</th>';
  372. for (h = 0; h <= 5; h++) {
  373. html += this._generateHTMLHourCell(inst, h, showPeriod, showLeadingZero);
  374. }
  375. html += '</tr><tr>';
  376. for (h = 6; h <= 11; h++) {
  377. html += this._generateHTMLHourCell(inst, h, showPeriod, showLeadingZero);
  378. }
  379. // PM
  380. html += '</tr><tr><th rowspan="2" class="periods">' + amPmText[1] + '</th>';
  381. for (h = 12; h <= 17; h++) {
  382. html += this._generateHTMLHourCell(inst, h, showPeriod, showLeadingZero);
  383. }
  384. html += '</tr><tr>';
  385. for (h = 18; h <= 23; h++) {
  386. html += this._generateHTMLHourCell(inst, h, showPeriod, showLeadingZero);
  387. }
  388. html += '</tr></table>' + // Close the hours cells table
  389. '</td>' + // Close the Hour td
  390. '<td class="ui-timepicker-minutes">';
  391. html += this._generateHTMLMinutes(inst);
  392. html += '</td></tr></table>';
  393. return html;
  394. },
  395. /* Special function that update the minutes selection in currently visible timepicker
  396. * called on hour selection when onMinuteShow is defined */
  397. _updateMinuteDisplay: function (inst) {
  398. var newHtml = this._generateHTMLMinutes(inst);
  399. inst.tpDiv.find('td.ui-timepicker-minutes').html(newHtml);
  400. },
  401. /* Generate the minutes table */
  402. _generateHTMLMinutes: function (inst) {
  403. var m;
  404. var showMinutesLeadingZero = (this._get(inst, 'showMinutesLeadingZero') == true);
  405. var onMinuteShow = this._get(inst, 'onMinuteShow');
  406. // if currently selected minute is not enabled, we have a problem and need to select a new minute.
  407. if ( (onMinuteShow) ) {
  408. if (onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours , inst.minutes]) == false) {
  409. // loop minutes and select first available
  410. for (m = 0; m < 60; m += 5) {
  411. if (onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours, m])) {
  412. inst.minutes = m;
  413. break;
  414. }
  415. }
  416. }
  417. }
  418. var html = '' + // open minutes td
  419. /* Add the minutes */
  420. '<div class="ui-timepicker-title ui-widget-header ui-helper-clearfix ui-corner-all">' +
  421. this._get(inst, 'minuteText') +
  422. '</div>' +
  423. '<table class="ui-timepicker">' +
  424. '<tr>';
  425. ;
  426. for (m = 0; m < 15; m += 5) {
  427. html += this._generateHTMLMinuteCell(inst, m, (m < 10) && showMinutesLeadingZero ? "0" + m.toString() : m.toString());
  428. }
  429. html += '</tr><tr>';
  430. for (m = 15; m < 30; m += 5) {
  431. html += this._generateHTMLMinuteCell(inst, m, m.toString());
  432. }
  433. html += '</tr><tr>';
  434. for (m = 30; m < 45; m += 5) {
  435. html += this._generateHTMLMinuteCell(inst, m, m.toString());
  436. }
  437. html += '</tr><tr>';
  438. for (m = 45; m < 60; m += 5) {
  439. html += this._generateHTMLMinuteCell(inst, m, m.toString());
  440. }
  441. html += '</tr></table>';
  442. return html;
  443. },
  444. /* Generate the content of a "Hour" cell */
  445. _generateHTMLHourCell: function (inst, hour, showPeriod, showLeadingZero) {
  446. var displayHour = hour;
  447. if ((hour > 12) && showPeriod) {
  448. displayHour = hour - 12;
  449. }
  450. if ((displayHour == 0) && showPeriod) {
  451. displayHour = 12;
  452. }
  453. if ((displayHour < 10) && showLeadingZero) {
  454. displayHour = '0' + displayHour;
  455. }
  456. var html = "";
  457. var enabled = true;
  458. var onHourShow = this._get(inst, 'onHourShow'); //custom callback
  459. if (onHourShow) {
  460. enabled = onHourShow.apply((inst.input ? inst.input[0] : null), [hour]);
  461. }
  462. if (enabled) {
  463. html = '<td ' +
  464. 'onclick="TP_jQuery_' + tpuuid + '.timepicker.selectHours(\'#' + inst.id + '\', ' + hour.toString() + ', this ); return false;" ' +
  465. 'ondblclick="TP_jQuery_' + tpuuid + '.timepicker.selectHours(\'#' + inst.id + '\', ' + hour.toString() + ', this, true ); return false;" ' +
  466. '>' +
  467. '<a href="#" class="ui-state-default ' +
  468. (hour == inst.hours ? 'ui-state-active' : '') +
  469. '">' +
  470. displayHour.toString() +
  471. '</a></td>';
  472. }
  473. else {
  474. html =
  475. '<td>' +
  476. '<span class="ui-state-default ui-state-disabled' +
  477. (hour == inst.hours ? 'ui-state-active' : '') +
  478. '">' +
  479. displayHour.toString() +
  480. '</span>' +
  481. '</td>';
  482. }
  483. return html;
  484. },
  485. /* Generate the content of a "Hour" cell */
  486. _generateHTMLMinuteCell: function (inst, minute, displayText) {
  487. var html = "";
  488. var enabled = true;
  489. var onMinuteShow = this._get(inst, 'onMinuteShow'); //custom callback
  490. if (onMinuteShow) {
  491. //NEW: 2011-02-03 we should give the hour as a parameter as well!
  492. enabled = onMinuteShow.apply((inst.input ? inst.input[0] : null), [inst.hours,minute]); //trigger callback
  493. }
  494. if (enabled) {
  495. html = '<td ' +
  496. 'onclick="TP_jQuery_' + tpuuid + '.timepicker.selectMinutes(\'#' + inst.id + '\', ' + minute.toString() + ', this ); return false;" ' +
  497. 'ondblclick="TP_jQuery_' + tpuuid + '.timepicker.selectMinutes(\'#' + inst.id + '\', ' + minute.toString() + ', this, true ); return false;" ' +
  498. '>' +
  499. '<a href="#" class="ui-state-default ' +
  500. (minute == inst.minutes ? 'ui-state-active' : '') +
  501. '" >' +
  502. displayText +
  503. '</a></td>';
  504. }
  505. else {
  506. html = '<td>' +
  507. '<span class="ui-state-default ui-state-disabled" >' +
  508. displayText +
  509. '</span>' +
  510. '</td>';
  511. }
  512. return html;
  513. },
  514. /* Is the first field in a jQuery collection disabled as a timepicker?
  515. @param target element - the target input field or division or span
  516. @return boolean - true if disabled, false if enabled */
  517. _isDisabledTimepicker: function (target) {
  518. if (!target) { return false; }
  519. for (var i = 0; i < this._disabledInputs.length; i++) {
  520. if (this._disabledInputs[i] == target) { return true; }
  521. }
  522. return false;
  523. },
  524. /* Check positioning to remain on screen. */
  525. _checkOffset: function (inst, offset, isFixed) {
  526. var tpWidth = inst.tpDiv.outerWidth();
  527. var tpHeight = inst.tpDiv.outerHeight();
  528. var inputWidth = inst.input ? inst.input.outerWidth() : 0;
  529. var inputHeight = inst.input ? inst.input.outerHeight() : 0;
  530. var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft();
  531. var viewHeight = document.documentElement.clientHeight + $(document).scrollTop();
  532. offset.left -= (this._get(inst, 'isRTL') ? (tpWidth - inputWidth) : 0);
  533. offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
  534. offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
  535. // now check if datepicker is showing outside window viewport - move to a better place if so.
  536. offset.left -= Math.min(offset.left, (offset.left + tpWidth > viewWidth && viewWidth > tpWidth) ?
  537. Math.abs(offset.left + tpWidth - viewWidth) : 0);
  538. offset.top -= Math.min(offset.top, (offset.top + tpHeight > viewHeight && viewHeight > tpHeight) ?
  539. Math.abs(tpHeight + inputHeight) : 0);
  540. return offset;
  541. },
  542. /* Find an object's position on the screen. */
  543. _findPos: function (obj) {
  544. var inst = this._getInst(obj);
  545. var isRTL = this._get(inst, 'isRTL');
  546. while (obj && (obj.type == 'hidden' || obj.nodeType != 1)) {
  547. obj = obj[isRTL ? 'previousSibling' : 'nextSibling'];
  548. }
  549. var position = $(obj).offset();
  550. return [position.left, position.top];
  551. },
  552. /* Retrieve the size of left and top borders for an element.
  553. @param elem (jQuery object) the element of interest
  554. @return (number[2]) the left and top borders */
  555. _getBorders: function (elem) {
  556. var convert = function (value) {
  557. return { thin: 1, medium: 2, thick: 3}[value] || value;
  558. };
  559. return [parseFloat(convert(elem.css('border-left-width'))),
  560. parseFloat(convert(elem.css('border-top-width')))];
  561. },
  562. /* Close time picker if clicked elsewhere. */
  563. _checkExternalClick: function (event) {
  564. if (!$.timepicker._curInst) { return; }
  565. var $target = $(event.target);
  566. if ($target[0].id != $.timepicker._mainDivId &&
  567. $target.parents('#' + $.timepicker._mainDivId).length == 0 &&
  568. !$target.hasClass($.timepicker.markerClassName) &&
  569. !$target.hasClass($.timepicker._triggerClass) &&
  570. $.timepicker._timepickerShowing && !($.timepicker._inDialog && $.blockUI))
  571. $.timepicker._hideTimepicker();
  572. },
  573. /* Hide the time picker from view.
  574. @param input element - the input field attached to the time picker */
  575. _hideTimepicker: function (input) {
  576. var inst = this._curInst;
  577. if (!inst || (input && inst != $.data(input, PROP_NAME))) { return; }
  578. if (this._timepickerShowing) {
  579. var showAnim = this._get(inst, 'showAnim');
  580. var duration = this._get(inst, 'duration');
  581. var postProcess = function () {
  582. $.timepicker._tidyDialog(inst);
  583. this._curInst = null;
  584. };
  585. if ($.effects && $.effects[showAnim]) {
  586. inst.tpDiv.hide(showAnim, $.timepicker._get(inst, 'showOptions'), duration, postProcess);
  587. }
  588. else {
  589. inst.tpDiv[(showAnim == 'slideDown' ? 'slideUp' :
  590. (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess);
  591. }
  592. if (!showAnim) { postProcess(); }
  593. var onClose = this._get(inst, 'onClose');
  594. if (onClose) {
  595. onClose.apply(
  596. (inst.input ? inst.input[0] : null),
  597. [(inst.input ? inst.input.val() : ''), inst]); // trigger custom callback
  598. }
  599. this._timepickerShowing = false;
  600. this._lastInput = null;
  601. if (this._inDialog) {
  602. this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
  603. if ($.blockUI) {
  604. $.unblockUI();
  605. $('body').append(this.tpDiv);
  606. }
  607. }
  608. this._inDialog = false;
  609. }
  610. },
  611. /* Tidy up after a dialog display. */
  612. _tidyDialog: function (inst) {
  613. inst.tpDiv.removeClass(this._dialogClass).unbind('.ui-timepicker');
  614. },
  615. /* Retrieve the instance data for the target control.
  616. @param target element - the target input field or division or span
  617. @return object - the associated instance data
  618. @throws error if a jQuery problem getting data */
  619. _getInst: function (target) {
  620. try {
  621. return $.data(target, PROP_NAME);
  622. }
  623. catch (err) {
  624. throw 'Missing instance data for this timepicker';
  625. }
  626. },
  627. /* Get a setting value, defaulting if necessary. */
  628. _get: function (inst, name) {
  629. return inst.settings[name] !== undefined ?
  630. inst.settings[name] : this._defaults[name];
  631. },
  632. /* Parse existing time and initialise time picker. */
  633. _setTimeFromField: function (inst) {
  634. if (inst.input.val() == inst.lastVal) { return; }
  635. var defaultTime = this._get(inst, 'defaultTime');
  636. var timeToParse = this._getCurrentTimeRounded(inst);
  637. if (defaultTime != '') { timeToParse = defaultTime }
  638. if ((inst.inline == false) && (inst.input.val() != '')) { timeToParse = inst.input.val() }
  639. var timeVal = inst.lastVal = timeToParse;
  640. var time = this.parseTime(inst, timeVal);
  641. inst.hours = time.hours;
  642. inst.minutes = time.minutes;
  643. $.timepicker._updateTimepicker(inst);
  644. },
  645. /* Set the dates for a jQuery selection.
  646. @param target element - the target input field or division or span
  647. @param date Date - the new date */
  648. _setTimeTimepicker: function(target, time) {
  649. var inst = this._getInst(target);
  650. if (inst) {
  651. this._setTime(inst, time);
  652. this._updateTimepicker(inst);
  653. this._updateAlternate(inst);
  654. }
  655. },
  656. /* Set the tm directly. */
  657. _setTime: function(inst, time, noChange) {
  658. var clear = !time;
  659. var origHours = inst.hours;
  660. var origMinutes = inst.minutes;
  661. var time = this.parseTime(inst, time);
  662. inst.hours = time.hours;
  663. inst.minutes = time.minutes;
  664. if ((origHours != inst.hours || origMinutes != inst.minuts) && !noChange) {
  665. inst.input.trigger('change');
  666. }
  667. this._updateTimepicker(inst);
  668. this._updateSelectedValue(inst);
  669. },
  670. /* Return the current time, ready to be parsed, rounded to the closest 5 minute */
  671. _getCurrentTimeRounded: function (inst) {
  672. var currentTime = new Date();
  673. var timeSeparator = this._get(inst, 'timeSeparator');
  674. // setting selected time , least priority first
  675. var currentMinutes = currentTime.getMinutes()
  676. // round to closest 5
  677. currentMinutes = Math.round( currentMinutes / 5 ) * 5;
  678. return currentTime.getHours().toString() + timeSeparator + currentMinutes.toString();
  679. },
  680. /*
  681. * Pase a time string into hours and minutes
  682. */
  683. parseTime: function (inst, timeVal) {
  684. var retVal = new Object();
  685. retVal.hours = -1;
  686. retVal.minutes = -1;
  687. var timeSeparator = this._get(inst, 'timeSeparator');
  688. var amPmText = this._get(inst, 'amPmText');
  689. var p = timeVal.indexOf(timeSeparator);
  690. if (p == -1) { return retVal; }
  691. retVal.hours = parseInt(timeVal.substr(0, p), 10);
  692. retVal.minutes = parseInt(timeVal.substr(p + 1), 10);
  693. var showPeriod = (this._get(inst, 'showPeriod') == true);
  694. var timeValUpper = timeVal.toUpperCase();
  695. if ((retVal.hours < 12) && (showPeriod) && (timeValUpper.indexOf(amPmText[1].toUpperCase()) != -1)) {
  696. retVal.hours += 12;
  697. }
  698. // fix for 12 AM
  699. if ((retVal.hours == 12) && (showPeriod) && (timeValUpper.indexOf(amPmText[0].toUpperCase()) != -1)) {
  700. retVal.hours = 0;
  701. }
  702. return retVal;
  703. },
  704. selectHours: function (id, newHours, td, fromDoubleClick) {
  705. var target = $(id);
  706. var inst = this._getInst(target[0]);
  707. $(td).parents('.ui-timepicker-hours:first').find('a').removeClass('ui-state-active');
  708. //inst.tpDiv.children('.ui-timepicker-hours a').removeClass('ui-state-active');
  709. $(td).children('a').addClass('ui-state-active');
  710. inst.hours = newHours;
  711. this._updateSelectedValue(inst);
  712. inst._hoursClicked = true;
  713. if ((inst._minutesClicked) || (fromDoubleClick)) {
  714. $.timepicker._hideTimepicker();
  715. return;
  716. }
  717. // added for onMinuteShow callback
  718. var onMinuteShow = this._get(inst, 'onMinuteShow');
  719. if (onMinuteShow) { this._updateMinuteDisplay(inst); }
  720. },
  721. selectMinutes: function (id, newMinutes, td, fromDoubleClick) {
  722. var target = $(id);
  723. var inst = this._getInst(target[0]);
  724. $(td).parents('.ui-timepicker-minutes:first').find('a').removeClass('ui-state-active');
  725. $(td).children('a').addClass('ui-state-active');
  726. inst.minutes = newMinutes;
  727. this._updateSelectedValue(inst);
  728. inst._minutesClicked = true;
  729. if ((inst._hoursClicked) || (fromDoubleClick)) { $.timepicker._hideTimepicker(); }
  730. },
  731. _updateSelectedValue: function (inst) {
  732. if ((inst.hours < 0) || (inst.hours > 23)) { inst.hours = 12; }
  733. if ((inst.minutes < 0) || (inst.minutes > 59)) { inst.minutes = 0; }
  734. var period = "";
  735. var showPeriod = (this._get(inst, 'showPeriod') == true);
  736. var showLeadingZero = (this._get(inst, 'showLeadingZero') == true);
  737. var amPmText = this._get(inst, 'amPmText');
  738. var selectedHours = inst.hours ? inst.hours : 0;
  739. var selectedMinutes = inst.minutes ? inst.minutes : 0;
  740. var displayHours = selectedHours;
  741. if ( ! displayHours) {
  742. displayHoyrs = 0;
  743. }
  744. if (showPeriod) {
  745. if (inst.hours == 0) {
  746. displayHours = 12;
  747. }
  748. if (inst.hours < 12) {
  749. period = amPmText[0];
  750. }
  751. else {
  752. period = amPmText[1];
  753. if (displayHours > 12) {
  754. displayHours -= 12;
  755. }
  756. }
  757. }
  758. var h = displayHours.toString();
  759. if (showLeadingZero && (displayHours < 10)) { h = '0' + h; }
  760. var m = selectedMinutes.toString();
  761. if (selectedMinutes < 10) { m = '0' + m; }
  762. var newTime = h + this._get(inst, 'timeSeparator') + m;
  763. if (period.length > 0) { newTime += " " + period; }
  764. if (inst.input) {
  765. inst.input.val(newTime);
  766. inst.input.trigger('change');
  767. }
  768. var onSelect = this._get(inst, 'onSelect');
  769. if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [newTime, inst]); } // trigger custom callback
  770. this._updateAlternate(inst, newTime);
  771. return newTime;
  772. },
  773. /* Update any alternate field to synchronise with the main field. */
  774. _updateAlternate: function(inst, newTime) {
  775. var altField = this._get(inst, 'altField');
  776. if (altField) { // update alternate field too
  777. $(altField).each(function() { $(this).val(newTime); });
  778. }
  779. }
  780. });
  781. /* Invoke the timepicker functionality.
  782. @param options string - a command, optionally followed by additional parameters or
  783. Object - settings for attaching new datepicker functionality
  784. @return jQuery object */
  785. $.fn.timepicker = function (options) {
  786. /* Initialise the date picker. */
  787. if (!$.timepicker.initialized) {
  788. $(document).mousedown($.timepicker._checkExternalClick).
  789. find('body').append($.timepicker.tpDiv);
  790. $.timepicker.initialized = true;
  791. }
  792. var otherArgs = Array.prototype.slice.call(arguments, 1);
  793. if (typeof options == 'string' && (options == 'isDisabled' || options == 'getTime' || options == 'widget'))
  794. return $.timepicker['_' + options + 'Datepicker'].
  795. apply($.timepicker, [this[0]].concat(otherArgs));
  796. if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string')
  797. return $.timepicker['_' + options + 'Datepicker'].
  798. apply($.timepicker, [this[0]].concat(otherArgs));
  799. return this.each(function () {
  800. typeof options == 'string' ?
  801. $.timepicker['_' + options + 'Timepicker'].
  802. apply($.timepicker, [this].concat(otherArgs)) :
  803. $.timepicker._attachTimepicker(this, options);
  804. });
  805. };
  806. /* jQuery extend now ignores nulls! */
  807. function extendRemove(target, props) {
  808. $.extend(target, props);
  809. for (var name in props)
  810. if (props[name] == null || props[name] == undefined)
  811. target[name] = props[name];
  812. return target;
  813. };
  814. $.timepicker = new Timepicker(); // singleton instance
  815. $.timepicker.initialized = false;
  816. $.timepicker.uuid = new Date().getTime();
  817. $.timepicker.version = "1.8.6";
  818. // Workaround for #4055
  819. // Add another global to avoid noConflict issues with inline event handlers
  820. window['TP_jQuery_' + tpuuid] = $;
  821. })(jQuery);
  822. /*
  823. ____
  824. ___ .-~. /_"-._
  825. `-._~-. / /_ "~o\ :Y
  826. \ \ / : \~x. ` ')
  827. ] Y / | Y< ~-.__j
  828. / ! _.--~T : l l< /.-~
  829. / / ____.--~ . ` l /~\ \<|Y
  830. / / .-~~" /| . ',-~\ \L|
  831. / / / .^ \ Y~Y \.^>/l_ "--'
  832. / Y .-"( . l__ j_j l_/ /~_.-~ .
  833. Y l / \ ) ~~~." / `/"~ / \.__/l_
  834. | \ _.-" ~-{__ l : l._Z~-.___.--~
  835. | ~---~ / ~~"---\_ ' __[>
  836. l . _.^ ___ _>-y~
  837. \ \ . .-~ .-~ ~>--" /
  838. \ ~---" / ./ _.-'
  839. "-.,_____.,_ _.--~\ _.-~
  840. ~~ ( _} -Row
  841. `. ~(
  842. ) \
  843. /,`--'~\--'~\
  844. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  845. ->T-Rex<-
  846. */