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