ced18d069febc681cada48ea6c2c852b98661c4f
[infodrom/rico3] / minsrc / ricoGridCommon.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 if(typeof Rico=='undefined') throw("GridCommon requires the Rico JavaScript framework");
17
18 /**
19  * Define methods that are common to both SimpleGrid and LiveGrid
20  */
21 Rico.GridCommon = {
22
23   baseInit: function() {
24     this.options = {
25       saveColumnInfo   : {width:true, filter:false, sort:false},  // save info in cookies?
26       cookiePrefix     : 'RicoGrid.',
27       allowColResize   : true,      // allow user to resize columns
28       windowResize     : true,      // Resize grid on window.resize event? Set to false when embedded in an accordian.
29       click            : null,
30       dblclick         : null,
31       contextmenu      : null,
32       menuEvent        : null,      // event that triggers menus - click, dblclick, contextmenu, or none (no menus)
33       defaultWidth     : -1,        // if -1, then use unformatted column width
34       scrollBarWidth   : 19,        // this is the value used in positioning calculations, it does not actually change the width of the scrollbar
35       minScrollWidth   : 100,       // min scroll area width when width of frozen columns exceeds window width
36       frozenColumns    : 0,
37       exportWindow     : "height=400,width=500,scrollbars=1,menubar=1,resizable=1,location=0,toolbar=0,status=0",
38       exportStyleList  : ['background-color','color','text-align','font-weight','font-size','font-family'],
39       exportImgTags    : false,       // applies to grid header and to SimpleGrid cells (not LiveGrid cells)
40       exportFormFields : true,
41       FilterLocation   : null,        // heading row number to place filters. -1=add a new heading row.
42       FilterAllToken   : '___ALL___', // select box value to use to indicate ALL
43       columnSpecs      : []
44     };
45     this.hdrCells=[];
46     this.headerColCnt=0;
47     this.headerRowIdx=0;       // row in header which gets resizers (no colspan's in this row)
48     this.tabs=new Array(2);
49     this.thead=new Array(2);
50     this.tbody=new Array(2);
51   },
52
53   attachMenuEvents: function() {
54     var i;
55     if (!this.options.menuEvent || this.options.menuEvent=='none') return;
56     this.hideScroll=navigator.userAgent.match(/Macintosh\b.*\b(Firefox|Camino)\b/i) || (Rico.isOpera && parseFloat(window.opera.version())<9.5);
57     this.options[this.options.menuEvent]=Rico.eventHandle(this,'handleMenuClick');
58     if (this.highlightDiv) {
59       switch (this.options.highlightElem) {
60         case 'cursorRow':
61           this.attachMenu(this.highlightDiv[0]);
62           break;
63         case 'cursorCell':
64           for (i=0; i<2; i++) {
65             this.attachMenu(this.highlightDiv[i]);
66           }
67           break;
68       }
69     }
70     for (i=0; i<2; i++) {
71       this.attachMenu(this.tbody[i]);
72     }
73   },
74
75   attachMenu: function(elem) {
76     if (this.options.click)
77       Rico.eventBind(elem, 'click', this.options.click, false);
78     if (this.options.dblclick) {
79       if (Rico.isWebKit || Rico.isOpera)
80         Rico.eventBind(elem, 'click', Rico.eventHandle(this,'handleDblClick'), false);
81       else
82         Rico.eventBind(elem, 'dblclick', this.options.dblclick, false);
83     }
84     if (this.options.contextmenu) {
85       if (Rico.isOpera || Rico.isKonqueror)
86         Rico.eventBind(elem, 'click', Rico.eventHandle(this,'handleContextMenu'), false);
87       else
88         Rico.eventBind(elem, 'contextmenu', this.options.contextmenu, false);
89     }
90   },
91
92 /**
93  * implement double-click for browsers that don't support a double-click event (e.g. Safari)
94  */
95   handleDblClick: function(e) {
96     var elem=Rico.eventElement(e);
97     if (this.dblClickElem == elem) {
98       this.options.dblclick(e);
99     } else {
100       this.dblClickElem = elem;
101       this.safariTimer=Rico.runLater(300,this,'clearDblClick');
102     }
103   },
104
105   clearDblClick: function() {
106     this.dblClickElem=null;
107   },
108
109 /**
110  * implement right-click for browsers that don't support contextmenu event (e.g. Opera, Konqueror)
111  * use control-click instead
112  */
113   handleContextMenu: function(e) {
114     var b;
115     if( typeof( e.which ) == 'number' )
116       b = e.which; //Netscape compatible
117     else if( typeof( e.button ) == 'number' )
118       b = e.button; //DOM
119     else
120       return;
121     if (b==1 && e.ctrlKey) {
122       this.options.contextmenu(e);
123     }
124   },
125
126   cancelMenu: function() {
127     if (this.menu) this.menu.cancelmenu();
128   },
129
130 /**
131  * gather info from original headings
132  */
133   getColumnInfo: function(hdrSrc) {
134     Rico.log('getColumnInfo: len='+hdrSrc.length);
135     if (hdrSrc.length == 0) return 0;
136     this.headerRowCnt=hdrSrc.length;
137     var r,c,colcnt;
138     for (r=0; r<this.headerRowCnt; r++) {
139       var headerRow = hdrSrc[r];
140       var headerCells=headerRow.cells;
141       if (r >= this.hdrCells.length) this.hdrCells[r]=[];
142       for (c=0; c<headerCells.length; c++) {
143         var obj={};
144         obj.cell=headerCells[c];
145         obj.colSpan=headerCells[c].colSpan || 1;  // Safari & Konqueror return default colspan of 0
146         if (this.options.defaultWidth < 0) obj.initWidth=headerCells[c].offsetWidth;
147         this.hdrCells[r].push(obj);
148       }
149       if (headerRow.id.slice(-5)=='_main') {
150         colcnt=this.hdrCells[r].length;
151         this.headerRowIdx=r;
152       }
153     }
154     if (!colcnt) {
155       this.headerRowIdx=this.headerRowCnt-1;
156       colcnt=this.hdrCells[this.headerRowIdx].length;
157     }
158     Rico.log("getColumnInfo: colcnt="+colcnt);
159     return colcnt;
160   },
161
162   addHeadingRow: function(className) {
163     var r=this.headerRowCnt++;
164     this.hdrCells[r]=[];
165     for( var h=0; h < 2; h++ ) {
166       var row = this.thead[h].insertRow(-1);
167       var newClass='ricoLG_hdg '+this.tableId+'_hdg'+r;
168       if (className) newClass+=' '+className;
169       row.className=newClass;
170       var limit= h==0 ? this.options.frozenColumns : this.headerColCnt-this.options.frozenColumns;
171       for( var c=0; c < limit; c++ ) {
172         var hdrCell=row.insertCell(-1);
173         var colDiv=Rico.wrapChildren(hdrCell,'ricoLG_col');
174         Rico.wrapChildren(colDiv,'ricoLG_cell');
175         this.hdrCells[r].push({cell:hdrCell,colSpan:1});
176       }
177     }
178     return r;
179   },
180   
181 /**
182  * create column array
183  */
184   createColumnArray: function(columnType) {
185     this.direction=Rico.getStyle(this.outerDiv,'direction').toLowerCase();  // ltr or rtl
186     this.align=this.direction=='rtl' ? ['right','left'] : ['left','right'];
187     Rico.log('createColumnArray: dir='+this.direction);
188     this.columns = [];
189     for (var c=0; c < this.headerColCnt; c++) {
190       Rico.log("createColumnArray: c="+c);
191       var tabidx=c<this.options.frozenColumns ? 0 : 1;
192       var col=new Rico[columnType](this, c, this.hdrCells[this.headerRowIdx][c], tabidx);
193       this.columns.push(col);
194       if (c > 0) this.columns[c-1].next=col;
195     }
196     this.getCookie();
197     Rico.runLater(100,this,'insertResizers');  // avoids peek-a-boo bug in column 1 in IE6/7
198   },
199
200 /**
201  * Insert resizing handles
202  */
203   insertResizers: function() {
204     if (!this.options.allowColResize) return;
205     for (var x=0;x<this.columns.length;x++) {
206       this.columns[x].insertResizer();
207     }
208   },
209
210 /**
211  * Create div structure
212  */
213   createDivs: function() {
214     Rico.log("createDivs start");
215     this.outerDiv = this.createDiv("outer");
216     if (Rico.theme.gridContainer) Rico.addClass(this.outerDiv,Rico.theme.gridContainer);
217     if (this.outerDiv.firstChild && this.outerDiv.firstChild.tagName && this.outerDiv.firstChild.tagName.toUpperCase()=='TABLE') {
218       this.structTab=this.outerDiv.firstChild;
219       this.structTabLeft=this.structTab.rows[0].cells[0];
220       this.structTabUR=this.structTab.rows[0].cells[1];
221       this.structTabLR=this.structTab.rows[1].cells[0];
222     } else {
223       this.structTab = document.createElement("table");
224       this.structTab.border=0;
225       this.structTab.cellPadding=0;
226       this.structTab.cellSpacing=0;
227       var tr1=this.structTab.insertRow(-1);
228       tr1.vAlign='top';
229       this.structTabLeft=tr1.insertCell(-1);
230       this.structTabLeft.rowSpan=2;
231       this.structTabLeft.style.padding='0px';
232       this.structTabLeft.style.border='none';
233       var tr2=this.structTab.insertRow(-1);
234       tr2.vAlign='top';
235       this.structTabUR=tr1.insertCell(-1);
236       this.structTabUR.style.padding='0px';
237       this.structTabUR.style.border='none';
238       this.structTabLR=tr2.insertCell(-1);
239       this.structTabLR.style.padding='0px';
240       this.structTabLR.style.border='none';
241       this.outerDiv.appendChild(this.structTab);
242     }
243     Rico.addClass(this.structTab,'ricoLG_StructTab');
244     //this.structTabLR.style.overflow='hidden';
245     //if (Rico.isOpera) this.outerDiv.style.overflow="hidden";
246     this.frozenTabs = this.createDiv("frozenTabs",this.structTabLeft);
247     this.innerDiv   = this.createDiv("inner",this.structTabUR);
248     this.scrollDiv  = this.createDiv("scroll",this.structTabLR);
249     this.resizeDiv  = this.createDiv("resize",this.outerDiv,true);
250
251     this.messagePopup=new Rico.Popup();
252     this.messagePopup.createContainer({hideOnEscape:false, hideOnClick:false, parent:this.outerDiv});
253     this.messagePopup.content.className='ricoLG_messageDiv';
254     if (Rico.theme.gridMessage) Rico.addClass(this.messagePopup.content,Rico.theme.gridMessage);
255
256     this.keywordPopup=new Rico.Window('', {zIndex:-1, parent:this.outerDiv});
257     Rico.addClass(this.keywordPopup.container, 'ricoLG_keywordDiv');
258     var instructions=this.keywordPopup.contentDiv.appendChild(document.createElement("p"));
259     instructions.innerHTML=Rico.getPhraseById("keywordPrompt");
260     this.keywordBox=this.keywordPopup.contentDiv.appendChild(document.createElement("input"));
261     this.keywordBox.size=20;
262     Rico.eventBind(this.keywordBox,"keypress", Rico.eventHandle(this,'keywordKey'), false);
263     this.keywordPopup.contentDiv.appendChild(Rico.floatButton('Checkmark', Rico.eventHandle(this,'processKeyword')));
264     var s=this.keywordPopup.contentDiv.appendChild(document.createElement("p"));
265     Rico.setStyle(s,{clear:'both'});
266
267     //this.frozenTabs.style[this.align[0]]='0px';
268     //this.innerDiv.style[this.align[0]]='0px';
269     Rico.log("createDivs end");
270   },
271   
272   keywordKey: function(e) {
273     switch (Rico.eventKey(e)) {
274       case 27: this.closeKeyword(); Rico.eventStop(e); return false;
275       case 13: this.processKeyword(); Rico.eventStop(e); return false;
276     }
277     return true;
278   },
279   
280   openKeyword: function(colnum) {
281     this.keywordCol=colnum;
282     this.keywordBox.value='';
283     this.keywordPopup.setTitle(this.columns[colnum].displayName);
284     this.keywordPopup.centerPopup();
285     this.keywordBox.focus();
286   },
287   
288   closeKeyword: function() {
289     this.keywordPopup.closePopup();
290     this.cancelMenu();
291   },
292   
293   processKeyword: function() {
294     var keyword=this.keywordBox.value;
295     this.closeKeyword();
296     this.columns[this.keywordCol].setFilterKW(keyword);
297   },
298
299 /**
300  * Create a div and give it a standardized id and class name.
301  * If the div already exists, then just assign the class name.
302  */
303   createDiv: function(elemName,elemParent,hidden) {
304     var id=this.tableId+"_"+elemName+"Div";
305     var newdiv=document.getElementById(id);
306     if (!newdiv) {
307       newdiv = document.createElement("div");
308       newdiv.id = id;
309       if (elemParent) elemParent.appendChild(newdiv);
310     }
311     newdiv.className = "ricoLG_"+elemName+"Div";
312     if (hidden) Rico.hide(newdiv);
313     return newdiv;
314   },
315
316 /**
317  * Common code used to size & position divs in both SimpleGrid & LiveGrid
318  */
319   baseSizeDivs: function() {
320     this.setOtherHdrCellWidths();
321
322     if (this.options.frozenColumns) {
323       Rico.show(this.tabs[0]);
324       Rico.show(this.frozenTabs);
325       // order of next 3 lines is critical in IE6
326       this.hdrHt=Math.max(Rico.nan2zero(this.thead[0].offsetHeight),this.thead[1].offsetHeight);
327       this.dataHt=Math.max(Rico.nan2zero(this.tbody[0].offsetHeight),this.tbody[1].offsetHeight);
328       this.frzWi=this.borderWidth(this.tabs[0]);
329     } else {
330       Rico.hide(this.tabs[0]);
331       Rico.hide(this.frozenTabs);
332       this.frzWi=0;
333       this.hdrHt=this.thead[1].offsetHeight;
334       this.dataHt=this.tbody[1].offsetHeight;
335     }
336
337     var wiLimit,i;
338     var borderWi=this.borderWidth(this.columns[0].dataCell);
339     Rico.log('baseSizeDivs '+this.tableId+': hdrHt='+this.hdrHt+' dataHt='+this.dataHt);
340     Rico.log(this.tableId+' frzWi='+this.frzWi+' borderWi='+borderWi);
341     for (i=0; i<this.options.frozenColumns; i++) {
342       if (this.columns[i].visible) this.frzWi+=parseInt(this.columns[i].colWidth,10)+borderWi;
343     }
344     this.scrTabWi=this.borderWidth(this.tabs[1]);
345     this.scrTabWi0=this.scrTabWi;
346     Rico.log('scrTabWi: '+this.scrTabWi);
347     for (i=this.options.frozenColumns; i<this.columns.length; i++) {
348       if (this.columns[i].visible) this.scrTabWi+=parseInt(this.columns[i].colWidth,10)+borderWi;
349     }
350     this.scrWi=this.scrTabWi+this.options.scrollBarWidth;
351     if (this.sizeTo=='parent') {
352       if (Rico.isIE) Rico.hide(this.outerDiv);
353       wiLimit=this.outerDiv.parentNode.offsetWidth;
354       if (Rico.isIE) Rico.show(this.outerDiv);
355     }  else {
356       wiLimit=Rico.windowWidth()-this.options.scrollBarWidth-8;
357     }
358     if (this.outerDiv.parentNode.clientWidth > 0)
359       wiLimit=Math.min(this.outerDiv.parentNode.clientWidth, wiLimit);
360     var overage=this.frzWi+this.scrWi-wiLimit;
361     Rico.log('baseSizeDivs '+this.tableId+': scrWi='+this.scrWi+' wiLimit='+wiLimit+' overage='+overage+' clientWidth='+this.outerDiv.parentNode.clientWidth);
362     if (overage > 0 && this.options.frozenColumns < this.columns.length)
363       this.scrWi=Math.max(this.scrWi-overage, this.options.minScrollWidth);
364     this.scrollDiv.style.width=this.scrWi+'px';
365     //this.scrollDiv.style.top=this.hdrHt+'px';
366     //this.frozenTabs.style.width=this.scrollDiv.style[this.align[0]]=this.innerDiv.style[this.align[0]]=this.frzWi+'px';
367     this.frozenTabs.style.width=this.frzWi+'px';
368     this.outerDiv.style.width=(this.frzWi+this.scrWi)+'px';
369   },
370
371 /**
372  * Returns the sum of the left & right border widths of an element
373  */
374   borderWidth: function(elem) {
375     var l=Rico.nan2zero(Rico.getStyle(elem,'borderLeftWidth'));
376     var r=Rico.nan2zero(Rico.getStyle(elem,'borderRightWidth'));
377     Rico.log((elem.id || elem.tagName)+' borderWidth: L='+l+', R='+r);
378     return l + r;
379 //    return Rico.nan2zero(Rico.getStyle(elem,'borderLeftWidth')) + Rico.nan2zero(Rico.getStyle(elem,'borderRightWidth'));
380   },
381
382   setOtherHdrCellWidths: function() {
383     var c,i,j,r,w,hdrcell,cell,origSpan,newSpan,divs;
384     for (r=0; r<this.hdrCells.length; r++) {
385       if (r==this.headerRowIdx) continue;
386       Rico.log('setOtherHdrCellWidths: r='+r);
387       c=i=0;
388       while (i<this.headerColCnt && c<this.hdrCells[r].length) {
389         hdrcell=this.hdrCells[r][c];
390         cell=hdrcell.cell;
391         origSpan=newSpan=hdrcell.colSpan;
392         for (w=j=0; j<origSpan; j++, i++) {
393           if (this.columns[i].hdrCell.style.display=='none')
394             newSpan--;
395           else if (this.columns[i].hdrColDiv.style.display!='none')
396             w+=parseInt(this.columns[i].colWidth,10);
397         }
398         if (!hdrcell.hdrColDiv || !hdrcell.hdrCellDiv) {
399           divs=cell.getElementsByTagName('div');
400           hdrcell.hdrColDiv=(divs.length<1) ? Rico.wrapChildren(cell,'ricoLG_col') : divs[0];
401           hdrcell.hdrCellDiv=(divs.length<2) ? Rico.wrapChildren(hdrcell.hdrColDiv,'ricoLG_cell') : divs[1];
402         }
403         if (newSpan==0) {
404           cell.style.display='none';
405         } else if (w==0) {
406           hdrcell.hdrColDiv.style.display='none';
407           cell.colSpan=newSpan;
408         } else {
409           cell.style.display='';
410           hdrcell.hdrColDiv.style.display='';
411           cell.colSpan=newSpan;
412           hdrcell.hdrColDiv.style.width=w+'px';
413         }
414         c++;
415       }
416     }
417   },
418
419   initFilterImage: function(filterRowNum){
420     this.filterAnchor=document.getElementById(this.tableId+'_filterLink');
421     if (!this.filterAnchor) return;
422     this.filterRows=Rico.select('tr.'+this.tableId+'_hdg'+filterRowNum);
423     if (this.filterRows.length!=2) return;
424     for (var i=0, r=[]; i<2; i++) r[i]=Rico.select('.ricoLG_cell',this.filterRows[i]);
425     this.filterElements=r[0].concat(r[1]);
426     this.saveHeight = this.filterElements[0].offsetHeight;
427     var pt=Rico.getStyle(this.filterElements[0],'paddingTop');
428     var pb=Rico.getStyle(this.filterElements[0],'paddingBottom');
429     if (pt) this.saveHeight-=parseInt(pt,10);
430     if (pb) this.saveHeight-=parseInt(pb,10);
431     this.rowNum = filterRowNum;
432     this.setFilterImage(false);
433     //Rico.eventBind(this.filterAnchor, 'click', Rico.eventHandle(this,'toggleFilterRow'), false);
434   },
435
436   toggleFilterRow: function() {
437     if ( Rico.visible(this.filterRows[0]) )
438       this.slideFilterUp();
439     else
440       this.slideFilterDown();
441   },
442
443   setFilterImage: function(expandFlag) {
444     var altText=Rico.getPhraseById((expandFlag ? 'show' : 'hide')+'FilterRow');
445     this.filterAnchor.innerHTML = '<img src="'+Rico.imgDir+'tableFilter'+(expandFlag ? 'Expand' : 'Collapse')+'.gif" alt="'+altText+'" border="0">';
446   },
447
448 /**
449  * Returns a div for the cell at the specified row and column index.
450  * In SimpleGrid, r can refer to any row in the grid.
451  * In LiveGrid, r refers to a visible row (row 0 is the first visible row).
452  */
453   cell: function(r,c) {
454     return (0<=c && c<this.columns.length && r>=0) ? this.columns[c].cell(r) : null;
455   },
456
457 /**
458  * Returns the screen height available for a grid
459  */
460   availHt: function() {
461     var divPos=Rico.cumulativeOffset(this.outerDiv);
462     return Rico.windowHeight()-divPos.top-2*this.options.scrollBarWidth-15;  // allow for scrollbar and some margin
463   },
464
465   setHorizontalScroll: function() {
466     var newLeft=(-this.scrollDiv.scrollLeft)+'px';
467     this.hdrTabs[1].style.marginLeft=newLeft;
468   },
469
470   pluginScroll: function() {
471      if (this.scrollPluggedIn) return;
472      Rico.eventBind(this.scrollDiv,"scroll",this.scrollEventFunc, false);
473      this.scrollPluggedIn=true;
474   },
475
476   unplugScroll: function() {
477      Rico.eventUnbind(this.scrollDiv,"scroll", this.scrollEventFunc , false);
478      this.scrollPluggedIn=false;
479   },
480
481   hideMsg: function() {
482     this.messagePopup.closePopup();
483   },
484
485   showMsg: function(msg) {
486     this.messagePopup.setContent(msg);
487     this.messagePopup.centerPopup();
488     Rico.log("showMsg: "+msg);
489   },
490
491 /**
492  * @return array of column objects which have invisible status
493  */
494   listInvisible: function(attr) {
495     var hiddenColumns=[];
496     for (var x=0;x<this.columns.length;x++) {
497       if (!this.columns[x].visible)
498         hiddenColumns.push(attr ? this.columns[x][attr] : this.columns[x]);
499     }
500     return hiddenColumns;
501   },
502
503 /**
504  * @return index of left-most visibile column, or -1 if there are no visible columns
505  */
506   firstVisible: function() {
507     for (var x=0;x<this.columns.length;x++) {
508       if (this.columns[x].visible) return x;
509     }
510     return -1;
511   },
512
513 /**
514  * Show all columns
515  */
516   showAll: function() {
517     var invisible=this.listInvisible();
518     for (var x=0;x<invisible.length;x++)
519       invisible[x].showColumn();
520   },
521   
522   chooseColumns: function() {
523     this.menu.cancelmenu();
524     var x,z,col,itemDiv,span,contentDiv;\r
525     if (!this.columnChooser) {
526       Rico.log('creating columnChooser');
527       z=Rico.getStyle(this.outerDiv.offsetParent,'zIndex');
528       if (typeof z!='number') z=0;
529       this.columnChooser=new Rico.Window(Rico.getPhraseById('gridChooseCols'), {zIndex:z+2, parent:this.outerDiv});
530       Rico.addClass(this.columnChooser.container, 'ricoLG_chooserDiv');
531       contentDiv=this.columnChooser.contentDiv;
532       for (x=0;x<this.columns.length;x++) {
533         col=this.columns[x];
534         itemDiv=contentDiv.appendChild(document.createElement('div'));
535         col.ChooserBox=Rico.createFormField(itemDiv,'input','checkbox');
536         span=itemDiv.appendChild(document.createElement('span'));
537         span.innerHTML=col.displayName;
538         Rico.eventBind(col.ChooserBox, 'click', Rico.eventHandle(col,'chooseColumn'), false);
539       }
540     }
541     Rico.log('opening columnChooser');
542     this.columnChooser.openPopup(1,this.hdrHt);
543     for (x=0;x<this.columns.length;x++) {
544       this.columns[x].ChooserBox.checked=this.columns[x].visible;
545       this.columns[x].ChooserBox.disabled = !this.columns[x].canHideShow();
546     }
547   },
548
549   blankRow: function(r) {
550     for (var c=0; c < this.columns.length; c++) {
551       this.columns[c].clearCell(r);
552     }
553   },
554   
555   getExportStyles: function(chkelem) {
556     var exportStyles=this.options.exportStyleList;
557     var bgImg=Rico.getStyle(chkelem,'backgroundImage');
558     if (!bgImg || bgImg=='none') return exportStyles;
559     for (var styles=[],i=0; i<exportStyles.length; i++)
560       if (exportStyles[i]!='background-color' && exportStyles[i]!='color') styles.push(exportStyles[i]);
561     return styles;
562   },
563
564 /**
565  * Support function for printVisible()
566  */
567   exportStart: function() {
568     var r,c,i,j,hdrcell,newSpan,divs,cell;
569     var exportStyles=this.getExportStyles(this.thead[0]);
570     //alert(exportStyles.join('\n'));
571     this.exportRows=[];
572     this.exportText="<html><head></head><body><table border='1' cellspacing='0'>";\r
573     for (c=0; c<this.columns.length; c++) {\r
574       if (this.columns[c].visible) this.exportText+="<col width='"+parseInt(this.columns[c].colWidth,10)+"'>";
575     }\r
576     this.exportText+="<thead style='display: table-header-group;'>";
577     if (this.exportHeader) this.exportText+=this.exportHeader;
578     for (r=0; r<this.hdrCells.length; r++) {
579       if (this.hdrCells[r].length==0 || !Rico.visible(this.hdrCells[r][0].cell.parentNode)) continue;
580       this.exportText+="<tr>";
581       for (c=0,i=0; c<this.hdrCells[r].length; c++) {
582         hdrcell=this.hdrCells[r][c];
583         newSpan=hdrcell.colSpan;
584         for (j=0; j<hdrcell.colSpan; j++, i++) {
585           if (!this.columns[i].visible) newSpan--;
586         }
587         if (newSpan > 0) {
588           divs=Rico.select('.ricoLG_cell',hdrcell.cell);
589           cell=divs && divs.length>0 ? divs[0] : hdrcell.cell;
590           this.exportText+="<td style='"+this.exportStyle(cell,exportStyles)+"'";
591           if (hdrcell.colSpan > 1) this.exportText+=" colspan='"+newSpan+"'";
592           this.exportText+=">"+Rico.getInnerText(cell,!this.options.exportImgTags, !this.options.exportFormFields, 'NoExport')+"</td>";
593         }
594       }
595       this.exportText+="</tr>";
596     }
597     this.exportText+="</thead><tbody>";
598   },
599
600 /**
601  * Support function for printVisible().
602  */
603   exportFinish: function() {
604     if (this.hideMsg) this.hideMsg();
605     window.status=Rico.getPhraseById('exportComplete');
606     if (this.exportRows.length > 0) this.exportText+='<tr>'+this.exportRows.join('</tr><tr>')+'</tr>';
607     if (this.exportFooter) this.exportText+=this.exportFooter;
608     this.exportText+="</tbody></table></body></html>";
609     if (this.cancelMenu) this.cancelMenu();
610     var w=window.open('','_blank',this.options.exportWindow);
611     if (w == null) {
612       alert(Rico.getPhraseById('disableBlocker'));
613     } else {
614       w.document.open();
615       w.document.write(this.exportText);
616       w.document.close();
617     }
618     this.exportText=undefined;
619     this.exportRows=undefined;
620   },
621
622 /**
623  * Support function for printVisible()
624  */
625   exportStyle: function(elem,styleList) {
626     for (var i=0,s=''; i < styleList.length; i++) {
627       try {
628         var curstyle=Rico.getStyle(elem,styleList[i]);
629         if (curstyle) s+=styleList[i]+':'+curstyle+';';
630       } catch(e) {};
631     }
632     return s;
633   },
634
635 /**
636  * Gets the value of the grid cookie and interprets the contents.
637  * All information for a particular grid is stored in a single cookie.
638  * This may include column widths, column hide/show status, current sort, and any column filters.
639  */
640   getCookie: function() {
641     var c=Rico.getCookie(this.options.cookiePrefix+this.tableId);
642     if (!c) return;
643     var cookieVals=c.split(',');
644     for (var i=0; i<cookieVals.length; i++) {
645       var v=cookieVals[i].split(':');
646       if (v.length!=2) continue;
647       var colnum=parseInt(v[0].slice(1),10);
648       if (colnum < 0 || colnum >= this.columns.length) continue;
649       var col=this.columns[colnum];
650       switch (v[0].charAt(0)) {
651         case 'w':
652           col.setColWidth(v[1]);
653           col.customWidth=true;
654           break;
655         case 'h':
656           if (v[1].toLowerCase()=='true')
657             col.hideshow(true,true);
658           else
659             col.hideshow(false,true);
660           break;
661         case 's':
662           if (!this.options.saveColumnInfo.sort || !col.sortable) break;
663           col.setSorted(v[1]);
664           break;
665         case 'f':
666           if (!this.options.saveColumnInfo.filter || !col.filterable) break;
667           var filterTemp=v[1].split('~');
668           col.filterOp=filterTemp.shift();
669           col.filterValues = [];
670           col.filterType = Rico.ColumnConst.USERFILTER;
671           for (var j=0; j<filterTemp.length; j++)
672             col.filterValues.push(unescape(filterTemp[j]));
673           break;
674       }
675     }
676   },
677
678 /**
679  * Sets the grid cookie.
680  * All information for a particular grid is stored in a single cookie.
681  * This may include column widths, column hide/show status, current sort, and any column filters.
682  */
683   setCookie: function() {
684     var cookieVals=[];
685     for (var i=0; i<this.columns.length; i++) {
686       var col=this.columns[i];
687       if (this.options.saveColumnInfo.width) {
688         if (col.customWidth) cookieVals.push('w'+i+':'+col.colWidth);
689         if (col.customVisible) cookieVals.push('h'+i+':'+col.visible);
690       }
691       if (this.options.saveColumnInfo.sort) {
692         if (col.currentSort != Rico.ColumnConst.UNSORTED)
693           cookieVals.push('s'+i+':'+col.currentSort);
694       }
695       if (this.options.saveColumnInfo.filter && col.filterType == Rico.ColumnConst.USERFILTER) {
696         var filterTemp=[col.filterOp];
697         for (var j=0; j<col.filterValues.length; j++)
698           filterTemp.push(escape(col.filterValues[j]));
699         cookieVals.push('f'+i+':'+filterTemp.join('~'));
700       }
701     }
702     Rico.setCookie(this.options.cookiePrefix+this.tableId, cookieVals.join(','), this.options.cookieDays, this.options.cookiePath, this.options.cookieDomain);
703   }
704
705 };
706
707
708 Rico.ColumnConst = {
709   UNFILTERED:   0,
710   SYSTEMFILTER: 1,
711   USERFILTER:   2,
712
713   UNSORTED:  0,
714   SORT_ASC:  "ASC",
715   SORT_DESC: "DESC",
716
717   MINWIDTH: 10
718 }
719
720
721 /**
722  * @class Define methods that are common to columns in both SimpleGrid and LiveGrid
723  */
724 Rico.TableColumnBase = function() {};
725
726 Rico.TableColumnBase.prototype = {
727
728 /**
729  * Common code used to initialize the column in both SimpleGrid & LiveGrid
730  */
731   baseInit: function(liveGrid,colIdx,hdrInfo,tabIdx) {
732     Rico.log("TableColumnBase.init index="+colIdx+" tabIdx="+tabIdx);
733     this.liveGrid  = liveGrid;
734     this.index     = colIdx;
735     this.hideWidth = Rico.isKonqueror || Rico.isWebKit || liveGrid.headerRowCnt>1 ? 5 : 2;  // column width used for "hidden" columns. Anything less than 5 causes problems with Konqueror. Best to keep this greater than padding used inside cell.
736     this.options   = liveGrid.options;
737     this.tabIdx    = tabIdx;
738     this.hdrCell   = hdrInfo.cell;
739     this.body = document.getElementsByTagName("body")[0];
740     this.displayName  = this.getDisplayName(this.hdrCell);
741     var divs=this.hdrCell.getElementsByTagName('div');
742     this.hdrColDiv=(divs.length<1) ? Rico.wrapChildren(this.hdrCell,'ricoLG_col') : divs[0];
743     this.hdrCellDiv=(divs.length<2) ? Rico.wrapChildren(this.hdrColDiv,'ricoLG_cell') : divs[1];
744     var sectionIndex= tabIdx==0 ? colIdx : colIdx-liveGrid.options.frozenColumns;
745     this.dataCell = liveGrid.tbody[tabIdx].rows[0].cells[sectionIndex];
746     divs=this.dataCell.getElementsByTagName('div');
747     this.dataColDiv=(divs.length<1) ? Rico.wrapChildren(this.dataCell,'ricoLG_col') : divs[0];
748
749     this.mouseDownHandler= Rico.eventHandle(this,'handleMouseDown');
750     this.mouseMoveHandler= Rico.eventHandle(this,'handleMouseMove');
751     this.mouseUpHandler  = Rico.eventHandle(this,'handleMouseUp');
752     this.mouseOutHandler = Rico.eventHandle(this,'handleMouseOut');
753
754     this.fieldName = 'col'+this.index;
755     this.format={type:"text"};
756     var spec = liveGrid.options.columnSpecs[colIdx];
757     if (typeof spec == 'object') Rico.extend(this.format, spec);
758     Rico.addClass(this.dataColDiv, this.colClassName());
759     this.visible=true;
760     if (typeof this.format.visible=='boolean') this.visible=this.format.visible;
761     Rico.log("TableColumn.init index="+colIdx+" fieldName="+this.fieldName);
762     this.sortable     = typeof this.format.canSort=='boolean' ? this.format.canSort : liveGrid.options.canSortDefault;
763     this.currentSort  = Rico.ColumnConst.UNSORTED;
764     this.filterable   = typeof this.format.canFilter=='boolean' ? this.format.canFilter : liveGrid.options.canFilterDefault;
765     this.filterType   = Rico.ColumnConst.UNFILTERED;
766     this.hideable     = typeof this.format.canHide=='boolean' ? this.format.canHide : liveGrid.options.canHideDefault;
767
768     var wi;
769     switch (typeof this.format.width) {
770       case 'number': wi=this.format.width; break;
771       case 'string': wi=parseInt(this.format.width,10); break;
772       default:       wi=hdrInfo.initWidth; break;
773     }
774     wi=(typeof(wi)=='number') ? Math.max(wi,Rico.ColumnConst.MINWIDTH) : liveGrid.options.defaultWidth;
775     this.setColWidth(wi);
776     if (!this.visible) this.setDisplay('none');
777   },
778   
779   colClassName: function() {
780     return this.format.ClassName ? this.format.ClassName : this.liveGrid.tableId+'_col'+this.index;
781   },
782
783   insertResizer: function() {
784     //this.hdrCell.style.width='';
785     if (this.format.noResize) return;
786     var resizer=document.createElement('div');
787     resizer.className='ricoLG_Resize';
788     resizer.style[this.liveGrid.align[1]]='0px';
789     this.hdrCellDiv.appendChild(resizer);
790     Rico.eventBind(resizer,"mousedown", this.mouseDownHandler, false);
791   },
792
793 /**
794  * get the display name of a column
795  */
796   getDisplayName: function(el) {
797     var anchors=el.getElementsByTagName("A");
798     //Check the existance of A tags
799     if (anchors.length > 0)
800       return anchors[0].innerHTML;
801     else
802       return Rico.stripTags(el.innerHTML);
803   },
804
805   _clear: function(gridCell) {
806     gridCell.innerHTML='&nbsp;';
807   },
808
809   clearCell: function(rowIndex) {
810     var gridCell=this.cell(rowIndex);
811     this._clear(gridCell,rowIndex);
812     if (this.liveGrid.buffer && this.liveGrid.buffer.options.acceptStyle) gridCell.style.cssText='';
813   },
814
815   dataTable: function() {
816     return this.liveGrid.tabs[this.tabIdx];
817   },
818
819   numRows: function() {
820     return this.dataColDiv.childNodes.length;
821   },
822
823   clearColumn: function() {
824     var childCnt=this.numRows();
825     for (var r=0; r<childCnt; r++)
826       this.clearCell(r);
827   },
828
829   cell: function(r) {
830     return this.dataColDiv.childNodes[r];
831   },
832
833   getFormattedValue: function(r,xImg,xForm,xClass) {
834     return Rico.getInnerText(this.cell(r),xImg,xForm,xClass);
835   },
836
837   setColWidth: function(wi) {
838     if (typeof wi=='number') {
839       wi=parseInt(wi,10);
840       if (wi < Rico.ColumnConst.MINWIDTH) return;
841       wi=wi+'px';
842     }
843     Rico.log('setColWidth '+this.index+': '+wi);
844     this.colWidth=wi;
845     this.hdrColDiv.style.width=wi;
846     this.dataColDiv.style.width=wi;
847   },
848
849   pluginMouseEvents: function() {
850     if (this.mousePluggedIn==true) return;
851     Rico.eventBind(this.body,"mousemove", this.mouseMoveHandler, false);
852     Rico.eventBind(this.body,"mouseup",   this.mouseUpHandler  , false);
853     Rico.eventBind(this.body,"mouseout",  this.mouseOutHandler , false);
854     this.mousePluggedIn=true;
855   },
856
857   unplugMouseEvents: function() {
858     Rico.eventUnbind(this.body,"mousemove", this.mouseMoveHandler, false);
859     Rico.eventUnbind(this.body,"mouseup",   this.mouseUpHandler  , false);
860     Rico.eventUnbind(this.body,"mouseout",  this.mouseOutHandler , false);
861     this.mousePluggedIn=false;
862   },
863
864   handleMouseDown: function(e) {
865     this.resizeStart=Rico.eventClient(e).x;
866     this.origWidth=parseInt(this.colWidth,10);
867     var p=Rico.positionedOffset(this.hdrCell);
868     if (this.liveGrid.direction=='rtl') {
869       this.edge=p.left+this.liveGrid.options.scrollBarWidth;
870       switch (this.tabIdx) {
871         case 0: this.edge+=this.liveGrid.innerDiv.offsetWidth; break;
872         case 1: this.edge-=this.liveGrid.scrollDiv.scrollLeft; break;
873       }
874     } else {
875       this.edge=p.left+this.hdrCell.offsetWidth;
876       if (this.tabIdx>0) this.edge+=Rico.nan2zero(this.liveGrid.tabs[0].offsetWidth);
877     }
878     this.liveGrid.resizeDiv.style.left=this.edge+"px";
879     this.liveGrid.resizeDiv.style.display="";
880     this.liveGrid.outerDiv.style.cursor='e-resize';
881     this.tmpHighlight=this.liveGrid.highlightEnabled;
882     this.liveGrid.highlightEnabled=false;
883     this.pluginMouseEvents();
884     Rico.eventStop(e);
885   },
886
887   handleMouseMove: function(e) {
888     var delta=Rico.eventClient(e).x-this.resizeStart;
889     var newWidth=(this.liveGrid.direction=='rtl') ? this.origWidth-delta : this.origWidth+delta;
890     if (newWidth < Rico.ColumnConst.MINWIDTH) return;
891     this.liveGrid.resizeDiv.style.left=(this.edge+delta)+"px";
892     this.colWidth=newWidth;
893     Rico.eventStop(e);
894   },
895
896   handleMouseUp: function(e) {
897     this.unplugMouseEvents();
898     Rico.log('handleMouseUp '+this.liveGrid.tableId);
899     this.liveGrid.outerDiv.style.cursor='';
900     this.liveGrid.resizeDiv.style.display="none";
901     this.setColWidth(this.colWidth);
902     this.customWidth=true;
903     this.liveGrid.setCookie();
904     this.liveGrid.highlightEnabled=this.tmpHighlight;
905     this.liveGrid.sizeDivs();
906     Rico.eventStop(e);
907   },
908
909   handleMouseOut: function(e) {
910     var reltg = Rico.eventRelatedTarget(e) || e.toElement;
911     while (reltg != null && reltg.nodeName.toLowerCase() != 'body')
912       reltg=reltg.parentNode;
913     if (reltg!=null && reltg.nodeName.toLowerCase() == 'body') return true;
914     this.handleMouseUp(e);
915     return true;
916   },
917
918   setDisplay: function(d) {
919     this.hdrCell.style.display=d;
920     this.hdrColDiv.style.display=d;
921     this.dataCell.style.display=d;
922     this.dataColDiv.style.display=d;
923   },
924   
925   hideshow: function(visible,noresize) {
926     this.setDisplay(visible ? '' : 'none');
927     this.liveGrid.cancelMenu();
928     this.visible=visible;
929     this.customVisible=true;
930     if (noresize) return;
931     this.liveGrid.setCookie();
932     this.liveGrid.sizeDivs();
933   },
934
935   hideColumn: function() {
936     Rico.log('hideColumn '+this.liveGrid.tableId);
937     this.hideshow(false,false);
938   },
939
940   showColumn: function() {
941     Rico.log('showColumn '+this.liveGrid.tableId);
942     this.hideshow(true,false);
943   },
944
945   chooseColumn: function(e) {
946     var elem=Rico.eventElement(e);
947     this.hideshow(elem.checked,false);
948   },
949
950   setImage: function() {
951     if ( this.currentSort == Rico.ColumnConst.SORT_ASC ) {
952        this.imgSort.style.display='inline-block';
953        this.imgSort.className=Rico.theme.sortAsc || 'rico-icon ricoLG_sortAsc';
954     } else if ( this.currentSort == Rico.ColumnConst.SORT_DESC ) {
955        this.imgSort.style.display='inline-block';
956        this.imgSort.className=Rico.theme.sortDesc || 'rico-icon ricoLG_sortDesc';
957     } else {
958        this.imgSort.style.display='none';
959     }
960     if (this.filterType == Rico.ColumnConst.USERFILTER) {
961        this.imgFilter.style.display='inline-block';
962        this.imgFilter.title=this.getFilterText();
963     } else {
964        this.imgFilter.style.display='none';
965     }
966   },
967
968   canHideShow: function() {
969     return this.hideable;
970   }
971
972 };