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