(function($) {

$.fn.mTabs = function(options) {
		
	function initTabs() {	
		
		opt.pushState = (window.history.pushState)? true : false;
		
		$(context).each(function(){
			
			var c = this;
			
			if($(c).attr('id').length>0)
			{			
				var cId = $(c).attr('id');
				var curTabId = GetCurTab(cId);
			}

			$('li', c).each(function(i){
			
				var TabId = $(this).attr('rel');
				
				if((curTabId && (curTabId.toLowerCase() != TabId.toLowerCase())) || (!curTabId && i>0))
				{
					$(this).removeClass('Active');
					$("#"+TabId).hide();
				}
				else 
				{
					$(this).addClass('Active');
					$("#"+TabId).show();
					curTabId = TabId;
				}
			});
			
			var param = {}; param.curTabId = curTabId; param.c = c; param.cId = cId;			

			$('li', c).each(function(i){var TabId = $(this).attr('rel'); $(this).bind('click', function(){ClickTab(TabId, opt, param);});});
		});
	}	
	
	function ClickTab(TabId, opt, param)
	{	
		$('[rel="'+param.curTabId+'"]', param.c).removeClass('Active'); $('#'+param.curTabId).hide(); $('[rel="'+TabId+'"]', param.c).addClass('Active'); $('#'+TabId).show(); param.curTabId = TabId;
	
		SetCurTab(TabId, param.cId);	
	}

	function GetCurTab(id)
	{
		if(!id)
			return;
	
		var hash = unescape(window.location.hash);
		
		var url = unescape(window.location);
		
		var exp = new RegExp(id+'=([^&#]*)', 'i');
		
		if(res = exp.exec(url))
		{
			return res[1];
		}		
		else if(hash.length>0 && (res = exp.exec(hash)))
		{	
			return res[1];
		}
		else
		{
			return false;
		}
	}
	
	function SetCurTab(TabId, cId)
	{
		if(!cId)
			return;

		var found = GetCurTab(cId);
		
		var hash = unescape(window.location.hash);
		
		if(hash.length>0 && hash.charAt(0) == "#")
			hash = hash.substr(1, hash.length);

		if(found)
		{
			//if(!opt.pushState || true)
			//{
				var exp = new RegExp(cId+'=([^&]*)');			
				hash = hash.replace(exp, cId+'='+TabId);
			//}
			//else
			//{			
				//var exp = new RegExp('[&]{0,1}'+cId+'=([^&]*)');
				//hash = hash.replace(exp, cId+'='+TabId);
				
				
			//}
		}
		else if(hash.length>0)
		{
			hash +='&'+cId+'='+TabId;
		}
		else
		{
			hash ='?'+cId+'='+TabId;
		}
		
		window.location.hash = escape(hash);
	}
	
	defaults = {};	
	var opt = $.extend(defaults, options);	
	var context = this;		
	initTabs();
}
})(jQuery);
