2 +-----------------------------------------------------------------------+
3 | Roundcube Webmail Client Script |
5 | This file is part of the Roundcube Webmail client |
6 | Copyright (C) 2005-2011, The Roundcube Dev Team |
7 | Copyright (C) 2011, Kolab Systems AG |
8 | Licensed under the GNU GPL |
10 +-----------------------------------------------------------------------+
11 | Authors: Thomas Bruederli <roundcube@gmail.com> |
12 | Aleksander 'A.L.E.C' Machniak <alec@alec.pl> |
13 | Charles McNulty <charles@charlesmcnulty.com> |
14 +-----------------------------------------------------------------------+
15 | Requires: jquery.js, common.js, list.js |
16 +-----------------------------------------------------------------------+
18 $Id: app.js 5635 2011-12-21 10:07:42Z alec $
21 function rcube_webmail()
23 this.env = { recipients_separator:',', recipients_delimiter:', ' };
26 this.buttons_sel = {};
27 this.gui_objects = {};
28 this.gui_containers = {};
30 this.command_handlers = {};
34 // create protected reference to myself
38 // webmail client settings
39 this.dblclick_time = 500;
40 this.message_time = 4000;
42 this.identifier_expr = new RegExp('[^0-9a-z\-_]', 'gi');
44 // default environment vars
45 this.env.keep_alive = 60; // seconds
46 this.env.request_timeout = 180; // seconds
47 this.env.draft_autosave = 0; // seconds
48 this.env.comm_path = './';
49 this.env.blankpage = 'program/blank.gif';
51 // set jQuery ajax options
54 error:function(request, status, err){ ref.http_error(request, status, err); },
55 beforeSend:function(xmlhttp){ xmlhttp.setRequestHeader('X-Roundcube-Request', ref.env.request_token); }
58 // set environment variable(s)
59 this.set_env = function(p, value)
61 if (p != null && typeof p === 'object' && !value)
68 // add a localized label to the client environment
69 this.add_label = function(p, value)
71 if (typeof p == 'string')
72 this.labels[p] = value;
73 else if (typeof p == 'object')
74 $.extend(this.labels, p);
77 // add a button to the button list
78 this.register_button = function(command, id, type, act, sel, over)
80 if (!this.buttons[command])
81 this.buttons[command] = [];
83 var button_prop = {id:id, type:type};
84 if (act) button_prop.act = act;
85 if (sel) button_prop.sel = sel;
86 if (over) button_prop.over = over;
88 this.buttons[command].push(button_prop);
91 init_button(command, button_prop);
94 // register a specific gui object
95 this.gui_object = function(name, id)
97 this.gui_objects[name] = this.loaded ? rcube_find_object(id) : id;
100 // register a container object
101 this.gui_container = function(name, id)
103 this.gui_containers[name] = id;
106 // add a GUI element (html node) to a specified container
107 this.add_element = function(elm, container)
109 if (this.gui_containers[container] && this.gui_containers[container].jquery)
110 this.gui_containers[container].append(elm);
113 // register an external handler for a certain command
114 this.register_command = function(command, callback, enable)
116 this.command_handlers[command] = callback;
119 this.enable_command(command, true);
122 // execute the given script on load
123 this.add_onload = function(f)
125 this.onloads.push(f);
128 // initialize webmail client
129 this.init = function()
132 this.task = this.env.task;
135 if (!bw.dom || !bw.xmlhttp_test()) {
136 this.goto_url('error', '_code=0x199');
140 // find all registered gui containers
141 for (n in this.gui_containers)
142 this.gui_containers[n] = $('#'+this.gui_containers[n]);
144 // find all registered gui objects
145 for (n in this.gui_objects)
146 this.gui_objects[n] = rcube_find_object(this.gui_objects[n]);
148 // clickjacking protection
149 if (this.env.x_frame_options) {
151 // bust frame if not allowed
152 if (this.env.x_frame_options == 'deny' && top.location.href != self.location.href)
153 top.location.href = self.location.href;
154 else if (top.location.hostname != self.location.hostname)
157 // possible clickjacking attack: disable all form elements
158 $('form').each(function(){ ref.lock_form(this, true); });
159 this.display_message("Blocked: possible clickjacking attack!", 'error');
164 // init registered buttons
167 // tell parent window that this frame is loaded
168 if (this.is_framed()) {
169 parent.rcmail.set_busy(false, null, parent.rcmail.env.frame_lock);
170 parent.rcmail.env.frame_lock = null;
173 // enable general commands
174 this.enable_command('logout', 'mail', 'addressbook', 'settings', 'save-pref', 'compose', 'undo', true);
176 if (this.env.permaurl)
177 this.enable_command('permaurl', true);
182 // enable mail commands
183 this.enable_command('list', 'checkmail', 'add-contact', 'search', 'reset-search', 'collapse-folder', true);
185 if (this.gui_objects.messagelist) {
187 this.message_list = new rcube_list_widget(this.gui_objects.messagelist, {
188 multiselect:true, multiexpand:true, draggable:true, keyboard:true,
189 column_movable:this.env.col_movable, dblclick_time:this.dblclick_time
191 this.message_list.row_init = function(o){ p.init_message_row(o); };
192 this.message_list.addEventListener('dblclick', function(o){ p.msglist_dbl_click(o); });
193 this.message_list.addEventListener('click', function(o){ p.msglist_click(o); });
194 this.message_list.addEventListener('keypress', function(o){ p.msglist_keypress(o); });
195 this.message_list.addEventListener('select', function(o){ p.msglist_select(o); });
196 this.message_list.addEventListener('dragstart', function(o){ p.drag_start(o); });
197 this.message_list.addEventListener('dragmove', function(e){ p.drag_move(e); });
198 this.message_list.addEventListener('dragend', function(e){ p.drag_end(e); });
199 this.message_list.addEventListener('expandcollapse', function(e){ p.msglist_expand(e); });
200 this.message_list.addEventListener('column_replace', function(e){ p.msglist_set_coltypes(e); });
202 document.onmouseup = function(e){ return p.doc_mouse_up(e); };
203 this.gui_objects.messagelist.parentNode.onmousedown = function(e){ return p.click_on_list(e); };
205 this.message_list.init();
206 this.enable_command('toggle_status', 'toggle_flag', 'menu-open', 'menu-save', true);
209 this.command('list');
212 if (this.gui_objects.qsearchbox) {
213 if (this.env.search_text != null) {
214 this.gui_objects.qsearchbox.value = this.env.search_text;
216 $(this.gui_objects.qsearchbox).focusin(function() { rcmail.message_list.blur(); });
219 if (!this.env.flag_for_deletion && this.env.trash_mailbox && this.env.mailbox != this.env.trash_mailbox)
220 this.set_alttext('delete', 'movemessagetotrash');
222 this.env.message_commands = ['show', 'reply', 'reply-all', 'reply-list', 'forward',
223 'moveto', 'copy', 'delete', 'open', 'mark', 'edit', 'viewsource', 'download',
224 'print', 'load-attachment', 'load-headers', 'forward-attachment'];
226 if (this.env.action == 'show' || this.env.action == 'preview') {
227 this.enable_command(this.env.message_commands, this.env.uid);
228 this.enable_command('reply-list', this.env.list_post);
230 if (this.env.action == 'show') {
231 this.http_request('pagenav', '_uid='+this.env.uid+'&_mbox='+urlencode(this.env.mailbox)
232 + (this.env.search_request ? '&_search='+this.env.search_request : ''),
233 this.display_message('', 'loading'));
236 if (this.env.blockedobjects) {
237 if (this.gui_objects.remoteobjectsmsg)
238 this.gui_objects.remoteobjectsmsg.style.display = 'block';
239 this.enable_command('load-images', 'always-load', true);
242 // make preview/message frame visible
243 if (this.env.action == 'preview' && this.is_framed()) {
244 this.enable_command('compose', 'add-contact', false);
245 parent.rcmail.show_contentframe(true);
248 else if (this.env.action == 'compose') {
249 this.env.compose_commands = ['send-attachment', 'remove-attachment', 'send', 'cancel', 'toggle-editor'];
251 if (this.env.drafts_mailbox)
252 this.env.compose_commands.push('savedraft')
254 this.enable_command(this.env.compose_commands, 'identities', true);
256 if (this.env.spellcheck) {
257 this.env.spellcheck.spelling_state_observer = function(s){ ref.set_spellcheck_state(s); };
258 this.env.compose_commands.push('spellcheck')
259 this.set_spellcheck_state('ready');
260 if ($("input[name='_is_html']").val() == '1')
261 this.display_spellcheck_controls(false);
264 document.onmouseup = function(e){ return p.doc_mouse_up(e); };
266 // init message compose form
267 this.init_messageform();
269 // show printing dialog
270 else if (this.env.action == 'print' && this.env.uid)
272 window.setTimeout('window.print()', 10);
276 // get unread count for each mailbox
277 if (this.gui_objects.mailboxlist) {
278 this.env.unread_counts = {};
279 this.gui_objects.folderlist = this.gui_objects.mailboxlist;
280 this.http_request('getunread', '');
283 // ask user to send MDN
284 if (this.env.mdn_request && this.env.uid) {
285 var mdnurl = '_uid='+this.env.uid+'&_mbox='+urlencode(this.env.mailbox);
286 if (confirm(this.get_label('mdnrequest')))
287 this.http_post('sendmdn', mdnurl);
289 this.http_post('mark', mdnurl+'&_flag=mdnsent');
295 if (this.gui_objects.folderlist)
296 this.env.contactfolders = $.extend($.extend({}, this.env.address_sources), this.env.contactgroups);
298 this.enable_command('add', 'import', this.env.writable_source);
299 this.enable_command('list', 'listgroup', 'listsearch', 'advanced-search', true);
301 if (this.gui_objects.contactslist) {
303 this.contact_list = new rcube_list_widget(this.gui_objects.contactslist,
304 {multiselect:true, draggable:this.gui_objects.folderlist?true:false, keyboard:true});
305 this.contact_list.row_init = function(row){ p.triggerEvent('insertrow', { cid:row.uid, row:row }); };
306 this.contact_list.addEventListener('keypress', function(o){ p.contactlist_keypress(o); });
307 this.contact_list.addEventListener('select', function(o){ p.contactlist_select(o); });
308 this.contact_list.addEventListener('dragstart', function(o){ p.drag_start(o); });
309 this.contact_list.addEventListener('dragmove', function(e){ p.drag_move(e); });
310 this.contact_list.addEventListener('dragend', function(e){ p.drag_end(e); });
311 this.contact_list.init();
314 this.contact_list.highlight_row(this.env.cid);
316 this.gui_objects.contactslist.parentNode.onmousedown = function(e){ return p.click_on_list(e); };
317 document.onmouseup = function(e){ return p.doc_mouse_up(e); };
318 if (this.gui_objects.qsearchbox) {
319 $(this.gui_objects.qsearchbox).focusin(function() { rcmail.contact_list.blur(); });
322 this.update_group_commands();
323 this.command('list');
326 this.set_page_buttons();
329 this.enable_command('show', 'edit', true);
330 // register handlers for group assignment via checkboxes
331 if (this.gui_objects.editform) {
332 $('input.groupmember').change(function() {
333 ref.group_member_change(this.checked ? 'add' : 'del', ref.env.cid, ref.env.source, this.value);
338 if (this.gui_objects.editform) {
339 this.enable_command('save', true);
340 if (this.env.action == 'add' || this.env.action == 'edit')
341 this.init_contact_form();
344 if (this.gui_objects.qsearchbox) {
345 this.enable_command('search', 'reset-search', 'moveto', true);
351 this.enable_command('preferences', 'identities', 'save', 'folders', true);
353 if (this.env.action == 'identities') {
354 this.enable_command('add', this.env.identities_level < 2);
356 else if (this.env.action == 'edit-identity' || this.env.action == 'add-identity') {
357 this.enable_command('add', this.env.identities_level < 2);
358 this.enable_command('save', 'delete', 'edit', 'toggle-editor', true);
360 else if (this.env.action == 'folders') {
361 this.enable_command('subscribe', 'unsubscribe', 'create-folder', 'rename-folder', true);
363 else if (this.env.action == 'edit-folder' && this.gui_objects.editform) {
364 this.enable_command('save', 'folder-size', true);
365 parent.rcmail.env.messagecount = this.env.messagecount;
366 parent.rcmail.enable_command('purge', this.env.messagecount);
367 $("input[type='text']").first().select();
370 if (this.gui_objects.identitieslist) {
371 this.identity_list = new rcube_list_widget(this.gui_objects.identitieslist, {multiselect:false, draggable:false, keyboard:false});
372 this.identity_list.addEventListener('select', function(o){ p.identity_select(o); });
373 this.identity_list.init();
374 this.identity_list.focus();
377 this.identity_list.highlight_row(this.env.iid);
379 else if (this.gui_objects.sectionslist) {
380 this.sections_list = new rcube_list_widget(this.gui_objects.sectionslist, {multiselect:false, draggable:false, keyboard:false});
381 this.sections_list.addEventListener('select', function(o){ p.section_select(o); });
382 this.sections_list.init();
383 this.sections_list.focus();
385 else if (this.gui_objects.subscriptionlist)
386 this.init_subscription_list();
391 var input_user = $('#rcmloginuser');
392 input_user.bind('keyup', function(e){ return rcmail.login_user_keyup(e); });
394 if (input_user.val() == '')
397 $('#rcmloginpwd').focus();
399 // detect client timezone
401 tz = dt.getTimezoneOffset() / -60,
402 stdtz = dt.getStdTimezoneOffset() / -60;
404 $('#rcmlogintz').val(stdtz);
405 $('#rcmlogindst').val(tz > stdtz ? 1 : 0);
407 // display 'loading' message on form submit, lock submit button
408 $('form').submit(function () {
409 $('input[type=submit]', this).prop('disabled', true);
410 rcmail.display_message('', 'loading');
413 this.enable_command('login', true);
420 // prevent from form submit with Enter key in file input fields
422 $('input[type=file]').keydown(function(e) { if (e.keyCode == '13') e.preventDefault(); });
424 // flag object as complete
428 if (this.pending_message)
429 this.display_message(this.pending_message[0], this.pending_message[1], this.pending_message[2]);
431 // map implicit containers
432 if (this.gui_objects.folderlist)
433 this.gui_containers.foldertray = $(this.gui_objects.folderlist);
435 // trigger init event hook
436 this.triggerEvent('init', { task:this.task, action:this.env.action });
438 // execute all foreign onload scripts
440 for (var i in this.onloads) {
441 if (typeof this.onloads[i] === 'string')
442 eval(this.onloads[i]);
443 else if (typeof this.onloads[i] === 'function')
447 // start keep-alive interval
448 this.start_keepalive();
451 this.log = function(msg)
453 if (window.console && console.log)
457 /*********************************************************/
458 /********* client command interface *********/
459 /*********************************************************/
461 // execute a specific command on the web client
462 this.command = function(command, props, obj)
464 var ret, uid, cid, url, flag;
472 // command not supported or allowed
473 if (!this.commands[command]) {
474 // pass command to parent window
475 if (this.is_framed())
476 parent.rcmail.command(command, props);
481 // check input before leaving compose step
482 if (this.task == 'mail' && this.env.action == 'compose' && $.inArray(command, this.env.compose_commands)<0) {
483 if (this.cmp_hash != this.compose_field_hash() && !confirm(this.get_label('notsentwarning')))
487 // process external commands
488 if (typeof this.command_handlers[command] === 'function') {
489 ret = this.command_handlers[command](props, obj);
490 return ret !== undefined ? ret : (obj ? false : true);
492 else if (typeof this.command_handlers[command] === 'string') {
493 ret = window[this.command_handlers[command]](props, obj);
494 return ret !== undefined ? ret : (obj ? false : true);
497 // trigger plugin hooks
498 this.triggerEvent('actionbefore', {props:props, action:command});
499 ret = this.triggerEvent('before'+command, props);
500 if (ret !== undefined) {
501 // abort if one of the handlers returned false
510 // process internal command
514 if (this.gui_objects.loginform)
515 this.gui_objects.loginform.submit();
518 // commands to switch task
523 this.switch_task(command);
527 if (obj && obj.href && obj.target)
529 else if (this.env.permaurl)
530 parent.location.href = this.env.permaurl;
535 this.triggerEvent(command, {props:props});
539 if (uid = this.get_single_uid()) {
540 obj.href = '?_task='+this.env.task+'&_action=show&_mbox='+urlencode(this.env.mailbox)+'&_uid='+uid;
546 this.reset_qsearch();
547 if (this.task == 'mail') {
548 this.list_mailbox(props);
550 if (this.env.trash_mailbox && !this.env.flag_for_deletion)
551 this.set_alttext('delete', this.env.mailbox != this.env.trash_mailbox ? 'movemessagetotrash' : 'deletemessage');
553 else if (this.task == 'addressbook') {
554 this.list_contacts(props);
559 this.load_headers(obj);
563 var sort_order, sort_col = props;
565 if (this.env.sort_col==sort_col)
566 sort_order = this.env.sort_order=='ASC' ? 'DESC' : 'ASC';
570 // set table header and update env
571 this.set_list_sorting(sort_col, sort_order);
573 // reload message list
574 this.list_mailbox('', '', sort_col+'_'+sort_order);
578 this.list_page('next');
582 this.list_page('last');
586 this.list_page('prev');
590 this.list_page('first');
594 if (this.env.messagecount)
595 this.expunge_mailbox(this.env.mailbox);
599 case 'empty-mailbox':
600 if (this.env.messagecount)
601 this.purge_mailbox(this.env.mailbox);
604 // common commands used in multiple tasks
606 if (this.task == 'mail') {
607 uid = this.get_single_uid();
608 if (uid && (!this.env.uid || uid != this.env.uid)) {
609 if (this.env.mailbox == this.env.drafts_mailbox)
610 this.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
612 this.show_message(uid);
615 else if (this.task == 'addressbook') {
616 cid = props ? props : this.get_single_cid();
617 if (cid && !(this.env.action == 'show' && cid == this.env.cid))
618 this.load_contact(cid, 'show');
623 if (this.task == 'addressbook')
624 this.load_contact(0, 'add');
625 else if (this.task == 'settings') {
626 this.identity_list.clear_selection();
627 this.load_identity(0, 'add-identity');
632 if (this.task=='addressbook' && (cid = this.get_single_cid()))
633 this.load_contact(cid, 'edit');
634 else if (this.task=='settings' && props)
635 this.load_identity(props, 'edit-identity');
636 else if (this.task=='mail' && (cid = this.get_single_uid())) {
637 url = (this.env.mailbox == this.env.drafts_mailbox) ? '_draft_uid=' : '_uid=';
638 this.goto_url('compose', url+cid+'&_mbox='+urlencode(this.env.mailbox), true);
643 var input, form = this.gui_objects.editform;
646 if (this.env.action == 'search') {
649 else if ((input = $("input[name='_pagesize']", form)) && input.length && isNaN(parseInt(input.val()))) {
650 alert(this.get_label('nopagesizewarning'));
654 // contacts/identities
657 if (props == 'reload') {
658 form.action += '?_reload=1';
660 else if (this.task == 'settings' && (this.env.identities_level % 2) == 0 &&
661 (input = $("input[name='_email']", form)) && input.length && !rcube_check_email(input.val())
663 alert(this.get_label('noemailwarning'));
668 // clear empty input fields
669 $('input.placeholder').each(function(){ if (this.value == this._placeholder) this.value = ''; });
672 // add selected source (on the list)
673 if (parent.rcmail && parent.rcmail.env.source)
674 form.action = this.add_url(form.action, '_orig_source', parent.rcmail.env.source);
682 if (this.task == 'mail')
683 this.delete_messages();
685 else if (this.task == 'addressbook')
686 this.delete_contacts();
687 // user settings task
688 else if (this.task == 'settings')
689 this.delete_identity();
692 // mail task commands
695 if (this.task == 'mail')
696 this.move_messages(props);
697 else if (this.task == 'addressbook' && this.drag_active)
698 this.copy_contact(null, props);
702 if (this.task == 'mail')
703 this.copy_messages(props);
708 this.mark_message(props);
711 case 'toggle_status':
712 if (props && !props._row)
717 if (props._row.uid) {
718 uid = props._row.uid;
720 // toggle read/unread
721 if (this.message_list.rows[uid].deleted) {
724 else if (!this.message_list.rows[uid].unread)
728 this.mark_message(flag, uid);
732 if (props && !props._row)
737 if (props._row.uid) {
738 uid = props._row.uid;
739 // toggle flagged/unflagged
740 if (this.message_list.rows[uid].flagged)
743 this.mark_message(flag, uid);
747 if (this.env.uid && this.env.sender) {
748 this.add_contact(urlencode(this.env.sender));
749 window.setTimeout(function(){ ref.command('load-images'); }, 300);
755 this.show_message(this.env.uid, true, this.env.action=='preview');
758 case 'load-attachment':
759 var qstring = '_mbox='+urlencode(this.env.mailbox)+'&_uid='+this.env.uid+'&_part='+props.part;
761 // open attachment in frame if it's of a supported mimetype
762 if (this.env.uid && props.mimetype && this.env.mimetypes && $.inArray(props.mimetype, this.env.mimetypes)>=0) {
763 if (props.mimetype == 'text/html')
764 qstring += '&_safe=1';
765 this.attachment_win = window.open(this.env.comm_path+'&_action=get&'+qstring+'&_frame=1', 'rcubemailattachment');
766 if (this.attachment_win) {
767 window.setTimeout(function(){ ref.attachment_win.focus(); }, 10);
772 this.goto_url('get', qstring+'&_download=1', false);
776 this.select_all_mode = props ? false : true;
777 this.dummy_select = true; // prevent msg opening if there's only one msg on the list
778 if (props == 'invert')
779 this.message_list.invert_selection();
781 this.message_list.select_all(props == 'page' ? '' : props);
782 this.dummy_select = null;
786 this.select_all_mode = false;
787 this.message_list.clear_selection();
791 this.env.autoexpand_threads = 1;
792 this.message_list.expand_all();
795 case 'expand-unread':
796 this.env.autoexpand_threads = 2;
797 this.message_list.collapse_all();
798 this.expand_unread();
802 this.env.autoexpand_threads = 0;
803 this.message_list.collapse_all();
807 if (this.env.next_uid)
808 this.show_message(this.env.next_uid, false, this.env.action=='preview');
812 if (this.env.last_uid)
813 this.show_message(this.env.last_uid);
816 case 'previousmessage':
817 if (this.env.prev_uid)
818 this.show_message(this.env.prev_uid, false, this.env.action=='preview');
822 if (this.env.first_uid)
823 this.show_message(this.env.first_uid);
827 this.check_for_recent(true);
831 url = this.url('mail/compose');
833 if (this.task == 'mail') {
834 url += '&_mbox='+urlencode(this.env.mailbox);
836 url += '&_to='+urlencode(props);
838 // modify url if we're in addressbook
839 else if (this.task == 'addressbook') {
840 // switch to mail compose step directly
841 if (props && props.indexOf('@') > 0) {
842 url = this.get_task_url('mail', url);
843 this.redirect(url + '&_to='+urlencode(props));
847 // use contact_id passed as command parameter
848 var n, len, a_cids = [];
851 // get selected contacts
852 else if (this.contact_list) {
853 var selection = this.contact_list.get_selection();
854 for (n=0, len=selection.length; n<len; n++)
855 a_cids.push(selection[n]);
859 this.http_post('mailto', { _cid: a_cids.join(','), _source: this.env.source}, true);
860 else if (this.env.group)
861 this.http_post('mailto', { _gid: this.env.group, _source: this.env.source}, true);
866 url += '&_to='+urlencode(props);
872 if (window.tinyMCE && tinyMCE.get(this.env.composebody)) {
873 tinyMCE.execCommand('mceSpellCheck', true);
875 else if (this.env.spellcheck && this.env.spellcheck.spellCheck && this.spellcheck_ready) {
876 this.env.spellcheck.spellCheck();
877 this.set_spellcheck_state('checking');
882 // Reset the auto-save timer
883 self.clearTimeout(this.save_timer);
885 if (!this.gui_objects.messageform)
888 // if saving Drafts is disabled in main.inc.php
889 // or if compose form did not change
890 if (!this.env.drafts_mailbox || this.cmp_hash == this.compose_field_hash())
893 var form = this.gui_objects.messageform,
894 msgid = this.set_busy(true, 'savingmessage');
896 form.target = "savetarget";
897 form._draft.value = '1';
898 form.action = this.add_url(form.action, '_unlock', msgid);
903 if (!this.gui_objects.messageform)
906 if (!props.nocheck && !this.check_compose_input(command))
909 // Reset the auto-save timer
910 self.clearTimeout(this.save_timer);
912 // all checks passed, send message
913 var lang = this.spellcheck_lang(),
914 form = this.gui_objects.messageform,
915 msgid = this.set_busy(true, 'sendingmessage');
917 form.target = 'savetarget';
918 form._draft.value = '';
919 form.action = this.add_url(form.action, '_unlock', msgid);
920 form.action = this.add_url(form.action, '_lang', lang);
923 // clear timeout (sending could take longer)
924 clearTimeout(this.request_timer);
927 case 'send-attachment':
928 // Reset the auto-save timer
929 self.clearTimeout(this.save_timer);
931 this.upload_file(props)
935 this.change_identity($("[name='_from']")[0], true);
941 if (uid = this.get_single_uid()) {
942 url = '_reply_uid='+uid+'&_mbox='+urlencode(this.env.mailbox);
943 if (command == 'reply-all')
944 // do reply-list, when list is detected and popup menu wasn't used
945 url += '&_all=' + (!props && this.commands['reply-list'] ? 'list' : 'all');
946 else if (command == 'reply-list')
949 this.goto_url('compose', url, true);
953 case 'forward-attachment':
955 if (uid = this.get_single_uid()) {
956 url = '_forward_uid='+uid+'&_mbox='+urlencode(this.env.mailbox);
957 if (command == 'forward-attachment' || (!props && this.env.forward_attachment))
958 url += '&_attachment=1';
959 this.goto_url('compose', url, true);
964 if (uid = this.get_single_uid()) {
965 ref.printwin = window.open(this.env.comm_path+'&_action=print&_uid='+uid+'&_mbox='+urlencode(this.env.mailbox)+(this.env.safemode ? '&_safe=1' : ''));
967 window.setTimeout(function(){ ref.printwin.focus(); }, 20);
968 if (this.env.action != 'show')
969 this.mark_message('read', uid);
975 if (uid = this.get_single_uid()) {
976 ref.sourcewin = window.open(this.env.comm_path+'&_action=viewsource&_uid='+uid+'&_mbox='+urlencode(this.env.mailbox));
978 window.setTimeout(function(){ ref.sourcewin.focus(); }, 20);
983 if (uid = this.get_single_uid())
984 this.goto_url('viewsource', '&_uid='+uid+'&_mbox='+urlencode(this.env.mailbox)+'&_save=1');
989 if (!props && this.gui_objects.qsearchbox)
990 props = this.gui_objects.qsearchbox.value;
998 var n, s = this.env.search_request || this.env.qsearch;
1000 this.reset_qsearch();
1001 this.select_all_mode = false;
1003 if (s && this.env.mailbox)
1004 this.list_mailbox(this.env.mailbox, 1);
1005 else if (s && this.task == 'addressbook') {
1006 if (this.env.source == '') {
1007 for (n in this.env.address_sources) break;
1008 this.env.source = n;
1009 this.env.group = '';
1011 this.list_contacts(this.env.source, this.env.group, 1);
1016 this.reset_qsearch();
1017 this.list_contacts(props.source, props.id);
1021 if (this.env.action == 'import' && this.gui_objects.importform) {
1022 var file = document.getElementById('rcmimportfile');
1023 if (file && !file.value) {
1024 alert(this.get_label('selectimportfile'));
1027 this.gui_objects.importform.submit();
1028 this.set_busy(true, 'importwait');
1029 this.lock_form(this.gui_objects.importform, true);
1032 this.goto_url('import', (this.env.source ? '_target='+urlencode(this.env.source)+'&' : ''));
1036 if (this.contact_list.rowcount > 0) {
1037 this.goto_url('export', { _source:this.env.source, _gid:this.env.group, _search:this.env.search_request });
1041 case 'upload-photo':
1042 this.upload_contact_photo(props);
1045 case 'delete-photo':
1046 this.replace_contact_photo('-del-');
1049 // user settings commands
1053 this.goto_url('settings/' + command);
1057 this.http_request('undo', '', this.display_message('', 'loading'));
1060 // unified command call (command name == function name)
1062 var func = command.replace(/-/g, '_');
1063 if (this[func] && typeof this[func] === 'function') {
1064 ret = this[func](props);
1069 if (this.triggerEvent('after'+command, props) === false)
1071 this.triggerEvent('actionafter', {props:props, action:command});
1073 return ret === false ? false : obj ? false : true;
1076 // set command(s) enabled or disabled
1077 this.enable_command = function()
1079 var i, n, args = Array.prototype.slice.call(arguments),
1080 enable = args.pop(), cmd;
1082 for (n=0; n<args.length; n++) {
1084 // argument of type array
1085 if (typeof cmd === 'string') {
1086 this.commands[cmd] = enable;
1087 this.set_button(cmd, (enable ? 'act' : 'pas'));
1089 // push array elements into commands array
1097 // lock/unlock interface
1098 this.set_busy = function(a, message, id)
1101 var msg = this.get_label(message);
1105 id = this.display_message(msg, 'loading');
1107 else if (!a && id) {
1108 this.hide_message(id);
1112 //document.body.style.cursor = a ? 'wait' : 'default';
1114 if (this.gui_objects.editform)
1115 this.lock_form(this.gui_objects.editform, a);
1117 // clear pending timer
1118 if (this.request_timer)
1119 clearTimeout(this.request_timer);
1121 // set timer for requests
1122 if (a && this.env.request_timeout)
1123 this.request_timer = window.setTimeout(function(){ ref.request_timed_out(); }, this.env.request_timeout * 1000);
1128 // return a localized string
1129 this.get_label = function(name, domain)
1131 if (domain && this.labels[domain+'.'+name])
1132 return this.labels[domain+'.'+name];
1133 else if (this.labels[name])
1134 return this.labels[name];
1139 // alias for convenience reasons
1140 this.gettext = this.get_label;
1142 // switch to another application task
1143 this.switch_task = function(task)
1145 if (this.task===task && task!='mail')
1148 var url = this.get_task_url(task);
1150 url += '&_mbox=INBOX';
1155 this.get_task_url = function(task, url)
1158 url = this.env.comm_path;
1160 return url.replace(/_task=[a-z]+/, '_task='+task);
1163 // called when a request timed out
1164 this.request_timed_out = function()
1166 this.set_busy(false);
1167 this.display_message('Request timed out!', 'error');
1170 this.reload = function(delay)
1172 if (this.is_framed())
1173 parent.rcmail.reload(delay);
1175 window.setTimeout(function(){ rcmail.reload(); }, delay);
1176 else if (window.location)
1177 location.href = this.env.comm_path + (this.env.action ? '&_action='+this.env.action : '');
1180 // Add variable to GET string, replace old value if exists
1181 this.add_url = function(url, name, value)
1183 value = urlencode(value);
1185 if (/(\?.*)$/.test(url)) {
1186 var urldata = RegExp.$1,
1187 datax = RegExp('((\\?|&)'+RegExp.escape(name)+'=[^&]*)');
1189 if (datax.test(urldata)) {
1190 urldata = urldata.replace(datax, RegExp.$2 + name + '=' + value);
1193 urldata += '&' + name + '=' + value
1195 return url.replace(/(\?.*)$/, urldata);
1198 return url + '?' + name + '=' + value;
1201 this.is_framed = function()
1203 return (this.env.framed && parent.rcmail && parent.rcmail != this && parent.rcmail.command);
1206 this.save_pref = function(prop)
1208 var request = {'_name': prop.name, '_value': prop.value};
1211 request['_session'] = prop.session;
1213 this.env[prop.env] = prop.value;
1215 this.http_post('save-pref', request);
1218 this.html_identifier = function(str, encode)
1222 return Base64.encode(str).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
1224 return str.replace(this.identifier_expr, '_');
1227 this.html_identifier_decode = function(str)
1229 str = String(str).replace(/-/g, '+').replace(/_/g, '/');
1231 while (str.length % 4) str += '=';
1233 return Base64.decode(str);
1237 /*********************************************************/
1238 /********* event handling methods *********/
1239 /*********************************************************/
1241 this.drag_menu = function(e, target)
1243 var modkey = rcube_event.get_modifier(e),
1244 menu = this.gui_objects.message_dragmenu;
1246 if (menu && modkey == SHIFT_KEY && this.commands['copy']) {
1247 var pos = rcube_event.get_mouse_pos(e);
1248 this.env.drag_target = target;
1249 $(menu).css({top: (pos.y-10)+'px', left: (pos.x-10)+'px'}).show();
1256 this.drag_menu_action = function(action)
1258 var menu = this.gui_objects.message_dragmenu;
1262 this.command(action, this.env.drag_target);
1263 this.env.drag_target = null;
1266 this.drag_start = function(list)
1268 var model = this.task == 'mail' ? this.env.mailboxes : this.env.contactfolders;
1270 this.drag_active = true;
1272 if (this.preview_timer)
1273 clearTimeout(this.preview_timer);
1274 if (this.preview_read_timer)
1275 clearTimeout(this.preview_read_timer);
1277 // save folderlist and folders location/sizes for droptarget calculation in drag_move()
1278 if (this.gui_objects.folderlist && model) {
1279 this.initialBodyScrollTop = bw.ie ? 0 : window.pageYOffset;
1280 this.initialListScrollTop = this.gui_objects.folderlist.parentNode.scrollTop;
1283 list = $(this.gui_objects.folderlist);
1284 pos = list.offset();
1286 this.env.folderlist_coords = { x1:pos.left, y1:pos.top, x2:pos.left + list.width(), y2:pos.top + list.height() };
1288 this.env.folder_coords = [];
1290 if (li = this.get_folder_li(k)) {
1291 // only visible folders
1292 if (height = li.firstChild.offsetHeight) {
1293 pos = $(li.firstChild).offset();
1294 this.env.folder_coords[k] = { x1:pos.left, y1:pos.top,
1295 x2:pos.left + li.firstChild.offsetWidth, y2:pos.top + height, on:0 };
1302 this.drag_end = function(e)
1304 this.drag_active = false;
1305 this.env.last_folder_target = null;
1307 if (this.folder_auto_timer) {
1308 window.clearTimeout(this.folder_auto_timer);
1309 this.folder_auto_timer = null;
1310 this.folder_auto_expand = null;
1314 if (this.gui_objects.folderlist && this.env.folder_coords) {
1315 for (var k in this.env.folder_coords) {
1316 if (this.env.folder_coords[k].on)
1317 $(this.get_folder_li(k)).removeClass('droptarget');
1322 this.drag_move = function(e)
1324 if (this.gui_objects.folderlist && this.env.folder_coords) {
1325 var k, li, div, check, oldclass,
1326 layerclass = 'draglayernormal',
1327 mouse = rcube_event.get_mouse_pos(e),
1328 pos = this.env.folderlist_coords,
1329 // offsets to compensate for scrolling while dragging a message
1330 boffset = bw.ie ? -document.documentElement.scrollTop : this.initialBodyScrollTop,
1331 moffset = this.initialListScrollTop-this.gui_objects.folderlist.parentNode.scrollTop;
1333 if (this.contact_list && this.contact_list.draglayer)
1334 oldclass = this.contact_list.draglayer.attr('class');
1336 mouse.y += -moffset-boffset;
1338 // if mouse pointer is outside of folderlist
1339 if (mouse.x < pos.x1 || mouse.x >= pos.x2 || mouse.y < pos.y1 || mouse.y >= pos.y2) {
1340 if (this.env.last_folder_target) {
1341 $(this.get_folder_li(this.env.last_folder_target)).removeClass('droptarget');
1342 this.env.folder_coords[this.env.last_folder_target].on = 0;
1343 this.env.last_folder_target = null;
1345 if (layerclass != oldclass && this.contact_list && this.contact_list.draglayer)
1346 this.contact_list.draglayer.attr('class', layerclass);
1351 for (k in this.env.folder_coords) {
1352 pos = this.env.folder_coords[k];
1353 if (mouse.x >= pos.x1 && mouse.x < pos.x2 && mouse.y >= pos.y1 && mouse.y < pos.y2){
1354 if ((check = this.check_droptarget(k))) {
1355 li = this.get_folder_li(k);
1356 div = $(li.getElementsByTagName('div')[0]);
1358 // if the folder is collapsed, expand it after 1sec and restart the drag & drop process.
1359 if (div.hasClass('collapsed')) {
1360 if (this.folder_auto_timer)
1361 window.clearTimeout(this.folder_auto_timer);
1363 this.folder_auto_expand = this.env.mailboxes[k].id;
1364 this.folder_auto_timer = window.setTimeout(function() {
1365 rcmail.command('collapse-folder', rcmail.folder_auto_expand);
1366 rcmail.drag_start(null);
1368 } else if (this.folder_auto_timer) {
1369 window.clearTimeout(this.folder_auto_timer);
1370 this.folder_auto_timer = null;
1371 this.folder_auto_expand = null;
1374 $(li).addClass('droptarget');
1375 this.env.folder_coords[k].on = 1;
1376 this.env.last_folder_target = k;
1377 layerclass = 'draglayer' + (check > 1 ? 'copy' : 'normal');
1378 } else { // Clear target, otherwise drag end will trigger move into last valid droptarget
1379 this.env.last_folder_target = null;
1383 $(this.get_folder_li(k)).removeClass('droptarget');
1384 this.env.folder_coords[k].on = 0;
1388 if (layerclass != oldclass && this.contact_list && this.contact_list.draglayer)
1389 this.contact_list.draglayer.attr('class', layerclass);
1393 this.collapse_folder = function(name)
1395 var li = this.get_folder_li(name, '', true),
1396 div = $('div:first', li),
1397 ul = $('ul:first', li);
1399 if (div.hasClass('collapsed')) {
1401 div.removeClass('collapsed').addClass('expanded');
1402 var reg = new RegExp('&'+urlencode(name)+'&');
1403 this.env.collapsed_folders = this.env.collapsed_folders.replace(reg, '');
1405 else if (div.hasClass('expanded')) {
1407 div.removeClass('expanded').addClass('collapsed');
1408 this.env.collapsed_folders = this.env.collapsed_folders+'&'+urlencode(name)+'&';
1410 // select parent folder if one of its childs is currently selected
1411 if (this.env.mailbox.indexOf(name + this.env.delimiter) == 0)
1412 this.command('list', name);
1417 // Work around a bug in IE6 and IE7, see #1485309
1418 if (bw.ie6 || bw.ie7) {
1419 var siblings = li.nextSibling ? li.nextSibling.getElementsByTagName('ul') : null;
1420 if (siblings && siblings.length && (li = siblings[0]) && li.style && li.style.display != 'none') {
1421 li.style.display = 'none';
1422 li.style.display = '';
1426 this.command('save-pref', { name: 'collapsed_folders', value: this.env.collapsed_folders });
1427 this.set_unread_count_display(name, false);
1430 this.doc_mouse_up = function(e)
1432 var model, list, li, id;
1434 // ignore event if jquery UI dialog is open
1435 if ($(rcube_event.get_target(e)).closest('.ui-dialog, .ui-widget-overlay').length)
1438 if (list = this.message_list) {
1439 if (!rcube_mouse_is_over(e, list.list.parentNode))
1443 model = this.env.mailboxes;
1445 else if (list = this.contact_list) {
1446 if (!rcube_mouse_is_over(e, list.list.parentNode))
1450 model = this.env.contactfolders;
1452 else if (this.ksearch_value) {
1453 this.ksearch_blur();
1456 // handle mouse release when dragging
1457 if (this.drag_active && model && this.env.last_folder_target) {
1458 var target = model[this.env.last_folder_target];
1460 $(this.get_folder_li(this.env.last_folder_target)).removeClass('droptarget');
1461 this.env.last_folder_target = null;
1462 list.draglayer.hide();
1464 if (!this.drag_menu(e, target))
1465 this.command('moveto', target);
1468 // reset 'pressed' buttons
1469 if (this.buttons_sel) {
1470 for (id in this.buttons_sel)
1471 if (typeof id !== 'function')
1472 this.button_out(this.buttons_sel[id], id);
1473 this.buttons_sel = {};
1477 this.click_on_list = function(e)
1479 if (this.gui_objects.qsearchbox)
1480 this.gui_objects.qsearchbox.blur();
1482 if (this.message_list)
1483 this.message_list.focus();
1484 else if (this.contact_list)
1485 this.contact_list.focus();
1490 this.msglist_select = function(list)
1492 if (this.preview_timer)
1493 clearTimeout(this.preview_timer);
1494 if (this.preview_read_timer)
1495 clearTimeout(this.preview_read_timer);
1497 var selected = list.get_single_selection() != null;
1499 this.enable_command(this.env.message_commands, selected);
1501 // Hide certain command buttons when Drafts folder is selected
1502 if (this.env.mailbox == this.env.drafts_mailbox)
1503 this.enable_command('reply', 'reply-all', 'reply-list', 'forward', 'forward-attachment', false);
1504 // Disable reply-list when List-Post header is not set
1506 var msg = this.env.messages[list.get_single_selection()];
1508 this.enable_command('reply-list', false);
1511 // Multi-message commands
1512 this.enable_command('delete', 'moveto', 'copy', 'mark', (list.selection.length > 0 ? true : false));
1514 // reset all-pages-selection
1515 if (selected || (list.selection.length && list.selection.length != list.rowcount))
1516 this.select_all_mode = false;
1518 // start timer for message preview (wait for double click)
1519 if (selected && this.env.contentframe && !list.multi_selecting && !this.dummy_select)
1520 this.preview_timer = window.setTimeout(function(){ ref.msglist_get_preview(); }, 200);
1521 else if (this.env.contentframe)
1522 this.show_contentframe(false);
1525 // This allow as to re-select selected message and display it in preview frame
1526 this.msglist_click = function(list)
1528 if (list.multi_selecting || !this.env.contentframe)
1531 if (list.get_single_selection() && window.frames && window.frames[this.env.contentframe]) {
1532 if (window.frames[this.env.contentframe].location.href.indexOf(this.env.blankpage)>=0) {
1533 if (this.preview_timer)
1534 clearTimeout(this.preview_timer);
1535 if (this.preview_read_timer)
1536 clearTimeout(this.preview_read_timer);
1537 this.preview_timer = window.setTimeout(function(){ ref.msglist_get_preview(); }, 200);
1542 this.msglist_dbl_click = function(list)
1544 if (this.preview_timer)
1545 clearTimeout(this.preview_timer);
1547 if (this.preview_read_timer)
1548 clearTimeout(this.preview_read_timer);
1550 var uid = list.get_single_selection();
1551 if (uid && this.env.mailbox == this.env.drafts_mailbox)
1552 this.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
1554 this.show_message(uid, false, false);
1557 this.msglist_keypress = function(list)
1559 if (list.modkey == CONTROL_KEY)
1562 if (list.key_pressed == list.ENTER_KEY)
1563 this.command('show');
1564 else if (list.key_pressed == list.DELETE_KEY || list.key_pressed == list.BACKSPACE_KEY)
1565 this.command('delete');
1566 else if (list.key_pressed == 33)
1567 this.command('previouspage');
1568 else if (list.key_pressed == 34)
1569 this.command('nextpage');
1572 this.msglist_get_preview = function()
1574 var uid = this.get_single_uid();
1575 if (uid && this.env.contentframe && !this.drag_active)
1576 this.show_message(uid, false, true);
1577 else if (this.env.contentframe)
1578 this.show_contentframe(false);
1581 this.msglist_expand = function(row)
1583 if (this.env.messages[row.uid])
1584 this.env.messages[row.uid].expanded = row.expanded;
1587 this.msglist_set_coltypes = function(list)
1589 var i, found, name, cols = list.list.tHead.rows[0].cells;
1591 this.env.coltypes = [];
1593 for (i=0; i<cols.length; i++)
1594 if (cols[i].id && cols[i].id.match(/^rcm/)) {
1595 name = cols[i].id.replace(/^rcm/, '');
1596 this.env.coltypes.push(name == 'to' ? 'from' : name);
1599 if ((found = $.inArray('flag', this.env.coltypes)) >= 0)
1600 this.env.flagged_col = found;
1602 if ((found = $.inArray('subject', this.env.coltypes)) >= 0)
1603 this.env.subject_col = found;
1605 this.command('save-pref', { name: 'list_cols', value: this.env.coltypes, session: 'list_attrib/columns' });
1608 this.check_droptarget = function(id)
1610 var allow = false, copy = false;
1612 if (this.task == 'mail')
1613 allow = (this.env.mailboxes[id] && this.env.mailboxes[id].id != this.env.mailbox && !this.env.mailboxes[id].virtual);
1614 else if (this.task == 'settings')
1615 allow = (id != this.env.mailbox);
1616 else if (this.task == 'addressbook') {
1617 if (id != this.env.source && this.env.contactfolders[id]) {
1618 if (this.env.contactfolders[id].type == 'group') {
1619 var target_abook = this.env.contactfolders[id].source;
1620 allow = this.env.contactfolders[id].id != this.env.group && !this.env.contactfolders[target_abook].readonly;
1621 copy = target_abook != this.env.source;
1624 allow = !this.env.contactfolders[id].readonly;
1630 return allow ? (copy ? 2 : 1) : 0;
1634 /*********************************************************/
1635 /********* (message) list functionality *********/
1636 /*********************************************************/
1638 this.init_message_row = function(row)
1640 var expando, self = this, uid = row.uid,
1641 status_icon = (this.env.status_col != null ? 'status' : 'msg') + 'icn' + row.uid;
1643 if (uid && this.env.messages[uid])
1644 $.extend(row, this.env.messages[uid]);
1646 // set eventhandler to status icon
1647 if (row.icon = document.getElementById(status_icon)) {
1648 row.icon._row = row.obj;
1649 row.icon.onmousedown = function(e) { self.command('toggle_status', this); rcube_event.cancel(e); };
1652 // save message icon position too
1653 if (this.env.status_col != null)
1654 row.msgicon = document.getElementById('msgicn'+row.uid);
1656 row.msgicon = row.icon;
1658 // set eventhandler to flag icon, if icon found
1659 if (this.env.flagged_col != null && (row.flagicon = document.getElementById('flagicn'+row.uid))) {
1660 row.flagicon._row = row.obj;
1661 row.flagicon.onmousedown = function(e) { self.command('toggle_flag', this); rcube_event.cancel(e); };
1664 if (!row.depth && row.has_children && (expando = document.getElementById('rcmexpando'+row.uid))) {
1665 row.expando = expando;
1666 expando.onmousedown = function(e) { return self.expand_message_row(e, uid); };
1669 this.triggerEvent('insertrow', { uid:uid, row:row });
1672 // create a table row in the message list
1673 this.add_message_row = function(uid, cols, flags, attop)
1675 if (!this.gui_objects.messagelist || !this.message_list)
1678 // Prevent from adding messages from different folder (#1487752)
1679 if (flags.mbox != this.env.mailbox && !flags.skip_mbox_check)
1682 if (!this.env.messages[uid])
1683 this.env.messages[uid] = {};
1685 // merge flags over local message object
1686 $.extend(this.env.messages[uid], {
1687 deleted: flags.deleted?1:0,
1688 replied: flags.answered?1:0,
1689 unread: !flags.seen?1:0,
1690 forwarded: flags.forwarded?1:0,
1691 flagged: flags.flagged?1:0,
1692 has_children: flags.has_children?1:0,
1693 depth: flags.depth?flags.depth:0,
1694 unread_children: flags.unread_children?flags.unread_children:0,
1695 parent_uid: flags.parent_uid?flags.parent_uid:0,
1696 selected: this.select_all_mode || this.message_list.in_selection(uid),
1699 // flags from plugins
1700 flags: flags.extra_flags
1703 var c, n, col, html, tree = '', expando = '',
1704 list = this.message_list,
1706 message = this.env.messages[uid],
1707 css_class = 'message'
1708 + (!flags.seen ? ' unread' : '')
1709 + (flags.deleted ? ' deleted' : '')
1710 + (flags.flagged ? ' flagged' : '')
1711 + (flags.unread_children && flags.seen && !this.env.autoexpand_threads ? ' unroot' : '')
1712 + (message.selected ? ' selected' : ''),
1713 // for performance use DOM instead of jQuery here
1714 row = document.createElement('tr');
1716 row.id = 'rcmrow'+uid;
1717 row.className = css_class;
1719 // message status icons
1720 css_class = 'msgicon';
1721 if (this.env.status_col === null) {
1722 css_class += ' status';
1724 css_class += ' deleted';
1725 else if (!flags.seen)
1726 css_class += ' unread';
1727 else if (flags.unread_children > 0)
1728 css_class += ' unreadchildren';
1731 css_class += ' replied';
1732 if (flags.forwarded)
1733 css_class += ' forwarded';
1736 if (message.selected && !list.in_selection(uid))
1737 list.selection.push(uid);
1740 if (this.env.threading) {
1741 if (message.depth) {
1742 // This assumes that div width is hardcoded to 15px,
1743 tree += '<span id="rcmtab' + uid + '" class="branch" style="width:' + (message.depth * 15) + 'px;"> </span>';
1745 if ((rows[message.parent_uid] && rows[message.parent_uid].expanded === false)
1746 || ((this.env.autoexpand_threads == 0 || this.env.autoexpand_threads == 2) &&
1747 (!rows[message.parent_uid] || !rows[message.parent_uid].expanded))
1749 row.style.display = 'none';
1750 message.expanded = false;
1753 message.expanded = true;
1755 else if (message.has_children) {
1756 if (message.expanded === undefined && (this.env.autoexpand_threads == 1 || (this.env.autoexpand_threads == 2 && message.unread_children))) {
1757 message.expanded = true;
1760 expando = '<div id="rcmexpando' + uid + '" class="' + (message.expanded ? 'expanded' : 'collapsed') + '"> </div>';
1764 tree += '<span id="msgicn'+uid+'" class="'+css_class+'"> </span>';
1766 // build subject link
1767 if (!bw.ie && cols.subject) {
1768 var action = flags.mbox == this.env.drafts_mailbox ? 'compose' : 'show';
1769 var uid_param = flags.mbox == this.env.drafts_mailbox ? '_draft_uid' : '_uid';
1770 cols.subject = '<a href="./?_task=mail&_action='+action+'&_mbox='+urlencode(flags.mbox)+'&'+uid_param+'='+uid+'"'+
1771 ' onclick="return rcube_event.cancel(event)" onmouseover="rcube_webmail.long_subject_title(this,'+(message.depth+1)+')">'+cols.subject+'</a>';
1774 // add each submitted col
1775 for (n in this.env.coltypes) {
1776 c = this.env.coltypes[n];
1777 col = document.createElement('td');
1778 col.className = String(c).toLowerCase();
1781 css_class = (flags.flagged ? 'flagged' : 'unflagged');
1782 html = '<span id="flagicn'+uid+'" class="'+css_class+'"> </span>';
1784 else if (c == 'attachment') {
1785 if (/application\/|multipart\/m/.test(flags.ctype))
1786 html = '<span class="attachment"> </span>';
1787 else if (/multipart\/report/.test(flags.ctype))
1788 html = '<span class="report"> </span>';
1792 else if (c == 'status') {
1794 css_class = 'deleted';
1795 else if (!flags.seen)
1796 css_class = 'unread';
1797 else if (flags.unread_children > 0)
1798 css_class = 'unreadchildren';
1800 css_class = 'msgicon';
1801 html = '<span id="statusicn'+uid+'" class="'+css_class+'"> </span>';
1803 else if (c == 'threads')
1805 else if (c == 'subject') {
1807 col.onmouseover = function() { rcube_webmail.long_subject_title_ie(this, message.depth+1); };
1808 html = tree + cols[c];
1810 else if (c == 'priority') {
1811 if (flags.prio > 0 && flags.prio < 6)
1812 html = '<span class="prio'+flags.prio+'"> </span>';
1819 col.innerHTML = html;
1821 row.appendChild(col);
1824 list.insert_row(row, attop);
1827 if (attop && this.env.pagesize && list.rowcount > this.env.pagesize) {
1828 var uid = list.get_last_row();
1829 list.remove_row(uid);
1830 list.clear_selection(uid);
1834 this.set_list_sorting = function(sort_col, sort_order)
1836 // set table header class
1837 $('#rcm'+this.env.sort_col).removeClass('sorted'+(this.env.sort_order.toUpperCase()));
1839 $('#rcm'+sort_col).addClass('sorted'+sort_order);
1841 this.env.sort_col = sort_col;
1842 this.env.sort_order = sort_order;
1845 this.set_list_options = function(cols, sort_col, sort_order, threads)
1847 var update, add_url = '';
1849 if (sort_col === undefined)
1850 sort_col = this.env.sort_col;
1852 sort_order = this.env.sort_order;
1854 if (this.env.sort_col != sort_col || this.env.sort_order != sort_order) {
1856 this.set_list_sorting(sort_col, sort_order);
1859 if (this.env.threading != threads) {
1861 add_url += '&_threads=' + threads;
1864 if (cols && cols.length) {
1865 // make sure new columns are added at the end of the list
1866 var i, idx, name, newcols = [], oldcols = this.env.coltypes;
1867 for (i=0; i<oldcols.length; i++) {
1868 name = oldcols[i] == 'to' ? 'from' : oldcols[i];
1869 idx = $.inArray(name, cols);
1875 for (i=0; i<cols.length; i++)
1877 newcols.push(cols[i]);
1879 if (newcols.join() != oldcols.join()) {
1881 add_url += '&_cols=' + newcols.join(',');
1886 this.list_mailbox('', '', sort_col+'_'+sort_order, add_url);
1889 // when user doble-clicks on a row
1890 this.show_message = function(id, safe, preview)
1895 var target = window,
1896 action = preview ? 'preview': 'show',
1897 url = '&_action='+action+'&_uid='+id+'&_mbox='+urlencode(this.env.mailbox);
1899 if (preview && this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
1900 target = window.frames[this.env.contentframe];
1901 url += '&_framed=1';
1907 // also send search request to get the right messages
1908 if (this.env.search_request)
1909 url += '&_search='+this.env.search_request;
1911 if (action == 'preview' && String(target.location.href).indexOf(url) >= 0)
1912 this.show_contentframe(true);
1914 this.location_href(this.env.comm_path+url, target, true);
1916 // mark as read and change mbox unread counter
1917 if (action == 'preview' && this.message_list && this.message_list.rows[id] && this.message_list.rows[id].unread && this.env.preview_pane_mark_read >= 0) {
1918 this.preview_read_timer = window.setTimeout(function() {
1919 ref.set_message(id, 'unread', false);
1920 ref.update_thread_root(id, 'read');
1921 if (ref.env.unread_counts[ref.env.mailbox]) {
1922 ref.env.unread_counts[ref.env.mailbox] -= 1;
1923 ref.set_unread_count(ref.env.mailbox, ref.env.unread_counts[ref.env.mailbox], ref.env.mailbox == 'INBOX');
1925 if (ref.env.preview_pane_mark_read > 0)
1926 ref.http_post('mark', '_uid='+id+'&_flag=read&_quiet=1');
1927 }, this.env.preview_pane_mark_read * 1000);
1932 this.show_contentframe = function(show)
1935 if (this.env.contentframe && (frm = $('#'+this.env.contentframe)) && frm.length) {
1936 if (!show && (win = window.frames[this.env.contentframe])) {
1937 if (win.location && win.location.href.indexOf(this.env.blankpage)<0)
1938 win.location.href = this.env.blankpage;
1940 else if (!bw.safari && !bw.konq)
1941 frm[show ? 'show' : 'hide']();
1944 if (!show && this.busy)
1945 this.set_busy(false, null, this.env.frame_lock);
1948 this.lock_frame = function()
1950 if (!this.env.frame_lock)
1951 (this.is_framed() ? parent.rcmail : this).env.frame_lock = this.set_busy(true, 'loading');
1954 // list a specific page
1955 this.list_page = function(page)
1958 page = this.env.current_page+1;
1959 else if (page == 'last')
1960 page = this.env.pagecount;
1961 else if (page == 'prev' && this.env.current_page > 1)
1962 page = this.env.current_page-1;
1963 else if (page == 'first' && this.env.current_page > 1)
1966 if (page > 0 && page <= this.env.pagecount) {
1967 this.env.current_page = page;
1969 if (this.task == 'mail')
1970 this.list_mailbox(this.env.mailbox, page);
1971 else if (this.task == 'addressbook')
1972 this.list_contacts(this.env.source, this.env.group, page);
1976 // list messages of a specific mailbox using filter
1977 this.filter_mailbox = function(filter)
1979 var lock = this.set_busy(true, 'searching');
1981 this.clear_message_list();
1984 this.env.current_page = 1;
1985 this.http_request('search', this.search_params(false, filter), lock);
1988 // list messages of a specific mailbox
1989 this.list_mailbox = function(mbox, page, sort, add_url)
1991 var url = '', target = window;
1994 mbox = this.env.mailbox ? this.env.mailbox : 'INBOX';
1999 // add sort to url if set
2001 url += '&_sort=' + sort;
2003 // also send search request to get the right messages
2004 if (this.env.search_request)
2005 url += '&_search='+this.env.search_request;
2007 // set page=1 if changeing to another mailbox
2008 if (this.env.mailbox != mbox) {
2010 this.env.current_page = page;
2011 this.select_all_mode = false;
2014 // unselect selected messages and clear the list and message data
2015 this.clear_message_list();
2017 if (mbox != this.env.mailbox || (mbox == this.env.mailbox && !page && !sort))
2018 url += '&_refresh=1';
2020 this.select_folder(mbox, '', true);
2021 this.env.mailbox = mbox;
2023 // load message list remotely
2024 if (this.gui_objects.messagelist) {
2025 this.list_mailbox_remote(mbox, page, url);
2029 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
2030 target = window.frames[this.env.contentframe];
2031 url += '&_framed=1';
2034 // load message list to target frame/window
2036 this.set_busy(true, 'loading');
2037 this.location_href(this.env.comm_path+'&_mbox='+urlencode(mbox)+(page ? '&_page='+page : '')+url, target);
2041 this.clear_message_list = function()
2043 this.env.messages = {};
2044 this.last_selected = 0;
2046 this.show_contentframe(false);
2047 if (this.message_list)
2048 this.message_list.clear(true);
2051 // send remote request to load message list
2052 this.list_mailbox_remote = function(mbox, page, add_url)
2054 // clear message list first
2055 this.message_list.clear();
2057 // send request to server
2058 var url = '_mbox='+urlencode(mbox)+(page ? '&_page='+page : ''),
2059 lock = this.set_busy(true, 'loading');
2060 this.http_request('list', url+add_url, lock);
2063 // removes messages that doesn't exists from list selection array
2064 this.update_selection = function()
2066 var selected = this.message_list.selection,
2067 rows = this.message_list.rows,
2071 if (rows[selected[i]])
2072 selection.push(selected[i]);
2074 this.message_list.selection = selection;
2077 // expand all threads with unread children
2078 this.expand_unread = function()
2080 var r, tbody = this.gui_objects.messagelist.tBodies[0],
2081 new_row = tbody.firstChild;
2084 if (new_row.nodeType == 1 && (r = this.message_list.rows[new_row.uid]) && r.unread_children) {
2085 this.message_list.expand_all(r);
2086 this.set_unread_children(r.uid);
2088 new_row = new_row.nextSibling;
2093 // thread expanding/collapsing handler
2094 this.expand_message_row = function(e, uid)
2096 var row = this.message_list.rows[uid];
2098 // handle unread_children mark
2099 row.expanded = !row.expanded;
2100 this.set_unread_children(uid);
2101 row.expanded = !row.expanded;
2103 this.message_list.expand_row(e, uid);
2106 // message list expanding
2107 this.expand_threads = function()
2109 if (!this.env.threading || !this.env.autoexpand_threads || !this.message_list)
2112 switch (this.env.autoexpand_threads) {
2113 case 2: this.expand_unread(); break;
2114 case 1: this.message_list.expand_all(); break;
2118 // Initializes threads indicators/expanders after list update
2119 this.init_threads = function(roots, mbox)
2122 if (mbox && mbox != this.env.mailbox)
2125 for (var n=0, len=roots.length; n<len; n++)
2126 this.add_tree_icons(roots[n]);
2127 this.expand_threads();
2130 // adds threads tree icons to the list (or specified thread)
2131 this.add_tree_icons = function(root)
2133 var i, l, r, n, len, pos, tmp = [], uid = [],
2134 row, rows = this.message_list.rows;
2137 row = rows[root] ? rows[root].obj : null;
2139 row = this.message_list.list.tBodies[0].firstChild;
2142 if (row.nodeType == 1 && (r = rows[row.uid])) {
2144 for (i=tmp.length-1; i>=0; i--) {
2145 len = tmp[i].length;
2146 if (len > r.depth) {
2147 pos = len - r.depth;
2148 if (!(tmp[i][pos] & 2))
2149 tmp[i][pos] = tmp[i][pos] ? tmp[i][pos]+2 : 2;
2151 else if (len == r.depth) {
2152 if (!(tmp[i][0] & 2))
2159 tmp.push(new Array(r.depth));
2160 tmp[tmp.length-1][0] = 1;
2166 this.set_tree_icons(uid[i], tmp[i]);
2171 if (root && row != rows[root].obj)
2175 row = row.nextSibling;
2180 this.set_tree_icons(uid[i], tmp[i]);
2185 // adds tree icons to specified message row
2186 this.set_tree_icons = function(uid, tree)
2188 var i, divs = [], html = '', len = tree.length;
2190 for (i=0; i<len; i++) {
2192 divs.push({'class': 'l3', width: 15});
2193 else if (tree[i] > 1)
2194 divs.push({'class': 'l2', width: 15});
2195 else if (tree[i] > 0)
2196 divs.push({'class': 'l1', width: 15});
2198 else if (divs.length && !divs[divs.length-1]['class'])
2199 divs[divs.length-1].width += 15;
2201 divs.push({'class': null, width: 15});
2204 for (i=divs.length-1; i>=0; i--) {
2205 if (divs[i]['class'])
2206 html += '<div class="tree '+divs[i]['class']+'" />';
2208 html += '<div style="width:'+divs[i].width+'px" />';
2212 $('#rcmtab'+uid).html(html);
2215 // update parent in a thread
2216 this.update_thread_root = function(uid, flag)
2218 if (!this.env.threading)
2221 var root = this.message_list.find_root(uid);
2226 var p = this.message_list.rows[root];
2228 if (flag == 'read' && p.unread_children) {
2229 p.unread_children--;
2231 else if (flag == 'unread' && p.has_children) {
2232 // unread_children may be undefined
2233 p.unread_children = p.unread_children ? p.unread_children + 1 : 1;
2239 this.set_message_icon(root);
2240 this.set_unread_children(root);
2243 // update thread indicators for all messages in a thread below the specified message
2244 // return number of removed/added root level messages
2245 this.update_thread = function (uid)
2247 if (!this.env.threading)
2250 var r, parent, count = 0,
2251 rows = this.message_list.rows,
2253 depth = rows[uid].depth,
2256 if (!row.depth) // root message: decrease roots count
2258 else if (row.unread) {
2259 // update unread_children for thread root
2260 parent = this.message_list.find_root(uid);
2261 rows[parent].unread_children--;
2262 this.set_unread_children(parent);
2265 parent = row.parent_uid;
2268 row = row.obj.nextSibling;
2270 if (row.nodeType == 1 && (r = rows[row.uid])) {
2271 if (!r.depth || r.depth <= depth)
2274 r.depth--; // move left
2275 // reset width and clear the content of a tab, icons will be added later
2276 $('#rcmtab'+r.uid).width(r.depth * 15).html('');
2277 if (!r.depth) { // a new root
2278 count++; // increase roots count
2280 if (r.has_children) {
2281 // replace 'leaf' with 'collapsed'
2282 $('#rcmrow'+r.uid+' '+'.leaf:first')
2283 .attr('id', 'rcmexpando' + r.uid)
2284 .attr('class', (r.obj.style.display != 'none' ? 'expanded' : 'collapsed'))
2285 .bind('mousedown', {uid:r.uid, p:this},
2286 function(e) { return e.data.p.expand_message_row(e, e.data.uid); });
2288 r.unread_children = 0;
2291 // show if it was hidden
2292 if (r.obj.style.display == 'none')
2296 if (r.depth == depth)
2297 r.parent_uid = parent;
2298 if (r.unread && roots.length)
2299 roots[roots.length-1].unread_children++;
2302 row = row.nextSibling;
2305 // update unread_children for roots
2306 for (var i=0; i<roots.length; i++)
2307 this.set_unread_children(roots[i].uid);
2312 this.delete_excessive_thread_rows = function()
2314 var rows = this.message_list.rows,
2315 tbody = this.message_list.list.tBodies[0],
2316 row = tbody.firstChild,
2317 cnt = this.env.pagesize + 1;
2320 if (row.nodeType == 1 && (r = rows[row.uid])) {
2321 if (!r.depth && cnt)
2325 this.message_list.remove_row(row.uid);
2327 row = row.nextSibling;
2332 this.set_message_icon = function(uid)
2335 row = this.message_list.rows[uid];
2341 css_class = 'msgicon';
2343 css_class += ' deleted';
2344 else if (row.unread)
2345 css_class += ' unread';
2346 else if (row.unread_children)
2347 css_class += ' unreadchildren';
2348 if (row.msgicon == row.icon) {
2350 css_class += ' replied';
2352 css_class += ' forwarded';
2353 css_class += ' status';
2356 row.icon.className = css_class;
2359 if (row.msgicon && row.msgicon != row.icon) {
2360 css_class = 'msgicon';
2361 if (!row.unread && row.unread_children)
2362 css_class += ' unreadchildren';
2364 css_class += ' replied';
2366 css_class += ' forwarded';
2368 row.msgicon.className = css_class;
2372 css_class = (row.flagged ? 'flagged' : 'unflagged');
2373 row.flagicon.className = css_class;
2377 // set message status
2378 this.set_message_status = function(uid, flag, status)
2380 var row = this.message_list.rows[uid];
2385 if (flag == 'unread')
2386 row.unread = status;
2387 else if(flag == 'deleted')
2388 row.deleted = status;
2389 else if (flag == 'replied')
2390 row.replied = status;
2391 else if (flag == 'forwarded')
2392 row.forwarded = status;
2393 else if (flag == 'flagged')
2394 row.flagged = status;
2397 // set message row status, class and icon
2398 this.set_message = function(uid, flag, status)
2400 var row = this.message_list.rows[uid];
2406 this.set_message_status(uid, flag, status);
2408 var rowobj = $(row.obj);
2410 if (row.unread && !rowobj.hasClass('unread'))
2411 rowobj.addClass('unread');
2412 else if (!row.unread && rowobj.hasClass('unread'))
2413 rowobj.removeClass('unread');
2415 if (row.deleted && !rowobj.hasClass('deleted'))
2416 rowobj.addClass('deleted');
2417 else if (!row.deleted && rowobj.hasClass('deleted'))
2418 rowobj.removeClass('deleted');
2420 if (row.flagged && !rowobj.hasClass('flagged'))
2421 rowobj.addClass('flagged');
2422 else if (!row.flagged && rowobj.hasClass('flagged'))
2423 rowobj.removeClass('flagged');
2425 this.set_unread_children(uid);
2426 this.set_message_icon(uid);
2429 // sets unroot (unread_children) class of parent row
2430 this.set_unread_children = function(uid)
2432 var row = this.message_list.rows[uid];
2437 if (!row.unread && row.unread_children && !row.expanded)
2438 $(row.obj).addClass('unroot');
2440 $(row.obj).removeClass('unroot');
2443 // copy selected messages to the specified mailbox
2444 this.copy_messages = function(mbox)
2446 if (mbox && typeof mbox === 'object')
2449 // exit if current or no mailbox specified or if selection is empty
2450 if (!mbox || mbox == this.env.mailbox || (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length)))
2454 lock = this.display_message(this.get_label('copyingmessage'), 'loading'),
2455 add_url = '&_target_mbox='+urlencode(mbox)+'&_from='+(this.env.action ? this.env.action : '');
2458 a_uids[0] = this.env.uid;
2460 var selection = this.message_list.get_selection();
2461 for (var n in selection) {
2462 a_uids.push(selection[n]);
2466 add_url += '&_uid='+this.uids_to_list(a_uids);
2468 // send request to server
2469 this.http_post('copy', '_mbox='+urlencode(this.env.mailbox)+add_url, lock);
2472 // move selected messages to the specified mailbox
2473 this.move_messages = function(mbox)
2475 if (mbox && typeof mbox === 'object')
2478 // exit if current or no mailbox specified or if selection is empty
2479 if (!mbox || mbox == this.env.mailbox || (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length)))
2483 add_url = '&_target_mbox='+urlencode(mbox)+'&_from='+(this.env.action ? this.env.action : '');
2485 // show wait message
2486 if (this.env.action == 'show') {
2487 lock = this.set_busy(true, 'movingmessage');
2490 this.show_contentframe(false);
2492 // Hide message command buttons until a message is selected
2493 this.enable_command(this.env.message_commands, false);
2495 this._with_selected_messages('moveto', lock, add_url);
2498 // delete selected messages from the current mailbox
2499 this.delete_messages = function()
2501 var uid, i, len, trash = this.env.trash_mailbox,
2502 list = this.message_list,
2503 selection = list ? $.merge([], list.get_selection()) : [];
2505 // exit if no mailbox specified or if selection is empty
2506 if (!this.env.uid && !selection.length)
2509 // also select childs of collapsed rows
2510 for (i=0, len=selection.length; i<len; i++) {
2512 if (list.rows[uid].has_children && !list.rows[uid].expanded)
2513 list.select_childs(uid);
2516 // if config is set to flag for deletion
2517 if (this.env.flag_for_deletion) {
2518 this.mark_message('delete');
2521 // if there isn't a defined trash mailbox or we are in it
2522 // @TODO: we should check if defined trash mailbox exists
2523 else if (!trash || this.env.mailbox == trash)
2524 this.permanently_remove_messages();
2525 // if there is a trash mailbox defined and we're not currently in it
2527 // if shift was pressed delete it immediately
2528 if (list && list.modkey == SHIFT_KEY) {
2529 if (confirm(this.get_label('deletemessagesconfirm')))
2530 this.permanently_remove_messages();
2533 this.move_messages(trash);
2539 // delete the selected messages permanently
2540 this.permanently_remove_messages = function()
2542 // exit if no mailbox specified or if selection is empty
2543 if (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length))
2546 this.show_contentframe(false);
2547 this._with_selected_messages('delete', false, '&_from='+(this.env.action ? this.env.action : ''));
2550 // Send a specifc moveto/delete request with UIDs of all selected messages
2552 this._with_selected_messages = function(action, lock, add_url)
2554 var a_uids = [], count = 0, msg;
2557 a_uids[0] = this.env.uid;
2559 var n, id, root, roots = [],
2560 selection = this.message_list.get_selection();
2562 for (n=0, len=selection.length; n<len; n++) {
2566 if (this.env.threading) {
2567 count += this.update_thread(id);
2568 root = this.message_list.find_root(id);
2569 if (root != id && $.inArray(root, roots) < 0) {
2573 this.message_list.remove_row(id, (this.env.display_next && n == selection.length-1));
2575 // make sure there are no selected rows
2576 if (!this.env.display_next)
2577 this.message_list.clear_selection();
2578 // update thread tree icons
2579 for (n=0, len=roots.length; n<len; n++) {
2580 this.add_tree_icons(roots[n]);
2584 // also send search request to get the right messages
2585 if (this.env.search_request)
2586 add_url += '&_search='+this.env.search_request;
2588 if (this.env.display_next && this.env.next_uid)
2589 add_url += '&_next_uid='+this.env.next_uid;
2592 add_url += '&_count='+(count*-1);
2594 // remove threads from the end of the list
2595 this.delete_excessive_thread_rows();
2597 add_url += '&_uid='+this.uids_to_list(a_uids);
2600 msg = action == 'moveto' ? 'movingmessage' : 'deletingmessage';
2601 lock = this.display_message(this.get_label(msg), 'loading');
2604 // send request to server
2605 this.http_post(action, '_mbox='+urlencode(this.env.mailbox)+add_url, lock);
2608 // set a specific flag to one or more messages
2609 this.mark_message = function(flag, uid)
2611 var a_uids = [], r_uids = [], len, n, id,
2612 selection = this.message_list ? this.message_list.get_selection() : [];
2616 else if (this.env.uid)
2617 a_uids[0] = this.env.uid;
2618 else if (this.message_list) {
2619 for (n=0, len=selection.length; n<len; n++) {
2620 a_uids.push(selection[n]);
2624 if (!this.message_list)
2627 for (n=0, len=a_uids.length; n<len; n++) {
2629 if ((flag=='read' && this.message_list.rows[id].unread)
2630 || (flag=='unread' && !this.message_list.rows[id].unread)
2631 || (flag=='delete' && !this.message_list.rows[id].deleted)
2632 || (flag=='undelete' && this.message_list.rows[id].deleted)
2633 || (flag=='flagged' && !this.message_list.rows[id].flagged)
2634 || (flag=='unflagged' && this.message_list.rows[id].flagged))
2641 if (!r_uids.length && !this.select_all_mode)
2647 this.toggle_read_status(flag, r_uids);
2651 this.toggle_delete_status(r_uids);
2655 this.toggle_flagged_status(flag, a_uids);
2660 // set class to read/unread
2661 this.toggle_read_status = function(flag, a_uids)
2663 var i, len = a_uids.length,
2664 url = '_uid='+this.uids_to_list(a_uids)+'&_flag='+flag,
2665 lock = this.display_message(this.get_label('markingmessage'), 'loading');
2667 // mark all message rows as read/unread
2668 for (i=0; i<len; i++)
2669 this.set_message(a_uids[i], 'unread', (flag=='unread' ? true : false));
2671 // also send search request to get the right messages
2672 if (this.env.search_request)
2673 url += '&_search='+this.env.search_request;
2675 this.http_post('mark', url, lock);
2677 for (i=0; i<len; i++)
2678 this.update_thread_root(a_uids[i], flag);
2681 // set image to flagged or unflagged
2682 this.toggle_flagged_status = function(flag, a_uids)
2684 var i, len = a_uids.length,
2685 url = '_uid='+this.uids_to_list(a_uids)+'&_flag='+flag,
2686 lock = this.display_message(this.get_label('markingmessage'), 'loading');
2688 // mark all message rows as flagged/unflagged
2689 for (i=0; i<len; i++)
2690 this.set_message(a_uids[i], 'flagged', (flag=='flagged' ? true : false));
2692 // also send search request to get the right messages
2693 if (this.env.search_request)
2694 url += '&_search='+this.env.search_request;
2696 this.http_post('mark', url, lock);
2699 // mark all message rows as deleted/undeleted
2700 this.toggle_delete_status = function(a_uids)
2702 var len = a_uids.length,
2703 i, uid, all_deleted = true,
2704 rows = this.message_list ? this.message_list.rows : [];
2707 if (!rows.length || (rows[a_uids[0]] && !rows[a_uids[0]].deleted))
2708 this.flag_as_deleted(a_uids);
2710 this.flag_as_undeleted(a_uids);
2715 for (i=0; i<len; i++) {
2717 if (rows[uid] && !rows[uid].deleted) {
2718 all_deleted = false;
2724 this.flag_as_undeleted(a_uids);
2726 this.flag_as_deleted(a_uids);
2731 this.flag_as_undeleted = function(a_uids)
2733 var i, len=a_uids.length,
2734 url = '_uid='+this.uids_to_list(a_uids)+'&_flag=undelete',
2735 lock = this.display_message(this.get_label('markingmessage'), 'loading');
2737 for (i=0; i<len; i++)
2738 this.set_message(a_uids[i], 'deleted', false);
2740 // also send search request to get the right messages
2741 if (this.env.search_request)
2742 url += '&_search='+this.env.search_request;
2744 this.http_post('mark', url, lock);
2748 this.flag_as_deleted = function(a_uids)
2752 rows = this.message_list ? this.message_list.rows : [],
2755 for (var i=0, len=a_uids.length; i<len; i++) {
2758 if (rows[uid].unread)
2759 r_uids[r_uids.length] = uid;
2761 if (this.env.skip_deleted) {
2762 count += this.update_thread(uid);
2763 this.message_list.remove_row(uid, (this.env.display_next && i == this.message_list.selection.length-1));
2766 this.set_message(uid, 'deleted', true);
2770 // make sure there are no selected rows
2771 if (this.env.skip_deleted && this.message_list) {
2772 if(!this.env.display_next)
2773 this.message_list.clear_selection();
2775 add_url += '&_count='+(count*-1);
2777 // remove threads from the end of the list
2778 this.delete_excessive_thread_rows();
2781 add_url = '&_from='+(this.env.action ? this.env.action : ''),
2782 lock = this.display_message(this.get_label('markingmessage'), 'loading');
2786 add_url += '&_ruid='+this.uids_to_list(r_uids);
2788 if (this.env.skip_deleted) {
2789 if (this.env.display_next && this.env.next_uid)
2790 add_url += '&_next_uid='+this.env.next_uid;
2793 // also send search request to get the right messages
2794 if (this.env.search_request)
2795 add_url += '&_search='+this.env.search_request;
2797 this.http_post('mark', '_uid='+this.uids_to_list(a_uids)+'&_flag=delete'+add_url, lock);
2801 // flag as read without mark request (called from backend)
2802 // argument should be a coma-separated list of uids
2803 this.flag_deleted_as_read = function(uids)
2805 var icn_src, uid, i, len,
2806 rows = this.message_list ? this.message_list.rows : [];
2808 uids = String(uids).split(',');
2810 for (i=0, len=uids.length; i<len; i++) {
2813 this.set_message(uid, 'unread', false);
2817 // Converts array of message UIDs to comma-separated list for use in URL
2818 // with select_all mode checking
2819 this.uids_to_list = function(uids)
2821 return this.select_all_mode ? '*' : uids.join(',');
2825 /*********************************************************/
2826 /********* mailbox folders methods *********/
2827 /*********************************************************/
2829 this.expunge_mailbox = function(mbox)
2831 var lock, url = '_mbox='+urlencode(mbox);
2833 // lock interface if it's the active mailbox
2834 if (mbox == this.env.mailbox) {
2835 lock = this.set_busy(true, 'loading');
2836 url += '&_reload=1';
2837 if (this.env.search_request)
2838 url += '&_search='+this.env.search_request;
2841 // send request to server
2842 this.http_post('expunge', url, lock);
2845 this.purge_mailbox = function(mbox)
2848 url = '_mbox='+urlencode(mbox);
2850 if (!confirm(this.get_label('purgefolderconfirm')))
2853 // lock interface if it's the active mailbox
2854 if (mbox == this.env.mailbox) {
2855 lock = this.set_busy(true, 'loading');
2856 url += '&_reload=1';
2859 // send request to server
2860 this.http_post('purge', url, lock);
2863 // test if purge command is allowed
2864 this.purge_mailbox_test = function()
2866 return (this.env.messagecount && (this.env.mailbox == this.env.trash_mailbox || this.env.mailbox == this.env.junk_mailbox
2867 || this.env.mailbox.match('^' + RegExp.escape(this.env.trash_mailbox) + RegExp.escape(this.env.delimiter))
2868 || this.env.mailbox.match('^' + RegExp.escape(this.env.junk_mailbox) + RegExp.escape(this.env.delimiter))));
2872 /*********************************************************/
2873 /********* login form methods *********/
2874 /*********************************************************/
2876 // handler for keyboard events on the _user field
2877 this.login_user_keyup = function(e)
2879 var key = rcube_event.get_keycode(e);
2880 var passwd = $('#rcmloginpwd');
2883 if (key == 13 && passwd.length && !passwd.val()) {
2885 return rcube_event.cancel(e);
2892 /*********************************************************/
2893 /********* message compose methods *********/
2894 /*********************************************************/
2896 // init message compose form: set focus and eventhandlers
2897 this.init_messageform = function()
2899 if (!this.gui_objects.messageform)
2902 var input_from = $("[name='_from']"),
2903 input_to = $("[name='_to']"),
2904 input_subject = $("input[name='_subject']"),
2905 input_message = $("[name='_message']").get(0),
2906 html_mode = $("input[name='_is_html']").val() == '1',
2907 ac_fields = ['cc', 'bcc', 'replyto', 'followupto'],
2910 // configure parallel autocompletion
2911 if (this.env.autocomplete_threads > 0) {
2913 threads: this.env.autocomplete_threads,
2914 sources: this.env.autocomplete_sources
2918 // init live search events
2919 this.init_address_input_events(input_to, ac_props);
2920 for (var i in ac_fields) {
2921 this.init_address_input_events($("[name='_"+ac_fields[i]+"']"), ac_props);
2925 this.set_caret_pos(input_message, this.env.top_posting ? 0 : $(input_message).val().length);
2926 // add signature according to selected identity
2927 // if we have HTML editor, signature is added in callback
2928 if (input_from.prop('type') == 'select-one' && $("input[name='_draft_saveid']").val() == '') {
2929 this.change_identity(input_from[0]);
2933 if (input_to.val() == '')
2935 else if (input_subject.val() == '')
2936 input_subject.focus();
2937 else if (input_message)
2938 input_message.focus();
2940 this.env.compose_focus_elem = document.activeElement;
2942 // get summary of all field values
2943 this.compose_field_hash(true);
2945 // start the auto-save timer
2946 this.auto_save_start();
2949 this.init_address_input_events = function(obj, props)
2951 this.env.recipients_delimiter = this.env.recipients_separator + ' ';
2953 obj[bw.ie || bw.safari || bw.chrome ? 'keydown' : 'keypress'](function(e) { return ref.ksearch_keydown(e, this, props); })
2954 .attr('autocomplete', 'off');
2957 // checks the input fields before sending a message
2958 this.check_compose_input = function(cmd)
2960 // check input fields
2961 var ed, input_to = $("[name='_to']"),
2962 input_cc = $("[name='_cc']"),
2963 input_bcc = $("[name='_bcc']"),
2964 input_from = $("[name='_from']"),
2965 input_subject = $("[name='_subject']"),
2966 input_message = $("[name='_message']");
2968 // check sender (if have no identities)
2969 if (input_from.prop('type') == 'text' && !rcube_check_email(input_from.val(), true)) {
2970 alert(this.get_label('nosenderwarning'));
2975 // check for empty recipient
2976 var recipients = input_to.val() ? input_to.val() : (input_cc.val() ? input_cc.val() : input_bcc.val());
2977 if (!rcube_check_email(recipients.replace(/^\s+/, '').replace(/[\s,;]+$/, ''), true)) {
2978 alert(this.get_label('norecipientwarning'));
2983 // check if all files has been uploaded
2984 for (var key in this.env.attachments) {
2985 if (typeof this.env.attachments[key] === 'object' && !this.env.attachments[key].complete) {
2986 alert(this.get_label('notuploadedwarning'));
2991 // display localized warning for missing subject
2992 if (input_subject.val() == '') {
2993 var myprompt = $('<div class="prompt">').html('<div class="message">' + this.get_label('nosubjectwarning') + '</div>').appendTo(document.body);
2994 var prompt_value = $('<input>').attr('type', 'text').attr('size', 30).appendTo(myprompt).val(this.get_label('nosubject'));
2997 buttons[this.get_label('cancel')] = function(){
2998 input_subject.focus();
2999 $(this).dialog('close');
3001 buttons[this.get_label('sendmessage')] = function(){
3002 input_subject.val(prompt_value.val());
3003 $(this).dialog('close');
3004 ref.command(cmd, { nocheck:true }); // repeat command which triggered this
3011 close: function(event, ui) { $(this).remove() }
3013 prompt_value.select();
3017 // Apply spellcheck changes if spell checker is active
3018 this.stop_spellchecking();
3021 ed = tinyMCE.get(this.env.composebody);
3023 // check for empty body
3024 if (!ed && input_message.val() == '' && !confirm(this.get_label('nobodywarning'))) {
3025 input_message.focus();
3029 if (!ed.getContent() && !confirm(this.get_label('nobodywarning'))) {
3033 // move body from html editor to textarea (just to be sure, #1485860)
3034 tinyMCE.triggerSave();
3040 this.toggle_editor = function(props)
3042 if (props.mode == 'html') {
3043 this.display_spellcheck_controls(false);
3044 this.plain2html($('#'+props.id).val(), props.id);
3045 tinyMCE.execCommand('mceAddControl', false, props.id);
3048 var thisMCE = tinyMCE.get(props.id), existingHtml;
3049 if (thisMCE.plugins.spellchecker && thisMCE.plugins.spellchecker.active)
3050 thisMCE.execCommand('mceSpellCheck', false);
3052 if (existingHtml = thisMCE.getContent()) {
3053 if (!confirm(this.get_label('editorwarning'))) {
3056 this.html2plain(existingHtml, props.id);
3058 tinyMCE.execCommand('mceRemoveControl', false, props.id);
3059 this.display_spellcheck_controls(true);
3065 this.stop_spellchecking = function()
3068 if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody))) {
3069 if (ed.plugins.spellchecker && ed.plugins.spellchecker.active)
3070 ed.execCommand('mceSpellCheck');
3072 else if ((ed = this.env.spellcheck) && !this.spellcheck_ready) {
3073 $(ed.spell_span).trigger('click');
3074 this.set_spellcheck_state('ready');
3078 this.display_spellcheck_controls = function(vis)
3080 if (this.env.spellcheck) {
3081 // stop spellchecking process
3083 this.stop_spellchecking();
3085 $(this.env.spellcheck.spell_container)[vis ? 'show' : 'hide']();
3089 this.set_spellcheck_state = function(s)
3091 this.spellcheck_ready = (s == 'ready' || s == 'no_error_found');
3092 this.enable_command('spellcheck', this.spellcheck_ready);
3095 // get selected language
3096 this.spellcheck_lang = function()
3099 if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody)) && ed.plugins.spellchecker) {
3100 return ed.plugins.spellchecker.selectedLang;
3102 else if (this.env.spellcheck) {
3103 return GOOGIE_CUR_LANG;
3107 // resume spellchecking, highlight provided mispellings without new ajax request
3108 this.spellcheck_resume = function(ishtml, data)
3111 var ed = tinyMCE.get(this.env.composebody);
3112 sp = ed.plugins.spellchecker;
3115 sp._markWords(data);
3119 var sp = this.env.spellcheck;
3120 sp.prepare(false, true);
3121 sp.processData(data);
3125 this.set_draft_id = function(id)
3127 $("input[name='_draft_saveid']").val(id);
3130 this.auto_save_start = function()
3132 if (this.env.draft_autosave)
3133 this.save_timer = self.setTimeout(function(){ ref.command("savedraft"); }, this.env.draft_autosave * 1000);
3135 // Unlock interface now that saving is complete
3139 this.compose_field_hash = function(save)
3141 // check input fields
3143 value_to = $("[name='_to']").val(),
3144 value_cc = $("[name='_cc']").val(),
3145 value_bcc = $("[name='_bcc']").val(),
3146 value_subject = $("[name='_subject']").val();
3149 str += value_to+':';
3151 str += value_cc+':';
3153 str += value_bcc+':';
3155 str += value_subject+':';
3157 if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody)))
3158 str += ed.getContent();
3160 str += $("[name='_message']").val();
3162 if (this.env.attachments)
3163 for (var upload_id in this.env.attachments)
3167 this.cmp_hash = str;
3172 this.change_identity = function(obj, show_sig)
3174 if (!obj || !obj.options)
3178 show_sig = this.env.show_sig;
3180 var cursor_pos, p = -1,
3181 id = obj.options[obj.selectedIndex].value,
3182 input_message = $("[name='_message']"),
3183 message = input_message.val(),
3184 is_html = ($("input[name='_is_html']").val() == '1'),
3185 sig = this.env.identity,
3186 sig_separator = this.env.sig_above && (this.env.compose_mode == 'reply' || this.env.compose_mode == 'forward') ? '---' : '-- ';
3188 // enable manual signature insert
3189 if (this.env.signatures && this.env.signatures[id]) {
3190 this.enable_command('insert-sig', true);
3191 this.env.compose_commands.push('insert-sig');
3194 this.enable_command('insert-sig', false);
3197 // remove the 'old' signature
3198 if (show_sig && sig && this.env.signatures && this.env.signatures[sig]) {
3200 sig = this.env.signatures[sig].is_html ? this.env.signatures[sig].plain_text : this.env.signatures[sig].text;
3201 sig = sig.replace(/\r\n/g, '\n');
3203 if (!sig.match(/^--[ -]\n/m))
3204 sig = sig_separator + '\n' + sig;
3206 p = this.env.sig_above ? message.indexOf(sig) : message.lastIndexOf(sig);
3208 message = message.substring(0, p) + message.substring(p+sig.length, message.length);
3210 // add the new signature string
3211 if (show_sig && this.env.signatures && this.env.signatures[id]) {
3212 sig = this.env.signatures[id]['is_html'] ? this.env.signatures[id]['plain_text'] : this.env.signatures[id]['text'];
3213 sig = sig.replace(/\r\n/g, '\n');
3215 if (!sig.match(/^--[ -]\n/m))
3216 sig = sig_separator + '\n' + sig;
3218 if (this.env.sig_above) {
3219 if (p >= 0) { // in place of removed signature
3220 message = message.substring(0, p) + sig + message.substring(p, message.length);
3223 else if (pos = this.get_caret_pos(input_message.get(0))) { // at cursor position
3224 message = message.substring(0, pos) + '\n' + sig + '\n\n' + message.substring(pos, message.length);
3229 message = '\n\n' + sig + '\n\n' + message.replace(/^[\r\n]+/, '');
3233 message = message.replace(/[\r\n]+$/, '');
3234 cursor_pos = !this.env.top_posting && message.length ? message.length+1 : 0;
3235 message += '\n\n' + sig;
3239 cursor_pos = this.env.top_posting ? 0 : message.length;
3241 input_message.val(message);
3243 // move cursor before the signature
3244 this.set_caret_pos(input_message.get(0), cursor_pos);
3246 else if (show_sig && this.env.signatures) { // html
3247 var editor = tinyMCE.get(this.env.composebody),
3248 sigElem = editor.dom.get('_rc_sig');
3250 // Append the signature as a div within the body
3252 var body = editor.getBody(),
3253 doc = editor.getDoc();
3255 sigElem = doc.createElement('div');
3256 sigElem.setAttribute('id', '_rc_sig');
3258 if (this.env.sig_above) {
3259 // if no existing sig and top posting then insert at caret pos
3260 editor.getWin().focus(); // correct focus in IE & Chrome
3262 var node = editor.selection.getNode();
3263 if (node.nodeName == 'BODY') {
3264 // no real focus, insert at start
3265 body.insertBefore(sigElem, body.firstChild);
3266 body.insertBefore(doc.createElement('br'), body.firstChild);
3269 body.insertBefore(sigElem, node.nextSibling);
3270 body.insertBefore(doc.createElement('br'), node.nextSibling);
3274 if (bw.ie) // add empty line before signature on IE
3275 body.appendChild(doc.createElement('br'));
3277 body.appendChild(sigElem);
3281 if (this.env.signatures[id]) {
3282 if (this.env.signatures[id].is_html) {
3283 sig = this.env.signatures[id].text;
3284 if (!this.env.signatures[id].plain_text.match(/^--[ -]\r?\n/m))
3285 sig = sig_separator + '<br />' + sig;
3288 sig = this.env.signatures[id].text;
3289 if (!sig.match(/^--[ -]\r?\n/m))
3290 sig = sig_separator + '\n' + sig;
3291 sig = '<pre>' + sig + '</pre>';
3294 sigElem.innerHTML = sig;
3298 this.env.identity = id;
3302 // upload attachment file
3303 this.upload_file = function(form)
3308 // get file input field, count files on capable browser
3309 var i, size = 0, field = $('input[type=file]', form).get(0),
3310 files = field.files ? field.files.length : field.value ? 1 : 0;
3312 // create hidden iframe and post upload form
3315 if (field.files && this.env.max_filesize && this.env.filesizeerror) {
3316 for (i=0; i<files; i++)
3317 size += field.files[i].size;
3318 if (size && size > this.env.max_filesize) {
3319 this.display_message(this.env.filesizeerror, 'error');
3324 var frame_name = this.async_upload_form(form, 'upload', function(e) {
3325 var d, content = '';
3327 if (this.contentDocument) {
3328 d = this.contentDocument;
3329 } else if (this.contentWindow) {
3330 d = this.contentWindow.document;
3332 content = d.childNodes[0].innerHTML;
3335 if (!content.match(/add2attachment/) && (!bw.opera || (rcmail.env.uploadframe && rcmail.env.uploadframe == e.data.ts))) {
3336 if (!content.match(/display_message/))
3337 rcmail.display_message(rcmail.get_label('fileuploaderror'), 'error');
3338 rcmail.remove_from_attachment_list(e.data.ts);
3340 // Opera hack: handle double onload
3342 rcmail.env.uploadframe = e.data.ts;
3345 // display upload indicator and cancel button
3346 var content = '<span>' + this.get_label('uploading' + (files > 1 ? 'many' : '')) + '</span>',
3347 ts = frame_name.replace(/^rcmupload/, '');
3349 if (this.env.loadingicon)
3350 content = '<img src="'+this.env.loadingicon+'" alt="" />'+content;
3351 if (this.env.cancelicon)
3352 content = '<a title="'+this.get_label('cancel')+'" onclick="return rcmail.cancel_attachment_upload(\''+ts+'\', \''+frame_name+'\');" href="#cancelupload"><img src="'+this.env.cancelicon+'" alt="" /></a>'+content;
3353 this.add2attachment_list(ts, { name:'', html:content, complete:false });
3355 // upload progress support
3356 if (this.env.upload_progress_time) {
3357 this.upload_progress_start('upload', ts);
3361 // set reference to the form object
3362 this.gui_objects.attachmentform = form;
3366 // add file name to attachment list
3367 // called from upload page
3368 this.add2attachment_list = function(name, att, upload_id)
3370 if (!this.gui_objects.attachmentlist)
3373 var indicator, li = $('<li>').attr('id', name).html(att.html);
3375 // replace indicator's li
3376 if (upload_id && (indicator = document.getElementById(upload_id))) {
3377 li.replaceAll(indicator);
3379 else { // add new li
3380 li.appendTo(this.gui_objects.attachmentlist);
3383 if (upload_id && this.env.attachments[upload_id])
3384 delete this.env.attachments[upload_id];
3386 this.env.attachments[name] = att;
3391 this.remove_from_attachment_list = function(name)
3393 delete this.env.attachments[name];
3394 $('#'+name).remove();
3397 this.remove_attachment = function(name)
3399 if (name && this.env.attachments[name])
3400 this.http_post('remove-attachment', { _id:this.env.compose_id, _file:name });
3405 this.cancel_attachment_upload = function(name, frame_name)
3407 if (!name || !frame_name)
3410 this.remove_from_attachment_list(name);
3411 $("iframe[name='"+frame_name+"']").remove();
3415 this.upload_progress_start = function(action, name)
3417 window.setTimeout(function() { rcmail.http_request(action, {_progress: name}); },
3418 this.env.upload_progress_time * 1000);
3421 this.upload_progress_update = function(param)
3423 var elem = $('#'+param.name + '> span');
3425 if (!elem.length || !param.text)
3428 elem.text(param.text);
3431 this.upload_progress_start(param.action, param.name);
3434 // send remote request to add a new contact
3435 this.add_contact = function(value)
3438 this.http_post('addcontact', '_address='+value);
3443 // send remote request to search mail or contacts
3444 this.qsearch = function(value)
3447 var n, lock = this.set_busy(true, 'searching');
3449 if (this.message_list)
3450 this.clear_message_list();
3451 else if (this.contact_list)
3452 this.list_contacts_clear();
3455 this.env.current_page = 1;
3456 r = this.http_request('search', this.search_params(value)
3457 + (this.env.source ? '&_source='+urlencode(this.env.source) : '')
3458 + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
3460 this.env.qsearch = {lock: lock, request: r};
3464 // build URL params for search
3465 this.search_params = function(search, filter)
3467 var n, url = [], mods_arr = [],
3468 mods = this.env.search_mods,
3469 mbox = this.env.mailbox;
3471 if (!filter && this.gui_objects.search_filter)
3472 filter = this.gui_objects.search_filter.value;
3474 if (!search && this.gui_objects.qsearchbox)
3475 search = this.gui_objects.qsearchbox.value;
3478 url.push('_filter=' + urlencode(filter));
3481 url.push('_q='+urlencode(search));
3483 if (mods && this.message_list)
3484 mods = mods[mbox] ? mods[mbox] : mods['*'];
3489 url.push('_headers='+mods_arr.join(','));
3494 url.push('_mbox='+urlencode(mbox));
3496 return url.join('&');
3499 // reset quick-search form
3500 this.reset_qsearch = function()
3502 if (this.gui_objects.qsearchbox)
3503 this.gui_objects.qsearchbox.value = '';
3505 if (this.env.qsearch)
3506 this.abort_request(this.env.qsearch);
3508 this.env.qsearch = null;
3509 this.env.search_request = null;
3510 this.env.search_id = null;
3513 this.sent_successfully = function(type, msg)
3515 this.display_message(msg, type);
3516 // before redirect we need to wait some time for Chrome (#1486177)
3517 window.setTimeout(function(){ ref.list_mailbox(); }, 500);
3521 /*********************************************************/
3522 /********* keyboard live-search methods *********/
3523 /*********************************************************/
3525 // handler for keyboard events on address-fields
3526 this.ksearch_keydown = function(e, obj, props)
3528 if (this.ksearch_timer)
3529 clearTimeout(this.ksearch_timer);
3532 key = rcube_event.get_keycode(e),
3533 mod = rcube_event.get_modifier(e);
3537 case 40: // key down
3538 if (!this.ksearch_pane)
3541 var dir = key==38 ? 1 : 0;
3543 highlight = document.getElementById('rcmksearchSelected');
3545 highlight = this.ksearch_pane.__ul.firstChild;
3548 this.ksearch_select(dir ? highlight.previousSibling : highlight.nextSibling);
3550 return rcube_event.cancel(e);
3553 if (mod == SHIFT_KEY || !this.ksearch_visible()) {
3554 this.ksearch_hide();
3559 if (!this.ksearch_visible())
3562 // insert selected address and hide ksearch pane
3563 this.insert_recipient(this.ksearch_selected);
3564 this.ksearch_hide();
3566 return rcube_event.cancel(e);
3569 this.ksearch_hide();
3574 if (mod != SHIFT_KEY)
3579 this.ksearch_timer = window.setTimeout(function(){ ref.ksearch_get_results(props); }, 200);
3580 this.ksearch_input = obj;
3585 this.ksearch_visible = function()
3587 return (this.ksearch_selected !== null && this.ksearch_selected !== undefined && this.ksearch_value);
3590 this.ksearch_select = function(node)
3592 var current = $('#rcmksearchSelected');
3593 if (current[0] && node) {
3594 current.removeAttr('id').removeClass('selected');
3598 $(node).attr('id', 'rcmksearchSelected').addClass('selected');
3599 this.ksearch_selected = node._rcm_id;
3603 this.insert_recipient = function(id)
3605 if (id === null || !this.env.contacts[id] || !this.ksearch_input)
3609 var inp_value = this.ksearch_input.value,
3610 cpos = this.get_caret_pos(this.ksearch_input),
3611 p = inp_value.lastIndexOf(this.ksearch_value, cpos),
3614 // replace search string with full address
3615 pre = inp_value.substring(0, p),
3616 end = inp_value.substring(p+this.ksearch_value.length, inp_value.length);
3618 this.ksearch_destroy();
3620 // insert all members of a group
3621 if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].id) {
3622 insert += this.env.contacts[id].name + this.env.recipients_delimiter;
3623 this.group2expand = $.extend({}, this.env.contacts[id]);
3624 this.group2expand.input = this.ksearch_input;
3625 this.http_request('mail/group-expand', '_source='+urlencode(this.env.contacts[id].source)+'&_gid='+urlencode(this.env.contacts[id].id), false);
3627 else if (typeof this.env.contacts[id] === 'string') {
3628 insert = this.env.contacts[id] + this.env.recipients_delimiter;
3632 this.ksearch_input.value = pre + insert + end;
3634 // set caret to insert pos
3635 cpos = p+insert.length;
3636 if (this.ksearch_input.setSelectionRange)
3637 this.ksearch_input.setSelectionRange(cpos, cpos);
3640 this.triggerEvent('autocomplete_insert', { field:this.ksearch_input, insert:insert });
3643 this.replace_group_recipients = function(id, recipients)
3645 if (this.group2expand && this.group2expand.id == id) {
3646 this.group2expand.input.value = this.group2expand.input.value.replace(this.group2expand.name, recipients);
3647 this.triggerEvent('autocomplete_insert', { field:this.group2expand.input, insert:recipients });
3648 this.group2expand = null;
3652 // address search processor
3653 this.ksearch_get_results = function(props)
3655 var inp_value = this.ksearch_input ? this.ksearch_input.value : null;
3657 if (inp_value === null)
3660 if (this.ksearch_pane && this.ksearch_pane.is(":visible"))
3661 this.ksearch_pane.hide();
3663 // get string from current cursor pos to last comma
3664 var cpos = this.get_caret_pos(this.ksearch_input),
3665 p = inp_value.lastIndexOf(this.env.recipients_separator, cpos-1),
3666 q = inp_value.substring(p+1, cpos),
3667 min = this.env.autocomplete_min_length,
3668 ac = this.ksearch_data;
3670 // trim query string
3673 // Don't (re-)search if the last results are still active
3674 if (q == this.ksearch_value)
3677 this.ksearch_destroy();
3679 if (q.length && q.length < min) {
3680 if (!this.ksearch_info) {
3681 this.ksearch_info = this.display_message(
3682 this.get_label('autocompletechars').replace('$min', min));
3687 var old_value = this.ksearch_value;
3688 this.ksearch_value = q;
3690 // ...string is empty
3694 // ...new search value contains old one and previous search was not finished or its result was empty
3695 if (old_value && old_value.length && q.indexOf(old_value) == 0 && (!ac || !ac.num) && this.env.contacts && !this.env.contacts.length)
3698 var i, lock, source, xhr, reqid = new Date().getTime(),
3699 threads = props && props.threads ? props.threads : 1,
3700 sources = props && props.sources ? props.sources : [],
3701 action = props && props.action ? props.action : 'mail/autocomplete';
3703 this.ksearch_data = {id: reqid, sources: sources.slice(), action: action,
3704 locks: [], requests: [], num: sources.length};
3706 for (i=0; i<threads; i++) {
3707 source = this.ksearch_data.sources.shift();
3708 if (threads > 1 && source === null)
3711 lock = this.display_message(this.get_label('searching'), 'loading');
3712 xhr = this.http_post(action, '_search='+urlencode(q)+'&_id='+reqid
3713 + (source ? '&_source='+urlencode(source) : ''), lock);
3715 this.ksearch_data.locks.push(lock);
3716 this.ksearch_data.requests.push(xhr);
3720 this.ksearch_query_results = function(results, search, reqid)
3722 // search stopped in meantime?
3723 if (!this.ksearch_value)
3726 // ignore this outdated search response
3727 if (this.ksearch_input && search != this.ksearch_value)
3730 // display search results
3731 var i, len, ul, li, text, init,
3732 value = this.ksearch_value,
3733 data = this.ksearch_data,
3734 maxlen = this.env.autocomplete_max ? this.env.autocomplete_max : 15;
3736 // create results pane if not present
3737 if (!this.ksearch_pane) {
3739 this.ksearch_pane = $('<div>').attr('id', 'rcmKSearchpane')
3740 .css({ position:'absolute', 'z-index':30000 }).append(ul).appendTo(document.body);
3741 this.ksearch_pane.__ul = ul[0];
3744 ul = this.ksearch_pane.__ul;
3746 // remove all search results or add to existing list if parallel search
3747 if (reqid && this.ksearch_pane.data('reqid') == reqid) {
3748 maxlen -= ul.childNodes.length;
3751 this.ksearch_pane.data('reqid', reqid);
3755 this.env.contacts = [];
3756 // move the results pane right under the input box
3757 var pos = $(this.ksearch_input).offset();
3758 this.ksearch_pane.css({ left:pos.left+'px', top:(pos.top + this.ksearch_input.offsetHeight)+'px', display: 'none'});
3761 // add each result line to list
3762 if (results && (len = results.length)) {
3763 for (i=0; i < len && maxlen > 0; i++) {
3764 text = typeof results[i] === 'object' ? results[i].name : results[i];
3765 li = document.createElement('LI');
3766 li.innerHTML = text.replace(new RegExp('('+RegExp.escape(value)+')', 'ig'), '##$1%%').replace(/</g, '<').replace(/>/g, '>').replace(/##([^%]+)%%/g, '<b>$1</b>');
3767 li.onmouseover = function(){ ref.ksearch_select(this); };
3768 li.onmouseup = function(){ ref.ksearch_click(this) };
3769 li._rcm_id = this.env.contacts.length + i;
3775 if (ul.childNodes.length) {
3776 this.ksearch_pane.show();
3778 if (!this.env.contacts.length) {
3779 $('li:first', ul).attr('id', 'rcmksearchSelected').addClass('selected');
3780 this.ksearch_selected = 0;
3785 this.env.contacts = this.env.contacts.concat(results);
3787 // run next parallel search
3788 if (data.id == reqid) {
3790 if (maxlen > 0 && data.sources.length) {
3791 var lock, xhr, source = data.sources.shift();
3793 lock = this.display_message(this.get_label('searching'), 'loading');
3794 xhr = this.http_post(data.action, '_search='+urlencode(value)+'&_id='+reqid
3795 +'&_source='+urlencode(source), lock);
3797 this.ksearch_data.locks.push(lock);
3798 this.ksearch_data.requests.push(xhr);
3802 if (!this.ksearch_msg)
3803 this.ksearch_msg = this.display_message(this.get_label('autocompletemore'));
3804 // abort pending searches
3805 this.ksearch_abort();
3810 this.ksearch_click = function(node)
3812 if (this.ksearch_input)
3813 this.ksearch_input.focus();
3815 this.insert_recipient(node._rcm_id);
3816 this.ksearch_hide();
3819 this.ksearch_blur = function()
3821 if (this.ksearch_timer)
3822 clearTimeout(this.ksearch_timer);
3824 this.ksearch_input = null;
3825 this.ksearch_hide();
3828 this.ksearch_hide = function()
3830 this.ksearch_selected = null;
3831 this.ksearch_value = '';
3833 if (this.ksearch_pane)
3834 this.ksearch_pane.hide();
3836 this.ksearch_destroy();
3839 // Clears autocomplete data/requests
3840 this.ksearch_destroy = function()
3842 this.ksearch_abort();
3844 if (this.ksearch_info)
3845 this.hide_message(this.ksearch_info);
3847 if (this.ksearch_msg)
3848 this.hide_message(this.ksearch_msg);
3850 this.ksearch_data = null;
3851 this.ksearch_info = null;
3852 this.ksearch_msg = null;
3855 // Aborts pending autocomplete requests
3856 this.ksearch_abort = function()
3858 var i, len, ac = this.ksearch_data;
3863 for (i=0, len=ac.locks.length; i<len; i++)
3864 this.abort_request({request: ac.requests[i], lock: ac.locks[i]});
3868 /*********************************************************/
3869 /********* address book methods *********/
3870 /*********************************************************/
3872 this.contactlist_keypress = function(list)
3874 if (list.key_pressed == list.DELETE_KEY)
3875 this.command('delete');
3878 this.contactlist_select = function(list)
3880 if (this.preview_timer)
3881 clearTimeout(this.preview_timer);
3883 var n, id, sid, ref = this, writable = false,
3884 source = this.env.source ? this.env.address_sources[this.env.source] : null;
3886 if (id = list.get_single_selection())
3887 this.preview_timer = window.setTimeout(function(){ ref.load_contact(id, 'show'); }, 200);
3888 else if (this.env.contentframe)
3889 this.show_contentframe(false);
3891 // no source = search result, we'll need to detect if any of
3892 // selected contacts are in writable addressbook to enable edit/delete
3893 if (list.selection.length) {
3895 for (n in list.selection) {
3896 sid = String(list.selection[n]).replace(/^[^-]+-/, '');
3897 if (sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly) {
3904 writable = !source.readonly;
3908 this.enable_command('compose', this.env.group || list.selection.length > 0);
3909 this.enable_command('edit', id && writable);
3910 this.enable_command('delete', list.selection.length && writable);
3915 this.list_contacts = function(src, group, page)
3917 var folder, add_url = '',
3921 src = this.env.source;
3923 if (page && this.current_page == page && src == this.env.source && group == this.env.group)
3926 if (src != this.env.source) {
3927 page = this.env.current_page = 1;
3928 this.reset_qsearch();
3930 else if (group != this.env.group)
3931 page = this.env.current_page = 1;
3933 if (this.env.search_id)
3934 folder = 'S'+this.env.search_id;
3936 folder = group ? 'G'+src+group : src;
3938 this.select_folder(folder);
3940 this.env.source = src;
3941 this.env.group = group;
3943 // load contacts remotely
3944 if (this.gui_objects.contactslist) {
3945 this.list_contacts_remote(src, group, page);
3949 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
3950 target = window.frames[this.env.contentframe];
3951 add_url = '&_framed=1';
3955 add_url += '&_gid='+group;
3957 add_url += '&_page='+page;
3959 // also send search request to get the correct listing
3960 if (this.env.search_request)
3961 add_url += '&_search='+this.env.search_request;
3963 this.set_busy(true, 'loading');
3964 this.location_href(this.env.comm_path + (src ? '&_source='+urlencode(src) : '') + add_url, target);
3967 // send remote request to load contacts list
3968 this.list_contacts_remote = function(src, group, page)
3970 // clear message list first
3971 this.list_contacts_clear();
3973 // send request to server
3974 var url = (src ? '_source='+urlencode(src) : '') + (page ? (src?'&':'') + '_page='+page : ''),
3975 lock = this.set_busy(true, 'loading');
3977 this.env.source = src;
3978 this.env.group = group;
3981 url += '&_gid='+group;
3983 // also send search request to get the right messages
3984 if (this.env.search_request)
3985 url += '&_search='+this.env.search_request;
3987 this.http_request('list', url, lock);
3990 this.list_contacts_clear = function()
3992 this.contact_list.clear(true);
3993 this.show_contentframe(false);
3994 this.enable_command('delete', false);
3995 this.enable_command('compose', this.env.group ? true : false);
3998 // load contact record
3999 this.load_contact = function(cid, action, framed)
4001 var add_url = '', target = window;
4003 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4004 add_url = '&_framed=1';
4005 target = window.frames[this.env.contentframe];
4006 this.show_contentframe(true);
4008 // load dummy content
4010 // unselect selected row(s)
4011 this.contact_list.clear_selection();
4012 this.enable_command('delete', 'compose', false);
4018 if (action && (cid || action=='add') && !this.drag_active) {
4020 add_url += '&_gid='+urlencode(this.env.group);
4022 this.location_href(this.env.comm_path+'&_action='+action
4023 +'&_source='+urlencode(this.env.source)
4024 +'&_cid='+urlencode(cid) + add_url, target, true);
4029 // add/delete member to/from the group
4030 this.group_member_change = function(what, cid, source, gid)
4032 what = what == 'add' ? 'add' : 'del';
4033 var lock = this.display_message(this.get_label(what == 'add' ? 'addingmember' : 'removingmember'), 'loading');
4035 this.http_post('group-'+what+'members', '_cid='+urlencode(cid)
4036 + '&_source='+urlencode(source)
4037 + '&_gid='+urlencode(gid), lock);
4040 // copy a contact to the specified target (group or directory)
4041 this.copy_contact = function(cid, to)
4044 cid = this.contact_list.get_selection().join(',');
4046 if (to.type == 'group' && to.source == this.env.source)
4047 this.group_member_change('add', cid, to.source, to.id);
4048 else if (to.type == 'group' && !this.env.address_sources[to.source].readonly) {
4049 var lock = this.display_message(this.get_label('copyingcontact'), 'loading');
4050 this.http_post('copy', '_cid='+urlencode(cid)
4051 + '&_source='+urlencode(this.env.source)
4052 + '&_to='+urlencode(to.source)
4053 + '&_togid='+urlencode(to.id)
4054 + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
4056 else if (to.id != this.env.source && cid && this.env.address_sources[to.id] && !this.env.address_sources[to.id].readonly) {
4057 var lock = this.display_message(this.get_label('copyingcontact'), 'loading');
4058 this.http_post('copy', '_cid='+urlencode(cid)
4059 + '&_source='+urlencode(this.env.source)
4060 + '&_to='+urlencode(to.id)
4061 + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
4065 this.delete_contacts = function()
4067 var selection = this.contact_list.get_selection(),
4068 undelete = this.env.source && this.env.address_sources[this.env.source].undelete;
4070 // exit if no mailbox specified or if selection is empty
4071 if (!(selection.length || this.env.cid) || (!undelete && !confirm(this.get_label('deletecontactconfirm'))))
4074 var id, n, a_cids = [], qs = '';
4077 a_cids.push(this.env.cid);
4079 for (n=0; n<selection.length; n++) {
4082 this.contact_list.remove_row(id, (n == selection.length-1));
4085 // hide content frame if we delete the currently displayed contact
4086 if (selection.length == 1)
4087 this.show_contentframe(false);
4091 qs += '&_gid='+urlencode(this.env.group);
4093 // also send search request to get the right records from the next page
4094 if (this.env.search_request)
4095 qs += '&_search='+this.env.search_request;
4097 // send request to server
4098 this.http_post('delete', '_cid='+urlencode(a_cids.join(','))
4099 +'&_source='+urlencode(this.env.source)
4100 +'&_from='+(this.env.action ? this.env.action : '')+qs,
4101 this.display_message(this.get_label('contactdeleting'), 'loading'));
4106 // update a contact record in the list
4107 this.update_contact_row = function(cid, cols_arr, newcid, source)
4109 var c, row, list = this.contact_list;
4111 cid = this.html_identifier(cid);
4113 // when in searching mode, concat cid with the source name
4114 if (!list.rows[cid]) {
4115 cid = cid+'-'+source;
4117 newcid = newcid+'-'+source;
4120 if (list.rows[cid] && (row = list.rows[cid].obj)) {
4121 for (c=0; c<cols_arr.length; c++)
4123 $(row.cells[c]).html(cols_arr[c]);
4127 newcid = this.html_identifier(newcid);
4128 row.id = 'rcmrow' + newcid;
4129 list.remove_row(cid);
4131 list.selection[0] = newcid;
4132 row.style.display = '';
4137 // add row to contacts list
4138 this.add_contact_row = function(cid, cols, select)
4140 if (!this.gui_objects.contactslist)
4143 var c, list = this.contact_list,
4144 row = document.createElement('tr');
4146 row.id = 'rcmrow'+this.html_identifier(cid);
4147 row.className = 'contact';
4149 if (list.in_selection(cid))
4150 row.className += ' selected';
4152 // add each submitted col
4154 col = document.createElement('td');
4155 col.className = String(c).toLowerCase();
4156 col.innerHTML = cols[c];
4157 row.appendChild(col);
4160 list.insert_row(row);
4162 this.enable_command('export', list.rowcount > 0);
4165 this.init_contact_form = function()
4167 var ref = this, col;
4169 this.set_photo_actions($('#ff_photo').val());
4171 for (col in this.env.coltypes)
4172 this.init_edit_field(col, null);
4174 $('.contactfieldgroup .row a.deletebutton').click(function() {
4175 ref.delete_edit_field(this);
4179 $('select.addfieldmenu').change(function(e) {
4180 ref.insert_edit_field($(this).val(), $(this).attr('rel'), this);
4181 this.selectedIndex = 0;
4184 // enable date pickers on date fields
4185 if ($.datepicker && this.env.date_format) {
4186 $.datepicker.setDefaults({
4187 dateFormat: this.env.date_format,
4190 yearRange: '-100:+10',
4191 showOtherMonths: true,
4192 selectOtherMonths: true,
4193 monthNamesShort: this.env.month_names,
4194 onSelect: function(dateText) { $(this).focus().val(dateText) }
4196 $('input.datepicker').datepicker();
4199 $("input[type='text']:visible").first().focus();
4202 this.group_create = function()
4204 this.add_input_row('contactgroup');
4207 this.group_rename = function()
4209 if (!this.env.group || !this.gui_objects.folderlist)
4212 if (!this.name_input) {
4213 this.enable_command('list', 'listgroup', false);
4214 this.name_input = $('<input>').attr('type', 'text').val(this.env.contactgroups['G'+this.env.source+this.env.group].name);
4215 this.name_input.bind('keydown', function(e){ return rcmail.add_input_keydown(e); });
4216 this.env.group_renaming = true;
4218 var link, li = this.get_folder_li(this.env.source+this.env.group, 'rcmliG');
4219 if (li && (link = li.firstChild)) {
4220 $(link).hide().before(this.name_input);
4224 this.name_input.select().focus();
4227 this.group_delete = function()
4229 if (this.env.group && confirm(this.get_label('deletegroupconfirm'))) {
4230 var lock = this.set_busy(true, 'groupdeleting');
4231 this.http_post('group-delete', '_source='+urlencode(this.env.source)+'&_gid='+urlencode(this.env.group), lock);
4235 // callback from server upon group-delete command
4236 this.remove_group_item = function(prop)
4238 var li, key = 'G'+prop.source+prop.id;
4239 if ((li = this.get_folder_li(key))) {
4240 this.triggerEvent('group_delete', { source:prop.source, id:prop.id, li:li });
4242 li.parentNode.removeChild(li);
4243 delete this.env.contactfolders[key];
4244 delete this.env.contactgroups[key];
4247 this.list_contacts(prop.source, 0);
4250 // @TODO: maybe it would be better to use popup instead of inserting input to the list?
4251 this.add_input_row = function(type)
4253 if (!this.gui_objects.folderlist)
4256 if (!this.name_input) {
4257 this.name_input = $('<input>').attr('type', 'text').data('tt', type);
4258 this.name_input.bind('keydown', function(e){ return rcmail.add_input_keydown(e); });
4259 this.name_input_li = $('<li>').addClass(type).append(this.name_input);
4261 var li = type == 'contactsearch' ? $('li:last', this.gui_objects.folderlist) : this.get_folder_li(this.env.source);
4262 this.name_input_li.insertAfter(li);
4265 this.name_input.select().focus();
4268 // handler for keyboard events on the input field
4269 this.add_input_keydown = function(e)
4271 var key = rcube_event.get_keycode(e),
4272 input = $(e.target), itype = input.data('tt');
4276 var newname = input.val();
4279 var lock = this.set_busy(true, 'loading');
4281 if (itype == 'contactsearch')
4282 this.http_post('search-create', '_search='+urlencode(this.env.search_request)+'&_name='+urlencode(newname), lock);
4283 else if (this.env.group_renaming)
4284 this.http_post('group-rename', '_source='+urlencode(this.env.source)+'&_gid='+urlencode(this.env.group)+'&_name='+urlencode(newname), lock);
4286 this.http_post('group-create', '_source='+urlencode(this.env.source)+'&_name='+urlencode(newname), lock);
4292 this.reset_add_input();
4297 this.reset_add_input = function()
4299 if (this.name_input) {
4300 if (this.env.group_renaming) {
4301 var li = this.name_input.parent();
4302 li.children().last().show();
4303 this.env.group_renaming = false;
4306 this.name_input.remove();
4308 if (this.name_input_li)
4309 this.name_input_li.remove();
4311 this.name_input = this.name_input_li = null;
4314 this.enable_command('list', 'listgroup', true);
4317 // callback for creating a new contact group
4318 this.insert_contact_group = function(prop)
4320 this.reset_add_input();
4322 prop.type = 'group';
4323 var key = 'G'+prop.source+prop.id,
4324 link = $('<a>').attr('href', '#')
4325 .attr('rel', prop.source+':'+prop.id)
4326 .click(function() { return rcmail.command('listgroup', prop, this); })
4328 li = $('<li>').attr({id: 'rcmli'+this.html_identifier(key), 'class': 'contactgroup'})
4331 this.env.contactfolders[key] = this.env.contactgroups[key] = prop;
4332 this.add_contact_group_row(prop, li);
4334 this.triggerEvent('group_insert', { id:prop.id, source:prop.source, name:prop.name, li:li[0] });
4337 // callback for renaming a contact group
4338 this.update_contact_group = function(prop)
4340 this.reset_add_input();
4342 var key = 'G'+prop.source+prop.id,
4343 li = this.get_folder_li(key),
4346 // group ID has changed, replace link node and identifiers
4347 if (li && prop.newid) {
4348 var newkey = 'G'+prop.source+prop.newid,
4349 newprop = $.extend({}, prop);;
4351 li.id = 'rcmli' + this.html_identifier(newkey);
4352 this.env.contactfolders[newkey] = this.env.contactfolders[key];
4353 this.env.contactfolders[newkey].id = prop.newid;
4354 this.env.group = prop.newid;
4356 delete this.env.contactfolders[key];
4357 delete this.env.contactgroups[key];
4359 newprop.id = prop.newid;
4360 newprop.type = 'group';
4362 link = $('<a>').attr('href', '#')
4363 .attr('rel', prop.source+':'+prop.newid)
4364 .click(function() { return rcmail.command('listgroup', newprop, this); })
4366 $(li).children().replaceWith(link);
4368 // update displayed group name
4369 else if (li && (link = li.firstChild) && link.tagName.toLowerCase() == 'a')
4370 link.innerHTML = prop.name;
4372 this.env.contactfolders[key].name = this.env.contactgroups[key].name = prop.name;
4373 this.add_contact_group_row(prop, $(li), true);
4375 this.triggerEvent('group_update', { id:prop.id, source:prop.source, name:prop.name, li:li[0], newid:prop.newid });
4378 // add contact group row to the list, with sorting
4379 this.add_contact_group_row = function(prop, li, reloc)
4381 var row, name = prop.name.toUpperCase(),
4382 sibling = this.get_folder_li(prop.source),
4383 prefix = 'rcmliG' + this.html_identifier(prop.source);
4385 // When renaming groups, we need to remove it from DOM and insert it in the proper place
4387 row = li.clone(true);
4393 $('li[id^="'+prefix+'"]', this.gui_objects.folderlist).each(function(i, elem) {
4394 if (name >= $(this).text().toUpperCase())
4400 row.insertAfter(sibling);
4403 this.update_group_commands = function()
4405 var source = this.env.source != '' ? this.env.address_sources[this.env.source] : null;
4406 this.enable_command('group-create', (source && source.groups && !source.readonly));
4407 this.enable_command('group-rename', 'group-delete', (source && source.groups && this.env.group && !source.readonly));
4410 this.init_edit_field = function(col, elem)
4413 elem = $('.ff_' + col);
4415 elem.focus(function(){ ref.focus_textfield(this); })
4416 .blur(function(){ ref.blur_textfield(this); })
4417 .each(function(){ this._placeholder = this.title = ref.env.coltypes[col].label; ref.blur_textfield(this); });
4420 this.insert_edit_field = function(col, section, menu)
4422 // just make pre-defined input field visible
4423 var elem = $('#ff_'+col);
4425 elem.show().focus();
4426 $(menu).children('option[value="'+col+'"]').prop('disabled', true);
4429 var lastelem = $('.ff_'+col),
4430 appendcontainer = $('#contactsection'+section+' .contactcontroller'+col);
4432 if (!appendcontainer.length)
4433 appendcontainer = $('<fieldset>').addClass('contactfieldgroup contactcontroller'+col).insertAfter($('#contactsection'+section+' .contactfieldgroup').last());
4435 if (appendcontainer.length && appendcontainer.get(0).nodeName == 'FIELDSET') {
4436 var input, colprop = this.env.coltypes[col],
4437 row = $('<div>').addClass('row'),
4438 cell = $('<div>').addClass('contactfieldcontent data'),
4439 label = $('<div>').addClass('contactfieldlabel label');
4441 if (colprop.subtypes_select)
4442 label.html(colprop.subtypes_select);
4444 label.html(colprop.label);
4446 var name_suffix = colprop.limit != 1 ? '[]' : '';
4447 if (colprop.type == 'text' || colprop.type == 'date') {
4448 input = $('<input>')
4449 .addClass('ff_'+col)
4450 .attr({type: 'text', name: '_'+col+name_suffix, size: colprop.size})
4453 this.init_edit_field(col, input);
4455 if (colprop.type == 'date' && $.datepicker)
4458 else if (colprop.type == 'composite') {
4459 var childcol, cp, first, templ, cols = [], suffices = [];
4460 // read template for composite field order
4461 if ((templ = this.env[col+'_template'])) {
4462 for (var j=0; j < templ.length; j++) {
4463 cols.push(templ[j][1]);
4464 suffices.push(templ[j][2]);
4467 else { // list fields according to appearance in colprop
4468 for (childcol in colprop.childs)
4469 cols.push(childcol);
4472 for (var i=0; i < cols.length; i++) {
4474 cp = colprop.childs[childcol];
4475 input = $('<input>')
4476 .addClass('ff_'+childcol)
4477 .attr({ type: 'text', name: '_'+childcol+name_suffix, size: cp.size })
4479 cell.append(suffices[i] || " ");
4480 this.init_edit_field(childcol, input);
4481 if (!first) first = input;
4483 input = first; // set focus to the first of this composite fields
4485 else if (colprop.type == 'select') {
4486 input = $('<select>')
4487 .addClass('ff_'+col)
4488 .attr('name', '_'+col+name_suffix)
4491 var options = input.attr('options');
4492 options[options.length] = new Option('---', '');
4493 if (colprop.options)
4494 $.each(colprop.options, function(i, val){ options[options.length] = new Option(val, i); });
4498 var delbutton = $('<a href="#del"></a>')
4499 .addClass('contactfieldbutton deletebutton')
4500 .attr({title: this.get_label('delete'), rel: col})
4501 .html(this.env.delbutton)
4502 .click(function(){ ref.delete_edit_field(this); return false })
4505 row.append(label).append(cell).appendTo(appendcontainer.show());
4506 input.first().focus();
4508 // disable option if limit reached
4509 if (!colprop.count) colprop.count = 0;
4510 if (++colprop.count == colprop.limit && colprop.limit)
4511 $(menu).children('option[value="'+col+'"]').prop('disabled', true);
4517 this.delete_edit_field = function(elem)
4519 var col = $(elem).attr('rel'),
4520 colprop = this.env.coltypes[col],
4521 fieldset = $(elem).parents('fieldset.contactfieldgroup'),
4522 addmenu = fieldset.parent().find('select.addfieldmenu');
4524 // just clear input but don't hide the last field
4525 if (--colprop.count <= 0 && colprop.visible)
4526 $(elem).parent().children('input').val('').blur();
4528 $(elem).parents('div.row').remove();
4529 // hide entire fieldset if no more rows
4530 if (!fieldset.children('div.row').length)
4534 // enable option in add-field selector or insert it if necessary
4535 if (addmenu.length) {
4536 var option = addmenu.children('option[value="'+col+'"]');
4538 option.prop('disabled', false);
4540 option = $('<option>').attr('value', col).html(colprop.label).appendTo(addmenu);
4545 this.upload_contact_photo = function(form)
4547 if (form && form.elements._photo.value) {
4548 this.async_upload_form(form, 'upload-photo', function(e) {
4549 rcmail.set_busy(false, null, rcmail.photo_upload_id);
4552 // display upload indicator
4553 this.photo_upload_id = this.set_busy(true, 'uploading');
4557 this.replace_contact_photo = function(id)
4559 var img_src = id == '-del-' ? this.env.photo_placeholder :
4560 this.env.comm_path + '&_action=photo&_source=' + this.env.source + '&_cid=' + this.env.cid + '&_photo=' + id;
4562 this.set_photo_actions(id);
4563 $(this.gui_objects.contactphoto).children('img').attr('src', img_src);
4566 this.photo_upload_end = function()
4568 this.set_busy(false, null, this.photo_upload_id);
4569 delete this.photo_upload_id;
4572 this.set_photo_actions = function(id)
4574 var n, buttons = this.buttons['upload-photo'];
4575 for (n=0; buttons && n < buttons.length; n++)
4576 $('#'+buttons[n].id).html(this.get_label(id == '-del-' ? 'addphoto' : 'replacephoto'));
4578 $('#ff_photo').val(id);
4579 this.enable_command('upload-photo', this.env.coltypes.photo ? true : false);
4580 this.enable_command('delete-photo', this.env.coltypes.photo && id != '-del-');
4583 // load advanced search page
4584 this.advanced_search = function()
4586 var add_url = '&_form=1', target = window;
4588 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4589 add_url += '&_framed=1';
4590 target = window.frames[this.env.contentframe];
4591 this.contact_list.clear_selection();
4594 this.location_href(this.env.comm_path+'&_action=search'+add_url, target, true);
4599 // unselect directory/group
4600 this.unselect_directory = function()
4602 this.select_folder('');
4603 this.enable_command('search-delete', false);
4606 // callback for creating a new saved search record
4607 this.insert_saved_search = function(name, id)
4609 this.reset_add_input();
4612 link = $('<a>').attr('href', '#')
4614 .click(function() { return rcmail.command('listsearch', id, this); })
4616 li = $('<li>').attr({id: 'rcmli' + this.html_identifier(key), 'class': 'contactsearch'})
4618 prop = {name:name, id:id, li:li[0]};
4620 this.add_saved_search_row(prop, li);
4621 this.select_folder('S'+id);
4622 this.enable_command('search-delete', true);
4623 this.env.search_id = id;
4625 this.triggerEvent('abook_search_insert', prop);
4628 // add saved search row to the list, with sorting
4629 this.add_saved_search_row = function(prop, li, reloc)
4631 var row, sibling, name = prop.name.toUpperCase();
4633 // When renaming groups, we need to remove it from DOM and insert it in the proper place
4635 row = li.clone(true);
4641 $('li[class~="contactsearch"]', this.gui_objects.folderlist).each(function(i, elem) {
4643 sibling = this.previousSibling;
4645 if (name >= $(this).text().toUpperCase())
4652 row.insertAfter(sibling);
4654 row.appendTo(this.gui_objects.folderlist);
4657 // creates an input for saved search name
4658 this.search_create = function()
4660 this.add_input_row('contactsearch');
4663 this.search_delete = function()
4665 if (this.env.search_request) {
4666 var lock = this.set_busy(true, 'savedsearchdeleting');
4667 this.http_post('search-delete', '_sid='+urlencode(this.env.search_id), lock);
4671 // callback from server upon search-delete command
4672 this.remove_search_item = function(id)
4674 var li, key = 'S'+id;
4675 if ((li = this.get_folder_li(key))) {
4676 this.triggerEvent('search_delete', { id:id, li:li });
4678 li.parentNode.removeChild(li);
4681 this.env.search_id = null;
4682 this.env.search_request = null;
4683 this.list_contacts_clear();
4684 this.reset_qsearch();
4685 this.enable_command('search-delete', 'search-create', false);
4688 this.listsearch = function(id)
4690 var folder, lock = this.set_busy(true, 'searching');
4692 if (this.contact_list) {
4693 this.list_contacts_clear();
4696 this.reset_qsearch();
4697 this.select_folder('S'+id);
4700 this.env.current_page = 1;
4701 this.http_request('search', '_sid='+urlencode(id), lock);
4705 /*********************************************************/
4706 /********* user settings methods *********/
4707 /*********************************************************/
4709 // preferences section select and load options frame
4710 this.section_select = function(list)
4712 var id = list.get_single_selection(), add_url = '', target = window;
4715 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4716 add_url = '&_framed=1';
4717 target = window.frames[this.env.contentframe];
4719 this.location_href(this.env.comm_path+'&_action=edit-prefs&_section='+id+add_url, target, true);
4725 this.identity_select = function(list)
4728 if (id = list.get_single_selection())
4729 this.load_identity(id, 'edit-identity');
4732 // load identity record
4733 this.load_identity = function(id, action)
4735 if (action=='edit-identity' && (!id || id==this.env.iid))
4738 var add_url = '', target = window;
4740 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4741 add_url = '&_framed=1';
4742 target = window.frames[this.env.contentframe];
4743 document.getElementById(this.env.contentframe).style.visibility = 'inherit';
4746 if (action && (id || action=='add-identity')) {
4747 this.set_busy(true);
4748 this.location_href(this.env.comm_path+'&_action='+action+'&_iid='+id+add_url, target);
4754 this.delete_identity = function(id)
4756 // exit if no mailbox specified or if selection is empty
4757 var selection = this.identity_list.get_selection();
4758 if (!(selection.length || this.env.iid))
4762 id = this.env.iid ? this.env.iid : selection[0];
4764 // append token to request
4765 this.goto_url('delete-identity', '_iid='+id+'&_token='+this.env.request_token, true);
4771 /*********************************************************/
4772 /********* folder manager methods *********/
4773 /*********************************************************/
4775 this.init_subscription_list = function()
4778 this.subscription_list = new rcube_list_widget(this.gui_objects.subscriptionlist,
4779 {multiselect:false, draggable:true, keyboard:false, toggleselect:true});
4780 this.subscription_list.addEventListener('select', function(o){ p.subscription_select(o); });
4781 this.subscription_list.addEventListener('dragstart', function(o){ p.drag_active = true; });
4782 this.subscription_list.addEventListener('dragend', function(o){ p.subscription_move_folder(o); });
4783 this.subscription_list.row_init = function (row) {
4784 row.obj.onmouseover = function() { p.focus_subscription(row.id); };
4785 row.obj.onmouseout = function() { p.unfocus_subscription(row.id); };
4787 this.subscription_list.init();
4789 .mouseover(function(){ p.focus_subscription(this.id); })
4790 .mouseout(function(){ p.unfocus_subscription(this.id); })
4793 this.focus_subscription = function(id)
4796 delim = RegExp.escape(this.env.delimiter),
4797 reg = RegExp('['+delim+']?[^'+delim+']+$');
4799 if (this.drag_active && this.env.mailbox && (row = document.getElementById(id)))
4800 if (this.env.subscriptionrows[id] &&
4801 (folder = this.env.subscriptionrows[id][0]) !== null
4803 if (this.check_droptarget(folder) &&
4804 !this.env.subscriptionrows[this.get_folder_row_id(this.env.mailbox)][2] &&
4805 (folder != this.env.mailbox.replace(reg, '')) &&
4806 (!folder.match(new RegExp('^'+RegExp.escape(this.env.mailbox+this.env.delimiter))))
4808 this.env.dstfolder = folder;
4809 $(row).addClass('droptarget');
4814 this.unfocus_subscription = function(id)
4816 var row = $('#'+id);
4818 this.env.dstfolder = null;
4819 if (this.env.subscriptionrows[id] && row[0])
4820 row.removeClass('droptarget');
4822 $(this.subscription_list.frame).removeClass('droptarget');
4825 this.subscription_select = function(list)
4829 if (list && (id = list.get_single_selection()) &&
4830 (folder = this.env.subscriptionrows['rcmrow'+id])
4832 this.env.mailbox = folder[0];
4833 this.show_folder(folder[0]);
4834 this.enable_command('delete-folder', !folder[2]);
4837 this.env.mailbox = null;
4838 this.show_contentframe(false);
4839 this.enable_command('delete-folder', 'purge', false);
4843 this.subscription_move_folder = function(list)
4845 var delim = RegExp.escape(this.env.delimiter),
4846 reg = RegExp('['+delim+']?[^'+delim+']+$');
4848 if (this.env.mailbox && this.env.dstfolder !== null && (this.env.dstfolder != this.env.mailbox) &&
4849 (this.env.dstfolder != this.env.mailbox.replace(reg, ''))
4851 reg = new RegExp('[^'+delim+']*['+delim+']', 'g');
4852 var basename = this.env.mailbox.replace(reg, ''),
4853 newname = this.env.dstfolder === '' ? basename : this.env.dstfolder+this.env.delimiter+basename;
4855 if (newname != this.env.mailbox) {
4856 this.http_post('rename-folder', '_folder_oldname='+urlencode(this.env.mailbox)+'&_folder_newname='+urlencode(newname), this.set_busy(true, 'foldermoving'));
4857 this.subscription_list.draglayer.hide();
4860 this.drag_active = false;
4861 this.unfocus_subscription(this.get_folder_row_id(this.env.dstfolder));
4864 // tell server to create and subscribe a new mailbox
4865 this.create_folder = function()
4867 this.show_folder('', this.env.mailbox);
4870 // delete a specific mailbox with all its messages
4871 this.delete_folder = function(name)
4873 var id = this.get_folder_row_id(name ? name : this.env.mailbox),
4874 folder = this.env.subscriptionrows[id][0];
4876 if (folder && confirm(this.get_label('deletefolderconfirm'))) {
4877 var lock = this.set_busy(true, 'folderdeleting');
4878 this.http_post('delete-folder', '_mbox='+urlencode(folder), lock);
4882 // Add folder row to the table and initialize it
4883 this.add_folder_row = function (name, display_name, is_protected, subscribed, skip_init, class_name)
4885 if (!this.gui_objects.subscriptionlist)
4888 var row, n, i, tmp, folders, rowid, list = [], slist = [],
4889 tbody = this.gui_objects.subscriptionlist.tBodies[0],
4890 refrow = $('tr', tbody).get(1),
4891 id = 'rcmrow'+((new Date).getTime());
4894 // Refresh page if we don't have a table row to clone
4895 this.goto_url('folders');
4899 // clone a table row if there are existing rows
4900 row = $(refrow).clone(true);
4902 // set ID, reset css class
4904 row.attr('class', class_name);
4907 row.find('td:first').html(display_name);
4909 // update subscription checkbox
4910 $('input[name="_subscribed[]"]', row).val(name)
4911 .prop({checked: subscribed ? true : false, disabled: is_protected ? true : false});
4913 // add to folder/row-ID map
4914 this.env.subscriptionrows[id] = [name, display_name, 0];
4916 // sort folders, to find a place where to insert the row
4918 $.each(this.env.subscriptionrows, function(k,v){ folders.push(v) });
4919 folders.sort(function(a,b){ return a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0) });
4921 for (n in folders) {
4923 if (folders[n][2]) {
4924 slist.push(folders[n][0]);
4925 tmp = folders[n][0]+this.env.delimiter;
4927 // protected folder's child
4928 else if (tmp && folders[n][0].indexOf(tmp) == 0)
4929 slist.push(folders[n][0]);
4932 list.push(folders[n][0]);
4937 // check if subfolder of a protected folder
4938 for (n=0; n<slist.length; n++) {
4939 if (name.indexOf(slist[n]+this.env.delimiter) == 0)
4940 rowid = this.get_folder_row_id(slist[n]);
4943 // find folder position after sorting
4944 for (n=0; !rowid && n<list.length; n++) {
4945 if (n && list[n] == name)
4946 rowid = this.get_folder_row_id(list[n-1]);
4949 // add row to the table
4951 $('#'+rowid).after(row);
4953 row.appendTo(tbody);
4955 // update list widget
4956 this.subscription_list.clear_selection();
4958 this.init_subscription_list();
4961 if (row.scrollIntoView)
4962 row.scrollIntoView();
4967 // replace an existing table row with a new folder line (with subfolders)
4968 this.replace_folder_row = function(oldfolder, newfolder, display_name, is_protected, class_name)
4970 if (!this.gui_objects.subscriptionlist)
4973 var i, n, len, name, dispname, oldrow, tmprow, row, level,
4974 tbody = this.gui_objects.subscriptionlist.tBodies[0],
4975 folders = this.env.subscriptionrows,
4976 id = this.get_folder_row_id(oldfolder),
4977 regex = new RegExp('^'+RegExp.escape(oldfolder)),
4978 subscribed = $('input[name="_subscribed[]"]', $('#'+id)).prop('checked'),
4979 // find subfolders of renamed folder
4980 list = this.get_subfolders(oldfolder);
4982 // replace an existing table row
4983 this._remove_folder_row(id);
4984 row = $(this.add_folder_row(newfolder, display_name, is_protected, subscribed, true, class_name));
4986 // detect tree depth change
4987 if (len = list.length) {
4988 level = (oldfolder.split(this.env.delimiter)).length - (newfolder.split(this.env.delimiter)).length;
4991 // move subfolders to the new branch
4992 for (n=0; n<len; n++) {
4994 name = this.env.subscriptionrows[id][0];
4995 dispname = this.env.subscriptionrows[id][1];
4997 tmprow = oldrow.clone(true);
5001 // update folder index
5002 name = name.replace(regex, newfolder);
5003 $('input[name="_subscribed[]"]', row).val(name);
5004 this.env.subscriptionrows[id][0] = name;
5005 // update the name if level is changed
5008 for (i=level; i>0; i--)
5009 dispname = dispname.replace(/^ /, '');
5012 for (i=level; i<0; i++)
5013 dispname = ' ' + dispname;
5015 row.find('td:first').html(dispname);
5016 this.env.subscriptionrows[id][1] = dispname;
5020 // update list widget
5021 this.init_subscription_list();
5024 // remove the table row of a specific mailbox from the table
5025 this.remove_folder_row = function(folder, subs)
5027 var n, len, list = [], id = this.get_folder_row_id(folder);
5029 // get subfolders if any
5031 list = this.get_subfolders(folder);
5034 this._remove_folder_row(id);
5036 // remove subfolders
5037 for (n=0, len=list.length; n<len; n++)
5038 this._remove_folder_row(list[n]);
5041 this._remove_folder_row = function(id)
5043 this.subscription_list.remove_row(id.replace(/^rcmrow/, ''));
5045 delete this.env.subscriptionrows[id];
5048 this.get_subfolders = function(folder)
5050 var name, list = [],
5051 regex = new RegExp('^'+RegExp.escape(folder)+RegExp.escape(this.env.delimiter)),
5052 row = $('#'+this.get_folder_row_id(folder)).get(0);
5054 while (row = row.nextSibling) {
5056 name = this.env.subscriptionrows[row.id][0];
5057 if (regex.test(name)) {
5068 this.subscribe = function(folder)
5071 var lock = this.display_message(this.get_label('foldersubscribing'), 'loading');
5072 this.http_post('subscribe', '_mbox='+urlencode(folder), lock);
5076 this.unsubscribe = function(folder)
5079 var lock = this.display_message(this.get_label('folderunsubscribing'), 'loading');
5080 this.http_post('unsubscribe', '_mbox='+urlencode(folder), lock);
5084 // helper method to find a specific mailbox row ID
5085 this.get_folder_row_id = function(folder)
5087 var id, folders = this.env.subscriptionrows;
5089 if (folders[id] && folders[id][0] == folder)
5095 // when user select a folder in manager
5096 this.show_folder = function(folder, path, force)
5098 var target = window,
5099 url = '&_action=edit-folder&_mbox='+urlencode(folder);
5102 url += '&_path='+urlencode(path);
5104 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
5105 target = window.frames[this.env.contentframe];
5106 url += '&_framed=1';
5109 if (String(target.location.href).indexOf(url) >= 0 && !force) {
5110 this.show_contentframe(true);
5113 this.location_href(this.env.comm_path+url, target, true);
5117 // disables subscription checkbox (for protected folder)
5118 this.disable_subscription = function(folder)
5120 var id = this.get_folder_row_id(folder);
5122 $('input[name="_subscribed[]"]', $('#'+id)).prop('disabled', true);
5125 this.folder_size = function(folder)
5127 var lock = this.set_busy(true, 'loading');
5128 this.http_post('folder-size', '_mbox='+urlencode(folder), lock);
5131 this.folder_size_update = function(size)
5133 $('#folder-size').replaceWith(size);
5137 /*********************************************************/
5138 /********* GUI functionality *********/
5139 /*********************************************************/
5141 var init_button = function(cmd, prop)
5143 var elm = document.getElementById(prop.id);
5147 var preload = false;
5148 if (prop.type == 'image') {
5149 elm = elm.parentNode;
5156 elm.onmousedown = function(e){ return rcmail.button_sel(this._command, this._id); };
5157 elm.onmouseup = function(e){ return rcmail.button_out(this._command, this._id); };
5159 new Image().src = prop.sel;
5162 elm.onmouseover = function(e){ return rcmail.button_over(this._command, this._id); };
5163 elm.onmouseout = function(e){ return rcmail.button_out(this._command, this._id); };
5165 new Image().src = prop.over;
5169 // enable/disable buttons for page shifting
5170 this.set_page_buttons = function()
5172 this.enable_command('nextpage', 'lastpage', (this.env.pagecount > this.env.current_page));
5173 this.enable_command('previouspage', 'firstpage', (this.env.current_page > 1));
5176 // set event handlers on registered buttons
5177 this.init_buttons = function()
5179 for (var cmd in this.buttons) {
5180 if (typeof cmd !== 'string')
5183 for (var i=0; i< this.buttons[cmd].length; i++) {
5184 init_button(cmd, this.buttons[cmd][i]);
5188 // set active task button
5189 this.set_button(this.task, 'sel');
5192 // set button to a specific state
5193 this.set_button = function(command, state)
5195 var n, button, obj, a_buttons = this.buttons[command],
5196 len = a_buttons ? a_buttons.length : 0;
5198 for (n=0; n<len; n++) {
5199 button = a_buttons[n];
5200 obj = document.getElementById(button.id);
5202 // get default/passive setting of the button
5203 if (obj && button.type=='image' && !button.status) {
5204 button.pas = obj._original_src ? obj._original_src : obj.src;
5205 // respect PNG fix on IE browsers
5206 if (obj.runtimeStyle && obj.runtimeStyle.filter && obj.runtimeStyle.filter.match(/src=['"]([^'"]+)['"]/))
5207 button.pas = RegExp.$1;
5209 else if (obj && !button.status)
5210 button.pas = String(obj.className);
5212 // set image according to button state
5213 if (obj && button.type=='image' && button[state]) {
5214 button.status = state;
5215 obj.src = button[state];
5217 // set class name according to button state
5218 else if (obj && button[state] !== undefined) {
5219 button.status = state;
5220 obj.className = button[state];
5222 // disable/enable input buttons
5223 if (obj && button.type=='input') {
5224 button.status = state;
5225 obj.disabled = !state;
5230 // display a specific alttext
5231 this.set_alttext = function(command, label)
5233 var n, button, obj, link, a_buttons = this.buttons[command],
5234 len = a_buttons ? a_buttons.length : 0;
5236 for (n=0; n<len; n++) {
5237 button = a_buttons[n];
5238 obj = document.getElementById(button.id);
5240 if (button.type == 'image' && obj) {
5241 obj.setAttribute('alt', this.get_label(label));
5242 if ((link = obj.parentNode) && link.tagName.toLowerCase() == 'a')
5243 link.setAttribute('title', this.get_label(label));
5246 obj.setAttribute('title', this.get_label(label));
5250 // mouse over button
5251 this.button_over = function(command, id)
5253 var n, button, obj, a_buttons = this.buttons[command],
5254 len = a_buttons ? a_buttons.length : 0;
5256 for (n=0; n<len; n++) {
5257 button = a_buttons[n];
5258 if (button.id == id && button.status == 'act') {
5259 obj = document.getElementById(button.id);
5260 if (obj && button.over) {
5261 if (button.type == 'image')
5262 obj.src = button.over;
5264 obj.className = button.over;
5270 // mouse down on button
5271 this.button_sel = function(command, id)
5273 var n, button, obj, a_buttons = this.buttons[command],
5274 len = a_buttons ? a_buttons.length : 0;
5276 for (n=0; n<len; n++) {
5277 button = a_buttons[n];
5278 if (button.id == id && button.status == 'act') {
5279 obj = document.getElementById(button.id);
5280 if (obj && button.sel) {
5281 if (button.type == 'image')
5282 obj.src = button.sel;
5284 obj.className = button.sel;
5286 this.buttons_sel[id] = command;
5291 // mouse out of button
5292 this.button_out = function(command, id)
5294 var n, button, obj, a_buttons = this.buttons[command],
5295 len = a_buttons ? a_buttons.length : 0;
5297 for (n=0; n<len; n++) {
5298 button = a_buttons[n];
5299 if (button.id == id && button.status == 'act') {
5300 obj = document.getElementById(button.id);
5301 if (obj && button.act) {
5302 if (button.type == 'image')
5303 obj.src = button.act;
5305 obj.className = button.act;
5311 this.focus_textfield = function(elem)
5313 elem._hasfocus = true;
5314 var $elem = $(elem);
5315 if ($elem.hasClass('placeholder') || $elem.val() == elem._placeholder)
5316 $elem.val('').removeClass('placeholder').attr('spellcheck', true);
5319 this.blur_textfield = function(elem)
5321 elem._hasfocus = false;
5322 var $elem = $(elem);
5323 if (elem._placeholder && (!$elem.val() || $elem.val() == elem._placeholder))
5324 $elem.addClass('placeholder').attr('spellcheck', false).val(elem._placeholder);
5327 // write to the document/window title
5328 this.set_pagetitle = function(title)
5330 if (title && document.title)
5331 document.title = title;
5334 // display a system message, list of types in common.css (below #message definition)
5335 this.display_message = function(msg, type, timeout)
5337 // pass command to parent window
5338 if (this.is_framed())
5339 return parent.rcmail.display_message(msg, type, timeout);
5341 if (!this.gui_objects.message) {
5342 // save message in order to display after page loaded
5343 if (type != 'loading')
5344 this.pending_message = [msg, type, timeout];
5348 type = type ? type : 'notice';
5351 key = this.html_identifier(msg),
5353 id = type + date.getTime();
5356 timeout = this.message_time * (type == 'error' || type == 'warning' ? 2 : 1);
5358 if (type == 'loading') {
5360 timeout = this.env.request_timeout * 1000;
5362 msg = this.get_label('loading');
5365 // The same message is already displayed
5366 if (this.messages[key]) {
5368 if (this.messages[key].obj)
5369 this.messages[key].obj.html(msg);
5370 // store label in stack
5371 if (type == 'loading') {
5372 this.messages[key].labels.push({'id': id, 'msg': msg});
5374 // add element and set timeout
5375 this.messages[key].elements.push(id);
5376 window.setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
5380 // create DOM object and display it
5381 var obj = $('<div>').addClass(type).html(msg).data('key', key),
5382 cont = $(this.gui_objects.message).append(obj).show();
5384 this.messages[key] = {'obj': obj, 'elements': [id]};
5386 if (type == 'loading') {
5387 this.messages[key].labels = [{'id': id, 'msg': msg}];
5390 obj.click(function() { return ref.hide_message(obj); });
5394 window.setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
5398 // make a message to disapear
5399 this.hide_message = function(obj, fade)
5401 // pass command to parent window
5402 if (this.is_framed())
5403 return parent.rcmail.hide_message(obj, fade);
5405 var k, n, i, msg, m = this.messages;
5407 // Hide message by object, don't use for 'loading'!
5408 if (typeof obj === 'object') {
5409 $(obj)[fade?'fadeOut':'hide']();
5410 msg = $(obj).data('key');
5411 if (this.messages[msg])
5412 delete this.messages[msg];
5414 // Hide message by id
5417 for (n in m[k].elements) {
5418 if (m[k] && m[k].elements[n] == obj) {
5419 m[k].elements.splice(n, 1);
5420 // hide DOM element if last instance is removed
5421 if (!m[k].elements.length) {
5422 m[k].obj[fade?'fadeOut':'hide']();
5425 // set pending action label for 'loading' message
5426 else if (k == 'loading') {
5427 for (i in m[k].labels) {
5428 if (m[k].labels[i].id == obj) {
5429 delete m[k].labels[i];
5432 msg = m[k].labels[i].msg;
5443 // mark a mailbox as selected and set environment variable
5444 this.select_folder = function(name, prefix, encode)
5446 if (this.gui_objects.folderlist) {
5447 var current_li, target_li;
5449 if ((current_li = $('li.selected', this.gui_objects.folderlist))) {
5450 current_li.removeClass('selected').addClass('unfocused');
5452 if ((target_li = this.get_folder_li(name, prefix, encode))) {
5453 $(target_li).removeClass('unfocused').addClass('selected');
5456 // trigger event hook
5457 this.triggerEvent('selectfolder', { folder:name, prefix:prefix });
5461 // helper method to find a folder list item
5462 this.get_folder_li = function(name, prefix, encode)
5467 if (this.gui_objects.folderlist) {
5468 name = this.html_identifier(name, encode);
5469 return document.getElementById(prefix+name);
5475 // for reordering column array (Konqueror workaround)
5476 // and for setting some message list global variables
5477 this.set_message_coltypes = function(coltypes, repl)
5479 var list = this.message_list,
5480 thead = list ? list.list.tHead : null,
5481 cell, col, n, len, th, tr;
5483 this.env.coltypes = coltypes;
5485 // replace old column headers
5488 th = document.createElement('thead');
5489 tr = document.createElement('tr');
5491 for (c=0, len=repl.length; c < len; c++) {
5492 cell = document.createElement('td');
5493 cell.innerHTML = repl[c].html;
5494 if (repl[c].id) cell.id = repl[c].id;
5495 if (repl[c].className) cell.className = repl[c].className;
5496 tr.appendChild(cell);
5499 thead.parentNode.replaceChild(th, thead);
5503 for (n=0, len=this.env.coltypes.length; n<len; n++) {
5504 col = this.env.coltypes[n];
5505 if ((cell = thead.rows[0].cells[n]) && (col=='from' || col=='to')) {
5506 cell.id = 'rcm'+col;
5507 // if we have links for sorting, it's a bit more complicated...
5508 if (cell.firstChild && cell.firstChild.tagName.toLowerCase()=='a') {
5509 cell = cell.firstChild;
5510 cell.onclick = function(){ return rcmail.command('sort', this.__col, this); };
5513 cell.innerHTML = this.get_label(col);
5518 this.env.subject_col = null;
5519 this.env.flagged_col = null;
5520 this.env.status_col = null;
5522 if ((n = $.inArray('subject', this.env.coltypes)) >= 0) {
5523 this.env.subject_col = n;
5525 list.subject_col = n;
5527 if ((n = $.inArray('flag', this.env.coltypes)) >= 0)
5528 this.env.flagged_col = n;
5529 if ((n = $.inArray('status', this.env.coltypes)) >= 0)
5530 this.env.status_col = n;
5536 // replace content of row count display
5537 this.set_rowcount = function(text, mbox)
5540 if (mbox && mbox != this.env.mailbox)
5543 $(this.gui_objects.countdisplay).html(text);
5545 // update page navigation buttons
5546 this.set_page_buttons();
5549 // replace content of mailboxname display
5550 this.set_mailboxname = function(content)
5552 if (this.gui_objects.mailboxname && content)
5553 this.gui_objects.mailboxname.innerHTML = content;
5556 // replace content of quota display
5557 this.set_quota = function(content)
5559 if (content && this.gui_objects.quotadisplay) {
5560 if (typeof content === 'object' && content.type == 'image')
5561 this.percent_indicator(this.gui_objects.quotadisplay, content);
5563 $(this.gui_objects.quotadisplay).html(content);
5567 // update the mailboxlist
5568 this.set_unread_count = function(mbox, count, set_title)
5570 if (!this.gui_objects.mailboxlist)
5573 this.env.unread_counts[mbox] = count;
5574 this.set_unread_count_display(mbox, set_title);
5577 // update the mailbox count display
5578 this.set_unread_count_display = function(mbox, set_title)
5580 var reg, link, text_obj, item, mycount, childcount, div;
5582 if (item = this.get_folder_li(mbox, '', true)) {
5583 mycount = this.env.unread_counts[mbox] ? this.env.unread_counts[mbox] : 0;
5584 link = $(item).children('a').eq(0);
5585 text_obj = link.children('span.unreadcount');
5586 if (!text_obj.length && mycount)
5587 text_obj = $('<span>').addClass('unreadcount').appendTo(link);
5588 reg = /\s+\([0-9]+\)$/i;
5591 if ((div = item.getElementsByTagName('div')[0]) &&
5592 div.className.match(/collapsed/)) {
5593 // add children's counters
5594 for (var k in this.env.unread_counts)
5595 if (k.indexOf(mbox + this.env.delimiter) == 0)
5596 childcount += this.env.unread_counts[k];
5599 if (mycount && text_obj.length)
5600 text_obj.html(' ('+mycount+')');
5601 else if (text_obj.length)
5604 // set parent's display
5605 reg = new RegExp(RegExp.escape(this.env.delimiter) + '[^' + RegExp.escape(this.env.delimiter) + ']+$');
5606 if (mbox.match(reg))
5607 this.set_unread_count_display(mbox.replace(reg, ''), false);
5609 // set the right classes
5610 if ((mycount+childcount)>0)
5611 $(item).addClass('unread');
5613 $(item).removeClass('unread');
5616 // set unread count to window title
5617 reg = /^\([0-9]+\)\s+/i;
5618 if (set_title && document.title) {
5620 doc_title = String(document.title);
5622 if (mycount && doc_title.match(reg))
5623 new_title = doc_title.replace(reg, '('+mycount+') ');
5625 new_title = '('+mycount+') '+doc_title;
5627 new_title = doc_title.replace(reg, '');
5629 this.set_pagetitle(new_title);
5633 this.toggle_prefer_html = function(checkbox)
5635 $('#rcmfd_show_images').prop('disabled', !checkbox.checked).val(0);
5638 this.toggle_preview_pane = function(checkbox)
5640 $('#rcmfd_preview_pane_mark_read').prop('disabled', !checkbox.checked);
5643 // display fetched raw headers
5644 this.set_headers = function(content)
5646 if (this.gui_objects.all_headers_row && this.gui_objects.all_headers_box && content)
5647 $(this.gui_objects.all_headers_box).html(content).show();
5650 // display all-headers row and fetch raw message headers
5651 this.load_headers = function(elem)
5653 if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box || !this.env.uid)
5656 $(elem).removeClass('show-headers').addClass('hide-headers');
5657 $(this.gui_objects.all_headers_row).show();
5658 elem.onclick = function() { rcmail.hide_headers(elem); };
5660 // fetch headers only once
5661 if (!this.gui_objects.all_headers_box.innerHTML) {
5662 var lock = this.display_message(this.get_label('loading'), 'loading');
5663 this.http_post('headers', '_uid='+this.env.uid, lock);
5667 // hide all-headers row
5668 this.hide_headers = function(elem)
5670 if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box)
5673 $(elem).removeClass('hide-headers').addClass('show-headers');
5674 $(this.gui_objects.all_headers_row).hide();
5675 elem.onclick = function() { rcmail.load_headers(elem); };
5678 // percent (quota) indicator
5679 this.percent_indicator = function(obj, data)
5684 var limit_high = 80,
5686 width = data.width ? data.width : this.env.indicator_width ? this.env.indicator_width : 100,
5687 height = data.height ? data.height : this.env.indicator_height ? this.env.indicator_height : 14,
5688 quota = data.percent ? Math.abs(parseInt(data.percent)) : 0,
5689 quota_width = parseInt(quota / 100 * width),
5690 pos = $(obj).position();
5692 // workarounds for Opera and Webkit bugs
5693 pos.top = Math.max(0, pos.top);
5694 pos.left = Math.max(0, pos.left);
5696 this.env.indicator_width = width;
5697 this.env.indicator_height = height;
5700 if (quota_width > width) {
5701 quota_width = width;
5706 data.title = this.get_label('quota') + ': ' + data.title;
5709 var main = $('<div>');
5710 main.css({position: 'absolute', top: pos.top, left: pos.left,
5711 width: width + 'px', height: height + 'px', zIndex: 100, lineHeight: height + 'px'})
5712 .attr('title', data.title).addClass('quota_text').html(quota + '%');
5714 var bar1 = $('<div>');
5715 bar1.css({position: 'absolute', top: pos.top + 1, left: pos.left + 1,
5716 width: quota_width + 'px', height: height + 'px', zIndex: 99});
5718 var bar2 = $('<div>');
5719 bar2.css({position: 'absolute', top: pos.top + 1, left: pos.left + 1,
5720 width: width + 'px', height: height + 'px', zIndex: 98})
5721 .addClass('quota_bg');
5723 if (quota >= limit_high) {
5724 main.addClass(' quota_text_high');
5725 bar1.addClass('quota_high');
5727 else if(quota >= limit_mid) {
5728 main.addClass(' quota_text_mid');
5729 bar1.addClass('quota_mid');
5732 main.addClass(' quota_text_low');
5733 bar1.addClass('quota_low');
5736 // replace quota image
5737 $(obj).html('').append(bar1).append(bar2).append(main);
5738 // update #quotaimg title
5739 $('#quotaimg').attr('title', data.title);
5742 /********************************************************/
5743 /********* html to text conversion functions *********/
5744 /********************************************************/
5746 this.html2plain = function(htmlText, id)
5749 url = '?_task=utils&_action=html2text',
5750 lock = this.set_busy(true, 'converting');
5752 this.log('HTTP POST: ' + url);
5754 $.ajax({ type: 'POST', url: url, data: htmlText, contentType: 'application/octet-stream',
5755 error: function(o, status, err) { rcmail.http_error(o, status, err, lock); },
5756 success: function(data) { rcmail.set_busy(false, null, lock); $('#'+id).val(data); rcmail.log(data); }
5760 this.plain2html = function(plain, id)
5762 var lock = this.set_busy(true, 'converting');
5764 plain = plain.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
5765 $('#'+id).val(plain ? '<pre>'+plain+'</pre>' : '');
5767 this.set_busy(false, null, lock);
5771 /********************************************************/
5772 /********* remote request methods *********/
5773 /********************************************************/
5775 // compose a valid url with the given parameters
5776 this.url = function(action, query)
5778 var querystring = typeof query === 'string' ? '&' + query : '';
5780 if (typeof action !== 'string')
5782 else if (!query || typeof query !== 'object')
5786 query._action = action;
5788 query._action = this.env.action;
5790 var base = this.env.comm_path;
5792 // overwrite task name
5793 if (query._action.match(/([a-z]+)\/([a-z0-9-_.]+)/)) {
5794 query._action = RegExp.$2;
5795 base = base.replace(/\_task=[a-z]+/, '_task='+RegExp.$1);
5798 // remove undefined values
5800 for (var k in query) {
5801 if (query[k] !== undefined && query[k] !== null)
5802 param[k] = query[k];
5805 return base + '&' + $.param(param) + querystring;
5808 this.redirect = function(url, lock)
5810 if (lock || lock === null)
5811 this.set_busy(true);
5813 if (this.is_framed())
5814 parent.rcmail.redirect(url, lock);
5816 this.location_href(url, window);
5819 this.goto_url = function(action, query, lock)
5821 this.redirect(this.url(action, query));
5824 this.location_href = function(url, target, frame)
5829 // simulate real link click to force IE to send referer header
5830 if (bw.ie && target == window)
5831 $('<a>').attr('href', url).appendTo(document.body).get(0).click();
5833 target.location.href = url;
5836 // send a http request to the server
5837 this.http_request = function(action, query, lock)
5839 var url = this.url(action, query);
5841 // trigger plugin hook
5842 var result = this.triggerEvent('request'+action, query);
5844 if (result !== undefined) {
5845 // abort if one the handlers returned false
5846 if (result === false)
5852 url += '&_remote=1';
5855 this.log('HTTP GET: ' + url);
5858 type: 'GET', url: url, data: { _unlock:(lock?lock:0) }, dataType: 'json',
5859 success: function(data){ ref.http_response(data); },
5860 error: function(o, status, err) { rcmail.http_error(o, status, err, lock); }
5864 // send a http POST request to the server
5865 this.http_post = function(action, postdata, lock)
5867 var url = this.url(action);
5869 if (postdata && typeof postdata === 'object') {
5870 postdata._remote = 1;
5871 postdata._unlock = (lock ? lock : 0);
5874 postdata += (postdata ? '&' : '') + '_remote=1' + (lock ? '&_unlock='+lock : '');
5876 // trigger plugin hook
5877 var result = this.triggerEvent('request'+action, postdata);
5878 if (result !== undefined) {
5879 // abort if one the handlers returned false
5880 if (result === false)
5887 this.log('HTTP POST: ' + url);
5890 type: 'POST', url: url, data: postdata, dataType: 'json',
5891 success: function(data){ ref.http_response(data); },
5892 error: function(o, status, err) { rcmail.http_error(o, status, err, lock); }
5896 // aborts ajax request
5897 this.abort_request = function(r)
5902 this.set_busy(false, null, r.lock);
5905 // handle HTTP response
5906 this.http_response = function(response)
5911 if (response.unlock)
5912 this.set_busy(false);
5914 this.triggerEvent('responsebefore', {response: response});
5915 this.triggerEvent('responsebefore'+response.action, {response: response});
5919 this.set_env(response.env);
5921 // we have labels to add
5922 if (typeof response.texts === 'object') {
5923 for (var name in response.texts)
5924 if (typeof response.texts[name] === 'string')
5925 this.add_label(name, response.texts[name]);
5928 // if we get javascript code from server -> execute it
5929 if (response.exec) {
5930 this.log(response.exec);
5931 eval(response.exec);
5934 // execute callback functions of plugins
5935 if (response.callbacks && response.callbacks.length) {
5936 for (var i=0; i < response.callbacks.length; i++)
5937 this.triggerEvent(response.callbacks[i][0], response.callbacks[i][1]);
5940 // process the response data according to the sent action
5941 switch (response.action) {
5943 if (this.task == 'addressbook') {
5944 var sid, uid = this.contact_list.get_selection(), writable = false;
5946 if (uid && this.contact_list.rows[uid]) {
5947 // search results, get source ID from record ID
5948 if (this.env.source == '') {
5949 sid = String(uid).replace(/^[^-]+-/, '');
5950 writable = sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly;
5953 writable = !this.env.address_sources[this.env.source].readonly;
5956 this.enable_command('compose', (uid && this.contact_list.rows[uid]));
5957 this.enable_command('delete', 'edit', writable);
5958 this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
5962 if (this.env.action == 'show') {
5963 // re-enable commands on move/delete error
5964 this.enable_command(this.env.message_commands, true);
5965 if (!this.env.list_post)
5966 this.enable_command('reply-list', false);
5968 else if (this.task == 'addressbook') {
5969 this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
5974 if (this.task == 'mail') {
5975 if (!this.env.messagecount) {
5976 // clear preview pane content
5977 if (this.env.contentframe)
5978 this.show_contentframe(false);
5979 // disable commands useless when mailbox is empty
5980 this.enable_command(this.env.message_commands, 'purge', 'expunge',
5981 'select-all', 'select-none', 'sort', 'expand-all', 'expand-unread', 'collapse-all', false);
5983 if (this.message_list)
5984 this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
5988 case 'check-recent':
5991 this.env.qsearch = null;
5993 if (this.task == 'mail') {
5994 this.enable_command('show', 'expunge', 'select-all', 'select-none', 'sort', (this.env.messagecount > 0));
5995 this.enable_command('purge', this.purge_mailbox_test());
5996 this.enable_command('expand-all', 'expand-unread', 'collapse-all', this.env.threading && this.env.messagecount);
5998 if (response.action == 'list' || response.action == 'search') {
5999 this.msglist_select(this.message_list);
6000 this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
6003 else if (this.task == 'addressbook') {
6004 this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
6006 if (response.action == 'list' || response.action == 'search') {
6007 this.enable_command('search-create', this.env.source == '');
6008 this.enable_command('search-delete', this.env.search_id);
6009 this.update_group_commands();
6010 this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
6016 if (response.unlock)
6017 this.hide_message(response.unlock);
6019 this.triggerEvent('responseafter', {response: response});
6020 this.triggerEvent('responseafter'+response.action, {response: response});
6023 // handle HTTP request errors
6024 this.http_error = function(request, status, err, lock)
6026 var errmsg = request.statusText;
6028 this.set_busy(false, null, lock);
6031 if (request.status && errmsg)
6032 this.display_message(this.get_label('servererror') + ' (' + errmsg + ')', 'error');
6035 // post the given form to a hidden iframe
6036 this.async_upload_form = function(form, action, onload)
6038 var ts = new Date().getTime(),
6039 frame_name = 'rcmupload'+ts;
6041 // upload progress support
6042 if (this.env.upload_progress_name) {
6043 var fname = this.env.upload_progress_name,
6044 field = $('input[name='+fname+']', form);
6046 if (!field.length) {
6047 field = $('<input>').attr({type: 'hidden', name: fname});
6048 field.prependTo(form);
6054 // have to do it this way for IE
6055 // otherwise the form will be posted to a new window
6057 var html = '<iframe name="'+frame_name+'" src="program/blank.gif" style="width:0;height:0;visibility:hidden;"></iframe>';
6058 document.body.insertAdjacentHTML('BeforeEnd', html);
6060 else { // for standards-compilant browsers
6061 var frame = document.createElement('iframe');
6062 frame.name = frame_name;
6063 frame.style.border = 'none';
6064 frame.style.width = 0;
6065 frame.style.height = 0;
6066 frame.style.visibility = 'hidden';
6067 document.body.appendChild(frame);
6070 // handle upload errors, parsing iframe content in onload
6071 $(frame_name).bind('load', {ts:ts}, onload);
6075 action: this.url(action, { _id:this.env.compose_id||'', _uploadid:ts }),
6077 .attr(form.encoding ? 'encoding' : 'enctype', 'multipart/form-data')
6083 // starts interval for keep-alive/check-recent signal
6084 this.start_keepalive = function()
6087 clearInterval(this._int);
6089 if (this.env.keep_alive && !this.env.framed && this.task == 'mail' && this.gui_objects.mailboxlist)
6090 this._int = setInterval(function(){ ref.check_for_recent(false); }, this.env.keep_alive * 1000);
6091 else if (this.env.keep_alive && !this.env.framed && this.task != 'login' && this.env.action != 'print')
6092 this._int = setInterval(function(){ ref.keep_alive(); }, this.env.keep_alive * 1000);
6095 // sends keep-alive signal
6096 this.keep_alive = function()
6099 this.http_request('keep-alive');
6102 // sends request to check for recent messages
6103 this.check_for_recent = function(refresh)
6108 var lock, addurl = '_mbox=' + urlencode(this.env.mailbox);
6111 lock = this.set_busy(true, 'checkingmail');
6112 addurl += '&_refresh=1';
6113 // reset check-recent interval
6114 this.start_keepalive();
6117 if (this.gui_objects.messagelist)
6118 addurl += '&_list=1';
6119 if (this.gui_objects.quotadisplay)
6120 addurl += '&_quota=1';
6121 if (this.env.search_request)
6122 addurl += '&_search=' + this.env.search_request;
6124 this.http_request('check-recent', addurl, lock);
6128 /********************************************************/
6129 /********* helper methods *********/
6130 /********************************************************/
6132 // check if we're in show mode or if we have a unique selection
6133 // and return the message uid
6134 this.get_single_uid = function()
6136 return this.env.uid ? this.env.uid : (this.message_list ? this.message_list.get_single_selection() : null);
6139 // same as above but for contacts
6140 this.get_single_cid = function()
6142 return this.env.cid ? this.env.cid : (this.contact_list ? this.contact_list.get_single_selection() : null);
6145 // gets cursor position
6146 this.get_caret_pos = function(obj)
6148 if (obj.selectionEnd !== undefined)
6149 return obj.selectionEnd;
6150 else if (document.selection && document.selection.createRange) {
6151 var range = document.selection.createRange();
6152 if (range.parentElement()!=obj)
6155 var gm = range.duplicate();
6156 if (obj.tagName == 'TEXTAREA')
6157 gm.moveToElementText(obj);
6159 gm.expand('textedit');
6161 gm.setEndPoint('EndToStart', range);
6162 var p = gm.text.length;
6164 return p<=obj.value.length ? p : -1;
6167 return obj.value.length;
6170 // moves cursor to specified position
6171 this.set_caret_pos = function(obj, pos)
6173 if (obj.setSelectionRange)
6174 obj.setSelectionRange(pos, pos);
6175 else if (obj.createTextRange) {
6176 var range = obj.createTextRange();
6177 range.collapse(true);
6178 range.moveEnd('character', pos);
6179 range.moveStart('character', pos);
6184 // disable/enable all fields of a form
6185 this.lock_form = function(form, lock)
6187 if (!form || !form.elements)
6193 this.disabled_form_elements = [];
6195 for (n=0, len=form.elements.length; n<len; n++) {
6196 elm = form.elements[n];
6198 if (elm.type == 'hidden')
6200 // remember which elem was disabled before lock
6201 if (lock && elm.disabled)
6202 this.disabled_form_elements.push(elm);
6203 // check this.disabled_form_elements before inArray() as a workaround for FF5 bug
6204 // http://bugs.jquery.com/ticket/9873
6205 else if (lock || (this.disabled_form_elements && $.inArray(elm, this.disabled_form_elements)<0))
6206 elm.disabled = lock;
6210 } // end object rcube_webmail
6213 // some static methods
6214 rcube_webmail.long_subject_title = function(elem, indent)
6217 var $elem = $(elem);
6218 if ($elem.width() + indent * 15 > $elem.parent().width())
6219 elem.title = $elem.html();
6223 rcube_webmail.long_subject_title_ie = function(elem, indent)
6226 var $elem = $(elem),
6227 txt = $.trim($elem.text()),
6228 tmp = $('<span>').text(txt)
6229 .css({'position': 'absolute', 'float': 'left', 'visibility': 'hidden',
6230 'font-size': $elem.css('font-size'), 'font-weight': $elem.css('font-weight')})
6231 .appendTo($('body')),
6235 if (w + indent * 15 > $elem.width())
6240 // copy event engine prototype
6241 rcube_webmail.prototype.addEventListener = rcube_event_engine.prototype.addEventListener;
6242 rcube_webmail.prototype.removeEventListener = rcube_event_engine.prototype.removeEventListener;
6243 rcube_webmail.prototype.triggerEvent = rcube_event_engine.prototype.triggerEvent;