on_click('header-links-logout', _log_out);

function _log_out(e) {

    delete_cookie('PREF');
    window.location = '/index.html';
}


// Load the features using the settings API.
var tabs = null;
var result = ajax("settings", "get", {"name": "home_page_tabs"});
if (result.status) {
    tabs = result.output;
} else {
    alert("Could not download critical site data.");
}

var panes = {};

function activate(tab) {

    if (tab == current_tab) {
        return;
    }

    if (tabs.length > 1) {
        if (current_tab) {
            set_class(current_tab, 'tab inactive');
        }

        set_class(tab, 'tab active');
    }

    if (current_tab) {
        hide(panes[current_tab]);
    }

    show(panes[tab]);
    current_tab = tab;
}


function tab_click_handler(e) {

    if (!e) var e = window.event;

    var el = e.target || e.srcElement;
    var tab = el.id;

    activate(tab);
}


function render_panes() {

    var content = document.getElementById('content');
    // TODO: 'create' is ambiguous. Rename it to create_element or something.
    var table = create('table', null, {'width': '100%', 'border': '0', 'cellspacing': '0'});
    var row = create('tr');

    for (var i=0; i < tabs.length; i++) {

        var tab = tabs[i];
        var td = create('td', tab.title, {'class': 'tab inactive', 'id': tab.name});
        on_click(td, tab_click_handler);
        row.appendChild(td);
    }

    row.appendChild(create('td', '\u00a0', {'class': 'tab empty'}));
    table.appendChild(row);
    content.appendChild(table);

    for (var i=0; i < tabs.length; ++i) {

        var tab = tabs[i];
        var iframe = create('iframe', null, {'class': 'pane', 'id': 'pane', 'src': tab.url});
        panes[tab.name] = iframe;
        hide(iframe);
        content.appendChild(iframe);
    }
}


// TODO: The currently active tab should be read from the cookie.
var current_tab = null;
render_panes();
activate(tabs[0].name);
