var imageMaxSize = 50;
var videoMaxSize = 200;
var appUrl = $('meta[name="appUrl"]').attr("content");
var currentUrl = window.location.pathname.replace("/", "");
$(function () {
    $('[data-toggle="tooltip"]').tooltip();
});

$(document).on("change", ".removeSameValueAndSpace", function (b) {
    $(this).val($.trim($(this).val()));
    var samevalue = $(this).val().charAt(0);
    var str = $(this).val();
    var flag = 0;
    for (var i = 0; i < str.length; i++) {
        if (samevalue != str.charAt(i) || !isNaN(str.charAt(i))) {
            flag = 1;
            break;
        }
    }
    if (flag == 0) {
        $(this).val("");
    }
});
$("input.onlyNumeric").on("input", function () {
    this.value = this.value
        .replace(/[^0-9]/g, "")
        .replace(/(\..*?)\..*/g, "$1");
});
jQuery.validator.addMethod(
    "email",
    function (value, element) {
        return (
            this.optional(element) ||
            /^([a-zA-Z0-9_.+-])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(
                value
            )
        );
    },
    "Please enter a valid email address."
);
jQuery.validator.addMethod(
    "imageRequired",
    function (value, element) {
        var fileInput = $(element);
        var hasProfileImg = $("#hasProfileImg").val() === "1";
        if (hasProfileImg) {
            return true;
        }
        var files = fileInput[0].files;
        if (files.length > 0) {
            return true;
        }
        return false;
    },
    "Please select an image."
);

jQuery.validator.addMethod(
    "validImage",
    function (value, element) {
        var fileInput = $(element);
        var hasProfileImg = $("#hasProfileImg").val() === "1";
        if (hasProfileImg) {
            return true;
        }
        var files = fileInput[0].files;
        var validExtensions = ["jpg", "jpeg", "png"];
        if (files.length > 0) {
            var extension = files[0].name.split(".").pop().toLowerCase();
            return $.inArray(extension, validExtensions) !== -1;
        }
        return false;
    },
    "Please select a valid image (JPG, JPEG, PNG)."
);

$(document).on("click", ".cancel_action", function () {
    $(".commanpopup").hide();
});

$(document).ready(function () {
    $(".by_default > li > a").click(function (event) {
        event.preventDefault();
        var $submenu = $(this).next(".sidebar-sub-menu");
        var $parentLi = $(this).parent();
        if ($submenu.is(":visible")) {
            $submenu.slideUp();
            if (!$parentLi.hasClass('active')) {
                $parentLi.removeClass("active");
            }
        } else {
            $(".sidebar-sub-menu").slideUp();
            $(".by_default > li").removeClass("active");
            var navUrl = $($submenu).find('li:first a').attr('href');
            if (navUrl !== "javascript:void(0);") {
                navUrl = new URL(navUrl, appUrl).pathname.replace("/", "");
                console.log(appUrl + "------" + currentUrl + "-----" + navUrl);
                if (currentUrl !== navUrl) {
                    // navUrl = navUrl.replace('admin/home');
                    window.location.href = appUrl + navUrl;
                }
            }
            $submenu.slideDown();
            $parentLi.addClass("active");
        }
    });
});

function createSpinnerLoader(selector, topClass = "mt-10") {
    const spinnerDiv = document.createElement("div");
    spinnerDiv.className = `d-flex justify-content-center ${topClass}`;
    spinnerDiv.id = "spinner_loader";

    const spinner = document.createElement("div");
    spinner.className = "spinner-border";
    spinner.setAttribute("role", "status");

    const spinnerSpan = document.createElement("span");
    spinnerSpan.className = "sr-only";
    spinnerSpan.innerText = "Loading...";

    spinner.appendChild(spinnerSpan);
    spinnerDiv.appendChild(spinner);

    document
        .getElementById(selector)
        .insertAdjacentElement("afterend", spinnerDiv);
}

$(".sideBarLinks").each(function () {
    var $this = $(this);
    var href = $this.find("a").attr("href");
    var pathname = new URL(href, appUrl).pathname.replace("/", "");
    var tagText = $this.parent().closest("li").find(".tabLi").text();
    tagText = tagText.toLowerCase();
    if (pathname == currentUrl) {
        if (currentUrl.includes(tagText)) {
            if ($this.closest(".sidebar-sub-menu").length == 0) {
                $this.addClass("active");
            }
            $this.find("a").addClass("active");
        } else {
            $this.addClass("active");
        }
    } else {
        if (currentUrl.includes(tagText)) {
            if ($this.closest(".sidebar-sub-menu").length == 0) {
                $this.removeClass("active");
            }
            $this.find("a").removeClass("active");
        } else {
            $this.removeClass("active");
        }
    }
});

$(document).on("click", ".sideBarLinks", function (e) {
    e.stopPropagation();
    var $this = $(this);
    var href = $this.find("a").attr("href");
    var pathname = new URL(href, appUrl).pathname.replace("/", "");
    var tagText = $this.parent().closest("li").find(".tabLi").text();
    tagText = tagText.toLowerCase();
    if (tagText == "lead+") {
        tagText = tagText.replace("+", "plus", tagText);
    }
    if (pathname == currentUrl) {
        if (currentUrl.includes(tagText)) {
            if ($this.closest(".sidebar-sub-menu").length == 0) {
                $this.addClass("active");
            }
            $this.find("a").addClass("active");
        } else {
            $this.addClass("active");
        }
    } else {
        if (currentUrl.includes(tagText)) {
            if ($this.closest(".sidebar-sub-menu").length == 0) {
                $this.removeClass("active");
            }
            $this.find("a").removeClass("active");
        } else {
            $this.removeClass("active");
        }
    }
    window.location.href = href;
});


function displayMessageModal(message, modalName, redirectLink = "") {
    if (redirectLink && modalName == "success") {
        $(`.${modalName}Modal`).find('.closeBtn').attr('data-redirect-url', redirectLink);
    }

    if ($(window).width() > 768) {
        $(`.${modalName}Modal`).find('.modal-dialog').removeClass('modal-md').addClass(
            'modal-lg');
    } else {
        $(`.${modalName}Modal`).find('.modal-dialog').removeClass('modal-lg').addClass(
            'modal-md');
    }
    $(`#${modalName}Message`).html(`${message}`);
    $(`.${modalName}Modal`).modal("show");
}

function activeLi(tag) {    
    $(".tabLi").each(function () {
        var $this = $(this);
        var text = $this.text();
        tag = tag.replace(/\s/g, "_");
        text = text.replace(/\s/g, "_");
        var submenu = $(this).next(".sidebar-sub-menu");        
        if (currentUrl.includes(tag.replace('_','-')) && tag.toLowerCase() == text.toLowerCase()) {
            submenu.parent().addClass("active");
            submenu.css('display', 'block');
            submenu.slideDown();
        }
        else if ((currentUrl.includes('terms') || currentUrl.includes('privacy-policy')) && tag.toLowerCase() == text.toLowerCase()) {
            submenu.parent().addClass("active");
            submenu.css('display', 'block');
            submenu.slideDown();
        } 
        else {
            submenu.parent().removeClass("active");
            submenu.css('display', 'none');
            submenu.slideUp();
        }
    });
}

$(document).on('click', '.closeBtn', function (e) {
    e.stopPropagation();
    var $this = $(this);
    var redirectUrl = $this.attr('data-redirect-url');
    if (redirectUrl) {
        if (redirectUrl == 'selfReload') {
            location.reload(true);
        } else {
            window.location.href = appUrl + redirectUrl;
        }
    } else {
        $this.closest('.modal').modal('hide');
    }
});

function tinyEditor(selector) {    
    tinymce.init({
        selector: `#${selector}`,
        height: 500,
        plugins: [
            "advlist autolink link image lists charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
            "table emoticons template paste help directionality",
            "charmap quickbars colorpicker textcolor autosave",
        ],
        toolbar: [
            "undo redo | styleselect | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist | forecolor backcolor",
            "outdent indent| fontselect fontsizeselect formatselect | link image media emoticons | fullscreen preview",
            "table | hr pagebreak | code | insertdatetime anchor nonbreaking charmap",
            "searchreplace visualblocks visualchars | removeformat | directionality ltr rtl | help",
        ].join(" | "),
        menubar: "file edit view insert format tools table help",
        branding: false,
        autosave_ask_before_unload: true,
        toolbar_mode: "sliding",
        visual: true,
        setup: (editor) => {
            editor.on("init", () => {
                const value = $(`#${selector}`).data("value");
                if (value) {
                    editor.setContent(value);
                }
                $(".tox-promotion-link").remove();
                $('.loader').remove();
                editor.getContainer().style.backGroundColor='#80bdff';
                
            });  
            editor.on('focus', () => {
                editor.getContainer().style.boxShadow='#3d1532 0px 0px 0px 0.2rem';
                editor.getContainer().style.borderColor='#FFF';
            });     
            editor.on('blur', () => {
                editor.getContainer().style.boxShadow='';
                editor.getContainer().style.borderColor='';
            });    
        },
    });
}

function validateMedia(file, mediaType){
    if(mediaType == 'video'){
        if (!file) {
            displayMessageModal(`Please select a video file.`, 'error');
            return false;
        }
        var allowedFormats = ['video/quicktime', 'video/mp4', 'video/webm', 'video/ogg'];
        if (allowedFormats.indexOf(file.type) === -1) {
            displayMessageModal(`Please select a video file in MP4, WebM, or Ogg format.`, 'error');
            $(".message_popup").show();
            return false;
        }
        var maxSize = videoMaxSize * 1024 * 1024;
        if (file.size > maxSize) {
            displayMessageModal(`Maximum file size allowed is ${videoMaxSize} MB.`, 'error');
            return false;
        }
        return true;
    }else if(mediaType == 'image'){
        if (!file) {
            displayMessageModal(`Please select a image file.`, 'error');
            return false;
        }
        var allowedFormats = ['image/jpeg', 'image/png', 'image/gif'];
        if (allowedFormats.indexOf(file.type) === -1) {
            displayMessageModal(`Please select an image file in JPEG, PNG, or GIF format.`, 'error');
            $(".message_popup").show();
            return false;
        }
        var maxSize = imageMaxSize * 1024 * 1024;
        if (file.size > maxSize) {
            displayMessageModal(`Maximum file size allowed is ${imageMaxSize} MB.`, 'error');
            return false;
        }
        return true;
    }else{
        return false;
    }
}   