Updated LoadRicoClient for asp and php, so all asp and php examples are working again...
[infodrom/rico3] / minsrc / ricoLiveGrid.js
1 /*
2  *  (c) 2005-2011 Richard Cowin (http://openrico.org)
3  *  (c) 2005-2011 Matt Brown (http://dowdybrown.com)
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
6  *  file except in compliance with the License. You may obtain a copy of the License at
7  *
8  *         http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *  Unless required by applicable law or agreed to in writing, software distributed under the
11  *  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
12  *  either express or implied. See the License for the specific language governing permissions
13  *  and limitations under the License.
14  */
15
16 /** @namespace */
17 if (!Rico.Buffer) Rico.Buffer = {};
18
19 Rico.Buffer.Base = function(dataTable, options) {
20   this.initialize(dataTable, options);
21 }
22 /** @lends Rico.Buffer.Base# */
23 Rico.Buffer.Base.prototype = {
24 /**
25  * @class Defines the static buffer class (no AJAX).
26  * Loads buffer with data that already exists in the document as an HTML table or passed via javascript.
27  * Also serves as a base class for AJAX-enabled buffers.
28  * @constructs
29  */
30   initialize: function(dataTable, options) {
31     this.clear();
32     this.updateInProgress = false;
33     this.lastOffset = 0;
34     this.rcvdRowCount = false;  // true if an eof element was included in the last response
35     this.foundRowCount = false; // true if a response is ever received with eof true
36     this.totalRows = 0;
37     this.rowcntContent = "";
38     this.rcvdOffset = -1;
39     this.options = {
40       fixedHdrRows     : 0,
41       canFilter        : true,  // does buffer object support filtering?
42       isEncoded        : true,  // is the data received via ajax html encoded?
43       acceptStyle      : false, // copy style from original/ajax data?
44       canRefresh       : false  // should "refresh" be shown on filter menu?
45     };
46     Rico.extend(this.options, options || {});
47     if (dataTable) {
48       this.loadRowsFromTable(dataTable,this.options.fixedHdrRows);
49       dataTable.parentNode.removeChild(dataTable);  // delete the data once it has been loaded
50     } else {
51       this.clear();
52     }
53   },
54
55   registerGrid: function(liveGrid) {
56     this.liveGrid = liveGrid;
57   },
58
59   setTotalRows: function( newTotalRows ) {
60     if (typeof(newTotalRows)!='number') newTotalRows=this.size;
61     if (this.totalRows == newTotalRows) return;
62     this.totalRows = newTotalRows;
63     if (!this.liveGrid) return;
64     Rico.log("setTotalRows, newTotalRows="+newTotalRows);
65     switch (this.liveGrid.sizeTo) {
66       case 'data':
67         this.liveGrid.resizeWindow();
68         break;
69       case 'datamax':
70         this.liveGrid.setPageSize(newTotalRows);
71         break;
72       default:
73         this.liveGrid.updateHeightDiv();
74         break;
75     }
76   },
77
78   loadRowsFromTable: function(tableElement,firstRow) {
79     var newRows = [];
80     var trs = tableElement.getElementsByTagName("tr");
81     for ( var i=firstRow || 0; i < trs.length; i++ ) {
82       var row = [];
83       var cells = trs[i].getElementsByTagName("td");
84       for ( var j=0; j < cells.length ; j++ )
85         row[j]=cells[j].innerHTML;
86       newRows.push( row );
87     }
88     this.loadRows(newRows);
89   },
90
91   loadRowsFromArray: function(array2D) {
92     for ( var i=0; i < array2D.length; i++ ) {
93       for ( var j=0; j < array2D[i].length ; j++ ) {
94         array2D[i][j]=array2D[i][j].toString();
95       }
96     }
97     this.loadRows(array2D);
98   },
99
100   loadRows: function(jstable) {
101     this.baseRows = jstable;
102     this.startPos = 0;
103     this.size = this.baseRows.length;
104   },
105
106   dom2jstable: function(rowsElement) {
107     Rico.log('dom2jstable: encoded='+this.options.isEncoded);
108     var newRows = [];
109     var trs = rowsElement.getElementsByTagName("tr");
110     for ( var i=0; i < trs.length; i++ ) {
111       var row = [];
112       var cells = trs[i].getElementsByTagName("td");
113       for ( var j=0; j < cells.length ; j++ )
114         row[j]=Rico.getContentAsString(cells[j],this.options.isEncoded);
115       newRows.push( row );
116     }
117     return newRows;
118   },
119
120   _blankRow: function() {
121     var newRow=[];
122     for (var i=0; i<this.liveGrid.columns.length; i++) {
123       newRow[i]='';
124     }
125     return newRow;
126   },
127
128   deleteRows: function(rowIndex,cnt) {
129     this.baseRows.splice(rowIndex,typeof(cnt)=='number' ? cnt : 1);
130     this.liveGrid.isPartialBlank=true;
131     this.size=this.baseRows.length;
132   },
133
134   insertRow: function(beforeRowIndex) {
135     var r=this._blankRow();
136     this.baseRows.splice(beforeRowIndex,0,r);
137     this.size=this.baseRows.length;
138     this.liveGrid.isPartialBlank=true;
139     if (this.startPos < 0) this.startPos=0;
140     return r;
141   },
142
143   appendRows: function(cnt) {
144     var newRows=[];
145     for (var i=0; i<cnt; i++) {
146       var r=this._blankRow();
147       this.baseRows.push(r);
148       newRows.push(r);
149     }
150     this.size=this.baseRows.length;
151     this.liveGrid.isPartialBlank=true;
152     if (this.startPos < 0) this.startPos=0;
153     return newRows;
154   },
155   
156   sortFunc: function(coltype) {
157     var self=this;
158     switch (coltype) {
159       case 'number': return function(a,b) { return self._sortNumeric(a,b); };
160       case 'control':return function(a,b) { return self._sortControl(a,b); };
161       default:       return function(a,b) { return self._sortAlpha(a,b); };
162     }
163   },
164
165   sortBuffer: function(colnum) {
166     if (!this.baseRows) {
167       this.delayedSortCol=colnum;
168       return;
169     }
170     this.liveGrid.showMsg(Rico.getPhraseById("sorting"));
171     this.sortColumn=colnum;
172     var col=this.liveGrid.columns[colnum];
173     this.getValFunc=col._sortfunc;
174     this.baseRows.sort(this.sortFunc(col.format.type));
175     if (col.getSortDirection()=='DESC') this.baseRows.reverse();
176   },
177   
178   _sortAlpha: function(a,b) {
179     var aa = this.sortColumn<a.length ? Rico.getInnerText(a[this.sortColumn]) : '';
180     var bb = this.sortColumn<b.length ? Rico.getInnerText(b[this.sortColumn]) : '';
181     if (aa==bb) return 0;
182     if (aa<bb) return -1;
183     return 1;
184   },
185
186   _sortNumeric: function(a,b) {
187     var aa = this.sortColumn<a.length ? this.nan2zero(Rico.getInnerText(a[this.sortColumn])) : 0;
188     var bb = this.sortColumn<b.length ? this.nan2zero(Rico.getInnerText(b[this.sortColumn])) : 0;
189     return aa-bb;
190   },
191
192   nan2zero: function(n) {
193     if (typeof(n)=='string') n=parseFloat(n);
194     return isNaN(n) || typeof(n)=='undefined' ? 0 : n;
195   },
196   
197   _sortControl: function(a,b) {
198     var aa = this.sortColumn<a.length ? Rico.getInnerText(a[this.sortColumn]) : '';
199     var bb = this.sortColumn<b.length ? Rico.getInnerText(b[this.sortColumn]) : '';
200     if (this.getValFunc) {
201       aa=this.getValFunc(aa);
202       bb=this.getValFunc(bb);
203     }
204     if (aa==bb) return 0;
205     if (aa<bb) return -1;
206     return 1;
207   },
208
209   clear: function() {
210     this.baseRows = [];
211     this.rows = [];
212     this.startPos = -1;
213     this.size = 0;
214     this.windowPos = 0;
215   },
216
217   isInRange: function(position) {
218     var lastRow=Math.min(this.totalRows, position + this.liveGrid.pageSize);
219     return (position >= this.startPos) && (lastRow <= this.endPos()); // && (this.size != 0);
220   },
221
222   endPos: function() {
223     return this.startPos + this.rows.length;
224   },
225
226   fetch: function(offset) {
227     Rico.log('fetch '+this.liveGrid.tableId+': offset='+offset);
228     this.applyFilters();
229     this.setTotalRows();
230     this.rcvdRowCount = true;
231     this.foundRowCount = true;
232     if (offset < 0) offset=0;
233     this.liveGrid.refreshContents(offset);
234     return;
235   },
236
237 /**
238  * @return a 2D array of buffer data representing the rows that are currently visible on the grid
239  */
240   visibleRows: function() {
241     return this.rows.slice(this.windowStart,this.windowEnd);
242   },
243
244   setWindow: function(startrow, endrow) {
245     this.windowStart = startrow - this.startPos;  // position in the buffer of first visible row
246     Rico.log('setWindow '+this.liveGrid.tableId+': '+startrow+', '+endrow+', newstart='+this.windowStart);
247     this.windowEnd = Math.min(endrow,this.size);  // position in the buffer of last visible row containing data+1
248     this.windowPos = startrow;                    // position in the dataset of first visible row
249   },
250
251 /**
252  * @return true if bufRow is currently visible in the grid
253  */
254   isVisible: function(bufRow) {
255     return bufRow < this.rows.length && bufRow >= this.windowStart && bufRow < this.windowEnd;
256   },
257   
258 /**
259  * takes a window row index and returns the corresponding buffer row index
260  */
261   bufferRow: function(windowRow) {
262     return this.windowStart+windowRow;
263   },
264
265 /**
266  * @return buffer cell at the specified visible row/col index
267  */
268   getWindowCell: function(windowRow,col) {
269     var bufrow=this.bufferRow(windowRow);
270     return this.isVisible(bufrow) && col < this.rows[bufrow].length ? this.rows[bufrow][col] : null;
271   },
272
273   getWindowStyle: function(windowRow,col) {
274     var bufrow=this.bufferRow(windowRow);
275     return this.attr && this.isVisible(bufrow) && this.attr[bufrow] && col < this.attr[bufrow].length ? this.attr[bufrow][col] : '';
276   },
277
278   getWindowValue: function(windowRow,col) {
279     return this.getWindowCell(windowRow,col);
280   },
281
282   setWindowValue: function(windowRow,col,newval) {
283     var bufrow=this.bufferRow(windowRow);
284     if (bufrow >= this.windowEnd) return false;
285     return this.setValue(bufrow,col,newval);
286   },
287
288   getCell: function(bufRow,col) {
289     return bufRow < this.size ? this.rows[bufRow][col] : null;
290   },
291
292   getValue: function(bufRow,col) {
293     return this.getCell(bufRow,col);
294   },
295
296   setValue: function(bufRow,col,newval,newstyle) {
297     if (bufRow>=this.size) return false;
298     if (!this.rows[bufRow][col]) this.rows[bufRow][col]={};
299     this.rows[bufRow][col]=newval;
300     if (typeof newstyle=='string') this.rows[bufRow][col]._style=newstyle;
301     this.rows[bufRow][col].modified=true;
302     return true;
303   },
304
305   getRows: function(start, count) {
306     var begPos = start - this.startPos;
307     var endPos = Math.min(begPos + count,this.size);
308     var results = [];
309     for ( var i=begPos; i < endPos; i++ ) {
310       results.push(this.rows[i]);
311     }
312     return results;
313   },
314
315   applyFilters: function() {
316     var newRows=[],re=[];
317     var r,c,n,i,showRow,filtercnt;
318     var cols=this.liveGrid.columns;
319     for (n=0,filtercnt=0; n<cols.length; n++) {
320       c=cols[n];
321       if (c.filterType == Rico.ColumnConst.UNFILTERED) continue;
322       filtercnt++;
323       if (c.filterOp=='LIKE') re[n]=new RegExp(c.filterValues[0],'i');
324     }
325     Rico.log('applyFilters: # of filters='+filtercnt);
326     if (filtercnt==0) {
327       this.rows = this.baseRows;
328     } else {
329       for (r=0; r<this.baseRows.length; r++) {
330         showRow=true;
331         for (n=0; n<cols.length && showRow; n++) {
332           c=cols[n];
333           if (c.filterType == Rico.ColumnConst.UNFILTERED) continue;
334           switch (c.filterOp) {
335             case 'LIKE':
336               showRow=re[n].test(this.baseRows[r][n]);
337               break;
338             case 'EQ':
339               showRow=this.baseRows[r][n]==c.filterValues[0];
340               break;
341             case 'NE':
342               for (i=0; i<c.filterValues.length && showRow; i++)
343                 showRow=this.baseRows[r][n]!=c.filterValues[i];
344               break;
345             case 'LE':
346               if (c.format.type=='number')
347                 showRow=this.nan2zero(this.baseRows[r][n])<=this.nan2zero(c.filterValues[0]);
348               else
349                 showRow=this.baseRows[r][n]<=c.filterValues[0];
350               break;
351             case 'GE':
352               if (c.format.type=='number')
353                 showRow=this.nan2zero(this.baseRows[r][n])>=this.nan2zero(c.filterValues[0]);
354               else
355                 showRow=this.baseRows[r][n]>=c.filterValues[0];
356               break;
357             case 'NULL':
358               showRow=this.baseRows[r][n]=='';
359               break;
360             case 'NOTNULL':
361               showRow=this.baseRows[r][n]!='';
362               break;
363           }
364         }
365         if (showRow) newRows.push(this.baseRows[r]);
366       }
367       this.rows = newRows;
368     }
369     this.rowcntContent = this.size = this.rows.length;
370   },
371
372   printAll: function() {
373     this.liveGrid.showMsg(Rico.getPhraseById('exportInProgress'));
374     Rico.runLater(10,this,'_printAll');  // allow message to paint
375   },
376
377 /**
378  * Support function for printAll()
379  */
380   _printAll: function() {
381     this.liveGrid.exportStart();
382     this.exportBuffer(this.getRows(0,this.totalRows));
383     this.liveGrid.exportFinish();
384   },
385
386 /**
387  * Copies visible rows to a new window as a simple html table.
388  */
389   printVisible: function() {
390     this.liveGrid.showMsg(Rico.getPhraseById('exportInProgress'));
391     Rico.runLater(10,this,'_printVisible');  // allow message to paint
392   },
393
394   _printVisible: function() {
395     this.liveGrid.exportStart();
396     this.exportBuffer(this.visibleRows());
397     this.liveGrid.exportFinish();
398   },
399
400 /**
401  * Send all rows to print/export window
402  */
403   exportBuffer: function(rows,startPos) {
404     var r,c,v,col,exportText;
405     Rico.log("exportBuffer: "+rows.length+" rows");
406     var exportStyles=this.liveGrid.getExportStyles(this.liveGrid.tbody[0]);
407     var tdstyle=[];
408     var totalcnt=startPos || 0;
409     var cols=this.liveGrid.columns;
410     for (c=0; c<cols.length; c++) {
411       if (cols[c].visible) tdstyle[c]=this.liveGrid.exportStyle(cols[c].cell(0),exportStyles);  // assumes row 0 style applies to all rows
412     }
413     for(r=0; r < rows.length; r++) {
414       exportText='';
415       for (c=0; c<cols.length; c++) {
416         if (!cols[c].visible) continue;
417         col=cols[c];
418         col.expStyle=tdstyle[c];
419         v=col._export(rows[r][c],rows[r]);
420         if (v=='') v='&nbsp;';
421         exportText+="<td style='"+col.expStyle+"'>"+v+"</td>";
422       }
423       this.liveGrid.exportRows.push(exportText);
424       totalcnt++;
425       if (totalcnt % 10 == 0) window.status=Rico.getPhraseById('exportStatus',totalcnt);
426     }
427   }
428
429 };
430
431
432 // Rico.LiveGrid -----------------------------------------------------
433
434 Rico.LiveGrid = function(tableId, buffer, options) {
435   this.initialize(tableId, buffer, options);
436 }
437
438 /** 
439  * @lends Rico.LiveGrid#
440  * @property tableId id string for this grid
441  * @property options the options object passed to the constructor extended with defaults
442  * @property buffer the buffer object containing the data for this grid
443  * @property columns array of {@link Rico.LiveGridColumn} objects
444  */
445 Rico.LiveGrid.prototype = {
446 /**
447  * @class Buffered LiveGrid component
448  * @extends Rico.GridCommon
449  * @constructs
450  */
451   initialize: function( tableId, buffer, options ) {
452     Rico.extend(this, Rico.GridCommon);
453     Rico.extend(this, Rico.LiveGridMethods);
454     this.baseInit();
455     this.tableId = tableId;
456     this.buffer = buffer;
457     this.actionId='_action_'+tableId;
458     Rico.setDebugArea(tableId+"_debugmsgs");    // if used, this should be a textarea
459
460     Rico.extend(this.options, {
461       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)
462       frozenColumns    : 0,
463       offset           : 0,     // first row to be displayed
464       prefetchBuffer   : true,  // load table on page load?
465       minPageRows      : 2,
466       maxPageRows      : 50,
467       canSortDefault   : true,  // can be overridden in the column specs
468       canFilterDefault : buffer.options.canFilter, // can be overridden in the column specs
469       canHideDefault   : true,  // can be overridden in the column specs
470
471       // highlight & selection parameters
472       highlightElem    : 'none',// what gets highlighted/selected (cursorRow, cursorCell, menuRow, menuCell, selection, or none)
473       highlightSection : 3,     // which section gets highlighted (frozen=1, scrolling=2, all=3, none=0)
474       highlightMethod  : 'class', // outline, class, both (outline is less CPU intensive on the client)
475       highlightClass   : Rico.theme.gridHighlightClass || 'ricoLG_selection',
476
477       // export/print parameters
478       maxPrint         : 5000,  // max # of rows that can be printed/exported, 0=disable print/export feature
479
480       // heading parameters
481       headingSort      : 'link', // link: make headings a link that will sort column, hover: make headings a hoverset, none: events on headings are disabled
482       hdrIconsFirst    : true    // true: put sort & filter icons before header text, false: after
483     });
484     // other options:
485     //   sortCol: initial sort column
486
487     var self=this;
488     this.options.sortHandler = function() { self.sortHandler(); };
489     this.options.filterHandler = function() { self.filterHandler(); };
490     this.options.onRefreshComplete = function(firstrow,lastrow) { self.bookmarkHandler(firstrow,lastrow); };
491     this.options.rowOverHandler = Rico.eventHandle(this,'rowMouseOver');
492     this.options.mouseDownHandler = Rico.eventHandle(this,'selectMouseDown');
493     this.options.mouseOverHandler = Rico.eventHandle(this,'selectMouseOver');
494     this.options.mouseUpHandler  = Rico.eventHandle(this,'selectMouseUp');
495     Rico.extend(this.options, options || {});
496
497     switch (typeof this.options.visibleRows) {
498       case 'string':
499         this.sizeTo=this.options.visibleRows;
500         switch (this.options.visibleRows) {
501           case 'data':   this.options.visibleRows=-2; break;
502           case 'body':   this.options.visibleRows=-3; break;
503           case 'parent': this.options.visibleRows=-4; break;
504           case 'datamax':this.options.visibleRows=-5; break;
505           default:       this.options.visibleRows=-1; break;
506         }
507         break;
508       case 'number':
509         switch (this.options.visibleRows) {
510           case -1: this.sizeTo='window'; break;
511           case -2: this.sizeTo='data'; break;
512           case -3: this.sizeTo='body'; break;
513           case -4: this.sizeTo='parent'; break;
514           case -5: this.sizeTo='datamax'; break;
515           default: this.sizeTo='fixed'; break;
516         }
517         break;
518       default:
519         this.sizeTo='body';
520         this.options.visibleRows=-3;
521         break;
522     }
523     this.highlightEnabled=this.options.highlightSection>0;
524     this.pageSize=0;
525     this.createTables();
526     if (this.headerColCnt==0) {
527       alert('ERROR: no columns found in "'+this.tableId+'"');
528       return;
529     }
530     this.createColumnArray('LiveGridColumn');
531     if (this.options.headingSort=='hover')
532       this.createHoverSet();
533
534     this.bookmark=document.getElementById(this.tableId+"_bookmark");
535     this.sizeDivs();
536     var filterUIrow=-1;
537     if (this.buffer.options.canFilter && this.options.AutoFilter)
538       filterUIrow=this.addHeadingRow('ricoLG_FilterRow');
539     this.createDataCells(this.options.visibleRows);
540     if (this.pageSize == 0) return;
541     this.buffer.registerGrid(this);
542     if (this.buffer.setBufferSize) this.buffer.setBufferSize(this.pageSize);
543     this.scrollTimeout = null;
544     this.lastScrollPos = 0;
545     this.attachMenuEvents();
546
547     this.setSortUI( this.options.sortCol, this.options.sortDir );
548     this.setImages();
549     if (this.listInvisible().length==this.columns.length)
550       this.columns[0].showColumn();
551     this.sizeDivs();
552     this.scrollDiv.style.display="";
553     if (this.buffer.totalRows>0)
554       this.updateHeightDiv();
555     if (this.options.prefetchBuffer) {
556       if (this.bookmark) this.bookmark.innerHTML = Rico.getPhraseById('bookmarkLoading');
557       if (this.options.canFilterDefault && this.options.getQueryParms)
558         this.checkForFilterParms();
559       this.scrollToRow(this.options.offset);
560       this.buffer.fetch(this.options.offset);
561     }
562     if (filterUIrow >= 0)
563       this.createFilters(filterUIrow);
564     this.scrollEventFunc=Rico.eventHandle(this,'handleScroll');
565     this.wheelEventFunc=Rico.eventHandle(this,'handleWheel');
566     this.wheelEvent=(Rico.isIE || Rico.isOpera || Rico.isWebKit) ? 'mousewheel' : 'DOMMouseScroll';
567     if (this.options.offset && this.options.offset < this.buffer.totalRows)
568       Rico.runLater(50,this,'scrollToRow',this.options.offset);  // Safari requires a delay
569     this.pluginScroll();
570     this.setHorizontalScroll();
571     Rico.log("setHorizontalScroll done");
572     if (this.options.windowResize)
573       Rico.runLater(100,this,'pluginWindowResize');
574     Rico.log("initialize complete for "+this.tableId);
575     //alert('clientLeft='+this.scrollDiv.clientLeft);
576     if (this.direction=='rtl' && (!Rico.isWebKit || this.scrollDiv.clientLeft > 0)) {
577       this.scrollTab.style.right='0px';
578     } else {
579       this.scrollTab.style.left='0px';
580       Rico.setStyle(this.tabs[1], {'float': 'left'});
581     }
582   }
583 };
584
585
586 Rico.LiveGridMethods = {
587 /** @lends Rico.LiveGrid# */
588
589   createHoverSet: function() {
590     var hdrs=[];
591     for( var c=0; c < this.headerColCnt; c++ ) {
592       if (this.columns[c].sortable) {\r
593         hdrs.push(this.columns[c].hdrCellDiv);
594       }
595     }
596     this.hoverSet = new Rico.HoverSet(hdrs);
597   },
598
599   checkForFilterParms: function() {
600     var s=window.location.search;
601     if (s.charAt(0)=='?') s=s.substring(1);
602     var pairs = s.split('&');
603     for (var i=0; i<pairs.length; i++) {
604       if (pairs[i].match(/^f\[\d+\]/)) {
605         this.buffer.options.requestParameters.push(pairs[i]);
606       }
607     }
608   },
609
610 /**
611  * Refreshes a detail grid from a master grid
612  * @returns row index on master table on success, -1 otherwise
613  */
614   drillDown: function(e,masterColNum,detailColNum) {
615     var cell=Rico.eventElement(e || window.event);
616     cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
617     if (!cell) return -1;
618     var idx=this.winCellIndex(cell);
619     if (idx.row >= this.buffer.totalRows) return -1
620     this.unhighlight();
621     this.menuIdx=idx;  // ensures selection gets cleared when menu is displayed
622     this.highlight(idx);
623     var drillValue=this.buffer.getWindowCell(idx.row,masterColNum);
624     for (var i=3; i<arguments.length; i++)
625       arguments[i].setDetailFilter(detailColNum,drillValue);
626     return idx.row;
627   },
628
629 /**
630  * set filter on a detail grid that is in a master-detail relationship
631  */
632   setDetailFilter: function(colNumber,filterValue) {
633     var c=this.columns[colNumber];
634     c.format.ColData=filterValue;
635     c.setSystemFilter('EQ',filterValue);
636   },
637
638 /**
639  * Create one table for frozen columns and one for scrolling columns.
640  * Also create div's to contain them.
641  * @returns true on success
642  */
643   createTables: function() {
644     var insertloc,hdrSrc,i;
645     var table = document.getElementById(this.tableId) || document.getElementById(this.tableId+'_outerDiv');
646     if (!table) return false;
647     if (table.tagName.toLowerCase()=='table') {
648       var theads=table.getElementsByTagName("thead");
649       if (theads.length == 1) {
650         Rico.log("createTables: using thead section, id="+this.tableId);
651         if (this.options.ColGroupsOnTabHdr && this.options.ColGroups) {
652           var r=theads[0].insertRow(0);
653           this.insertPanelNames(r, 0, this.options.frozenColumns, 'ricoFrozen');
654           this.insertPanelNames(r, this.options.frozenColumns, this.options.columnSpecs.length);
655         }
656         hdrSrc=theads[0].rows;
657       } else {
658         Rico.log("createTables: using tbody section, id="+this.tableId);
659         hdrSrc=new Array(table.rows[0]);
660       }
661       insertloc=table;
662     } else if (this.options.columnSpecs.length > 0) {
663       if (!table.id.match(/_outerDiv$/)) insertloc=table;
664       Rico.log("createTables: inserting at "+table.tagName+", id="+this.tableId);
665     } else {
666       alert("ERROR!\n\nUnable to initialize '"+this.tableId+"'\n\nLiveGrid terminated");
667       return false;
668     }
669
670     this.createDivs();
671     this.scrollContainer = this.createDiv("scrollContainer",this.structTabLR);
672     this.scrollContainer.appendChild(this.scrollDiv); // move scrollDiv
673     this.scrollTab = this.createDiv("scrollTab",this.scrollContainer);
674     this.shadowDiv  = this.createDiv("shadow",this.scrollDiv);
675     this.shadowDiv.style.direction='ltr';  // avoid FF bug
676     this.scrollDiv.style.display="none";
677     this.scrollDiv.scrollTop=0;
678     if (this.options.highlightMethod!='class') {
679       this.highlightDiv=[];
680       switch (this.options.highlightElem) {
681         case 'menuRow':
682         case 'cursorRow':
683           this.highlightDiv[0] = this.createDiv("highlight",this.outerDiv);
684           this.highlightDiv[0].style.display="none";
685           break;
686         case 'menuCell':
687         case 'cursorCell':
688           for (i=0; i<2; i++) {
689             this.highlightDiv[i] = this.createDiv("highlight",i==0 ? this.frozenTabs : this.scrollTab);
690             this.highlightDiv[i].style.display="none";
691             this.highlightDiv[i].id+=i;
692           }
693           break;
694         case 'selection':
695           // create one div for each side of the rectangle
696           var parentDiv=this.options.highlightSection==1 ? this.frozenTabs : this.scrollTab;
697           for (i=0; i<4; i++) {
698             this.highlightDiv[i] = this.createDiv("highlight",parentDiv);
699             this.highlightDiv[i].style.display="none";
700             this.highlightDiv[i].style.overflow="hidden";
701             this.highlightDiv[i].id+=i;
702             this.highlightDiv[i].style[i % 2==0 ? 'height' : 'width']="0px";
703           }
704           break;
705       }
706     }
707
708     // create new tables
709     for (i=0; i<3; i++) {
710       this.tabs[i] = document.createElement("table");
711       this.tabs[i].className = (i < 2) ? 'ricoLG_table' : 'ricoLG_scrollTab';
712       this.tabs[i].border=0;
713       this.tabs[i].cellPadding=0;
714       this.tabs[i].cellSpacing=0;
715       this.tabs[i].id = this.tableId+"_tab"+i;
716     }
717     // set headings
718     for (i=0; i<2; i++) {
719       this.thead[i]=this.tabs[i].createTHead();
720       //Rico.addClass(this.tabs[i],'ricoLG_top');
721       this.thead[i].className='ricoLG_top';
722       if (Rico.theme.gridheader) Rico.addClass(this.thead[i],Rico.theme.gridheader);
723     }
724     // set bodies
725     for (i=0; i<2; i++) {
726       this.tbody[i]=Rico.getTBody(this.tabs[i==0?0:2]);
727       this.tbody[i].className='ricoLG_bottom';
728       if (Rico.theme.gridcontent) Rico.addClass(this.tbody[i],Rico.theme.gridcontent);
729       this.tbody[i].insertRow(-1);
730     }
731     this.frozenTabs.appendChild(this.tabs[0]);
732     this.innerDiv.appendChild(this.tabs[1]);
733     this.scrollTab.appendChild(this.tabs[2]);
734     if (insertloc) insertloc.parentNode.insertBefore(this.outerDiv,insertloc);
735     if (hdrSrc) {
736       this.headerColCnt = this.getColumnInfo(hdrSrc);
737       this.loadHdrSrc(hdrSrc);
738     } else {
739       this.createHdr(0,0,this.options.frozenColumns);
740       this.createHdr(1,this.options.frozenColumns,this.options.columnSpecs.length);
741       if (this.options.ColGroupsOnTabHdr && this.options.ColGroups) {
742         this.insertPanelNames(this.thead[0].insertRow(0), 0, this.options.frozenColumns);
743         this.insertPanelNames(this.thead[1].insertRow(0), this.options.frozenColumns, this.options.columnSpecs.length);
744       }
745       for (i=0; i<2; i++)
746         this.headerColCnt = this.getColumnInfo(this.thead[i].rows);
747     }
748     for( var c=0; c < this.headerColCnt; c++ )
749       this.tbody[c<this.options.frozenColumns ? 0 : 1].rows[0].insertCell(-1);
750     if (insertloc) table.parentNode.removeChild(table);
751     Rico.log('createTables end');
752     return true;
753   },
754
755   createDataCells: function(visibleRows) {
756     if (visibleRows < 0) {
757       for (var i=0; i<this.options.minPageRows; i++)
758         this.appendBlankRow();
759       this.sizeDivs();
760       this.autoAppendRows(this.remainingHt());
761     } else {
762       for( var r=0; r < visibleRows; r++ )
763         this.appendBlankRow();
764     }
765     var s=this.options.highlightSection;
766     if (s & 1) this.attachHighlightEvents(this.tbody[0]);
767     if (s & 2) this.attachHighlightEvents(this.tbody[1]);
768   },
769
770 /**
771  * @param colnum column number
772  * @return id string for a filter element
773  */
774   filterId: function(colnum) {
775     return 'RicoFilter_'+this.tableId+'_'+colnum;
776   },
777
778 /**
779  * Create filter elements in heading
780  * Reads this.columns[].filterUI to determine type of filter element for each column (t=text box, s=select list, c=custom)
781  * @param r heading row where filter elements will be placed
782  */
783   createFilters: function(r) {
784     for( var c=0; c < this.headerColCnt; c++ ) {
785       var col=this.columns[c];
786       var fmt=col.format;
787       if (typeof fmt.filterUI!='string') continue;
788       var cell=this.hdrCells[r][c].cell;
789       var field,name=this.filterId(c);\r
790       var divs=cell.getElementsByTagName('div');
791       // copy text alignment from data cell
792       var align=Rico.getStyle(this.cell(0,c),'textAlign');
793       divs[1].style.textAlign=align;
794       switch (fmt.filterUI.charAt(0)) {
795         case 't':
796           // text field
797           field=Rico.createFormField(divs[1],'input',Rico.inputtypes.search ? 'search' : 'text',name,name);
798           var size=fmt.filterUI.match(/\d+/);
799           field.maxLength=fmt.Length || 50;\r
800           field.size=size ? parseInt(size,10) : 10;
801           if (field.type != 'search') divs[1].appendChild(Rico.clearButton(Rico.eventHandle(col,'filterClear')));
802           if (col.filterType==Rico.ColumnConst.USERFILTER && col.filterOp=='LIKE') {
803             var v=col.filterValues[0];
804             if (v.charAt(0)=='*') v=v.substr(1);
805             if (v.slice(-1)=='*') v=v.slice(0,-1);
806             field.value=v;
807             col.lastKeyFilter=v;
808           }
809           Rico.eventBind(field,'keyup',Rico.eventHandle(col,'filterKeypress'),false);
810           col.filterField=field;\r
811           break;\r
812         case 'm':
813           // multi-select
814         case 's':
815           // drop-down select
816           field=Rico.createFormField(divs[1],'select',null,name);\r
817           Rico.addSelectOption(field,this.options.FilterAllToken,Rico.getPhraseById("filterAll"));\r
818           col.filterField=field;
819           var options={};\r
820           Rico.extend(options, this.buffer.ajaxOptions);
821           var colnum=typeof(fmt.filterCol)=='number' ? fmt.filterCol : c;
822           options.parameters = {id: this.tableId, distinct:colnum};
823           options.parameters[this.actionId]="query";
824           options.onComplete = this.filterValuesUpdateFunc(c);
825           new Rico.ajaxRequest(this.buffer.dataSource, options);
826           break;\r
827         case 'c':
828           // custom
829           if (typeof col._createFilters == 'function')
830             col._createFilters(divs[1], name);
831           break;
832       }
833     }
834     this.initFilterImage(r);
835   },
836   
837   filterValuesUpdateFunc: function(colnum) {
838     var self=this;
839     return function (request) { self.filterValuesUpdate(colnum,request); };
840   },
841
842 /**
843  * update select list filter with values in AJAX response
844  * @returns true on success
845  */
846   filterValuesUpdate: function(colnum,request) {
847     var response = request.responseXML.getElementsByTagName("ajax-response");
848     Rico.log("filterValuesUpdate: "+request.status);
849     if (response == null || response.length != 1) return false;
850     response=response[0];
851     var error = response.getElementsByTagName('error');
852     if (error.length > 0) {
853       Rico.log("Data provider returned an error:\n"+Rico.getContentAsString(error[0],this.buffer.isEncoded));
854       alert(Rico.getPhraseById("requestError",Rico.getContentAsString(error[0],this.buffer.isEncoded)));
855       return false;
856     }\r
857     response=response.getElementsByTagName('response')[0];\r
858     var rowsElement = response.getElementsByTagName('rows')[0];\r
859     var col=this.columns[parseInt(colnum,10)];
860     var rows = this.buffer.dom2jstable(rowsElement);\r
861     var c,opt,v;
862     if (col.filterType==Rico.ColumnConst.USERFILTER && col.filterOp=='EQ') v=col.filterValues[0];
863     Rico.log('filterValuesUpdate: col='+colnum+' rows='+rows.length);
864     switch (col.format.filterUI.charAt(0)) {
865       case 'm':
866         // multi-select
867         col.mFilter = document.body.appendChild(document.createElement("div"));
868         col.mFilter.className = 'ricoLG_mFilter'
869         Rico.hide(col.mFilter);
870         var contentDiv = col.mFilter.appendChild(document.createElement("div"));
871         contentDiv.className = 'ricoLG_mFilter_content'
872         var buttonDiv = col.mFilter.appendChild(document.createElement("div"));
873         buttonDiv.className = 'ricoLG_mFilter_button'
874         col.mFilterButton=buttonDiv.appendChild(document.createElement("button"));
875         col.mFilterButton.innerHTML=Rico.getPhraseById("apply");
876         var eventName=Rico.isWebKit ? 'mousedown' : 'click';
877         Rico.eventBind(col.filterField,eventName,Rico.eventHandle(col,'mFilterSelectClick'));
878         Rico.eventBind(col.mFilterButton,'click',Rico.eventHandle(col,'mFilterFinish'));
879         //col.filterField.options[0].text=$('AllLabel').innerHTML;
880         tab = contentDiv.appendChild(document.createElement("table"));
881         tab.border=0;
882         tab.cellPadding=2;
883         tab.cellSpacing=0;
884         //tbody=(tab.tBodies.length==0) ? tab.appendChild(document.createElement("tbody")) : tab.tBodies[0];
885         var baseId=this.filterId(colnum)+'_';
886         this.createMFilterItem(tab,this.options.FilterAllToken,Rico.getPhraseById("filterAll"),baseId+'all',Rico.eventHandle(col,'mFilterAllClick'));
887         var handle=Rico.eventHandle(col,'mFilterOtherClick')
888         for (var i=0; i<rows.length; i++) {
889           if (rows[i].length>0) {
890             c=rows[i][0];
891             this.createMFilterItem(tab,c,c || Rico.getPhraseById("filterBlank"),baseId+i,handle);
892           }
893         }
894         col.mFilterInputs=contentDiv.getElementsByTagName('input');
895         col.mFilterLabels=contentDiv.getElementsByTagName('label');
896         col.mFilterFocus=col.mFilterInputs.length ? col.mFilterInputs[0] : col.mFilterButton;
897         break;
898
899       case 's':
900         // drop-down select
901         for (var i=0; i<rows.length; i++) {
902           if (rows[i].length>0) {
903             c=rows[i][0];
904             opt=Rico.addSelectOption(col.filterField,c,c || Rico.getPhraseById("filterBlank"));
905             if (col.filterType==Rico.ColumnConst.USERFILTER && c==v) opt.selected=true;
906           }
907         }
908         Rico.eventBind(col.filterField,'change',Rico.eventHandle(col,'filterChange'));
909         break;
910     }
911     return true;\r
912   },
913   
914   createMFilterItem: function(table,code,description,id,eventHandle) {
915     var tr=table.insertRow(-1);
916     tr.vAlign='top';
917     if (tr.rowIndex % 2 == 1) tr.className='ricoLG_mFilter_oddrow';
918     var td1=tr.insertCell(-1)
919     var td2=tr.insertCell(-1)
920     var field=Rico.createFormField(td1,'input','checkbox',id);
921     field.value=code;
922     field.checked=true;
923     var label = td2.appendChild(document.createElement("label"));
924     label.htmlFor = id;
925     label.innerHTML=description;
926     Rico.eventBind(field,'click',eventHandle);
927   },
928
929   unplugHighlightEvents: function() {
930     var s=this.options.highlightSection;
931     if (s & 1) this.detachHighlightEvents(this.tbody[0]);
932     if (s & 2) this.detachHighlightEvents(this.tbody[1]);
933   },
934
935 /**
936  * place panel names on first row of grid header (used by LiveGridForms)
937  */
938   insertPanelNames: function(r,start,limit,cellClass) {
939     Rico.log('insertPanelNames: start='+start+' limit='+limit);
940     r.className='ricoLG_hdg';
941     var lastIdx=-1, span, newCell=null, spanIdx=0;
942     for( var c=start; c < limit; c++ ) {
943       if (lastIdx == this.options.columnSpecs[c].ColGroupIdx) {
944         span++;
945       } else {
946         if (newCell) newCell.colSpan=span;
947         newCell = r.insertCell(-1);
948         if (cellClass) newCell.className=cellClass;
949         span=1;
950         lastIdx=this.options.columnSpecs[c].ColGroupIdx;
951         newCell.innerHTML=this.options.ColGroups[lastIdx];
952       }
953     }
954     if (newCell) newCell.colSpan=span;
955   },
956
957 /**
958  * create grid header for table i (if none was provided)
959  */
960   createHdr: function(i,start,limit) {
961     Rico.log('createHdr: i='+i+' start='+start+' limit='+limit);
962     var mainRow = this.thead[i].insertRow(-1);
963     mainRow.id=this.tableId+'_tab'+i+'h_main';
964     mainRow.className='ricoLG_hdg';
965     for( var c=start; c < limit; c++ ) {
966       var newCell = mainRow.insertCell(-1);
967       newCell.innerHTML=this.options.columnSpecs[c].Hdg;
968     }
969   },
970
971 /**
972  * move header cells in original table to grid
973  */
974   loadHdrSrc: function(hdrSrc) {
975     var i,h,c,r,newrow,cells;
976     Rico.log('loadHdrSrc start');
977     for (i=0; i<2; i++) {
978       for (r=0; r<hdrSrc.length; r++) {
979         newrow = this.thead[i].insertRow(-1);
980         newrow.className='ricoLG_hdg '+this.tableId+'_hdg'+r;
981       }
982     }
983     if (hdrSrc.length==1) {
984       cells=hdrSrc[0].cells;
985       for (c=0; cells.length > 0; c++)
986         this.thead[c<this.options.frozenColumns ? 0 : 1].rows[0].appendChild(cells[0]);
987     } else {
988       for (r=0; r<hdrSrc.length; r++) {
989         cells=hdrSrc[r].cells;
990         for (c=0,h=0; cells.length > 0; c++) {
991           if (Rico.hasClass(cells[0],'ricoFrozen')) {
992             if (r==this.headerRowIdx) this.options.frozenColumns=c+1;
993           } else {
994             h=1;
995           }
996           this.thead[h].rows[r].appendChild(cells[0]);
997         }
998       }
999     }
1000     Rico.log('loadHdrSrc end');
1001   },
1002
1003 /**
1004  * Size div elements
1005  */
1006   sizeDivs: function() {
1007     Rico.log('sizeDivs: '+this.tableId);
1008     //this.cancelMenu();
1009     this.unhighlight();
1010     this.baseSizeDivs();
1011     var firstVisible=this.firstVisible();
1012     if (this.pageSize == 0 || firstVisible < 0) return;
1013     var totRowHt=this.columns[firstVisible].dataColDiv.offsetHeight;
1014     this.rowHeight = Math.round(totRowHt/this.pageSize);
1015     var scrHt=this.dataHt;
1016     if (this.scrTabWi0 == this.scrTabWi) {
1017       // no scrolling columns - horizontal scroll bar not needed
1018       this.innerDiv.style.height=(this.hdrHt+1)+'px';
1019       this.scrollDiv.style.overflowX='hidden';
1020     } else {
1021       this.scrollDiv.style.overflowX='scroll';
1022       scrHt+=this.options.scrollBarWidth;
1023     }
1024     this.scrollDiv.style.height=scrHt+'px';
1025     this.innerDiv.style.width=(this.scrWi)+'px';
1026     this.scrollTab.style.width=(this.scrWi-this.options.scrollBarWidth)+'px';
1027     //this.resizeDiv.style.height=this.frozenTabs.style.height=this.innerDiv.style.height=(this.hdrHt+this.dataHt+1)+'px';
1028     this.resizeDiv.style.height=(this.hdrHt+this.dataHt+1)+'px';
1029     Rico.log('sizeDivs scrHt='+scrHt+' innerHt='+this.innerDiv.style.height+' rowHt='+this.rowHeight+' pageSize='+this.pageSize);
1030     var pad=(this.scrWi-this.scrTabWi < this.options.scrollBarWidth) ? 2 : 0;
1031     this.shadowDiv.style.width=(this.scrTabWi+pad)+'px';
1032     this.outerDiv.style.height=(this.hdrHt+scrHt)+'px';
1033     this.setHorizontalScroll();
1034   },
1035
1036   setHorizontalScroll: function() {
1037     var newLeft=(-this.scrollDiv.scrollLeft)+'px';
1038     this.tabs[1].style.marginLeft=newLeft;
1039     this.tabs[2].style.marginLeft=newLeft;
1040   },
1041
1042   remainingHt: function() {
1043     var tabHt=this.outerDiv.offsetHeight;
1044     var winHt=Rico.windowHeight();
1045     var margin=Rico.isIE ? 15 : 10;
1046     // if there is a horizontal scrollbar take it into account
1047     if (!Rico.isIE && window.frameElement && window.frameElement.scrolling=='yes' && this.sizeTo!='parent') margin+=this.options.scrollBarWidth;
1048     switch (this.sizeTo) {
1049       case 'window':
1050         var divTop=Rico.cumulativeOffset(this.outerDiv).top;
1051         Rico.log("remainingHt/window, winHt="+winHt+' tabHt='+tabHt+' gridY='+divTop);
1052         return winHt-divTop-tabHt-margin;  // allow for scrollbar and some margin
1053       case 'parent':
1054         var offset=this.offsetFromParent(this.outerDiv);
1055         if (Rico.isIE) Rico.hide(this.outerDiv);
1056         var parentHt=this.outerDiv.parentNode.clientHeight;
1057         if (Rico.isIE) Rico.show(this.outerDiv);
1058         Rico.log("remainingHt/parent, parentHt="+parentHt+' offset='+offset+' tabHt='+tabHt);
1059         return parentHt-tabHt-offset-margin;
1060       case 'data':
1061       case 'body':
1062         var bodyHt=Rico.isIE ? document.body.scrollHeight : document.body.offsetHeight;
1063         //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);
1064         var remHt=winHt-bodyHt-margin;
1065         if (!Rico.isWebKit) remHt-=this.options.scrollBarWidth;
1066         Rico.log("remainingHt, winHt="+winHt+' pageHt='+bodyHt+' remHt='+remHt);
1067         return remHt;
1068       default:
1069         Rico.log("remainingHt, winHt="+winHt+' tabHt='+tabHt);
1070         if (this.sizeTo.slice(-1)=='%') winHt*=parseFloat(this.sizeTo)/100.0;
1071         else if (this.sizeTo.slice(-2)=='px') winHt=parseInt(this.sizeTo,10);
1072         return winHt-tabHt-margin;  // allow for scrollbar and some margin
1073     }
1074   },
1075
1076   offsetFromParent: function(element) {
1077     var valueT = 0;
1078     var elParent=element.parentNode;
1079     do {
1080       //Rico.log("offsetFromParent: "+element.tagName+' id='+element.id+' otop='+element.offsetTop);
1081       valueT += element.offsetTop  || 0;
1082       element = element.offsetParent;
1083       if (!element || element==null) break;
1084       var p = Rico.getStyle(element, 'position');
1085       if (element.tagName=='BODY' || element.tagName=='HTML' || p=='absolute') return valueT-elParent.offsetTop;
1086     } while (element != elParent);
1087     return valueT;
1088   },
1089
1090   adjustPageSize: function() {
1091     var remHt=this.remainingHt();
1092     Rico.log('adjustPageSize remHt='+remHt+' lastRow='+this.lastRowPos);
1093     if (remHt > this.rowHeight)
1094       this.autoAppendRows(remHt);
1095     else if (remHt < 0 || this.sizeTo=='data')
1096       this.autoRemoveRows(-remHt);
1097   },
1098   
1099   setPageSize: function(newRowCount) {
1100     newRowCount=Math.min(newRowCount,this.options.maxPageRows);
1101     newRowCount=Math.max(newRowCount,this.options.minPageRows);
1102     this.sizeTo='fixed';
1103     var oldSize=this.pageSize;
1104     while (this.pageSize > newRowCount) {
1105       this.removeRow();
1106     }
1107     while (this.pageSize < newRowCount) {
1108       this.appendBlankRow();
1109     }
1110     this.finishResize(oldSize);
1111   },
1112
1113   pluginWindowResize: function() {
1114     Rico.log("pluginWindowResize");
1115     this.resizeWindowHandler=Rico.eventHandle(this,'resizeWindow');
1116     Rico.eventBind(window, "resize", this.resizeWindowHandler, false);
1117   },
1118
1119   unplugWindowResize: function() {
1120     if (!this.resizeWindowHandler) return;
1121     Rico.eventUnbind(window,"resize", this.resizeWindowHandler, false);
1122     this.resizeWindowHandler=null;
1123   },
1124
1125   resizeWindow: function() {
1126     Rico.log('resizeWindow '+this.tableId+' lastRow='+this.lastRowPos);
1127     if (this.resizeState=='finish') {
1128       Rico.log('resizeWindow postponed');
1129       this.resizeState='resize';
1130       return;
1131     }
1132     if (!this.sizeTo || this.sizeTo=='fixed') {
1133       this.sizeDivs();
1134       return;
1135     }
1136     if (this.sizeTo=='parent' && Rico.getStyle(this.outerDiv.parentNode,'display') == 'none') return;
1137     var oldSize=this.pageSize;
1138     this.adjustPageSize();
1139     this.finishResize(oldSize);
1140   },
1141
1142   finishResize: function(oldSize) {
1143     if (this.pageSize > oldSize && this.buffer.totalRows>0) {
1144       this.isPartialBlank=true;
1145       var adjStart=this.adjustRow(this.lastRowPos);
1146       this.buffer.fetch(adjStart);
1147     } else if (this.pageSize < oldSize) {
1148       if (this.options.onRefreshComplete) this.options.onRefreshComplete(this.contentStartPos,this.contentStartPos+this.pageSize-1);  // update bookmark
1149     }
1150     this.resizeState='finish';
1151     Rico.runLater(20,this,'finishResize2');
1152     Rico.log('Resize '+this.tableId+' complete. old size='+oldSize+' new size='+this.pageSize);
1153   },
1154
1155   finishResize2: function() {
1156     this.sizeDivs();
1157     this.updateHeightDiv();
1158     if (this.resizeState=='resize') {
1159       this.resizeWindow();
1160     } else {
1161       this.resizeState='';
1162     }
1163   },
1164
1165   topOfLastPage: function() {
1166     return Math.max(this.buffer.totalRows-this.pageSize,0);
1167   },
1168
1169   updateHeightDiv: function() {
1170     var notdisp=this.topOfLastPage();
1171     var ht = notdisp ? this.scrollDiv.clientHeight + Math.floor(this.rowHeight * (notdisp + 0.4)) : 1;
1172     Rico.log("updateHeightDiv, ht="+ht+' scrollDiv.clientHeight='+this.scrollDiv.clientHeight+' rowsNotDisplayed='+notdisp);
1173     this.shadowDiv.style.height=ht+'px';
1174   },
1175
1176   autoRemoveRows: function(overage) {
1177     if (!this.rowHeight) return;
1178     var removeCnt=Math.ceil(overage / this.rowHeight);
1179     if (this.sizeTo=='data')
1180       removeCnt=Math.max(removeCnt,this.pageSize-this.buffer.totalRows);
1181     Rico.log("autoRemoveRows overage="+overage+" removeCnt="+removeCnt);
1182     for (var i=0; i<removeCnt; i++)
1183       this.removeRow();
1184   },
1185
1186   removeRow: function() {
1187     if (this.pageSize <= this.options.minPageRows) return;
1188     this.pageSize--;
1189     for( var c=0; c < this.headerColCnt; c++ ) {
1190       var cell=this.columns[c].cell(this.pageSize);
1191       this.columns[c].dataColDiv.removeChild(cell);
1192     }
1193   },
1194
1195   autoAppendRows: function(overage) {
1196     if (!this.rowHeight) return;
1197     var addCnt=Math.floor(overage / this.rowHeight);
1198     Rico.log("autoAppendRows overage="+overage+" cnt="+addCnt+" rowHt="+this.rowHeight);
1199     for (var i=0; i<addCnt; i++) {
1200       if (this.sizeTo=='data' && this.pageSize>=this.buffer.totalRows) break;
1201       this.appendBlankRow();
1202     }
1203   },
1204
1205 /**
1206  * on older systems, this can be fairly slow
1207  */
1208   appendBlankRow: function() {
1209     if (this.pageSize >= this.options.maxPageRows) return;
1210     Rico.log("appendBlankRow #"+this.pageSize);
1211     var cls=this.defaultRowClass(this.pageSize);
1212     for( var c=0; c < this.headerColCnt; c++ ) {
1213       var newdiv = document.createElement("div");
1214       newdiv.className = 'ricoLG_cell '+cls;
1215       newdiv.id=this.tableId+'_'+this.pageSize+'_'+c;
1216       this.columns[c].dataColDiv.appendChild(newdiv);
1217       if (this.columns[c]._create) {
1218         this.columns[c]._create(newdiv,this.pageSize);
1219       } else {
1220         newdiv.innerHTML='&nbsp;';   // this seems to be required by IE
1221       }
1222       if (this.columns[c].format.canDrag && Rico.registerDraggable) {
1223         Rico.registerDraggable( new Rico.LiveGridDraggable(this, this.pageSize, c), this.options.dndMgrIdx );
1224       }
1225     }
1226     this.pageSize++;
1227   },
1228
1229   defaultRowClass: function(rownum) {
1230     var cls
1231     if (rownum % 2==0) {
1232       cls='ricoLG_evenRow';
1233       //if (Rico.theme.primary) cls+=' '+Rico.theme.primary;
1234     } else {
1235       cls='ricoLG_oddRow';
1236       //if (Rico.theme.secondary) cls+=' '+Rico.theme.secondary;
1237     }
1238     return cls;
1239   },
1240
1241   handleMenuClick: function(e) {
1242     if (!this.menu) return;
1243     this.cancelMenu();
1244     this.unhighlight(); // in case highlighting was invoked externally
1245     var idx;
1246     var cell=Rico.eventElement(e);
1247     if (cell.className=='ricoLG_highlightDiv') {
1248       idx=this.highlightIdx;
1249     } else {
1250       cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
1251       if (!cell) return;
1252       idx=this.winCellIndex(cell);
1253       if ((this.options.highlightSection & (idx.tabIdx+1))==0) return;
1254     }
1255     this.highlight(idx);
1256     this.highlightEnabled=false;
1257     if (this.hideScroll) this.scrollDiv.style.overflow="hidden";
1258     this.menuIdx=idx;
1259     if (!this.menu.div) this.menu.createDiv();
1260     this.menu.liveGrid=this;
1261     if (this.menu.buildGridMenu) {
1262       var showMenu=this.menu.buildGridMenu(idx.row, idx.column, idx.tabIdx);
1263       if (!showMenu) return;
1264     }
1265     if (this.options.highlightElem=='selection' && !this.isSelected(idx.cell)) {
1266       this.selectCell(idx.cell);
1267     }
1268     var self=this;
1269     this.menu.showmenu(e,function() { self.closeMenu(); });
1270     return false;
1271   },
1272
1273   closeMenu: function() {
1274     if (!this.menuIdx) return;
1275     if (this.hideScroll) this.scrollDiv.style.overflow="";
1276     //this.unhighlight();
1277     this.highlightEnabled=true;
1278     this.menuIdx=null;
1279   },
1280
1281 /**
1282  * @return index of cell within the window
1283  */
1284   winCellIndex: function(cell) {
1285     var l=cell.id.lastIndexOf('_',cell.id.length);
1286     var l2=cell.id.lastIndexOf('_',l-1)+1;
1287     var c=parseInt(cell.id.substr(l+1));
1288     var r=parseInt(cell.id.substr(l2,l));
1289     return {row:r, column:c, tabIdx:this.columns[c].tabIdx, cell:cell};
1290   },
1291
1292 /**
1293  * @return index of cell within the dataset
1294  */
1295   datasetIndex: function(cell) {
1296     var idx=this.winCellIndex(cell);
1297     idx.row+=this.buffer.windowPos;
1298     idx.onBlankRow=(idx.row >= this.buffer.endPos());
1299     return idx;
1300   },
1301
1302   attachHighlightEvents: function(tBody) {
1303     switch (this.options.highlightElem) {
1304       case 'selection':
1305         Rico.eventBind(tBody,"mousedown", this.options.mouseDownHandler, false);
1306         /** @ignore */
1307         tBody.ondrag = function () { return false; };
1308         /** @ignore */
1309         tBody.onselectstart = function () { return false; };
1310         break;
1311       case 'cursorRow':
1312       case 'cursorCell':
1313         Rico.eventBind(tBody,"mouseover", this.options.rowOverHandler, false);
1314         break;
1315     }
1316   },
1317
1318   detachHighlightEvents: function(tBody) {
1319     switch (this.options.highlightElem) {
1320       case 'selection':
1321         Rico.eventUnbind(tBody,"mousedown", this.options.mouseDownHandler, false);
1322         tBody.ondrag = null;
1323         tBody.onselectstart = null;
1324         break;
1325       case 'cursorRow':
1326       case 'cursorCell':
1327         Rico.eventUnbind(tBody,"mouseover", this.options.rowOverHandler, false);
1328         break;
1329     }
1330   },
1331
1332 /**
1333  * @return array of objects containing row/col indexes (index values are relative to the start of the window)
1334  */
1335   getVisibleSelection: function() {
1336     var cellList=[];
1337     if (this.SelectIdxStart && this.SelectIdxEnd) {
1338       var r1=Math.max(Math.min(this.SelectIdxEnd.row,this.SelectIdxStart.row)-this.buffer.startPos,this.buffer.windowStart);
1339       var r2=Math.min(Math.max(this.SelectIdxEnd.row,this.SelectIdxStart.row)-this.buffer.startPos,this.buffer.windowEnd-1);
1340       var c1=Math.min(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1341       var c2=Math.max(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1342       //Rico.log("getVisibleSelection "+r1+','+c1+' to '+r2+','+c2+' ('+this.SelectIdxStart.row+',startPos='+this.buffer.startPos+',windowPos='+this.buffer.windowPos+',windowEnd='+this.buffer.windowEnd+')');
1343       for (var r=r1; r<=r2; r++) {
1344         for (var c=c1; c<=c2; c++)
1345           cellList.push({row:r-this.buffer.windowStart,column:c});
1346       }
1347     }
1348     if (this.SelectCtrl) {
1349       for (var i=0; i<this.SelectCtrl.length; i++) {
1350         if (this.SelectCtrl[i].row>=this.buffer.windowStart && this.SelectCtrl[i].row<this.buffer.windowEnd)
1351           cellList.push({row:this.SelectCtrl[i].row-this.buffer.windowStart,column:this.SelectCtrl[i].column});
1352       }
1353     }
1354     return cellList;
1355   },
1356
1357   updateSelectOutline: function() {
1358     if (!this.SelectIdxStart || !this.SelectIdxEnd) return;
1359     var r1=Math.max(Math.min(this.SelectIdxEnd.row,this.SelectIdxStart.row), this.buffer.windowStart);
1360     var r2=Math.min(Math.max(this.SelectIdxEnd.row,this.SelectIdxStart.row), this.buffer.windowEnd-1);
1361     if (r1 > r2) {
1362       this.HideSelection();
1363       return;
1364     }
1365     var c1=Math.min(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1366     var c2=Math.max(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1367     var top1=this.columns[c1].cell(r1-this.buffer.windowStart).offsetTop;
1368     var cell2=this.columns[c1].cell(r2-this.buffer.windowStart);
1369     var bottom2=cell2.offsetTop+cell2.offsetHeight;
1370     var left1=this.columns[c1].dataCell.offsetLeft;
1371     var left2=this.columns[c2].dataCell.offsetLeft;
1372     var right2=left2+this.columns[c2].dataCell.offsetWidth;
1373     //window.status='updateSelectOutline: '+r1+' '+r2+' top='+top1+' bot='+bottom2;
1374     this.highlightDiv[0].style.top=this.highlightDiv[3].style.top=this.highlightDiv[1].style.top=(this.hdrHt+top1-1) + 'px';
1375     this.highlightDiv[2].style.top=(this.hdrHt+bottom2-1)+'px';
1376     this.highlightDiv[3].style.left=(left1-2)+'px';
1377     this.highlightDiv[0].style.left=this.highlightDiv[2].style.left=(left1-1)+'px';
1378     this.highlightDiv[1].style.left=(right2-1)+'px';
1379     this.highlightDiv[0].style.width=this.highlightDiv[2].style.width=(right2-left1-1) + 'px';
1380     this.highlightDiv[1].style.height=this.highlightDiv[3].style.height=(bottom2-top1) + 'px';
1381     //this.highlightDiv[0].style.right=this.highlightDiv[2].style.right=this.highlightDiv[1].style.right=()+'px';
1382     //this.highlightDiv[2].style.bottom=this.highlightDiv[3].style.bottom=this.highlightDiv[1].style.bottom=(this.hdrHt+bottom2) + 'px';
1383     for (var i=0; i<4; i++)
1384       this.highlightDiv[i].style.display='';
1385   },
1386
1387   HideSelection: function() {
1388     var i;
1389     if (this.options.highlightMethod!='class') {
1390       for (i=0; i<this.highlightDiv.length; i++)
1391         this.highlightDiv[i].style.display='none';
1392     }
1393     if (this.options.highlightMethod!='outline') {
1394       var cellList=this.getVisibleSelection();
1395       Rico.log("HideSelection "+cellList.length);
1396       for (i=0; i<cellList.length; i++)
1397         this.unhighlightCell(this.columns[cellList[i].column].cell(cellList[i].row));
1398     }
1399   },
1400
1401   ShowSelection: function() {
1402     if (this.options.highlightMethod!='class')
1403       this.updateSelectOutline();
1404     if (this.options.highlightMethod!='outline') {
1405       var cellList=this.getVisibleSelection();
1406       for (var i=0; i<cellList.length; i++)
1407         this.highlightCell(this.columns[cellList[i].column].cell(cellList[i].row));
1408     }
1409   },
1410
1411   ClearSelection: function() {
1412     Rico.log("ClearSelection");
1413     this.HideSelection();
1414     this.SelectIdxStart=null;
1415     this.SelectIdxEnd=null;
1416     this.SelectCtrl=[];
1417   },
1418
1419   selectCell: function(cell) {
1420     this.ClearSelection();
1421     this.SelectIdxStart=this.SelectIdxEnd=this.datasetIndex(cell);
1422     this.ShowSelection();
1423   },
1424
1425   AdjustSelection: function(cell) {
1426     var newIdx=this.datasetIndex(cell);
1427     if (this.SelectIdxStart.tabIdx != newIdx.tabIdx) return;
1428     this.HideSelection();
1429     this.SelectIdxEnd=newIdx;
1430     this.ShowSelection();
1431   },
1432
1433   RefreshSelection: function() {
1434     var cellList=this.getVisibleSelection();
1435     for (var i=0; i<cellList.length; i++) {
1436       this.columns[cellList[i].column].displayValue(cellList[i].row);
1437     }
1438   },
1439
1440   FillSelection: function(newVal,newStyle) {
1441     if (this.SelectIdxStart && this.SelectIdxEnd) {
1442       var r1=Math.min(this.SelectIdxEnd.row,this.SelectIdxStart.row);
1443       var r2=Math.max(this.SelectIdxEnd.row,this.SelectIdxStart.row);
1444       var c1=Math.min(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1445       var c2=Math.max(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1446       for (var r=r1; r<=r2; r++) {
1447         for (var c=c1; c<=c2; c++) {
1448           this.buffer.setValue(r,c,newVal,newStyle);
1449         }
1450       }
1451     }
1452     if (this.SelectCtrl) {
1453       for (var i=0; i<this.SelectCtrl.length; i++) {
1454         this.buffer.setValue(this.SelectCtrl[i].row,this.SelectCtrl[i].column,newVal,newStyle);
1455       }
1456     }
1457     this.RefreshSelection();
1458   },
1459
1460 /**
1461  * Process mouse down event
1462  * @param e event object
1463  */
1464   selectMouseDown: function(e) {
1465     if (this.highlightEnabled==false) return true;
1466     this.cancelMenu();
1467     var cell=Rico.eventElement(e);
1468     if (!Rico.eventLeftClick(e)) return true;
1469     cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
1470     if (!cell) return true;
1471     Rico.eventStop(e);
1472     var newIdx=this.datasetIndex(cell);
1473     if (newIdx.onBlankRow) return true;
1474     Rico.log("selectMouseDown @"+newIdx.row+','+newIdx.column);
1475     if (e.ctrlKey) {
1476       if (!this.SelectIdxStart || this.options.highlightMethod!='class') return true;
1477       if (!this.isSelected(cell)) {
1478         this.highlightCell(cell);
1479         this.SelectCtrl.push(this.datasetIndex(cell));
1480       } else {
1481         for (var i=0; i<this.SelectCtrl.length; i++) {
1482           if (this.SelectCtrl[i].row==newIdx.row && this.SelectCtrl[i].column==newIdx.column) {
1483             this.unhighlightCell(cell);
1484             this.SelectCtrl.splice(i,1);
1485             break;
1486           }
1487         }
1488       }
1489     } else if (e.shiftKey) {
1490       if (!this.SelectIdxStart) return true;
1491       this.AdjustSelection(cell);
1492     } else {
1493       this.selectCell(cell);
1494       this.pluginSelect();
1495     }
1496     return false;
1497   },
1498
1499   pluginSelect: function() {
1500     if (this.selectPluggedIn) return;
1501     var tBody=this.tbody[this.SelectIdxStart.tabIdx];
1502     Rico.eventBind(tBody,"mouseover", this.options.mouseOverHandler, false);
1503     Rico.eventBind(this.outerDiv,"mouseup",  this.options.mouseUpHandler,  false);
1504     this.selectPluggedIn=true;
1505   },
1506
1507   unplugSelect: function() {
1508     if (!this.selectPluggedIn) return;
1509     var tBody=this.tbody[this.SelectIdxStart.tabIdx];
1510     Rico.eventUnbind(tBody,"mouseover", this.options.mouseOverHandler , false);
1511     Rico.eventUnbind(this.outerDiv,"mouseup", this.options.mouseUpHandler , false);
1512     this.selectPluggedIn=false;
1513   },
1514
1515   selectMouseUp: function(e) {
1516     this.unplugSelect();
1517     var cell=Rico.eventElement(e);
1518     cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
1519     if (!cell) return;
1520     if (this.SelectIdxStart && this.SelectIdxEnd)
1521       this.AdjustSelection(cell);
1522     else
1523       this.ClearSelection();
1524   },
1525
1526   selectMouseOver: function(e) {
1527     var cell=Rico.eventElement(e);
1528     cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
1529     if (!cell) return;
1530     this.AdjustSelection(cell);
1531     Rico.eventStop(e);
1532   },
1533
1534   isSelected: function(cell) {
1535     if (this.options.highlightMethod!='outline') return Rico.hasClass(cell,this.options.highlightClass);
1536     if (!this.SelectIdxStart || !this.SelectIdxEnd) return false;
1537     var r1=Math.max(Math.min(this.SelectIdxEnd.row,this.SelectIdxStart.row), this.buffer.windowStart);
1538     var r2=Math.min(Math.max(this.SelectIdxEnd.row,this.SelectIdxStart.row), this.buffer.windowEnd-1);
1539     if (r1 > r2) return false;
1540     var c1=Math.min(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1541     var c2=Math.max(this.SelectIdxEnd.column,this.SelectIdxStart.column);
1542     var curIdx=this.datasetIndex(cell);
1543     return (r1<=curIdx.row && curIdx.row<=r2 && c1<=curIdx.column && curIdx.column<=c2);
1544   },
1545
1546   highlightCell: function(cell) {
1547     Rico.addClass(cell,this.options.highlightClass);
1548   },
1549
1550   unhighlightCell: function(cell) {
1551     if (cell) Rico.removeClass(cell,this.options.highlightClass);
1552   },
1553
1554   selectRow: function(r) {
1555     for (var c=0; c<this.columns.length; c++)
1556       this.highlightCell(this.columns[c].cell(r));
1557   },
1558
1559   unselectRow: function(r) {
1560     for (var c=0; c<this.columns.length; c++)
1561       this.unhighlightCell(this.columns[c].cell(r));
1562   },
1563
1564   rowMouseOver: function(e) {
1565     if (!this.highlightEnabled) return;
1566     var cell=Rico.eventElement(e);
1567     cell=Rico.getParentByTagName(cell,'div','ricoLG_cell');
1568     if (!cell) return;
1569     var newIdx=this.winCellIndex(cell);
1570     if ((this.options.highlightSection & (newIdx.tabIdx+1))==0) return;
1571     this.highlight(newIdx);
1572   },
1573
1574   highlight: function(newIdx) {
1575     if (this.options.highlightMethod!='outline') this.cursorSetClass(newIdx);
1576     if (this.options.highlightMethod!='class') this.cursorOutline(newIdx);
1577     this.highlightIdx=newIdx;
1578   },
1579
1580   cursorSetClass: function(newIdx) {
1581     switch (this.options.highlightElem) {
1582       case 'menuCell':
1583       case 'cursorCell':
1584         if (this.highlightIdx) this.unhighlightCell(this.highlightIdx.cell);
1585         this.highlightCell(newIdx.cell);
1586         break;
1587       case 'menuRow':
1588       case 'cursorRow':
1589         if (this.highlightIdx) this.unselectRow(this.highlightIdx.row);
1590         var s1=this.options.highlightSection & 1;
1591         var s2=this.options.highlightSection & 2;
1592         var c0=s1 ? 0 : this.options.frozenColumns;
1593         var c1=s2 ? this.columns.length : this.options.frozenColumns;
1594         for (var c=c0; c<c1; c++)
1595           this.highlightCell(this.columns[c].cell(newIdx.row));
1596         break;
1597       default: return;
1598     }
1599   },
1600
1601   cursorOutline: function(newIdx) {
1602     var div;
1603     switch (this.options.highlightElem) {
1604       case 'menuCell':
1605       case 'cursorCell':
1606         div=this.highlightDiv[newIdx.tabIdx];
1607         div.style.left=(this.columns[newIdx.column].dataCell.offsetLeft-1)+'px';
1608         div.style.width=this.columns[newIdx.column].colWidth;
1609         this.highlightDiv[1-newIdx.tabIdx].style.display='none';
1610         break;
1611       case 'menuRow':
1612       case 'cursorRow':
1613         div=this.highlightDiv[0];
1614         var s1=this.options.highlightSection & 1;
1615         var s2=this.options.highlightSection & 2;
1616         div.style.left=s1 ? '0px' : this.frozenTabs.style.width;
1617         div.style.width=((s1 ? this.frozenTabs.offsetWidth : 0) + (s2 ? this.innerDiv.offsetWidth : 0) - 4)+'px';
1618         break;
1619       default: return;
1620     }
1621     div.style.top=(this.hdrHt+newIdx.row*this.rowHeight-1)+'px';
1622     div.style.height=(this.rowHeight-1)+'px';
1623     div.style.display='';
1624   },
1625
1626   unhighlight: function() {
1627     switch (this.options.highlightElem) {
1628       case 'menuCell':
1629         //this.highlightIdx=this.menuIdx;
1630         /*jsl:fallthru*/
1631       case 'cursorCell':
1632         if (this.highlightIdx) this.unhighlightCell(this.highlightIdx.cell);
1633         if (!this.highlightDiv) return;
1634         for (var i=0; i<2; i++)
1635           this.highlightDiv[i].style.display='none';
1636         break;
1637       case 'menuRow':
1638         //this.highlightIdx=this.menuIdx;
1639         /*jsl:fallthru*/
1640       case 'cursorRow':
1641         if (this.highlightIdx) this.unselectRow(this.highlightIdx.row);
1642         if (this.highlightDiv) this.highlightDiv[0].style.display='none';
1643         break;
1644     }
1645   },
1646
1647   resetContents: function() {
1648     Rico.log("resetContents");
1649     this.ClearSelection();
1650     this.buffer.clear();
1651     this.clearRows();
1652     this.clearBookmark();
1653   },
1654
1655   setImages: function() {
1656     for (var n=0; n<this.columns.length; n++)
1657       this.columns[n].setImage();
1658   },
1659
1660 /**
1661  * @return column index, or -1 if there are no sorted columns
1662  */
1663   findSortedColumn: function() {
1664     for (var n=0; n<this.columns.length; n++) {
1665       if (this.columns[n].isSorted()) 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( columnIdOrNum, sortDirection ) {
1686     Rico.log("setSortUI: "+columnIdOrNum+' '+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 columnIdOrNum) {
1698         case 'string':
1699           colnum=this.findColumnsBySpec('id',columnIdOrNum);
1700           break;
1701         case 'number':
1702           colnum=columnIdOrNum;
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 };