// JavaScript Document
(function($) {
	$.fn.slideshow = function(options) {
		var opts = $.extend({}, $.fn.slideshow.defaults, options);
		return this.each(function() {
			var $this 					= $(this);
			$this.opts 					= $.extend({}, opts);
			$this.opts.elementwidth		= $this.find('.slider li').outerWidth();
			$this.opts.position 		= 0;
			$this.opts.visibleelements 	= 4;
			$this.opts.speedfactor 		= 10;
			$this.opts.title			= '';
			$this.opts.timeout			= null;
			$this.opts.totalwidth		= $this.find('.slider li').length * $this.opts.elementwidth;
			
			
			$this.find('.slider ul').css('width',$this.opts.totalwidth+'px');
			$this.find('.navigation .right').click(function(event){
				$this.opts.position++; 
				if($this.opts.position > $this.find('.slider li').length - $this.opts.visibleelements){
					$this.opts.position = $this.find('.slider li').length - $this.opts.visibleelements;	
				}
				$.fn.slideshow.slide($this);
				event.preventDefault();
			});
			$this.find('.navigation .left').click(function(event){
				$this.opts.position--; 
				if($this.opts.position < 0){
					$this.opts.position = 0;	
				}
				$.fn.slideshow.slide($this);
				event.preventDefault();
			});
			
			$this.find('.navigation .slider ul a').each(function(){
				$(this).bind('click',function(event){
					event.preventDefault();
					$.fn.slideshow.show($this, $(this));
				});
			});
		});
	};
	$.fn.slideshow.defaults = {
	};
	
	$.fn.slideshow.show = function($this, $el){
		$this.opts.title = $el.find('img').attr('title');
		$oldpic = $this.find('.bigpic img');
		$newpic = $('<img src="" />')
		$this.find('label').html($el.attr('title'));
		$newpic.load(function(){			
			$oldpic.css('position','absolute').fadeTo(400,0,function(){ $(this).remove(); })
			$this.find('.bigpic').css('height',$newpic.height()+'px')
			$newpic.fadeTo(400,1)
			$this.find('label').stop().fadeTo(400, 0, function(){
				if($this.opts.title){
					$(this).html($this.opts.title);	
					$this.find('label').fadeTo(400, 0.8);
				}
			})
		});
		$this.find('.bigpic').prepend($newpic);
		$newpic.hide();
		$newpic.attr('src',$el.attr('href'));
	}
	
	$.fn.slideshow.slide = function($this, $el){
		clearTimeout($this.opts.timeout);
		targetposition 	= $this.opts.position * $this.opts.elementwidth * -1;
		currentpos		= parseInt($this.find('.slider ul').css('left'));
		if(targetposition != currentpos){
			speed =  ((targetposition - currentpos) / $this.opts.speedfactor);
			if(speed < 0 && speed > -1) speed = -1;
			if(speed > 0 && speed < 1) speed = 1;
			newpos = currentpos + speed;
			$this.find('.slider ul').css({left:newpos+'px'});
			$this.opts.timeout = setTimeout(function(){ $.fn.slideshow.slide($this); }, 20);
		}
	}
	
})(jQuery);
