//http://groups.google.com/group/Google-Maps-API/browse_thread/thread/341841313d30dd83?pli=1

$(function() {

	$('.left_toggle').click(function(){
		$('.left_rail').toggle();
		$('#map').toggleClass('slim');
	});
	
	$('#search').example(function() {
  		return $(this).attr('title');
	});
	
	var json_autocomplete_settings = "({\
		dataType: 'json',\
		width: '165px',\
		parse: function(data) {\
		    var parsed = [];\
		    for (var i = 0; i < data.length; i++) {\
		        parsed[parsed.length] = {\
		            data: data[i],\
		            value: data[i].text ,\
		            result: data[i].text\
		        };\
		    }\
		    return parsed;\
		},\
		formatItem: function(item) {\
			return item.display;\
		}})";

	$("#search").autocomplete('/api/search', $.extend(
				eval(json_autocomplete_settings), 
				{ multiple: false} 
				));
				
	$('#search').result(findValueCallback);
	
	function findValueCallback(event, data, formatted) {
		location.href = data.url;
	}

	$("#jquery_jplayer").jPlayer();
	$("#jquery_jplayer").jPlayerId("play", "play");
	$("#jquery_jplayer").jPlayerId("pause", "pause");
	$("#jquery_jplayer").jPlayerId("stop", "stop");
	$("#jquery_jplayer").jPlayerId("volumeMin", "vmute");
	$("#jquery_jplayer").jPlayerId("volumeMax", "vunmute");
	
	$("#mute a").click(function(){$("#mute a").toggle()});

	$("#jquery_jplayer").onProgressChange( function(lp,ppr,ppa,pt,tt) {
		var width = (parseInt(ppa) / 100) * 217;
 		$(".pcent").width(width);
	});
	
	if ($("#map").length > 0) {
		var apiResults = new Object();
	
		var map = new GMap2($("#map").get(0));
		var center = new GLatLng(33.76602, -84.38942);
		
		map.setCenter(center, 15);
		map.setUIToDefault();
		map.disableScrollWheelZoom();
		
		main(map, center);
 	} else {
 		listenForClicks(null);
 	}
 
	function main(map, center) 
	{
		this.map = map;
		this.center = center;
		this.locations = [];
		
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.image = "/images/map_marker.png";
        baseIcon.shadow = "/images/map_markerShadow.png";
	    baseIcon.iconSize = new GSize(21.0, 25.0);
	    baseIcon.shadowSize = new GSize(34.0, 25.0);
	    baseIcon.iconAnchor = new GPoint(10.0, 12.0);
	    baseIcon.infoWindowAnchor = new GPoint(10.0, 12.0);
		
		$('#map_message').hover(function(){
			map.disableDoubleClickZoom();
			map.disableDragging();
		}, function(){
			map.enableDoubleClickZoom();
			map.enableDragging();
		});
		
		$("#map_message").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));
		
		$('.map_close').livequery('click', function(){
			$("#map_message").hide();
		});
		
		var bounds = new GLatLngBounds();

		$.getJSON("/api/map",
		function(result){
			apiResults = result;
			//setup sidebar
			$.each(result.places, function(i, place){
				if (place.stories != '') {
					//map setup
					var location = new GLatLng( place.latitude , place.longitude );
					bounds.extend(location);
					markerOptions = { icon:baseIcon };
					var marker = new GMarker(location, markerOptions);
					map.addOverlay(marker);
					
					GEvent.addListener(marker, "click", function(){
						mapOpen(place.place_id);
					});
					
					//sidebar setup
					$("<li />").attr('id', 'nav_place_container_' + place.place_id).html('<strong id="nav_place_' + place.place_id + '" class="place">'+place.place_name+' <a href="/place/'+place.place_url+'">link</a></strong>').appendTo("#map_nav");
					
					var output = '<ul>';
					$.each(place.stories, function(i, story){
						output += '<li id="nav_story_'+story.story_id+'" class="story">'+story.story_title+' <a class="fakelink play">play</a> <a href="/story/'+story.story_url+'">link</a></li>';
					});
					output += '</ul>';
					
					$('#nav_place_container_' + place.place_id).append(output);
				}
			});
					    	
			map.setZoom(map.getBoundsZoomLevel(bounds));
			map.setCenter(bounds.getCenter());
			
			listenForClicks(result);
			
		});
		  	
	}
	
	function getStory_ids(result, item){
		var ids = new Object();
		var story_id = '';
		var place_id = '';
		
		story_id = parseInt(item.attr('id').replace('nav_story_', '').replace('map_story_', ''));
   		$.each(result.places, function(i, place){
   			$.each(place.stories, function(i, story){
   				if (story.story_id == story_id) {
   					place_id = place.place_id;
   				}
   			});
   		});
   			
		ids.story_id = story_id;
		ids.place_id = place_id;
		
		return ids;
	}
	
	
	function listenForClicks(result){
	
		// STORY CLICKS
		$('.story').click(function(){
			var story_id = '';
			var place_id = '';				

			var ids = getStory_ids(result, $(this));
			story_id = ids.story_id;
			place_id = ids.place_id;
			
			mapOpen(place_id, story_id);
		});
		
		$('.play').livequery('click', (function(){
			if ($(this).attr('storyid')) {
				playStory($(this).attr('storyid'));
			} else {
				var story_id = '';
				var place_id = '';				

				var ids = getStory_ids(result, $(this));
				story_id = ids.story_id;
				place_id = ids.place_id;
				
				// if the play button doesn't have the story id data, traverse up the dom until you hit the div with the story data
				if (!story_id) {
					var parent = $(this).parents('.story');
					var ids = getStory_ids(result, parent);
					story_id = ids.story_id;
					place_id = ids.place_id;
				}
			 	playStory(story_id);
		 	}
		}));

		
		// PLACE CLICKS
		$('.place').click(function(){
			var place_id = parseInt($(this).attr('id').replace('nav_place_', '').replace('map_place', ''));
			mapOpen(place_id);
		});

	}
	
	function mapOpen(place_id, story_id){
		//alert('place id: ' + place_id + ' / story_id: ' + story_id);
	    var place = apiResults.places[place_id];
	    var position = new GLatLng(place.latitude, place.longitude);
	    var description = '<div class="map_bubble_place"><img src="/images/map_close.png" class="map_close"><h4><a href="/place/'+place.place_url+'">'+place.place_name+'</a></h4>';
	    $.each(place.stories, function(i, story){
	    	description += '<div id="map_'+story.story_id+'" class="map_bubble_story"><a class="play" storyid="'+story.story_id+'"><img src="/images/map_play.png"></a>'; 
	    	description += '<div class="title_container"><h3><a href="/story/'+story.story_url+'">'+story.story_title+'</a></h3><p class="small">by ' + story.author_name + ' | ' + story.mp3_hms + '</p></div>';
	    	description += '<p>' + story.description + '</p></div>';
	    });
	    description += '</div>';
	    
	    $("#map_message").html(description);
	    
		if ($('#map_message').is(':hidden')) {
			if ($('#map_message').hasClass('place_'+place_id)) {
				$('#map_message').show(0, function(){
					scrollToStory(story_id)
				});
			}
		} else {
			if ($('#map_message').hasClass('place_'+place_id+'_story_'+story_id)) {
				$('#map_message').hide();
			} else if ($('#map_message').hasClass('place_'+place_id)) {
				scrollToStory(story_id);
			} else {
				$('#map_message').hide();
			}
		}
		
		$('#map_message').attr('class', 'place_'+place_id +' place_'+place_id+'_story_'+story_id);
		
		var moveEnd = GEvent.addListener(map, "moveend", function(){
			var markerOffset = map.fromLatLngToDivPixel(position);
			$("#map_message")
				.css({ top:markerOffset.y - 280, left:markerOffset.x - 25}).fadeIn(0, function(){
					//scrollToStory(story_id)
				});
			GEvent.removeListener(moveEnd);
		});
		
		function scrollToStory(story_id){
			if (story_id) {
				$('#map_'+story_id).addClass('map_bubble_story_active');
				$('#map_message').scrollTo( '#map_'+story_id, 180 );
			} else {
				$('#map_message').scrollTo('h4', 180);
			}
		}
		
		var panOffset = map.fromLatLngToDivPixel(position);
		var panPosition = map.fromDivPixelToLatLng(new GPoint(panOffset.x + 100, panOffset.y - 100));
		map.panTo(panPosition);
	}
	
	function playStory(story_id) {
		$.getJSON("/api/story/"+story_id,
		function(data){
			$("#trackname").html(data.story.story_title);
			$("#jquery_jplayer").changeAndPlay('/'+data.story.mp3_location);
		});
	}


});
