/* 
 * slide images, contents
 * @method textSlider 
*/

$.fn.textSlider = function (o) {
	
	var $self = $(this);
	
	var options = $.extend ({}, {
		header    : 'div.t-container div > h3',
		elements  : '> div',
		_class    : 't-slider',
		loadClass : 't-loader',
		step      : 1,  // how many slides
		//lazyload : true,  TODO
		axis      : 'horizontal', // [vertical,horizontal]
		slide     : 0,  // current slide
		nextslide : 0,  // next slide
		mousewheel: true,
		auto      : false, // [left, previous]  autoslide
		autostop  : 'slideshow stopped', 
		onAuto    : function() {},
		onAutoStop: function() {},
		wait      : 3000,
		ajax      : false,
		ajaxElements: 'div.section-presentation > div',
		breadcrumb: true,
		around    : true,
		//breadcrumbText : '%s slide',  TODO
		breadcrumbTitle : ' slide',
		navigate  : true,
		animate   : 'slide',
		animoption: [1000], 
		autosize  : false, // time for size ms
		animations: {
			slide : function ($container, $slide, option) {
				var coords;
				
				if (option.axis == 'horizontal') coords = {
					left: -option._nextposition
				} 
				else if (option.axis == 'vertical') coords = {
					top: -option._nextposition
				};
				
				$container.animate (coords, option.animoption[0], function () {
					option._animation = false;
				});
			},
			show : function ($container, $slide, option) {
				var coords;
				
				if (option.axis == 'horizontal') coords = {
					left: -option._nextposition
				}
				else if (option.axis == 'vertical') coords = {
					top: -option._nextposition
				};
								
				$container.css (coords);
				option._animation = false;
			},
			fade : function ($container, $slide, option) {
				var coords;
				
				if (option.axis == 'horizontal') coords = {
					left: -option._nextposition
				}
				else if (option.axis == 'vertical') coords = {
					top: -option._nextposition
				};
								
				$container.fadeOut (option.animoption[0], function() {
					$container.css (coords);
				});
				$container.fadeIn (option.animoption[0], function () {
					option._animation = false;
				});
			}	
		},
		onCreate : function () {},
		onSlide  : function () {},
		_nextposition : 0,
		titlePrevious : 'show previous slide',
		titleNext     : 'show next slide'
	}, o);
	
	// display slide
	function display ($self, $container) {
		var node = $container[0].parentNode;
		var $slides = {
			current : $(node.options.elements + ':eq(' + node.options.slide + ')', $container),
			next    : $(node.options.elements + ':eq(' + node.options.nextslide + ')', $container)
		}
		
		node.options._animation = true;

		node.options._nextposition = 0;
		$slides.next.prevAll ('.t-slide').each (function() {
			node.options._nextposition += (node.options.axis == 'horizontal' ? this.offsetWidth : this.offsetHeight);	
		});
		
		node.options.onSlide (node, $slides);
				
		$self[0].blur();
		
		current (node.options.nextslide, node);
		
		node.options.animations[node.options.animate] ($container, $slides, node.options);

		if (node.options.autosize) autosize (node, $slides.next);

		if (node.options.auto) auto (node);
		
		node.options.slide = node.options.nextslide;
	}

	// get slide width
	function width ($slide, step) {
		var width = $slide[0].offsetWidth;
		for (var i=1; i < step; i++) {
			width += $slide.next ('.t-slide')[0].offsetWidth;	
		}
		return width;		
	}
	// get slide height
	function height ($slide, step) {
		var height = $slide[0].offsetHeight;
		for (var i=1; i < step; i++) {
			height += $slide.next ('.t-slide')[0].offsetHeight;
		}
		return height;		
	}
	
	// autoslide	
	function auto (self) {
		if (!self.options.auto || self.options.mouseover) return;
		
		self.options.onAuto (self);

		$('.t-breadcrumb a:eq(' + self.options.nextslide + ')', self).fadeTo (self.options.wait, 0, function () {
			this.removeAttribute ('style');
		});
				
		self.options._timeout = window.setTimeout (function (){
			trigger ($(self), (self.options.auto == 'next' ? 't-next' : 't-previous'));
		}, self.options.wait); 
	}
	
	// show custom slide
        function custom () {
		var $this = $(this), $self = $this.parents ('div.t-slider');
		var $container = $('div.t-container', $self);
		
		$self[0].options.nextslide = parseInt ($this.attr ('slide'));
		display ($this, $container);
		
		return false;
	}

	// show next slide 
	function next() {
		var $this = $(this), $self = $this.parents ('div.t-slider'); // TODO _class
		var $container = $('div.t-container', $self);
                
                //alert (this.getAttribute ('href', 2));
                if (this.getAttribute ('href', 2) != '#' && $self[0].options.ajax && !$($self[0].options.elements + ':eq('+($self[0].options.slide + $self[0].options.step)+')', $container).length) {
			$self.addClass ($self[0].options.loadClass);
			$.ajax ({
				async: false,
				url: this.getAttribute ('href', 2),
				success: function (data) {
					$container.append ($(data).find ($self[0].options.ajaxElements));    
					var $next = $('.t-next', $container);
					var $previous = $('.t-previous', $container);
					if ($('> .t-next', $self).length) {
						$('> .t-next', $self).replaceWith ($next);
					} else {
						$next.appendTo ($self);
					}	
					if ($('> .t-previous', $self).length) {
						$('> .t-previous', $self).replaceWith ($previous);
					} else {
						$previous.appendTo ($self);
					}					
					$($self[0].options.elements, $container).addClass ('t-slide');
					$self.removeClass ($self[0].options.loadClass);	
				},
				error : function () {
					$self.removeClass ($self[0].options.loadClass);		
				}
			});
		}
		
                
                if (!$self[0].options._animation) {
			$self[0].options.nextslide = $self[0].options.slide + $self[0].options.step;
			if ($self[0].options.nextslide > ($($self[0].options.elements, $container).length-1)) $self[0].options.nextslide = 0;
			display ($this, $container);
		}

		return false;
	}
	
	// show previous slide
        function previous() {
		var $this = $(this), $self = $(this).parents ('div.t-slider');
		var $container = $('div.t-container', $self);

                if (this.getAttribute ('href', 2) != '#' && $self[0].options.ajax && !$($self[0].options.elements + ':eq('+($self[0].options.slide - $self[0].options.step)+')', $container).length) {
			$self.addClass ($self[0].options.loadClass);
			$.ajax ({
				async: false,
				url: this.getAttribute ('href', 2),
				success: function (data) {
					$container.prepend (data);
					$($self[0].options.elements, $container).addClass ('t-slide');	
					$self.removeClass ($self[0].options.loadClass);	
				},
				error : function () {
					$self.removeClass ($self[0].options.loadClass);		
				}
			});
		}
		                
                if (!$self[0].options._animation) {
			$self[0].options.nextslide = $self[0].options.slide - $self[0].options.step;
			if ($self[0].options.nextslide < 0) $self[0].options.nextslide = $($self[0].options.elements, $container).length - $self[0].options.step;
			display ($this, $container);
		}

		return false;
	}
	
	// select current breadcrumb
	function current (id, $self) {
		$('.t-breadcrumb a', $self).removeClass ('active').empty();
		$('.t-breadcrumb a:eq(' + id + ')', $self).addClass ('active');
	}
	
	// create breadcrumb		
	function breadcrumb ($this) {
		var $breadcrumb = $('<div/>').addClass ('t-breadcrumb');
		$('div.t-container' + $this[0].options.elements, $this).each (function (index) {
			var header = $('> h3', this);
			$('<a href="#slide" title="' + (header.text()||($this[0].options.breadcrumbTitle+(index+1))) + '" slide="' + index + '"/>').html (index).appendTo ($breadcrumb);	
		});
		return $breadcrumb;	
	}
	
	// create navigation
	function navigate ($this) {
	        $this.append ($('<a/>').addClass ('t-previous').text('previous').attr ({
			href: '#previous-slide',
			accesskey : 'B',
			title: options.titlePrevious
		}));
		$this.append ($('<a/>').addClass ('t-next').text('next').attr ({
			href: '#next-slide',
			accesskey : 'N', 
			title: options.titleNext
		}));	
	}

	// trigger nect/previous
	function trigger (self, event) {
		$('<a class="' + event + '"/>').appendTo(self).trigger ('click').remove();	
	}
	
	// event mousewheel TODO 
	function wheel (event) {
		var delta;
		if (window.event && window.event.wheelDelta) { /* IE/Opera. */
			delta = window.event.wheelDelta/120;
		} else if (event.detail) { /** Mozilla case. */
			delta = -event.detail/3;
		}
		
		if ($self[0].options.mouseover) {
			trigger ($self, (delta > 0 ? 't-next' : 't-previous'));
			
			if (window.addEventListener) event.preventDefault();
			else window.event.returnValue = false;
			
			return false;
		}
	}

	// set size
	function autosize (node, $next) {
		var coords;
		
		if (node.options.axis == 'horizontal') 
			coords = {width: width ($next, node.options.step)};
		
		if (node.options.axis == 'vertical') 
			coords = {width: $next.width(), height: height ($next, node.options.step)};
			
		$(node).animate (coords, node.options.autosize);	
	}
				
	this.each (function () {
		var $this = $(this);

		// events
                $('a.t-previous').die ('click', previous);
		$('a.t-previous').live ('click', previous);
	        $('div.t-breadcrumb a').die ('click', custom);
	        $('div.t-breadcrumb a').live ('click', custom);	
		$('a.t-next').die ('click', next);
		$('a.t-next').live ('click', next);
	
               	if (!$this.hasClass (options._class)) { $this.addClass (options._class); };
               	if (!$this.hasClass ('t-' + options.axis)) { $this.addClass ('t-' + options.axis); };
               	
		if (!$('div.t-container', this).length) { $this.html ('<div class="t-container">' + $this.html() + '</div>'); }

                $('.t-container' + options.elements).addClass ('t-slide');
                
                var $slide = $('.t-container' + options.elements + ':eq(' + options.slide + ')', $this);

		if (options.mousewheel) {		
			if (window.addEventListener) window.addEventListener ('DOMMouseScroll', wheel, false);
			else document.onmousewheel = wheel;
		}

		// autoslide
		$this.mouseover (function () {
			this.options.mouseover = true;
			if (this.options.auto) {
				window.clearTimeout (this.options._timeout);
				$('<p class="t-notice">' + this.options.autostop + '</p>').appendTo (this);
				$('.t-breadcrumb a:eq(' + this.options.slide + ')', this).stop().removeAttr ('style');
				(this.options.onAutoStop ? this.options.onAutoStop (this) : null);
			}
		});
		$this.mouseout (function () {
			this.options.mouseover = false;
			if (this.options.auto) {
				auto (this);
				$('.t-notice', this).remove();
			}	
		});

                this.options = options;
                
                if (options.navigate && !options.ajax) navigate ($this);
                
                if (options.ajax) {
                	$('a.t-previous', this).appendTo (this);
                	$('a.t-next', this).appendTo (this);
                }
                
		if (options.breadcrumb) {
			breadcrumb ($this).appendTo ($this);
			current (options.slide, $this); 
		}

		if (options.slide != 0) {
			this.options.nextslide = options.slide;
			this.options.slide = 0;
			display ($this, $('div.t-container', this)); 
		} 
		else if (options.autosize) autosize (this, $slide);

		if (options.auto) auto (this);
		
		options.onCreate (this);
	});
	
	$.fn.extend ({
		
		textSliderUpdate : function (o) {
			this.each (function () {
				var $this = $(this);
				
				if (o) {
					this.options = $.extend ({}, this.options, o);
				}
								
				if (o.nextslide != undefined && o.nextslide.toString().length) {
					display ($this, $('div.t-container', this));
				} 

				if (o.breadcrumb != undefined && o.breadcrumb.toString().length) {
					var $breadcrumb = $('.t-breadcrumb', this);
					if (this.options.breadcrumb && !$breadcrumb.length) breadcrumb ($this).appendTo (this);
					if (!this.options.breadcrumb && $breadcrumb.length) $breadcrumb.remove();
				}
				
				if (o.navigate != undefined && o.navigate.toString().length) {
					var $navigate = $('.t-previous, .t-next', this);
					if (this.options.navigate && !$navigate.length) navigate ($this);
					if (!this.options.navigate && $navigate.length) $navigate.remove();
				}				
			});		
		}			
	});
}