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