$(function () {
    "use strict";
    $('#menuAdminList').on('click', function (e) {
        e.stopPropagation();
    });

    // Link Generator.
    var $linkGenerator = $('.link-generator');
    if ($linkGenerator.length > 0) {
        $linkGenerator.linkGenerator({
            link: Routing.generate('wi_admin_menu_link_generator_link'),
            linkItems: Routing.generate('wi_admin_menu_link_generator_items'),
            linkModules: Routing.generate('wi_admin_menu_link_generator_modules'),
        });
    }

    var $modal = $('#ajaxSuggestions');
    $('.repportSuggestions').on('click', function () {
        $.ajax({
            type: 'GET',
            url: Routing.generate('wi_admin_core_suggestions_index'),
            success: function (ret) {
                $modal.html(ret).foundation('open');
            },
            error: function () {
                var html='<p>' + $('#ajaxSuggestions').attr('data-ajaxError') + '</p>'
                $modal.html(html).foundation('open');
            }
        });
    });
    //console.log(pathInfo);
    $('#ajaxSuggestions').on('click', '.suggestiosnButton', function () {
        var content = $('#contentSuggestion').val();
        var name = $('#nameSuggestion').val();

        if (content === '' || name === ''){
            $('.validationSuggestionForm').removeClass('hide');
        } else {
            $.ajax({
                type: 'GET',
                url: Routing.generate('wi_admin_core_suggestions_send'),
                data: {
                    content: content,
                    name: name,
                    url: pathInfo,
                },
                success: function (ret) {
                    $modal.html(ret);
                    setTimeout(function () {
                        $modal.foundation('close');
                    }, 4000);
                },
                error: function (ret) {
                    var html='<p>' + $('#ajaxSuggestions').attr('data-ajaxError') + '</p>'
                    $modal.html(html);
                },
            });
        }

    });

    // Uruchomienie TinyMCE dla treści
    $(document).ready(function () {
        var $panelmini = $('.panelminiNotActive');
        $('article.fullContent').before($panelmini);
    });
    var dataBeforeInit = null;
    var imgLink = null;

    $('.linkEditPostHere').on('click', function () {
        $('.adminPanelMini').removeClass('hide');
        $('.buttonEditLiveNotActive').addClass('hide');
        $('.buttonEditLiveActiv').removeClass('hide');
        $('.adminPanelMini').css('display', 'block');
        dataBeforeInit = $('article.fullContent').html();
        tinymce.init({
            selector: 'article.fullContent',
            language: language,
            convert_urls : (base_url != '' ? true : false),
            relative_urls : false,
            remove_script_host : false,
            document_base_url : base_url,
            object_resizing : true,
            inline: true,
            theme: "modern",
            resize: "both",
            fix_list_elements : true,
            image_list: Routing.generate('wi_admin_media_image_list'),
            rel_list: [
                {title: 'Lightbox', value: 'lightbox'},
                {title: 'Canonical', value: 'canonical'},
                {title: 'Nofollow', value: 'nofollow'}
            ],
            image_advtab: true,
            //  plugins: ["style,layer,advhr,advimage,advlink,iespell,inlinepopups,noneditable,xhtmlxtras"],   - tych pluginĂłw nie ma w nowej wersji
            plugins: [
                "advlist autolink image lists charmap print preview hr anchor pagebreak ",
                "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
                "save table contextmenu directionality emoticons template paste textcolor"
            ],
            toolbar1: " insertfile undo redo | styleselect | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | webimpulsLink unlink image | print preview media fullpage | forecolor backcolor emoticons | removeformat",
            toolbar2: "webimpulsRWD | webimpulsMedia",
            visualblocks_default_state: true,
            end_container_on_empty_block: true,
            valid_elements: 'figure[*],aside[*],blockquote[*],article[*],section[*],a[*],abbr[*],acronym[*],address[*],area[*],audio[*],b[*],bdo[*],big[*],blockquote[*],br[*],button[*],caption[*],center[*],cite[*],code[*],col[*],colgroup[*],del[*],dfn[*],dir[*],div[*],dl[*],dd[*],dt[*],em[*],embed[*],fieldset[*],font[*],form[*],h1[*],h2[*],h3[*],h4[*],h5[*],h6[*],hr[*],i[*],iframe[*],img[*],input[*],ins[*],kbd[*],label[*],legend[*],li[*],map[*],menu[*],nobr[*],object[*],ol[*],optgroup[*],option[*],p[*],param[*],pre[*],q[*],s[*],samp[*],script[*],select[*],small[*],source[*],span[*],strike[*],strong[*],sub[*],sup[*],table[*],tbody[*],td[*],textarea[*],tfoot[*],th[*],thead[*],tr[*],tt[*],u[*],ul[*],var[*],' +
            "@[id|class|style|title|dir<ltr?rtl|lang|xml::lang|onclick|ondblclick|"
            + "onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|"
            + "onkeydown|onkeyup],a[rel|rev|charset|hreflang|tabindex|accesskey|type|"
            + "name|href|target|title|class|onfocus|onblur],strong/b,em/i,strike,u,"
            + "#p,-ol[type|compact],-ul[type|compact],-li,br,img[longdesc|usemap|"
            + "src|border|alt=|title|hspace|vspace|width|height|align],-sub,-sup,"
            + "-blockquote,-table[border=0|cellspacing|cellpadding|width|frame|rules|"
            + "height|align|summary|bgcolor|background|bordercolor],-tr[rowspan|width|"
            + "height|align|valign|bgcolor|background|bordercolor],tbody,thead,tfoot,"
            + "#td[colspan|rowspan|width|height|align|valign|bgcolor|background|bordercolor"
            + "|scope],#th[colspan|rowspan|width|height|align|valign|scope],caption,-div,"
            + "-span,-code,-pre,address,-h1,-h2,-h3,-h4,-h5,-h6,hr[size|noshade],-font[face"
            + "|size|color],dd,dl,dt,cite,abbr,acronym,del[datetime|cite],ins[datetime|cite],"
            + "object[classid|width|height|codebase|*],param[name|value|_value],embed[type|width"
            + "|height|src|*],script[src|type],map[name],area[shape|coords|href|alt|target],bdo,"
            + "button,col[align|char|charoff|span|valign|width],colgroup[align|char|charoff|span|"
            + "valign|width],dfn,fieldset,form[action|accept|accept-charset|enctype|method],"
            + "input[accept|alt|checked|disabled|maxlength|name|readonly|size|src|type|value],"
            + "kbd,label[for],legend,noscript,optgroup[label|disabled],option[disabled|label|selected|value],"
            + "q[cite],samp,select[disabled|multiple|name|size],small,"
            + "textarea[cols|rows|disabled|name|readonly],tt,var,big",
            extended_valid_elements: 'div*,div[*],i*,i[*]',
            fontsize_formats: 'inherit 8px 9px 10px 11px 12px 13px 14px 16px 18px 20px 24px 36px 48px',
            style_formats: [
                {title: naglowki, items: [
                        {title: 'h1', format: 'h1'},
                        {title: 'h2', format: 'h2'},
                        {title: 'h3', format: 'h3'},
                        {title: 'h4', format: 'h4'},
                        {title: 'h5', format: 'h5'}
                    ]},
                {title: linki, items: [
                        {title: 'Button Large', selector: 'a, div, span, p', classes : 'button large'},
                        {title: 'Button (podstawowy)', selector: 'a, div, span, p', classes : 'button'},
                        {title: 'Button small', selector: 'a, div, span, p', classes : 'button small'},
                        {title: 'Button tiny', selector: 'a, div, span, p', classes : 'button tiny'},
                        {title: 'expand', selector: 'a, div, span, p', classes : 'expand'},
                        {title: kolory, items: [
                                {title: 'alert', selector: 'a, div, span, p', classes : 'alert'},
                                {title: 'success', selector: 'a, div, span, p', classes : 'success'},
                                {title: 'secondary', selector: 'a, div, span, p', classes : 'secondary'},
                                {title: 'info', selector: 'a, div, span, p', classes : 'info'},
                                {title: 'expand', selector: 'a, div, span, p', classes : 'expand'},
                            ]},
                        {title: zaokraglenie, items: [
                                {title: 'round', selector: 'a, div, span, p', classes : 'round'},
                                {title: 'radius', selector: 'a, div, span, p', classes : 'radius'},
                            ]},
                    ]},
                {title: bloki, items: [
                        {title: 'p', block: 'p'},
                        {title: 'div', block: 'div'},
                        {title: 'pre', block: 'pre'},
                        {title: 'panel', block: 'div', classes : 'panel'}
                    ]},

                {title: kontenery, items: [
                        {title: 'section', block: 'section', wrapper: true, merge_siblings: false},
                        {title: 'article', block: 'article', wrapper: true, merge_siblings: false},
                        {title: 'blockquote', block: 'blockquote', wrapper: true},
                        {title: 'aside', block: 'aside', wrapper: true},
                        {title: 'figure', block: 'figure', wrapper: true}
                    ]},
                {title: interlinia, items: [
                        {title: '1', selector: 'p, div', styles: {'line-height': '100%'}},
                        {title: '1,15', selector: 'p, div', styles: {'line-height': '115%'}},
                        {title: '1,5', selector: 'p, div', styles: {'line-height': '150%'}},
                        {title: '2', selector: 'p, div', styles: {'line-height': '200%'}},
                        {title: '2,5', selector: 'p, div', styles: {'line-height': '250%'}},
                        {title: '3', selector: 'p, div', styles: {'line-height': '300%'}},
                    ]},
                {title: padding, items: [
                        {title: '1px', selector: 'div, p, h1, h2, h3, h4, h5, h6, pre, panel', styles: {'padding': '1px'}},
                        {title: '5px', selector: 'div, p, h1, h2, h3, h4, h5, h6, pre, panel', styles: {'padding': '5px'}},
                        {title: '10px', selector: 'div, p, h1, h2, h3, h4, h5, h6, pre, panel', styles: {'padding': '10px'}},
                        {title: '20px', selector: 'div, p, h1, h2, h3, h4, h5, h6, pre, panel', styles: {'padding': '20px'}},

                    ]},
                {title: callout, items: [
                        {title: 'callout', selector: 'div, p', classes: 'callout'},
                        {title: 'secondary callout', selector: 'div, p', classes: 'callout secondary'},
                        {title: 'primary callout', selector: 'div, p', classes: 'callout primary'},
                        {title: 'callout success', selector: 'div, p', classes: 'callout success'},
                        {title: 'callout warning', selector: 'div, p', classes: 'callout warning'},
                        {title: 'callout alert', selector: 'div, p', classes: 'callout alert'},
                    ]},

            ],
            setup: function (editor) {
                editor.addMenuItem('webimpulsLink', {
                    text: insertLink,
                    icon: 'link',
                    context: 'insert',
                    onclick: function () {
                        imgLink = addLink(imgLink, editor, tinyMCE);
                    },
                });
                editor.addButton('webimpulsLink', {
                    text: '',
                    icon: 'link',
                    tooltip: insertLink,
                    onclick: function () {
                        imgLink = addLink(imgLink, editor, tinyMCE);
                    },
                    onpostrender: function () {
                        var btn = this;
                        editor.on('init', function() {
                            editor.formatter.formatChanged('link', function(state) {
                                btn.active(state);
                            });
                        });
                    }
                });
                editor.addButton('webimpulsRWD', {
                    text: 'Grid RWD',
                    onclick: function () {
                        if(tinyMCE) {
                            tinyMCE.execCommand('mceFocus',false, $('.mceEditor:visible').prev().attr('id'));
                        }
                        $('#GridRWDModal').foundation('open');
                    },
                });
            }
        });
    });

    $('#insertLinkButton').on('click', function () {
        var linkURL = $('#linkURL').val();
        var linkText = (imgLink != null ? imgLink : $('#linkText').val());
        var linkTitle = $('#linkTitle').val();
        var linkRel = $('#linkRel').val();
        var linkGoal = $('#linkGoal').val();
        var classCss = $('#classCss').val();
        $('#linkURL').val('');
        $('#linkText').val('');
        $('#linkTitle').val('');
        $('#classCss').val('');
        var linkData = {
            href: linkURL,
            title: linkTitle,
            class: classCss,
        };
        if(linkRel != 'norel'){
            linkData.rel = linkRel;
        }
        imgLink = null;
        if(linkGoal == 'newWindow'){
            linkData.target = '_blank';
        }
        if(linkURL == ''){
            tinymce.activeEditor.selection.setNode(linkText);
        } else {
            tinymce.activeEditor.selection.setNode(tinymce.activeEditor.dom.create('a', linkData, linkText));
        }
        //tinyMCE.activeEditor.execCommand('mceInsertContent',false, 'ddd');
        $('#linkiModal').foundation('close');
    });

    $('.buttonCloseMiniPanel').on('click', function () {
        $('.adminPanelMini').fadeOut(1000);
    });
    $('.cancelChangeMiniButton').on('click', function () {
        tinymce.remove();
        $('article.fullContent').html(dataBeforeInit);
        $('.adminPanelMini').fadeOut(1000);
        $('.buttonEditLiveNotActive').removeClass('hide');
        $('.buttonEditLiveActiv').addClass('hide');
    });
    $('.saveChangeMiniButton').on('click', function () {
        var content = JSON.stringify($('article.fullContent').html());
        if(typeEditPage == 'page'){
            var address = 'wi_admin_pages_live_edit'
            var data = {
                page: {
                    content: content,
                }
            };
        } else if(typeEditPage == 'news'){
            var address = 'wi_admin_news_live_edit'
            var data = {
                news: {
                    content: content,
                }
            };
        }
        $.ajax({
            type: 'POST',
            url: Routing.generate(address, {'id': idEditPage}),
            data: data,
            success: function (ret) {
                if(ret.status == true){
                    tinymce.remove();
                    $('.saveSuccess').removeClass('hide');
                    $('.adminPanelMini').delay(2000).fadeOut(1000);
                    $('.buttonEditLiveNotActive').removeClass('hide');
                    $('.buttonEditLiveActiv').addClass('hide');
                } else {
                    $('.saveError').removeClass('hide');
                }
            },
            error: function (ret) {
                $('.saveError').removeClass('hide');
            }
        })

    });

    $('.insertBut').bind('click', function() {
        if(tinyMCE) {
            var wartosc = $(this).attr('id');
            var grid = $('.'+wartosc).html();
            //alert(grid);
            tinyMCE.activeEditor.execCommand('mceInsertContent',false, grid);
            $('#GridRWDModal').foundation('close');
        }
    });
});


function addLink(imgLink, editor, tinyMCE){
    imgLink = null;
    if(tinyMCE) {
        tinyMCE.execCommand('mceFocus',false, $('.mceEditor:visible').prev().attr('id'));
    }
    var node = editor.selection.getNode()
    var rng = editor.selection.getRng();
    if(node.nodeName == 'A') {
        $('#linkURL').val(node.href);
        $('#linkText').val(node.text);
        $('#linkTitle').val(node.title);
        $('#classCss').val(node.className);

        var rel = node.rel;
        if (rel == 'lightbox') {
            $('#linkRel').val('lightbox');
        } else if (rel == 'canonical') {
            $('#linkRel').val('canonical');
        } else if (rel == 'nofollow noopener') {
            $('#linkRel').val('nofollow');
        } else {
            $('#linkRel').val('norel');
        }

        if (node.target) {
            $('#linkGoal').val('newWindow');
        }
        editor.selection.select(node)
    } else if(node.nodeName == 'IMG') {
        imgLink = node;
        if(rng.endContainer.nodeName == 'A'){
            var rngNodeParent = rng.endContainer;
            $('#linkURL').val(rngNodeParent.href);
            $('#linkText').val(rngNodeParent.text);
            $('#linkTitle').val(rngNodeParent.title);
            $('#classCss').val(rngNodeParent.className);
            var rel = rngNodeParent.rel;
            if (rel == 'lightbox') {
                $('#linkRel').val('lightbox');
            } else if (rel == 'canonical') {
                $('#linkRel').val('canonical');
            } else if (rel == 'nofollow noopener') {
                $('#linkRel').val('nofollow');
            } else {
                $('#linkRel').val('norel');
            }

            if (rngNodeParent.target) {
                $('#linkGoal').val('newWindow');
            }
            editor.selection.select(rngNodeParent)
        }
        //console.log(editor.selection.getRng());
    } else if (rng.startOffset != rng.endOffset) {
        $('#linkText').val(rng.startContainer.data.substr(rng.startOffset, rng.endOffset));
    }
    if(imgLink != null){
        $('.linkTextHideImg').addClass('hide');
    }
    $('#linkiModal').foundation('open');
    return imgLink;
}