korndaweizen / MKM

// ==UserScript==
// @name         MKM
// @namespace    http://tampermonkey.net/
// @version      0.5.0
// @updateUrl    https://openuserjs.org/install/korndaweizen/MKM.user.js
// @description  Allows users of magiccardmarket to perform multiple autobuyer queries without refreshing the site. Allows users to remove bought items from all Wantslists at once. Shows hoverable card as icon in autobuyer view. Changes to wantslists
// @author       Korndaweizen
// @match        https://www.cardmarket.com/*
// @exclude      */Magic/MainPage/addWants*
// @require      https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js
// @grant GM.xmlHttpRequest
// @run-at document-idle
// @license      MIT
// ==/UserScript==
function ab_OnSubmit() {
    resetProgressBar();
    document.getElementById('abSubmit').style.display = "unset";
    document.getElementById('abCartForm').innerHTML = null;
}

function resetProgressBar() {
    document.getElementById('lbar').style.display = "inline-block";
    document.getElementById('lbar').style.visibility = "visible";
    var progressBar = document.getElementById('loadingBar');
    progressBar.style.width = "0px";
}

function updateProgressBar(result) {
    var progress = getAJAXResponseValue(result, "progress", "int");
    var progressBar = document.getElementById('loadingBar');
    var tWidth = progressBar.parentNode.style.width.replace('px', '');
    progressBar.style.width = Math.round(progress * tWidth / 100) + "px";

    if (progress !== 100) {
        setTimeout('ab_startBarUpdate()', 500);
    }
    else {
        var cartForm = getAJAXResponseValue(result, "cartForm", "b64");

        document.getElementById('lbar').style.display = "none";
        document.getElementById('abCartForm').innerHTML = cartForm;
        showImages();
    }
}

unsafeWindow.ab_OnSubmit = ab_OnSubmit;
unsafeWindow.updateProgressBar = updateProgressBar;
HandleWants();
function HandleWants(){
    var list = $("#innerNavBarCodeDiv tr > td:nth-child(5)");
    list.each(function(){
        var jqContext=$(this);
        var link =  jqContext.children().first();

        var nLink= link.clone();
        var href = nLink.attr("href");
        var splittedHref = href.split("/");
        var cardname =splittedHref[splittedHref.length-1];
        var baseUrl = href.split("Products")[0]+ "Cards/"+cardname;
nLink.attr("href",baseUrl);
        nLink.addClass("a-btn a-info");
        nLink.text("All");
        jqContext.append(" ");
        jqContext.append(nLink);
    })
}

function showImages() {
    //set icon
    $('.MKMTable tr>td:nth-child(2)').each(function () {
        if (localStorage.getItem($(this).text()))
            $("<td class=\"centered\"><span style=\"display: inline-block; width: 16px; height: 16px; background-image: url('//static.cardmarket.com/img/30d78b786d4d5af636f96a5a3d6c6b1f/spriteSheets/ssMain.png'); background-position: -228px -86px;\" class=\"icon\" data-toggle=\"tooltip\" data-html=\"true\" data-placement=\"bottom\" onmouseover=\"" + localStorage.getItem($(this).text()) + "\" onmouseout=\"hideImgBox()\" data-original-title=\"" + $(this).text() + "\"></span></td>").insertBefore($(this));
        else
            $("<td></td>").insertBefore($(this));
    });
    $('.MKMTable thead tr').append($('<th></th>'));
    $('.MKMTable tfoot tr').append($('<td></td>'));

}

function removeAll() {
    $('#alertBox').remove();
    var __cmtkn = $('#removeWithShipment').children('.MKMContentBlockContent').children('form').children('input[name=__cmtkn]').val();
    var idShipment = $('#removeWithShipment').children('.MKMContentBlockContent').children('form').children('input[name=idShipment]').val();
    var idWantsList = $('#removeWithShipment').children('.MKMContentBlockContent').children('form').find('select[name=idWantsList]').val();

    var allOptions = $('#removeWithShipment').children('.MKMContentBlockContent').children('form').find('select[name=idWantsList] option');

    var idDictionary = {};

    var idsWantsList = $.map(allOptions, function (option) {
        idDictionary[option.value] = option.innerHTML;
        return option.value;
    });
    $.each(idsWantsList, function (key, idWantsList) {
        GM.xmlHttpRequest({
            method: "POST",
            url: "/de/Magic?action=WantsList_RemoveShipment",
            data: "__cmtkn=" + __cmtkn + "&idShipment=" + idShipment + "&idWantsList=" + idWantsList,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
                "Cache-Control": "max-age=0",
                "Origin": "https://www.cardmarket.com",
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
                "Referer": "https://www.cardmarket.com/de/Magic/MainPage/showShipment?idShipment=" + idShipment,
                "Upgrade-Insecure-Requests": "1"

            },
            onload: function (response) {
                var el = $('<div></div>');
                el.html(response.responseText);
                var responseText = el.find("#errorMessageBox p").html();
                $('#removeWithShipment').children('.MKMContentBlockContent').append($('<div id="alertBox"></div>'));
                $('#alertBox').append($('<p class="alert-box brad4 warning wrong">' + idDictionary[idWantsList] + ": " + responseText + '</p>'));
            }
        });
    });
}

function removeSingle() {
    $('#alertBox').remove();
    var __cmtkn = $('#removeWithShipment').children('.MKMContentBlockContent').children('form').children('input[name=__cmtkn]').val();
    var idShipment = $('#removeWithShipment').children('.MKMContentBlockContent').children('form').children('input[name=idShipment]').val();
    var idWantsList = $('#removeWithShipment').children('.MKMContentBlockContent').children('form').find('select[name=idWantsList]').val();

    var allOptions = $('#removeWithShipment').children('.MKMContentBlockContent').children('form').find('select[name=idWantsList] option');

    var idDictionary = {};

    var idsWantsList = $.map(allOptions, function (option) {
        idDictionary[option.value] = option.innerHTML;
        return option.value;
    });

    GM.xmlHttpRequest({
        method: "POST",
        url: "/de/Magic?action=WantsList_RemoveShipment",
        data: "__cmtkn=" + __cmtkn + "&idShipment=" + idShipment + "&idWantsList=" + idWantsList,
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cache-Control": "max-age=0",
            "Origin": "https://www.cardmarket.com",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "Referer": "https://www.cardmarket.com/de/Magic/MainPage/showShipment?idShipment=" + idShipment,
            "Upgrade-Insecure-Requests": "1"

        },
        onload: function (response) {
            var el = $('<div></div>');
            el.html(response.responseText);
            var responseText = el.find("#errorMessageBox p").html();
            $('#removeWithShipment').children('.MKMContentBlockContent').append($('<div id="alertBox"><p class="alert-box brad4 warning wrong">' + idDictionary[idWantsList] + ": " + responseText + '</p></div>'));
        }
    });
}
$('#removeWithShipment').children('.MKMContentBlockContent').children('form').find('input[type=submit]').remove();
$('#removeWithShipment').children('.MKMContentBlockContent').append("<button id='removeSingle' >Remove from selected wantslist</button>").children('#removeSingle').click(removeSingle);
$('#removeWithShipment').children('.MKMContentBlockContent').append("<button id='removeAll' >Remove from all wantlists</button>").children('#removeAll').click(removeAll);

//get icon
var icons = $("table").find(".icon[onmouseover^='setAndShowImgBox']");
$.each(icons, function (index, icon) {
    var iconContext = $(icon);
    var name = iconContext.parent().next().children().first().text();
    localStorage.setItem(iconContext.attr('data-original-title'), iconContext.attr('onMouseOver'));
})

//stylehelper
function GM_addStyle(css) {
  const style = document.getElementById("GM_addStyleBy8626") || (function() {
    const style = document.createElement('style');
    style.type = 'text/css';
    style.id = "GM_addStyleBy8626";
    document.head.appendChild(style);
    return style;
  })();
  const sheet = style.sheet;
  sheet.insertRule(css, (sheet.rules || sheet.cssRules || []).length);
}

//GM_addStyle(".a-button {  background-color: red;  box-shadow: 0 5px 0 darkred;  color: white;  padding: 1em 1.5em;  position: relative;  text-decoration: none;  text-transform: uppercase;}");
GM_addStyle("a.a-info {  color: #fff !important;    background-color: #17a2b8;    border-color: #17a2b8 !important;}");
GM_addStyle("a.a-info:hover {  color: #fff !important;    background-color: #31b0d5 !important;    border-color: #269abc !important;}");
GM_addStyle("a.a-btn {    padding: 1px 5px !important;    font-size: 12px !important;    line-height: 1.5 !important;    border-radius: 3px; display: inline-block;    padding: 6px 12px;    margin-bottom: 0;    font-size: 14px;    font-weight: 400 !important;line-height: 1.42857143;    text-align: center;    white-space: nowrap;    vertical-align: middle;    -ms-touch-action: manipulation;    touch-action: manipulation;    cursor: pointer;    -webkit-user-select: none;    -moz-user-select: none;    -ms-user-select: none;    user-select: none;    background-image: none;    border: 1px solid transparent;    border-radius: 4px;}")