
//u3imgTip = new Ext.Tip({element:'body',html: '<img src="" style="" alt="">', closable: true});

Ext.grid.CheckColumn = function(config){

    Ext.apply(this, config);
    if(!this.id){
        this.id = Ext.id();
    }
this.renderer = this.renderer.createDelegate(this);
};

Ext.grid.CheckColumn.prototype ={
    init : function(grid){
        this.grid = grid;
    },

    renderer : function(v, p, record){
        p.css += ' x-grid3-check-col-td';
        return v ? '<img src="/global/ext/resources/images/default/menu/checked.gif" alt="X">' : '<img src="/global/ext/resources/images/default/menu/unchecked.gif" alt=" ">';
    }
};


// Now we can begin adding members to the Ext.u3 application using the Module Pattern
u3.tvkGrid = Ext.extend(Ext.grid.GridPanel, {
	primaryKey : 'articul',
	id: 'tvk-grid',
	onum: '',
	
	
	load : function(cfg) {
		this.store.load({params: cfg});
	},
	
	setOnum : function(o) {
		this.onum=o;
	},
	
	unsetOnum : function() {
		this.onum = '';
	},
	
	buyRenderer : function (data, metadata, record, rowIndex, columnIndex, store) {
	var articul = record.get('articul');
	var html;
	if ( articul == record.get('part_articul') ) {
		html = '<a href="javascript://" onclick="showNabor(\''+ articul + '\')">Список товаров</a>';
	} else {
		metadata.attr = 'title="Добавить к заказу"';
    	html = '<input type="text" id="qty'+ articul + '" class="x-form-text x-form-field" autocomplete="off" onclick="fixFocus(this)" onKeyPress="CaddToBasket(event,' 
    	+ rowIndex 
    	+',\'' 
    	+ articul +'\')" size="2" title="Добавить к заказу"><button title="Добавить к заказу" class="x-btn-image" style="padding: 0px; vertical-align: middle;" type="button" onclick="addToBasket(' 
    	+ rowIndex 
    	+',\'' 
    	+ articul 
    	+ '\')"><img src="/images/korzina.gif" style="vertical-align: middle"></button>';
	}
    	//return the display text:
		return html;
	},
	
	float2Renderer : function (data, metadata, record, rowIndex, columnIndex, store) {
		return data ? data.toFixed(2) : '';
	},
	
	titleRenderer : function (data, metadata, record, rowIndex, columnIndex, store) {
		if ( record.get('articul') == record.get('part_articul') ) {
			return record.get('part_title');
		} else {
			return data;
		}
	},
	
	fixImages : function (store, records, options) {

		for (var i = 0; i < records.length; i++ ) {
			var s = records[i].get('img1');
			if ( s ) {
				var obj = Ext.util.JSON.decode(s);
				records[i].set('img1file', obj.file);
				records[i].set('img1width', obj.width);
				records[i].set('img1height', obj.height);
			} 
			
			s = records[i].get('img2');
			if ( s ) {
				var obj = Ext.util.JSON.decode(s);
				records[i].set('img2file', obj.file);
				records[i].set('img2width', obj.width);
				records[i].set('img2height', obj.height);
			}
		}
	},
	
    initComponent:function() {
   	
    	// FIXME: This one should be created dynamically...
    	this.dbRecord = Ext.data.Record.create([
    		{name: '_isnew', type: 'boolean', defaultValue: false},
    		{name: '_del', type: 'boolean'},
        	{name: 'articul', type: 'string'},
        	{name: 'part_articul', type: 'string'},
        	{name: 'part_title', type: 'string'},
        	{name: '_key', type: 'string', mapping: 'articul'},
        	{name: 'code', type: 'string'},
            {name: 'onum', type: 'string'},  //type = how the data should be displayed
            {name: 'grp', type: 'int', defaultValue: this.dbGrp},
            {name: 'tm', type: 'string'},
        	{name: 'collection', type: 'string'},
            {name: 'name', type: 'string'},
			{name: 'description', type: 'string'},
            {name: 'oldprice', type: 'float'},
            {name: 'price', type: 'float'},
            {name: 'aspb', type: 'boolean'},
            {name: 'amsk', type: 'boolean'},
            {name: 'aeburg', type: 'boolean'},
            {name: 'anovosib', type: 'boolean'},
            {name: 'asamara', type: 'boolean'},
            {name: 'akrasnoyarsk', type: 'boolean'},
            {name: 'arostov', type: 'boolean'},
            {name: 'img1', type: 'string'},
            {name: 'img1width', type: 'string'},
            {name: 'img1height', type: 'string'},
            {name: 'img1file', type: 'string'},
            {name: 'img2', type: 'string'},
            {name: 'img2width', type: 'string'},
            {name: 'img2height', type: 'string'},
            {name: 'img2file', type: 'string'}
        ]);
        
    	var u3reader =  new Ext.data.JsonReader(
    		{ //creates array from JSON response
            	root: 'items', // name of the property that is container for an Array of row objects
            	totalProperty: 'recordsTotal',
            	id: this.primaryKey //the property within each row object that provides an ID for the record (optional)
        	},
        	this.dbRecord //instead of defining inline just pass a reference to the object 
    	);
        
        
        // Ext.data.HttpProxy has event named loadexception : ( Object this, Object options, Object response, Error e )
    	var u3ds = new Ext.ux.data.PagingStore({
            proxy: new Ext.data.HttpProxy({
                //where to retrieve data
                url: '/ajax.pl', //url to data object (server side script)
                method: 'POST'
            }),
            reader: u3reader,
            baseParams: { '_function' : 'TVKOfferSearch' },
            lastOptions: { params: { start: 0, limit: u3gridPerPage} },
            autoLoad: false,
            listeners: {
            	load: function(store, records, opt) {
            		var grid = Ext.getCmp('u3tvkgrid');
            		grid.expand();
            		if(opt.params && opt.params.onum) {
            			var i = Ext.getCmp('offers-view').store.find('onum', opt.params.onum);
            			if ( i > -1 ) {
            				var r = Ext.getCmp('offers-view').store.getAt(i);
            				grid.setTitle( '<span style="font-weight: bold">' + r.get('slogan') + '</span>');
            			} else {
            				grid.setTitle( '<span style="font-weight: bold">Товары:' + '' + '</span>');
            			}
            		} else {
            			grid.setTitle( '<span style="font-weight: bold">Товары:' + '' + '</span>');
            		}
            	},
            	beforeload : function(store, opt) {
            		var grid = Ext.getCmp('u3tvkgrid');
            		if ( opt.params && ! opt.params.onum && grid.onum != '' ) {
            			opt.params.onum = grid.onum;
            		}
            		return true;
            	}
            }
      	});
      	
      	u3ds.on('load', this.fixImages, this );
      	u3ds.on('loadexception',
      	function (th, options,  response,  e ) {
      		Ext.MessageBox.alert('Ошибка загрузки ТВК!', e);
      	}, this );

        this.imageColumn = new u3.ImageColumn ({
                    header:"Вид",//header = text that appears at top of column
                    width: 50,      //column width
                    sortable: false,//false (default) to disable sorting by this column
                    dataIndex: 'img1'//the DataStore field "name" this column draws its data from
        });

        
    	this.c1 = new Ext.grid.CheckColumn({
       				header: "Спб",
       				dataIndex: 'aspb',
       				width: 75
    			});
    	this.c2 = new Ext.grid.CheckColumn({
       				header: "Москва",
       				dataIndex: 'amsk',
       				width: 75
    			});			
 		this.c3 = new Ext.grid.CheckColumn({
       				header: "Екатеринбург",
       				dataIndex: 'aeburg',
       				width: 75
    			});
    	this.c4 = new Ext.grid.CheckColumn({
       				header: "Новосибирск",
       				dataIndex: 'anovosib',
       				width: 75
    			});               
  		this.c5 = new Ext.grid.CheckColumn({
       				header: "Самара",
       				dataIndex: 'asamara',
       				width: 75
    			});
  		this.c6 = new Ext.grid.CheckColumn({
       				header: "Красноярск",
       				dataIndex: 'akrasnoyarsk',
       				width: 75
    			});
  		this.c7 = new Ext.grid.CheckColumn({
       				header: "Ростов",
       				dataIndex: 'arostov',
       				width: 75
    			});

    	
    	
		Ext.apply(this,{
		        store: u3ds,       //the DataStore object to use (ds: is shorthand)
            	colModel: this.getColumnModel(u3ds), //gets the ColumnModel object to use (cm: is shorthand)
            	//autoExpandColumn: 'title', //which column to stretch in width to fill up the grid width and not leave blank space
            //Enable a Selection Model.  The Selection Model defines the selection behavior,
            //(single vs. multiple select, row or cell selection, etc.)
            selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),//true to limit row selection to 1 row})
           //footer: true,
            plugins: [this.imageColumn, this.c1,this.c2,this.c3,this.c4,this.c5, this.c6, this.c7],
            stripeRows: false,
            bbar:new Ext.PagingToolbar({
                store: u3ds,
                pageSize: u3gridPerPage,
                displayInfo: true,
                displayMsg: 'Товары {0} - {1} из {2}',
                emptyMsg: "Нет данных для показа"
        	})
		});
        // call parent initComponent
        u3.tvkGrid.superclass.initComponent.call(this);
        
        this.loadingMask = new Ext.LoadMask(Ext.getBody(), {msg:"Пожалуйста подождите, идёт загрузка информации...", store: this.store});
    } // end of function initComponent
});
//-> this = window



u3.tvkGrid.prototype.getColumnModel = function (store) {

          return new Ext.grid.ColumnModel([
				this.imageColumn,
                {
                    header: "ТМ", 
                    width: 100, 
                    sortable: true,
                    dataIndex: 'tm'
                },{
                    header: "Коллекция", 
                    width: 70, 
                    sortable: true,
                    dataIndex: 'collection'
                },
                {
                    header: "Описание", 
                    id: "tvk-grid-descr-column",
                    width: 150, 
                    sortable: true,
                    renderer: this.titleRenderer,
                    dataIndex: 'description'
                },
                 {
                    header: "Артикул", 
                    width: 100, 
                    sortable: true,
                    dataIndex: 'articul'
                },
                {
                    header: "Код", 
                    width: 90, 
                    sortable: true,
                    dataIndex: 'code'
                },
                {
                    header: "Старая цена<br>у.е.", 
                    width: 80, 
                    sortable: true,
                    dataIndex: 'oldprice',
                    align: 'right',
                    renderer: this.float2Renderer
                },
                {
                    header: "Новая цена<br>у.е.", 
                    width: 80, 
                    sortable: true,
                    dataIndex: 'price',
                    align: 'right',
                    renderer: this.float2Renderer
                },
                {
                    header: "Ваш заказ/шт.", 
                    width: 80, 
                    sortable: false,
                    dataIndex: 'articul',
                    renderer: this.buyRenderer
                },
				this.c1,
				this.c2,
				this.c3,
				this.c4,
				this.c5,
				this.c6,
				this.c7
            ]);//end colModel
}

// register xtype
Ext.reg('u3tvkgrid', u3.tvkGrid);
