Roo/grid/GridView.js
[roojs1] / Roo / grid / GridView.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11   
12 /**
13  * @class Roo.grid.GridView
14  * @extends Roo.util.Observable
15  *
16  * @constructor
17  * @param {Object} config
18  */
19 Roo.grid.GridView = function(config){
20     Roo.grid.GridView.superclass.constructor.call(this);
21     this.el = null;
22
23     Roo.apply(this, config);
24 };
25
26 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
27
28     unselectable :  'unselectable="on"',
29     unselectableCls :  'x-unselectable',
30     
31     
32     rowClass : "x-grid-row",
33
34     cellClass : "x-grid-col",
35
36     tdClass : "x-grid-td",
37
38     hdClass : "x-grid-hd",
39
40     splitClass : "x-grid-split",
41
42     sortClasses : ["sort-asc", "sort-desc"],
43
44     enableMoveAnim : false,
45
46     hlColor: "C3DAF9",
47
48     dh : Roo.DomHelper,
49
50     fly : Roo.Element.fly,
51
52     css : Roo.util.CSS,
53
54     borderWidth: 1,
55
56     splitOffset: 3,
57
58     scrollIncrement : 22,
59
60     cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
61
62     findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
63
64     bind : function(ds, cm){
65         if(this.ds){
66             this.ds.un("load", this.onLoad, this);
67             this.ds.un("datachanged", this.onDataChange, this);
68             this.ds.un("add", this.onAdd, this);
69             this.ds.un("remove", this.onRemove, this);
70             this.ds.un("update", this.onUpdate, this);
71             this.ds.un("clear", this.onClear, this);
72         }
73         if(ds){
74             ds.on("load", this.onLoad, this);
75             ds.on("datachanged", this.onDataChange, this);
76             ds.on("add", this.onAdd, this);
77             ds.on("remove", this.onRemove, this);
78             ds.on("update", this.onUpdate, this);
79             ds.on("clear", this.onClear, this);
80         }
81         this.ds = ds;
82
83         if(this.cm){
84             this.cm.un("widthchange", this.onColWidthChange, this);
85             this.cm.un("headerchange", this.onHeaderChange, this);
86             this.cm.un("hiddenchange", this.onHiddenChange, this);
87             this.cm.un("columnmoved", this.onColumnMove, this);
88             this.cm.un("columnlockchange", this.onColumnLock, this);
89         }
90         if(cm){
91             this.generateRules(cm);
92             cm.on("widthchange", this.onColWidthChange, this);
93             cm.on("headerchange", this.onHeaderChange, this);
94             cm.on("hiddenchange", this.onHiddenChange, this);
95             cm.on("columnmoved", this.onColumnMove, this);
96             cm.on("columnlockchange", this.onColumnLock, this);
97         }
98         this.cm = cm;
99     },
100
101     init: function(grid){
102         Roo.grid.GridView.superclass.init.call(this, grid);
103
104         this.bind(grid.dataSource, grid.colModel);
105
106         grid.on("headerclick", this.handleHeaderClick, this);
107
108         if(grid.trackMouseOver){
109             grid.on("mouseover", this.onRowOver, this);
110             grid.on("mouseout", this.onRowOut, this);
111         }
112         grid.cancelTextSelection = function(){};
113         this.gridId = grid.id;
114
115         var tpls = this.templates || {};
116
117         if(!tpls.master){
118             tpls.master = new Roo.Template(
119                '<div class="x-grid" hidefocus="true">',
120                 '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
121                   '<div class="x-grid-topbar"></div>',
122                   '<div class="x-grid-scroller"><div></div></div>',
123                   '<div class="x-grid-locked">',
124                       '<div class="x-grid-header">{lockedHeader}</div>',
125                       '<div class="x-grid-body">{lockedBody}</div>',
126                   "</div>",
127                   '<div class="x-grid-viewport">',
128                       '<div class="x-grid-header">{header}</div>',
129                       '<div class="x-grid-body">{body}</div>',
130                   "</div>",
131                   '<div class="x-grid-bottombar"></div>',
132                  
133                   '<div class="x-grid-resize-proxy">&#160;</div>',
134                "</div>"
135             );
136             tpls.master.disableformats = true;
137         }
138
139         if(!tpls.header){
140             tpls.header = new Roo.Template(
141                '<table border="0" cellspacing="0" cellpadding="0">',
142                '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
143                "</table>{splits}"
144             );
145             tpls.header.disableformats = true;
146         }
147         tpls.header.compile();
148
149         if(!tpls.hcell){
150             tpls.hcell = new Roo.Template(
151                 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
152                 '<div class="x-grid-hd-text" unselectable="on">{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
153                 "</div></td>"
154              );
155              tpls.hcell.disableFormats = true;
156         }
157         tpls.hcell.compile();
158
159         if(!tpls.hsplit){
160             tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style}" unselectable="on">&#160;</div>');
161             tpls.hsplit.disableFormats = true;
162         }
163         tpls.hsplit.compile();
164
165         if(!tpls.body){
166             tpls.body = new Roo.Template(
167                '<table border="0" cellspacing="0" cellpadding="0">',
168                "<tbody>{rows}</tbody>",
169                "</table>"
170             );
171             tpls.body.disableFormats = true;
172         }
173         tpls.body.compile();
174
175         if(!tpls.row){
176             tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
177             tpls.row.disableFormats = true;
178         }
179         tpls.row.compile();
180
181         if(!tpls.cell){
182             tpls.cell = new Roo.Template(
183                 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
184                 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text" unselectable="on" {attr}>{value}</div></div>',
185                 "</td>"
186             );
187             tpls.cell.disableFormats = true;
188         }
189         tpls.cell.compile();
190
191         this.templates = tpls;
192     },
193
194     // remap these for backwards compat
195     onColWidthChange : function(){
196         this.updateColumns.apply(this, arguments);
197     },
198     onHeaderChange : function(){
199         this.updateHeaders.apply(this, arguments);
200     }, 
201     onHiddenChange : function(){
202         this.handleHiddenChange.apply(this, arguments);
203     },
204     onColumnMove : function(){
205         this.handleColumnMove.apply(this, arguments);
206     },
207     onColumnLock : function(){
208         this.handleLockChange.apply(this, arguments);
209     },
210
211     onDataChange : function(){
212         this.refresh();
213         this.updateHeaderSortState();
214     },
215
216     onClear : function(){
217         this.refresh();
218     },
219
220     onUpdate : function(ds, record){
221         this.refreshRow(record);
222     },
223
224     refreshRow : function(record){
225         var ds = this.ds, index;
226         if(typeof record == 'number'){
227             index = record;
228             record = ds.getAt(index);
229         }else{
230             index = ds.indexOf(record);
231         }
232         this.insertRows(ds, index, index, true);
233         this.onRemove(ds, record, index+1, true);
234         this.syncRowHeights(index, index);
235         this.layout();
236         this.fireEvent("rowupdated", this, index, record);
237     },
238
239     onAdd : function(ds, records, index){
240         this.insertRows(ds, index, index + (records.length-1));
241     },
242
243     onRemove : function(ds, record, index, isUpdate){
244         if(isUpdate !== true){
245             this.fireEvent("beforerowremoved", this, index, record);
246         }
247         var bt = this.getBodyTable(), lt = this.getLockedTable();
248         if(bt.rows[index]){
249             bt.firstChild.removeChild(bt.rows[index]);
250         }
251         if(lt.rows[index]){
252             lt.firstChild.removeChild(lt.rows[index]);
253         }
254         if(isUpdate !== true){
255             this.stripeRows(index);
256             this.syncRowHeights(index, index);
257             this.layout();
258             this.fireEvent("rowremoved", this, index, record);
259         }
260     },
261
262     onLoad : function(){
263         this.scrollToTop();
264     },
265
266     /**
267      * Scrolls the grid to the top
268      */
269     scrollToTop : function(){
270         if(this.scroller){
271             this.scroller.dom.scrollTop = 0;
272             this.syncScroll();
273         }
274     },
275
276     /**
277      * Gets a panel in the header of the grid that can be used for toolbars etc.
278      * After modifying the contents of this panel a call to grid.autoSize() may be
279      * required to register any changes in size.
280      * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
281      * @return Roo.Element
282      */
283     getHeaderPanel : function(doShow){
284         if(doShow){
285             this.headerPanel.show();
286         }
287         return this.headerPanel;
288     },
289
290     /**
291      * Gets a panel in the footer of the grid that can be used for toolbars etc.
292      * After modifying the contents of this panel a call to grid.autoSize() may be
293      * required to register any changes in size.
294      * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
295      * @return Roo.Element
296      */
297     getFooterPanel : function(doShow){
298         if(doShow){
299             this.footerPanel.show();
300         }
301         return this.footerPanel;
302     },
303
304     initElements : function(){
305         var E = Roo.Element;
306         var el = this.grid.getGridEl().dom.firstChild;
307         var cs = el.childNodes;
308
309         this.el = new E(el);
310         
311          this.focusEl = new E(el.firstChild);
312         this.focusEl.swallowEvent("click", true);
313         
314         this.headerPanel = new E(cs[1]);
315         this.headerPanel.enableDisplayMode("block");
316
317         this.scroller = new E(cs[2]);
318         this.scrollSizer = new E(this.scroller.dom.firstChild);
319
320         this.lockedWrap = new E(cs[3]);
321         this.lockedHd = new E(this.lockedWrap.dom.firstChild);
322         this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
323
324         this.mainWrap = new E(cs[4]);
325         this.mainHd = new E(this.mainWrap.dom.firstChild);
326         this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
327
328         this.footerPanel = new E(cs[5]);
329         this.footerPanel.enableDisplayMode("block");
330
331         this.resizeProxy = new E(cs[6]);
332
333         this.headerSelector = String.format(
334            '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
335            this.lockedHd.id, this.mainHd.id
336         );
337
338         this.splitterSelector = String.format(
339            '#{0} div.x-grid-split, #{1} div.x-grid-split',
340            this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
341         );
342     },
343     idToCssName : function(s)
344     {
345         return s.replace(/[^a-z0-9]+/ig, '-');
346     },
347
348     getHeaderCell : function(index){
349         return Roo.DomQuery.select(this.headerSelector)[index];
350     },
351
352     getHeaderCellMeasure : function(index){
353         return this.getHeaderCell(index).firstChild;
354     },
355
356     getHeaderCellText : function(index){
357         return this.getHeaderCell(index).firstChild.firstChild;
358     },
359
360     getLockedTable : function(){
361         return this.lockedBody.dom.firstChild;
362     },
363
364     getBodyTable : function(){
365         return this.mainBody.dom.firstChild;
366     },
367
368     getLockedRow : function(index){
369         return this.getLockedTable().rows[index];
370     },
371
372     getRow : function(index){
373         return this.getBodyTable().rows[index];
374     },
375
376     getRowComposite : function(index){
377         if(!this.rowEl){
378             this.rowEl = new Roo.CompositeElementLite();
379         }
380         var els = [], lrow, mrow;
381         if(lrow = this.getLockedRow(index)){
382             els.push(lrow);
383         }
384         if(mrow = this.getRow(index)){
385             els.push(mrow);
386         }
387         this.rowEl.elements = els;
388         return this.rowEl;
389     },
390     /**
391      * Gets the 'td' of the cell
392      * 
393      * @param {Integer} rowIndex row to select
394      * @param {Integer} colIndex column to select
395      * 
396      * @return {Object} 
397      */
398     getCell : function(rowIndex, colIndex){
399         var locked = this.cm.getLockedCount();
400         var source;
401         if(colIndex < locked){
402             source = this.lockedBody.dom.firstChild;
403         }else{
404             source = this.mainBody.dom.firstChild;
405             colIndex -= locked;
406         }
407         return source.rows[rowIndex].childNodes[colIndex];
408     },
409
410     getCellText : function(rowIndex, colIndex){
411         return this.getCell(rowIndex, colIndex).firstChild.firstChild;
412     },
413
414     getCellBox : function(cell){
415         var b = this.fly(cell).getBox();
416         if(Roo.isOpera){ // opera fails to report the Y
417             b.y = cell.offsetTop + this.mainBody.getY();
418         }
419         return b;
420     },
421
422     getCellIndex : function(cell){
423         var id = String(cell.className).match(this.cellRE);
424         if(id){
425             return parseInt(id[1], 10);
426         }
427         return 0;
428     },
429
430     findHeaderIndex : function(n){
431         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
432         return r ? this.getCellIndex(r) : false;
433     },
434
435     findHeaderCell : function(n){
436         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
437         return r ? r : false;
438     },
439
440     findRowIndex : function(n){
441         if(!n){
442             return false;
443         }
444         var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
445         return r ? r.rowIndex : false;
446     },
447
448     findCellIndex : function(node){
449         var stop = this.el.dom;
450         while(node && node != stop){
451             if(this.findRE.test(node.className)){
452                 return this.getCellIndex(node);
453             }
454             node = node.parentNode;
455         }
456         return false;
457     },
458
459     getColumnId : function(index){
460         return this.cm.getColumnId(index);
461     },
462
463     getSplitters : function()
464     {
465         if(this.splitterSelector){
466            return Roo.DomQuery.select(this.splitterSelector);
467         }else{
468             return null;
469       }
470     },
471
472     getSplitter : function(index){
473         return this.getSplitters()[index];
474     },
475
476     onRowOver : function(e, t){
477         var row;
478         if((row = this.findRowIndex(t)) !== false){
479             this.getRowComposite(row).addClass("x-grid-row-over");
480         }
481     },
482
483     onRowOut : function(e, t){
484         var row;
485         if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
486             this.getRowComposite(row).removeClass("x-grid-row-over");
487         }
488     },
489
490     renderHeaders : function(){
491         var cm = this.cm;
492         var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
493         var cb = [], lb = [], sb = [], lsb = [], p = {};
494         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
495             p.cellId = "x-grid-hd-0-" + i;
496             p.splitId = "x-grid-csplit-0-" + i;
497             p.id = cm.getColumnId(i);
498             p.title = cm.getColumnTooltip(i) || "";
499             p.value = cm.getColumnHeader(i) || "";
500             p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
501             if(!cm.isLocked(i)){
502                 cb[cb.length] = ct.apply(p);
503                 sb[sb.length] = st.apply(p);
504             }else{
505                 lb[lb.length] = ct.apply(p);
506                 lsb[lsb.length] = st.apply(p);
507             }
508         }
509         return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
510                 ht.apply({cells: cb.join(""), splits:sb.join("")})];
511     },
512
513     updateHeaders : function(){
514         var html = this.renderHeaders();
515         this.lockedHd.update(html[0]);
516         this.mainHd.update(html[1]);
517     },
518
519     /**
520      * Focuses the specified row.
521      * @param {Number} row The row index
522      */
523     focusRow : function(row)
524     {
525         //Roo.log('GridView.focusRow');
526         var x = this.scroller.dom.scrollLeft;
527         this.focusCell(row, 0, false);
528         this.scroller.dom.scrollLeft = x;
529     },
530
531     /**
532      * Focuses the specified cell.
533      * @param {Number} row The row index
534      * @param {Number} col The column index
535      * @param {Boolean} hscroll false to disable horizontal scrolling
536      */
537     focusCell : function(row, col, hscroll)
538     {
539         //Roo.log('GridView.focusCell');
540         var el = this.ensureVisible(row, col, hscroll);
541         this.focusEl.alignTo(el, "tl-tl");
542         if(Roo.isGecko){
543             this.focusEl.focus();
544         }else{
545             this.focusEl.focus.defer(1, this.focusEl);
546         }
547     },
548
549     /**
550      * Scrolls the specified cell into view
551      * @param {Number} row The row index
552      * @param {Number} col The column index
553      * @param {Boolean} hscroll false to disable horizontal scrolling
554      */
555     ensureVisible : function(row, col, hscroll)
556     {
557         //Roo.log('GridView.ensureVisible,' + row + ',' + col);
558         //return null; //disable for testing.
559         if(typeof row != "number"){
560             row = row.rowIndex;
561         }
562         if(row < 0 && row >= this.ds.getCount()){
563             return  null;
564         }
565         col = (col !== undefined ? col : 0);
566         var cm = this.grid.colModel;
567         while(cm.isHidden(col)){
568             col++;
569         }
570
571         var el = this.getCell(row, col);
572         if(!el){
573             return null;
574         }
575         var c = this.scroller.dom;
576
577         var ctop = parseInt(el.offsetTop, 10);
578         var cleft = parseInt(el.offsetLeft, 10);
579         var cbot = ctop + el.offsetHeight;
580         var cright = cleft + el.offsetWidth;
581         
582         var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
583         var stop = parseInt(c.scrollTop, 10);
584         var sleft = parseInt(c.scrollLeft, 10);
585         var sbot = stop + ch;
586         var sright = sleft + c.clientWidth;
587         /*
588         Roo.log('GridView.ensureVisible:' +
589                 ' ctop:' + ctop +
590                 ' c.clientHeight:' + c.clientHeight +
591                 ' this.mainHd.dom.offsetHeight:' + this.mainHd.dom.offsetHeight +
592                 ' stop:' + stop +
593                 ' cbot:' + cbot +
594                 ' sbot:' + sbot +
595                 ' ch:' + ch  
596                 );
597         */
598         if(ctop < stop){
599              c.scrollTop = ctop;
600             //Roo.log("set scrolltop to ctop DISABLE?");
601         }else if(cbot > sbot){
602             //Roo.log("set scrolltop to cbot-ch");
603             c.scrollTop = cbot-ch;
604         }
605         
606         if(hscroll !== false){
607             if(cleft < sleft){
608                 c.scrollLeft = cleft;
609             }else if(cright > sright){
610                 c.scrollLeft = cright-c.clientWidth;
611             }
612         }
613          
614         return el;
615     },
616
617     updateColumns : function(){
618         this.grid.stopEditing();
619         var cm = this.grid.colModel, colIds = this.getColumnIds();
620         //var totalWidth = cm.getTotalWidth();
621         var pos = 0;
622         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
623             //if(cm.isHidden(i)) continue;
624             var w = cm.getColumnWidth(i);
625             this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
626             this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
627         }
628         this.updateSplitters();
629     },
630
631     generateRules : function(cm){
632         var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
633         Roo.util.CSS.removeStyleSheet(rulesId);
634         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
635             var cid = cm.getColumnId(i);
636             var align = '';
637             if(cm.config[i].align){
638                 align = 'text-align:'+cm.config[i].align+';';
639             }
640             var hidden = '';
641             if(cm.isHidden(i)){
642                 hidden = 'display:none;';
643             }
644             var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
645             ruleBuf.push(
646                     this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
647                     this.hdSelector, cid, " {\n", align, width, "}\n",
648                     this.tdSelector, cid, " {\n",hidden,"\n}\n",
649                     this.splitSelector, cid, " {\n", hidden , "\n}\n");
650         }
651         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
652     },
653
654     updateSplitters : function(){
655         var cm = this.cm, s = this.getSplitters();
656         if(s){ // splitters not created yet
657             var pos = 0, locked = true;
658             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
659                 if(cm.isHidden(i)) continue;
660                 var w = cm.getColumnWidth(i); // make sure it's a number
661                 if(!cm.isLocked(i) && locked){
662                     pos = 0;
663                     locked = false;
664                 }
665                 pos += w;
666                 s[i].style.left = (pos-this.splitOffset) + "px";
667             }
668         }
669     },
670
671     handleHiddenChange : function(colModel, colIndex, hidden){
672         if(hidden){
673             this.hideColumn(colIndex);
674         }else{
675             this.unhideColumn(colIndex);
676         }
677     },
678
679     hideColumn : function(colIndex){
680         var cid = this.getColumnId(colIndex);
681         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
682         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
683         if(Roo.isSafari){
684             this.updateHeaders();
685         }
686         this.updateSplitters();
687         this.layout();
688     },
689
690     unhideColumn : function(colIndex){
691         var cid = this.getColumnId(colIndex);
692         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
693         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
694
695         if(Roo.isSafari){
696             this.updateHeaders();
697         }
698         this.updateSplitters();
699         this.layout();
700     },
701
702     insertRows : function(dm, firstRow, lastRow, isUpdate){
703         if(firstRow == 0 && lastRow == dm.getCount()-1){
704             this.refresh();
705         }else{
706             if(!isUpdate){
707                 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
708             }
709             var s = this.getScrollState();
710             var markup = this.renderRows(firstRow, lastRow);
711             this.bufferRows(markup[0], this.getLockedTable(), firstRow);
712             this.bufferRows(markup[1], this.getBodyTable(), firstRow);
713             this.restoreScroll(s);
714             if(!isUpdate){
715                 this.fireEvent("rowsinserted", this, firstRow, lastRow);
716                 this.syncRowHeights(firstRow, lastRow);
717                 this.stripeRows(firstRow);
718                 this.layout();
719             }
720         }
721     },
722
723     bufferRows : function(markup, target, index){
724         var before = null, trows = target.rows, tbody = target.tBodies[0];
725         if(index < trows.length){
726             before = trows[index];
727         }
728         var b = document.createElement("div");
729         b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
730         var rows = b.firstChild.rows;
731         for(var i = 0, len = rows.length; i < len; i++){
732             if(before){
733                 tbody.insertBefore(rows[0], before);
734             }else{
735                 tbody.appendChild(rows[0]);
736             }
737         }
738         b.innerHTML = "";
739         b = null;
740     },
741
742     deleteRows : function(dm, firstRow, lastRow){
743         if(dm.getRowCount()<1){
744             this.fireEvent("beforerefresh", this);
745             this.mainBody.update("");
746             this.lockedBody.update("");
747             this.fireEvent("refresh", this);
748         }else{
749             this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
750             var bt = this.getBodyTable();
751             var tbody = bt.firstChild;
752             var rows = bt.rows;
753             for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
754                 tbody.removeChild(rows[firstRow]);
755             }
756             this.stripeRows(firstRow);
757             this.fireEvent("rowsdeleted", this, firstRow, lastRow);
758         }
759     },
760
761     updateRows : function(dataSource, firstRow, lastRow){
762         var s = this.getScrollState();
763         this.refresh();
764         this.restoreScroll(s);
765     },
766
767     handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
768         if(!noRefresh){
769            this.refresh();
770         }
771         this.updateHeaderSortState();
772     },
773
774     getScrollState : function(){
775         
776         var sb = this.scroller.dom;
777         return {left: sb.scrollLeft, top: sb.scrollTop};
778     },
779
780     stripeRows : function(startRow){
781         if(!this.grid.stripeRows || this.ds.getCount() < 1){
782             return;
783         }
784         startRow = startRow || 0;
785         var rows = this.getBodyTable().rows;
786         var lrows = this.getLockedTable().rows;
787         var cls = ' x-grid-row-alt ';
788         for(var i = startRow, len = rows.length; i < len; i++){
789             var row = rows[i], lrow = lrows[i];
790             var isAlt = ((i+1) % 2 == 0);
791             var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
792             if(isAlt == hasAlt){
793                 continue;
794             }
795             if(isAlt){
796                 row.className += " x-grid-row-alt";
797             }else{
798                 row.className = row.className.replace("x-grid-row-alt", "");
799             }
800             if(lrow){
801                 lrow.className = row.className;
802             }
803         }
804     },
805
806     restoreScroll : function(state){
807         //Roo.log('GridView.restoreScroll');
808         var sb = this.scroller.dom;
809         sb.scrollLeft = state.left;
810         sb.scrollTop = state.top;
811         this.syncScroll();
812     },
813
814     syncScroll : function(){
815         //Roo.log('GridView.syncScroll');
816         var sb = this.scroller.dom;
817         var sh = this.mainHd.dom;
818         var bs = this.mainBody.dom;
819         var lv = this.lockedBody.dom;
820         sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
821         lv.scrollTop = bs.scrollTop = sb.scrollTop;
822     },
823
824     handleScroll : function(e){
825         this.syncScroll();
826         var sb = this.scroller.dom;
827         this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
828         e.stopEvent();
829     },
830
831     handleWheel : function(e){
832         var d = e.getWheelDelta();
833         this.scroller.dom.scrollTop -= d*22;
834         // set this here to prevent jumpy scrolling on large tables
835         this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
836         e.stopEvent();
837     },
838
839     renderRows : function(startRow, endRow){
840         // pull in all the crap needed to render rows
841         var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
842         var colCount = cm.getColumnCount();
843
844         if(ds.getCount() < 1){
845             return ["", ""];
846         }
847
848         // build a map for all the columns
849         var cs = [];
850         for(var i = 0; i < colCount; i++){
851             var name = cm.getDataIndex(i);
852             cs[i] = {
853                 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
854                 renderer : cm.getRenderer(i),
855                 id : cm.getColumnId(i),
856                 locked : cm.isLocked(i)
857             };
858         }
859
860         startRow = startRow || 0;
861         endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
862
863         // records to render
864         var rs = ds.getRange(startRow, endRow);
865
866         return this.doRender(cs, rs, ds, startRow, colCount, stripe);
867     },
868
869     // As much as I hate to duplicate code, this was branched because FireFox really hates
870     // [].join("") on strings. The performance difference was substantial enough to
871     // branch this function
872     doRender : Roo.isGecko ?
873             function(cs, rs, ds, startRow, colCount, stripe){
874                 var ts = this.templates, ct = ts.cell, rt = ts.row;
875                 // buffers
876                 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
877                 
878                 var hasListener = this.grid.hasListener('rowclass');
879                 var rowcfg = {};
880                 for(var j = 0, len = rs.length; j < len; j++){
881                     r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
882                     for(var i = 0; i < colCount; i++){
883                         c = cs[i];
884                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
885                         p.id = c.id;
886                         p.css = p.attr = "";
887                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
888                         if(p.value == undefined || p.value === "") p.value = "&#160;";
889                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
890                             p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
891                         }
892                         var markup = ct.apply(p);
893                         if(!c.locked){
894                             cb+= markup;
895                         }else{
896                             lcb+= markup;
897                         }
898                     }
899                     var alt = [];
900                     if(stripe && ((rowIndex+1) % 2 == 0)){
901                         alt.push("x-grid-row-alt")
902                     }
903                     if(r.dirty){
904                         alt.push(  " x-grid-dirty-row");
905                     }
906                     rp.cells = lcb;
907                     if(this.getRowClass){
908                         alt.push(this.getRowClass(r, rowIndex));
909                     }
910                     if (hasListener) {
911                         rowcfg = {
912                              
913                             record: r,
914                             rowIndex : rowIndex,
915                             rowClass : ''
916                         }
917                         this.grid.fireEvent('rowclass', this, rowcfg);
918                         alt.push(rowcfg.rowClass);
919                     }
920                     rp.alt = alt.join(" ");
921                     lbuf+= rt.apply(rp);
922                     rp.cells = cb;
923                     buf+=  rt.apply(rp);
924                 }
925                 return [lbuf, buf];
926             } :
927             function(cs, rs, ds, startRow, colCount, stripe){
928                 var ts = this.templates, ct = ts.cell, rt = ts.row;
929                 // buffers
930                 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
931                 var hasListener = this.grid.hasListener('rowclass');
932  
933                 var rowcfg = {};
934                 for(var j = 0, len = rs.length; j < len; j++){
935                     r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
936                     for(var i = 0; i < colCount; i++){
937                         c = cs[i];
938                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
939                         p.id = c.id;
940                         p.css = p.attr = "";
941                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
942                         if(p.value == undefined || p.value === "") p.value = "&#160;";
943                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
944                             p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
945                         }
946                         
947                         var markup = ct.apply(p);
948                         if(!c.locked){
949                             cb[cb.length] = markup;
950                         }else{
951                             lcb[lcb.length] = markup;
952                         }
953                     }
954                     var alt = [];
955                     if(stripe && ((rowIndex+1) % 2 == 0)){
956                         alt.push( "x-grid-row-alt");
957                     }
958                     if(r.dirty){
959                         alt.push(" x-grid-dirty-row");
960                     }
961                     rp.cells = lcb;
962                     if(this.getRowClass){
963                         alt.push( this.getRowClass(r, rowIndex));
964                     }
965                     if (hasListener) {
966                         rowcfg = {
967                              
968                             record: r,
969                             rowIndex : rowIndex,
970                             rowClass : ''
971                         }
972                         this.grid.fireEvent('rowclass', this, rowcfg);
973                         alt.push(rowcfg.rowClass);
974                     }
975                     rp.alt = alt.join(" ");
976                     rp.cells = lcb.join("");
977                     lbuf[lbuf.length] = rt.apply(rp);
978                     rp.cells = cb.join("");
979                     buf[buf.length] =  rt.apply(rp);
980                 }
981                 return [lbuf.join(""), buf.join("")];
982             },
983
984     renderBody : function(){
985         var markup = this.renderRows();
986         var bt = this.templates.body;
987         return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
988     },
989
990     /**
991      * Refreshes the grid
992      * @param {Boolean} headersToo
993      */
994     refresh : function(headersToo){
995         this.fireEvent("beforerefresh", this);
996         this.grid.stopEditing();
997         var result = this.renderBody();
998         this.lockedBody.update(result[0]);
999         this.mainBody.update(result[1]);
1000         if(headersToo === true){
1001             this.updateHeaders();
1002             this.updateColumns();
1003             this.updateSplitters();
1004             this.updateHeaderSortState();
1005         }
1006         this.syncRowHeights();
1007         this.layout();
1008         this.fireEvent("refresh", this);
1009     },
1010
1011     handleColumnMove : function(cm, oldIndex, newIndex){
1012         this.indexMap = null;
1013         var s = this.getScrollState();
1014         this.refresh(true);
1015         this.restoreScroll(s);
1016         this.afterMove(newIndex);
1017     },
1018
1019     afterMove : function(colIndex){
1020         if(this.enableMoveAnim && Roo.enableFx){
1021             this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
1022         }
1023         // if multisort - fix sortOrder, and reload..
1024         if (this.grid.dataSource.multiSort) {
1025             // the we can call sort again..
1026             var dm = this.grid.dataSource;
1027             var cm = this.grid.colModel;
1028             var so = [];
1029             for(var i = 0; i < cm.config.length; i++ ) {
1030                 
1031                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined')) {
1032                     continue; // dont' bother, it's not in sort list or being set.
1033                 }
1034                 
1035                 so.push(cm.config[i].dataIndex);
1036             };
1037             dm.sortOrder = so;
1038             dm.load(dm.lastOptions);
1039             
1040             
1041         }
1042         
1043     },
1044
1045     updateCell : function(dm, rowIndex, dataIndex){
1046         var colIndex = this.getColumnIndexByDataIndex(dataIndex);
1047         if(typeof colIndex == "undefined"){ // not present in grid
1048             return;
1049         }
1050         var cm = this.grid.colModel;
1051         var cell = this.getCell(rowIndex, colIndex);
1052         var cellText = this.getCellText(rowIndex, colIndex);
1053
1054         var p = {
1055             cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
1056             id : cm.getColumnId(colIndex),
1057             css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
1058         };
1059         var renderer = cm.getRenderer(colIndex);
1060         var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
1061         if(typeof val == "undefined" || val === "") val = "&#160;";
1062         cellText.innerHTML = val;
1063         cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
1064         this.syncRowHeights(rowIndex, rowIndex);
1065     },
1066
1067     calcColumnWidth : function(colIndex, maxRowsToMeasure){
1068         var maxWidth = 0;
1069         if(this.grid.autoSizeHeaders){
1070             var h = this.getHeaderCellMeasure(colIndex);
1071             maxWidth = Math.max(maxWidth, h.scrollWidth);
1072         }
1073         var tb, index;
1074         if(this.cm.isLocked(colIndex)){
1075             tb = this.getLockedTable();
1076             index = colIndex;
1077         }else{
1078             tb = this.getBodyTable();
1079             index = colIndex - this.cm.getLockedCount();
1080         }
1081         if(tb && tb.rows){
1082             var rows = tb.rows;
1083             var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
1084             for(var i = 0; i < stopIndex; i++){
1085                 var cell = rows[i].childNodes[index].firstChild;
1086                 maxWidth = Math.max(maxWidth, cell.scrollWidth);
1087             }
1088         }
1089         return maxWidth + /*margin for error in IE*/ 5;
1090     },
1091     /**
1092      * Autofit a column to its content.
1093      * @param {Number} colIndex
1094      * @param {Boolean} forceMinSize true to force the column to go smaller if possible
1095      */
1096      autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
1097          if(this.cm.isHidden(colIndex)){
1098              return; // can't calc a hidden column
1099          }
1100         if(forceMinSize){
1101             var cid = this.cm.getColumnId(colIndex);
1102             this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
1103            if(this.grid.autoSizeHeaders){
1104                this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
1105            }
1106         }
1107         var newWidth = this.calcColumnWidth(colIndex);
1108         this.cm.setColumnWidth(colIndex,
1109             Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
1110         if(!suppressEvent){
1111             this.grid.fireEvent("columnresize", colIndex, newWidth);
1112         }
1113     },
1114
1115     /**
1116      * Autofits all columns to their content and then expands to fit any extra space in the grid
1117      */
1118      autoSizeColumns : function(){
1119         var cm = this.grid.colModel;
1120         var colCount = cm.getColumnCount();
1121         for(var i = 0; i < colCount; i++){
1122             this.autoSizeColumn(i, true, true);
1123         }
1124         if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
1125             this.fitColumns();
1126         }else{
1127             this.updateColumns();
1128             this.layout();
1129         }
1130     },
1131
1132     /**
1133      * Autofits all columns to the grid's width proportionate with their current size
1134      * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
1135      */
1136     fitColumns : function(reserveScrollSpace){
1137         var cm = this.grid.colModel;
1138         var colCount = cm.getColumnCount();
1139         var cols = [];
1140         var width = 0;
1141         var i, w;
1142         for (i = 0; i < colCount; i++){
1143             if(!cm.isHidden(i) && !cm.isFixed(i)){
1144                 w = cm.getColumnWidth(i);
1145                 cols.push(i);
1146                 cols.push(w);
1147                 width += w;
1148             }
1149         }
1150         var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
1151         if(reserveScrollSpace){
1152             avail -= 17;
1153         }
1154         var frac = (avail - cm.getTotalWidth())/width;
1155         while (cols.length){
1156             w = cols.pop();
1157             i = cols.pop();
1158             cm.setColumnWidth(i, Math.floor(w + w*frac), true);
1159         }
1160         this.updateColumns();
1161         this.layout();
1162     },
1163
1164     onRowSelect : function(rowIndex){
1165         var row = this.getRowComposite(rowIndex);
1166         row.addClass("x-grid-row-selected");
1167     },
1168
1169     onRowDeselect : function(rowIndex){
1170         var row = this.getRowComposite(rowIndex);
1171         row.removeClass("x-grid-row-selected");
1172     },
1173
1174     onCellSelect : function(row, col){
1175         var cell = this.getCell(row, col);
1176         if(cell){
1177             Roo.fly(cell).addClass("x-grid-cell-selected");
1178         }
1179     },
1180
1181     onCellDeselect : function(row, col){
1182         var cell = this.getCell(row, col);
1183         if(cell){
1184             Roo.fly(cell).removeClass("x-grid-cell-selected");
1185         }
1186     },
1187
1188     updateHeaderSortState : function(){
1189         
1190         // sort state can be single { field: xxx, direction : yyy}
1191         // or   { xxx=>ASC , yyy : DESC ..... }
1192         
1193         var mstate = {};
1194         if (!this.ds.multiSort) { 
1195             var state = this.ds.getSortState();
1196             if(!state){
1197                 return;
1198             }
1199             mstate[state.field] = state.direction;
1200             // FIXME... - this is not used here.. but might be elsewhere..
1201             this.sortState = state;
1202             
1203         } else {
1204             mstate = this.ds.sortToggle;
1205         }
1206         //remove existing sort classes..
1207         
1208         var sc = this.sortClasses;
1209         var hds = this.el.select(this.headerSelector).removeClass(sc);
1210         
1211         for(var f in mstate) {
1212         
1213             var sortColumn = this.cm.findColumnIndex(f);
1214             
1215             if(sortColumn != -1){
1216                 var sortDir = mstate[f];        
1217                 hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
1218             }
1219         }
1220         
1221          
1222         
1223     },
1224
1225
1226     handleHeaderClick : function(g, index){
1227         if(this.headersDisabled){
1228             return;
1229         }
1230         var dm = g.dataSource, cm = g.colModel;
1231         if(!cm.isSortable(index)){
1232             return;
1233         }
1234         g.stopEditing();
1235         
1236         if (dm.multiSort) {
1237             // update the sortOrder
1238             var so = [];
1239             for(var i = 0; i < cm.config.length; i++ ) {
1240                 
1241                 if ((typeof(dm.sortToggle[cm.config[i].dataIndex]) == 'undefined') && (index != i)) {
1242                     continue; // dont' bother, it's not in sort list or being set.
1243                 }
1244                 
1245                 so.push(cm.config[i].dataIndex);
1246             };
1247             dm.sortOrder = so;
1248         }
1249         
1250         
1251         dm.sort(cm.getDataIndex(index));
1252     },
1253
1254
1255     destroy : function(){
1256         if(this.colMenu){
1257             this.colMenu.removeAll();
1258             Roo.menu.MenuMgr.unregister(this.colMenu);
1259             this.colMenu.getEl().remove();
1260             delete this.colMenu;
1261         }
1262         if(this.hmenu){
1263             this.hmenu.removeAll();
1264             Roo.menu.MenuMgr.unregister(this.hmenu);
1265             this.hmenu.getEl().remove();
1266             delete this.hmenu;
1267         }
1268         if(this.grid.enableColumnMove){
1269             var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1270             if(dds){
1271                 for(var dd in dds){
1272                     if(!dds[dd].config.isTarget && dds[dd].dragElId){
1273                         var elid = dds[dd].dragElId;
1274                         dds[dd].unreg();
1275                         Roo.get(elid).remove();
1276                     } else if(dds[dd].config.isTarget){
1277                         dds[dd].proxyTop.remove();
1278                         dds[dd].proxyBottom.remove();
1279                         dds[dd].unreg();
1280                     }
1281                     if(Roo.dd.DDM.locationCache[dd]){
1282                         delete Roo.dd.DDM.locationCache[dd];
1283                     }
1284                 }
1285                 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1286             }
1287         }
1288         Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
1289         this.bind(null, null);
1290         Roo.EventManager.removeResizeListener(this.onWindowResize, this);
1291     },
1292
1293     handleLockChange : function(){
1294         this.refresh(true);
1295     },
1296
1297     onDenyColumnLock : function(){
1298
1299     },
1300
1301     onDenyColumnHide : function(){
1302
1303     },
1304
1305     handleHdMenuClick : function(item){
1306         var index = this.hdCtxIndex;
1307         var cm = this.cm, ds = this.ds;
1308         switch(item.id){
1309             case "asc":
1310                 ds.sort(cm.getDataIndex(index), "ASC");
1311                 break;
1312             case "desc":
1313                 ds.sort(cm.getDataIndex(index), "DESC");
1314                 break;
1315             case "lock":
1316                 var lc = cm.getLockedCount();
1317                 if(cm.getColumnCount(true) <= lc+1){
1318                     this.onDenyColumnLock();
1319                     return;
1320                 }
1321                 if(lc != index){
1322                     cm.setLocked(index, true, true);
1323                     cm.moveColumn(index, lc);
1324                     this.grid.fireEvent("columnmove", index, lc);
1325                 }else{
1326                     cm.setLocked(index, true);
1327                 }
1328             break;
1329             case "unlock":
1330                 var lc = cm.getLockedCount();
1331                 if((lc-1) != index){
1332                     cm.setLocked(index, false, true);
1333                     cm.moveColumn(index, lc-1);
1334                     this.grid.fireEvent("columnmove", index, lc-1);
1335                 }else{
1336                     cm.setLocked(index, false);
1337                 }
1338             break;
1339             default:
1340                 index = cm.getIndexById(item.id.substr(4));
1341                 if(index != -1){
1342                     if(item.checked && cm.getColumnCount(true) <= 1){
1343                         this.onDenyColumnHide();
1344                         return false;
1345                     }
1346                     cm.setHidden(index, item.checked);
1347                 }
1348         }
1349         return true;
1350     },
1351
1352     beforeColMenuShow : function(){
1353         var cm = this.cm,  colCount = cm.getColumnCount();
1354         this.colMenu.removeAll();
1355         for(var i = 0; i < colCount; i++){
1356             this.colMenu.add(new Roo.menu.CheckItem({
1357                 id: "col-"+cm.getColumnId(i),
1358                 text: cm.getColumnHeader(i),
1359                 checked: !cm.isHidden(i),
1360                 hideOnClick:false
1361             }));
1362         }
1363     },
1364
1365     handleHdCtx : function(g, index, e){
1366         e.stopEvent();
1367         var hd = this.getHeaderCell(index);
1368         this.hdCtxIndex = index;
1369         var ms = this.hmenu.items, cm = this.cm;
1370         ms.get("asc").setDisabled(!cm.isSortable(index));
1371         ms.get("desc").setDisabled(!cm.isSortable(index));
1372         if(this.grid.enableColLock !== false){
1373             ms.get("lock").setDisabled(cm.isLocked(index));
1374             ms.get("unlock").setDisabled(!cm.isLocked(index));
1375         }
1376         this.hmenu.show(hd, "tl-bl");
1377     },
1378
1379     handleHdOver : function(e){
1380         var hd = this.findHeaderCell(e.getTarget());
1381         if(hd && !this.headersDisabled){
1382             if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
1383                this.fly(hd).addClass("x-grid-hd-over");
1384             }
1385         }
1386     },
1387
1388     handleHdOut : function(e){
1389         var hd = this.findHeaderCell(e.getTarget());
1390         if(hd){
1391             this.fly(hd).removeClass("x-grid-hd-over");
1392         }
1393     },
1394
1395     handleSplitDblClick : function(e, t){
1396         var i = this.getCellIndex(t);
1397         if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
1398             this.autoSizeColumn(i, true);
1399             this.layout();
1400         }
1401     },
1402
1403     render : function(){
1404
1405         var cm = this.cm;
1406         var colCount = cm.getColumnCount();
1407
1408         if(this.grid.monitorWindowResize === true){
1409             Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
1410         }
1411         var header = this.renderHeaders();
1412         var body = this.templates.body.apply({rows:""});
1413         var html = this.templates.master.apply({
1414             lockedBody: body,
1415             body: body,
1416             lockedHeader: header[0],
1417             header: header[1]
1418         });
1419
1420         //this.updateColumns();
1421
1422         this.grid.getGridEl().dom.innerHTML = html;
1423
1424         this.initElements();
1425         
1426         // a kludge to fix the random scolling effect in webkit
1427         this.el.on("scroll", function() {
1428             this.el.dom.scrollTop=0; // hopefully not recursive..
1429         },this);
1430
1431         this.scroller.on("scroll", this.handleScroll, this);
1432         this.lockedBody.on("mousewheel", this.handleWheel, this);
1433         this.mainBody.on("mousewheel", this.handleWheel, this);
1434
1435         this.mainHd.on("mouseover", this.handleHdOver, this);
1436         this.mainHd.on("mouseout", this.handleHdOut, this);
1437         this.mainHd.on("dblclick", this.handleSplitDblClick, this,
1438                 {delegate: "."+this.splitClass});
1439
1440         this.lockedHd.on("mouseover", this.handleHdOver, this);
1441         this.lockedHd.on("mouseout", this.handleHdOut, this);
1442         this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
1443                 {delegate: "."+this.splitClass});
1444
1445         if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
1446             new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1447         }
1448
1449         this.updateSplitters();
1450
1451         if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
1452             new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1453             new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1454         }
1455
1456         if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
1457             this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
1458             this.hmenu.add(
1459                 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
1460                 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
1461             );
1462             if(this.grid.enableColLock !== false){
1463                 this.hmenu.add('-',
1464                     {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
1465                     {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
1466                 );
1467             }
1468             if(this.grid.enableColumnHide !== false){
1469
1470                 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
1471                 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
1472                 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
1473
1474                 this.hmenu.add('-',
1475                     {id:"columns", text: this.columnsText, menu: this.colMenu}
1476                 );
1477             }
1478             this.hmenu.on("itemclick", this.handleHdMenuClick, this);
1479
1480             this.grid.on("headercontextmenu", this.handleHdCtx, this);
1481         }
1482
1483         if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
1484             this.dd = new Roo.grid.GridDragZone(this.grid, {
1485                 ddGroup : this.grid.ddGroup || 'GridDD'
1486             });
1487             
1488         }
1489
1490         /*
1491         for(var i = 0; i < colCount; i++){
1492             if(cm.isHidden(i)){
1493                 this.hideColumn(i);
1494             }
1495             if(cm.config[i].align){
1496                 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
1497                 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
1498             }
1499         }*/
1500         
1501         this.updateHeaderSortState();
1502
1503         this.beforeInitialResize();
1504         this.layout(true);
1505
1506         // two part rendering gives faster view to the user
1507         this.renderPhase2.defer(1, this);
1508     },
1509
1510     renderPhase2 : function(){
1511         // render the rows now
1512         this.refresh();
1513         if(this.grid.autoSizeColumns){
1514             this.autoSizeColumns();
1515         }
1516     },
1517
1518     beforeInitialResize : function(){
1519
1520     },
1521
1522     onColumnSplitterMoved : function(i, w){
1523         this.userResized = true;
1524         var cm = this.grid.colModel;
1525         cm.setColumnWidth(i, w, true);
1526         var cid = cm.getColumnId(i);
1527         this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1528         this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1529         this.updateSplitters();
1530         this.layout();
1531         this.grid.fireEvent("columnresize", i, w);
1532     },
1533
1534     syncRowHeights : function(startIndex, endIndex){
1535         if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
1536             startIndex = startIndex || 0;
1537             var mrows = this.getBodyTable().rows;
1538             var lrows = this.getLockedTable().rows;
1539             var len = mrows.length-1;
1540             endIndex = Math.min(endIndex || len, len);
1541             for(var i = startIndex; i <= endIndex; i++){
1542                 var m = mrows[i], l = lrows[i];
1543                 var h = Math.max(m.offsetHeight, l.offsetHeight);
1544                 m.style.height = l.style.height = h + "px";
1545             }
1546         }
1547     },
1548
1549     layout : function(initialRender, is2ndPass){
1550         var g = this.grid;
1551         var auto = g.autoHeight;
1552         var scrollOffset = 16;
1553         var c = g.getGridEl(), cm = this.cm,
1554                 expandCol = g.autoExpandColumn,
1555                 gv = this;
1556         //c.beginMeasure();
1557
1558         if(!c.dom.offsetWidth){ // display:none?
1559             if(initialRender){
1560                 this.lockedWrap.show();
1561                 this.mainWrap.show();
1562             }
1563             return;
1564         }
1565
1566         var hasLock = this.cm.isLocked(0);
1567
1568         var tbh = this.headerPanel.getHeight();
1569         var bbh = this.footerPanel.getHeight();
1570
1571         if(auto){
1572             var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
1573             var newHeight = ch + c.getBorderWidth("tb");
1574             if(g.maxHeight){
1575                 newHeight = Math.min(g.maxHeight, newHeight);
1576             }
1577             c.setHeight(newHeight);
1578         }
1579
1580         if(g.autoWidth){
1581             c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
1582         }
1583
1584         var s = this.scroller;
1585
1586         var csize = c.getSize(true);
1587
1588         this.el.setSize(csize.width, csize.height);
1589
1590         this.headerPanel.setWidth(csize.width);
1591         this.footerPanel.setWidth(csize.width);
1592
1593         var hdHeight = this.mainHd.getHeight();
1594         var vw = csize.width;
1595         var vh = csize.height - (tbh + bbh);
1596
1597         s.setSize(vw, vh);
1598
1599         var bt = this.getBodyTable();
1600         var ltWidth = hasLock ?
1601                       Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
1602
1603         var scrollHeight = bt.offsetHeight;
1604         var scrollWidth = ltWidth + bt.offsetWidth;
1605         var vscroll = false, hscroll = false;
1606
1607         this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
1608
1609         var lw = this.lockedWrap, mw = this.mainWrap;
1610         var lb = this.lockedBody, mb = this.mainBody;
1611
1612         setTimeout(function(){
1613             var t = s.dom.offsetTop;
1614             var w = s.dom.clientWidth,
1615                 h = s.dom.clientHeight;
1616
1617             lw.setTop(t);
1618             lw.setSize(ltWidth, h);
1619
1620             mw.setLeftTop(ltWidth, t);
1621             mw.setSize(w-ltWidth, h);
1622
1623             lb.setHeight(h-hdHeight);
1624             mb.setHeight(h-hdHeight);
1625
1626             if(is2ndPass !== true && !gv.userResized && expandCol){
1627                 // high speed resize without full column calculation
1628                 
1629                 var ci = cm.getIndexById(expandCol);
1630                 if (ci < 0) {
1631                     ci = cm.findColumnIndex(expandCol);
1632                 }
1633                 ci = Math.max(0, ci); // make sure it's got at least the first col.
1634                 var expandId = cm.getColumnId(ci);
1635                 var  tw = cm.getTotalWidth(false);
1636                 var currentWidth = cm.getColumnWidth(ci);
1637                 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
1638                 if(currentWidth != cw){
1639                     cm.setColumnWidth(ci, cw, true);
1640                     gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1641                     gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1642                     gv.updateSplitters();
1643                     gv.layout(false, true);
1644                 }
1645             }
1646
1647             if(initialRender){
1648                 lw.show();
1649                 mw.show();
1650             }
1651             //c.endMeasure();
1652         }, 10);
1653     },
1654
1655     onWindowResize : function(){
1656         if(!this.grid.monitorWindowResize || this.grid.autoHeight){
1657             return;
1658         }
1659         this.layout();
1660     },
1661
1662     appendFooter : function(parentEl){
1663         return null;
1664     },
1665
1666     sortAscText : "Sort Ascending",
1667     sortDescText : "Sort Descending",
1668     lockText : "Lock Column",
1669     unlockText : "Unlock Column",
1670     columnsText : "Columns"
1671 });
1672
1673
1674 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
1675     Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
1676     this.proxy.el.addClass('x-grid3-col-dd');
1677 };
1678
1679 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
1680     handleMouseDown : function(e){
1681
1682     },
1683
1684     callHandleMouseDown : function(e){
1685         Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
1686     }
1687 });