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