var MaM = {
    vtxt: "vtxt_mam",
    cgiSave: '/' + Admin.dir_cgi_cpn + '/mam/mam_save.cgi',
    cgiList: '/' + Admin.dir_cgi_cpn + '/mam/mam_list.cgi',
    cgiDelete: '/' + Admin.dir_cgi_cpn + '/mam/mam_delete.cgi',
    listType: 'all',
    init: function () {
        if (mainFidJs.TS == '') {
            showModalAlert({
                title: 'Minuto a minuto',
                type: 'green',
                msg: 'Debe guardar el artículo para poder usar el Minuto a Minuto'
            });
            $('.mam').hide();
            return false;
        }
        // configuracion base
        let tinyConfig = Object.assign({}, Fid.tinyConfig);
        tinyConfig.selector = "#" + MaM.vtxt;
        tinyConfig.toolbar1 = 'bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | bullist numlist | indent outdent | hr blockquote charmap';
        tinyConfig.toolbar2 = 'styleselect searchreplace pastetext | undo redo removeformat | link unlink | image html_insert table media | code | help';

        tinyConfig.height = 199;
        tinyConfig.max_height = 500;
        tinyConfig.plugins = "searchreplace autolink visualchars image imagetools link media table_responsive hr charmap pagebreak anchor lists textcolor imagetools contextmenu textpattern code paste help html_insert";
        tinyConfig.setup = function (ed) {
            ed.settings.body_class = ed.id.substr(5);
            if (ed.settings.body_class != 'CUERPO') {
                ed.settings.body_class = ed.settings.body_class + ' CUERPO';
            }
            ed.on('Init', function (e) {
                MediaManager.fotofija.methods.initDroppableVTXT(tinyConfig.selector);
            });
        };

        tinyMCE.init(tinyConfig);

        $('#actualizar-pub-mam').click(MaM.updateTimeStamp);
        $('#clean-mam').click(MaM.clean);
        $('#save-mam').click(MaM.savePost);
        $('#remove-img-mam').click(MaM.removeImag);
        $('#mam-filter-last').click('last', MaM.refreshList);
        $('#mam-filter-all').click('all', MaM.refreshList);
        $('#reload-mam').click('reload', MaM.refreshList);

        $("#mam_list").on("click", ".edit-mam", function (e) {
            e.preventDefault();
            e.stopPropagation();
            MaM.edit(this);
        });

        $("#mam_list").on("click", ".delete-mam", function (e) {
            e.preventDefault();
            e.stopPropagation();
            MaM.delete(this);
        });

        $('div#recuadro_foto_mam').droppable({
            accept: '.fotodrag',
            hoverClass: 'ui-state-active',
            drop: function (event, ui) {
                var $item = ui.helper;
                var imgSrc = $item.attr('src');
                var w = $item.attr("data-w");
                var h = $item.attr("data-h");

                $('div#recuadro_foto_mam').html('<img src="' + imgSrc + '" />');
                document.getElementById('mam-img').value = imgSrc;
                document.getElementById('mam-img-w').value = w;
                document.getElementById('mam-img-h').value = h;
            }
        });

        MaM.refreshList();
    },

    edit: function (element) {
        MaM.clean();
        document.getElementById('mam-date').value = $(element.parentElement.parentElement).find('.date').val();
        document.getElementById('mam-time').value = $(element.parentElement.parentElement).find('.time').val();
        document.getElementById('mam-img').value = $(element.parentElement.parentElement).find('.img').val();
        $('div#recuadro_foto_mam').html('<img src="' + document.getElementById('mam-img').value + '" />');
        document.getElementById('mam-img-h').value = $(element.parentElement.parentElement).find('.height').val();
        document.getElementById('mam-img-w').value = $(element.parentElement.parentElement).find('.width').val();
        document.getElementById('mam-id').value = $(element.parentElement.parentElement).find('.id').val();
        document.getElementById('mam-title').value = $(element.parentElement.parentElement).find('.title').val();
        tinymce.get(MaM.vtxt).setContent($(element.parentElement.parentElement).find('.txt').val());
        element.focus()
        document.getElementById('save-mam').focus();
    },

    delete: function (element) {
        showModalConfirm({
            msg: "El relato será eliminado. ¿Estás seguro?",
            type: 'blue',
            icon: "glyphicon glyphicon-question-sign",
            btnClassOk: 'hovwhite radius15 noborder txtnextwhite pad-top-bot7 pad-lef-rig20 int-nextred nextred',
            cbBtnOK: function () {
                MaM.deletePost($(element.parentElement.parentElement).find('.id').val());
            },
            cbBtnCancel: function () {
            }
        });
    },

    deletePost: function(id) {
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: MaM.cgiDelete,
            data: {
                _prontus_id: Admin.prontus_id,
                _ts: mainFidJs.TS,
                id: id
            },
            success: function (resp) {
                if (resp.status == 1) {
                    MaM.refreshList();
                    showModalAlert({
                        title: 'Minuto a minuto',
                        type: 'green',
                        msg: 'Relato borrado con éxito.'
                    });
                } else {
                    showModalAlert({
                        title: 'Minuto a minuto',
                        type: 'red',
                        msg: 'Error al borrar: ' + resp.msg
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus) {
                showModalAlert({
                    title: 'Minuto a minuto',
                    type: 'red',
                    msg: 'Error al borrar: ' + textStatus
                });
            }
        });
    },

    updateTimeStamp: function () {
        let now = new Date();
        let zeroLeft = function (val) {
            if (val < 10 && val >= 0) {
                val = '0' + val;
            }
            return val;
        }

        let seconds = now.getSeconds();
        let min = now.getMinutes();
        let hour = now.getHours();
        document.getElementById('mam-time').value = zeroLeft(hour) + ':' + zeroLeft(min) + ':' + zeroLeft(seconds);

        let day = now.getDate();
        let month = now.getMonth() + 1;
        let year = now.getYear();
        if (year < 1000) {
            year = year + 1900;
        }
        document.getElementById('mam-date').value = zeroLeft(day) + '/' + zeroLeft(month) + '/' + zeroLeft(year);
    },
    savePost: function () {
        $.ajax({
            type: "POST",
            dataType: 'json',
            url: MaM.cgiSave,
            data: {
                _prontus_id: Admin.prontus_id,
                _ts: mainFidJs.TS,
                id: document.getElementById('mam-id').value,
                txt: tinymce.get(MaM.vtxt).getContent(),
                img: document.getElementById('mam-img').value,
                img_w: document.getElementById('mam-img-w').value,
                img_h: document.getElementById('mam-img-h').value,
                date: document.getElementById('mam-date').value,
                time: document.getElementById('mam-time').value,
                title: document.getElementById('mam-title').value,
                type: document.getElementById('mam-type').value
            },
            success: function (resp) {
                if (resp.status == 1) {
                    MaM.clean();
                    MaM.refreshList();
                    showModalAlert({
                        title: 'Minuto a minuto',
                        type: 'green',
                        msg: 'Relato guardado con éxito.'
                    });
                } else {
                    showModalAlert({
                        title: 'Minuto a minuto',
                        type: 'red',
                        msg: 'Error en el guardado: ' + resp.msg
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus) {
                showModalAlert({
                    title: 'Minuto a minuto',
                    type: 'red',
                    msg: 'Error en el guardado: ' + textStatus
                });
            }
        });
    },
    clean: function () {
        document.getElementById('mam-id').value = '';
        document.getElementById('mam-date').value = '';
        document.getElementById('mam-time').value = '';
        document.getElementById('mam-title').value = '';
        tinymce.get(MaM.vtxt).setContent('');
        MaM.removeImag();
    },
    refreshList: function (e) {
        if (e && e.data != 'reload') {
            MaM.listType = e.data;
        }
        if (mainFidJs.TS == '') {
            return false;
        }

        if (MaM.listType == 'last') {
            if ($('#mam-filter-all').hasClass('active') ) {
                $('#mam-filter-all').removeClass('active');
            }
            if (!$('#mam-filter-last').hasClass('active') ) {
                $('#mam-filter-last').addClass('active');
            }
        }
        if (MaM.listType == 'all') {
            if ($('#mam-filter-last').hasClass('active') ) {
                $('#mam-filter-last').removeClass('active');
            }
            if (!$('#mam-filter-all').hasClass('active') ) {
                $('#mam-filter-all').addClass('active');
            }
        }

        $.ajax({
            type: "POST",
            dataType: 'json',
            url: MaM.cgiList,
            data: {
                _prontus_id: Admin.prontus_id,
                _ts: mainFidJs.TS,
                order: MaM.listType
            },
            success: function (resp) {
                if (resp.status == 1) {
                    if (resp.list.length > 0) {
                        let list = '';
                        let template = $('#tpl_mam_list').html();
                        for (let i = 0; i < resp.list.length; i++) {
                            let clone = template;
                            let item = resp.list[i];
                            clone = clone.replace(/__date__/g, item.mam_date);
                            clone = clone.replace(/__height__/g, item.mam_height);
                            clone = clone.replace(/__id__/g, item.mam_id);
                            clone = clone.replace(/__img__/g, item.mam_img);
                            clone = clone.replace(/__type__/g, item.mam_type);
                            clone = clone.replace(/__time__/g, item.mam_time);
                            clone = clone.replace(/__ts__/g, item.mam_ts);
                            clone = clone.replace(/__txt__/g, item.mam_txt);
                            if (item.mam_title == undefined) {
                                item.mam_title = '';
                            }
                            clone = clone.replace(/__title__/g, item.mam_title);
                            clone = clone.replace(/__width__/g, item.mam_width);
                            list = list + clone;
                        }
                        document.getElementById('mam_list').innerHTML = list;
                    }
                } else {
                    showModalAlert({
                        title: 'Minuto a minuto',
                        type: 'red',
                        msg: 'Error al listar: ' + resp.msg
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus) {
                showModalAlert({
                    title: 'Minuto a minuto',
                    type: 'red',
                    msg: 'Error al listar: ' + textStatus
                });
            }
        });
    },

    removeImag: function () {
        document.getElementById('mam-img').value = '';
        document.getElementById('mam-img-w').value = '';
        document.getElementById('mam-img-h').value = '';
        if (document.getElementById('recuadro_foto_mam').children[0]) {
            document.getElementById('recuadro_foto_mam').children[0].remove();
        }
    },

    human_fechahora: function (ahora, fechahorap, hoy, dia, hora) {
        if (fechahorap >= ahora) {
            return 'Hace pocos segundos';
        }

        var seg_hora = MaM.ts_to_segs(ahora);
        var seg_fechahorap = MaM.ts_to_segs(fechahorap);

        var segundos = seg_hora - seg_fechahorap;

        if (segundos < 60) {
            return 'Hace un minuto aproximadamente';
        }
        var minutos = Math.floor(segundos / 60);
        if (minutos == 1) {
            return 'Hace ' + minutos + ' minuto';
        } else if (minutos < 60) {
            return 'Hace ' + minutos + ' minutos';
        }

        var horas = Math.floor(minutos / 60);
        if (horas < 2) {
            return 'Hace una hora aproximadamente';
        }
        if (dia == hoy) {
            if (horas < 12) {
                return 'Hace ' + horas + ' horas';
            } else {
                return 'Hoy a las ' + hora + ' horas';
            }
        }
        return dia + ' a las ' + hora;
    },

    ts_to_segs: function (ts) {
        var ms = MaM.ts_to_ms(ts);
        return Math.floor(ms / 1000);
    },

    ts_to_ms: function (ts) {
        var date = MaM.ts_to_date(ts);
        return date.getTime();
    },

    ts_to_date: function (ts) {
        ts = ts + '';
        if (ts.length != 14) {
            return new Date();
        }
        var y = ts.substr(0, 4);
        var m = ts.substr(4, 2);
        var d = ts.substr(6, 2);
        var h = ts.substr(8, 2);
        var min = ts.substr(10, 2);
        var s = ts.substr(12, 2);
        var ms = 0;

        var date = new Date(y, m, d, h, min, s, ms);
        return date;
    }
}
