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);
			records[i].set('img1height', obj.height);
			records[i].set('img1title', obj.title);
		}
	}
	gridMask.hide();
}

var firstLoad = true;

var myProxy = new Ext.data.HttpProxy({
                				//where to retrieve data
                				url: '/ajax.pl', //url to data object (server side script)
                				method: 'POST'
            				});
            				
    
var collectionsStore = new Ext.data.Store({
            				proxy: myProxy,
            				reader: new Ext.data.JsonReader(
    							{ //creates array from JSON response
            						root: 'collections-view' // name of the property that is container for an Array of row objects
        						},
        						[
        						{name: 'collection', type: 'string'},
        						{name: 'img1', type: 'string'},
        						{name: 'img1file', type: 'string'},
        						{name: 'img1width', type: 'string'},
        						{name: 'img1height', type: 'string'},
        						{name: 'img1title', type: 'string'}
        						]//instead of defining inline just pass a reference to the object 
    						),
            				sortInfo:{field: 'collection', direction: "ASC"},
            				autoLoad: false
    });

var gridMask = new Ext.LoadMask(Ext.getBody(), {msg:"Пожалуйста подождите, идёт загрузка информации...", store: collectionsStore});
    
collectionsStore.on('load',   filterJSON);

var colorStore = new Ext.data.Store({
            				proxy: myProxy,
            				reader: new Ext.data.JsonReader(
    							{ //creates array from JSON response
            						root: 'colors' // name of the property that is container for an Array of row objects
        						},
        						[
        						{name: 'color', type: 'string'}
								]
    						),
            				sortInfo:{field: 'color', direction: "ASC"},
            				autoLoad: false
    });

var countryStore = new Ext.data.Store({
            				proxy: myProxy,
            				reader: new Ext.data.JsonReader(
    							{ //creates array from JSON response
            						root: 'countries' // name of the property that is container for an Array of row objects
        						},
        						[
        						{name: 'country', type: 'string'}
								]
    						),
            				sortInfo:{field: 'country', direction: "ASC"},
            				autoLoad: false
    });
    
var priceStore = new Ext.data.Store({
            				proxy: myProxy,
            				reader: new Ext.data.JsonReader(
    							{ //creates array from JSON response
            						root: 'pricem2' // name of the property that is container for an Array of row objects
        						},
        						[
        						{name: 'pricem2', type: 'string'}
								]
    						),
            				sortInfo:{field: 'pricem2', direction: "ASC"},
            				autoLoad: false
    });
    
var suitStore = new Ext.data.Store({
            				proxy: myProxy,
            				reader: new Ext.data.JsonReader(
    							{ //creates array from JSON response
            						root: 'suitable' // name of the property that is container for an Array of row objects
        						},
        						[
        						{name: 'suitable', type: 'string'}
								]
    						),
            				sortInfo:{field: 'suitable', direction: "ASC"},
            				autoLoad: false
    });

var mainStore = 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: 'collection', type: 'string'}]//instead of defining inline just pass a reference to the object 
    						),
            				baseParams: {'_function' : 'CollectionSearch' },
            				sortInfo:{field: 'collection', direction: "ASC"},
            				autoLoad: true,
            				listeners: {
            					load : {
            						fn: function(store, records,  options  ){
            							 form = Ext.getCmp('u3searchForm');
            							 if ( form && form.items ) { 
            							 	form.items.each( function(c) {c.collapse(); c.hasFocus = false; } );
            							 }
            						
            							if (options.params && options.params._results) {
										 	collectionsStore.loadData( this.reader.jsonData , false ); // for a dataPanel
										 	var col = Ext.getCmp('collections-view');
            							 	if (col) col.expand();
										 }
										
										 
										 if ( firstLoad ) {
										 	firstLoad = false;
										 	colorStore.loadData( this.reader.jsonData , false );
										 	countryStore.loadData( this.reader.jsonData , false );
										 	priceStore.loadData( this.reader.jsonData , false );
										 	suitStore.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 != 'color' || options.params.color.search(' ') == 0) {
											 	colorStore.loadData( this.reader.jsonData , false );
											 }
											 if ( options.params.lastCombo != 'country' || options.params.country.search(' ') == 0) {
											 	countryStore.loadData( this.reader.jsonData , false );
											 }
											 if ( options.params.lastCombo != 'pricem2' || options.params.pricem2.search(' ') == 0) {
											 	priceStore.loadData( this.reader.jsonData , false );
											 }
											 if ( options.params.lastCombo != 'suitable' || options.params.suitable.search(' ') == 0) {
											 	suitStore.loadData( this.reader.jsonData , false );
											 }
            							 }
            							 if ( this.reader.jsonData.items.length < 2 ) {
            							 	Ext.MessageBox.alert('Внимание!', 'Ничего не найдено по вашему запросу.<br>Попробуйте изменить условия поиска');
            							 }
            						}
            					}
            				}
      					});



function makeSearch (combo, record, idx) {
	var frm = Ext.getCmp('u3searchForm');

	var param = {};
	frm.items.each( function(c) {
		if ( c.xtype == 'combo' || c.xtype == 'textfield') {
			param[c.displayField] = c.getValue();
		}
	});
	if ( ! combo ) {
		param._results = 1;
	} else {
		param.lastCombo = '';
		
		var val = combo.getValue();
		if ( combo.xtype == 'combo' ) {
				if ( val.search(' Люб') != 0) {
					param.lastCombo = combo.displayField;
				}
		}
	}
	if ( param._results == 1 ) { gridMask.show(); }
	mainStore.load({params: param});
}


function SetupMain() {
	Ext.QuickTips.init();

var tpl = new Ext.XTemplate(
		'<tpl for=".">',
			'<tpl if="this.isANY(collection)">',
            '<div class="thumb-wrap" title="{collection}">',
		    '<div class="thumb" style="background: url(\'/images/u/{img1file}\') center no-repeat"></div>',
		    '<span class="title">{collection}</span></div>',
		   '</tpl>',
		   '<tpl if="this.isANY(collection) == false">',
		   '<div class="thumb-wrap" title="{collection}" style="display: none">',
		   '</div>',
		   '</tpl>',
		   '</tpl>',
		   '<div class="x-clear"></div>',
	//	 '<div class="x-clear"></div>',
		 {
		 	  isANY : function(name){
                  return name != ' Любая';
              }
		 }
	);

Laverna.viewport = new Ext.Viewport({
	layout: 'border',
	items : 
	[
		{
           region:'south',
                    split:true,
                    height: 91,
                    minSize: 30,
                    maxSize: 91,
                    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',
              title:'Поиск',
              split: true,
              collapsed: true,
              id :  'u3searchFormPanel',
              xtype: 'panel',
              frame: true,
              width: 200,
              maxWidth: 400,
              buttons: [
                    	/*{  
						text: 'Очистить',
						id: 'clear-btn',
						handler: function(){var frm = Ext.ComponentMgr.get('u3searchForm'); frm.getForm().reset(); }  
						}*/
						{  
						text: 'Коллекции',
						id: 'back-btn',
						handler: function(){
								Ext.getCmp('collections-view').expand();
								collectionsStore.load({params: {'_function' : 'CollectionSearch' , '_results' : 1}}); 
								
						}  
					},{  
						text: 'На главную',
						id: 'back-btn',
						handler: function(){ Ext.getCmp('welcome-view').expand() }  
					}
			],
              items: {
                        border:false,
                        iconCls:'nav',
                        xtype:'form',
                        id: 'u3searchForm',
                        frame: false,
                        
                        labelAlign : 'top',
                        width: 200,
                        items: [
					{
						fieldLabel: 'Коллекция',
               			typeAhead: false,
               			editable: false,
               			allowBlank: false,
               			listWidth: 200,
               			triggerAction: 'all',
               			//transform:'light',
               			lazyRender:true,
               			xtype: 'combo',
               			mode: 'local',
               			displayField: 'collection',
               			listClass: 'x-combo-list-small',
               			store : mainStore,
               			forceSelection : true,
               			listeners:{
         					'select': makeSearch
    					}
            		},
            		
            		{
            			fieldLabel: 'Цвет',
            		    typeAhead: false,
               			allowBlank: false,
               			editable: false,
               			listWidth: 200,
               			triggerAction: 'all',
               			//transform:'light',
               			lazyRender:false,
               			listClass: 'x-combo-list-small',
               			displayField: 'color',
               			xtype: 'combo',
               			store: colorStore,
               			forceSelection : true,
               			mode: 'local',
               			listeners:{
         					'select': makeSearch
    					}
            		},
            		 {
            		fieldLabel: "Страна", 
                    sortable: true,
                    editable: false,
                    listWidth: 200,
                    dataIndex: 'country',
					xtype: 'combo',
               			typeAhead: false,
               			allowBlank: false,
               			triggerAction: 'all',
               			displayField: 'country',
               			store: countryStore,
               			mode: 'local',
               			//transform:'light',
               			lazyRender:true,
               			forceSelection : true,
               			listClass: 'x-combo-list-small',
               			listeners:{
         					'select': makeSearch
    					}
               		},
            		{
            		fieldLabel: "Цена за м<sup>2</sup>", 
                    sortable: true,
                    editable: false,
                    dataIndex: 'pricem2',
					xtype: 'combo',
					listWidth: 200,
               			typeAhead: false,
               			allowBlank: false,
               			triggerAction: 'all',
               			displayField: 'pricem2',
               			store: priceStore,
               			mode: 'local',
               			//transform:'light',
               			lazyRender:true,
               			forceSelection : true,
               			listClass: 'x-combo-list-small',
               			listeners:{
         					'select': makeSearch
    					}
               		},
            		{
            		fieldLabel: "Тип плитки", 
                    sortable: true,
                    editable: false,
                    dataIndex: 'suitable',
					xtype: 'combo',
					listWidth: 200,
               			typeAhead: false,
               			allowBlank: false,
               			triggerAction: 'all',
               			displayField: 'suitable',
               			store: suitStore,
               			mode: 'local',
               			//transform:'light',
               			lazyRender:true,
               			forceSelection : true,
               			listClass: 'x-combo-list-small',
               			listeners:{
         					'select': makeSearch
    					}
               		},
               		{
            		fieldLabel: "Наличие", 
                    sortable: true,
                    editable: false,
					xtype: 'combo',
					listWidth: 200,
               			typeAhead: false,
               			allowBlank: false,
               			triggerAction: 'all',
               			displayField: 'text',
               			store: [
               			['','Везде'],
               			['amsk','Москва'],
               			['aspb','Санкт-Петербург'],
               			['aeburg','Екатеринбург'],
               			['anovosib','Новосибирск'],
               			['asamara','Самара']
               			],
               			mode: 'local',
               			//transform:'light',
               			lazyRender:true,
               			forceSelection : true,
               			listClass: 'x-combo-list-small',
               			listeners:{
         					'select': makeSearch
    					}
               		}
               		
                    ],
                        buttons: [
                        {
						text: 'Искать',
						id: 'clear-btn',
						handler: function(){ makeSearch(); }  
						},
                    	{  
						text: 'Очистить',
						id: 'clear-btn',
						handler: function(){
							var frm = Ext.getCmp('u3searchForm'); 
							frm.getForm().reset();
							mainStore.load({params: {_function: 'TVKSearch'}});
							Ext.getCmp('main-view').expand();
						}
						}
					]
				}
         },
		{
              region:'center',
              layout:'accordion',
              id: 'u3center',
              layoutOnTabChange:true,
              height: 400,
              layoutConfig:{
                        animate:true,
                         titleCollapse: false,
                         autoWidth: false
                    },
             xtype: 'panel',
              items:
              [
              { 
                 title: 'Добро пожаловать',
                 contentEl: "Lwelcome",
                 autoHeight: false,
                 autoWidth: false,
                 id: 'welcome-view',
                 layout: 'fit',
                 autoScroll:true

              },
              {
                   title: 'Коллекции кафельной плитки',
                    //autoScroll:true,
                    id:'collections-view',
        			frame:false,
        			xtype: 'panel',
        			autoWidth: false,
        			AutoHeight: true,
        			layout:'fit',
                    	items: [
                    	{
                    	xtype: 'dataview',
                        closable:false,
                        store: collectionsStore,
                        margin: 0,
            			tpl: tpl,
            			multiSelect: false,
            			overClass:'x-view-over',
            			itemSelector:'div.thumb-wrap',
            			emptyText: 'Нет ни одной коллекции, удовлетворяющей условиям поиска.',
            			listeners: {
            				click: {
            					fn: function(dv, index,  node, e ){
            						var col = node.getAttribute('title');
            						if ( ! col ) return;
            							form = Ext.getCmp('u3searchForm');

										var param = {};
										form.items.each( function(c) {param[c.displayField] = c.getValue() } );
										param.collection = col;
            						
            						Ext.getCmp('u3kafelgrid').load(param);
            					}
            				}
            			}
                    	}
                    	]
              },
              {
              	xtype: 'u3kafelgrid',
              	title: 'Плитка',
              	id: 'u3kafelgrid',
              	autoScroll: true,
              	buttons: [{  
						text: 'Назад, к коллекциям',
						id: 'back-btn',
						handler: function(){Ext.getCmp('collections-view').expand()}
					},{  
						text: 'На главную',
						id: 'back-btn',
						handler: function(){ Ext.getCmp('welcome-view').expand() }  
					}
				]
              }
              ]
          }
 
    ],
    renderTo: Ext.getBody()
});

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


} //eof u2setupMain
