drchloe / NewXchan Gold

// ==UserScript==
// @name         NewXchan Gold
// @version      0.0.1.5
// @description  Tweak use of new xchan beta
// @author       Doc
// @include      https://xchan.pw/board/*
// @grant        none
// ==/UserScript==

//BACKLINKS
var quotePreview = function () {
    $('.ref').tooltipster({
        content : 'Loading...',
        contentAsHTML : true,
        animationDuration : 0,
        interactive : true,
        trigger : 'hover',
        theme : 'tooltipster-fuhrerchan',
        functionBefore : function (instance, helper) {
            var $origin = $(helper.origin),
                post_id = $origin.data('post-id'),
                $post = $('#post-' + post_id);
            if ($post.length) {
                instance.content($post.clone().removeAttr('id').removeClass('highlight').addClass('reply'));
                return true;
            }
            if (!$origin.data('loaded')) {
                $.get('/post/' + post_id + '/', function (data) {
                    instance.content(data);
                    $origin.data('loaded', true);
                });
            }
            return true;
        },
    });
};


$('.ref').not('.backlink').each(function(){
    var id = $(this).attr('data-post-id');
    var parent_id = $(this).parent().parent().parent().attr('id').replace('post-', '');
    $('#post-'+id+'').find('#backlink-'+id+'').remove();
    $('#post-'+id+' > .metadata').append('<a href="#" style="font-size:10px" id="backlink-'+parent_id+'" class="ref backlink" data-post-id="'+parent_id+'">&gt;&gt;'+parent_id+'</a> ');
});
quotePreview();



$(document).on('mouseenter', ".ref", function () {
    setTimeout(function() {
        quotePreview();
    }, 500);
});
//<a href="/board/b/thread/874548/#post-874587" class="ref tooltipstered" data-post-id="874587">&gt;&gt;874587</a>

//PREVIEW THING

$(document).on('click', ".quote-post", function () {
    var parent = $(this).attr('data-parent-id');
    var optext = $('#post-'+parent+'').find('.message').text();
    $('#reply-to').append('('+optext.slice(0, 20)+'...)');
});

// NEW FILE POSTING
$('input[type="submit"]').replaceWith('<input type="button" id="newsubmit" value="Enviar">');
var progressElem = $('#progress');
$('#id_file').prop('multiple', true);

var dumploop = 0;
$(document).on('click', "#newsubmit", function () {
    var Reader = new FileReader(); 
    var fileSelect = document.getElementById('id_file');
    var files = fileSelect.files;
    dumploop = r(files.length);
    dump(0);
});

function dump(count){
    var countshow = 'Enviando '+(count + 1)+' de '+ dumploop;

    if (count == dumploop){
        $(window).off('beforeunload');
        document.location.href = 'https://xchan.pw/board/b/';
        return;
    }

    var cookie = document.cookie;
    cookie = cookie.split('=')[1];
    var fileSelect = document.getElementById('id_file');
    var Reader = new FileReader(); 
    var files = fileSelect.files;
    if (files.length > 1 && $("input[name='parent']").val() === "") {alert('Selecione apenas um arquivo para criar thread.'); return false;} 
    var file = files[count];

    $('#newsubmit').val(countshow);
    document.title = countshow;

    $("form#id_form").each(function(){

        var formData = new FormData();
        formData.append('csrfmiddlewaretoken', cookie);
        formData.append('file', file);
        formData.append('name', $("input[name='name']").val());
        formData.append('subject', $("input[name='subject']").val());
        formData.append('email', $("input[name='email']").val());
        if (count === 0){formData.append('message', $("#id_message").val());} else {formData.append('message', '');}
        formData.append('board', $("input[name='board']").val());
        formData.append('parent', $("input[name='parent']").val());

        function uploadFile() {
            var fd = formData;
            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener("progress", uploadProgress, false);
            xhr.open("POST", window.location.pathname);
            xhr.onload = function(e) {
                if (this.status == 200) {
                    setTimeout(function() {
                        dump(count+1);
                    }, 1000);
                }
            };

            xhr.send(fd);            
        }
        uploadFile();

        function uploadProgress(evt) {
            if (evt.lengthComputable) {
                var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                var percentnum = countshow + ' ('+percentComplete.toString() + '%)';
                document.title = percentnum;
                $('#newsubmit').val(percentnum);
            }
        }
    });
}


$(document).on('change', "#id_file", function () {
    if (window.FileReader) {
        $('.previmg').remove();

        for (var i = 0; i < this.files.length; i++) {
            var Reader = new FileReader();
            var file = this.files[i];
            if (file.type.indexOf("video") > -1) {
                Reader.onload = function (event) {
                    $('#id_file').parent().prepend('<video class="previmg" height="150" autoplay loop muted><source src="' + event.target.result + '">Your browser does not support the video tag.</video><br>');
                };
                Reader.readAsDataURL(file);

            } else {
                Reader.onload = function (event) {
                    $('#id_file').parent().prepend('<img class="previmg" src="' + event.target.result + '" style="max-height:150px;"><br>');
                };
                Reader.readAsDataURL(file);
            }
        }

    } else {
        alert('no filereader');
    }

});


//WEBMFIX & Autoplay
$('head').append('<style type="text/css"> video, .gifplayer-wrapper{width:auto !important;height:auto !important;} .scaled{width:255px !important;}</style>');
$('.play-gif').css('display', 'none');
function r(a){var s = 3;s = s * 2;if (a > s){a = s;}if(a === 0){a = 1;}return a;}
$(document).on('mouseenter', "video", function () {
    if ($(this).attr('controls') === undefined){
        $(this).attr('controls', 'controls');
        $(this).attr('muted', '');
    }
});

$(document).on('click', "video", function () {
    $(this).toggleClass('scaled');
});

// NEW LIVE INDEX
var oldtitle = $(document).prop('title');
var ur = ''+document.location+'';

var last_date;
setTimeout(function() {
    last_date = new Date(); //Json Reader
}, 14000);

function update() {
    $.get( 'https://xchan.pw/api/boards/', function( data ) {
        var lastpost_date = new Date(data[0]['last_post']);
        if (lastpost_date > last_date){
            last_date = lastpost_date;
            load();
        }
    });
}

function load(){ //Response behavior
    if (window_focus){
        $(document).prop('title', 'Novos Posts!');
        $('body').append('<div class="newposts" onclick="location.reload();" style="cursor:pointer;background:orange;color:black;font-weigth:bold;border-radius:5px;position:fixed;top:3px;left:10%;padding:7px;">Novos Posts!</div>');
    } else {
        if ($('#id_message').val() === '' || $('.previmg').length === 0 ){
            localStorage.setItem("newposts", '1');
            location.reload();
        }
    }
}

setTimeout(function() {
    if (localStorage.getItem("newposts")){
        localStorage.removeItem("newposts");
        document.title = 'Novos Posts!';
    }
}, 200);

if (ur.indexOf('thread') == -1){
    setInterval(function () { //Tick
        update();
    }, 15000);
}

var vis = (function(){  // Tab Focus System
    var stateKey, eventKey, keys = {
        hidden: "visibilitychange",
        webkitHidden: "webkitvisibilitychange",
        mozHidden: "mozvisibilitychange",
        msHidden: "msvisibilitychange"
    };
    for (stateKey in keys) {
        if (stateKey in document) {
            eventKey = keys[stateKey];
            break;
        }
    }
    return function(c) {
        if (c) document.addEventListener(eventKey, c);
        return !document[stateKey];
    };
})();

var window_focus; 

function testvis(){
    window_focus = vis();
    if (window_focus){
        $(document).prop('title', '>'+oldtitle);
    } else {
        $(document).prop('title', oldtitle);
    }
}

testvis();

vis(function(){testvis();});