/*jslint browser: true, nomen: true,  white: true */
/* global jQuery, $ */
jQuery(function($) {
"use strict";

    function setupTab() {
        // if we have one form with many div tabs within it - eg profile page
        if ($('.pieform.jstabs .pieform-fieldset').length) {
            setupTabContext($('.pieform.jstabs .pieform-fieldset').parent(), '.pieform.jstabs', true);
        }
        // if we have many forms each in their own div/tab - eg user bulk actions
        if ($('.bulk.jstabs').length) {
            setupTabContext($('.bulk.jstabs .tabcontent'), '.bulk.jstabs', false);
        }
    }

    function setupTabContext(tabcontent,ident,createmenu) {

        var i,
            id,
            listitem,
            heading,
            activetab,
            fsParam;

        if (createmenu) {
            $(ident).prepend('<ul class="nav nav-tabs" role="tablist"></ul>');
        }
        mahara.tabnav = $(ident).find('.nav-tabs');

        // Remove class collasped that has been generated by pieform
        if ($(ident + ' .pieform-fieldset').length) {
            $(ident + ' .pieform-fieldset').removeClass('collapsed');
        }
        tabcontent.removeClass('collapsed');
        // Add div and bootstrap class on tabcontent to show and hide
        tabcontent.addClass('tab-pane').attr('role', 'tabpanel').wrapAll('<div class="tab-content">');

        // Set up tab navigation
        for (i = 0; i < tabcontent.length; i = i + 1) {
            // get id and title from div (tabcontent)
            id = $(tabcontent[i]).attr('id');
            heading = $(tabcontent[i]).find('legend').first().text();

            // if the tab-pane isn't hidden
            if (!$(tabcontent[i]).hasClass('d-none')) {
                listitem = '<li role="presentation" aria-hidden="true">' +
                    '<a href="#'+id+'" role="tab" data-bs-toggle="tab" aria-controls="'+id+'" aria-expanded="false">'+heading+'</a>' +
                '</li>';
                mahara.tabnav.append(listitem);
            }
        }
        // first tab to be the active one by default
        activetab = mahara.tabnav.find('li:first-child a');

        // check url params to see what tab to activate
        fsParam = getUrlParameter('fs');
        if (typeof(fsParam) != 'undefined' && fsParam) {
            var targettab = mahara.tabnav.find('li a[href="#profileform_' + fsParam + '_container"]');
            if (typeof(targettab) != 'undefined' && targettab.length) {
                activetab = targettab;
            }
        }
        // set tab active
        saveTab(activetab[0]);

        if ($(mahara.tabnav.find('li:first-child a').attr('href')).find('.requiredmarker').length) {
            // show 'required' header message
            mahara.tabnav.closest('form').find('.requiredmarkerdesc').removeClass('d-none');
        }
        else {
            // hide 'required' header message
            mahara.tabnav.closest('form').find('.requiredmarkerdesc').addClass('d-none');
        }
        // Store current tab on change
        $('a[data-bs-toggle="tab"]').on('shown.bs.tab', function(e){
            if ($($(e.target).attr('href')).find('.requiredmarker').length) {
                // show 'required' header message
                $(e.target).closest('form').find('.requiredmarkerdesc').removeClass('d-none');
            }
            else {
                // hide 'required' header message
                $(e.target).closest('form').find('.requiredmarkerdesc').addClass('d-none');
            }
            saveTab(e.target);
        });
    }

    /*
     * Check that the stored location matches our current location
     * then attempt to load saved tab state
     */
    function checkSavedTab() {
        var currentPath =  window.location.pathname,
            stateObject = JSON.parse(sessionStorage.getItem('StateObject'));

        if(stateObject === null || stateObject.url === undefined){
            return;
        }

        if(currentPath === stateObject.url) {
            restoreTab();
        }
    }

    /*
     * Restore any tab state stored in sessionStorage
     */
    function restoreTab() {
        var stateObject = JSON.parse(sessionStorage.getItem('StateObject')),
            storedTabId = stateObject.tabID,
            currentTab = mahara.tabnav.find('a[href^="'+ storedTabId +'"]');

        if(currentTab.length > 0){
            currentTab.tab('show');
        }
    }

    /*
     * Store the current active tab in session Storage
     * @param e | Event
     */
    function saveTab(target) {

        var currentTabId = $(target).attr('href'),
            stateObject = {
                tabID: currentTabId,
                url: window.location.pathname
            };

        sessionStorage.setItem('StateObject', JSON.stringify(stateObject));
    }

    var mahara = {};

    setupTab();
    checkSavedTab();

});
