/**********************************************************************
*	Photogallery by Jason Koi / Develop Things
*	html format:
*		<div>
*			<div class=panel>
*				<img />
*				<div class=panel-overlay><h2>[CAPTION GOES HERE]</h2></div>
*			</div>
*			<-- MORE PANELS -->
*		</div>
*
***********************************************************************/

		
jQuery.fn.gallery = function(options) {
	 options = jQuery.extend({
            interval: 4000, // Speed at which the subitems open up - valid options are: slow, normal, fast
            hoverOpacity: 0.7 // 'true': Automatically activate items with links corresponding to the current page, '2': Activate item #2
        }, options);
	
	
	
    jQuery.fn.preloadImages = function( callback ) {
		var imageCount = $(this).find(".panel img").size();
		var imagesLoaded = 0;
		$(this).find(".panel img").each(function() {
			// The image has already been loaded (cached)
			if ($(this)[0].complete) {
				imageCount--;
			// The image is loading, so attach the listener
			} else {
				$(this).load(function() {
					imagesLoaded++;
					// An image has been loaded
					if (imagesLoaded >= imageCount) { if (callback) callback(); }
				});
			}
		});
		
		// There are no unloaded images
		if (imageCount <= 0)
			if (callback) callback();

    };

    
    jQuery.fn.transition = function(current, next) {
		
		//Set the fade in effect for the next image, the show class has higher z-index
		next.css({opacity: 0.0})
		.addClass('show')
		.animate({opacity: 1.0}, 500);
		var ind = next.index(".panel"); //the panel number will be used to show the same number caption block
		jQuery(this).find(".count span.index").text( ind + 1 );
	
	
		//Hide the current image and caption
		current.animate({opacity: 0.0}, 500)
		.removeClass('show');
	
		//update legend do reflect new transition
		jQuery(this).find('.key.active').removeClass("active");
		jQuery(this).find(".legend .key:eq(" + ind + ")").addClass("active"); //fade in corresponding caption	
	};
	
	jQuery.fn.goTo = function (index) {
		var current = jQuery(this).find('.panel.show');
		var next = jQuery(this).find('.panel:eq(' + index + ')');				

		jQuery(this).transition( current, next );
	}
	
	jQuery.fn.goNext = function() {
		//Get the current image
		var current = jQuery(this).find('.panel.show');
	
		//Get next image, when it reaches the end, rotate it back to the first image
		var next = ((current.next('.panel').length) ? ((current.next().hasClass('show')) ? jQuery(this).find('.panel:first') :current.next('.panel')) : jQuery(this).find('.panel:first'));
		
		jQuery(this).transition(current, next);	
	};
	
	jQuery.fn.goPrev = function() {
		//Get the current image
		var current = jQuery(this).find('.panel.show');
	
		//Get previous image, when it reaches the beginning, rotate it back to the last image
		var prev = ((current.prev('.panel').length) ? ((current.prev().hasClass('show')) ? jQuery(this).find('.panel:last') :current.prev('.panel')) : jQuery(this).find('.panel:last'));	
		
		jQuery(this).transition(current, prev);
	};	
	
	jQuery.fn.prepareDOM = function() {
		//insert overlay classes
		jQuery(this).append('<div class="prev control hover">&lsaquo;</div>');
		jQuery(this).append('<div class="next control hover">&rsaquo;</div>');
		jQuery(this).append('<div class="legend"></div>');
		
		
		var i = 0;
		jQuery(this).find('.panel').each( function() {	
			jQuery(this).addClass("panel-" + i);
			

//REFACTOR
			jQuery(this).parent("#gallery").find(".legend").append('<div class="key"></div>');
			i++;
		});
		
		
	};
	
	jQuery.fn.startSlideshow = function() {
				//fade in slideshow
		jQuery(this).fadeIn("slow");		
		
		//position left/right navigation in the center of the frame (minus the caption overlay)
		var controlPos = (jQuery(this).innerHeight() - jQuery(this).find(".overlay").height()) / 2 - (jQuery(this).find(".prev.control").height() / 2);
		jQuery(this).find(".control").css("top", controlPos + "px");
			
		//Call the rotator function to kick off the slideshow
		jQuery(this).everyTime( options.interval, function() { jQuery(this).goNext(); } );				
	};
		
	
	/***** MAIN PLUGIN CODE ********/
	

	jQuery(this).prepareDOM();
	
	//Set the opacity of all images to 0
	jQuery(this).find('.panel').css({opacity: 0.0});
	
	//Get the first image and display it (gets set to full opacity)
	jQuery(this).find('.panel:first').css({opacity: 1.0}).addClass('show');
	//get the first caption and display it
	jQuery(this).find('.legend .key:first').addClass('active');
	
	//fade in controls / image count on hover
	jQuery(this).hover( function() {
		 //on mouse enter
		 jQuery(this).find('.hover').css({opacity: 0.0}).show().animate({opacity: options.hoverOpacity }, 200);
		 jQuery(this).stopTime(); //stop timer
		}, function() {
		//on mouse leave
		 jQuery(this).find('.hover').fadeOut('fast');
		 jQuery(this).everyTime( options.interval, function() { jQuery(this).goNext(); } );	//reset timer
	} );
	
	
	//add click event for prev/next controls
	main = jQuery(this);
	jQuery(this).find(".control").click( function() {
		if (jQuery(this).hasClass('next')) {
			main.goNext();
		} else if (jQuery(this).hasClass('prev')) {
			main.goPrev();
		}
	});
	
	jQuery(this).find(".legend .key").click( function() {
		if ( ! jQuery(this).hasClass("active") ) main.goTo(jQuery(this).index());
	});
	
	//move IE controls all the way to the sides (it just looks better)		
	if (jQuery.browser.msie) {
		jQuery(".prev.control").css("left", "0");
		jQuery(".next.control").css("right", "0");
	}
	
	//preload images, then kick off slideshow
	jQuery(this).preloadImages( function() { main.startSlideshow(); } );
	
	
};


jQuery(document).ready(function () {
	if ( !jQuery("#gallery").length == 0	) jQuery('#gallery').gallery({interval: 5000, hoverOpacity: 1.0});			
});
