/*
 * jQuery navigator component 
 * @name jquery.nextgallery.js
 * @author Alberto Arena
 * @version 0.2
 * @date September 9, 2010
 * @category jQuery plugin
 */
;(function($) {
	document.write('<meta http-equiv="X-UA-Compatible" content="IE=7" />');

	var $nextGallery = $.nextGallery = function( options ){
		$(window).nextGallery( options );
	};

	$.fn.nextGallery = function( options ){
		// Private settings
		this.selected = 0;
		this.innerItems = new Array();
		this.timeout = null;
		this.version = "0.2";
		this.startIndex = 0;
		// Default settings
        this.settings = {
        	cssClass: "nextGallery",
        	imagePath: "css/jquery.nextgallery",
        	scrollInterval: 8,
        	transitionSpeed: 1000,
        	thumbSize: [ "40px", "40px" ],
			imageSize: [ "630px", "330px" ],
			linkTarget: "_self",
			showTitle: true,
			showPictureTrigger: "mouseover,mouseout",
			stopOnSelect: false,
			navigationBar: false,
			navigationButtonsFolder: 'images',
			navigationButtons: [ "arrow-left.gif", "arrow-mines.gif", "arrow-plus.gif", "arrow-right.gif", "icon-pause.gif", "icon-play.gif" ]
        };
        // Loads customized setting
        jQuery.extend(this.settings, arguments[0]);
        // Initializes object
        $nextGallery.init( this );
	};

	// Initialize component
	$nextGallery.init = function( $this ) {
		// Applies menu class
        $this.addClass($this.settings.cssClass);

        // Gets ID; if not available, it creates a random one
        $this.mainid = $this.attr('id');
        if ( !$this.mainid ) {
			$this.mainid = 'nextGallery_'+Math.round(Math.random()*500000000);
			$this.attr('id',$this.mainid);
		}
        
        // Builds list of items
        var i = 0;
        var li = $this.find("ul li").each(function(){
        	var a_href = $(this).find('a');
        	a_href = ( a_href.length > 0 ? a_href.attr('href') : '' );
        	var img = $(this).find('img');
        	var p = $(this).find('p').html();
        	var thumb = $(this).find('p + span img').attr('src');
			$this.innerItems[i] = {
				'a': a_href,
				'img': img,
				'p': p,
				'thumb': thumb
			};
			i++;
		});
		
		// Removes UL list
		$this.find("ul").remove();
		
		// If not navigation bar
		if ( !$this.settings.navigationBar ) {
			// Navigation buttons
			if ( $this.innerItems.length > 1 ) {
				$this.append("<div class='pause'><img src='"+$this.settings.imagePath+"/pause.png'></div>");
				$this.append("<div class='play'><img src='"+$this.settings.imagePath+"/play.png'></div>");
				$this.append("<div class='back'><img src='"+$this.settings.imagePath+"/back.png'></div>");
				$this.append("<div class='next'><img src='"+$this.settings.imagePath+"/next.png'></div>");
			}
		}

		// Text holder
		if ( $this.settings.showTitle ) {
			$this.append("<div class='textholder' style='bottom:"+(parseInt($this.settings.thumbSize[1])+6)+"px;' />");
		}
		
        // Builds list of hidden items
        $this.append("<div class='items' style='height:"+$this.settings.imageSize[1]+"' />");
        var $items = $this.find(".items");
        for ( i = 0; i < $this.innerItems.length; i++ ) {
        	var item = $this.innerItems[i];
        	var html = "<div class='item' id='"+$this.mainid+"_img_"+i+"'>";
        	if ( item['a'] != "" )
        		html += "<a href='"+item['a']+"' target='"+$this.settings.linkTarget+"'>";
        	html += "<img src='"+item['img'].attr('src')+"' style='width:"+$this.settings.imageSize[0]+";height:"+$this.settings.imageSize[1]+";'>";
        	if ( item['a'] != "" )
        		html += "</a>";
			html += "</div>";
			$items.append(html);
		}
		
        // Builds thumbs
        $this.append("<div class='thumbs' style='heigth:"+$this.settings.thumbSize[1]+"' />");
        var $thumbs = $this.find(".thumbs");
		if ( $this.settings.navigationBar ) {
	        $thumbs.append("<div class='thumbs-inner' style='heigth:"+($this.settings.thumbSize[1]-2)+"' />");
	        var $thumbsInner = $this.find(".thumbs .thumbs-inner");
		}
        for ( i = 0; i < $this.innerItems.length; i++ ) {
        	var item = $this.innerItems[i];
        	var html = "<div class='thumb' style='width:"+$this.settings.thumbSize[0]+";height:"+$this.settings.thumbSize[1]+";' id='"+$this.mainid+"_thumb_"+i+"'>";
			html += "<img src='";
			if ( item['thumb'] ) // customized thumb
				html += item['thumb'];
			else // default thumb
				html += item['img'].attr('src');
			
			html += "' style='width:"+$this.settings.thumbSize[0]+";height:"+$this.settings.thumbSize[1]+";'";
			if ( !$this.settings.showTitle ) {
				if ( item['p'] )
					html += " title='"+item['p']+"'";
			}	
			html += ">";
			html += "</div>"
			if ( $this.settings.navigationBar )
				$thumbsInner.append(html);
			else
				$thumbs.append(html);
		}
		
		if ( $this.settings.navigationBar ) {
			// Navigation bar
			$thumbs.prepend("<div class='navigation left' id='navPreviousBtn'><img src='"+$this.settings.navigationButtonsFolder+"/"+$this.settings.navigationButtons[1]+"'></div>");
			$thumbs.prepend("<div class='navigation left' id='navFirstBtn'><img src='"+$this.settings.navigationButtonsFolder+"/"+$this.settings.navigationButtons[0]+"'></div>");
			$thumbs.append("<div class='navigation right' id='navPlayBtn' style='display:none;'><img src='"+$this.settings.navigationButtonsFolder+"/"+$this.settings.navigationButtons[5]+"'></div>");
			$thumbs.append("<div class='navigation right' id='navPauseBtn'><img src='"+$this.settings.navigationButtonsFolder+"/"+$this.settings.navigationButtons[4]+"'></div>");
			$thumbs.append("<div class='navigation right' id='navLastBtn'><img src='"+$this.settings.navigationButtonsFolder+"/"+$this.settings.navigationButtons[3]+"'></div>");
			$thumbs.append("<div class='navigation right' id='navNextBtn'><img src='"+$this.settings.navigationButtonsFolder+"/"+$this.settings.navigationButtons[2]+"'></div>");
		}			

		// Shows first block of thumbs
		$thumbs.find('.thumb').slice($this.startIndex,10).fadeIn();
		$nextGallery.updateNavigationButtons( $this );

		// Click event for items
		$nextGallery.initEvents( $this );
        
        // Starts autoscroll
		$this.selected = -1;
        $nextGallery.autoScroll( $this );
	}
	
	$nextGallery.autoScroll = function($this) {
		var oldSelected = $this.selected;
		// Updates index to next one, or starts again by first item
		$this.selected++;
		if ( $this.selected >= $this.innerItems.length )
			$this.selected = 0;
			
		// Shows picture
		$nextGallery.showPicture( $this, oldSelected, $this.selected, true );
	}
	
	$nextGallery.showPicture = function($this,oldSelected,newSelected,timerActive) {
		if ( $this.innerItems.length == 0 )
			return;
		
		if ( oldSelected == -2 )
			oldSelected = $this.selected;
		
		if ( newSelected < 0 || newSelected >= $this.innerItems.length )
		//if ( newSelected < 0 || newSelected >= $this.startIndex+10 )
			newSelected = 0;
			
		// Resync $this.selected
		$this.selected = newSelected;
		
		// Resync visible page
		newStartIndex = Math.floor( newSelected / 10 ) * 10;
		if ( $this.startIndex != newStartIndex ) {
			$this.startIndex = newStartIndex;
			$this.find(".thumbs").find('.thumb').hide().slice($this.startIndex,$this.startIndex+10).fadeIn();
		}

		// Stops all running animation
		$this.find(".item").stop(true);
		
		// Removes selected class
		$this.find(".thumbs img").removeClass('selected');
			
		// Hides all other images
		$this.find(".item").hide();
		if ( $this.settings.showTitle ) {
			$this.find(".textholder").hide();
		}
		
		// Shows new one
		var curItem = $this.innerItems[$this.selected];
		if ( oldSelected != -1 ) {
			var oldItem = $this.innerItems[oldSelected];
			$this.find(".item:eq("+$this.selected+")").css("background","url("+oldItem['img'].attr('src')+")");
		}
		$this.find(".item:eq("+$this.selected+") img").hide().fadeIn($this.settings.transitionSpeed);
		$this.find(".item:eq("+$this.selected+")").show();
		if ( curItem['p'] ) {
			if ( curItem['p'] != "" && $this.settings.showTitle ) {
					$this.find(".textholder").html( curItem['p'] ).slideDown();
			}
		}

		// Adds selected class
		$this.find("#"+$this.mainid+"_thumb_"+$this.selected+" img").addClass('selected');
		
		// Restarts timer
		if ( timerActive )
			$nextGallery.startTimer( $this );
	}

	// Stops scrolling timer
	$nextGallery.stopTimer = function( $this ) {
		if ( $this.timeout ) {
			clearTimeout( $this.timeout );
			if ( $this.settings.navigationBar ) {
				$this.find('#navPauseBtn').hide();
				$this.find('#navPlayBtn').show();
			}
			else {
				$this.find('.pause').hide();
				$this.find('.play').show();
			}
		}
	}

	// Starts scrolling timer
	$nextGallery.startTimer = function( $this ) {
		if ( $this.innerItems.length > 1 ) {
			if ( $this.settings.navigationBar ) {
				$this.find('#navPlayBtn').hide();
				$this.find('#navPauseBtn').show();
			}
			else {
				$this.find('.play').hide();
				$this.find('.pause').show();
			}
			if ( $this.timeout )
				clearTimeout( $this.timeout );

			// debug
			//if ( true ) {
				$this.timeout = setTimeout(function(){ $nextGallery.autoScroll($this) }, $this.settings.scrollInterval*1000 );
			//}
		}
	}
	
	$nextGallery.updateNavigationButtons = function( $this ) {
		var $thumbs = $this.find(".thumbs");
		
		if ( $this.find(".thumb").length < 10 ) {
			$this.find('#navFirstBtn').addClass("inactive");
			$this.find('#navPreviousBtn').addClass("inactive");
			$this.find('#navNextBtn').addClass("inactive");
			$this.find('#navLastBtn').addClass("inactive");
		} else {
			if ( $this.startIndex == 0 ) {
				$this.find('#navFirstBtn').addClass("inactive");
				$this.find('#navPreviousBtn').addClass("inactive");
				$this.find('#navNextBtn').removeClass("inactive");
				$this.find('#navLastBtn').removeClass("inactive");
			} else {
				$this.find('#navFirstBtn').removeClass("inactive");
				$this.find('#navPreviousBtn').removeClass("inactive");
			}
				
			if ( $this.startIndex != 0 ) {
				var count = $thumbs.find(".thumb").length;
				var lastStart = ( parseInt( count / 10 ) + ( count % 10 == 0 ? 0 : 1 ) - 1 ) * 10;
				if ( $this.startIndex == lastStart ) {
					$this.find('#navNextBtn').addClass("inactive");
					$this.find('#navLastBtn').addClass("inactive");
				} else {
					$this.find('#navNextBtn').removeClass("inactive");
					$this.find('#navLastBtn').removeClass("inactive");
				}
			}
		}
	}
	
	
	// Initializes events
	$nextGallery.initEvents = function( $this ) {
		// Play/pause
		if ( $this.settings.navigationBar ) {
			var $thumbs = $this.find(".thumbs");
			$this.find('#navPlayBtn').unbind('click').click(function(){
				$this.find('#navPlayBtn').hide();
				$this.find('#navPauseBtn').show();
				$nextGallery.startTimer( $this );
			});
			$this.find('#navPauseBtn').unbind('click').click(function(){
				$this.find('#navPauseBtn').hide();
				$this.find('#navPlayBtn').show();
				$nextGallery.stopTimer( $this );
			});
			$this.find('#navFirstBtn').unbind('click').click(function(){
				if ( $this.startIndex > 0 ) {
					$this.startIndex = 0;
					$thumbs.find('.thumb').hide().slice($this.startIndex,$this.startIndex+10).fadeIn();
					$nextGallery.showPicture( $this, -2, $this.startIndex, true );
					$nextGallery.updateNavigationButtons( $this );
				}
			});
			$this.find('#navPreviousBtn').unbind('click').click(function(){
				if ( $this.startIndex - 10 >= 0 ) { 
					$this.startIndex -= 10;
					$thumbs.find('.thumb').hide().slice($this.startIndex,$this.startIndex+10).fadeIn();
					$nextGallery.showPicture( $this, -2, $this.startIndex, true );
					$nextGallery.updateNavigationButtons( $this );
				}
			});
			$this.find('#navNextBtn').unbind('click').click(function(){
				if ( $this.startIndex + 10 < $thumbs.find(".thumb").length ) { 
					$this.startIndex += 10;
					$thumbs.find('.thumb').hide().slice($this.startIndex,$this.startIndex+10).fadeIn();
					$nextGallery.showPicture( $this, -2, $this.startIndex, true );
					$nextGallery.updateNavigationButtons( $this );
				}
			});
			$this.find('#navLastBtn').unbind('click').click(function(){
				var count = $thumbs.find(".thumb").length;
				var newStart = ( parseInt( count / 10 ) + ( count % 10 == 0 ? 0 : 1 ) - 1 ) * 10;
				if ( $this.startIndex != newStart ) {
					$this.startIndex = newStart;
					$thumbs.find('.thumb').hide().slice($this.startIndex,$this.startIndex+10).fadeIn();
					$nextGallery.showPicture( $this, -2, $this.startIndex, true );
					$nextGallery.updateNavigationButtons( $this );
				}
			});

		} 
		else {
			$this.find('.play').unbind('click').click(function(){
				$this.find('.play').hide();
				$this.find('.pause').show();
				$nextGallery.startTimer( $this );
			});
			$this.find('.pause').unbind('click').click(function(){
				$this.find('.pause').hide();
				$this.find('.play').show();
				$nextGallery.stopTimer( $this );
			});
			// Back/next
			$this.find('.back').unbind('click').click(function(){
				$nextGallery.stopTimer( $this );
				var newSelected = $this.selected-1;
				if ( newSelected - 1 < 0 )
					newSelected = $this.innerItems.length-1;
				$nextGallery.showPicture( $this, $this.selected, newSelected, true );
			});
			$this.find('.next').unbind('click').click(function(){
				$nextGallery.stopTimer( $this );
				$nextGallery.showPicture( $this, $this.selected, $this.selected+1, true );
			});
		}
		
		// Triggers for thumbs
		var showPictureTriggers = $this.settings.showPictureTrigger.split(",");
		// Mouse over on thumb: stops scrolling timer and shows picture
		$this.find('.thumb').unbind(showPictureTriggers[0]).bind(showPictureTriggers[0],function(){
			$nextGallery.stopTimer( $this );
			var id = $(this).attr('id');
			var idx = parseInt(id.substr($this.mainid.length+7));
			$nextGallery.showPicture( $this, -2, idx, false );
		});

		// Mouse out on thumb: restarts scrolling timer
		$this.find('.thumb').unbind(showPictureTriggers[1]).bind(showPictureTriggers[1],function(){
			if ( !$this.settings.stopOnSelect )
				$nextGallery.startTimer( $this )
		});
		
		/*		
		// Mouse over on thumb: stops scrolling timer and shows picture
		$this.find('.thumb').unbind('mouseover').mouseover(function(){
			$nextGallery.stopTimer( $this );
			var id = $(this).attr('id');
			var idx = parseInt(id.substr($this.mainid.length+7));
			$nextGallery.showPicture( $this, -2, idx, false );
		});

		// Mouse out on thumb: restarts scrolling timer
		$this.find('.thumb').unbind('mouseout').mouseout(function(){
			$nextGallery.startTimer( $this )
		});
		*/
	}
})( jQuery );
