/**
 * @class Ext.grid.TableGrid
 * @extends Ext.grid.Grid
 * A Grid which creates itself from an existing HTML table element.
 * @constructor
 * @param {String/HTMLElement/Ext.Element} table The table element from which this grid will be created - 
 * The table MUST have some type of size defined for the grid to fill. The container will be 
 * automatically set to position relative if it isn't already.
 * @param {Object} config A config object that sets properties on this grid and has two additional (optional)
 * properties: fields and columns which allow for customizing data fields and columns for this grid.
 * @history
 * 2007-03-01 Original version by Nige "Animal" White
 * 2007-03-10 jvs Slightly refactored to reuse existing classes
 */

Ext.grid.TableGrid = function(table, config){

	config = config ||
	{};
	Ext.apply(this, config);
	var cf = config.fields || [], ch = config.columns || [];
	this.table = Ext.get(table);
	
	var ct = this.table.insertSibling();
	
	var fields = [], cols = [];
	var headers = this.table.query("thead th");
	for (var i = 0, h; h = headers[i]; i++) {
		var text = h.innerHTML;
		var name = 'tcol-' + i;
		
		/* Общие свойства: */
		var field = {
			name: name,
			type: 'string',
			mapping: 'td:nth(' + (i + 1) + ')/@innerHTML'
		}
		var col = {
			'header': text,
			'menuDisabled': (h.className.indexOf('grid_sort') != -1) ? false : true,
			'cls': h.className,
			'dataIndex': name,
			'width': h.offsetWidth,
			'tooltip': h.title,//данные для тултипа, надо добавить инициализацию Quicktips
			'sortable': (h.className.indexOf('grid_sort') != -1) ? true : false,
			'resizable': false
			//		'stripeRows': true,//полосатит строчки
		}
		/* Частные свойства */
		col.suffix = h.getAttribute('suffix');
		col.prefix = h.getAttribute('prefix');
		field.type = 'string';//тип данных строка по дефолту 
		if (h.className.indexOf('grid_date') != -1) { //в ячейках даты
			field.type = 'date';//тип данных для сортировки
			field.dateFormat = 'd.m.Y';//формат приёма дат из ячеек
			col.renderer = formaterDate;//форматтер для дат
		} else if (h.className.indexOf('grid_dec') != -1 || h.className.indexOf('grid_int') != -1) { //числа c 4 десятичными знаками
			field.type = 'float';
			field.sortType = sortTypeFloat;
			col.renderer = getCustomNumberFormatter(h.className);
		}
		
		fields.push(Ext.applyIf(cf[i] ||
		{}, field));
		cols.push(Ext.applyIf(ch[i] ||
		{}, col));
	}

	
	var ds = new Ext.data.Store({
		reader: new Ext.data.XmlReader({
			record: 'tbody tr'
		}, fields)
	});
	
	ds.loadData(this.table.dom);
	
	var a = 1;
	var cm = new Ext.grid.ColumnModel(cols);
	
	if (config.width || config.height) {
		ct.setSize(config.width || 'auto', config.height || 'auto');
	}
	else {
		ct.setWidth(this.table.getWidth());
	}
	Ext.applyIf(this, {
		'ds': ds,
		'cm': cm,
		'sm': new Ext.grid.RowSelectionModel(),
		autoHeight: true,
		autoWidth: true
	});
    this.view = new Ext.grid.SimpleGridView();
	Ext.grid.TableGrid.superclass.constructor.call(this, ct, {});
}

Ext.grid.SimpleGridView = Ext.extend(Ext.grid.GridView, {
    initTemplates : function(){

        var ts = this.templates || {};
        if(!ts.row){
            ts.row = new Ext.Template(
                    '<div class="x-grid3-row {alt} {rowcls}" style="{tstyle}"><table class="x-grid3-row-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
                    '<tbody><tr>{cells}</tr>',
                    (this.enableRowBody ? '<tr class="x-grid3-row-body-tr" style="{bodyStyle}"><td colspan="{cols}" class="x-grid3-body-cell" tabIndex="0" hidefocus="on"><div class="x-grid3-row-body">{body}</div></td></tr>' : ''),
                    '</tbody></table></div>'
                    );
        }
        this.templates = ts;

        Ext.grid.SimpleGridView.superclass.initTemplates.call(this);
	},
    renderHeaders : function(){
		var cm = this.cm, ts = this.templates;
        var ct = ts.hcell;

        var cb = [], sb = [], p = {};
        var len = cm.getColumnCount();
        var last = len - 1;
        for(var i = 0; i < len; i++){
            p.id = cm.getColumnId(i);
            p.value = cm.getColumnHeader(i) || "";
            p.style = this.getColumnStyle(i, true);
            p.tooltip = this.getColumnTooltip(i);
            p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '');

/* Fedos */
			if((i+1) % 2 == 0) //подсветка колонок
				p.css += ' x-grid3-col-even';
			else
				p.css += ' x-grid3-col-odd';
            if (cm.config[i].cls) {
				p.css += ' ' + cm.config[i].cls;
			}
/* /Fedos */			
            if(cm.config[i].align == 'right'){
                p.istyle = 'padding-right:16px';
            } else {
                delete p.istyle;
            }
            cb[cb.length] = ct.apply(p);
        }
        return ts.header.apply({cells: cb.join(""), tstyle:'width:'+this.getTotalWidth()+';'});
    },
    doRender : function(cs, rs, ds, startRow, colCount, stripe){
        var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1;
        var tstyle = 'width:'+this.getTotalWidth()+';';
        // buffers
        var buf = [], cb, c, p = {}, rp = {tstyle: tstyle}, r;
        for(var j = 0, len = rs.length; j < len; j++){
            r = rs[j]; cb = [];
/* Fedos*/
			var childelems = r.node.childNodes, cellz = [];
			for(var k=0; k<childelems.length;k++){//формируем массив ячеек строки
				if(childelems[k].nodeName == 'TD')
					cellz.push(childelems[k]);
			}
/* /Fedos*/

            var rowIndex = (j+startRow);
            for(var i = 0; i < colCount; i++){
                c = cs[i];
				p.id = c.id;
                p.css = i == 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '');
                p.attr = p.cellAttr = "";
/* Fedos*/
				if (cellz[i].className)
					p.css += ' ' + cellz[i].className;
				if((i+1) % 2 == 0) //подсветка колонок
					p.css += ' x-grid3-col-even';
				else
					p.css += ' x-grid3-col-odd';

	            if (this.cm.config[i].cls) {
					p.css += ' ' + this.cm.config[i].cls;
				}

				p.prefix = cellz[i].getAttribute('prefix');
				p.suffix = cellz[i].getAttribute('suffix');
				
				if(!p.prefix) p.prefix = r.node.getAttribute('prefix');
				if(!p.suffix) p.suffix = r.node.getAttribute('suffix');
				
				if(!p.prefix) p.prefix = this.cm.config[i].prefix;
				if(!p.suffix) p.suffix = this.cm.config[i].suffix;
				
				
				if(cellz[i].className && getCustomNumberFormatter(cellz[i].className)) {
					p.value = getCustomNumberFormatter(cellz[i].className)(r.data[c.name], p, r, rowIndex, i, ds);
				} else {
					p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
				}
/* /Fedos*/
                p.style = c.style;
				if(p.value == undefined || p.value === "") p.value = "&#160;";
                if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
                    p.css += ' x-grid3-dirty-cell';
                }
                cb[cb.length] = ct.apply(p);
            }
            var alt = [];
            if(stripe && ((rowIndex+1) % 2 == 0)){
                alt[0] = "x-grid3-row-alt";
            }
            if(r.dirty){
                alt[1] = " x-grid3-dirty-row";
            }
            rp.cols = colCount;
            if(this.getRowClass){
                alt[2] = this.getRowClass(r, rowIndex, rp, ds);
            }
            rp.alt = alt.join(" ");
			rp.rowcls = r.node.className;
            rp.cells = cb.join("");
            buf[buf.length] =  rt.apply(rp);
        }
        return buf.join("");
    }
});


Ext.onReady(function() {
	Ext.BLANK_IMAGE_URL = '/fileadmin/templates/main/js/grids/imgs/s.gif';
	Ext.QuickTips.init();
	Ext.extend(Ext.grid.TableGrid, Ext.grid.GridPanel);
    // create the grid
	var tables = Ext.DomQuery.select('.simplegrid');
	if(tables){
		var table;
		for(var i = 0; i <  tables.length; i++) {
			table = new Ext.grid.TableGrid(tables[i], {
			    stripeRows: true, // stripe alternate rows
			    autoHeight: true,
				enableColumnMove:true,
				enableColumnHide:false,
				enableHdMenu:false,
				cls: tables[i].className, //проставляет классы исходной таблицы в div грида
				listeners : {
					render : function () {
						if (this.table) {
							this.table.setDisplayed(false);
						}
					}
				}
		    });
		    table.render();
		}
	}
});
