/*  
From the article http://www.learningjquery.com/2007/10/a-plugin-development-pattern
*/

//
// create closure
//
(function($) {
	//
	// plugin definition
	//
	var _self;
	
	var images;
	
	var numImgs, arrLeft, totalWidth, myInterval;

	var isRunning = false;
	
	var o;
	
	var $controls;
	
	// index of the current image
    var currentpic;
	
	$.fn.tremblantSlider = function(options) 
	{
		var opts = $.extend({}, $.fn.tremblantSlider.defaults, options);

		return this.each(function() {
			
			_self = $(this);
			
			images = _self.find('img');
			
			numImgs = images.length;
			
			arrLeft = new Array(numImgs);

			images.hide();
			// build element specific options
			o = $.meta ? $.extend({}, opts, $this.data()) : opts;
			
			addButtons();
			
			currentpic = o.firstImage;
			
			images.eq(currentpic).show();
			
			_self.find("#trsldr-ctrl div:eq(" + (currentpic) + ")").addClass('active');
			
			_self.css({ 'height' : images.eq(currentpic).height(), 'width' : images.eq(currentpic).width() } );
			
			// update element styles
			$controls = '<div id="slide-controls"> \
							<p id="slide-client" class="text"><strong>post: </strong><span></span></p> \
							<p id="slide-desc" class="text"></p> \
							<p id="slide-nav"></p> \
						</div>';
						
			
			
			/*
			for (var i = 0; i < numImgs; i++)
			{
				totalWidth=0;
				for(var n = 0; n < i; n++)
				{
					totalWidth += $(images[n]).width();
				}
			
				arrLeft[i] = totalWidth;
				images.eq(i).css("left",totalWidth);
			}
			*/
			//myInterval = setInterval(flexiScrollLeft,20);
			//myInterval = setInterval(flexiScrollRight,50);
			//myInterval = setInterval(flexiScroll,50);
			//myInterval = setInterval(flexiScroll,50);
			
			//$('#imageloader').hide();
			if(o.autostart)
			{
				isRunning = true;
				myInterval = setInterval(changePic,o.slideTimer);
			}
		});
	};
	function addButtons()
	{
		var $ctrlHolder = $('<div id="trsldr-ctrl">');
		
		_self.append($ctrlHolder);
		
		images.each(
			function(i,el)
			{
				$ctrl = $('<div class="controls">'+(i+1)+'</div>');
				
				$ctrl.css(
							{
								'left'	: Math.round($('.controls').outerWidth() * i) + "px"
								, 'margin' : o.controlsMargin
							}
						).bind('click', changePic);
			
				$ctrlHolder.append($ctrl);
			}
		)	
		$ctrlHolder.css({'top':o.controlTop, 'left':o.controlLeft});	
	}
	
	function changePic(e)
	{
		
		hidePicture();
		
		// no button have been clicked it's the timer
		if(e)
		{
			// some button have been click tak it's index
			var idx = $(e.target).index();
			
			if(isRunning)
			{
				clearInterval(myInterval);
				myInterval = setInterval(changePic,o.slideTimer);
			}
		}
		else
		{			
			var idx = currentpic + 1;
		}
		
		currentpic = setIndex(idx);	
		
		updatePicture();
	}
	
	function flexiScrollLeft()
	{
		for (i=0;i<numImgs;i++){
			arrLeft[i] -= 1;		

			if (arrLeft[i] == -(images.eq(i).width())){
				totalWidth = 0;
				for (n=0;n<numImgs;n++){
					if (n!=i){
						totalWidth += images.eq(n).width();
					}
				}
				arrLeft[i] =  totalWidth;
			}
			images.eq(i).css("left",arrLeft[i]);
		}
	}
	function flexiScrollRight()
	{
		for (var i = numImgs - 1; i > -1; i--)
		{
			arrLeft[i] += 1;
			
			if (arrLeft[i] >= _self.width())
			{	
				totalWidth = 0;
				for (var n = 0; n < numImgs; n++)
				{
					totalWidth += images.eq(n).width();
				}
				arrLeft[i] = arrLeft[i] - totalWidth;
			}
		images.eq(i).css("left",arrLeft[i]);
		}
	}

	function hidePicture()
	{
		// we fade out the old image
		images.eq(currentpic).fadeOut(o.transitionSpeed);
		
		// we also remove the active class from the control buttons
		_self.find("#trsldr-ctrl div").removeClass('active');
		/*
		// and we hide the tip attach to that slide
		_self.find("#ss_tip .tip:eq(" + currentpic + ")").hide();
		
		
		
		// finally we remove the title text
		_self.find("#ss_tip_tab span").html('');
		*/
	}
	
	function updatePicture()
	{
		// we have the new index or currentpic let's show the new image
		images.eq(currentpic).fadeIn(o.transitionSpeed);
		
		// and we had the active class to the control button
		_self.find("#trsldr-ctrl div:eq(" + (currentpic) + ")").addClass('active');
		/*
		_self.find("#ss_img img:eq(" + currentpic + ")").fadeIn(o.transitionSpeed);
		// update the title text
		_self.find("#ss_tip_tab span").html(image.eq(currentpic).attr('title') + " - " + image.eq(currentpic).attr('alt'));
		
		*/
	}
	//
	// private function for debugging
	//
	function debug($m) {
		if (window.console && window.console.log)
		window.console.log($m);
	};
	
	function setIndex($x)
	{	
		// previous button
		if ($x < 0)
		{
			return currentpic == 0 ? images.length - 1 : currentpic-1;
		}
		// next btn
		else if ($x >= images.length) 
		{
			return currentpic < images.length - 1 ? (currentpic + 1) : 0;
		} 
		else 
		{
			return $x;
		}
	}

	//
	// plugin defaults
	//
	$.fn.tremblantSlider.defaults = 
	{
		  autostart				: false
		, firstImage			: 0
		, slideTimer			: 7500
		, transitionSpeed		: 750
		, controlsMargin		: '0 4px 0 0'
		, controlTop			: 260
		, controlLeft			: 15
		, controlActiveColor	: '#F5E125'
	};
//
// end of closure
//
})(jQuery);
