///////////////////////////////////////////////
// Benny Wong
//   2007/04/25

///////////////////////////////////////////////
// Contants
//////////////////////////////////////////////
var ITEM = 0;
var LIST = 1;
var LISTINGS_PER_PAGE = 8;

///////////////////////////////////////////////
// Variables
//////////////////////////////////////////////
var restaurants;
var current;
var map;
var old;
var filters = {'Cuisine' : [null, null], 'Price' : [null, null], 'Street' : [null, null], 'Avenue' : [null, null]};

///////////////////////////////////////////////
// General Functions
//////////////////////////////////////////////
function load(flag) {
	if (GBrowserIsCompatible()) {
		// Add the map, the regular controls, and center it on CU.
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(40.807783927398695, -73.96212816238403), 16);
		
		// If this is the main page.
		if (!flag) {
			// Get the restaurants, display the tab switcher, and get the list
			// of the categories.
			getRestaurants();
			map.addControl(new TabSwitcher());
			
			filters['Cuisine'][LIST] = $('Cuisine').innerHTML;
			filters['Price'][LIST] = $('Price').innerHTML;
			filters['Street'][LIST] = $('Street').innerHTML;
			filters['Avenue'][LIST] = $('Avenue').innerHTML;
		}
		// Else, add the individual markers.
		else { individualMarkers(); }
	}
}

function updateApp() {
	// Update the application.
	placeMarkers();
	fillListContent();
}

///////////////////////////////////////////////
// Maps
//////////////////////////////////////////////
function placeMarkers() {
	// clear the map of any overlays.
	map.clearOverlays();
	
	// For each from the filtered array, add the marker and add
	// the event listener.
	current.each( function(r) {
		var marker = new GMarker(new GLatLng(r.longitude, r.latitude), {draggable : false});
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(printRestaurant(r));
		});
		/*
		// Make draggable.
		GEvent.addListener(marker, "dragstart", function() {
			map.closeInfoWindow();
		});

		GEvent.addListener(marker, "dragend", function() {
			new Ajax.Request('/ajax/adjust_marker', {
				parameters : "id=" + r.name + "&restaurant[latitude]=" + marker.getPoint().lng() + "&restaurant[longitude]=" + marker.getPoint().lat()
			});
		});
		*/
		map.addOverlay(marker);
	});
}

function placePoint(point) {
	// Take the point, place it, and center the map on the new marker.
	var marker = new GMarker(point);
	map.addOverlay(marker);
	map.setCenter(point, 16);
}

// Same as above, except with two coordinates.
function placeMarker(longitude, latitude) { placePoint(new GLatLng(longitude, latitude)); }

///////////////////////////////////////////////
// Restaurants
//////////////////////////////////////////////
function getRestaurants() {
	/*
	// Since we're getting a JSON response, it'll be easy just to eval the response.
	var handlerFunc = function(t) {
		eval("(" + t.responseText + ")");
		
		current = new Array();
		for (i=0;i<10;i++) current.push(restaurants[i]);
		//current = restaurants;
		
		updateApp();
	}
	var errFunc = function(t) { alert('Error ' + t.status + ' -- ' + t.statusText); }
	new Ajax.Request('/ajax/restaurants', {parameters:'', onSuccess:handlerFunc, onFailure:errFunc});
	*/
	//current = new Array();
	//for (i=0;i<10;i++) current.push(restaurants[i]);
	current = restaurants;
	
	updateApp();
}

function updateRestaurants() {
	// The filtered response array.
	current = new Array();
	
	// For each of the restaurants, run through the filters.
	restaurants.each(function(r) {
		flag = true;
		if (filters['Cuisine'][ITEM] != null && (r['Cuisine'].indexOf(filters['Cuisine'][ITEM]) == -1)) flag = false;
		if (flag && filters['Price'][ITEM] != null && (r['Price'].indexOf(filters['Price'][ITEM]) == -1)) flag = false;
		if (flag && filters['Street'][ITEM] != null && (r['Street'].indexOf(filters['Street'][ITEM]) == -1)) flag = false;
		if (flag && filters['Avenue'][ITEM] != null && (r['Avenue'].indexOf(filters['Avenue'][ITEM]) == -1)) flag = false;
		if (flag) current.push(r);
	});
	
	// Update everything.
	updateApp();
}

function printRestaurant(r) {
	// Formatted output.
	var str = "<b>" + r.name + "</b><br/>";
	str += "<table class=\"marker\">";
	str += "<tr><td valign=\"top\">Address:</td><td>" + r.street1 + "</td></tr>";
	if (r.street2) str += "<tr><td></td><td>" + r.street2 + "</td></tr>";
	str += "<tr><td valign=\"top\">Phone:</td><td>"
	str += (r.phone == "") ? "None" : r.phone;
	str += "</td></tr>";
	str += "<tr><td valign=\"top\">Cuisine:</td><td>" + r.Cuisine + "</td></tr>";
	if (r.delivery) str += "<tr><td valign=\"top\">Delivery:</td><td>" + r.delivery + "</td></tr>";
	str += "</table>";
	str += "<a href=\"/restaurants/list/" + r.slug + "\">more info &raquo;</a>";
	return str;
}

///////////////////////////////////////////////
// Listings
//////////////////////////////////////////////
function fillListContent(pageNum) {
	Effect.Fade('pages', { afterFinish : function() {
		// The HTML.
		if (!pageNum) pageNum = 1;
		var result = "";
		var pages = Math.ceil(current.length / LISTINGS_PER_PAGE);
	
		// Print the pagination links (numbers and next/previous links).
		for (i = 1; i <= pages; i++) {
			if (i == 1) {
				if (pageNum != 1)
					result += "<a href=\"javascript:;\" onclick=\"fillListContent(" + (pageNum-1) + ");\">&#171 Previous</a> ";
				else
					result += "&#171 Previous ";
			}

			if (pageNum == i) result += i + " ";
			else result += "<a href=\"javascript:;\" onclick=\"fillListContent(" + i + ");\">" + i + "</a> ";

			if (i == pages) {
				if (i == pages && pageNum == pages)
					result += "Next &#187";
				else
					result += "<a href=\"javascript:;\" onclick=\"fillListContent(" + (pageNum+1) + ");\">Next &#187</a>";
			}
		}
		result += "<br /><br />";

		// The start index.
		var start = (pageNum - 1) * LISTINGS_PER_PAGE;
		for (i = start; i<(start + LISTINGS_PER_PAGE) && i<current.length; i++) {
			// Output the restObj.
			result += printRestaurant(current[i]) + "<hr/>";
		}
		$('pages').innerHTML = result;
		Effect.Appear('pages', {duration : 0.1, fps:40});
	}, duration : 0.1, fps:40});
}

///////////////////////////////////////////////
// Filters
//////////////////////////////////////////////
function addFilter(type, category) {
	// Replace the filter with the drill-down.
	$(type).innerHTML = "<span class=\"red\">" + category + "</span>";
	$(type).innerHTML += "<br/><a href=\"javascript:;\" onclick=\"javascript:removeFilter('" + type  + "', 0);\">Remove filter</a>";
	
	// Set the filter and update.
	filters[type][ITEM] = category;
	updateRestaurants();
}

function removeFilter(type) {
	// Remove the filter and restore the list.
	filters[type][ITEM] = null;
	$(type).innerHTML = filters[type][LIST];
	
	// Restore the array and then update.
	current = restaurants;
	updateRestaurants();
}

function clearFilters() { ['Cuisine', 'Price', 'Street', 'Avenue'].each(function(t) { removeFilter(t); }) }
function clearFeatured() { }//Effect.Fade('featured')}

///////////////////////////////////////////////
// Tab Switcher
//////////////////////////////////////////////
function TabSwitcher() {}
TabSwitcher.prototype = new GControl();
TabSwitcher.prototype.getDefaultPosition = function() { return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(60, 7)); }

TabSwitcher.prototype.initialize = function(map) {
	var button = document.createElement("div");
	this.setButtonStyle_(button);
	button.appendChild(document.createTextNode("Switch to Text Listings"));
	GEvent.addDomListener(button, "click", function() {
		new TabToggle('map');
	});

	map.getContainer().appendChild(button);
	return button;
}

// Sets the proper CSS for the given button element.
TabSwitcher.prototype.setButtonStyle_ = function(button) {
	button.style.textDecoration = "none";
	button.style.fontWeight = "bold";
	button.style.color = "#336699";
	button.style.backgroundColor = "white";
	button.style.border = "1px solid black";
	button.style.padding = "5px";
	button.style.textAlign = "center";
	button.style.width = "15em";
	button.style.cursor = "pointer";
}

TabToggle = function(element) {
	var on = (element == 'map') ? $('listing') : $('map');
	$(element).style.display = 'none';
  	new Effect.Appear(on, {duration:0.5});
}
