Ext.namespace('Ext.searchParams');
Ext.searchParams['sid'] = Math.random();
var countriesStore = new Ext.data.SimpleStore({
    fields: ['orign', 'rus'],
    data : Ext.countries // from states.js
});
var hotelsStore;
var regions = new Ext.form.ComboBox();
var hotels = new Ext.form.ComboBox();
var stars = new Ext.form.ComboBox();


Ext.apply(Ext.form.VTypes, {
	
	prices: function(value, field) {
		
		var minprice = Ext.getCmp('minprice');
		if (value < minprice.getValue()) {
			return false;
		}
		return true;
	}
});



Ext.onReady(function(){
    
	Ext.QuickTips.init();
	
    Ext.form.Field.prototype.msgTarget = 'side';
    
    function afterSelect(combo, item, param) {
		
		if(item.get('rus')) {
			combo.setValue(item.get('rus'));
		}else {
			combo.setValue(item.get('orign'));			
		}
		combo.collapse();
		
		Ext.searchParams[param] = item.get('orign');
		ds.baseParams = Ext.searchParams;
		ds.load();
	}
    
    var countries = new Ext.form.ComboBox({
    	store: countriesStore,
        displayField:'rus',
        typeAhead: true,
        forceSelection: true,
        mode: 'local',
        triggerAction: 'all',
        emptyText:'Выберите страну...',
        selectOnFocus:true,
        id: 'country',
        renderTo: 'general'
    });

    //
    //	On Country Selected
    //
    countries.on ({
    	select: function(c, item){
			
    		delete Ext.searchParams['region'];
    		delete Ext.searchParams['hotel'];
    		
    		Ext.searchParams['country'] = item.get('orign');
			ds.baseParams = Ext.searchParams;
    		ds.load();
    		
    		var regionsStore = new Ext.data.SimpleStore({
		        fields: ['region','rus'],
		        data : Ext.regions[item.get('orign')] // e.g. Egypt
		    });
		    
		    //
		    //	Region ComboBox
		    //
		    hotels.destroy();
		    regions.destroy();
		    regions = new Ext.form.ComboBox({
		        store: regionsStore,
		        displayField:'region',
		        typeAhead: true,
		        mode: 'local',
		        triggerAction: 'all',
		        emptyText:'Выберите регион...',
		        selectOnFocus:true,
		        renderTo: 'general'
		    });
		    
		    
		    //
		    //	On Region Selected
		    //
		    regions.on ({
		    	select: function(c){
		    		
		    		delete Ext.searchParams['hotel'];
		    		
		    		Ext.searchParams['region'] = c.getValue();
					ds.baseParams = Ext.searchParams;
    				ds.load();
		    		
		    		hotelsStore = new Ext.data.SimpleStore({
				        fields: ['hotel'],
				        data : Ext.hotels[c.getValue()] // e.g. Dahab
				    });
				    
				    //
				    //	Hotel ComboBox
				    //
				    hotels.destroy();
				    hotels = new Ext.form.ComboBox({
				        store: hotelsStore,
				        displayField:'hotel',
				        typeAhead: true,
				        mode: 'local',
				        triggerAction: 'all',
				        emptyText:'Выберите отель...',
				        selectOnFocus:true,
				        renderTo: 'general'
				    });
				    hotels.on ({
				    	select: function(c) {
				    		Ext.searchParams['hotel'] = c.getValue();
							ds.baseParams = Ext.searchParams;
//				    		ds.baseParams = {hotel : c.getValue()};
    						ds.load();
				    	}
				    });
				    
		    	}
		    });
    	}
    });
    
    	//
	//	 section
	//
	var dr = new Ext.FormPanel({
		labelWidth: 125,
		bodyStyle:'padding:5px 5px 0',
//		width: 300,
		frame: true,
		layout:'form',	
		items: [{
            xtype:'fieldset',
		title: 'Время',
            autoHeight:true,
            collapsible: true,
            defaults: {width: 100, format: 'd-m-Y'},
            defaultType: 'numberfield',
            
			items: [{
				xtype: 'datefield',
			    fieldLabel: 'Дата начала',
			    name: 'start_date',
			    id: 'start_date'
//			    vtype: 'daterange',
//			    endDateField: 'enddt' // id of the end date field
	      	},{
		        fieldLabel: '+/-',
		        name: 'start_datedisp',
		        id: 'start_datedisp'
	      	},{
		        fieldLabel: 'ночей',
		        name: 'nights',
		        id: 'nights'
	      	}/*,{
		        fieldLabel: '+/-',
		        name: 'nightsdisp',
		        id: 'nightsdisp'
	      	}*/]
		},{
			xtype:'fieldset',
			title: 'Размещение',
            autoHeight:true,
            defaults: {width: 100},
            defaultType: 'combobox',
            collapsible: true,
            collapsed: true,
            
			items: [
				new Ext.form.ComboBox({
			    fieldLabel: 'Номер',
			    store: new Ext.data.SimpleStore({
			        fields: ['orign','rus'],
			        data : [
				    	['DBL','Двуместный'],
				    	['SNG','Одномесный']
				    ]
			    }),
			    displayField:'rus',
//			    name: 'roomtype',
//			    id: 'roomtype',
		        typeAhead: true,
		        mode: 'local',
		        triggerAction: 'all',
		        selectOnFocus:true,
		        onSelect: function(item) {
		        	afterSelect(this, item, 'roomtype');
				return true
		        }
	      	}),
	      		new Ext.form.ComboBox({
			    fieldLabel: 'Питание',
			    store: new Ext.data.SimpleStore({
			        fields: ['orign','rus'],
			        data : [
				    	['AI','Всё включено'],
				    	['HB','Полупансион'],
				    	['BB','Завтраки']
				    ]
			    }),
			    displayField:'rus',
		        typeAhead: true,
		        mode: 'local',
		        triggerAction: 'all',
		        selectOnFocus:true,
		        onSelect: function(item) {
		        	afterSelect(this, item, 'food');
		        }
	      	}),
	      		new Ext.form.ComboBox({
			    fieldLabel: 'Класс отеля',
			    store: new Ext.data.SimpleStore({
			        fields: ['orign'],
			        data : [
				    	['3'],
				    	['3+'],
				    	['4'],
				    	['4+'],
				    	['5'],
				    	['HV1']
				    ]
			    }),
			    displayField:'orign',
			    name: 'stars',
			    id: 'stars',
		        typeAhead: true,
		        mode: 'local',
		        triggerAction: 'all',
		        selectOnFocus:true,
		        onSelect: function(item) {
		        	afterSelect(this, item, 'stars');
		        }
	      	})]
		},{
            xtype:'fieldset',
//            layout:'fit',
//            labelAlign: 'top',
//            checkboxToggle:true,
			title: 'Цена',
            autoHeight:true,
            defaults: {width: 60},
            defaultType: 'numberfield',
            collapsible: true,
            collapsed: true,
            
			items: [{
			    fieldLabel: 'Минимальная $',
			    name: 'minprice',
			    id: 'minprice'
	      	},{
		        fieldLabel: 'Максимальная $',
		        name: 'maxprice',
		        id: 'maxprice',
			    vtype: 'prices',
			    vtypeText: 'Значение должно быть больше предыдущего'
	      	}]
		},{
            xtype:'fieldset',
            
//            labelAlign: 'top',
//            checkboxToggle:true,
			title: 'Сортировка',
            autoHeight:true,
            defaults: {width: 100},
            defaultType: 'combobox',
            collapsible: true,
            collapsed: true,
            
			items: new Ext.form.ComboBox({
			    fieldLabel: 'Сортировать по',
			    store: new Ext.data.SimpleStore({
			        fields: ['orign','rus'],
			        data : [
				    	['price','ценам'],
				    	['nights','длительности'],
				    	['start_date','дате начала'],
				    	['stars','классу отеля']
				    ]
			    }),
			    displayField:'rus',
//			    name: 'sortBy',
//			    id: 'sortBy',
//			    tpl: '<tpl for="."><div class="x-combo-list-item">{rus}</div></tpl>',
		        typeAhead: true,
		        mode: 'local',
		        triggerAction: 'all',
		        emptyText:'ценам',
		        selectOnFocus:true,
		        onSelect: function(item) {
		        	afterSelect(this, item, 'sort');
		        }
	      	})
		}]
    });

    var submit = dr.addButton({
        text: 'Обновить',
        handler: function(){
            ds.load();
        }
    });
    
	dr.render('wraper');
    
	Ext.getCmp('start_date').on ({
		change: function(c) {
			if (!c.getRawValue()) {
				delete Ext.searchParams['start_date']
			}else {
				Ext.searchParams['start_date'] = c.parseDate(c.getValue()).format("Y-m-d");
			}
			ds.baseParams = Ext.searchParams;
    		ds.load();
		}
	});
	
	Ext.getCmp('start_datedisp').on ({
		change: function(c) {
			Ext.searchParams['start_datedisp'] = c.getValue();
			ds.baseParams = Ext.searchParams;
    		ds.load();
		}
	});
	
	Ext.getCmp('nights').on ({
		change: function(c) {
			Ext.searchParams['nights'] = c.getValue();
			ds.baseParams = Ext.searchParams;
    		ds.load();
		}
	});
	
	Ext.getCmp('minprice').on ({
		change: function(c) {
			Ext.searchParams['minprice'] = c.getValue();
			ds.baseParams = Ext.searchParams;
    		ds.load();
		}
	});
	
	Ext.getCmp('maxprice').on ({
		change: function(c) {
			Ext.searchParams['maxprice'] = c.getValue();
			ds.baseParams = Ext.searchParams;
    		ds.load();
		}
	});
	
    var ds = new Ext.data.Store({
        proxy: new Ext.data.ScriptTagProxy({
            url: 'http://tur.m-travel.kiev.ua/toursearch/model/getSearchResults.php'
        }),
        reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'totalCount',
            id: 'id'
        }, [
            {name: 'id'},
            {name: 'country'},
            {name: 'region'},
            {name: 'hotel'},
            {name: 'stars'},
            {name: 'nights'},
            {name: 'food'},
            {name: 'roomclass'},
            {name: 'roomtype'},
            {name: 'price'},
            {name: 'start_date', mapping: 'start_date', type: 'date', dateFormat: 'Y-m-d'}
        ]),
        
        // turn on remote sorting
        remoteSort: true
//        baseParams: {country: Ext.getCmp('country').getValue()}
//        baseParams: {country: Ext.my}
//		baseParams: {}
    });

//    ds.setDefaultSort('price', 'desc');
//    ds.setDefaultSort('price');
    
     
    // Custom rendering Template for the View
    var resultTpl = new Ext.XTemplate(
        '<tpl for=".">',
        '<div class="search-item"  ext:qtip="Клас отеля: <b>{stars}</b><br/>Питание: <b>{food}</b><br/>Размещене: <b>{roomtype}</b> ({roomclass})">',
            '<h3>',
//            '<span>{start_date:date("d-m-Y")}<br />',
            '<span>{start_date:date("j F, Y")}<br />',
            '<b>{nights} ночей</b><br/>',
//            '$<b>{price}</b>',
            '$<a onclick="open_popup(\'http://tur.m-travel.kiev.ua/inframeoffer.php?id={id}&table=stures\',500,500,\'popup\', \'no\');return false;" href="#" ext:qtip="отправить заявку">{price}</a>',
//            '$<a href="http://tur.m-travel.kiev.ua/inframeoffer.php?id={id}&table=stures" ext:qtip="отправить заявку"  target="_blank">{price}</a>',
            
            '</span></h3>',
            '<img ext:qtip="Класс отеля: {stars}" src="toursearch/images/stars-{stars}.png"/><br/>',
            '<b>{country}</b> {region}',
            '<br>{hotel}',
        '</div></tpl>'
    );

    var panel = new Ext.Panel({
//        applyTo: 'search-panel',
        title:'Результат поиска',
//        height:300,
//        width:400,
        autoScroll:true,
        loadMask: true,
		
        items: new Ext.DataView({
            tpl: resultTpl,
            store: ds,
            loadingText: 'Идёт поиск...',
            emptyText: 'К сожалению по Вашему запросу не найдено туров, попробуйте изменить параметры поиска',
//            overClass:'x-view-over',
//            itemSelector:'div.thumb-wrap'
            itemSelector: 'div.search-item'
        }),

        bbar: new Ext.PagingToolbar({
            store: ds,
            pageSize: 5,
            displayInfo: true,
		displayMsg: '',
            //displayMsg: '<b ext:qtip="всего найдено">{2}</b>',
//            displayMsg: 'Туры {0} - {1} из <b>{2}</b>',
            emptyMsg: "",
		afterPageText: "",
            //afterPageText: "из {0}",
            beforePageText: "Страница",
            lastText: "Последняя страница",
            nextText: "Следующая страница",
            prevText: "Предыдущая страница",
            firstText: "Первая страница",
            refreshText: "Обновить"
        })
    });

    panel.render('result');
    ds.load({params:{start:0, limit:5}});

   

});
