// JavaScript Document


$(function(){
		   
	var map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(37.332495,-122.032013), 13);
	map.addControl(new GLargeMapControl());

	function addLocation(x,y,myHtml,name) {
			
			var point = new GLatLng(x, y);
			var marker = new GMarker(point);
			
			map.addOverlay(marker);
			
			GEvent.addListener(marker,"click", function() {
				map.openInfoWindowHtml(point, myHtml);
			});
			
		} // end addLocation();
		
	function getYelpData(query) {
		map.clearOverlays(); 
		map.setCenter(new GLatLng(37.332495,-122.032013), 13);
		
		$('#leftBarList').empty();
		$("#leftBarList").html('<div id="busy"><img src="images/busy.gif"></div>');
		$.get("getyelp.php", { q: query },
		   function(data){
			 $('#leftBarList').html(data);
			 $('.loc').each(function(index) {

				phone = $(this).find(".phone").text();
				name = $(this).find(".name").text();
				latitude = $(this).find(".lat").text();
				longitude = $(this).find(".long").text();
				address1 = $(this).find(".address1").text();
				address2 = $(this).find(".address2").text();
				reviews = $(this).find(".reviews").text();
				img = $(this).find(".img").text();
				url = $(this).find(".url").text();
				
				bubble_html = make_bubble_html(name, address1, address2, phone, reviews, img, url);			
							
				addLocation(latitude, longitude, bubble_html, name);
			});			 
		});			   						
	} // end getYelpData();
	
	function make_bubble_html(name, address1, address2, phone, reviews, img, url) {
		html = "<div id=\"bub\"><h2>" + 
		name + "</h2>" + 
		"<img align=right src=\"" + img + "\" />" + 
		address1 + "<br />" + 
		address2 + "<br />" + 
		phone + "<br />" + reviews + 
		"<br /><a target=\"_blank\" href=\"" + 
		url + "\">more reviews</a><br />" + 
		"</div>" +
		
		
		"</div>";	
		
		return html;
	} // end make_bubble_html()
	
	$('.query-btn').click(function(){
		var text = $(this).text();
		yquery = text + ".json";
		getYelpData(yquery);	
		$("#tweets").html('<div id="busy"><img src="images/busy.gif"></div>');
		$("#tweets").load("getsocial.php?s=" + text);	
		
	});
	
	$('.loc').live('click', function() {
		
		 map.setCenter(new GLatLng($(this).find('.lat').html(),$(this).find('.long').html()), 15);
		 
		 phone = $(this).find(".phone").text();
		 name = $(this).find(".name").text();
		 latitude = $(this).find(".lat").text();
		 longitude = $(this).find(".long").text();
		 address1 = $(this).find(".address1").text();
		 address2 = $(this).find(".address2").text();
		 reviews = $(this).find(".reviews").text();
	 	 img = $(this).find(".img").text();
		 url = $(this).find(".url").text();
		 
		 bubble_html = make_bubble_html(name, address1, address2, phone, reviews, img, url);			
		 map.openInfoWindowHtml(new GLatLng($(this).find('.lat').html(),$(this).find('.long').html()), bubble_html);
		
	});

	$('.zoom').click(function(){
	 	 map.setCenter(new GLatLng(37.332495,-122.032013), 13);	 
	});
	
});
