/*
 *  Konstruktor pro Záložky
 */
 /*
 	TODO: regulár na komplikovanější hash (#hash1&hash2&tab=test)
 */


sk.widgets.Tabs = function(element, options){
	this.$element = element.jquery ? element : $(element);
	this.options = $.extend({
		current: 0,
		item: 'a',
		eventName: 'click touchstart',
		tabHideClass: 'sk-tab-hide',
		menuActiveClass: 'active',
		onActiveTab: function(){}
	}, options);
	this.currentIndex = this.options.current;
	this.currentId = null;
	// tabs menu
	this.$menu = this.$element.find(this.options.item);
	// tabs fragment
	var $tabs = $([]);
	this.$menu.each(function(){
		$tabs = $tabs.add($(this).attr('href'));
	})
	this.$tabs = $tabs;

	return this;
};

sk.widgets.Tabs.prototype.init = function(){
	if(!this.$element.length){
		return this;
	}
	
	var o = this.options;
	this.$menu.bind(o.eventName, $.proxy(this.handle, this));
	
	// určování která záložka má být defaultně aktivní
	this.hash();
	
	return this;
};

sk.widgets.Tabs.prototype.hash = function(){
	var o = this.options;
	// určování která záložka má být defaultně aktivní
	var tab = '';
	var scroll = '';
	this.$tabs.each(function(){
		var hash = location.hash.split('#');
        hash = hash[hash.length - 1];
        
        if(hash){
        	hash = location.hash.split('tab=');
       		hash = hash[hash.length - 1];
        	
	        if($(this).is('#'+hash)){
	        	tab = '#' + $(this).attr('id');
	        }
	        else if($(this).find('#'+ hash).length){
	        	tab = '#' + $(this).attr('id');
	        	scroll = '#' + hash;	
	        }
    	}
	})
	this.set(tab || this.currentIndex, scroll);	
};

sk.widgets.Tabs.prototype.handle = function(e){
	var $target = $(e.currentTarget);
	var href = $target.attr('href').split('#');
        href = href[href.length - 1];
    
    // pokud záložka již není aktivní tak nastavit
    if(!$target.hasClass(this.options.menuActiveClass)){   
   		location.hash = '#tab=' + href;
   	}
	return false;
};

sk.widgets.Tabs.prototype.set = function(current, scroll)
{
	var id = typeof current == 'number' ? this.$menu.eq(current).attr('href') : current;	
	
	if(this.currentId !== id){
		this.currentIndex = this.$menu.filter('[href="'+id+'"]').index();
		this.currentId = id;
		this.setTab(id);	
		this.setMenu(id);
		
		scroll && $('html, body').scrollTop($(scroll).offset().top);
	}	
};

sk.widgets.Tabs.prototype.setTab = function(id){
	this.$tabs
		.filter(id)
		.removeClass(this.options.tabHideClass)
		.end()
		.not(id)
		.addClass(this.options.tabHideClass);
		
	this.options.onActiveTab.call(this);
};

sk.widgets.Tabs.prototype.setMenu = function(id){
	this.$menu
		.removeClass(this.options.menuActiveClass)
		.filter('[href="'+id+'"]')
		.addClass(this.options.menuActiveClass);	
};
