$(document).on('click', '.dropdown-toggle', function () {
    let li = $(this).closest('li.dropdown');
    $('li.dropdown').not(li).removeClass('open');
    li.toggleClass('open');
});

$('.navbar-toggle').click(function () {
    let target = $(this).data('target');
    $(target).toggleClass('collapse');
});

$("#search-input").on('paste keyup', function () {
    var a = "";
    a = $(this).val();
    a = a.replace(/ /g, "-");
    0 == a.length ? $(".list-search-res").html("").addClass("hide") : 3 <= a.length && ($(".list-search-res").html('<img src="/public/assets/images/loading-search.gif" alt="loading">').removeClass("hide"),
        setTimeout(function () {
            quick_search(a)
        }, 500))
});

$("html").click(function (e) {
    "#search-input" != e.target.id && $(".list-search-res").html("").addClass("hide")
});

function quick_search(k) {
    $.get(
        "/tim-kiem-nhanh",
        {
            tukhoa: k
        }
    ).done(function (r) {
        $(".list-search-res").html(r);
    });
}

$(".chapter-nav").on("click", "button.chapter_jump", function () {
    $("button.chapter_jump").attr("disabled", !0);
    $.get(
        '/chapter-list',
        {
            'comic_slug': $(this).data('comic_slug'),
            'chapter_slug': $(this).data('chapter_slug')
        }
    ).done(function (res) {
        $(".chapter_jump").replaceWith(res.data)
    });
});

$("#truyen").on("click", ".showmore .btn", function (a) {
    a.preventDefault();
    $('.limit-desc').removeClass('limit-desc');
    $(this).addClass("hide");
});

$('.list-truyen.list-side .top-nav div').click(function () {
    $('.list-truyen.list-side .top-nav div').removeClass('active');
    $('.list-truyen.list-side .top-item').addClass('hide');
    $(this).addClass('active');
    $('.list-truyen.list-side .top-item.' + $(this).data('type')).removeClass('hide');
});

// set history
if ($('#chapter-big-container').length) {
    // get local storage data
    let comics = localStorage.getItem("history");
    comics = comics ? JSON.parse(comics) : {};

    // check length
    if (Object.keys(comics).length > 5) {
        for (k in comics) {
            delete comics[k];
            if (Object.keys(comics).length == 5) {
                break;
            }
        }
    }

    // get current data
    let comic_name = $('.truyen-title').text();
    let comic_slug = $('.truyen-title').attr('href').split('/').slice(-1)[0];
    let chapter_name = $('.chapter-title .chapter-text span').text().split(':')[0];
    let chapter_slug = $('.chapter-title').attr('href').split('/').slice(-1)[0];

    // remove data if exist
    delete comics[comic_slug];

    // add data to object
    comics[comic_slug] = {
        'comic_name': comic_name,
        'comic_slug': comic_slug,
        'chapter_name': chapter_name,
        'chapter_slug': chapter_slug
    }

    // set local storage data
    localStorage.setItem("history", JSON.stringify(comics));
}

// get history
if (('#history-holder-side').length) {
    // get local storage data
    let comics = localStorage.getItem("history");

    if (comics) {
        comics = JSON.parse(comics);
        comicsKeys = Object.keys(comics).reverse();

        let history = '<div class="list list-truyen list-history col-xs-12"><div class="title-list"><h2>Truyện đang đọc</h2></div><div class="row">';
        comicsKeys.forEach(function (k) {
            history += '<div class="col-md-5 col-lg-7"><span class="glyphicon glyphicon-chevron-right"></span>';
            history += '<h3 itemprop="name"><a href="/' + comics[k].comic_slug + '"> ' + comics[k].comic_name + '</a></h3></div>';
            history += '<div class="col-md-7 col-lg-5 text-info"><a href="/' + comics[k].comic_slug + '/' + comics[k].chapter_slug + '">' + comics[k].chapter_name + '</a></div>';
        });
        history += '</div></div>';
        $('#history-holder-side').replaceWith(history)
    }
}

// theme
if (!localStorage.getItem('bgcolor')) {
    localStorage.setItem('bgcolor', '#F4F4F4');
}
var m = localStorage.getItem('bgcolor'), n = "light"; "#232323" == m && (n = "dark");
m && "#F4F4F4" != m && $("#truyen-background").val(m);
$("#truyen-background").on("change", function () {
    var a = this.value;
    '' ? "hatsan" == a ? ($("body").css({
        "background-color": "#f2f2f2",
        "background-image": "url('/public/assets/images/bg_op.png')",
        "background-repeat": "repeat"
    }).removeClass("dark-theme"), n = "light") : "sachcu" == a ? ($("body").css({
        "background-color": "#c2b49b",
        "background-image": "url('/public/assets/images/bg_book_op.png')",
        "background-repeat": "repeat"
    }).removeClass("dark-theme"), n = "light") : "#232323" == a ? ($("body").css({
        "background-color": a,
        "background-image": "url('/public/assets/images/bg_dark.gif')",
        "background-repeat": "repeat"
    }).addClass("dark-theme"), n = "dark") : ($("body").css({
        "background-color": a,
        "background-image": "none"
    }).removeClass("dark-theme"), n = "light") : "#232323" == a ? ($("body").addClass("dark-theme"), n = "dark") : ($("body").removeClass("dark-theme"), n = "light");
    localStorage.setItem("bgcolor", a);
});

$('.btn_search_collapse').click(function () {
    let target = $(this).data('target');
    target = $(this).closest('section').find(target);
    target.toggleClass('collapse');
    if (target.hasClass('collapse')) {
        $(this).text('Hiện khung tìm kiếm');
    } else {
        $(this).text('Ẩn khung tìm kiếm');
    };
});

$(document).on('click', '.nav.nav-tabs a', function () {
    $(this).closest('ul').find('li').removeClass('active');
    $(this).closest('li').addClass('active');
    $('.tab-content .tab-pane').removeClass('active');
    $('.tab-content .tab-pane' + $(this).data('target')).addClass('active');
});

$(document).ajaxStart(function () {
    //
});
$(document).ajaxStop(function () {
    //
});

$(document).ajaxSuccess(function (event, xhr, settings) {
    let reload = false;
    if (xhr.responseJSON) {
        if (xhr.responseJSON.message) {
            alert(xhr.responseJSON.message);
        }
        reload = xhr.responseJSON.reload;
    }
    if (reload === true) {
        location.reload();
    }
});
$(document).ajaxError(function (event, xhr, settings) {
    if (xhr.responseJSON) {
        if (xhr.responseJSON.message) {
            alert(xhr.responseJSON.message);
        }
    }
});

$(document).on('submit', 'form#login', function (e) {
    e.preventDefault();
    let email = $(this).find('[name="email"]').val();
    let password = $(this).find('[name="password"]').val();

    // send api
    $.ajax({
        url: '/user/login',
        type: 'post',
        data: {
            _token: $('#csrf_token').val(),
            email: email,
            password: password
        }
    });
});

$(document).on('submit', 'form#register', function (e) {
    e.preventDefault();
    let email = $(this).find('[name="email"]').val();
    let password = $(this).find('[name="password"]').val();
    let rePassword = $(this).find('[name="re-password"]').val();

    // validation
    if (password.length < 6) {
        alert('Mật khẩu phải dài hơn 6 ký tự !!!');
        return;
    }
    if (password != rePassword) {
        alert('Mật khẩu không trùng khớp !!!');
        return;
    }

    // send api
    $.ajax({
        url: '/user/create',
        type: 'post',
        data: {
            _token: $('#csrf_token').val(),
            email: email,
            password: password
        }
    });
});

$(document).on('submit', 'form#lost-password', function (e) {
    e.preventDefault();
    let email = $(this).find('[name="email"]').val();

    // send api
    $.ajax({
        url: '/user/lost-password',
        type: 'post',
        data: {
            _token: $('#csrf_token').val(),
            email: email
        }
    });
});

$(document).on('submit', 'form#user-settings', function (e) {
    e.preventDefault();
    let name = $(this).find('[name="name"]').val();
    let password = $(this).find('[name="password"]').val();
    let rePassword = $(this).find('[name="re-password"]').val();

    // validation
    if (password) {
        if (password.length < 6) {
            alert('Mật khẩu phải dài hơn 6 ký tự !!!');
            return;
        }
        if (password != rePassword) {
            alert('Mật khẩu không trùng khớp !!!');
            return;
        }
    }

    // send api
    $.ajax({
        url: '/user/update',
        type: 'post',
        data: {
            _token: $('#csrf_token').val(),
            name: name,
            password: password
        }
    });
});

$(document).on('click', '.follow a', function (e) {
    let status = 'add';
    if ($(this).hasClass('remove')) {
        status = 'remove';
    }

    // send api
    $.ajax({
        url: '/user/follow',
        type: 'post',
        data: {
            _token: $('#csrf_token').val(),
            status: status,
            comic_name: $(this).closest('.follow').data('comic_name'),
            comic_slug: $(this).closest('.follow').data('comic_slug'),
            chapter_name: $(this).closest('.follow').data('chapter_name'),
            chapter_slug: $(this).closest('.follow').data('chapter_slug'),
        },
        success: function () {
            $('.follow a').toggleClass('hide');
        }
    });
});

$(document).on('click', '#user-follow .remove', function (e) {
    let info = $(this).closest('div.row');
    let comicName = info.data('comic_name');
    if (confirm('Xoá truyện "' + comicName + '" khỏi danh sách theo dõi ?')) {
        // send api
        $.ajax({
            url: '/user/follow',
            type: 'post',
            data: {
                _token: $('#csrf_token').val(),
                status: 'remove',
                comic_name: comicName,
                comic_slug: info.data('comic_slug')
            },
            success: function () {
                info.remove();
            }
        });
    }
});

$(window).on("load", function () {
    $('img').each(function () {
        if (!this.complete
            || typeof this.naturalWidth == "undefined"
            || this.naturalWidth == 0) {
            this.src = '/public/assets/images/default-image.jpg';
        }
    });
});

// Get the modal
var modal = $("#myModal")[0];
var modalContent = $("#myModal .modal-content div");

// Get the <span> element that closes the modal
var modalClose = $("#myModal .close")[0];

// When the user clicks on <span> (x), close the modal
modalClose.onclick = function () {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

$('.btnModal').click(function () {
    $.ajax({
        url: $(this).data('url'),
        success: function (res) {
            modalContent.html(res);
            modal.style.display = "block";
        }
    });
});