]> git.donarmstrong.com Git - roundcube.git/blob - program/js/common.js.src
Imported Upstream version 0.6+dfsg
[roundcube.git] / program / js / common.js.src
1 /*
2  +-----------------------------------------------------------------------+
3  | Roundcube common js library                                           |
4  |                                                                       |
5  | This file is part of the Roundcube web development suite              |
6  | Copyright (C) 2005-2007, The Roundcube Dev Team                       |
7  | Licensed under the GNU GPL                                            |
8  |                                                                       |
9  +-----------------------------------------------------------------------+
10  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
11  +-----------------------------------------------------------------------+
12  
13  $Id: common.js 5281 2011-09-27 07:29:49Z alec $
14 */
15
16 // Constants
17 var CONTROL_KEY = 1;
18 var SHIFT_KEY = 2;
19 var CONTROL_SHIFT_KEY = 3;
20
21
22 /**
23  * Default browser check class
24  * @constructor
25  */
26 function roundcube_browser()
27 {
28   var n = navigator;
29
30   this.ver = parseFloat(n.appVersion);
31   this.appver = n.appVersion;
32   this.agent = n.userAgent;
33   this.agent_lc = n.userAgent.toLowerCase();
34   this.name = n.appName;
35   this.vendor = n.vendor ? n.vendor : '';
36   this.vendver = n.vendorSub ? parseFloat(n.vendorSub) : 0;
37   this.product = n.product ? n.product : '';
38   this.platform = String(n.platform).toLowerCase();
39   this.lang = (n.language) ? n.language.substring(0,2) :
40               (n.browserLanguage) ? n.browserLanguage.substring(0,2) :
41               (n.systemLanguage) ? n.systemLanguage.substring(0,2) : 'en';
42
43   this.win = (this.platform.indexOf('win') >= 0);
44   this.mac = (this.platform.indexOf('mac') >= 0);
45   this.linux = (this.platform.indexOf('linux') >= 0);
46   this.unix = (this.platform.indexOf('unix') >= 0);
47
48   this.dom = document.getElementById ? true : false;
49   this.dom2 = (document.addEventListener && document.removeEventListener);
50
51   this.ie = (document.all && !window.opera);
52   this.ie4 = (this.ie && !this.dom);
53   this.ie5 = (this.dom && this.appver.indexOf('MSIE 5')>0);
54   this.ie8 = (this.dom && this.appver.indexOf('MSIE 8')>0);
55   this.ie7 = (this.dom && this.appver.indexOf('MSIE 7')>0);
56   this.ie6 = (this.dom && !this.ie8 && !this.ie7 && this.appver.indexOf('MSIE 6')>0);
57
58   this.ns = ((this.ver < 5 && this.name == 'Netscape') || (this.ver >= 5 && this.vendor.indexOf('Netscape') >= 0));
59   this.chrome = (this.agent_lc.indexOf('chrome') > 0);
60   this.safari = (!this.chrome && (this.agent_lc.indexOf('safari') > 0 || this.agent_lc.indexOf('applewebkit') > 0));
61   this.mz = (this.dom && !this.ie && !this.ns && !this.chrome && !this.safari && this.agent.indexOf('Mozilla') >= 0);
62   this.konq   = (this.agent_lc.indexOf('konqueror') > 0);
63   this.iphone = (this.safari && this.agent_lc.indexOf('iphone') > 0);
64   this.ipad = (this.safari && this.agent_lc.indexOf('ipad') > 0);
65   this.opera = window.opera ? true : false;
66
67   if (this.opera && window.RegExp)
68     this.vendver = (/opera(\s|\/)([0-9\.]+)/.test(this.agent_lc)) ? parseFloat(RegExp.$2) : -1;
69   else if (this.chrome && window.RegExp)
70     this.vendver = (/chrome\/([0-9\.]+)/.test(this.agent_lc)) ? parseFloat(RegExp.$1) : 0;
71   else if (!this.vendver && this.safari)
72     this.vendver = (/(safari|applewebkit)\/([0-9]+)/.test(this.agent_lc)) ? parseInt(RegExp.$2) : 0;
73   else if ((!this.vendver && this.mz) || this.agent.indexOf('Camino')>0)
74     this.vendver = (/rv:([0-9\.]+)/.test(this.agent)) ? parseFloat(RegExp.$1) : 0;
75   else if (this.ie && window.RegExp)
76     this.vendver = (/msie\s+([0-9\.]+)/.test(this.agent_lc)) ? parseFloat(RegExp.$1) : 0;
77   else if (this.konq && window.RegExp)
78     this.vendver = (/khtml\/([0-9\.]+)/.test(this.agent_lc)) ? parseFloat(RegExp.$1) : 0;
79
80   // get real language out of safari's user agent
81   if (this.safari && (/;\s+([a-z]{2})-[a-z]{2}\)/.test(this.agent_lc)))
82     this.lang = RegExp.$1;
83
84   this.dhtml = ((this.ie4 && this.win) || this.ie5 || this.ie6 || this.ns4 || this.mz);
85   this.vml = (this.win && this.ie && this.dom && !this.opera);
86   this.pngalpha = (this.mz || (this.opera && this.vendver >= 6) || (this.ie && this.mac && this.vendver >= 5) ||
87                    (this.ie && this.win && this.vendver >= 5.5) || this.safari);
88   this.opacity = (this.mz || (this.ie && this.vendver >= 5.5 && !this.opera) || (this.safari && this.vendver >= 100));
89   this.cookies = n.cookieEnabled;
90
91   // test for XMLHTTP support
92   this.xmlhttp_test = function()
93   {
94     var activeX_test = new Function("try{var o=new ActiveXObject('Microsoft.XMLHTTP');return true;}catch(err){return false;}");
95     this.xmlhttp = (window.XMLHttpRequest || (window.ActiveXObject && activeX_test()));
96     return this.xmlhttp;
97   };
98
99   // set class names to html tag according to the current user agent detection
100   // this allows browser-specific css selectors like "html.chrome .someclass"
101   this.set_html_class = function()
102   {
103     var classname = ' js';
104
105     if (this.ie) {
106       classname += ' ie';
107       if (this.ie5)
108         classname += ' ie5';
109       else if (this.ie6)
110         classname += ' ie6';
111       else if (this.ie7)
112         classname += ' ie7';
113       else if (this.ie8)
114         classname += ' ie8';
115     }
116     else if (this.opera)
117       classname += ' opera';
118     else if (this.konq)
119       classname += ' konqueror';
120     else if (this.safari)
121       classname += ' safari';
122
123     if (this.chrome)
124       classname += ' chrome';
125     else if (this.iphone)
126       classname += ' iphone';
127     else if (this.ipad)
128       classname += ' ipad';
129
130     if (document.documentElement)
131       document.documentElement.className += classname;
132   };
133 };
134
135
136 // static functions for DOM event handling
137 var rcube_event = {
138
139 /**
140  * returns the event target element
141  */
142 get_target: function(e)
143 {
144   e = e || window.event;
145   return e && e.target ? e.target : e.srcElement;
146 },
147
148 /**
149  * returns the event key code
150  */
151 get_keycode: function(e)
152 {
153   e = e || window.event;
154   return e && e.keyCode ? e.keyCode : (e && e.which ? e.which : 0);
155 },
156
157 /**
158  * returns the event key code
159  */
160 get_button: function(e)
161 {
162   e = e || window.event;
163   return e && e.button !== undefined ? e.button : (e && e.which ? e.which : 0);
164 },
165
166 /**
167  * returns modifier key (constants defined at top of file)
168  */
169 get_modifier: function(e)
170 {
171   var opcode = 0;
172   e = e || window.event;
173
174   if (bw.mac && e) {
175     opcode += (e.metaKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
176     return opcode;
177   }
178   if (e) {
179     opcode += (e.ctrlKey && CONTROL_KEY) + (e.shiftKey && SHIFT_KEY);
180     return opcode;
181   }
182 },
183
184 /**
185  * Return absolute mouse position of an event
186  */
187 get_mouse_pos: function(e)
188 {
189   if (!e) e = window.event;
190   var mX = (e.pageX) ? e.pageX : e.clientX,
191     mY = (e.pageY) ? e.pageY : e.clientY;
192
193   if (document.body && document.all) {
194     mX += document.body.scrollLeft;
195     mY += document.body.scrollTop;
196   }
197
198   if (e._offset) {
199     mX += e._offset.left;
200     mY += e._offset.top;
201   }
202
203   return { x:mX, y:mY };
204 },
205
206 /**
207  * Add an object method as event listener to a certain element
208  */
209 add_listener: function(p)
210 {
211   if (!p.object || !p.method)  // not enough arguments
212     return;
213   if (!p.element)
214     p.element = document;
215
216   if (!p.object._rc_events)
217     p.object._rc_events = [];
218
219   var key = p.event + '*' + p.method;
220   if (!p.object._rc_events[key])
221     p.object._rc_events[key] = function(e){ return p.object[p.method](e); };
222
223   if (p.element.addEventListener)
224     p.element.addEventListener(p.event, p.object._rc_events[key], false);
225   else if (p.element.attachEvent) {
226     // IE allows multiple events with the same function to be applied to the same object
227     // forcibly detach the event, then attach
228     p.element.detachEvent('on'+p.event, p.object._rc_events[key]);
229     p.element.attachEvent('on'+p.event, p.object._rc_events[key]);
230   }
231   else
232     p.element['on'+p.event] = p.object._rc_events[key];
233 },
234
235 /**
236  * Remove event listener
237  */
238 remove_listener: function(p)
239 {
240   if (!p.element)
241     p.element = document;
242
243   var key = p.event + '*' + p.method;
244   if (p.object && p.object._rc_events && p.object._rc_events[key]) {
245     if (p.element.removeEventListener)
246       p.element.removeEventListener(p.event, p.object._rc_events[key], false);
247     else if (p.element.detachEvent)
248       p.element.detachEvent('on'+p.event, p.object._rc_events[key]);
249     else
250       p.element['on'+p.event] = null;
251   }
252 },
253
254 /**
255  * Prevent event propagation and bubbeling
256  */
257 cancel: function(evt)
258 {
259   var e = evt ? evt : window.event;
260   if (e.preventDefault)
261     e.preventDefault();
262   if (e.stopPropagation)
263     e.stopPropagation();
264
265   e.cancelBubble = true;
266   e.returnValue = false;
267   return false;
268 },
269
270 touchevent: function(e)
271 {
272   return { pageX:e.pageX, pageY:e.pageY, offsetX:e.pageX - e.target.offsetLeft, offsetY:e.pageY - e.target.offsetTop, target:e.target, istouch:true };
273 }
274
275 };
276
277
278 /**
279  * rcmail objects event interface
280  */
281 function rcube_event_engine()
282 {
283   this._events = {};
284 };
285
286 rcube_event_engine.prototype = {
287
288 /**
289  * Setter for object event handlers
290  *
291  * @param {String}   Event name
292  * @param {Function} Handler function
293  * @return Listener ID (used to remove this handler later on)
294  */
295 addEventListener: function(evt, func, obj)
296 {
297   if (!this._events)
298     this._events = {};
299   if (!this._events[evt])
300     this._events[evt] = [];
301
302   var e = {func:func, obj:obj ? obj : window};
303   this._events[evt][this._events[evt].length] = e;
304 },
305
306 /**
307  * Removes a specific event listener
308  *
309  * @param {String} Event name
310  * @param {Int}    Listener ID to remove
311  */
312 removeEventListener: function(evt, func, obj)
313 {
314   if (obj === undefined)
315     obj = window;
316
317   for (var h,i=0; this._events && this._events[evt] && i < this._events[evt].length; i++)
318     if ((h = this._events[evt][i]) && h.func == func && h.obj == obj)
319       this._events[evt][i] = null;
320 },
321
322 /**
323  * This will execute all registered event handlers
324  *
325  * @param {String} Event to trigger
326  * @param {Object} Event object/arguments
327  */
328 triggerEvent: function(evt, e)
329 {
330   var ret, h;
331   if (e === undefined)
332     e = this;
333   else if (typeof e === 'object')
334     e.event = evt;
335
336   if (this._events && this._events[evt] && !this._event_exec) {
337     this._event_exec = true;
338     for (var i=0; i < this._events[evt].length; i++) {
339       if ((h = this._events[evt][i])) {
340         if (typeof h.func === 'function')
341           ret = h.func.call ? h.func.call(h.obj, e) : h.func(e);
342         else if (typeof h.obj[h.func] === 'function')
343           ret = h.obj[h.func](e);
344
345         // cancel event execution
346         if (ret !== undefined && !ret)
347           break;
348       }
349     }
350     if (ret && ret.event) {
351       try {
352         delete ret.event;
353       } catch (err) {
354         // IE6-7 doesn't support deleting HTMLFormElement attributes (#1488017)
355         $(ret).removeAttr('event');
356       }
357     }
358   }
359
360   this._event_exec = false;
361   if (e.event) {
362     try {
363       delete e.event;
364     } catch (err) {
365       // IE6-7 doesn't support deleting HTMLFormElement attributes (#1488017)
366       $(e).removeAttr('event');
367     }
368   }
369
370   return ret;
371 }
372
373 };  // end rcube_event_engine.prototype
374
375
376
377 /**
378  * Roundcube generic layer (floating box) class
379  *
380  * @constructor
381  */
382 function rcube_layer(id, attributes)
383 {
384   this.name = id;
385
386   // create a new layer in the current document
387   this.create = function(arg)
388   {
389     var l = (arg.x) ? arg.x : 0,
390       t = (arg.y) ? arg.y : 0,
391       w = arg.width,
392       h = arg.height,
393       z = arg.zindex,
394       vis = arg.vis,
395       parent = arg.parent,
396       obj = document.createElement('DIV');
397
398     obj.id = this.name;
399     obj.style.position = 'absolute';
400     obj.style.visibility = (vis) ? (vis==2) ? 'inherit' : 'visible' : 'hidden';
401     obj.style.left = l+'px';
402     obj.style.top = t+'px';
403     if (w)
404           obj.style.width = w.toString().match(/\%$/) ? w : w+'px';
405     if (h)
406           obj.style.height = h.toString().match(/\%$/) ? h : h+'px';
407     if (z)
408       obj.style.zIndex = z;
409
410     if (parent)
411       parent.appendChild(obj);
412     else
413       document.body.appendChild(obj);
414
415     this.elm = obj;
416   };
417
418   // create new layer
419   if (attributes != null) {
420     this.create(attributes);
421     this.name = this.elm.id;
422   }
423   else  // just refer to the object
424     this.elm = document.getElementById(id);
425
426   if (!this.elm)
427     return false;
428
429
430   // ********* layer object properties *********
431
432   this.css = this.elm.style;
433   this.event = this.elm;
434   this.width = this.elm.offsetWidth;
435   this.height = this.elm.offsetHeight;
436   this.x = parseInt(this.elm.offsetLeft);
437   this.y = parseInt(this.elm.offsetTop);
438   this.visible = (this.css.visibility=='visible' || this.css.visibility=='show' || this.css.visibility=='inherit') ? true : false;
439
440
441   // ********* layer object methods *********
442
443   // move the layer to a specific position
444   this.move = function(x, y)
445   {
446     this.x = x;
447     this.y = y;
448     this.css.left = Math.round(this.x)+'px';
449     this.css.top = Math.round(this.y)+'px';
450   };
451
452   // change the layers width and height
453   this.resize = function(w,h)
454   {
455     this.css.width  = w+'px';
456     this.css.height = h+'px';
457     this.width = w;
458     this.height = h;
459   };
460
461   // show or hide the layer
462   this.show = function(a)
463   {
464     if(a == 1) {
465       this.css.visibility = 'visible';
466       this.visible = true;
467     }
468     else if(a == 2) {
469       this.css.visibility = 'inherit';
470       this.visible = true;
471     }
472     else {
473       this.css.visibility = 'hidden';
474       this.visible = false;
475     }
476   };
477
478   // write new content into a Layer
479   this.write = function(cont)
480   {
481     this.elm.innerHTML = cont;
482   };
483
484 };
485
486
487 // check if input is a valid email address
488 // By Cal Henderson <cal@iamcal.com>
489 // http://code.iamcal.com/php/rfc822/
490 function rcube_check_email(input, inline)
491 {
492   if (input && window.RegExp) {
493     var qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]',
494       dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]',
495       atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+',
496       quoted_pair = '\\x5c[\\x00-\\x7f]',
497       quoted_string = '\\x22('+qtext+'|'+quoted_pair+')*\\x22',
498       // Use simplified domain matching, because we need to allow Unicode characters here
499       // So, e-mail address should be validated also on server side after idn_to_ascii() use
500       //domain_literal = '\\x5b('+dtext+'|'+quoted_pair+')*\\x5d',
501       //sub_domain = '('+atom+'|'+domain_literal+')',
502       // allow punycode/unicode top-level domain
503       domain = '([^@\\x2e]+\\x2e)+([^\\x00-\\x40\\x5b-\\x60\\x7b-\\x7f]{2,}|xn--[a-z0-9]{2,})',
504       // ICANN e-mail test (http://idn.icann.org/E-mail_test)
505       icann_domains = [
506         '\\u0645\\u062b\\u0627\\u0644\\x2e\\u0625\\u062e\\u062a\\u0628\\u0627\\u0631',
507         '\\u4f8b\\u5b50\\x2e\\u6d4b\\u8bd5',
508         '\\u4f8b\\u5b50\\x2e\\u6e2c\\u8a66',
509         '\\u03c0\\u03b1\\u03c1\\u03ac\\u03b4\\u03b5\\u03b9\\u03b3\\u03bc\\u03b1\\x2e\\u03b4\\u03bf\\u03ba\\u03b9\\u03bc\\u03ae',
510         '\\u0909\\u0926\\u093e\\u0939\\u0930\\u0923\\x2e\\u092a\\u0930\\u0940\\u0915\\u094d\\u0937\\u093e',
511         '\\u4f8b\\u3048\\x2e\\u30c6\\u30b9\\u30c8',
512         '\\uc2e4\\ub840\\x2e\\ud14c\\uc2a4\\ud2b8',
513         '\\u0645\\u062b\\u0627\\u0644\\x2e\\u0622\\u0632\\u0645\\u0627\\u06cc\\u0634\u06cc',
514         '\\u043f\\u0440\\u0438\\u043c\\u0435\\u0440\\x2e\\u0438\\u0441\\u043f\\u044b\\u0442\\u0430\\u043d\\u0438\\u0435',
515         '\\u0b89\\u0ba4\\u0bbe\\u0bb0\\u0ba3\\u0bae\\u0bcd\\x2e\\u0baa\\u0bb0\\u0bbf\\u0b9f\\u0bcd\\u0b9a\\u0bc8',
516         '\\u05d1\\u05f2\\u05b7\\u05e9\\u05e4\\u05bc\\u05d9\\u05dc\\x2e\\u05d8\\u05e2\\u05e1\\u05d8'
517       ],
518       icann_addr = 'mailtest\\x40('+icann_domains.join('|')+')',
519       word = '('+atom+'|'+quoted_string+')',
520       delim = '[,;\s\n]',
521       local_part = word+'(\\x2e'+word+')*',
522       addr_spec = '(('+local_part+'\\x40'+domain+')|('+icann_addr+'))',
523       reg1 = inline ? new RegExp('(^|<|'+delim+')'+addr_spec+'($|>|'+delim+')', 'i') : new RegExp('^'+addr_spec+'$', 'i');
524
525     return reg1.test(input) ? true : false;
526   }
527
528   return false;
529 };
530
531
532 // recursively copy an object
533 function rcube_clone_object(obj)
534 {
535   var out = {};
536
537   for (var key in obj) {
538     if (obj[key] && typeof obj[key] === 'object')
539       out[key] = clone_object(obj[key]);
540     else
541       out[key] = obj[key];
542   }
543
544   return out;
545 };
546
547 // make a string URL safe
548 function urlencode(str)
549 {
550   return window.encodeURIComponent ? encodeURIComponent(str) : escape(str);
551 };
552
553
554 // get any type of html objects by id/name
555 function rcube_find_object(id, d)
556 {
557   var n, f, obj, e;
558   if(!d) d = document;
559
560   if(d.getElementsByName && (e = d.getElementsByName(id)))
561     obj = e[0];
562   if(!obj && d.getElementById)
563     obj = d.getElementById(id);
564   if(!obj && d.all)
565     obj = d.all[id];
566
567   if(!obj && d.images.length)
568     obj = d.images[id];
569
570   if (!obj && d.forms.length) {
571     for (f=0; f<d.forms.length; f++) {
572       if(d.forms[f].name == id)
573         obj = d.forms[f];
574       else if(d.forms[f].elements[id])
575         obj = d.forms[f].elements[id];
576     }
577   }
578
579   if (!obj && d.layers) {
580     if (d.layers[id]) obj = d.layers[id];
581     for (n=0; !obj && n<d.layers.length; n++)
582       obj = rcube_find_object(id, d.layers[n].document);
583   }
584
585   return obj;
586 };
587
588 // determine whether the mouse is over the given object or not
589 function rcube_mouse_is_over(ev, obj)
590 {
591   var mouse = rcube_event.get_mouse_pos(ev),
592     pos = $(obj).offset();
593
594   return ((mouse.x >= pos.left) && (mouse.x < (pos.left + obj.offsetWidth)) &&
595     (mouse.y >= pos.top) && (mouse.y < (pos.top + obj.offsetHeight)));
596 };
597
598
599 // cookie functions by GoogieSpell
600 function setCookie(name, value, expires, path, domain, secure)
601 {
602   var curCookie = name + "=" + escape(value) +
603       (expires ? "; expires=" + expires.toGMTString() : "") +
604       (path ? "; path=" + path : "") +
605       (domain ? "; domain=" + domain : "") +
606       (secure ? "; secure" : "");
607   document.cookie = curCookie;
608 };
609
610 function getCookie(name)
611 {
612   var dc = document.cookie,
613     prefix = name + "=",
614     begin = dc.indexOf("; " + prefix);
615
616   if (begin == -1) {
617     begin = dc.indexOf(prefix);
618     if (begin != 0)
619       return null;
620   }
621   else {
622     begin += 2;
623   }
624
625   var end = dc.indexOf(";", begin);
626   if (end == -1)
627     end = dc.length;
628
629   return unescape(dc.substring(begin + prefix.length, end));
630 };
631
632 roundcube_browser.prototype.set_cookie = setCookie;
633 roundcube_browser.prototype.get_cookie = getCookie;
634
635 // tiny replacement for Firebox functionality
636 function rcube_console()
637 {
638   this.log = function(msg)
639   {
640     var box = rcube_find_object('dbgconsole');
641
642     if (box) {
643       if (msg.charAt(msg.length-1)=='\n')
644         msg += '--------------------------------------\n';
645       else
646         msg += '\n--------------------------------------\n';
647
648       // Konqueror doesn't allow to just change the value of hidden element
649       if (bw.konq) {
650         box.innerText += msg;
651         box.value = box.innerText;
652       } else
653         box.value += msg;
654     }
655   };
656
657   this.reset = function()
658   {
659     var box = rcube_find_object('dbgconsole');
660     if (box)
661       box.innerText = box.value = '';
662   };
663 };
664
665 var bw = new roundcube_browser();
666 bw.set_html_class();
667
668
669 // Add escape() method to RegExp object
670 // http://dev.rubyonrails.org/changeset/7271
671 RegExp.escape = function(str)
672 {
673   return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
674 };
675
676
677 // Make getElementById() case-sensitive on IE
678 if (bw.ie)
679 {
680   document._getElementById = document.getElementById;
681   document.getElementById = function(id)
682   {
683     var i = 0, obj = document._getElementById(id);
684
685     if (obj && obj.id != id)
686       while ((obj = document.all[i]) && obj.id != id)
687         i++;
688
689     return obj;
690   }
691 }