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