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