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