/*
	GalleryView - jQuery Content Gallery Plugin
	Author: 		Jack Anderson
	Modified:       Kanazawa
	Version:		1.1 (April 5, 2009)
	Documentation: 	http://www.spaceforaname.com/jquery/galleryview/
	
	Please use this development script if you intend to make changes to the
	plugin code.  For production sites, please use jquery.galleryview-1.0.1-pack.js.
*/

(function($){
	$.fn.galleryView = function(options) {
		var opts = $.extend($.fn.galleryView.defaults,options);
		
		var id;
		var iterator = 7;
		var strip_height;
		var item_count = 0;
		var paused = false;
		
		//Define jQuery objects for reuse
		// main
		var j_gallery;
		
		// dynamic gallery
		var j_filmstrip;
		
		// white frame
		var j_frames;
		
		// main banner
		var j_panels;
		
		// pointer
		var j_pointer;
		
/************************************************/
/*	Plugin Methods								*/
/************************************************/
		function showItem(i) {
			//Disable next/prev buttons until transition is complete
			$('img.nav-next').unbind('click');
			$('img.nav-prev').unbind('click');
			j_frames.unbind('click');
			
			if(opts.fade_panels) {
				//Fade out all panels and fade in target panel
				j_panels.fadeOut(opts.transition_speed).eq(i%item_count).fadeIn(opts.transition_speed,function(){
				});
			}
			
			//Stop filmstrip if it's currently in motion
			j_filmstrip.stop();
			
			//Determine distance between pointer (eventual destination) and target frame
			var distance = getPos(j_frames[i]).top - (getPos(j_pointer[0]).top);
			var topstr = (distance>=0?'-=':'+=')+Math.abs(distance)+'px';
			
			//Animate filmstrip and slide target frame under pointer
			//If target frame is a duplicate, jump back to 'original' frame
			j_filmstrip.animate({
				'top':topstr
			},opts.transition_speed,opts.easing,function(){
				//Always ensure that there are a sufficient number of hidden frames on either
				//side of the filmstrip to avoid empty frames
				//alert('i: ' + i + ' item_count: ' + item_count);
				if(i>item_count) {
					i = i%item_count;
					iterator = i;
					j_filmstrip.css('top','-'+((opts.frame_height+opts.frame_margin)*i)+'px');
				} else if (i<=(item_count-strip_size)) {
					i = (i%item_count)+item_count;
					iterator = i;
					j_filmstrip.css('top','-'+((opts.frame_height+opts.frame_margin)*i)+'px');
				}
				
				if(!opts.fade_panels) {
					j_panels.hide().eq(i%item_count).show();
				}
				$('img.nav-prev').click(showPrevItem);
				$('img.nav-next').click(showNextItem);
				enableFrameClicking();
			});
			
			if($('a',j_frames[i])[0]) {
				j_pointer.unbind('click').click(function(){
					var a = $('a',j_frames[i]).eq(0);
					if(a.attr('target')=='_blank') {window.open(a.attr('href'));}
					else {location.href = a.attr('href');}
				});
			}
		};
		
		function showNextItem() {
			$(document).stopTime("transition");
			if(++iterator==j_frames.length) {iterator=0;}
			showItem(iterator);
			$(document).everyTime(opts.transition_interval,"transition",function(){
				showNextItem();
			});
		};
		
		function showPrevItem() {
			$(document).stopTime("transition");
			if(--iterator<0) {iterator = item_count-1;}
			showItem(iterator);
			$(document).everyTime(opts.transition_interval,"transition",function(){
				showNextItem();
			});
		};
		
		function getPos(el) {
			//alert('start tagname: ' + el.tagName + ' id: ' + el.id + ' class: ' + el.className);
			var left = 0, top = 0;
			var el_id = el.id;
			
			if(el.offsetParent) {
				do {
					//alert('tag: ' + el.tagName + ' id: ' + el.id + ' class: ' + el.className);
					left += el.offsetLeft;
					top += el.offsetTop;
				} while (el = el.offsetParent);
			}
			//If we want the position of the gallery itself, return it
			if (el_id == id) {
				return {'left':left,'top':top};
				
			//Otherwise, get position of element relative to gallery
			} else {
				var gPos = getPos(j_gallery[0]);
				var gLeft = gPos.left;
				var gTop = gPos.top;
				
				return {'left':left-gLeft,'top':top-gTop};
			}
		};
		
		function enableFrameClicking() {
			j_frames.each(function(i){
				//If there isn't a link in this frame, set up frame to slide on click
				//Frames with links will handle themselves
				if($('a',this).length==0) {
					$(this).click(function(){
						$(document).stopTime("transition");
						showItem(i);
						iterator = i;
						$(document).everyTime(opts.transition_interval,"transition",function(){
							showNextItem();
						});
					});
				}
			});
		};
		
		function buildPanels() {
			//If there are panel captions, add overlay divs
			if($('.panel-overlay').length>0) {j_panels.append('<div class="overlay"></div>');}
			
			j_panels.css({
				'width':(opts.panel_width-parseInt(j_panels.css('paddingLeft').split('px')[0],10)-parseInt(j_panels.css('paddingRight').split('px')[0],10))+'px',
				'height':(opts.panel_height-parseInt(j_panels.css('paddingTop').split('px')[0],10)-parseInt(j_panels.css('paddingBottom').split('px')[0],10))+'px',
				'position':'absolute',
				'top':'0px',
				'left':'0px',
				'overflow':'hidden',
				'background':'white',
				'display':'none'
			});
		};
		
		function buildFilmstrip() {
			//Add wrapper to filmstrip to hide extra frames
			j_filmstrip.wrap('<div class="strip_wrapper"></div>');
			j_frames.clone().appendTo(j_filmstrip);
			j_frames.clone().appendTo(j_filmstrip);
			j_frames = $('li',j_filmstrip);
			
			j_filmstrip.css({
				'margin':'0',
				'padding':'0',
				'width':opts.filmstrip_width+'px',
				'position':'absolute',
				'zIndex':'900',
				'top':'0',
				'left':'0'
				//'background':opts.background_color
			});
			
			j_frames.css({
				'position':'relative',
				'height':opts.frame_height+'px',
				'zIndex':'901',
				'marginTop':opts.frame_margin+'px',
				'marginBottom':'0px',
				'padding':'0',
				'background':'#FFFFFF',
				//'border':'1px solid #7CCBFF',
				'cursor':'pointer'
			});
			$('img',j_frames).css({
				'border':'none'
			});
			
			$('.strip_wrapper',j_gallery).css({
				'position':'absolute',
				'top': opts.navi_height + 'px',
				'right':'0px',
				'width':opts.filmstrip_width+'px',
				'height':opts.filmstrip_height - opts.navi_height*2 +'px',
				'overflow':'hidden'
			});
			var pointer = $('<div></div>');
			pointer.attr('id','pointer').appendTo(j_gallery).css({
				 'position':'absolute',
				 'zIndex':'1000',
				 'cursor':'pointer',
				 'top':getPos(j_frames[0]).top-(opts.frame_border_width/2)+'px',
				 'left':getPos(j_frames[0]).left-(opts.frame_border_width/2)+'px',
				 'height':opts.frame_height-opts.frame_border_width+'px',
				 'width':opts.frame_width-opts.frame_border_width+'px'
				 //'border':opts.frame_border_width+'px solid #068BEE'
			});
			j_pointer = $('#pointer',j_gallery);
			/*
			var pointerArrow = $('<img />');
			pointerArrow.attr('src',opts.img_path+'/ico_pointer.gif').appendTo($('#pointer')).css({
				'position':'absolute',
				'zIndex':'1001',
				'top':(opts.frame_height/2-opts.pointer_height/2)+'px',
				'left':'-' + opts.pointer_height + 'px'
			});
			*/
			
			//If there's a link under the pointer, enable clicking on the pointer
			if($('a',j_frames[iterator])[0]) {
				j_pointer.click(function(){
				var a = $('a',j_frames[iterator]).eq(0);
				if(a.attr('target')=='_blank') {window.open(a.attr('href'));}
				else {location.href = a.attr('href');}
				});
			}
			
			//Add navigation buttons
			$('<img />').addClass('nav-prev').attr('src',opts.img_path+'/ico_prev.gif').appendTo(j_gallery).css({
			'position':'absolute',
			'cursor':'pointer',
			'top':opts.navi_margin + 'px',
			'right':opts.filmstrip_width/2 + opts.navi_width/2 + 'px'
			}).click(showPrevItem);
			$('<img />').addClass('nav-next').attr('src',opts.img_path+'/ico_next.gif').appendTo(j_gallery).css({
			'position':'absolute',
			'cursor':'pointer',
			'bottom':opts.navi_margin + 'px',
			'right':opts.filmstrip_width/2 + opts.navi_width/2 + 'px'
			}).click(showNextItem);
		};
		
		//Check mouse to see if it is within the borders of the panel
		//More reliable than 'mouseover' event when elements overlay the panel
		function mouseIsOverPanels(x,y) {		
			var pos = getPos(j_gallery[0]);
			var top = pos.top;
			var left = pos.left;
			return x > left && x < left+opts.panel_width && y > top && y < top+opts.panel_height;				
		};
		
/************************************************/
/*	Main Plugin Code							*/
/************************************************/
		return this.each(function() {
			j_gallery = $(this);
			
			//Hide gallery to prevent Flash of Unstyled Content (FoUC) in IE
			j_gallery.css('visibility','hidden');
			
			//Assign elements to variables for reuse
			j_filmstrip = $('.filmstrip',j_gallery);
			j_frames = $('li',j_filmstrip);
			j_panels = $('.panel',j_gallery);
			
			id = j_gallery.attr('id');
			
			//Number of frames in filmstrip
			item_count = j_panels.length;
			
			//Number of frames that can display within the screen's width
			//64 = width of block for navigation button * 2
			//5 = minimum frame margin
			strip_size = Math.floor((opts.panel_height-opts.navi_height*2)/((opts.frame_height+opts.frame_margin)+opts.frame_margin)); 
			
			
			/************************************************/
			/*	Determine dimensions of various elements	*/
			/************************************************/
			//Height of filmstrip
			//strip_height = (opts.frame_height*item_count*3)+(opts.frame_margin*(item_count*3));
			/************************************************/
			/*	Apply CSS Styles							*/
			/************************************************/
			j_gallery.css({
				'position':'relative',
				'margin':'0',
				//'background':'#FFFFFF',
				//'border':'2px solid #38A9FA',
				'width':opts.gallery_width+'px',
				'height':opts.gallery_height+'px'
			});
			
			/************************************************/
			/*	Build filmstrip and/or panels				*/
			/************************************************/
			buildFilmstrip();
			buildPanels();
			
			/************************************************/
			/*	Add events to various elements				*/
			/************************************************/
			enableFrameClicking();
			
			$().mousemove(function(e){
				if(mouseIsOverPanels(e.pageX,e.pageY)) {
					if(opts.pause_on_hover) {
						$(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;
						}
					}
				}
			});
			
			/************************************************/
			/*	Initiate Automated Animation				*/
			/************************************************/
			//Show the first panel
			j_panels.eq(0).show();
			
			//If we have more than one item, begin automated transitions
			if(item_count > 1) {
				$(document).everyTime(opts.transition_interval,"transition",function(){
					showNextItem();
				});
			}
			
			//Make gallery visible now that work is complete
			j_gallery.css('visibility','visible');
			
			showNextItem();
		});
	};
	
	$.fn.galleryView.defaults = {
		gallery_width: 940,
		gallery_height: 210,
		panel_width: 735,
		panel_height: 210,
		filmstrip_width: 200,
		filmstrip_height: 210,
		frame_width: 200,
		frame_height: 54,
		frame_margin: 5,
		frame_border_width: 2,
		navi_width: 12,
		navi_height: 15,
		navi_margin: 0,
		pointer_width: 25,
		pointer_height: 23,
		
		transition_speed: 400,
		transition_interval: 8000,
		easing: 'swing',
		fade_panels: true,
		pause_on_hover: true,
		img_path: '/top/img/banner'
		
	};
})(jQuery);
