try and get ctrl-enter to add a clear all
[roojs1] / Roo / DatePicker.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12 /**
13  * @class Roo.DatePicker
14  * @extends Roo.Component
15  * Simple date picker class.
16  * @constructor
17  * Create a new DatePicker
18  * @param {Object} config The config object
19  */
20 Roo.DatePicker = function(config){
21     Roo.DatePicker.superclass.constructor.call(this, config);
22
23     this.value = config && config.value ?
24                  config.value.clearTime() : new Date().clearTime();
25
26     this.addEvents({
27         /**
28              * @event select
29              * Fires when a date is selected
30              * @param {DatePicker} this
31              * @param {Date} date The selected date
32              */
33         'select': true,
34         /**
35              * @event monthchange
36              * Fires when the displayed month changes 
37              * @param {DatePicker} this
38              * @param {Date} date The selected month
39              */
40         'monthchange': true
41     });
42
43     if(this.handler){
44         this.on("select", this.handler,  this.scope || this);
45     }
46     // build the disabledDatesRE
47     if(!this.disabledDatesRE && this.disabledDates){
48         var dd = this.disabledDates;
49         var re = "(?:";
50         for(var i = 0; i < dd.length; i++){
51             re += dd[i];
52             if(i != dd.length-1) {
53                 re += "|";
54             }
55         }
56         this.disabledDatesRE = new RegExp(re + ")");
57     }
58 };
59
60 Roo.extend(Roo.DatePicker, Roo.Component, {
61     /**
62      * @cfg {String} todayText
63      * The text to display on the button that selects the current date (defaults to "Today")
64      */
65     todayText : "Today",
66     /**
67      * @cfg {String} okText
68      * The text to display on the ok button
69      */
70     okText : "&#160;OK&#160;", // &#160; to give the user extra clicking room
71     /**
72      * @cfg {String} cancelText
73      * The text to display on the cancel button
74      */
75     cancelText : "Cancel",
76     /**
77      * @cfg {String} todayTip
78      * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
79      */
80     todayTip : "{0} (Spacebar)",
81     /**
82      * @cfg {Date} minDate
83      * Minimum allowable date (JavaScript date object, defaults to null)
84      */
85     minDate : null,
86     /**
87      * @cfg {Date} maxDate
88      * Maximum allowable date (JavaScript date object, defaults to null)
89      */
90     maxDate : null,
91     /**
92      * @cfg {String} minText
93      * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
94      */
95     minText : "This date is before the minimum date",
96     /**
97      * @cfg {String} maxText
98      * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
99      */
100     maxText : "This date is after the maximum date",
101     /**
102      * @cfg {String} format
103      * The default date format string which can be overriden for localization support.  The format must be
104      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
105      */
106     format : "m/d/y",
107     /**
108      * @cfg {Array} disabledDays
109      * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
110      */
111     disabledDays : null,
112     /**
113      * @cfg {String} disabledDaysText
114      * The tooltip to display when the date falls on a disabled day (defaults to "")
115      */
116     disabledDaysText : "",
117     /**
118      * @cfg {RegExp} disabledDatesRE
119      * JavaScript regular expression used to disable a pattern of dates (defaults to null)
120      */
121     disabledDatesRE : null,
122     /**
123      * @cfg {String} disabledDatesText
124      * The tooltip text to display when the date falls on a disabled date (defaults to "")
125      */
126     disabledDatesText : "",
127     /**
128      * @cfg {Boolean} constrainToViewport
129      * True to constrain the date picker to the viewport (defaults to true)
130      */
131     constrainToViewport : true,
132     /**
133      * @cfg {Array} monthNames
134      * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
135      */
136     monthNames : Date.monthNames,
137     /**
138      * @cfg {Array} dayNames
139      * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
140      */
141     dayNames : Date.dayNames,
142     /**
143      * @cfg {String} nextText
144      * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
145      */
146     nextText: 'Next Month (Control+Right)',
147     /**
148      * @cfg {String} prevText
149      * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
150      */
151     prevText: 'Previous Month (Control+Left)',
152     /**
153      * @cfg {String} monthYearText
154      * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
155      */
156     monthYearText: 'Choose a month (Control+Up/Down to move years)',
157     /**
158      * @cfg {Number} startDay
159      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
160      */
161     startDay : 0,
162     /**
163      * @cfg {Bool} showClear
164      * Show a clear button (usefull for date form elements that can be blank.)
165      */
166     
167     showClear: false,
168     
169     /**
170      * Sets the value of the date field
171      * @param {Date} value The date to set
172      */
173     setValue : function(value){
174         var old = this.value;
175         
176         if (typeof(value) == 'string') {
177          
178             value = Date.parseDate(value, this.format);
179         }
180         if (!value) {
181             value = new Date();
182         }
183         
184         this.value = value.clearTime(true);
185         if(this.el){
186             this.update(this.value);
187         }
188     },
189
190     /**
191      * Gets the current selected value of the date field
192      * @return {Date} The selected date
193      */
194     getValue : function(){
195         return this.value;
196     },
197
198     // private
199     focus : function(){
200         if(this.el){
201             this.update(this.activeDate);
202         }
203     },
204
205     // privateval
206     onRender : function(container, position){
207         
208         var m = [
209              '<table cellspacing="0">',
210                 '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'">&#160;</a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'">&#160;</a></td></tr>',
211                 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
212         var dn = this.dayNames;
213         for(var i = 0; i < 7; i++){
214             var d = this.startDay+i;
215             if(d > 6){
216                 d = d-7;
217             }
218             m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
219         }
220         m[m.length] = "</tr></thead><tbody><tr>";
221         for(var i = 0; i < 42; i++) {
222             if(i % 7 == 0 && i != 0){
223                 m[m.length] = "</tr><tr>";
224             }
225             m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
226         }
227         m[m.length] = '</tr></tbody></table></td></tr><tr>'+
228             '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
229
230         var el = document.createElement("div");
231         el.className = "x-date-picker";
232         el.innerHTML = m.join("");
233
234         container.dom.insertBefore(el, position);
235
236         this.el = Roo.get(el);
237         this.eventEl = Roo.get(el.firstChild);
238
239         new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
240             handler: this.showPrevMonth,
241             scope: this,
242             preventDefault:true,
243             stopDefault:true
244         });
245
246         new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
247             handler: this.showNextMonth,
248             scope: this,
249             preventDefault:true,
250             stopDefault:true
251         });
252
253         this.eventEl.on("mousewheel", this.handleMouseWheel,  this);
254
255         this.monthPicker = this.el.down('div.x-date-mp');
256         this.monthPicker.enableDisplayMode('block');
257         
258         var kn = new Roo.KeyNav(this.eventEl, {
259             "left" : function(e){
260                 e.ctrlKey ?
261                     this.showPrevMonth() :
262                     this.update(this.activeDate.add("d", -1));
263             },
264
265             "right" : function(e){
266                 e.ctrlKey ?
267                     this.showNextMonth() :
268                     this.update(this.activeDate.add("d", 1));
269             },
270
271             "up" : function(e){
272                 e.ctrlKey ?
273                     this.showNextYear() :
274                     this.update(this.activeDate.add("d", -7));
275             },
276
277             "down" : function(e){
278                 e.ctrlKey ?
279                     this.showPrevYear() :
280                     this.update(this.activeDate.add("d", 7));
281             },
282
283             "pageUp" : function(e){
284                 this.showNextMonth();
285             },
286
287             "pageDown" : function(e){
288                 this.showPrevMonth();
289             },
290
291             "enter" : function(e){
292                 e.stopPropagation();
293                 return true;
294             },
295
296             scope : this
297         });
298
299         this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});
300
301         this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday,  this);
302
303         this.el.unselectable();
304         
305         this.cells = this.el.select("table.x-date-inner tbody td");
306         this.textNodes = this.el.query("table.x-date-inner tbody span");
307
308         this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
309             text: "&#160;",
310             tooltip: this.monthYearText
311         });
312
313         this.mbtn.on('click', this.showMonthPicker, this);
314         this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
315
316
317         var today = (new Date()).dateFormat(this.format);
318         
319         var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
320         if (this.showClear) {
321             baseTb.add( new Roo.Toolbar.Fill());
322         }
323         baseTb.add({
324             text: String.format(this.todayText, today),
325             tooltip: String.format(this.todayTip, today),
326             handler: this.selectToday,
327             scope: this
328         });
329         
330         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
331             
332         //});
333         if (this.showClear) {
334             
335             baseTb.add( new Roo.Toolbar.Fill());
336             baseTb.add({
337                 text: '&#160;',
338                 cls: 'x-btn-icon x-btn-clear',
339                 handler: function() {
340                     //this.value = '';
341                     this.fireEvent("select", this, '');
342                 },
343                 scope: this
344             });
345         }
346         
347         
348         if(Roo.isIE){
349             this.el.repaint();
350         }
351         this.update(this.value);
352     },
353
354     createMonthPicker : function(){
355         if(!this.monthPicker.dom.firstChild){
356             var buf = ['<table border="0" cellspacing="0">'];
357             for(var i = 0; i < 6; i++){
358                 buf.push(
359                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
360                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
361                     i == 0 ?
362                     '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
363                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
364                 );
365             }
366             buf.push(
367                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
368                     this.okText,
369                     '</button><button type="button" class="x-date-mp-cancel">',
370                     this.cancelText,
371                     '</button></td></tr>',
372                 '</table>'
373             );
374             this.monthPicker.update(buf.join(''));
375             this.monthPicker.on('click', this.onMonthClick, this);
376             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
377
378             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
379             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
380
381             this.mpMonths.each(function(m, a, i){
382                 i += 1;
383                 if((i%2) == 0){
384                     m.dom.xmonth = 5 + Math.round(i * .5);
385                 }else{
386                     m.dom.xmonth = Math.round((i-1) * .5);
387                 }
388             });
389         }
390     },
391
392     showMonthPicker : function(){
393         this.createMonthPicker();
394         var size = this.el.getSize();
395         this.monthPicker.setSize(size);
396         this.monthPicker.child('table').setSize(size);
397
398         this.mpSelMonth = (this.activeDate || this.value).getMonth();
399         this.updateMPMonth(this.mpSelMonth);
400         this.mpSelYear = (this.activeDate || this.value).getFullYear();
401         this.updateMPYear(this.mpSelYear);
402
403         this.monthPicker.slideIn('t', {duration:.2});
404     },
405
406     updateMPYear : function(y){
407         this.mpyear = y;
408         var ys = this.mpYears.elements;
409         for(var i = 1; i <= 10; i++){
410             var td = ys[i-1], y2;
411             if((i%2) == 0){
412                 y2 = y + Math.round(i * .5);
413                 td.firstChild.innerHTML = y2;
414                 td.xyear = y2;
415             }else{
416                 y2 = y - (5-Math.round(i * .5));
417                 td.firstChild.innerHTML = y2;
418                 td.xyear = y2;
419             }
420             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
421         }
422     },
423
424     updateMPMonth : function(sm){
425         this.mpMonths.each(function(m, a, i){
426             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
427         });
428     },
429
430     selectMPMonth: function(m){
431         
432     },
433
434     onMonthClick : function(e, t){
435         e.stopEvent();
436         var el = new Roo.Element(t), pn;
437         if(el.is('button.x-date-mp-cancel')){
438             this.hideMonthPicker();
439         }
440         else if(el.is('button.x-date-mp-ok')){
441             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
442             this.hideMonthPicker();
443         }
444         else if(pn = el.up('td.x-date-mp-month', 2)){
445             this.mpMonths.removeClass('x-date-mp-sel');
446             pn.addClass('x-date-mp-sel');
447             this.mpSelMonth = pn.dom.xmonth;
448         }
449         else if(pn = el.up('td.x-date-mp-year', 2)){
450             this.mpYears.removeClass('x-date-mp-sel');
451             pn.addClass('x-date-mp-sel');
452             this.mpSelYear = pn.dom.xyear;
453         }
454         else if(el.is('a.x-date-mp-prev')){
455             this.updateMPYear(this.mpyear-10);
456         }
457         else if(el.is('a.x-date-mp-next')){
458             this.updateMPYear(this.mpyear+10);
459         }
460     },
461
462     onMonthDblClick : function(e, t){
463         e.stopEvent();
464         var el = new Roo.Element(t), pn;
465         if(pn = el.up('td.x-date-mp-month', 2)){
466             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
467             this.hideMonthPicker();
468         }
469         else if(pn = el.up('td.x-date-mp-year', 2)){
470             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
471             this.hideMonthPicker();
472         }
473     },
474
475     hideMonthPicker : function(disableAnim){
476         if(this.monthPicker){
477             if(disableAnim === true){
478                 this.monthPicker.hide();
479             }else{
480                 this.monthPicker.slideOut('t', {duration:.2});
481             }
482         }
483     },
484
485     // private
486     showPrevMonth : function(e){
487         this.update(this.activeDate.add("mo", -1));
488     },
489
490     // private
491     showNextMonth : function(e){
492         this.update(this.activeDate.add("mo", 1));
493     },
494
495     // private
496     showPrevYear : function(){
497         this.update(this.activeDate.add("y", -1));
498     },
499
500     // private
501     showNextYear : function(){
502         this.update(this.activeDate.add("y", 1));
503     },
504
505     // private
506     handleMouseWheel : function(e){
507         var delta = e.getWheelDelta();
508         if(delta > 0){
509             this.showPrevMonth();
510             e.stopEvent();
511         } else if(delta < 0){
512             this.showNextMonth();
513             e.stopEvent();
514         }
515     },
516
517     // private
518     handleDateClick : function(e, t){
519         e.stopEvent();
520         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
521             this.setValue(new Date(t.dateValue));
522             this.fireEvent("select", this, this.value);
523         }
524     },
525
526     // private
527     selectToday : function(){
528         this.setValue(new Date().clearTime());
529         this.fireEvent("select", this, this.value);
530     },
531
532     // private
533     update : function(date)
534     {
535         var vd = this.activeDate;
536         this.activeDate = date;
537         if(vd && this.el){
538             var t = date.getTime();
539             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
540                 this.cells.removeClass("x-date-selected");
541                 this.cells.each(function(c){
542                    if(c.dom.firstChild.dateValue == t){
543                        c.addClass("x-date-selected");
544                        setTimeout(function(){
545                             try{c.dom.firstChild.focus();}catch(e){}
546                        }, 50);
547                        return false;
548                    }
549                 });
550                 return;
551             }
552         }
553         
554         var days = date.getDaysInMonth();
555         var firstOfMonth = date.getFirstDateOfMonth();
556         var startingPos = firstOfMonth.getDay()-this.startDay;
557
558         if(startingPos <= this.startDay){
559             startingPos += 7;
560         }
561
562         var pm = date.add("mo", -1);
563         var prevStart = pm.getDaysInMonth()-startingPos;
564
565         var cells = this.cells.elements;
566         var textEls = this.textNodes;
567         days += startingPos;
568
569         // convert everything to numbers so it's fast
570         var day = 86400000;
571         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
572         var today = new Date().clearTime().getTime();
573         var sel = date.clearTime().getTime();
574         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
575         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
576         var ddMatch = this.disabledDatesRE;
577         var ddText = this.disabledDatesText;
578         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
579         var ddaysText = this.disabledDaysText;
580         var format = this.format;
581
582         var setCellClass = function(cal, cell){
583             cell.title = "";
584             var t = d.getTime();
585             cell.firstChild.dateValue = t;
586             if(t == today){
587                 cell.className += " x-date-today";
588                 cell.title = cal.todayText;
589             }
590             if(t == sel){
591                 cell.className += " x-date-selected";
592                 setTimeout(function(){
593                     try{cell.firstChild.focus();}catch(e){}
594                 }, 50);
595             }
596             // disabling
597             if(t < min) {
598                 cell.className = " x-date-disabled";
599                 cell.title = cal.minText;
600                 return;
601             }
602             if(t > max) {
603                 cell.className = " x-date-disabled";
604                 cell.title = cal.maxText;
605                 return;
606             }
607             if(ddays){
608                 if(ddays.indexOf(d.getDay()) != -1){
609                     cell.title = ddaysText;
610                     cell.className = " x-date-disabled";
611                 }
612             }
613             if(ddMatch && format){
614                 var fvalue = d.dateFormat(format);
615                 if(ddMatch.test(fvalue)){
616                     cell.title = ddText.replace("%0", fvalue);
617                     cell.className = " x-date-disabled";
618                 }
619             }
620         };
621
622         var i = 0;
623         for(; i < startingPos; i++) {
624             textEls[i].innerHTML = (++prevStart);
625             d.setDate(d.getDate()+1);
626             cells[i].className = "x-date-prevday";
627             setCellClass(this, cells[i]);
628         }
629         for(; i < days; i++){
630             intDay = i - startingPos + 1;
631             textEls[i].innerHTML = (intDay);
632             d.setDate(d.getDate()+1);
633             cells[i].className = "x-date-active";
634             setCellClass(this, cells[i]);
635         }
636         var extraDays = 0;
637         for(; i < 42; i++) {
638              textEls[i].innerHTML = (++extraDays);
639              d.setDate(d.getDate()+1);
640              cells[i].className = "x-date-nextday";
641              setCellClass(this, cells[i]);
642         }
643
644         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
645         this.fireEvent('monthchange', this, date);
646         
647         if(!this.internalRender){
648             var main = this.el.dom.firstChild;
649             var w = main.offsetWidth;
650             this.el.setWidth(w + this.el.getBorderWidth("lr"));
651             Roo.fly(main).setWidth(w);
652             this.internalRender = true;
653             // opera does not respect the auto grow header center column
654             // then, after it gets a width opera refuses to recalculate
655             // without a second pass
656             if(Roo.isOpera && !this.secondPass){
657                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
658                 this.secondPass = true;
659                 this.update.defer(10, this, [date]);
660             }
661         }
662         
663         
664     }
665 });