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