jQuery(document).ready(function ($) {
    /* ------------- yascode metaboxes ------- */

    $(document).on("click", ".listitem-option .add-new-item", function (e) {
        e.preventDefault();
        var btn = $(this);
        var list = btn.parent().find(".real-items-list");
        var indexes = list
            .find(".item")
            .map(function () {
                return $(this).attr("data-index");
            })
            .get();
        var index_id = parseInt(Math.max.apply(Math, indexes)) + 1;
        var clone_item = list.find(".item.example-item").clone();
        clone_item.removeClass("example-item");
        clone_item.attr("data-index", index_id);
        clone_item.find("[data-name]").each(function () {
            var $t = $(this);
            var input_name_text = $t.attr("data-name");
            var new_text = input_name_text.replace("index_id", index_id);
            $t.attr("data-name", new_text);
            $t.attr({
                name: $t.attr("data-name"),
            }).removeAttr("data-name");
        });
        clone_item.find(".inner-items").sortable({
            cursor: "move",
            handle: ".mover",
        });
        clone_item.appendTo(list);
    });

    $(".listitem-option > .real-items-list").sortable({
        cursor: "move",
        handle: ".btn.move",
    });

    $(".real-items-list > .item > .inner-body .inner-items").sortable({
        cursor: "move",
        handle: ".mover",
    });

    $(document).on(
        "click",
        ".headline > .input-item .operations > .btn.open",
        function (e) {
            e.preventDefault();
            var btn = $(this);
            var item = btn.parent().parent().parent().parent();
            var innerbody = item.find(".inner-body");
            if (innerbody.css("display") == "none") {
                innerbody.slideDown(300);
                btn.text("ببند");
            } else {
                innerbody.slideUp(300);
                btn.text("باز کن");
            }
        }
    );

    $(document).on(
        "click",
        ".item > .inner-body .add-new-inner-item",
        function (e) {
            e.preventDefault();
            var btn = $(this);
            var item = btn.parent().parent();
            var inner_list = btn.parent().find(".inner-items");
            var index_id = parseInt(item.attr("data-index"));
            var indexes = inner_list
                .find(".inner-item")
                .map(function () {
                    return $(this).attr("data-inner");
                })
                .get();
            var inner_id = parseInt(Math.max.apply(Math, indexes)) + 1;
            var clone_item = inner_list.find(".inner-item.example-item").clone();
            clone_item.removeClass("example-item");
            clone_item.attr("data-inner", inner_id);
            clone_item.find("[data-innername]").each(function () {
                var $t = $(this);
                var input_name_text = $t.attr("data-innername");
                var new_text = input_name_text.replace("index_id", index_id);
                new_text = new_text.replace("inner_index_id", inner_id);
                $t.attr("data-innername", new_text);
                $t.attr({
                    name: $t.attr("data-innername"),
                }).removeAttr("data-innername");
            });
            clone_item.appendTo(inner_list);
        }
    );

    $(document).on(
        "click",
        ".headline > .input-item .operations > .btn.delete",
        function (e) {
            e.preventDefault();
            var btn = $(this);
            btn.parent().parent().parent().parent().remove();
        }
    );

    $(document).on(
        "click",
        ".inner-item .input-box.operations > span.delete",
        function (e) {
            e.preventDefault();
            var btn = $(this);
            btn.parent().parent().remove();
        }
    );

    $(document).on(
        "click",
        ".yascode-metaboxes > .head-metabox-tabs .nav-tab",
        function (e) {
            e.preventDefault();
            var btn = $(this);
            var section_id = btn.attr("data-id");
            var main_list = $(this).parent().parent().find(".metaboxes-body");
            main_list.find(".section-list").addClass("none");
            main_list
                .find('.section-list[data-id="' + section_id + '"]')
                .removeClass("none");
            btn.parent().find(".nav-tab").removeClass("nav-tab-active");
            btn.addClass("nav-tab-active");
        }
    );

    $(document).on(
        "click",
        ".metafield-box.checkbox > .checkbox-slider",
        function (e) {
            e.preventDefault();
            var checkBox = $(this).parent().find("input");
            checkBox.prop("checked", !checkBox.prop("checked"));
        }
    );

    //update post actors
    var countPostActors = 0;
    var finalPostActors = [];
    jQuery(".metafield-box.import-imdb-actors .progress-info .btn").click(function () {
        var btn_update_actors = jQuery(".metafield-box.import-imdb-actors .progress-info .btn");
        var actors_progress = btn_update_actors
            .parent()
            .find(".item_actorsp");
        var count_val = parseInt(actors_progress.attr("data-count"));
        if (btn_update_actors.attr('data-active') == 'true') {
            if (count_val > 0) {
                btn_update_actors.attr('data-active', 'false');
                countPostActors = count_val;
                $('.metafield-box.import-imdb-actors>.progress-info .result-navar .info').text('در حال انجام :');
                ajaxCallPostActor(actors_progress, actors_progress.attr('data-itemid'));
            } else alert("بازیگری یافت نشد !");
        } else alert('هم اکنون پروسه ای در حال انجام دارید !');
    });

    function ajaxCallPostActor(actors_progress, itemid) {
        var btn_update_actors = jQuery(".metafield-box.import-imdb-actors .progress-info .btn");
        var pr = btn_update_actors
            .parent()
            .find(".item_actorsp");
        var acts = actors_progress.attr("data-items");
        var save_actor_images = $(".save_actor_images_imdb").is(":checked");
        var save_actor_biography = $(".save_actor_biography").is(":checked");
        jQuery.ajax({
            url: ajaxurl,
            type: "POST",
            dataType: "json",
            data: {
                action: "fetch_actor_data",
                itemid: itemid,
                actors: acts,
                save_images: save_actor_images,
                save_biography: save_actor_biography
            },
            success: function (response) {
                actors_progress.find(".inner-navar").css({
                    width: response.id * (100 / countPostActors) + "%",
                });
                actors_progress.attr("data-itemid", response.id);
                $('.metafield-box.import-imdb-actors>.progress-info .result-navar .rs span').text(response.id);
                finalPostActors.push(response.name);
                if (parseInt(itemid) == countPostActors - 1) sendFinalPostActors(finalPostActors);
                else if (parseInt(itemid) < countPostActors - 1) {
                    ajaxCallPostActor(pr, pr.attr('data-itemid'));
                }
            },
            error: function (error) {
                alert("خطایی رخ داد صفحه را رفرش و مجددا امتحان نمایید !");
            },
        });
    }

    function sendFinalPostActors(finalPostActors) {
        var actors_div = $("#tagsdiv-actor");
        actors_div.find("#new-tag-actor").val(finalPostActors);
        actors_div.find(".tagadd").trigger("click");
        countPostActors = 0;
        finalPostActors = [];
        var btn_update_actors = jQuery(".metafield-box.import-imdb-actors .progress-info .btn");
        var actors_progress = btn_update_actors
            .parent()
            .find(".item_actorsp");
        actors_progress.attr("data-itemid", 0);
        btn_update_actors.attr('data-active', 'true');
        $('.metafield-box.import-imdb-actors>.progress-info .result-navar').text('بازیگران با موفقیت دریافت شد مطلب را ذخیره نمایید.');
        $('.metafield-box.import-imdb-actors>.progress-info .result-navar').addClass('success');
    }

    /* --------------------------------------- */

    /* --- js metabox imdb --- */
    $(document).on(
        "click",
        ".upload_btn_open, .metafield-box.upload > .upload-btn",
        function (e) {
            e.preventDefault();
            var thisBtn = $(this);
            var image = wp
                .media({
                    title: "انتخاب تصویر",
                    // mutiple: true if you want to upload multiple files at once
                    multiple: false,
                })
                .open()
                .on("select", function (e) {
                    var uploaded_image = image.state().get("selection").first();
                    var image_id = uploaded_image.toJSON().id;
                    var image_url = uploaded_image.toJSON().url;
                    thisBtn.parent().find("img").attr("src", image_url);
                    thisBtn.parent().find("input").val(image_id);
                });
        }
    );
    $(document).on("click", ".search_title", function (e) {
        e.preventDefault();
        getIMDbData();
    });
    //set terms
    function set_terms(stars, release, country, genre, director, language, post_tags) {
        if ($("body").hasClass("post-type-movies")) {
            var actors_div = $("#tagsdiv-actor");
            actors_div.find("#new-tag-actor").val(stars);
            actors_div.find(".tagadd").trigger("click");

            var release_div = $("#tagsdiv-release");
            release_div.find("#new-tag-release").val(release);
            release_div.find(".tagadd").trigger("click");

            var country_div = $("#tagsdiv-country");
            country_div.find("#new-tag-country").val(country);
            country_div.find(".tagadd").trigger("click");

            var directors_div = $("#tagsdiv-director");
            directors_div.find("#new-tag-director").val(director);
            directors_div.find(".tagadd").trigger("click");

            var genres_div = $("#tagsdiv-genre");
            genres_div.find("#new-tag-genre").val(genre);
            genres_div.find(".tagadd").trigger("click");

            var language_div = $("#tagsdiv-language");
            language_div.find("#new-tag-language").val(language);
            language_div.find(".tagadd").trigger("click");

            var tags_div = $("#tagsdiv-movie_tags");
            tags_div.find("#new-tag-movie_tags").val(post_tags);
            tags_div.find(".tagadd").trigger("click");
        } else if ($("body").hasClass("post-type-series")) {
            var actors_div = $("#tagsdiv-actor");
            actors_div.find("#new-tag-actor").val(stars);
            actors_div.find(".tagadd").trigger("click");

            var release_div = $("#tagsdiv-release");
            release_div.find("#new-tag-release").val(release);
            release_div.find(".tagadd").trigger("click");

            var country_div = $("#tagsdiv-country");
            country_div.find("#new-tag-country").val(country);
            country_div.find(".tagadd").trigger("click");

            var directors_div = $("#tagsdiv-director");
            directors_div.find("#new-tag-director").val(director);
            directors_div.find(".tagadd").trigger("click");

            var genres_div = $("#tagsdiv-genre");
            genres_div.find("#new-tag-genre").val(genre);
            genres_div.find(".tagadd").trigger("click");

            var language_div = $("#tagsdiv-language");
            language_div.find("#new-tag-language").val(language);
            language_div.find(".tagadd").trigger("click");

            var tags_div = $("#tagsdiv-movie_tags");
            tags_div.find("#new-tag-movie_tags").val(post_tags);
            tags_div.find(".tagadd").trigger("click");
        }
    }

    function set_thumbnail(poster_id, post_id) {
        var target = $("#postimagediv .inside");
        $.ajax({
            type: "POST",
            url: ajax_var.ajaxurl,
            data: {
                thumbnail_id: poster_id,
                post_id: post_id,
                action: "yascode_thumb_set",
            },
            success: function (data) {
                target.html(data);
            },
        });
    }

    function insertAdminMessage(status, msg) {
        var status_txt = '';
        if (status == 'success') status_txt = 'notice-success';
        else status_txt = 'notice-error';
        var data = '<div class="msg-body"> <div class="custom-notice ' + status_txt + '"> <p class="content">' + msg + '</p><button type="button" class="notice-dismiss"></button> </div> </div>';
        if ($('.msg-body').length > 0) $('.msg-body').remove();
        $(data).insertAfter('.wp-header-end');
        $('html, body').animate({ scrollTop: '0px' }, 300);
    }

    function getIMDbData() {
        var nonce = $(".search_title").attr("data-security");
        var imdb_id = $(".title_str").val();
        var save_actor_images = $(".save_actor_images_imdb").is(":checked");
        var save_actor_biography = $(".save_actor_biography").is(":checked");
        var save_bg_tmdb = $(".save_post_bg_tmdb").is(":checked");
        var post_id = $("#post_ID").val();
        var thumb_bg = $("#movie_thumb_bg");
        var status_imdb = $(".status_imdb");
        var title_movie = $("#title_movie");
        var fa_title_movie = $("#fa_title_movie");
        var release_movie = $("#release_movie");
        var country_movie = $("#country_movie");
        var language_item = $("#language_movie");
        var genre_movie = $("#genre_movie");
        var imdb_rate_movie = $("#imdb_rate_movie");
        var vote_count = $("#vote_movie");
        var stars_movie = $("#stars_movie");
        var director_movie = $("#director_movie");
        var persian_plot = $("#fa_plot_movie");
        var english_plot = $("#en_plot_movie");
        var metacritic_rate = $("#metacritic_rate");
        var summary_awards = $("#summary_awards");
        var imdb_id_put = $("#imdbid_movie");
        var runtime_movie = $("#runtime_movie");
        var top250 = $("#top250movie");
        var item_age = $("#age_movie");
        var post_type = "movies";
        if ($("body").hasClass("post-type-series")) {
            post_type = "series";
        }
        var release_obj = [];

        $.ajax({
            url: ajax_var.ajaxurl,
            type: "POST",
            data: {
                action: "dataimdb",
                imdb_id: imdb_id,
                post_id: post_id,
                actor_images: save_actor_images,
                actor_bio: save_actor_biography,
                post_bg: save_bg_tmdb,
                security: nonce,
            },
            beforeSend: function () {
                status_imdb.show().css({ display: "flex" });
                if ($('.msg-body').length > 0) $('.msg-body').remove();
            },
            success: function (results) {
                console.log(results);
                if (results.activeresponse == 'server-error') {
                    insertAdminMessage('error', results.msg);
                    status_imdb.hide();
                    $('.title_str').val('');
                } else {
                    if (results.activeresponse == "false") {
                        getIMDbData();
                    } else if (results.activeresponse == "true") {
                        if (results.duration != "") {
                            runtime_movie.val(results.duration + " دقیقه");
                        }
                        if (results.votes != "") {
                            vote_count.val(results.votes);
                        }
                        if (results.age != "") {
                            item_age.val(results.age);
                        }
                        if (post_type == "series") {
                            if (results.main_endyear !== "0") {
                                release_obj.push(results.main_endyear);
                            }
                        }
                        if (results.main_year != "") {
                            release_obj.push(results.main_year);
                        }
                        if (release_obj != "") {
                            release_movie.val(release_obj);
                        }
                        if (results.background_id != "") {
                            thumb_bg.val(results.background_id);
                        }
                        if (results.title != "") {
                            title_movie.val(results.title);
                            var dltext = "";
                            if (post_type == "series") {
                                dltext = "دانلود سریال " + results.title;
                            } else if (post_type == "movies") {
                                var year = "";
                                if (release_obj != "") {
                                    year = release_obj;
                                }
                                dltext = "دانلود فیلم " + results.title + " " + year;
                            }
                            $("#titlediv #title").val(dltext);
                        }
                        if (results.fa_title != "") {
                            fa_title_movie.val(results.fa_title);
                        }
                        if (results.fa_country != "") {
                            country_movie.val(results.fa_country);
                        }
                        if (results.score != "") {
                            metacritic_rate.val(results.score);
                        }
                        if (results.fa_genre != "") {
                            genre_movie.val(results.fa_genre);
                        }
                        if (results.rating != "") {
                            imdb_rate_movie.val(results.rating);
                        }
                        if (results.starnames != "") {
                            stars_movie.val(results.starnames);
                        }
                        if (results.director != "") {
                            director_movie.val(results.director.names);
                        }
                        if (results.imdb_id != "") {
                            imdb_id_put.val(results.imdb_id);
                        }
                        if (results.en_plot_movie != "") {
                            english_plot.val(results.en_plot_movie);
                        }
                        if (results.fa_plot_movie != "") {
                            persian_plot.val(results.fa_plot_movie);
                        }
                        if (results.top250 != "") {
                            top250.val(results.top250);
                        }
                        if (results.summary_awards != "") {
                            summary_awards.val(results.summary_awards);
                        }
                        if (results.languages != "") {
                            language_item.val(results.languages);
                        }
                        if (results.actorsList != "") {
                            $('.section-list .get-actors-field').removeClass('none').fadeIn(300);
                            $('.section-list .get-actors-field .navar.item_actorsp').attr('data-itemid', '0');
                            $('.section-list .get-actors-field .navar.item_actorsp').attr('data-count', results.actorsListCount);
                            $('.section-list .get-actors-field .navar.item_actorsp').attr('data-items', results.actorsList);
                            $('.section-list .get-actors-field .result-navar .count').text(results.actorsListCount);
                        }
                        set_terms(
                            results.starnames,
                            release_obj,
                            results.fa_country,
                            results.fa_genre,
                            results.director.names,
                            results.languages,
                            results.post_tags
                        );
                        if (results.poster_id != "") {
                            set_thumbnail(results.poster_id, post_id);
                        }
                        status_imdb.hide();
                    }
                }

            },
            error: function (jqXhr, textStatus, errorThrown) {
                alert("خطا : خطایی رخ داده صفحه را رفرش کنید و دوباره امتحان کنید");
            },
        });
    }

    $(document).on("click", ".thetvdb_save", function (e) {
        e.preventDefault();
        getThetvdbData();
    });

    function getThetvdbData() {
        var nonce = $(".thetvdb_save").attr("data-security");
        var thetvdb_link = $(".thetvdb_link").val();
        var status_thetvdb = $(".status_thetvdb");
        var post_id = $("#post_ID").val();
        var post_type = "movies";
        if ($("body").hasClass("post-type-series")) {
            post_type = "series";
        }
        var thumb_bg = $("#movie_thumb_bg");
        var smallogo = $("#smalllogo");
        var smallbanner = $("#smallbanner");
        var nav_tabs = $(".yascode-metaboxes > .head-metabox-tabs");
        $.ajax({
            url: ajax_var.ajaxurl,
            type: "POST",
            data: {
                action: "datathetvdb",
                post_id: post_id,
                thetvdb_url: thetvdb_link,
                security: nonce,
            },
            beforeSend: function () {
                status_thetvdb.show().css({ display: "flex" });
                if ($('.msg-body').length > 0) $('.msg-body').remove();
            },
            success: function (results) {
                console.log(results);
                if (results.activeresponse == "false") {
                    getThetvdbData();
                    if (results.msg) insertAdminMessage('error', results.msg);
                } else {
                    status_thetvdb.hide();
                    if (results.msg) insertAdminMessage('success', results.msg);
                    nav_tabs.find(".nav-tab").removeClass("nav-tab-active");
                    nav_tabs.find(".nav-tab").first().addClass("nav-tab-active");
                    nav_tabs
                        .parent()
                        .find(".metaboxes-body > .section-list")
                        .addClass("none");
                    nav_tabs
                        .parent()
                        .find(".metaboxes-body > .section-list")
                        .first()
                        .removeClass("none");
                    $('.thetvdb_link').val('');
                    if (results.background_id != "") {
                        thumb_bg.val(results.background_id);
                    }
                    if (results.logo != "") {
                        smallogo.val(results.logo);
                    }
                    if (results.banner != "") {
                        smallbanner.val(results.banner);
                    }
                }
            },
            error: function (jqXhr, textStatus, errorThrown) {
                alert("خطا : خطایی رخ داده صفحه را رفرش کنید و دوباره امتحان کنید");
            },
        });
    }

    /* -------------------------- */
    /* ------- admin settings ---------- */
    $(document).on("click", ".upload-box-info .modual-selectfile", function (e) {
        e.preventDefault();
        var thisBtn = $(this);
        var image = wp
            .media({
                title: "انتخاب تصویر",
                multiple: false,
            })
            .open()
            .on("select", function (e) {
                var uploaded_image = image.state().get("selection").first();
                var image_id = uploaded_image.toJSON().id;
                var image_url = uploaded_image.toJSON().url;
                thisBtn.parent().find("img").attr("src", image_url);
                thisBtn.parent().find("input").val(image_id);
            });
    });
    $(document).on(
        "change",
        '.input-box.colorpicker-input input[type="color"],.data-box.input-color>.input-box-info input[type="color"]',
        function (e) {
            e.preventDefault();
            var thisBtn = $(this);
            thisBtn.parent().find('input[type="text"]').val(thisBtn.val());
        }
    );
    $(document).on(
        "keyup",
        '.input-box.colorpicker-input input[type="text"],.data-box.input-color>.input-box-info input[type="text"]',
        function (e) {
            e.preventDefault();
            var thisBtn = $(this);
            thisBtn.parent().find('input[type="color"]').val(thisBtn.val());
        }
    );

    $(document).on("click", ".upload-box-info .delete-file", function (e) {
        e.preventDefault();
        $(this).parent().find("input").val("");
    });

    $(document).on("click", ".check-box-info .checkbox-radio", function (e) {
        e.preventDefault();
        var checkBox = $(this).find("input");
        checkBox.prop("checked", !checkBox.prop("checked"));
    });

    $(document).on("click", ".input-listitem > .add-item", function (e) {
        e.preventDefault();
        var item_list = $(this).parent().find(".listitem-list");
        var new_index =
            parseInt(item_list.find(".list-item").last().attr("data-index")) + 1;
        var main_item = item_list.find(".list-item.example-item");
        var clone_item = main_item.clone();
        clone_item.removeClass("example-item");
        clone_item.attr("data-index", new_index);
        clone_item.find("[data-name]").each(function () {
            var $t = $(this);
            var input_name_text = $t.attr("data-name");
            var new_text = input_name_text.replace("index_id", new_index);
            $t.attr("data-name", new_text);
            $t.attr({
                name: $t.attr("data-name"),
            }).removeAttr("data-name");
        });
        $(".input-listitem > .listitem-list > .list-item > .inner-item").slideUp(
            300
        );
        clone_item.appendTo(item_list);
        clone_item.find(".inner-item").slideDown(300);
        $("html, body").animate(
            {
                scrollTop: clone_item.offset().top - 150,
            },
            500
        );
    });

    $(document).on(
        "click",
        ".panel-settings-body > .right-sidebar > .list-menu > li",
        function (e) {
            e.preventDefault();
            var btn = $(this);
            var list = $(".panel-settings-body > .main-panel-body > .sec-body-info");
            var sec = $(this).attr("data-tabid");
            if (sec) {
                var tit = btn.text();
                btn.parent().find("li").removeClass("active");
                btn.addClass("active");
                list.find(".sect-box").addClass("none");
                list.find('.sect-box[data-secid="' + sec + '"]').removeClass("none");
                $(
                    ".panel-settings-body > .main-panel-body > .headline-title > .title-info"
                ).text(tit);
            }
        }
    );

    $(document).on(
        "keyup",
        ".inner-item > .main-content > .input-box.text-input > input.autoComplete",
        function (e) {
            e.preventDefault();
            var item = $(this).parent().parent().parent().parent();
            var tex = $(this).val();
            if (tex.length <= 0) tex = "مدیریت آیتم";
            item.find(".head-item > .title").text(tex);
        }
    );

    $(document).on(
        "click",
        ".listitem-list > .list-item > .head-item > .manage-btns > samp.edit",
        function (e) {
            e.preventDefault();
            var item = $(this).parent().parent().parent();
            item.find(".inner-item").slideToggle(300);
        }
    );

    $(document).on(
        "click",
        ".listitem-list > .list-item > .head-item > .manage-btns > samp.delete",
        function (e) {
            e.preventDefault();
            $(this).parent().parent().parent().remove();
        }
    );
    /* ------------------------------ */
    /* ----- subscriptions ------- */
    if ($.isFunction($.fn.persianDatepicker)) {
        $(function () {
            $("input.datepicker, span.datepicker").persianDatepicker({
                formatDate: "YYYY/0M/0D",
            });
        });

        $(function () {
            $("input.datetimepicker, span.datetimepicker").persianDatepicker({
                formatDate: "YYYY/0M/0D 0h:0m:0s",
            });
        });
    }
    /* --------------------------- */
});