/*
**
**	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 paused = false;		// BOOLEAN - flag to indicate whether automated transitions are active
		
	// Element dimensions
		var gallery_width;
		var gallery_height;
		var f_frame_width;
		var f_frame_height;

		
	// Arrays used to scale frames and panels
		var frame_img_scale = {};
		var panel_img_scale = {};
		var img_h = {};
		var img_w = {};
		
	// Flag indicating whether to scale panel images
		var scale_panel_images = true;
		
		var panel_nav_displayed = false;
		
	// Define jQuery objects for reuse
		var j_gallery;
		var j_frames;
		var j_panels ;
		var j_frame_caption = {};
		var j_frame_title = {};
	
		
		
/*
**	Plugin Functions
*/

	/*
	**	showItem(int)
	**		Transition from current frame to frame i (1-based index)
	*/
		function showTab(i)
		{
			//stop timer from previous transition
			$(document).stopTime("transition");
			
			//close any open tabs. Sets position of closed tab from top of container. This value should be in css also
			$('.current',j_gallery).animate({'top':'272px'},opts.tab_in_speed,opts.tab_in_easing,function(){
					//$(this).find('.frame_caption').hide();
					//$(this).find('.frame_title').removeClass('popup');
					
					j_frame_title[j_frames.index(this)].removeClass('popup');
					j_frame_caption[j_frames.index(this)].hide();
										
					});
			
			
			j_frames.removeClass('current');
			//Make selected tab more opaque
			j_frames.eq(i).css('opacity',.85);
			
			//refernce to tab text <p>
			//var _text = j_frames.eq(i).find('.frame_caption');
						
			//make tab text visible
			//_text.show();
			j_frame_caption[i].show();
			//j_frames.eq(i).find('.frame_title').addClass('popup');
			j_frame_title[i].addClass('popup');
			
			//add .current class name to selected tab, popup the tab and make text visible. Open tab position
			j_frames.eq(i).addClass('current').animate({'top':'240px'},opts.tab_out_speed,opts.tab_out_easing,function(){

					//$(this).find('.frame_caption').css('opacity','1');
					//j_frame_caption[j_frames.index(this)].css('opacity','1');
					

});
			
			//make all tabs not the current more transparent
			j_frames.not('.current').css('opacity',.5);
									
			//fade out previous shown panel image <div> if page not just loaded
			//if(window_loaded) j_panels.fadeOut(opts.transition_speed);
			j_panels.fadeOut(opts.transition_speed);
			
			//fade in selected panel image <div>
			j_panels.eq(i).fadeIn(opts.transition_speed);
			
			//set global selected tab id
			iterator = i;
			
		}
		
	
		function showNextTab() {
			
			// Cancel any transition timers until we have completed this function
			$(document).stopTime("transition");
			if(++iterator==j_frames.length) {iterator=0;}
			// We've already written the code to transition to an arbitrary panel/frame, so use it
			showTab(iterator);
			// If automated transitions haven't been cancelled by an option or paused on hover, re-enable them
			if(!paused) {
				$(document).everyTime(opts.transition_interval,"transition",function(){
					showNextTab();
				});
			}
		};
	
	/*
	**	buildGallery()
	**		Construct HTML and CSS for the gallery, based on user options
	*/
		function buildGallery() {
			//changed by andy
			var gallery_images = $('img',j_panels);
			//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;
				if(opts.frame_scale=='nocrop') {
					frame_img_scale[i] = Math.min(opts.frame_height/img_h[i],opts.frame_width/img_w[i]);
				} else {
					frame_img_scale[i] = Math.max(opts.frame_height/img_h[i],opts.frame_width/img_w[i]);
				}
				
				if(opts.panel_scale=='nocrop') {
					panel_img_scale[i] = Math.min(opts.panel_height/img_h[i],opts.panel_width/img_w[i]);
				} else {
					panel_img_scale[i] = Math.max(opts.panel_height/img_h[i],opts.panel_width/img_w[i]);
				}
			});
			
			// Size gallery based on position of filmstrip
			j_gallery.css({
				'position':'relative',
				'width':gallery_width+'px',
				'height':gallery_height+'px'
			});
			
			// Hide loading box and display gallery
			// start transition animation
			//j_filmstrip.css('visibility','visible');
			j_gallery.css('visibility','visible');
			$('#loadit').css('backgroundImage', 'none' );

			//$('#loadit').fadeOut('1000');
				// Show the 'first' panel (set by opts.start_frame)
				//console.log(iterator);
				showTab(iterator);
				//showItem(iterator);
				// If we have more than one item, begin automated transitions
				
				if(item_count > 1) {
					$(document).everyTime(opts.transition_interval,"transition",function(){
						showNextTab();
					});
				}
					
			//});	
		};
		
		function linkTab(tab)
		{
			var _alink = tab.find('a');
			var _url = _alink.attr('href');
			var _target = _alink.attr('target');
			
			var _linktxt = 'href="' + _url + '"';
			if(_target) _linktxt = _linktxt + ' target="' + _target + '"';
			tab.wrap('<a ' + _linktxt + '></a>');
		}
		
	/*
	**	MAIN PLUGIN CODE
	*/
		return this.each(function() {
			//
			//Hide the entire gallery div
			$(this).css('visibility','hidden');
						
			//reference to gallery container div
			j_gallery = $(this);
			
			// If the transition or pause timers exist for any reason, stop them now.
			$(document).stopTime("transition");
			$(document).stopTime("animation_pause");
			
			// save the parent <div> id #myGallery
			id = j_gallery.attr('id');
			
			//if no .panel-content images then scale img to fit panel
			scale_panel_images = $('.panel-content',j_gallery).length==0;
					
			j_frames = $('div.page_tab',j_gallery); //reference to <div> .page_tab collection
		
			// If the user wants panels, generate them using .panel-content <img> or the default <img>
			if(opts.show_panels) {
				
				//go through each <li>
				for(i=j_frames.length-1;i>=0;i--) {
					//Insert panel image
					
					linkTab(j_frames.eq(i));
					
					//retrieve the href from the only <a> link in <li>
					_alink = j_frames.eq(i).find('a'); 
					
					_url = _alink.attr('href');
					_target = _alink.attr('target');
					
					//if .panel-content exists then use as panel image
					if(j_frames.eq(i).find('.panel-content').length>0) 
					{
						
						//reference <img> in .panel-content
						_img = j_frames.eq(i).find('.panel-content img').css('border','0');
						
						//wrap <img> with link to content page
						var _linktxt = 'href="' + _url + '"';
						if(_target) _linktxt = _linktxt + ' target="' + _target + '"';
						_img.wrap('<a ' + _linktxt + '></a>');
						
						//move .panel-content div to main #mygallery div and rename class to .panel. append to top of
						//#myGallery. Removes from <li>, prepends to #myGallery and adds class .panel
						j_frames.eq(i).find('.panel-content').remove().prependTo(j_gallery).addClass('panel');
						
						
						//console.log(j_frames.eq(i).find('a').attr('href'));
					} 
					//
					else {
						//There is no .panel-content <div>, so use default img for panel image
						p = $('<div>');
						p.addClass('panel');
						im = $('<img />');
						//There is only one <img> in <li>, so find it
						im.attr('src',j_frames.eq(i).find('img').eq(0).attr('src')).attr("border","0");
						//need to append first for wrap to work
						im.appendTo(p)
						//make panel image clickable to page content
						im.wrap('<a href="' + _url + '"></a>');
						//Add to top of #myGallery <div>
						p.prependTo(j_gallery);
						
						j_frames.eq(i).find('.panel-overlay').remove().appendTo(p);
					}
					
					//make tab linkable to page
					j_frames.eq(i).click(function(){
						if(!$(this).hasClass('current')) 
							showTab(j_frames.index(this));
							//event.stopPropagation();
						else
						{	
							//var _url = $(this).find('a').attr('href');
							//document.location.href=_url;
						}
												  });
					
					j_frame_caption[i] = j_frames.eq(i).find('.frame_caption');
					j_frame_title[i] = j_frames.eq(i).find('.frame_title');
					
				}
				//console.log(j_frame_title.length);
				//add mouseover and mouseout events to tab.
				//when hover stop transition in progress, if selected tab is not yet current
				//then open tab and use pointer cursor. On mouse out begin transition to next
				//tab
				
				j_frames.hover(function(){
						$(document).stopTime("transition");
						//console.log(j_frames.index(this));
						var _tab = $(this);
						if(!_tab.hasClass('current')) showTab(j_frames.index(this));
						_tab.css('cursor','pointer');
						
						},function(){
						$(document).everyTime(opts.transition_interval,"transition",function(){
							showNextTab();
						});
											
				});
				
			} 
					
			//reference to panel image div's
			j_panels = $('.panel',j_gallery);
			
			//number of images
			item_count = j_frames.length;
			
			//global start image frame index
			iterator = (opts.start_frame<1)?0:opts.start_frame-1;

			gallery_width = opts.panel_width;
				
			// Height of gallery block 
			if(opts.gallery_height>0)
				gallery_height = opts.gallery_height;
			else
				gallery_height = opts.panel_height;
	
			//gallery_padding = getInt(j_gallery.css('paddingTop'));
			j_gallery.css('padding','0px');
			
			//hide all image panels
			j_panels.hide();

				
			//build rotator
			buildGallery();
			/*			
			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
		
		panel_width: 600,					//INT - width of gallery panel (in pixels)
		panel_height: 400,					//INT - height of gallery panel (in pixels)
		gallery_height: 0,					//INT - total height of gallery. this is optional. If 0 then will use panel height
		start_frame: 1,						//INT - index of panel/frame to show first when gallery loads
		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)
		
		//nav_theme: 'dark',					//STRING - name of navigation theme to use (folder must exist within 'themes' directory)
		easing: 'swing',					//STRING - easing method to use for animations (jQuery provides 'swing' or 'linear', more available with jQuery UI or Easing plugin)
				
		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)
		
		fade_panels: true,					//BOOLEAN - flag to fade panels during transitions or swap instantly
		
		tab_out_speed: 395,
		tab_in_speed: 370,
		tab_out_easing: 'easeOutBack',
		tab_in_easing: 'easeInBack'
		
	};
})(jQuery);
