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