var autosaveState       = {tabs: false, fields: false, focus: false, scroll: false, comments: false};
var tabSwitchTrigger    = {};
var tabUserMessage      = {};
var currentTab          = 0;
var useStoredTab        = false;

	Array.prototype.indexOf = function(n)
	{  // Works exactly like its String.indexOf counterpart; returns the index when successful, -1 on failure
		for( var i = 0; i < this.length; i++ ) {
			if( this[i] == n ) return i;
		}

		return -1;
	}

	Array.prototype.filterEmpty = function()
	{  // Remove empty entries from an array
		var saveArray = [];
		for( var i = 0; i < this.length; i++ ) if( this[i] != '' ) saveArray.push(this[i]);

		return saveArray;
	}

	String.prototype.stripTags = function()
	{
      // Default filtering (which will remove -all- tags)
		if( arguments.length == 0 ) return this.replace(/<([^>]+)>/g, '');
		else { // Remove only specified tags
         var filterTags = [];
         for( var i = 0; i < arguments.length; i++ ) filterTags.push(arguments[i]);
         var tagFilter = new RegExp('<\/?(' + filterTags.join('|') + ')([^>]+)*>', 'gi');
			return this.replace(tagFilter, '');
		}
	};

	function cssAddClass(el, cssClass) { // Add a class to the specified element
		if( typeof cssClass != 'string' ) return;
		var classes = el.className.split(' ').filterEmpty();
		if( classes.indexOf(cssClass) == -1 ) classes.push(cssClass);

		// Trim the className attribute
		el.className = classes.join(' '); //.replace(/ {2,}/g, ' ');
	}

	function cssRemoveClass(el, cssClass) { // Remove a class from the specified element
		if( el.className == '' ) return; // If the element doesn't have any classes, there aren't any to remove...
		if( typeof cssClass != 'string' ) return;
		var classes = el.className.split(' ').filterEmpty(); // Remove empty elements
		if( classes.indexOf(cssClass) > -1 ) { // Does the class exist?
			for( var i = classes.length - 1; i >= 0; i-- ) { // Remove any occurances of cssClass
				if( classes[i] == cssClass ) classes.splice(i, 1);
			}
		}

		el.className = classes.join(' '); //.replace(/ {2,}/g, ' '); <-- disabled for now (for some reason, classes were being padded - a lot)
	}

	function cssHasClass(el, cssClass) { // Find out if the element has the specified class assigned to it
		var classes = el.className.split(' ').filterEmpty();
		return (classes.indexOf(cssClass) > -1);
	}


	function getTab(tabPos) { // Fetch a pointer to the specified tab
		if( document.getElementById('tabs') ) {
			return (document.getElementById('tabs').getElementsByTagName('li').length >= tabPos ? document.getElementById('tabs').getElementsByTagName('li')[tabPos] : 0);
		}
		else return 0;
	}

	function getTabContent(tabPos) { // Fetch a pointer to the tab content
		return document.getElementById('tabcontent_' + tabPos);
	}

	function getTabPos(tabElem) { // Find out where the specified tab is located
		if( document.getElementById('tabs') ) {
			var tabList = document.getElementById('tabs').getElementsByTagName('li');
			for( var i = 0; i < tabList.length; i++ ) {
				if( tabList[i] == tabElem ) return i;
			}
		}
		return 0;
	}

	function tabControl(tabElem) { // This function toggles the specified tab (tabElem can either be a direct pointer to the tab OR an integer, specifying its position)

		// If the specified tabElem is a position, we'll fetch a pointer to the tab
		if( typeof tabElem != 'object' ) tabElem = getTab(tabElem);

		// If the to-be-selected tab is already selected, nothing should happen
		if( getTabPos(tabElem) == currentTab ) return;

      if( tabElem.className == 'disabled' ) {
      	var tabPos = getTabPos(tabElem);

         if( typeof tabUserMessage['tab' + tabPos] == 'string' ) {
      		alert(tabUserMessage['tab' + tabPos]);
			}

			return true;
		}

		// If the tab contains an actual URL, we'll go to it
		if( tabElem.getAttribute('hrefTab') && tabElem.getAttribute('hrefTab') != '' ) {
			if( document.location.href.indexOf(tabElem.getAttribute('hrefTab')) == -1 ) {
				document.location.href = tabElem.getAttribute('hrefTab');
				return true;
			}
		}

		// Hide the current tab and reset the first one (which has a special class assigned to it)
		if( currentTab != null ) getTabContent(currentTab).style.display = 'none';
		cssRemoveClass(getTab(currentTab), 'current');
		getTab(0).className = 'first';

		// If the tab exists, fetch it, mark it as active, show its contents, reset the scroll position and
		// execute the trigger function if one has been specified
		cssAddClass(tabElem, 'current');
		currentTab = getTabPos(tabElem);
		getTabContent(currentTab).style.display = '';

		if( typeof tabSwitchTrigger['tab' + currentTab] == 'function' ) {
			tabSwitchTrigger['tab' + currentTab]();
		}

		document.cookie = document.location.href + '=' + currentTab;

		// Append the current tab title to the page title
		//document.title = currentPageTitle + ' - ' + getTab(currentTab).firstChild.innerHTML.stripTags(); //replace(/<([^>]+)>/g, '');

      if( document.getElementById('storedTab') ) document.getElementById('storedTab').value = currentTab;
		if( autosaveState.tabs ) { // If autosave for tabs has been enabled, store the current tab position and save it
			document.getElementById('currentTabIndex').value = currentTab;
			//forceFormAutosave();
		}
	}

	function initTabControl() { // Initialize the current set of tabs
		if( !document.getElementById('tabs') ) { // Make sure the tab container exists
         disableTabSelection();
			return;
		}
		var urlBasedTab = false; // Determine wether or not we've encountered a tab which points to a URL different from this one

		var tabList = document.getElementById('tabs').getElementsByTagName('li'); // Gather tabs
		for( var i = 0; i < tabList.length; i++ ) { // Attach the tabControl() to it and set the switch-trigger function
			if( tabList[i].className == 'last' ) continue;
			if( typeof tabSwitchTrigger['tab' + i] != 'function' ) tabSwitchTrigger['tab' + i] = null;
			if( typeof tabUserMessage['tab' + i]   != 'string'   ) tabUserMessage['tab' + i]   = null;
			tabList[i].onclick = function() { tabControl(this); };

			if( tabList[i].firstChild.href.indexOf('javascript:') == -1 ) {
				tabList[i].setAttribute('hrefTab', tabList[i].firstChild.href);
				tabList[i].firstChild.href = 'javascript:void(0);';
				tabList[i].firstChild.onclick = function () { return false; };
			}

			if( tabList[i].getAttribute('hrefTab') && (document.location.href.indexOf(tabList[i].getAttribute('hrefTab')) > -1) ) {
				currentTab  = i;
				urlBasedTab = true;
			}
		}

		if( allowTabSelection() && (document.cookie.indexOf(document.location.href) > -1) ) {
			currentTab = parseInt(document.cookie.substring(document.cookie.indexOf(document.location.href) + (document.location.href.length + 1)));
		}

			// Find out if the URL contains a #tab anchor; if so, set the currentTab to that one
		if( !urlBasedTab && document.location.href.indexOf('#tab') > 0 ) {
			var oldTabPos = currentTab;
			currentTab    = parseInt(document.location.href.substring(document.location.href.indexOf('#tab') + 4)) - 1;

			if( tabList[currentTab].className == 'disabled' ) currentTab = oldTabPos;
		}
		cssAddClass(tabList[currentTab], 'current');  // Set the current tab
		getTabContent(currentTab).style.display = ''; // ...and display it's contents
		if( typeof tabSwitchTrigger['tab' + currentTab] == 'function' ) {
			tabSwitchTrigger['tab' + currentTab](); // If defined, execute the switch trigger
		}

		// Store the current page title
		currentPageTitle = document.title;
		//document.title   = currentPageTitle + ' - ' + getTab(currentTab).firstChild.innerHTML.stripTags();

		if( document.getElementById('storedTab') ) document.getElementById('storedTab').value = currentTab;

		disableTabSelection();
	}

	function enableTabSelection() {
		document.cookie = 'restoretab=true';
	}

	function disableTabSelection() {
		document.cookie = 'restoretab=false';
	}

	function allowTabSelection() {
		return (document.cookie.indexOf('restoretab=true') > -1);
	}


	if( window.addEvent ) addEvent(window, 'load', initTabControl);
