﻿Agility.RegisterNamespace("CleanEating.Controls");

(function () {

    var Tabs = CleanEating.Controls.Tabs = function (containerID) {
        this._containerID = containerID;
        this._tabPointerID = containerID + "_TabPointer";
        this._onSelectedEvents = [];
    };

    Tabs.prototype._getTabs = function () {
        return $("#" + this._containerID + " li").not(".Separator");
    };

    Tabs.prototype._getTab = function (index) {
        return this._getTabs().eq(index);
    };

    Tabs.prototype._getTabPointer = function () {
        return $("#" + this._tabPointerID);
    };

    Tabs.prototype.init = function () {
        var tabControl = this,
            container = $("#" + this._containerID),
            tabs = this._getTabs();
        if (tabs.length > 0) {
            container.addClass("CleanEatingTabs");
            this._initTabPointer();
            tabs.each(function (index) {
                tabControl._initTab(tabControl, $(this), index);
            });
            this._selectTab(0);
        }
    };

    Tabs.prototype._initTab = function (tabControl, tab, index) {
        if (index > 0) {
            tab.before("<li class=\"Separator\">|</li>");
        }
        tab.find("a").each(function () {
            $(this).data("url", $(this).attr("href"));
            $(this).click(function () {
                tabControl._selectTab(index);
            });
        });
    };

    Tabs.prototype._initTabPointer = function () {
        var container = $("#" + this._containerID);

        container.append("<div id=\"" + this._tabPointerID + "\" class=\"TabPointer\"></div>");
    };

    Tabs.prototype._selectTab = function (index) {
        var tab = this._getTab(index);
        
        this._resetTabs();

        tab.addClass("Selected");
        tab.find("a").each(function () {
            $(this).removeAttr("href");
        });
        this._moveTabPointerTo(tab);
        if (this._onSelectedEvents[index]) {
            this._onSelectedEvents[index]();
        }
    };

    Tabs.prototype._resetTabs = function () {
        this._getTabs().each(function () {
            var tab = $(this);
            tab.removeClass("Selected");
            tab.find("a").each(function () {
                var link = $(this);
                link.attr("href", link.data("url"));
            });
        });
    };

    Tabs.prototype._moveTabPointerTo = function (tab) {
        var offset = tab.offset(),
			position = tab.position(),
            pointer = this._getTabPointer();
        pointer.css({
            top: tab.outerHeight() + 3,
            left: position.left + tab.outerWidth() / 2 - pointer.width() / 2
        });
    };

    Tabs.prototype.onTabSelected = function (index, fnOnSelected) {
        this._onSelectedEvents[index] = fnOnSelected;
    };

}());
