var CUR_TAB = null;
var MAX_TABS = 4;
var TAB_4_LOADED = false;
function HideTabs()
{
	jQuery(".TabButton").removeClass("selected");
	jQuery(".TabPanel").hide().removeClass("selected");
}
function InitTab(button_id)
{
	// Special handling for tab-panel-4.
	// In Internet Explorer 8, the contents of the iFrame do not render correctly when the parent div (tab-panel-4) is initially hidden,
	// which requires a complete reload of the iFrame contents as a workaround; not the best solution, but it works.
	if (button_id == 'tab-button-4' && !TAB_4_LOADED)
	{
		var iframe = document.getElementById('ctl00_tab_content_4_IFrame2');
		iframe.src = iframe.title;
		TAB_4_LOADED = true;
	}
}
function ShowTab(button_id)
{
	if (CUR_TAB != button_id)
	{
		var tab = parseInt(button_id.split("-")[2]);
		HideTabs();
		jQuery('#tab-button-'+tab).addClass("selected");
		jQuery('#tab-panel-'+tab).show().addClass("selected");
		InitTab(button_id);
		CUR_TAB = button_id;
		jQuery('#ctl00_GCTab').attr('value', tab);
	}
}
jQuery(document).ready(function () {
	if (window.location.href.indexOf("?cmspagemode=edit") == -1 && window.location.href.indexOf("&cmspagemode=edit") == -1)
	{
		HideTabs();
		
		// Determine how many buttons/tabs are being used and add event handlers
		var count = 0;
		var i;
		for (i = 1; i <= MAX_TABS; i++)
		{
			jQuery('#tab-button-'+i).click(function() { ShowTab(this.id); });
			count++;
		}
		
		// Add first/last classes to buttons/tabs
		jQuery('#tab-button-1').addClass("first");
		jQuery('#tab-button-'+count).addClass("last");
		jQuery('#tab-panel-1').addClass("first");
		jQuery('#tab-panel-'+count).addClass("last");
		
		// Tab can be preset via hidden form field (gctab) translated to ctl00_GCTab
		if (jQuery('#ctl00_GCTab').attr('value') != "")
		{
			var gctab = parseInt(jQuery('#ctl00_GCTab').attr('value'));
			if (1 <= gctab && gctab <= MAX_TABS)
			{
				ShowTab('tab-button-'+gctab);
			}
		}
		else if (CUR_TAB == null && count > 0)
		{
			ShowTab('tab-button-1');
		}
	}
});
