var postalcodeTextField;
var _postalCodeLatitude;
var _postalCodeLongitude;

Ext.onReady(function(){
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';

	var neighbourhoodStore = new Ext.data.Store({
	        proxy: new Ext.data.MemoryProxy(neighbourhoodData),
	        reader: new Ext.data.ArrayReader({}, [
                   {name: 'neighbourhood_name'},
                   {name: 'neighbourhood_id', type: 'int'}                   
              ])
    });
	
	neighbourhoodStore.load();
		
	var cuisineStore = new Ext.data.Store({
	        proxy: new Ext.data.MemoryProxy(cuisineData),
	        reader: new Ext.data.ArrayReader({}, [
                   {name: 'cuisine_name'},
                   {name: 'cuisine_id', type: 'int'}                 
              ])
    });
	
	cuisineStore.load();
        
	var searchForm = new Ext.form.Form({
		id: 'searchForm',
        labelWidth: 150,
        url:'restaurant_list.php?search=1',
        method: 'GET',
        baseParams: {search: '1'},
        labelAlign: 'top'
    });
    
    var searchFieldWidth = 155;
    
	searchForm.fieldset(
        {legend:'By Categories:'},
		nameTextField = new Ext.form.TextField({
			fieldLabel: 'Name',
			name: 'name',
			maxLength: 30,
			width: searchFieldWidth,
			fieldClass: 'search-form-text',
			emptyClass: 'search-form-text',
			value: _name
		}),

		neighbourhoodComboBox = new Ext.form.ComboBox({
			fieldLabel: 'Neighbourhood',
			hiddenName:'neighbourhood_id',
			valueField: 'neighbourhood_id',
			store: neighbourhoodStore,
			displayField:'neighbourhood_name',
			forceSelection: true,
			typeAhead: true,
			mode: 'local',
			triggerAction: 'all',
			emptyText:'Select a neighbourhood...',
			selectOnFocus:true,
			width: searchFieldWidth
		}),
        
		cuisineComboBox = new Ext.form.ComboBox({
			fieldLabel: 'Cuisine',
			hiddenName:'cuisine_id',
			valueField: 'cuisine_id',
			store: cuisineStore,
			displayField:'cuisine_name',
			forceSelection: true,
			typeAhead: true,
			mode: 'local',
			triggerAction: 'all',
			emptyText:'Select a cuisine...',
			selectOnFocus:true,
			width: searchFieldWidth
		}),
        
		ratingComboBox = new Ext.form.ComboBox({
			fieldLabel: 'Average rating',
			hiddenName:'rating',
			valueField: 'rating',
			store: new Ext.data.SimpleStore({
                fields: ['rating','name'],
				data: [[1,'1 - Poor'],[2,'2 - Fair'],[3, '3 - Average'], [4, '4 - Good'], [5, '5 - Excellent']]
			}),
			forceSelection: true,
			displayField:'name',
			typeAhead: true,
			mode: 'local',
			triggerAction: 'all',
			emptyText:'Select an average rating...',
			selectOnFocus:true,
			width: searchFieldWidth
        }),
        
		recommendationComboBox = new Ext.form.ComboBox({
			fieldLabel: 'Recommendations',
			hiddenName:'recommendation',
			valueField: 'recommendation',
			store: new Ext.data.SimpleStore({
                fields: ['recommendation','name'],
				data: [[1,'1-10'],[2,'11-20'],[3, '21-50'], [4, '>50']]
			}),
			forceSelection: true,
			displayField:'name',
			typeAhead: true,
			mode: 'local',
			triggerAction: 'all',
			emptyText:'Select a number...',
			selectOnFocus:true,
			width: searchFieldWidth
        })
	);
	
	searchForm.fieldset(
        {legend:'By Distance:'},
		postalcodeTextField = new Ext.form.TextField({
			fieldLabel: 'Postal Code',
			name: 'postalcode',
			maxLength: 6,
			width: searchFieldWidth,
			fieldClass: 'postalcode',
			emptyClass: 'postalcode',
			vtype: 'postalcode',
			value: _postalCode
		})
	);
	
	searchButton = searchForm.addButton(
		{
			text: 'Search',
			cls: 'search-form-button'
		}, 
		submitSearch
   	);
	
	resetButton = searchForm.addButton('Reset', function(){	
		resetCategoryFields();
		resetPostalCodeFields();
   	});
   	
	searchForm.render('form-ct');	
	nameTextField.on("specialkey", specialKey, this);
	nameTextField.on("focus", function(){
		resetPostalCodeFields();
   	}, this);
   	
   	postalcodeTextField.on("specialkey", specialKey, this);
   	postalcodeTextField.on("focus", function(){
   		resetCategoryFields();
   	}, this);
   	
   	neighbourhoodComboBox.on("focus", function(){
   		resetPostalCodeFields();
   	}, this);
   	
   	cuisineComboBox.on("focus", function(){
   		resetPostalCodeFields();
   	}, this);
   	
   	ratingComboBox.on("focus", function(){
   		resetPostalCodeFields();
   	}, this);
   	
   	recommendationComboBox.on("focus", function(){
   		resetPostalCodeFields();
   	}, this);

   	if (location.href.indexOf("restaurant_list.php") < 0){
   	    recommendationComboBox.el.up('.x-form-item').remove();
   	}
   	  	
	function specialKey(field, e) {
		if ( e.getKey() == e.RETURN || e.getKey() == e.ENTER ) {
			submitSearch();
		}
	}
	
	if (_postalCode.length == 6){
		postalcodeTextField.focus();
	} else {
		nameTextField.focus();
	}
	
	function resetCategoryFields(){
		_name = ''
   		nameTextField.originalValue = '';
		nameTextField.reset();		
		
		neighbourhoodComboBox.reset();
    	cuisineComboBox.reset();
   		ratingComboBox.reset();
   		recommendationComboBox.reset();
	}
	
	function resetPostalCodeFields(){		
		_postalCode = '';
		_postalCodeLongitude = '';
		_postalCodeLatitude = '';		
		postalcodeTextField.originalValue = '';
   		postalcodeTextField.reset();
	}
	
	function submitSearch(){
		if (postalcodeTextField.isValid() == false){
			postalcodeTextField.focus();
			return;
		} else if (postalcodeTextField.getRawValue().length == 0){
			resetPostalCodeFields();
			Ext.util.GoogleMaps.setPostalCodeLatitude('');
			Ext.util.GoogleMaps.setPostalCodeLongitude('');
			submit();
		} else {
			postalcodeTextField.setRawValue(postalcodeTextField.getRawValue().toUpperCase());
			_postalCode = postalcodeTextField.getRawValue();
		
			if (location.href.indexOf("restaurant_list.php") > 0){
				var geocoder = new GClientGeocoder();
				geocoder.setBaseCountryCode("CA");
				geocoder.getLatLng(
				    _postalCode,
				    function(point) {
				      if (point){
				      	_postalCodeLatitude = point.y;
				        _postalCodeLongitude = point.x;
				        
				        Ext.util.GoogleMaps.setPostalCode(_postalCode);
				        Ext.util.GoogleMaps.setPostalCodeLatitude(point.y);
				        Ext.util.GoogleMaps.setPostalCodeLongitude(point.x);
				        
				        restaurantDs.baseParams['name'] = nameTextField.getRawValue();
						restaurantDs.baseParams['neighbourhood_id'] = neighbourhoodComboBox.getValue();
						restaurantDs.baseParams['cuisine_id'] = cuisineComboBox.getValue();
						restaurantDs.baseParams['rating'] = ratingComboBox.getValue();						
						restaurantDs.baseParams['recommendation'] = recommendationComboBox.getValue();
						
						restaurantDs.baseParams['latitude'] = point.y;
						restaurantDs.baseParams['longitude']= point.x;
						restaurantDs.reload();
				      }
				    }
				  );
			} else {
				submit();
			}
		}
	}

	function submit(){
		if (location.href.indexOf("restaurant_list.php") > 0){			
			restaurantDs.baseParams['name'] = nameTextField.getRawValue();
			restaurantDs.baseParams['neighbourhood_id'] = neighbourhoodComboBox.getValue();
			restaurantDs.baseParams['cuisine_id'] = cuisineComboBox.getValue();
			restaurantDs.baseParams['recommendation'] = recommendationComboBox.getValue();
			restaurantDs.baseParams['rating'] = ratingComboBox.getValue();
			restaurantDs.baseParams['latitude'] = _postalCodeLatitude;
			restaurantDs.baseParams['longitude'] = _postalCodeLongitude;
			restaurantDs.reload();
		} else {		
			var form = document.getElementById("searchForm");
			form.action = "restaurant_list.php";
			form.submit();
		}		
	}
	
	if (_neighbourhoodId.length > 0){
		neighbourhoodComboBox.setValue(_neighbourhoodId);
	}
	
	if (_cuisineId.length > 0){
		cuisineComboBox.setValue(_cuisineId);
	}
	
	if (_rating.length > 0){
		ratingComboBox.setValue(_rating);
	}
	
	if (_postalCode.length > 0){
		postalcodeTextField.setValue(_postalCode);
	}
});