// Tiny MCE
$(function () {
    "use strict";

    var imgLink = null;
    tinymce.init({
        selector: '.tinyMCE',
        language: language,
        convert_urls : (base_url != '' ? true : false),
        relative_urls : false,
        remove_script_host : false,
        document_base_url : base_url,
        object_resizing : true,
        theme: "modern",
        resize: "both",
        height: "400",
        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'}
        ],
        content_css: [sciezkaCss, sciezkaCss2],
        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 link imagetools"
        ],
        toolbar1: "insertfile undo redo | styleselect fontsizeselect | 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|placeholder],"
        + "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,video[*], i*,i[*]",
        extended_valid_elements: 'div*,div[*], i*,i[*]',
        verify_html: true,
        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: 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.on('init', function (e) {
                editor.getContainer().className += ' ' + editor.getElement().className;
            });
            editor.addButton('webimpulsRWD', {
                text: 'Grid RWD',
                onclick: function () {
                    if(tinyMCE) {
                        tinyMCE.execCommand('mceFocus',false, $('.mceEditor:visible').prev().attr('id'));
                    }
                    $('#GridRWDModal').foundation('open');
                },
            });
            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('webimpulsMedia', {
                text: 'Media library',
                onclick: function () {
                    if(tinyMCE) {
                        tinyMCE.execCommand('mceFocus',false, $('.mceEditor:visible').prev().attr('id'));
                    }
                    var directory = '/';
                    loadMedia();
                    $('#mediaModal').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();
        //console.log(classCss);
        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.setContent(linkText);
        } else {
            tinymce.activeEditor.selection.setNode(tinymce.activeEditor.dom.create('a', linkData, linkText));
        }
       // tinymce.activeEditor.selection.setNode(tinymce.activeEditor.dom.create('a', linkData, linkText));

        $('#linkURL').val('');
        $('#linkText').val('');
        $('#linkTitle').val('');
        $('#classCss').val('');

        $('#linkiModal').foundation('close');
    });
    $('.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');
        }
    });
});

var $returnAjax = $('#returnAjax');

function loadMedia(directory = null) {
    $.ajax({
        type: 'GET',
        url: Routing.generate('wi_admin_media_tinymce_media_view'),
        data: {
            directory: directory,
        },
        cache: false,
        success: function (html) {
            afterLoadAjax(html);
        }
    });
}

$returnAjax
    .on('click', '.item[data-url] .item-name', function () {
        var link = $(this).closest('.item[data-url]').data('url');
        loadMedia(link);
    })
    .on('click', '.back[data-url]', function () {
        var link = $(this).data('url');
        loadMedia(link);
    })
    .on('click', '.media-view', function () {
        // Widok listy.
        if ($(this).data('view') == 'grid') {
            localStorage.setItem('wicms3_media_modal_list_view', 0);
        } else {
            localStorage.setItem('wicms3_media_modal_list_view', 1);
        }
        changeView();
    })
    .on('click', '.item[data-info] .my-item-thumbnail, .item[data-info] .item-name', function (e) {
        if ($('#gallery-main').hasClass('without-info')) {
            $('#gallery-main').removeClass('without-info');
            $('#gallery-info').removeClass('hide');
        }

        var data = $(this).closest('.item[data-info]').data();
        var image = $('#media-info-image');
        image.empty();
        $('#media-info-icon').empty().append($('<i class="'+data.icon+'"></i>'));
        $('#media_url').val(data.link);
        $('#media-info-name').text(data.filename);
        $('#media-info-url').val(data.link);
        $('#media-info-size span').text(data.size);
        $('#media-info-type span').text(data.extension);
        $('#insert-button').data('link', data.link).data('filename', data.filename);
        var dimensions = $('#media-info-dimensions');

        if (data.dimensionWidth != '' && data.dimensionHeight != '') {
            dimensions.show();
            dimensions.find('span').text(data.dimensionWidth+' x '+data.dimensionHeight+' px')
        } else {
            dimensions.hide();
        }

        if (data.isImage) {
            image.append($('<img src="'+data.link+'?thumb=200x200">'));
        } else {
            image.append($('<i class="'+data.icon+'"></i>'));
        }
    })
    .on('click', '[data-open="rename-form"]', function () {
        var oldName = $(this).data('old-name');
        $('#rename_oldName').val(oldName);
    })
    .on('click', '[data-open="delete-form"]', function () {
        var name = $(this).data('name');
        $('#delete_delete').val(name)
    })
    .on('click', '.insert-file-hover', function () {
        if (tinyMCE) {
            var $item = $(this).closest('[data-link][data-filename]');
            tinyMCE.activeEditor.execCommand('mceInsertContent', false, '<img src="'+$item.data('link')+'" alt="'+$item.data('filename')+'">')
            $('#mediaModal').foundation('close');
        }
    })
    .on('dblclick', '.item[data-link][data-filename]', function () {
        if (tinyMCE) {
            tinyMCE.activeEditor.execCommand('mceInsertContent', false, '<img src="'+$(this).data('link')+'" alt="'+$(this).data('filename')+'">')
            $('#mediaModal').foundation('close');
        }
    })
    .on('click', '#copy-to-clipboard', function () {
        $('#media-info-url').select();
        document.execCommand('copy');
        $('.infoCopyUrl').css({'opacity': 1, 'z-index': 1}).animate({'opacity': 0, 'z-index': -1}, 3000);
    })
    .on('click', '#insert-button', function () {
        if (tinyMCE) {
            tinyMCE.activeEditor.execCommand('mceInsertContent', false, '<img src="'+$(this).data('link')+'" alt="'+$(this).data('filename')+'">')
            $('#mediaModal').foundation('close');
        }
    })
;
$('body')
    .on('submit', '#nameNewFolderSend', function (e) {
        e.preventDefault();
        var directory = $('#media-drop-area').data('directory');

        $.ajax({
            type: 'POST',
            url: Routing.generate('wi_admin_media_tinymce_media_view', { directory: directory }),
            data: {
                add_folder: 1,
                name: $('#nameNewFolder').val(),
            },
            success: function (html) {
                $('#addFolder').foundation('close');
                afterLoadAjax(html);
            }
        });
    })
    .on('submit', '#renameForm', function (e) {
        e.preventDefault();
        var directory = $('#media-drop-area').data('directory');

        $.ajax({
            type: 'POST',
            url: Routing.generate('wi_admin_media_tinymce_media_view', { directory: directory }),
            data: {
                rename: 1,
                name: $('#rename_name').val(),
                oldName: $('#rename_oldName').val(),
            },
            success: function (html) {
                $('#rename-form').foundation('close');
                afterLoadAjax(html);
            }
        });
    })
    .on('submit', '#deleteForm', function (e) {
        e.preventDefault();
        var directory = $('#media-drop-area').data('directory');

        $.ajax({
            type: 'POST',
            url: Routing.generate('wi_admin_media_tinymce_media_view', { directory: directory }),
            data: {
                delete: $('#delete_delete').val(),
            },
            success: function (html) {
                $('#delete-form').foundation('close');
                afterLoadAjax(html);
            }
        });
    })
;

function changeView() {
    var $items = $('.gallery-wrapper .items');

    if (parseInt(localStorage.getItem('wicms3_media_modal_list_view'))) {
        $items.addClass('list')
    } else {
        $items.removeClass('list')
        localStorage.setItem('wicms3_media_modal_list_view', 0);
    }
}

function mediaUploader() {
    var $dropArea = $('#media-drop-area.media-drop-area');

    if ($dropArea.length > 0) {
        var $currentNumber = $('#current-number');
        var $totalNumber = $('#total-number');
        var $uploadProgress = $('#upload-progress');

        $dropArea
            .on('dragenter', function () {$(this).addClass('dragover');})
            .on('dragover', function () {$(this).addClass('dragover');})
            .on('dragleave', function () {$(this).removeClass('dragover');})
            .on('drop', function () {$(this).removeClass('dragover');})
        ;

        var uploader = new plupload.Uploader({
            browse_button: 'media-button',
            drop_element: 'media-drop-area',
            url: Routing.generate('wi_admin_media_upload', { d: $dropArea.data('directory')}),
            chunk_size: '200kb',
            max_retries: 3,
            unique_names: false,
            filters: {
                mime_types: [
                    { title: 'Image files', extensions: 'jpg,jpeg,png' }
                ]
            },
            init: {
                FilesAdded: function (up, files) {
                    $currentNumber.text('0');
                    $totalNumber.text(files.length);
                    uploader.start();
                    $('#upload-progress-wrapper').foundation('open');
                },
                UploadProgress: function (up, file) {
                    $uploadProgress
                        .find('span').width(up.total.percent + '%')
                        .find('p').text(up.total.percent + '%')
                    ;
                    $currentNumber.text(up.total.uploaded);
                },
                UploadComplete: function (up, files) {
                    $uploadProgress
                        .find('span').width(up.total.percent + '%')
                        .find('p').text(up.total.percent + '%')
                    ;
                    $currentNumber.text(up.total.uploaded);
                    loadMedia();
                    $('#upload-progress-wrapper').foundation('close');
                    $uploadProgress
                        .find('span').width(0 + '%')
                        .find('p').text(0 + '%')
                    ;
                }
            }
        });

        // Inicjalizacja mechanizmu do przesyłania plików.
        uploader.init($dropArea.data('directory'));
    }
}

function afterLoadAjax(html) {
    var directory = $('#media-drop-area').data('directory');
    $returnAjax.html(html).foundation();
    mediaUploader();
    changeView();

    if (directory != null) {
        $('#nameNewFolderSend').attr('data-directory', directory);
    }
}
