jquery.datepick.js 83KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056
  1. /* http://keith-wood.name/datepick.html
  2. Date picker for jQuery v4.1.0.
  3. Written by Keith Wood (kbwood{at}iinet.com.au) February 2010.
  4. Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and
  5. MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses.
  6. Please attribute the author if you use it. */
  7. (function($) { // Hide scope, no $ conflict
  8. /* Datepicker manager. */
  9. function Datepicker() {
  10. this._defaults = {
  11. pickerClass: '', // CSS class to add to this instance of the datepicker
  12. showOnFocus: true, // True for popup on focus, false for not
  13. showTrigger: null, // Element to be cloned for a trigger, null for none
  14. showAnim: 'show', // Name of jQuery animation for popup, '' for no animation
  15. showOptions: {}, // Options for enhanced animations
  16. showSpeed: 'normal', // Duration of display/closure
  17. popupContainer: null, // The element to which a popup calendar is added, null for body
  18. alignment: 'bottom', // Alignment of popup - with nominated corner of input:
  19. // 'top' or 'bottom' aligns depending on language direction,
  20. // 'topLeft', 'topRight', 'bottomLeft', 'bottomRight'
  21. fixedWeeks: false, // True to always show 6 weeks, false to only show as many as are needed
  22. firstDay: 0, // First day of the week, 0 = Sunday, 1 = Monday, ...
  23. calculateWeek: this.iso8601Week, // Calculate week of the year from a date, null for ISO8601
  24. monthsToShow: 1, // How many months to show, cols or [rows, cols]
  25. monthsOffset: 0, // How many months to offset the primary month by;
  26. // may be a function that takes the date and returns the offset
  27. monthsToStep: 1, // How many months to move when prev/next clicked
  28. monthsToJump: 12, // How many months to move when large prev/next clicked
  29. useMouseWheel: true, // True to use mousewheel if available, false to never use it
  30. changeMonth: true, // True to change month/year via drop-down, false for navigation only
  31. yearRange: 'c-10:c+10', // Range of years to show in drop-down: 'any' for direct text entry
  32. // or 'start:end', where start/end are '+-nn' for relative to today
  33. // or 'c+-nn' for relative to the currently selected date
  34. // or 'nnnn' for an absolute year
  35. shortYearCutoff: '+10', // Cutoff for two-digit year in the current century
  36. showOtherMonths: false, // True to show dates from other months, false to not show them
  37. selectOtherMonths: false, // True to allow selection of dates from other months too
  38. defaultDate: null, // Date to show if no other selected
  39. selectDefaultDate: false, // True to pre-select the default date if no other is chosen
  40. minDate: null, // The minimum selectable date
  41. maxDate: null, // The maximum selectable date
  42. dateFormat: 'mm/dd/yyyy', // Format for dates
  43. autoSize: false, // True to size the input field according to the date format
  44. rangeSelect: false, // Allows for selecting a date range on one date picker
  45. rangeSeparator: ' - ', // Text between two dates in a range
  46. multiSelect: 0, // Maximum number of selectable dates, zero for single select
  47. multiSeparator: ',', // Text between multiple dates
  48. onDate: null, // Callback as a date is added to the datepicker
  49. onShow: null, // Callback just before a datepicker is shown
  50. onChangeMonthYear: null, // Callback when a new month/year is selected
  51. onSelect: null, // Callback when a date is selected
  52. onClose: null, // Callback when a datepicker is closed
  53. altField: null, // Alternate field to update in synch with the datepicker
  54. altFormat: null, // Date format for alternate field, defaults to dateFormat
  55. constrainInput: true, // True to constrain typed input to dateFormat allowed characters
  56. commandsAsDateFormat: false, // True to apply formatDate to the command texts
  57. commands: this.commands // Command actions that may be added to a layout by name
  58. };
  59. this.regional = [];
  60. this.regional[''] = { // US/English
  61. monthNames: ['January', 'February', 'March', 'April', 'May', 'June',
  62. 'July', 'August', 'September', 'October', 'November', 'December'],
  63. monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  64. dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  65. dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
  66. dayNamesMin: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
  67. dateFormat: 'mm/dd/yyyy', // See options on formatDate
  68. firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
  69. renderer: this.defaultRenderer, // The rendering templates
  70. prevText: '<Prev', // Text for the previous month command
  71. prevStatus: 'Show the previous month', // Status text for the previous month command
  72. prevJumpText: '<<', // Text for the previous year command
  73. prevJumpStatus: 'Show the previous year', // Status text for the previous year command
  74. nextText: 'Next>', // Text for the next month command
  75. nextStatus: 'Show the next month', // Status text for the next month command
  76. nextJumpText: '>>', // Text for the next year command
  77. nextJumpStatus: 'Show the next year', // Status text for the next year command
  78. currentText: 'Current', // Text for the current month command
  79. currentStatus: 'Show the current month', // Status text for the current month command
  80. todayText: 'Today', // Text for the today's month command
  81. todayStatus: 'Show today\'s month', // Status text for the today's month command
  82. clearText: 'Clear', // Text for the clear command
  83. clearStatus: 'Clear all the dates', // Status text for the clear command
  84. closeText: 'Close', // Text for the close command
  85. closeStatus: 'Close the datepicker', // Status text for the close command
  86. yearStatus: 'Change the year', // Status text for year selection
  87. monthStatus: 'Change the month', // Status text for month selection
  88. weekText: 'Wk', // Text for week of the year column header
  89. weekStatus: 'Week of the year', // Status text for week of the year column header
  90. dayStatus: 'Select DD, M d, yyyy', // Status text for selectable days
  91. defaultStatus: 'Select a date', // Status text shown by default
  92. isRTL: false // True if language is right-to-left
  93. };
  94. $.extend(this._defaults, this.regional['']);
  95. this._disabled = [];
  96. }
  97. $.extend(Datepicker.prototype, {
  98. /* Class name added to elements to indicate already configured with datepicker. */
  99. markerClassName: 'hasDatepick',
  100. /* Name of the data property for instance settings. */
  101. propertyName: 'datepick',
  102. _popupClass: 'datepick-popup', // Marker for popup division
  103. _triggerClass: 'datepick-trigger', // Marker for trigger element
  104. _disableClass: 'datepick-disable', // Marker for disabled element
  105. _monthYearClass: 'datepick-month-year', // Marker for month/year inputs
  106. _curMonthClass: 'datepick-month-', // Marker for current month/year
  107. _anyYearClass: 'datepick-any-year', // Marker for year direct input
  108. _curDoWClass: 'datepick-dow-', // Marker for day of week
  109. commands: { // Command actions that may be added to a layout by name
  110. // name: { // The command name, use '{button:name}' or '{link:name}' in layouts
  111. // text: '', // The field in the regional settings for the displayed text
  112. // status: '', // The field in the regional settings for the status text
  113. // // The keystroke to trigger the action
  114. // keystroke: {keyCode: nn, ctrlKey: boolean, altKey: boolean, shiftKey: boolean},
  115. // enabled: fn, // The function that indicates the command is enabled
  116. // date: fn, // The function to get the date associated with this action
  117. // action: fn} // The function that implements the action
  118. prev: {text: 'prevText', status: 'prevStatus', // Previous month
  119. keystroke: {keyCode: 33}, // Page up
  120. enabled: function(inst) {
  121. var minDate = inst.curMinDate();
  122. return (!minDate || plugin.add(plugin.day(
  123. plugin._applyMonthsOffset(plugin.add(plugin.newDate(inst.drawDate),
  124. 1 - inst.options.monthsToStep, 'm'), inst), 1), -1, 'd').
  125. getTime() >= minDate.getTime()); },
  126. date: function(inst) {
  127. return plugin.day(plugin._applyMonthsOffset(plugin.add(
  128. plugin.newDate(inst.drawDate), -inst.options.monthsToStep, 'm'), inst), 1); },
  129. action: function(inst) {
  130. plugin._changeMonthPlugin(this, -inst.options.monthsToStep); }
  131. },
  132. prevJump: {text: 'prevJumpText', status: 'prevJumpStatus', // Previous year
  133. keystroke: {keyCode: 33, ctrlKey: true}, // Ctrl + Page up
  134. enabled: function(inst) {
  135. var minDate = inst.curMinDate();
  136. return (!minDate || plugin.add(plugin.day(
  137. plugin._applyMonthsOffset(plugin.add(plugin.newDate(inst.drawDate),
  138. 1 - inst.options.monthsToJump, 'm'), inst), 1), -1, 'd').
  139. getTime() >= minDate.getTime()); },
  140. date: function(inst) {
  141. return plugin.day(plugin._applyMonthsOffset(plugin.add(
  142. plugin.newDate(inst.drawDate), -inst.options.monthsToJump, 'm'), inst), 1); },
  143. action: function(inst) {
  144. plugin._changeMonthPlugin(this, -inst.options.monthsToJump); }
  145. },
  146. next: {text: 'nextText', status: 'nextStatus', // Next month
  147. keystroke: {keyCode: 34}, // Page down
  148. enabled: function(inst) {
  149. var maxDate = inst.get('maxDate');
  150. return (!maxDate || plugin.day(plugin._applyMonthsOffset(plugin.add(
  151. plugin.newDate(inst.drawDate), inst.options.monthsToStep, 'm'), inst), 1).
  152. getTime() <= maxDate.getTime()); },
  153. date: function(inst) {
  154. return plugin.day(plugin._applyMonthsOffset(plugin.add(
  155. plugin.newDate(inst.drawDate), inst.options.monthsToStep, 'm'), inst), 1); },
  156. action: function(inst) {
  157. plugin._changeMonthPlugin(this, inst.options.monthsToStep); }
  158. },
  159. nextJump: {text: 'nextJumpText', status: 'nextJumpStatus', // Next year
  160. keystroke: {keyCode: 34, ctrlKey: true}, // Ctrl + Page down
  161. enabled: function(inst) {
  162. var maxDate = inst.get('maxDate');
  163. return (!maxDate || plugin.day(plugin._applyMonthsOffset(plugin.add(
  164. plugin.newDate(inst.drawDate), inst.options.monthsToJump, 'm'), inst), 1).
  165. getTime() <= maxDate.getTime()); },
  166. date: function(inst) {
  167. return plugin.day(plugin._applyMonthsOffset(plugin.add(
  168. plugin.newDate(inst.drawDate), inst.options.monthsToJump, 'm'), inst), 1); },
  169. action: function(inst) {
  170. plugin._changeMonthPlugin(this, inst.options.monthsToJump); }
  171. },
  172. current: {text: 'currentText', status: 'currentStatus', // Current month
  173. keystroke: {keyCode: 36, ctrlKey: true}, // Ctrl + Home
  174. enabled: function(inst) {
  175. var minDate = inst.curMinDate();
  176. var maxDate = inst.get('maxDate');
  177. var curDate = inst.selectedDates[0] || plugin.today();
  178. return (!minDate || curDate.getTime() >= minDate.getTime()) &&
  179. (!maxDate || curDate.getTime() <= maxDate.getTime()); },
  180. date: function(inst) {
  181. return inst.selectedDates[0] || plugin.today(); },
  182. action: function(inst) {
  183. var curDate = inst.selectedDates[0] || plugin.today();
  184. plugin._showMonthPlugin(this, curDate.getFullYear(), curDate.getMonth() + 1); }
  185. },
  186. today: {text: 'todayText', status: 'todayStatus', // Today's month
  187. keystroke: {keyCode: 36, ctrlKey: true}, // Ctrl + Home
  188. enabled: function(inst) {
  189. var minDate = inst.curMinDate();
  190. var maxDate = inst.get('maxDate');
  191. return (!minDate || plugin.today().getTime() >= minDate.getTime()) &&
  192. (!maxDate || plugin.today().getTime() <= maxDate.getTime()); },
  193. date: function(inst) { return plugin.today(); },
  194. action: function(inst) { plugin._showMonthPlugin(this); }
  195. },
  196. clear: {text: 'clearText', status: 'clearStatus', // Clear the datepicker
  197. keystroke: {keyCode: 35, ctrlKey: true}, // Ctrl + End
  198. enabled: function(inst) { return true; },
  199. date: function(inst) { return null; },
  200. action: function(inst) { plugin._clearPlugin(this); }
  201. },
  202. close: {text: 'closeText', status: 'closeStatus', // Close the datepicker
  203. keystroke: {keyCode: 27}, // Escape
  204. enabled: function(inst) { return true; },
  205. date: function(inst) { return null; },
  206. action: function(inst) { plugin._hidePlugin(this); }
  207. },
  208. prevWeek: {text: 'prevWeekText', status: 'prevWeekStatus', // Previous week
  209. keystroke: {keyCode: 38, ctrlKey: true}, // Ctrl + Up
  210. enabled: function(inst) {
  211. var minDate = inst.curMinDate();
  212. return (!minDate || plugin.add(plugin.newDate(inst.drawDate), -7, 'd').
  213. getTime() >= minDate.getTime()); },
  214. date: function(inst) { return plugin.add(plugin.newDate(inst.drawDate), -7, 'd'); },
  215. action: function(inst) { plugin._changeDayPlugin(this, -7); }
  216. },
  217. prevDay: {text: 'prevDayText', status: 'prevDayStatus', // Previous day
  218. keystroke: {keyCode: 37, ctrlKey: true}, // Ctrl + Left
  219. enabled: function(inst) {
  220. var minDate = inst.curMinDate();
  221. return (!minDate || plugin.add(plugin.newDate(inst.drawDate), -1, 'd').
  222. getTime() >= minDate.getTime()); },
  223. date: function(inst) { return plugin.add(plugin.newDate(inst.drawDate), -1, 'd'); },
  224. action: function(inst) { plugin._changeDayPlugin(this, -1); }
  225. },
  226. nextDay: {text: 'nextDayText', status: 'nextDayStatus', // Next day
  227. keystroke: {keyCode: 39, ctrlKey: true}, // Ctrl + Right
  228. enabled: function(inst) {
  229. var maxDate = inst.get('maxDate');
  230. return (!maxDate || plugin.add(plugin.newDate(inst.drawDate), 1, 'd').
  231. getTime() <= maxDate.getTime()); },
  232. date: function(inst) { return plugin.add(plugin.newDate(inst.drawDate), 1, 'd'); },
  233. action: function(inst) { plugin._changeDayPlugin(this, 1); }
  234. },
  235. nextWeek: {text: 'nextWeekText', status: 'nextWeekStatus', // Next week
  236. keystroke: {keyCode: 40, ctrlKey: true}, // Ctrl + Down
  237. enabled: function(inst) {
  238. var maxDate = inst.get('maxDate');
  239. return (!maxDate || plugin.add(plugin.newDate(inst.drawDate), 7, 'd').
  240. getTime() <= maxDate.getTime()); },
  241. date: function(inst) { return plugin.add(plugin.newDate(inst.drawDate), 7, 'd'); },
  242. action: function(inst) { plugin._changeDayPlugin(this, 7); }
  243. }
  244. },
  245. /* Default template for generating a datepicker. */
  246. defaultRenderer: {
  247. // Anywhere: '{l10n:name}' to insert localised value for name,
  248. // '{link:name}' to insert a link trigger for command name,
  249. // '{button:name}' to insert a button trigger for command name,
  250. // '{popup:start}...{popup:end}' to mark a section for inclusion in a popup datepicker only,
  251. // '{inline:start}...{inline:end}' to mark a section for inclusion in an inline datepicker only
  252. // Overall structure: '{months}' to insert calendar months
  253. picker: '<div class="datepick">' +
  254. '<div class="datepick-nav">{link:prev}{link:today}{link:next}</div>{months}' +
  255. '{popup:start}<div class="datepick-ctrl">{link:clear}{link:close}</div>{popup:end}' +
  256. '<div class="datepick-clear-fix"></div></div>',
  257. // One row of months: '{months}' to insert calendar months
  258. monthRow: '<div class="datepick-month-row">{months}</div>',
  259. // A single month: '{monthHeader:dateFormat}' to insert the month header -
  260. // dateFormat is optional and defaults to 'MM yyyy',
  261. // '{weekHeader}' to insert a week header, '{weeks}' to insert the month's weeks
  262. month: '<div class="datepick-month"><div class="datepick-month-header">{monthHeader}</div>' +
  263. '<table><thead>{weekHeader}</thead><tbody>{weeks}</tbody></table></div>',
  264. // A week header: '{days}' to insert individual day names
  265. weekHeader: '<tr>{days}</tr>',
  266. // Individual day header: '{day}' to insert day name
  267. dayHeader: '<th>{day}</th>',
  268. // One week of the month: '{days}' to insert the week's days, '{weekOfYear}' to insert week of year
  269. week: '<tr>{days}</tr>',
  270. // An individual day: '{day}' to insert day value
  271. day: '<td>{day}</td>',
  272. // jQuery selector, relative to picker, for a single month
  273. monthSelector: '.datepick-month',
  274. // jQuery selector, relative to picker, for individual days
  275. daySelector: 'td',
  276. // Class for right-to-left (RTL) languages
  277. rtlClass: 'datepick-rtl',
  278. // Class for multi-month datepickers
  279. multiClass: 'datepick-multi',
  280. // Class for selectable dates
  281. defaultClass: '',
  282. // Class for currently selected dates
  283. selectedClass: 'datepick-selected',
  284. // Class for highlighted dates
  285. highlightedClass: 'datepick-highlight',
  286. // Class for today
  287. todayClass: 'datepick-today',
  288. // Class for days from other months
  289. otherMonthClass: 'datepick-other-month',
  290. // Class for days on weekends
  291. weekendClass: 'datepick-weekend',
  292. // Class prefix for commands
  293. commandClass: 'datepick-cmd',
  294. // Extra class(es) for commands that are buttons
  295. commandButtonClass: '',
  296. // Extra class(es) for commands that are links
  297. commandLinkClass: '',
  298. // Class for disabled commands
  299. disabledClass: 'datepick-disabled'
  300. },
  301. /* Override the default settings for all datepicker instances.
  302. @param options (object) the new settings to use as defaults
  303. @return (Datepicker) this object */
  304. setDefaults: function(options) {
  305. $.extend(this._defaults, options || {});
  306. return this;
  307. },
  308. _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
  309. Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
  310. _msPerDay: 24 * 60 * 60 * 1000,
  311. ATOM: 'yyyy-mm-dd', // RFC 3339/ISO 8601
  312. COOKIE: 'D, dd M yyyy',
  313. FULL: 'DD, MM d, yyyy',
  314. ISO_8601: 'yyyy-mm-dd',
  315. JULIAN: 'J',
  316. RFC_822: 'D, d M yy',
  317. RFC_850: 'DD, dd-M-yy',
  318. RFC_1036: 'D, d M yy',
  319. RFC_1123: 'D, d M yyyy',
  320. RFC_2822: 'D, d M yyyy',
  321. RSS: 'D, d M yy', // RFC 822
  322. TICKS: '!',
  323. TIMESTAMP: '@',
  324. W3C: 'yyyy-mm-dd', // ISO 8601
  325. /* Format a date object into a string value.
  326. The format can be combinations of the following:
  327. d - day of month (no leading zero)
  328. dd - day of month (two digit)
  329. o - day of year (no leading zeros)
  330. oo - day of year (three digit)
  331. D - day name short
  332. DD - day name long
  333. w - week of year (no leading zero)
  334. ww - week of year (two digit)
  335. m - month of year (no leading zero)
  336. mm - month of year (two digit)
  337. M - month name short
  338. MM - month name long
  339. yy - year (two digit)
  340. yyyy - year (four digit)
  341. @ - Unix timestamp (s since 01/01/1970)
  342. ! - Windows ticks (100ns since 01/01/0001)
  343. '...' - literal text
  344. '' - single quote
  345. @param format (string) the desired format of the date (optional, default datepicker format)
  346. @param date (Date) the date value to format
  347. @param settings (object) attributes include:
  348. dayNamesShort (string[]) abbreviated names of the days from Sunday (optional)
  349. dayNames (string[]) names of the days from Sunday (optional)
  350. monthNamesShort (string[]) abbreviated names of the months (optional)
  351. monthNames (string[]) names of the months (optional)
  352. calculateWeek (function) function that determines week of the year (optional)
  353. @return (string) the date in the above format */
  354. formatDate: function(format, date, settings) {
  355. if (typeof format != 'string') {
  356. settings = date;
  357. date = format;
  358. format = '';
  359. }
  360. if (!date) {
  361. return '';
  362. }
  363. format = format || this._defaults.dateFormat;
  364. settings = settings || {};
  365. var dayNamesShort = settings.dayNamesShort || this._defaults.dayNamesShort;
  366. var dayNames = settings.dayNames || this._defaults.dayNames;
  367. var monthNamesShort = settings.monthNamesShort || this._defaults.monthNamesShort;
  368. var monthNames = settings.monthNames || this._defaults.monthNames;
  369. var calculateWeek = settings.calculateWeek || this._defaults.calculateWeek;
  370. // Check whether a format character is doubled
  371. var doubled = function(match, step) {
  372. var matches = 1;
  373. while (iFormat + matches < format.length && format.charAt(iFormat + matches) == match) {
  374. matches++;
  375. }
  376. iFormat += matches - 1;
  377. return Math.floor(matches / (step || 1)) > 1;
  378. };
  379. // Format a number, with leading zeroes if necessary
  380. var formatNumber = function(match, value, len, step) {
  381. var num = '' + value;
  382. if (doubled(match, step)) {
  383. while (num.length < len) {
  384. num = '0' + num;
  385. }
  386. }
  387. return num;
  388. };
  389. // Format a name, short or long as requested
  390. var formatName = function(match, value, shortNames, longNames) {
  391. return (doubled(match) ? longNames[value] : shortNames[value]);
  392. };
  393. var output = '';
  394. var literal = false;
  395. for (var iFormat = 0; iFormat < format.length; iFormat++) {
  396. if (literal) {
  397. if (format.charAt(iFormat) == "'" && !doubled("'")) {
  398. literal = false;
  399. }
  400. else {
  401. output += format.charAt(iFormat);
  402. }
  403. }
  404. else {
  405. switch (format.charAt(iFormat)) {
  406. case 'd': output += formatNumber('d', date.getDate(), 2); break;
  407. case 'D': output += formatName('D', date.getDay(),
  408. dayNamesShort, dayNames); break;
  409. case 'o': output += formatNumber('o', this.dayOfYear(date), 3); break;
  410. case 'w': output += formatNumber('w', calculateWeek(date), 2); break;
  411. case 'm': output += formatNumber('m', date.getMonth() + 1, 2); break;
  412. case 'M': output += formatName('M', date.getMonth(),
  413. monthNamesShort, monthNames); break;
  414. case 'y':
  415. output += (doubled('y', 2) ? date.getFullYear() :
  416. (date.getFullYear() % 100 < 10 ? '0' : '') + date.getFullYear() % 100);
  417. break;
  418. case '@': output += Math.floor(date.getTime() / 1000); break;
  419. case '!': output += date.getTime() * 10000 + this._ticksTo1970; break;
  420. case "'":
  421. if (doubled("'")) {
  422. output += "'";
  423. }
  424. else {
  425. literal = true;
  426. }
  427. break;
  428. default:
  429. output += format.charAt(iFormat);
  430. }
  431. }
  432. }
  433. return output;
  434. },
  435. /* Parse a string value into a date object.
  436. See formatDate for the possible formats, plus:
  437. * - ignore rest of string
  438. @param format (string) the expected format of the date ('' for default datepicker format)
  439. @param value (string) the date in the above format
  440. @param settings (object) attributes include:
  441. shortYearCutoff (number) the cutoff year for determining the century (optional)
  442. dayNamesShort (string[]) abbreviated names of the days from Sunday (optional)
  443. dayNames (string[]) names of the days from Sunday (optional)
  444. monthNamesShort (string[]) abbreviated names of the months (optional)
  445. monthNames (string[]) names of the months (optional)
  446. @return (Date) the extracted date value or null if value is blank
  447. @throws errors if the format and/or value are missing,
  448. if the value doesn't match the format,
  449. or if the date is invalid */
  450. parseDate: function(format, value, settings) {
  451. if (value == null) {
  452. throw 'Invalid arguments';
  453. }
  454. value = (typeof value == 'object' ? value.toString() : value + '');
  455. if (value == '') {
  456. return null;
  457. }
  458. format = format || this._defaults.dateFormat;
  459. settings = settings || {};
  460. var shortYearCutoff = settings.shortYearCutoff || this._defaults.shortYearCutoff;
  461. shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
  462. this.today().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
  463. var dayNamesShort = settings.dayNamesShort || this._defaults.dayNamesShort;
  464. var dayNames = settings.dayNames || this._defaults.dayNames;
  465. var monthNamesShort = settings.monthNamesShort || this._defaults.monthNamesShort;
  466. var monthNames = settings.monthNames || this._defaults.monthNames;
  467. var year = -1;
  468. var month = -1;
  469. var day = -1;
  470. var doy = -1;
  471. var shortYear = false;
  472. var literal = false;
  473. // Check whether a format character is doubled
  474. var doubled = function(match, step) {
  475. var matches = 1;
  476. while (iFormat + matches < format.length && format.charAt(iFormat + matches) == match) {
  477. matches++;
  478. }
  479. iFormat += matches - 1;
  480. return Math.floor(matches / (step || 1)) > 1;
  481. };
  482. // Extract a number from the string value
  483. var getNumber = function(match, step) {
  484. var isDoubled = doubled(match, step);
  485. var size = [2, 3, isDoubled ? 4 : 2, 11, 20]['oy@!'.indexOf(match) + 1];
  486. var digits = new RegExp('^-?\\d{1,' + size + '}');
  487. var num = value.substring(iValue).match(digits);
  488. if (!num) {
  489. throw 'Missing number at position {0}'.replace(/\{0\}/, iValue);
  490. }
  491. iValue += num[0].length;
  492. return parseInt(num[0], 10);
  493. };
  494. // Extract a name from the string value and convert to an index
  495. var getName = function(match, shortNames, longNames, step) {
  496. var names = (doubled(match, step) ? longNames : shortNames);
  497. for (var i = 0; i < names.length; i++) {
  498. if (value.substr(iValue, names[i].length).toLowerCase() == names[i].toLowerCase()) {
  499. iValue += names[i].length;
  500. return i + 1;
  501. }
  502. }
  503. throw 'Unknown name at position {0}'.replace(/\{0\}/, iValue);
  504. };
  505. // Confirm that a literal character matches the string value
  506. var checkLiteral = function() {
  507. if (value.charAt(iValue) != format.charAt(iFormat)) {
  508. throw 'Unexpected literal at position {0}'.replace(/\{0\}/, iValue);
  509. }
  510. iValue++;
  511. };
  512. var iValue = 0;
  513. for (var iFormat = 0; iFormat < format.length; iFormat++) {
  514. if (literal) {
  515. if (format.charAt(iFormat) == "'" && !doubled("'")) {
  516. literal = false;
  517. }
  518. else {
  519. checkLiteral();
  520. }
  521. }
  522. else {
  523. switch (format.charAt(iFormat)) {
  524. case 'd': day = getNumber('d'); break;
  525. case 'D': getName('D', dayNamesShort, dayNames); break;
  526. case 'o': doy = getNumber('o'); break;
  527. case 'w': getNumber('w'); break;
  528. case 'm': month = getNumber('m'); break;
  529. case 'M': month = getName('M', monthNamesShort, monthNames); break;
  530. case 'y':
  531. var iSave = iFormat;
  532. shortYear = !doubled('y', 2);
  533. iFormat = iSave;
  534. year = getNumber('y', 2);
  535. break;
  536. case '@':
  537. var date = this._normaliseDate(new Date(getNumber('@') * 1000));
  538. year = date.getFullYear();
  539. month = date.getMonth() + 1;
  540. day = date.getDate();
  541. break;
  542. case '!':
  543. var date = this._normaliseDate(
  544. new Date((getNumber('!') - this._ticksTo1970) / 10000));
  545. year = date.getFullYear();
  546. month = date.getMonth() + 1;
  547. day = date.getDate();
  548. break;
  549. case '*': iValue = value.length; break;
  550. case "'":
  551. if (doubled("'")) {
  552. checkLiteral();
  553. }
  554. else {
  555. literal = true;
  556. }
  557. break;
  558. default: checkLiteral();
  559. }
  560. }
  561. }
  562. if (iValue < value.length) {
  563. throw 'Additional text found at end';
  564. }
  565. if (year == -1) {
  566. year = this.today().getFullYear();
  567. }
  568. else if (year < 100 && shortYear) {
  569. year += (shortYearCutoff == -1 ? 1900 : this.today().getFullYear() -
  570. this.today().getFullYear() % 100 - (year <= shortYearCutoff ? 0 : 100));
  571. }
  572. if (doy > -1) {
  573. month = 1;
  574. day = doy;
  575. for (var dim = this.daysInMonth(year, month); day > dim;
  576. dim = this.daysInMonth(year, month)) {
  577. month++;
  578. day -= dim;
  579. }
  580. }
  581. var date = this.newDate(year, month, day);
  582. if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day) {
  583. throw 'Invalid date';
  584. }
  585. return date;
  586. },
  587. /* A date may be specified as an exact value or a relative one.
  588. @param dateSpec (Date or number or string) the date as an object or string
  589. in the given format or an offset - numeric days from today,
  590. or string amounts and periods, e.g. '+1m +2w'
  591. @param defaultDate (Date) the date to use if no other supplied, may be null
  592. @param currentDate (Date) the current date as a possible basis for relative dates,
  593. if null today is used (optional)
  594. @param dateFormat (string) the expected date format - see formatDate above (optional)
  595. @param settings (object) attributes include:
  596. shortYearCutoff (number) the cutoff year for determining the century (optional)
  597. dayNamesShort (string[7]) abbreviated names of the days from Sunday (optional)
  598. dayNames (string[7]) names of the days from Sunday (optional)
  599. monthNamesShort (string[12]) abbreviated names of the months (optional)
  600. monthNames (string[12]) names of the months (optional)
  601. @return (Date) the decoded date */
  602. determineDate: function(dateSpec, defaultDate, currentDate, dateFormat, settings) {
  603. if (currentDate && typeof currentDate != 'object') {
  604. settings = dateFormat;
  605. dateFormat = currentDate;
  606. currentDate = null;
  607. }
  608. if (typeof dateFormat != 'string') {
  609. settings = dateFormat;
  610. dateFormat = '';
  611. }
  612. var offsetString = function(offset) {
  613. try {
  614. return plugin.parseDate(dateFormat, offset, settings);
  615. }
  616. catch (e) {
  617. // Ignore
  618. }
  619. offset = offset.toLowerCase();
  620. var date = (offset.match(/^c/) && currentDate ? plugin.newDate(currentDate) : null) ||
  621. plugin.today();
  622. var pattern = /([+-]?[0-9]+)\s*(d|w|m|y)?/g;
  623. var matches = null;
  624. while (matches = pattern.exec(offset)) {
  625. date = plugin.add(date, parseInt(matches[1], 10), matches[2] || 'd');
  626. }
  627. return date;
  628. };
  629. defaultDate = (defaultDate ? plugin.newDate(defaultDate) : null);
  630. dateSpec = (dateSpec == null ? defaultDate :
  631. (typeof dateSpec == 'string' ? offsetString(dateSpec) : (typeof dateSpec == 'number' ?
  632. (isNaN(dateSpec) || dateSpec == Infinity || dateSpec == -Infinity ? defaultDate :
  633. plugin.add(plugin.today(), dateSpec, 'd')) : plugin.newDate(dateSpec))));
  634. return dateSpec;
  635. },
  636. /* Find the number of days in a given month.
  637. @param year (Date) the date to get days for or
  638. (number) the full year
  639. @param month (number) the month (1 to 12)
  640. @return (number) the number of days in this month */
  641. daysInMonth: function(year, month) {
  642. month = (year.getFullYear ? year.getMonth() + 1 : month);
  643. year = (year.getFullYear ? year.getFullYear() : year);
  644. return this.newDate(year, month + 1, 0).getDate();
  645. },
  646. /* Calculate the day of the year for a date.
  647. @param year (Date) the date to get the day-of-year for or
  648. (number) the full year
  649. @param month (number) the month (1-12)
  650. @param day (number) the day
  651. @return (number) the day of the year */
  652. dayOfYear: function(year, month, day) {
  653. var date = (year.getFullYear ? year : this.newDate(year, month, day));
  654. var newYear = this.newDate(date.getFullYear(), 1, 1);
  655. return Math.floor((date.getTime() - newYear.getTime()) / this._msPerDay) + 1;
  656. },
  657. /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
  658. @param year (Date) the date to get the week for or
  659. (number) the full year
  660. @param month (number) the month (1-12)
  661. @param day (number) the day
  662. @return (number) the number of the week within the year that contains this date */
  663. iso8601Week: function(year, month, day) {
  664. var checkDate = (year.getFullYear ?
  665. new Date(year.getTime()) : this.newDate(year, month, day));
  666. // Find Thursday of this week starting on Monday
  667. checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
  668. var time = checkDate.getTime();
  669. checkDate.setMonth(0, 1); // Compare with Jan 1
  670. return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
  671. },
  672. /* Return today's date.
  673. @return (Date) today */
  674. today: function() {
  675. return this._normaliseDate(new Date());
  676. },
  677. /* Return a new date.
  678. @param year (Date) the date to clone or
  679. (number) the year
  680. @param month (number) the month (1-12)
  681. @param day (number) the day
  682. @return (Date) the date */
  683. newDate: function(year, month, day) {
  684. return (!year ? null : (year.getFullYear ? this._normaliseDate(new Date(year.getTime())) :
  685. new Date(year, month - 1, day, 12)));
  686. },
  687. /* Standardise a date into a common format - time portion is 12 noon.
  688. @param date (Date) the date to standardise
  689. @return (Date) the normalised date */
  690. _normaliseDate: function(date) {
  691. if (date) {
  692. date.setHours(12, 0, 0, 0);
  693. }
  694. return date;
  695. },
  696. /* Set the year for a date.
  697. @param date (Date) the original date
  698. @param year (number) the new year
  699. @return the updated date */
  700. year: function(date, year) {
  701. date.setFullYear(year);
  702. return this._normaliseDate(date);
  703. },
  704. /* Set the month for a date.
  705. @param date (Date) the original date
  706. @param month (number) the new month (1-12)
  707. @return the updated date */
  708. month: function(date, month) {
  709. date.setMonth(month - 1);
  710. return this._normaliseDate(date);
  711. },
  712. /* Set the day for a date.
  713. @param date (Date) the original date
  714. @param day (number) the new day of the month
  715. @return the updated date */
  716. day: function(date, day) {
  717. date.setDate(day);
  718. return this._normaliseDate(date);
  719. },
  720. /* Add a number of periods to a date.
  721. @param date (Date) the original date
  722. @param amount (number) the number of periods
  723. @param period (string) the type of period d/w/m/y
  724. @return the updated date */
  725. add: function(date, amount, period) {
  726. if (period == 'd' || period == 'w') {
  727. this._normaliseDate(date);
  728. date.setDate(date.getDate() + amount * (period == 'w' ? 7 : 1));
  729. }
  730. else {
  731. var year = date.getFullYear() + (period == 'y' ? amount : 0);
  732. var month = date.getMonth() + (period == 'm' ? amount : 0);
  733. date.setTime(plugin.newDate(year, month + 1,
  734. Math.min(date.getDate(), this.daysInMonth(year, month + 1))).getTime());
  735. }
  736. return date;
  737. },
  738. /* Apply the months offset value to a date.
  739. @param date (Date) the original date
  740. @param inst (object) the current instance settings
  741. @return (Date) the updated date */
  742. _applyMonthsOffset: function(date, inst) {
  743. var monthsOffset = inst.options.monthsOffset;
  744. if ($.isFunction(monthsOffset)) {
  745. monthsOffset = monthsOffset.apply(inst.target[0], [date]);
  746. }
  747. return plugin.add(date, -monthsOffset, 'm');
  748. },
  749. /* Attach the datepicker functionality to an input field.
  750. @param target (element) the control to affect
  751. @param options (object) the custom options for this instance */
  752. _attachPlugin: function(target, options) {
  753. target = $(target);
  754. if (target.hasClass(this.markerClassName)) {
  755. return;
  756. }
  757. var inlineSettings = ($.fn.metadata ? target.metadata() : {});
  758. var inst = {options: $.extend({}, this._defaults, inlineSettings, options),
  759. target: target, selectedDates: [], drawDate: null, pickingRange: false,
  760. inline: ($.inArray(target[0].nodeName.toLowerCase(), ['div', 'span']) > -1),
  761. get: function(name) { // Get a setting value, computing if necessary
  762. if ($.inArray(name, ['defaultDate', 'minDate', 'maxDate']) > -1) { // Decode date settings
  763. return plugin.determineDate(this.options[name], null,
  764. this.selectedDates[0], this.options.dateFormat, inst.getConfig());
  765. }
  766. return this.options[name];
  767. },
  768. curMinDate: function() {
  769. return (this.pickingRange ? this.selectedDates[0] : this.get('minDate'));
  770. },
  771. getConfig: function() {
  772. return {dayNamesShort: this.options.dayNamesShort, dayNames: this.options.dayNames,
  773. monthNamesShort: this.options.monthNamesShort, monthNames: this.options.monthNames,
  774. calculateWeek: this.options.calculateWeek,
  775. shortYearCutoff: this.options.shortYearCutoff};
  776. }
  777. };
  778. target.addClass(this.markerClassName).data(this.propertyName, inst);
  779. if (inst.inline) {
  780. inst.drawDate = plugin._checkMinMax(plugin.newDate(inst.selectedDates[0] ||
  781. inst.get('defaultDate') || plugin.today()), inst);
  782. inst.prevDate = plugin.newDate(inst.drawDate);
  783. this._update(target[0]);
  784. if ($.fn.mousewheel) {
  785. target.mousewheel(this._doMouseWheel);
  786. }
  787. }
  788. else {
  789. this._attachments(target, inst);
  790. target.bind('keydown.' + this.propertyName, this._keyDown).
  791. bind('keypress.' + this.propertyName, this._keyPress).
  792. bind('keyup.' + this.propertyName, this._keyUp);
  793. if (target.attr('disabled')) {
  794. this._disablePlugin(target[0]);
  795. }
  796. }
  797. },
  798. /* Retrieve or reconfigure the settings for a control.
  799. @param target (element) the control to affect
  800. @param options (object) the new options for this instance or
  801. (string) an individual property name
  802. @param value (any) the individual property value (omit if options
  803. is an object or to retrieve the value of a setting)
  804. @return (any) if retrieving a value */
  805. _optionPlugin: function(target, options, value) {
  806. target = $(target);
  807. var inst = target.data(this.propertyName);
  808. if (!options || (typeof options == 'string' && value == null)) { // Get option
  809. var name = options;
  810. options = (inst || {}).options;
  811. return (options && name ? options[name] : options);
  812. }
  813. if (!target.hasClass(this.markerClassName)) {
  814. return;
  815. }
  816. options = options || {};
  817. if (typeof options == 'string') {
  818. var name = options;
  819. options = {};
  820. options[name] = value;
  821. }
  822. if (options.calendar && options.calendar != inst.options.calendar) {
  823. var discardDate = function(name) {
  824. return (typeof inst.options[name] == 'object' ? null : inst.options[name]);
  825. };
  826. options = $.extend({defaultDate: discardDate('defaultDate'),
  827. minDate: discardDate('minDate'), maxDate: discardDate('maxDate')}, options);
  828. inst.selectedDates = [];
  829. inst.drawDate = null;
  830. }
  831. var dates = inst.selectedDates;
  832. $.extend(inst.options, options);
  833. this._setDatePlugin(target[0], dates, null, false, true);
  834. inst.pickingRange = false;
  835. inst.drawDate = plugin.newDate(this._checkMinMax(
  836. (inst.options.defaultDate ? inst.get('defaultDate') : inst.drawDate) ||
  837. inst.get('defaultDate') || plugin.today(), inst));
  838. if (!inst.inline) {
  839. this._attachments(target, inst);
  840. }
  841. if (inst.inline || inst.div) {
  842. this._update(target[0]);
  843. }
  844. },
  845. /* Attach events and trigger, if necessary.
  846. @param target (jQuery) the control to affect
  847. @param inst (object) the current instance settings */
  848. _attachments: function(target, inst) {
  849. target.unbind('focus.' + this.propertyName);
  850. if (inst.options.showOnFocus) {
  851. target.bind('focus.' + this.propertyName, this._showPlugin);
  852. }
  853. if (inst.trigger) {
  854. inst.trigger.remove();
  855. }
  856. var trigger = inst.options.showTrigger;
  857. inst.trigger = (!trigger ? $([]) :
  858. $(trigger).clone().removeAttr('id').addClass(this._triggerClass)
  859. [inst.options.isRTL ? 'insertBefore' : 'insertAfter'](target).
  860. click(function() {
  861. if (!plugin._isDisabledPlugin(target[0])) {
  862. plugin[plugin.curInst == inst ? '_hidePlugin' : '_showPlugin'](target[0]);
  863. }
  864. }));
  865. this._autoSize(target, inst);
  866. var dates = this._extractDates(inst, target.val());
  867. if (dates) {
  868. this._setDatePlugin(target[0], dates, null, true);
  869. }
  870. var defaultDate = inst.get('defaultDate');
  871. if (inst.options.selectDefaultDate && defaultDate && inst.selectedDates.length == 0) {
  872. this._setDatePlugin(target[0], plugin.newDate(defaultDate || plugin.today()));
  873. }
  874. },
  875. /* Apply the maximum length for the date format.
  876. @param inst (object) the current instance settings */
  877. _autoSize: function(target, inst) {
  878. if (inst.options.autoSize && !inst.inline) {
  879. var date = plugin.newDate(2009, 10, 20); // Ensure double digits
  880. var dateFormat = inst.options.dateFormat;
  881. if (dateFormat.match(/[DM]/)) {
  882. var findMax = function(names) {
  883. var max = 0;
  884. var maxI = 0;
  885. for (var i = 0; i < names.length; i++) {
  886. if (names[i].length > max) {
  887. max = names[i].length;
  888. maxI = i;
  889. }
  890. }
  891. return maxI;
  892. };
  893. date.setMonth(findMax(inst.options[dateFormat.match(/MM/) ? // Longest month
  894. 'monthNames' : 'monthNamesShort']));
  895. date.setDate(findMax(inst.options[dateFormat.match(/DD/) ? // Longest day
  896. 'dayNames' : 'dayNamesShort']) + 20 - date.getDay());
  897. }
  898. inst.target.attr('size', plugin.formatDate(dateFormat, date, inst.getConfig()).length);
  899. }
  900. },
  901. /* Remove the datepicker functionality from a control.
  902. @param target (element) the control to affect */
  903. _destroyPlugin: function(target) {
  904. target = $(target);
  905. if (!target.hasClass(this.markerClassName)) {
  906. return;
  907. }
  908. var inst = target.data(this.propertyName);
  909. if (inst.trigger) {
  910. inst.trigger.remove();
  911. }
  912. target.removeClass(this.markerClassName).removeData(this.propertyName).
  913. empty().unbind('.' + this.propertyName);
  914. if (inst.inline && $.fn.mousewheel) {
  915. target.unmousewheel();
  916. }
  917. if (!inst.inline && inst.options.autoSize) {
  918. target.removeAttr('size');
  919. }
  920. },
  921. /* Apply multiple event functions.
  922. Usage, for example: onShow: multipleEvents(fn1, fn2, ...)
  923. @param fns (function...) the functions to apply */
  924. multipleEvents: function(fns) {
  925. var funcs = arguments;
  926. return function(args) {
  927. for (var i = 0; i < funcs.length; i++) {
  928. funcs[i].apply(this, arguments);
  929. }
  930. };
  931. },
  932. /* Enable the control.
  933. @param target (element) the control to affect */
  934. _enablePlugin: function(target) {
  935. target = $(target);
  936. if (!target.hasClass(this.markerClassName)) {
  937. return;
  938. }
  939. var inst = target.data(this.propertyName);
  940. if (inst.inline) {
  941. target.children('.' + this._disableClass).remove().end().
  942. find('button,select').removeAttr('disabled').end().
  943. find('a').attr('href', 'javascript:void(0)');
  944. }
  945. else {
  946. target.prop('disabled', false);
  947. inst.trigger.filter('button.' + this._triggerClass).
  948. removeAttr('disabled').end().
  949. filter('img.' + this._triggerClass).
  950. css({opacity: '1.0', cursor: ''});
  951. }
  952. this._disabled = $.map(this._disabled,
  953. function(value) { return (value == target[0] ? null : value); }); // Delete entry
  954. },
  955. /* Disable the control.
  956. @param target (element) the control to affect */
  957. _disablePlugin: function(target) {
  958. target = $(target);
  959. if (!target.hasClass(this.markerClassName)) {
  960. return;
  961. }
  962. var inst = target.data(this.propertyName);
  963. if (inst.inline) {
  964. var inline = target.children(':last');
  965. var offset = inline.offset();
  966. var relOffset = {left: 0, top: 0};
  967. inline.parents().each(function() {
  968. if ($(this).css('position') == 'relative') {
  969. relOffset = $(this).offset();
  970. return false;
  971. }
  972. });
  973. var zIndex = target.css('zIndex');
  974. zIndex = (zIndex == 'auto' ? 0 : parseInt(zIndex, 10)) + 1;
  975. target.prepend('<div class="' + this._disableClass + '" style="' +
  976. 'width: ' + inline.outerWidth() + 'px; height: ' + inline.outerHeight() +
  977. 'px; left: ' + (offset.left - relOffset.left) + 'px; top: ' +
  978. (offset.top - relOffset.top) + 'px; z-index: ' + zIndex + '"></div>').
  979. find('button,select').attr('disabled', 'disabled').end().
  980. find('a').removeAttr('href');
  981. }
  982. else {
  983. target.prop('disabled', true);
  984. inst.trigger.filter('button.' + this._triggerClass).
  985. attr('disabled', 'disabled').end().
  986. filter('img.' + this._triggerClass).
  987. css({opacity: '0.5', cursor: 'default'});
  988. }
  989. this._disabled = $.map(this._disabled,
  990. function(value) { return (value == target[0] ? null : value); }); // Delete entry
  991. this._disabled.push(target[0]);
  992. },
  993. /* Is the first field in a jQuery collection disabled as a datepicker?
  994. @param target (element) the control to examine
  995. @return (boolean) true if disabled, false if enabled */
  996. _isDisabledPlugin: function(target) {
  997. return (target && $.inArray(target, this._disabled) > -1);
  998. },
  999. /* Show a popup datepicker.
  1000. @param target (event) a focus event or
  1001. (element) the control to use */
  1002. _showPlugin: function(target) {
  1003. target = $(target.target || target);
  1004. var inst = target.data(plugin.propertyName);
  1005. if (plugin.curInst == inst) {
  1006. return;
  1007. }
  1008. if (plugin.curInst) {
  1009. plugin._hidePlugin(plugin.curInst, true);
  1010. }
  1011. if (inst) {
  1012. // Retrieve existing date(s)
  1013. inst.lastVal = null;
  1014. inst.selectedDates = plugin._extractDates(inst, target.val());
  1015. inst.pickingRange = false;
  1016. inst.drawDate = plugin._checkMinMax(plugin.newDate(inst.selectedDates[0] ||
  1017. inst.get('defaultDate') || plugin.today()), inst);
  1018. inst.prevDate = plugin.newDate(inst.drawDate);
  1019. plugin.curInst = inst;
  1020. // Generate content
  1021. plugin._update(target[0], true);
  1022. // Adjust position before showing
  1023. var offset = plugin._checkOffset(inst);
  1024. inst.div.css({left: offset.left, top: offset.top});
  1025. // And display
  1026. var showAnim = inst.options.showAnim;
  1027. var showSpeed = inst.options.showSpeed;
  1028. showSpeed = (showSpeed == 'normal' && $.ui && $.ui.version >= '1.8' ?
  1029. '_default' : showSpeed);
  1030. if ($.effects && $.effects[showAnim]) {
  1031. var data = inst.div.data(); // Update old effects data
  1032. for (var key in data) {
  1033. if (key.match(/^ec\.storage\./)) {
  1034. data[key] = inst._mainDiv.css(key.replace(/ec\.storage\./, ''));
  1035. }
  1036. }
  1037. inst.div.data(data).show(showAnim, inst.options.showOptions, showSpeed);
  1038. }
  1039. else {
  1040. inst.div[showAnim || 'show']((showAnim ? showSpeed : ''));
  1041. }
  1042. }
  1043. },
  1044. /* Extract possible dates from a string.
  1045. @param inst (object) the current instance settings
  1046. @param text (string) the text to extract from
  1047. @return (CDate[]) the extracted dates */
  1048. _extractDates: function(inst, datesText) {
  1049. if (datesText == inst.lastVal) {
  1050. return;
  1051. }
  1052. inst.lastVal = datesText;
  1053. datesText = datesText.split(inst.options.multiSelect ? inst.options.multiSeparator :
  1054. (inst.options.rangeSelect ? inst.options.rangeSeparator : '\x00'));
  1055. var dates = [];
  1056. for (var i = 0; i < datesText.length; i++) {
  1057. try {
  1058. var date = plugin.parseDate(inst.options.dateFormat, datesText[i], inst.getConfig());
  1059. if (date) {
  1060. var found = false;
  1061. for (var j = 0; j < dates.length; j++) {
  1062. if (dates[j].getTime() == date.getTime()) {
  1063. found = true;
  1064. break;
  1065. }
  1066. }
  1067. if (!found) {
  1068. dates.push(date);
  1069. }
  1070. }
  1071. }
  1072. catch (e) {
  1073. // Ignore
  1074. }
  1075. }
  1076. dates.splice(inst.options.multiSelect || (inst.options.rangeSelect ? 2 : 1), dates.length);
  1077. if (inst.options.rangeSelect && dates.length == 1) {
  1078. dates[1] = dates[0];
  1079. }
  1080. return dates;
  1081. },
  1082. /* Update the datepicker display.
  1083. @param target (event) a focus event or
  1084. (element) the control to use
  1085. @param hidden (boolean) true to initially hide the datepicker */
  1086. _update: function(target, hidden) {
  1087. target = $(target.target || target);
  1088. var inst = target.data(plugin.propertyName);
  1089. if (inst) {
  1090. if (inst.inline || plugin.curInst == inst) {
  1091. if ($.isFunction(inst.options.onChangeMonthYear) && (!inst.prevDate ||
  1092. inst.prevDate.getFullYear() != inst.drawDate.getFullYear() ||
  1093. inst.prevDate.getMonth() != inst.drawDate.getMonth())) {
  1094. inst.options.onChangeMonthYear.apply(target[0],
  1095. [inst.drawDate.getFullYear(), inst.drawDate.getMonth() + 1]);
  1096. }
  1097. }
  1098. if (inst.inline) {
  1099. target.html(this._generateContent(target[0], inst));
  1100. }
  1101. else if (plugin.curInst == inst) {
  1102. if (!inst.div) {
  1103. inst.div = $('<div></div>').addClass(this._popupClass).
  1104. css({display: (hidden ? 'none' : 'static'), position: 'absolute',
  1105. left: target.offset().left,
  1106. top: target.offset().top + target.outerHeight()}).
  1107. appendTo($(inst.options.popupContainer || 'body'));
  1108. if ($.fn.mousewheel) {
  1109. inst.div.mousewheel(this._doMouseWheel);
  1110. }
  1111. }
  1112. inst.div.html(this._generateContent(target[0], inst));
  1113. target.focus();
  1114. }
  1115. }
  1116. },
  1117. /* Update the input field and any alternate field with the current dates.
  1118. @param target (element) the control to use
  1119. @param keyUp (boolean, internal) true if coming from keyUp processing */
  1120. _updateInput: function(target, keyUp) {
  1121. var inst = $.data(target, this.propertyName);
  1122. if (inst) {
  1123. var value = '';
  1124. var altValue = '';
  1125. var sep = (inst.options.multiSelect ? inst.options.multiSeparator :
  1126. inst.options.rangeSeparator);
  1127. var altFormat = inst.options.altFormat || inst.options.dateFormat;
  1128. for (var i = 0; i < inst.selectedDates.length; i++) {
  1129. value += (keyUp ? '' : (i > 0 ? sep : '') + plugin.formatDate(
  1130. inst.options.dateFormat, inst.selectedDates[i], inst.getConfig()));
  1131. altValue += (i > 0 ? sep : '') + plugin.formatDate(
  1132. altFormat, inst.selectedDates[i], inst.getConfig());
  1133. }
  1134. if (!inst.inline && !keyUp) {
  1135. $(target).val(value);
  1136. }
  1137. $(inst.options.altField).val(altValue);
  1138. if ($.isFunction(inst.options.onSelect) && !keyUp && !inst.inSelect) {
  1139. inst.inSelect = true; // Prevent endless loops
  1140. inst.options.onSelect.apply(target, [inst.selectedDates]);
  1141. inst.inSelect = false;
  1142. }
  1143. }
  1144. },
  1145. /* Retrieve the size of left and top borders for an element.
  1146. @param elem (jQuery) the element of interest
  1147. @return (number[2]) the left and top borders */
  1148. _getBorders: function(elem) {
  1149. var convert = function(value) {
  1150. return {thin: 1, medium: 3, thick: 5}[value] || value;
  1151. };
  1152. return [parseFloat(convert(elem.css('border-left-width'))),
  1153. parseFloat(convert(elem.css('border-top-width')))];
  1154. },
  1155. /* Check positioning to remain on the screen.
  1156. @param inst (object) the current instance settings
  1157. @return (object) the updated offset for the datepicker */
  1158. _checkOffset: function(inst) {
  1159. var base = (inst.target.is(':hidden') && inst.trigger ? inst.trigger : inst.target);
  1160. var offset = base.offset();
  1161. var browserWidth = $(window).width();
  1162. var browserHeight = $(window).height();
  1163. if (browserWidth == 0) {
  1164. return offset;
  1165. }
  1166. var isFixed = false;
  1167. $(inst.target).parents().each(function() {
  1168. isFixed |= $(this).css('position') == 'fixed';
  1169. return !isFixed;
  1170. });
  1171. var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
  1172. var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
  1173. var above = offset.top - (isFixed ? scrollY : 0) - inst.div.outerHeight();
  1174. var below = offset.top - (isFixed ? scrollY : 0) + base.outerHeight();
  1175. var alignL = offset.left - (isFixed ? scrollX : 0);
  1176. var alignR = offset.left - (isFixed ? scrollX : 0) + base.outerWidth() - inst.div.outerWidth();
  1177. var tooWide = (offset.left - scrollX + inst.div.outerWidth()) > browserWidth;
  1178. var tooHigh = (offset.top - scrollY + inst.target.outerHeight() +
  1179. inst.div.outerHeight()) > browserHeight;
  1180. inst.div.css('position', isFixed ? 'fixed' : 'absolute');
  1181. var alignment = inst.options.alignment;
  1182. if (alignment == 'topLeft') {
  1183. offset = {left: alignL, top: above};
  1184. }
  1185. else if (alignment == 'topRight') {
  1186. offset = {left: alignR, top: above};
  1187. }
  1188. else if (alignment == 'bottomLeft') {
  1189. offset = {left: alignL, top: below};
  1190. }
  1191. else if (alignment == 'bottomRight') {
  1192. offset = {left: alignR, top: below};
  1193. }
  1194. else if (alignment == 'top') {
  1195. offset = {left: (inst.options.isRTL || tooWide ? alignR : alignL), top: above};
  1196. }
  1197. else { // bottom
  1198. offset = {left: (inst.options.isRTL || tooWide ? alignR : alignL),
  1199. top: (tooHigh ? above : below)};
  1200. }
  1201. offset.left = Math.max((isFixed ? 0 : scrollX), offset.left);
  1202. offset.top = Math.max((isFixed ? 0 : scrollY), offset.top);
  1203. return offset;
  1204. },
  1205. /* Close date picker if clicked elsewhere.
  1206. @param event (MouseEvent) the mouse click to check */
  1207. _checkExternalClick: function(event) {
  1208. if (!plugin.curInst) {
  1209. return;
  1210. }
  1211. var target = $(event.target);
  1212. if (!target.parents().andSelf().hasClass(plugin._popupClass) &&
  1213. !target.hasClass(plugin.markerClassName) &&
  1214. !target.parents().andSelf().hasClass(plugin._triggerClass)) {
  1215. plugin._hidePlugin(plugin.curInst);
  1216. }
  1217. },
  1218. /* Hide a popup datepicker.
  1219. @param target (element) the control to use or
  1220. (object) the current instance settings
  1221. @param immediate (boolean) true to close immediately without animation */
  1222. _hidePlugin: function(target, immediate) {
  1223. if (!target) {
  1224. return;
  1225. }
  1226. var inst = $.data(target, this.propertyName) || target;
  1227. if (inst && inst == plugin.curInst) {
  1228. var showAnim = (immediate ? '' : inst.options.showAnim);
  1229. var showSpeed = inst.options.showSpeed;
  1230. showSpeed = (showSpeed == 'normal' && $.ui && $.ui.version >= '1.8' ?
  1231. '_default' : showSpeed);
  1232. var postProcess = function() {
  1233. if (!inst.div) {
  1234. return;
  1235. }
  1236. inst.div.remove();
  1237. inst.div = null;
  1238. plugin.curInst = null;
  1239. if ($.isFunction(inst.options.onClose)) {
  1240. inst.options.onClose.apply(target, [inst.selectedDates]);
  1241. }
  1242. };
  1243. inst.div.stop();
  1244. if ($.effects && $.effects[showAnim]) {
  1245. inst.div.hide(showAnim, inst.options.showOptions, showSpeed, postProcess);
  1246. }
  1247. else {
  1248. var hideAnim = (showAnim == 'slideDown' ? 'slideUp' :
  1249. (showAnim == 'fadeIn' ? 'fadeOut' : 'hide'));
  1250. inst.div[hideAnim]((showAnim ? showSpeed : ''), postProcess);
  1251. }
  1252. if (!showAnim) {
  1253. postProcess();
  1254. }
  1255. }
  1256. },
  1257. /* Handle keystrokes in the datepicker.
  1258. @param event (KeyEvent) the keystroke
  1259. @return (boolean) true if not handled, false if handled */
  1260. _keyDown: function(event) {
  1261. var target = event.target;
  1262. var inst = $.data(target, plugin.propertyName);
  1263. var handled = false;
  1264. if (inst.div) {
  1265. if (event.keyCode == 9) { // Tab - close
  1266. plugin._hidePlugin(target);
  1267. }
  1268. else if (event.keyCode == 13) { // Enter - select
  1269. plugin._selectDatePlugin(target,
  1270. $('a.' + inst.options.renderer.highlightedClass, inst.div)[0]);
  1271. handled = true;
  1272. }
  1273. else { // Command keystrokes
  1274. var commands = inst.options.commands;
  1275. for (var name in commands) {
  1276. var command = commands[name];
  1277. if (command.keystroke.keyCode == event.keyCode &&
  1278. !!command.keystroke.ctrlKey == !!(event.ctrlKey || event.metaKey) &&
  1279. !!command.keystroke.altKey == event.altKey &&
  1280. !!command.keystroke.shiftKey == event.shiftKey) {
  1281. plugin._performActionPlugin(target, name);
  1282. handled = true;
  1283. break;
  1284. }
  1285. }
  1286. }
  1287. }
  1288. else { // Show on 'current' keystroke
  1289. var command = inst.options.commands.current;
  1290. if (command.keystroke.keyCode == event.keyCode &&
  1291. !!command.keystroke.ctrlKey == !!(event.ctrlKey || event.metaKey) &&
  1292. !!command.keystroke.altKey == event.altKey &&
  1293. !!command.keystroke.shiftKey == event.shiftKey) {
  1294. plugin._showPlugin(target);
  1295. handled = true;
  1296. }
  1297. }
  1298. inst.ctrlKey = ((event.keyCode < 48 && event.keyCode != 32) ||
  1299. event.ctrlKey || event.metaKey);
  1300. if (handled) {
  1301. event.preventDefault();
  1302. event.stopPropagation();
  1303. }
  1304. return !handled;
  1305. },
  1306. /* Filter keystrokes in the datepicker.
  1307. @param event (KeyEvent) the keystroke
  1308. @return (boolean) true if allowed, false if not allowed */
  1309. _keyPress: function(event) {
  1310. var inst = $.data(event.target, plugin.propertyName);
  1311. if (inst && inst.options.constrainInput) {
  1312. var ch = String.fromCharCode(event.keyCode || event.charCode);
  1313. var allowedChars = plugin._allowedChars(inst);
  1314. return (event.metaKey || inst.ctrlKey || ch < ' ' ||
  1315. !allowedChars || allowedChars.indexOf(ch) > -1);
  1316. }
  1317. return true;
  1318. },
  1319. /* Determine the set of characters allowed by the date format.
  1320. @param inst (object) the current instance settings
  1321. @return (string) the set of allowed characters, or null if anything allowed */
  1322. _allowedChars: function(inst) {
  1323. var allowedChars = (inst.options.multiSelect ? inst.options.multiSeparator :
  1324. (inst.options.rangeSelect ? inst.options.rangeSeparator : ''));
  1325. var literal = false;
  1326. var hasNum = false;
  1327. var dateFormat = inst.options.dateFormat;
  1328. for (var i = 0; i < dateFormat.length; i++) {
  1329. var ch = dateFormat.charAt(i);
  1330. if (literal) {
  1331. if (ch == "'" && dateFormat.charAt(i + 1) != "'") {
  1332. literal = false;
  1333. }
  1334. else {
  1335. allowedChars += ch;
  1336. }
  1337. }
  1338. else {
  1339. switch (ch) {
  1340. case 'd': case 'm': case 'o': case 'w':
  1341. allowedChars += (hasNum ? '' : '0123456789'); hasNum = true; break;
  1342. case 'y': case '@': case '!':
  1343. allowedChars += (hasNum ? '' : '0123456789') + '-'; hasNum = true; break;
  1344. case 'J':
  1345. allowedChars += (hasNum ? '' : '0123456789') + '-.'; hasNum = true; break;
  1346. case 'D': case 'M': case 'Y':
  1347. return null; // Accept anything
  1348. case "'":
  1349. if (dateFormat.charAt(i + 1) == "'") {
  1350. allowedChars += "'";
  1351. }
  1352. else {
  1353. literal = true;
  1354. }
  1355. break;
  1356. default:
  1357. allowedChars += ch;
  1358. }
  1359. }
  1360. }
  1361. return allowedChars;
  1362. },
  1363. /* Synchronise datepicker with the field.
  1364. @param event (KeyEvent) the keystroke
  1365. @return (boolean) true if allowed, false if not allowed */
  1366. _keyUp: function(event) {
  1367. var target = event.target;
  1368. var inst = $.data(target, plugin.propertyName);
  1369. if (inst && !inst.ctrlKey && inst.lastVal != inst.target.val()) {
  1370. try {
  1371. var dates = plugin._extractDates(inst, inst.target.val());
  1372. if (dates.length > 0) {
  1373. plugin._setDatePlugin(target, dates, null, true);
  1374. }
  1375. }
  1376. catch (event) {
  1377. // Ignore
  1378. }
  1379. }
  1380. return true;
  1381. },
  1382. /* Increment/decrement month/year on mouse wheel activity.
  1383. @param event (event) the mouse wheel event
  1384. @param delta (number) the amount of change */
  1385. _doMouseWheel: function(event, delta) {
  1386. var target = (plugin.curInst && plugin.curInst.target[0]) ||
  1387. $(event.target).closest('.' + plugin.markerClassName)[0];
  1388. if (plugin._isDisabledPlugin(target)) {
  1389. return;
  1390. }
  1391. var inst = $.data(target, plugin.propertyName);
  1392. if (inst.options.useMouseWheel) {
  1393. delta = (delta < 0 ? -1 : +1);
  1394. plugin._changeMonthPlugin(target,
  1395. -inst.options[event.ctrlKey ? 'monthsToJump' : 'monthsToStep'] * delta);
  1396. }
  1397. event.preventDefault();
  1398. },
  1399. /* Clear an input and close a popup datepicker.
  1400. @param target (element) the control to use */
  1401. _clearPlugin: function(target) {
  1402. var inst = $.data(target, this.propertyName);
  1403. if (inst) {
  1404. inst.selectedDates = [];
  1405. this._hidePlugin(target);
  1406. var defaultDate = inst.get('defaultDate');
  1407. if (inst.options.selectDefaultDate && defaultDate) {
  1408. this._setDatePlugin(target, plugin.newDate(defaultDate || plugin.today()));
  1409. }
  1410. else {
  1411. this._updateInput(target);
  1412. }
  1413. }
  1414. },
  1415. /* Retrieve the selected date(s) for a datepicker.
  1416. @param target (element) the control to examine
  1417. @return (CDate[]) the selected date(s) */
  1418. _getDatePlugin: function(target) {
  1419. var inst = $.data(target, this.propertyName);
  1420. return (inst ? inst.selectedDates : []);
  1421. },
  1422. /* Set the selected date(s) for a datepicker.
  1423. @param target (element) the control to examine
  1424. @param dates (CDate or number or string or [] of these) the selected date(s)
  1425. @param endDate (CDate or number or string) the ending date for a range (optional)
  1426. @param keyUp (boolean, internal) true if coming from keyUp processing
  1427. @param setOpt (boolean, internal) true if coming from option processing */
  1428. _setDatePlugin: function(target, dates, endDate, keyUp, setOpt) {
  1429. var inst = $.data(target, this.propertyName);
  1430. if (inst) {
  1431. if (!$.isArray(dates)) {
  1432. dates = [dates];
  1433. if (endDate) {
  1434. dates.push(endDate);
  1435. }
  1436. }
  1437. var minDate = inst.get('minDate');
  1438. var maxDate = inst.get('maxDate');
  1439. var curDate = inst.selectedDates[0];
  1440. inst.selectedDates = [];
  1441. for (var i = 0; i < dates.length; i++) {
  1442. var date = plugin.determineDate(
  1443. dates[i], null, curDate, inst.options.dateFormat, inst.getConfig());
  1444. if (date) {
  1445. if ((!minDate || date.getTime() >= minDate.getTime()) &&
  1446. (!maxDate || date.getTime() <= maxDate.getTime())) {
  1447. var found = false;
  1448. for (var j = 0; j < inst.selectedDates.length; j++) {
  1449. if (inst.selectedDates[j].getTime() == date.getTime()) {
  1450. found = true;
  1451. break;
  1452. }
  1453. }
  1454. if (!found) {
  1455. inst.selectedDates.push(date);
  1456. }
  1457. }
  1458. }
  1459. }
  1460. inst.selectedDates.splice(inst.options.multiSelect ||
  1461. (inst.options.rangeSelect ? 2 : 1), inst.selectedDates.length);
  1462. if (inst.options.rangeSelect) {
  1463. switch (inst.selectedDates.length) {
  1464. case 1: inst.selectedDates[1] = inst.selectedDates[0]; break;
  1465. case 2: inst.selectedDates[1] =
  1466. (inst.selectedDates[0].getTime() > inst.selectedDates[1].getTime() ?
  1467. inst.selectedDates[0] : inst.selectedDates[1]); break;
  1468. }
  1469. inst.pickingRange = false;
  1470. }
  1471. inst.prevDate = (inst.drawDate ? plugin.newDate(inst.drawDate) : null);
  1472. inst.drawDate = this._checkMinMax(plugin.newDate(inst.selectedDates[0] ||
  1473. inst.get('defaultDate') || plugin.today()), inst);
  1474. if (!setOpt) {
  1475. this._update(target);
  1476. this._updateInput(target, keyUp);
  1477. }
  1478. }
  1479. },
  1480. /* Determine whether a date is selectable for this datepicker.
  1481. @param target (element) the control to check
  1482. @param date (Date or string or number) the date to check
  1483. @return (boolean) true if selectable, false if not */
  1484. _isSelectablePlugin: function(target, date) {
  1485. var inst = $.data(target, this.propertyName);
  1486. if (!inst) {
  1487. return false;
  1488. }
  1489. date = plugin.determineDate(date, inst.selectedDates[0] || this.today(), null,
  1490. inst.options.dateFormat, inst.getConfig());
  1491. return this._isSelectable(target, date, inst.options.onDate,
  1492. inst.get('minDate'), inst.get('maxDate'));
  1493. },
  1494. /* Internally determine whether a date is selectable for this datepicker.
  1495. @param target (element) the control to check
  1496. @param date (Date) the date to check
  1497. @param onDate (function or boolean) any onDate callback or callback.selectable
  1498. @param mindate (Date) the minimum allowed date
  1499. @param maxdate (Date) the maximum allowed date
  1500. @return (boolean) true if selectable, false if not */
  1501. _isSelectable: function(target, date, onDate, minDate, maxDate) {
  1502. var dateInfo = (typeof onDate == 'boolean' ? {selectable: onDate} :
  1503. (!$.isFunction(onDate) ? {} : onDate.apply(target, [date, true])));
  1504. return (dateInfo.selectable != false) &&
  1505. (!minDate || date.getTime() >= minDate.getTime()) &&
  1506. (!maxDate || date.getTime() <= maxDate.getTime());
  1507. },
  1508. /* Perform a named action for a datepicker.
  1509. @param target (element) the control to affect
  1510. @param action (string) the name of the action */
  1511. _performActionPlugin: function(target, action) {
  1512. var inst = $.data(target, this.propertyName);
  1513. if (inst && !this._isDisabledPlugin(target)) {
  1514. var commands = inst.options.commands;
  1515. if (commands[action] && commands[action].enabled.apply(target, [inst])) {
  1516. commands[action].action.apply(target, [inst]);
  1517. }
  1518. }
  1519. },
  1520. /* Set the currently shown month, defaulting to today's.
  1521. @param target (element) the control to affect
  1522. @param year (number) the year to show (optional)
  1523. @param month (number) the month to show (1-12) (optional)
  1524. @param day (number) the day to show (optional) */
  1525. _showMonthPlugin: function(target, year, month, day) {
  1526. var inst = $.data(target, this.propertyName);
  1527. if (inst && (day != null ||
  1528. (inst.drawDate.getFullYear() != year || inst.drawDate.getMonth() + 1 != month))) {
  1529. inst.prevDate = plugin.newDate(inst.drawDate);
  1530. var show = this._checkMinMax((year != null ?
  1531. plugin.newDate(year, month, 1) : plugin.today()), inst);
  1532. inst.drawDate = plugin.newDate(show.getFullYear(), show.getMonth() + 1,
  1533. (day != null ? day : Math.min(inst.drawDate.getDate(),
  1534. plugin.daysInMonth(show.getFullYear(), show.getMonth() + 1))));
  1535. this._update(target);
  1536. }
  1537. },
  1538. /* Adjust the currently shown month.
  1539. @param target (element) the control to affect
  1540. @param offset (number) the number of months to change by */
  1541. _changeMonthPlugin: function(target, offset) {
  1542. var inst = $.data(target, this.propertyName);
  1543. if (inst) {
  1544. var date = plugin.add(plugin.newDate(inst.drawDate), offset, 'm');
  1545. this._showMonthPlugin(target, date.getFullYear(), date.getMonth() + 1);
  1546. }
  1547. },
  1548. /* Adjust the currently shown day.
  1549. @param target (element) the control to affect
  1550. @param offset (number) the number of days to change by */
  1551. _changeDayPlugin: function(target, offset) {
  1552. var inst = $.data(target, this.propertyName);
  1553. if (inst) {
  1554. var date = plugin.add(plugin.newDate(inst.drawDate), offset, 'd');
  1555. this._showMonthPlugin(target, date.getFullYear(), date.getMonth() + 1, date.getDate());
  1556. }
  1557. },
  1558. /* Restrict a date to the minimum/maximum specified.
  1559. @param date (CDate) the date to check
  1560. @param inst (object) the current instance settings */
  1561. _checkMinMax: function(date, inst) {
  1562. var minDate = inst.get('minDate');
  1563. var maxDate = inst.get('maxDate');
  1564. date = (minDate && date.getTime() < minDate.getTime() ? plugin.newDate(minDate) : date);
  1565. date = (maxDate && date.getTime() > maxDate.getTime() ? plugin.newDate(maxDate) : date);
  1566. return date;
  1567. },
  1568. /* Retrieve the date associated with an entry in the datepicker.
  1569. @param target (element) the control to examine
  1570. @param elem (element) the selected datepicker element
  1571. @return (CDate) the corresponding date, or null */
  1572. _retrieveDatePlugin: function(target, elem) {
  1573. var inst = $.data(target, this.propertyName);
  1574. return (!inst ? null : this._normaliseDate(
  1575. new Date(parseInt(elem.className.replace(/^.*dp(-?\d+).*$/, '$1'), 10))));
  1576. },
  1577. /* Select a date for this datepicker.
  1578. @param target (element) the control to examine
  1579. @param elem (element) the selected datepicker element */
  1580. _selectDatePlugin: function(target, elem) {
  1581. var inst = $.data(target, this.propertyName);
  1582. if (inst && !this._isDisabledPlugin(target)) {
  1583. var date = this._retrieveDatePlugin(target, elem);
  1584. if (inst.options.multiSelect) {
  1585. var found = false;
  1586. for (var i = 0; i < inst.selectedDates.length; i++) {
  1587. if (date.getTime() == inst.selectedDates[i].getTime()) {
  1588. inst.selectedDates.splice(i, 1);
  1589. found = true;
  1590. break;
  1591. }
  1592. }
  1593. if (!found && inst.selectedDates.length < inst.options.multiSelect) {
  1594. inst.selectedDates.push(date);
  1595. }
  1596. }
  1597. else if (inst.options.rangeSelect) {
  1598. if (inst.pickingRange) {
  1599. inst.selectedDates[1] = date;
  1600. }
  1601. else {
  1602. inst.selectedDates = [date, date];
  1603. }
  1604. inst.pickingRange = !inst.pickingRange;
  1605. }
  1606. else {
  1607. inst.selectedDates = [date];
  1608. }
  1609. inst.prevDate = plugin.newDate(date);
  1610. this._updateInput(target);
  1611. if (inst.inline || inst.pickingRange || inst.selectedDates.length <
  1612. (inst.options.multiSelect || (inst.options.rangeSelect ? 2 : 1))) {
  1613. this._update(target);
  1614. }
  1615. else {
  1616. this._hidePlugin(target);
  1617. }
  1618. }
  1619. },
  1620. /* Generate the datepicker content for this control.
  1621. @param target (element) the control to affect
  1622. @param inst (object) the current instance settings
  1623. @return (jQuery) the datepicker content */
  1624. _generateContent: function(target, inst) {
  1625. var monthsToShow = inst.options.monthsToShow;
  1626. monthsToShow = ($.isArray(monthsToShow) ? monthsToShow : [1, monthsToShow]);
  1627. inst.drawDate = this._checkMinMax(
  1628. inst.drawDate || inst.get('defaultDate') || plugin.today(), inst);
  1629. var drawDate = plugin._applyMonthsOffset(plugin.newDate(inst.drawDate), inst);
  1630. // Generate months
  1631. var monthRows = '';
  1632. for (var row = 0; row < monthsToShow[0]; row++) {
  1633. var months = '';
  1634. for (var col = 0; col < monthsToShow[1]; col++) {
  1635. months += this._generateMonth(target, inst, drawDate.getFullYear(),
  1636. drawDate.getMonth() + 1, inst.options.renderer, (row == 0 && col == 0));
  1637. plugin.add(drawDate, 1, 'm');
  1638. }
  1639. monthRows += this._prepare(inst.options.renderer.monthRow, inst).replace(/\{months\}/, months);
  1640. }
  1641. var picker = this._prepare(inst.options.renderer.picker, inst).replace(/\{months\}/, monthRows).
  1642. replace(/\{weekHeader\}/g, this._generateDayHeaders(inst, inst.options.renderer));
  1643. // Add commands
  1644. var addCommand = function(type, open, close, name, classes) {
  1645. if (picker.indexOf('{' + type + ':' + name + '}') == -1) {
  1646. return;
  1647. }
  1648. var command = inst.options.commands[name];
  1649. var date = (inst.options.commandsAsDateFormat ? command.date.apply(target, [inst]) : null);
  1650. picker = picker.replace(new RegExp('\\{' + type + ':' + name + '\\}', 'g'),
  1651. '<' + open +
  1652. (command.status ? ' title="' + inst.options[command.status] + '"' : '') +
  1653. ' class="' + inst.options.renderer.commandClass + ' ' +
  1654. inst.options.renderer.commandClass + '-' + name + ' ' + classes +
  1655. (command.enabled(inst) ? '' : ' ' + inst.options.renderer.disabledClass) + '">' +
  1656. (date ? plugin.formatDate(inst.options[command.text], date, inst.getConfig()) :
  1657. inst.options[command.text]) + '</' + close + '>');
  1658. };
  1659. for (var name in inst.options.commands) {
  1660. addCommand('button', 'button type="button"', 'button', name,
  1661. inst.options.renderer.commandButtonClass);
  1662. addCommand('link', 'a href="javascript:void(0)"', 'a', name,
  1663. inst.options.renderer.commandLinkClass);
  1664. }
  1665. picker = $(picker);
  1666. if (monthsToShow[1] > 1) {
  1667. var count = 0;
  1668. $(inst.options.renderer.monthSelector, picker).each(function() {
  1669. var nth = ++count % monthsToShow[1];
  1670. $(this).addClass(nth == 1 ? 'first' : (nth == 0 ? 'last' : ''));
  1671. });
  1672. }
  1673. // Add datepicker behaviour
  1674. var self = this;
  1675. picker.find(inst.options.renderer.daySelector + ' a').hover(
  1676. function() { $(this).addClass(inst.options.renderer.highlightedClass); },
  1677. function() {
  1678. (inst.inline ? $(this).parents('.' + self.markerClassName) : inst.div).
  1679. find(inst.options.renderer.daySelector + ' a').
  1680. removeClass(inst.options.renderer.highlightedClass);
  1681. }).
  1682. click(function() {
  1683. self._selectDatePlugin(target, this);
  1684. }).end().
  1685. find('select.' + this._monthYearClass + ':not(.' + this._anyYearClass + ')').
  1686. change(function() {
  1687. var monthYear = $(this).val().split('/');
  1688. self._showMonthPlugin(target, parseInt(monthYear[1], 10), parseInt(monthYear[0], 10));
  1689. }).end().
  1690. find('select.' + this._anyYearClass).click(function() {
  1691. $(this).css('visibility', 'hidden').
  1692. next('input').css({left: this.offsetLeft, top: this.offsetTop,
  1693. width: this.offsetWidth, height: this.offsetHeight}).show().focus();
  1694. }).end().
  1695. find('input.' + self._monthYearClass).change(function() {
  1696. try {
  1697. var year = parseInt($(this).val(), 10);
  1698. year = (isNaN(year) ? inst.drawDate.getFullYear() : year);
  1699. self._showMonthPlugin(target, year, inst.drawDate.getMonth() + 1, inst.drawDate.getDate());
  1700. }
  1701. catch (e) {
  1702. alert(e);
  1703. }
  1704. }).keydown(function(event) {
  1705. if (event.keyCode == 13) { // Enter
  1706. $(event.target).change();
  1707. }
  1708. else if (event.keyCode == 27) { // Escape
  1709. $(event.target).hide().prev('select').css('visibility', 'visible');
  1710. inst.target.focus();
  1711. }
  1712. });
  1713. // Add command behaviour
  1714. picker.find('.' + inst.options.renderer.commandClass).click(function() {
  1715. if (!$(this).hasClass(inst.options.renderer.disabledClass)) {
  1716. var action = this.className.replace(
  1717. new RegExp('^.*' + inst.options.renderer.commandClass + '-([^ ]+).*$'), '$1');
  1718. plugin._performActionPlugin(target, action);
  1719. }
  1720. });
  1721. // Add classes
  1722. if (inst.options.isRTL) {
  1723. picker.addClass(inst.options.renderer.rtlClass);
  1724. }
  1725. if (monthsToShow[0] * monthsToShow[1] > 1) {
  1726. picker.addClass(inst.options.renderer.multiClass);
  1727. }
  1728. if (inst.options.pickerClass) {
  1729. picker.addClass(inst.options.pickerClass);
  1730. }
  1731. // Resize
  1732. $('body').append(picker);
  1733. var width = 0;
  1734. picker.find(inst.options.renderer.monthSelector).each(function() {
  1735. width += $(this).outerWidth();
  1736. });
  1737. picker.width(width / monthsToShow[0]);
  1738. // Pre-show customisation
  1739. if ($.isFunction(inst.options.onShow)) {
  1740. inst.options.onShow.apply(target, [picker, inst]);
  1741. }
  1742. return picker;
  1743. },
  1744. /* Generate the content for a single month.
  1745. @param target (element) the control to affect
  1746. @param inst (object) the current instance settings
  1747. @param year (number) the year to generate
  1748. @param month (number) the month to generate
  1749. @param renderer (object) the rendering templates
  1750. @param first (boolean) true if first of multiple months
  1751. @return (string) the month content */
  1752. _generateMonth: function(target, inst, year, month, renderer, first) {
  1753. var daysInMonth = plugin.daysInMonth(year, month);
  1754. var monthsToShow = inst.options.monthsToShow;
  1755. monthsToShow = ($.isArray(monthsToShow) ? monthsToShow : [1, monthsToShow]);
  1756. var fixedWeeks = inst.options.fixedWeeks || (monthsToShow[0] * monthsToShow[1] > 1);
  1757. var firstDay = inst.options.firstDay;
  1758. var leadDays = (plugin.newDate(year, month, 1).getDay() - firstDay + 7) % 7;
  1759. var numWeeks = (fixedWeeks ? 6 : Math.ceil((leadDays + daysInMonth) / 7));
  1760. var selectOtherMonths = inst.options.selectOtherMonths && inst.options.showOtherMonths;
  1761. var minDate = (inst.pickingRange ? inst.selectedDates[0] : inst.get('minDate'));
  1762. var maxDate = inst.get('maxDate');
  1763. var showWeeks = renderer.week.indexOf('{weekOfYear}') > -1;
  1764. var today = plugin.today();
  1765. var drawDate = plugin.newDate(year, month, 1);
  1766. plugin.add(drawDate, -leadDays - (fixedWeeks && (drawDate.getDay() == firstDay) ? 7 : 0), 'd');
  1767. var ts = drawDate.getTime();
  1768. // Generate weeks
  1769. var weeks = '';
  1770. for (var week = 0; week < numWeeks; week++) {
  1771. var weekOfYear = (!showWeeks ? '' : '<span class="dp' + ts + '">' +
  1772. ($.isFunction(inst.options.calculateWeek) ? inst.options.calculateWeek(drawDate) : 0) + '</span>');
  1773. var days = '';
  1774. for (var day = 0; day < 7; day++) {
  1775. var selected = false;
  1776. if (inst.options.rangeSelect && inst.selectedDates.length > 0) {
  1777. selected = (drawDate.getTime() >= inst.selectedDates[0] &&
  1778. drawDate.getTime() <= inst.selectedDates[1]);
  1779. }
  1780. else {
  1781. for (var i = 0; i < inst.selectedDates.length; i++) {
  1782. if (inst.selectedDates[i].getTime() == drawDate.getTime()) {
  1783. selected = true;
  1784. break;
  1785. }
  1786. }
  1787. }
  1788. var dateInfo = (!$.isFunction(inst.options.onDate) ? {} :
  1789. inst.options.onDate.apply(target, [drawDate, drawDate.getMonth() + 1 == month]));
  1790. var selectable = (selectOtherMonths || drawDate.getMonth() + 1 == month) &&
  1791. this._isSelectable(target, drawDate, dateInfo.selectable, minDate, maxDate);
  1792. days += this._prepare(renderer.day, inst).replace(/\{day\}/g,
  1793. (selectable ? '<a href="javascript:void(0)"' : '<span') +
  1794. ' class="dp' + ts + ' ' + (dateInfo.dateClass || '') +
  1795. (selected && (selectOtherMonths || drawDate.getMonth() + 1 == month) ?
  1796. ' ' + renderer.selectedClass : '') +
  1797. (selectable ? ' ' + renderer.defaultClass : '') +
  1798. ((drawDate.getDay() || 7) < 6 ? '' : ' ' + renderer.weekendClass) +
  1799. (drawDate.getMonth() + 1 == month ? '' : ' ' + renderer.otherMonthClass) +
  1800. (drawDate.getTime() == today.getTime() && (drawDate.getMonth() + 1) == month ?
  1801. ' ' + renderer.todayClass : '') +
  1802. (drawDate.getTime() == inst.drawDate.getTime() && (drawDate.getMonth() + 1) == month ?
  1803. ' ' + renderer.highlightedClass : '') + '"' +
  1804. (dateInfo.title || (inst.options.dayStatus && selectable) ? ' title="' +
  1805. (dateInfo.title || plugin.formatDate(
  1806. inst.options.dayStatus, drawDate, inst.getConfig())) + '"' : '') + '>' +
  1807. (inst.options.showOtherMonths || (drawDate.getMonth() + 1) == month ?
  1808. dateInfo.content || drawDate.getDate() : '&nbsp;') +
  1809. (selectable ? '</a>' : '</span>'));
  1810. plugin.add(drawDate, 1, 'd');
  1811. ts = drawDate.getTime();
  1812. }
  1813. weeks += this._prepare(renderer.week, inst).replace(/\{days\}/g, days).
  1814. replace(/\{weekOfYear\}/g, weekOfYear);
  1815. }
  1816. var monthHeader = this._prepare(renderer.month, inst).match(/\{monthHeader(:[^\}]+)?\}/);
  1817. monthHeader = (monthHeader[0].length <= 13 ? 'MM yyyy' :
  1818. monthHeader[0].substring(13, monthHeader[0].length - 1));
  1819. monthHeader = (first ? this._generateMonthSelection(
  1820. inst, year, month, minDate, maxDate, monthHeader, renderer) :
  1821. plugin.formatDate(monthHeader, plugin.newDate(year, month, 1), inst.getConfig()));
  1822. var weekHeader = this._prepare(renderer.weekHeader, inst).
  1823. replace(/\{days\}/g, this._generateDayHeaders(inst, renderer));
  1824. return this._prepare(renderer.month, inst).replace(/\{monthHeader(:[^\}]+)?\}/g, monthHeader).
  1825. replace(/\{weekHeader\}/g, weekHeader).replace(/\{weeks\}/g, weeks);
  1826. },
  1827. /* Generate the HTML for the day headers.
  1828. @param inst (object) the current instance settings
  1829. @param renderer (object) the rendering templates
  1830. @return (string) a week's worth of day headers */
  1831. _generateDayHeaders: function(inst, renderer) {
  1832. var header = '';
  1833. for (var day = 0; day < 7; day++) {
  1834. var dow = (day + inst.options.firstDay) % 7;
  1835. header += this._prepare(renderer.dayHeader, inst).replace(/\{day\}/g,
  1836. '<span class="' + this._curDoWClass + dow + '" title="' +
  1837. inst.options.dayNames[dow] + '">' + inst.options.dayNamesMin[dow] + '</span>');
  1838. }
  1839. return header;
  1840. },
  1841. /* Generate selection controls for month.
  1842. @param inst (object) the current instance settings
  1843. @param year (number) the year to generate
  1844. @param month (number) the month to generate
  1845. @param minDate (CDate) the minimum date allowed
  1846. @param maxDate (CDate) the maximum date allowed
  1847. @param monthHeader (string) the month/year format
  1848. @return (string) the month selection content */
  1849. _generateMonthSelection: function(inst, year, month, minDate, maxDate, monthHeader) {
  1850. if (!inst.options.changeMonth) {
  1851. return plugin.formatDate(
  1852. monthHeader, plugin.newDate(year, month, 1), inst.getConfig());
  1853. }
  1854. // Months
  1855. var monthNames = inst.options['monthNames' + (monthHeader.match(/mm/i) ? '' : 'Short')];
  1856. var html = monthHeader.replace(/m+/i, '\\x2E').replace(/y+/i, '\\x2F');
  1857. var selector = '<select class="' + this._monthYearClass +
  1858. '" title="' + inst.options.monthStatus + '">';
  1859. for (var m = 1; m <= 12; m++) {
  1860. if ((!minDate || plugin.newDate(year, m, plugin.daysInMonth(year, m)).
  1861. getTime() >= minDate.getTime()) &&
  1862. (!maxDate || plugin.newDate(year, m, 1).getTime() <= maxDate.getTime())) {
  1863. selector += '<option value="' + m + '/' + year + '"' +
  1864. (month == m ? ' selected="selected"' : '') + '>' +
  1865. monthNames[m - 1] + '</option>';
  1866. }
  1867. }
  1868. selector += '</select>';
  1869. html = html.replace(/\\x2E/, selector);
  1870. // Years
  1871. var yearRange = inst.options.yearRange;
  1872. if (yearRange == 'any') {
  1873. selector = '<select class="' + this._monthYearClass + ' ' + this._anyYearClass +
  1874. '" title="' + inst.options.yearStatus + '">' +
  1875. '<option>' + year + '</option></select>' +
  1876. '<input class="' + this._monthYearClass + ' ' + this._curMonthClass +
  1877. month + '" value="' + year + '">';
  1878. }
  1879. else {
  1880. yearRange = yearRange.split(':');
  1881. var todayYear = plugin.today().getFullYear();
  1882. var start = (yearRange[0].match('c[+-].*') ? year + parseInt(yearRange[0].substring(1), 10) :
  1883. ((yearRange[0].match('[+-].*') ? todayYear : 0) + parseInt(yearRange[0], 10)));
  1884. var end = (yearRange[1].match('c[+-].*') ? year + parseInt(yearRange[1].substring(1), 10) :
  1885. ((yearRange[1].match('[+-].*') ? todayYear : 0) + parseInt(yearRange[1], 10)));
  1886. selector = '<select class="' + this._monthYearClass +
  1887. '" title="' + inst.options.yearStatus + '">';
  1888. start = plugin.add(plugin.newDate(start + 1, 1, 1), -1, 'd');
  1889. end = plugin.newDate(end, 1, 1);
  1890. var addYear = function(y) {
  1891. if (y != 0) {
  1892. selector += '<option value="' + month + '/' + y + '"' +
  1893. (year == y ? ' selected="selected"' : '') + '>' + y + '</option>';
  1894. }
  1895. };
  1896. if (start.getTime() < end.getTime()) {
  1897. start = (minDate && minDate.getTime() > start.getTime() ? minDate : start).getFullYear();
  1898. end = (maxDate && maxDate.getTime() < end.getTime() ? maxDate : end).getFullYear();
  1899. for (var y = start; y <= end; y++) {
  1900. addYear(y);
  1901. }
  1902. }
  1903. else {
  1904. start = (maxDate && maxDate.getTime() < start.getTime() ? maxDate : start).getFullYear();
  1905. end = (minDate && minDate.getTime() > end.getTime() ? minDate : end).getFullYear();
  1906. for (var y = start; y >= end; y--) {
  1907. addYear(y);
  1908. }
  1909. }
  1910. selector += '</select>';
  1911. }
  1912. html = html.replace(/\\x2F/, selector);
  1913. return html;
  1914. },
  1915. /* Prepare a render template for use.
  1916. Exclude popup/inline sections that are not applicable.
  1917. Localise text of the form: {l10n:name}.
  1918. @param text (string) the text to localise
  1919. @param inst (object) the current instance settings
  1920. @return (string) the localised text */
  1921. _prepare: function(text, inst) {
  1922. var replaceSection = function(type, retain) {
  1923. while (true) {
  1924. var start = text.indexOf('{' + type + ':start}');
  1925. if (start == -1) {
  1926. return;
  1927. }
  1928. var end = text.substring(start).indexOf('{' + type + ':end}');
  1929. if (end > -1) {
  1930. text = text.substring(0, start) +
  1931. (retain ? text.substr(start + type.length + 8, end - type.length - 8) : '') +
  1932. text.substring(start + end + type.length + 6);
  1933. }
  1934. }
  1935. };
  1936. replaceSection('inline', inst.inline);
  1937. replaceSection('popup', !inst.inline);
  1938. var pattern = /\{l10n:([^\}]+)\}/;
  1939. var matches = null;
  1940. while (matches = pattern.exec(text)) {
  1941. text = text.replace(matches[0], inst.options[matches[1]]);
  1942. }
  1943. return text;
  1944. }
  1945. });
  1946. // The list of commands that return values and don't permit chaining
  1947. var getters = ['getDate', 'isDisabled', 'isSelectable', 'retrieveDate'];
  1948. /* Determine whether a command is a getter and doesn't permit chaining.
  1949. @param command (string, optional) the command to run
  1950. @param otherArgs ([], optional) any other arguments for the command
  1951. @return true if the command is a getter, false if not */
  1952. function isNotChained(command, otherArgs) {
  1953. if (command == 'option' && (otherArgs.length == 0 ||
  1954. (otherArgs.length == 1 && typeof otherArgs[0] == 'string'))) {
  1955. return true;
  1956. }
  1957. return $.inArray(command, getters) > -1;
  1958. }
  1959. /* Attach the datepicker functionality to a jQuery selection.
  1960. @param options (object) the new settings to use for these instances (optional) or
  1961. (string) the command to run (optional)
  1962. @return (jQuery) for chaining further calls or
  1963. (any) getter value */
  1964. $.fn.datepick = function(options) {
  1965. var otherArgs = Array.prototype.slice.call(arguments, 1);
  1966. if (isNotChained(options, otherArgs)) {
  1967. return plugin['_' + options + 'Plugin'].apply(plugin, [this[0]].concat(otherArgs));
  1968. }
  1969. return this.each(function() {
  1970. if (typeof options == 'string') {
  1971. if (!plugin['_' + options + 'Plugin']) {
  1972. throw 'Unknown command: ' + options;
  1973. }
  1974. plugin['_' + options + 'Plugin'].apply(plugin, [this].concat(otherArgs));
  1975. }
  1976. else {
  1977. plugin._attachPlugin(this, options || {});
  1978. }
  1979. });
  1980. };
  1981. /* Initialise the datepicker functionality. */
  1982. var plugin = $.datepick = new Datepicker(); // Singleton instance
  1983. $(function() {
  1984. $(document).mousedown(plugin._checkExternalClick).
  1985. resize(function() { plugin._hidePlugin(plugin.curInst); });
  1986. });
  1987. })(jQuery);