jQuery(function($) {

    $('#smat-button').on('click', function(e) {
        e.preventDefault();

        if ($('#smat-shortcode-dialog').length === 0) {

            var html = '<div id="smat-shortcode-dialog" title="' + smatData.title + '" style="display:none">' +
                '<div id="smat-tabs"><ul>';

            for (var key in smatData.tabs)
                html += '<li><a href="#smat-tab-' + key + '">' + smatData.tabs[key].label + '</a></li>';

            html += '</ul>';

            for (var key in smatData.tabs) {

                html += '<div id="smat-tab-' + key + '">';

                if (smatData.tabs[key].message)
                    html += '<p>' + smatData.tabs[key].message + '</p>';

                html += '<p>';

                if (Array.isArray(smatData.tabs[key].shortcodes)) {
                    smatData.tabs[key].shortcodes.forEach(function(sc){
                        var tooltip = sc.tooltip ? 'title="' + sc.tooltip + '"' : '';
                        html += (sc.id === 'hr') ? '<hr>' : '<a ' + tooltip + ' class="button smat-shortcode-btn" data-shortcode="'+ sc.id + '">' + sc.label + '</a>';
                    });
                }

                html += '</p></div>';
            }

            html += '</div></div>';

            $('body').append(html);
        }

        $('#smat-shortcode-dialog').dialog({
            modal: true,
            appendTo: $('#poststuff'),
            width: smatData.width,
            height: smatData.height,
            buttons: [{
                text: smatData.cancel,
                class: 'button',
                click: function() { $(this).dialog('close'); }
            }],
            open: function() {
                $(this).find('#smat-tabs').tabs();
            }
        });
    });

    // CLIC EN SHORTCODE.
    $(document).on('click', '.smat-shortcode-btn', function(e) {
        e.preventDefault();

        var scId   = $(this).data('shortcode');
        var scData = null;

        for (var key in smatData.tabs) {
            smatData.tabs[key].shortcodes.forEach(function(sc) {
                if (sc.id === scId)
                    scData = sc;
            });
        }

        if (!scData) return;

        // Sin atributos → insertar directo.
        if (!scData.atts) {
            insertShortcode('[' + scId + ']');
            return;
        }

        // Con atributos → mini formulario.
        var formHtml = '<div class="smat-attr-form">';

        for (var attr in scData.atts) {

            var attrData = scData.atts[attr];

            formHtml += '<p>';
            formHtml += '<label>' + attrData.label + '</label><br>';

            if (attrData.options) {
                formHtml += '<select class="smat-attr-input" data-attr="'+ attr +'">';
                for (var optValue in attrData.options) {
                    var selected = (optValue === attrData.default) ? ' selected' : '';
                    formHtml += '<option value="'+ optValue +'"'+ selected +'>' + attrData.options[optValue] + '</option>';
                }
                formHtml += '</select>';
            } else {
                var type = attrData.type ? attrData.type : 'text';
                formHtml += '<input type="'+ type +'" class="smat-attr-input" data-attr="'+ attr +'" value="'+ attrData.default +'"';
                if (attrData.min) formHtml += ' min="'+ attrData.min +'"';
                if (attrData.max) formHtml += ' max="'+ attrData.max +'"';
                formHtml += ' />';
            }

            formHtml += '</p>';
        }

        formHtml += '</div>';

        $('<div>' + formHtml + '</div>').dialog({
            modal: true,
            title: scData.label,
            buttons: [
                {
                    text: smatData.insert,
                    class: 'button button-primary',
                    click: function() {

                        var shortcode = '[' + scId;

                        $(this).find('.smat-attr-input').each(function() {
                            var attr = $(this).data('attr');
                            var val  = $(this).val().trim();
                            if (val) shortcode += ' ' + attr + '="' + val + '"';
                        });

                        shortcode += ']';
                        insertShortcode(shortcode);
                        $(this).dialog('close');
                    }
                },
                {
                    text: smatData.cancel,
                    class: 'button',
                    click: function() { $(this).dialog('close'); }
                }
            ]
        });

    });

    // FUNCIÓN AUXILIAR GLOBAL.
    function insertShortcode(shortcode) {
        if (typeof tinymce !== 'undefined' && tinymce.get('content') && !tinymce.get('content').isHidden()) {
            tinymce.get('content').focus();
            tinyMCE.activeEditor.execCommand('mceInsertContent', false, shortcode);
        } else {
            var textarea = $('#content');
            textarea.val(textarea.val() + shortcode);
        }
        $('#smat-shortcode-dialog').dialog('close');
    }

});