/**
 * Background Slider
 */
(function($) {
	$.fn.backslider = function(options) {

		var settings = {
				'indicator': true,
				'delay': 4000
		};
		
		return this.each(function() {
			
			if ( options ) { 
				$.extend( settings, options );
			}
			
			var $this = $(this);
			var SLIDE_TIME = settings.delay;
			var ANIM_TIME = 1500;	
			
			var $container = $this.find("#slideshow-content");
			var $imgs = $this.find(".images");
			var $first = $this.find(".images:first");
			var $navigation = $('<div id="imgage-nav"></div>').appendTo($container);
			var $curIndex = $first.index();
			
			var $footer = $this.find("#slideshow-footer .sf-right1");
			
			/* add caption tme*/
			$footer.empty();
			$first.find('h3').clone().removeClass("hide-h3").appendTo($footer);
			
			//var $lightbox = $('<div id="lightbox-btn"></div>').appendTo($container);
			
			//console.log($first);
			//console.log($imgs.length);
			
			$imgs.hide().addClass("hide-image");
			$first.show();
			
			/* Build navigation */
			if ($imgs.length > 1 && settings.indicator) {
				$imgs.each(function(i){
					var visible = i+1;
					var $item = $("<span class=" + i + ">" + visible + "</span>");
					$navigation.append($item);
					i++;
				});
			}
			
			$navigation.children("span:first").attr("id", "current-img");
			var $numbers = $navigation.find("span");
			
			/* Interval */
			var interval = setInterval(function() {
				var $lastIndex = $curIndex;
				$curIndex = ($curIndex < $imgs.length - 1 ? $curIndex + 1 : 0);
				var $next = $imgs.eq($curIndex);
				if ($next.length && $curIndex !== $lastIndex) {
					$next.fadeIn(ANIM_TIME);
					
					/* add caption tme */
					$footer.empty();
					$next.find('h3').clone().removeClass("hide-h3").appendTo($footer);
					
					$imgs.eq($lastIndex).fadeOut(ANIM_TIME);
					activateNavigation($curIndex);
				}
			}, SLIDE_TIME);
			
			/* Navigation */
			var activateNavigation = function(index) {
				var $act = $navigation.find("span").eq(index);
				$navigation.children("span").removeAttr("id");
				$act.attr("id", "current-img");
			}
			
			/* Navigation click */
			$numbers.click(function() {
				clearInterval(interval);
				
				var $actNumber = $(this);
				$index = $actNumber.attr("class");
				
				activateNavigation($index);

				$imgs.fadeOut(ANIM_TIME);
				$imgs.eq($index).fadeIn(ANIM_TIME);
				
				/* add caption tme */
				$footer.empty();
				$imgs.eq($index).find('h3').clone().removeClass("hide-h3").appendTo($footer);
			});
		});
	}
}) (jQuery);
