/*
**
**	GalleryView - jQuery Content Gallery Plugin
**	Author: 		Jack Anderson
**	Version:		2.1 (March 14, 2010)
**	
**
*/

var $j=jQuery.noConflict();

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
			$('.current',j_gallery).animate({'top':'335px'},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
			j_frames.eq(i).addClass('current').animate({'top':'285px'},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);
			
			//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', 'url()' );

			//$('#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();
					});
				}
					
			//});	
		};
		
	/*
	**	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
			
					//retrieve the href from the only <a> link in <li>
					_url = j_frames.eq(i).find('a').attr('href');
					
					//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
						_img.wrap('<a href="' + _url + '"></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);
	

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 */

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});


/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/10/16
 *
 * @author Blair Mitchelmore
 * @version 1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval < 0)
				return;

			if (typeof times != 'number' || isNaN(times) || times < 0) 
				times = 0;
			
			times = times || 0;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});
