Fixes based on recent testing. Key changes: EntryType DT (datetime) has been replaced...
[infodrom/rico3] / minsrc / ricoUI.js
1 /*
2  *  (c) 2005-2009 Richard Cowin (http://openrico.org)
3  *  (c) 2005-2009 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.applyShadow = function(elem,shadowFlag) {
17   if (typeof shadowFlag=='undefined') shadowFlag=true;
18   if (shadowFlag) Rico.addClass(elem,'ricoShadow');
19   return elem;
20 };
21
22 // ensure popups/windows get closed in the right order when the user hits escape key
23 Rico._OpenPopupList = [];
24 Rico._RemoveOpenPopup = function(popup) {
25   if (popup.openIndex >= 0 && popup.openIndex < Rico._OpenPopupList.length) Rico._OpenPopupList.splice(popup.openIndex,1);
26   popup.openIndex = -1;
27 };
28 Rico._AddOpenPopup = function(popup) {
29   popup.openIndex = Rico._OpenPopupList.push(popup) - 1;
30 };
31 Rico._checkEscKey = function(e) {
32   if (Rico.eventKey(e) != 27) return true;
33   while (Rico._OpenPopupList.length > 0) {
34     var popup = Rico._OpenPopupList.pop();
35     if (popup && popup.visible()) {
36       popup.openIndex = -1;
37       Rico.eventStop(e);
38       popup.closeFunc();
39       return false;
40     }
41   }
42   return true;
43 };
44 Rico.eventBind(document,"keyup", Rico.eventHandle(Rico,'_checkEscKey'));
45
46
47 Rico.Popup = function(containerDiv,options) {
48   this.initialize(containerDiv,options);
49 };
50
51 Rico.Popup.prototype = {
52 /**
53  * @class Class to manage pop-up div windows.
54  * @constructs
55  * @param options object may contain any of the following:<dl>
56  *   <dt>hideOnClick </dt><dd> hide popup when mouse button is clicked? default=true</dd>
57  *   <dt>ignoreClicks</dt><dd> if true, mouse clicks within the popup are not allowed to bubble up to parent elements</dd>
58  *   <dt>position    </dt><dd> defaults to absolute, use "auto" to auto-detect</dd>
59  *   <dt>shadow      </dt><dd> display shadow with popup? default=true</dd>
60  *   <dt>zIndex      </dt><dd> which layer? default=1</dd>
61  *   <dt>canDrag     </dt><dd> boolean value (or function that returns a boolean) indicating if it is ok to drag/reposition popup, default=false</dd>
62  *   <dt>onClose     </dt><dd> function to call when the popup is closed</dd>
63  *</dl>
64  * @param containerDiv if supplied, then setDiv() is called at the end of initialization
65  */
66   initialize: function(containerDiv,options) {
67     this.options = {
68       hideOnClick   : false,
69       ignoreClicks  : false,
70       position      : 'absolute',
71       shadow        : true,
72       zIndex        : 2,
73       canDrag       : false,
74       dragElement   : false,
75       closeFunc     : false
76     };
77     this.openIndex=-1;
78     if (containerDiv) this.setDiv(containerDiv,options);
79   },
80
81   createContainer: function(options) {
82     this.setDiv(document.createElement('div'), options);
83     if (options && options.parent) {
84       options.parent.appendChild(this.container);
85     } else {
86       document.getElementsByTagName("body")[0].appendChild(this.container);
87     }
88   },
89
90 /**
91  * Apply popup behavior to a div that already exists in the DOM
92  * @param containerDiv div element (or element id) in the DOM. If null, then the div is created automatically.
93  */
94   setDiv: function(containerDiv,options) {
95     Rico.extend(this.options, options || {});
96     this.container=Rico.$(containerDiv);
97     if (this.options.position == 'auto') {
98       this.position=Rico.getStyle(this.container,'position').toLowerCase();
99     } else {
100       this.position=this.container.style.position=this.options.position;
101     }
102     this.content=document.createElement('div');
103     while (this.container.firstChild) {
104       this.content.appendChild(this.container.firstChild);
105     }
106     this.container.appendChild(this.content);
107     this.content.className='RicoPopupContent';
108     if (this.position != 'absolute') return;
109
110     if (this.options.closeFunc) {
111       this.closeFunc=this.options.closeFunc;
112     } else {
113       var self=this;
114       this.closeFunc=function() { self.closePopup(); };
115     }
116     this.container.style.top='0px';
117     this.container.style.left='0px';
118     this.container.style.display='none';
119     if (this.options.zIndex >= 0) this.container.style.zIndex=this.options.zIndex;
120
121     if (Rico.isIE && Rico.ieVersion < 7 && this.options.shim!==false) {
122       this.content.style.position='relative';
123       this.content.style.zIndex=2;
124       // create iframe shim
125       this.ifr = document.createElement('iframe');
126       this.ifr.className='RicoShim';
127       this.ifr.frameBorder=0;
128       this.ifr.src="javascript:'';";
129       this.container.appendChild(this.ifr);
130     }
131     Rico.applyShadow(this.container,this.options.shadow);
132
133     if (this.options.hideOnClick)
134       Rico.eventBind(document,"click", Rico.eventHandle(this,'_docClick'));
135     this.dragEnabled=false;
136     this.mousedownHandler = Rico.eventHandle(this,'_startDrag');
137     this.dragHandler = Rico.eventHandle(this,'_drag');
138     this.dropHandler = Rico.eventHandle(this,'_endDrag');
139     if (this.options.canDrag) this.enableDragging();
140     if (this.options.ignoreClicks || this.options.canDrag) this.ignoreClicks();
141   },
142
143   clearContent: function() {
144     this.content.innerHTML="";
145   },
146
147   setContent: function(content) {
148     this.content.innerHTML=content;
149   },
150
151   enableDragging: function() {
152     if (!this.dragEnabled && this.options.dragElement) {
153       Rico.eventBind(this.options.dragElement, "mousedown", this.mousedownHandler);
154       this.dragEnabled=true;
155     }
156     return this.dragEnabled;
157   },
158
159   disableDragging: function() {
160     if (!this.dragEnabled) return;
161     Rico.eventUnbind(this.options.dragElement, "mousedown", this.mousedownHandler);
162     this.dragEnabled=false;
163   },
164
165   setZ: function(zIndex) {
166     this.container.style.zIndex=zIndex;
167   },
168
169 /** @private */
170   ignoreClicks: function() {
171     Rico.eventBind(this.container,"click", Rico.eventHandle(this,'_ignoreClick'));
172   },
173
174   _ignoreClick: function(e) {
175     if (e.stopPropagation)
176       e.stopPropagation();
177     else
178       e.cancelBubble = true;
179     return true;
180   },
181
182   _docClick: function(e) {
183     this.closeFunc();
184     return true;
185   },
186
187 /**
188  * Move popup to specified position
189  */
190   move: function(left,top) {
191     if (typeof left=='number') this.container.style.left=left+'px';
192     if (typeof top=='number') this.container.style.top=top+'px';
193   },
194
195   _startDrag : function(event){
196     var elem=Rico.eventElement(event);
197     this.container.style.cursor='move';
198     this.lastMouse = Rico.eventClient(event);
199     Rico.eventBind(document, "mousemove", this.dragHandler);
200     Rico.eventBind(document, "mouseup", this.dropHandler);
201     Rico.eventStop(event);
202   },
203
204   _drag : function(event){
205     var newMouse = Rico.eventClient(event);
206     var newLeft = parseInt(this.container.style.left,10) + newMouse.x - this.lastMouse.x;
207     var newTop = parseInt(this.container.style.top,10) + newMouse.y - this.lastMouse.y;
208     this.move(newLeft, newTop);
209     this.lastMouse = newMouse;
210     Rico.eventStop(event);
211   },
212
213   _endDrag : function(){
214     this.container.style.cursor='';
215     Rico.eventUnbind(document, "mousemove", this.dragHandler);
216     Rico.eventUnbind(document, "mouseup", this.dropHandler);
217   },
218
219 /**
220  * Display popup at specified position
221  */
222   openPopup: function(left,top) {
223     this.move(left,top);
224     this.container.style.display='';
225     if (this.container.id) Rico.log('openPopup '+this.container.id+' at '+left+','+top);
226     Rico._AddOpenPopup(this);
227   },
228   
229   centerPopup: function() {
230     this.openPopup();
231     var msgWidth=this.container.offsetWidth;
232     var msgHeight=this.container.offsetHeight;
233     var divwi=this.container.parentNode.offsetWidth;
234     var divht=this.container.parentNode.offsetHeight;
235     this.move(parseInt(Math.max((divwi-msgWidth)/2,0),10), parseInt(Math.max((divht-msgHeight)/2,0),10));
236   },
237
238   visible: function() {
239     return Rico.visible(this.container);
240   },
241
242 /**
243  * Hide popup
244  */
245   closePopup: function() {
246     Rico._RemoveOpenPopup(this);
247     if (!Rico.visible(this.container)) return;
248     if (this.container.id) Rico.log('closePopup '+this.container.id);
249     if (this.dragEnabled) this._endDrag();
250     this.container.style.display="none";
251     if (this.options.onClose) this.options.onClose();
252   }
253
254 };
255
256 Rico.closeButton = function(handle) {
257   var a = document.createElement('a');
258   a.className='RicoCloseAnchor';
259   if (Rico.theme.closeAnchor) Rico.addClass(a,Rico.theme.closeAnchor);
260   var span = a.appendChild(document.createElement('span'));
261   span.title=Rico.getPhraseById('close');
262   new Rico.HoverSet([a],{hoverClass: Rico.theme.hover || 'ricoCloseHover'});
263   Rico.addClass(span,Rico.theme.close || 'rico-icon RicoClose');
264   Rico.eventBind(a,"click", handle);
265   return a;
266 };
267
268 Rico.floatButton = function(buttonName, handle, title) {
269   var a=document.createElement("a");
270   a.className='RicoButtonAnchor'
271   Rico.addClass(a,Rico.theme.buttonAnchor || 'RicoButtonAnchorNative');
272   var span=a.appendChild(document.createElement("span"));
273   if (title) span.title=title;
274   span.className=Rico.theme[buttonName.toLowerCase()] || 'rico-icon Rico'+buttonName;
275   Rico.eventBind(a,"click", handle, false);
276   new Rico.HoverSet([a]);
277   return a
278 }
279
280 Rico.clearButton = function(handle) {
281   var span=document.createElement("span");
282   span.title=Rico.getPhraseById('clear');
283   span.className='ricoClear';
284   Rico.addClass(span, Rico.theme.clear || 'rico-icon ricoClearNative');
285   Rico.eventBind(span,"click", handle);
286   return span;
287 }
288
289 Rico.Window = function(title, options, contentParam) {
290   this.initialize(title, options, contentParam);
291 };
292
293 Rico.Window.prototype = {
294
295 /**
296  * Create popup div with a title bar.
297  */
298   initialize: function(title, options, contentParam) {
299     options=options || {overflow:'auto'};
300     Rico.extend(this, new Rico.Popup());
301
302     this.titleDiv = document.createElement('div');
303     this.options.canDrag=true;
304     this.options.dragElement=this.titleDiv;
305     this.createContainer(options);
306     this.content.appendChild(this.titleDiv);
307     contentParam=Rico.$(contentParam);
308     if (contentParam) {
309       this.contentDiv=contentParam
310       contentParam.parentNode.insertBefore(this.container,contentParam);
311     } else {
312       this.contentDiv=document.createElement('div');
313     }
314     this.content.appendChild(this.contentDiv);
315
316     // create title area
317     this.titleDiv.className='ricoTitle';
318     if (Rico.theme.dialogTitle) Rico.addClass(this.titleDiv,Rico.theme.dialogTitle);
319     this.titleDiv.style.position='relative';
320     this.titleContent = document.createElement('span');
321     this.titleContent.className='ricoTitleSpan';
322     this.titleDiv.appendChild(this.titleContent);
323     this.titleDiv.appendChild(Rico.closeButton(Rico.eventHandle(this,'closeFunc')));
324     if (!title && contentParam) {
325       title=contentParam.title;
326       contentParam.title='';
327     }
328     this.setTitle(title || '&nbsp;');
329
330     // create content area
331     this.contentDiv.className='ricoContent';
332     if (Rico.theme.dialogContent) Rico.addClass(this.contentDiv,Rico.theme.dialogContent);
333     this.contentDiv.style.position='relative';
334     if (options.height) this.contentDiv.style.height=options.height;
335     if (options.width) this.contentDiv.style.width=options.width;
336     if (options.overflow) this.contentDiv.style.overflow=options.overflow;
337     Rico.addClass(this.container,'ricoWindow');
338     if (Rico.theme.dialog) Rico.addClass(this.container,Rico.theme.dialog);
339     /*
340     if (Rico.isIE) {
341       // fix float'ed content in IE
342       this.titleDiv.style.zoom=1;
343       this.contentDiv.style.zoom=1;
344     }
345     */
346     this.content=this.contentDiv;
347   },
348
349   setTitle: function(title) {
350     this.titleContent.innerHTML=title;
351   }
352
353 }
354
355
356 Rico.Menu = function(options) {
357   this.initialize(options);
358 }
359
360 Rico.Menu.prototype = {
361 /**
362  * @class Implements popup menus and submenus
363  * @extends Rico.Popup
364  * @constructs
365  */
366   initialize: function(options) {
367     Rico.extend(this, new Rico.Popup());
368     Rico.extend(this.options, {
369       width        : "15em",
370       arrowColor   : "b",   // for submenus: b=black, w=white
371       showDisabled : false,
372       hideOnClick  : true
373     });
374     if (typeof options=='string')
375       this.options.width=options;
376     else
377       Rico.extend(this.options, options || {});
378     this.hideFunc=null;
379     this.highlightElem=null;
380   },
381
382   createDiv: function(parentNode) {
383     if (this.container) return;
384     var self=this;
385     var options={ closeFunc: function() { self.cancelmenu(); } };
386     if (parentNode) options.parent=parentNode;
387     this.createContainer(options);
388     this.content.className = Rico.isWebKit ? 'ricoMenuSafari' : 'ricoMenu';
389     this.content.style.width=this.options.width;
390     this.direction=Rico.direction(this.container);
391     this.hidemenu();
392     this.itemCount=0;
393   },
394
395   showmenu: function(e,hideFunc){
396     Rico.eventStop(e);
397     this.hideFunc=hideFunc;
398     if (this.content.childNodes.length==0) {
399       this.cancelmenu();
400       return false;
401     }
402     var mousePos = Rico.eventClient(e);
403     this.openmenu(mousePos.x,mousePos.y,0,0);
404   },
405
406   openmenu: function(x,y,clickItemWi,clickItemHt,noOffset) {
407     var newLeft=x + (noOffset ? 0 : Rico.docScrollLeft());
408     this.container.style.visibility="hidden";
409     this.container.style.display="block";
410     var w=this.container.offsetWidth;
411     var cw=this.content.offsetWidth;
412     //window.status='openmenu: newLeft='+newLeft+' width='+w+' clickItemWi='+clickItemWi+' windowWi='+Rico.windowWidth();
413     if (this.direction == 'rtl') {
414       if (newLeft > w+clickItemWi) newLeft-=cw+clickItemWi;
415     } else {
416       if (x+w > Rico.windowWidth()) newLeft-=cw+clickItemWi-2;
417     }
418     var scrTop=Rico.docScrollTop();
419     var newTop=y + (noOffset ? 0 : scrTop);
420     if (y+this.container.offsetHeight-scrTop > Rico.windowHeight())
421       newTop=Math.max(newTop-this.content.offsetHeight+clickItemHt,0);
422     this.openPopup(newLeft,newTop);
423     this.container.style.visibility ="visible";
424     return false;
425   },
426
427   clearMenu: function() {
428     this.clearContent();
429     this.defaultAction=null;
430     this.itemCount=0;
431   },
432
433   addMenuHeading: function(hdg) {
434     var el=document.createElement('div');
435     el.innerHTML=hdg;
436     el.className='ricoMenuHeading';
437     this.content.appendChild(el);
438   },
439
440   addMenuBreak: function() {
441     var brk=document.createElement('div');
442     brk.className="ricoMenuBreak";
443     this.content.appendChild(brk);
444   },
445
446   addSubMenuItem: function(menutext, submenu, translate) {
447     var dir=this.direction=='rtl' ? 'left' : 'right';
448     var a=this.addMenuItem(menutext,null,true,null,translate);
449     a.className='ricoSubMenu';
450     var arrowdiv = a.appendChild(document.createElement('div'));
451     arrowdiv.className='rico-icon rico-'+dir+'-'+this.options.arrowColor;
452     Rico.setStyle(arrowdiv,{position:'absolute',top:'2px'});
453     arrowdiv.style[dir]='0px';
454     a.RicoSubmenu=submenu;
455     Rico.eventBind(a,"mouseover", Rico.eventHandle(this,'showSubMenu'));
456     //Rico.eventBind(a,"mouseout", Rico.eventHandle(this,'subMenuOut'));
457   },
458
459   showSubMenu: function(e) {
460     if (this.openSubMenu) this.hideSubMenu();
461     var a=Rico.eventElement(e);
462     if (!a.RicoSubmenu) a=a.parentNode; // event can happen on arrow div
463     if (!a.RicoSubmenu) return;
464     this.openSubMenu=a.RicoSubmenu;
465     this.openMenuAnchor=a;
466     if (Rico.hasClass(a,'ricoSubMenu')) {
467       Rico.removeClass(a,'ricoSubMenu');
468       Rico.addClass(a,'ricoSubMenuOpen');
469     }
470     a.RicoSubmenu.openmenu(parseInt(this.container.style.left)+a.offsetWidth, parseInt(this.container.style.top)+a.offsetTop, a.offsetWidth-2, a.offsetHeight+2,true);
471   },
472
473   /*
474   subMenuOut: function(e) {
475     if (!this.openSubMenu) return;
476     Rico.eventStop(e);
477     var elem=Rico.eventElement(e);
478     var reltg = Rico.eventRelatedTarget(e) || e.toElement;
479     try {
480       while (reltg != null && reltg != this.openSubMenu.div)
481         reltg=reltg.parentNode;
482     } catch(err) {}
483     if (reltg == this.openSubMenu.div) return;
484     this.hideSubMenu();
485   },
486   */
487
488   hideSubMenu: function() {
489     if (this.openMenuAnchor) {
490       Rico.removeClass(this.openMenuAnchor,'ricoSubMenuOpen');
491       Rico.addClass(this.openMenuAnchor,'ricoSubMenu');
492       this.openMenuAnchor=null;
493     }
494     if (this.openSubMenu) {
495       this.openSubMenu.hidemenu();
496       this.openSubMenu=null;
497     }
498   },
499
500   addMenuItemId: function(phraseId,action,enabled,title,target) {
501     if ( arguments.length < 3 ) enabled=true;
502     this.addMenuItem(Rico.getPhraseById(phraseId),action,enabled,title,target);
503   },
504
505 // if action is a string, then it is assumed to be a URL and the target parm can be used indicate which window gets the content
506 // action can also be a function
507 // action can also be a Rico.eventHandle, but set target='event' in this case
508   addMenuItem: function(menutext,action,enabled,title,target) {
509     if (arguments.length >= 3 && !enabled && !this.options.showDisabled) return null;
510     this.itemCount++;
511     var a = document.createElement(typeof action=='string' ? 'a' : 'div');
512     if ( arguments.length < 3 || enabled ) {
513       if (typeof action=='string') {
514         a.href = action;
515         if (target) a.target = target;
516       } else if (target=='event') {
517         Rico.eventBind(a,"click", action);
518       } else {
519         a.onclick=action;
520       }
521       a.className = 'enabled';
522       if (this.defaultAction==null) this.defaultAction=action;
523     } else {
524       a.disabled = true;
525       a.className = 'disabled';
526     }
527     a.innerHTML = menutext;
528     if (typeof title=='string')
529       a.title = title;
530     a=this.content.appendChild(a);
531     Rico.eventBind(a,"mouseover", Rico.eventHandle(this,'mouseOver'));
532     Rico.eventBind(a,"mouseout", Rico.eventHandle(this,'mouseOut'));
533     return a;
534   },
535
536   mouseOver: function(e) {
537     if (this.highlightElem && this.highlightElem.className=='enabled-hover') {
538       // required for Safari
539       this.highlightElem.className='enabled';
540       this.highlightElem=null;
541     }
542     var elem=Rico.eventElement(e);
543     if (elem.parentNode == this.openMenuAnchor) elem=elem.parentNode;
544     if (this.openMenuAnchor && this.openMenuAnchor!=elem)
545       this.hideSubMenu();
546     if (elem.className=='enabled') {
547       elem.className='enabled-hover';
548       this.highlightElem=elem;
549     }
550   },
551
552   mouseOut: function(e) {
553     var elem=Rico.eventElement(e);
554     if (elem.className=='enabled-hover') elem.className='enabled';
555     if (this.highlightElem==elem) this.highlightElem=null;
556   },
557
558   cancelmenu: function() {
559     if (!this.visible()) return;
560     if (this.hideFunc) this.hideFunc();
561     this.hideFunc=null;
562     this.hidemenu();
563   },
564
565   hidemenu: function() {
566     if (this.openSubMenu) this.openSubMenu.hidemenu();
567     this.closePopup();
568   }
569
570 }
571
572
573 Rico.SelectionSet = function(selectionSet, options) {
574   this.initialize(selectionSet, options);
575 }
576
577 Rico.SelectionSet.prototype = {
578 /**
579  * @class
580  * @constructs
581  * @param selectionSet collection of DOM elements (or a CSS selection string)
582  * @param options object may contain any of the following:<dl>
583  *   <dt>selectedClass</dt><dd>class name to add when element is selected, default is "selected"</dd>
584  *   <dt>selectNode   </dt><dd>optional function that returns the element to be selected</dd>
585  *   <dt>onSelect     </dt><dd>optional function that gets called when element is selected</dd>
586  *   <dt>onFirstSelect</dt><dd>optional function that gets called the first time element is selected</dd>
587  *   <dt>noDefault    </dt><dd>when true, no element in the set is initially selected, default is false</dd>
588  *   <dt>selectedIndex</dt><dd>index of the element that should be initially selected, default is 0</dd>
589  *   <dt>cookieName   </dt><dd>optional name of cookie to use to remember selected element. If specified, and the cookie exists, then the cookie value overrides selectedIndex.</dd>
590  *   <dt>cookieDays   </dt><dd>specifies how long cookie should persist (in days). If unspecified, then the cookie persists for the current session.</dd>
591  *   <dt>cookiePath   </dt><dd>optional cookie path</dd>
592  *   <dt>cookieDomain </dt><dd>optional cookie domain</dd>
593  *</dl>
594  */
595   initialize: function(selectionSet, options){
596     Rico.log('SelectionSet#initialize');
597     this.options = options || {};
598     if (typeof selectionSet == 'string')
599       selectionSet = Rico.select(selectionSet);
600     this.previouslySelected = [];
601     this.selectionSet = [];
602     this.selectedClassName = this.options.selectedClass || Rico.theme.selected || "selected";
603     this.selectNode = this.options.selectNode || function(e){return e;};
604     this.onSelect = this.options.onSelect;
605     this.onFirstSelect = this.options.onFirstSelect;
606     var self=this;
607     this.clickHandler = function(idx) { self.selectIndex(idx); };
608     this.selectedIndex=-1;
609     for (var i=0; i<selectionSet.length; i++)
610       this.add(selectionSet[i]);
611     if (!this.options.noDefault) {
612       var cookieIndex=this.options.cookieName ? this.getCookie() : 0;
613       this.selectIndex(cookieIndex || this.options.selectedIndex || 0);
614     }
615   },
616   getCookie: function() {
617     var cookie = Rico.getCookie(this.options.cookieName);
618     if (!cookie) return 0;
619     var index = parseInt(cookie);
620     return index < this.selectionSet.length ? index : 0;
621   },
622   reset: function(){
623     this.previouslySelected = [];
624     this._notifySelected(this.selectedIndex);
625   },
626   clearSelected: function() {
627     if (this.selected)
628       Rico.removeClass(this.selectNode(this.selected), this.selectedClassName);
629   },
630   getIndex: function(element) {
631     for (var i=0; i<this.selectionSet.length; i++) {
632       if (element == this.selectionSet[i]) return i;
633     }
634     return -1;
635   },
636   select: function(element){
637     if (this.selected == element) return;
638     var i=this.getIndex(element);
639     if (i >= 0) this.selectIndex(i);
640   },
641   _notifySelected: function(index){
642     if (index < 0) return;
643     var element = this.selectionSet[index];
644     if (this.options.cookieName)
645       Rico.setCookie(this.options.cookieName, index, this.options.cookieDays, this.options.cookiePath, this.options.cookieDomain);
646     if (this.onFirstSelect && !this.previouslySelected[index]){
647       this.onFirstSelect(element, index);
648       this.previouslySelected[index] = true;
649     }
650     if (this.onSelect)
651       try{
652         this.onSelect(index);
653       } catch (e) {};
654   },
655   selectIndex: function(index){
656     if (this.selectedIndex == index || index >= this.selectionSet.length) return;
657     this.clearSelected();
658     this._notifySelected(index);
659     this.selectedIndex = index;
660     this.selected=this.selectionSet[index].element;
661     Rico.addClass(this.selectNode(this.selected), this.selectedClassName);
662   },
663   nextSelectIndex: function(){
664     return (this.selectedIndex + 1) % this.selectionSet.length;
665   },
666   nextSelectItem: function(){
667     return this.selectionSet[this.nextSelectIndex()];
668   },
669   selectNext: function(){
670     this.selectIndex(this.nextSelectIndex());
671   },
672   add: function(item){
673     var index=this.selectionSet.length;
674     this.selectionSet[index] = new Rico._SelectionItem(item,index,this.clickHandler);
675   },
676   remove: function(item){
677     if (item==this.selected) this.clearSelected();
678     var i=this.getIndex(item);
679     if (i < 0) return;
680     this.selectionSet[i].remove();
681     this.selectionSet.splice(i,1);
682   },
683   removeAll: function(){
684     this.clearSelected();
685     while (this.selectionSet.length > 0) {
686       this.selectionSet.pop().remove();
687     }
688   }
689 };
690
691
692 Rico._SelectionItem=function(element,index,callback) {
693   this.add(element,index,callback);
694 };
695
696 Rico._SelectionItem.prototype = {
697   add: function(element,index,callback) {
698     this.element=element;
699     this.index=index;
700     this.callback=callback;
701     this.handle=Rico.eventHandle(this,'click');
702     Rico.eventBind(element, "click", this.handle);
703   },
704
705   click: function(ev) {
706     this.callback(this.index);
707   },
708
709   remove: function() {
710     Rico.eventUnbind(this.element, "click", this.handle);
711   }
712 };
713
714
715 Rico.HoverSet = function(hoverSet, options) {
716   this.initialize(hoverSet, options);
717 };
718
719 Rico.HoverSet.prototype = {
720 /**
721  * @class
722  * @constructs
723  * @param hoverSet collection of DOM elements
724  * @param options object may contain any of the following:<dl>
725  *   <dt>hoverClass</dt><dd> class name to add when mouse is over element, default is "hover"</dd>
726  *   <dt>hoverNodes</dt><dd> optional function to select/filter which nodes are in the set</dd>
727  *</dl>
728  */
729   initialize: function(hoverSet, options){
730     Rico.log('HoverSet#initialize');
731     options = options || {};
732     this.hoverClass = options.hoverClass || Rico.theme.hover || "hover";
733     this.hoverFunc = options.hoverNodes || function(e){return [e];};
734     this.hoverSet=[];
735     if (!hoverSet) return;
736     for (var i=0; i<hoverSet.length; i++)
737       this.add(hoverSet[i]);
738   },
739   add: function(item) {
740     this.hoverSet.push(new Rico._HoverItem(item,this.hoverFunc,this.hoverClass));
741   },
742   removeAll: function(){
743     while (this.hoverSet.length > 0) {
744       this.hoverSet.pop().remove();
745     }
746   }
747 };
748
749
750 Rico._HoverItem=function(element,selectFunc,hoverClass) {
751   this.add(element,selectFunc,hoverClass);
752 };
753
754 Rico._HoverItem.prototype = {
755   add: function(element,selectFunc,hoverClass) {
756     this.element=element;
757     this.selectFunc=selectFunc;
758     this.hoverClass=hoverClass;
759     this.movehandle=Rico.eventHandle(this,'move');
760     this.outhandle=Rico.eventHandle(this,'mouseout');
761     Rico.eventBind(element, "mousemove", this.movehandle);
762     Rico.eventBind(element, "mouseout", this.outhandle);
763   },
764
765   move: function(ev) {
766     var elems=this.selectFunc(this.element);
767     for (var i=0; i<elems.length; i++)
768       Rico.addClass(elems[i],this.hoverClass);
769   },
770
771   mouseout: function(ev) {
772     var elems=this.selectFunc(this.element);
773     for (var i=0; i<elems.length; i++)
774       Rico.removeClass(elems[i],this.hoverClass);
775   },
776
777   remove: function() {
778     Rico.eventUnbind(element, "mousemove", this.movehandle);
779     Rico.eventUnbind(element, "mouseout", this.outhandle);
780   }
781 };
782
783
784 /** @class core methods for transition effects */
785 Rico.ContentTransitionBase = function() {};
786 Rico.ContentTransitionBase.prototype = {
787   initBase: function(titles, contents, options) {
788     this.options = options || {};
789     this.titles = titles;
790     this.contents = contents;
791     this.hoverSet = new Rico.HoverSet(titles, options);
792     for (var i=0; i<contents.length; i++) {
793       if (contents[i]) Rico.hide(contents[i]);
794     }
795     var self=this;
796     this.selectionSet = new Rico.SelectionSet(titles, Rico.extend(options, { onSelect: function(idx) { self._finishSelect(idx); } }));
797   },
798   reset: function(){
799     this.selectionSet.reset();
800   },
801   select: function(index) {
802     this.selectionSet.selectIndex(index);
803   },
804   _finishSelect: function(index) {
805     Rico.log('ContentTransitionBase#_finishSelect');
806     var panel = this.contents[index];
807     if (!panel) {
808       alert('Internal error: no panel @index='+index);
809       return;
810     }
811     if ( this.selected == panel) return;
812     if (this.transition){
813       if (this.selected){
814         this.transition(panel);
815       } else {
816         panel.style.display='block';
817       }
818     } else {
819       if (this.selected) Rico.hide(this.selected);
820       panel.style.display='block';
821     }
822     this.selected = panel;
823   },
824   addBase: function(title, content){
825     this.titles.push(title);
826     this.contents.push(content);
827     this.hoverSet.add(title);
828     this.selectionSet.add(title);
829     Rico.hide(content);
830     //this.selectionSet.select(title);
831   },
832   removeAll: function(){
833     this.hoverSet.removeAll();
834     this.selectionSet.removeAll();
835   }
836 };
837
838
839 /**
840  * @class Implements accordion effect
841  * @see Rico.ContentTransitionBase#initialize for construction parameters
842  * @extends Rico.ContentTransitionBase
843  */
844 Rico.Accordion = function(element, options) {
845   this.initialize(element, options);
846 };
847
848 Rico.Accordion.prototype = Rico.extend(new Rico.ContentTransitionBase(),
849 /** @lends Rico.Accordion# */
850 {
851   initialize: function(element, options) {
852     element=Rico.$(element);
853     element.style.overflow='hidden';
854     element.className=options.accClass || Rico.theme.accordion || "Rico_accordion";
855     if (typeof options.panelWidth=='number') options.panelWidth+="px";
856     if (options.panelWidth) element.style.width = options.panelWidth;
857     var panels=Rico.getDirectChildrenByTag(element,'div');
858     var items,titles=[], contents=[];
859     for (var i=0; i<panels.length; i++) {
860       items=Rico.getDirectChildrenByTag(panels[i],'div');
861       if (items.length>=2) {
862         items[0].className=options.titleClass || Rico.theme.accTitle || "Rico_accTitle";
863         items[1].className=options.contentClass || Rico.theme.accContent || "Rico_accContent";
864         titles.push(items[0]);
865         contents.push(items[1]);
866         var a=Rico.wrapChildren(items[0],'','','a');
867         a.href="javascript:void(0)";
868       }
869     }
870     Rico.log('creating Rico.Accordion for '+element.id+' with '+titles.length+' panels');
871     this.initBase(titles, contents, options);
872     this.selected.style.height = this.options.panelHeight + "px";
873     this.totSteps=(typeof options.duration =='number' ? options.duration : 200)/25;
874   },
875   transition: function(p){
876     if (!this.options.noAnimate) {
877       this.closing=this.selected;
878       this.opening=p;
879       this.curStep=0;
880       var self=this;
881       this.timer=setInterval(function() { self.step(); },25);
882     } else {
883       p.style.height = this.options.panelHeight + "px";
884       if (this.selected) Rico.hide(this.selected);
885       p.style.display='block';
886     }
887   },
888   step: function() {
889     this.curStep++;
890     var oheight=Math.round(this.curStep/this.totSteps*this.options.panelHeight);
891     this.opening.style.height=oheight+'px';
892     this.closing.style.height=(this.options.panelHeight - oheight)+'px';
893     if (this.curStep==1) {
894       this.opening.style.paddingTop=this.opening.style.paddingBottom='0px';
895       this.opening.style.display='block';
896     }
897     if (this.curStep==this.totSteps) {
898       clearInterval(this.timer);
899       this.opening.style.paddingTop=this.opening.style.paddingBottom='';
900       Rico.hide(this.closing);
901     }
902   },
903   setPanelHeight: function(h) {
904     this.options.panelHeight = h;
905     this.selected.style.height = this.options.panelHeight + "px";
906   }
907 });
908
909
910 /**
911  * @class Implements tabbed panel effect
912  * @see Rico.ContentTransitionBase#initialize for construction parameters
913  * @extends Rico.ContentTransitionBase
914  */
915 Rico.TabbedPanel = function(element, options) {
916   this.initialize(element, options);
917 };
918
919 Rico.TabbedPanel.prototype = Rico.extend(new Rico.ContentTransitionBase(),
920 {
921   initialize: function(element, options) {
922     element=Rico.$(element);
923     options=options || {};
924     if (typeof options.panelWidth=='number') options.panelWidth+="px";
925     if (typeof options.panelHeight=='number') options.panelHeight+="px";
926     element.className=options.tabClass || Rico.theme.tabPanel || "Rico_tabPanel";
927     if (options.panelWidth) element.style.width = options.panelWidth;
928     var items = [];
929     var allKids = element.childNodes;
930     for( var i = 0 ; i < allKids.length ; i++ ) {
931       if (allKids[i] && allKids[i].tagName && allKids[i].tagName.match(/^div|ul$/i))
932         items.push(allKids[i]);
933     }
934     if (items.length < 2) return;
935     var childTag=items[0].tagName.toLowerCase()=='ul' ? 'li' : 'div';
936     items[0].className=options.navContainerClass || Rico.theme.tabNavContainer || "Rico_tabNavContainer";
937     items[0].style.listStyle='none';
938     items[1].className=options.contentContainerClass || Rico.theme.tabContentContainer || "Rico_tabContentContainer";
939     var titles=Rico.getDirectChildrenByTag(items[0], childTag);
940     var contents=Rico.getDirectChildrenByTag(items[1],'div');
941     var direction=Rico.direction(element);
942     if (!options.corners) options.corners='top';
943     for (var i=0; i<titles.length; i++) {
944       if (direction == 'rtl') Rico.setStyle(titles[i], {'float':'right'});
945       titles[i].className=options.titleClass || Rico.theme.tabTitle || "Rico_tabTitle";
946       var a=Rico.wrapChildren(titles[i],'','','a');
947       a.href="javascript:void(0)";
948       contents[i].className=options.contentClass || Rico.theme.tabContent || "Rico_tabContent";
949       if (options.panelHeight) contents[i].style.overflow='auto';
950       if (options.corners!='none') {
951         if (options.panelHdrWidth) titles[i].style.width=options.panelHdrWidth;
952         Rico.Corner.round(titles[i], Rico.theme.tabCornerOptions || options);
953       }
954     }
955     options.selectedClass=Rico.theme.tabSelected || 'selected';
956     this.initBase(titles, contents, options);
957     if (this.selected) this.transition(this.selected);
958   },
959   transition: function(p){
960     Rico.log('TabbedPanel#transition '+typeof(p));
961     if (this.selected) Rico.hide(this.selected);
962     Rico.show(p);
963     if (this.options.panelHeight) p.style.height = this.options.panelHeight;
964   }
965 });
966
967
968 /**
969  * @namespace
970  */
971 Rico.Corner = {
972
973    round: function(e, options) {
974       e = Rico.$(e);
975       this.options = {
976          corners : "all",
977          bgColor : "fromParent",
978          compact : false,
979          nativeCorners: false  // only use native corners?
980       };
981       Rico.extend(this.options, options || {});
982       if (typeof(Rico.getStyle(e,'border-radius'))=='string')
983         this._roundCornersStdCss(e);
984       else if (typeof(Rico.getStyle(e,'-webkit-border-radius'))=='string')
985         this._roundCornersWebKit(e);
986       else if (typeof(Rico.getStyle(e,'-moz-border-radius'))=='string')
987         this._roundCornersMoz(e);
988       else if (!this.options.nativeCorners)
989         this._roundCornersImpl(e);
990    },
991
992     _roundCornersStdCss: function(e) {
993       var radius=this.options.compact ? '4px' : '8px';
994       if (this._hasString(this.options.corners, "all"))
995         Rico.setStyle(e, {borderRadius:radius});
996       else {
997         if (this._hasString(this.options.corners, "top", "tl")) Rico.setStyle(e, {borderTopLeftRadius:radius});
998         if (this._hasString(this.options.corners, "top", "tr")) Rico.setStyle(e, {borderTopRightRadius:radius});
999         if (this._hasString(this.options.corners, "bottom", "bl")) Rico.setStyle(e, {borderBottomLeftRadius:radius});
1000         if (this._hasString(this.options.corners, "bottom", "br")) Rico.setStyle(e, {borderBottomRightRadius:radius});
1001       }
1002    },
1003
1004    _roundCornersWebKit: function(e) {
1005       var radius=this.options.compact ? '4px' : '8px';
1006       if (this._hasString(this.options.corners, "all"))
1007         Rico.setStyle(e, {WebkitBorderRadius:radius});
1008       else {
1009         if (this._hasString(this.options.corners, "top", "tl")) Rico.setStyle(e, {WebkitBorderTopLeftRadius:radius});
1010         if (this._hasString(this.options.corners, "top", "tr")) Rico.setStyle(e, {WebkitBorderTopRightRadius:radius});
1011         if (this._hasString(this.options.corners, "bottom", "bl")) Rico.setStyle(e, {WebkitBorderBottomLeftRadius:radius});
1012         if (this._hasString(this.options.corners, "bottom", "br")) Rico.setStyle(e, {WebkitBorderBottomRightRadius:radius});
1013       }
1014    },
1015
1016    _roundCornersMoz: function(e) {
1017       var radius=this.options.compact ? '4px' : '8px';
1018       if (this._hasString(this.options.corners, "all"))
1019         Rico.setStyle(e, {MozBorderRadius:radius});
1020       else {
1021         if (this._hasString(this.options.corners, "top", "tl")) Rico.setStyle(e, {MozBorderRadiusTopleft:radius});
1022         if (this._hasString(this.options.corners, "top", "tr")) Rico.setStyle(e, {MozBorderRadiusTopright:radius});
1023         if (this._hasString(this.options.corners, "bottom", "bl")) Rico.setStyle(e, {MozBorderRadiusBottomleft:radius});
1024         if (this._hasString(this.options.corners, "bottom", "br")) Rico.setStyle(e, {MozBorderRadiusBottomright:radius});
1025       }
1026    },
1027
1028   _roundCornersImpl: function(e) {
1029       var bgColor = this.options.bgColor == "fromParent" ? this._background(e.parentNode) : this.options.bgColor;
1030       e.style.position='relative';
1031       //this.options.numSlices = this.options.compact ? 2 : 4;
1032       if (this._hasString(this.options.corners, "all", "top", "tl")) this._createCorner(e,'top','left',bgColor);
1033       if (this._hasString(this.options.corners, "all", "top", "tr")) this._createCorner(e,'top','right',bgColor);
1034       if (this._hasString(this.options.corners, "all", "bottom", "bl")) this._createCorner(e,'bottom','left',bgColor);
1035       if (this._hasString(this.options.corners, "all", "bottom", "br")) this._createCorner(e,'bottom','right',bgColor);
1036    },
1037
1038   _createCorner: function(elem,tb,lr,bgColor) {
1039     //alert('Corner: '+tb+' '+lr+' bgColor='+typeof(bgColor));
1040     var corner = document.createElement("div");
1041     corner.className='ricoCorner';
1042     Rico.setStyle(corner,{width:'6px', height:'5px'});
1043     var borderStyle = Rico.getStyle(elem,'border-'+tb+'-style');
1044     var borderColor = borderStyle=='none' ? bgColor : Rico.getStyle(elem,'border-'+tb+'-color');
1045     //alert('Corner: '+tb+' '+borderStyle+borderColor+' '+);
1046     var pos=borderStyle=='none' ? '0px' : '-1px';
1047     corner.style[tb]=pos;
1048     corner.style[lr]=Rico.isIE && Rico.ieVersion<7 && lr=='right' && borderStyle!='none' ? '-2px' : '-1px';
1049     //corner.style[lr]='-1px';
1050     elem.appendChild(corner);
1051     var marginSizes = [ 0, 2, 3, 4, 4 ];
1052     if (tb=='bottom') marginSizes.reverse();
1053     var borderVal= borderStyle=='none' ? '0px none' : '1px solid '+borderColor;
1054     var d= lr=='left' ? 'Right' : 'Left';
1055     for (var i=0; i<marginSizes.length; i++) {
1056       var slice = document.createElement("div");
1057       Rico.setStyle(slice,{backgroundColor:bgColor,height:'1px'});
1058       slice.style['margin'+d]=marginSizes[i]+'px';
1059       slice.style['border'+d]=borderVal;
1060       corner.appendChild(slice);
1061     }
1062   },
1063
1064   _background: function(elem) {
1065      try {
1066        var actualColor = Rico.getStyle(elem, "backgroundColor");
1067
1068        // if color is tranparent, check parent
1069        // Safari returns "rgba(0, 0, 0, 0)", which means transparent
1070        if ( actualColor.match(/^(transparent|rgba\(0,\s*0,\s*0,\s*0\))$/i) && elem.parentNode )
1071           return this._background(elem.parentNode);
1072
1073        return actualColor == null ? "#ffffff" : actualColor;
1074      } catch(err) {
1075        return "#ffffff";
1076      }
1077    },
1078
1079    _hasString: function(str) {
1080      for(var i=1 ; i<arguments.length ; i++) {
1081        if (str.indexOf(arguments[i]) >= 0) return true;
1082      }
1083      return false;
1084    }
1085
1086 };
1087
1088 Rico.toColorPart = function(c) {
1089   return Rico.zFill(c, 2, 16);
1090 };
1091
1092
1093 Rico.Color = function(red, green, blue) {
1094   this.initialize(red, green, blue);
1095 };
1096
1097 Rico.Color.prototype = {
1098 /**
1099  * @class Methods to manipulate color values.
1100  * @constructs
1101  * @param red integer (0-255)
1102  * @param green integer (0-255)
1103  * @param blue integer (0-255)
1104  */
1105    initialize: function(red, green, blue) {
1106       this.rgb = { r: red, g : green, b : blue };
1107    },
1108
1109    setRed: function(r) {
1110       this.rgb.r = r;
1111    },
1112
1113    setGreen: function(g) {
1114       this.rgb.g = g;
1115    },
1116
1117    setBlue: function(b) {
1118       this.rgb.b = b;
1119    },
1120
1121    setHue: function(h) {
1122
1123       // get an HSB model, and set the new hue...
1124       var hsb = this.asHSB();
1125       hsb.h = h;
1126
1127       // convert back to RGB...
1128       this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, hsb.b);
1129    },
1130
1131    setSaturation: function(s) {
1132       // get an HSB model, and set the new hue...
1133       var hsb = this.asHSB();
1134       hsb.s = s;
1135
1136       // convert back to RGB and set values...
1137       this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, hsb.b);
1138    },
1139
1140    setBrightness: function(b) {
1141       // get an HSB model, and set the new hue...
1142       var hsb = this.asHSB();
1143       hsb.b = b;
1144
1145       // convert back to RGB and set values...
1146       this.rgb = Rico.Color.HSBtoRGB( hsb.h, hsb.s, hsb.b );
1147    },
1148
1149    darken: function(percent) {
1150       var hsb  = this.asHSB();
1151       this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, Math.max(hsb.b - percent,0));
1152    },
1153
1154    brighten: function(percent) {
1155       var hsb  = this.asHSB();
1156       this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, Math.min(hsb.b + percent,1));
1157    },
1158
1159    blend: function(other) {
1160       this.rgb.r = Math.floor((this.rgb.r + other.rgb.r)/2);
1161       this.rgb.g = Math.floor((this.rgb.g + other.rgb.g)/2);
1162       this.rgb.b = Math.floor((this.rgb.b + other.rgb.b)/2);
1163    },
1164
1165    isBright: function() {
1166       var hsb = this.asHSB();
1167       return this.asHSB().b > 0.5;
1168    },
1169
1170    isDark: function() {
1171       return ! this.isBright();
1172    },
1173
1174    asRGB: function() {
1175       return "rgb(" + this.rgb.r + "," + this.rgb.g + "," + this.rgb.b + ")";
1176    },
1177
1178    asHex: function() {
1179       return "#" + Rico.toColorPart(this.rgb.r) + Rico.toColorPart(this.rgb.g) + Rico.toColorPart(this.rgb.b);
1180    },
1181
1182    asHSB: function() {
1183       return Rico.Color.RGBtoHSB(this.rgb.r, this.rgb.g, this.rgb.b);
1184    },
1185
1186    toString: function() {
1187       return this.asHex();
1188    }
1189
1190 };
1191
1192 /**
1193  * Factory method for creating a color from an RGB string
1194  * @param hexCode a 3 or 6 digit hex string, optionally preceded by a # symbol
1195  * @returns a Rico.Color object
1196  */
1197 Rico.Color.createFromHex = function(hexCode) {
1198   if(hexCode.length==4) {
1199     var shortHexCode = hexCode;
1200     hexCode = '#';
1201     for(var i=1;i<4;i++)
1202       hexCode += (shortHexCode.charAt(i) + shortHexCode.charAt(i));
1203   }
1204   if ( hexCode.indexOf('#') == 0 )
1205     hexCode = hexCode.substring(1);
1206   if (!hexCode.match(/^[0-9A-Fa-f]{6}$/)) return null;
1207   var red   = hexCode.substring(0,2);
1208   var green = hexCode.substring(2,4);
1209   var blue  = hexCode.substring(4,6);
1210   return new Rico.Color( parseInt(red,16), parseInt(green,16), parseInt(blue,16) );
1211 };
1212
1213 /**
1214  * Retrieves the background color of an HTML element
1215  * @param elem the DOM element whose background color should be retreived
1216  * @returns a Rico.Color object
1217  */
1218 Rico.Color.createColorFromBackground = function(elem) {
1219
1220    if (!elem.style) return new Rico.Color(255,255,255);
1221    var actualColor = Rico.getStyle(elem, "background-color");
1222
1223    // if color is tranparent, check parent
1224    // Safari returns "rgba(0, 0, 0, 0)", which means transparent
1225    if ( actualColor.match(/^(transparent|rgba\(0,\s*0,\s*0,\s*0\))$/i) && elem.parentNode )
1226       return Rico.Color.createColorFromBackground(elem.parentNode);
1227
1228    if (actualColor == null) return new Rico.Color(255,255,255);
1229
1230    if ( actualColor.indexOf("rgb(") == 0 ) {
1231       var colors = actualColor.substring(4, actualColor.length - 1 );
1232       var colorArray = colors.split(",");
1233       return new Rico.Color( parseInt( colorArray[0],10 ),
1234                              parseInt( colorArray[1],10 ),
1235                              parseInt( colorArray[2],10 )  );
1236
1237    }
1238    else if ( actualColor.indexOf("#") == 0 ) {
1239       return Rico.Color.createFromHex(actualColor);
1240    }
1241    else
1242       return new Rico.Color(255,255,255);
1243 };
1244
1245 /**
1246  * Converts hue/saturation/brightness to RGB
1247  * @returns a 3-element object: r=red, g=green, b=blue.
1248  */
1249 Rico.Color.HSBtoRGB = function(hue, saturation, brightness) {
1250
1251   var red   = 0;
1252   var green = 0;
1253   var blue  = 0;
1254
1255   if (saturation == 0) {
1256      red = parseInt(brightness * 255.0 + 0.5,10);
1257      green = red;
1258      blue = red;
1259   }
1260   else {
1261       var h = (hue - Math.floor(hue)) * 6.0;
1262       var f = h - Math.floor(h);
1263       var p = brightness * (1.0 - saturation);
1264       var q = brightness * (1.0 - saturation * f);
1265       var t = brightness * (1.0 - (saturation * (1.0 - f)));
1266
1267       switch (parseInt(h,10)) {
1268          case 0:
1269             red   = (brightness * 255.0 + 0.5);
1270             green = (t * 255.0 + 0.5);
1271             blue  = (p * 255.0 + 0.5);
1272             break;
1273          case 1:
1274             red   = (q * 255.0 + 0.5);
1275             green = (brightness * 255.0 + 0.5);
1276             blue  = (p * 255.0 + 0.5);
1277             break;
1278          case 2:
1279             red   = (p * 255.0 + 0.5);
1280             green = (brightness * 255.0 + 0.5);
1281             blue  = (t * 255.0 + 0.5);
1282             break;
1283          case 3:
1284             red   = (p * 255.0 + 0.5);
1285             green = (q * 255.0 + 0.5);
1286             blue  = (brightness * 255.0 + 0.5);
1287             break;
1288          case 4:
1289             red   = (t * 255.0 + 0.5);
1290             green = (p * 255.0 + 0.5);
1291             blue  = (brightness * 255.0 + 0.5);
1292             break;
1293           case 5:
1294             red   = (brightness * 255.0 + 0.5);
1295             green = (p * 255.0 + 0.5);
1296             blue  = (q * 255.0 + 0.5);
1297             break;
1298       }
1299   }
1300
1301    return { r : parseInt(red,10), g : parseInt(green,10) , b : parseInt(blue,10) };
1302 };
1303
1304 /**
1305  * Converts RGB value to hue/saturation/brightness
1306  * @param r integer (0-255)
1307  * @param g integer (0-255)
1308  * @param b integer (0-255)
1309  * @returns a 3-element object: h=hue, s=saturation, b=brightness.
1310  * (unlike some HSB documentation which states hue should be a value 0-360, this routine returns hue values from 0 to 1.0)
1311  */
1312 Rico.Color.RGBtoHSB = function(r, g, b) {
1313
1314    var hue;
1315    var saturation;
1316    var brightness;
1317
1318    var cmax = (r > g) ? r : g;
1319    if (b > cmax)
1320       cmax = b;
1321
1322    var cmin = (r < g) ? r : g;
1323    if (b < cmin)
1324       cmin = b;
1325
1326    brightness = cmax / 255.0;
1327    if (cmax != 0)
1328       saturation = (cmax - cmin)/cmax;
1329    else
1330       saturation = 0;
1331
1332    if (saturation == 0)
1333       hue = 0;
1334    else {
1335       var redc   = (cmax - r)/(cmax - cmin);
1336       var greenc = (cmax - g)/(cmax - cmin);
1337       var bluec  = (cmax - b)/(cmax - cmin);
1338
1339       if (r == cmax)
1340          hue = bluec - greenc;
1341       else if (g == cmax)
1342          hue = 2.0 + redc - bluec;
1343       else
1344          hue = 4.0 + greenc - redc;
1345
1346       hue = hue / 6.0;
1347       if (hue < 0)
1348          hue = hue + 1.0;
1349    }
1350
1351    return { h : hue, s : saturation, b : brightness };
1352 };
1353
1354 /**
1355  * Returns a new XML document object
1356  */
1357 Rico.createXmlDocument = function() {
1358   if (document.implementation && document.implementation.createDocument) {
1359     var doc = document.implementation.createDocument("", "", null);
1360     // some older versions of Moz did not support the readyState property
1361     // and the onreadystate event so we patch it!
1362     if (doc.readyState == null) {
1363       doc.readyState = 1;
1364       doc.addEventListener("load", function () {
1365         doc.readyState = 4;
1366         if (typeof doc.onreadystatechange == "function") {
1367           doc.onreadystatechange();
1368         }
1369       }, false);
1370     }
1371     return doc;
1372   }
1373
1374   if (window.ActiveXObject)
1375       return Rico.tryFunctions(
1376         function() { return new ActiveXObject('MSXML2.DomDocument');   },
1377         function() { return new ActiveXObject('Microsoft.DomDocument');},
1378         function() { return new ActiveXObject('MSXML.DomDocument');    },
1379         function() { return new ActiveXObject('MSXML3.DomDocument');   }
1380       ) || false;
1381   return null;
1382 }