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