(function (window) {
    var self = null;
    var MultiTag = {
        init: function () {
            self = this;

            self.actions.loadData(function () {
                $('input[id^="multitag_"]').click(function () {
                    // Actualizar hidden con secciones/temas/substemas
                    self.actions.updateHidden($(this).attr('data-type'));
                });

                $('#btnCombMtag').click(function () {
                    self.actions.makeCombinations();
                });

                $('#divCombinaciones').on('shown.bs.modal', function (e) {
                    //función copiar al clipboard
                    self.actions.bindCopyLink();
                });

                $('#mtag-seccion-search').on('blur', {type: 'seccion'}, self.filtrarItems);
                $('#mtag-seccion-search').on('keyup', {type: 'seccion'}, self.filtrarItems);
                $('#mtag-tema-search').on('blur', {type: 'tema'}, self.filtrarItems);
                $('#mtag-tema-search').on('keyup', {type: 'tema'}, self.filtrarItems);
                $('#mtag-subtema-search').on('blur', {type: 'subtema'}, self.filtrarItems);
                $('#mtag-subtema-search').on('keyup', {type: 'subtema'}, self.filtrarItems);
            });
        },
        filtrarItems: function (event){
            var elements = $('#multitag_lista_'+event.data.type+' .checkbox');
            var total = elements.length;
            for (var i = 0; i < total; i++) {
                if (elements[i].dataset.title.indexOf(event.target.value) > -1) {
                    $(elements[i]).show();
                } else {
                    $(elements[i]).hide();
                }
            }
        },
        instalaClipboardHtml5: function(element) {
            var $elem = $(element);
            var $link_rel = $elem.parents("div.row").first().find(".link_rel");
            var clipboard = new ClipboardJS($elem.get(0),{
                    text: function(trigger) {
                        return $link_rel.find('a').attr('href');
                    }
                });
            clipboard.on('success', function(e) {
                $link_rel.animate({
                    backgroundColor: "#dff0d8"
                }, 500).animate({
                    backgroundColor: "#fff"
                }, 500);
                return true;
            });
        },
        actions: {
            bindCopyLink: function () {
                var $copy = $('#divCombinaciones #lista_enlaces .copiar-link-mtag');

                $copy.on('click', function(e) {
                    e.preventDefault();
                });

                $copy.each( function() {
                    // Para el copiar al Clipboard
                    self.instalaClipboardHtml5(this);
                });
            },
            makeCombinations: function () {
                var secciones = $('#multitag_lista_seccion').find('input[type="checkbox"]:checked');
                var temas = $('#multitag_lista_tema').find('input[type="checkbox"]:checked');
                var subtemas = $('#multitag_lista_subtema').find('input[type="checkbox"]:checked');
                var btnCopy = '<a href="#" class="mar-bot15 iblock noborder pt9 monlight mar-lef-rig0 hovgray radius15 noborder int-txtnextgray2 txtnextgray2 pad-top-bot4 pad-lef-rig15 int-nextgray2 nextgray2 btn btn-xs copiar-link-mtag" title="Copiar enlace"><span class="txtnextgray2 int-txtnextgray2 glyphicon glyphicon-link"></span> Copiar enlace</a>';

                $('#divCombinaciones #lista_enlaces').html('');

                var prontus = '';
                if (ProntusConf['multitag-incluir-prontus_id-url'] == 1) {
                    prontus = '/' + Admin.prontus_id;
                }

                $.each(secciones, function () {
                    var sf = $(this).attr('data-friendly');
                    var sn = $(this).attr('data-title');
                    let link_secc = '<a target="_blank" href="'+ prontus +'/seccion/' + sf + '/p/1" class="lv1">'+ prontus +'/seccion/' + sf + '/p/1</a>';

                    $('#divCombinaciones #lista_enlaces').append(self.row.getHtmlTemplateModal(sn,btnCopy,link_secc));

                    $.each(temas, function () {
                        var tf = $(this).attr('data-friendly');
                        var tn = $(this).attr('data-title');
                        let link_tem = '<a target="_blank" href="'+ prontus +'/seccion/' + sf + '/tema/' + tf + '/p/1" class="lv2">'+ prontus +'/seccion/' + sf + '/tema/' + tf + '/p/1</a>';

                        $('#divCombinaciones #lista_enlaces').append(self.row.getHtmlTemplateModal(sn+' &raquo; '+tn,btnCopy,link_tem));

                        $.each(subtemas, function () {
                            var stf = $(this).attr('data-friendly');
                            var stn = $(this).attr('data-title');
                            let link_subtem = '<a target="_blank" href="'+ prontus +'/seccion/' + sf + '/tema/' + tf + '/subtema/' + stf + '/p/1" class="lv3">'+ prontus +'/seccion/' + sf + '/tema/' + tf + '/subtema/' + stf + '/p/1</a>';

                            $('#divCombinaciones #lista_enlaces').append(self.row.getHtmlTemplateModal(sn+' &raquo; '+tn+' &raquo; '+stn,btnCopy,link_subtem));
                        });
                    });
                });

                $.each(secciones, function () {
                    var sf = $(this).attr('data-friendly');
                    var sn = $(this).attr('data-title');

                    $.each(subtemas, function () {
                        var stf = $(this).attr('data-friendly');
                        var stn = $(this).attr('data-title');
                        var link_subtem = '<a target="_blank" href="'+ prontus +'/seccion/' + sf + '/subtema/' + stf + '/p/1" class="lv1">'+ prontus +'/seccion/' + sf + '/subtema/' + stf + '/p/1</a>';

                        $('#divCombinaciones #lista_enlaces').append(self.row.getHtmlTemplateModal(sn+' &raquo; '+stn,btnCopy,link_subtem));
                    });
                });

                $.each(temas, function () {
                    var tf = $(this).attr('data-friendly');
                    var tn = $(this).attr('data-title');
                    var link_tem = '<a target="_blank" href="/tema/' + tf + '/p/1" class="lv1">/tema/' + tf + '/p/1</a>';

                    $('#divCombinaciones #lista_enlaces').append(self.row.getHtmlTemplateModal(tn,btnCopy,link_tem));

                    $.each(subtemas, function () {
                        var stf = $(this).attr('data-friendly');
                        var stn = $(this).attr('data-title');
                        var link_subtem = '<a target="_blank" href="'+ prontus +'/tema/' + tf + '/subtema/' + stf + '/p/1" class="lv2">'+ prontus +'/tema/' + tf + '/subtema/' + stf + '/p/1</a>';

                        $('#divCombinaciones #lista_enlaces').append(self.row.getHtmlTemplateModal(tn+' &raquo; '+stn,btnCopy,link_subtem));
                    });
                });

                $.each(subtemas, function () {
                    var stf = $(this).attr('data-friendly');
                    var stn = $(this).attr('data-title');
                    var link_subtem = '<a target="_blank" href="'+ prontus +'/subtema/' + stf + '/p/1" class="lv1">'+ prontus +'/subtema/' + stf + '/p/1</a>';

                    $('#divCombinaciones #lista_enlaces').append(self.row.getHtmlTemplateModal(stn,btnCopy,link_subtem));
                });
            },
            loadData: function (callback) {
                $.ajax({
                    url: '/'+ Admin.prontus_id + '/cpan/procs/data4fids/multitag_fid.json',
                    dataType: 'json',
                    cache: false,
                    success: function (data) {
                        var mtagSList = self.actions.getMtagList('seccion');
                        $.each(data.seccion, function (i, v) {
                            self.row.addRow(v.MULTITAG_s_id, 'seccion', v.MULTITAG_s_nombre, v.MULTITAG_s_friendly, mtagSList);
                        });

                        var mtagTList = self.actions.getMtagList('tema');
                        $.each(data.tema, function (i, v) {
                            self.row.addRow(v.MULTITAG_t_id, 'tema', v.MULTITAG_t_nombre, v.MULTITAG_t_friendly, mtagTList);
                        });

                        var mtagSTList = self.actions.getMtagList('subtema');
                        $.each(data.subtema, function (i, v) {
                            self.row.addRow(v.MULTITAG_st_id, 'subtema', v.MULTITAG_st_nombre, v.MULTITAG_st_friendly, mtagSTList);
                        });

                        if (typeof callback === "function") {
                            callback();
                        }
                    }
                });
            },
            updateHidden: function (type) {
                var data = [];

                $('input[id^="multitag_' + type + '"]:checked').each(function () {
                    data.push($(this).val());
                });

                $('#multitag_' + type).val(data.join(','));
            },
            getMtagList: function (type) {
                var str = $('#multitag_' + type).val();
                var arr = str.split(',');

                return arr;
            }
        },
        row: {
            // ------------------------------------------------------------------
            getHtmlTemplate: function (id, type, nombre, friendly, checked) {
                var html = [
                    '<div class="checkbox"  data-title="%%nombre%%"><label class="control-label"><input type="checkbox" id="multitag_%%type%%_%%id%%" data-type="%%type%%" data-title="%%nombre%%" data-friendly="%%friendly%%" value="%%id%%" %%checked%%/>%%nombre%%</label></div>'
                ].join('');

                html = html.replace(/%%id%%/g, id);
                html = html.replace(/%%_prontus_id%%/g, Admin.prontus_id);
                html = html.replace(/%%type%%/g, type);
                html = html.replace(/%%nombre%%/g, nombre);
                html = html.replace(/%%friendly%%/g, friendly);

                if (checked) {
                    html = html.replace(/%%checked%%/, 'checked="checked"');
                } else {
                    html = html.replace(/%%checked%%/, '');
                }

                return html;
            },
            // ------------------------------------------------------------------
            getHtmlTemplateModal: function (nombre, btnCopy, link) {
                var html = '<div class="row">' +
                    '   <div class="col-xs-24 col-sm-10 col-md-10">'+nombre+'</div>'+
                    '   <div class="col-xs-24 col-sm-4 col-md-4">';

                    // está soportada función copiar clipboard
                    html += btnCopy;
                    html += '</div><div class="col-xs-24 col-sm-10 col-md-10 link_rel">'+link+'</div></div>';
                return html;
            },
            // ------------------------------------------------------------------
            addRow: function (id, type, nombre, friendly, mtagList) {
                var checked = false;
                if ($.inArray(String(id), mtagList) >= 0) checked = true;

                var $html = self.row.getHtmlTemplate(id, type, nombre, friendly, checked);
                $('#multitag_lista_' + type).append($html);
            }
        }
    };

    window.MultiTag = MultiTag;
})(this);
