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