var debug = false;
var currentPage;

$(document).ready(function () {
    $(window).bind('hashchange', function (e) {
        if (window.location.hash.substr(1) === currentPage)
            return;

        initializeTabs();
    });

    initializeStartsWith();

    $('.tabs-container:not(.tabs-normal)').on('click', 'a', function (e) {
        interceptLinksForAjaxTabs(e, $(this));
    });

    handler = function (e) {
        e.preventDefault();

        var container = $(this).closest(".tabs-container:not(.tabs-normal)").find(".tab-content .tab-pane .panel-body");
        var formData = $(this).serialize();
        if (debug) {
            console.log(formData);
        }

        var tabsReturnMethod = $("#TabsReturnMethod").val();
        container.html("<div class='ibox'><div class='ibox-content'><div class='text-center tabs-loading'><i class='fa fa-spinner fa-spin fa-3x'></i></div></div></div>");
        $.post($(this).attr('action'), formData, function (data) {
            container.html(data);
            initializeTabs(container);

            if (container.find("form").length > 0 && container.find("form").attr("action")) {
                var methodName = splitUrlToMethodName(container.find("form").attr('action'));
                runMethod(methodName);
            } else if (tabsReturnMethod && tabsReturnMethod.length > 0) {
                runMethod(tabsReturnMethod);
            } else {
                var activeTabs = $(".nav-tabs .active a");
                $(activeTabs[activeTabs.length - 1]).trigger('click');
            }
        });
    };

    $('.tabs-container:not(.tabs-normal)').on('submit', 'form:not(.tab-ignore)', handler);
    $(document.body).on('click', '.nav-tabs a', function (e) {
        if ($(this).hasClass("allow-redirect") || $(this).hasClass("local-tab"))
            return;

        var url = $(this).attr('data-href');
        var methodName = $(this).attr('data-method');
        var initialParameters = $(this).attr('data-initial-parameters');

        if (initialParameters !== '') {
            $(this).attr('data-initial-parameters', '');
            url = url + "?" + initialParameters;
        }

        var container = $(this).closest(".tabs-container:not(.tabs-normal)").find(".tab-content .tab-pane .panel-body");
        var tabName = $(this).html();

        $(".page-heading .breadcrumb li:last-child").html(tabName);
        displayContentInTab(url, methodName, container);
        setAnchorLinks($(this).attr("data-name"));
    });

    initializeTabs();
});

function initializeTabs($element) {
    if (!$element) {
        $element = $("body");
    }

    var activeTab;
    var anchor = window.location.hash.substr(1);

    if (!$element.is('body') || anchor === "") {
        activeTab = $element.find(".tabs-container:not(.tabs-normal) .nav-tabs .active a");
    }
    else {
        activeTab = $element.find(".tabs-container:not(.tabs-normal) .nav-tabs a[data-name='" + anchor +"']");
    }

    if (activeTab) {
        activeTab.trigger("click");
    }
}

function displayContentInTab(url, methodName, container) {
    container.html("<div class='ibox'><div class='ibox-content'><div class='text-center tabs-loading'><i class='fa fa-spinner fa-spin fa-3x'></i></div></div></div>");

    if (debug) {
        console.log(methodName);
    }

    $.get(url, function (data) {
        container.html(data).promise().done(function () {
            initializeTabs(container);
            runMethod(methodName);
        });
    }).fail(function () {
        container.html("<div class='ibox'><div class='ibox-content'><div class='text-danger text-center'>Napaka!</div></div></div>");
    });
}

function interceptLinksForAjaxTabs(e, $element) {
    if ($element.attr("data-toggle") === "tab" || $element.hasClass("allow-redirect") || $element.hasClass('paginate_button ') || $element.attr("href").startsWith("javascript:") || $element.attr("href").startsWith("#")) {
        return;
    }

    e.stopPropagation();
    e.stopImmediatePropagation();
    e.preventDefault ? e.preventDefault() : e.returnValue = false;

    if (debug) {
        console.log("Redirect", $element.attr("href"));
    }

    var container = $element.closest('.panel-body');
    if ($element.hasClass('display-parent-tab')) {
        container = container.closest('.tabs-container:not(.tabs-normal)').closest('.panel-body');
    }

    displayContentInTab($element.attr("href"), $element.attr("data-method"), container);
    setAnchorLinks($element.attr("data-name"));

    return false;
}

function initializeStartsWith() {
    if (!String.prototype.startsWith) {
        String.prototype.startsWith = function (searchString, position) {
            position = position || 0;
            return this.indexOf(searchString, position) === position;
        };
    }
}

function splitUrlToMethodName(url) {
    var urlParts = url ? url.split('/') : [];
    var urlLastParts = urlParts.length > 0 ? urlParts[urlParts.length - 1].split('?') : "";
    return "initialize" + (urlParts.length > 1 ? urlParts[urlParts.length - 2] : "") + urlLastParts[0];
}

function runMethod(methodName) {
    if (typeof window[methodName] === "function") {
        window[methodName]();
        if (debug) {
            console.log(methodName, "exists");
        }
    }
}

function setAnchorLinks(anchor) {
    if (!anchor) {
        return;
    }

    currentPage = anchor;
    window.location.hash = '#' + anchor;
}