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