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