// -----------------------------------------
// !BGGallery
// -----------------------------------------
(function($) {

	$.fn.GYROBGGallery = function(config) {

		var defaults = {
			autoplay: true,
			autoplayInterval: 5000,
			transitionLength: 500,
			imageSources: [],
			imageCaptions: [],
			startImageIndex: 0,
			mouseAreaId: "#bg-gallery-mouse-area",
			navigationContainerId: "#bg-gallery-navigation",
			imageContainerId: "#bg-gallery-image",
			captionContainerId: "#bg-gallery-caption",
			imageDimentionRatio: 4/3
		};
	
		var autoplayIntervalId;	
		var currentImageIndex;
		var gallery = {};
		var image = {};
		var mouseArea = {};
		var navigation = {};
		var caption = {};

		// override config with any matching settings		
		if (config) {
			$.extend(defaults, config);
		}
		
		function setup(config) {
		
			// override defaults with any matching config passed in		
			if (config) {
				$.extend(defaults, config);
			}

			navigation.update(config);
			updateCaption();
		}

		// -----------------------------------------------------------------------
		// navigate using mouse
		// - called as handler of mouse click on target
		// -----------------------------------------------------------------------
		function handleMouseClick(event) {
			
			event.stopPropagation();

			var mouseCoordinate = {
				"x": event.pageX,
				"y": event.pageY
			};
				
			// if autoplay is off and there is a mouse area
			// - mouse based navigation is forbidden during autoplay
			if (!defaults.autoplay && mouseArea.length > 0) {
	
				// If mouse is located on the left half of the area
				if (event.pageX > (mouseArea.width()/2)) {
					showNextImage(mouseCoordinate);
				} else {	
					showPrevImage(mouseCoordinate);
				}
				handleMouseOver(event);				
			}
			
		}
	
		// -----------------------------------------------------------------------
		// update the mouse
		// - called as handler to mouse move/over on target
		// -----------------------------------------------------------------------
		function handleMouseOver(event) {
		
			event.stopPropagation();
	
			var mouseCoordinate = {
				"x": event.pageX,
				"y": event.pageY
			};
	
			var tooltipType;
			var cursorType;
	
			// If mouse is located on the left half of the area
			if (event.pageX < (mouseArea.width()/2)) {
			
				// if the current image is not the first item
				if (currentImageIndex > 1) {
					tooltipType = "prev";
					cursorType = "pointer";
				} else {					
					tooltipType = "start";
					cursorType = "default";
				}
						
			} else {
			
				// if the current image is not the last item
				if (currentImageIndex < (defaults.imageSources.length - 1)) {
					tooltipType = "next";
					cursorType = "pointer";
				} else {
					tooltipType = "end";
					cursorType = "default";
				}
	
			}
	
			gallery.trigger("mouseUpdate", {"mouseCoordinate": mouseCoordinate, "tooltipType": tooltipType});

			$(event.target).css("cursor", cursorType);
	
		}
		
		// -----------------------------------------------------------------------
		// show given image - private
		// -----------------------------------------------------------------------
		function showImage(newImageIndex) {
		
			// if the new image index is within the bounds of the available images
			if (newImageIndex >= 0 && newImageIndex < defaults.imageSources.length) {
	
				currentImageIndex = newImageIndex;
				
				image.showImage(defaults.imageSources[currentImageIndex]);
				
			}		
		}
		
		// -----------------------------------------------------------------------
		// update caption - private
		// -----------------------------------------------------------------------
		function updateCaption() {
			if (caption.length > 0) {
				if (defaults.imageCaptions.length > 0 && defaults.imageCaptions[currentImageIndex] !== "") {
					caption.empty();
					caption.append("<p></p>");
					$(defaults.captionContainerId + ">p").text(defaults.imageCaptions[currentImageIndex]);
					caption.fadeIn();
				} else {
					caption.stop();
					caption.fadeOut();
				}
			}
		}
		
		// -----------------------------------------------------------------------
		// show next image - private
		// - start at the first if was at end and autoplay is true
		// -----------------------------------------------------------------------
		function showNextImage(mouseCoordinate) {
	
			var nextImageIndex = currentImageIndex + 1;
			
			// if there is a next image
			if (nextImageIndex < defaults.imageSources.length) {
	
				if (!defaults.autoplay && nextImageIndex === defaults.imageSources.length - 1) {
				
					var mouseCursor = gallery.trigger("mouseUpdate", { "mouseCoordinate": mouseCoordinate, "tooltipType": "end" });
					mouseArea.css("cursor", mouseCursor);
				}
				
				showImage(nextImageIndex);
	
			// not but if autoplay			
			} else if (defaults.autoplay) {
			
				// restart at the start
				showImage(0);
	
			}
				
		}
		
		// -----------------------------------------------------------------------
		// show previous image - private
		// - start at the last if was at first and autoplay is true (should not be)
		// -----------------------------------------------------------------------
		function showPrevImage(mouseCoordinate) {

			var prevImageIndex = currentImageIndex - 1;
	
			// if there is a previous image
			if (prevImageIndex >= 0) {
	
				if (!defaults.autoplay && prevImageIndex === 0) {
					var mouseCursor = gallery.trigger("mouseUpdate", { "mouseCoordinate": mouseCoordinate, "tooltipType": "start" });
					mouseArea.css("cursor", mouseCursor);
				}
				
				showImage(prevImageIndex);
	
			// not but if autoplay			
			} else if (defaults.autoplay) {
			
				$.log("WARNING: looping backwards.");
				
				// restart at the end
				showImage(defaults.imageSources.length - 1);
	
			}
		}

		// -----------------------------------------------------------------------
		// pause the autoplay and enable mouse events
		// - do not loop when reached the ends
		// -----------------------------------------------------------------------
		function pauseAutoplay() {
		
			clearInterval(autoplayIntervalId);
			
			// if mouse area is setup
			if (mouseArea && mouseArea.length > 0) {
			
				mouseArea.mouseover(function() { gallery.trigger("mouseEnable"); });
				mouseArea.mouseleave(function() { gallery.trigger("mouseDisable"); })
				mouseArea.mousemove(handleMouseOver);	
				mouseArea.click(handleMouseClick);
			}
		}
		
		// -----------------------------------------------------------------------
		// autoplay through the images starting with the next image in the list 
		// - forward only
		// - loop when reached end
		// -----------------------------------------------------------------------
		function startAutoplay() {
		
			// if mouse area is setup
			if (mouseArea && mouseArea.length > 0) {
	
				gallery.trigger("mouseDiable");
								
				// unbind mouse events/navigation
				mouseArea.unbind("mouseover");
				mouseArea.unbind("mousemove");
				mouseArea.unbind("click");
			}
	
			// if there is more than one image
			if (config.imageSources.length > 0) {
				autoplayIntervalId = setInterval(showNextImage, defaults.autoplayInterval);		
			}
		}

		// -----------------------------------------------------------------------
		// handle image load complete event
		// -----------------------------------------------------------------------
		function handleImageLoadComplete() {
			updateCaption();
			gallery.trigger("loadComplete");
		}

		// -----------------------------------------------------------------------
		// handle new item selected by navigation
		// -----------------------------------------------------------------------
		function navigateTo(event, data) {
			showImage(data.newSelectedIndex);
		}

		// -----------------------------------------------------------------------
		// update the gallery with new image, taking into account autoplay setting
		// -----------------------------------------------------------------------
		this.update = function(config) {
			setup(config);
		};
	
		// -----------------------------------------------------------------------
		// gallery obj with public methods
		// -----------------------------------------------------------------------
		return this.each(function() {

			gallery = $(this);

			// setup mouse area			
			mouseArea = $(defaults.mouseAreaId);

			image = $(defaults.imageContainerId).GYROBGGalleryImage(defaults);
			image.bind("loadStart", function() { gallery.trigger("loadStart"); });			
			image.bind("loadComplete", handleImageLoadComplete);			

			caption = $(defaults.captionContainerId);

			if (navigation.length > 0) {
				navigation.update(config);							
			} else {
				navigation = $(defaults.navigationContainerId).GYROBGGalleryNavigation(config);
				navigation.bind("newItemSelect", navigateTo)
			}
			
			if (defaults.autoplay) {
				startAutoplay();
				navigation.hide();
			} else {				
				pauseAutoplay();
				navigation.show();
			}		


			showImage(defaults.startImageIndex);
			
			$.log("Finished initializing GYROBGGallery");

		});

	};
		
})(jQuery);


