$(document).ready(function(){


if( $("#gallery").hasClass("full")) {

	var index = 1;
	var gallery = $("#gallery.full");
	var slideShow = $("#slideshow");
	var slides = slideShow.children();
	var images = $("#slideshow .image-master");
	var numberOfSlides = slides.length;
	var section1Width = $("#section1").width();

	// make it all happen	
	gallery.addClass("js-enabled");

	// enable sliding
	slides.wrapAll('<div id="slideWrapper"></div>').css({ width: section1Width * numberOfSlides });
	
	var slideWrapper = $("#slideWrapper");
	
	function updateImage() { slideWrapper.css({ 'marginLeft': section1Width * (-(index-1)) }).fadeIn("medium"); }
	
	// set slide width			
	slides.width(section1Width);

	(function createThumbs(){
		var thumb, thumb_src;
		var thumb_width = numberOfSlides * 85;
		var thumb_padding = numberOfSlides * 10;
		var thumbsWrapper = $("#images-thumbs");
		var thumbs = thumbsWrapper.children();
		var thumbsWrapperWidth = thumb_width + thumb_padding;
					
		var thumbsWrapper = $("<ul/>").attr("id", "images-thumbs");
		var gallery_controls = $("<div/>").attr("id", "gallery-controls");
		
		var nav = "<div class='nav'><a class='next' href='javascript://' rel='history'>next image</a><a class='previous' href='javascript://' rel='history'>previous image</a></div>";
		
		var overlay_nav = "<div id='overlay-nav'><a class='next' href='javascript://' rel='history'>next image</a><a class='previous' href='javascript://' rel='history'>previous image</a></div>";

		// upper nav
		gallery.prepend(nav);
		
		// lower nav
		gallery_controls
		    .prepend(thumbsWrapper)
		    .prepend(nav)
		    .appendTo(gallery);
		    
		// Retrieve thumb src from large image rel & generate thumbs  		    
		images.each( function( indexValue ){
			thumb_src = $(this).attr("rel");
			thumb = "<li><a href='#" + (indexValue + 1) + "' rel='history'><img src='" + thumb_src + "' /></a></li>";
			thumbsWrapper.append(thumb);
		});
		
		//slideShow.prepend(overlay_nav);
			
		// center align short galleries
		if ($("#images-thumbs li").length < 6) {
			thumbsWrapper.css({ width: thumbsWrapperWidth + 'px' });
		}			
	})();
	
	// PageLoad function
	// This function is called when:
	// 1. after calling $.historyInit();
	// 2. after calling $.historyLoad();
	// 3. after pushing "Go Back" button of a browser
	function pageload(hash) {
		// hash doesn't contain the first # character.
		if(hash) {
			index = hash;
			// restore ajax loaded state
			$("#images-thumbs li").eq(index-1).addClass("active");
			updateImage();
		} else {
			// start page
			$("#load").empty();
		}
	}
	
	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	$.history.init(pageload);
		
	(function slideShowHeight() {	
		
		var $t = 0, $t_store, img_height, meta_height = $(".image-meta").outerHeight();
			
		// determine tallest image + pad short images
		images.each(function () {
    		if ( $(this).outerHeight() > $t ) {
        		$t_store = $(this);
        		$t = $t_store.outerHeight();
    		}
		});
	
		// set height including image-meta div height
		$("#slideshow, #slideshow li").css({ height: $t + meta_height });
		//$("#overlay-nav a").css({ height: $t });

		// top-pad short images
		//images.each( function() {
		//	img_height = $(this).outerHeight();
		//	if ( img_height < $t ) { $(this).css({ 'padding-top': ($t/2 - img_height/2) }); }
	    //});
	})();
	
	function resetThumbState() { $("#images-thumbs li").removeClass("active"); }
	
	// show/hide prev/next
	function manageControls() {
		var nextButton = $(".next"),
			prevButton = $(".previous");
			
		(index == numberOfSlides) ? nextButton.hide() : nextButton.show();
		(index == 1) ? prevButton.hide() : prevButton.show();
	}

	function manageViews() { $("#images-thumbs li").eq(index-1).addClass("active"); }
	
	manageControls();
	manageViews();

	(function createMapThumbs(){
		
		slides.each( function(index) {
			
			if( $(".geodata", this).length > 0 ) {
			
				// Add Mapable Indicator to Map Thumbs
				$("#images-thumbs li").eq(index).each( function(){
				
					var mapable = $("<a/>").addClass("mapable")
										   .attr("href", "javascript://")
										   .click( function(){
										 		gallery.addClass("map-enabled");
												$("a.map-it").remove();
												mapButtonClose();
											});
					$(this).attr("rel", "map-enabled").prepend(mapable);
				});
			}
		})
	})();
	
	$(".mapable").click( function() {
		if( !gallery.hasClass("mapped")) {
			createMaps();
			gallery.addClass("mapped");
		} else {
			return;
		}
	});	
	
	$("#overlay-nav a").hover( function(){
		el = $(this).attr('class');
		$(".nav ." + el).addClass("hover");
	}, function() {
		$(".nav ." + el).removeClass("hover");
	});	
				
	function createMaps(){
						
		var map_height = slides.outerHeight();

		slides.each( function(index) {
		
			if( $(".geodata", this).length > 0 ) {
			
				// Thumb Stuff
				var img_thumb = $("#images-thumbs li:eq(" + index + ") img").attr('src');
				var img_title = $(".image-description h3", this).text();	
				var img_caption = $(".image-caption", this).text();	
						
				var latitude = $(".latitude", this).text();
				var longitude = $(".longitude", this).text();
				
				var map = $("<div/>").attr({ id: 'map-' + index })
									 .addClass("map-placeholder")
									 .css({ height: map_height + 'px' });
				
				var map_thumb = $("<img/>").addClass("map-thumb").attr({ src: img_thumb });
	
				// add map elements
				$(this).prepend(map);
					//.prepend(map_thumb);
								
				// Create Map Center
			    var map = new GMap2(document.getElementById('map-'+ index));
			    var location = new GLatLng(latitude, longitude);
    			map.setCenter( location, 15);
    			
    			// Add Default Google Maps Interface
    			map.setUIToDefault();

				// Create Map Point
				marker = new GMarker(location);
				map.addOverlay(marker);			
			        
			    var hcard = $('.vcard, this');
			    var infoWindowContent = 
			    	'<div class="bubble"><img src="'+img_thumb+'" /><h3>'+img_title+'</h3>' + img_caption + hcard.html() + '</div>';
			   	
			   	marker.openInfoWindowHtml(infoWindowContent);
			   	
			   	GEvent.addListener(marker, "click", function() {  
				  // When clicked, open an Info Window  
				  	this.openInfoWindowHtml(infoWindowContent);
				});
			}
		});
	}

	if ( $("#images-thumbs li").eq(index).attr("rel") == "map-enabled" ) {
		mapButton();
	}
	
	function mapButton() {
		$("<a/>").attr("href", "javascript://")
				 .addClass("map-it")
				 .text("Map This Image!")
				 .click( function(){
				 	gallery.addClass("map-enabled");
				 	$("a.map-it").remove();
				 	mapButtonClose();
				 	if( !gallery.hasClass("mapped")) {
						createMaps();
						gallery.addClass("mapped");
						createMaps();
					} else {
						return;
					}
				 }).prependTo(".nav");
	}
	
	function mapButtonClose() {
		$("<a/>").attr("href", "javascript://")
				 .addClass("map-on")
				 .text("Close Map Interface")
				 .click( function(){
				 	gallery.removeClass("map-enabled");
					$("a.map-on").remove();
					mapButton();
				 }).prependTo(".nav");
	}

	function removeMapButton() {
		$(".map-it").remove();
		$(".map-on").remove();
	}

	// THUMB CLICK
	$("#images-thumbs a").click( function(){
				
		index = $(this).parent().prevAll().length + 1;		
					
	    updateImage();	    
		removeMapButton();    
	    resetThumbState();
	    manageControls();
	    manageViews();

		if ( $(this).parent().attr("rel") === "map-enabled" ) {
			(gallery.hasClass("map-enabled")) ? mapButtonClose() : mapButton();		
		} else {
			gallery.removeClass("map-enabled");
		}
	});

	// NEXT / PREVIOUS CLICK
  	$('a.next, a.previous').click (function() {
  	  			
  		var target = $(this).attr('class');	
  						
	   (target == "next") ? index = index*1 + 1 : index = index*1 - 1; 

		updateImage();
		removeMapButton();
		resetThumbState();	 		
		manageControls();
		manageViews();
		gallery.removeClass("map-enabled");

		if ( $("#images-thumbs li").eq(index).attr("rel") === "map-enabled" ) {
			mapButton();
		} 
	});
	
	// History Register CLICK
	$("a[rel=history]").click(function(){
		var hash = index;
		// moves to a new page. 
		// pageload is called at once. 
		$.history.load(hash);
		return false;
	});
	
	// add Reflections
	//addReflections();

	
	/* OTHER GALLERIES
	$("#other-galleries.sidebar-block a").hover(function() {
		$(this).parent().stop().fadeTo(0,1);
		$(this).parent().siblings().stop().fadeTo(300,0.6);
	}, function() {
		$(this).parent().siblings().stop().fadeTo(500,1);
	}); */
}
});