function filterJSON (store, records, options) {
	for (var i = 0; i < records.length; i++ ) {
		var s = records[i].get('img1');
		if ( s && s != '{}' ) {
			var obj = Ext.util.JSON.decode(s);
			records[i].set('img1file', obj.file);
			records[i].set('img1width', obj.width);
			if ( parseInt(obj.width) > 210 ) {
				records[i].set('style', 'width: ' + obj.width + 'px;');
			} else {
				records[i].set('style', 'width: 210px;');
			}
			records[i].set('img1height', obj.height);
			records[i].set('img1title', obj.title);
		}
		u3FormatDate(records[i],'start');
		u3FormatDate(records[i],'finish');

	}
	gridMask.hide();
}

function u3FormatDate(record, col) {
	var val = record.get(col);
    	if ( val instanceof Date ) {
    		d = val;
    	} else {
    	 	d = Date.parseDate(val,"Y-m-dT00:00:00");
    	 	if ( d == undefined ) {
    			d = Date.parseDate(val,"Y-m-d");
    		}
    		if ( d == undefined ) {
    			d = Date.parseDate(val,"d/m/y");
    		}
    	}

    	if ( d ) { 
    		record.set(col, d.getDate() + "." + (d.getMonth() + 1) + "." +  d.getFullYear());
    	}

}

function fixFocus(i) {
	(function(){i.focus();}).defer(500);
}

function showBasket() {
	if ( Laverna.basket.store.getCount() == 0 ) {
		Ext.MessageBox.alert('Заказ:','Вы ничего не заказали.');
	} else {
		Laverna.basket.show();
	}
}

function CaddToBasket(event, idx, articul) {
  if (typeof event == 'undefined') {
    event = window.event;
  }
	if (event.keyCode == 13) {
		addToBasket(idx, articul);
	}
}

function addToBasket(idx, articul) {
	var q = document.getElementById('qty' + articul);
	var qty = parseInt(q.value);

	if ( isNaN(qty) || qty == 0 ) {
		Ext.MessageBox.alert('Внимание!','Не указано количество для покупки товара');
		return;
	}
	
	var src = Ext.getCmp('u3tvkgrid').store;
	var i = src.find('articul',articul);

	if ( i == -1 ) return;
	var r = src.getAt(i);
	Laverna.basket.addItem(r, qty);
	
    //Laverna.basket.show();
}

u3.ImageColumn = function(config){

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

u3.ImageColumn.prototype = {
    init : function(grid){
        this.grid = grid;
    },
    renderer : function(v, p, r){
    	var file, w, h;

    	if ( ! r.data['img1file'] ) {
    		file = '../empty.png';
    		h = 22;
    		w = 22;
    	} else {
    		file = r.data['img1file'];
    		h = r.data['img1height'];
    		w = r.data['img1width'];
    	}
    	
       	return String.format("<div class='x-grid3-image-{6}' style='background: url(/images/u/{0}) no-repeat; width:{1}px; height:{2}px;' ext:qtip='<img src=\"/images/u/{3}\" width=\"{4}\" height=\"{5}\">'></div>", file, w, h, r.data['img2file'], r.data['img2width'],r.data['img2height'], this.id );
    }
};

var firstLoad = true;
var u3gridPerPage = 20;
var gridMask;
var allowPageUnload = false;
var u3History = new Array();

var myProxy = new Ext.data.HttpProxy({
                				//where to retrieve data
                				url: '/ajax.pl', //url to data object (server side script)
                				method: 'POST'
            				});


Laverna.tgrpStore = new Ext.data.SimpleStore({
         					id:0,
        					fields:
            				[
                				'grp',
                				'title',
                				'img1file',
                				'img1width',
                				'img1height',
                				'style'
                				
            				]
        					,data:  [
               				[1,'Сантехника','main/1.jpg', 250,170,''],
							[2,'Смесители','main/2.jpg', 250, 170,''],
							[3,'Мебель для ванной комнаты', 'main/3.jpg', 250, 170,''],
							[4,'Фитинги', 'main/4.jpg', 180, 170,'clear: both'],
							[5,"Аксессуары\n для ванной комнаты", 'main/5.jpg', 180, 170,''],
							[6,"Аксессуары\n для хранения",'main/6.jpg', 180, 170,''],
							[7,"Аксессуары\n для кухни", 'main/7.jpg', 180, 170,'']
               				]
});

var offersStore = new Ext.data.Store({
            				proxy: myProxy,
            				reader: new Ext.data.JsonReader(
    							{ //creates array from JSON response
            						root: 'items' // name of the property that is container for an Array of row objects
        						},
        						[
        						{name: 'onum', type: 'string'},
        						{name: 'tm', type: 'string'},
        						{name: 'slogan', type: 'string'},
        						{name: 'start', type: 'string'},
        						{name: 'finish', type: 'string'},
        						{name: 'description', type: 'string'},
        						{name: 'img1', type: 'string'},
        						{name: 'img1file', type: 'string'},
        						{name: 'img1width', type: 'string'},
        						{name: 'img1height', type: 'string'},
        						{name: 'img1title', type: 'string'},
        						{name: 'style', type: 'string'}
        						]//instead of defining inline just pass a reference to the object 
    						),
            				sortInfo:{field: 'finish', direction: "DESC"},
            				autoLoad: false,
            				listeners : {
            					'load' : {fn: filterJSON, scope: this}
            				}
    });

var tmStore = new Ext.data.Store({
            				proxy: myProxy,
            				reader: new Ext.data.JsonReader(
    							{ 
            						root: 'tm' 
        						},
        						[
        						{name: 'tm', type: 'string'}
								]
    						),
            				sortInfo:{field: 'tm', direction: "ASC"},
            				autoLoad: false,
            				listeners: {
            					load : {
            						fn: function(store, records,  options  ){
            							var v = Ext.getCmp('u3-s-tm');
            							if ( v ) {
            								v = v.getValue();
            								if ( !v ) {
            									Ext.getCmp('u3-s-tm').setValue(' Любая');
            								}
            							}
            						}
            					}
            				}
    });

var collectionStore = new Ext.data.Store({
            				proxy: myProxy,
            				reader: new Ext.data.JsonReader(
    							{ //creates array from JSON response
            						root: 'collection' // name of the property that is container for an Array of row objects
        						},
        						[
        						{name: 'collection', type: 'string'}
								]
    						),
            				sortInfo:{field: 'collection', direction: "ASC"},
            				autoLoad: false,
            				listeners: {
            					load : {
            						fn: function(store, records,  options  ){
            							var v = Ext.getCmp('u3-s-collection');
            							if ( v ) {
            								v = v.getValue();
            								if ( !v ) {
            									Ext.getCmp('u3-s-collection').setValue(' Любая');
            								}
            							}
            						}
            					}
            				}
    });
    
var nameStore = new Ext.data.Store({
            				proxy: myProxy,
            				reader: new Ext.data.JsonReader(
    							{ //creates array from JSON response
            						root: 'name' // name of the property that is container for an Array of row objects
        						},
        						[
        						{name: 'name', type: 'string'}
								]
    						),
            				sortInfo:{field: 'name', direction: "ASC"},
            				autoLoad: false,
            				listeners: {
            					load : {
            						fn: function(store, records,  options  ){
            							var v = Ext.getCmp('u3-s-name');
            							if ( v) {
            								v = v.getValue();
            								if ( !v ) {
            									Ext.getCmp('u3-s-name').setValue(' Любое');
            								}
            							}
            						}
            					}
            				}
    });

var mainStore = new Ext.data.Store({
            				proxy: myProxy,
            				reader: new Ext.data.JsonReader(
    							{ //creates array from JSON response
            						root: 'groups' // name of the property that is container for an Array of row objects
        						},
        						[{name: 'grp', type: 'int'}, {name: 'grp_title', type: 'string'}]//instead of defining inline just pass a reference to the object 
    						),
            				baseParams: {'_function' : 'TVKSearch' },
            				sortInfo:{field: 'grp', direction: "ASC"},
            				autoLoad: true,
            				listeners: {
            					load : {
            						fn: function(store, records,  options  ){
            							 form = Ext.getCmp('u3searchForm');
            							 if ( form && form.items ) { 
            							 	form.items.each( function(c) {
            							 		if (c.xtype == 'combo') {
            							 			c.collapse();
            							 			c.hasFocus = false;
            							 			if ( firstLoad && c.name == 'grp' ) {
            							 				c.setValue('0');
            							 			}
            							 		} 
            							 	});
            							 }
            						
            							if ( gridMask ) gridMask.hide();
										 //collectionsStore.loadData( this.reader.jsonData , false ); // for a dataPanel
										
										 
										 if ( firstLoad ) {
										 	firstLoad = false;
										 	
										 	tmStore.loadData( this.reader.jsonData , false );
										 	collectionStore.loadData( this.reader.jsonData , false );
										 	nameStore.loadData( this.reader.jsonData , false );
											var fn = function() {
										 		var col = Ext.getCmp('u3searchFormPanel');
										 		if ( col ) col.expand();
										 	}
										 	fn.defer(100);
										 } else {
										 	if ( options.params.lastCombo != 'tm' || options.params.tm.search(' ') == 0) {
											 	tmStore.loadData( this.reader.jsonData , false );
											 }
											 if ( options.params.lastCombo != 'collection' || options.params.collection.search(' ') == 0) {
											 	collectionStore.loadData( this.reader.jsonData , false );
											 }
											 if ( options.params.lastCombo != 'name' || options.params.name.search(' ') == 0) {
											 	nameStore.loadData( this.reader.jsonData , false );
											 }

            							 	if ( options.params._results == 1 ) {
            							 		if ( this.reader.jsonData.items.length < 1 ) {
	            							 		Ext.MessageBox.alert('Внимание!', 'Ничего не найдено по вашему запросу.<br>Попробуйте изменить условия поиска');
    		       							 	} else {
            								 		var col = Ext.getCmp('u3tvkgrid');
            								 		// to support paging... HACK
            								 		col.unsetOnum();
            								 		col.store.lastOptions={start: 0, limit: u3gridPerPage};
            								 		col.store.loadData( this.reader.jsonData , false );
            								 		col.expand();
            								 	}
            								 }
            							 }
            						}
            					}
            				}
      					});



function makeSearch (combo, record, idx) {
	

	form = Ext.getCmp('u3searchForm');

	var param = {};
	form.items.each( function(c) {
		if ( c.xtype == 'combo' || c.xtype == 'textfield') {
			param[c.name] = c.getValue();
		}
	});
	param.selectedCombo = '';
	if ( ! combo ) {
		param._results = 1;
		gridMask.show(); 
	} else {
		param.lastCombo = '';
		
		var val = combo.getValue();
		if ( combo.xtype == 'combo' ) {
			param.selectedCombo = combo.name;
			if ( combo.name == 'grp' ) {
				if ( val != 0) {
					param.lastCombo = combo.name;
				}
			} else {
				if ( val.search(' Люб') != 0) {
					param.lastCombo = combo.name;
				}
			}
		}
	}
	param.p1 = Ext.getCmp('u3p1').getValue();
	param.p2 = Ext.getCmp('u3p2').getValue();
	
	if ( param._results == 1 )  {
	     param._u3store = 'mainStore';
         u3History.push( {params: param}  );
         Ext.History.add( u3History.length );
    } else {
		mainStore.load({params: param});
	}
}

function showNabor(articul) {
	// we search for the record....
	var i = Ext.getCmp('u3tvkgrid').store.find('articul',articul);
	if ( i > -1 ){
		allowPageUnload = true;
		Laverna.nabor.load(Ext.getCmp('u3tvkgrid').store.getAt(i));
	}
}

function SetupMain() {
	
	// Init the singleton.  Any tag-based quick tips will start working.
Ext.QuickTips.init();
gridMask = new Ext.LoadMask(Ext.getBody(), {msg:"Пожалуйста подождите, идёт загрузка информации..."});

// Apply a set of config properties to the singleton
Ext.apply(Ext.QuickTips.getQuickTip(), {
    maxWidth: 300,
    minWidth: 100,
    showDelay: 50,
    trackMouse: false
});

Ext.History.init(function() {Ext.History.add( "home" )});

Laverna.basket = new Laverna.BasketWindow({});
Laverna.nabor = new Laverna.NaborWindow({});


var tplTG = new Ext.XTemplate(
		'<tpl for=".">',
            '<div class="thumb-wrap" title="{title}" style="{style}">',
		    '<div class="thumb" style="background: url(\'/images/{img1file}\') center no-repeat; width: {img1width}px; height: {img1height}px"></div>',
		    '<span class="title">{[values.title.replace("\n","<BR>")]}</span></div>',
	   '</tpl>',
	   '<div class="x-clear"></div>'
	);
	
var tplOffers = new Ext.XTemplate(
		'<tpl for=".">',
            '<div class="thumb-wrap" ext:Lonum="{onum}" style="{style}">',
            '<table style="{style}"><tr><td>',
		    '<span class="thumb" style="background: url(\'/images/u/{img1file}\') center no-repeat;" ext:qtitle="Условия акции:"  ext:qtip="<div class=&quot;qtipOffer&quot;>{[Ext.util.Format.htmlEncode(values.description)]}</div>"></span></td></tr>',
		    '<tr><td><span class="title">&nbsp;{tm}&nbsp;</span></td></tr>',
		    '<tr><td class="slogan"><span class="title" style="white-space: no-wrap">{slogan}</span></td></tr>',
		    '<tr><td><span class="title" style="white-space: no-wrap">{start} - {finish}</span></td></tr>',
		    '</table></div>',
	   '</tpl>',
	   '<div class="x-clear"></div>'
	);	

Laverna.viewport = new Ext.Viewport({
	layout: 'border',
	items : 
	[
		{
           region:'south',
                    split:true,
                    height: 80,
                    minSize: 10,
                    maxSize: 85,
                    collapsible: false,
                    header: false,
                    margins:'0 0 0 0',
                    contentEl: "Laddresses"
     	},{
     	           region:'north',
                    split:false,
                    height: 100,
                    minSize: 10,
                    maxSize: 100,
                    collapsible: false,
                    header: false,
                    margins:'0 0 0 0',
                    contentEl: "Llogo"
     	},
		{
                    region:'west',
                    id: 'u3searchFormPanel',
                    title:'Поиск',
                    split: true,
                    border:false,
                    iconCls:'nav',
					width: 200,
					maxWidth: 400,
					autoHeight: true,
					collapsible: true,
					collapsed: true,
					layout: 'table',
					layoutConfig: {
				        columns: 1
    				},
					
                    items: [{
                        xtype:'form',
                        id: 'u3searchForm',
                        autoWidth: true,
                        frame: true,
                        labelAlign : 'top',
                        width: 200,
                        maxWidth: 400,
                        listeners : {
                        	render : {
                        		fn: function() {
                        						var fn = function() {
										 		var col = Ext.getCmp('u3searchFormPanel');
										 		if ( col ) col.expand();
										 	}
										 	fn.defer(400);
                        		}
                        	}
                        
                        },
                        items: [
                      {
            			fieldLabel: 'Товарная группа',
            		    typeAhead: false,
               			allowBlank: false,
               			editable: false,
               			listWidth: 200,
               			triggerAction: 'all',
               			//transform:'light',
               			lazyRender:false,
               			listClass: 'x-combo-list-small',
               			xtype: 'combo',
               			store: mainStore,
               			valueField: 'grp',
               			name: 'grp',
               			disableKeyFilter : false,
               			forceSelection : true,
               			displayField: 'grp_title',
               			mode: 'local',
               			listeners:{
         					'select': makeSearch
    					}
            		},
                    {
            		fieldLabel: "Товарная марка", 
            		id: 'u3-s-tm',
                    sortable: true,
                    editable: false,
					xtype: 'combo',
               			typeAhead: false,
               			allowBlank: false,
               			triggerAction: 'all',
               			displayField: 'tm',
               			name: 'tm',
               			store: tmStore,
               			mode: 'local',
               			listWidth: 200,
               			//transform:'light',
               			lazyRender:true,
               			forceSelection : true,
               			listClass: 'x-combo-list-small',
               			listeners:{
         					'select': makeSearch
    					}
               		},
					{
						fieldLabel: 'Коллекция',
						id: 'u3-s-collection',
               			typeAhead: false,
               			editable: false,
               			allowBlank: false,
               			listWidth: 200,
               			triggerAction: 'all',
               			//transform:'light',
               			lazyRender:true,
               			xtype: 'combo',
               			mode: 'local',
               			displayField: 'collection',
               			name: 'collection',
               			listClass: 'x-combo-list-small',
               			store : collectionStore,
               			forceSelection : true,
               			listeners:{
         					'select': makeSearch
    					}
            		},
            		{
            		fieldLabel: "Наименование", 
            		id: 'u3-s-name',
                    sortable: true,
                    editable: false,
					xtype: 'combo',
               			typeAhead: false,
               			allowBlank: false,
               			triggerAction: 'all',
               			displayField: 'name',
               			name: 'name',
               			store: nameStore,
               			listWidth: 200,
               			mode: 'local',
               			//transform:'light',
               			lazyRender:true,
               			forceSelection : true,
               			listClass: 'x-combo-list-small',
               			listeners:{
         					'select': makeSearch
    					}
               		},
               		{
            		fieldLabel: "Артикул", 
                    name: 'articul',
					xtype: 'textfield'
               		},
               		{
            		fieldLabel: "Наличие", 
                    sortable: true,
                    editable: false,
					xtype: 'combo',
               			typeAhead: false,
               			allowBlank: false,
               			triggerAction: 'all',
               			displayField: 'available',
               			name: 'available',
               			listWidth: 150,
               			store: [
               			['','Везде'],
               			['amsk','Москва'],
               			['aspb','Санкт-Петербург'],
               			['aeburg','Екатеринбург'],
               			['anovosib','Новосибирск'],
               			['asamara','Самара'],
               			['akrasnoyarsk','Красноярск'],
               			['arostov','Ростов']
               			],
               			mode: 'local',
               			//transform:'light',
               			lazyRender:true,
               			forceSelection : true,
               			listClass: 'x-combo-list-small',
               			listeners:{
         					'select': makeSearch
    					}
               		},	
               		{
               		layout:'column',
               		width: 200,
            		items:[
            		    {
                			columnWidth: .2,
                			items: [{
                    			xtype:'label',
                    			text: 'Цена от: ',
                    			cls: 'x-form-item'
                			}]
                		},
            			{
                			columnWidth: .2,
                			items: [{
                    			xtype:'textfield',
                    			name: 'p1',
                    			id: 'u3p1',
                    			width: 50,
                    			style: 'margin-left: 3px; margin-right: 3px'
                			}]
						},
						{
                			columnWidth: .2,
                			items: [{
                    			xtype:'label',
                    			text: 'до: ',
                    			cls: 'x-form-item'
                			}]
                		},
            			{
                			columnWidth: .2,
                			items: [{
                    			xtype:'textfield',
                    			name: 'p2',
                    			id: 'u3p2',
                    			width: 50,
                    			style: 'margin-left: 3px; margin-right: 3px'
                			}]
						},
						{
                			columnWidth: .2,
                			items: [{
                    			xtype:'label',
                    			text: 'у.е.',
								cls: 'x-form-item'
                			}]
						}
					]
               		}
               	],
                buttons: [
                        {
						text: 'Искать',
						id: 'clear-btn',
						handler: function(){ makeSearch(); }  
						},
                    	{  
						text: 'Очистить',
						id: 'clear-btn',
						handler: function(){
							var frm = Ext.ComponentMgr.get('u3searchForm'); 
							frm.getForm().reset();
							mainStore.load({params: {_function: 'TVKSearch'}});
							Ext.getCmp('main-view').expand();
						}
						}/*,
						{  
							text: 'На главную',
							handler: function(){ Ext.getCmp('main-view').expand() }  
						}*/
					]
				},
				{ 
					xtype: 'panel',
					frame: true,
					buttonAlign: 'center',
					buttons: [
					{
					xtype: 'button',
					text: 'Посмотреть Заказ',
					handler: showBasket
					}
					]
				}
				]
         },
		{
              region:'center',
              layout:'accordion',
              id: 'u3center',
              layoutOnTabChange:true,
              height: 400,
              layoutConfig:{
                        animate:true,
                         titleCollapse: false,
                         autoWidth: false,
                         hideCollapseTool: false
                    },
             xtype: 'panel',
              items:
              [
              { 
					title: 'Товары для ванной комнаты.',
                    //autoScroll:true,
                    id:'main-view',
                    tools:[
                    	{
    						id:'help',
    						hidden: false
    					},
    					{
    						id: 'toggle',
    						handler: function(event, toolEl, panel){Ext.History.add( "home" );}
    					}
					],
        			frame:false,
        			hideCollapseTool: false,
        			xtype: 'panel',
        			autoWidth: false,
        			AutoHeight: true,
        			listeners: {
        				render : {
        					fn: function(me) {
        						var d = me.el.child('div.x-tool-help');
        						d.dom.innerHTML = "Минимальная сумма заказа для физических лиц 500 у.е.";
        					}
        				}
        			},
        			layout:'fit',
                    	items: [
                    	{
                    	xtype: 'dataview',
                        closable:false,
                        store: Laverna.tgrpStore,
                        margin: 0,
            			tpl: tplTG,
            			multiSelect: false,
            			overClass:'x-view-over',
            			itemSelector:'div.thumb-wrap',
            			listeners: {
            				click: {
            					fn: function(dv, index,  node, e ){
            						var record = Laverna.tgrpStore.getAt(index);

            						if ( ! record ) return;

									u3History.push(
									{
            							params: {
            								'_filter_value': record.get('grp'),
            								'_filter_column': 'grp',
            								'_table' : 'offers',
            								'_function' : 'Table',
            								'_u3store' : 'offers-view'
            							},
            							callback: function(records, options, success) {
            								if ( success ) {
            									Ext.getCmp('offers-view').refresh();
            									Ext.getCmp('offers-tab').expand();
            									//Ext.QuickTips.init();
            								}
            							}
            						}
									);
									Ext.History.add( u3History.length );
            					}
            				},
            				resize : {
            					fn : function( panel, adjWidth, adjHeight, rawWidth, rawHeight  ) {
            						var w = (adjWidth - 822) / 2;
            						if ( w < 10 ) w = 0;
            						panel.getEl().setStyle('padding-left',w + 'px');
            						
            						var h = (adjHeight - 400) / 2;
            						if ( h < 10 ) h = 0;
            						panel.getEl().setStyle('padding-top',h + 'px');
            					}
            				}
            			}
                    	}
                    	]

              },
              {
                   title: 'Специальные предложения',
                    //autoScroll:true,
                    id: 'offers-tab',
        			frame:false,
        			xtype: 'panel',
        			layout:'fit',
                    	items: [
                    	{
                    	xtype: 'dataview',
                        closable:false,
                        store: offersStore,
                        margin: 0,
                        id: 'offers-view',
            			tpl: tplOffers,
            			multiSelect: false,
            			overClass:'x-view-over',
            			itemSelector:'div.thumb-wrap',
            			emptyText: 'В этой товарной группе нет ни одного спец. предложения',
            			loadingText: 'Пожалуйста подождите, загружаются спец. предложения',
            			listeners: {
            				click: {
            					fn: function(dv, index,  node, e ){
            						var onum = node.getAttribute('ext:Lonum');
            						if ( ! onum ) return;
            						
            						u3History.push(
									{
            							params: {
            								'_u3store' : 'u3tvkgrid'
            							},
            							onum: onum, 
            							start:0,
            							limit:u3gridPerPage
            						}
									);
									Ext.History.add( u3History.length );
            						
            					}
            				}
            			}
                    	}
                    	],
                    	buttons: [
                    	{	
							xtype: 'button',
							text: 'Посмотреть Заказ',
							handler: showBasket
						},{  
							text: 'На главную',
							id: 'back-btn',
							handler: function(){ Ext.History.add( "home" ); }  
						}
						]
              },
              {
              	xtype: 'u3tvkgrid',
              	title: 'ТВК',
              	id: 'u3tvkgrid',
              	autoScroll: true,
              	buttons: [
              		{
					xtype: 'button',
					text: 'Посмотреть Заказ',
					handler: showBasket
					},
              		{  
						text: 'Назад, к спец. предложениям',
						id: 'back-btn',
						handler: function(){
							if ( u3History.length > 1 ) {
							for ( var i = u3History.length-2; i>=0; i--) {
								if ( u3History[i].params._u3store == 'offers-view' ) {
									u3History.push(u3History[i]);
									Ext.History.add( u3History.length );
									return;
								}
							}
							}
						 		Ext.History.add( "home" );
						} 
					},{  
						text: 'На главную',
						id: 'back-btn',
						handler: function(){ Ext.History.add( "home" ); }
					}
				]
              }
              ]
          }
 
    ],
    renderTo: Ext.getBody()
});

    if(Ext.isIE6){
        Ext.EventManager.onWindowResize(function(){
            Ext.getCmp('u3center').doLayout();
        });
    }


    Ext.History.on('change', function(token){
        if(token){
       		if ( token == 'home' ) {
       			Ext.getCmp('main-view').expand();
       		} else {
        		//alert(token + "\n" + Ext.util.JSON.encode(u3History[parseInt(token)-1]));
        		var options = u3History[parseInt(token)-1];
        		if ( options.params._u3store == 'mainStore') {
        			mainStore.load(options);
        		} else if (options.params._u3store == 'offers-view') {
        			Ext.getCmp('offers-view').store.load(options);
        		} else if (options.params._u3store == 'u3tvkgrid') {
        			Ext.getCmp('u3tvkgrid').setOnum(options.onum);
            		Ext.getCmp('u3tvkgrid').load(options);
        		} else {
					Ext.getCmp('main-view').expand();
				}
			}
        }else{
			Ext.getCmp('main-view').expand();
        }

    });

window.onbeforeunload = function(event) {

return;

  var message = "Вы собираетесь перейти на другой сайт, либо обновить текущую страницу сайта ТВК.\nЕсли Вы согласитесь сделать это, то информация о вашем заказе будет очищена.\nДля подтверждения ухода с сайта ТВК нажмите 'Ok', для просмотра или печати заказа закройте это окно и нажмите кнопку 'Посмотреть заказ' слева внизу";
  
  if ( allowPageUnload ) {
  	return;
  }
  if (typeof event == 'undefined') {
    event = window.event;
  }
  if (event) {
    event.returnValue = message;
  }
  return message;
}

} //eof u2setupMain
