/**
 * app/js/main.js
 *
 * This file is for 'access anywhere' javascript.
 *
 * @version 3.0
 * @author  Joey Kimsey <Joey@thetempusproject.com>
 * @link    https://TheTempusProject.com
 * @license https://opensource.org/licenses/MIT [MIT LICENSE]
 */
/**
 * Automatically selects/de-selects all check boxes associated with that field
 **/
function checkAll(ele) {
    var checkboxes = document.getElementsByTagName( 'input' );
    if (ele.checked) {
        test = true;
    } else {
        test = false;
    }
    for ( var i = 0; i < checkboxes.length; i++ ) {
        if ( checkboxes[i].type == 'checkbox' ) {
            if ( checkboxes[i].name == ele.value ) {
                checkboxes[i].checked = test;
            }
        }
    }
}

function insertTag( box, tag ) {
    var Field = document.getElementById( box );
    var currentPos = cursorPos( Field );
    var val = Field.value;
    var before = val.substring( 0, currentPos );
    var after = val.substring( currentPos, val.length );
    Field.value = before + '(' + tag + ')' + after;
}

function cursorPos( el ) {
    if ( el.selectionStart ) {
        return el.selectionStart;
    } else if ( document.selection ) {
        el.focus();
        var r = document.selection.createRange();
        if ( r == null ) {
            return 0;
        }
        var re = el.createTextRange(),
            rc = re.duplicate();
        re.moveToBookmark( r.getBookmark() );
        rc.setEndPoint( 'EndToStart', re );
        return rc.text.length;
    }
    return 0;
}

function getRandomInt(min, max) {
    const minCeiled = Math.ceil(min);
    const maxFloored = Math.floor(max);
    return Math.floor(Math.random() * (maxFloored - minCeiled) + minCeiled);
}

function copyElementText( id ) {
    const inputElement = document.getElementById( id );
    const textToCopy = inputElement.value;

    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(textToCopy)
            .then(() => alert('Copied to clipboard!'))
            .catch((err) => console.error('Failed to copy: ', err));
    } else {
        // Fallback for older browsers
        inputElement.select();
        try {
            document.execCommand('copy');
            alert('Copied to clipboard!');
        } catch (err) {
            console.error('Failed to copy: ', err);
        }
    }
}

$(document).ready(function() {
    $('select').each(function() {
        var selectedValue = $(this).attr('value');
        if (selectedValue) {
            $(this).removeAttr('value');
            $(this).find('option').each(function() {
                if ($(this).attr('value') === selectedValue) {
                    $(this).prop('selected', true);
                }
            });
        }
    });
});

document.addEventListener('DOMContentLoaded', function () {
    const ttpDarkmode = document.getElementById('dark-mode-pref');
    const toggleButton = document.getElementById('dark-mode-toggle');
    const enableButton = document.getElementById('dark-mode-toggle-button');
    const darkModeStylesheet = document.getElementById('dark-mode-stylesheet');
    let currentState = '';

    // Check if dark mode is set by ttp
    if ( ttpDarkmode ) {
        if ( 'true' == ttpDarkmode.value ) {
            currentState = 'enabled';
        }
        if ( 'false' == ttpDarkmode.value ) {
            currentState = 'disabled';
        }
    }

    // Check if dark mode is set in localStorage
    if ( '' == currentState ) {
        if ( localStorage.getItem('darkMode') === 'enabled' ) {
            currentState = 'enabled';
        }
    }

    // Update current button states
    if ( 'enabled' == currentState ) {
        darkModeStylesheet.disabled = false;

        if ( toggleButton ) {
            toggleButton.checked = true;
        }
      
        if ( enableButton ) {
            enableButton.innerText = 'Disable Now';
        }
    }

    // Style striped table elements
    document.querySelectorAll('.table-striped').forEach((table) => {
        if ( 'enabled' == currentState ) {
            table.classList.add('table-dark');
        } else {
            table.classList.add('table-light')
        }
    });

    if ( enableButton ) {
        enableButton.addEventListener('click', function () {
            if ( darkModeStylesheet.disabled ) {
                darkModeStylesheet.disabled = false;
                localStorage.setItem('darkMode', 'enabled');
                enableButton.innerText = 'Disable Now';
            } else {
                darkModeStylesheet.disabled = true;
                localStorage.setItem('darkMode', 'disabled');
                enableButton.innerText = 'Enable Now';
            }
        });
    }

    if ( toggleButton ) {
        toggleButton.addEventListener('click', function () {
            if (darkModeStylesheet.disabled) {
                toggleDarkModePref( true );
                darkModeStylesheet.disabled = false;
                localStorage.setItem('darkMode', 'enabled');
            } else {
                toggleDarkModePref( false );
                darkModeStylesheet.disabled = true;
                localStorage.setItem('darkMode', 'disabled');
            }
        
            document.querySelectorAll('.table-striped').forEach((table) => {
                if (localStorage.getItem('darkMode') === 'enabled') {
                    table.classList.add('table-dark');
                    table.classList.remove('table-light');
                } else {
                    table.classList.add('table-light');
                    table.classList.remove('table-dark');
                }
            });
        });
    }

    function toggleDarkModePref( value ) {
        var fields = {};
        fields.prefName = 'darkMode';
        fields.prefValue = value;
        $.post( '/usercp/updatePref', fields ).done(function(response) {
            // alert('Timer updated successfully!');
        });
    }
});


document.addEventListener('DOMContentLoaded', function () {
    const postSelector = document.getElementById('postSelector');
    const goToPostButton = document.getElementById('goToPost');

    if ( postSelector && goToPostButton ) {
        goToPostButton.addEventListener('click', function () {
            const selectedValue = postSelector.value;
            if (selectedValue) {
                const url = `/blog/post/${selectedValue}`;
                window.location.href = url;
            } else {
                alert('Please select an option before proceeding.');
            }
        });
    }
  });