let csrf = document.head.querySelector('meta[name="csrf-token"]').content;

var URLBASE = "/";
var baseDiv = document.querySelector('#DisplayContent');

function cl(e){
    console.log(e);
}

window.addEventListener('load', function() {
    permiso('', 1, '', 0);
    echo.init({
        callback: function(e, t) {}
    });
});

// Opciones de video PlAYER!
function go_to_player(url, type, load) {
    if (type === 1) {
        insertIframe(url, 1, load);
    }
    // Procesador!
    if (type === 2) {
        procesador(url, load);
    }
    // Recolector
    if (type === 3) {
        document.querySelector(".BotHumano").classList.add('BotHumanoA');
        document.querySelector(".BotHumano").insertAdjacentHTML('afterbegin', '<div class="BoxHumano"><span><b>Obteniendo vÃ­deo externos</b> <p>Por favor espere unos segundos</p></span></div>');
        recolector(url);
    }
}


function permiso(url, type, load, proz) {
    document.querySelector(".FirstLoad").classList.remove('FirstLoadA');
    document.querySelector(".BotHumano").classList.add('BotHumanoA');
    document.querySelector(".BotHumano").insertAdjacentHTML('afterbegin', '<div class="BoxHumano"><span>Comprobando que no eres un Bot...</span></div>');
    setTimeout(function() {
        reCaptcha(type).then(re => {
            // if (re.status == 200) {
            document.querySelector(".BotHumano").classList.remove('BotHumanoA');
            document.querySelector(".BoxHumano").remove();
            baseDiv.insertAdjacentHTML('afterbegin', re.data);
            // work_player();
            // } else {
            //     document.querySelector(".BotHumano").classList.remove('BotHumanoA');
            //     document.querySelector(".BoxHumano").remove();
            //     baseDiv.insertAdjacentHTML('afterbegin', re.data);
            // }
        });
    }, 300);
}
function reCaptcha(type) {

    return grecaptcha.execute(key_recaptcha, {
        action: 'peticiones'
    }).then(function(token) {
        if (token != null) {
            var t = new FormData;
            t.append("_token", csrf);
            t.append("cpt", token);
            t.append("type", type);
            t.append("imdb", window.imdb);
            t.append("season", window.season);
            t.append("episode", window.epsidoe);
            return fetch(window.url_links,{
                method: 'POST',
                body : t
            }).then(res => res.json())
                .then(dato => {
                    // console.log(dato);
                    return dato;
                }).catch(function(error) {
                    var error = {
                        status: 404,
                        data: '<div class="BotHumanoFail BotHumanoFailA"><div class="BoxHumanoFail"><span><b>Error de verificaciÃ³n</b><p>Compruebe que no tengas nada que bloquee las peticiones (Vpn, Adblocks, Plugins o Navegadores no oficiales)</p></span></div></div>'
                    };
                    return error;
                });
        } else {
            return {
                status: 301,
                data: 'Hash inexistente'
            };
        }
    });
}
function procesador(url, type) {
    var u = url;
    document.querySelector(".BotHumano").classList.add('BotHumanoA');
    document.querySelector(".BotHumano").insertAdjacentHTML('afterbegin', '<div class="BoxHumano"><span><b>Procesando vÃ­deo</b> <p>Por favor espere unos segundos</p></span></div>');
    fetch(u, {
        method: 'GET'
    }).then(res => res.json())
        .then(dato => {
            document.querySelector(".BotHumano").classList.remove('BotHumanoA');
            document.querySelector(".BoxHumano").remove();



            if (dato.status == 200) {
                // console.log(dato);
                insertIframe('/player/' + dato.data +'/redirect', 1, 2);
            }
            if (dato.status == 300) {
                document.querySelector(".BotHumano").classList.add('BotHumanoA');
                document.querySelector(".BotHumano").insertAdjacentHTML('afterbegin', '<div class="BoxHumano coding"><span>Los vÃ­deos aun estÃ¡n en proceso de codificaciÃ³n, vuelva en unos minutos</span></div>');
                setTimeout(function() {
                    document.querySelector(".BotHumano").classList.remove('BotHumanoA');
                    document.querySelector(".BoxHumano").remove();
                }, 3000);
            }
            if (dato.status == 404) {
                document.querySelector(".BotHumano").classList.add('BotHumanoA');
                document.querySelector(".BotHumano").insertAdjacentHTML('afterbegin', '<div class="BoxHumano coding" style="background: #083632;"><span>Todos los vÃ­deos de esta opciÃ³n han sido eliminados, sentimos mucho las molestias</span></div>');
                setTimeout(function() {
                    document.querySelector(".BotHumano").classList.remove('BotHumanoA');
                    document.querySelector(".BoxHumano").remove();
                }, 3000);
            }
        }).catch(function(error) {
        // document.querySelector(".BoxHumano").remove();
        document.querySelector(".BotHumano").insertAdjacentHTML('afterbegin', '<div class="BoxHumano coding" style="background: #57130e;"><span>Hubo un error inesperado al procesar los vÃ­deos, intÃ©ntelo mas tarde</span></div>');
        setTimeout(function() {
            document.querySelector(".BotHumano").classList.remove('BotHumanoA');
            document.querySelector(".BoxHumano").remove();
        }, 3000);
    });
}
function recolector(url) {
    var u = url_links;
    var load = document.querySelector(".BotHumano");
    fetch(u, {
        method: 'GET'
    }).then(res => res.json())
        .then(dato => {
            if (dato.status == 200) {
                load.innerHTML = `
                <div class="BoxHumano reAct"><span>
                    <div class="tl1"> ${dato.total} <b>Videos Totales</b> </div>
                    <div class="tl2"> 1 </div>
                    <div class="tl3"> ${dato.doned} </div>
                </span></div>`;
                setTimeout(function() {
                    document.querySelector(".BotHumano").classList.remove('BotHumanoA');
                    document.querySelector(".BoxHumano").remove();
                    insertIframe('get-player/' + dato.data.data, 1, 2);
                }, 500);
            } else {
                if (dato.status == 202) {
                    load.innerHTML = `<div class="BoxHumano coding"><span>Los vÃ­deos aun estÃ¡n en proceso de codificaciÃ³n, vuelva en unos minutos</span></div>`;
                    setTimeout(function() {
                        document.querySelector(".BotHumano").classList.remove('BotHumanoA');
                        document.querySelector(".BoxHumano").remove();
                    }, 3000);
                } else {
                    if (dato.doned >= dato.total) {
                        load.innerHTML = `<div class="BoxHumano coding" style="background: #083632;"><span>Los vÃ­deos analizados no estÃ¡n disponibles, lo sentimos mucho</span></div>`;
                        setTimeout(function() {
                            document.querySelector(".BotHumano").classList.remove('BotHumanoA');
                            document.querySelector(".BoxHumano").remove();
                        }, 3000);
                    } else {
                        load.innerHTML = `
                            <div class="BoxHumano reAct"><span>
                            <div class="tl1"> ${dato.total} <b>Videos Totales</b> </div>
                            <div class="tl2"> 0 </div>
                            <div class="tl3"> ${dato.doned} </div>
                            </span></div>`;
                        setTimeout(function() {
                            recolector(url);
                        }, 500);
                    }
                }
            }
        }).catch(function(error) {
        load.innerHTML = `<div class="BoxHumano coding" style="background: #57130e;"><span>Hubo un error inesperado al analizar los vÃ­deos, intÃ©ntelo mas tarde</span></div>`;
        setTimeout(function() {
            document.querySelector(".BotHumano").classList.remove('BotHumanoA');
            document.querySelector(".BoxHumano").remove();
        }, 3000);
    });
}


function insertIframe(url, type, load) {
    var urlInserted = url;

    // cl(urlInserted);
    var displayVideo = document.querySelector(".DisplayVideo");
    if (type === 1) {
        var pbl = '';
        displayVideo.classList.add('DisplayVideoA');
        if (load === 1) {
            displayVideo.innerHTML = `
            ${pbl}
            <span onclick="insertIframe('', 2);">
                <img src="https://i.imgur.com/CyF9UPO.png">
            </span>
            <iframe id="IFR" src="${urlInserted}" frameborder="0" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>`;
        } else {
            displayVideo.innerHTML = `
            ${pbl}
            <p></p>
            <span onclick="insertIframe('', 2);">
                <img src="https://i.imgur.com/CyF9UPO.png">
            </span>
            <iframe id="IFR" frameborder="0" allowfullscreen="true" webkitallowfullscreen="true" mozallowfullscreen="true"></iframe>`;
            var myIframe = document.getElementById('IFR');
            myIframe.addEventListener("load", function() {
                setTimeout(function() {
                    document.querySelector(".DisplayVideo p").remove();
                }, 1000);
            });
            myIframe.src = urlInserted;
        }
    } else {
        displayVideo.classList.remove('DisplayVideoA');
        displayVideo.innerHTML = '';
    }
}
function pbl(who) {
    who.remove();
    var timep = time(8);
    localStorage.setItem('varDirect', timep);
}
function SelLang(who, id) {
    document.querySelector(".FirstLoad").classList.add('FirstLoadA');
    if (document.querySelector(".SLD_A") != null) {
        document.querySelector(".SLD_A").classList.remove('SLD_A');
    }
    who.classList.add('SLD_A');
    setTimeout(function() {
        document.querySelector(".FirstLoad").classList.remove('FirstLoadA');
        if (document.querySelector(".REactiv") != null) {
            document.querySelector(".REactiv").classList.remove('REactiv');
        }
        document.querySelector(".OD_" + id).classList.add('REactiv');
    }, 300);
}
! function(e, t) {
    "function" == typeof define && define.amd ? define(function() {
        return t(e)
    }) : "object" == typeof exports ? module.exports = t : e.echo = t(e)
}(this, function(e) {
    "use strict";
    var t, i, n, o, r, c = {},
        l = function() {},
        s = function(e, t) {
            if (function(e) {
                return null === e.offsetParent
            }(e)) return !1;
            var i = e.getBoundingClientRect();
            return i.right >= t.l && i.bottom >= t.t && i.left <= t.r && i.top <= t.b
        },
        a = function() {
            !o && i || (clearTimeout(i), i = setTimeout(function() {
                c.render(), i = null
            }, n))
        };
    return c.init = function(i) {
        var s = (i = i || {}).offset || 0,
            d = i.offsetVertical || s,
            u = i.offsetHorizontal || s,
            m = function(e, t) {
                return parseInt(e || t, 10)
            };
        t = {
            t: m(i.offsetTop, d),
            b: m(i.offsetBottom, d),
            l: m(i.offsetLeft, u),
            r: m(i.offsetRight, u)
        }, n = m(i.throttle, 250),
            o = !1 !== i.debounce,
            r = !!i.unload,
            l = i.callback || l,
            c.render(),
            document.addEventListener ? (e.addEventListener("scroll", a, !1), e.addEventListener("load", a, !1)) : (e.attachEvent("onscroll", a), e.attachEvent("onload", a))
    }, c.render = function(i) {
        for (var n, o, a = (i || document).querySelectorAll("[data-echo], [data-echo-background]"), d = a.length, u = {
            l: 0 - t.l,
            t: 0 - t.t,
            b: (e.innerHeight || document.documentElement.clientHeight) + t.b,
            r: (e.innerWidth || document.documentElement.clientWidth) + t.r
        }, m = 0; m < d; m++) o = a[m], s(o, u) ? (r && o.setAttribute("data-echo-placeholder", o.src), null !== o.getAttribute("data-echo-background") ? o.style.backgroundImage = "url(" + o.getAttribute("data-echo-background") + ")" : o.src !== (n = o.getAttribute("data-echo")) && (o.src = n), r || (o.removeAttribute("data-echo"), o.removeAttribute("data-echo-background")), l(o, "load")) : r && (n = o.getAttribute("data-echo-placeholder")) && (null !== o.getAttribute("data-echo-background") ? o.style.backgroundImage = "url(" + n + ")" : o.src = n, o.removeAttribute("data-echo-placeholder"), l(o, "unload"));
        d || c.detach()
    }, c.detach = function() {
        document.removeEventListener ? e.removeEventListener("scroll", a) : e.detachEvent("onscroll", a), clearTimeout(i)
    }, c
});

function time(sump) {
    var fecha = new Date();
    var horas = sump;
    fecha = new Date(fecha);
    fecha.setHours(fecha.getHours() + horas);
    fecha = fecha.toISOString();
    var fecha_date = fecha.split('T');
    var fecha_time = fecha_date[1].split('.');
    var fecha_time = fecha_date[1].split(':');
    fecha_date = fecha_date[0];
    fecha = fecha_date + ' ' + fecha_time[0] + ':' + fecha_time[1];
    return fecha;
}
function copy() {
    var copyText = document.getElementById("copyUrl");
    copyText.select();
    copyText.setSelectionRange(0, 99999);
    document.execCommand("copy");
    document.querySelector(".share").insertAdjacentHTML('afterbegin', '<p>Url copiado</p>');
    setTimeout(function() {
        document.querySelector(".share p").remove();
    }, 1200);
}

