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