var tab_rewriting = new Array();
var search_clicked = new Array();

function tab_init(tabbar_id)
{
	$$('ul#' + tabbar_id + '_tabbar li').each(function(element, i)
	{
		var content_idx = element.readAttribute('content_idx');
		var ajax_subtab = element.readAttribute('ajax_subtab');
		var hasHref = false;
		if(typeof(element.childNodes[0].href) != 'undefined')
		{
			hasHref = (element.childNodes[0].href != '' 
						? (element.childNodes[0].href.substr(0,18).toLowerCase() == 'javascript:void(0)' ? false : true)
						: false);
		}
		
		// setup click listeners for tabs that aren't already clickable links
		if((content_idx != null && !hasHref) || ajax_subtab == "true")
		{
			$(element).observe('click', tab_tabClick);
		}
	});
	
	$$('div#' + tabbar_id + '_subtab_area span','div#' + tabbar_id + '_subtab_area div.subtab a').each(function(element, i)
	{
		var content_idx = element.getAttribute('content_idx');
		if(content_idx != null)
		{
			$(element).observe('click', tab_tabClick);
		}
	});

	$$('.tabSearchBox').each(function(element, i)
	{
		element.observe('click', searchFocus);
		element.observe('keydown', handleSearchButtonClick);
		search_clicked[element.readAttribute('idx')] = false;
	});
}

function getSelectedTab(tabbar_id)
{
	var selectedMainTab = $$('#' + tabbar_id + '_tabbar .selected')[0];
	var subTabIndex = selectedMainTab.readAttribute('subtab_idx');
	var selectedSubTab;
	if(subTabIndex !== null)
	{
		selectedSubTab = ':' + $$('#' + tabbar_id + '_subtab_' + subTabIndex + ' .selected')[0].id;
	}
	
	return selectedMainTab.id + selectedSubTab;
}

function searchFocus(e)
{
	var searchId = e.target.readAttribute('idx');
	if(!search_clicked[searchId])
	{
		e.target.value = "";
		e.target.className = "tabSearchBox focus";
		search_clicked[searchId] = true;
	}
}

function handleSearchButtonClick(e)
{
	if(e.keyCode == Event.KEY_RETURN)
	{
		var searchId = e.target.readAttribute('idx');
		$('tabSearchBtn_' + searchId)["click"]();
		e.stop();
	}
}

function tab_tabClick(event)
{
	var e = $(Event.element(event));

// TODO we need to figure out which tabbar clicked us
	var tabbar_id = e.parentNode.parentNode.parentNode.id;

	tab_tabClickByElement(e, tabbar_id);
}

function tab_tabClickByElement(e, tabbar_id, wasClicked)
{
	if(typeof(wasClicked) == 'undefined')
	{
		wasClicked = true;
	}
	
	e = $(e);
	var original_elem = e;

	/* firing all switchouts before selected class is cleared */
	$$(	'ul#' + tabbar_id + '_tabbar li .selected', '#' + tabbar_id + ' .subtab.selected a.selected').each(function(element, i)
	{
		if (element.tagName.toLowerCase() == 'a')
		{
			$(element).fire('tab:switchout');
		}
	});
	
	e = tab_tabSwitch(e,tabbar_id);
	
	/* firing all switchins after selected class is set/reset */
	$$(	'ul#' + tabbar_id + '_tabbar li .selected', '#' + tabbar_id + ' .subtab.selected a.selected').each(function(element, i)
	{
		if (element.tagName.toLowerCase() == 'a')
		{
			$(element).fire('tab:switchin');
		}
	});

	/* show content div */
	var content_idx = e.readAttribute('content_idx');
	if(content_idx != null)
	{
		var content = $(tabbar_id + '_content_' + content_idx);
		var ajax_url = original_elem.readAttribute('ajax');
		var content_loaded = original_elem.readAttribute('contentloaded');
		if(ajax_url !== null && content_loaded != '1')
		{
			// check if the page has already been loaded (and reload != always)
			content.innerHTML = '<img src=\"/shared/images/others/loading.gif\"> Loading...';
			var d = new Date();
			var timestring = d.toString();

			if(!wasClicked)
			{
				// wasn't clicked, we must be loading the page directly from a url
				// add any additional params provided
				var additionalParams = null;
				var anchors = location.hash.substr(1).split('|');
				for(i=0; i<anchors.length; i++)
				{
					var tab = anchors[i].split('+')[0];
					if(tabbar_id + "_tabitem_" + tab.split(':')[1] == e.id)
					{
						additionalParams = anchors[i].split('+')[1];
					}
				}
				
				if(additionalParams != null)
				{
					ajax_url += unescape(additionalParams);
				}
			}
			
			var glue = ajax_url.indexOf('?') !== -1 ? '&' : '?';
			ajax_loaded = new Ajax.Request(ajax_url + glue + d.getTime(),
			{
				evalScripts: true,
			    method:'post',
			    parameters: { __Cache_Buster__ : timestring },
			    onSuccess: function(transport)
			    {
					if(content_loaded != '-1')
					{
						original_elem.writeAttribute('contentloaded', '1');
					}
					Element.update(content, transport.responseText);
					$(content).fire('tab:bodyloaded');
			    },
			    
			    onFailure: function()
			    {
			    	content.innerHTML = 'Could not load contents, please try again later.';
			    }
			});
		}
		
		content.addClassName('selected');
	}

	if(wasClicked)// only mess with the url hash if we've actually clicked a tab
	{
		setHashLocation(tabbar_id, content_idx);
	}
	
	if(e.readAttribute('ajax_subtab') == 'true')
	{
		var subtab_idx = e.readAttribute('subtab_idx');
		tab_tabClickByElement($(tabbar_id+'_subtab_'+subtab_idx).down('a'), tabbar_id);
	}
	tab_linkRewriter(tabbar_id);
	if(e.tagName.toLowerCase() == 'a' || e.readAttribute('ajax_subtab') != 'true')
	{
		$(e).fire('tab:switchdone');
	}
}

/* REVIEW: make this take aliases and smoothly handle both parent tabs and subtabs with aliases*/
function tab_tabSwitch(e,tabbar_id)
{
	/* clear menu selection */
	$$(	'ul#' + tabbar_id + '_tabbar .selected', 
		'#' + tabbar_id + '_subtab_area div.subtab.selected',
		'#' + tabbar_id + '_subtab_area * .selected',
		'div#' + tabbar_id + '_content_area div.tab_content.' + tabbar_id + '.selected').each(function(element, i)
	{
		$(element).removeClassName('selected');
	});

	var main_tab_idx = 0;
	e.addClassName('selected');
	
	/* is e a main tab? */
	if(e.parentNode.tagName.toLowerCase() == 'li')
	{
		e = e.parentNode;
		/* yes, does tab have a subtab? */
		var subtab_idx = e.readAttribute('subtab_idx');
		if(subtab_idx != null)
		{
			/* yes, show subtab */
			$(tabbar_id + '_subtab_' + subtab_idx).addClassName('selected');
			$$('div#' + tabbar_id + '_subtab_' + subtab_idx + ' span').each(function(element,i)
			{
				var attr = $(element).readAttribute('content_idx');
				if(attr == e.readAttribute('content_idx'))
				{
					$(element).addClassName('selected');
				}
			});
		}
	}
	else
	{
		/* no, show wrapping tab & select main tab */
		var subtab = $(e.parentNode.id);
		subtab.addClassName('selected');
		
		var main_tab_idx = subtab.readAttribute('tab_idx');
		if(main_tab_idx != null)
		{
			$$('div#' + tabbar_id + ' ul.tabbar li').each(function(element,i)
			{
				if(i == main_tab_idx)
				{
					$(element).addClassName('selected');
				}
			});
		}
	}
	
	e.addClassName('selected');
	return e;
}


function tab_linkRewriter(tabbar_id)
{
	//TODO check if link rewriting is enabled for this tabbar...
	if(tab_rewriting[tabbar_id] == false)
	{
		return;
	}

	$$("#" + tabbar_id + " div.content_area div.tab_content.selected").each(function(element,i)
	{
		element = $(element);
		if(element != null)
		{
			var a_list = element.getElementsByTagName('a');
			for(i=0; i < a_list.length; i++)
			{
				if($(a_list[i]).hasClassName('no_rewrite_links'))
				{
					// Skip links tagged with no-rewrite
					continue;
				}
				
				/* FIXME filter out any links navigating away from this page */ 
				var tmp = a_list[i].href;
				if(tmp != '' && tmp.substr(0,11).toLowerCase() != 'javascript:')
				{
					var hashIdx = tmp.indexOf('#');
					if(hashIdx >= 0)
					{
						tmp = tmp.substring(0, hashIdx);
					}
					
					a_list[i].href = tmp + location.hash;
				}
			}
			
			/* FIXME we need re-write the urls for self submitting forms too */
		}
	});
}


function tab_selectInitialTab(tabbar_id)
{
	var tabSelected = false;
	if(location.hash.length > 1)
	{
		var anchors = location.hash.substr(1).split('|');
		for(i=0; i<anchors.length; i++)
		{
			var tab = anchors[i].split('+')[0];
			var additionalParams = anchors[i].split('+')[1];
			var a = tab.split(':');
			
			// THIS IS A HACK! TEMPORARILY REDIRECTING OLD HEALTHTRACKER BOOKMARKS
			if(a[0] == 'main_tab' && tabbar_id == 'ht_main')
			{
				a[0] = 'ht_main';
				location.hash = location.hash.replace(/main_tab:/,"");
			}
			
			if(a.length == 2 && a[0] == tabbar_id)
			{
				var e = $($$('#' + tabbar_id + '_tab_' + a[1] + ' a').first());
				if(e == null)
				{
					/* couldn't find a main tab with that index, try the subtabs */
					e = $(tabbar_id + '_tabitem_' + a[1]);
				}
				
				if(e != null)
				{
					if(e.readAttribute('href') != null && e.readAttribute('href').substr(0,11).toLowerCase() != 'javascript:' && additionalParams != null)
					{
						e.writeAttribute('href',e.readAttribute('href')+unescape(additionalParams));
					}
					
					tab_tabClickByElement(e, tabbar_id, false);
					tabSelected = true;
				}
				else if(!isNaN(new Number(a[1]))) // it is likely that they are trying to access an aliased tab using a tab number; find the element with the corresponding 'idx' attribute
				{
					$$('ul#'+tabbar_id+'_tabbar li').each(function(elem){
						if($(elem).readAttribute('idx') == a[1])
						{
							e = $($(elem).down('a'));
						}
					});
					
					$$('div#'+tabbar_id+'_subtab_area div.subtab a').each(function(elem){
						if($(elem).readAttribute('idx') == a[1])
						{
							e = $(elem);
						}
					});
					
					if(e != null)
					{
						tab_tabClickByElement(e, tabbar_id);
						tabSelected = true;
					}
				}
			}
		}
		if(tabSelected)
		{
			tab_linkRewriter(tabbar_id);
		}
	}
	
	if(!tabSelected)
	{
		// 'click' the selected tab so that ajax loading can occur (if necessary)
		var element = $$('ul#' + tabbar_id + '_tabbar li.selected a')[0];
		var subtab_elements = $$('div#' + tabbar_id + '_subtab_area div.selected');
		var subtab_element = null; 
		if(subtab_elements.length > 0)
		{
			subtab_element = subtab_elements[0].down('a');
		}
		if(element.hasAttribute('ajax'))
		{
			tab_tabClickByElement(element, tabbar_id);
		}
		else if(subtab_element != null && subtab_element.hasAttribute('ajax'))
		{
			tab_tabClickByElement(subtab_element, tabbar_id);
		}
	}
}


/************** Ajax Tab Functions **************/

function overwriteTab(ajax_url,content)
{
	content = $(content);
	content.innerHTML = '<img src=\"/shared/images/others/loading.gif\"> Loading...';
	var d = new Date();
	var glue = ajax_url.indexOf('?') !== -1 ? '&' : '?';
	content.addClassName('selected');
	
	ajax_loaded = new Ajax.Request(ajax_url + glue + d.getTime(),
	{
		evalScripts: true,
	    method:'get',
	    onSuccess: function(transport)
	    {
			content.update(transport.responseText);
			content.fire('tab:bodyloaded');
	    },
	    
	    onFailure: function()
	    {
	    	content.innerHTML = 'Could not load contents, please try again later.';
	    }
	});
}


function setHashLocation(tabbar_id, content_idx)
{
	var newhash = '';
	var additionalParams = '';
	var anchors = location.hash.substr(1).split('|');
	for(i=0; i<anchors.length; i++)
	{
		var tabparts = anchors[i].split('+');
		var a = tabparts[0].split(':');
		if(a.length == 2 && a[0] != tabbar_id)
		{
			// multiple tab bars on 1 page. don't lose additional params for the tab bar that's not being changed
			newhash = newhash + a[0] + ':' + parseInt(a[1]) + (tabparts[1] != null ? '+'+tabparts[1] : '') + '|';
		}
	}
	newhash = newhash + tabbar_id + ':' + content_idx + additionalParams;
	
	location.hash = newhash;
}


function getHashParams(tabbar_id)
{
	var hashParams = {};
	
	var hash = location.hash.substring(1);
	var tabs = hash.split('|');
	var tabparts;
	
	for (var i = 0; i < tabs.length; i++)
	{
		tabparts = tabs[i].split('+');
		
		//find the correct tab
		if(tabparts[0].indexOf(tabbar_id) !== -1)
		{
			if(tabparts[1] != null)
			{
				var paramParts = tabparts[1].split('/');
				for (var k = 0; k < paramParts.length; k++)
				{
					var paramName = paramParts[k].split(',')[0];
					var paramVal = paramParts[k].split(',')[1];
					
					hashParams[paramName] = paramVal;
				}
			}
			break;
		}
	}
	
	return hashParams;
}


function setHashParams(tabbar_id,hashParams)
{
	var hash = location.hash.substring(1);
	var tabs = hash.split('|');
	var tabparts;
	
	for (var i = 0; i < tabs.length; i++)
	{
		tabparts = tabs[i].split('+');
		
		//find the correct tab
		if(tabparts[0].indexOf(tabbar_id) !== -1)
		{
			var paramParts = new Array();
			var k = 0;
			for (var paramName in hashParams)
			{
				if(paramName != "" && paramName != null && hashParams[paramName] != null)
				{
					paramParts[k] = paramName + ',' + hashParams[paramName];
					k++;
				}
			}
			
			tabs[i] = tabparts[0] + (paramParts.length > 0 ? '+' + paramParts.join('/') + '/' : '');
			break;
		}
	}
	
	location.hash = tabs.join('|');
}


function getSelectedTabAlias(tabbar_id, include_parent)
{
	var hash = location.hash.substring(1);
	var tabs = hash.split('|');
	var tabparts;
	var parentId = '';
	
	for (var i = 0; i < tabs.length; i++)
	{
		tabparts = tabs[i].split('+');
		
		//find the correct tab
		if(tabparts[0].indexOf(tabbar_id) !== -1)
		{
			var tabAlias = tabparts[0].split(':')[1];
			if(typeof include_parent != 'undefined' && include_parent == true)
			{
				parentId = getParentTabAlias(tabbar_id);
				if(parentId != tabAlias) // if parentID == tabAlias, we've found the same tab
				{
					tabAlias = parentId + ":" + tabAlias;
				}
				return tabAlias;
			}
			else
			{
				return tabAlias;
			}
		}
	}
	
	return null;
}


function getParentTabAlias(tabbar_id)
{
	var parentId = '';

	$$('#' + tabbar_id + '_tabbar li.selected').each(function(elem)
			{
				// should only get one of these...
				parentId = elem.id;
			});
	parentId = parentId.substring(tabbar_id.length+5);
	
	return parentId;
}

function clearHash(tabbar_id)
{
	var hashParams = {};
	setHashParams(tabbar_id,hashParams);
}