var fetchData = true;
var mapArray = new Array();
var restaurantDs2;
google.load("maps", "2.x");

Ext.onReady(function(){	
    var tabs = new Ext.TabPanel('tabs1');
    exploreTab = tabs.addTab('explore', 'Restaurants (0)');
    tabs.activate('explore');

    var mapTabDiv =  Ext.get("map_area");
	var mapDiv = document.getElementById("map_area");
	mapDiv.style.height = mapTabDiv.getComputedHeight();
	mapDiv.style.width = mapTabDiv.getComputedWidth();
	
	var nearbyIcon = new google.maps.Icon();		
	nearbyIcon.shadow = "images/mm_20_shadow.png";
	nearbyIcon.iconSize = new google.maps.Size(12, 20);
	nearbyIcon.shadowSize = new google.maps.Size(22, 20);
	nearbyIcon.iconAnchor = new google.maps.Point(6, 20);
	nearbyIcon.infoWindowAnchor = new google.maps.Point(5, 1);
	
	var map = new google.maps.Map2(mapDiv);
	map.addControl(new google.maps.LargeMapControl());
	map.addControl(new google.maps.ScaleControl());
	map.addControl(new google.maps.MapTypeControl());    
	map.addControl(new google.maps.OverviewMapControl());
    map.addControl(new DragZoomControl(
        {
            opacity:.2,
            border:"2px solid red"
        },{
            buttonHTML:"<img src='/images/zoom-button.gif' />",
            buttonZoomingHTML:"<img src='/images/zoom-button-activated.gif' />",
            buttonStartingStyle:{width:'24px',height:'24px'}
        }
       )
    );	
	
	map.setCenter(new google.maps.LatLng(45.326565,-75.66679), 13);
	var bounds = map.getBounds();
	var ne = bounds.getNorthEast();
	var sw = bounds.getSouthWest();
	
	restaurantDs2 = new Ext.data.Store({
    	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: 'id', type: 'int'},
            {name: 'restaurant_name', mapping: 'n'},
            {name: 'average_rating', mapping: 'avg', type: 'int'},
            {name: 'latitude', mapping: 'lat', type: 'float'},
            {name: 'longitude', mapping: 'lng', type: 'float'},
        ])
    });
	
    restaurantDs2.on('load', restaurantCallback);
    restaurantDs2.load();
    
    var mgr = new MarkerManager(map);
    
    function restaurantCallback(){
        mgr.clearMarkers();
        restaurantDs2.sort('restaurant_name', 'asc');
        exploreTab.setText("Restaurants (" + restaurantDs2.getTotalCount() + ")");
                
        
        nearbyIcon.image = "images/marker_20_red.png";
        
    	for (var i=0; i<restaurantDs2.getTotalCount(); i++){
			record = restaurantDs2.getAt(i);
			var marker;
			var markerExists = false;
			
			for (var j=0; j<mapArray.length; j++){
			    if (mapArray[record.get("restaurant_id")] != null){
                    markerExists = true;
                    marker = mapArray[record.get("restaurant_id")];
                    break;
			    }			     
			}
			
			if (markerExists == false){
    			if (record.get("latitude") != 0 && record.get("longitude") != 0){
    				var point = new google.maps.LatLng(record.get("latitude"), record.get("longitude"));				
    				marker = createMarker(point, displayRestaurantHtml(record), nearbyIcon);
    				mapArray[record.get("restaurant_id")] = marker;
    			}
			}
			
			mgr.addMarker(marker, 10);
		}
		
		 mgr.refresh();
    }
    
	GEvent.addListener(map, "moveend", function() {
        var bounds = map.getBounds();
        var ne = bounds.getNorthEast();
        var sw = bounds.getSouthWest();
        restaurantDs2.baseParams['ne_lat'] = ne.lat();
        restaurantDs2.baseParams['ne_lng'] = ne.lng();
        restaurantDs2.baseParams['sw_lat'] = sw.lat();
        restaurantDs2.baseParams['sw_lng'] = sw.lng();
        restaurantDs2.baseParams['type'] = 'restaurants';
        restaurantDs2.reload();
    });
	
	var restaurantCm = new Ext.grid.ColumnModel([{
		id: "topic", 
	 	header: "Restaurant Name",
		dataIndex: 'restaurant_name', 
		width: 260,
		renderer: renderRestaurant,
		resizable: false
	},{
		header: "Average Rating", 
		dataIndex: 'average_rating', 
		width: 100,
		renderer: renderRating,
		resizable: false
    }]);

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

    restaurantsGrid.getSelectionModel().lock();
	restaurantsGrid.render();
	
	function renderRestaurant(value, p, record){
	    return String.format('<a href="javascript:displayMarker({1})">{0}</a>', value, record.data['restaurant_id']);
	}
	
	function createMarker(point, value, icon) {
        var marker = new google.maps.Marker(point, icon);
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(value);
        });	  
        return marker;
	}
	
	function displayRestaurantHtml(record){
    	var html = "<h4>" + String.format('<a href="/restaurant/{0}/">{1}</a>', record.get("restaurant_id"), record.get("restaurant_name")) + "</h4><br />";
    	html += renderRating(record.get("average_rating"));		
    	return html;
    }
    
    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 displayMarker(id){
	for (var i=0; i<restaurantDs2.getTotalCount(); i++){
		var record = restaurantDs2.getAt(i);
		
		if (record.get("restaurant_id") == id){
			GEvent.trigger(mapArray[id], 'click');
			return;
		}
    }
}
