$(function() {
    buildTabMenu();
});

/**
 * Build the tab menu  */
function buildTabMenu(){
   var tabs = '';
   $('#centrecolumn .tab-content').each( function(){
        var tabId = $(this).attr('id');
        var tabTitle =  $(this).find('h2:first').text();
        tabs += '<li><a href="#'+tabId+'">'+tabTitle+'</a></li>';
   });

    $('#tab-controls').append('<ul>'+tabs+'</ul>');
    $('#tab-controls a').click( tabClick );

    setInitialTab();
}


/**
 * Returns anchor (without octothorpe) */
function  findAnchor(){
    var url = document.location.toString();
    if( url.match('#') ){
        return url.split('#')[1];
    } else {
        return false;
    }
}


/**
 * Hide things on page load */
function setInitialTab(){

    var anchor = findAnchor();

    // hide the first h2 and then hide all the content
    $('#centrecolumn .tab-content h2:first-child').not('.tab-content-right h2').hide().parent().hide();

    if( anchor != false && $('#'+anchor).hasClass('tab-content') ){
        $('#'+anchor).show();
        $('#tab-controls a[href$="#'+anchor+'"]').parent().addClass('selected');
    } else {
        // first tab is visible and selected by default
        $('#centrecolumn .tab-content:first').show();
        $('#tab-controls li:first').addClass('selected');
    }
}


/**
 * Click on an <a> tag in a tab. */
function tabClick(e){

    $('#centrecolumn .tab-content').hide(); // hide all tabs
    $('#tab-controls li').removeClass(); // deselect any tab

    var idOfContent = '#'+$(this).attr('href').split('#')[1]; // note: hash tag links ie return the full url.
    $( idOfContent ).show(); // show the tab the user clicked on
    $(this).parent().addClass('selected'); // select the tab the user clicked on

    return false;
}
