Fix caret in filter specs
[infodrom/rico3] / minsrc / ricoLiveGrid.js
1 /*
2  *  (c) 2005-2011 Richard Cowin (http://openrico.org)
3  *  (c) 2005-2011 Matt Brown (http://dowdybrown.com)
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
6  *  file except in compliance with the License. You may obtain a copy of the License at
7  *
8  *         http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software distributed under the
11  *  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
12  *  either express or implied. See the License for the specific language governing permissions
13  *  and limitations under the License.
14  */
15
16 /** @namespace */
17 if (!Rico.Buffer) Rico.Buffer = {};
18
19 Rico.Buffer.Base = function(dataTable, options) {
20   this.initialize(dataTable, options);
21 }
22 /** @lends Rico.Buffer.Base# */
23 Rico.Buffer.Base.prototype = {
24 /**
25  * @class Defines the static buffer class (no AJAX).
26  * Loads buffer with data that already exists in the document as an HTML table or passed via javascript.
27  * Also serves as a base class for AJAX-enabled buffers.
28  * @constructs
29  */
30   initialize: function(dataTable, options) {
31     this.clear();
32     this.updateInProgress = false;
33     this.lastOffset = 0;
34     this.rcvdRowCount = false;  // true if an eof element was included in the last response
35     this.foundRowCount = false; // true if a response is ever received with eof true
36     this.totalRows = 0;
37     this.rowcntContent = "";
38     this.rcvdOffset = -1;
39     this.options = {
40       fixedHdrRows     : 0,
41       canFilter        : true,  // does buffer object support filtering?
42       isEncoded        : true,  // is the data received via ajax html encoded?
43       acceptStyle      : false, // copy style from original/ajax data?
44       canRefresh       : false  // should "refresh" be shown on filter menu?
45     };
46     Rico.extend(this.options, options || {});
47     if (dataTable) {
48       this.loadRowsFromTable(dataTable,this.options.fixedHdrRows);
49       dataTable.parentNode.removeChild(dataTable);  // delete the data once it has been loaded
50     }
51   },
52
53   registerGrid: function(liveGrid) {
54     this.liveGrid = liveGrid;
55   },
56
57   setTotalRows: function( newTotalRows ) {
58     if (typeof(newTotalRows)!='number') newTotalRows=this.size;
59     if (this.totalRows == newTotalRows) return;
60     this.totalRows = newTotalRows;
61     if (!this.liveGrid) return;
62     Rico.log("setTotalRows, newTotalRows="+newTotalRows);
63     switch (this.liveGrid.sizeTo) {
64       case 'data':
65         this.liveGrid.resizeWindow();
66         break;
67       case 'datamax':
68         this.liveGrid.setPageSize(newTotalRows);
69         break;
70       default:
71         this.liveGrid.updateHeightDiv();
72         break;
73     }
74   },
75
76   loadRowsFromTable: function(tableElement,firstRow) {
77     var newRows = [];
78     var trs = tableElement.getElementsByTagName("tr");
79     for ( var i=firstRow || 0; i < trs.length; i++ ) {
80       var row = [];
81       var cells = trs[i].getElementsByTagName("td");
82       for ( var j=0; j < cells.length ; j++ )
83         row[j]=cells[j].innerHTML;
84       newRows.push( row );
85     }
86     this.loadRows(newRows);
87   },
88
89   loadRowsFromArray: function(array2D) {
90     for ( var i=0; i < array2D.length; i++ ) {
91       for ( var j=0; j < array2D[i].length ; j++ ) {
92         array2D[i][j]=array2D[i][j].toString();
93       }
94     }
95     this.loadRows(array2D);
96   },
97
98   loadRows: function(jstable) {
99     this.baseRows = jstable;
100     this.startPos = 0;
101     this.size = this.baseRows.length;
102   },
103
104   dom2jstable: function(rowsElement) {
105     Rico.log('dom2jstable: encoded='+this.options.isEncoded);
106     var newRows = [];
107     var trs = rowsElement.getElementsByTagName("tr");
108     for ( var i=0; i < trs.length; i++ ) {
109       var row = [];
110       var cells = trs[i].getElementsByTagName("td");
111       for ( var j=0; j < cells.length ; j++ )
112         row[j]=Rico.getContentAsString(cells[j],this.options.isEncoded);
113       newRows.push( row );
114     }
115     return newRows;
116   },
117
118   _blankRow: function() {
119     var newRow=[];
120     for (var i=0; i<this.liveGrid.columns.length; i++) {
121       newRow[i]='';
122     }
123     return newRow;
124   },
125
126   deleteRows: function(rowIndex,cnt) {
127     this.baseRows.splice(rowIndex,typeof(cnt)=='number' ? cnt : 1);
128     this.liveGrid.isPartialBlank=true;
129     this.size=this.baseRows.length;
130   },
131
132   insertRow: function(beforeRowIndex) {
133     var r=this._blankRow();
134     this.baseRows.splice(beforeRowIndex,0,r);
135     this.size=this.baseRows.length;
136     this.liveGrid.isPartialBlank=true;
137     if (this.startPos < 0) this.startPos=0;
138     return r;
139   },
140
141   appendRows: function(cnt) {
142     var newRows=[];
143     for (var i=0; i<cnt; i++) {
144       var r=this._blankRow();
145       this.baseRows.push(r);
146       newRows.push(r);
147     }
148     this.size=this.baseRows.length;
149     this.liveGrid.isPartialBlank=true;
150     if (this.startPos < 0) this.startPos=0;
151     return newRows;
152   },
153   
154   sortFunc: function(coltype) {
155     var self=this;
156     switch (coltype) {
157       case 'number': return function(a,b) { return self._sortNumeric(a,b); };
158       case 'control':return function(a,b) { return self._sortControl(a,b); };
159       default:       return function(a,b) { return self._sortAlpha(a,b); };
160     }
161   },
162
163   sortBuffer: function(colnum) {
164     if (!this.baseRows) {
165       this.delayedSortCol=colnum;
166       return;
167     }
168     this.liveGrid.showMsg(Rico.getPhraseById("sorting"));
169     this.sortColumn=colnum;
170     var col=this.liveGrid.columns[colnum];
171     this.getValFunc=col._sortfunc;
172     this.baseRows.sort(this.sortFunc(col.format.type));
173     if (col.getSortDirection()=='DESC') this.baseRows.reverse();
174   },
175   
176   _sortAlpha: function(a,b) {
177     var aa = this.sortColumn<a.length ? Rico.getInnerText(a[this.sortColumn]) : '';
178     var bb = this.sortColumn<b.length ? Rico.getInnerText(b[this.sortColumn]) : '';
179     if (aa==bb) return 0;
180     if (aa<bb) return -1;
181     return 1;
182   },
183
184   _sortNumeric: function(a,b) {
185     var aa = this.sortColumn<a.length ? this.nan2zero(Rico.getInnerText(a[this.sortColumn])) : 0;
186     var bb = this.sortColumn<b.length ? this.nan2zero(Rico.getInnerText(b[this.sortColumn])) : 0;
187     return aa-bb;
188   },
189
190   nan2zero: function(n) {
191     if (typeof(n)=='string') n=parseFloat(n);
192     return isNaN(n) || typeof(n)=='undefined' ? 0 : n;
193   },
194   
195   _sortControl: function(a,b) {
196     var aa = this.sortColumn<a.length ? Rico.getInnerText(a[this.sortColumn]) : '';
197     var bb = this.sortColumn<b.length ? Rico.getInnerText(b[this.sortColumn]) : '';
198     if (this.getValFunc) {
199       aa=this.getValFunc(aa);
200       bb=this.getValFunc(bb);
201     }
202     if (aa==bb) return 0;
203     if (aa<bb) return -1;
204     return 1;
205   },
206
207   clear: function() {
208     this.baseRows = [];
209     this.rows = [];
210     this.modified = [];
211     this.attr = null;
212     this.startPos = -1;
213     this.size = 0;
214     this.windowPos = 0;
215   },
216
217   isInRange: function(position) {
218     var lastRow=Math.min(this.totalRows, position + this.liveGrid.pageSize);
219     return (position >= this.startPos) && (lastRow <= this.endPos()); // && (this.size != 0);
220   },
221
222   endPos: function() {
223     return this.startPos + this.rows.length;
224   },
225
226   fetch: function(offset) {
227     Rico.log('fetch '+this.liveGrid.tableId+': offset='+offset);
228     this.applyFilters();
229     this.setTotalRows();
230     this.rcvdRowCount = true;
231     this.foundRowCount = true;
232     if (offset < 0) offset=0;
233     this.liveGrid.refreshContents(offset);
234     return;
235   },
236
237 /**
238  * @return a 2D array of buffer data representing the rows that are currently visible on the grid
239  */
240   visibleRows: function() {
241     return this.rows.slice(this.windowStart,this.windowEnd);
242   },
243
244   setWindow: function(startrow, endrow) {
245     this.windowStart = startrow - this.startPos;  // position in the buffer of first visible row
246     Rico.log('setWindow '+this.liveGrid.tableId+': '+startrow+', '+endrow+', newstart='+this.windowStart);
247     this.windowEnd = Math.min(endrow,this.size);  // position in the buffer of last visible row containing data+1
248     this.windowPos = startrow;                    // position in the dataset of first visible row
249   },
250
251 /**
252  * @return true if bufRow is currently visible in the grid
253  */
254   isVisible: function(bufRow) {
255     return bufRow < this.rows.length && bufRow >= this.windowStart && bufRow < this.windowEnd;
256   },
257   
258 /**
259  * takes a window row index and returns the corresponding buffer row index
260  */
261   bufferRow: function(windowRow) {
262     return this.windowStart+windowRow;
263   },
264
265 /**
266  * @return buffer cell at the specified visible row/col index
267  */
268   getWindowCell: function(windowRow,col) {
269     var bufrow=this.bufferRow(windowRow);
270     return this.isVisible(bufrow) && col < this.rows[bufrow].length ? this.rows[bufrow][col] : null;
271   },
272
273   getWindowStyle: function(windowRow,col) {
274     var bufrow=this.bufferRow(windowRow);
275     return this.attr && this.isVisible(bufrow) && this.attr[bufrow] && col < this.attr[bufrow].length ? this.attr[bufrow][col] : '';
276   },
277
278   getWindowValue: function(windowRow,col) {
279     return this.getWindowCell(windowRow,col);
280   },
281
282   setWindowValue: function(windowRow,col,newval) {
283     var bufrow=this.bufferRow(windowRow);
284     if (bufrow >= this.windowEnd) return false;
285     return this.setValue(bufrow,col,newval);
286   },
287
288   getCell: function(bufRow,col) {
289     return bufRow < this.size ? this.rows[bufRow][col] : null;
290   },
291
292   getValue: function(bufRow,col) {
293     return this.getCell(bufRow,col);
294   },
295
296   setValue: function(bufRow,col,newval,newstyle) {
297     if (bufRow>=this.size) return false;
298     if (!this.rows[bufRow][col]) this.rows[bufRow][col]={};
299     this.rows[bufRow][col]=newval;
300     if (this.options.acceptStyle && typeof newstyle=='string') {
301       if (!this.attr) this.attr=[];
302       if (!this.attr[bufRow]) this.attr[bufRow]=[];
303       this.attr[bufRow][col]=newstyle;
304     }
305     if (!this.modified[bufRow]) this.modified[bufRow]=[];
306     this.modified[bufRow][col]=true;
307     return true;
308   },
309
310   getRows: function(start, count) {
311     var begPos = start - this.startPos;
312     var endPos = Math.min(begPos + count,this.size);
313     var results = [];
314     for ( var i=begPos; i < endPos; i++ ) {
315       results.push(this.rows[i]);
316     }
317     return results;
318   },
319
320   applyFilters: function() {
321     var newRows=[],re=[];
322     var r,c,n,i,showRow,filtercnt;
323     var cols=this.liveGrid.columns;
324     for (n=0,filtercnt=0; n<cols.length; n++) {
325       c=cols[n];
326       if (c.filterType == Rico.ColumnConst.UNFILTERED) continue;
327       filtercnt++;
328       if (c.filterOp=='LIKE') re[n]=new RegExp(c.filterValues[0],'i');
329     }
330     Rico.log('applyFilters: # of filters='+filtercnt);
331     if (filtercnt==0) {
332       this.rows = this.baseRows;
333     } else {
334       for (r=0; r<this.baseRows.length; r++) {
335         showRow=true;
336         for (n=0; n<cols.length && showRow; n++) {
337           c=cols[n];
338           if (c.filterType == Rico.ColumnConst.UNFILTERED) continue;
339           switch (c.filterOp) {
340             case 'LIKE':
341               showRow=re[n].test(this.baseRows[r][n]);
342               break;
343             case 'EQ':
344               showRow=this.baseRows[r][n]==c.filterValues[0];
345               break;
346             case 'NE':
347               for (i=0; i<c.filterValues.length && showRow; i++)
348                 showRow=this.baseRows[r][n]!=c.filterValues[i];
349               break;
350             case 'LE':
351               if (c.format.type=='number')
352                 showRow=this.nan2zero(this.baseRows[r][n])<=this.nan2zero(c.filterValues[0]);
353               else
354                 showRow=this.baseRows[r][n]<=c.filterValues[0];
355               break;
356             case 'GE':
357               if (c.format.type=='number')
358                 showRow=this.nan2zero(this.baseRows[r][n])>=this.nan2zero(c.filterValues[0]);
359               else
360                 showRow=this.baseRows[r][n]>=c.filterValues[0];
361               break;
362             case 'NULL':
363               showRow=this.baseRows[r][n]=='';
364               break;
365             case 'NOTNULL':
366               showRow=this.baseRows[r][n]!='';
367               break;
368           }
369         }
370         if (showRow) newRows.push(this.baseRows[r]);
371       }
372       this.rows = newRows;
373     }
374     this.rowcntContent = this.size = this.rows.length;
375   },
376
377   printAll: function() {
378     this.liveGrid.showMsg(Rico.getPhraseById('exportInProgress'));
379     Rico.runLater(10,this,'_printAll');  // allow message to paint
380   },
381
382 /**
383  * Support function for printAll()
384  */
385   _printAll: function() {
386     this.liveGrid.exportStart();
387     this.exportBuffer(this.getRows(0,this.totalRows));
388     this.liveGrid.exportFinish();
389   },
390
391 /**
392  * Copies visible rows to a new window as a simple html table.
393  */
394   printVisible: function() {
395     this.liveGrid.showMsg(Rico.getPhraseById('exportInProgress'));
396     Rico.runLater(10,this,'_printVisible');  // allow message to paint
397   },
398
399   _printVisible: function() {
400     this.liveGrid.exportStart();
401     this.exportBuffer(this.visibleRows());
402     this.liveGrid.exportFinish();
403   },
404
405 /**
406  * Send all rows to print/export window
407  */
408   exportBuffer: function(rows,startPos) {
409     var r,c,v,col,exportText;
410     Rico.log("exportBuffer: "+rows.length+" rows");
411     var exportStyles=this.liveGrid.getExportStyles(this.liveGrid.tbody[0]);
412     var tdstyle=[];
413     var totalcnt=startPos || 0;
414     var cols=this.liveGrid.columns;
415     for (c=0; c<cols.length; c++) {
416       if (cols[c].visible) tdstyle[c]=this.liveGrid.exportStyle(cols[c].cell(0),exportStyles);  // assumes row 0 style applies to all rows
417     }
418     for(r=0; r < rows.length; r++) {
419       exportText='';
420       for (c=0; c<cols.length; c++) {
421         if (!cols[c].visible) continue;
422         col=cols[c];
423         col.expStyle=tdstyle[c];
424         v=col._export(rows[r][c],rows[r]);
425         if (v=='') v='&nbsp;';
426         exportText+="<td style='"+col.expStyle+"'>"+v+"</td>";
427       }
428       this.liveGrid.exportRows.push(exportText);
429       totalcnt++;
430       if (totalcnt % 10 == 0) window.status=Rico.getPhraseById('exportStatus',totalcnt);
431     }
432   }
433
434 };
435
436
437 // Rico.LiveGrid -----------------------------------------------------
438
439 Rico.LiveGrid = function(tableId, buffer, options) {
440   this.initialize(tableId, buffer, options);
441 }
442
443 /** 
444  * @lends Rico.LiveGrid#
445  * @property tableId id string for this grid
446  * @property options the options object passed to the constructor extended with defaults
447  * @property buffer the buffer object containing the data for this grid
448  * @property columns array of {@link Rico.LiveGridColumn} objects
449  */
450 Rico.LiveGrid.prototype = {
451 /**
452  * @class Buffered LiveGrid component
453  * @extends Rico.GridCommon
454  * @constructs
455  */
456   initialize: function( tableId, buffer, options ) {
457     Rico.extend(this, Rico.GridCommon);
458     Rico.extend(this, Rico.LiveGridMethods);
459     this.baseInit();
460     this.tableId = tableId;
461     this.buffer = buffer;
462     this.actionId='_action_'+tableId;
463     Rico.setDebugArea(tableId+"_debugmsgs");    // if used, this should be a textarea
464
465     Rico.extend(this.options, {
466       visibleRows      : -3,    // -1 or 'window'=size grid to client window; -2 or 'data'=size grid to min(window,data); -3 or 'body'=size so body does not have a scrollbar; -4 or 'parent'=size to parent element (e.g. if grid is inside a div)
467       frozenColumns    : 0,
468       offset           : 0,     // first row to be displayed
469       prefetchBuffer   : true,  // load table on page load?
470       minPageRows      : 2,
471       maxPageRows      : 50,
472       canSortDefault   : true,  // can be overridden in the column specs
473       canFilterDefault : buffer.options.canFilter, // can be overridden in the column specs
474       canHideDefault   : true,  // can be overridden in the column specs
475
476       // highlight & selection parameters
477       highlightElem    : 'none',// what gets highlighted/selected (cursorRow, cursorCell, menuRow, menuCell, selection, or none)
478       highlightSection : 3,     // which section gets highlighted (frozen=1, scrolling=2, all=3, none=0)
479       highlightMethod  : 'class', // outline, class, both (outline is less CPU intensive on the client)
480       highlightClass   : Rico.theme.gridHighlightClass || 'ricoLG_selection',
481
482       // export/print parameters
483       maxPrint         : 5000,  // max # of rows that can be printed/exported, 0=disable print/export feature
484
485       // heading parameters
486       headingSort      : 'link', // link: make headings a link that will sort column, hover: make headings a hoverset, none: events on headings are disabled
487       hdrIconsFirst    : true    // true: put sort & filter icons before header text, false: after
488     });
489     // other options:
490     //   sortCol: initial sort column
491
492     var self=this;
493     this.options.sortHandler = function() { self.sortHandler(); };
494     this.options.filterHandler = function() { self.filterHandler(); };
495     this.options.onRefreshComplete = function(firstrow,lastrow) { self.bookmarkHandler(firstrow,lastrow); };
496     this.options.rowOverHandler = Rico.eventHandle(this,'rowMouseOver');
497     this.options.mouseDownHandler = Rico.eventHandle(this,'selectMouseDown');
498     this.options.mouseOverHandler = Rico.eventHandle(this,'selectMouseOver');
499     this.options.mouseUpHandler  = Rico.eventHandle(this,'selectMouseUp');
500     Rico.extend(this.options, options || {});
501
502     switch (typeof this.options.visibleRows) {
503       case 'string':
504         this.sizeTo=this.options.visibleRows;
505         switch (this.options.visibleRows) {
506           case 'data':   this.options.visibleRows=-2; break;
507           case 'body':   this.options.visibleRows=-3; break;
508           case 'parent': this.options.visibleRows=-4; break;
509           case 'datamax':this.options.visibleRows=-5; break;
510           default:       this.options.visibleRows=-1; break;
511         }
512         break;
513       case 'number':
514         switch (this.options.visibleRows) {
515           case -1: this.sizeTo='window'; break;
516           case -2: this.sizeTo='data'; break;
517           case -3: this.sizeTo='body'; break;
518           case -4: this.sizeTo='parent'; break;
519           case -5: this.sizeTo='datamax'; break;
520           default: this.sizeTo='fixed'; break;
521         }
522         break;
523       default:
524         this.sizeTo='body';
525         this.options.visibleRows=-3;
526         break;
527     }
528     this.highlightEnabled=this.options.highlightSection>0;
529     this.pageSize=0;
530     this.createTables();
531     if (this.headerColCnt==0) {
532       alert('ERROR: no columns found in "'+this.tableId+'"');
533       return;
534     }
535     this.createColumnArray('LiveGridColumn');
536     if (this.options.headingSort=='hover')
537       this.createHoverSet();
538
539     this.bookmark=document.getElementById(this.tableId+"_bookmark");
540     this.sizeDivs();
541     var filterUIrow=-1;
542     if (this.buffer.options.canFilter && this.options.AutoFilter)
543       filterUIrow=this.addHeadingRow('ricoLG_FilterRow');
544     this.createDataCells(this.options.visibleRows);
545     if (this.pageSize == 0) return;
546     this.buffer.registerGrid(this);
547     if (this.buffer.setBufferSize) this.buffer.setBufferSize(this.pageSize);
548     this.scrollTimeout = null;
549     this.lastScrollPos = 0;
550     this.attachMenuEvents();
551
552     this.setSortUI( this.options.sortCol, this.options.sortDir );
553     this.setImages();
554     if (this.listInvisible().length==this.columns.length)
555       this.columns[0].showColumn();
556     this.sizeDivs();
557     this.scrollDiv.style.display="";
558     if (this.buffer.totalRows>0)
559       this.updateHeightDiv();
560     if (this.options.prefetchBuffer) {
561       if (this.bookmark) this.bookmark.innerHTML = Rico.getPhraseById('bookmarkLoading');
562       if (this.options.canFilterDefault && this.options.getQueryParms)
563         this.checkForFilterParms();
564       this.scrollToRow(this.options.offset);
565       this.buffer.fetch(this.options.offset);
566     }
567     if (filterUIrow >= 0)
568       this.createFilters(filterUIrow);
569     this.scrollEventFunc=Rico.eventHandle(this,'handleScroll');
570     this.wheelEventFunc=Rico.eventHandle(this,'handleWheel');
571     this.wheelEvent=(Rico.isIE || Rico.isOpera || Rico.isWebKit) ? 'mousewheel' : 'DOMMouseScroll';
572     if (this.options.offset && this.options.offset < this.buffer.totalRows)
573       Rico.runLater(50,this,'scrollToRow',this.options.offset);  // Safari requires a delay
574     this.pluginScroll();
575     this.setHorizontalScroll();
576     Rico.log("setHorizontalScroll done");
577     if (this.options.windowResize)
578       Rico.runLater(100,this,'pluginWindowResize');
579     Rico.log("initialize complete for "+this.tableId);
580     //alert('clientLeft='+this.scrollDiv.clientLeft);
581     if (this.direction=='rtl' && (!Rico.isWebKit || this.scrollDiv.clientLeft > 0)) {
582       this.scrollTab.style.right='0px';
583     } else {
584       this.scrollTab.style.left='0px';
585       Rico.setStyle(this.tabs[1], {'float': 'left'});
586     }
587   }
588 };
589
590
591 Rico.LiveGridMethods = {
592 /** @lends Rico.LiveGrid# */
593
594   createHoverSet: function() {
595     var hdrs=[];
596     for( var c=0; c < this.headerColCnt; c++ ) {
597       if (this.columns[c].sortable) {\r
598         hdrs.push(this.columns[c].hdrCellDiv);
599       }
600     }
601     this.hoverSet = new Rico.HoverSet(hdrs);
602   },
603
604   checkForFilterParms: function() {
605     var s=window.location.search;
606     if (s.charAt(0)=='?') s=s.substring(1);
607     var pairs = s.split('&');
608     for (var i=0; i<pairs.length; i++) {
609       if (pairs[i].match(/^f\[\d+\]/)) {
610         this.buffer.options.requestParameters.push(pairs[i]);
611       }
612     }
613   },
614
615 /**
616  * Refreshes a detail grid from a master grid
617  * @returns row index on master table on success, -1 otherwise
618  */
619   drillDown: function(e,masterColNum,detailColNum) {
620     var cell=Rico.eventElement(e || window.event);
621     cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
622     if (!cell) return -1;
623     var idx=this.winCellIndex(cell);
624     if (idx.row >= this.buffer.totalRows) return -1
625     this.unhighlight();
626     this.menuIdx=idx;  // ensures selection gets cleared when menu is displayed
627     this.highlight(idx);
628     var drillValue=this.buffer.getWindowCell(idx.row,masterColNum);
629     for (var i=3; i<arguments.length; i++)
630       arguments[i].setDetailFilter(detailColNum,drillValue);
631     return idx.row;
632   },
633
634 /**
635  * set filter on a detail grid that is in a master-detail relationship
636  */
637   setDetailFilter: function(colNumber,filterValue) {
638     var c=this.columns[colNumber];
639     c.format.ColData=filterValue;
640     c.setSystemFilter('EQ',filterValue);
641   },
642
643 /**
644  * Create one table for frozen columns and one for scrolling columns.
645  * Also create div's to contain them.
646  * @returns true on success
647  */
648   createTables: function() {
649     var insertloc,hdrSrc,i;
650     var table = document.getElementById(this.tableId) || document.getElementById(this.tableId+'_outerDiv');
651     if (!table) return false;
652     if (table.tagName.toLowerCase()=='table') {
653       var theads=table.getElementsByTagName("thead");
654       if (theads.length == 1) {
655         Rico.log("createTables: using thead section, id="+this.tableId);
656         if (this.options.ColGroupsOnTabHdr && this.options.ColGroups) {
657           var r=theads[0].insertRow(0);
658           this.insertPanelNames(r, 0, this.options.frozenColumns, 'ricoFrozen');
659           this.insertPanelNames(r, this.options.frozenColumns, this.options.columnSpecs.length);
660         }
661         hdrSrc=theads[0].rows;
662       } else {
663         Rico.log("createTables: using tbody section, id="+this.tableId);
664         hdrSrc=new Array(table.rows[0]);
665       }
666       insertloc=table;
667     } else if (this.options.columnSpecs.length > 0) {
668       if (!table.id.match(/_outerDiv$/)) insertloc=table;
669       Rico.log("createTables: inserting at "+table.tagName+", id="+this.tableId);
670     } else {
671       alert("ERROR!\n\nUnable to initialize '"+this.tableId+"'\n\nLiveGrid terminated");
672       return false;
673     }
674
675     this.createDivs();
676     this.scrollContainer = this.createDiv("scrollContainer",this.structTabLR);
677     this.scrollContainer.appendChild(this.scrollDiv); // move scrollDiv
678     this.scrollTab = this.createDiv("scrollTab",this.scrollContainer);
679     this.shadowDiv  = this.createDiv("shadow",this.scrollDiv);
680     this.shadowDiv.style.direction='ltr';  // avoid FF bug
681     this.scrollDiv.style.display="none";
682     this.scrollDiv.scrollTop=0;
683     if (this.options.highlightMethod!='class') {
684       this.highlightDiv=[];
685       switch (this.options.highlightElem) {
686         case 'menuRow':
687         case 'cursorRow':
688           this.highlightDiv[0] = this.createDiv("highlight",this.outerDiv);
689           this.highlightDiv[0].style.display="none";
690           break;
691         case 'menuCell':
692         case 'cursorCell':
693           for (i=0; i<2; i++) {
694             this.highlightDiv[i] = this.createDiv("highlight",i==0 ? this.frozenTabs : this.scrollTab);
695             this.highlightDiv[i].style.display="none";
696             this.highlightDiv[i].id+=i;
697           }
698           break;
699         case 'selection':
700           // create one div for each side of the rectangle
701           var parentDiv=this.options.highlightSection==1 ? this.frozenTabs : this.scrollTab;
702           for (i=0; i<4; i++) {
703             this.highlightDiv[i] = this.createDiv("highlight",parentDiv);
704             this.highlightDiv[i].style.display="none";
705             this.highlightDiv[i].style.overflow="hidden";
706             this.highlightDiv[i].id+=i;
707             this.highlightDiv[i].style[i % 2==0 ? 'height' : 'width']="0px";
708           }
709           break;
710       }
711     }
712
713     // create new tables
714     for (i=0; i<3; i++) {
715       this.tabs[i] = document.createElement("table");
716       this.tabs[i].className = (i < 2) ? 'ricoLG_table' : 'ricoLG_scrollTab';
717       this.tabs[i].border=0;
718       this.tabs[i].cellPadding=0;
719       this.tabs[i].cellSpacing=0;
720       this.tabs[i].id = this.tableId+"_tab"+i;
721     }
722     // set headings
723     for (i=0; i<2; i++) {
724       this.thead[i]=this.tabs[i].createTHead();
725       this.thead[i].className='ricoLG_top';
726       if (Rico.theme.gridheader) Rico.addClass(this.thead[i],Rico.theme.gridheader);
727     }
728     // set bodies
729     for (i=0; i<2; i++) {
730       this.tbody[i]=Rico.getTBody(this.tabs[i==0?0:2]);
731       this.tbody[i].className='ricoLG_bottom';
732       if (Rico.theme.gridcontent) Rico.addClass(this.tbody[i],Rico.theme.gridcontent);
733       this.tbody[i].insertRow(-1);
734     }
735     this.frozenTabs.appendChild(this.tabs[0]);
736     this.innerDiv.appendChild(this.tabs[1]);
737     this.scrollTab.appendChild(this.tabs[2]);
738     if (insertloc) insertloc.parentNode.insertBefore(this.outerDiv,insertloc);
739     if (hdrSrc) {
740       this.headerColCnt = this.getColumnInfo(hdrSrc);
741       this.loadHdrSrc(hdrSrc);
742     } else {
743       this.createHdr(0,0,this.options.frozenColumns);
744       this.createHdr(1,this.options.frozenColumns,this.options.columnSpecs.length);
745       if (this.options.ColGroupsOnTabHdr && this.options.ColGroups) {
746         this.insertPanelNames(this.thead[0].insertRow(0), 0, this.options.frozenColumns);
747         this.insertPanelNames(this.thead[1].insertRow(0), this.options.frozenColumns, this.options.columnSpecs.length);
748       }
749       for (i=0; i<2; i++)
750         this.headerColCnt = this.getColumnInfo(this.thead[i].rows);
751     }
752     for( var c=0; c < this.headerColCnt; c++ )
753       this.tbody[c<this.options.frozenColumns ? 0 : 1].rows[0].insertCell(-1);
754     if (insertloc) table.parentNode.removeChild(table);
755     Rico.log('createTables end');
756     return true;
757   },
758
759   createDataCells: function(visibleRows) {
760     if (visibleRows < 0) {
761       for (var i=0; i<this.options.minPageRows; i++)
762         this.appendBlankRow();
763       this.sizeDivs();
764       this.autoAppendRows(this.remainingHt());
765     } else {
766       for( var r=0; r < visibleRows; r++ )
767         this.appendBlankRow();
768     }
769     var s=this.options.highlightSection;
770     if (s & 1) this.attachHighlightEvents(this.tbody[0]);
771     if (s & 2) this.attachHighlightEvents(this.tbody[1]);
772   },
773
774 /**
775  * @param colnum column number
776  * @return id string for a filter element
777  */
778   filterId: function(colnum) {
779     return 'RicoFilter_'+this.tableId+'_'+colnum;
780   },
781
782 /**
783  * Create filter elements in heading
784  * Reads this.columns[].filterUI to determine type of filter element for each column (t=text box, s=select list, c=custom)
785  * @param r heading row where filter elements will be placed
786  */
787   createFilters: function(r) {
788     for( var c=0; c < this.headerColCnt; c++ ) {
789       var col=this.columns[c];
790       var fmt=col.format;
791       if (typeof fmt.filterUI!='string') continue;
792       var cell=this.hdrCells[r][c].cell;
793       var field,name=this.filterId(c);\r
794       var divs=cell.getElementsByTagName('div');
795       // copy text alignment from data cell
796       var align=Rico.getStyle(this.cell(0,c),'textAlign');
797       divs[1].style.textAlign=align;
798       switch (fmt.filterUI.charAt(0)) {
799         case 't':
800           // text field
801           field=Rico.createFormField(divs[1],'input',Rico.inputtypes.search ? 'search' : 'text',name,'RicoFilter');
802           var size=fmt.filterUI.match(/\d+/);
803           field.maxLength=fmt.Length || 50;\r
804           field.size=size ? parseInt(size,10) : 10;
805           if (field.type != 'search') divs[1].appendChild(Rico.clearButton(Rico.eventHandle(col,'filterClear')));
806           if (col.filterType==Rico.ColumnConst.USERFILTER && col.filterOp=='LIKE') {
807             var v=col.filterValues[0];
808             if (v.charAt(0)=='*') v=v.substr(1);
809             if (v.slice(-1)=='*') v=v.slice(0,-1);
810             field.value=v;
811             col.lastKeyFilter=v;
812           }
813           Rico.eventBind(field,'keyup',Rico.eventHandle(col,'filterKeypress'),false);
814           col.filterField=field;\r
815           break;\r
816         case 'm':
817           // multi-select
818         case 's':
819           // drop-down select
820           field=Rico.createFormField(divs[1],'select',null,name,'RicoFilter');\r
821           Rico.addSelectOption(field,this.options.FilterAllToken,Rico.getPhraseById("filterAll"));\r
822           col.filterField=field;
823           var options={};\r
824           Rico.extend(options, this.buffer.ajaxOptions);
825           var colnum=typeof(fmt.filterCol)=='number' ? fmt.filterCol : c;
826           options.parameters = this.buffer.formQueryHashXML(0,-1);
827           options.parameters.distinct = colnum;
828           options.onComplete = this.filterValuesUpdateFunc(c);
829           new Rico.ajaxRequest(this.buffer.dataSource, options);
830           break;\r
831         case 'n':
832           field=Rico.createFormField(divs[1],'select',null,name,'RicoFilter');
833           Rico.addSelectOption(field,this.options.FilterAllToken,Rico.getPhraseById("filterAll"));
834           col.filterField=field;
835           var choices=fmt.filterUI.length == 1 ? "-0+" : fmt.filterUI.substr(1);
836           if (choices.indexOf("-") >= 0) Rico.addSelectOption(field,"LT0","< 0");
837           if (choices.indexOf("0") >= 0) Rico.addSelectOption(field,"EQ0","= 0");
838           if (choices.indexOf("+") >= 0) Rico.addSelectOption(field,"GT0","> 0");
839           Rico.eventBind(col.filterField,'change',Rico.eventHandle(col,'nFilterChange'));
840           break;
841         case 'c':
842           // custom
843           if (typeof col._createFilters == 'function')
844             col._createFilters(divs[1], name);
845           break;
846       }
847     }
848     this.initFilterImage(r);
849   },
850   
851   filterValuesUpdateFunc: function(colnum) {
852     var self=this;
853     return function (request) { self.filterValuesUpdate(colnum,request); };
854   },
855
856 /**
857  * update select list filter with values in AJAX response
858  * @returns true on success
859  */
860   filterValuesUpdate: function(colnum,request) {
861     var response = request.responseXML.getElementsByTagName("ajax-response");
862     Rico.log("filterValuesUpdate: "+request.status);
863     if (response == null || response.length != 1) return false;
864     response=response[0];
865     var error = response.getElementsByTagName('error');
866     if (error.length > 0) {
867       Rico.log("Data provider returned an error:\n"+Rico.getContentAsString(error[0],this.buffer.isEncoded));
868       alert(Rico.getPhraseById("requestError",Rico.getContentAsString(error[0],this.buffer.isEncoded)));
869       return false;
870     }\r
871     response=response.getElementsByTagName('response')[0];\r
872     var rowsElement = response.getElementsByTagName('rows')[0];\r
873     var col=this.columns[parseInt(colnum,10)];
874     var rows = this.buffer.dom2jstable(rowsElement);\r
875     var c,opt,v;
876     if (col.filterType==Rico.ColumnConst.USERFILTER && col.filterOp=='EQ') v=col.filterValues[0];
877     Rico.log('filterValuesUpdate: col='+colnum+' rows='+rows.length);
878     switch (col.format.filterUI.charAt(0)) {
879       case 'm':
880         // multi-select
881         col.mFilter = document.body.appendChild(document.createElement("div"));
882         col.mFilter.className = 'ricoLG_mFilter'
883         Rico.hide(col.mFilter);
884         var contentDiv = col.mFilter.appendChild(document.createElement("div"));
885         contentDiv.className = 'ricoLG_mFilter_content'
886         var buttonDiv = col.mFilter.appendChild(document.createElement("div"));
887         buttonDiv.className = 'ricoLG_mFilter_button'
888         col.mFilterButton=buttonDiv.appendChild(document.createElement("button"));
889         col.mFilterButton.innerHTML=Rico.getPhraseById("apply");
890         var eventName=Rico.isWebKit ? 'mousedown' : 'click';
891         Rico.eventBind(col.filterField,eventName,Rico.eventHandle(col,'mFilterSelectClick'));
892         Rico.eventBind(col.mFilterButton,'click',Rico.eventHandle(col,'mFilterFinish'));
893         //col.filterField.options[0].text=$('AllLabel').innerHTML;
894         tab = contentDiv.appendChild(document.createElement("table"));
895         tab.border=0;
896         tab.cellPadding=2;
897         tab.cellSpacing=0;
898         //tbody=(tab.tBodies.length==0) ? tab.appendChild(document.createElement("tbody")) : tab.tBodies[0];
899         var baseId=this.filterId(colnum)+'_';
900         this.createMFilterItem(tab,this.options.FilterAllToken,Rico.getPhraseById("filterAll"),baseId+'all',Rico.eventHandle(col,'mFilterAllClick'));
901         var handle=Rico.eventHandle(col,'mFilterOtherClick')
902         for (var i=0; i<rows.length; i++) {
903           if (rows[i].length>0) {
904             c=rows[i][0];
905             this.createMFilterItem(tab,c,c || Rico.getPhraseById("filterBlank"),baseId+i,handle);
906           }
907         }
908         col.mFilterInputs=contentDiv.getElementsByTagName('input');
909         col.mFilterLabels=contentDiv.getElementsByTagName('label');
910         col.mFilterFocus=col.mFilterInputs.length ? col.mFilterInputs[0] : col.mFilterButton;
911         break;
912
913       case 's':
914         // drop-down select
915         for (var i=0; i<rows.length; i++) {
916           if (rows[i].length>0) {
917             c=rows[i][0];
918             opt=Rico.addSelectOption(col.filterField,c,c || Rico.getPhraseById("filterBlank"));
919             if (col.filterType==Rico.ColumnConst.USERFILTER && c==v) opt.selected=true;
920           }
921         }
922         Rico.eventBind(col.filterField,'change',Rico.eventHandle(col,'filterChange'));
923         break;
924     }
925     return true;\r
926   },
927   
928   createMFilterItem: function(table,code,description,id,eventHandle) {
929     var tr=table.insertRow(-1);
930     tr.vAlign='top';
931     if (tr.rowIndex % 2 == 1) tr.className='ricoLG_mFilter_oddrow';
932     var td1=tr.insertCell(-1)
933     var td2=tr.insertCell(-1)
934     var field=Rico.createFormField(td1,'input','checkbox',id);
935     field.value=code;
936     field.checked=true;
937     var label = td2.appendChild(document.createElement("label"));
938     label.htmlFor = id;
939     label.innerHTML=description;
940     Rico.eventBind(field,'click',eventHandle);
941   },
942
943   unplugHighlightEvents: function() {
944     var s=this.options.highlightSection;
945     if (s & 1) this.detachHighlightEvents(this.tbody[0]);
946     if (s & 2) this.detachHighlightEvents(this.tbody[1]);
947   },
948
949 /**
950  * place panel names on first row of grid header (used by LiveGridForms)
951  */
952   insertPanelNames: function(r,start,limit,cellClass) {
953     Rico.log('insertPanelNames: start='+start+' limit='+limit);
954     r.className='ricoLG_hdg';
955     var lastIdx=-1, span, newCell=null, spanIdx=0;
956     for( var c=start; c < limit; c++ ) {
957       if (lastIdx == this.options.columnSpecs[c].ColGroupIdx) {
958         span++;
959       } else {
960         if (newCell) newCell.colSpan=span;
961         newCell = r.insertCell(-1);
962         if (cellClass) newCell.className=cellClass;
963         span=1;
964         lastIdx=this.options.columnSpecs[c].ColGroupIdx;
965         newCell.innerHTML=this.options.ColGroups[lastIdx];
966       }
967     }
968     if (newCell) newCell.colSpan=span;
969   },
970
971 /**
972  * create grid header for table i (if none was provided)
973  */
974   createHdr: function(i,start,limit) {
975     Rico.log('createHdr: i='+i+' start='+start+' limit='+limit);
976     var mainRow = this.thead[i].insertRow(-1);
977     mainRow.id=this.tableId+'_tab'+i+'h_main';
978     mainRow.className='ricoLG_hdg';
979     for( var c=start; c < limit; c++ ) {
980       var newCell = mainRow.insertCell(-1);
981       newCell.innerHTML=this.options.columnSpecs[c].Hdg;
982     }
983   },
984
985 /**
986  * move header cells in original table to grid
987  */
988   loadHdrSrc: function(hdrSrc) {
989     var i,h,c,r,newrow,cells;
990     Rico.log('loadHdrSrc start');
991     for (i=0; i<2; i++) {
992       for (r=0; r<hdrSrc.length; r++) {
993         newrow = this.thead[i].insertRow(-1);
994         newrow.className='ricoLG_hdg '+this.tableId+'_hdg'+r;
995       }
996     }
997     if (hdrSrc.length==1) {
998       cells=hdrSrc[0].cells;
999       for (c=0; cells.length > 0; c++)
1000         this.thead[c<this.options.frozenColumns ? 0 : 1].rows[0].appendChild(cells[0]);
1001     } else {
1002       for (r=0; r<hdrSrc.length; r++) {
1003         cells=hdrSrc[r].cells;
1004         for (c=0,h=0; cells.length > 0; c++) {
1005           if (Rico.hasClass(cells[0],'ricoFrozen')) {
1006             if (r==this.headerRowIdx) this.options.frozenColumns=c+1;
1007           } else {
1008             h=1;
1009           }
1010           this.thead[h].rows[r].appendChild(cells[0]);
1011         }
1012       }
1013     }
1014     Rico.log('loadHdrSrc end');
1015   },
1016
1017 /**
1018  * Size div elements
1019  */
1020   sizeDivs: function() {
1021     Rico.log('sizeDivs: '+this.tableId);
1022     //this.cancelMenu();
1023     this.unhighlight();
1024     this.baseSizeDivs();
1025     var firstVisible=this.firstVisible();
1026     if (this.pageSize == 0 || firstVisible < 0) return;
1027     var totRowHt=this.columns[firstVisible].dataColDiv.offsetHeight;
1028     this.rowHeight = Math.round(totRowHt/this.pageSize);
1029     var scrHt=this.dataHt;
1030     if (this.scrTabWi0 == this.scrTabWi) {
1031       // no scrolling columns - horizontal scroll bar not needed
1032       this.innerDiv.style.height=(this.hdrHt+1)+'px';
1033       this.scrollDiv.style.overflowX='hidden';
1034     } else {
1035       this.scrollDiv.style.overflowX='scroll';
1036       scrHt+=this.options.scrollBarWidth;
1037     }
1038     this.scrollDiv.style.height=scrHt+'px';
1039     this.innerDiv.style.width=(this.scrWi)+'px';
1040     this.scrollTab.style.width=(this.scrWi-this.options.scrollBarWidth)+'px';
1041     //this.resizeDiv.style.height=this.frozenTabs.style.height=this.innerDiv.style.height=(this.hdrHt+this.dataHt+1)+'px';
1042     this.resizeDiv.style.height=(this.hdrHt+this.dataHt+1)+'px';
1043     Rico.log('sizeDivs scrHt='+scrHt+' innerHt='+this.innerDiv.style.height+' rowHt='+this.rowHeight+' pageSize='+this.pageSize);
1044     var pad=(this.scrWi-this.scrTabWi < this.options.scrollBarWidth) ? 2 : 0;
1045     this.shadowDiv.style.width=(this.scrTabWi+pad)+'px';
1046     this.outerDiv.style.height=(this.hdrHt+scrHt)+'px';
1047     this.setHorizontalScroll();
1048   },
1049
1050   setHorizontalScroll: function() {
1051     var newLeft=(-this.scrollDiv.scrollLeft)+'px';
1052     this.tabs[1].style.marginLeft=newLeft;
1053     this.tabs[2].style.marginLeft=newLeft;
1054   },
1055
1056   remainingHt: function() {
1057     var tabHt=this.outerDiv.offsetHeight;
1058     var winHt=Rico.windowHeight();
1059     var margin=Rico.isIE ? 15 : 10;
1060     // if there is a horizontal scrollbar take it into account
1061     if (!Rico.isIE && window.frameElement && window.frameElement.scrolling=='yes' && this.sizeTo!='parent') margin+=this.options.scrollBarWidth;
1062     switch (this.sizeTo) {
1063       case 'window':
1064         var divTop=Rico.cumulativeOffset(this.outerDiv).top;
1065         Rico.log("remainingHt/window, winHt="+winHt+' tabHt='+tabHt+' gridY='+divTop);
1066         return winHt-divTop-tabHt-margin;  // allow for scrollbar and some margin
1067       case 'parent':
1068         var offset=this.offsetFromParent(this.outerDiv);
1069         if (Rico.isIE) Rico.hide(this.outerDiv);
1070         var parentHt=this.outerDiv.parentNode.clientHeight;
1071         if (Rico.isIE) Rico.show(this.outerDiv);
1072         Rico.log("remainingHt/parent, parentHt="+parentHt+' offset='+offset+' tabHt='+tabHt);
1073         return parentHt-tabHt-offset-margin;
1074       case 'data':
1075       case 'body':
1076         var bodyHt=Rico.isIE ? document.body.scrollHeight : document.body.offsetHeight;
1077         //alert("remainingHt\n document.height="+document.height+"\n body.offsetHeight="+document.body.offsetHeight+"\n body.scrollHeight="+document.body.scrollHeight+"\n documentElement.scrollHeight="+document.documentElement.scrollHeight);
1078         var remHt=winHt-bodyHt-margin;
1079         if (!Rico.isWebKit) remHt-=this.options.scrollBarWidth;
1080         Rico.log("remainingHt, winHt="+winHt+' pageHt='+bodyHt+' remHt='+remHt);
1081         return remHt;
1082       default:
1083         Rico.log("remainingHt, winHt="+winHt+' tabHt='+tabHt);
1084         if (this.sizeTo.slice(-1)=='%') winHt*=parseFloat(this.sizeTo)/100.0;
1085         else if (this.sizeTo.slice(-2)=='px') winHt=parseInt(this.sizeTo,10);
1086         return winHt-tabHt-margin;  // allow for scrollbar and some margin
1087     }
1088   },
1089
1090   offsetFromParent: function(element) {
1091     var valueT = 0;
1092     var elParent=element.parentNode;
1093     do {
1094       //Rico.log("offsetFromParent: "+element.tagName+' id='+element.id+' otop='+element.offsetTop);
1095       valueT += element.offsetTop  || 0;
1096       element = element.offsetParent;
1097       if (!element || element==null) break;
1098       var p = Rico.getStyle(element, 'position');
1099       if (element.tagName=='BODY' || element.tagName=='HTML' || p=='absolute') return valueT-elParent.offsetTop;
1100     } while (element != elParent);
1101     return valueT;
1102   },
1103
1104   adjustPageSize: function() {
1105     Rico.log('adjustPageSize start');
1106     var remHt=this.remainingHt();
1107     Rico.log('adjustPageSize remHt='+remHt+' lastRow='+this.lastRowPos);
1108     if (remHt > this.rowHeight)
1109       this.autoAppendRows(remHt);
1110     else if (remHt < 0 || this.sizeTo=='data')
1111       this.autoRemoveRows(-remHt);
1112     Rico.log('adjustPageSize end');
1113   },
1114   
1115   setPageSize: function(newRowCount) {
1116     Rico.log('setPageSize '+this.tableId+' newRowCount='+newRowCount);
1117     newRowCount=Math.min(newRowCount,this.options.maxPageRows);
1118     newRowCount=Math.max(newRowCount,this.options.minPageRows);
1119     this.sizeTo='fixed';
1120     var oldSize=this.pageSize;
1121     while (this.pageSize > newRowCount) {
1122       this.removeRow();
1123     }
1124     while (this.pageSize < newRowCount) {
1125       this.appendBlankRow();
1126     }
1127     this.finishResize(oldSize);
1128   },
1129
1130   pluginWindowResize: function() {
1131     Rico.log("pluginWindowResize");
1132     this.resizeWindowHandler=Rico.eventHandle(this,'resizeWindow');
1133     Rico.eventBind(window, "resize", this.resizeWindowHandler, false);
1134   },
1135
1136   unplugWindowResize: function() {
1137     if (!this.resizeWindowHandler) return;
1138     Rico.eventUnbind(window,"resize", this.resizeWindowHandler, false);
1139     this.resizeWindowHandler=null;
1140   },
1141
1142   resizeWindow: function() {
1143     Rico.log('resizeWindow '+this.tableId+' lastRow='+this.lastRowPos+' resizeState='+this.resizeState);
1144     if (this.resizeState=='finish') {
1145       Rico.log('resizeWindow postponed');
1146       this.resizeState='resize';
1147       return;
1148     }
1149     if (!this.sizeTo || this.sizeTo=='fixed') {
1150       this.sizeDivs();
1151       return;
1152     }
1153     if (this.sizeTo=='parent' && Rico.getStyle(this.outerDiv.parentNode,'display') == 'none') return;
1154     Rico.log('resizeWindow: about to adjustPageSize')
1155     var oldSize=this.pageSize;
1156     this.adjustPageSize();
1157     this.finishResize(oldSize);
1158   },
1159
1160   finishResize: function(oldSize) {
1161     Rico.log('finishResize '+this.tableId);
1162     if (this.pageSize > oldSize && this.buffer.totalRows>0) {
1163       this.isPartialBlank=true;
1164       var adjStart=this.adjustRow(this.lastRowPos);
1165       this.buffer.fetch(adjStart);
1166     } else if (this.pageSize < oldSize) {
1167       if (this.options.onRefreshComplete) this.options.onRefreshComplete(this.contentStartPos,this.contentStartPos+this.pageSize-1);  // update bookmark
1168     }
1169     this.resizeState='finish';
1170     Rico.runLater(20,this,'finishResize2');
1171     Rico.log('Resize '+this.tableId+' complete. old size='+oldSize+' new size='+this.pageSize);
1172   },
1173
1174   finishResize2: function() {
1175     Rico.log('finishResize2 '+this.tableId+': resizeState='+this.resizeState);
1176     this.sizeDivs();
1177     this.updateHeightDiv();
1178     if (this.resizeState=='resize') {
1179       this.resizeWindow();
1180     } else {
1181       this.resizeState='';
1182     }
1183   },
1184
1185   topOfLastPage: function() {
1186     return Math.max(this.buffer.totalRows-this.pageSize,0);
1187   },
1188
1189   updateHeightDiv: function() {
1190     var notdisp=this.topOfLastPage();
1191     var ht = notdisp ? this.scrollDiv.clientHeight + Math.floor(this.rowHeight * (notdisp + 0.4)) : 1;
1192     Rico.log("updateHeightDiv, ht="+ht+' scrollDiv.clientHeight='+this.scrollDiv.clientHeight+' rowsNotDisplayed='+notdisp);
1193     this.shadowDiv.style.height=ht+'px';
1194   },
1195
1196   autoRemoveRows: function(overage) {
1197     if (!this.rowHeight) return;
1198     var removeCnt=Math.ceil(overage / this.rowHeight);
1199     if (this.sizeTo=='data')
1200       removeCnt=Math.max(removeCnt,this.pageSize-this.buffer.totalRows);
1201     Rico.log("autoRemoveRows overage="+overage+" removeCnt="+removeCnt);
1202     for (var i=0; i<removeCnt; i++)
1203       this.removeRow();
1204   },
1205
1206   removeRow: function() {
1207     if (this.pageSize <= this.options.minPageRows) return;
1208     this.pageSize--;
1209     for( var c=0; c < this.headerColCnt; c++ ) {
1210       var cell=this.columns[c].cell(this.pageSize);
1211       this.columns[c].dataColDiv.removeChild(cell);
1212     }
1213   },
1214
1215   autoAppendRows: function(overage) {
1216     if (!this.rowHeight) return;
1217     var addCnt=Math.floor(overage / this.rowHeight);
1218     Rico.log("autoAppendRows overage="+overage+" cnt="+addCnt+" rowHt="+this.rowHeight);
1219     for (var i=0; i<addCnt; i++) {
1220       if (this.sizeTo=='data' && this.pageSize>=this.buffer.totalRows) break;
1221       this.appendBlankRow();
1222     }
1223   },
1224
1225 /**
1226  * on older systems, this can be fairly slow
1227  */
1228   appendBlankRow: function() {
1229     if (this.pageSize >= this.options.maxPageRows) return;
1230     Rico.log("appendBlankRow #"+this.pageSize);
1231     var cls=this.defaultRowClass(this.pageSize);
1232     for( var c=0; c < this.headerColCnt; c++ ) {
1233       var newdiv = document.createElement("div");
1234       newdiv.className = 'ricoLG_cell '+cls;
1235       newdiv.id=this.tableId+'_'+this.pageSize+'_'+c;
1236       this.columns[c].dataColDiv.appendChild(newdiv);
1237       if (this.columns[c]._create) {
1238         this.columns[c]._create(newdiv,this.pageSize);
1239       } else {
1240         newdiv.innerHTML='&nbsp;';   // this seems to be required by IE
1241       }
1242       if (this.columns[c].format.canDrag && Rico.registerDraggable) {
1243         Rico.registerDraggable( new Rico.LiveGridDraggable(this, this.pageSize, c), this.options.dndMgrIdx );
1244       }
1245     }
1246     this.pageSize++;
1247   },
1248
1249   defaultRowClass: function(rownum) {
1250     var cls
1251     if (rownum % 2==0) {
1252       cls='ricoLG_evenRow';
1253       //if (Rico.theme.primary) cls+=' '+Rico.theme.primary;
1254     } else {
1255       cls='ricoLG_oddRow';
1256       //if (Rico.theme.secondary) cls+=' '+Rico.theme.secondary;
1257     }
1258     return cls;
1259   },
1260
1261   handleMenuClick: function(e) {
1262     if (!this.menu) return;
1263     this.cancelMenu();
1264     this.unhighlight(); // in case highlighting was invoked externally
1265     var idx;
1266     var cell=Rico.eventElement(e);
1267     if (cell.className=='ricoLG_highlightDiv') {
1268       idx=this.highlightIdx;
1269     } else {
1270       cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
1271       if (!cell) return;
1272       idx=this.winCellIndex(cell);
1273       if ((this.options.highlightSection & (idx.tabIdx+1))==0) return;
1274     }
1275     this.highlight(idx);
1276     this.highlightEnabled=false;
1277     if (this.hideScroll) this.scrollDiv.style.overflow="hidden";
1278     this.menuIdx=idx;
1279     if (!this.menu.div) this.menu.createDiv();
1280     this.menu.liveGrid=this;
1281     if (this.menu.buildGridMenu) {
1282       var showMenu=this.menu.buildGridMenu(idx.row, idx.column, idx.tabIdx);
1283       if (!showMenu) return;
1284     }
1285     if (this.options.highlightElem=='selection' && !this.isSelected(idx.cell)) {
1286       this.selectCell(idx.cell);
1287     }
1288     var self=this;
1289     this.menu.showmenu(e,function() { self.closeMenu(); });
1290     return false;
1291   },
1292
1293   closeMenu: function() {
1294     if (!this.menuIdx) return;
1295     if (this.hideScroll) this.scrollDiv.style.overflow="";
1296     //this.unhighlight();
1297     this.highlightEnabled=true;
1298     this.menuIdx=null;
1299   },
1300
1301 /**
1302  * @return index of cell within the window
1303  */
1304   winCellIndex: function(cell) {
1305     var l=cell.id.lastIndexOf('_',cell.id.length);
1306     var l2=cell.id.lastIndexOf('_',l-1)+1;
1307     var c=parseInt(cell.id.substr(l+1));
1308     var r=parseInt(cell.id.substr(l2,l));
1309     return {row:r, column:c, tabIdx:this.columns[c].tabIdx, cell:cell};
1310   },
1311
1312 /**
1313  * @return index of cell within the dataset
1314  */
1315   datasetIndex: function(cell) {
1316     var idx=this.winCellIndex(cell);
1317     idx.row+=this.buffer.windowPos;
1318     idx.onBlankRow=(idx.row >= this.buffer.endPos());
1319     return idx;
1320   },
1321
1322   attachHighlightEvents: function(tBody) {
1323     switch (this.options.highlightElem) {
1324       case 'selection':
1325         Rico.eventBind(tBody,"mousedown", this.options.mouseDownHandler, false);
1326         /** @ignore */
1327         tBody.ondrag = function () { return false; };
1328         /** @ignore */
1329         tBody.onselectstart = function () { return false; };
1330         break;
1331       case 'cursorRow':
1332       case 'cursorCell':
1333         Rico.eventBind(tBody,"mouseover", this.options.rowOverHandler, false);
1334         break;
1335     }
1336   },
1337
1338   detachHighlightEvents: function(tBody) {
1339     switch (this.options.highlightElem) {
1340       case 'selection':
1341         Rico.eventUnbind(tBody,"mousedown", this.options.mouseDownHandler, false);
1342         tBody.ondrag = null;
1343         tBody.onselectstart = null;
1344         break;
1345       case 'cursorRow':
1346       case 'cursorCell':
1347         Rico.eventUnbind(tBody,"mouseover", this.options.rowOverHandler, false);
1348         break;
1349     }
1350   },
1351
1352 /**
1353  * @return array of objects containing row/col indexes (index values are relative to the start of the window)
1354  */
1355   getVisibleSelection: function() {
1356     var cellList=[];
1357     if (this.SelectIdxStart && this.SelectIdxEnd) {
1358       var r1=Math.max(Math.min(this.SelectIdxEnd.row,this.SelectIdxStart.row)-this.buffer.startPos,this.buffer.windowStart);
1359       var r2=Math.min(Math.max(this.SelectIdxEnd.row,this.SelectIdxStart.row)-this.buffer.startPos,this.buffer.windowEnd-1);
1360       var c1=Math.min(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1361       var c2=Math.max(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1362       //Rico.log("getVisibleSelection "+r1+','+c1+' to '+r2+','+c2+' ('+this.SelectIdxStart.row+',startPos='+this.buffer.startPos+',windowPos='+this.buffer.windowPos+',windowEnd='+this.buffer.windowEnd+')');
1363       for (var r=r1; r<=r2; r++) {
1364         for (var c=c1; c<=c2; c++)
1365           cellList.push({row:r-this.buffer.windowStart,column:c});
1366       }
1367     }
1368     if (this.SelectCtrl) {
1369       for (var i=0; i<this.SelectCtrl.length; i++) {
1370         if (this.SelectCtrl[i].row>=this.buffer.windowStart && this.SelectCtrl[i].row<this.buffer.windowEnd)
1371           cellList.push({row:this.SelectCtrl[i].row-this.buffer.windowStart,column:this.SelectCtrl[i].column});
1372       }
1373     }
1374     return cellList;
1375   },
1376
1377   updateSelectOutline: function() {
1378     if (!this.SelectIdxStart || !this.SelectIdxEnd) return;
1379     var r1=Math.max(Math.min(this.SelectIdxEnd.row,this.SelectIdxStart.row), this.buffer.windowStart);
1380     var r2=Math.min(Math.max(this.SelectIdxEnd.row,this.SelectIdxStart.row), this.buffer.windowEnd-1);
1381     if (r1 > r2) {
1382       this.HideSelection();
1383       return;
1384     }
1385     var c1=Math.min(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1386     var c2=Math.max(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1387     var top1=this.columns[c1].cell(r1-this.buffer.windowStart).offsetTop;
1388     var cell2=this.columns[c1].cell(r2-this.buffer.windowStart);
1389     var bottom2=cell2.offsetTop+cell2.offsetHeight;
1390     var left1=this.columns[c1].dataCell.offsetLeft;
1391     var left2=this.columns[c2].dataCell.offsetLeft;
1392     var right2=left2+this.columns[c2].dataCell.offsetWidth;
1393     //window.status='updateSelectOutline: '+r1+' '+r2+' top='+top1+' bot='+bottom2;
1394     this.highlightDiv[0].style.top=this.highlightDiv[3].style.top=this.highlightDiv[1].style.top=(this.hdrHt+top1-1) + 'px';
1395     this.highlightDiv[2].style.top=(this.hdrHt+bottom2-1)+'px';
1396     this.highlightDiv[3].style.left=(left1-2)+'px';
1397     this.highlightDiv[0].style.left=this.highlightDiv[2].style.left=(left1-1)+'px';
1398     this.highlightDiv[1].style.left=(right2-1)+'px';
1399     this.highlightDiv[0].style.width=this.highlightDiv[2].style.width=(right2-left1-1) + 'px';
1400     this.highlightDiv[1].style.height=this.highlightDiv[3].style.height=(bottom2-top1) + 'px';
1401     //this.highlightDiv[0].style.right=this.highlightDiv[2].style.right=this.highlightDiv[1].style.right=()+'px';
1402     //this.highlightDiv[2].style.bottom=this.highlightDiv[3].style.bottom=this.highlightDiv[1].style.bottom=(this.hdrHt+bottom2) + 'px';
1403     for (var i=0; i<4; i++)
1404       this.highlightDiv[i].style.display='';
1405   },
1406
1407   HideSelection: function() {
1408     var i;
1409     if (this.options.highlightMethod!='class') {
1410       for (i=0; i<this.highlightDiv.length; i++)
1411         this.highlightDiv[i].style.display='none';
1412     }
1413     if (this.options.highlightMethod!='outline') {
1414       var cellList=this.getVisibleSelection();
1415       Rico.log("HideSelection "+cellList.length);
1416       for (i=0; i<cellList.length; i++)
1417         this.unhighlightCell(this.columns[cellList[i].column].cell(cellList[i].row));
1418     }
1419   },
1420
1421   ShowSelection: function() {
1422     if (this.options.highlightMethod!='class')
1423       this.updateSelectOutline();
1424     if (this.options.highlightMethod!='outline') {
1425       var cellList=this.getVisibleSelection();
1426       for (var i=0; i<cellList.length; i++)
1427         this.highlightCell(this.columns[cellList[i].column].cell(cellList[i].row));
1428     }
1429   },
1430
1431   ClearSelection: function() {
1432     Rico.log("ClearSelection");
1433     this.HideSelection();
1434     this.SelectIdxStart=null;
1435     this.SelectIdxEnd=null;
1436     this.SelectCtrl=[];
1437   },
1438
1439   selectCell: function(cell) {
1440     this.ClearSelection();
1441     this.SelectIdxStart=this.SelectIdxEnd=this.datasetIndex(cell);
1442     this.ShowSelection();
1443   },
1444
1445   AdjustSelection: function(cell) {
1446     var newIdx=this.datasetIndex(cell);
1447     if (this.SelectIdxStart.tabIdx != newIdx.tabIdx) return;
1448     this.HideSelection();
1449     this.SelectIdxEnd=newIdx;
1450     this.ShowSelection();
1451   },
1452
1453   RefreshSelection: function() {
1454     var cellList=this.getVisibleSelection();
1455     for (var i=0; i<cellList.length; i++) {
1456       this.columns[cellList[i].column].displayValue(cellList[i].row);
1457     }
1458   },
1459
1460   FillSelection: function(newVal,newStyle) {
1461     if (this.SelectIdxStart && this.SelectIdxEnd) {
1462       var r1=Math.min(this.SelectIdxEnd.row,this.SelectIdxStart.row);
1463       var r2=Math.max(this.SelectIdxEnd.row,this.SelectIdxStart.row);
1464       var c1=Math.min(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1465       var c2=Math.max(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1466       for (var r=r1; r<=r2; r++) {
1467         for (var c=c1; c<=c2; c++) {
1468           this.buffer.setValue(r,c,newVal,newStyle);
1469         }
1470       }
1471     }
1472     if (this.SelectCtrl) {
1473       for (var i=0; i<this.SelectCtrl.length; i++) {
1474         this.buffer.setValue(this.SelectCtrl[i].row,this.SelectCtrl[i].column,newVal,newStyle);
1475       }
1476     }
1477     this.RefreshSelection();
1478   },
1479
1480 /**
1481  * Process mouse down event
1482  * @param e event object
1483  */
1484   selectMouseDown: function(e) {
1485     if (this.highlightEnabled==false) return true;
1486     this.cancelMenu();
1487     var cell=Rico.eventElement(e);
1488     if (!Rico.eventLeftClick(e)) return true;
1489     cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
1490     if (!cell) return true;
1491     Rico.eventStop(e);
1492     var newIdx=this.datasetIndex(cell);
1493     if (newIdx.onBlankRow) return true;
1494     Rico.log("selectMouseDown @"+newIdx.row+','+newIdx.column);
1495     if (e.ctrlKey) {
1496       if (!this.SelectIdxStart || this.options.highlightMethod!='class') return true;
1497       if (!this.isSelected(cell)) {
1498         this.highlightCell(cell);
1499         this.SelectCtrl.push(this.datasetIndex(cell));
1500       } else {
1501         for (var i=0; i<this.SelectCtrl.length; i++) {
1502           if (this.SelectCtrl[i].row==newIdx.row && this.SelectCtrl[i].column==newIdx.column) {
1503             this.unhighlightCell(cell);
1504             this.SelectCtrl.splice(i,1);
1505             break;
1506           }
1507         }
1508       }
1509     } else if (e.shiftKey) {
1510       if (!this.SelectIdxStart) return true;
1511       this.AdjustSelection(cell);
1512     } else {
1513       this.selectCell(cell);
1514       this.pluginSelect();
1515     }
1516     return false;
1517   },
1518
1519   pluginSelect: function() {
1520     if (this.selectPluggedIn) return;
1521     var tBody=this.tbody[this.SelectIdxStart.tabIdx];
1522     Rico.eventBind(tBody,"mouseover", this.options.mouseOverHandler, false);
1523     Rico.eventBind(this.outerDiv,"mouseup",  this.options.mouseUpHandler,  false);
1524     this.selectPluggedIn=true;
1525   },
1526
1527   unplugSelect: function() {
1528     if (!this.selectPluggedIn) return;
1529     var tBody=this.tbody[this.SelectIdxStart.tabIdx];
1530     Rico.eventUnbind(tBody,"mouseover", this.options.mouseOverHandler , false);
1531     Rico.eventUnbind(this.outerDiv,"mouseup", this.options.mouseUpHandler , false);
1532     this.selectPluggedIn=false;
1533   },
1534
1535   selectMouseUp: function(e) {
1536     this.unplugSelect();
1537     var cell=Rico.eventElement(e);
1538     cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
1539     if (!cell) return;
1540     if (this.SelectIdxStart && this.SelectIdxEnd)
1541       this.AdjustSelection(cell);
1542     else
1543       this.ClearSelection();
1544   },
1545
1546   selectMouseOver: function(e) {
1547     var cell=Rico.eventElement(e);
1548     cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
1549     if (!cell) return;
1550     this.AdjustSelection(cell);
1551     Rico.eventStop(e);
1552   },
1553
1554   isSelected: function(cell) {
1555     if (this.options.highlightMethod!='outline') return Rico.hasClass(cell,this.options.highlightClass);
1556     if (!this.SelectIdxStart || !this.SelectIdxEnd) return false;
1557     var r1=Math.max(Math.min(this.SelectIdxEnd.row,this.SelectIdxStart.row), this.buffer.windowStart);
1558     var r2=Math.min(Math.max(this.SelectIdxEnd.row,this.SelectIdxStart.row), this.buffer.windowEnd-1);
1559     if (r1 > r2) return false;
1560     var c1=Math.min(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1561     var c2=Math.max(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1562     var curIdx=this.datasetIndex(cell);
1563     return (r1<=curIdx.row && curIdx.row<=r2 && c1<=curIdx.column && curIdx.column<=c2);
1564   },
1565
1566   highlightCell: function(cell) {
1567     Rico.addClass(cell,this.options.highlightClass);
1568   },
1569
1570   unhighlightCell: function(cell) {
1571     if (cell) Rico.removeClass(cell,this.options.highlightClass);
1572   },
1573
1574   selectRow: function(r) {
1575     for (var c=0; c<this.columns.length; c++)
1576       this.highlightCell(this.columns[c].cell(r));
1577   },
1578
1579   unselectRow: function(r) {
1580     for (var c=0; c<this.columns.length; c++)
1581       this.unhighlightCell(this.columns[c].cell(r));
1582   },
1583
1584   rowMouseOver: function(e) {
1585     if (!this.highlightEnabled) return;
1586     var cell=Rico.eventElement(e);
1587     cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
1588     if (!cell) return;
1589     var newIdx=this.winCellIndex(cell);
1590     if ((this.options.highlightSection & (newIdx.tabIdx+1))==0) return;
1591     this.highlight(newIdx);
1592   },
1593
1594   highlight: function(newIdx) {
1595     if (this.options.highlightMethod!='outline') this.cursorSetClass(newIdx);
1596     if (this.options.highlightMethod!='class') this.cursorOutline(newIdx);
1597     this.highlightIdx=newIdx;
1598   },
1599
1600   cursorSetClass: function(newIdx) {
1601     switch (this.options.highlightElem) {
1602       case 'menuCell':
1603       case 'cursorCell':
1604         if (this.highlightIdx) this.unhighlightCell(this.highlightIdx.cell);
1605         this.highlightCell(newIdx.cell);
1606         break;
1607       case 'menuRow':
1608       case 'cursorRow':
1609         if (this.highlightIdx) this.unselectRow(this.highlightIdx.row);
1610         var s1=this.options.highlightSection & 1;
1611         var s2=this.options.highlightSection & 2;
1612         var c0=s1 ? 0 : this.options.frozenColumns;
1613         var c1=s2 ? this.columns.length : this.options.frozenColumns;
1614         for (var c=c0; c<c1; c++)
1615           this.highlightCell(this.columns[c].cell(newIdx.row));
1616         break;
1617       default: return;
1618     }
1619   },
1620
1621   cursorOutline: function(newIdx) {
1622     var div;
1623     switch (this.options.highlightElem) {
1624       case 'menuCell':
1625       case 'cursorCell':
1626         div=this.highlightDiv[newIdx.tabIdx];
1627         div.style.left=(this.columns[newIdx.column].dataCell.offsetLeft-1)+'px';
1628         div.style.width=this.columns[newIdx.column].colWidth;
1629         this.highlightDiv[1-newIdx.tabIdx].style.display='none';
1630         break;
1631       case 'menuRow':
1632       case 'cursorRow':
1633         div=this.highlightDiv[0];
1634         var s1=this.options.highlightSection & 1;
1635         var s2=this.options.highlightSection & 2;
1636         div.style.left=s1 ? '0px' : this.frozenTabs.style.width;
1637         div.style.width=((s1 ? this.frozenTabs.offsetWidth : 0) + (s2 ? this.innerDiv.offsetWidth : 0) - 4)+'px';
1638         break;
1639       default: return;
1640     }
1641     div.style.top=(this.hdrHt+newIdx.row*this.rowHeight-1)+'px';
1642     div.style.height=(this.rowHeight-1)+'px';
1643     div.style.display='';
1644   },
1645
1646   unhighlight: function() {
1647     switch (this.options.highlightElem) {
1648       case 'menuCell':
1649         //this.highlightIdx=this.menuIdx;
1650         /*jsl:fallthru*/
1651       case 'cursorCell':
1652         if (this.highlightIdx) this.unhighlightCell(this.highlightIdx.cell);
1653         if (!this.highlightDiv) return;
1654         for (var i=0; i<2; i++)
1655           this.highlightDiv[i].style.display='none';
1656         break;
1657       case 'menuRow':
1658         //this.highlightIdx=this.menuIdx;
1659         /*jsl:fallthru*/
1660       case 'cursorRow':
1661         if (this.highlightIdx) this.unselectRow(this.highlightIdx.row);
1662         if (this.highlightDiv) this.highlightDiv[0].style.display='none';
1663         break;
1664     }
1665   },
1666
1667   resetContents: function() {
1668     Rico.log("resetContents");
1669     this.ClearSelection();
1670     this.buffer.clear();
1671     this.clearRows();
1672     this.clearBookmark();
1673   },
1674
1675   setImages: function() {
1676     for (var n=0; n<this.columns.length; n++)
1677       this.columns[n].setImage();
1678   },
1679
1680 /**
1681  * @return column index, or -1 if there are no sorted columns
1682  */
1683   findSortedColumn: function() {
1684     for (var n=0; n<this.columns.length; n++) {
1685       if (this.columns[n].isSorted()) return n;
1686     }
1687     return -1;
1688   },
1689
1690 /**
1691  * Searches options.columnSpecs colAttr for matching colValue
1692  * @return array of matching column indexes
1693  */
1694   findColumnsBySpec: function(colAttr, colValue) {
1695     var result=[];
1696     for (var n=0; n<this.options.columnSpecs.length; n++) {
1697       if (this.options.columnSpecs[n][colAttr] == colValue) result.push(n);
1698     }
1699     return result;
1700   },
1701
1702 /**
1703  * Set initial sort
1704  */
1705   setSortUI: function( columnIdOrNum, sortDirection ) {
1706     Rico.log("setSortUI: "+columnIdOrNum+' '+sortDirection);
1707     var colnum=this.findSortedColumn();
1708     if (colnum >= 0) {
1709       sortDirection=this.columns[colnum].getSortDirection();
1710     } else {
1711       if (typeof sortDirection!='string') {
1712         sortDirection=Rico.ColumnConst.SORT_ASC;
1713       } else {
1714         sortDirection=sortDirection.toUpperCase();
1715         if (sortDirection != Rico.ColumnConst.SORT_DESC) sortDirection=Rico.ColumnConst.SORT_ASC;
1716       }
1717       switch (typeof columnIdOrNum) {
1718         case 'string':
1719           colnum=this.findColumnsBySpec('id',columnIdOrNum);
1720           break;
1721         case 'number':
1722           colnum=columnIdOrNum;
1723           break;
1724       }
1725     }
1726     if (typeof(colnum)!='number' || colnum < 0) return;
1727     this.clearSort();
1728     this.columns[colnum].setSorted(sortDirection);
1729     this.buffer.sortBuffer(colnum);
1730   },
1731
1732 /**
1733  * clear sort flag on all columns
1734  */
1735   clearSort: function() {
1736     for (var x=0;x<this.columns.length;x++)
1737       this.columns[x].setUnsorted();
1738   },
1739
1740 /**
1741  * clear filters on all columns
1742  */
1743   clearFilters: function() {
1744     for (var x=0;x<this.columns.length;x++) {
1745       this.columns[x].setUnfiltered(true);
1746     }
1747     if (this.options.filterHandler) {
1748       this.options.filterHandler();
1749     }
1750   },
1751
1752 /**
1753  * returns number of columns with a user filter set
1754  */
1755   filterCount: function() {
1756     for (var x=0,cnt=0;x<this.columns.length;x++) {
1757       if (this.columns[x].isFiltered()) cnt++;
1758     }
1759     return cnt;
1760   },
1761
1762   sortHandler: function() {
1763     this.cancelMenu();
1764     this.ClearSelection();
1765     this.setImages();
1766     var n=this.findSortedColumn();
1767     if (n < 0) return;
1768     Rico.log("sortHandler: sorting column "+n);
1769     this.buffer.sortBuffer(n);
1770     this.clearRows();
1771     this.scrollDiv.scrollTop = 0;
1772     this.buffer.fetch(0);
1773   },
1774
1775   filterHandler: function() {
1776     Rico.log("filterHandler");
1777     this.cancelMenu();
1778     if (this.buffer.processingRequest) {
1779       this.queueFilter=true;
1780       return;
1781     }
1782     this.unplugScroll();
1783     this.ClearSelection();
1784     this.setImages();
1785     this.clearBookmark();
1786     this.clearRows();
1787     this.buffer.fetch(-1);
1788     Rico.runLater(10,this,'pluginScroll'); // resetting ht div can cause a scroll event, triggering an extra fetch
1789   },
1790
1791   clearBookmark: function() {
1792     if (this.bookmark) this.bookmark.innerHTML="&nbsp;";
1793   },
1794
1795   bookmarkHandler: function(firstrow,lastrow) {
1796     var newhtml;
1797     if (isNaN(firstrow) || !this.bookmark) return;
1798     var totrows=this.buffer.totalRows;
1799     if (totrows < lastrow) lastrow=totrows;
1800     if (totrows<=0) {
1801       newhtml = Rico.getPhraseById('bookmarkNoMatch');
1802     } else if (lastrow<0) {
1803       newhtml = Rico.getPhraseById('bookmarkNoRec');
1804     } else if (this.buffer.foundRowCount) {
1805       newhtml = Rico.getPhraseById('bookmarkExact',firstrow,lastrow,totrows);
1806     } else {
1807       newhtml = Rico.getPhraseById('bookmarkAbout',firstrow,lastrow,totrows);
1808     }
1809     this.bookmark.innerHTML = newhtml;
1810   },
1811
1812   clearRows: function() {
1813     if (this.isBlank==true) return;
1814     for (var c=0; c < this.columns.length; c++)
1815       this.columns[c].clearColumn();
1816     this.isBlank = true;
1817   },
1818
1819   refreshContents: function(startPos) {
1820     Rico.log("refreshContents1 "+this.tableId+": startPos="+startPos+" lastRow="+this.lastRowPos+" PartBlank="+this.isPartialBlank+" pageSize="+this.pageSize);
1821     this.hideMsg();
1822     this.cancelMenu();
1823     this.unhighlight(); // in case highlighting was manually invoked
1824     if (this.queueFilter) {
1825       Rico.log("refreshContents: cancelling refresh because filter has changed");
1826       this.queueFilter=false;
1827       this.filterHandler();
1828       return;
1829     }
1830     this.highlightEnabled=this.options.highlightSection!='none';
1831     var viewPrecedesBuffer = this.buffer.startPos > startPos;
1832     var contentStartPos = viewPrecedesBuffer ? this.buffer.startPos: startPos;
1833     this.contentStartPos = contentStartPos+1;
1834     var contentEndPos = Math.min(this.buffer.startPos + this.buffer.size, startPos + this.pageSize);
1835     this.buffer.setWindow(contentStartPos, contentEndPos);
1836     Rico.log('refreshContents2 '+this.tableId+': cStartPos='+contentStartPos+' cEndPos='+contentEndPos+' vPrecedesBuf='+viewPrecedesBuffer+' b.startPos='+this.buffer.startPos);
1837     if (startPos == this.lastRowPos && !this.isPartialBlank && !this.isBlank) return;
1838     this.isBlank = false;
1839     var onRefreshComplete = this.options.onRefreshComplete;
1840
1841     if ((startPos + this.pageSize < this.buffer.startPos) ||
1842         (this.buffer.startPos + this.buffer.size < startPos) ||
1843         (this.buffer.size == 0)) {
1844       this.clearRows();
1845       if (onRefreshComplete) onRefreshComplete(this.contentStartPos,contentEndPos);  // update bookmark
1846       return;
1847     }
1848
1849     Rico.log('refreshContents: contentStartPos='+contentStartPos+' contentEndPos='+contentEndPos+' viewPrecedesBuffer='+viewPrecedesBuffer);
1850     var rowSize = contentEndPos - contentStartPos;
1851     var blankSize = this.pageSize - rowSize;
1852     var blankOffset = viewPrecedesBuffer ? 0: rowSize;
1853     var contentOffset = viewPrecedesBuffer ? blankSize: 0;
1854
1855     for (var r=0; r < rowSize; r++) { //initialize what we have
1856       for (var c=0; c < this.columns.length; c++)
1857         this.columns[c].displayValue(r + contentOffset);
1858     }
1859     for (var i=0; i < blankSize; i++)     // blank out the rest
1860       this.blankRow(i + blankOffset);
1861     if (this.options.highlightElem=='selection') this.ShowSelection();
1862     this.isPartialBlank = blankSize > 0;
1863     this.lastRowPos = startPos;
1864     Rico.log("refreshContents complete, startPos="+startPos);
1865     if (onRefreshComplete) onRefreshComplete(this.contentStartPos,contentEndPos);  // update bookmark
1866   },
1867
1868   scrollToRow: function(rowOffset) {
1869      var p=this.rowToPixel(rowOffset);
1870      Rico.log("scrollToRow, rowOffset="+rowOffset+" pixel="+p);
1871      this.scrollDiv.scrollTop = p; // this causes a scroll event
1872      if ( this.options.onscroll )
1873         this.options.onscroll( this, rowOffset );
1874   },
1875
1876   scrollUp: function() {
1877      this.moveRelative(-1);
1878   },
1879
1880   scrollDown: function() {
1881      this.moveRelative(1);
1882   },
1883
1884   pageUp: function() {
1885      this.moveRelative(-this.pageSize);
1886   },
1887
1888   pageDown: function() {
1889      this.moveRelative(this.pageSize);
1890   },
1891
1892   adjustRow: function(rowOffset) {
1893      var notdisp=this.topOfLastPage();
1894      if (notdisp == 0 || !rowOffset) return 0;
1895      return Math.min(notdisp,rowOffset);
1896   },
1897
1898   rowToPixel: function(rowOffset) {
1899      return this.adjustRow(rowOffset) * this.rowHeight;
1900   },
1901
1902 /**
1903  * @returns row to display at top of scroll div
1904  */
1905   pixeltorow: function(p) {
1906      var notdisp=this.topOfLastPage();
1907      if (notdisp == 0) return 0;
1908      var prow=parseInt(p/this.rowHeight,10);
1909      return Math.min(notdisp,prow);
1910   },
1911
1912   moveRelative: function(relOffset) {
1913      var newoffset=Math.max(this.scrollDiv.scrollTop+relOffset*this.rowHeight,0);
1914      newoffset=Math.min(newoffset,this.scrollDiv.scrollHeight);
1915      //Rico.log("moveRelative, newoffset="+newoffset);
1916      this.scrollDiv.scrollTop=newoffset;
1917   },
1918
1919   pluginScroll: function() {
1920      if (this.scrollPluggedIn) return;
1921      Rico.log("pluginScroll: wheelEvent="+this.wheelEvent);
1922      Rico.eventBind(this.scrollDiv,"scroll",this.scrollEventFunc, false);
1923      for (var t=0; t<2; t++)
1924        Rico.eventBind(this.tabs[t],this.wheelEvent,this.wheelEventFunc, false);
1925      this.scrollPluggedIn=true;
1926   },
1927
1928   unplugScroll: function() {
1929      if (!this.scrollPluggedIn) return;
1930      Rico.log("unplugScroll");
1931      Rico.eventUnbind(this.scrollDiv,"scroll", this.scrollEventFunc , false);
1932      for (var t=0; t<2; t++)
1933        Rico.eventUnbind(this.tabs[t],this.wheelEvent,this.wheelEventFunc, false);
1934      this.scrollPluggedIn=false;
1935   },
1936
1937   handleWheel: function(e) {
1938     var delta = 0;
1939     if (e.wheelDelta) {
1940       if (Rico.isOpera)
1941         delta = e.wheelDelta/120;
1942       else if (Rico.isWebKit)
1943         delta = -e.wheelDelta/12;
1944       else
1945         delta = -e.wheelDelta/120;
1946     } else if (e.detail) {
1947       delta = e.detail/3; /* Mozilla/Gecko */
1948     }
1949     if (delta) this.moveRelative(delta);
1950     Rico.eventStop(e);
1951     return false;
1952   },
1953
1954   handleScroll: function(e) {
1955      if ( this.scrollTimeout )
1956        clearTimeout( this.scrollTimeout );
1957      this.setHorizontalScroll();
1958      var scrtop=this.scrollDiv.scrollTop;
1959      var vscrollDiff = this.lastScrollPos-scrtop;
1960      if (vscrollDiff == 0.00) return;
1961      var newrow=this.pixeltorow(scrtop);
1962      if (newrow == this.lastRowPos && !this.isPartialBlank && !this.isBlank) return;
1963      var stamp1 = new Date();
1964      Rico.log("handleScroll, newrow="+newrow+" scrtop="+scrtop);
1965      if (this.options.highlightElem=='selection') this.HideSelection();
1966      this.buffer.fetch(newrow);
1967      if (this.options.onscroll) this.options.onscroll(this, newrow);
1968      this.scrollTimeout = Rico.runLater(1200,this,'scrollIdle');
1969      this.lastScrollPos = this.scrollDiv.scrollTop;
1970      var stamp2 = new Date();
1971      //Rico.log("handleScroll, time="+(stamp2.getTime()-stamp1.getTime()));
1972   },
1973
1974   scrollIdle: function() {
1975      if ( this.options.onscrollidle )
1976         this.options.onscrollidle();
1977   }
1978
1979 };
1980
1981
1982 Rico.LiveGridColumn = function(grid,colIdx,hdrInfo,tabIdx) {
1983   this.initialize(grid,colIdx,hdrInfo,tabIdx);
1984 };
1985
1986 Rico.LiveGridColumn.prototype = 
1987 /** @lends Rico.LiveGridColumn# */
1988 {
1989 /**
1990  * Implements a LiveGrid column. Also contains static properties used by SimpleGrid columns.
1991  * @extends Rico.TableColumnBase
1992  * @constructs
1993  */
1994 initialize: function(liveGrid,colIdx,hdrInfo,tabIdx) {
1995   Rico.extend(this, new Rico.TableColumnBase());
1996   this.baseInit(liveGrid,colIdx,hdrInfo,tabIdx);
1997   this.buffer=liveGrid.buffer;
1998   if (typeof(this.format.type)!='string' || this.format.EntryType=='tinyMCE') this.format.type='html';
1999   if (typeof this.isNullable!='boolean') this.isNullable = /number|date/.test(this.format.type);
2000   this.isText = /html|text/.test(this.format.type);
2001   Rico.log(" sortable="+this.sortable+" filterable="+this.filterable+" hideable="+this.hideable+" isNullable="+this.isNullable+' isText='+this.isText);
2002   this.fixHeaders(this.liveGrid.tableId, this.options.hdrIconsFirst);
2003   if (this['format_'+this.format.type]) {
2004     this._format=this['format_'+this.format.type];
2005   }
2006   if (this.format.control) {
2007     // copy all properties/methods that start with '_'
2008     if (typeof this.format.control=='string') {
2009       this.format.control=eval(this.format.control);
2010     }
2011     for (var property in this.format.control) {
2012       if (property.charAt(0)=='_') {
2013         Rico.log("Copying control property "+property+ ' to ' + this);
2014         this[property] = this.format.control[property];
2015       }
2016     }
2017   }
2018 },
2019
2020 /**
2021  * Sorts the column in ascending order
2022  */
2023 sortAsc: function() {
2024   this.setColumnSort(Rico.ColumnConst.SORT_ASC);
2025 },
2026
2027 /**
2028  * Sorts the column in descending order
2029  */
2030 sortDesc: function() {
2031   this.setColumnSort(Rico.ColumnConst.SORT_DESC);
2032 },
2033
2034 /**
2035  * Sorts the column in the specified direction
2036  * @param direction must be one of Rico.ColumnConst.UNSORTED, .SORT_ASC, or .SORT_DESC
2037  */
2038 setColumnSort: function(direction) {
2039   this.liveGrid.clearSort();
2040   this.setSorted(direction);
2041   if (this.liveGrid.options.saveColumnInfo.sort)
2042     this.liveGrid.setCookie();
2043   if (this.options.sortHandler)
2044     this.options.sortHandler();
2045 },
2046
2047 /**
2048  * @returns true if this column is allowed to be sorted
2049  */
2050 isSortable: function() {
2051   return this.sortable;
2052 },
2053
2054 /**
2055  * @returns true if this column is currently sorted
2056  */
2057 isSorted: function() {
2058   return this.currentSort != Rico.ColumnConst.UNSORTED;
2059 },
2060
2061 /**
2062  * @returns Rico.ColumnConst.UNSORTED, .SORT_ASC, or .SORT_DESC
2063  */
2064 getSortDirection: function() {
2065   return this.currentSort;
2066 },
2067
2068 /**
2069  * toggle the sort sequence for this column
2070  */
2071 toggleSort: function() {
2072   if (this.buffer && this.buffer.totalRows==0) return;
2073   if (this.currentSort == Rico.ColumnConst.SORT_ASC)
2074     this.sortDesc();
2075   else
2076     this.sortAsc();
2077 },
2078
2079 /**
2080  * Flags that this column is not sorted
2081  */
2082 setUnsorted: function() {
2083   this.setSorted(Rico.ColumnConst.UNSORTED);
2084 },
2085
2086 /**
2087  * Flags that this column is sorted, but doesn't actually carry out the sort
2088  * @param direction must be one of Rico.ColumnConst.UNSORTED, .SORT_ASC, or .SORT_DESC
2089  */
2090 setSorted: function(direction) {
2091   this.currentSort = direction;
2092 },
2093
2094 /**
2095  * @returns true if this column is allowed to be filtered
2096  */
2097 canFilter: function() {
2098   return this.filterable;
2099 },
2100
2101 /**
2102  * @returns a textual representation of how this column is filtered
2103  */
2104 getFilterText: function() {
2105   var vals=[];
2106   for (var i=0; i<this.filterValues.length; i++) {
2107     var v=this.filterValues[i];
2108     vals.push(v=='' ? Rico.getPhraseById('filterBlank') : v);
2109   }
2110   switch (this.filterOp) {
2111     case 'EQ':   return '= '+vals.join(', ');
2112     case 'NE':   return Rico.getPhraseById('filterNot',vals.join(', '));
2113     case 'LT':   return '< '+vals[0];
2114     case 'GT':   return '> '+vals[0];
2115     case 'LE':   return '<= '+vals[0];
2116     case 'GE':   return '>= '+vals[0];
2117     case 'LIKE': return Rico.getPhraseById('filterLike',vals[0]);
2118     case 'NULL': return Rico.getPhraseById('filterEmpty');
2119     case 'NOTNULL': return Rico.getPhraseById('filterNotEmpty');
2120   }
2121   return '?';
2122 },
2123
2124 /**
2125  * @returns returns the query string representation of the filter
2126  */
2127 getFilterQueryParm: function() {
2128   if (this.filterType == Rico.ColumnConst.UNFILTERED) return '';
2129   var retval='&f['+this.index+'][op]='+this.filterOp;
2130   retval+='&f['+this.index+'][len]='+this.filterValues.length;
2131   for (var i=0; i<this.filterValues.length; i++) {
2132     retval+='&f['+this.index+']['+i+']='+escape(this.filterValues[i]);
2133   }
2134   return retval;
2135 },
2136
2137 /**
2138  * removes the filter from this column
2139  */
2140 setUnfiltered: function(skipHandler) {
2141   this.filterType = Rico.ColumnConst.UNFILTERED;
2142   if (this.liveGrid.options.saveColumnInfo.filter)
2143     this.liveGrid.setCookie();
2144   if (this.removeFilterFunc)
2145     this.removeFilterFunc();
2146   if (this.options.filterHandler && !skipHandler)
2147     this.options.filterHandler();
2148 },
2149
2150 setFilterEQ: function() {
2151   this.setUserFilter('EQ');
2152 },
2153 setFilterNE: function() {
2154   this.setUserFilter('NE');
2155 },
2156 addFilterNE: function() {
2157   this.filterValues.push(this.userFilter);
2158   if (this.liveGrid.options.saveColumnInfo.filter)
2159     this.liveGrid.setCookie();
2160   if (this.options.filterHandler)
2161     this.options.filterHandler();
2162 },
2163 setFilterGE: function() { this.setUserFilter('GE'); },
2164 setFilterLE: function() { this.setUserFilter('LE'); },
2165 setFilterKW: function(keyword) {
2166   if (keyword!='' && keyword!=null) {
2167     this.setFilter('LIKE',keyword,Rico.ColumnConst.USERFILTER);
2168   } else {
2169     this.setUnfiltered(false);
2170   }
2171 },
2172
2173 setUserFilter: function(relop) {
2174   this.setFilter(relop,this.userFilter,Rico.ColumnConst.USERFILTER);
2175 },
2176
2177 setSystemFilter: function(relop,filter) {
2178   this.setFilter(relop,filter,Rico.ColumnConst.SYSTEMFILTER);
2179 },
2180
2181 setFilter: function(relop,filter,type,removeFilterFunc) {
2182   this.filterValues = typeof(filter)=='object' ? filter : [filter];
2183   this.filterType = type;
2184   this.filterOp = relop;
2185   if (type == Rico.ColumnConst.USERFILTER && this.liveGrid.options.saveColumnInfo.filter)
2186     this.liveGrid.setCookie();
2187   this.removeFilterFunc=removeFilterFunc;
2188   if (this.options.filterHandler)
2189     this.options.filterHandler();
2190 },
2191
2192 isFiltered: function() {
2193   return this.filterType == Rico.ColumnConst.USERFILTER;
2194 },
2195
2196 filterChange: function(e) {
2197   var selbox=Rico.eventElement(e);
2198   if (selbox.value==this.liveGrid.options.FilterAllToken)
2199     this.setUnfiltered();
2200   else
2201     this.setFilter('EQ',selbox.value,Rico.ColumnConst.USERFILTER,function() {selbox.selectedIndex=0;});
2202 },
2203
2204 nFilterChange: function(e) {
2205   var selbox=Rico.eventElement(e);
2206   if (selbox.value==this.liveGrid.options.FilterAllToken) {
2207     this.setUnfiltered();
2208   } else {
2209     var op=selbox.value.substr(0,2);
2210     var value=selbox.value.substr(2);
2211     this.setFilter(op,value,Rico.ColumnConst.USERFILTER,function() {selbox.selectedIndex=0;});
2212   }
2213 },
2214
2215 filterClear: function(e) {\r
2216   this.filterField.value='';
2217   this.setUnfiltered();\r
2218 },
2219
2220 filterKeypress: function(e) {\r
2221   var txtbox=Rico.eventElement(e);
2222   if (typeof this.lastKeyFilter != 'string') this.lastKeyFilter='';\r
2223   if (this.lastKeyFilter==txtbox.value) return;\r
2224   var v=txtbox.value;\r
2225   Rico.log("filterKeypress: "+this.index+' '+v);\r
2226   this.lastKeyFilter=v;
2227   if (v=='' || v=='*')\r
2228     this.setUnfiltered();\r
2229   else {
2230     this.setFilter('LIKE', v, Rico.ColumnConst.USERFILTER, function() {txtbox.value='';});
2231   }\r
2232 },\r
2233
2234 mFilterSelectClick: function(e) {
2235   Rico.eventStop(e);
2236   if (this.mFilter.style.display!='none') {
2237     this.mFilterFinish(e);
2238     if (Rico.isIE && Rico.ieVersion <= 6) {
2239       this.filterField.focus();
2240     } else {
2241       this.filterField.blur();
2242     }
2243   } else {
2244     var offset=Rico.cumulativeOffset(this.filterField);
2245     this.mFilter.style.top=(offset.top+this.filterField.offsetHeight)+'px';
2246     this.mFilter.style.left=offset.left+'px';
2247     this.mFilter.style.width=Math.min(this.filterField.offsetWidth,parseInt(this.colWidth,10))+'px';
2248     Rico.show(this.mFilter);
2249     this.mFilterFocus.focus();
2250   }
2251 },
2252
2253 mFilterFinish: function(e) {
2254   if (!this.mFilterChange) {
2255     Rico.hide(this.mFilter);
2256     return;
2257   }
2258   if (this.mFilterInputs[0].checked) {
2259     this.mFilterReset();
2260     Rico.hide(this.mFilter);
2261     this.setUnfiltered();
2262     return;
2263   }
2264   var newValues=[];
2265   var newLabels=[];
2266   for (var i=1; i<this.mFilterInputs.length; i++) {
2267     if (this.mFilterInputs[i].checked) {
2268       newValues.push(this.mFilterInputs[i].value)
2269       newLabels.push(this.mFilterLabels[i].innerHTML)
2270     }
2271   }
2272   if (newValues.length > 0) {
2273     var newText=newLabels.join(', ');
2274     this.filterField.options[0].text=newText;
2275     this.filterField.title=newText;
2276     Rico.hide(this.mFilter);
2277     this.mFilterChange=false;
2278     var self=this;
2279     this.setFilter('EQ',newValues,Rico.ColumnConst.USERFILTER,function() { self.mFilterReset(); });
2280   } else {
2281     alert('Please select at least one value');
2282   }
2283 },
2284
2285 mFilterReset: function() {
2286   var newText=this.mFilterLabels[0].innerHTML;  // all
2287   this.filterField.options[0].text=newText;
2288   this.filterField.title=newText;
2289 },
2290
2291 mFilterAllClick: function(e) {
2292   var allChecked=this.mFilterInputs[0].checked;
2293   for (var i=1; i<this.mFilterInputs.length; i++) {
2294     this.mFilterInputs[i].checked=allChecked;
2295   }
2296   this.mFilterChange=true;
2297 },
2298
2299 mFilterOtherClick: function(e) {
2300   this.mFilterInputs[0].checked=false;
2301   this.mFilterChange=true;
2302 },
2303
2304 format_text: function(v) {
2305   if (typeof v!='string')
2306     return '&nbsp;';
2307   else
2308     return v.replace(/&/g, '&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
2309 },
2310
2311 format_number: function(v) {
2312   if (typeof v=='undefined' || v=='' || v==null)
2313     return '&nbsp;';
2314   else
2315     return Rico.formatNumber(v,this.format);
2316 },
2317
2318 format_datetime: function(v) {
2319   if (typeof v=='undefined' || v=='' || v==null)
2320     return '&nbsp;';
2321   else {
2322     var d=Rico.setISO8601(v);
2323     if (!d) return v;
2324     return (this.format.prefix || '')+Rico.formatDate(d,this.format.dateFmt || 'translateDateTime')+(this.format.suffix || '');
2325   }
2326 },
2327
2328 // converts GMT/UTC to local time
2329 format_utcaslocaltime: function(v) {
2330   if (typeof v=='undefined' || v=='' || v==null)
2331     return '&nbsp;';
2332   else {
2333     var tz=new Date();
2334     var d=Rico.setISO8601(v,-tz.getTimezoneOffset());
2335     if (!d) return v;
2336     return (this.format.prefix || '')+Rico.formatDate(d,this.format.dateFmt || 'translateDateTime')+(this.format.suffix || '');
2337   }
2338 },
2339
2340 format_date: function(v) {
2341   if (typeof v=='undefined' || v==null || v=='')
2342     return '&nbsp;';
2343   else {
2344     var d=Rico.setISO8601(v);
2345     if (!d) return v;
2346     return (this.format.prefix || '')+Rico.formatDate(d,this.format.dateFmt || 'translateDate')+(this.format.suffix || '');
2347   }
2348 },
2349
2350 fixHeaders: function(prefix, iconsfirst) {
2351   if (this.sortable) {
2352     var handler=Rico.eventHandle(this,'toggleSort');
2353     switch (this.options.headingSort) {
2354       case 'link':
2355         var a=Rico.wrapChildren(this.hdrCellDiv,'ricoSort',undefined,'a');
2356         a.href = "javascript:void(0)";
2357         Rico.eventBind(a,"click", handler);
2358         break;
2359       case 'hover':
2360         Rico.eventBind(this.hdrCellDiv,"click", handler);
2361         break;
2362     }
2363   }
2364   this.imgFilter = document.createElement('span');
2365   this.imgFilter.style.display='none';
2366   this.imgFilter.className='rico-icon ricoLG_filterCol';
2367   this.imgSort = document.createElement('span');
2368   this.imgSort.style.display='none';
2369   this.imgSort.style.verticalAlign='top';
2370   if (iconsfirst) {
2371     this.hdrCellDiv.insertBefore(this.imgSort,this.hdrCellDiv.firstChild);
2372     this.hdrCellDiv.insertBefore(this.imgFilter,this.hdrCellDiv.firstChild);
2373   } else {
2374     this.hdrCellDiv.appendChild(this.imgFilter);
2375     this.hdrCellDiv.appendChild(this.imgSort);
2376   }
2377   if (!this.format.filterUI) {
2378     Rico.eventBind(this.imgFilter, 'click', Rico.eventHandle(this,'filterClick'), false);
2379   }
2380 },
2381
2382 filterClick: function(e) {
2383   if (this.filterType==Rico.ColumnConst.USERFILTER && this.filterOp=='LIKE') {
2384     this.liveGrid.openKeyword(this.index);
2385   }
2386 },
2387
2388 getValue: function(windowRow) {
2389   return this.buffer.getWindowCell(windowRow,this.index);
2390 },
2391
2392 getBufferStyle: function(windowRow) {
2393   return this.buffer.getWindowStyle(windowRow,this.index);
2394 },
2395
2396 setValue: function(windowRow,newval) {
2397   this.buffer.setWindowValue(windowRow,this.index,newval);
2398 },
2399
2400 _format: function(v) {
2401   return v;
2402 },
2403
2404 _display: function(v,gridCell) {
2405   gridCell.innerHTML=this._format(v);
2406 },
2407
2408 _export: function(v) {
2409   return this._format(v);
2410 },
2411
2412 exportBuffer: function(bufRow) {
2413   return this._export(this.buffer.getValue(bufRow,this.index));
2414 },
2415
2416 displayValue: function(windowRow) {
2417   var bufval=this.getValue(windowRow);
2418   if (bufval==null) {
2419     this.clearCell(windowRow);
2420     return;
2421   }
2422   var gridCell=this.cell(windowRow);
2423   this._display(bufval,gridCell,windowRow);
2424   if (this.buffer.options.acceptStyle) {
2425     gridCell.style.cssText=this.getBufferStyle(windowRow);
2426   }
2427 }
2428
2429 };