var restaurantDs;
google.load("maps", "2.x");

Ext.onReady(function(){	
  	var tabs = new Ext.TabPanel('tabs1');
	restaurantTab = tabs.addTab('restaurants_tab', 'Results (0)');
   	mapTab = tabs.addTab('map_tab', 'Map Locations (0)');
    tabs.activate('restaurants_tab');
    
	restaurantDs = new Ext.data.Store({
		baseParams: {
			name: _name,
			neighbourhood_id: _neighbourhoodId,
			cuisine_id: _cuisineId,
			rating: _rating,
			recommendation: '',
			latitude: '',
			longitude: '',
			type: 'restaurants'
		},
		
	    proxy: new Ext.data.HttpProxy({
			url: 'http://www.hungrytable.com/json.php'
		}),
	
	    reader: new Ext.data.JsonReader({
	        root: 'restaurants',
	        totalProperty: 'totalCount',
	        id: 'restaurant_id'
	    }, [
	    	{name: 'restaurant_id', mapping: 'restaurant_id', type: 'int'},
	        {name: 'restaurant_name', mapping: 'restaurant_name'},
	        {name: 'neighbourhood_id', mapping: 'neighbourhood_id'},
	        {name: 'neighbourhood_name', mapping: 'neighbourhood_name'},
	        {name: 'address', mapping: 'address'},		        
	        {name: 'province', mapping: 'province'},
	        {name: 'city', mapping: 'city'},
	        {name: 'postal_code', mapping: 'postal_code'},
	        {name: 'telephone', mapping: 'telephone'},
	        {name: 'comment_count', mapping: 'comment_count', type: 'int'},
	        {name: 'average_rating', mapping: 'average_rating', type: 'int'},
	        {name: 'latitude', mapping: 'latitude', type: 'float'},
	        {name: 'longitude', mapping: 'longitude', type: 'float'},	        
	        {name: 'created_date', mapping: 'created_date'},
	        {name: 'tags', mapping: 'tags'},
	        {name: 'distance', type: 'float'},
	        {name: 'recommendation_count', mapping: 'rec_count', type: 'float'}
	    ])
	});
	
	var restaurantCm = new Ext.grid.ColumnModel([{
		id: "topic", 
	 	header: "Restaurant Name",
		dataIndex: 'restaurant_name', 
		width: 260,
		renderer: renderRestaurant,
		resizable: false
	},{
		header: "Neighbourhood", 
		dataIndex: 'neighbourhood_name', 
		width: 95,
		renderer: renderNeighbourhood,
		resizable: false
	},{
		header: "Cuisine", 
		dataIndex: 'tags', 
		width: 95,
		renderer: renderCuisine,
		sortable: false,
		resizable: false
	},{
		header: "Average Rating", 
		dataIndex: 'average_rating', 
		width: 95,
		renderer: renderRating,
		resizable: false
	},{
		header: "Reviews", 
		dataIndex: 'comment_count', 
		width: 55,
		resizable: false
    },{
        id: 'recommendation',
		header: "Recommendations", 
		dataIndex: 'recommendation_count', 
		width: 110,
		resizable: false,
		renderer: renderRecommendation
	},{
		id: 'distance',
		header: "Distance", 
		dataIndex: 'distance', 
		renderer: renderDistance,
		width: 95,
		resizable: false
    }]);

	restaurantCm.defaultSortable = true;
	
    var restaurantsGrid = new Ext.grid.Grid('grid-restaurants', {
        ds: restaurantDs,
        cm: restaurantCm,
        loadMask: true,
        enableColumnMove: false,
        autoExpandColumn: 'topic'
    });

    restaurantsGrid.getSelectionModel().lock();
	restaurantsGrid.render();
	
	var gridFoot =  restaurantsGrid.getView().getFooterPanel(true);

    var paging = new Ext.PagingToolbar(gridFoot, restaurantDs, {
        pageSize: 25,
        displayInfo: true,
        displayMsg: 'Displaying restaurants {0} - {1} of {2}',
        emptyMsg: "No restaurants to display"
    });
    
    var toolbarButton = new Ext.Toolbar.Button({
        pressed: false,
        enableToggle:true,
        text: 'Standard View',
        cls: 'x-btn-text-icon details',
        toggleHandler: toggleDetails
    });
    
    paging.add('-', toolbarButton);

    if (_postalCode.length == 6){
		restaurantCm.setHidden(5, false);
		
		var geocoder = new GClientGeocoder();
			geocoder.setBaseCountryCode("CA");
			geocoder.getLatLng(
			    _postalCode,
			    function(point) {
			      if (point){
			        restaurantDs.baseParams['latitude'] = point.y;
					restaurantDs.baseParams['longitude'] = point.x;
					Ext.util.GoogleMaps.setPostalCode(_postalCode);
			        Ext.util.GoogleMaps.setPostalCodeLatitude(point.y);
			        Ext.util.GoogleMaps.setPostalCodeLongitude(point.x);
			        restaurantDs.on('load', restaurantCallback);
					restaurantDs.load({params: {start:0, limit:25}});
			      }
			    }
			  );
	} else {
		restaurantCm.setHidden(5, true);
		restaurantDs.sort('restaurant_name', 'asc');
		restaurantDs.on('load', restaurantCallback);
		restaurantDs.load({params: {start:0, limit:25}});
	}

	function restaurantCallback(){
		restaurantTab.setText("Results (" + restaurantDs.getCount() + ")");
		mapTab.setText("Map Locations (" + restaurantDs.getCount() + ")");
		
		if (Ext.util.GoogleMaps.isAvailable() == true){
			Ext.util.GoogleMaps.createMap(Ext.get("map_tab"), document.getElementById("map_area"), restaurantDs);
		}
		
		if (restaurantDs.getCount() > 0) {
			if (_postalCode.length == 6){				
				restaurantCm.setHidden(5, true);
				restaurantCm.setHidden(6, false);
				restaurantDs.sort('distance', 'asc');
			} else {				
				restaurantCm.setHidden(5, false);
				restaurantCm.setHidden(6, true);
				restaurantDs.sort('restaurant_name', 'asc');
			}
		} else {			
			restaurantsGrid.view.mainBody.update('<div style="padding:10px;">Your search did not match any restaurants.</div>');
		}
	}
	
	function toggleDetails(btn, pressed){
	    document.getElementById("neighbourhood_id").focus();
	    
        if (pressed == true){
	       toolbarButton.setText("Detailed View");
	    } else {
	       toolbarButton.setText("Standard View"); 
	    }
	    
    	restaurantCm.getColumnById('topic').renderer = pressed ? renderRestaurantDetails : renderRestaurant;
    	restaurantsGrid.getView().refresh();
	}
	
	function renderDistance(value){
		if (value >= 1){
			return Math.round(value*10)/10 + " km";				
		} else {
			return Math.round(value*1000, 0) + " m";
		}
	}
	
	function renderRating(value, p, record){
		var fullStars = "";
		var emptyStars = "";			
		
		for (var i=0; i<value; i++){
			fullStars = fullStars + "*";
		}
		
		for (var i=0; i<(5-value); i++){
			emptyStars = emptyStars + "*";
		}
		
		return '<font class="ratings" color="#cc3300">' + fullStars + '</font><font class="ratings" color="#cccccc">' + emptyStars + '</font>';
	}
	
	function renderRestaurant(value, p, record){
	    return String.format('<a href="/restaurant/{1}/">{0}</a>', value, record.data['restaurant_id']);
	}
	 
	function renderRestaurantDetails(value, p, record){
	    var name = String.format('<a href="/restaurant/{1}/">{0}</a>', value, record.data['restaurant_id']);
	    var telephone = '(' + record.data['telephone'].substring(0,3) + ') ' + record.data['telephone'].substring(3,6) + '-' + record.data['telephone'].substring(6,10);
	    var postal_code = record.data['postal_code'].substring(0,3) + " " + record.data['postal_code'].substring(3,6);
	    
	    var restaurant = name + "<br/>";
	    restaurant = restaurant + record.data['address'] + "<br />";
	    restaurant = restaurant + record.data['city'] + ", " + record.data['province'] + "<br />";
	    restaurant = restaurant + postal_code + "<br />";		    
	    restaurant = restaurant + telephone + "<br />";
	    
	    return restaurant;
	}
	
	function renderUsername(value, p, record){
	    return String.format('<a href="user.php?id={1}">{0}</a>', value, record.data['user_id']);
	}
	
	function renderNeighbourhood(value, p, record){
		return String.format('<a href="restaurant_list.php?neighbourhood_id={1}">{0}</a>', value, record.data['neighbourhood_id']);
	}
	
	function renderRecommendation(value, p, record){
	    if (value == 0){
	        return '';
	    } else {
	        return value;
	    }
	}
	
	function renderCuisine(value, p, record){
		tagArray = value;
		if (tagArray.length > 0){
			var tagText = "";
			
			for (var i=0; i<tagArray.length; i++){
				tagText += '<a href="restaurant_list.php?cuisine_id=' + tagArray[i].cuisine_id + '">' + tagArray[i].cuisine_name + '</a> ';
			}
			
			return tagText;
		} else {
			return;
		}
	}
	
	function displayRestaurantHtml(record){
		var html = "<h4>" + String.format('<a href="/restaurant/{0}/">{1}</a>', record.get("restaurant_id"), record.get("restaurant_name")) + "</h4>";
		html += record.get("address") + "<br />";
		html += record.get("city") + ", " +  record.get("province") + "&nbsp;" + record.get("postal_code") + "<br /><br />";
		html += '(' + record.get("telephone").substring(0,3) + ') ' + record.get("telephone").substring(3,6) + '-' + record.get("telephone").substring(6,10) + "<br />";
		html += renderRating(record.get("rating"));		
		return html;
	}
	
	function createMarker(point, value, icon) {
	  var marker = new GMarker(point, icon);
	  GEvent.addListener(marker, "click", function() {
	    marker.openInfoWindowHtml(value);
	  });		  
	  return marker;
	}
});	
