]> git.donarmstrong.com Git - roundcube.git/blob - skins/default/functions.js
Imported Upstream version 0.7
[roundcube.git] / skins / default / functions.js
1 /**
2  * Roundcube functions for default skin interface
3  */
4
5 /**
6  * Settings
7  */
8
9 function rcube_init_settings_tabs()
10 {
11   var tab = '#settingstabdefault';
12   if (window.rcmail && rcmail.env.action)
13     tab = '#settingstab' + (rcmail.env.action=='preferences' ? 'default' : (rcmail.env.action.indexOf('identity')>0 ? 'identities' : rcmail.env.action.replace(/\./g, '')));
14
15   $(tab).addClass('tablink-selected');
16   $(tab + '> a').removeAttr('onclick').click(function() { return false; });
17 }
18
19 function rcube_show_advanced(visible)
20 {
21   $('tr.advanced').css('display', (visible ? (bw.ie ? 'block' : 'table-row') : 'none'));
22 }
23
24 // Fieldsets-to-tabs converter
25 // Warning: don't place "caller" <script> inside page element (id)
26 function rcube_init_tabs(id, current)
27 {
28   var content = $('#'+id),
29     fs = content.children('fieldset');
30
31   if (!fs.length)
32     return;
33
34   current = current ? current : 0;
35
36   // first hide not selected tabs
37   fs.each(function(idx) { if (idx != current) $(this).hide(); });
38
39   // create tabs container
40   var tabs = $('<div>').addClass('tabsbar').appendTo(content);
41
42   // convert fildsets into tabs
43   fs.each(function(idx) {
44     var tab, a, elm = $(this), legend = elm.children('legend');
45
46     // create a tab
47     a   = $('<a>').text(legend.text()).attr('href', '#');
48     tab = $('<span>').attr({'id': 'tab'+idx, 'class': 'tablink'})
49         .click(function() { rcube_show_tab(id, idx); return false })
50
51     // remove legend
52     legend.remove();
53     // style fieldset
54     elm.addClass('tabbed');
55     // style selected tab
56     if (idx == current)
57       tab.addClass('tablink-selected');
58
59     // add the tab to container
60     tab.append(a).appendTo(tabs);
61   });
62 }
63
64 function rcube_show_tab(id, index)
65 {
66   var fs = $('#'+id).children('fieldset');
67
68   fs.each(function(idx) {
69     // Show/hide fieldset (tab content)
70     $(this)[index==idx ? 'show' : 'hide']();
71     // Select/unselect tab
72     $('#tab'+idx).toggleClass('tablink-selected', idx==index);
73   });
74 }
75
76 /**
77  * Mail UI
78  */
79
80 function rcube_mail_ui()
81 {
82   this.popups = {
83     markmenu:       {id:'markmessagemenu'},
84     replyallmenu:   {id:'replyallmenu'},
85     forwardmenu:    {id:'forwardmenu', editable:1},
86     searchmenu:     {id:'searchmenu', editable:1},
87     messagemenu:    {id:'messagemenu'},
88     listmenu:       {id:'listmenu', editable:1},
89     dragmessagemenu:{id:'dragmessagemenu', sticky:1},
90     groupmenu:      {id:'groupoptionsmenu', above:1},
91     mailboxmenu:    {id:'mailboxoptionsmenu', above:1},
92     composemenu:    {id:'composeoptionsmenu', editable:1, overlap:1},
93     // toggle: #1486823, #1486930
94     uploadmenu:     {id:'attachment-form', editable:1, above:1, toggle:!bw.ie&&!bw.linux },
95     uploadform:     {id:'upload-form', editable:1, toggle:!bw.ie&&!bw.linux }
96   };
97
98   var obj;
99   for (var k in this.popups) {
100     obj = $('#'+this.popups[k].id)
101     if (obj.length)
102       this.popups[k].obj = obj;
103     else {
104       delete this.popups[k];
105     }
106   }
107 }
108
109 rcube_mail_ui.prototype = {
110
111 show_popup: function(popup, show, config)
112 {
113   var obj;
114   // auto-register menu object
115   if (!this.popups[popup] && (obj = $('#'+popup)) && obj.length)
116     this.popups[popup] = $.extend(config, {id: popup, obj: obj});
117
118   if (typeof this[popup] == 'function')
119     return this[popup](show);
120   else
121     return this.show_popupmenu(popup, show);
122 },
123
124 show_popupmenu: function(popup, show)
125 {
126   var obj = this.popups[popup].obj,
127     above = this.popups[popup].above,
128     ref = rcube_find_object(popup+'link');
129
130   if (typeof show == 'undefined')
131     show = obj.is(':visible') ? false : true;
132   else if (this.popups[popup].toggle && show && this.popups[popup].obj.is(':visible') )
133     show = false;
134
135   if (show && ref) {
136     var parent = $(ref).parent(),
137       win = $(window),
138       pos = parent.hasClass('dropbutton') ? parent.offset() : $(ref).offset();
139
140     if (!above && pos.top + ref.offsetHeight + obj.height() > win.height())
141       above = true;
142     if (pos.left + obj.width() > win.width())
143       pos.left = win.width() - obj.width() - 30;
144
145     obj.css({ left:pos.left, top:(pos.top + (above ? -obj.height() : ref.offsetHeight)) });
146   }
147
148   obj[show?'show':'hide']();
149
150   if (bw.ie6 && this.popups[popup].overlap) {
151     $('select').css('visibility', show?'hidden':'inherit');
152     $('select', obj).css('visibility', 'inherit');
153   }
154 },
155
156 dragmessagemenu: function(show)
157 {
158   this.popups.dragmessagemenu.obj[show?'show':'hide']();
159 },
160
161 forwardmenu: function(show)
162 {
163   $("input[name='forwardtype'][value="+(rcmail.env.forward_attachment ? 1 : 0)+"]", this.popups.forwardmenu.obj)
164     .prop('checked', true);
165   this.show_popupmenu('forwardmenu', show);
166 },
167
168 uploadmenu: function(show)
169 {
170   if (typeof show == 'object') // called as event handler
171     show = false;
172
173   // clear upload form
174   if (!show) {
175     try { $('#attachment-form form')[0].reset(); }
176     catch(e){}  // ignore errors
177   }
178
179   this.show_popupmenu('uploadmenu', show);
180
181   if (!document.all && this.popups.uploadmenu.obj.is(':visible'))
182     $('#attachment-form input[type=file]').click();
183 },
184
185 searchmenu: function(show)
186 {
187   var obj = this.popups.searchmenu.obj,
188     ref = rcube_find_object('searchmenulink');
189
190   if (typeof show == 'undefined')
191     show = obj.is(':visible') ? false : true;
192
193   if (show && ref) {
194     var pos = $(ref).offset();
195     obj.css({left:pos.left, top:(pos.top + ref.offsetHeight + 2)});
196
197     if (rcmail.env.search_mods) {
198       var n, all,
199         list = $('input:checkbox[name="s_mods[]"]', obj),
200         mbox = rcmail.env.mailbox,
201         mods = rcmail.env.search_mods;
202
203       if (rcmail.env.task == 'mail') {
204         mods = mods[mbox] ? mods[mbox] : mods['*'];
205         all = 'text';
206       }
207       else {
208         all = '*';
209       }
210
211       if (mods[all])
212         list.map(function() {
213           this.checked = true;
214           this.disabled = this.value != all;
215         });
216       else {
217         list.prop('disabled', false).prop('checked', false);
218         for (n in mods)
219           $('#s_mod_' + n).prop('checked', true);
220       }
221     }
222   }
223   obj[show?'show':'hide']();
224 },
225
226 set_searchmod: function(elem)
227 {
228   var all, m, task = rcmail.env.task,
229     mods = rcmail.env.search_mods,
230     mbox = rcmail.env.mailbox;
231
232   if (!mods)
233     mods = {};
234
235   if (task == 'mail') {
236     if (!mods[mbox])
237       mods[mbox] = rcube_clone_object(mods['*']);
238     m = mods[mbox];
239     all = 'text';
240   }
241   else { //addressbook
242     m = mods;
243     all = '*';
244   }
245
246   if (!elem.checked)
247     delete(m[elem.value]);
248   else
249     m[elem.value] = 1;
250
251   // mark all fields
252   if (elem.value != all)
253     return;
254
255   $('input:checkbox[name="s_mods[]"]').map(function() {
256     if (this == elem)
257       return;
258
259     this.checked = true;
260     if (elem.checked) {
261       this.disabled = true;
262       delete m[this.value];
263     }
264     else {
265       this.disabled = false;
266       m[this.value] = 1;
267     }
268   });
269 },
270
271 listmenu: function(show)
272 {
273   var obj = this.popups.listmenu.obj,
274     ref = rcube_find_object('listmenulink');
275
276   if (typeof show == 'undefined')
277     show = obj.is(':visible') ? false : true;
278
279   if (show && ref) {
280     var pos = $(ref).offset(),
281       menuwidth = obj.width(),
282       pagewidth = $(document).width();
283
284     if (pagewidth - pos.left < menuwidth && pos.left > menuwidth)
285       pos.left = pos.left - menuwidth;
286
287     obj.css({ left:pos.left, top:(pos.top + ref.offsetHeight + 2)});
288     // set form values
289     $('input[name="sort_col"][value="'+rcmail.env.sort_col+'"]').prop('checked', true);
290     $('input[name="sort_ord"][value="DESC"]').prop('checked', rcmail.env.sort_order == 'DESC');
291     $('input[name="sort_ord"][value="ASC"]').prop('checked', rcmail.env.sort_order != 'DESC');
292     $('input[name="view"][value="thread"]').prop('checked', rcmail.env.threading ? true : false);
293     $('input[name="view"][value="list"]').prop('checked', rcmail.env.threading ? false : true);
294     // list columns
295     var found, cols = $('input[name="list_col[]"]');
296     for (var i=0; i<cols.length; i++) {
297       if (cols[i].value != 'from')
298         found = jQuery.inArray(cols[i].value, rcmail.env.coltypes) != -1;
299       else
300         found = (jQuery.inArray('from', rcmail.env.coltypes) != -1
301                 || jQuery.inArray('to', rcmail.env.coltypes) != -1);
302       $(cols[i]).prop('checked', found);
303     }
304   }
305
306   obj[show?'show':'hide']();
307
308   if (show) {
309     var maxheight=0;
310     $('#listmenu fieldset').each(function() {
311       var height = $(this).height();
312       if (height > maxheight) {
313         maxheight = height;
314       }
315     });
316     $('#listmenu fieldset').css("min-height", maxheight+"px")
317     // IE6 complains if you set this attribute using either method:
318     //$('#listmenu fieldset').css({'height':'auto !important'});
319     //$('#listmenu fieldset').css("height","auto !important");
320       .height(maxheight);
321   };
322 },
323
324 open_listmenu: function(e)
325 {
326   this.listmenu();
327 },
328
329 save_listmenu: function()
330 {
331   this.listmenu();
332
333   var sort = $('input[name="sort_col"]:checked').val(),
334     ord = $('input[name="sort_ord"]:checked').val(),
335     thread = $('input[name="view"]:checked').val(),
336     cols = $('input[name="list_col[]"]:checked')
337       .map(function(){ return this.value; }).get();
338
339   rcmail.set_list_options(cols, sort, ord, thread == 'thread' ? 1 : 0);
340 },
341
342 body_mouseup: function(evt, p)
343 {
344   var i, target = rcube_event.get_target(evt);
345
346   for (i in this.popups) {
347     if (this.popups[i].obj.is(':visible') && target != rcube_find_object(i+'link')
348       && !this.popups[i].toggle
349       && (!this.popups[i].editable || !this.target_overlaps(target, this.popups[i].id))
350       && (!this.popups[i].sticky || !rcube_mouse_is_over(evt, rcube_find_object(this.popups[i].id)))
351     ) {
352       window.setTimeout('rcmail_ui.show_popup("'+i+'",false);', 50);
353     }
354   }
355 },
356
357 target_overlaps: function (target, elementid)
358 {
359   var element = rcube_find_object(elementid);
360   while (target.parentNode) {
361     if (target.parentNode == element)
362       return true;
363     target = target.parentNode;
364   }
365   return false;
366 },
367
368 body_keydown: function(evt, p)
369 {
370   if (rcube_event.get_keycode(evt) == 27) {
371     for (var k in this.popups) {
372       if (this.popups[k].obj.is(':visible'))
373         this.show_popup(k, false);
374     }
375   }
376 },
377
378 switch_preview_pane: function(elem)
379 {
380   var uid, prev_frm = $('#mailpreviewframe');
381
382   if (elem.checked) {
383     rcmail.env.contentframe = 'messagecontframe';
384     if (mailviewsplit.layer) {
385       mailviewsplit.resize();
386       mailviewsplit.layer.elm.style.display = '';
387     }
388     else
389       mailviewsplit.init();
390
391     if (bw.opera) {
392       $('#messagelistcontainer').css({height: ''});
393     }
394     prev_frm.show();
395
396     if (uid = rcmail.message_list.get_single_selection())
397       rcmail.show_message(uid, false, true);
398   }
399   else {
400     prev_frm.hide();
401     if (bw.ie6 || bw.ie7) {
402       var fr = document.getElementById('mailcontframe');
403       fr.style.bottom = 0;
404       fr.style.height = parseInt(fr.parentNode.offsetHeight)+'px';
405     }
406     else {
407       $('#mailcontframe').css({height: 'auto', bottom: 0});
408       if (bw.opera)
409         $('#messagelistcontainer').css({height: 'auto'});
410     }
411     if (mailviewsplit.layer)
412       mailviewsplit.layer.elm.style.display = 'none';
413
414     rcmail.env.contentframe = null;
415     rcmail.show_contentframe(false);
416   }
417
418   rcmail.command('save-pref', {name: 'preview_pane', value: (elem.checked?1:0)});
419 },
420
421 /* Message composing */
422 init_compose_form: function()
423 {
424   var f, field, fields = ['cc', 'bcc', 'replyto', 'followupto'],
425     div = document.getElementById('compose-div'),
426     headers_div = document.getElementById('compose-headers-div');
427
428   // Show input elements with non-empty value
429   for (f=0; f<fields.length; f++) {
430     if ((field = $('#_'+fields[f])) && field.length && field.val() != '')
431       rcmail_ui.show_header_form(fields[f]);
432   }
433
434   // prevent from form data loss when pressing ESC key in IE
435   if (bw.ie) {
436     var form = rcube_find_object('form');
437     form.onkeydown = function (e) {
438       if (rcube_event.get_keycode(e) == 27)
439         rcube_event.cancel(e);
440     };
441   }
442
443   $(window).resize(function() {
444     rcmail_ui.resize_compose_body();
445   });
446
447   $('#compose-container').resize(function() {
448     rcmail_ui.resize_compose_body();
449   });
450
451   div.style.top = (parseInt(headers_div.offsetHeight, 10) + 3) + 'px';
452   $(window).resize();
453 },
454
455 resize_compose_body: function()
456 {
457   var div = $('#compose-div .boxlistcontent'), w = div.width(), h = div.height();
458   w -= 8;  // 2 x 3px padding + 2 x 1px border
459   h -= 4;
460
461   $('#compose-body').width(w+'px').height(h+'px');
462
463   if (window.tinyMCE && tinyMCE.get('compose-body')) {
464     $('#compose-body_tbl').width((w+6)+'px').height('');
465     $('#compose-body_ifr').width((w+6)+'px').height((h-54)+'px');
466   }
467   else {
468     $('#googie_edit_layer').height(h+'px');
469   }
470 },
471
472 resize_compose_body_ev: function()
473 {
474   window.setTimeout(function(){rcmail_ui.resize_compose_body();}, 100);
475 },
476
477 show_header_form: function(id)
478 {
479   var row, s,
480     link = document.getElementById(id + '-link');
481
482   if ((s = this.next_sibling(link)))
483     s.style.display = 'none';
484   else if ((s = this.prev_sibling(link)))
485     s.style.display = 'none';
486
487   link.style.display = 'none';
488
489   if ((row = document.getElementById('compose-' + id))) {
490     var div = document.getElementById('compose-div'),
491       headers_div = document.getElementById('compose-headers-div');
492     row.style.display = (document.all && !window.opera) ? 'block' : 'table-row';
493     div.style.top = (parseInt(headers_div.offsetHeight, 10) + 3) + 'px';
494     this.resize_compose_body();
495   }
496
497   return false;
498 },
499
500 hide_header_form: function(id)
501 {
502   var row, ns,
503     link = document.getElementById(id + '-link'),
504     parent = link.parentNode,
505     links = parent.getElementsByTagName('a');
506
507   link.style.display = '';
508
509   for (var i=0; i<links.length; i++)
510     if (links[i].style.display != 'none')
511       for (var j=i+1; j<links.length; j++)
512             if (links[j].style.display != 'none')
513           if ((ns = this.next_sibling(links[i]))) {
514                 ns.style.display = '';
515                 break;
516               }
517
518   document.getElementById('_' + id).value = '';
519
520   if ((row = document.getElementById('compose-' + id))) {
521     var div = document.getElementById('compose-div'),
522       headers_div = document.getElementById('compose-headers-div');
523     row.style.display = 'none';
524     div.style.top = (parseInt(headers_div.offsetHeight, 10) + 1) + 'px';
525     this.resize_compose_body();
526   }
527
528   return false;
529 },
530
531 next_sibling: function(elm)
532 {
533   var ns = elm.nextSibling;
534   while (ns && ns.nodeType == 3)
535     ns = ns.nextSibling;
536   return ns;
537 },
538
539 prev_sibling: function(elm)
540 {
541   var ps = elm.previousSibling;
542   while (ps && ps.nodeType == 3)
543     ps = ps.previousSibling;
544   return ps;
545 }
546
547 };
548
549
550 var rcmail_ui;
551
552 function rcube_init_mail_ui()
553 {
554   rcmail_ui = new rcube_mail_ui();
555   rcube_event.add_listener({ object:rcmail_ui, method:'body_mouseup', event:'mouseup' });
556   rcube_event.add_listener({ object:rcmail_ui, method:'body_keydown', event:'keydown' });
557
558   $('iframe').load(iframe_events)
559     .contents().mouseup(function(e){rcmail_ui.body_mouseup(e)});
560
561   if (rcmail.env.task == 'mail') {
562     rcmail.addEventListener('menu-open', 'open_listmenu', rcmail_ui);
563     rcmail.addEventListener('menu-save', 'save_listmenu', rcmail_ui);
564     rcmail.addEventListener('aftersend-attachment', 'uploadmenu', rcmail_ui);
565     rcmail.addEventListener('aftertoggle-editor', 'resize_compose_body_ev', rcmail_ui);
566     rcmail.gui_object('message_dragmenu', 'dragmessagemenu');
567
568     if (rcmail.gui_objects.mailboxlist) {
569       rcmail.addEventListener('responseaftermark', rcube_render_mailboxlist);
570       rcmail.addEventListener('responseaftergetunread', rcube_render_mailboxlist);
571       rcmail.addEventListener('responseaftercheck-recent', rcube_render_mailboxlist);
572       rcmail.addEventListener('aftercollapse-folder', rcube_render_mailboxlist);
573     }
574
575     if (rcmail.env.action == 'compose')
576       rcmail_ui.init_compose_form();
577   }
578   else if (rcmail.env.task == 'addressbook') {
579     rcmail.addEventListener('afterupload-photo', function(){ rcmail_ui.show_popup('uploadform', false); });
580   }
581 }
582
583 // Events handling in iframes (eg. preview pane)
584 function iframe_events()
585 {
586   // this==iframe
587   var doc = this.contentDocument ? this.contentDocument : this.contentWindow ? this.contentWindow.document : null;
588   rcube_event.add_listener({ element: doc, object:rcmail_ui, method:'body_mouseup', event:'mouseup' });
589 }
590
591 // Abbreviate mailbox names to fit width of the container
592 function rcube_render_mailboxlist()
593 {
594   var list = $('#mailboxlist > li a, #mailboxlist ul:visible > li a');
595
596   // it's too slow with really big number of folders, especially on IE
597   if (list.length > 500 * (bw.ie ? 0.2 : 1))
598     return;
599
600   list.each(function(){
601     var elem = $(this),
602       text = elem.data('text');
603
604     if (!text) {
605       text = elem.text().replace(/\s+\(.+$/, '');
606       elem.data('text', text);
607     }
608     if (text.length < 6)
609       return;
610
611     var abbrev = fit_string_to_size(text, elem, elem.width() - elem.children('span.unreadcount').width());
612     if (abbrev != text)
613       elem.attr('title', text);
614     elem.contents().filter(function(){ return (this.nodeType == 3); }).get(0).data = abbrev;
615   });
616 }
617
618 // inspired by https://gist.github.com/24261/7fdb113f1e26111bd78c0c6fe515f6c0bf418af5
619 function fit_string_to_size(str, elem, len)
620 {
621   var w, span, result = str, ellip = '...';
622
623   if (!rcmail.env.tmp_span) {
624     // it should be appended to elem to use the same css style
625     // but for performance reasons we'll append it to body (once)
626     span = $('<b>').css({visibility: 'hidden', padding: '0px'})
627       .appendTo($('body', document)).get(0);
628     rcmail.env.tmp_span = span;
629   }
630   else {
631     span = rcmail.env.tmp_span;
632   }
633   span.innerHTML = result;
634
635   // on first run, check if string fits into the length already.
636   w = span.offsetWidth;
637   if (w > len) {
638     var cut = Math.max(1, Math.floor(str.length * ((w - len) / w) / 2)),
639       mid = Math.floor(str.length / 2),
640       offLeft = mid,
641       offRight = mid;
642
643     while (true) {
644       offLeft = mid - cut;
645       offRight = mid + cut;
646       span.innerHTML = str.substring(0,offLeft) + ellip + str.substring(offRight);
647
648       // break loop if string fits size
649       if (offLeft < 3 || span.offsetWidth)
650         break;
651
652       cut++;
653     }
654
655     // build resulting string
656     result = str.substring(0,offLeft) + ellip + str.substring(offRight);
657   }
658
659   return result;
660 }
661
662 // Optional parameters used by TinyMCE
663 var rcmail_editor_settings = {
664   skin : "default", // "default", "o2k7"
665   skin_variant : "" // "", "silver", "black"
666 };