/*
**
**	GalleryView - jQuery Content Gallery Plugin
**	Author: 		Jack Anderson
**	Version:		2.1 (March 14, 2010)
**
*/
var window_loaded = false;
(function($){
	$.fn.galleryView = function(options) {
		var opts = $.extend($.fn.galleryView.defaults,options);
		var id;
		var iterator = 0;		// INT - Currently visible panel/frame
		var item_count = 0;		// INT - Total number of panels/frames
		var slide_method;		// STRING - indicator to slide entire filmstrip or just the pointer ('strip','pointer')
		var paused = false;		// BOOLEAN - flag to indicate whether automated transitions are active
		
	// Element dimensions
		var gallery_width;
		var gallery_height;
		var pointer_height;
		var pointer_width;
		var strip_width;
		var strip_height;
		var wrapper_width;
		var f_frame_width;
		var f_frame_height;
		var frame_caption_size = 20;
		var gallery_padding;
		var filmstrip_margin;
		var filmstrip_orientation;
		/* WHAT I ADDED -----------------------------------------------------------------------------------------------------------------------*/
		var filmstrip_arbitrary_margin = 10;
		var margTop = -44;
		var margLeft = -10;
		
	// Arrays used to scale frames and panels
		var img_h = {};
		var img_w = {};
		
	// Flag indicating whether to scale panel images
		var scale_panel_images = false;
		var panel_nav_displayed = false;
		
	// Define jQuery objects for reuse
		var j_gallery;
		var j_filmstrip;
		var j_frames;
		var j_frame_img_wrappers;
		var j_panels;
		var j_pointer;
		
		
/*  Plugin Functions */

	/*
	**	showItem(int)
	**		Transition from current frame to frame i (1-based index)
	*/
		function showItem(i) {
			// Disable next/prev buttons until transition is complete
			$('.nav-next-overlay',j_gallery).unbind('click');$('.nav-prev-overlay',j_gallery).unbind('click');$('.nav-next',j_gallery).unbind('click');$('.nav-prev',j_gallery).unbind('click');j_frames.unbind('click');
			
			if(opts.show_filmstrip) {
				// Fade out all frames
				j_frames.removeClass('current').find('img').stop().animate({
					'opacity':opts.frame_opacity
				},300, 'linear');
				j_frames.eq(i).addClass('current').find('img').stop().animate({
					'opacity':1.0
				},300, 'linear');
				j_frames.find('.img_wrap').stop().animate({
					'height':'80px'
					
					
				},300, 'linear');
				j_frames.eq(i).find('.img_wrap').stop().animate({
					'height':'80px'
					
					
				},300, 'linear');
				j_frames.find('.caption').stop().animate({
					'opacity':opts.frame_opacity
				},300, 'linear');
				j_frames.eq(i).find('.caption').stop().animate({
					'opacity':1.0
				},300, 'linear');
				j_frames.find('.showtitle').stop().animate({
					'opacity':opts.frame_opacity
				},300, 'linear');
				j_frames.eq(i).find('.showtitle').stop().animate({
					'opacity':1.0
				},300, 'linear');
			}
				//-------------------------------------------------------------------------------------------------------------------------------
			//If necessary, fade out all panels while fading in target panel
			if(opts.show_panels && opts.fade_panels) {
				j_panels.fadeOut(opts.transition_speed).eq(i%item_count).fadeIn(opts.transition_speed,function(){
					//If no filmstrip exists, re-bind click events to navigation buttons
					if(!opts.show_filmstrip) {$('.nav-prev-overlay',j_gallery).click(showPrevItem);$('.nav-next-overlay',j_gallery).click(showNextItem);$('.nav-prev',j_gallery).click(showPrevItem);$('.nav-next',j_gallery).click(showNextItem);}});
			}
			
			// If gallery has a filmstrip, handle animation of frames
			if(opts.show_filmstrip) {
				if(slide_method=='strip') {
					// Stop filmstrip if it's currently in motion
					j_filmstrip.stop();
					var distance;
					var diststr;
					if(filmstrip_orientation=='horizontal') {
						// Determine distance between pointer (eventual destination) and target frame
						distance = getPos(j_frames[i]).left + 4 + (f_frame_width/2) - getPos(j_pointer[0]).left - (pointer_width/2);
						/*----------------------------------------------------------------------------------------------------------------------*/
						diststr = (distance>=0?'-=':'+=')+Math.abs(distance)+'px';
						
						j_filmstrip.animate({
							'left':diststr
						},opts.transition_speed,opts.easing,function(){
							var old_i = i;
							// After transition is complete, shift filmstrip so that a sufficient number of frames
							// remain on either side of the visible filmstrip
							if(i>item_count) {
								i = i%item_count;
								iterator = i;
								j_filmstrip.css('left','-'+((f_frame_width+opts.frame_gap)*i)+'px');
							} else if (i<=(item_count-strip_size)) {
								i = (i%item_count)+item_count;
								iterator = i;
								j_filmstrip.css('left','-'+((f_frame_width+opts.frame_gap)*i)+'px');
							}
							// If the target frame has changed due to filmstrip shifting,
							// make sure new target frame has 'current' class and correct size/opacity settings
							if(old_i != i) {
								j_frames.eq(old_i).removeClass('current').find('img').css({
									'opacity':opts.frame_opacity
								});
								j_frames.eq(i).addClass('current').find('img').css({
									'opacity':1.0
								});
				//-------------------------------------------------------------------------------------------------------------------------------
								j_frames.eq(old_i).find('.img_wrap').css({
							        'height':'80px'
									});
								j_frames.eq(i).find('.img_wrap').css({
							        'height':'80px'
									});
								j_frames.eq(old_i).find('.caption').css({
									'opacity':opts.frame_opacity
								});
								j_frames.eq(i).find('.caption').css({
									'opacity':1.0
								});
								j_frames.eq(old_i).find('.showtitle').css({
									'opacity':opts.frame_opacity
								});
								j_frames.eq(i).find('.showtitle').css({
									'opacity':1.0
								});
							}
				//--------------------------------------------------------------------------------------------------------------------------------
							// If panels are not set to fade in/out, simply hide all panels and show the target panel
							if(!opts.fade_panels) {j_panels.hide().eq(i%item_count).show();}$('.nav-prev-overlay',j_gallery).click(showPrevItem);$('.nav-next-overlay',j_gallery).click(showNextItem);$('.nav-prev',j_gallery).click(showPrevItem);$('.nav-next',j_gallery).click(showNextItem);enableFrameClicking();});}
				} else if(slide_method=='pointer'){ j_pointer.stop(); var pos = getPos(j_frames[i]); if(filmstrip_orientation=='horizontal') {	j_pointer.animate({	'left':(pos.left+(f_frame_width/0)-(pointer_width/0)+'px')},opts.transition_speed,opts.easing,function(){if(!opts.fade_panels){j_panels.hide().eq(i%item_count).show();}$('.nav-prev-overlay',j_gallery).click(showPrevItem);$('.nav-next-overlay',j_gallery).click(showNextItem);$('.nav-prev',j_gallery).click(showPrevItem);$('.nav-next',j_gallery).click(showNextItem);enableFrameClicking();});}}}};
	/*  extraWidth(jQuery element) - Return the combined width of the border and padding to the elements left and right. */
		function extraWidth(el) {if(!el) { return 0; }if(el.length==0) { return 0; }el = el.eq(0);var ew = 0;ew += getInt(el.css('paddingLeft'));ew += getInt(el.css('paddingRight'));ew += getInt(el.css('borderLeftWidth'));ew += getInt(el.css('borderRightWidth'));return ew;};
	/*  showNextItem() - Transition from current frame to next frame */
		function showNextItem() {$(document).stopTime("transition");if(++iterator==j_frames.length) {iterator=0;}showItem(iterator);if(!paused) {$(document).everyTime(opts.transition_interval,"transition",function(){showNextItem();});}};
	/*	showPrevItem() - Transition from current frame to previous frame */
		function showPrevItem() {$(document).stopTime("transition");if(--iterator<0) {iterator = item_count-1;}showItem(iterator);if(!paused) {$(document).everyTime(opts.transition_interval,"transition",function(){showNextItem();});}};
	/*  getPos(jQuery element) - Calculate position of an element relative to top/left corner of gallery */
		function getPos(el) {var left = 0, top = 0;var el_id = el.id;if(el.offsetParent) {do {left += el.offsetLeft;top += el.offsetTop;} while(el = el.offsetParent);}if(el_id == id) {return {'left':left,'top':top};}else {var gPos = getPos(j_gallery[0]);var gLeft = gPos.left;var gTop = gPos.top;return {'left':left-gLeft,'top':top-gTop};}};
	/*  enableFrameClicking() - Add an onclick event handler to each frame */
		function enableFrameClicking() {j_frames.each(function(i){if($('a',this).length==0) {$(this).click(function(){if(iterator!=i) {$(document).stopTime("transition");showItem(i);iterator = i;if(!paused) {$(document).everyTime(opts.transition_interval,"transition",function(){showNextItem();});}}});}});};
	/*  buildPanels() - Construct gallery panels from <div class="panel"> elements */
		function buildPanels() {j_panels.each(function(i){if($('.panel-overlay',this).length>0) {$(this).append('<div class="overlay-background"></div>');}});};
	/*  buildFilmstrip() - Construct filmstrip from <ul class="filmstrip"> element */
		function buildFilmstrip() { j_filmstrip.wrap('<div class="strip_wrapper"></div>');
			if(opts.show_captions) {
				j_frame_img_wrappers.prepend('<div class="caption"></div>').each(function(i){
					$(this).find('.caption').html('<p style="text-align:center;">'+$(this).find('img').attr('title')+'</p>');	
				});
				j_frame_img_wrappers.append('<div class="showtitle"></div>').each(function(i){
					$(this).find('.showtitle').html($(this).find('img').attr('alt'));	
				});
			}
			if(slide_method=='strip') {
				j_frames.clone().appendTo(j_filmstrip);
				j_frames.clone().appendTo(j_filmstrip);
				j_frames = $('li',j_filmstrip);
			}
			// Position the filmstrip within the gallery
			j_filmstrip.css({
				'width':strip_width+'px',
				'left':(filmstrip_orientation=='horizontal' && slide_method=='strip'?-((f_frame_width+opts.frame_gap)*iterator):0)+120+'px', 
				//------------------------------------------------------------------------------------------------------------------------------------------------------------
				'height':strip_height+'px'
			});
			// Set frame margins based on user options and position of filmstrip within gallery
			j_frames.css({'marginRight':opts.frame_gap+'px'});
			// Position each filmstrip image within the image wrapper
			$('img',j_frames).each(function(i){$(this).mouseover(function(){$(this).stop().animate({'opacity':1.0},300);}).mouseout(function(){if(!$(this).parent().parent().hasClass('current')) { $(this).stop().animate({'opacity':opts.frame_opacity},300); }});});
		    
			// Create pointer for current frame
			var pointer = $('<div></div>');pointer.addClass('pointer').appendTo(j_gallery)
			var transColor = $.browser.msie && $.browser.version.substr(0,1)=='6' ? 'pink' : 'transparent';if(!opts.show_panels) { pointer.css('borderColor',transColor); }switch(opts.filmstrip_position) {
					case 'bottom': pointer.css({
				 						'left':((gallery_width-wrapper_width)/2)+(slide_method=='strip'?0:((f_frame_width+opts.frame_gap)*iterator))+((f_frame_width/2)-(pointer_width/2))+gallery_padding+2+'px',
				 						//---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
										'borderTopColor':transColor,'borderRightColor':transColor,'borderLeftColor':transColor}); break;}
			j_pointer = $('.pointer',j_gallery);
			
			// Add navigation buttons
			var navNext = $('<img />');
			navNext.addClass('nav-next').attr('src','images/next.png').appendTo(j_gallery).click(showNextItem);
			var navPrev = $('<img />');
		    navPrev.addClass('nav-prev').attr('src','images/prev.png').appendTo(j_gallery).click(showPrevItem);
		};
	/*	mouseIsOverGallery(int,int) */
		function mouseIsOverGallery(x,y) {var pos = getPos(j_gallery[0]);var top = pos.top;var left = pos.left;return x > left && x < left+gallery_width+(filmstrip_orientation=='horizontal'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin)) && y > top && y < top+gallery_height+(filmstrip_orientation=='vertical'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin));};
	
	/*  getInt(string)  */
		function getInt(i) {i = parseInt(i,10);if(isNaN(i)) { i = 0; }return i;	};
	
	/*
	**	buildGallery()
	**		Construct HTML and CSS for the gallery, based on user options
	*/
		function buildGallery() {
			var gallery_images = opts.show_filmstrip?$('img',j_frames):$('img',j_panels);
			// For each image in the gallery, add its original dimensions and scaled dimensions to the appropriate arrays for later reference
			gallery_images.each(function(i){
				img_h[i] = this.height;
				img_w[i] = this.width;
			});
			// Build filmstrip if necessary
			if(opts.show_filmstrip) {
				buildFilmstrip();
				enableFrameClicking();
			}
			// Build panels if necessary
			if(opts.show_panels) {
				buildPanels();
			}
			
			// If user opts to pause on hover, add some mouseover functionality
			if(opts.pause_on_hover || (opts.show_panels && !opts.show_filmstrip)) {$(document).mousemove(function(e){if(mouseIsOverGallery(e.pageX,e.pageY)) {if(opts.pause_on_hover) {if(!paused) {$(document).oneTime(500,"animation_pause",function(){$(document).stopTime("transition");paused=true;});}}} else {if(opts.pause_on_hover) {$(document).stopTime("animation_pause");if(paused) {$(document).everyTime(opts.transition_interval,"transition",function(){showNextItem();});paused = false;}}}});}
			
			// Hide loading box and display gallery
			j_filmstrip.css('visibility','visible');
			j_gallery.css('visibility','visible');
			$('.loader',j_gallery).fadeOut('50',function(){
				// Show the 'first' panel (set by opts.start_frame)
				showItem(iterator);
				// If we have more than one item, begin automated transitions
				if(item_count > 1) {
					$(document).everyTime(opts.transition_interval,"transition",function(){
						showNextItem();
					});
				}	
			});	
		};
		
	/*  MAIN PLUGIN CODE */
	
		return this.each(function() {
			//Hide the unstyled UL until we've created the gallery
			$(this).css('visibility','hidden');
			
			// Wrap UL in DIV and transfer ID to container DIV
			$(this).wrap("<div></div>");
			j_gallery = $(this).parent();
			j_gallery.css('visibility','visible').attr('id',$(this).attr('id')).addClass('gallery');
			
			// Assign filmstrip class to UL
			$(this).removeAttr('id').addClass('filmstrip');
			
			// If the transition or pause timers exist for any reason, stop them now.
			$(document).stopTime("transition");$(document).stopTime("animation_pause");
			
			// Save the id of the UL passed to the plugin
			id = j_gallery.attr('id');
			
			// Define dimensions of pointer <div>
			pointer_height = opts.pointer_size;
			pointer_width = opts.pointer_size*2;
			
			// Determine filmstrip orientation (vertical or horizontal)
			filmstrip_orientation = (opts.filmstrip_position=='top'||opts.filmstrip_position=='bottom'?'horizontal':'vertical');
			
			// Assign elements to variables to minimize calls to jQuery
			j_filmstrip = $('.filmstrip',j_gallery);
			j_frames = $('li',j_filmstrip);
			
			// If the user wants panels, generate them using the filmstrip images
			if(opts.show_panels) {
				for(i=j_frames.length-1;i>=0;i--) {
					if(j_frames.eq(i).find('.panel-content').length>0) {
						j_frames.eq(i).find('.panel-content').remove().prependTo(j_gallery).addClass('panel');
					} else {
						p = $('<div>');
						p.addClass('panel');
						im = $('<img />');
						im.attr('src',j_frames.eq(i).find('img').eq(0).attr('src')).appendTo(p);
						p.prependTo(j_gallery);
						j_frames.eq(i).find('.panel-overlay').remove().appendTo(p);
					}
				}
			}
		
			j_frame_img_wrappers = $('.img_wrap',j_frames);
			j_panels = $('.panel',j_gallery);
			
			// Determine final frame dimensions, accounting for user-added padding and border
			f_frame_width = opts.frame_width+extraWidth(j_frame_img_wrappers);
			f_frame_height = opts.frame_height;
			
			// Number of frames in filmstrip
			item_count = opts.show_panels?j_panels.length:j_frames.length;
			
			// Number of frames that can display within the gallery block
			// 64 = width of block for navigation button * 2 + 20
			if(filmstrip_orientation=='horizontal') {
				strip_size = opts.show_panels?Math.floor((opts.panel_width-((opts.frame_gap+22)*2))/(f_frame_width+opts.frame_gap)):Math.min(item_count,opts.filmstrip_size); 
			}
			
			// Determine animation method for filmstrip
			// If more items than strip size, slide filmstrip
			// Otherwise, slide pointer
			if(strip_size >= item_count) {
				slide_method = 'pointer';
				strip_size = item_count;
			}
			else {slide_method = 'strip';}
			
			iterator = (strip_size<item_count?item_count:0)+opts.start_frame-1;
			
			// Determine dimensions of various gallery elements
			filmstrip_margin = (opts.show_panels?getInt(j_filmstrip.css('marginTop')):0);
			/*-----------------------------------------------------------------------------------------------------------------------------------
			filmstrip_margin = '40';			
			-----------------------------------------------------------------------------------------------------------------------------------*/
			j_filmstrip.css('margin','0px');
			
			if(filmstrip_orientation=='horizontal') {
				// Width of gallery block
				gallery_width = opts.show_panels?opts.panel_width:(strip_size*(f_frame_width+opts.frame_gap))+44+opts.frame_gap;
				
				// Height of gallery block = screen + filmstrip + captions (optional)
				gallery_height = 395
				/*-------------------------------------------------------------------------------------------------------------------------------------------------------
			    gallery_height = (opts.show_panels?opts.panel_height:0)+(opts.show_filmstrip?f_frame_height+filmstrip_margin+(opts.show_captions?frame_caption_size:0):0);
			    -------------------------------------------------------------------------------------------------------------------------------------------------------*/
			}
			
			// Width of filmstrip
			if(filmstrip_orientation=='horizontal') {
				if(slide_method == 'pointer') {strip_width = (f_frame_width*item_count)+(opts.frame_gap*(item_count));}
				else {strip_width = (f_frame_width*item_count*3)+(opts.frame_gap*(item_count*3));}
			}
			if(filmstrip_orientation=='horizontal') {
				strip_height = (f_frame_height+filmstrip_margin+(opts.show_captions?frame_caption_size:0));	
			}
			
			// Width of filmstrip wrapper (to hide overflow)
			wrapper_width = ((strip_size*f_frame_width)+((strip_size-1)*opts.frame_gap));
			wrapper_height = ((strip_size*f_frame_height)+((strip_size-1)*opts.frame_gap));

			
			gallery_padding = getInt(j_gallery.css('paddingTop'));
			j_gallery.css('padding','0px');

			// Place loading box over gallery until page loads
			galleryPos = getPos(j_gallery[0]);
			$('<div>').addClass('loader').appendTo(j_gallery);
					
			// Don't call the buildGallery function until the window is loaded
			// NOTE - lazy way of waiting until all images are loaded, may find a better solution for future versions
			if(!window_loaded) {
				$(window).load(function(){
					window_loaded = true;
					buildGallery();
				});
			} else {
				buildGallery();
			}
					
		});
	};
	
/*  GalleryView options and default values */
	$.fn.galleryView.defaults = {
		show_panels: true,					//BOOLEAN - flag to show or hide panel portion of gallery
		show_filmstrip: true,				//BOOLEAN - flag to show or hide filmstrip portion of gallery
		panel_width: 600,					//INT - width of gallery panel (in pixels)
		panel_height: 400,					//INT - height of gallery panel (in pixels)
		frame_width: 60,					//INT - width of filmstrip frames (in pixels)
		frame_height: 40,					//INT - width of filmstrip frames (in pixels)
		start_frame: 1,						//INT - index of panel/frame to show first when gallery loads
		filmstrip_size: 3,					
		transition_speed: 800,				//INT - duration of panel/frame transition (in milliseconds)
		transition_interval: 4000,			//INT - delay between panel/frame transitions (in milliseconds)
		overlay_opacity: 0.7,				//FLOAT - transparency for panel overlay (1.0 = opaque, 0.0 = transparent)
		frame_opacity: 0.3,					//FLOAT - transparency of non-active frames (1.0 = opaque, 0.0 = transparent)
		pointer_size: 8,					//INT - Height of frame pointer (in pixels)
		easing: 'swing',					//STRING - easing method to use for animations (jQuery provides 'swing' or 'linear', more available with jQuery UI or Easing plugin)
		filmstrip_position: 'bottom',		//STRING - position of filmstrip within gallery (bottom, top, left, right)
		overlay_position: 'bottom',			//STRING - position of panel overlay (bottom, top, left, right)
		panel_scale: 'nocrop',				//STRING - cropping option for panel images (crop = scale image and fit to aspect ratio determined by panel_width and panel_height, nocrop = scale image and preserve original aspect ratio)
		frame_scale: 'crop',				//STRING - cropping option for filmstrip images (same as above)
		frame_gap: 5,						//INT - spacing between frames within filmstrip (in pixels)
		show_captions: false,				//BOOLEAN - flag to show or hide frame captions
		fade_panels: true,					//BOOLEAN - flag to fade panels during transitions or swap instantly
		pause_on_hover: false				//BOOLEAN - flag to pause slideshow when user hovers over the gallery
	};
})(jQuery);
