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