/*
 * Author: VRB
 * Date: 16.XI.2009
 */
;(function($){
	$.fn.tabs = function(op){
		var s = [],
		_this,
		$this,
		tabPosition = 0;
		o = [];
		oldLi = {};
		_defaults = {
			leftPosition	: 0,			// Czy pozycja taba ma byc przesunieta
			selectStartTab	: '#tabs-1',	// Ktory taba startowo zaznaczamy
			startDepth		: 50,
			tabActiveClass	: 'active',
			divActiveClass	: 'active',
			liTabIndex		: '-liid',
			loadingId		: '#loadTabData'
		},
		setTabPosition = function($li, i){
			$li.css("position", "absolute");
			$li.css("left", tabPosition);
			tabPosition += $li.width() + o.leftPosition;
			$li.css("z-index", o.startDepth - i);
		},
		getIdFromURL = function(){
			var location = new String(document.location);
			var pos = location.indexOf("#");
			if (pos < 0) return null;
			return(location.substr(pos));
		},
		setActive = function(id){
			if (id == null)
				return false;
			$("div." + o.divActiveClass, _this).removeClass(o.divActiveClass).hide();
			//alert($(id).addClass(o.tabActiveClass).fadeIn("slow").length);
			if ($(id).addClass(o.tabActiveClass).fadeIn("slow").length < 1) return false;
			$("ul li." + o.tabActiveClass , _this).removeClass(o.tabActiveClass);
			if (o.leftPosition != 0) {
				var $li = $("ul li", _this);
				$li.each(function(i) {
					$li.eq(i).css("z-index", o.startDepth - i);
				});
			}
			$(id + o.liTabIndex).addClass(o.tabActiveClass).css("z-index", o.startDepth + 1);
			return true;
		};
		
		return this.each(function(i) {
			_this = this;
			$this = $(this);
			o = $.extend({},_defaults,op);
			
			var $li = $("ul li", _this);
			$li.each(function(i) {
				var $liT = $li.eq(i);
				$aT = $liT.find("a");
				if (o.leftPosition != 0)
					setTabPosition($liT, i);

				$liT.attr("id", $aT.attr("href").substr(1) + o.liTabIndex);
				$aT.click(function(e){
					setActive($(this).attr("href"));
				});
				
			});
			//alert($(o.selectStartTab).length);
			$(o.loadingId).hide();
			if (!setActive(getIdFromURL()))
				setActive(o.selectStartTab);			
		});
	};
	
})(jQuery);
