weekly release 4.0dev
[moodle.git] / lib / form / yui / build / moodle-form-dateselector / moodle-form-dateselector.js
1 YUI.add('moodle-form-dateselector', function (Y, NAME) {
3 var CALENDAR;
4 var MOODLECALENDAR;
5 var DIALOGUE_SELECTOR = ' [role=dialog]',
6     MENUBAR_SELECTOR = '[role=menubar]',
7     DOT = '.',
8     HAS_ZINDEX = 'moodle-has-zindex';
10 /**
11  * Add some custom methods to the node class to make our lives a little
12  * easier within this module.
13  */
14 Y.mix(Y.Node.prototype, {
15     /**
16      * Gets the value of the first option in the select box
17      */
18     firstOptionValue: function() {
19         if (this.get('nodeName').toLowerCase() !== 'select') {
20             return false;
21         }
22         return this.one('option').get('value');
23     },
24     /**
25      * Gets the value of the last option in the select box
26      */
27     lastOptionValue: function() {
28         if (this.get('nodeName').toLowerCase() !== 'select') {
29             return false;
30         }
31         return this.all('option').item(this.optionSize() - 1).get('value');
32     },
33     /**
34      * Gets the number of options in the select box
35      */
36     optionSize: function() {
37         if (this.get('nodeName').toLowerCase() !== 'select') {
38             return false;
39         }
40         return parseInt(this.all('option').size(), 10);
41     },
42     /**
43      * Gets the value of the selected option in the select box
44      */
45     selectedOptionValue: function() {
46         if (this.get('nodeName').toLowerCase() !== 'select') {
47             return false;
48         }
49         return this.all('option').item(this.get('selectedIndex')).get('value');
50     }
51 });
53 M.form = M.form || {};
54 M.form.dateselector = {
55     panel: null,
56     calendar: null,
57     currentowner: null,
58     hidetimeout: null,
59     repositiontimeout: null,
60     init_date_selectors: function(config) {
61         if (this.panel === null) {
62             this.initPanel(config);
63         }
64         Y.all('.fdate_time_selector').each(function() {
65             config.node = this;
66             new CALENDAR(config);
67         });
68         Y.all('.fdate_selector').each(function() {
69             config.node = this;
70             new CALENDAR(config);
71         });
72     },
73     initPanel: function(config) {
74         this.panel = new Y.Overlay({
75             visible: false,
76             bodyContent: Y.Node.create('<div id="dateselector-calendar-content"></div>'),
77             id: 'dateselector-calendar-panel',
78             constrain: true // constrain panel to viewport.
79         });
80         this.panel.render(document.body);
82         // Determine the correct zindex by looking at all existing dialogs and menubars in the page.
83         var highestzindex = 0;
84         Y.all(DIALOGUE_SELECTOR + ', ' + MENUBAR_SELECTOR + ', ' + DOT + HAS_ZINDEX).each(function(node) {
85             var zindex = this.findZIndex(node);
86             if (zindex > highestzindex) {
87                 highestzindex = zindex;
88             }
89         }, this);
90         // Only set the zindex if we found a wrapper.
91         var zindexvalue = (highestzindex + 1).toString();
92         Y.one('#dateselector-calendar-panel').setStyle('zIndex', zindexvalue);
94         this.panel.on('heightChange', this.fix_position, this);
96         Y.one('#dateselector-calendar-panel').on('click', function(e) {
97             e.halt();
98         });
99         Y.one(document.body).on('click', this.document_click, this);
101         this.calendar = new MOODLECALENDAR({
102             contentBox: "#dateselector-calendar-content",
103             width: "300px",
104             showPrevMonth: true,
105             showNextMonth: true,
106             firstdayofweek: parseInt(config.firstdayofweek, 10),
107             WEEKDAYS_MEDIUM: [
108                 config.sun,
109                 config.mon,
110                 config.tue,
111                 config.wed,
112                 config.thu,
113                 config.fri,
114                 config.sat]
115         });
116     },
117     findZIndex: function(node) {
118         // In most cases the zindex is set on the parent of the dialog.
119         var zindex = node.getStyle('zIndex') || node.ancestor().getStyle('zIndex');
120         if (zindex) {
121             return parseInt(zindex, 10);
122         }
123         return 0;
124     },
125     cancel_any_timeout: function() {
126         if (this.hidetimeout) {
127             clearTimeout(this.hidetimeout);
128             this.hidetimeout = null;
129         }
130         if (this.repositiontimeout) {
131             clearTimeout(this.repositiontimeout);
132             this.repositiontimeout = null;
133         }
134     },
135     delayed_reposition: function() {
136         if (this.repositiontimeout) {
137             clearTimeout(this.repositiontimeout);
138             this.repositiontimeout = null;
139         }
140         this.repositiontimeout = setTimeout(this.fix_position, 500);
141     },
142     fix_position: function() {
143         if (this.currentowner) {
144             var alignpoints = [
145                 Y.WidgetPositionAlign.BL,
146                 Y.WidgetPositionAlign.TL
147             ];
149             // Change the alignment if this is an RTL language.
150             if (window.right_to_left()) {
151                 alignpoints = [
152                     Y.WidgetPositionAlign.BR,
153                     Y.WidgetPositionAlign.TR
154                 ];
155             }
157             this.panel.set('align', {
158                 node: this.currentowner.get('node').one('select'),
159                 points: alignpoints
160             });
161         }
162     },
163     document_click: function(e) {
164         if (this.currentowner) {
165             if (this.currentowner.get('node').ancestor('div').contains(e.target)) {
166                 setTimeout(function() {
167                     M.form.dateselector.cancel_any_timeout();
168                 }, 100);
169             } else {
170                 this.currentowner.release_calendar(e);
171             }
172         }
173     }
174 };
175 /**
176  * Provides the Moodle Calendar class.
177  *
178  * @module moodle-form-dateselector
179  */
181 /**
182  * A class to overwrite the YUI3 Calendar in order to change the strings..
183  *
184  * @class M.form_moodlecalendar
185  * @constructor
186  * @extends Calendar
187  */
188 MOODLECALENDAR = function() {
189     MOODLECALENDAR.superclass.constructor.apply(this, arguments);
190 };
192 Y.extend(MOODLECALENDAR, Y.Calendar, {
193         initializer: function(cfg) {
194             this.set("strings.very_short_weekdays", cfg.WEEKDAYS_MEDIUM);
195             this.set("strings.first_weekday", cfg.firstdayofweek);
196         }
197     }, {
198         NAME: 'Calendar',
199         ATTRS: {}
200     }
201 );
203 M.form_moodlecalendar = M.form_moodlecalendar || {};
204 M.form_moodlecalendar.initializer = function(params) {
205     return new MOODLECALENDAR(params);
206 };
207 /**
208  * Provides the Calendar class.
209  *
210  * @module moodle-form-dateselector
211  */
213 /**
214  * Calendar class
215  */
216 CALENDAR = function() {
217     CALENDAR.superclass.constructor.apply(this, arguments);
218 };
219 CALENDAR.prototype = {
220     panel: null,
221     yearselect: null,
222     monthselect: null,
223     dayselect: null,
224     calendarimage: null,
225     enablecheckbox: null,
226     closepopup: true,
227     initializer: function() {
228         var controls = this.get('node').all('select');
229         controls.each(function(node) {
230             if (node.get('name').match(/\[year\]/)) {
231                 this.yearselect = node;
232             } else if (node.get('name').match(/\[month\]/)) {
233                 this.monthselect = node;
234             } else if (node.get('name').match(/\[day\]/)) {
235                 this.dayselect = node;
236             }
237             node.after('change', this.handle_select_change, this);
238         }, this);
240         // Loop through the input fields.
241         var inputs = this.get('node').all('input, a');
242         inputs.each(function(node) {
243             // Check if the current node is a calendar image field.
244             if (node.get('name').match(/\[calendar\]/)) {
245                 // Set it so that when the image is clicked the pop-up displays.
246                 node.on('click', this.focus_event, this);
247                 // Set the node to the calendarimage variable.
248                 this.calendarimage = node;
249             } else { // Must be the enabled checkbox field.
250                 // If the enable checkbox is clicked we want to either disable/enable the calendar image.
251                 node.on('click', this.toggle_calendar_image, this);
252                 // Set the node to the enablecheckbox variable.
253                 this.enablecheckbox = node;
254             }
255             // Ensure that the calendarimage and enablecheckbox values have been set.
256             if (this.calendarimage && this.enablecheckbox) {
257                 // Set the calendar icon status depending on the value of the checkbox.
258                 this.toggle_calendar_image();
259             }
260         }, this);
261     },
262     focus_event: function(e) {
263         M.form.dateselector.cancel_any_timeout();
264         // If the current owner is set, then the pop-up is currently being displayed, so hide it.
265         if (M.form.dateselector.currentowner === this) {
266             this.release_calendar();
267         } else if ((this.enablecheckbox === null)
268             || (this.enablecheckbox.get('checked'))) { // Must be hidden. If the field is enabled display the pop-up.
269             this.claim_calendar();
270         }
271         // Stop the input image field from submitting the form.
272         e.preventDefault();
273     },
274     handle_select_change: function() {
275         // It may seem as if the following variable is not used, however any call to set_date_from_selects will trigger a
276         // call to set_selects_from_date if the calendar is open as the date has changed. Whenever the calendar is displayed
277         // the set_selects_from_date function is set to trigger on any date change (see function connect_handlers).
278         this.closepopup = false;
279         this.set_date_from_selects();
280         this.closepopup = true;
281     },
282     claim_calendar: function() {
283         M.form.dateselector.cancel_any_timeout();
284         if (M.form.dateselector.currentowner === this) {
285             return;
286         }
287         if (M.form.dateselector.currentowner) {
288             M.form.dateselector.currentowner.release_calendar();
289         }
290         if (M.form.dateselector.currentowner !== this) {
291             this.connect_handlers();
292             this.set_date_from_selects();
293         }
294         M.form.dateselector.currentowner = this;
295         M.form.dateselector.calendar.set('mindate', new Date(this.yearselect.firstOptionValue(), 0, 1));
296         M.form.dateselector.calendar.set('maxdate', new Date(this.yearselect.lastOptionValue(), 11, 31));
297         M.form.dateselector.panel.show();
298         M.form.dateselector.calendar.show();
299         M.form.dateselector.fix_position();
300         setTimeout(function() {
301             M.form.dateselector.cancel_any_timeout();
302         }, 100);
304         // Focus on the calendar.
305         M.form.dateselector.calendar.focus();
307         // When the user tab out the calendar, close it.
308         Y.one(document.body).on('keyup', function(e) {
309             // hide the calendar if we press a key and the calendar is not focussed, or if we press ESC in the calendar.
310             if ((M.form.dateselector.currentowner === this && !M.form.dateselector.calendar.get('focused')) ||
311                 ((e.keyCode === 27) && M.form.dateselector.calendar.get('focused'))) {
312                 // Focus back on the calendar button.
313                 this.calendarimage.focus();
314                 this.release_calendar();
315             }
316         }, this);
318     },
319     set_date_from_selects: function() {
320         var year = parseInt(this.yearselect.get('value'), 10);
321         var month = parseInt(this.monthselect.get('value'), 10) - 1;
322         var day = parseInt(this.dayselect.get('value'), 10);
323         var date = new Date(year, month, day);
324         M.form.dateselector.calendar.deselectDates();
325         M.form.dateselector.calendar.selectDates([date]);
326         M.form.dateselector.calendar.set("date", date);
327         M.form.dateselector.calendar.render();
328         if (date.getDate() !== day) {
329             // Must've selected the 29 to 31st of a month that doesn't have such dates.
330             this.dayselect.set('value', date.getDate());
331             this.monthselect.set('value', date.getMonth() + 1);
332         }
333     },
334     set_selects_from_date: function(ev) {
335         var date = ev.newSelection[0];
336         var newyear = Y.DataType.Date.format(date, {format: "%Y"});
337         var newindex = newyear - this.yearselect.firstOptionValue();
338         this.yearselect.set('selectedIndex', newindex);
339         this.monthselect.set('selectedIndex', Y.DataType.Date.format(date, {format: "%m"}) - this.monthselect.firstOptionValue());
340         this.dayselect.set('selectedIndex', Y.DataType.Date.format(date, {format: "%d"}) - this.dayselect.firstOptionValue());
341         if (M.form.dateselector.currentowner && this.closepopup) {
342             this.release_calendar();
343         }
344     },
345     connect_handlers: function() {
346         M.form.dateselector.calendar.on('selectionChange', this.set_selects_from_date, this, true);
347     },
348     release_calendar: function(e) {
349         var wasOwner = M.form.dateselector.currentowner === this;
350         M.form.dateselector.panel.hide();
351         M.form.dateselector.calendar.detach('selectionChange', this.set_selects_from_date);
352         M.form.dateselector.calendar.hide();
353         M.form.dateselector.currentowner = null;
355         // Put the focus back to the image calendar that we clicked, only if it was visible.
356         if (wasOwner && (e === null || typeof e === "undefined" || e.type !== "click")) {
357             this.calendarimage.focus();
358         }
359     },
360     toggle_calendar_image: function() {
361         // If the enable checkbox is det checked, disable the image.
362         if (!this.enablecheckbox.get('checked')) {
363             this.calendarimage.set('disabled', 'disabled');
364             this.calendarimage.setStyle('cursor', 'default');
365             this.release_calendar();
366         } else {
367             this.calendarimage.set('disabled', false);
368             this.calendarimage.setStyle('cursor', null);
369         }
370     }
371 };
372 Y.extend(CALENDAR, Y.Base, CALENDAR.prototype, {
373     NAME: 'Date Selector',
374     ATTRS: {
375         firstdayofweek: {
376             validator: Y.Lang.isString
377         },
378         node: {
379             setter: function(node) {
380                 return Y.one(node);
381             }
382         }
383     }
384 });
387 }, '@VERSION@', {"requires": ["base", "node", "overlay", "calendar"]});