/*General String repeat function
 * 
 * 'test'.repeat(2) returns 'testtest'
 */
String.prototype.repeat = function( num )
{
    return new Array( num + 1 ).join( this );
}



/***
 * General function for tabs
 * http://jqueryfordesigners.com/jquery-tabs/
 * http://benalman.com/code/projects/jquery-bbq/
 * 
 * TODO: rewrite so no double: click-function > url changes > onhashchange-function
 */

$(document).ready(function () {
	
	// Define the onclick event
    $('.tabs ul.tabNavigation a').click(function ()
    {
    	// Search for parent tabContainer
    	var strDepth = $(this).parents('div[class$*="tabDepth_"]').attr('class');
    	var strStart = strDepth.indexOf('tabDepth_');
    	var depth 	 = parseInt( strDepth.substring(strStart+9, strStart+10) );
    	
    	//Hide others
    	$('.tabs '.repeat(depth) + '> div.tabContent').hide();
    	
    	//Show item
    	var url = this.hash;
    	
    	if (this.hash.indexOf('/') > -1)
    	{
    		var tabLevels = this.hash.split('/');
    		url = '#'+tabLevels[ tabLevels.length - 1 ];
    	}
    	
    	$('.tabs '.repeat(depth) + '> div.tabContent').filter(url+'Content').show();
    	
        //Set active
        $('.tabs '.repeat(depth) + 'ul.tabNavigation li').removeClass('active');
        $(this).parent().addClass('active');
        
        //Check for sub-tabs, if so: fire first
        if ($('.tabs '.repeat(depth) + url+'Content' + ' .tabs').length)
        	$('.tabs '.repeat(depth) + url+'Content' + ' .tabs .tabNavigation a:first').click();
    });
    
    // The haschange event is fired when history changes
    $(window).bind('hashchange', function(e)
    {
    	// Get the URL after the #
    	var url = $.param.fragment();
    	if (url.length > 0)
    	{
	    	// Split into levels
	    	var tabLevels = url.split('/');
	    	if (tabLevels.length == 0)
	    		tabLevels[0] = url;
			
	    	// Click all levels
			for (var i=0; i<tabLevels.length; i++)
			{
				var item = '.tabs '.repeat(i+1) + '.tabNavigation a[href="'+ tabBaseAnchor;
				for (var j=0; j<i; j++)
					item += tabLevels[j]+'/';
				item += tabLevels[i] +'"]';
								
				// Click tab if valid, or click the first
				if ($(item).length)
				    $(item).click();
				else
				    $('.tabs '.repeat(i+1) + '.tabNavigation a:first').click();
			}
    	}
    	// Default is the first tab
    	else
    		$('.tabs .tabNavigation a:first').click();
    });
    
    // Trigger the event the first time
    $(window).trigger('hashchange');
});

