/**
 * @author Fstrauss <florian.strauss@wgo-online.com>
 */
(function($){
    $.products = function(el, options){
       
        var base = this;
        var active = 1;
		var count = 0;
		var timer;
		var changer = true;
		
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;
        
        // Add a reverse reference to the DOM object
        base.$el.data("products", base);
        
        base.init = function(){
            base.options = $.extend({},$.products.defaultOptions, options);
          
            count = base.createNavigation();
			base.switchTo(1);

			timer = setTimeout(base.switcher, base.options.speed);

	
			
        };
		base.switcher = function() {
			if(changer) {
				active+=1;
				if(active > count) {
					active = 1;
				}
				base.switchTo(active);
				timer = setTimeout(base.switcher, base.options.speed);
			}
			
		}
		base.createNavigation = function(){
			var products = base.$el.find('ul.product-switcher-products > li'),
				navigation = base.$el.find('ul.product-switcher-navigation');

			$(products).each(function(i, product) {
				var li = $('<li>'),
					a = $('<a>');

				a
					.html((i+1))
					.attr('href','#')
					.click(function() {
						changer = false;
						base.switchTo((i+1));
						return false;
					})

				li
					.append(a);

				navigation
					.append(li);

			});
			return products.length;
        };

		base.switchTo = function(num) {
			var product = base.$el.find('ul.product-switcher-products > li:nth-child('+num+')'),
				products = base.$el.find('ul.product-switcher-products > li'),
				navigation = base.$el.find('ul.product-switcher-navigation').find('a'),
				navigationItem = base.$el.find('ul.product-switcher-navigation > li:nth-child('+num+') > a');

			products.find('.product-switcher-product').parent().hide();

			product.children('div').parent().show();
			navigation.removeClass('active');
			navigationItem.addClass('active');
		};
        
        // Run initializer
        base.init();
    };
    
    $.products.defaultOptions = {
        speed: 2000

    };
    
    $.fn.products = function(options){
        return this.each(function(){
            (new $.products(this, options));
        });
    };
    
})(jQuery);

