let resolutionA = 16;
let resolutionB = 9;
let fontSize = 1;
let global_scale = 1;
let popover;

$(document).ready(function () {
        // -------------- Credits -------------
    $("#credits_title").html($.trim(credits[0]))
    $("#credits_version").text($.trim(credits[1]))
    $("#credits_date").text($.trim(credits[2]))
    $("#credits_role_1").text($.trim(credits[3]))
    $("#credits_role_2").text($.trim(credits[4]))

    // -------------- Sources -------------
    if(sources.length > 0) {
        $(".fieldset-original").removeClass('d-none');
        $.each(sources, function(key, source_value) {
            $("#sources").append("<li>"+source_value+"</li>")
        });
    }

    // ------------- Fix Links ------------
    $("#inner_container a").attr("target", "_blank");
    $(".modal a").attr("target", "_blank");

    // Change titles with credits_title var
    $('.app-title').html(credits[0]);

    // Change guidelines with guidelines var
    $("#intro_text").html(guidelines);

    init_controls();

    // Resize window
    $(window).resize();

    $('.img_but').click(function(){
        $("#imgFile").val("").click()
    })
    
    $('#img_remove').click(function(){
        $('#img_preview').empty()
        $(this).addClass('visually-hidden').attr('aria-hidden', 'true')
    })
    
    // Hide image selection button if already has fix image
    if(FIX_IMAGE && images_base64.length > 0){
        $("#image_select_wrapper").addClass('d-none');

        index = Math.floor(Math.random()*images_base64.length)
        imgData = images_base64[index]

        if(imgData.length > 1){
            imgData3 = imgData
            imageLoaded = 1

            let tmpImage = new Image();
            tmpImage.src = imgData3;
            tmpImage.onload = function () {
                // Get original Image Dimensions
                image_width = tmpImage.width;
                image_height = tmpImage.height;
                image_aspect = image_width/image_height;
            }
            pre_init_puz();
        }
    }

    // ----- Full screen and popover ------
    popover = new bootstrap.Popover($('.popover'), {
        container: '#canvas_wrapper',
        html: true,
        title: credits[0],
        content: `<p>`+guidelines+`</p>` // Add html content for popover here.
    })

    // Open popover on start
    popover.toggle();

    $("#view_instructions").click(function(){
        if($(this).hasClass('btn-success')){
            $(this).removeClass('btn-success')
        } else {
            $(this).addClass('btn-success')
        }
    });

    $("body").click(function(e){
        if(e.target.id != 'popover_icon' && $("#view_instructions").hasClass('btn-success')){
            popover.hide();
            $("#view_instructions").removeClass('btn-success')
        }
    });

    // --------- Theme Mode ----------
    // Set initial theme based on local storage
    if (localStorage.getItem("theme") === "dark") {
        $("body").addClass("dark-mode");
        $("#themeIcon").removeClass("bi-moon").addClass("bi-sun")
    }

    // Change theme mode
    $("#themeToggle").click(function() {
        isDark = $("body").hasClass("dark-mode");
        if(isDark) {
            $("body").removeClass("dark-mode");
            $("#themeIcon").removeClass("bi-sun").addClass("bi-moon");
            localStorage.setItem("theme", "light");
        } else {
            $("body").addClass("dark-mode");
            $("#themeIcon").removeClass("bi-moon").addClass("bi-sun");
            localStorage.setItem("theme", "dark");
        }

        if(show_image) {
            $("#transparency").change()
        }
    });

    // Hide theme button
    if(!ENABLE_DARK_MODE){
        $("#themeToggle").hide();
        $("body").removeClass("dark-mode");
    }

    // ----------- Help screen ------------
    // Hide help screen button
    if(!ENABLE_HELP_SCREEN){
        $("#helpBtn").hide();
    }

    $('#outer_container').removeClass('opacity-0');
});

$(window).resize(function () {
    $('#alert_success').hide()
    // Adjust inner_container height on window resize
    // Window Dimensions
    let windowWidth = $(window).width();
    let windowHeight = $(window).height();

    // Adjust font size (dynamically set size based on screen size)
    fontSize = 0.018 * Math.min(windowWidth, windowHeight) + 4;
    $("*")
        .not("video, audio, track, img, canvas, script, mjx-container *, #formFile, .img_but, .edit_but, .items, #view_instructions, .form-range")
        .css('font-size', fontSize)
        .css('line-height', (fontSize * 1.5) + "px")

    $("h1").css('font-size', (fontSize * 1.30));
    $("h2").css('font-size', (fontSize * 1.25));
    $("h3").css('font-size', (fontSize * 1.2));
    $("h4").css('font-size', (fontSize * 1.15));
    $("h5, strong, fieldset, legend").css('font-size', (fontSize * 1.1));
    $("h6").css('font-size', (fontSize * 1.05));
    $("sup, sub").css('font-size', (fontSize * 0.7));
    $(".bi").css('font-size', (fontSize * 1.8));
    $(".bi.small").css('font-size', (fontSize * 1.1));
    $("#controls_wrapper label, #controls_wrapper label span").css('font-size', (fontSize * 0.9)).css('line-height', (fontSize * 1.15) + "px");
    $("#size_division_label, #transparency_label, #items_stats").css('font-size', (fontSize * 0.9)).css('line-height', fontSize + "px");

    // Adjust width
    let maxWidth = 1280;
    let width = (windowWidth >= maxWidth) ? maxWidth : windowWidth;

    // Adjust resolution (landscape OR portrait)
    if (windowWidth > windowHeight) {
        resolutionA = 16;
        resolutionB = 9;
    } else if (windowWidth < windowHeight) {
        resolutionA = 9;
        resolutionB = 16;
    }

    // Fix for mobile devices to make width - body padding
    if(windowWidth < maxWidth){
        width -= (2 * windowWidth / 100)
    }

    // Adjust height
    let height = (width * resolutionB) / resolutionA;

    // Additional check if height with body margin is bigger than window Height to recalculate height and width
    if ((height + (2 * windowWidth / 100)) > windowHeight) {
        height = windowHeight - (2 * windowWidth / 100);
        width = (height * resolutionA) / resolutionB;
    }
    $("#outer_container").css('width', width);

    // Fix the inner_container height
    let tHeight = height - $("#header").outerHeight() - ($("#main").outerHeight(true) - $("#inner_container").outerHeight(true));// (height - header_height - (main_padding))
    $("#inner_container").css('height', tHeight);
    $("#canvas_wrapper").css('height', ($("#canvas_wrapper").width() / canvasAspectRatio));

    // Recalculate canvas size on resize
    window.setTimeout(function () {
        mainW = $("#canvas_wrapper").width()
        scaleFactor = mainW / maxW 
        $("#my-canvas").css({ transformOrigin: '0px 0px', transform: `scale(${ scaleFactor  })` })
    }, 100);
});


$('.btn-primary').mouseup(function() {
    $(this).blur()
    $('body').click()
    window.setTimeout(function () {
        $('body').click()
    }, 1000);
})