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 5952 2012-03-03 13:20:14Z 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 the folder if one of its childs is currently selected
1411 // don't select if it's virtual (#1488346)
1412 if (this.env.mailbox.indexOf(name + this.env.delimiter) == 0 && !$(li).hasClass('virtual'))
1413 this.command('list', name);
1418 // Work around a bug in IE6 and IE7, see #1485309
1419 if (bw.ie6 || bw.ie7) {
1420 var siblings = li.nextSibling ? li.nextSibling.getElementsByTagName('ul') : null;
1421 if (siblings && siblings.length && (li = siblings[0]) && li.style && li.style.display != 'none') {
1422 li.style.display = 'none';
1423 li.style.display = '';
1427 this.command('save-pref', { name: 'collapsed_folders', value: this.env.collapsed_folders });
1428 this.set_unread_count_display(name, false);
1431 this.doc_mouse_up = function(e)
1433 var model, list, li, id;
1435 // ignore event if jquery UI dialog is open
1436 if ($(rcube_event.get_target(e)).closest('.ui-dialog, .ui-widget-overlay').length)
1439 if (list = this.message_list) {
1440 if (!rcube_mouse_is_over(e, list.list.parentNode))
1444 model = this.env.mailboxes;
1446 else if (list = this.contact_list) {
1447 if (!rcube_mouse_is_over(e, list.list.parentNode))
1451 model = this.env.contactfolders;
1453 else if (this.ksearch_value) {
1454 this.ksearch_blur();
1457 // handle mouse release when dragging
1458 if (this.drag_active && model && this.env.last_folder_target) {
1459 var target = model[this.env.last_folder_target];
1461 $(this.get_folder_li(this.env.last_folder_target)).removeClass('droptarget');
1462 this.env.last_folder_target = null;
1463 list.draglayer.hide();
1465 if (!this.drag_menu(e, target))
1466 this.command('moveto', target);
1469 // reset 'pressed' buttons
1470 if (this.buttons_sel) {
1471 for (id in this.buttons_sel)
1472 if (typeof id !== 'function')
1473 this.button_out(this.buttons_sel[id], id);
1474 this.buttons_sel = {};
1478 this.click_on_list = function(e)
1480 if (this.gui_objects.qsearchbox)
1481 this.gui_objects.qsearchbox.blur();
1483 if (this.message_list)
1484 this.message_list.focus();
1485 else if (this.contact_list)
1486 this.contact_list.focus();
1491 this.msglist_select = function(list)
1493 if (this.preview_timer)
1494 clearTimeout(this.preview_timer);
1495 if (this.preview_read_timer)
1496 clearTimeout(this.preview_read_timer);
1498 var selected = list.get_single_selection() != null;
1500 this.enable_command(this.env.message_commands, selected);
1502 // Hide certain command buttons when Drafts folder is selected
1503 if (this.env.mailbox == this.env.drafts_mailbox)
1504 this.enable_command('reply', 'reply-all', 'reply-list', 'forward', 'forward-attachment', false);
1505 // Disable reply-list when List-Post header is not set
1507 var msg = this.env.messages[list.get_single_selection()];
1509 this.enable_command('reply-list', false);
1512 // Multi-message commands
1513 this.enable_command('delete', 'moveto', 'copy', 'mark', (list.selection.length > 0 ? true : false));
1515 // reset all-pages-selection
1516 if (selected || (list.selection.length && list.selection.length != list.rowcount))
1517 this.select_all_mode = false;
1519 // start timer for message preview (wait for double click)
1520 if (selected && this.env.contentframe && !list.multi_selecting && !this.dummy_select)
1521 this.preview_timer = window.setTimeout(function(){ ref.msglist_get_preview(); }, 200);
1522 else if (this.env.contentframe)
1523 this.show_contentframe(false);
1526 // This allow as to re-select selected message and display it in preview frame
1527 this.msglist_click = function(list)
1529 if (list.multi_selecting || !this.env.contentframe)
1532 if (list.get_single_selection() && window.frames && window.frames[this.env.contentframe]) {
1533 if (window.frames[this.env.contentframe].location.href.indexOf(this.env.blankpage)>=0) {
1534 if (this.preview_timer)
1535 clearTimeout(this.preview_timer);
1536 if (this.preview_read_timer)
1537 clearTimeout(this.preview_read_timer);
1538 this.preview_timer = window.setTimeout(function(){ ref.msglist_get_preview(); }, 200);
1543 this.msglist_dbl_click = function(list)
1545 if (this.preview_timer)
1546 clearTimeout(this.preview_timer);
1548 if (this.preview_read_timer)
1549 clearTimeout(this.preview_read_timer);
1551 var uid = list.get_single_selection();
1552 if (uid && this.env.mailbox == this.env.drafts_mailbox)
1553 this.goto_url('compose', '_draft_uid='+uid+'&_mbox='+urlencode(this.env.mailbox), true);
1555 this.show_message(uid, false, false);
1558 this.msglist_keypress = function(list)
1560 if (list.modkey == CONTROL_KEY)
1563 if (list.key_pressed == list.ENTER_KEY)
1564 this.command('show');
1565 else if (list.key_pressed == list.DELETE_KEY || list.key_pressed == list.BACKSPACE_KEY)
1566 this.command('delete');
1567 else if (list.key_pressed == 33)
1568 this.command('previouspage');
1569 else if (list.key_pressed == 34)
1570 this.command('nextpage');
1573 this.msglist_get_preview = function()
1575 var uid = this.get_single_uid();
1576 if (uid && this.env.contentframe && !this.drag_active)
1577 this.show_message(uid, false, true);
1578 else if (this.env.contentframe)
1579 this.show_contentframe(false);
1582 this.msglist_expand = function(row)
1584 if (this.env.messages[row.uid])
1585 this.env.messages[row.uid].expanded = row.expanded;
1588 this.msglist_set_coltypes = function(list)
1590 var i, found, name, cols = list.list.tHead.rows[0].cells;
1592 this.env.coltypes = [];
1594 for (i=0; i<cols.length; i++)
1595 if (cols[i].id && cols[i].id.match(/^rcm/)) {
1596 name = cols[i].id.replace(/^rcm/, '');
1597 this.env.coltypes.push(name == 'to' ? 'from' : name);
1600 if ((found = $.inArray('flag', this.env.coltypes)) >= 0)
1601 this.env.flagged_col = found;
1603 if ((found = $.inArray('subject', this.env.coltypes)) >= 0)
1604 this.env.subject_col = found;
1606 this.command('save-pref', { name: 'list_cols', value: this.env.coltypes, session: 'list_attrib/columns' });
1609 this.check_droptarget = function(id)
1611 var allow = false, copy = false;
1613 if (this.task == 'mail')
1614 allow = (this.env.mailboxes[id] && this.env.mailboxes[id].id != this.env.mailbox && !this.env.mailboxes[id].virtual);
1615 else if (this.task == 'settings')
1616 allow = (id != this.env.mailbox);
1617 else if (this.task == 'addressbook') {
1618 if (id != this.env.source && this.env.contactfolders[id]) {
1619 if (this.env.contactfolders[id].type == 'group') {
1620 var target_abook = this.env.contactfolders[id].source;
1621 allow = this.env.contactfolders[id].id != this.env.group && !this.env.contactfolders[target_abook].readonly;
1622 copy = target_abook != this.env.source;
1625 allow = !this.env.contactfolders[id].readonly;
1631 return allow ? (copy ? 2 : 1) : 0;
1635 /*********************************************************/
1636 /********* (message) list functionality *********/
1637 /*********************************************************/
1639 this.init_message_row = function(row)
1641 var expando, self = this, uid = row.uid,
1642 status_icon = (this.env.status_col != null ? 'status' : 'msg') + 'icn' + row.uid;
1644 if (uid && this.env.messages[uid])
1645 $.extend(row, this.env.messages[uid]);
1647 // set eventhandler to status icon
1648 if (row.icon = document.getElementById(status_icon)) {
1649 row.icon._row = row.obj;
1650 row.icon.onmousedown = function(e) { self.command('toggle_status', this); rcube_event.cancel(e); };
1653 // save message icon position too
1654 if (this.env.status_col != null)
1655 row.msgicon = document.getElementById('msgicn'+row.uid);
1657 row.msgicon = row.icon;
1659 // set eventhandler to flag icon, if icon found
1660 if (this.env.flagged_col != null && (row.flagicon = document.getElementById('flagicn'+row.uid))) {
1661 row.flagicon._row = row.obj;
1662 row.flagicon.onmousedown = function(e) { self.command('toggle_flag', this); rcube_event.cancel(e); };
1665 if (!row.depth && row.has_children && (expando = document.getElementById('rcmexpando'+row.uid))) {
1666 row.expando = expando;
1667 expando.onmousedown = function(e) { return self.expand_message_row(e, uid); };
1670 this.triggerEvent('insertrow', { uid:uid, row:row });
1673 // create a table row in the message list
1674 this.add_message_row = function(uid, cols, flags, attop)
1676 if (!this.gui_objects.messagelist || !this.message_list)
1679 // Prevent from adding messages from different folder (#1487752)
1680 if (flags.mbox != this.env.mailbox && !flags.skip_mbox_check)
1683 if (!this.env.messages[uid])
1684 this.env.messages[uid] = {};
1686 // merge flags over local message object
1687 $.extend(this.env.messages[uid], {
1688 deleted: flags.deleted?1:0,
1689 replied: flags.answered?1:0,
1690 unread: !flags.seen?1:0,
1691 forwarded: flags.forwarded?1:0,
1692 flagged: flags.flagged?1:0,
1693 has_children: flags.has_children?1:0,
1694 depth: flags.depth?flags.depth:0,
1695 unread_children: flags.unread_children?flags.unread_children:0,
1696 parent_uid: flags.parent_uid?flags.parent_uid:0,
1697 selected: this.select_all_mode || this.message_list.in_selection(uid),
1700 // flags from plugins
1701 flags: flags.extra_flags
1704 var c, n, col, html, tree = '', expando = '',
1705 list = this.message_list,
1707 message = this.env.messages[uid],
1708 css_class = 'message'
1709 + (!flags.seen ? ' unread' : '')
1710 + (flags.deleted ? ' deleted' : '')
1711 + (flags.flagged ? ' flagged' : '')
1712 + (flags.unread_children && flags.seen && !this.env.autoexpand_threads ? ' unroot' : '')
1713 + (message.selected ? ' selected' : ''),
1714 // for performance use DOM instead of jQuery here
1715 row = document.createElement('tr');
1717 row.id = 'rcmrow'+uid;
1718 row.className = css_class;
1720 // message status icons
1721 css_class = 'msgicon';
1722 if (this.env.status_col === null) {
1723 css_class += ' status';
1725 css_class += ' deleted';
1726 else if (!flags.seen)
1727 css_class += ' unread';
1728 else if (flags.unread_children > 0)
1729 css_class += ' unreadchildren';
1732 css_class += ' replied';
1733 if (flags.forwarded)
1734 css_class += ' forwarded';
1737 if (message.selected && !list.in_selection(uid))
1738 list.selection.push(uid);
1741 if (this.env.threading) {
1742 if (message.depth) {
1743 // This assumes that div width is hardcoded to 15px,
1744 tree += '<span id="rcmtab' + uid + '" class="branch" style="width:' + (message.depth * 15) + 'px;"> </span>';
1746 if ((rows[message.parent_uid] && rows[message.parent_uid].expanded === false)
1747 || ((this.env.autoexpand_threads == 0 || this.env.autoexpand_threads == 2) &&
1748 (!rows[message.parent_uid] || !rows[message.parent_uid].expanded))
1750 row.style.display = 'none';
1751 message.expanded = false;
1754 message.expanded = true;
1756 else if (message.has_children) {
1757 if (message.expanded === undefined && (this.env.autoexpand_threads == 1 || (this.env.autoexpand_threads == 2 && message.unread_children))) {
1758 message.expanded = true;
1761 expando = '<div id="rcmexpando' + uid + '" class="' + (message.expanded ? 'expanded' : 'collapsed') + '"> </div>';
1765 tree += '<span id="msgicn'+uid+'" class="'+css_class+'"> </span>';
1767 // build subject link
1768 if (!bw.ie && cols.subject) {
1769 var action = flags.mbox == this.env.drafts_mailbox ? 'compose' : 'show';
1770 var uid_param = flags.mbox == this.env.drafts_mailbox ? '_draft_uid' : '_uid';
1771 cols.subject = '<a href="./?_task=mail&_action='+action+'&_mbox='+urlencode(flags.mbox)+'&'+uid_param+'='+uid+'"'+
1772 ' onclick="return rcube_event.cancel(event)" onmouseover="rcube_webmail.long_subject_title(this,'+(message.depth+1)+')">'+cols.subject+'</a>';
1775 // add each submitted col
1776 for (n in this.env.coltypes) {
1777 c = this.env.coltypes[n];
1778 col = document.createElement('td');
1779 col.className = String(c).toLowerCase();
1782 css_class = (flags.flagged ? 'flagged' : 'unflagged');
1783 html = '<span id="flagicn'+uid+'" class="'+css_class+'"> </span>';
1785 else if (c == 'attachment') {
1786 if (/application\/|multipart\/m/.test(flags.ctype))
1787 html = '<span class="attachment"> </span>';
1788 else if (/multipart\/report/.test(flags.ctype))
1789 html = '<span class="report"> </span>';
1793 else if (c == 'status') {
1795 css_class = 'deleted';
1796 else if (!flags.seen)
1797 css_class = 'unread';
1798 else if (flags.unread_children > 0)
1799 css_class = 'unreadchildren';
1801 css_class = 'msgicon';
1802 html = '<span id="statusicn'+uid+'" class="'+css_class+'"> </span>';
1804 else if (c == 'threads')
1806 else if (c == 'subject') {
1808 col.onmouseover = function() { rcube_webmail.long_subject_title_ie(this, message.depth+1); };
1809 html = tree + cols[c];
1811 else if (c == 'priority') {
1812 if (flags.prio > 0 && flags.prio < 6)
1813 html = '<span class="prio'+flags.prio+'"> </span>';
1820 col.innerHTML = html;
1822 row.appendChild(col);
1825 list.insert_row(row, attop);
1828 if (attop && this.env.pagesize && list.rowcount > this.env.pagesize) {
1829 var uid = list.get_last_row();
1830 list.remove_row(uid);
1831 list.clear_selection(uid);
1835 this.set_list_sorting = function(sort_col, sort_order)
1837 // set table header class
1838 $('#rcm'+this.env.sort_col).removeClass('sorted'+(this.env.sort_order.toUpperCase()));
1840 $('#rcm'+sort_col).addClass('sorted'+sort_order);
1842 this.env.sort_col = sort_col;
1843 this.env.sort_order = sort_order;
1846 this.set_list_options = function(cols, sort_col, sort_order, threads)
1848 var update, add_url = '';
1850 if (sort_col === undefined)
1851 sort_col = this.env.sort_col;
1853 sort_order = this.env.sort_order;
1855 if (this.env.sort_col != sort_col || this.env.sort_order != sort_order) {
1857 this.set_list_sorting(sort_col, sort_order);
1860 if (this.env.threading != threads) {
1862 add_url += '&_threads=' + threads;
1865 if (cols && cols.length) {
1866 // make sure new columns are added at the end of the list
1867 var i, idx, name, newcols = [], oldcols = this.env.coltypes;
1868 for (i=0; i<oldcols.length; i++) {
1869 name = oldcols[i] == 'to' ? 'from' : oldcols[i];
1870 idx = $.inArray(name, cols);
1876 for (i=0; i<cols.length; i++)
1878 newcols.push(cols[i]);
1880 if (newcols.join() != oldcols.join()) {
1882 add_url += '&_cols=' + newcols.join(',');
1887 this.list_mailbox('', '', sort_col+'_'+sort_order, add_url);
1890 // when user doble-clicks on a row
1891 this.show_message = function(id, safe, preview)
1896 var target = window,
1897 action = preview ? 'preview': 'show',
1898 url = '&_action='+action+'&_uid='+id+'&_mbox='+urlencode(this.env.mailbox);
1900 if (preview && this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
1901 target = window.frames[this.env.contentframe];
1902 url += '&_framed=1';
1908 // also send search request to get the right messages
1909 if (this.env.search_request)
1910 url += '&_search='+this.env.search_request;
1912 if (action == 'preview' && String(target.location.href).indexOf(url) >= 0)
1913 this.show_contentframe(true);
1915 this.location_href(this.env.comm_path+url, target, true);
1917 // mark as read and change mbox unread counter
1918 if (action == 'preview' && this.message_list && this.message_list.rows[id] && this.message_list.rows[id].unread && this.env.preview_pane_mark_read >= 0) {
1919 this.preview_read_timer = window.setTimeout(function() {
1920 ref.set_message(id, 'unread', false);
1921 ref.update_thread_root(id, 'read');
1922 if (ref.env.unread_counts[ref.env.mailbox]) {
1923 ref.env.unread_counts[ref.env.mailbox] -= 1;
1924 ref.set_unread_count(ref.env.mailbox, ref.env.unread_counts[ref.env.mailbox], ref.env.mailbox == 'INBOX');
1926 if (ref.env.preview_pane_mark_read > 0)
1927 ref.http_post('mark', '_uid='+id+'&_flag=read&_quiet=1');
1928 }, this.env.preview_pane_mark_read * 1000);
1933 this.show_contentframe = function(show)
1936 if (this.env.contentframe && (frm = $('#'+this.env.contentframe)) && frm.length) {
1937 if (!show && (win = window.frames[this.env.contentframe])) {
1938 if (win.location && win.location.href.indexOf(this.env.blankpage)<0)
1939 win.location.href = this.env.blankpage;
1941 else if (!bw.safari && !bw.konq)
1942 frm[show ? 'show' : 'hide']();
1945 if (!show && this.busy)
1946 this.set_busy(false, null, this.env.frame_lock);
1949 this.lock_frame = function()
1951 if (!this.env.frame_lock)
1952 (this.is_framed() ? parent.rcmail : this).env.frame_lock = this.set_busy(true, 'loading');
1955 // list a specific page
1956 this.list_page = function(page)
1959 page = this.env.current_page+1;
1960 else if (page == 'last')
1961 page = this.env.pagecount;
1962 else if (page == 'prev' && this.env.current_page > 1)
1963 page = this.env.current_page-1;
1964 else if (page == 'first' && this.env.current_page > 1)
1967 if (page > 0 && page <= this.env.pagecount) {
1968 this.env.current_page = page;
1970 if (this.task == 'mail')
1971 this.list_mailbox(this.env.mailbox, page);
1972 else if (this.task == 'addressbook')
1973 this.list_contacts(this.env.source, this.env.group, page);
1977 // list messages of a specific mailbox using filter
1978 this.filter_mailbox = function(filter)
1980 var lock = this.set_busy(true, 'searching');
1982 this.clear_message_list();
1985 this.env.current_page = 1;
1986 this.http_request('search', this.search_params(false, filter), lock);
1989 // list messages of a specific mailbox
1990 this.list_mailbox = function(mbox, page, sort, add_url)
1992 var url = '', target = window;
1995 mbox = this.env.mailbox ? this.env.mailbox : 'INBOX';
2000 // add sort to url if set
2002 url += '&_sort=' + sort;
2004 // also send search request to get the right messages
2005 if (this.env.search_request)
2006 url += '&_search='+this.env.search_request;
2008 // set page=1 if changeing to another mailbox
2009 if (this.env.mailbox != mbox) {
2011 this.env.current_page = page;
2012 this.select_all_mode = false;
2015 // unselect selected messages and clear the list and message data
2016 this.clear_message_list();
2018 if (mbox != this.env.mailbox || (mbox == this.env.mailbox && !page && !sort))
2019 url += '&_refresh=1';
2021 this.select_folder(mbox, '', true);
2022 this.env.mailbox = mbox;
2024 // load message list remotely
2025 if (this.gui_objects.messagelist) {
2026 this.list_mailbox_remote(mbox, page, url);
2030 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
2031 target = window.frames[this.env.contentframe];
2032 url += '&_framed=1';
2035 // load message list to target frame/window
2037 this.set_busy(true, 'loading');
2038 this.location_href(this.env.comm_path+'&_mbox='+urlencode(mbox)+(page ? '&_page='+page : '')+url, target);
2042 this.clear_message_list = function()
2044 this.env.messages = {};
2045 this.last_selected = 0;
2047 this.show_contentframe(false);
2048 if (this.message_list)
2049 this.message_list.clear(true);
2052 // send remote request to load message list
2053 this.list_mailbox_remote = function(mbox, page, add_url)
2055 // clear message list first
2056 this.message_list.clear();
2058 // send request to server
2059 var url = '_mbox='+urlencode(mbox)+(page ? '&_page='+page : ''),
2060 lock = this.set_busy(true, 'loading');
2061 this.http_request('list', url+add_url, lock);
2064 // removes messages that doesn't exists from list selection array
2065 this.update_selection = function()
2067 var selected = this.message_list.selection,
2068 rows = this.message_list.rows,
2072 if (rows[selected[i]])
2073 selection.push(selected[i]);
2075 this.message_list.selection = selection;
2078 // expand all threads with unread children
2079 this.expand_unread = function()
2081 var r, tbody = this.gui_objects.messagelist.tBodies[0],
2082 new_row = tbody.firstChild;
2085 if (new_row.nodeType == 1 && (r = this.message_list.rows[new_row.uid]) && r.unread_children) {
2086 this.message_list.expand_all(r);
2087 this.set_unread_children(r.uid);
2089 new_row = new_row.nextSibling;
2094 // thread expanding/collapsing handler
2095 this.expand_message_row = function(e, uid)
2097 var row = this.message_list.rows[uid];
2099 // handle unread_children mark
2100 row.expanded = !row.expanded;
2101 this.set_unread_children(uid);
2102 row.expanded = !row.expanded;
2104 this.message_list.expand_row(e, uid);
2107 // message list expanding
2108 this.expand_threads = function()
2110 if (!this.env.threading || !this.env.autoexpand_threads || !this.message_list)
2113 switch (this.env.autoexpand_threads) {
2114 case 2: this.expand_unread(); break;
2115 case 1: this.message_list.expand_all(); break;
2119 // Initializes threads indicators/expanders after list update
2120 this.init_threads = function(roots, mbox)
2123 if (mbox && mbox != this.env.mailbox)
2126 for (var n=0, len=roots.length; n<len; n++)
2127 this.add_tree_icons(roots[n]);
2128 this.expand_threads();
2131 // adds threads tree icons to the list (or specified thread)
2132 this.add_tree_icons = function(root)
2134 var i, l, r, n, len, pos, tmp = [], uid = [],
2135 row, rows = this.message_list.rows;
2138 row = rows[root] ? rows[root].obj : null;
2140 row = this.message_list.list.tBodies[0].firstChild;
2143 if (row.nodeType == 1 && (r = rows[row.uid])) {
2145 for (i=tmp.length-1; i>=0; i--) {
2146 len = tmp[i].length;
2147 if (len > r.depth) {
2148 pos = len - r.depth;
2149 if (!(tmp[i][pos] & 2))
2150 tmp[i][pos] = tmp[i][pos] ? tmp[i][pos]+2 : 2;
2152 else if (len == r.depth) {
2153 if (!(tmp[i][0] & 2))
2160 tmp.push(new Array(r.depth));
2161 tmp[tmp.length-1][0] = 1;
2167 this.set_tree_icons(uid[i], tmp[i]);
2172 if (root && row != rows[root].obj)
2176 row = row.nextSibling;
2181 this.set_tree_icons(uid[i], tmp[i]);
2186 // adds tree icons to specified message row
2187 this.set_tree_icons = function(uid, tree)
2189 var i, divs = [], html = '', len = tree.length;
2191 for (i=0; i<len; i++) {
2193 divs.push({'class': 'l3', width: 15});
2194 else if (tree[i] > 1)
2195 divs.push({'class': 'l2', width: 15});
2196 else if (tree[i] > 0)
2197 divs.push({'class': 'l1', width: 15});
2199 else if (divs.length && !divs[divs.length-1]['class'])
2200 divs[divs.length-1].width += 15;
2202 divs.push({'class': null, width: 15});
2205 for (i=divs.length-1; i>=0; i--) {
2206 if (divs[i]['class'])
2207 html += '<div class="tree '+divs[i]['class']+'" />';
2209 html += '<div style="width:'+divs[i].width+'px" />';
2213 $('#rcmtab'+uid).html(html);
2216 // update parent in a thread
2217 this.update_thread_root = function(uid, flag)
2219 if (!this.env.threading)
2222 var root = this.message_list.find_root(uid);
2227 var p = this.message_list.rows[root];
2229 if (flag == 'read' && p.unread_children) {
2230 p.unread_children--;
2232 else if (flag == 'unread' && p.has_children) {
2233 // unread_children may be undefined
2234 p.unread_children = p.unread_children ? p.unread_children + 1 : 1;
2240 this.set_message_icon(root);
2241 this.set_unread_children(root);
2244 // update thread indicators for all messages in a thread below the specified message
2245 // return number of removed/added root level messages
2246 this.update_thread = function (uid)
2248 if (!this.env.threading)
2251 var r, parent, count = 0,
2252 rows = this.message_list.rows,
2254 depth = rows[uid].depth,
2257 if (!row.depth) // root message: decrease roots count
2259 else if (row.unread) {
2260 // update unread_children for thread root
2261 parent = this.message_list.find_root(uid);
2262 rows[parent].unread_children--;
2263 this.set_unread_children(parent);
2266 parent = row.parent_uid;
2269 row = row.obj.nextSibling;
2271 if (row.nodeType == 1 && (r = rows[row.uid])) {
2272 if (!r.depth || r.depth <= depth)
2275 r.depth--; // move left
2276 // reset width and clear the content of a tab, icons will be added later
2277 $('#rcmtab'+r.uid).width(r.depth * 15).html('');
2278 if (!r.depth) { // a new root
2279 count++; // increase roots count
2281 if (r.has_children) {
2282 // replace 'leaf' with 'collapsed'
2283 $('#rcmrow'+r.uid+' '+'.leaf:first')
2284 .attr('id', 'rcmexpando' + r.uid)
2285 .attr('class', (r.obj.style.display != 'none' ? 'expanded' : 'collapsed'))
2286 .bind('mousedown', {uid:r.uid, p:this},
2287 function(e) { return e.data.p.expand_message_row(e, e.data.uid); });
2289 r.unread_children = 0;
2292 // show if it was hidden
2293 if (r.obj.style.display == 'none')
2297 if (r.depth == depth)
2298 r.parent_uid = parent;
2299 if (r.unread && roots.length)
2300 roots[roots.length-1].unread_children++;
2303 row = row.nextSibling;
2306 // update unread_children for roots
2307 for (var i=0; i<roots.length; i++)
2308 this.set_unread_children(roots[i].uid);
2313 this.delete_excessive_thread_rows = function()
2315 var rows = this.message_list.rows,
2316 tbody = this.message_list.list.tBodies[0],
2317 row = tbody.firstChild,
2318 cnt = this.env.pagesize + 1;
2321 if (row.nodeType == 1 && (r = rows[row.uid])) {
2322 if (!r.depth && cnt)
2326 this.message_list.remove_row(row.uid);
2328 row = row.nextSibling;
2333 this.set_message_icon = function(uid)
2336 row = this.message_list.rows[uid];
2342 css_class = 'msgicon';
2344 css_class += ' deleted';
2345 else if (row.unread)
2346 css_class += ' unread';
2347 else if (row.unread_children)
2348 css_class += ' unreadchildren';
2349 if (row.msgicon == row.icon) {
2351 css_class += ' replied';
2353 css_class += ' forwarded';
2354 css_class += ' status';
2357 row.icon.className = css_class;
2360 if (row.msgicon && row.msgicon != row.icon) {
2361 css_class = 'msgicon';
2362 if (!row.unread && row.unread_children)
2363 css_class += ' unreadchildren';
2365 css_class += ' replied';
2367 css_class += ' forwarded';
2369 row.msgicon.className = css_class;
2373 css_class = (row.flagged ? 'flagged' : 'unflagged');
2374 row.flagicon.className = css_class;
2378 // set message status
2379 this.set_message_status = function(uid, flag, status)
2381 var row = this.message_list.rows[uid];
2386 if (flag == 'unread')
2387 row.unread = status;
2388 else if(flag == 'deleted')
2389 row.deleted = status;
2390 else if (flag == 'replied')
2391 row.replied = status;
2392 else if (flag == 'forwarded')
2393 row.forwarded = status;
2394 else if (flag == 'flagged')
2395 row.flagged = status;
2398 // set message row status, class and icon
2399 this.set_message = function(uid, flag, status)
2401 var row = this.message_list.rows[uid];
2407 this.set_message_status(uid, flag, status);
2409 var rowobj = $(row.obj);
2411 if (row.unread && !rowobj.hasClass('unread'))
2412 rowobj.addClass('unread');
2413 else if (!row.unread && rowobj.hasClass('unread'))
2414 rowobj.removeClass('unread');
2416 if (row.deleted && !rowobj.hasClass('deleted'))
2417 rowobj.addClass('deleted');
2418 else if (!row.deleted && rowobj.hasClass('deleted'))
2419 rowobj.removeClass('deleted');
2421 if (row.flagged && !rowobj.hasClass('flagged'))
2422 rowobj.addClass('flagged');
2423 else if (!row.flagged && rowobj.hasClass('flagged'))
2424 rowobj.removeClass('flagged');
2426 this.set_unread_children(uid);
2427 this.set_message_icon(uid);
2430 // sets unroot (unread_children) class of parent row
2431 this.set_unread_children = function(uid)
2433 var row = this.message_list.rows[uid];
2438 if (!row.unread && row.unread_children && !row.expanded)
2439 $(row.obj).addClass('unroot');
2441 $(row.obj).removeClass('unroot');
2444 // copy selected messages to the specified mailbox
2445 this.copy_messages = function(mbox)
2447 if (mbox && typeof mbox === 'object')
2450 // exit if current or no mailbox specified or if selection is empty
2451 if (!mbox || mbox == this.env.mailbox || (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length)))
2455 lock = this.display_message(this.get_label('copyingmessage'), 'loading'),
2456 add_url = '&_target_mbox='+urlencode(mbox)+'&_from='+(this.env.action ? this.env.action : '');
2459 a_uids[0] = this.env.uid;
2461 var selection = this.message_list.get_selection();
2462 for (var n in selection) {
2463 a_uids.push(selection[n]);
2467 add_url += '&_uid='+this.uids_to_list(a_uids);
2469 // send request to server
2470 this.http_post('copy', '_mbox='+urlencode(this.env.mailbox)+add_url, lock);
2473 // move selected messages to the specified mailbox
2474 this.move_messages = function(mbox)
2476 if (mbox && typeof mbox === 'object')
2479 // exit if current or no mailbox specified or if selection is empty
2480 if (!mbox || mbox == this.env.mailbox || (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length)))
2484 add_url = '&_target_mbox='+urlencode(mbox)+'&_from='+(this.env.action ? this.env.action : '');
2486 // show wait message
2487 if (this.env.action == 'show') {
2488 lock = this.set_busy(true, 'movingmessage');
2491 this.show_contentframe(false);
2493 // Hide message command buttons until a message is selected
2494 this.enable_command(this.env.message_commands, false);
2496 this._with_selected_messages('moveto', lock, add_url);
2499 // delete selected messages from the current mailbox
2500 this.delete_messages = function()
2502 var uid, i, len, trash = this.env.trash_mailbox,
2503 list = this.message_list,
2504 selection = list ? $.merge([], list.get_selection()) : [];
2506 // exit if no mailbox specified or if selection is empty
2507 if (!this.env.uid && !selection.length)
2510 // also select childs of collapsed rows
2511 for (i=0, len=selection.length; i<len; i++) {
2513 if (list.rows[uid].has_children && !list.rows[uid].expanded)
2514 list.select_childs(uid);
2517 // if config is set to flag for deletion
2518 if (this.env.flag_for_deletion) {
2519 this.mark_message('delete');
2522 // if there isn't a defined trash mailbox or we are in it
2523 // @TODO: we should check if defined trash mailbox exists
2524 else if (!trash || this.env.mailbox == trash)
2525 this.permanently_remove_messages();
2526 // if there is a trash mailbox defined and we're not currently in it
2528 // if shift was pressed delete it immediately
2529 if (list && list.modkey == SHIFT_KEY) {
2530 if (confirm(this.get_label('deletemessagesconfirm')))
2531 this.permanently_remove_messages();
2534 this.move_messages(trash);
2540 // delete the selected messages permanently
2541 this.permanently_remove_messages = function()
2543 // exit if no mailbox specified or if selection is empty
2544 if (!this.env.uid && (!this.message_list || !this.message_list.get_selection().length))
2547 this.show_contentframe(false);
2548 this._with_selected_messages('delete', false, '&_from='+(this.env.action ? this.env.action : ''));
2551 // Send a specifc moveto/delete request with UIDs of all selected messages
2553 this._with_selected_messages = function(action, lock, add_url)
2555 var a_uids = [], count = 0, msg;
2558 a_uids[0] = this.env.uid;
2560 var n, id, root, roots = [],
2561 selection = this.message_list.get_selection();
2563 for (n=0, len=selection.length; n<len; n++) {
2567 if (this.env.threading) {
2568 count += this.update_thread(id);
2569 root = this.message_list.find_root(id);
2570 if (root != id && $.inArray(root, roots) < 0) {
2574 this.message_list.remove_row(id, (this.env.display_next && n == selection.length-1));
2576 // make sure there are no selected rows
2577 if (!this.env.display_next)
2578 this.message_list.clear_selection();
2579 // update thread tree icons
2580 for (n=0, len=roots.length; n<len; n++) {
2581 this.add_tree_icons(roots[n]);
2585 // also send search request to get the right messages
2586 if (this.env.search_request)
2587 add_url += '&_search='+this.env.search_request;
2589 if (this.env.display_next && this.env.next_uid)
2590 add_url += '&_next_uid='+this.env.next_uid;
2593 add_url += '&_count='+(count*-1);
2595 // remove threads from the end of the list
2596 this.delete_excessive_thread_rows();
2598 add_url += '&_uid='+this.uids_to_list(a_uids);
2601 msg = action == 'moveto' ? 'movingmessage' : 'deletingmessage';
2602 lock = this.display_message(this.get_label(msg), 'loading');
2605 // send request to server
2606 this.http_post(action, '_mbox='+urlencode(this.env.mailbox)+add_url, lock);
2609 // set a specific flag to one or more messages
2610 this.mark_message = function(flag, uid)
2612 var a_uids = [], r_uids = [], len, n, id,
2613 selection = this.message_list ? this.message_list.get_selection() : [];
2617 else if (this.env.uid)
2618 a_uids[0] = this.env.uid;
2619 else if (this.message_list) {
2620 for (n=0, len=selection.length; n<len; n++) {
2621 a_uids.push(selection[n]);
2625 if (!this.message_list)
2628 for (n=0, len=a_uids.length; n<len; n++) {
2630 if ((flag=='read' && this.message_list.rows[id].unread)
2631 || (flag=='unread' && !this.message_list.rows[id].unread)
2632 || (flag=='delete' && !this.message_list.rows[id].deleted)
2633 || (flag=='undelete' && this.message_list.rows[id].deleted)
2634 || (flag=='flagged' && !this.message_list.rows[id].flagged)
2635 || (flag=='unflagged' && this.message_list.rows[id].flagged))
2642 if (!r_uids.length && !this.select_all_mode)
2648 this.toggle_read_status(flag, r_uids);
2652 this.toggle_delete_status(r_uids);
2656 this.toggle_flagged_status(flag, a_uids);
2661 // set class to read/unread
2662 this.toggle_read_status = function(flag, a_uids)
2664 var i, len = a_uids.length,
2665 url = '_uid='+this.uids_to_list(a_uids)+'&_flag='+flag,
2666 lock = this.display_message(this.get_label('markingmessage'), 'loading');
2668 // mark all message rows as read/unread
2669 for (i=0; i<len; i++)
2670 this.set_message(a_uids[i], 'unread', (flag=='unread' ? true : false));
2672 // also send search request to get the right messages
2673 if (this.env.search_request)
2674 url += '&_search='+this.env.search_request;
2676 this.http_post('mark', url, lock);
2678 for (i=0; i<len; i++)
2679 this.update_thread_root(a_uids[i], flag);
2682 // set image to flagged or unflagged
2683 this.toggle_flagged_status = function(flag, a_uids)
2685 var i, len = a_uids.length,
2686 url = '_uid='+this.uids_to_list(a_uids)+'&_flag='+flag,
2687 lock = this.display_message(this.get_label('markingmessage'), 'loading');
2689 // mark all message rows as flagged/unflagged
2690 for (i=0; i<len; i++)
2691 this.set_message(a_uids[i], 'flagged', (flag=='flagged' ? true : false));
2693 // also send search request to get the right messages
2694 if (this.env.search_request)
2695 url += '&_search='+this.env.search_request;
2697 this.http_post('mark', url, lock);
2700 // mark all message rows as deleted/undeleted
2701 this.toggle_delete_status = function(a_uids)
2703 var len = a_uids.length,
2704 i, uid, all_deleted = true,
2705 rows = this.message_list ? this.message_list.rows : [];
2708 if (!rows.length || (rows[a_uids[0]] && !rows[a_uids[0]].deleted))
2709 this.flag_as_deleted(a_uids);
2711 this.flag_as_undeleted(a_uids);
2716 for (i=0; i<len; i++) {
2718 if (rows[uid] && !rows[uid].deleted) {
2719 all_deleted = false;
2725 this.flag_as_undeleted(a_uids);
2727 this.flag_as_deleted(a_uids);
2732 this.flag_as_undeleted = function(a_uids)
2734 var i, len=a_uids.length,
2735 url = '_uid='+this.uids_to_list(a_uids)+'&_flag=undelete',
2736 lock = this.display_message(this.get_label('markingmessage'), 'loading');
2738 for (i=0; i<len; i++)
2739 this.set_message(a_uids[i], 'deleted', false);
2741 // also send search request to get the right messages
2742 if (this.env.search_request)
2743 url += '&_search='+this.env.search_request;
2745 this.http_post('mark', url, lock);
2749 this.flag_as_deleted = function(a_uids)
2753 rows = this.message_list ? this.message_list.rows : [],
2756 for (var i=0, len=a_uids.length; i<len; i++) {
2759 if (rows[uid].unread)
2760 r_uids[r_uids.length] = uid;
2762 if (this.env.skip_deleted) {
2763 count += this.update_thread(uid);
2764 this.message_list.remove_row(uid, (this.env.display_next && i == this.message_list.selection.length-1));
2767 this.set_message(uid, 'deleted', true);
2771 // make sure there are no selected rows
2772 if (this.env.skip_deleted && this.message_list) {
2773 if(!this.env.display_next)
2774 this.message_list.clear_selection();
2776 add_url += '&_count='+(count*-1);
2778 // remove threads from the end of the list
2779 this.delete_excessive_thread_rows();
2782 add_url = '&_from='+(this.env.action ? this.env.action : ''),
2783 lock = this.display_message(this.get_label('markingmessage'), 'loading');
2787 add_url += '&_ruid='+this.uids_to_list(r_uids);
2789 if (this.env.skip_deleted) {
2790 if (this.env.display_next && this.env.next_uid)
2791 add_url += '&_next_uid='+this.env.next_uid;
2794 // also send search request to get the right messages
2795 if (this.env.search_request)
2796 add_url += '&_search='+this.env.search_request;
2798 this.http_post('mark', '_uid='+this.uids_to_list(a_uids)+'&_flag=delete'+add_url, lock);
2802 // flag as read without mark request (called from backend)
2803 // argument should be a coma-separated list of uids
2804 this.flag_deleted_as_read = function(uids)
2806 var icn_src, uid, i, len,
2807 rows = this.message_list ? this.message_list.rows : [];
2809 uids = String(uids).split(',');
2811 for (i=0, len=uids.length; i<len; i++) {
2814 this.set_message(uid, 'unread', false);
2818 // Converts array of message UIDs to comma-separated list for use in URL
2819 // with select_all mode checking
2820 this.uids_to_list = function(uids)
2822 return this.select_all_mode ? '*' : uids.join(',');
2826 /*********************************************************/
2827 /********* mailbox folders methods *********/
2828 /*********************************************************/
2830 this.expunge_mailbox = function(mbox)
2832 var lock, url = '_mbox='+urlencode(mbox);
2834 // lock interface if it's the active mailbox
2835 if (mbox == this.env.mailbox) {
2836 lock = this.set_busy(true, 'loading');
2837 url += '&_reload=1';
2838 if (this.env.search_request)
2839 url += '&_search='+this.env.search_request;
2842 // send request to server
2843 this.http_post('expunge', url, lock);
2846 this.purge_mailbox = function(mbox)
2849 url = '_mbox='+urlencode(mbox);
2851 if (!confirm(this.get_label('purgefolderconfirm')))
2854 // lock interface if it's the active mailbox
2855 if (mbox == this.env.mailbox) {
2856 lock = this.set_busy(true, 'loading');
2857 url += '&_reload=1';
2860 // send request to server
2861 this.http_post('purge', url, lock);
2864 // test if purge command is allowed
2865 this.purge_mailbox_test = function()
2867 return (this.env.messagecount && (this.env.mailbox == this.env.trash_mailbox || this.env.mailbox == this.env.junk_mailbox
2868 || this.env.mailbox.match('^' + RegExp.escape(this.env.trash_mailbox) + RegExp.escape(this.env.delimiter))
2869 || this.env.mailbox.match('^' + RegExp.escape(this.env.junk_mailbox) + RegExp.escape(this.env.delimiter))));
2873 /*********************************************************/
2874 /********* login form methods *********/
2875 /*********************************************************/
2877 // handler for keyboard events on the _user field
2878 this.login_user_keyup = function(e)
2880 var key = rcube_event.get_keycode(e);
2881 var passwd = $('#rcmloginpwd');
2884 if (key == 13 && passwd.length && !passwd.val()) {
2886 return rcube_event.cancel(e);
2893 /*********************************************************/
2894 /********* message compose methods *********/
2895 /*********************************************************/
2897 // init message compose form: set focus and eventhandlers
2898 this.init_messageform = function()
2900 if (!this.gui_objects.messageform)
2903 var input_from = $("[name='_from']"),
2904 input_to = $("[name='_to']"),
2905 input_subject = $("input[name='_subject']"),
2906 input_message = $("[name='_message']").get(0),
2907 html_mode = $("input[name='_is_html']").val() == '1',
2908 ac_fields = ['cc', 'bcc', 'replyto', 'followupto'],
2911 // configure parallel autocompletion
2912 if (this.env.autocomplete_threads > 0) {
2914 threads: this.env.autocomplete_threads,
2915 sources: this.env.autocomplete_sources
2919 // init live search events
2920 this.init_address_input_events(input_to, ac_props);
2921 for (var i in ac_fields) {
2922 this.init_address_input_events($("[name='_"+ac_fields[i]+"']"), ac_props);
2926 this.set_caret_pos(input_message, this.env.top_posting ? 0 : $(input_message).val().length);
2927 // add signature according to selected identity
2928 // if we have HTML editor, signature is added in callback
2929 if (input_from.prop('type') == 'select-one' && $("input[name='_draft_saveid']").val() == '') {
2930 this.change_identity(input_from[0]);
2934 if (input_to.val() == '')
2936 else if (input_subject.val() == '')
2937 input_subject.focus();
2938 else if (input_message)
2939 input_message.focus();
2941 this.env.compose_focus_elem = document.activeElement;
2943 // get summary of all field values
2944 this.compose_field_hash(true);
2946 // start the auto-save timer
2947 this.auto_save_start();
2950 this.init_address_input_events = function(obj, props)
2952 this.env.recipients_delimiter = this.env.recipients_separator + ' ';
2954 obj[bw.ie || bw.safari || bw.chrome ? 'keydown' : 'keypress'](function(e) { return ref.ksearch_keydown(e, this, props); })
2955 .attr('autocomplete', 'off');
2958 // checks the input fields before sending a message
2959 this.check_compose_input = function(cmd)
2961 // check input fields
2962 var ed, input_to = $("[name='_to']"),
2963 input_cc = $("[name='_cc']"),
2964 input_bcc = $("[name='_bcc']"),
2965 input_from = $("[name='_from']"),
2966 input_subject = $("[name='_subject']"),
2967 input_message = $("[name='_message']");
2969 // check sender (if have no identities)
2970 if (input_from.prop('type') == 'text' && !rcube_check_email(input_from.val(), true)) {
2971 alert(this.get_label('nosenderwarning'));
2976 // check for empty recipient
2977 var recipients = input_to.val() ? input_to.val() : (input_cc.val() ? input_cc.val() : input_bcc.val());
2978 if (!rcube_check_email(recipients.replace(/^\s+/, '').replace(/[\s,;]+$/, ''), true)) {
2979 alert(this.get_label('norecipientwarning'));
2984 // check if all files has been uploaded
2985 for (var key in this.env.attachments) {
2986 if (typeof this.env.attachments[key] === 'object' && !this.env.attachments[key].complete) {
2987 alert(this.get_label('notuploadedwarning'));
2992 // display localized warning for missing subject
2993 if (input_subject.val() == '') {
2994 var myprompt = $('<div class="prompt">').html('<div class="message">' + this.get_label('nosubjectwarning') + '</div>').appendTo(document.body);
2995 var prompt_value = $('<input>').attr('type', 'text').attr('size', 30).appendTo(myprompt).val(this.get_label('nosubject'));
2998 buttons[this.get_label('cancel')] = function(){
2999 input_subject.focus();
3000 $(this).dialog('close');
3002 buttons[this.get_label('sendmessage')] = function(){
3003 input_subject.val(prompt_value.val());
3004 $(this).dialog('close');
3005 ref.command(cmd, { nocheck:true }); // repeat command which triggered this
3012 close: function(event, ui) { $(this).remove() }
3014 prompt_value.select();
3018 // Apply spellcheck changes if spell checker is active
3019 this.stop_spellchecking();
3022 ed = tinyMCE.get(this.env.composebody);
3024 // check for empty body
3025 if (!ed && input_message.val() == '' && !confirm(this.get_label('nobodywarning'))) {
3026 input_message.focus();
3030 if (!ed.getContent() && !confirm(this.get_label('nobodywarning'))) {
3034 // move body from html editor to textarea (just to be sure, #1485860)
3035 tinyMCE.triggerSave();
3041 this.toggle_editor = function(props)
3043 if (props.mode == 'html') {
3044 this.display_spellcheck_controls(false);
3045 this.plain2html($('#'+props.id).val(), props.id);
3046 tinyMCE.execCommand('mceAddControl', false, props.id);
3049 var thisMCE = tinyMCE.get(props.id), existingHtml;
3050 if (thisMCE.plugins.spellchecker && thisMCE.plugins.spellchecker.active)
3051 thisMCE.execCommand('mceSpellCheck', false);
3053 if (existingHtml = thisMCE.getContent()) {
3054 if (!confirm(this.get_label('editorwarning'))) {
3057 this.html2plain(existingHtml, props.id);
3059 tinyMCE.execCommand('mceRemoveControl', false, props.id);
3060 this.display_spellcheck_controls(true);
3066 this.stop_spellchecking = function()
3069 if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody))) {
3070 if (ed.plugins.spellchecker && ed.plugins.spellchecker.active)
3071 ed.execCommand('mceSpellCheck');
3073 else if ((ed = this.env.spellcheck) && !this.spellcheck_ready) {
3074 $(ed.spell_span).trigger('click');
3075 this.set_spellcheck_state('ready');
3079 this.display_spellcheck_controls = function(vis)
3081 if (this.env.spellcheck) {
3082 // stop spellchecking process
3084 this.stop_spellchecking();
3086 $(this.env.spellcheck.spell_container)[vis ? 'show' : 'hide']();
3090 this.set_spellcheck_state = function(s)
3092 this.spellcheck_ready = (s == 'ready' || s == 'no_error_found');
3093 this.enable_command('spellcheck', this.spellcheck_ready);
3096 // get selected language
3097 this.spellcheck_lang = function()
3100 if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody)) && ed.plugins.spellchecker) {
3101 return ed.plugins.spellchecker.selectedLang;
3103 else if (this.env.spellcheck) {
3104 return GOOGIE_CUR_LANG;
3108 // resume spellchecking, highlight provided mispellings without new ajax request
3109 this.spellcheck_resume = function(ishtml, data)
3112 var ed = tinyMCE.get(this.env.composebody);
3113 sp = ed.plugins.spellchecker;
3116 sp._markWords(data);
3120 var sp = this.env.spellcheck;
3121 sp.prepare(false, true);
3122 sp.processData(data);
3126 this.set_draft_id = function(id)
3128 $("input[name='_draft_saveid']").val(id);
3131 this.auto_save_start = function()
3133 if (this.env.draft_autosave)
3134 this.save_timer = self.setTimeout(function(){ ref.command("savedraft"); }, this.env.draft_autosave * 1000);
3136 // Unlock interface now that saving is complete
3140 this.compose_field_hash = function(save)
3142 // check input fields
3144 value_to = $("[name='_to']").val(),
3145 value_cc = $("[name='_cc']").val(),
3146 value_bcc = $("[name='_bcc']").val(),
3147 value_subject = $("[name='_subject']").val();
3150 str += value_to+':';
3152 str += value_cc+':';
3154 str += value_bcc+':';
3156 str += value_subject+':';
3158 if (window.tinyMCE && (ed = tinyMCE.get(this.env.composebody)))
3159 str += ed.getContent();
3161 str += $("[name='_message']").val();
3163 if (this.env.attachments)
3164 for (var upload_id in this.env.attachments)
3168 this.cmp_hash = str;
3173 this.change_identity = function(obj, show_sig)
3175 if (!obj || !obj.options)
3179 show_sig = this.env.show_sig;
3181 var cursor_pos, p = -1,
3182 id = obj.options[obj.selectedIndex].value,
3183 input_message = $("[name='_message']"),
3184 message = input_message.val(),
3185 is_html = ($("input[name='_is_html']").val() == '1'),
3186 sig = this.env.identity,
3187 sig_separator = this.env.sig_above && (this.env.compose_mode == 'reply' || this.env.compose_mode == 'forward') ? '---' : '-- ';
3189 // enable manual signature insert
3190 if (this.env.signatures && this.env.signatures[id]) {
3191 this.enable_command('insert-sig', true);
3192 this.env.compose_commands.push('insert-sig');
3195 this.enable_command('insert-sig', false);
3198 // remove the 'old' signature
3199 if (show_sig && sig && this.env.signatures && this.env.signatures[sig]) {
3201 sig = this.env.signatures[sig].is_html ? this.env.signatures[sig].plain_text : this.env.signatures[sig].text;
3202 sig = sig.replace(/\r\n/g, '\n');
3204 if (!sig.match(/^--[ -]\n/m))
3205 sig = sig_separator + '\n' + sig;
3207 p = this.env.sig_above ? message.indexOf(sig) : message.lastIndexOf(sig);
3209 message = message.substring(0, p) + message.substring(p+sig.length, message.length);
3211 // add the new signature string
3212 if (show_sig && this.env.signatures && this.env.signatures[id]) {
3213 sig = this.env.signatures[id]['is_html'] ? this.env.signatures[id]['plain_text'] : this.env.signatures[id]['text'];
3214 sig = sig.replace(/\r\n/g, '\n');
3216 if (!sig.match(/^--[ -]\n/m))
3217 sig = sig_separator + '\n' + sig;
3219 if (this.env.sig_above) {
3220 if (p >= 0) { // in place of removed signature
3221 message = message.substring(0, p) + sig + message.substring(p, message.length);
3224 else if (pos = this.get_caret_pos(input_message.get(0))) { // at cursor position
3225 message = message.substring(0, pos) + '\n' + sig + '\n\n' + message.substring(pos, message.length);
3230 message = '\n\n' + sig + '\n\n' + message.replace(/^[\r\n]+/, '');
3234 message = message.replace(/[\r\n]+$/, '');
3235 cursor_pos = !this.env.top_posting && message.length ? message.length+1 : 0;
3236 message += '\n\n' + sig;
3240 cursor_pos = this.env.top_posting ? 0 : message.length;
3242 input_message.val(message);
3244 // move cursor before the signature
3245 this.set_caret_pos(input_message.get(0), cursor_pos);
3247 else if (show_sig && this.env.signatures) { // html
3248 var editor = tinyMCE.get(this.env.composebody),
3249 sigElem = editor.dom.get('_rc_sig');
3251 // Append the signature as a div within the body
3253 var body = editor.getBody(),
3254 doc = editor.getDoc();
3256 sigElem = doc.createElement('div');
3257 sigElem.setAttribute('id', '_rc_sig');
3259 if (this.env.sig_above) {
3260 // if no existing sig and top posting then insert at caret pos
3261 editor.getWin().focus(); // correct focus in IE & Chrome
3263 var node = editor.selection.getNode();
3264 if (node.nodeName == 'BODY') {
3265 // no real focus, insert at start
3266 body.insertBefore(sigElem, body.firstChild);
3267 body.insertBefore(doc.createElement('br'), body.firstChild);
3270 body.insertBefore(sigElem, node.nextSibling);
3271 body.insertBefore(doc.createElement('br'), node.nextSibling);
3275 if (bw.ie) // add empty line before signature on IE
3276 body.appendChild(doc.createElement('br'));
3278 body.appendChild(sigElem);
3282 if (this.env.signatures[id]) {
3283 if (this.env.signatures[id].is_html) {
3284 sig = this.env.signatures[id].text;
3285 if (!this.env.signatures[id].plain_text.match(/^--[ -]\r?\n/m))
3286 sig = sig_separator + '<br />' + sig;
3289 sig = this.env.signatures[id].text;
3290 if (!sig.match(/^--[ -]\r?\n/m))
3291 sig = sig_separator + '\n' + sig;
3292 sig = '<pre>' + sig + '</pre>';
3295 sigElem.innerHTML = sig;
3299 this.env.identity = id;
3303 // upload attachment file
3304 this.upload_file = function(form)
3309 // get file input field, count files on capable browser
3310 var i, size = 0, field = $('input[type=file]', form).get(0),
3311 files = field.files ? field.files.length : field.value ? 1 : 0;
3313 // create hidden iframe and post upload form
3316 if (field.files && this.env.max_filesize && this.env.filesizeerror) {
3317 for (i=0; i<files; i++)
3318 size += field.files[i].size;
3319 if (size && size > this.env.max_filesize) {
3320 this.display_message(this.env.filesizeerror, 'error');
3325 var frame_name = this.async_upload_form(form, 'upload', function(e) {
3326 var d, content = '';
3328 if (this.contentDocument) {
3329 d = this.contentDocument;
3330 } else if (this.contentWindow) {
3331 d = this.contentWindow.document;
3333 content = d.childNodes[0].innerHTML;
3336 if (!content.match(/add2attachment/) && (!bw.opera || (rcmail.env.uploadframe && rcmail.env.uploadframe == e.data.ts))) {
3337 if (!content.match(/display_message/))
3338 rcmail.display_message(rcmail.get_label('fileuploaderror'), 'error');
3339 rcmail.remove_from_attachment_list(e.data.ts);
3341 // Opera hack: handle double onload
3343 rcmail.env.uploadframe = e.data.ts;
3346 // display upload indicator and cancel button
3347 var content = '<span>' + this.get_label('uploading' + (files > 1 ? 'many' : '')) + '</span>',
3348 ts = frame_name.replace(/^rcmupload/, '');
3350 if (this.env.loadingicon)
3351 content = '<img src="'+this.env.loadingicon+'" alt="" />'+content;
3352 if (this.env.cancelicon)
3353 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;
3354 this.add2attachment_list(ts, { name:'', html:content, complete:false });
3356 // upload progress support
3357 if (this.env.upload_progress_time) {
3358 this.upload_progress_start('upload', ts);
3362 // set reference to the form object
3363 this.gui_objects.attachmentform = form;
3367 // add file name to attachment list
3368 // called from upload page
3369 this.add2attachment_list = function(name, att, upload_id)
3371 if (!this.gui_objects.attachmentlist)
3374 var indicator, li = $('<li>').attr('id', name).html(att.html);
3376 // replace indicator's li
3377 if (upload_id && (indicator = document.getElementById(upload_id))) {
3378 li.replaceAll(indicator);
3380 else { // add new li
3381 li.appendTo(this.gui_objects.attachmentlist);
3384 if (upload_id && this.env.attachments[upload_id])
3385 delete this.env.attachments[upload_id];
3387 this.env.attachments[name] = att;
3392 this.remove_from_attachment_list = function(name)
3394 delete this.env.attachments[name];
3395 $('#'+name).remove();
3398 this.remove_attachment = function(name)
3400 if (name && this.env.attachments[name])
3401 this.http_post('remove-attachment', { _id:this.env.compose_id, _file:name });
3406 this.cancel_attachment_upload = function(name, frame_name)
3408 if (!name || !frame_name)
3411 this.remove_from_attachment_list(name);
3412 $("iframe[name='"+frame_name+"']").remove();
3416 this.upload_progress_start = function(action, name)
3418 window.setTimeout(function() { rcmail.http_request(action, {_progress: name}); },
3419 this.env.upload_progress_time * 1000);
3422 this.upload_progress_update = function(param)
3424 var elem = $('#'+param.name + '> span');
3426 if (!elem.length || !param.text)
3429 elem.text(param.text);
3432 this.upload_progress_start(param.action, param.name);
3435 // send remote request to add a new contact
3436 this.add_contact = function(value)
3439 this.http_post('addcontact', '_address='+value);
3444 // send remote request to search mail or contacts
3445 this.qsearch = function(value)
3448 var n, lock = this.set_busy(true, 'searching');
3450 if (this.message_list)
3451 this.clear_message_list();
3452 else if (this.contact_list)
3453 this.list_contacts_clear();
3456 this.env.current_page = 1;
3457 r = this.http_request('search', this.search_params(value)
3458 + (this.env.source ? '&_source='+urlencode(this.env.source) : '')
3459 + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
3461 this.env.qsearch = {lock: lock, request: r};
3465 // build URL params for search
3466 this.search_params = function(search, filter)
3468 var n, url = [], mods_arr = [],
3469 mods = this.env.search_mods,
3470 mbox = this.env.mailbox;
3472 if (!filter && this.gui_objects.search_filter)
3473 filter = this.gui_objects.search_filter.value;
3475 if (!search && this.gui_objects.qsearchbox)
3476 search = this.gui_objects.qsearchbox.value;
3479 url.push('_filter=' + urlencode(filter));
3482 url.push('_q='+urlencode(search));
3484 if (mods && this.message_list)
3485 mods = mods[mbox] ? mods[mbox] : mods['*'];
3490 url.push('_headers='+mods_arr.join(','));
3495 url.push('_mbox='+urlencode(mbox));
3497 return url.join('&');
3500 // reset quick-search form
3501 this.reset_qsearch = function()
3503 if (this.gui_objects.qsearchbox)
3504 this.gui_objects.qsearchbox.value = '';
3506 if (this.env.qsearch)
3507 this.abort_request(this.env.qsearch);
3509 this.env.qsearch = null;
3510 this.env.search_request = null;
3511 this.env.search_id = null;
3514 this.sent_successfully = function(type, msg)
3516 this.display_message(msg, type);
3517 // before redirect we need to wait some time for Chrome (#1486177)
3518 window.setTimeout(function(){ ref.list_mailbox(); }, 500);
3522 /*********************************************************/
3523 /********* keyboard live-search methods *********/
3524 /*********************************************************/
3526 // handler for keyboard events on address-fields
3527 this.ksearch_keydown = function(e, obj, props)
3529 if (this.ksearch_timer)
3530 clearTimeout(this.ksearch_timer);
3533 key = rcube_event.get_keycode(e),
3534 mod = rcube_event.get_modifier(e);
3538 case 40: // key down
3539 if (!this.ksearch_pane)
3542 var dir = key==38 ? 1 : 0;
3544 highlight = document.getElementById('rcmksearchSelected');
3546 highlight = this.ksearch_pane.__ul.firstChild;
3549 this.ksearch_select(dir ? highlight.previousSibling : highlight.nextSibling);
3551 return rcube_event.cancel(e);
3554 if (mod == SHIFT_KEY || !this.ksearch_visible()) {
3555 this.ksearch_hide();
3560 if (!this.ksearch_visible())
3563 // insert selected address and hide ksearch pane
3564 this.insert_recipient(this.ksearch_selected);
3565 this.ksearch_hide();
3567 return rcube_event.cancel(e);
3570 this.ksearch_hide();
3575 if (mod != SHIFT_KEY)
3580 this.ksearch_timer = window.setTimeout(function(){ ref.ksearch_get_results(props); }, 200);
3581 this.ksearch_input = obj;
3586 this.ksearch_visible = function()
3588 return (this.ksearch_selected !== null && this.ksearch_selected !== undefined && this.ksearch_value);
3591 this.ksearch_select = function(node)
3593 var current = $('#rcmksearchSelected');
3594 if (current[0] && node) {
3595 current.removeAttr('id').removeClass('selected');
3599 $(node).attr('id', 'rcmksearchSelected').addClass('selected');
3600 this.ksearch_selected = node._rcm_id;
3604 this.insert_recipient = function(id)
3606 if (id === null || !this.env.contacts[id] || !this.ksearch_input)
3610 var inp_value = this.ksearch_input.value,
3611 cpos = this.get_caret_pos(this.ksearch_input),
3612 p = inp_value.lastIndexOf(this.ksearch_value, cpos),
3615 // replace search string with full address
3616 pre = inp_value.substring(0, p),
3617 end = inp_value.substring(p+this.ksearch_value.length, inp_value.length);
3619 this.ksearch_destroy();
3621 // insert all members of a group
3622 if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].id) {
3623 insert += this.env.contacts[id].name + this.env.recipients_delimiter;
3624 this.group2expand = $.extend({}, this.env.contacts[id]);
3625 this.group2expand.input = this.ksearch_input;
3626 this.http_request('mail/group-expand', '_source='+urlencode(this.env.contacts[id].source)+'&_gid='+urlencode(this.env.contacts[id].id), false);
3628 else if (typeof this.env.contacts[id] === 'string') {
3629 insert = this.env.contacts[id] + this.env.recipients_delimiter;
3633 this.ksearch_input.value = pre + insert + end;
3635 // set caret to insert pos
3636 cpos = p+insert.length;
3637 if (this.ksearch_input.setSelectionRange)
3638 this.ksearch_input.setSelectionRange(cpos, cpos);
3641 this.triggerEvent('autocomplete_insert', { field:this.ksearch_input, insert:insert });
3644 this.replace_group_recipients = function(id, recipients)
3646 if (this.group2expand && this.group2expand.id == id) {
3647 this.group2expand.input.value = this.group2expand.input.value.replace(this.group2expand.name, recipients);
3648 this.triggerEvent('autocomplete_insert', { field:this.group2expand.input, insert:recipients });
3649 this.group2expand = null;
3653 // address search processor
3654 this.ksearch_get_results = function(props)
3656 var inp_value = this.ksearch_input ? this.ksearch_input.value : null;
3658 if (inp_value === null)
3661 if (this.ksearch_pane && this.ksearch_pane.is(":visible"))
3662 this.ksearch_pane.hide();
3664 // get string from current cursor pos to last comma
3665 var cpos = this.get_caret_pos(this.ksearch_input),
3666 p = inp_value.lastIndexOf(this.env.recipients_separator, cpos-1),
3667 q = inp_value.substring(p+1, cpos),
3668 min = this.env.autocomplete_min_length,
3669 ac = this.ksearch_data;
3671 // trim query string
3674 // Don't (re-)search if the last results are still active
3675 if (q == this.ksearch_value)
3678 this.ksearch_destroy();
3680 if (q.length && q.length < min) {
3681 if (!this.ksearch_info) {
3682 this.ksearch_info = this.display_message(
3683 this.get_label('autocompletechars').replace('$min', min));
3688 var old_value = this.ksearch_value;
3689 this.ksearch_value = q;
3691 // ...string is empty
3695 // ...new search value contains old one and previous search was not finished or its result was empty
3696 if (old_value && old_value.length && q.indexOf(old_value) == 0 && (!ac || !ac.num) && this.env.contacts && !this.env.contacts.length)
3699 var i, lock, source, xhr, reqid = new Date().getTime(),
3700 threads = props && props.threads ? props.threads : 1,
3701 sources = props && props.sources ? props.sources : [],
3702 action = props && props.action ? props.action : 'mail/autocomplete';
3704 this.ksearch_data = {id: reqid, sources: sources.slice(), action: action,
3705 locks: [], requests: [], num: sources.length};
3707 for (i=0; i<threads; i++) {
3708 source = this.ksearch_data.sources.shift();
3709 if (threads > 1 && source === null)
3712 lock = this.display_message(this.get_label('searching'), 'loading');
3713 xhr = this.http_post(action, '_search='+urlencode(q)+'&_id='+reqid
3714 + (source ? '&_source='+urlencode(source) : ''), lock);
3716 this.ksearch_data.locks.push(lock);
3717 this.ksearch_data.requests.push(xhr);
3721 this.ksearch_query_results = function(results, search, reqid)
3723 // search stopped in meantime?
3724 if (!this.ksearch_value)
3727 // ignore this outdated search response
3728 if (this.ksearch_input && search != this.ksearch_value)
3731 // display search results
3732 var i, len, ul, li, text, init,
3733 value = this.ksearch_value,
3734 data = this.ksearch_data,
3735 maxlen = this.env.autocomplete_max ? this.env.autocomplete_max : 15;
3737 // create results pane if not present
3738 if (!this.ksearch_pane) {
3740 this.ksearch_pane = $('<div>').attr('id', 'rcmKSearchpane')
3741 .css({ position:'absolute', 'z-index':30000 }).append(ul).appendTo(document.body);
3742 this.ksearch_pane.__ul = ul[0];
3745 ul = this.ksearch_pane.__ul;
3747 // remove all search results or add to existing list if parallel search
3748 if (reqid && this.ksearch_pane.data('reqid') == reqid) {
3749 maxlen -= ul.childNodes.length;
3752 this.ksearch_pane.data('reqid', reqid);
3756 this.env.contacts = [];
3757 // move the results pane right under the input box
3758 var pos = $(this.ksearch_input).offset();
3759 this.ksearch_pane.css({ left:pos.left+'px', top:(pos.top + this.ksearch_input.offsetHeight)+'px', display: 'none'});
3762 // add each result line to list
3763 if (results && (len = results.length)) {
3764 for (i=0; i < len && maxlen > 0; i++) {
3765 text = typeof results[i] === 'object' ? results[i].name : results[i];
3766 li = document.createElement('LI');
3767 li.innerHTML = text.replace(new RegExp('('+RegExp.escape(value)+')', 'ig'), '##$1%%').replace(/</g, '<').replace(/>/g, '>').replace(/##([^%]+)%%/g, '<b>$1</b>');
3768 li.onmouseover = function(){ ref.ksearch_select(this); };
3769 li.onmouseup = function(){ ref.ksearch_click(this) };
3770 li._rcm_id = this.env.contacts.length + i;
3776 if (ul.childNodes.length) {
3777 this.ksearch_pane.show();
3779 if (!this.env.contacts.length) {
3780 $('li:first', ul).attr('id', 'rcmksearchSelected').addClass('selected');
3781 this.ksearch_selected = 0;
3786 this.env.contacts = this.env.contacts.concat(results);
3788 // run next parallel search
3789 if (data.id == reqid) {
3791 if (maxlen > 0 && data.sources.length) {
3792 var lock, xhr, source = data.sources.shift();
3794 lock = this.display_message(this.get_label('searching'), 'loading');
3795 xhr = this.http_post(data.action, '_search='+urlencode(value)+'&_id='+reqid
3796 +'&_source='+urlencode(source), lock);
3798 this.ksearch_data.locks.push(lock);
3799 this.ksearch_data.requests.push(xhr);
3803 if (!this.ksearch_msg)
3804 this.ksearch_msg = this.display_message(this.get_label('autocompletemore'));
3805 // abort pending searches
3806 this.ksearch_abort();
3811 this.ksearch_click = function(node)
3813 if (this.ksearch_input)
3814 this.ksearch_input.focus();
3816 this.insert_recipient(node._rcm_id);
3817 this.ksearch_hide();
3820 this.ksearch_blur = function()
3822 if (this.ksearch_timer)
3823 clearTimeout(this.ksearch_timer);
3825 this.ksearch_input = null;
3826 this.ksearch_hide();
3829 this.ksearch_hide = function()
3831 this.ksearch_selected = null;
3832 this.ksearch_value = '';
3834 if (this.ksearch_pane)
3835 this.ksearch_pane.hide();
3837 this.ksearch_destroy();
3840 // Clears autocomplete data/requests
3841 this.ksearch_destroy = function()
3843 this.ksearch_abort();
3845 if (this.ksearch_info)
3846 this.hide_message(this.ksearch_info);
3848 if (this.ksearch_msg)
3849 this.hide_message(this.ksearch_msg);
3851 this.ksearch_data = null;
3852 this.ksearch_info = null;
3853 this.ksearch_msg = null;
3856 // Aborts pending autocomplete requests
3857 this.ksearch_abort = function()
3859 var i, len, ac = this.ksearch_data;
3864 for (i=0, len=ac.locks.length; i<len; i++)
3865 this.abort_request({request: ac.requests[i], lock: ac.locks[i]});
3869 /*********************************************************/
3870 /********* address book methods *********/
3871 /*********************************************************/
3873 this.contactlist_keypress = function(list)
3875 if (list.key_pressed == list.DELETE_KEY)
3876 this.command('delete');
3879 this.contactlist_select = function(list)
3881 if (this.preview_timer)
3882 clearTimeout(this.preview_timer);
3884 var n, id, sid, ref = this, writable = false,
3885 source = this.env.source ? this.env.address_sources[this.env.source] : null;
3887 if (id = list.get_single_selection())
3888 this.preview_timer = window.setTimeout(function(){ ref.load_contact(id, 'show'); }, 200);
3889 else if (this.env.contentframe)
3890 this.show_contentframe(false);
3892 // no source = search result, we'll need to detect if any of
3893 // selected contacts are in writable addressbook to enable edit/delete
3894 if (list.selection.length) {
3896 for (n in list.selection) {
3897 sid = String(list.selection[n]).replace(/^[^-]+-/, '');
3898 if (sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly) {
3905 writable = !source.readonly;
3909 this.enable_command('compose', this.env.group || list.selection.length > 0);
3910 this.enable_command('edit', id && writable);
3911 this.enable_command('delete', list.selection.length && writable);
3916 this.list_contacts = function(src, group, page)
3918 var folder, add_url = '',
3922 src = this.env.source;
3924 if (page && this.current_page == page && src == this.env.source && group == this.env.group)
3927 if (src != this.env.source) {
3928 page = this.env.current_page = 1;
3929 this.reset_qsearch();
3931 else if (group != this.env.group)
3932 page = this.env.current_page = 1;
3934 if (this.env.search_id)
3935 folder = 'S'+this.env.search_id;
3937 folder = group ? 'G'+src+group : src;
3939 this.select_folder(folder);
3941 this.env.source = src;
3942 this.env.group = group;
3944 // load contacts remotely
3945 if (this.gui_objects.contactslist) {
3946 this.list_contacts_remote(src, group, page);
3950 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
3951 target = window.frames[this.env.contentframe];
3952 add_url = '&_framed=1';
3956 add_url += '&_gid='+group;
3958 add_url += '&_page='+page;
3960 // also send search request to get the correct listing
3961 if (this.env.search_request)
3962 add_url += '&_search='+this.env.search_request;
3964 this.set_busy(true, 'loading');
3965 this.location_href(this.env.comm_path + (src ? '&_source='+urlencode(src) : '') + add_url, target);
3968 // send remote request to load contacts list
3969 this.list_contacts_remote = function(src, group, page)
3971 // clear message list first
3972 this.list_contacts_clear();
3974 // send request to server
3975 var url = (src ? '_source='+urlencode(src) : '') + (page ? (src?'&':'') + '_page='+page : ''),
3976 lock = this.set_busy(true, 'loading');
3978 this.env.source = src;
3979 this.env.group = group;
3982 url += '&_gid='+group;
3984 // also send search request to get the right messages
3985 if (this.env.search_request)
3986 url += '&_search='+this.env.search_request;
3988 this.http_request('list', url, lock);
3991 this.list_contacts_clear = function()
3993 this.contact_list.clear(true);
3994 this.show_contentframe(false);
3995 this.enable_command('delete', false);
3996 this.enable_command('compose', this.env.group ? true : false);
3999 // load contact record
4000 this.load_contact = function(cid, action, framed)
4002 var add_url = '', target = window;
4004 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4005 add_url = '&_framed=1';
4006 target = window.frames[this.env.contentframe];
4007 this.show_contentframe(true);
4009 // load dummy content
4011 // unselect selected row(s)
4012 this.contact_list.clear_selection();
4013 this.enable_command('delete', 'compose', false);
4019 if (action && (cid || action=='add') && !this.drag_active) {
4021 add_url += '&_gid='+urlencode(this.env.group);
4023 this.location_href(this.env.comm_path+'&_action='+action
4024 +'&_source='+urlencode(this.env.source)
4025 +'&_cid='+urlencode(cid) + add_url, target, true);
4030 // add/delete member to/from the group
4031 this.group_member_change = function(what, cid, source, gid)
4033 what = what == 'add' ? 'add' : 'del';
4034 var lock = this.display_message(this.get_label(what == 'add' ? 'addingmember' : 'removingmember'), 'loading');
4036 this.http_post('group-'+what+'members', '_cid='+urlencode(cid)
4037 + '&_source='+urlencode(source)
4038 + '&_gid='+urlencode(gid), lock);
4041 // copy a contact to the specified target (group or directory)
4042 this.copy_contact = function(cid, to)
4045 cid = this.contact_list.get_selection().join(',');
4047 if (to.type == 'group' && to.source == this.env.source)
4048 this.group_member_change('add', cid, to.source, to.id);
4049 else if (to.type == 'group' && !this.env.address_sources[to.source].readonly) {
4050 var lock = this.display_message(this.get_label('copyingcontact'), 'loading');
4051 this.http_post('copy', '_cid='+urlencode(cid)
4052 + '&_source='+urlencode(this.env.source)
4053 + '&_to='+urlencode(to.source)
4054 + '&_togid='+urlencode(to.id)
4055 + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
4057 else if (to.id != this.env.source && cid && this.env.address_sources[to.id] && !this.env.address_sources[to.id].readonly) {
4058 var lock = this.display_message(this.get_label('copyingcontact'), 'loading');
4059 this.http_post('copy', '_cid='+urlencode(cid)
4060 + '&_source='+urlencode(this.env.source)
4061 + '&_to='+urlencode(to.id)
4062 + (this.env.group ? '&_gid='+urlencode(this.env.group) : ''), lock);
4066 this.delete_contacts = function()
4068 var selection = this.contact_list.get_selection(),
4069 undelete = this.env.source && this.env.address_sources[this.env.source].undelete;
4071 // exit if no mailbox specified or if selection is empty
4072 if (!(selection.length || this.env.cid) || (!undelete && !confirm(this.get_label('deletecontactconfirm'))))
4075 var id, n, a_cids = [], qs = '';
4078 a_cids.push(this.env.cid);
4080 for (n=0; n<selection.length; n++) {
4083 this.contact_list.remove_row(id, (n == selection.length-1));
4086 // hide content frame if we delete the currently displayed contact
4087 if (selection.length == 1)
4088 this.show_contentframe(false);
4092 qs += '&_gid='+urlencode(this.env.group);
4094 // also send search request to get the right records from the next page
4095 if (this.env.search_request)
4096 qs += '&_search='+this.env.search_request;
4098 // send request to server
4099 this.http_post('delete', '_cid='+urlencode(a_cids.join(','))
4100 +'&_source='+urlencode(this.env.source)
4101 +'&_from='+(this.env.action ? this.env.action : '')+qs,
4102 this.display_message(this.get_label('contactdeleting'), 'loading'));
4107 // update a contact record in the list
4108 this.update_contact_row = function(cid, cols_arr, newcid, source)
4110 var c, row, list = this.contact_list;
4112 cid = this.html_identifier(cid);
4114 // when in searching mode, concat cid with the source name
4115 if (!list.rows[cid]) {
4116 cid = cid+'-'+source;
4118 newcid = newcid+'-'+source;
4121 if (list.rows[cid] && (row = list.rows[cid].obj)) {
4122 for (c=0; c<cols_arr.length; c++)
4124 $(row.cells[c]).html(cols_arr[c]);
4128 newcid = this.html_identifier(newcid);
4129 row.id = 'rcmrow' + newcid;
4130 list.remove_row(cid);
4132 list.selection[0] = newcid;
4133 row.style.display = '';
4138 // add row to contacts list
4139 this.add_contact_row = function(cid, cols, select)
4141 if (!this.gui_objects.contactslist)
4144 var c, list = this.contact_list,
4145 row = document.createElement('tr');
4147 row.id = 'rcmrow'+this.html_identifier(cid);
4148 row.className = 'contact';
4150 if (list.in_selection(cid))
4151 row.className += ' selected';
4153 // add each submitted col
4155 col = document.createElement('td');
4156 col.className = String(c).toLowerCase();
4157 col.innerHTML = cols[c];
4158 row.appendChild(col);
4161 list.insert_row(row);
4163 this.enable_command('export', list.rowcount > 0);
4166 this.init_contact_form = function()
4168 var ref = this, col;
4170 this.set_photo_actions($('#ff_photo').val());
4172 for (col in this.env.coltypes)
4173 this.init_edit_field(col, null);
4175 $('.contactfieldgroup .row a.deletebutton').click(function() {
4176 ref.delete_edit_field(this);
4180 $('select.addfieldmenu').change(function(e) {
4181 ref.insert_edit_field($(this).val(), $(this).attr('rel'), this);
4182 this.selectedIndex = 0;
4185 // enable date pickers on date fields
4186 if ($.datepicker && this.env.date_format) {
4187 $.datepicker.setDefaults({
4188 dateFormat: this.env.date_format,
4191 yearRange: '-100:+10',
4192 showOtherMonths: true,
4193 selectOtherMonths: true,
4194 monthNamesShort: this.env.month_names,
4195 onSelect: function(dateText) { $(this).focus().val(dateText) }
4197 $('input.datepicker').datepicker();
4200 $("input[type='text']:visible").first().focus();
4203 this.group_create = function()
4205 this.add_input_row('contactgroup');
4208 this.group_rename = function()
4210 if (!this.env.group || !this.gui_objects.folderlist)
4213 if (!this.name_input) {
4214 this.enable_command('list', 'listgroup', false);
4215 this.name_input = $('<input>').attr('type', 'text').val(this.env.contactgroups['G'+this.env.source+this.env.group].name);
4216 this.name_input.bind('keydown', function(e){ return rcmail.add_input_keydown(e); });
4217 this.env.group_renaming = true;
4219 var link, li = this.get_folder_li(this.env.source+this.env.group, 'rcmliG');
4220 if (li && (link = li.firstChild)) {
4221 $(link).hide().before(this.name_input);
4225 this.name_input.select().focus();
4228 this.group_delete = function()
4230 if (this.env.group && confirm(this.get_label('deletegroupconfirm'))) {
4231 var lock = this.set_busy(true, 'groupdeleting');
4232 this.http_post('group-delete', '_source='+urlencode(this.env.source)+'&_gid='+urlencode(this.env.group), lock);
4236 // callback from server upon group-delete command
4237 this.remove_group_item = function(prop)
4239 var li, key = 'G'+prop.source+prop.id;
4240 if ((li = this.get_folder_li(key))) {
4241 this.triggerEvent('group_delete', { source:prop.source, id:prop.id, li:li });
4243 li.parentNode.removeChild(li);
4244 delete this.env.contactfolders[key];
4245 delete this.env.contactgroups[key];
4248 this.list_contacts(prop.source, 0);
4251 // @TODO: maybe it would be better to use popup instead of inserting input to the list?
4252 this.add_input_row = function(type)
4254 if (!this.gui_objects.folderlist)
4257 if (!this.name_input) {
4258 this.name_input = $('<input>').attr('type', 'text').data('tt', type);
4259 this.name_input.bind('keydown', function(e){ return rcmail.add_input_keydown(e); });
4260 this.name_input_li = $('<li>').addClass(type).append(this.name_input);
4262 var li = type == 'contactsearch' ? $('li:last', this.gui_objects.folderlist) : this.get_folder_li(this.env.source);
4263 this.name_input_li.insertAfter(li);
4266 this.name_input.select().focus();
4269 // handler for keyboard events on the input field
4270 this.add_input_keydown = function(e)
4272 var key = rcube_event.get_keycode(e),
4273 input = $(e.target), itype = input.data('tt');
4277 var newname = input.val();
4280 var lock = this.set_busy(true, 'loading');
4282 if (itype == 'contactsearch')
4283 this.http_post('search-create', '_search='+urlencode(this.env.search_request)+'&_name='+urlencode(newname), lock);
4284 else if (this.env.group_renaming)
4285 this.http_post('group-rename', '_source='+urlencode(this.env.source)+'&_gid='+urlencode(this.env.group)+'&_name='+urlencode(newname), lock);
4287 this.http_post('group-create', '_source='+urlencode(this.env.source)+'&_name='+urlencode(newname), lock);
4293 this.reset_add_input();
4298 this.reset_add_input = function()
4300 if (this.name_input) {
4301 if (this.env.group_renaming) {
4302 var li = this.name_input.parent();
4303 li.children().last().show();
4304 this.env.group_renaming = false;
4307 this.name_input.remove();
4309 if (this.name_input_li)
4310 this.name_input_li.remove();
4312 this.name_input = this.name_input_li = null;
4315 this.enable_command('list', 'listgroup', true);
4318 // callback for creating a new contact group
4319 this.insert_contact_group = function(prop)
4321 this.reset_add_input();
4323 prop.type = 'group';
4324 var key = 'G'+prop.source+prop.id,
4325 link = $('<a>').attr('href', '#')
4326 .attr('rel', prop.source+':'+prop.id)
4327 .click(function() { return rcmail.command('listgroup', prop, this); })
4329 li = $('<li>').attr({id: 'rcmli'+this.html_identifier(key), 'class': 'contactgroup'})
4332 this.env.contactfolders[key] = this.env.contactgroups[key] = prop;
4333 this.add_contact_group_row(prop, li);
4335 this.triggerEvent('group_insert', { id:prop.id, source:prop.source, name:prop.name, li:li[0] });
4338 // callback for renaming a contact group
4339 this.update_contact_group = function(prop)
4341 this.reset_add_input();
4343 var key = 'G'+prop.source+prop.id,
4344 li = this.get_folder_li(key),
4347 // group ID has changed, replace link node and identifiers
4348 if (li && prop.newid) {
4349 var newkey = 'G'+prop.source+prop.newid,
4350 newprop = $.extend({}, prop);;
4352 li.id = 'rcmli' + this.html_identifier(newkey);
4353 this.env.contactfolders[newkey] = this.env.contactfolders[key];
4354 this.env.contactfolders[newkey].id = prop.newid;
4355 this.env.group = prop.newid;
4357 delete this.env.contactfolders[key];
4358 delete this.env.contactgroups[key];
4360 newprop.id = prop.newid;
4361 newprop.type = 'group';
4363 link = $('<a>').attr('href', '#')
4364 .attr('rel', prop.source+':'+prop.newid)
4365 .click(function() { return rcmail.command('listgroup', newprop, this); })
4367 $(li).children().replaceWith(link);
4369 // update displayed group name
4370 else if (li && (link = li.firstChild) && link.tagName.toLowerCase() == 'a')
4371 link.innerHTML = prop.name;
4373 this.env.contactfolders[key].name = this.env.contactgroups[key].name = prop.name;
4374 this.add_contact_group_row(prop, $(li), true);
4376 this.triggerEvent('group_update', { id:prop.id, source:prop.source, name:prop.name, li:li[0], newid:prop.newid });
4379 // add contact group row to the list, with sorting
4380 this.add_contact_group_row = function(prop, li, reloc)
4382 var row, name = prop.name.toUpperCase(),
4383 sibling = this.get_folder_li(prop.source),
4384 prefix = 'rcmliG' + this.html_identifier(prop.source);
4386 // When renaming groups, we need to remove it from DOM and insert it in the proper place
4388 row = li.clone(true);
4394 $('li[id^="'+prefix+'"]', this.gui_objects.folderlist).each(function(i, elem) {
4395 if (name >= $(this).text().toUpperCase())
4401 row.insertAfter(sibling);
4404 this.update_group_commands = function()
4406 var source = this.env.source != '' ? this.env.address_sources[this.env.source] : null;
4407 this.enable_command('group-create', (source && source.groups && !source.readonly));
4408 this.enable_command('group-rename', 'group-delete', (source && source.groups && this.env.group && !source.readonly));
4411 this.init_edit_field = function(col, elem)
4414 elem = $('.ff_' + col);
4416 elem.focus(function(){ ref.focus_textfield(this); })
4417 .blur(function(){ ref.blur_textfield(this); })
4418 .each(function(){ this._placeholder = this.title = ref.env.coltypes[col].label; ref.blur_textfield(this); });
4421 this.insert_edit_field = function(col, section, menu)
4423 // just make pre-defined input field visible
4424 var elem = $('#ff_'+col);
4426 elem.show().focus();
4427 $(menu).children('option[value="'+col+'"]').prop('disabled', true);
4430 var lastelem = $('.ff_'+col),
4431 appendcontainer = $('#contactsection'+section+' .contactcontroller'+col);
4433 if (!appendcontainer.length)
4434 appendcontainer = $('<fieldset>').addClass('contactfieldgroup contactcontroller'+col).insertAfter($('#contactsection'+section+' .contactfieldgroup').last());
4436 if (appendcontainer.length && appendcontainer.get(0).nodeName == 'FIELDSET') {
4437 var input, colprop = this.env.coltypes[col],
4438 row = $('<div>').addClass('row'),
4439 cell = $('<div>').addClass('contactfieldcontent data'),
4440 label = $('<div>').addClass('contactfieldlabel label');
4442 if (colprop.subtypes_select)
4443 label.html(colprop.subtypes_select);
4445 label.html(colprop.label);
4447 var name_suffix = colprop.limit != 1 ? '[]' : '';
4448 if (colprop.type == 'text' || colprop.type == 'date') {
4449 input = $('<input>')
4450 .addClass('ff_'+col)
4451 .attr({type: 'text', name: '_'+col+name_suffix, size: colprop.size})
4454 this.init_edit_field(col, input);
4456 if (colprop.type == 'date' && $.datepicker)
4459 else if (colprop.type == 'composite') {
4460 var childcol, cp, first, templ, cols = [], suffices = [];
4461 // read template for composite field order
4462 if ((templ = this.env[col+'_template'])) {
4463 for (var j=0; j < templ.length; j++) {
4464 cols.push(templ[j][1]);
4465 suffices.push(templ[j][2]);
4468 else { // list fields according to appearance in colprop
4469 for (childcol in colprop.childs)
4470 cols.push(childcol);
4473 for (var i=0; i < cols.length; i++) {
4475 cp = colprop.childs[childcol];
4476 input = $('<input>')
4477 .addClass('ff_'+childcol)
4478 .attr({ type: 'text', name: '_'+childcol+name_suffix, size: cp.size })
4480 cell.append(suffices[i] || " ");
4481 this.init_edit_field(childcol, input);
4482 if (!first) first = input;
4484 input = first; // set focus to the first of this composite fields
4486 else if (colprop.type == 'select') {
4487 input = $('<select>')
4488 .addClass('ff_'+col)
4489 .attr('name', '_'+col+name_suffix)
4492 var options = input.attr('options');
4493 options[options.length] = new Option('---', '');
4494 if (colprop.options)
4495 $.each(colprop.options, function(i, val){ options[options.length] = new Option(val, i); });
4499 var delbutton = $('<a href="#del"></a>')
4500 .addClass('contactfieldbutton deletebutton')
4501 .attr({title: this.get_label('delete'), rel: col})
4502 .html(this.env.delbutton)
4503 .click(function(){ ref.delete_edit_field(this); return false })
4506 row.append(label).append(cell).appendTo(appendcontainer.show());
4507 input.first().focus();
4509 // disable option if limit reached
4510 if (!colprop.count) colprop.count = 0;
4511 if (++colprop.count == colprop.limit && colprop.limit)
4512 $(menu).children('option[value="'+col+'"]').prop('disabled', true);
4518 this.delete_edit_field = function(elem)
4520 var col = $(elem).attr('rel'),
4521 colprop = this.env.coltypes[col],
4522 fieldset = $(elem).parents('fieldset.contactfieldgroup'),
4523 addmenu = fieldset.parent().find('select.addfieldmenu');
4525 // just clear input but don't hide the last field
4526 if (--colprop.count <= 0 && colprop.visible)
4527 $(elem).parent().children('input').val('').blur();
4529 $(elem).parents('div.row').remove();
4530 // hide entire fieldset if no more rows
4531 if (!fieldset.children('div.row').length)
4535 // enable option in add-field selector or insert it if necessary
4536 if (addmenu.length) {
4537 var option = addmenu.children('option[value="'+col+'"]');
4539 option.prop('disabled', false);
4541 option = $('<option>').attr('value', col).html(colprop.label).appendTo(addmenu);
4546 this.upload_contact_photo = function(form)
4548 if (form && form.elements._photo.value) {
4549 this.async_upload_form(form, 'upload-photo', function(e) {
4550 rcmail.set_busy(false, null, rcmail.photo_upload_id);
4553 // display upload indicator
4554 this.photo_upload_id = this.set_busy(true, 'uploading');
4558 this.replace_contact_photo = function(id)
4560 var img_src = id == '-del-' ? this.env.photo_placeholder :
4561 this.env.comm_path + '&_action=photo&_source=' + this.env.source + '&_cid=' + this.env.cid + '&_photo=' + id;
4563 this.set_photo_actions(id);
4564 $(this.gui_objects.contactphoto).children('img').attr('src', img_src);
4567 this.photo_upload_end = function()
4569 this.set_busy(false, null, this.photo_upload_id);
4570 delete this.photo_upload_id;
4573 this.set_photo_actions = function(id)
4575 var n, buttons = this.buttons['upload-photo'];
4576 for (n=0; buttons && n < buttons.length; n++)
4577 $('#'+buttons[n].id).html(this.get_label(id == '-del-' ? 'addphoto' : 'replacephoto'));
4579 $('#ff_photo').val(id);
4580 this.enable_command('upload-photo', this.env.coltypes.photo ? true : false);
4581 this.enable_command('delete-photo', this.env.coltypes.photo && id != '-del-');
4584 // load advanced search page
4585 this.advanced_search = function()
4587 var add_url = '&_form=1', target = window;
4589 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4590 add_url += '&_framed=1';
4591 target = window.frames[this.env.contentframe];
4592 this.contact_list.clear_selection();
4595 this.location_href(this.env.comm_path+'&_action=search'+add_url, target, true);
4600 // unselect directory/group
4601 this.unselect_directory = function()
4603 this.select_folder('');
4604 this.enable_command('search-delete', false);
4607 // callback for creating a new saved search record
4608 this.insert_saved_search = function(name, id)
4610 this.reset_add_input();
4613 link = $('<a>').attr('href', '#')
4615 .click(function() { return rcmail.command('listsearch', id, this); })
4617 li = $('<li>').attr({id: 'rcmli' + this.html_identifier(key), 'class': 'contactsearch'})
4619 prop = {name:name, id:id, li:li[0]};
4621 this.add_saved_search_row(prop, li);
4622 this.select_folder('S'+id);
4623 this.enable_command('search-delete', true);
4624 this.env.search_id = id;
4626 this.triggerEvent('abook_search_insert', prop);
4629 // add saved search row to the list, with sorting
4630 this.add_saved_search_row = function(prop, li, reloc)
4632 var row, sibling, name = prop.name.toUpperCase();
4634 // When renaming groups, we need to remove it from DOM and insert it in the proper place
4636 row = li.clone(true);
4642 $('li[class~="contactsearch"]', this.gui_objects.folderlist).each(function(i, elem) {
4644 sibling = this.previousSibling;
4646 if (name >= $(this).text().toUpperCase())
4653 row.insertAfter(sibling);
4655 row.appendTo(this.gui_objects.folderlist);
4658 // creates an input for saved search name
4659 this.search_create = function()
4661 this.add_input_row('contactsearch');
4664 this.search_delete = function()
4666 if (this.env.search_request) {
4667 var lock = this.set_busy(true, 'savedsearchdeleting');
4668 this.http_post('search-delete', '_sid='+urlencode(this.env.search_id), lock);
4672 // callback from server upon search-delete command
4673 this.remove_search_item = function(id)
4675 var li, key = 'S'+id;
4676 if ((li = this.get_folder_li(key))) {
4677 this.triggerEvent('search_delete', { id:id, li:li });
4679 li.parentNode.removeChild(li);
4682 this.env.search_id = null;
4683 this.env.search_request = null;
4684 this.list_contacts_clear();
4685 this.reset_qsearch();
4686 this.enable_command('search-delete', 'search-create', false);
4689 this.listsearch = function(id)
4691 var folder, lock = this.set_busy(true, 'searching');
4693 if (this.contact_list) {
4694 this.list_contacts_clear();
4697 this.reset_qsearch();
4698 this.select_folder('S'+id);
4701 this.env.current_page = 1;
4702 this.http_request('search', '_sid='+urlencode(id), lock);
4706 /*********************************************************/
4707 /********* user settings methods *********/
4708 /*********************************************************/
4710 // preferences section select and load options frame
4711 this.section_select = function(list)
4713 var id = list.get_single_selection(), add_url = '', target = window;
4716 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4717 add_url = '&_framed=1';
4718 target = window.frames[this.env.contentframe];
4720 this.location_href(this.env.comm_path+'&_action=edit-prefs&_section='+id+add_url, target, true);
4726 this.identity_select = function(list)
4729 if (id = list.get_single_selection())
4730 this.load_identity(id, 'edit-identity');
4733 // load identity record
4734 this.load_identity = function(id, action)
4736 if (action=='edit-identity' && (!id || id==this.env.iid))
4739 var add_url = '', target = window;
4741 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
4742 add_url = '&_framed=1';
4743 target = window.frames[this.env.contentframe];
4744 document.getElementById(this.env.contentframe).style.visibility = 'inherit';
4747 if (action && (id || action=='add-identity')) {
4748 this.set_busy(true);
4749 this.location_href(this.env.comm_path+'&_action='+action+'&_iid='+id+add_url, target);
4755 this.delete_identity = function(id)
4757 // exit if no mailbox specified or if selection is empty
4758 var selection = this.identity_list.get_selection();
4759 if (!(selection.length || this.env.iid))
4763 id = this.env.iid ? this.env.iid : selection[0];
4765 // append token to request
4766 this.goto_url('delete-identity', '_iid='+id+'&_token='+this.env.request_token, true);
4772 /*********************************************************/
4773 /********* folder manager methods *********/
4774 /*********************************************************/
4776 this.init_subscription_list = function()
4779 this.subscription_list = new rcube_list_widget(this.gui_objects.subscriptionlist,
4780 {multiselect:false, draggable:true, keyboard:false, toggleselect:true});
4781 this.subscription_list.addEventListener('select', function(o){ p.subscription_select(o); });
4782 this.subscription_list.addEventListener('dragstart', function(o){ p.drag_active = true; });
4783 this.subscription_list.addEventListener('dragend', function(o){ p.subscription_move_folder(o); });
4784 this.subscription_list.row_init = function (row) {
4785 row.obj.onmouseover = function() { p.focus_subscription(row.id); };
4786 row.obj.onmouseout = function() { p.unfocus_subscription(row.id); };
4788 this.subscription_list.init();
4790 .mouseover(function(){ p.focus_subscription(this.id); })
4791 .mouseout(function(){ p.unfocus_subscription(this.id); })
4794 this.focus_subscription = function(id)
4797 delim = RegExp.escape(this.env.delimiter),
4798 reg = RegExp('['+delim+']?[^'+delim+']+$');
4800 if (this.drag_active && this.env.mailbox && (row = document.getElementById(id)))
4801 if (this.env.subscriptionrows[id] &&
4802 (folder = this.env.subscriptionrows[id][0]) !== null
4804 if (this.check_droptarget(folder) &&
4805 !this.env.subscriptionrows[this.get_folder_row_id(this.env.mailbox)][2] &&
4806 (folder != this.env.mailbox.replace(reg, '')) &&
4807 (!folder.match(new RegExp('^'+RegExp.escape(this.env.mailbox+this.env.delimiter))))
4809 this.env.dstfolder = folder;
4810 $(row).addClass('droptarget');
4815 this.unfocus_subscription = function(id)
4817 var row = $('#'+id);
4819 this.env.dstfolder = null;
4820 if (this.env.subscriptionrows[id] && row[0])
4821 row.removeClass('droptarget');
4823 $(this.subscription_list.frame).removeClass('droptarget');
4826 this.subscription_select = function(list)
4830 if (list && (id = list.get_single_selection()) &&
4831 (folder = this.env.subscriptionrows['rcmrow'+id])
4833 this.env.mailbox = folder[0];
4834 this.show_folder(folder[0]);
4835 this.enable_command('delete-folder', !folder[2]);
4838 this.env.mailbox = null;
4839 this.show_contentframe(false);
4840 this.enable_command('delete-folder', 'purge', false);
4844 this.subscription_move_folder = function(list)
4846 var delim = RegExp.escape(this.env.delimiter),
4847 reg = RegExp('['+delim+']?[^'+delim+']+$');
4849 if (this.env.mailbox && this.env.dstfolder !== null && (this.env.dstfolder != this.env.mailbox) &&
4850 (this.env.dstfolder != this.env.mailbox.replace(reg, ''))
4852 reg = new RegExp('[^'+delim+']*['+delim+']', 'g');
4853 var basename = this.env.mailbox.replace(reg, ''),
4854 newname = this.env.dstfolder === '' ? basename : this.env.dstfolder+this.env.delimiter+basename;
4856 if (newname != this.env.mailbox) {
4857 this.http_post('rename-folder', '_folder_oldname='+urlencode(this.env.mailbox)+'&_folder_newname='+urlencode(newname), this.set_busy(true, 'foldermoving'));
4858 this.subscription_list.draglayer.hide();
4861 this.drag_active = false;
4862 this.unfocus_subscription(this.get_folder_row_id(this.env.dstfolder));
4865 // tell server to create and subscribe a new mailbox
4866 this.create_folder = function()
4868 this.show_folder('', this.env.mailbox);
4871 // delete a specific mailbox with all its messages
4872 this.delete_folder = function(name)
4874 var id = this.get_folder_row_id(name ? name : this.env.mailbox),
4875 folder = this.env.subscriptionrows[id][0];
4877 if (folder && confirm(this.get_label('deletefolderconfirm'))) {
4878 var lock = this.set_busy(true, 'folderdeleting');
4879 this.http_post('delete-folder', '_mbox='+urlencode(folder), lock);
4883 // Add folder row to the table and initialize it
4884 this.add_folder_row = function (name, display_name, is_protected, subscribed, skip_init, class_name)
4886 if (!this.gui_objects.subscriptionlist)
4889 var row, n, i, tmp, folders, rowid, list = [], slist = [],
4890 tbody = this.gui_objects.subscriptionlist.tBodies[0],
4891 refrow = $('tr', tbody).get(1),
4892 id = 'rcmrow'+((new Date).getTime());
4895 // Refresh page if we don't have a table row to clone
4896 this.goto_url('folders');
4900 // clone a table row if there are existing rows
4901 row = $(refrow).clone(true);
4903 // set ID, reset css class
4905 row.attr('class', class_name);
4908 row.find('td:first').html(display_name);
4910 // update subscription checkbox
4911 $('input[name="_subscribed[]"]', row).val(name)
4912 .prop({checked: subscribed ? true : false, disabled: is_protected ? true : false});
4914 // add to folder/row-ID map
4915 this.env.subscriptionrows[id] = [name, display_name, 0];
4917 // sort folders, to find a place where to insert the row
4919 $.each(this.env.subscriptionrows, function(k,v){ folders.push(v) });
4920 folders.sort(function(a,b){ return a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0) });
4922 for (n in folders) {
4924 if (folders[n][2]) {
4925 slist.push(folders[n][0]);
4926 tmp = folders[n][0]+this.env.delimiter;
4928 // protected folder's child
4929 else if (tmp && folders[n][0].indexOf(tmp) == 0)
4930 slist.push(folders[n][0]);
4933 list.push(folders[n][0]);
4938 // check if subfolder of a protected folder
4939 for (n=0; n<slist.length; n++) {
4940 if (name.indexOf(slist[n]+this.env.delimiter) == 0)
4941 rowid = this.get_folder_row_id(slist[n]);
4944 // find folder position after sorting
4945 for (n=0; !rowid && n<list.length; n++) {
4946 if (n && list[n] == name)
4947 rowid = this.get_folder_row_id(list[n-1]);
4950 // add row to the table
4952 $('#'+rowid).after(row);
4954 row.appendTo(tbody);
4956 // update list widget
4957 this.subscription_list.clear_selection();
4959 this.init_subscription_list();
4962 if (row.scrollIntoView)
4963 row.scrollIntoView();
4968 // replace an existing table row with a new folder line (with subfolders)
4969 this.replace_folder_row = function(oldfolder, newfolder, display_name, is_protected, class_name)
4971 if (!this.gui_objects.subscriptionlist)
4974 var i, n, len, name, dispname, oldrow, tmprow, row, level,
4975 tbody = this.gui_objects.subscriptionlist.tBodies[0],
4976 folders = this.env.subscriptionrows,
4977 id = this.get_folder_row_id(oldfolder),
4978 regex = new RegExp('^'+RegExp.escape(oldfolder)),
4979 subscribed = $('input[name="_subscribed[]"]', $('#'+id)).prop('checked'),
4980 // find subfolders of renamed folder
4981 list = this.get_subfolders(oldfolder);
4983 // replace an existing table row
4984 this._remove_folder_row(id);
4985 row = $(this.add_folder_row(newfolder, display_name, is_protected, subscribed, true, class_name));
4987 // detect tree depth change
4988 if (len = list.length) {
4989 level = (oldfolder.split(this.env.delimiter)).length - (newfolder.split(this.env.delimiter)).length;
4992 // move subfolders to the new branch
4993 for (n=0; n<len; n++) {
4995 name = this.env.subscriptionrows[id][0];
4996 dispname = this.env.subscriptionrows[id][1];
4998 tmprow = oldrow.clone(true);
5002 // update folder index
5003 name = name.replace(regex, newfolder);
5004 $('input[name="_subscribed[]"]', row).val(name);
5005 this.env.subscriptionrows[id][0] = name;
5006 // update the name if level is changed
5009 for (i=level; i>0; i--)
5010 dispname = dispname.replace(/^ /, '');
5013 for (i=level; i<0; i++)
5014 dispname = ' ' + dispname;
5016 row.find('td:first').html(dispname);
5017 this.env.subscriptionrows[id][1] = dispname;
5021 // update list widget
5022 this.init_subscription_list();
5025 // remove the table row of a specific mailbox from the table
5026 this.remove_folder_row = function(folder, subs)
5028 var n, len, list = [], id = this.get_folder_row_id(folder);
5030 // get subfolders if any
5032 list = this.get_subfolders(folder);
5035 this._remove_folder_row(id);
5037 // remove subfolders
5038 for (n=0, len=list.length; n<len; n++)
5039 this._remove_folder_row(list[n]);
5042 this._remove_folder_row = function(id)
5044 this.subscription_list.remove_row(id.replace(/^rcmrow/, ''));
5046 delete this.env.subscriptionrows[id];
5049 this.get_subfolders = function(folder)
5051 var name, list = [],
5052 regex = new RegExp('^'+RegExp.escape(folder)+RegExp.escape(this.env.delimiter)),
5053 row = $('#'+this.get_folder_row_id(folder)).get(0);
5055 while (row = row.nextSibling) {
5057 name = this.env.subscriptionrows[row.id][0];
5058 if (regex.test(name)) {
5069 this.subscribe = function(folder)
5072 var lock = this.display_message(this.get_label('foldersubscribing'), 'loading');
5073 this.http_post('subscribe', '_mbox='+urlencode(folder), lock);
5077 this.unsubscribe = function(folder)
5080 var lock = this.display_message(this.get_label('folderunsubscribing'), 'loading');
5081 this.http_post('unsubscribe', '_mbox='+urlencode(folder), lock);
5085 // helper method to find a specific mailbox row ID
5086 this.get_folder_row_id = function(folder)
5088 var id, folders = this.env.subscriptionrows;
5090 if (folders[id] && folders[id][0] == folder)
5096 // when user select a folder in manager
5097 this.show_folder = function(folder, path, force)
5099 var target = window,
5100 url = '&_action=edit-folder&_mbox='+urlencode(folder);
5103 url += '&_path='+urlencode(path);
5105 if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
5106 target = window.frames[this.env.contentframe];
5107 url += '&_framed=1';
5110 if (String(target.location.href).indexOf(url) >= 0 && !force) {
5111 this.show_contentframe(true);
5114 this.location_href(this.env.comm_path+url, target, true);
5118 // disables subscription checkbox (for protected folder)
5119 this.disable_subscription = function(folder)
5121 var id = this.get_folder_row_id(folder);
5123 $('input[name="_subscribed[]"]', $('#'+id)).prop('disabled', true);
5126 this.folder_size = function(folder)
5128 var lock = this.set_busy(true, 'loading');
5129 this.http_post('folder-size', '_mbox='+urlencode(folder), lock);
5132 this.folder_size_update = function(size)
5134 $('#folder-size').replaceWith(size);
5138 /*********************************************************/
5139 /********* GUI functionality *********/
5140 /*********************************************************/
5142 var init_button = function(cmd, prop)
5144 var elm = document.getElementById(prop.id);
5148 var preload = false;
5149 if (prop.type == 'image') {
5150 elm = elm.parentNode;
5157 elm.onmousedown = function(e){ return rcmail.button_sel(this._command, this._id); };
5158 elm.onmouseup = function(e){ return rcmail.button_out(this._command, this._id); };
5160 new Image().src = prop.sel;
5163 elm.onmouseover = function(e){ return rcmail.button_over(this._command, this._id); };
5164 elm.onmouseout = function(e){ return rcmail.button_out(this._command, this._id); };
5166 new Image().src = prop.over;
5170 // enable/disable buttons for page shifting
5171 this.set_page_buttons = function()
5173 this.enable_command('nextpage', 'lastpage', (this.env.pagecount > this.env.current_page));
5174 this.enable_command('previouspage', 'firstpage', (this.env.current_page > 1));
5177 // set event handlers on registered buttons
5178 this.init_buttons = function()
5180 for (var cmd in this.buttons) {
5181 if (typeof cmd !== 'string')
5184 for (var i=0; i< this.buttons[cmd].length; i++) {
5185 init_button(cmd, this.buttons[cmd][i]);
5189 // set active task button
5190 this.set_button(this.task, 'sel');
5193 // set button to a specific state
5194 this.set_button = function(command, state)
5196 var n, button, obj, a_buttons = this.buttons[command],
5197 len = a_buttons ? a_buttons.length : 0;
5199 for (n=0; n<len; n++) {
5200 button = a_buttons[n];
5201 obj = document.getElementById(button.id);
5203 // get default/passive setting of the button
5204 if (obj && button.type=='image' && !button.status) {
5205 button.pas = obj._original_src ? obj._original_src : obj.src;
5206 // respect PNG fix on IE browsers
5207 if (obj.runtimeStyle && obj.runtimeStyle.filter && obj.runtimeStyle.filter.match(/src=['"]([^'"]+)['"]/))
5208 button.pas = RegExp.$1;
5210 else if (obj && !button.status)
5211 button.pas = String(obj.className);
5213 // set image according to button state
5214 if (obj && button.type=='image' && button[state]) {
5215 button.status = state;
5216 obj.src = button[state];
5218 // set class name according to button state
5219 else if (obj && button[state] !== undefined) {
5220 button.status = state;
5221 obj.className = button[state];
5223 // disable/enable input buttons
5224 if (obj && button.type=='input') {
5225 button.status = state;
5226 obj.disabled = !state;
5231 // display a specific alttext
5232 this.set_alttext = function(command, label)
5234 var n, button, obj, link, a_buttons = this.buttons[command],
5235 len = a_buttons ? a_buttons.length : 0;
5237 for (n=0; n<len; n++) {
5238 button = a_buttons[n];
5239 obj = document.getElementById(button.id);
5241 if (button.type == 'image' && obj) {
5242 obj.setAttribute('alt', this.get_label(label));
5243 if ((link = obj.parentNode) && link.tagName.toLowerCase() == 'a')
5244 link.setAttribute('title', this.get_label(label));
5247 obj.setAttribute('title', this.get_label(label));
5251 // mouse over button
5252 this.button_over = function(command, id)
5254 var n, button, obj, a_buttons = this.buttons[command],
5255 len = a_buttons ? a_buttons.length : 0;
5257 for (n=0; n<len; n++) {
5258 button = a_buttons[n];
5259 if (button.id == id && button.status == 'act') {
5260 obj = document.getElementById(button.id);
5261 if (obj && button.over) {
5262 if (button.type == 'image')
5263 obj.src = button.over;
5265 obj.className = button.over;
5271 // mouse down on button
5272 this.button_sel = function(command, id)
5274 var n, button, obj, a_buttons = this.buttons[command],
5275 len = a_buttons ? a_buttons.length : 0;
5277 for (n=0; n<len; n++) {
5278 button = a_buttons[n];
5279 if (button.id == id && button.status == 'act') {
5280 obj = document.getElementById(button.id);
5281 if (obj && button.sel) {
5282 if (button.type == 'image')
5283 obj.src = button.sel;
5285 obj.className = button.sel;
5287 this.buttons_sel[id] = command;
5292 // mouse out of button
5293 this.button_out = function(command, id)
5295 var n, button, obj, a_buttons = this.buttons[command],
5296 len = a_buttons ? a_buttons.length : 0;
5298 for (n=0; n<len; n++) {
5299 button = a_buttons[n];
5300 if (button.id == id && button.status == 'act') {
5301 obj = document.getElementById(button.id);
5302 if (obj && button.act) {
5303 if (button.type == 'image')
5304 obj.src = button.act;
5306 obj.className = button.act;
5312 this.focus_textfield = function(elem)
5314 elem._hasfocus = true;
5315 var $elem = $(elem);
5316 if ($elem.hasClass('placeholder') || $elem.val() == elem._placeholder)
5317 $elem.val('').removeClass('placeholder').attr('spellcheck', true);
5320 this.blur_textfield = function(elem)
5322 elem._hasfocus = false;
5323 var $elem = $(elem);
5324 if (elem._placeholder && (!$elem.val() || $elem.val() == elem._placeholder))
5325 $elem.addClass('placeholder').attr('spellcheck', false).val(elem._placeholder);
5328 // write to the document/window title
5329 this.set_pagetitle = function(title)
5331 if (title && document.title)
5332 document.title = title;
5335 // display a system message, list of types in common.css (below #message definition)
5336 this.display_message = function(msg, type, timeout)
5338 // pass command to parent window
5339 if (this.is_framed())
5340 return parent.rcmail.display_message(msg, type, timeout);
5342 if (!this.gui_objects.message) {
5343 // save message in order to display after page loaded
5344 if (type != 'loading')
5345 this.pending_message = [msg, type, timeout];
5349 type = type ? type : 'notice';
5352 key = this.html_identifier(msg),
5354 id = type + date.getTime();
5357 timeout = this.message_time * (type == 'error' || type == 'warning' ? 2 : 1);
5359 if (type == 'loading') {
5361 timeout = this.env.request_timeout * 1000;
5363 msg = this.get_label('loading');
5366 // The same message is already displayed
5367 if (this.messages[key]) {
5369 if (this.messages[key].obj)
5370 this.messages[key].obj.html(msg);
5371 // store label in stack
5372 if (type == 'loading') {
5373 this.messages[key].labels.push({'id': id, 'msg': msg});
5375 // add element and set timeout
5376 this.messages[key].elements.push(id);
5377 window.setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
5381 // create DOM object and display it
5382 var obj = $('<div>').addClass(type).html(msg).data('key', key),
5383 cont = $(this.gui_objects.message).append(obj).show();
5385 this.messages[key] = {'obj': obj, 'elements': [id]};
5387 if (type == 'loading') {
5388 this.messages[key].labels = [{'id': id, 'msg': msg}];
5391 obj.click(function() { return ref.hide_message(obj); });
5395 window.setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
5399 // make a message to disapear
5400 this.hide_message = function(obj, fade)
5402 // pass command to parent window
5403 if (this.is_framed())
5404 return parent.rcmail.hide_message(obj, fade);
5406 var k, n, i, msg, m = this.messages;
5408 // Hide message by object, don't use for 'loading'!
5409 if (typeof obj === 'object') {
5410 $(obj)[fade?'fadeOut':'hide']();
5411 msg = $(obj).data('key');
5412 if (this.messages[msg])
5413 delete this.messages[msg];
5415 // Hide message by id
5418 for (n in m[k].elements) {
5419 if (m[k] && m[k].elements[n] == obj) {
5420 m[k].elements.splice(n, 1);
5421 // hide DOM element if last instance is removed
5422 if (!m[k].elements.length) {
5423 m[k].obj[fade?'fadeOut':'hide']();
5426 // set pending action label for 'loading' message
5427 else if (k == 'loading') {
5428 for (i in m[k].labels) {
5429 if (m[k].labels[i].id == obj) {
5430 delete m[k].labels[i];
5433 msg = m[k].labels[i].msg;
5444 // mark a mailbox as selected and set environment variable
5445 this.select_folder = function(name, prefix, encode)
5447 if (this.gui_objects.folderlist) {
5448 var current_li, target_li;
5450 if ((current_li = $('li.selected', this.gui_objects.folderlist))) {
5451 current_li.removeClass('selected').addClass('unfocused');
5453 if ((target_li = this.get_folder_li(name, prefix, encode))) {
5454 $(target_li).removeClass('unfocused').addClass('selected');
5457 // trigger event hook
5458 this.triggerEvent('selectfolder', { folder:name, prefix:prefix });
5462 // helper method to find a folder list item
5463 this.get_folder_li = function(name, prefix, encode)
5468 if (this.gui_objects.folderlist) {
5469 name = this.html_identifier(name, encode);
5470 return document.getElementById(prefix+name);
5476 // for reordering column array (Konqueror workaround)
5477 // and for setting some message list global variables
5478 this.set_message_coltypes = function(coltypes, repl)
5480 var list = this.message_list,
5481 thead = list ? list.list.tHead : null,
5482 cell, col, n, len, th, tr;
5484 this.env.coltypes = coltypes;
5486 // replace old column headers
5489 th = document.createElement('thead');
5490 tr = document.createElement('tr');
5492 for (c=0, len=repl.length; c < len; c++) {
5493 cell = document.createElement('td');
5494 cell.innerHTML = repl[c].html;
5495 if (repl[c].id) cell.id = repl[c].id;
5496 if (repl[c].className) cell.className = repl[c].className;
5497 tr.appendChild(cell);
5500 thead.parentNode.replaceChild(th, thead);
5504 for (n=0, len=this.env.coltypes.length; n<len; n++) {
5505 col = this.env.coltypes[n];
5506 if ((cell = thead.rows[0].cells[n]) && (col=='from' || col=='to')) {
5507 cell.id = 'rcm'+col;
5508 // if we have links for sorting, it's a bit more complicated...
5509 if (cell.firstChild && cell.firstChild.tagName.toLowerCase()=='a') {
5510 cell = cell.firstChild;
5511 cell.onclick = function(){ return rcmail.command('sort', this.__col, this); };
5514 cell.innerHTML = this.get_label(col);
5519 this.env.subject_col = null;
5520 this.env.flagged_col = null;
5521 this.env.status_col = null;
5523 if ((n = $.inArray('subject', this.env.coltypes)) >= 0) {
5524 this.env.subject_col = n;
5526 list.subject_col = n;
5528 if ((n = $.inArray('flag', this.env.coltypes)) >= 0)
5529 this.env.flagged_col = n;
5530 if ((n = $.inArray('status', this.env.coltypes)) >= 0)
5531 this.env.status_col = n;
5537 // replace content of row count display
5538 this.set_rowcount = function(text, mbox)
5541 if (mbox && mbox != this.env.mailbox)
5544 $(this.gui_objects.countdisplay).html(text);
5546 // update page navigation buttons
5547 this.set_page_buttons();
5550 // replace content of mailboxname display
5551 this.set_mailboxname = function(content)
5553 if (this.gui_objects.mailboxname && content)
5554 this.gui_objects.mailboxname.innerHTML = content;
5557 // replace content of quota display
5558 this.set_quota = function(content)
5560 if (content && this.gui_objects.quotadisplay) {
5561 if (typeof content === 'object' && content.type == 'image')
5562 this.percent_indicator(this.gui_objects.quotadisplay, content);
5564 $(this.gui_objects.quotadisplay).html(content);
5568 // update the mailboxlist
5569 this.set_unread_count = function(mbox, count, set_title)
5571 if (!this.gui_objects.mailboxlist)
5574 this.env.unread_counts[mbox] = count;
5575 this.set_unread_count_display(mbox, set_title);
5578 // update the mailbox count display
5579 this.set_unread_count_display = function(mbox, set_title)
5581 var reg, link, text_obj, item, mycount, childcount, div;
5583 if (item = this.get_folder_li(mbox, '', true)) {
5584 mycount = this.env.unread_counts[mbox] ? this.env.unread_counts[mbox] : 0;
5585 link = $(item).children('a').eq(0);
5586 text_obj = link.children('span.unreadcount');
5587 if (!text_obj.length && mycount)
5588 text_obj = $('<span>').addClass('unreadcount').appendTo(link);
5589 reg = /\s+\([0-9]+\)$/i;
5592 if ((div = item.getElementsByTagName('div')[0]) &&
5593 div.className.match(/collapsed/)) {
5594 // add children's counters
5595 for (var k in this.env.unread_counts)
5596 if (k.indexOf(mbox + this.env.delimiter) == 0)
5597 childcount += this.env.unread_counts[k];
5600 if (mycount && text_obj.length)
5601 text_obj.html(' ('+mycount+')');
5602 else if (text_obj.length)
5605 // set parent's display
5606 reg = new RegExp(RegExp.escape(this.env.delimiter) + '[^' + RegExp.escape(this.env.delimiter) + ']+$');
5607 if (mbox.match(reg))
5608 this.set_unread_count_display(mbox.replace(reg, ''), false);
5610 // set the right classes
5611 if ((mycount+childcount)>0)
5612 $(item).addClass('unread');
5614 $(item).removeClass('unread');
5617 // set unread count to window title
5618 reg = /^\([0-9]+\)\s+/i;
5619 if (set_title && document.title) {
5621 doc_title = String(document.title);
5623 if (mycount && doc_title.match(reg))
5624 new_title = doc_title.replace(reg, '('+mycount+') ');
5626 new_title = '('+mycount+') '+doc_title;
5628 new_title = doc_title.replace(reg, '');
5630 this.set_pagetitle(new_title);
5634 this.toggle_prefer_html = function(checkbox)
5636 $('#rcmfd_show_images').prop('disabled', !checkbox.checked).val(0);
5639 this.toggle_preview_pane = function(checkbox)
5641 $('#rcmfd_preview_pane_mark_read').prop('disabled', !checkbox.checked);
5644 // display fetched raw headers
5645 this.set_headers = function(content)
5647 if (this.gui_objects.all_headers_row && this.gui_objects.all_headers_box && content)
5648 $(this.gui_objects.all_headers_box).html(content).show();
5651 // display all-headers row and fetch raw message headers
5652 this.load_headers = function(elem)
5654 if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box || !this.env.uid)
5657 $(elem).removeClass('show-headers').addClass('hide-headers');
5658 $(this.gui_objects.all_headers_row).show();
5659 elem.onclick = function() { rcmail.hide_headers(elem); };
5661 // fetch headers only once
5662 if (!this.gui_objects.all_headers_box.innerHTML) {
5663 var lock = this.display_message(this.get_label('loading'), 'loading');
5664 this.http_post('headers', '_uid='+this.env.uid, lock);
5668 // hide all-headers row
5669 this.hide_headers = function(elem)
5671 if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box)
5674 $(elem).removeClass('hide-headers').addClass('show-headers');
5675 $(this.gui_objects.all_headers_row).hide();
5676 elem.onclick = function() { rcmail.load_headers(elem); };
5679 // percent (quota) indicator
5680 this.percent_indicator = function(obj, data)
5685 var limit_high = 80,
5687 width = data.width ? data.width : this.env.indicator_width ? this.env.indicator_width : 100,
5688 height = data.height ? data.height : this.env.indicator_height ? this.env.indicator_height : 14,
5689 quota = data.percent ? Math.abs(parseInt(data.percent)) : 0,
5690 quota_width = parseInt(quota / 100 * width),
5691 pos = $(obj).position();
5693 // workarounds for Opera and Webkit bugs
5694 pos.top = Math.max(0, pos.top);
5695 pos.left = Math.max(0, pos.left);
5697 this.env.indicator_width = width;
5698 this.env.indicator_height = height;
5701 if (quota_width > width) {
5702 quota_width = width;
5707 data.title = this.get_label('quota') + ': ' + data.title;
5710 var main = $('<div>');
5711 main.css({position: 'absolute', top: pos.top, left: pos.left,
5712 width: width + 'px', height: height + 'px', zIndex: 100, lineHeight: height + 'px'})
5713 .attr('title', data.title).addClass('quota_text').html(quota + '%');
5715 var bar1 = $('<div>');
5716 bar1.css({position: 'absolute', top: pos.top + 1, left: pos.left + 1,
5717 width: quota_width + 'px', height: height + 'px', zIndex: 99});
5719 var bar2 = $('<div>');
5720 bar2.css({position: 'absolute', top: pos.top + 1, left: pos.left + 1,
5721 width: width + 'px', height: height + 'px', zIndex: 98})
5722 .addClass('quota_bg');
5724 if (quota >= limit_high) {
5725 main.addClass(' quota_text_high');
5726 bar1.addClass('quota_high');
5728 else if(quota >= limit_mid) {
5729 main.addClass(' quota_text_mid');
5730 bar1.addClass('quota_mid');
5733 main.addClass(' quota_text_low');
5734 bar1.addClass('quota_low');
5737 // replace quota image
5738 $(obj).html('').append(bar1).append(bar2).append(main);
5739 // update #quotaimg title
5740 $('#quotaimg').attr('title', data.title);
5743 /********************************************************/
5744 /********* html to text conversion functions *********/
5745 /********************************************************/
5747 this.html2plain = function(htmlText, id)
5750 url = '?_task=utils&_action=html2text',
5751 lock = this.set_busy(true, 'converting');
5753 this.log('HTTP POST: ' + url);
5755 $.ajax({ type: 'POST', url: url, data: htmlText, contentType: 'application/octet-stream',
5756 error: function(o, status, err) { rcmail.http_error(o, status, err, lock); },
5757 success: function(data) { rcmail.set_busy(false, null, lock); $('#'+id).val(data); rcmail.log(data); }
5761 this.plain2html = function(plain, id)
5763 var lock = this.set_busy(true, 'converting');
5765 plain = plain.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
5766 $('#'+id).val(plain ? '<pre>'+plain+'</pre>' : '');
5768 this.set_busy(false, null, lock);
5772 /********************************************************/
5773 /********* remote request methods *********/
5774 /********************************************************/
5776 // compose a valid url with the given parameters
5777 this.url = function(action, query)
5779 var querystring = typeof query === 'string' ? '&' + query : '';
5781 if (typeof action !== 'string')
5783 else if (!query || typeof query !== 'object')
5787 query._action = action;
5789 query._action = this.env.action;
5791 var base = this.env.comm_path;
5793 // overwrite task name
5794 if (query._action.match(/([a-z]+)\/([a-z0-9-_.]+)/)) {
5795 query._action = RegExp.$2;
5796 base = base.replace(/\_task=[a-z]+/, '_task='+RegExp.$1);
5799 // remove undefined values
5801 for (var k in query) {
5802 if (query[k] !== undefined && query[k] !== null)
5803 param[k] = query[k];
5806 return base + '&' + $.param(param) + querystring;
5809 this.redirect = function(url, lock)
5811 if (lock || lock === null)
5812 this.set_busy(true);
5814 if (this.is_framed())
5815 parent.rcmail.redirect(url, lock);
5817 this.location_href(url, window);
5820 this.goto_url = function(action, query, lock)
5822 this.redirect(this.url(action, query));
5825 this.location_href = function(url, target, frame)
5830 // simulate real link click to force IE to send referer header
5831 if (bw.ie && target == window)
5832 $('<a>').attr('href', url).appendTo(document.body).get(0).click();
5834 target.location.href = url;
5837 // send a http request to the server
5838 this.http_request = function(action, query, lock)
5840 var url = this.url(action, query);
5842 // trigger plugin hook
5843 var result = this.triggerEvent('request'+action, query);
5845 if (result !== undefined) {
5846 // abort if one the handlers returned false
5847 if (result === false)
5853 url += '&_remote=1';
5856 this.log('HTTP GET: ' + url);
5859 type: 'GET', url: url, data: { _unlock:(lock?lock:0) }, dataType: 'json',
5860 success: function(data){ ref.http_response(data); },
5861 error: function(o, status, err) { rcmail.http_error(o, status, err, lock); }
5865 // send a http POST request to the server
5866 this.http_post = function(action, postdata, lock)
5868 var url = this.url(action);
5870 if (postdata && typeof postdata === 'object') {
5871 postdata._remote = 1;
5872 postdata._unlock = (lock ? lock : 0);
5875 postdata += (postdata ? '&' : '') + '_remote=1' + (lock ? '&_unlock='+lock : '');
5877 // trigger plugin hook
5878 var result = this.triggerEvent('request'+action, postdata);
5879 if (result !== undefined) {
5880 // abort if one the handlers returned false
5881 if (result === false)
5888 this.log('HTTP POST: ' + url);
5891 type: 'POST', url: url, data: postdata, dataType: 'json',
5892 success: function(data){ ref.http_response(data); },
5893 error: function(o, status, err) { rcmail.http_error(o, status, err, lock); }
5897 // aborts ajax request
5898 this.abort_request = function(r)
5903 this.set_busy(false, null, r.lock);
5906 // handle HTTP response
5907 this.http_response = function(response)
5912 if (response.unlock)
5913 this.set_busy(false);
5915 this.triggerEvent('responsebefore', {response: response});
5916 this.triggerEvent('responsebefore'+response.action, {response: response});
5920 this.set_env(response.env);
5922 // we have labels to add
5923 if (typeof response.texts === 'object') {
5924 for (var name in response.texts)
5925 if (typeof response.texts[name] === 'string')
5926 this.add_label(name, response.texts[name]);
5929 // if we get javascript code from server -> execute it
5930 if (response.exec) {
5931 this.log(response.exec);
5932 eval(response.exec);
5935 // execute callback functions of plugins
5936 if (response.callbacks && response.callbacks.length) {
5937 for (var i=0; i < response.callbacks.length; i++)
5938 this.triggerEvent(response.callbacks[i][0], response.callbacks[i][1]);
5941 // process the response data according to the sent action
5942 switch (response.action) {
5944 if (this.task == 'addressbook') {
5945 var sid, uid = this.contact_list.get_selection(), writable = false;
5947 if (uid && this.contact_list.rows[uid]) {
5948 // search results, get source ID from record ID
5949 if (this.env.source == '') {
5950 sid = String(uid).replace(/^[^-]+-/, '');
5951 writable = sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly;
5954 writable = !this.env.address_sources[this.env.source].readonly;
5957 this.enable_command('compose', (uid && this.contact_list.rows[uid]));
5958 this.enable_command('delete', 'edit', writable);
5959 this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
5963 if (this.env.action == 'show') {
5964 // re-enable commands on move/delete error
5965 this.enable_command(this.env.message_commands, true);
5966 if (!this.env.list_post)
5967 this.enable_command('reply-list', false);
5969 else if (this.task == 'addressbook') {
5970 this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
5975 if (this.task == 'mail') {
5976 if (!this.env.messagecount) {
5977 // clear preview pane content
5978 if (this.env.contentframe)
5979 this.show_contentframe(false);
5980 // disable commands useless when mailbox is empty
5981 this.enable_command(this.env.message_commands, 'purge', 'expunge',
5982 'select-all', 'select-none', 'sort', 'expand-all', 'expand-unread', 'collapse-all', false);
5984 if (this.message_list)
5985 this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
5989 case 'check-recent':
5992 this.env.qsearch = null;
5994 if (this.task == 'mail') {
5995 this.enable_command('show', 'expunge', 'select-all', 'select-none', 'sort', (this.env.messagecount > 0));
5996 this.enable_command('purge', this.purge_mailbox_test());
5997 this.enable_command('expand-all', 'expand-unread', 'collapse-all', this.env.threading && this.env.messagecount);
5999 if (response.action == 'list' || response.action == 'search') {
6000 this.msglist_select(this.message_list);
6001 this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
6004 else if (this.task == 'addressbook') {
6005 this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
6007 if (response.action == 'list' || response.action == 'search') {
6008 this.enable_command('search-create', this.env.source == '');
6009 this.enable_command('search-delete', this.env.search_id);
6010 this.update_group_commands();
6011 this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
6017 if (response.unlock)
6018 this.hide_message(response.unlock);
6020 this.triggerEvent('responseafter', {response: response});
6021 this.triggerEvent('responseafter'+response.action, {response: response});
6024 // handle HTTP request errors
6025 this.http_error = function(request, status, err, lock)
6027 var errmsg = request.statusText;
6029 this.set_busy(false, null, lock);
6032 if (request.status && errmsg)
6033 this.display_message(this.get_label('servererror') + ' (' + errmsg + ')', 'error');
6036 // post the given form to a hidden iframe
6037 this.async_upload_form = function(form, action, onload)
6039 var ts = new Date().getTime(),
6040 frame_name = 'rcmupload'+ts;
6042 // upload progress support
6043 if (this.env.upload_progress_name) {
6044 var fname = this.env.upload_progress_name,
6045 field = $('input[name='+fname+']', form);
6047 if (!field.length) {
6048 field = $('<input>').attr({type: 'hidden', name: fname});
6049 field.prependTo(form);
6055 // have to do it this way for IE
6056 // otherwise the form will be posted to a new window
6058 var html = '<iframe name="'+frame_name+'" src="program/blank.gif" style="width:0;height:0;visibility:hidden;"></iframe>';
6059 document.body.insertAdjacentHTML('BeforeEnd', html);
6061 else { // for standards-compilant browsers
6062 var frame = document.createElement('iframe');
6063 frame.name = frame_name;
6064 frame.style.border = 'none';
6065 frame.style.width = 0;
6066 frame.style.height = 0;
6067 frame.style.visibility = 'hidden';
6068 document.body.appendChild(frame);
6071 // handle upload errors, parsing iframe content in onload
6072 $(frame_name).bind('load', {ts:ts}, onload);
6076 action: this.url(action, { _id:this.env.compose_id||'', _uploadid:ts }),
6078 .attr(form.encoding ? 'encoding' : 'enctype', 'multipart/form-data')
6084 // starts interval for keep-alive/check-recent signal
6085 this.start_keepalive = function()
6088 clearInterval(this._int);
6090 if (this.env.keep_alive && !this.env.framed && this.task == 'mail' && this.gui_objects.mailboxlist)
6091 this._int = setInterval(function(){ ref.check_for_recent(false); }, this.env.keep_alive * 1000);
6092 else if (this.env.keep_alive && !this.env.framed && this.task != 'login' && this.env.action != 'print')
6093 this._int = setInterval(function(){ ref.keep_alive(); }, this.env.keep_alive * 1000);
6096 // sends keep-alive signal
6097 this.keep_alive = function()
6100 this.http_request('keep-alive');
6103 // sends request to check for recent messages
6104 this.check_for_recent = function(refresh)
6109 var lock, addurl = '_mbox=' + urlencode(this.env.mailbox);
6112 lock = this.set_busy(true, 'checkingmail');
6113 addurl += '&_refresh=1';
6114 // reset check-recent interval
6115 this.start_keepalive();
6118 if (this.gui_objects.messagelist)
6119 addurl += '&_list=1';
6120 if (this.gui_objects.quotadisplay)
6121 addurl += '&_quota=1';
6122 if (this.env.search_request)
6123 addurl += '&_search=' + this.env.search_request;
6125 this.http_request('check-recent', addurl, lock);
6129 /********************************************************/
6130 /********* helper methods *********/
6131 /********************************************************/
6133 // check if we're in show mode or if we have a unique selection
6134 // and return the message uid
6135 this.get_single_uid = function()
6137 return this.env.uid ? this.env.uid : (this.message_list ? this.message_list.get_single_selection() : null);
6140 // same as above but for contacts
6141 this.get_single_cid = function()
6143 return this.env.cid ? this.env.cid : (this.contact_list ? this.contact_list.get_single_selection() : null);
6146 // gets cursor position
6147 this.get_caret_pos = function(obj)
6149 if (obj.selectionEnd !== undefined)
6150 return obj.selectionEnd;
6151 else if (document.selection && document.selection.createRange) {
6152 var range = document.selection.createRange();
6153 if (range.parentElement()!=obj)
6156 var gm = range.duplicate();
6157 if (obj.tagName == 'TEXTAREA')
6158 gm.moveToElementText(obj);
6160 gm.expand('textedit');
6162 gm.setEndPoint('EndToStart', range);
6163 var p = gm.text.length;
6165 return p<=obj.value.length ? p : -1;
6168 return obj.value.length;
6171 // moves cursor to specified position
6172 this.set_caret_pos = function(obj, pos)
6174 if (obj.setSelectionRange)
6175 obj.setSelectionRange(pos, pos);
6176 else if (obj.createTextRange) {
6177 var range = obj.createTextRange();
6178 range.collapse(true);
6179 range.moveEnd('character', pos);
6180 range.moveStart('character', pos);
6185 // disable/enable all fields of a form
6186 this.lock_form = function(form, lock)
6188 if (!form || !form.elements)
6194 this.disabled_form_elements = [];
6196 for (n=0, len=form.elements.length; n<len; n++) {
6197 elm = form.elements[n];
6199 if (elm.type == 'hidden')
6201 // remember which elem was disabled before lock
6202 if (lock && elm.disabled)
6203 this.disabled_form_elements.push(elm);
6204 // check this.disabled_form_elements before inArray() as a workaround for FF5 bug
6205 // http://bugs.jquery.com/ticket/9873
6206 else if (lock || (this.disabled_form_elements && $.inArray(elm, this.disabled_form_elements)<0))
6207 elm.disabled = lock;
6211 } // end object rcube_webmail
6214 // some static methods
6215 rcube_webmail.long_subject_title = function(elem, indent)
6218 var $elem = $(elem);
6219 if ($elem.width() + indent * 15 > $elem.parent().width())
6220 elem.title = $elem.html();
6224 rcube_webmail.long_subject_title_ie = function(elem, indent)
6227 var $elem = $(elem),
6228 txt = $.trim($elem.text()),
6229 tmp = $('<span>').text(txt)
6230 .css({'position': 'absolute', 'float': 'left', 'visibility': 'hidden',
6231 'font-size': $elem.css('font-size'), 'font-weight': $elem.css('font-weight')})
6232 .appendTo($('body')),
6236 if (w + indent * 15 > $elem.width())
6241 // copy event engine prototype
6242 rcube_webmail.prototype.addEventListener = rcube_event_engine.prototype.addEventListener;
6243 rcube_webmail.prototype.removeEventListener = rcube_event_engine.prototype.removeEventListener;
6244 rcube_webmail.prototype.triggerEvent = rcube_event_engine.prototype.triggerEvent;