gfi.tabs.ajax = new Class ({
    Extends: gfi.tabs,

    // override parent and make a request object
    initialize: function(tabs, tabAreas, tabItems, options) {
        this.tabItems = tabItems;
        this.request = new Request.HTML({
            evalScripts: false,
            evalResponse: true,
            link: 'cancel',
            onSuccess: this.contentRequestComplete.bind(this)
        });
        return this.parent(tabs, tabAreas, options);
    },

    // override parent check to see if the tab has any content if not then make the ajax call
    showArea: function(tabIndex) {
        // first tab is loaded in the JSP not by AJAX
        if (tabIndex == 0) {
            this.tabAreas[tabIndex].loaded = true;
        }
        if (!this.tabAreas[tabIndex].loaded) {
            this.currentRequestTabIndex = tabIndex;
            this.getContent(tabIndex);
        } else {
            this.parent(tabIndex);
        }
    },

    getContent: function(tabIndex) {
        this.request.setOptions({url: this.tabItems[tabIndex].url});
        // first tab isn't loaded by ajax
        if (tabIndex == 0) {
            this.contentRequestComplete('', '', '', '');
        } else {
            this.request.send();
        }
    },

    contentRequestComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
        if (this.currentRequestTabIndex !== undefined) {
            this.tabAreas[this.currentRequestTabIndex].adopt(responseTree);
            // need to eval the js after the responseTree has been adopted, otherwise we don't have access to the
            // elements from the response
            Browser.exec(responseJavaScript);
            this.tabAreas[this.currentRequestTabIndex].loaded = true;
            this.showArea(this.currentRequestTabIndex);
            this.tabItems[this.currentRequestTabIndex].onSuccess();
        }
    }
});

gfi.tabs.ajax.TabItem = new Class ({
    initialize: function (url, onSuccess) {
        this.url = url;
        this.onSuccess = onSuccess;
        this.loaded = false;
    }
});
