var tabs = (function($) {
  
  function triggerCallback(eventName, element, thisvar) {
    var f = element.data(eventName);
    if (typeof f == 'function') {
      f.call(thisvar);
    }    
  }

	function switchTab(e) {
		var activeTab, tabset, tab, storageLocation, l;
		
    e = e||window.event;
    
    if ($(e.target).parents('li').is('.active') && $(e.target).parents('li').data('init'))
      return false;
		
		activeTab = $('li.active', $(e.target).parents('ul'));
		
		triggerCallback('deactivate', $('a', activeTab), this);
    triggerCallback('activate', $(this), this);
      
		tabset = $(e.target).parents('.tabset');
		tab = $(e.target).attr('href').replace(/^.*#(.*)$/, '$1');
		storageLocation = window.location.pathname + 't' + $(e.target).data('tabset');

		$(e.target).parents('li').data('init', true);

		try {
			sessionStorage.setItem(storageLocation, tab);
		}
		catch(e) {
		}

		$("ul.tabs li", tabset).removeClass('active');
		$(e.target, tabset).parents('li:first').addClass('active');
		$('.tabbody', tabset).removeClass('active');
		$('#' + tab, tabset).addClass('active');
		return false;
	}
	
  function getQueryString() {
    var result = {},
        queryString = location.search.substring(1),
        re = /([^&=]+)=([^&]*)/g, m;
  
    while (m = re.exec(queryString)) {
      result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }
  
    return result || false;
  }
  
  function findActiveTab(e) {
    var tabs, tabstr, result = false;

    if (tabstr = getQueryString()["tabs"]) {
      tabs = tabstr.split(',');
      if (tabs.length > 0) {
        for (var i=0, x=tabs.length; i<x; i++) {
          if ($('#' + tabs[i], e).length > 0) {
            result = tabs[i];
            break;
          }
        }
      }
    }
    
    if (!result) {
      result = $('ul.tabs li a:eq(0)', e).attr("href").replace(/^.*#(.*)$/, '$1');
    }

    return result;
  }

	function initTabs(idx, e) {
		var currentTab = findActiveTab(e);
		  
		$('ul.tabs li', e).data('init', false);
		$('ul.tabs li a', e).data('tabset', idx).click(switchTab);
		if (currentTab) {
			$('ul.tabs li a[href=#' + currentTab + ']', e).click();
		}
	}

	function init() {
		$('.tabset').each(initTabs);
	}
	
	function attachCallback(tabName, callback, event) {
    var l = $('ul.tabs a[href=#' + tabName + ']');
    
    if ((l.length > 0) && (typeof callback == 'function')) {
      l.data(event, callback);
      return l;
    }
    return false;
	}
	
	this.tabDeactivate = function(tabName, callback) {
	  attachCallback(tabName, callback, 'deactivate');
	} 
	
  this.tabActivate = function(tabName, callback, ignoreStartup) {
    var el = attachCallback(tabName, callback, 'activate');
    
    if (el && el.parent().is('.active') && (typeof ignoreStartup !== 'undefined') && !ignoreStartup) {
      callback();
    }
  }

	$(document).ready(init);

	return this;
})(jQuery);
