VLADOS776 / Pikabu link overview

// ==UserScript==
// @name         Pikabu link overview
// @version      0.1
// @description  Превью поста и профиля, при наведении на ссылку
// @author       SmallPeris
// @icon         http://cs.pikabu.ru/images/icon_ios114.png
// @match        *://pikabu.ru/*
// @grant        GM_xmlhttpRequest
// @updateURL    https://openuserjs.org/meta/VLADOS776/Pikabu_link_overview.meta.js
// ==/UserScript==

(function() {
    'use strict';
    var DEBUG = false;

    //Settings
	var divWidth = 430,
		divHeight = 300,
        hide_n_show_time = 700; //ms

	var sheet = (function() {
		var style = document.createElement("style");
		document.head.appendChild(style);
		return style.sheet;
	})();
	sheet.insertRule("#link-overview { background:#f7f7f7; width:"+divWidth+"px; height:"+divHeight+"px; position:absolute;z-index:10000;box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.5);border-radius:5px; resize:horizontal;}", 0);
	sheet.insertRule("#link-overview i.fa {font-size: 1em;position: relative;left: 5px;top: 5px;}");
	sheet.insertRule(".link-overview__top {width: 100%;height: 50px; background: #fff; border-radius: 5px 5px 0 0; box-shadow: 0 1px 0px rgba(0, 0, 0, 0.1);}");
	sheet.insertRule(".link-overview__top span {display: block;line-height: 50px;padding: 0px 10px;font-family: Tahoma;color: #5f5f5f;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;}");
	sheet.insertRule(".link-overview__content {height: "+(divHeight-65)+"px;padding: 5px; overflow:auto; font-family: Arial;line-height: 1.3em;color: #4c4c4c;}");
	sheet.insertRule(".link-overview__content .b-story-block {padding: 0 !important;font-size: 0.9em !important;}");
	sheet.insertRule(".link-overview__content img {max-width: "+(divWidth-40)+"px;}");
    sheet.insertRule(".link-overview__top img {width: 40px;float: left;border-radius: 50%;margin: 5px;}");
    sheet.insertRule(".link-overview__content table {width: 100%;border-collapse: collapse;}");
    sheet.insertRule(".link-overview__content table td {padding: 7px;}");
    sheet.insertRule(".link-overview__content table tr td:nth-child(2n) {text-align: right;}");
    sheet.insertRule(".link-overview__content table tr:nth-child(2n) {background: #eaeaea;}");
    sheet.insertRule(".link-overview__pluses {background: linear-gradient(45deg, #9ef95a, #00940b);color: #fff;font-weight: bold;border-radius: 5px 0 0 5px;text-align:center}");
    sheet.insertRule(".link-overview__minuses {text-align: center !important;width: 50%;color: #fff;font-weight: bold;background: linear-gradient(-45deg, #ff7575, #940000);border-radius: 0 5px 5px 0;}");
	var div = document.createElement('div');
	div.setAttribute('id', 'link-overview');
    div.setAttribute('style', 'display:none');

	document.getElementById('wrap').appendChild(div);

	var timeoutId = null;
    var timeoutId2 = null;

	$('a').on("mouseenter", function() {
        if(DEBUG) console.log('%cMouse over link: '+'%c True ','', 'background:green; color:#fff');
        if ($(this).find('img').length !== 0 && !$(this).attr('href').match(/pikabu.ru\/profile/)) return false;
		var pos = $(this).offset(),
			elemWidth = $(this).width(),
			href = $(this).attr('href');
        if(DEBUG) console.log(href);
        if (!/http[s]?:\/\/pikabu\.ru\/(story|profile)/.test(href) || /#comments/.test(href) || $(this).hasClass('story__title-link') || $(this).hasClass('b-story__show-all')) {
            if(DEBUG) console.log('%c URL не прошел проверку ', 'background:red; color:#fff');
            return false;
        }
        if ($('#link-overview').data('href') == href) {
            $('#link-overview').fadeIn('slow');
            window.clearTimeout(timeoutId);
            window.clearTimeout(timeoutId2);
            if(DEBUG) console.log('%c Data.href == href ', 'background:green; color:#fff');
            return false;
        }

        clearInterval(timeoutId2);
		if (!timeoutId) {
			timeoutId = window.setTimeout(function() {
                $('#link-overview').data('href', href);
				timeoutId = null;
                $('#link-overview').css('display', 'block');
				one(pos, elemWidth, href);
			}, 500);
		}
	});

	$('a').on("mouseout", function() {
		window.clearTimeout(timeoutId);
		timeoutId = null;
        if(DEBUG) console.log('%cMouse over link: '+'%c False '+'%c; #link-overview data-mouseover: '+'%c '+$('#link-overview').data('mouseover') + '; %ctimeoutId2: ' + '%c ' + timeoutId2,'', 'background:red; color:#fff','','background:#da8301; color:#fff', '', 'background:pink; color:#fff');
        clearInterval(timeoutId2);
        timeoutId2 = null;
        timeoutId2 = window.setInterval(function() {
            if (!($('#link-overview').data('mouseover')) || (typeof $('#link-overview').data('mouseover') == 'undefined')) {
                clearInterval(timeoutId2);
                timeoutId2 = null;
                $('#link-overview').fadeOut('slow');
            }
        }, hide_n_show_time);
	});

    $('#link-overview').on('mouseover', function() {
        $(this).data('mouseover', true);
        clearInterval(timeoutId2);
        if(DEBUG) console.log('%cMouse over #link-overview: '+'%c True ', '', 'background:green; color:#fff');
    });

    $('#link-overview').on('mouseout', function() {
        $(this).data('mouseover', false);
        if(DEBUG) console.log('%cMouse over #link-overview: '+'%c False ', '', 'background:red; color:#fff');
        clearInterval(timeoutId2);
        window.clearTimeout(timeoutId);
        timeoutId2 = null;
            timeoutId2 = window.setInterval(function() {
                if (!($('#link-overview').data('mouseover'))) {
                    clearInterval(timeoutId2);
                    timeoutId2 = null;
                    $('#link-overview').fadeOut('slow');
                }
            }, hide_n_show_time);
    });

	function one(pos, elemWidth, href) {
		pos.left = pos.left + (elemWidth / 2) - (divWidth / 2);
		pos.top = pos.top - divHeight;
		$('#link-overview').css('left', pos.left);
		$('#link-overview').css('top', pos.top);
		$('#link-overview').html('<div class="link-overview__top"><span>Загрузка...</span></div><div class="link-overview__content"><i class="fa fa-circle-o-notch fa-spin"></i></div>');
		getPage(href);
	}

	function getPage(url) {
		var data = GM_xmlhttpRequest ({
			method: 'GET',
			url: url,
			headers: {
				'User-Agent': 'Mozilla/5.0',
				'Accept': 'text/xml'
			},
			onload: function(response) {
				var txt = response.responseText;
				var start = txt.indexOf('<title>')+7;
				var end = txt.indexOf('</title>');
				var title = txt.substr(start, end-start);
				if(DEBUG) console.log(title);
				if (response.finalUrl.indexOf('/story/') != -1) {
					var content = $($.parseHTML(response.responseText)).find('.b-story__content')[0].innerHTML;
				} else if (response.finalUrl.indexOf('/profile/') != -1) {
                    var table = $($.parseHTML(response.responseText)).find('.b-user-profile')[0].getElementsByTagName('td');//.find('tr');
                    var img_url = $(table[0].children[0].children[0]).attr('src');
                    var how_old = $($(table[1]).find('span')[1]).text();
                    var rating = $($(table[1]).find('span')[3]).text();
                    var comments= $($(table[1]).find('span')[5]).text();
                    var posts   = $($(table[1]).find('span')[7]).text();
                    var hot_posts=$($(table[1]).find('span')[9]).text();
                    var pluses  = parseInt($($(table[1]).find('span')[11]).text());
                    var minuses = parseInt($($(table[1]).find('span')[11]).text().trim().substr(20));

                    if(DEBUG) console.log(table);
                    $('.link-overview__top').html('<img src="'+img_url+'"><span></span>');
					var content = '<table><tr style="text-align:center;"><td colspan=2>Пикабушник '+how_old+'</td></tr><tr><td>Рейтинг</td><td>'+rating+'</td></tr>';
                    content += '<tr><td>Комментариев</td><td>'+comments+'</td></tr>';
                    content += '<tr><td>Посты/Посты в горячем</td><td>'+posts+'/'+hot_posts+'</td></tr>';
                    content += '</table><table>';
                    content += '<tr style="text-align:center;"><td colspan=2>Поставил</td></tr>';
                    content += '<tr><td class="link-overview__pluses">'+pluses+'</td><td class="link-overview__minuses">'+minuses+'</td></tr>';
                    content += '</table>';
                    //if(DEBUG) debugger;
				}

				$('.link-overview__top span').text(title);
				$('.link-overview__content').html(content);
			}
		});
	}
})();