/**
 * jQuery jqGalScroll Plugin
 * Examples and documentation at: http://benjaminsterling.com/jquery-jqgalscroll-photo-gallery/
 *
 * @author: Benjamin Sterling
 * @version: 2.1
 * @copyright (c) 2007 Benjamin Sterling, KenzoMedia
 * @extendThanks Koesmanto Bong http://www.koesbong.com/
 *		Koes put a fire under my butt to improve this plugin
 *		and when I took too long he took what I had and added
 *		the horizontal scroll and in turn I ripped it from his
 *		hands and made it better :)
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *   
 * @requires jQuery v1.2.1 or later
 * @optional jQuery Easing v1.2
 *
 * @name jqGalScroll
 * @example $('ul').jqGalScroll();
 * 
 * @Semantic requirements:
 * 				The structure fairly simple; the structure should consist
 * 				of a ul > li > img structure.
 * 
 * 	<ul>
 *		<li><img src="common/img/dsc_0003.thumbnail.JPG"/></li>
 *		<li><img src="common/img/dsc_0012.thumbnail.JPG"/></li>
 *	</ul>
 *
 * @param String ease
 *					refer to http://gsgd.co.uk/sandbox/jquery.easing.php for values
 * 
 * @example $('#gallery').jqGalScroll({speed:1000});
 
 * @param String speed
 * 					fast, slow, 1000, ext..
 * 
 * @example $('#gallery').jqGalScroll({speed:1000});
 * 
 * @param String height
 * 					the default height of your wrapper
 * 
 * @example $('#gallery').jqGalScroll({height:490});
 * 
 * @param String titleOpacity
 * 					the opacity of your title bar (if present)
 * 
 * @example $('#gallery').jqGalScroll({titleOpacity:.70});
 * 
 * @param String direction 
 *					vertical horizontal diagonal
 * 
 * @example $('#gallery').jqGalScroll({direction:'vertical'});
 * 			
 */
(function($) {
	$.fn.jqGalScroll = function(options){
		return this.each(function(i){
			var el = this
			el.curImage = 0;
			el.jqthis = $(this).css({position:'relative'});
			
			el.jqchildren = el.jqthis.children();
			el.opts = $.extend({}, jqGalScroll, options);
			el.index = i;
	
			el.totalChildren = el.jqchildren.size();
			var width,height;
			//alert('starting');
			//$(el.jqchildren).each(function(){
			//							  alert($(this)[0].nodeName)
			//							   });
			
			// this sets up our image slide based on whether we are slidding vertically, horizontally, etc
			switch(el.opts.direction){
				case 'horizontal':
					width = el.totalChildren *el.opts.width;
					height = el.opts.height;
					break;
				case 'vertical':
					width = el.opts.width;
					height = el.totalChildren *el.opts.height;
					break;
				
				case 'disolve':
				
					break;
					
				default:
					width = el.totalChildren *el.opts.width;
					height = el.totalChildren *el.opts.height;
					break;
			};
			el.container = $('<div id="jqGS'+i+'" class="jqGSContainer" style=" width:'+el.opts.width+'px;">').css({position:'relative'});
			el.ImgContainer = 
				$('<div class="jqGSImgContainer" style=" position:relative;overflow:hidden">')
				.css({height:el.opts.height + "px",width:el.opts.width + "px",position:'relative',overflow:'hidden'});
				
			el.jqthis.css({height:height,width:width});




			//this throws our image slide into the container
			el.jqthis.wrap(el.container);
			el.jqthis.wrap(el.ImgContainer);

			//this starts on the pagination controls
			if(typeof options.width != 'undefined' && !isNaN(options.width))
				el.pagination = $('<div class="jqGSPagination" style="width: ' + options.width + 'px;" >');
			else
				el.pagination = $('<div class="jqGSPagination" >');
				
			if (!el.opts.hidenav)
				$(el.pagination).css('display', 'none');
				
			el.jqthis.parent().parent().append(el.pagination);
			var jqul = $('<ul>').appendTo(el.pagination);
			var pos = {x:0,y:0};

			//this loops through each of the li's attaching the click event handler to all of the images
			// this provides the animation affect, etc.
			el.jqchildren
			.each(function(j){
				var selected = '';
				if(j == 0) selected = 'selected';
				
				// this creates the button for this image to have a control in the pagination container
				var $a = $('<a href="#'+(j)+'" class="'+selected+'">'+(j+1)+'</a>').click(function(){
					var href = this.index;//href.replace(/^.*#/, '');
					el.pagination.find('.selected').removeClass('selected');
					$(this).addClass('selected');
					var params = {};
					if( el.opts.direction == 'diagonal'){
						params = {right:(el.opts.width*href),bottom:(el.opts.height*href)}
					}
					else if( el.opts.direction == 'vertical'){
						params = {bottom:(el.opts.height*href)}
					}
					else if( el.opts.direction == 'disolve'){
						params = {right:(el.opts.width*href)}
					}					
					else if( el.opts.direction == 'horizontal'){
						params = {right:(el.opts.width*href)}
					};
				
					window.currentjqgalslide = href;
					
					if( el.opts.direction == 'disolve'){
						if(!window._jqgalz)
							window._jqgalz =5;
						 
						 window._jqgalz += 1;
						 
						 //$(document.body).append("<span style='color: white;'>" + href + "</span><br>");
						 // logging/debugging info I dont use any more
						 
						$(el.jqthis.children()[href])
							.css('opacity', '0')							
							.css('z-index', ++window._jqgalz);

						$(el.jqthis.children()[href])
							.animate({opacity: 1},el.opts.speed, el.opts.ease);
					}else{
						el.jqthis.stop().animate(params,el.opts.speed, el.opts.ease);
					}
					index = href;
	
					if(window.jqgalslideinterval){
						try{
							clearTimeout(window.thejqgalinterval);
						}catch(e){}
						window.thejqgalinterval = setTimeout(doNextSlide, window.jqgalslideinterval);
					}
						
					return false;
				});
			
				//n is now the good old fashioned javascript object  it would have been easier to do "var n = $a[0];"
				var n = $a.get(0);
				n.index = j;


				//finally we add the button and its attributes to the pagination form control container
				$('<li>').appendTo(jqul).append($a);

				//
				if( el.opts.direction == 'diagonal'){
					pos.x = j * el.opts.width;
					pos.y = j * el.opts.height;
				}
				else if( el.opts.direction == 'horizontal'){
					pos.x = j * el.opts.width;
				}
				else if( el.opts.direction == 'disolve'){
					pos.x = 0;
					pos.y = 0;
				}
				else if( el.opts.direction == 'vertical'){
					pos.y = j * el.opts.height;
				};

				//this sets the image's position in the slide container
				var jqchild = $(this).css({height:el.opts.height,width:el.opts.width,position:'absolute',left:pos.x, top:pos.y});

				//this hides the image, the animation call that transitioons frames un hides it.
				var jqimg = jqchild.find('img').hide()
				
				//if the images is in a link we set that href for the image and add the configured image to the list
				if(jqimg.parent().is('a')){
					var p = jqimg.parent();
					jqimg.get(0).linkHref = p.attr('href');
					jqimg.css('cursor', 'pointer');
					p.remove();
					jqimg.appendTo(jqchild);
				};

				// this binds the click action to the image itself
				jqimg.click(function(){
					if (typeof jqimg.get(0).linkHref != 'undefined'){
						window.location.href = jqimg.get(0).linkHref;	
					}
					else
					{				
						// this would trigger images without an enclosing A tag to cycle to the next image int he gallery.
						// I think this is counter intuitive, since some clicks open new windows
						/*
						var next = n.index + 1;
						if((n.index + 1) == el.totalChildren ){
							el.pagination.find('[href$=#0]').click();
						}
						else{
							el.pagination.find('[href$=#'+next+']').click();
						}
						*/
					}
				});
				$(el.jqchildren[0]).css('z-index', '3');

				//this makes it so the image are only shown if they are fully loaded
				var $loader = $('<div class="jqGSLoader">').appendTo(jqchild);
				if (typeof jqimg.get(0).linkHref != 'undefined' && jqimg.get(0).linkHref.length > 0){
					var $titleHolder = $('<div class="jqGSTitle" onclick="window.location.href = \'' + jqimg.get(0).linkHref + '\';">').appendTo(jqchild).addClass(jqimg.attr('id')).hide();
					var $descHolder = $('<div class="jqGSDescription"  onclick="window.location.href = \'' + jqimg.get(0).linkHref + '\';" >').appendTo(jqchild).addClass(jqimg.attr('id')).hide();					
				}else{
					var $titleHolder = $('<div class="jqGSTitle" >').appendTo(jqchild).addClass(jqimg.attr('id')).hide();
					var $descHolder = $('<div class="jqGSDescription">').appendTo(jqchild).addClass(jqimg.attr('id')).hide();
				}
				
				var image = new Image();
				image.onload = function(){
					if (typeof jqimg.get(0).linkHref != 'undefined' && jqimg.get(0).linkHref.length > 0)
					{
						$titleHolder.css('cursor', 'pointer');
						$descHolder.css('cursor', 'pointer');
					}
						
					image.onload = null;
					$loader.fadeOut();
					jqimg.css({marginLeft:-image.width*.5,marginTop:-image.height*.5,position:'absolute',left:'50%',top:'50%'}).fadeIn();
					var alt = jqimg.attr('alt');
					var desc = jqimg.attr('description');
					if (typeof desc != 'undefined' && desc.length)
						$descHolder.html(desc).fadeIn();
						
					if(typeof alt != 'undefined'){
						$titleHolder.text(alt).fadeIn();
					}
				};
				image.src = jqimg.attr('src');
				

					
			});
							
				jqul.prepend('<li><a href="javascript: doNextSlide(-1); void(0);">&lt;&lt;</a></li>');
				jqul.append('<li><a href="javascript: doNextSlide(1); void(0);">&gt;&gt;</a></li>');	
			
		}); // end : this.each(function()
				function nextslide(){
						var next = n.index + 1;
						
						if((n.index + 1) == el.totalChildren ){
							
							el.pagination.find('[href$=#0]').click();
							
						}else{
							
							el.pagination.find('[href$=#'+next+']').click();
							
						}
						
				}
				
	};  // end : $.fn.jqGalScroll
	
	
	// this is  fancy way of calling the constructor with defaults.
	jqGalScroll = {
		ease: null,
		speed:3,
		height: 500,
		width: 500,
		titleOpacity : .60,
		direction : 'horizontal' // vertical horizontal diagonal
	};
})(jQuery);
