/**
 * @author Fstrauss <florian.strauss@wgo-online.com>
 */
(function($){
    $.teaser = function(el, options){

        var base = this;
		var first = true;
		var active = 1;
		var timer;
		var changer = true;
		
        base.$el = $(el);
        base.el = el;

        // Add a reverse reference to the DOM object
        base.$el.data("teaser", base);

        base.init = function(){
            base.options = $.extend({},$.teaser.defaultOptions, options);
			
			base.switchTo(1);
			base.createNavigation();
			base.setSize();

			base.getItems().css('position','absolute');

			timer = setTimeout(base.switcher, base.options.speed);

        };
		base.setSize = function() {
			base.$el
				.css('width', base.$el.width())
				.css('height', base.$el.height())
		}
		base.getSize = function() {
			return {
				width: base.$el.width(),
				height: base.$el.height()
			};
		}
		base.switchTo = function(i) {

			if(first) {
				base.$el
					.children('ul')
					.children('li:nth-child('+i+')')
					.show()

				first = false;
				return;
			}

			base
				.getItems()
				.fadeOut(1000);

			base.$el
				.find('ul.teaser-switcher-navigation > li')
				.removeClass('active');

			base.$el
				.find('ul.teaser-switcher-navigation > li:nth-child('+i+')')
				.addClass('active');

			base.$el
				.children('ul')
				.children('li:nth-child('+i+')')
				.fadeIn(1000)
	
		}
		base.switcher = function() {
			if(changer) {
				active+=1;

				if(active > base.getItems().length) {
					active = 1;
				}
				base.switchTo(active);
				timer = setTimeout(base.switcher, base.options.speed);
			}

		}

	
		base.getItems = function() {
			return base.$el
						.children('ul:first')
						.children('li')
		}
		base.getItem = function(i) {
			i+=1;
			return base.$el
						.children('ul')
						.children('li:nth-child('+i+')')
		}

		base.createNavigation = function(){

			var items = base.getItems(),
				navigation = $('<ul class="teaser-switcher-navigation"></ul>'),
				width = 0;

			width = base.getSize().width / items.length;

			$(items).each(function(i, item) {
				var li = $('<li>'),
					a = $('<a>');

				a
					
					.html($(item).find('a').attr('title'))
					.attr('href','#')
					.click(function() {
						base.switchTo((i+1));
						changer = false;
						return false;
					})
					.css('width',(width -30)+'px')
				

				if(i == 0) {
					li.addClass('active');
				}

				if(items.length == (i+1)) {
					a.css('width',(width - 20) +'px');
					
				}
				
				li
					.css('width',width+'px')
					.append(a)
					
		
				
				navigation
					.append(li);

			});

			base.$el.append(navigation);

			return items.length;
        };

        // Run initializer
        base.init();
    };

    $.teaser.defaultOptions = {
		speed: 6000
    };

    $.fn.teaser = function(options){

        return this.each(function(){
            (new $.teaser(this, options));
        });
    };

})(jQuery);

