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