]> git.donarmstrong.com Git - roundcube.git/blob - program/js/list.js.src
e47b5470d6692c222a1392f0c67fc2501e7fdda0
[roundcube.git] / program / js / list.js.src
1 /*
2  +-----------------------------------------------------------------------+
3  | Roundcube List Widget                                                 |
4  |                                                                       |
5  | This file is part of the Roundcube Webmail client                     |
6  | Copyright (C) 2006-2009, The Roundcube Dev Team                       |
7  | Licensed under the GNU GPL                                            |
8  |                                                                       |
9  +-----------------------------------------------------------------------+
10  | Authors: Thomas Bruederli <roundcube@gmail.com>                       |
11  |          Charles McNulty <charles@charlesmcnulty.com>                 |
12  +-----------------------------------------------------------------------+
13  | Requires: common.js                                                   |
14  +-----------------------------------------------------------------------+
15
16   $Id: list.js 4750 2011-05-12 09:27:17Z alec $
17 */
18
19
20 /**
21  * Roundcube List Widget class
22  * @contructor
23  */
24 function rcube_list_widget(list, p)
25 {
26   // static contants
27   this.ENTER_KEY = 13;
28   this.DELETE_KEY = 46;
29   this.BACKSPACE_KEY = 8;
30
31   this.list = list ? list : null;
32   this.frame = null;
33   this.rows = [];
34   this.selection = [];
35   this.rowcount = 0;
36   this.colcount = 0;
37
38   this.subject_col = -1;
39   this.shiftkey = false;
40   this.multiselect = false;
41   this.multiexpand = false;
42   this.multi_selecting = false;
43   this.draggable = false;
44   this.column_movable = false;
45   this.keyboard = false;
46   this.toggleselect = false;
47
48   this.dont_select = false;
49   this.drag_active = false;
50   this.col_drag_active = false;
51   this.column_fixed = null;
52   this.last_selected = 0;
53   this.shift_start = 0;
54   this.in_selection_before = false;
55   this.focused = false;
56   this.drag_mouse_start = null;
57   this.dblclick_time = 600;
58   this.row_init = function(){};
59
60   // overwrite default paramaters
61   if (p && typeof p === 'object')
62     for (var n in p)
63       this[n] = p[n];
64 };
65
66
67 rcube_list_widget.prototype = {
68
69
70 /**
71  * get all message rows from HTML table and init each row
72  */
73 init: function()
74 {
75   if (this.list && this.list.tBodies[0]) {
76     this.rows = [];
77     this.rowcount = 0;
78
79     var r, len, rows = this.list.tBodies[0].rows;
80
81     for (r=0, len=rows.length; r<len; r++) {
82       this.init_row(rows[r]);
83       this.rowcount++;
84     }
85
86     this.init_header();
87     this.frame = this.list.parentNode;
88
89     // set body events
90     if (this.keyboard) {
91       rcube_event.add_listener({event:bw.opera?'keypress':'keydown', object:this, method:'key_press'});
92       rcube_event.add_listener({event:'keydown', object:this, method:'key_down'});
93     }
94   }
95 },
96
97
98 /**
99  * Init list row and set mouse events on it
100  */
101 init_row: function(row)
102 {
103   // make references in internal array and set event handlers
104   if (row && String(row.id).match(/^rcmrow([a-z0-9\-_=\+\/]+)/i)) {
105     var self = this,
106       uid = RegExp.$1;
107     row.uid = uid;
108     this.rows[uid] = {uid:uid, id:row.id, obj:row};
109
110     // set eventhandlers to table row
111     row.onmousedown = function(e){ return self.drag_row(e, this.uid); };
112     row.onmouseup = function(e){ return self.click_row(e, this.uid); };
113
114     if (bw.iphone || bw.ipad) {
115       row.addEventListener('touchstart', function(e) {
116         if (e.touches.length == 1) {
117           if (!self.drag_row(rcube_event.touchevent(e.touches[0]), this.uid))
118             e.preventDefault();
119         }
120       }, false);
121       row.addEventListener('touchend', function(e) {
122         if (e.changedTouches.length == 1)
123           if (!self.click_row(rcube_event.touchevent(e.changedTouches[0]), this.uid))
124             e.preventDefault();
125       }, false);
126     }
127
128     if (document.all)
129       row.onselectstart = function() { return false; };
130
131     this.row_init(this.rows[uid]);
132   }
133 },
134
135
136 /**
137  * Init list column headers and set mouse events on them
138  */
139 init_header: function()
140 {
141   if (this.list && this.list.tHead) {
142     this.colcount = 0;
143
144     var col, r, p = this;
145     // add events for list columns moving
146     if (this.column_movable && this.list.tHead && this.list.tHead.rows) {
147       for (r=0; r<this.list.tHead.rows[0].cells.length; r++) {
148         if (this.column_fixed == r)
149           continue;
150         col = this.list.tHead.rows[0].cells[r];
151         col.onmousedown = function(e){ return p.drag_column(e, this); };
152         this.colcount++;
153       }
154     }
155   }
156 },
157
158
159 /**
160  * Remove all list rows
161  */
162 clear: function(sel)
163 {
164   var tbody = document.createElement('tbody');
165
166   this.list.insertBefore(tbody, this.list.tBodies[0]);
167   this.list.removeChild(this.list.tBodies[1]);
168   this.rows = [];
169   this.rowcount = 0;
170
171   if (sel)
172     this.clear_selection();
173
174   // reset scroll position (in Opera)
175   if (this.frame)
176     this.frame.scrollTop = 0;
177 },
178
179
180 /**
181  * 'remove' message row from list (just hide it)
182  */
183 remove_row: function(uid, sel_next)
184 {
185   if (this.rows[uid].obj)
186     this.rows[uid].obj.style.display = 'none';
187
188   if (sel_next)
189     this.select_next();
190
191   delete this.rows[uid];
192   this.rowcount--;
193 },
194
195
196 /**
197  * Add row to the list and initialize it
198  */
199 insert_row: function(row, attop)
200 {
201   var tbody = this.list.tBodies[0];
202
203   if (attop && tbody.rows.length)
204     tbody.insertBefore(row, tbody.firstChild);
205   else
206     tbody.appendChild(row);
207
208   this.init_row(row);
209   this.rowcount++;
210 },
211
212
213
214 /**
215  * Set focus to the list
216  */
217 focus: function(e)
218 {
219   var n, id;
220   this.focused = true;
221
222   for (n in this.selection) {
223     id = this.selection[n];
224     if (this.rows[id] && this.rows[id].obj) {
225       $(this.rows[id].obj).addClass('selected').removeClass('unfocused');
226     }
227   }
228
229   // Un-focus already focused elements
230   $('*:focus', window).blur();
231   $('iframe').each(function() { this.blur(); });
232
233   if (e || (e = window.event))
234     rcube_event.cancel(e);
235 },
236
237
238 /**
239  * remove focus from the list
240  */
241 blur: function()
242 {
243   var n, id;
244   this.focused = false;
245   for (n in this.selection) {
246     id = this.selection[n];
247     if (this.rows[id] && this.rows[id].obj) {
248       $(this.rows[id].obj).removeClass('selected').addClass('unfocused');
249     }
250   }
251 },
252
253
254 /**
255  * onmousedown-handler of message list column
256  */
257 drag_column: function(e, col)
258 {
259   if (this.colcount > 1) {
260     this.drag_start = true;
261     this.drag_mouse_start = rcube_event.get_mouse_pos(e);
262
263     rcube_event.add_listener({event:'mousemove', object:this, method:'column_drag_mouse_move'});
264     rcube_event.add_listener({event:'mouseup', object:this, method:'column_drag_mouse_up'});
265
266     // enable dragging over iframes
267     this.add_dragfix();
268
269     // find selected column number
270     for (var i=0; i<this.list.tHead.rows[0].cells.length; i++) {
271       if (col == this.list.tHead.rows[0].cells[i]) {
272         this.selected_column = i;
273         break;
274       }
275     }
276   }
277
278   return false;
279 },
280
281
282 /**
283  * onmousedown-handler of message list row
284  */
285 drag_row: function(e, id)
286 {
287   // don't do anything (another action processed before)
288   var evtarget = rcube_event.get_target(e),
289     tagname = evtarget.tagName.toLowerCase();
290
291   if (this.dont_select || (evtarget && (tagname == 'input' || tagname == 'img')))
292     return true;
293
294   // accept right-clicks
295   if (rcube_event.get_button(e) == 2)
296     return true;
297
298   this.in_selection_before = this.in_selection(id) ? id : false;
299
300   // selects currently unselected row
301   if (!this.in_selection_before) {
302     var mod_key = rcube_event.get_modifier(e);
303     this.select_row(id, mod_key, false);
304   }
305
306   if (this.draggable && this.selection.length) {
307     this.drag_start = true;
308     this.drag_mouse_start = rcube_event.get_mouse_pos(e);
309     rcube_event.add_listener({event:'mousemove', object:this, method:'drag_mouse_move'});
310     rcube_event.add_listener({event:'mouseup', object:this, method:'drag_mouse_up'});
311     if (bw.iphone || bw.ipad) {
312       rcube_event.add_listener({event:'touchmove', object:this, method:'drag_mouse_move'});
313       rcube_event.add_listener({event:'touchend', object:this, method:'drag_mouse_up'});
314     }
315
316     // enable dragging over iframes
317     this.add_dragfix();
318   }
319
320   return false;
321 },
322
323
324 /**
325  * onmouseup-handler of message list row
326  */
327 click_row: function(e, id)
328 {
329   var now = new Date().getTime(),
330     mod_key = rcube_event.get_modifier(e),
331     evtarget = rcube_event.get_target(e),
332     tagname = evtarget.tagName.toLowerCase();
333
334   if ((evtarget && (tagname == 'input' || tagname == 'img')))
335     return true;
336
337   // don't do anything (another action processed before)
338   if (this.dont_select) {
339     this.dont_select = false;
340     return false;
341   }
342
343   var dblclicked = now - this.rows[id].clicked < this.dblclick_time;
344
345   // unselects currently selected row
346   if (!this.drag_active && this.in_selection_before == id && !dblclicked)
347     this.select_row(id, mod_key, false);
348
349   this.drag_start = false;
350   this.in_selection_before = false;
351
352   // row was double clicked
353   if (this.rows && dblclicked && this.in_selection(id))
354     this.triggerEvent('dblclick');
355   else
356     this.triggerEvent('click');
357
358   if (!this.drag_active) {
359     // remove temp divs
360     this.del_dragfix();
361     rcube_event.cancel(e);
362   }
363
364   this.rows[id].clicked = now;
365   return false;
366 },
367
368
369 /*
370  * Returns thread root ID for specified row ID
371  */
372 find_root: function(uid)
373 {
374    var r = this.rows[uid];
375
376    if (r && r.parent_uid)
377      return this.find_root(r.parent_uid);
378    else
379      return uid;
380 },
381
382
383 expand_row: function(e, id)
384 {
385   var row = this.rows[id],
386     evtarget = rcube_event.get_target(e),
387     mod_key = rcube_event.get_modifier(e);
388
389   // Don't select this message
390   this.dont_select = true;
391   // Don't treat double click on the expando as double click on the message.
392   row.clicked = 0;
393
394   if (row.expanded) {
395     evtarget.className = 'collapsed';
396     if (mod_key == CONTROL_KEY || this.multiexpand)
397       this.collapse_all(row);
398     else
399       this.collapse(row);
400   }
401   else {
402     evtarget.className = 'expanded';
403     if (mod_key == CONTROL_KEY || this.multiexpand)
404       this.expand_all(row);
405     else
406      this.expand(row);
407   }
408 },
409
410 collapse: function(row)
411 {
412   row.expanded = false;
413   this.triggerEvent('expandcollapse', { uid:row.uid, expanded:row.expanded });
414   var depth = row.depth;
415   var new_row = row ? row.obj.nextSibling : null;
416   var r;
417
418   while (new_row) {
419     if (new_row.nodeType == 1) {
420       var r = this.rows[new_row.uid];
421       if (r && r.depth <= depth)
422         break;
423       $(new_row).css('display', 'none');
424       if (r.expanded) {
425         r.expanded = false;
426         this.triggerEvent('expandcollapse', { uid:r.uid, expanded:r.expanded });
427       }
428     }
429     new_row = new_row.nextSibling;
430   }
431
432   return false;
433 },
434
435 expand: function(row)
436 {
437   var r, p, depth, new_row, last_expanded_parent_depth;
438
439   if (row) {
440     row.expanded = true;
441     depth = row.depth;
442     new_row = row.obj.nextSibling;
443     this.update_expando(row.uid, true);
444     this.triggerEvent('expandcollapse', { uid:row.uid, expanded:row.expanded });
445   }
446   else {
447     var tbody = this.list.tBodies[0];
448     new_row = tbody.firstChild;
449     depth = 0;
450     last_expanded_parent_depth = 0;
451   }
452
453   while (new_row) {
454     if (new_row.nodeType == 1) {
455       r = this.rows[new_row.uid];
456       if (r) {
457         if (row && (!r.depth || r.depth <= depth))
458           break;
459
460         if (r.parent_uid) {
461           p = this.rows[r.parent_uid];
462           if (p && p.expanded) {
463             if ((row && p == row) || last_expanded_parent_depth >= p.depth - 1) {
464               last_expanded_parent_depth = p.depth;
465               $(new_row).css('display', '');
466               r.expanded = true;
467               this.triggerEvent('expandcollapse', { uid:r.uid, expanded:r.expanded });
468             }
469           }
470           else
471             if (row && (! p || p.depth <= depth))
472               break;
473         }
474       }
475     }
476     new_row = new_row.nextSibling;
477   }
478
479   return false;
480 },
481
482
483 collapse_all: function(row)
484 {
485   var depth, new_row, r;
486
487   if (row) {
488     row.expanded = false;
489     depth = row.depth;
490     new_row = row.obj.nextSibling;
491     this.update_expando(row.uid);
492     this.triggerEvent('expandcollapse', { uid:row.uid, expanded:row.expanded });
493
494     // don't collapse sub-root tree in multiexpand mode 
495     if (depth && this.multiexpand)
496       return false;
497   }
498   else {
499     new_row = this.list.tBodies[0].firstChild;
500     depth = 0;
501   }
502
503   while (new_row) {
504     if (new_row.nodeType == 1) {
505       if (r = this.rows[new_row.uid]) {
506         if (row && (!r.depth || r.depth <= depth))
507           break;
508
509         if (row || r.depth)
510           $(new_row).css('display', 'none');
511         if (r.has_children && r.expanded) {
512           r.expanded = false;
513           this.update_expando(r.uid, false);
514           this.triggerEvent('expandcollapse', { uid:r.uid, expanded:r.expanded });
515         }
516       }
517     }
518     new_row = new_row.nextSibling;
519   }
520
521   return false;
522 },
523
524 expand_all: function(row)
525 {
526   var depth, new_row, r;
527
528   if (row) {
529     row.expanded = true;
530     depth = row.depth;
531     new_row = row.obj.nextSibling;
532     this.update_expando(row.uid, true);
533     this.triggerEvent('expandcollapse', { uid:row.uid, expanded:row.expanded });
534   }
535   else {
536     new_row = this.list.tBodies[0].firstChild;
537     depth = 0;
538   }
539
540   while (new_row) {
541     if (new_row.nodeType == 1) {
542       if (r = this.rows[new_row.uid]) {
543         if (row && r.depth <= depth)
544           break;
545
546         $(new_row).css('display', '');
547         if (r.has_children && !r.expanded) {
548           r.expanded = true;
549           this.update_expando(r.uid, true);
550           this.triggerEvent('expandcollapse', { uid:r.uid, expanded:r.expanded });
551         }
552       }
553     }
554     new_row = new_row.nextSibling;
555   }
556   return false;
557 },
558
559 update_expando: function(uid, expanded)
560 {
561   var expando = document.getElementById('rcmexpando' + uid);
562   if (expando)
563     expando.className = expanded ? 'expanded' : 'collapsed';
564 },
565
566
567 /**
568  * get first/next/previous/last rows that are not hidden
569  */
570 get_next_row: function()
571 {
572   if (!this.rows)
573     return false;
574
575   var last_selected_row = this.rows[this.last_selected],
576     new_row = last_selected_row ? last_selected_row.obj.nextSibling : null;
577
578   while (new_row && (new_row.nodeType != 1 || new_row.style.display == 'none'))
579     new_row = new_row.nextSibling;
580
581   return new_row;
582 },
583
584 get_prev_row: function()
585 {
586   if (!this.rows)
587     return false;
588
589   var last_selected_row = this.rows[this.last_selected],
590     new_row = last_selected_row ? last_selected_row.obj.previousSibling : null;
591
592   while (new_row && (new_row.nodeType != 1 || new_row.style.display == 'none'))
593     new_row = new_row.previousSibling;
594
595   return new_row;
596 },
597
598 get_first_row: function()
599 {
600   if (this.rowcount) {
601     var i, len, rows = this.list.tBodies[0].rows;
602
603     for (i=0, len=rows.length-1; i<len; i++)
604       if (rows[i].id && String(rows[i].id).match(/^rcmrow([a-z0-9\-_=\+\/]+)/i) && this.rows[RegExp.$1] != null)
605             return RegExp.$1;
606   }
607
608   return null;
609 },
610
611 get_last_row: function()
612 {
613   if (this.rowcount) {
614     var i, rows = this.list.tBodies[0].rows;
615
616     for (i=rows.length-1; i>=0; i--)
617       if (rows[i].id && String(rows[i].id).match(/^rcmrow([a-z0-9\-_=\+\/]+)/i) && this.rows[RegExp.$1] != null)
618         return RegExp.$1;
619   }
620
621   return null;
622 },
623
624
625 /**
626  * selects or unselects the proper row depending on the modifier key pressed
627  */
628 select_row: function(id, mod_key, with_mouse)
629 {
630   var select_before = this.selection.join(',');
631   if (!this.multiselect)
632     mod_key = 0;
633
634   if (!this.shift_start)
635     this.shift_start = id
636
637   if (!mod_key) {
638     this.shift_start = id;
639     this.highlight_row(id, false);
640     this.multi_selecting = false;
641   }
642   else {
643     switch (mod_key) {
644       case SHIFT_KEY:
645         this.shift_select(id, false);
646         break;
647
648       case CONTROL_KEY:
649         if (!with_mouse)
650           this.highlight_row(id, true);
651         break; 
652
653       case CONTROL_SHIFT_KEY:
654         this.shift_select(id, true);
655         break;
656
657       default:
658         this.highlight_row(id, false);
659         break;
660     }
661     this.multi_selecting = true;
662   }
663
664   // trigger event if selection changed
665   if (this.selection.join(',') != select_before)
666     this.triggerEvent('select');
667
668   if (this.last_selected != 0 && this.rows[this.last_selected])
669     $(this.rows[this.last_selected].obj).removeClass('focused');
670
671   // unselect if toggleselect is active and the same row was clicked again
672   if (this.toggleselect && this.last_selected == id) {
673     this.clear_selection();
674     id = null;
675   }
676   else
677     $(this.rows[id].obj).addClass('focused');
678
679   if (!this.selection.length)
680     this.shift_start = null;
681
682   this.last_selected = id;
683 },
684
685
686 /**
687  * Alias method for select_row
688  */
689 select: function(id)
690 {
691   this.select_row(id, false);
692   this.scrollto(id);
693 },
694
695
696 /**
697  * Select row next to the last selected one.
698  * Either below or above.
699  */
700 select_next: function()
701 {
702   var next_row = this.get_next_row(),
703     prev_row = this.get_prev_row(),
704     new_row = (next_row) ? next_row : prev_row;
705
706   if (new_row)
707     this.select_row(new_row.uid, false, false);
708 },
709
710
711 /**
712  * Select first row 
713  */
714 select_first: function(mod_key)
715 {
716   var row = this.get_first_row();
717   if (row) {
718     if (mod_key) {
719       this.shift_select(row, mod_key);
720       this.triggerEvent('select');
721       this.scrollto(row);
722     }
723     else {
724       this.select(row);
725     }
726   }
727 },
728
729
730 /**
731  * Select last row 
732  */
733 select_last: function(mod_key)
734 {
735   var row = this.get_last_row();
736   if (row) {
737     if (mod_key) {
738       this.shift_select(row, mod_key);
739       this.triggerEvent('select');
740       this.scrollto(row);
741     }
742     else {
743       this.select(row);
744     }
745   }
746 },
747
748
749 /**
750  * Add all childs of the given row to selection
751  */
752 select_childs: function(uid)
753 {
754   if (!this.rows[uid] || !this.rows[uid].has_children)
755     return;
756
757   var depth = this.rows[uid].depth,
758     row = this.rows[uid].obj.nextSibling;
759
760   while (row) {
761     if (row.nodeType == 1) {
762       if ((r = this.rows[row.uid])) {
763         if (!r.depth || r.depth <= depth)
764           break;
765         if (!this.in_selection(r.uid))
766           this.select_row(r.uid, CONTROL_KEY);
767       }
768     }
769     row = row.nextSibling;
770   }
771 },
772
773
774 /**
775  * Perform selection when shift key is pressed
776  */
777 shift_select: function(id, control)
778 {
779   if (!this.rows[this.shift_start] || !this.selection.length)
780     this.shift_start = id;
781
782   var n, from_rowIndex = this.rows[this.shift_start].obj.rowIndex,
783     to_rowIndex = this.rows[id].obj.rowIndex,
784     i = ((from_rowIndex < to_rowIndex)? from_rowIndex : to_rowIndex),
785     j = ((from_rowIndex > to_rowIndex)? from_rowIndex : to_rowIndex);
786
787   // iterate through the entire message list
788   for (n in this.rows) {
789     if (this.rows[n].obj.rowIndex >= i && this.rows[n].obj.rowIndex <= j) {
790       if (!this.in_selection(n)) {
791         this.highlight_row(n, true);
792       }
793     }
794     else {
795       if (this.in_selection(n) && !control) {
796         this.highlight_row(n, true);
797       }
798     }
799   }
800 },
801
802
803 /**
804  * Check if given id is part of the current selection
805  */
806 in_selection: function(id)
807 {
808   for (var n in this.selection)
809     if (this.selection[n]==id)
810       return true;
811
812   return false;
813 },
814
815
816 /**
817  * Select each row in list
818  */
819 select_all: function(filter)
820 {
821   if (!this.rows || !this.rows.length)
822     return false;
823
824   // reset but remember selection first
825   var n, select_before = this.selection.join(',');
826   this.selection = [];
827
828   for (n in this.rows) {
829     if (!filter || this.rows[n][filter] == true) {
830       this.last_selected = n;
831       this.highlight_row(n, true);
832     }
833     else {
834       $(this.rows[n].obj).removeClass('selected').removeClass('unfocused');
835     }
836   }
837
838   // trigger event if selection changed
839   if (this.selection.join(',') != select_before)
840     this.triggerEvent('select');
841
842   this.focus();
843
844   return true;
845 },
846
847
848 /**
849  * Invert selection
850  */
851 invert_selection: function()
852 {
853   if (!this.rows || !this.rows.length)
854     return false;
855
856   // remember old selection
857   var n, select_before = this.selection.join(',');
858
859   for (n in this.rows)
860     this.highlight_row(n, true);
861
862   // trigger event if selection changed
863   if (this.selection.join(',') != select_before)
864     this.triggerEvent('select');
865
866   this.focus();
867
868   return true;
869 },
870
871
872 /**
873  * Unselect selected row(s)
874  */
875 clear_selection: function(id)
876 {
877   var n, num_select = this.selection.length;
878
879   // one row
880   if (id) {
881     for (n in this.selection)
882       if (this.selection[n] == id) {
883         this.selection.splice(n,1);
884         break;
885       }
886   }
887   // all rows
888   else {
889     for (n in this.selection)
890       if (this.rows[this.selection[n]]) {
891         $(this.rows[this.selection[n]].obj).removeClass('selected').removeClass('unfocused');
892       }
893
894     this.selection = [];
895   }
896
897   if (num_select && !this.selection.length)
898     this.triggerEvent('select');
899 },
900
901
902 /**
903  * Getter for the selection array
904  */
905 get_selection: function()
906 {
907   return this.selection;
908 },
909
910
911 /**
912  * Return the ID if only one row is selected
913  */
914 get_single_selection: function()
915 {
916   if (this.selection.length == 1)
917     return this.selection[0];
918   else
919     return null;
920 },
921
922
923 /**
924  * Highlight/unhighlight a row
925  */
926 highlight_row: function(id, multiple)
927 {
928   if (this.rows[id] && !multiple) {
929     if (this.selection.length > 1 || !this.in_selection(id)) {
930       this.clear_selection();
931       this.selection[0] = id;
932       $(this.rows[id].obj).addClass('selected');
933     }
934   }
935   else if (this.rows[id]) {
936     if (!this.in_selection(id)) { // select row
937       this.selection[this.selection.length] = id;
938       $(this.rows[id].obj).addClass('selected');
939     }
940     else { // unselect row
941       var p = $.inArray(id, this.selection),
942         a_pre = this.selection.slice(0, p),
943         a_post = this.selection.slice(p+1, this.selection.length);
944
945       this.selection = a_pre.concat(a_post);
946       $(this.rows[id].obj).removeClass('selected').removeClass('unfocused');
947     }
948   }
949 },
950
951
952 /**
953  * Handler for keyboard events
954  */
955 key_press: function(e)
956 {
957   if (this.focused != true)
958     return true;
959
960   var keyCode = rcube_event.get_keycode(e),
961     mod_key = rcube_event.get_modifier(e);
962
963   switch (keyCode) {
964     case 40:
965     case 38: 
966     case 63233: // "down", in safari keypress
967     case 63232: // "up", in safari keypress
968       // Stop propagation so that the browser doesn't scroll
969       rcube_event.cancel(e);
970       return this.use_arrow_key(keyCode, mod_key);
971     case 61:
972     case 107: // Plus sign on a numeric keypad (fc11 + firefox 3.5.2)
973     case 109:
974     case 32:
975       // Stop propagation
976       rcube_event.cancel(e);
977       var ret = this.use_plusminus_key(keyCode, mod_key);
978       this.key_pressed = keyCode;
979       this.triggerEvent('keypress');
980       return ret;
981     case 36: // Home
982       this.select_first(mod_key);
983       return rcube_event.cancel(e);
984     case 35: // End
985       this.select_last(mod_key);
986       return rcube_event.cancel(e);
987     default:
988       this.shiftkey = e.shiftKey;
989       this.key_pressed = keyCode;
990       this.triggerEvent('keypress');
991       // reset shiftkey flag, we need it only for registered events
992       this.shiftkey = false;
993
994       if (this.key_pressed == this.BACKSPACE_KEY)
995         return rcube_event.cancel(e);
996   }
997
998   return true;
999 },
1000
1001 /**
1002  * Handler for keydown events
1003  */
1004 key_down: function(e)
1005 {
1006   switch (rcube_event.get_keycode(e)) {
1007     case 27:
1008       if (this.drag_active)
1009             return this.drag_mouse_up(e);
1010       if (this.col_drag_active) {
1011         this.selected_column = null;
1012             return this.column_drag_mouse_up(e);
1013       }
1014
1015     case 40:
1016     case 38: 
1017     case 63233:
1018     case 63232:
1019     case 61:
1020     case 107:
1021     case 109:
1022     case 32:
1023       if (!rcube_event.get_modifier(e) && this.focused)
1024         return rcube_event.cancel(e);
1025
1026     default:
1027   }
1028
1029   return true;
1030 },
1031
1032
1033 /**
1034  * Special handling method for arrow keys
1035  */
1036 use_arrow_key: function(keyCode, mod_key)
1037 {
1038   var new_row;
1039   // Safari uses the nonstandard keycodes 63232/63233 for up/down, if we're
1040   // using the keypress event (but not the keydown or keyup event).
1041   if (keyCode == 40 || keyCode == 63233) // down arrow key pressed
1042     new_row = this.get_next_row();
1043   else if (keyCode == 38 || keyCode == 63232) // up arrow key pressed
1044     new_row = this.get_prev_row();
1045
1046   if (new_row) {
1047     this.select_row(new_row.uid, mod_key, true);
1048     this.scrollto(new_row.uid);
1049   }
1050
1051   return false;
1052 },
1053
1054
1055 /**
1056  * Special handling method for +/- keys
1057  */
1058 use_plusminus_key: function(keyCode, mod_key)
1059 {
1060   var selected_row = this.rows[this.last_selected];
1061   if (!selected_row)
1062     return;
1063
1064   if (keyCode == 32)
1065     keyCode = selected_row.expanded ? 109 : 61;
1066   if (keyCode == 61 || keyCode == 107)
1067     if (mod_key == CONTROL_KEY || this.multiexpand)
1068       this.expand_all(selected_row);
1069     else
1070      this.expand(selected_row);
1071   else
1072     if (mod_key == CONTROL_KEY || this.multiexpand)
1073       this.collapse_all(selected_row);
1074     else
1075       this.collapse(selected_row);
1076
1077   this.update_expando(selected_row.uid, selected_row.expanded);
1078
1079   return false;
1080 },
1081
1082
1083 /**
1084  * Try to scroll the list to make the specified row visible
1085  */
1086 scrollto: function(id)
1087 {
1088   var row = this.rows[id].obj;
1089   if (row && this.frame) {
1090     var scroll_to = Number(row.offsetTop);
1091
1092     // expand thread if target row is hidden (collapsed)
1093     if (!scroll_to && this.rows[id].parent_uid) {
1094       var parent = this.find_root(this.rows[id].uid);
1095       this.expand_all(this.rows[parent]);
1096       scroll_to = Number(row.offsetTop);
1097     }
1098
1099     if (scroll_to < Number(this.frame.scrollTop))
1100       this.frame.scrollTop = scroll_to;
1101     else if (scroll_to + Number(row.offsetHeight) > Number(this.frame.scrollTop) + Number(this.frame.offsetHeight))
1102       this.frame.scrollTop = (scroll_to + Number(row.offsetHeight)) - Number(this.frame.offsetHeight);
1103   }
1104 },
1105
1106
1107 /**
1108  * Handler for mouse move events
1109  */
1110 drag_mouse_move: function(e)
1111 {
1112   // convert touch event
1113   if (e.type == 'touchmove') {
1114     if (e.changedTouches.length == 1)
1115       e = rcube_event.touchevent(e.changedTouches[0]);
1116     else
1117       return rcube_event.cancel(e);
1118   }
1119   
1120   if (this.drag_start) {
1121     // check mouse movement, of less than 3 pixels, don't start dragging
1122     var m = rcube_event.get_mouse_pos(e);
1123
1124     if (!this.drag_mouse_start || (Math.abs(m.x - this.drag_mouse_start.x) < 3 && Math.abs(m.y - this.drag_mouse_start.y) < 3))
1125       return false;
1126
1127     if (!this.draglayer)
1128       this.draglayer = $('<div>').attr('id', 'rcmdraglayer')
1129         .css({ position:'absolute', display:'none', 'z-index':2000 })
1130         .appendTo(document.body);
1131
1132     // also select childs of (collapsed) threads for dragging
1133     var n, uid, selection = $.merge([], this.selection);
1134     for (n in selection) {
1135       uid = selection[n];
1136       if (this.rows[uid].has_children && !this.rows[uid].expanded)
1137         this.select_childs(uid);
1138     }
1139
1140     // reset content
1141     this.draglayer.html('');
1142
1143     // get subjects of selected messages
1144     var c, i, n, subject, obj;
1145     for (n=0; n<this.selection.length; n++) {
1146       // only show 12 lines
1147       if (n>12) {
1148         this.draglayer.append('...');
1149         break;
1150       }
1151
1152       if (obj = this.rows[this.selection[n]].obj) {
1153         subject = '';
1154
1155         for (c=0, i=0; i<obj.childNodes.length; i++) {
1156               if (obj.childNodes[i].nodeName == 'TD') {
1157             if (n == 0)
1158                   this.drag_start_pos = $(obj.childNodes[i]).offset();
1159
1160                 if (this.subject_col < 0 || (this.subject_col >= 0 && this.subject_col == c)) {
1161                   var entry, node, tmp_node, nodes = obj.childNodes[i].childNodes;
1162                   // find text node
1163                   for (m=0; m<nodes.length; m++) {
1164                     if ((tmp_node = obj.childNodes[i].childNodes[m]) && (tmp_node.nodeType==3 || tmp_node.nodeName=='A'))
1165                       node = tmp_node;
1166                   }
1167
1168                   if (!node)
1169                     break;
1170
1171               subject = $(node).text();
1172                   // remove leading spaces
1173               subject = $.trim(subject);
1174               // truncate line to 50 characters
1175               subject = (subject.length > 50 ? subject.substring(0, 50) + '...' : subject);
1176
1177               entry = $('<div>').text(subject);
1178                   this.draglayer.append(entry);
1179               break;
1180             }
1181             c++;
1182           }
1183         }
1184       }
1185     }
1186
1187     this.draglayer.show();
1188     this.drag_active = true;
1189     this.triggerEvent('dragstart');
1190   }
1191
1192   if (this.drag_active && this.draglayer) {
1193     var pos = rcube_event.get_mouse_pos(e);
1194     this.draglayer.css({ left:(pos.x+20)+'px', top:(pos.y-5 + (bw.ie ? document.documentElement.scrollTop : 0))+'px' });
1195     this.triggerEvent('dragmove', e?e:window.event);
1196   }
1197
1198   this.drag_start = false;
1199
1200   return false;
1201 },
1202
1203
1204 /**
1205  * Handler for mouse up events
1206  */
1207 drag_mouse_up: function(e)
1208 {
1209   document.onmousemove = null;
1210   
1211   if (e.type == 'touchend') {
1212     if (e.changedTouches.length != 1)
1213       return rcube_event.cancel(e);
1214   }
1215
1216   if (this.draglayer && this.draglayer.is(':visible')) {
1217     if (this.drag_start_pos)
1218       this.draglayer.animate(this.drag_start_pos, 300, 'swing').hide(20);
1219     else
1220       this.draglayer.hide();
1221   }
1222
1223   if (this.drag_active)
1224     this.focus();
1225   this.drag_active = false;
1226
1227   rcube_event.remove_listener({event:'mousemove', object:this, method:'drag_mouse_move'});
1228   rcube_event.remove_listener({event:'mouseup', object:this, method:'drag_mouse_up'});
1229   
1230   if (bw.iphone || bw.ipad) {
1231     rcube_event.remove_listener({event:'touchmove', object:this, method:'drag_mouse_move'});
1232     rcube_event.remove_listener({event:'touchend', object:this, method:'drag_mouse_up'});
1233   }
1234
1235   // remove temp divs
1236   this.del_dragfix();
1237
1238   this.triggerEvent('dragend');
1239
1240   return rcube_event.cancel(e);
1241 },
1242
1243
1244 /**
1245  * Handler for mouse move events for dragging list column
1246  */
1247 column_drag_mouse_move: function(e)
1248 {
1249   if (this.drag_start) {
1250     // check mouse movement, of less than 3 pixels, don't start dragging
1251     var i, m = rcube_event.get_mouse_pos(e);
1252
1253     if (!this.drag_mouse_start || (Math.abs(m.x - this.drag_mouse_start.x) < 3 && Math.abs(m.y - this.drag_mouse_start.y) < 3))
1254       return false;
1255
1256     if (!this.col_draglayer) {
1257       var lpos = $(this.list).offset(),
1258         cells = this.list.tHead.rows[0].cells;
1259
1260       // create dragging layer
1261       this.col_draglayer = $('<div>').attr('id', 'rcmcoldraglayer')
1262         .css(lpos).css({ position:'absolute', 'z-index':2001,
1263            'background-color':'white', opacity:0.75,
1264            height: (this.frame.offsetHeight-2)+'px', width: (this.frame.offsetWidth-2)+'px' })
1265         .appendTo(document.body)
1266         // ... and column position indicator
1267        .append($('<div>').attr('id', 'rcmcolumnindicator')
1268           .css({ position:'absolute', 'border-right':'2px dotted #555', 
1269           'z-index':2002, height: (this.frame.offsetHeight-2)+'px' }));
1270
1271       this.cols = [];
1272       this.list_pos = this.list_min_pos = lpos.left;
1273       // save columns positions
1274       for (i=0; i<cells.length; i++) {
1275         this.cols[i] = cells[i].offsetWidth;
1276         if (this.column_fixed !== null && i <= this.column_fixed) {
1277           this.list_min_pos += this.cols[i];
1278         }
1279       }
1280     }
1281
1282     this.col_draglayer.show();
1283     this.col_drag_active = true;
1284     this.triggerEvent('column_dragstart');
1285   }
1286
1287   // set column indicator position
1288   if (this.col_drag_active && this.col_draglayer) {
1289     var i, cpos = 0, pos = rcube_event.get_mouse_pos(e);
1290
1291     for (i=0; i<this.cols.length; i++) {
1292       if (pos.x >= this.cols[i]/2 + this.list_pos + cpos)
1293         cpos += this.cols[i];
1294       else
1295         break;
1296     }
1297
1298     // handle fixed columns on left
1299     if (i == 0 && this.list_min_pos > pos.x)
1300       cpos = this.list_min_pos - this.list_pos;
1301     // empty list needs some assignment
1302     else if (!this.list.rowcount && i == this.cols.length)
1303       cpos -= 2;
1304     $('#rcmcolumnindicator').css({ width: cpos+'px'});
1305     this.triggerEvent('column_dragmove', e?e:window.event);
1306   }
1307
1308   this.drag_start = false;
1309
1310   return false;
1311 },
1312
1313
1314 /**
1315  * Handler for mouse up events for dragging list columns
1316  */
1317 column_drag_mouse_up: function(e)
1318 {
1319   document.onmousemove = null;
1320
1321   if (this.col_draglayer) {
1322     (this.col_draglayer).remove();
1323     this.col_draglayer = null;
1324   }
1325
1326   if (this.col_drag_active)
1327     this.focus();
1328   this.col_drag_active = false;
1329
1330   rcube_event.remove_listener({event:'mousemove', object:this, method:'column_drag_mouse_move'});
1331   rcube_event.remove_listener({event:'mouseup', object:this, method:'column_drag_mouse_up'});
1332   // remove temp divs
1333   this.del_dragfix();
1334
1335   if (this.selected_column !== null && this.cols && this.cols.length) {
1336     var i, cpos = 0, pos = rcube_event.get_mouse_pos(e);
1337
1338     // find destination position
1339     for (i=0; i<this.cols.length; i++) {
1340       if (pos.x >= this.cols[i]/2 + this.list_pos + cpos)
1341         cpos += this.cols[i];
1342       else
1343         break;
1344     }
1345
1346     if (i != this.selected_column && i != this.selected_column+1) {
1347       this.column_replace(this.selected_column, i);
1348     }
1349   }
1350
1351   this.triggerEvent('column_dragend');
1352
1353   return rcube_event.cancel(e);
1354 },
1355
1356
1357 /**
1358  * Creates a layer for drag&drop over iframes
1359  */
1360 add_dragfix: function()
1361 {
1362   $('iframe').each(function() {
1363     $('<div class="iframe-dragdrop-fix"></div>')
1364       .css({background: '#fff',
1365         width: this.offsetWidth+'px', height: this.offsetHeight+'px',
1366         position: 'absolute', opacity: '0.001', zIndex: 1000
1367       })
1368       .css($(this).offset())
1369       .appendTo(document.body);
1370   });
1371 },
1372
1373
1374 /**
1375  * Removes the layer for drag&drop over iframes
1376  */
1377 del_dragfix: function()
1378 {
1379   $('div.iframe-dragdrop-fix').each(function() { this.parentNode.removeChild(this); });
1380 },
1381
1382
1383 /**
1384  * Replaces two columns
1385  */
1386 column_replace: function(from, to)
1387 {
1388   var len, cells = this.list.tHead.rows[0].cells,
1389     elem = cells[from],
1390     before = cells[to],
1391     td = document.createElement('td');
1392
1393   // replace header cells
1394   if (before)
1395     cells[0].parentNode.insertBefore(td, before);
1396   else
1397     cells[0].parentNode.appendChild(td);
1398   cells[0].parentNode.replaceChild(elem, td);
1399
1400   // replace list cells
1401   for (r=0, len=this.list.tBodies[0].rows.length; r<len; r++) {
1402     row = this.list.tBodies[0].rows[r];
1403
1404     elem = row.cells[from];
1405     before = row.cells[to];
1406     td = document.createElement('td');
1407
1408     if (before)
1409       row.insertBefore(td, before);
1410     else
1411       row.appendChild(td);
1412     row.replaceChild(elem, td);
1413   }
1414
1415   // update subject column position
1416   if (this.subject_col == from)
1417     this.subject_col = to > from ? to - 1 : to;
1418   else if (this.subject_col < from && to <= this.subject_col)
1419     this.subject_col++;
1420   else if (this.subject_col > from && to >= this.subject_col)
1421     this.subject_col--;
1422
1423   this.triggerEvent('column_replace');
1424 }
1425
1426 };
1427
1428 rcube_list_widget.prototype.addEventListener = rcube_event_engine.prototype.addEventListener;
1429 rcube_list_widget.prototype.removeEventListener = rcube_event_engine.prototype.removeEventListener;
1430 rcube_list_widget.prototype.triggerEvent = rcube_event_engine.prototype.triggerEvent;