<script>

    function moveUpMessage(){ new Noty({ text: '{sections:messages:3}', type: 'warning' }).show(); }
    function moveDownMessage(){ new Noty({ text: '{sections:messages:4}', layout: 'topRight', type: 'warning' }).show(); }
    function topMenuMessage(){ new Noty({ text: '{sections:messages:6}', type: 'warning' }).show(); }
    function downMenuMessage(){ new Noty({ text: '{sections:messages:7}', type: 'warning' }).show(); }
    function sectionVisibleMessage(){ new Noty({ text: '{sections:messages:8}', type: 'warning' }).show(); }
    function sectionHiddenMessage(){ new Noty({ text: '{sections:messages:9}', type: 'warning' }).show(); }

    $(document).ready(function () {

        {if isset($messages.saved)} new Noty({ text: '{sections:messages:0}', type: 'success' }).show(); {/if}
        {if isset($messages.deleted)} new Noty({ text: '{sections:messages:1}', type: 'success' }).show(); {/if}
        {if isset($messages.sorted)} new Noty({ text: '{sections:messages:2}', type: 'success' }).show();{/if}

        {if isset($errors.not_saved)} new Noty({ text: '{sections:errors:0}', type: 'error' }).show(); {/if}
        {if isset($errors.section_not_found)} new Noty({ text: '{sections:errors:1}', type: 'error' }).show();{/if}
        {if isset($errors.name)} new Noty({ text: '{sections:errors:2}', type: 'error' }).show(); {/if}
        {if isset($errors.fileName)} new Noty({ text: '{sections:errors:3}', type: 'error' }).show(); {/if}
        {if isset($errors.fileNameExists)} new Noty({ text: '{sections:errors:4}', type: 'error' }).show(); {/if}
        {if isset($errors.htaccess)} new Noty({ text: '{sections:errors:5}', type: 'error' }).show(); {/if}
        {if isset($errors.serializations)} new Noty({ text: '{sections:errors:6}', type: 'error' }).show(); {/if}
        {if isset($errors.fileNameProhibited)} new Noty({ text: '{sections:errors:7}', type: 'error' }).show(); {/if}
        {if isset($errors.fileNameCharacters)} new Noty({ text: '{sections:errors:8}', type: 'error' }).show(); {/if}
        {if isset($errors.error_typeContent)} new Noty({ text: '{sections:errors:13}', type: 'error' }).show(); {/if}
        {if isset($errors.error_parent_typeContent)} new Noty({ text: '{sections:errors:15}', type: 'error' }).show(); {/if}
        {if isset($errors.error_parent_type)} new Noty({ text: '{sections:errors:16}', type: 'error' }).show(); {/if}
        {if isset($errors.sectionType)} new Noty({ text: '{sections:errors:13}', type: 'error' }).show(); {/if}
        {if isset($errors.externalLink)} new Noty({ text: 'Укажите ссылку на модальное окно или внешнюю ссылку', type: 'error' }).show(); {/if}

    });

{if isset($action) && ($action eq 'add' OR $action eq 'edit')}

    $(function () { function e() { alias_touched || $("#alias").val(a()), meta_title_touched || $("#meta_title").val(m()), keywords_touched || $("#keywords").val(i()), description_touched || $("#description").val(t()), fileName_touched || $("#fileName").val(n()) } function a() { return name = $("#name").val() } function m() { return name = $("#name").val() } function i() { return name = $("#name").val() } function t() { return name = $("#name").val() } function n() { return fileName = $("#name").val(), fileName = fileName.replace(/[\s]+/gi, "{$config.filename_word_separator}"), fileName = l(fileName), fileName = fileName.replace(/[^0-9a-z_\-]+/gi, "").toLowerCase() } function l(e) { for (var a = "А-а-Б-б-В-в-Ґ-ґ-Г-г-Д-д-Е-е-Ё-ё-Є-є-Ж-ж-З-з-И-и-І-і-Ї-ї-Й-й-К-к-Л-л-М-м-Н-н-О-о-П-п-Р-р-С-с-Т-т-У-у-Ф-ф-Х-х-Ц-ц-Ч-ч-Ш-ш-Щ-щ-Ъ-ъ-Ы-ы-Ь-ь-Э-э-Ю-ю-Я-я".split("-"), i = "A-a-B-b-V-v-G-g-G-g-D-d-E-e-E-e-E-e-ZH-zh-Z-z-I-i-I-i-I-i-J-j-K-k-L-l-M-m-N-n-O-o-P-p-R-r-S-s-T-t-U-u-F-f-H-h-TS-ts-CH-ch-SH-sh-SCH-sch-'-'-Y-y-'-'-E-e-YU-yu-YA-ya".split("-"), t = "", n = 0, l = e.length; l > n; n++) {
        var o = e.charAt(n),c = a.indexOf(o);t += c >= 0 ? i[c] : o
    } return t }
        alias_touched = !0,
            meta_title_touched = !0,
            keywords_touched = !0,
            description_touched = !0,
            fileName_touched = !0,
        ($("#alias").val() == a() || "" == $("#alias").val()) && (alias_touched = !1),
        ($("#meta_title").val() == i() || "" == $("#meta_title").val()) && (meta_title_touched = !1),
        ($("#keywords").val() == i() || "" == $("#keywords").val()) && (keywords_touched = !1),
        ($("#description").val() == t() || "" == $("#description").val()) && (description_touched = !1),
        ($("#fileName").val() == n() || "" == $("#fileName").val()) && (fileName_touched = !1),
            $("#alias").change( function () { alias_touched = !0 }),
            $("#meta_title").change( function () { meta_title_touched = !0 }),
            $("#keywords").change( function () { keywords_touched = !0 }),
            $("#description").change( function () { description_touched = !0 }),
            $("#fileName").change( function () { fileName_touched = !0 }),
            $("#name").keyup( function () { e() })
    });
{/if}

    $(document).on('click', '.top_menu', function() {
        var id = $(this).attr("data-id");
        $.post("{$adminUrl}/sections?action=menu", { id: id }, function(data){
            console.log(data.check);
            if (data.check === 1) {
                {*$.jGrowl('{sections:messages:6} 👍', { theme: 'bg-primary alert-rounded', position: 'top-right', life: 1000 });*}
                new Noty({ text: '{sections:messages:6} 👍', layout: 'topCenter', type: 'warning' }).show();
            } else{
                {*$.jGrowl('{sections:messages:7} 👍', { theme: 'bg-primary alert-rounded', position: 'top-right', life: 1000 });*}
                new Noty({ text: '{sections:messages:7} 👍', layout: 'topCenter', type: 'warning' }).show();
            }
        }, 'json');
    });

    $(document).ready(function() {
        var type = $('#type :selected').val();
        if (type === 'plain') {
            $('#typeContent').prop("disabled", true);
            $('.pages').hide();
        }

        $('#type').change(function() {
            var typeContent = $(this).val();
            $('#typeContent').prop("disabled", true);
            $('.pages').hide();
            if (typeContent === 'tree') {
                $('.pages').show();
                $('#typeContent').prop("disabled", false);
            }
        });


        // добавление информации к картинке в галереи
        $(document).on('click', '.edit_image', function() {
            var $this =  $(this);
            var confirm = $this.attr('data-confirm'),
                imageId = $this.attr('data-id'),
                title = $this.attr('data-title'),
                alias = $this.attr('data-alias'),
                description =$this.attr('data-description'),
                link = $this.attr('data-link'),
                position = $this.attr('data-position');

            bootbox.prompt({
                title: confirm,
                message:'<div class="form-group">' +
                    '<label class="form-group-float-label is-visible">Заголовок</label>'+
                    '<input type="text" class="form-control" id="image_title" value="'+title+'" />' +
                    '</div>' +
                    '<div class="form-group">' +
                    '<label class="form-group-float-label is-visible">Альтернативный заголовок</label>'+
                    '<input type="text" class="form-control" id="image_alias" value="'+alias+'" />' +
                    '</div>' +
                    '<div class="form-group">' +
                    '<label class="form-group-float-label is-visible">Описание</label>' +
                    '<textarea rows="3" cols="3" class="form-control" placeholder="" id="image_description">'+description+'</textarea>'+

                    '</div>' +
                    '<div class="form-group">' +
                    '<label class="form-group-float-label is-visible">Ссылка</label>'+
                    '<input type="text" class="form-control" id="image_link" value="'+link+'" />' +
                    '</div>',
                inputType: 'select',
                value: position,
                inputOptions: [
                    { text: 'По умолчанию', value: 'default' },
                    { text: 'Банер', value: 'banner' },
                    { text: 'Блок', value: 'block' },
                    { text: 'Карусель', value: 'carousel' },
                    { text: 'Модальное окно', value: 'modal' },
                    { text: 'Баннер для PDF', value: 'pdf' }
                ],
                buttons: {
                    cancel: { label: '{general:cancel}', className: 'btn-sm btn-light' },
                    confirm: { label: "{general:yes}", className: 'btn-sm  btn-primary' }
                },
                callback: function (result) {
                    console.log(result);

                    var link = $("#image_link").val(), title = $("#image_title").val(), alias = $("#image_alias").val(), description = $("#image_description").val();


                    if (result !== null) {
                        $.post('{$adminUrl}/section?action=editPictureInfo', { imageId: imageId, 'picture[title]': title, 'picture[alias]' : alias, 'picture[description]': description, 'picture[link]': link, 'picture[position]' : result }, function (response) {
                            if (response.status === 200) {
                                console.log(imageId)
                                $('#edit_image_' + imageId).attr('data-title', response.title).attr('data-alias', response.alias).attr('data-description', response.description).attr('data-link', response.link).attr('data-position', response.position);
                                $('#meta_image_' + imageId + ' #im_title').text(response.title);
                                $('#meta_image_' + imageId + ' #im_alias').text(response.alias);
                                $('#meta_image_' + imageId + ' #im_description').text(response.description);
                                $('#meta_image_' + imageId + ' #im_link').text(response.link);
                                $('#meta_image_' + imageId + ' #im_position').text(response.position);
                            }
                        }, 'json');
                    }
                }
            })
        });

        $(document).on('click', '#enableIcon', function(){
            if (!$(this).is(':checked'))
                $('#icon').val('');
        });

        $('#selectUrlType').change(function(){
            console.log($('#selectUrlType').val())
            if($('#selectUrlType').val() === 'external') {
                if (!$("#icon-urlType").hasClass("show"))
                    $('#icon-urlType').addClass("show");
            } else {
                if ($("#icon-urlType").hasClass("show"))
                    $('#icon-urlType').removeClass("show");
            }
        });
    });

    $(document).on('click', '.sortable_save_button', function () {
        var ids = new Array();
        $('.sortable tr').each(function () {
            console.log($(this).attr('data-id'))

            ids.push($(this).attr('data-id'));
        })
        $.post( "{$adminUrl}/sections?action=reorder", { sectionIds : ids }, function( data ) {
            $('.sortable_footer_navbar').removeClass('show');
            // location.reload();
        });
    })
    $(document).on('click', '.sortable_cancel_button', function () {
        $('.sortable_footer_navbar').removeClass('show');
        location.reload();
    })


    // сортировка галереи
    // $("#fileList").sortable({
    //     items: "> figure.gallery-item",
    //     opacity: 0.5,
    //     revert: true,
    //     scroll: true,
    //     tolerance: "pointer",
    //     handle: ".move_zone",
    //     cursor: "move",
    //     scrollSensitivity: 50,
    //     scrollSpeed: 50,
    //     forcePlaceholderSize: true,
    //     connectWith: '.gallery-product',
    //     placeholder: "gallery-sortable",
    //     stop : function () {
    //         $('.btn-sorting').addClass('show');
    //     }
    // }).disableSelection();
    // // применить сортировку галереи
    // $(document).on("click", ".btn-sorting" , function() {
    //     var module = $(this).attr('data-module'), action = $(this).attr('data-action');
    //     var ids = new Array();
    //     $('#fileList figure.gallery-item-images').each(function() {
    //         ids.push($(this).attr("data-id"));
    //     });
    //
    //     $.ajax({
    //        url: "{$adminUrl}/"+module,
    //         method: "POST",
    //         data: { imageIds: ids, action: action },
    //         success: function () {
    //             $("#fileList").load(location.href + " figure.gallery-item-images");
    //             new Noty({ text: 'Фотогалерея отсортирована', type: 'success' }).show();
    //             $('.btn-sorting').removeClass('show');
    //         }
    //     });
    // });

    // $("#section_list").sortable({
    //     items: "> tr",
    //     opacity: 0.5,
    //     revert: true,
    //     scroll: true,
    //     tolerance: "pointer",
    //     handle: ".move_zone",
    //     scrollSensitivity: 50,
    //     scrollSpeed: 50,
    //     cursor: "move",
    //     connectWith: '.sections_list',
    //     placeholder: "ui-sortable-handle",
    //     update	   : function(event, ui) {
    // 	    var sectionIds = new Array();
    //
    //         $('#section_list tr').each(function() {
    //             sectionIds.push($(this).attr("data-id"));
    // 	    });

    // console.log(sectionIds);
    // $.ajax({
    //    url:"{$adminUrl}/sections?action=reorder",
    //             method:"POST",
    //             data:{ sectionIds: sectionIds },
    //             success:function(data) {
    //                 location.reload();
    //                 //alert(data);
    //             }
    //         });
    //     }
    // }).disableSelection();

</script>