/*  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Script: page-control.js     | Version: 5.2
    Author: DNC Thomas          | February 2026
    Last edit: 
    -------------------------------------------
    Function:   Utility for all pages.
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

//  Edit this script at your peril - you break it - you fix it

//Configure the name for session Storage
var tmp = location.pathname;
var owsStore = tmp.split('/');
owsStore.pop();
owsStore.shift();
owsStore = owsStore.join('~') + '~apwSession';
console.log('Session storage variable: ' + owsStore);

function setTheme( theme ) {
    //var theme = cmxConfig.Custom.Theme;
    if( theme != '' ) {
        $('#Theme').after('<link rel="stylesheet" href="css/themes/' + theme + '.css">');
        console.log("Setting theme to " + cmxConfig.Custom.Theme);
    }
}

function setLogo( logo ) {
    //var logo = cmxConfig.Custom.Logo;
    switch( logo ) {
        case '' : $('#siteLogo').attr('src', 'images/logo.png'); break;
        case 'None':    $('#siteLogo').css('display', 'none');  break;
        default:    
            $('#siteLogo').attr('src', reqLogo);
            //  This should be changed to describe your site
            $('#siteLogo').attr('alt','User supplied logo');
    }
}

function setBannerImage( head ) {
    var img = head.BannerImage;
    var pos = head.BannerPosition || 'center center';
    if( img != '') {
        $('#pageHead').css('background', 'url(' + img + ') repeat-x ' + pos);
        console.log("Banner image is " + head.BannerImage + ' positioned ' + head.BannerPosition)
    }
}

function setPageGeometry( geometry ) {
    var headHeight = $('#pageHead').outerHeight();
    var footHeight = $('#pageFoot').outerHeight();
    $('#pageContent').css('padding-top', geometry.PaddingTop + geometry.Units );
    $('#pageContent').css('padding-bottom', geometry.PaddingBottom + geometry.Units );

    // Head & Foot
    if( geometry.StaticHead ) {
        //  Static Header requested
        $('#pageHead').css({'position': 'fixed', 'top': 0 });
        $('#pageContent').css('margin-top', headHeight + 'px') ;
    } else {
        $('pageHead').css( {'position': 'relative', 'top': ''});
        $('#pageContent').css('margin-top', '0px');
    }
    if( geometry.StaticFoot && $(window).height() > 600 ) {
        //  Static Footer requested
        $('#pageFoot').css( {'position': 'fixed', 'bottom': 0});
        $('#pageContent').css( 'margin-bottom', footHeight + 'px');
        var contentHeight = $(window).height() - (headHeight + footHeight);
        $('#pageContent').css('height', contentHeight + 'px');
        // Check if gull need to be reset
        if( $('#subContent').height() > contentHeight) {
            $('#Gull-body').css({'position': 'fixed', 'bottom': footHeight + 'px'})
        } else {
            $('#Gull-body').css({'position': 'absolute', 'bottom': 0});
        }
    } else {
        $('#pageFoot').css( {'position': 'unset', 'bottom': ''});
        $('#Gull-body').css({'position': 'absolute', 'bottom': 0});
        $('#pageContent').css('margin-bottom', '');
    }
    $('[data-owsData="Version"]').html('<span class="w3-small">V&nbsp;5.01</span>')
}

function setPanels( panels ) {
    switch( panels.Shadows ) {
        case 'Basic' : $('.ows-flex, .ows-grid').children().addClass( 'ows-theme-shadow1');    break;
        case 'Enhanced': $('.ows-flex, .ows-grid').children().addClass( 'ows-theme-shadow2');  break;
    }
    if( panels.VariableHeights ) {
        $('.ows-flex, .ows-grid').css('align-items', 'start');
    } else {
        $('.ows-flex, .ows-grid').css( 'align-items', '');
    }
}

function setGull( gull ) {
    //  z-index
    if( gull.OnTop ) {
        $('#Gull-body').css('z-index', 50 );
    } else {
        $('#Gull-body').css('z-index', -50 );
    }
    //  Animation
    var animation, msg = gull.Animation;
    switch( gull.Animation ) {
        case "Expand" :     animation = 'gullBody-Expand';  break;
        case "Enter left":  animation = 'gullBody-LtR';     break;
        case "Enter right": animation = 'gullBody-RtL';     break;
        case "Drop":        animation = 'gullBody-Drop';    break;
        default:            animation = 'gullBody-FadeIn'; msg = 'Fade In';
    }
    console.log('Gull animation is ' + msg);
    $('#Gull-body').css('animation', animation + ' ' + gull.Speed + 's');
}

let createMenus = function( stdMenu, src ) {
    var baseClass, btnClass;
    if( stdMenu ) {
        HTMLmenu = '<div class="w3-bar ows-theme5" style="grid-area:menu;">\n';
        //console.log("Creating standard menu with " + HTMLmenu)
        baseClass = 'w3-bar-item w3-button ows-theme6-hvr w3-hide-small w3-hide-medium ';
        btnClass  = 'class="w3-button ows-theme5 ows-theme6-hvr w3-hide-small w3-hide-medium" onClick="toggleDD(this);" ';
        createMenu( 'Bar', src, false, '', baseClass, btnClass);
    }
    
    HTMLmenu = ""; 
    //console.log("Creating sidebar menu with: " + HTMLmenu);
    baseClass = 'w3-bar-item w3-button ows-theme6-hvr ';
    btnClass  = 'class="w3-button ows-theme5 ows-theme6-hvr" onClick="toggleDD(this)" ';
    createMenu( '', src, false, '', baseClass, btnClass)
    //  Add right carets
    $('.w3-dropdown-content').children('a').prepend('<i class="fa-solid fa-caret-right fa-sm"></i>&nbsp;&nbsp;');
    $('.ows-Accordion').children('a').prepend('<i class="fa-solid fa-caret-right fa-sm"></i>&nbsp;&nbsp;');
}

let createMenu = function( menu, src, dropDown, prefix, baseClass, btnClass ) {
    var target, icon, lnkClass;
    //console.log('Menu2 src: ' + JSON.stringify( src));
    src.forEach( function( item ) {
        icon = ( item.icon ? '<i class="' + item.icon + ' menuIcon"></i>' : '');
        if( item.subMenu ) {
            if( menu=="Bar") { icon = '';}
            HTMLmenu += '<div class="w3-dropdown-click">\n';
            HTMLmenu += '\t<button id="' + item.title.replaceAll(/ /g, '') + menu + '" ';
            HTMLmenu += btnClass ;
            HTMLmenu += 'aria-label="View ' + item.title + '" aria-expanded="false">' + item.title + ' ';// Space may not be required
            HTMLmenu += '<i class="fa-solid fa-caret-down fa-xs"></i>' + icon + '</button>';
            HTMLmenu += '\n\t<div id="dd' + item.title.replaceAll(/ /g, "") + menu + '" class="w3-dropdown-content w3-bar-block">\n';
            createMenu( menu, item.items, true, '\t\t', baseClass, btnClass);
            HTMLmenu += '\n\t</div>\n</div>\n';
        } else {
            //  Standard menu entries
            lnkClass = baseClass + (dropDown ? 'ows-theme4' : 'ows-theme5');    // Applies different colour if in a dropdown
            target = ( item.new_window ? ' target="_blank"' : '');
            switch(item.url) {
                case '#' :
                    if( item.forum && cmxData.forumurl != '') { // Its a forum link with a valid url
                        HTMLmenu += '<a href="' + cmxData.forumurl + '"' + target + ' class="' + lnkClass + '">' + item.title + '</a>\n';
                    }
                    if( item.webcam && cmxData.webcamurl != '') {   // A webcam link with a valid url
                        HTMLmenu += '<a href="' + cmxData.webcamurl + '"' + target + ' class="' + lnkClass + '">' + item.title + icon +'</a>\n';
                    }
                    break;
                default:
                    if( item.url === '' ){  // Replace with a dividing bar
                        HTMLmenu += '<div class="w3-bar-item mnuDivider"></div>\n';
                    } else {    // Insert basic link
                        HTMLmenu += '<a href="' + item.url + '"' + target + ' class="' + lnkClass + '" aria-label="View ' + item.title + '">' + item.title;
                        HTMLmenu += (cmxConfig.Custom.StandardMenu && !dropDown ? '' : icon) + '</a>\n';
                    }
            }
        }
    });
    if( dropDown ) { return; }
    if( menu=='Bar') {
        HTMLmenu += '<button class="w3-button ows-theme3 w3-hide-large" type="button" onClick="menuToggle()">&#9776;</button>'; // Add hamburger
        HTMLmenu += '\n</div>' ;    // Close html block
        //Insert into existing hamburger
         $( HTMLmenu ).replaceAll( '#hamburger' );
        //console.log("Bar menu: " + HTMLmenu + '\n\n')
    } else {
        HTMLmenu += '\n<div class="menuEnd ows-theme1 w3-bar-item" style="height:0.5vh; "></div>';
        // insert into menuSidebar
        $('#menuSidebar').append( HTMLmenu );
        //console.log("// Sidepanel Menu\n" + HTMLmenu + '\n\n')
    }
}

function addLeadingZeros(n) {
    return n <= 9 ? '0' + n : n;
}

function menuToggle() {
    if( $('#menuSidebar, .w3-bar').css('display') == 'block') {
        $('#menuSidebar, .w3-bar').css('animation','menuClose 0.5s ease-in-out');
        setTimeout( function() {
            $('#menuSidebar, .w3-bar' ).css('display', 'none').attr('aria-label', 'Open the menu');
        }, 450);
    } else {
        $('#menuSidebar, .w3-bar').css('display', 'block').attr('aria-label', 'Close the menu');
        $('#menuSidebar, .w3-bar').css('animation', 'menuOpen 0.5s ease-in-out')
    }
}

function toggleDD( el )  {
    //  This controls the menu drop downs!
    if($('#dd' + el.id).css('display' ) == 'none') {
        $('#menuSidebar').find('w3-dropdown-content').css('display', 'none');
        $('#menuSidebar').find('.w3-button').removeClass('ows-theme2')
        $('.w3-bar').find('.w3-dropdown-content').css('display', 'none');
        $('.w3-bar').find('.w3-button').removeClass('ows-theme2');
        $('#dd' + el.id).css('display', 'block');
        $('#' + el.id).toggleClass('ows-theme5').toggleClass('ows-theme2');
    } else {
        $('#dd' + el.id).css('display', 'none');
        $('#' + el.id).toggleClass('ows-theme5').toggleClass('ows-theme2');
    }
}

function togglePopup( el ){
    //  This controls the popups
    $('#' + el).css( 'display', ($('#' + el).css('display') == 'none' ? 'block' : 'none'));
}

dataLoadedPromise = new Promise((myResolve, myReject) => {
    $(function() {
        getPageData(myResolve, myReject);
    })
})

$().ready( function() {
    setTheme( cmxConfig.Custom.Theme );
    setPageGeometry( cmxConfig.Geometry );
    setGull( cmxConfig.Gull );
    setBannerImage( cmxConfig.Custom );
    setLogo( cmxConfig.Custom.Logo );
    setPanels( cmxConfig.Panels );
})