Automatically remove column select filter if unapplyable
[infodrom/rico3] / minsrc / rico.js
1 /*
2  *  (c) 2005-2012 Richard Cowin (http://openrico.org)
3  *  (c) 2005-2012 Matt Brown (http://dowdybrown.com)
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
6  *  file except in compliance with the License. You may obtain a copy of the License at
7  *
8  *         http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software distributed under the
11  *  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
12  *  either express or implied. See the License for the specific language governing permissions
13  *  and limitations under the License.
14  */
15
16 Rico.Version='3.0';
17 Rico.theme={};
18 Rico.onLoadCallbacks=[];
19 Rico.windowIsLoaded=false;
20 Rico.inputtypes={search: 0, number: 0, range: 0, color: 0, tel: 0, url: 0, email: 0, date: 0, month: 0, week: 0, time: 0, datetime: 0, 'datetime-local': 0};
21
22 // called by the document onload event
23 Rico.windowLoaded=function() {
24   this.windowIsLoaded=true;
25   if (typeof Rico_CONFIG == 'object') {
26     if (Rico_CONFIG.enableLogging) this.enableLogging();
27     if (Rico_CONFIG.enableHTML5) this._CheckInputTypes();
28   }
29   Rico.writeDebugMsg=Rico.log;  // for backwards compatibility
30   Rico.log('Processing callbacks');
31   while (this.onLoadCallbacks.length > 0) {
32     var callback=this.onLoadCallbacks.shift();
33     if (callback) callback();
34   }
35 };
36
37 // check for availability of HTML5 input types
38 Rico._CheckInputTypes=function() {
39   var i = document.createElement("input");
40   for (var itype in this.inputtypes) {
41     i.setAttribute("type", "text");
42     i.setAttribute("type", itype);
43     this.inputtypes[itype]=(i.type !== "text");
44   }
45 };
46
47 Rico.onLoad=function(callback,frontOfQ) {
48   if (this.windowIsLoaded)
49     callback();
50   else if (frontOfQ)
51     this.onLoadCallbacks.unshift(callback);
52   else
53     this.onLoadCallbacks.push(callback);
54 };
55
56 Rico.isKonqueror=navigator.userAgent.toLowerCase().indexOf("konqueror") > -1;
57 Rico.isIE=!!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1);
58 Rico.isOpera=navigator.userAgent.indexOf('Opera') > -1;
59 Rico.isWebKit=navigator.userAgent.indexOf('AppleWebKit/') > -1;
60 Rico.isGecko=navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') === -1;
61 Rico.ieVersion=/MSIE (\d+\.\d+);/.test(navigator.userAgent) ? new Number(RegExp.$1) : null;
62
63 // logging funtions
64
65 Rico.startTime=new Date();
66
67 Rico.timeStamp=function() {
68   var stamp = new Date();
69   return (stamp.getTime()-this.startTime.getTime())+": ";
70 };
71
72 Rico.setDebugArea=function(id, forceit) {
73   if (!this.debugArea || forceit) {
74     var newarea=document.getElementById(id);
75     if (!newarea) return;
76     this.debugArea=newarea;
77     newarea.value='';
78   }
79 };
80
81 Rico.log=function() {};
82
83 Rico.enableLogging=function() {
84   if (this.debugArea) {
85     this.log = function(msg, resetFlag) {
86       if (resetFlag) this.debugArea.value='';
87       this.debugArea.value+=this.timeStamp()+msg+"\n";
88     };
89   } else if (window.console) {
90     if (window.console.firebug)
91       this.log = function(msg) { window.console.log(this.timeStamp(),msg); };
92     else
93       this.log = function(msg) { window.console.log(this.timeStamp()+msg); };\r
94   } else if (window.opera) {
95     this.log = function(msg) { window.opera.postError(this.timeStamp()+msg); };
96   }
97 };
98
99 Rico.$=function(e) {
100   return typeof e == 'string' ? document.getElementById(e) : e;
101 };
102
103 Rico.runLater=function() {
104   var args = Array.prototype.slice.call(arguments);
105   var msec = args.shift();
106   var object = args.shift();
107   var method = args.shift();
108   return setTimeout(function() { object[method].apply(object,args); },msec);
109 };
110
111 Rico.visible=function(element) {
112   return Rico.getStyle(element,"display") != 'none';
113 };
114
115 Rico.show=function(element) {
116   element.style.display = '';
117 };
118
119 Rico.hide=function(element) {
120   element.style.display = 'none';
121 };
122
123 Rico.toggle=function(element) {
124   element.style.display = element.style.display == 'none' ? '' : 'none';
125 };
126
127 // ltr or rtl
128 Rico.direction=function(element) {
129   return (Rico.getStyle(element,'direction') || 'ltr').toLowerCase();
130 };
131
132 Rico.viewportOffset=function(element) {
133   var offset=Rico.cumulativeOffset(element);
134   offset.left -= this.docScrollLeft();
135   offset.top -= this.docScrollTop();
136   return offset;
137 };
138
139 /**
140  * Return text within an html element
141  * @param el DOM node
142  * @param xImg true to exclude img tag info
143  * @param xForm true to exclude input, select, and textarea tags
144  * @param xClass exclude elements with a class name of xClass
145  */
146 Rico.getInnerText=function(el,xImg,xForm,xClass) {
147   switch (typeof el) {
148     case 'string': return el;
149     case 'undefined': return el;
150     case 'number': return el.toString();
151   }
152   var cs = el.childNodes;
153   var l = cs.length;
154   var str = "";
155   for (var i = 0; i < l; i++) {
156     switch (cs[i].nodeType) {
157     case 1: //ELEMENT_NODE
158       if (this.getStyle(cs[i],'display')=='none') continue;
159       if (xClass && this.hasClass(cs[i],xClass)) continue;
160       switch (cs[i].tagName.toLowerCase()) {
161         case 'img':   if (!xImg) str += cs[i].alt || cs[i].title || cs[i].src; break;
162         case 'input': if (!xForm && !cs[i].disabled && cs[i].type.toLowerCase()=='text') str += cs[i].value; break;
163         case 'select': if (!xForm && cs[i].selectedIndex>=0) str += cs[i].options[cs[i].selectedIndex].text; break;
164         case 'textarea': if (!xForm && !cs[i].disabled) str += cs[i].value; break;
165         default:      str += this.getInnerText(cs[i],xImg,xForm,xClass); break;
166       }
167       break;
168     case 3: //TEXT_NODE
169       str += cs[i].nodeValue;
170       break;
171     }
172   }
173   return str;
174 };
175
176 /**
177  * Return value of a node in an XML response.
178  * For Konqueror 3.5, isEncoded must be true.
179  */
180 Rico.getContentAsString=function( parentNode, isEncoded ) {
181   if (isEncoded) return this._getEncodedContent(parentNode);
182   if (typeof parentNode.xml != 'undefined') return this._getContentAsStringIE(parentNode);
183   return this._getContentAsStringMozilla(parentNode);
184 };
185
186 Rico._getEncodedContent=function(parentNode) {
187   if (parentNode.innerHTML) return parentNode.innerHTML;
188   switch (parentNode.childNodes.length) {
189     case 0:  return "";
190     case 1:  return parentNode.firstChild.nodeValue;
191     default: return parentNode.childNodes[1].nodeValue;
192   }
193 };
194
195 Rico._getContentAsStringIE=function(parentNode) {
196   var contentStr = "";
197   for ( var i = 0 ; i < parentNode.childNodes.length ; i++ ) {
198      var n = parentNode.childNodes[i];
199      contentStr += (n.nodeType == 4) ? n.nodeValue : n.xml;
200   }
201   return contentStr;
202 };
203
204 Rico._getContentAsStringMozilla=function(parentNode) {
205    var xmlSerializer = new XMLSerializer();
206    var contentStr = "";
207    for ( var i = 0 ; i < parentNode.childNodes.length ; i++ ) {
208         var n = parentNode.childNodes[i];
209         if (n.nodeType == 4) { // CDATA node
210             contentStr += n.nodeValue;
211         }
212         else {
213           contentStr += xmlSerializer.serializeToString(n);
214       }
215    }
216    return contentStr;
217 };
218
219 /**
220  * @param n a number (or a string to be converted using parseInt)
221  * @returns the integer value of n, or 0 if n is not a number
222  */
223 Rico.nan2zero=function(n) {
224   if (typeof(n)=='string') n=parseInt(n,10);
225   return isNaN(n) || typeof(n)=='undefined' ? 0 : n;
226 };
227
228 Rico.stripTags=function(s) {
229   return s.replace(/<\/?[^>]+>/gi, '');
230 };
231
232 Rico.truncate=function(s,length) {
233   return s.length > length ? s.substr(0, length - 3) + '...' : s;
234 };
235
236 Rico.zFill=function(n,slen, radix) {
237   var s=n.toString(radix || 10);
238   while (s.length<slen) s='0'+s;
239   return s;
240 };
241
242 Rico.keys=function(obj) {
243   var objkeys=[];
244   for(var k in obj)
245     objkeys.push(k);
246   return objkeys;
247 };
248
249 /**
250  * @param e event object
251  * @returns the key code stored in the event
252  */
253 Rico.eventKey=function(e) {
254   if( typeof( e.keyCode ) == 'number'  ) {
255     return e.keyCode; //DOM
256   } else if( typeof( e.which ) == 'number' ) {
257     return e.which;   //NS 4 compatible
258   } else if( typeof( e.charCode ) == 'number'  ) {
259     return e.charCode; //also NS 6+, Mozilla 0.9+
260   }
261   return -1;  //total failure, we have no way of obtaining the key code
262 };
263
264 Rico.eventLeftClick=function(e) {
265   return (((e.which) && (e.which == 1)) ||
266           ((e.button) && (e.button == 1)));
267 };
268
269 Rico.eventRelatedTarget=function(e) {
270   return e.relatedTarget;
271 };
272
273   /**
274  * Return the previous sibling that has the specified tagName
275  */
276  Rico.getPreviosSiblingByTagName=function(el,tagName) {
277    var sib=el.previousSibling;
278    while (sib) {
279      if ((sib.tagName==tagName) && (sib.style.display!='none')) return sib;
280      sib=sib.previousSibling;
281    }
282    return null;
283  };
284
285 /**
286  * Return the parent of el that has the specified tagName.
287  * @param el DOM node
288  * @param tagName tag to search for
289  * @param className optional
290  */
291 Rico.getParentByTagName=function(el,tagName,className) {
292   var par=el;
293   tagName=tagName.toLowerCase();
294   while (par) {
295     if (par.tagName && par.tagName.toLowerCase()==tagName) {
296       if (!className || par.className.indexOf(className)>=0) return par;
297     }
298         par=par.parentNode;
299   }
300   return null;
301 };
302
303 /**
304  * Wrap the children of a DOM element in a new element
305  * @param el the element whose children are to be wrapped
306  * @param cls class name of the wrapper (optional)
307  * @param id id of the wrapper (optional)
308  * @param wrapperTag type of wrapper element to be created (optional, defaults to DIV)
309  * @returns new wrapper element
310  */
311 Rico.wrapChildren=function(el,cls,id,wrapperTag) {
312   var wrapper = document.createElement(wrapperTag || 'div');
313   if (id) wrapper.id=id;
314   if (cls) wrapper.className=cls;
315   while (el.firstChild) {
316     wrapper.appendChild(el.firstChild);
317   }
318   el.appendChild(wrapper);
319   return wrapper;
320 };
321
322 /**
323  * Positions ctl over icon
324  * @param ctl (div with position:absolute)
325  * @param icon element (img, button, etc) that ctl should be displayed next to
326  */
327 Rico.positionCtlOverIcon=function(ctl,icon) {
328   icon=this.$(icon);
329   var offsets=this.cumulativeOffset(icon);
330   var scrTop=this.docScrollTop();
331   var winHt=this.windowHeight();
332   if (ctl.style.display=='none') ctl.style.display='block';
333   var correction=2;  // based on a 1px border
334   if (Rico.direction(icon) == 'rtl') {
335     //var margin=this.nan2zero(this.getStyle(icon,'marginRight'));
336     ctl.style.left = (offsets.left + icon.offsetWidth - ctl.offsetWidth)+'px';
337   } else {
338     var margin=this.nan2zero(this.getStyle(icon,'marginLeft'));
339     ctl.style.left = (offsets.left+margin+correction)+'px';
340   }
341   var newTop=offsets.top + correction;// + scrTop;
342   var ctlht=ctl.offsetHeight;
343   var iconht=icon.offsetHeight;
344   var margin=10;  // account for shadow
345   if (newTop+iconht+ctlht+margin < winHt+scrTop) {
346     newTop+=iconht;  // display below icon
347   } else {
348     newTop=Math.max(newTop-ctlht,scrTop);  // display above icon
349   }
350   ctl.style.top = newTop+'px';
351 };
352
353 /**
354  * Creates a form element
355  * @param parent new element will be appended to this node
356  * @param elemTag element to be created (input, button, select, textarea, ...)
357  * @param elemType for input tag this specifies the type (checkbox, radio, text, ...)
358  * @param id id for new element
359  * @param name name for new element, if not specified then name will be the same as the id
360  * @returns new element
361  */
362 Rico.createFormField=function(parent,elemTag,elemType,id,name) {
363   var field;
364   if (typeof name!='string') name=id;
365   if (this.isIE && this.ieVersion < 8) {
366     // IE cannot set NAME attribute on dynamically created elements
367     var s=elemTag+' id="'+id+'"';
368     if (elemType) {
369       s+=' type="'+elemType+'"';
370     }
371     if (elemTag.match(/^(form|input|select|textarea|object|button|img)$/)) {
372       s+=' name="'+name+'"';
373     }
374     field=document.createElement('<'+s+' />');
375   } else {
376     field=document.createElement(elemTag);
377     if (elemType) {
378       field.type=elemType;
379     }
380     field.id=id;
381     if (typeof field.name=='string') {
382       field.name=name;
383     }
384   }
385   parent.appendChild(field);
386   return field;
387 };
388
389 /**
390  * Adds a new option to the end of a select list
391  * @returns new option element
392  */
393 Rico.addSelectOption=function(elem,value,text) {
394   var opt=document.createElement('option');
395   if (typeof value=='string') opt.value=value;
396   opt.text=text;
397   if (this.isIE) {
398     elem.add(opt);
399   } else {
400     elem.add(opt,null);
401   }
402   return opt;
403 };
404
405 /**
406  * @returns the value of the specified cookie (or null if it doesn't exist)
407  */
408 Rico.getCookie=function(itemName) {
409   var arg = itemName+'=';
410   var alen = arg.length;
411   var clen = document.cookie.length;
412   var i = 0;
413   while (i < clen) {
414     var j = i + alen;
415     if (document.cookie.substring(i, j) == arg) {
416       var endstr = document.cookie.indexOf (';', j);
417       if (endstr == -1) {
418         endstr=document.cookie.length;
419       }
420       return unescape(document.cookie.substring(j, endstr));
421     }
422     i = document.cookie.indexOf(' ', i) + 1;
423     if (i == 0) break;
424   }
425   return null;
426 };
427
428 Rico.getTBody=function(tab) {
429   return tab.tBodies.length==0 ? tab.appendChild(document.createElement("tbody")) : tab.tBodies[0];
430 };
431
432 /**
433  * Write information to a cookie.
434  * For cookies to be retained for the current session only, set daysToKeep=null.
435  * To erase a cookie, pass a negative daysToKeep value.
436  * @see <a href="http://www.quirksmode.org/js/cookies.html">Quirksmode article</a> for more information about cookies.
437  */
438 Rico.setCookie=function(itemName,itemValue,daysToKeep,cookiePath,cookieDomain) {
439   var c = itemName+"="+escape(itemValue);
440   if (typeof(daysToKeep)=='number') {
441     var date = new Date();
442     date.setTime(date.getTime()+(daysToKeep*24*60*60*1000));
443     c+="; expires="+date.toGMTString();
444   }
445   if (typeof(cookiePath)=='string') {
446     c+="; path="+cookiePath;
447   }
448   if (typeof(cookieDomain)=='string') {
449     c+="; domain="+cookieDomain;
450   }
451   document.cookie = c;
452 };
453
454 Rico.phrasesById = {};
455 /** thousands separator for number formatting */
456 Rico.thouSep = ",";
457 /** decimal point for number formatting */
458 Rico.decPoint = ".";
459 /** target language (2 character code) */
460 Rico.langCode = "en";
461 /** date format */
462 Rico.dateFmt = "mm/dd/yyyy";
463 /** time format */
464 Rico.timeFmt = "hh:nn:ss a/pm";
465 /** month name array (Jan is at index 0) */
466 Rico.monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
467 /** day of week array (Sunday is at index 0) */
468 Rico.dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
469
470 /**
471  * @param monthIdx 0-11
472  * @returns month abbreviation
473  */
474 Rico.monthAbbr=function(monthIdx) {
475   return this.monthNamesShort ? this.monthNamesShort[monthIdx] : this.monthNames[monthIdx].substr(0,3);
476 };
477
478 /**
479  * @param dayIdx 0-6 (Sunday=0)
480  * @returns day of week abbreviation
481  */
482 Rico.dayAbbr=function(dayIdx) {
483   return this.dayNamesShort ? this.dayNamesShort[dayIdx] : this.dayNames[dayIdx].substr(0,3);
484 };
485
486 Rico.addPhraseId=function(phraseId, phrase) {
487   this.phrasesById[phraseId]=phrase;
488 };
489
490 Rico.getPhraseById=function(phraseId) {
491   var phrase=this.phrasesById[phraseId];
492   if (!phrase) {
493     alert('Error: missing phrase for '+phraseId);
494     return '';
495   }
496   if (arguments.length <= 1) return phrase;
497   var a=arguments;
498   return phrase.replace(/(\$\d)/g,
499     function($1) {
500       var idx=parseInt($1.charAt(1),10);
501       return (idx < a.length) ? a[idx] : '';
502     }
503   );
504 };
505
506 /**
507  * Format a positive number (integer or float)
508  * @param posnum number to format
509  * @param decPlaces the number of digits to display after the decimal point
510  * @param thouSep boolean indicating whether to insert thousands separator
511  * @returns formatted string
512  */
513 Rico.formatPosNumber=function(posnum,decPlaces,thouSep) {
514   var a=posnum.toFixed(decPlaces).split(/\./);
515   if (thouSep) {
516     var rgx = /(\d+)(\d{3})/;
517     while (rgx.test(a[0])) {
518       a[0]=a[0].replace(rgx, '$1'+Rico.thouSep+'$2');
519     }
520   }
521   return a.join(Rico.decPoint);
522 };
523
524 /**
525  * Format a number according to the specs in fmt object.
526  * @returns string, wrapped in a span element with a class of: negNumber, zeroNumber, posNumber
527  * These classes can be set in CSS to display negative numbers in red, for example.
528  *
529  * @param n number to be formatted
530  * @param fmt may contain any of the following:<dl>
531  *   <dt>multiplier </dt><dd> the original number is multiplied by this amount before formatting</dd>
532  *   <dt>decPlaces  </dt><dd> number of digits to the right of the decimal point</dd>
533  *   <dt>thouSep    </dt><dd> boolean indicating whether to insert thousands separator</dd>
534  *   <dt>prefix     </dt><dd> string added to the beginning of the result (e.g. a currency symbol)</dd>
535  *   <dt>suffix     </dt><dd> string added to the end of the result (e.g. % symbol)</dd>
536  *   <dt>negSign    </dt><dd> specifies format for negative numbers: L=leading minus, T=trailing minus, P=parens</dd>
537  *</dl>
538  */
539 Rico.formatNumber=function(n,fmt) {
540   if (typeof n=='string') n=parseFloat(n.replace(/,/,'.'),10);
541   if (isNaN(n)) return 'NaN';
542   if (typeof fmt.multiplier=='number') n*=fmt.multiplier;
543   var decPlaces=typeof fmt.decPlaces=='number' ? fmt.decPlaces : 0;
544   var thouSep=typeof fmt.thouSep=='undefined' ? true : fmt.thouSep;
545   var prefix=fmt.prefix || "";
546   var suffix=fmt.suffix || "";
547   var negSign=typeof fmt.negSign=='string' ? fmt.negSign : "L";
548   negSign=negSign.toUpperCase();
549   var s,cls;
550   if (n<0.0) {
551     s=this.formatPosNumber(-n,decPlaces,thouSep);
552     if (negSign=="P") s="("+s+")";
553     s=prefix+s;
554     if (negSign=="L") s="-"+s;
555     if (negSign=="T") s+="-";
556     cls='negNumber';
557   } else {
558     cls=n==0.0 ? 'zeroNumber' : 'posNumber';
559     s=prefix+this.formatPosNumber(n,decPlaces,thouSep);
560   }
561   return "<span class='"+cls+"'>"+s+suffix+"</span>";
562 };
563
564 /**
565  * Converts a date to a string according to specs in fmt
566  * @returns formatted string
567  * @param d date to be formatted
568  * @param fmt string specifying the output format, may be one of the following:<dl>
569  * <dt>locale or localeDateTime</dt>
570  *   <dd>use javascript's built-in toLocaleString() function</dd>
571  * <dt>localeDate or 'Long Date'</dt>
572  *   <dd>use javascript's built-in toLocaleDateString() function</dd>
573  * <dt>translate or translateDateTime</dt>
574  *   <dd>use the formats specified in the Rico.dateFmt and Rico.timeFmt properties</dd>
575  * <dt>translateDate or 'Short Date'</dt>
576  *   <dd>use the date format specified in the Rico.dateFmt property</dd>
577  * <dt>Otherwise</dt>
578  *   <dd>Any combination of: yyyy, yy, mmmm, mmm, mm, m, dddd, ddd, dd, d, hh, h, HH, H, nn, ss, a/p</dd>
579  *</dl>
580  */
581 Rico.formatDate=function(d,fmt) {
582   var datefmt=(typeof fmt=='string') ? fmt : 'translateDate';
583   switch (datefmt) {
584     case 'locale':
585     case 'localeDateTime':
586       return d.toLocaleString();
587     case 'Long Date':
588     case 'localeDate':
589       return d.toLocaleDateString();
590     case 'translate':
591     case 'translateDateTime':
592       datefmt=this.dateFmt+' '+this.timeFmt;
593       break;
594     case 'Short Date':
595     case 'translateDate':
596       datefmt=this.dateFmt;
597       break;
598   }
599   return datefmt.replace(/(yyyy|yy|mmmm|mmm|mm|dddd|ddd|dd|d|hh|nn|ss|a\/p)/gi,
600     function($1) {
601       var h;
602       switch ($1) {
603       case 'yyyy': return d.getFullYear();
604       case 'yy':   return d.getFullYear().toString().substr(2);
605       case 'mmmm': return Rico.monthNames[d.getMonth()];
606       case 'mmm':  return Rico.monthAbbr(d.getMonth());
607       case 'mm':   return Rico.zFill(d.getMonth() + 1, 2);
608       case 'm':    return (d.getMonth() + 1);
609       case 'dddd': return Rico.dayNames[d.getDay()];
610       case 'ddd':  return Rico.dayAbbr(d.getDay());
611       case 'dd':   return Rico.zFill(d.getDate(), 2);
612       case 'd':    return d.getDate();
613       case 'hh':   return Rico.zFill((h = d.getHours() % 12) ? h : 12, 2);
614       case 'h':    return ((h = d.getHours() % 12) ? h : 12);
615       case 'HH':   return Rico.zFill(d.getHours(), 2);
616       case 'H':    return d.getHours();
617       case 'nn':   return Rico.zFill(d.getMinutes(), 2);
618       case 'ss':   return Rico.zFill(d.getSeconds(), 2);
619       case 'a/p':  return d.getHours() < 12 ? 'a' : 'p';
620       }
621     }
622   );
623 };
624
625 /**
626  * Converts a string in ISO 8601 format to a date object.
627  * @returns date object, or false if string is not a valid date or date-time.
628  * @param string value to be converted
629  * @param offset can be used to bias the conversion and must be in minutes if provided
630  * @see Based on <a href='http://delete.me.uk/2005/03/iso8601.html'>delete.me.uk article</a>
631  */
632 Rico.setISO8601=function (string,offset) {
633   if (!string) return false;
634   var d = string.match(/(\d\d\d\d)(?:-?(\d\d)(?:-?(\d\d)(?:[T ](\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|(?:([-+])(\d\d)(?::?(\d\d))?)?)?)?)?)?/);
635   if (!d) return false;
636   if (!offset) offset=0;
637   var date = new Date(d[1], 0, 1);
638
639   if (d[2]) { date.setMonth(d[2] - 1); }
640   if (d[3]) { date.setDate(d[3]); }
641   if (d[4]) { date.setHours(d[4]); }
642   if (d[5]) { date.setMinutes(d[5]); }
643   if (d[6]) { date.setSeconds(d[6]); }
644   if (d[7]) { date.setMilliseconds(Number("0." + d[7]) * 1000); }
645   if (d[8]) {
646       if (d[10] && d[11]) {
647         offset = (Number(d[10]) * 60) + Number(d[11]);
648       }
649       offset *= ((d[9] == '-') ? 1 : -1);
650       offset -= date.getTimezoneOffset();
651   }
652   var time = (Number(date) + (offset * 60 * 1000));
653   date.setTime(Number(time));
654   return date;
655 };
656
657 /**
658  * Convert date to an ISO 8601 formatted string.
659  * @param date date object to be converted
660  * @param format an integer in the range 1-6 (default is 6):<dl>
661  * <dt>1 (year)</dt>
662  *   <dd>YYYY (eg 1997)</dd>
663  * <dt>2 (year and month)</dt>
664  *   <dd>YYYY-MM (eg 1997-07)</dd>
665  * <dt>3 (complete date)</dt>
666  *   <dd>YYYY-MM-DD (eg 1997-07-16)</dd>
667  * <dt>4 (complete date plus hours and minutes)</dt>
668  *   <dd>YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)</dd>
669  * <dt>5 (complete date plus hours, minutes and seconds)</dt>
670  *   <dd>YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)</dd>
671  * <dt>6 (complete date plus hours, minutes, seconds and a decimal
672  *   fraction of a second)</dt>
673  *   <dd>YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00)</dd>
674  *</dl>
675  * @see Based on: <a href='http://www.codeproject.com/jscript/dateformat.asp'>codeproject.com article</a>
676  */
677 Rico.toISO8601String=function (date, format, offset) {
678   if (!format) format=6;
679   if (!offset) {
680       offset = 'Z';
681   } else {
682       var d = offset.match(/([-+])([0-9]{2}):([0-9]{2})/);
683       var offsetnum = (Number(d[2]) * 60) + Number(d[3]);
684       offsetnum *= ((d[1] == '-') ? -1 : 1);
685       date = new Date(Number(Number(date) + (offsetnum * 60000)));
686   }
687
688   var zeropad = function (num) { return ((num < 10) ? '0' : '') + num; };
689
690   var str = date.getUTCFullYear();
691   if (format > 1) { str += "-" + zeropad(date.getUTCMonth() + 1); }
692   if (format > 2) { str += "-" + zeropad(date.getUTCDate()); }
693   if (format > 3) {
694       str += "T" + zeropad(date.getUTCHours()) +
695              ":" + zeropad(date.getUTCMinutes());
696   }
697   if (format > 5) {
698     var secs = Number(date.getUTCSeconds() + "." +
699                ((date.getUTCMilliseconds() < 100) ? '0' : '') +
700                zeropad(date.getUTCMilliseconds()));
701     str += ":" + zeropad(secs);
702   } else if (format > 4) {
703     str += ":" + zeropad(date.getUTCSeconds());
704   }
705
706   if (format > 3) { str += offset; }
707   return str;
708 };
709
710 /**
711  * Returns a new XML document object
712  */
713 Rico.createXmlDocument=function() {
714   if (document.implementation && document.implementation.createDocument) {
715     var doc = document.implementation.createDocument("", "", null);
716     // some older versions of Moz did not support the readyState property
717     // and the onreadystate event so we patch it!
718     if (doc.readyState == null) {
719       doc.readyState = 1;
720       doc.addEventListener("load", function () {
721         doc.readyState = 4;
722         if (typeof doc.onreadystatechange == "function") {
723           doc.onreadystatechange();
724         }
725       }, false);
726     }
727     return doc;
728   }
729
730   if (window.ActiveXObject)
731       return Rico.tryFunctions(
732         function() { return new ActiveXObject('MSXML2.DomDocument');   },
733         function() { return new ActiveXObject('Microsoft.DomDocument');},
734         function() { return new ActiveXObject('MSXML.DomDocument');    },
735         function() { return new ActiveXObject('MSXML3.DomDocument');   }
736       ) || false;
737   return null;
738 };
739
740 /**
741  * Update the contents of an HTML element via an AJAX call
742  */
743 Rico.ajaxUpdater = function(elem,url,options) {
744   this.updateSend(elem,url,options);
745 };
746
747 Rico.ajaxUpdater.prototype = {
748   updateSend : function(elem,url,options) {
749     this.element=elem;
750     this.onComplete=options.onComplete;
751     var self=this;
752     options.onComplete=function(xhr) { self.updateComplete(xhr); };
753     new Rico.ajaxRequest(url,options);
754   },
755
756   updateComplete : function(xhr) {
757     this.element.innerHTML=xhr.responseText;
758     if (this.onComplete) this.onComplete(xhr);
759   }
760 };
761
762 try {  // fix IE background image flicker (credit: www.mister-pixel.com)
763   document.execCommand("BackgroundImageCache", false, true);
764 } catch(err) {}
765 Rico.eventBind(window,"load", Rico.eventHandle(Rico,'windowLoaded'));