/*----------------------------
    Prevent Onclick #
------------------------------ */
if (document.querySelectorAll('a[href="#"]') != null) {
    var elem = document.querySelectorAll('a[href="#"]');
    for (i = 0; i < elem.length; i++) {
        elem[i].addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
        });
    }
}

/*----------------------------
    Flash Messages
------------------------------ */
window.addEventListener('load', () => {
    if (typeof flash_message != "undefined") {
        if (flash_message.messageType == "error") {
            new Toast({
                type: "danger",
                title: flash_message.messageTitle,
                message: flash_message.message
            });
        } else {
            new Toast({
                type: flash_message.messageType,
                title: flash_message.messageTitle,
                message: flash_message.message
            });
        }
    }
});


//new Lazyload("lazyload");
//new CookieConsent();

/*----------------------------
    Lazy Load
------------------------------ */
function Lazyload(lazyClass) {
    let selector = "img." + lazyClass;
    let _this = this;
    this.init = () => {
        var lazyImages = [].slice.call(document.querySelectorAll(selector));
        if ("IntersectionObserver" in window) {
            let lazyImageObserver = new IntersectionObserver(function (entries, observer) {
                entries.forEach(function (entry) {
                    if (entry.isIntersecting) {
                        let lazyImage = entry.target;
                        lazyImage.src = lazyImage.dataset.src;
                        //lazyImage.srcset = lazyImage.dataset.srcset;
                        lazyImage.classList.remove(lazyClass);
                        lazyImageObserver.unobserve(lazyImage);
                    }
                });
            });
            lazyImages.forEach(function (lazyImage) {
                lazyImageObserver.observe(lazyImage);
            });
        }
    }
    document.addEventListener("DOMContentLoaded", function () {
        _this.init();
    });
}

/*----------------------------
    KVKK & GDPR cookie consent
------------------------------ */
function CookieConsent() {
    let _this = this;
    this.init = () => {
        if (!(document.cookie.indexOf("cookie-consent=1") > -1)) {
            _this.create();
        }
    }

    this.create = () => {
        const text = "Sitemizden en iyi şekilde faydalanabilmeniz için, kişisel verilerinize ve gizliliğe uygun şekilde çerez kullanmaktayız. Detaylı bilgi için <a href=\"/cerez-politikasi\" class=\"info-text-modal\" data-text=\"cookie-policy\" data-print=\"false\">Çerez Politikamızı</a> inceleyebilirsiniz.";
        const hmtl_text = "<div class=\"cc-notification active\"><div class=\"wrapper\"><div class=\"cc-title\">Çerez Politikası</div><span class=\"cc-text\">" + text + "</span><div class=\"buttons\"><button type=\"button\" class=\"btn btn-secondary btn-sm cc-close\">Kapat</button><button type=\"button\" class=\"btn btn-primary btn-sm cc-accept\">Tamam</button></div><button type=\"button\" class=\"close cc-close\" aria-label=\"Close\"><svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 16 16\"><path d=\"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z\"/></svg></a></div></div>";

        document.body.insertAdjacentHTML('beforeend', hmtl_text);

        document.querySelector('.cc-notification .cc-accept').addEventListener('click', () => {
            document.querySelector('.cc-notification').remove();
            _this.setCookie();
        });
        document.querySelector('.cc-notification .cc-close').addEventListener('click', () => {
            document.querySelector('.cc-notification').remove();
        });
        document.querySelector('.cc-notification .close').addEventListener('click', () => {
            document.querySelector('.cc-notification').remove();
        });
    }

    this.setCookie = () => {
        var d1 = new Date();
        d1.setTime(d1.getTime() + 365 * 24 * 60 * 60 * 1000);
        var expiredate = "expires=" + d1.toUTCString();
        document.cookie = "cookie-consent=1;" + expiredate + ";path=/;SameSite=None;Secure";
    }

    _this.init();
}

/*----------------------------
    Custom Toast
------------------------------ */
function Toast(options) {
    let defaults = {
        title: "",
        message: "",
        duration: 5000,
        autoHide: true,
        animation: true,
        type: "info", //error, warning, success, info
        icon: true,
        close: true,
        position: "top-right"
    }

    var toast_id = randomString(6);
    options = { ...defaults, ...options };

    options.title = "<div class=\"title\"><strong>" + options.title + "</strong></div>" || "";
    options.message = "<span class=\"message\">" + options.message + "<span>" || "";

    options.close_btn = options.close ? "<button type=\"button\" class=\"btn-close btn-close-toast\" data-toast-id=\"" + toast_id + "\" aria-label=\"Close\"></button>" : "";

    let _this = this;
    let content = "";

    this.init = () => {
        var container = document.getElementById('toast-container');
        if (typeof (container) == 'undefined' || container == null) {
            container = this.createContainer();
        }


        content = "<div id=\"" + toast_id + "\" class=\"toast bg-" + options.type + " text-white fade show\" role=\"alert\" aria-live=\"assertive\" aria-atomic=\"true\">\
						<div class=\"d-flex\">\
							<div class=\"toast-body\">\
								"+ options.title + "\n " + options.message + "\
							</div>\
							"+ options.close_btn + "\
						</div>\
					</div>";
        container.innerHTML += content;
        var toast = new bootstrap.Toast(document.getElementById(toast_id), {
            animation: options.animation,
            autohide: options.autoHide,
            delay: options.duration
        });

        toast.show();

        document.getElementById(toast_id).addEventListener('hidden.bs.toast', function (event) {
            document.getElementById(toast_id).remove();
            _this.removeContainer();
        });

        var close_btns = document.querySelectorAll(".btn-close-toast");
        for (let i = 0; i < close_btns.length; i++) {
            close_btns[i].addEventListener("click", function () {
                new bootstrap.Toast(document.getElementById(close_btns[i].getAttribute("data-toast-id"))).hide();
            });
        }
    }

    this.createContainer = () => {
        var container = document.createElement("div");
        container.id = "toast-container";
        container.className = "toast-" + options.position;
        document.body.appendChild(container);

        return document.getElementById('toast-container');
    }

    this.removeContainer = () => {
        var container = document.getElementById('toast-container');
        if (container.innerHTML === "") {
            container.remove();
        }
    }

    this.init();
}

/*----------------------------
    Custom Alert
------------------------------ */
async function CustomAlert(options) {
    return new Promise(function (resolve) {
        let defaults = {
            title: "",
            message: "",
            type: "info", //error, warning, success, info, question
            icon: true,
            showCancelButton: true,
            showCloseButton: true,
            showConfirmButton: true,
            cancelButtonText: 'İptal',
            confirmButtonText: 'Tamam',
            static: false
        }

        options = { ...defaults, ...options };

        let content = "";
        var container;
        var confirmButton = "";
        var cancelButton = "";
        var closeButton = "";
        var result = "";
        var icon = "";

        container = document.querySelector('#custom-alert');
        if (container) {
            container.remove();
        }

        container = document.createElement("div");
        container.id = "custom-alert";
        container.className = "modal fade custom-alert custom-alert-" + options.type;
        document.body.appendChild(container);

        if (options.static) {
            container.setAttribute('data-bs-backdrop', 'static');
            container.setAttribute('data-bs-keyboard', 'false');
        }

        if (options.showCloseButton) {
            closeButton = "<button type=\"button\" id=\"custom-alert-btn-close\" class=\"close\" aria-label=\"Close\"></button>";
        }
        if (options.showConfirmButton) {
            confirmButton = "<button type=\"button\" id=\"custom-alert-btn-confirm\" class=\"btn btn-primary\">" + options.confirmButtonText + "</button>";
        }
        if (options.showCancelButton) {
            cancelButton = "<button type=\"button\" id=\"custom-alert-btn-cancel\" class=\"btn btn-secondary\">" + options.cancelButtonText + "</button>";
        }

        if (options.icon) {
            icon = "<span class=\"custom-alert-icon\"></span>";
        }

        content = "<div class=\"modal-dialog modal-dialog-centered\">\
                            <div class=\"modal-content\">\
                                <div class=\"modal-body\">\
                                    "+ closeButton + "\
                                    "+ icon + "\
                                    <h2 class=\"custom-modal-title\">"+ options.title + "</h2>\
                                    <div class=\"custom-modal-message\">"+ options.message + "</div>\
                                    <div class=\"custom-alert-actions\">\
                                        "+ cancelButton + " " + confirmButton + "\
                                    </div>\
                                </div>\
                            </div>\
                        </div>";

        container.innerHTML = content;
        var modal = new bootstrap.Modal(document.querySelector('#custom-alert'), {
            keyboard: false
        });

        modal.show();

        document.querySelector('#custom-alert').addEventListener('hidden.bs.modal', (e) => {
            if (container) {
                container.remove();
            }
            result = { isConfirmed: false, isCancelled: false, isDismissed: true, value: false };
            resolve(result);
        });
        if (options.showCloseButton) {
            document.getElementById('custom-alert-btn-close').addEventListener('click', () => {
                modal.hide();
                result = { isConfirmed: false, isCancelled: false, isDismissed: true, value: false };
                resolve(result);
            });
        }

        if (options.showCancelButton) {
            document.getElementById('custom-alert-btn-cancel').addEventListener('click', () => {
                modal.hide();
                result = { isConfirmed: false, isCancelled: true, isDismissed: true, value: false };
                resolve(result);
            });
        }

        if (options.showConfirmButton) {
            document.getElementById('custom-alert-btn-confirm').addEventListener('click', () => {
                modal.hide();
                result = { isConfirmed: true, isCancelled: false, isDismissed: false, value: true };
                resolve(result);
            });
        }
    });
}

/*----------------------------
    XMLHttpRequest POST Function
------------------------------ */
function request(url, data, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.addEventListener('readystatechange', function () {
        if (xhr.readyState === 4) {
            if (callback) {
                callback(xhr.response);
            }
        }
    });

    var formdata = data ? (data instanceof FormData ? data : new FormData(document.querySelector(data))) : new FormData();

    var checkboxes = document.querySelectorAll('input[type=checkbox]');
    for (i = 0; i < checkboxes.length; i++) {
        var checkbox = checkboxes[i];
        if (!checkbox.checked) {
            formdata.append(checkbox.getAttribute("name"), 0);
        } else {
            formdata.append(checkbox.getAttribute("name"), 1);
        }
    }

    var csrfMetaTag = document.querySelector('meta[name="csrf_token"]');
    if (csrfMetaTag) {
        formdata.append('csrf_token', csrfMetaTag.getAttribute('content'));
    }

    xhr.send(formdata);
}

/*----------------------------
    Password Visibility Toggler
------------------------------ */
if (document.querySelectorAll('.password-visibility-toggler') != null) {
    var elem = document.querySelectorAll('.password-visibility-toggler');
    for (i = 0; i < elem.length; i++) {
        elem[i].addEventListener('click', function () {
            var hide = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" fill=\"currentColor\" viewBox=\"0 0 16 16\">\
							<path d=\"M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM1.173 8a13.133 13.133 0 0 1 1.66-2.043C4.12 4.668 5.88 3.5 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13.133 13.133 0 0 1 14.828 8c-.058.087-.122.183-.195.288-.335.48-.83 1.12-1.465 1.755C11.879 11.332 10.119 12.5 8 12.5c-2.12 0-3.879-1.168-5.168-2.457A13.134 13.134 0 0 1 1.172 8z\"/>\
							<path d=\"M8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5zM4.5 8a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0z\"/>\
						</svg>";
            var show = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"20\" height=\"20\" fill=\"currentColor\" viewBox=\"0 0 16 16\">\
							<path d=\"M13.359 11.238C15.06 9.72 16 8 16 8s-3-5.5-8-5.5a7.028 7.028 0 0 0-2.79.588l.77.771A5.944 5.944 0 0 1 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13.134 13.134 0 0 1 14.828 8c-.058.087-.122.183-.195.288-.335.48-.83 1.12-1.465 1.755-.165.165-.337.328-.517.486l.708.709z\"/>\
							<path d=\"M11.297 9.176a3.5 3.5 0 0 0-4.474-4.474l.823.823a2.5 2.5 0 0 1 2.829 2.829l.822.822zm-2.943 1.299.822.822a3.5 3.5 0 0 1-4.474-4.474l.823.823a2.5 2.5 0 0 0 2.829 2.829z\"/>\
							<path d=\"M3.35 5.47c-.18.16-.353.322-.518.487A13.134 13.134 0 0 0 1.172 8l.195.288c.335.48.83 1.12 1.465 1.755C4.121 11.332 5.881 12.5 8 12.5c.716 0 1.39-.133 2.02-.36l.77.772A7.029 7.029 0 0 1 8 13.5C3 13.5 0 8 0 8s.939-1.721 2.641-3.238l.708.709zm10.296 8.884-12-12 .708-.708 12 12-.708.708z\"/>\
						</svg>";
            var password = this.getAttribute("data-password");
            var e = document.getElementById(password);
            if (e.type === "password") {
                e.type = "text";
                this.innerHTML = show;
            } else {
                e.type = "password";
                this.innerHTML = hide;
            }
        });
    }
}

/*----------------------------
    Custom Modal
------------------------------ */
function createModal(title, body, print = false, dismiss = true) {
    var id = randomString(6);
    var print_btn = "";
    var dismiss_btn = "";
    if (print) {
        print_btn = "<button class=\"btn btn-secondary print\" type=\"button\" data-action=\"print\" data-title=\"" + title + "\" data-element=\"#" + id + " .modal-body\">Yazdır</button>";
    }
    if (dismiss) {
        dismiss_btn = "<button class=\"btn btn-primary\" type=\"button\" data-bs-dismiss=\"modal\">Tamam</button>";
    }

    var modal_element = document.createElement("div");
    modal_element.id = id;
    modal_element.className = "modal fade";
    document.body.appendChild(modal_element);

    var content = "<div class=\"modal-dialog modal-lg modal-dialog-scrollable modal-dialog-centered\">\
						<div class=\"modal-content\">\
							<div class=\"modal-header\">\
								<h5 class=\"modal-title\">"+ title + "</h5>\
								<button type=\"button\" class=\"custom-close custom-close-light\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button>\
							</div>\
							<div class=\"modal-body text-content\">\
							"+ body + "\
							</div>\
							<div class=\"modal-footer\">\
								"+ print_btn + " " + dismiss_btn + "\
							</div>\
						</div>\
					</div>";

    modal_element.innerHTML = content;
    var modal = new bootstrap.Modal(document.getElementById(id), {
        keyboard: false
    });

    modal.show();

    document.getElementById(id).addEventListener('hidden.bs.modal', () => {
        document.getElementById(id).remove();
    });

    if (print) {
        setPrintButtons();
    }
}

function createCustomModal(modal_id, content) {
    var id = randomString(6);
    var modal_element = document.createElement("div");
    modal_element.id = id;
    document.body.appendChild(modal_element);

    modal_element.innerHTML = content;
    var modal = new bootstrap.Modal(document.getElementById(modal_id), {
        keyboard: false
    });

    modal.show();

    document.getElementById(modal_id).addEventListener('hidden.bs.modal', function (event) {
        document.getElementById(id).remove();
    });

    setPrintButtons();
}

function randomString(length) {
    var result = [];
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
        result.push(characters.charAt(Math.floor(Math.random() * charactersLength)));
    }
    return result.join('');
}