jQuery.delegate = function(rules) {
  return function(e) {
    var target = $(e.target);
    for (var selector in rules)
      if (target.is(selector)) return rules[selector].apply(this, $.makeArray(arguments));
  }
}

// ----------------------------------------------------------------------------

var map;

Mapping = $.klass({
	markers: new Array(),
	currentInfoWindow: null,
	
	createMap: function(id) {
		id = id || "map";
		var latlng = new google.maps.LatLng(37.538693290693175,-77.497071978717742);
		var myOptions = {
			zoom: 11,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById(id), myOptions);	
	},
	plotPointsJSON: function(points) {
		var bounds = new google.maps.LatLngBounds();

		// package single point into an array.
		points = jQuery.makeArray(points);

		var self = this;
		// iterate through the points and plot them w/ info windows
		$.each(points, function() {
			var lat = $(this).data('Point').lat;
			var lon = $(this).data('Point').lon;		
			var text = $(this).data('Point').text;	
			
			var point = new google.maps.LatLng(lat, lon);
			bounds.extend(point); // extend the bounds with the new point
			var infowindow = new google.maps.InfoWindow({
				content: text,
				size: new google.maps.Size(50,50)
			});		

			var marker = new google.maps.Marker({
				position: point, 
				map: map, 
				title: text
			}); 
			
			self.markers.push(marker);
			
			google.maps.event.addListener(marker, 'click', function() {
				if(self.currentInfoWindow) 
					self.currentInfoWindow.close();
				infowindow.open(map,marker);
				self.currentInfoWindow = infowindow;					
			});
		});	

		// zoom to bounds
		map.fitBounds(bounds);		
	},
	geocode: function(address, callback) {
		var gcoder = new google.maps.Geocoder();
		var self = this
		gcoder.geocode({address: address}, function (response) {
			self._processGeocode(response, callback);
		});			
	},
	_processGeocode: function(response, callback) {
		var latlon = {
			lat: response[0].geometry.location.lat(),
			lon: response[0].geometry.location.lng()
		}
		callback(latlon);
	}
});

// ----------------------------------------------------------------------------

MapContainer = $.klass(Mapping, {
	container: null,
	e: null,
	
	initialize: function(arg) {
		this.e = $(this.element[0]);		
		this.container = $(this.e.find('.padding')[0]);
	},
	onclick: $.delegate({
		'.viewMap a': function(e) { 
			return this.toggleMap($(e.target)); 
		}
	}),	
	toggleMap: function(e) {
		if(!this.container.hasClass('active')) {		
			// show map
			e.addClass('disabled');
			this.container.addClass('active');
			this.container.show();		

			// create a map the first time
			if(!this.container.hasClass('map')) {
				this.container.addClass('map');
				this.createMap();
				this.loadMapData();				
			}
				
		} else {
			e.removeClass('disabled');
			this.container.removeClass('active');
			this.container.hide();
		}
		return false;
	},
	loadMapData: function() {
		return false;
	},
	buildInfoWindow: function(i) {
		var str = '';
		str += '<div class = "infoWindow">';
		str += '	<h2><a href = "/eats/' + i.Restaurant.slug + '">' + i.Restaurant.name + '</a></h2>';
		str += '	<p>';
		if(i.Restaurant.website != '') str += '		<a href = "' + i.Restaurant.website + '">' + i.Restaurant.website +  '</a><br />';
		str += '	   ' + i.Restaurant.street + '<br />';
		if(i.Restaurant.phone != '') str += '	   ' + i.Restaurant.phone;
		str += '	</p>';
		str += '</div>';
		return str;
	}
}); // MapContainer

// ----------------------------------------------------------------------------

Result = $.klass({
	result: null,
	initialize: function() {

	},
	onclick: function(e) {
		// tags
		if($(e.target).parents('.tags')[0]) {
			return true;
		// stars
		} else if ($(e.target).parents('.eatsStars li')[0]) {
			return false;
		// view			
		} else if (this.isResult(e.target)) {
			this.view($(e.target));
			return false;
		}
	},
	onmouseover: function(e) {
		if (this.isResult(e.target)) {
			var result = this.findResult(e.target);
			if(!result.hasClass('active')) {
				result.addClass('active');
			}
			return false;
		}		
	},
	onmouseout: function(e) {
		if (this.isResult(e.target)) {
			var result = this.findResult(e.target);
			if(result.hasClass('active')) {
				result.removeClass('active');
			}
			return false;
		}
	},	
	view: function(e) {
		var location = $(e.parents('.result')[0]).find('.restaurant-slug')[0];
		//console.log(e.parents('.result').find('restaurant-slug'));
		window.location = '/eats/' + $(location).val();
		return false;		
	},
	isResult: function(e) {
		return $(e).hasClass('result') || $(e).parents('.result')[0];
	},
	findResult: function(e) {
		if($(e).hasClass('result')) {
			return $(e);
		} else {
			return $($(e).parents('.result')[0]);
		}
	}
});
	
// ----------------------------------------------------------------------------

SearchAndBrowse = $.klass({
	searchTab: null,
	browseTab: null,
	nearbyTab: null,
	e: '',
	oldText: null,
	
	initialize: function(arg) {
		this.e = $(this.element[0]);		
		this.searchTab = $(this.e.find('.search a')[0]);	
		this.browseTab = $(this.e.find('.browse a')[0]);			
		this.nearbyTab = $(this.e.find('.nearby a')[0]);

		if($('#el').val() == '')
			$('#el').val('Ex: 1205 W. Main St.');
	},
	onclick: $.delegate({
		'.search a': function() { return this.search() },
		'.browse a': function() { return this.browse() },
		'.nearby a': function() { return this.nearby() },
		'.textbox' : function(e) { return this.textbox($(e.target)) }
	}),
	onfocus: $.delegate({
		'.textbox' : function(e) { return this.textbox(e) }
	}),
	textbox: function(e) {
		this.oldText = e.text();
		e.select();
	},
	search: function() {
		if(!this.searchTab.hasClass('active')) {
			// switch active tab
			this.browseTab.removeClass('active');			
			this.searchTab.addClass('active');
			this.nearbyTab.removeClass('active');			
			
			this.e.find('#searchForm').show();
			this.e.find('#browseForm').hide();
			this.e.find('#nearbyForm').hide();			
		}
		return false;
	},
	browse: function(e) {
		if(!this.browseTab.hasClass('active')) {
			// switch active tab			
			this.browseTab.addClass('active');
			this.searchTab.removeClass('active');
			this.nearbyTab.removeClass('active');						

			this.e.find('#searchForm').hide();						
			this.e.find('#browseForm').show();
			this.e.find('#nearbyForm').hide();						
		}		
		return false;
	},
	nearby: function(e) {
		if(!navigator.geolocation) {
			if(!this.nearbyTab.hasClass('active')) {
				// switch active tab			
				this.browseTab.removeClass('active');
				this.searchTab.removeClass('active');			
				this.nearbyTab.addClass('active');						

				this.e.find('#searchForm').hide();						
				this.e.find('#browseForm').hide();
				this.e.find('#nearbyForm').show();						
			}		
			return false;
		} else {
			return true;
		}
	}	
}); // SearchAndBrowse

// ----------------------------------------------------------------------------

function hideAll() {
	var menus = $('div.lh_container');
	jQuery.each(menus, function() {
		$(this).hide();
	});
} // hideAll

// ----------------------------------------------------------------------------

$(document).ready( function() {
	// mouse out of a menu drop down
	$('#menu').mouseleave(function() {
		hideAll();
	});
	
	// hover over a menu
	$('.lh_hMenu ul li p a').mouseenter(function() {
		hideAll();
		$(this).parent().next('div.lh_container').show();
	});	
	
	$('#searchAndBrowse').attach(SearchAndBrowse);
	$('#searchResults').attach(Result);	
});
