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