Laverna.BasketWindow = Ext.extend(Ext.Window, {
	initComponent:function() {
	
	this.store = new Ext.data.SimpleStore({
        					fields:
            				[
                				'tm',
                				'collection',
                				'description',
                				'articul',
                				'part_articul',
                				'stamp',
                				'code',
                				'qty',
                				'price',
                				'total'
            				]
        					,data:  []
		});
		
		this.dbRecord = Ext.data.Record.create([
        	{name: 'tm', type: 'string'},
        	{name: 'collection', type: 'string'},
			{name: 'description', type: 'string'},
        	{name: 'articul', type: 'string'},
        	{name: 'part_articul', type: 'string'},
        	{name: 'stamp', type : 'int'},
        	{name: 'code', type: 'string'},
			{name: 'qty', type: 'int'},
			{name: 'price', type: 'float'},
			{name: 'total', type: 'float'},
			{name: 'del', type: 'string'}
        ]);
        
        this.total = new Ext.Toolbar.TextItem({text: ' '});
		
		Ext.apply( this, {
                    minHeight: 30,
                    minWidth: 300,
                    width: 790,
                    height: 500,
                    title:'Ваш заказ',
                    layout: 'fit',
                    modal: true,
					closeAction: 'hide',
                    closable:true,
					items : 
					[{
						xtype: 'grid',
						store: this.store,
						autoExpandColumn: 'description',
						autoScroll: true,
            			columns: [
        					{header: "ТМ", width: 100, sortable: true, dataIndex: 'tm'},
        					{header: "Коллекция", width: 100, sortable: true, dataIndex: 'collection'},
        					{header: "Описание", id: 'description', width: 200, sortable: true, dataIndex: 'description', renderer: this.qtipRenderer},
        					{header: "Артикул", width: 80, sortable: true, dataIndex: 'articul'},
        					{header: "Код", width: 80, sortable: true, dataIndex: 'code'},
        					{header: "Кол-во", width: 30, sortable: true, dataIndex: 'qty'},
        					{header: "Цена,у.е.", width: 65, sortable: true, dataIndex: 'price', renderer: Ext.util.Format.Money},
        					{header: "Всего,у.е.", width: 65, sortable: true, dataIndex: 'total', renderer: Ext.util.Format.Money},
        					{header: "Удалить", width: 65, sortable: false, dataIndex: 'del', renderer: this.delRenderer, iconCls:'remove'}
    					],

            			selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),//true to limit row selection to 1 row})

			            stripeRows: false,
			            viewConfig: {
        					//forceFit: true
        				},
        				frame:true,
        				bbar : [
        					'->',
							{xtype: 'tbtext', text: 'Итого: '},
							this.total,
							{xtype: 'tbtext', text: '&nbsp;у.е.'}
						],
						listeners : {
							'cellclick' : function(grid, rowIndex, columnIndex, e) {
       							 // Get the Record for the row
       							 var store = grid.getStore();
        						var record = store.getAt(rowIndex);
        						// Get field name for the column
        						var fieldName = grid.getColumnModel().getDataIndex(columnIndex);
        						if ( fieldName == 'del' ) {
        							var flag = false;
        							if ( record.get('part_articul') ) {
        								var art = record.get('articul');
        								if ( record.get('part_articul') == art ) {
        									var a = new Array();
        									store.each(function(r) {
        										if ( r.get('part_articul') == art ) {
        											store.remove(r);
        											flag = true;
        										}
        									});
        								}
        							} else {
        								store.remove(record);
        								flag = true;
        							}
        							if ( flag) {
        								var t = 0.0;
    									store.each( function (r) {t = t + parseFloat(r.get('total'))} );
    									Laverna.basket.total.getEl().innerHTML = t.toFixed(2);
        							}
        						}
    						}
						}
					}],
					buttons: [{
						id: 'u3-media-selector-ok-btn',
						text: 'Печать',
						handler: function(){ this.print(); },
						scope: this
					},{
						id: 'u3-media-selector-ok-btn',
						text: 'Загрузить в Excel',
						handler: function(){ this.loadExcel(); },
						scope: this
					},
					{
						text: 'Закрыть',
						handler: function(){ this.hide(); },
						scope: this
					}],
					keys: {
						key: 27, // Esc key
						handler: function(){ this.hide(); },
						scope: this
					}
		});
		
		Laverna.BasketWindow.superclass.initComponent.call(this, arguments);
	},
	
	delRenderer : function (v, p, r){
		if ( r.get('part_articul') ) {
			if ( r.get('part_articul') == r.get('articul') ) {
				return '<img src="/images/toolbar-del.gif">';
			} else {
				return '';
			}
		}
       	return '<img src="/images/toolbar-del.gif">';
	},
	
	qtipRenderer : function (data, metadata, record, rowIndex, columnIndex, store) {
    	metadata.attr = 'ext:qtip="' + data + '"';
 
    	//return the display text:
		return data;
	},
	
	addItem : function (rec, qty, stamp ) {
		var tot = parseInt(qty) * parseFloat(rec.get('price'));
		var p = new this.dbRecord({
        	articul : rec.get('articul'),
        	part_articul : rec.get('part_articul'),
        	stamp : stamp,
        	code : rec.get('code'),
        	tm : rec.get('tm'),
        	collection : rec.get('collection'),
            description : rec.get('description'), 
            price : rec.get('price'),
            qty : qty,
            total : tot.toFixed(2)
    	});
    
    	this.store.insert(0, p);
    	var t = 0.0;
    	this.store.each( function (r) {t = t + parseFloat(r.get('total'))} );
    	
    	this.total.getEl().innerHTML = t.toFixed(2);
    	Ext.MessageBox.alert('Заказ', qty == 1 ? 'Товар "' + rec.get('description')+ '" добавлен в корзину' : 'Товары "'  +rec.get('description') + '" добавлены в корзину');
	},
	
	fillPrintIframe : function(hasTotal) {
		if ( ! this.iframe ) {

			this.iframe = new Ext.ux.ManagedIFrame({
				autoCreate: { html : '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><title>Заказ</title></head><body><div class="basket-print-area"></div></body></html>'},
				listeners: {
       				domready : function(frame){ //only raised for "same-origin" documents
       					var doc= frame.getDocument();
 						var rule = '* {font-size: 9pt;} table, tr, td, th {border: solid 1px grey; } td {padding: 2pt;}';
            			frame.CSS.createStyleSheet( rule, 'u3csspopup' );
       				}
       			}
			});
			//this.iframe.getDocument().CSS.createStyleSheet('* {font-size: 9pt;} table, tr, td {border: solid 1px grey; } td {padding: 2pt;}', 'u3csspopup');
		}

		var html = '<h1>Зaказ </h1>';
		
		if ( hasTotal ) {
			html += '<table style="border-collapse: collapse; font-size: 9pt;">';
		} else {
		 	html += '<table border="1">';
		 }
		 html += '<thead><tr><th>ТМ</th><th>Коллекция</th><th>Описание</th><th>Артикул</th><th>Код</th><th>Цена,у.е.</th><th>Кол-во</th><th>Итого,у.е.</th></tr></thead><tbody>';
		
		var t = 0.0;
		var q = 0;

		this.store.each( function (r) {
			var price = r.get('price').toFixed(2);
			var total = parseFloat(r.get('total')).toFixed(2);
			html += String.format('<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>&nbsp;{3}</td><td>{4}</td><td x:num="{5}">{6}</td><td>{7}</td><td x:num="{8}">{9}</td></tr>',
				r.get('tm'),r.get('collection'),r.get('description'),r.get('articul'),r.get('code'),price,price.replace('.',','), r.get('qty'),total, total.replace('.',','));
			t = t + parseFloat(r.get('total'));
			q = q + r.get('qty');
		} );

		if ( hasTotal) {html += String.format('<tr><td colspan="6" style="text-align: right">Итого:</td><td>{0}</td><td>{1}</td></tr>', q,t.toFixed(2));}
		html += '</tbody></table>';
		this.iframe.update(html);
	},
	
	print : function () {
		this.fillPrintIframe(true);
		this.iframe.print();
	},
	
	loadExcel : function () {
		this.fillPrintIframe(false);
		if ( this.eFrame ) {
			this.eFrame.destroy();
		}
		this.eFrame = new Ext.ux.ManagedIFrame({autoCreate: { html : '<html><title>Заказ</title></head><body></body></html>'}});
		
		this.eFrame.update('<form id="u3form7" method="POST" action="/ajax.pl"><input type="hidden" name="_function" value="pingPongExcel"><input id="u3html7" type="hidden" name="html" value=""></form>');


		this.eFrame.fly('u3html7').dom.value =  '<html>' + this.iframe.getDocument().documentElement.innerHTML + '</html>';
		allowPageUnload = true;
		this.eFrame.fly('u3form7').dom.submit();
		(function(){allowPageUnload= false;}).defer(1000);
	}
	
});
	
