Advertisement
junh1024

PTH CBH

Feb 5th, 2017
584
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // @name        PTH :: Collage Building Helper
  3. // @author      Z4ppy - Updated for PTH by jungletek
  4. // @namespace   jungletek.passtheheadphones.me
  5. // @description Make it easier to build your collage.
  6. // @include     https://*passtheheadphones.me/torrents.php*
  7. // @include     https://*passtheheadphones.me/collages.php*
  8. // @include     https://*passtheheadphones.me/collage.php*
  9. // @include     https://*passtheheadphones.me/artist.php*
  10. // @include     https://*passtheheadphones.me/bookmarks.php*
  11. // @grant       GM_setValue
  12. // @grant       GM_getValue
  13. // @grant       GM_deleteValue
  14. // @grant       GM_registerMenuCommand
  15. // @grant       GM_xmlhttpRequest
  16. // @version     1.0.1
  17. // @date        2016-12-01
  18. // ==/UserScript==
  19.  
  20. // Changelog can be found at https://userscripts.org/topics/118127
  21.  
  22. var collageID, collName;
  23. // Momenticons: http://findicons.com/icon/263495/folder_open_add
  24. var ICON_ADD = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAACmUlEQVR4nIWRS0hVURSGv33Ovp57j0oqV7Qkil5mEwNDKoILikQjg6Jykg0qIrIkwkySbOANahBYCj0oigoLCyxqpFRIUHTLHlb0tCJTTK2b9+HjnLMbHDOjsjXca+1vfaxfKKVoOTUz/01X9N7IcBQAw5uMIWMFGyoHb/KfEsdqfGtT/HMb16xaCdHngILEbC5dvsrAlzdFW2riLZMCjtdmqk2l61H9t0BZgAPCQKQu5UxjE+Fw3/iwLr1k+FN9q7e9Hfr5JuOxMERegh0HoSN0AWoYwm2UFueCNNxJI5OO1zYfX7eKiQYSAMdGKRvLcjh7rZPYsBprP/ubdaxurwmApusfxgCjaFjcbu+ndONJpPMJhQ1MXOagCQVCgPJA2iKOHij56AJsBysWQU8rwjPchoo8RCg14bMABEoIUAphzuTtg26SszJ3ugAsbj+OEChejDNwEWVFQGhuSynQvOjmbPDNB6FD0ixaL1Tc3VzdFXIBQ1FsfwEy1o4T63PFhZsoykIz02joinDgfT0CRWnKEraXXAyOH/FWRz+BwCrUl3MwEgc0lyAT0BIyICmPnr4eqgM7kB548qjje/qcZRaQKQFsXzZG9D5WtMdVdlNHmnNp+Kpz5Ml5wqMRtqabSAmXum+YN05nXS5buKtJHN7jVeVlJ6D3Cox8++UuJGSsYHpLkOpAOb3RTtq7WvEmQv6MIqYmz2B382GklB7q6jf/LW9SprxD+B10zUbXwPCBYehIXSAlCARC/RbXHzXv0P3g/hMd9cWDo4MJlcvX6bqE4PVGO8mTPFK2cFfTpIBXn1t986YVpgB5++5UHVywwMyRmuDps+iLmqXBCmAsxn+tn1YYB+JAyG+mhyqba3NAsDO3KgSEgJ4f88//Bf3Zb/0AAAAASUVORK5CYII=';
  25. // Yusuke Kamiyamane: http://findicons.com/icon/118036/cross
  26. var ICON_ERR = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAX5JREFUeNrEU71OwlAUPrVqrDFBHsARX6AJri4kJSEyEBMHggkLK8EEFsauvoPo4iN04gkgLiYOOBHUxDSUCBO0XL9z7a1t1YnBJl967/l+enIOaEII2uTZog2fbXW41zTSiSwcbaAbEDl+TJTmLsLO4x1YIOzzTscMvoRWmjtrNn9yPAPGHdFg3W6Lx1JJLFstwXfACjF4r9clN6lWJad8UUAPwhsQXqMh+vm8eK3VBN8ZT+WyrA0LBVljrfJpags9zMBnAi2eVirm82hEmUyGFosFvUwmZBgGzcfjoYYZYCbOZehLBKzwDsKQo1zOnLqu5HRdpw/XlWYM09lBTQVEW3gDdsMChLSazWhfkUEgw9nCm1n+9TuAwILAPs5mTcP36QA1Ba4xJ5LbSa4RX7FPIFSmB88bMtSduVVqjVEAE8WYuQ8jvthl9GMhxe+QZMAcwlsI93DmN9/RrsP4jVO+aAtX2IKH1tZIR2o3C+NhKJoBae46vcZ/+zd+CjAAN5vaL1x3kMMAAAAASUVORK5CYII=';
  27. // Yusuke Kamiyamane: http://findicons.com/icon/119015/tick
  28. var ICON_OK = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAehJREFUeNpi/P//PwMlgImBQsACIhhnCAFZjEAGkANy0B8gwQ00m5kRogpEMYHl5YF4LZBXw/D3/47/Ea/xuOD7PwaGX1AMMvDvfwGGf/8nprkkGQPZLUAVHqR4gY3hH0Ofoby+6ZcvXxjinWL0Gf4wtMC9QAAwAjXXK0jIO8gLyUl9/Pzx98Fjh24AXdOA7gIPoP/PwJwGdvoPoNP/MGQIcwkGq4mrKHz5+uXf0UtH7wBdMRGodgvCgP9ATX/+tyT5JxqCaDAfIu7DwcSWJckjqfzgwQOGU5dP3f3w4cNSoJq5DL//I0Xjn38tMX4xes+ePWOK8IowAPGBmnNZ/jPVS4vLqH7985Xl5YcXDz99+rAJGIDtQAxxIcKA/zVLViy8xM7J9uvU7VPMDnaOOkAb4sVkxTV+sPxgf/fhzdOP797vZ/gLjD4Ghn8oAQRKiYx9/AxADaAwaDF2NtN6+vMZpwCnAMP7b+8Zfrz49vrj3fdHGJgZkhhYmT4wsELTC8iHWe+RAvE/ww6g02vO7jhxjfkv49fXjK8Zvn/5+uHTzXcXgSGeC1TxAWdKRDHk81+Gp5vutnCZ8Mt8v/DpDtCBeUBrnuJNyigAmEQZ3v9h+LbzTQsw+ZYwCLJcBydjXIlkwHMjQIABAIHQ3hY9qLekAAAAAElFTkSuQmCC';
  29. // ajaxload.info
  30. var ICON_LOADING = 'data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==';
  31.  
  32. var torrentCache = {
  33.     Cache: [],
  34.     GM_read: function () {
  35.         this.clear();
  36.         this.Cache = JSON.parse(GM_getValue('torrentCache', '[]'));
  37.         return this.Cache.length;
  38.     },
  39.     GM_save: function () {
  40.         return GM_setValue('torrentCache', JSON.stringify(this.Cache));
  41.     },
  42.     GM_delete: function () {
  43.         GM_deleteValue('torrentCache');
  44.     },
  45.     add: function (torrentgroupid) {
  46.         if (this.Cache.indexOf(torrentgroupid) != -1) {
  47.             return false;
  48.         }
  49.         this.Cache.push(torrentgroupid);
  50.         return true;
  51.     },
  52.     contains: function (torrentgroupid) {
  53.         return (this.Cache.indexOf(torrentgroupid) != -1);
  54.     },
  55.     remove: function (torrentgroupid) {
  56.         if (this.Cache.indexOf(torrentgroupid) == -1) {
  57.             return false;
  58.         }
  59.         this.Cache.splice(this.Cache.indexOf(torrentgroupid), 1);
  60.         return true;
  61.     },
  62.     clear: function () {
  63.         this.Cache.length = 0;
  64.     }
  65. }
  66.  
  67. var URL = new Object();
  68. function parseURL() {
  69.     var URLArr = document.URL.match(/^(https:\/\/(?:ssl\.)?passtheheadphones\.me)\/([\w\/\.]+?)(\?(.*?))?(#.*)?$/);
  70.     URL.Host = URLArr[1]; //protocol + hostname, eg. https://passtheheadphones.me
  71.     URL.Path = URLArr[2];
  72.     URL.Hash = URLArr[5];
  73.     URL.Parameters = new Object();
  74.     if (typeof URLArr[4] != 'undefined') {
  75.         var URLPArr = URLArr[4].split('&'); //URL parameter array
  76.         var tmpP; //temporary Parameter
  77.         for (var i = 0; i < URLPArr.length; ++i) {
  78.             tmpP = URLPArr[i].split('=');
  79.             URL.Parameters[tmpP[0]] = tmpP[1];
  80.         }
  81.     }
  82. }
  83.  
  84. function init() {
  85.     parseURL();
  86.  
  87.     getCollageID();
  88.  
  89.     torrentCache.GM_read();
  90.  
  91.     // putting the add image on various pages (with an active collage)
  92.     // $.inArray(URL.Path, ['torrents.php', 'artist.php'])
  93.     if ((URL.Path == 'torrents.php' || URL.Path == 'artist.php' || URL.Path == 'bookmarks.php' || URL.Path == 'collages.php') && (collageID != 0)) {
  94.         if (URL.Path == 'torrents.php' && URL.Parameters['id']) {
  95.             //torrent group page
  96.             var title = document.getElementById('content').getElementsByTagName('h2')[0];
  97.             title.insertBefore(document.createTextNode(' '), null);
  98.             title.insertBefore(createAddIcon(URL.Host + '/torrents.php?id=' + URL.Parameters['id'], URL.Parameters['id']), null);
  99.         } else {
  100.             var tableId = '';
  101.             if (URL.Path == 'torrents.php' && (URL.Parameters['type'] || URL.Parameters['action'] == 'notify')) {
  102.                 // user uploaded/snatched/etc and notifications
  103.                 tableId = 'content';
  104.             } else if (URL.Path == 'artist.php' || (URL.Path == 'collages.php' && URL.Parameters['id'] && URL.Parameters['id'] != collageID)) {
  105.                 // artist page; other collages
  106.                 tableId = 'discog_table';
  107.             } else if (URL.Path == 'torrents.php' || URL.Path == 'bookmarks.php') {
  108.                 // search page; bookmarks
  109.                 tableId = 'torrent_table';
  110.             }
  111.  
  112.             if (tableId != '') {
  113.                 var linkArr = extractTorrentgroupLinks(tableId);
  114.                 for (var i = 0; i < linkArr.length; ++i) {
  115.                     linkArr[i].parentNode.insertBefore(document.createTextNode(' '), linkArr[i].parentNode.firstChild);
  116.                     linkArr[i].parentNode.insertBefore(createAddIcon(linkArr[i].href, linkArr[i].getAttribute('torrentgroupid')), linkArr[i].parentNode.firstChild);
  117.                 }
  118.             }
  119.         }
  120.     }
  121.    
  122.     if (URL.Path == 'collages.php' && URL.Parameters['id'] && !URL.Parameters['action']) {
  123.         var currentCollURL = URL.Parameters['id'];
  124.  
  125.         var cx = document.getElementsByTagName('h2')[0];
  126.  
  127.         if (collageID != 0 && collageID != currentCollURL) {
  128.             // if there is an active collage & the active collage is different than current page, use name + link
  129.             cx.parentNode.innerHTML = "\<h3 id=\"actcollage\"\>The active collage is: \<a href\=\"" + URL.Host + "\/collages.php\?id\=" + collageID + "\"\>" + collName + "\<\/a\>" + cx.parentNode.innerHTML;
  130.         } else {
  131.             // else just display name
  132.             cx.parentNode.innerHTML = "\<h3 id=\"actcollage\"\>The active collage is: " + collName + cx.parentNode.innerHTML;
  133.         }
  134.  
  135.         var jx = document.getElementsByTagName('h2')[0];
  136.  
  137.         // display "Make This Active Collage!"
  138.         if (currentCollURL != collageID) {
  139.             //standard collage pages
  140.             var collageLink = document.createElement('a');
  141.             collageLink.href = '#';
  142.             collageLink.textContent = 'Make this the active collage';
  143.             collageLink.setAttribute('collage-id', currentCollURL);
  144.             collageLink.setAttribute('collage-name', jx.innerHTML);
  145.             collageLink.className = 'brackets';
  146.             collageLink.id = 'thelink';
  147.             collageLink.addEventListener('click', function(e) { setCollageID(e.target); return false; }, false);
  148.             jx.parentNode.insertBefore(collageLink, jx);
  149.         }
  150.  
  151.         // display "Remove Active Collage"
  152.         if (collageID != 0) {
  153.             var removeActColl = document.createElement('a');
  154.             removeActColl.href = '#';
  155.             removeActColl.textContent = 'Remove the active collage';
  156.             removeActColl.setAttribute('collage-id', '0');
  157.             removeActColl.className = 'brackets';
  158.             removeActColl.id = 'thelink';
  159.             removeActColl.addEventListener('click', function(e) { setCollageID(e.target); return false; }, false);
  160.             jx.parentNode.insertBefore(removeActColl, jx);
  161.         }
  162.  
  163.        
  164.         makeitp = document.getElementById("thelink");
  165.         makeitp.insertAdjacentHTML("beforeBegin",'\<p\>');
  166.         makeitp.insertAdjacentHTML("afterEnd",'&nbsp;\</p\>\<hr\>');
  167.        
  168.         // cache the current contents of the active collage
  169.         if (currentCollURL == collageID) {
  170.             var linkArr = extractTorrentgroupLinks('discog_table');
  171.             torrentCache.clear();
  172.             for (var i = 0; i < linkArr.length; ++i) {
  173.                 torrentCache.add(linkArr[i].getAttribute('torrentgroupid'));
  174.             }
  175.             torrentCache.GM_save();
  176.         }
  177.     } else if (URL.Path == 'collages.php' && URL.Parameters['collageid'] && URL.Parameters['action'] == 'manage') {
  178.         manageStuff();
  179.     }
  180. }
  181.  
  182. function extractTorrentgroupLinks(tableId) {
  183.     var linkArr = new Array();
  184.  
  185.     if (document.getElementById(tableId) != null) {
  186.         var lx = document.getElementById(tableId).getElementsByTagName('a');
  187.         if (typeof lx != 'undefined') {
  188.             var curTorrID = '0';
  189.             for (var i = 0; i < lx.length; ++i) {
  190.                 match = /torrents\.php\?id=(\d+)/.exec(lx[i].href);
  191.                 if (match != null && match[1] != curTorrID) {
  192.                     lx[i].setAttribute('torrentgroupid', match[1]);
  193.                     linkArr.push(lx[i]);
  194.                     curTorrID = match[1];
  195.                 }
  196.             }
  197.         }
  198.     }
  199.  
  200.     return linkArr;
  201. }
  202.  
  203. function createAddIcon(torrent_url, torrentgroupid) {
  204.     var res = document.createElement('img');
  205.     res.setAttribute('torrent-url', torrent_url);
  206.     res.setAttribute('torrentgroupid', torrentgroupid);
  207.     updateAddIcon(res);
  208.     res.addEventListener('click', image_click, false);
  209.     return res;
  210. }
  211.  
  212. function updateAddIcon(img) {
  213.     if (torrentCache.contains(img.getAttribute('torrentgroupid'))) {
  214.         img.src = ICON_OK;
  215.         img.title = 'Remove from collage "' + collName + '"...';
  216.     } else {
  217.         img.src = ICON_ADD;
  218.         img.title = 'Add to collage "' + collName + '"...';
  219.     }
  220. }
  221.  
  222. function manageStuff() {
  223.     var authKey = findAuthKey();
  224.    
  225.     var activeCollageID = URL.Parameters['collageid'];
  226.     var allGroupNumbers=new Array();
  227.     var allNewSortNumbers=new Array();
  228.     var allOrigSortNumbers=new Array();
  229.     var isUpdated = 0;
  230.  
  231.     //get initial group numbers
  232.     var jx = document.getElementsByName('groupid');
  233.     for (var i = 0;i < jx.length; ++i) {
  234.         allGroupNumbers[i]=parseInt(jx[i].value);
  235.     }
  236.    
  237.     //get initial group sort numbers
  238.     var kx = document.getElementsByName('sort');
  239.     for (var i = 0; i < kx.length; ++i) {
  240.         allOrigSortNumbers[i]=parseInt(kx[i].value);
  241.     }
  242.    
  243.     var editAllButton = document.createElement('input');
  244.     editAllButton.type = 'button';
  245.     editAllButton.value = 'Edit All';
  246.    
  247.     var zx = document.getElementById('content').getElementsByTagName('h2')[0];
  248.     zx.parentNode.insertBefore(editAllButton, zx);
  249.    
  250.     //edit all button
  251.     editAllButton.addEventListener("click", function(){
  252.         var mx = document.getElementsByName('sort');
  253.         var i = 0;
  254.         isUpdated = 1;
  255.         editAllButton.value = 'Updating...';
  256.        
  257.         for (i = 0; i < mx.length; ++i) {
  258.             allNewSortNumbers[i]=parseInt(mx[i].value);
  259.            
  260.             //only update new numbers
  261.             if (allNewSortNumbers[i] != allOrigSortNumbers[i]) {
  262.                 GM_xmlhttpRequest({
  263.                     method: "POST",
  264.                     url: URL.Host + "/collages.php",
  265.                     data: "action=manage_handle&auth=" + authKey + "&collageid=" + activeCollageID + "&groupid=" + allGroupNumbers[i] + "&sort=" + allNewSortNumbers[i],
  266.                     headers: { "Content-Type" : "application/x-www-form-urlencoded" },
  267.                     //I can't figure out a way to error check this page...
  268.                     onload: function(e) {
  269.                         if (e.responseText.match(/Invalid authorization key/)) {
  270.                             var temp = document.getElementById('content');
  271.                             temp.innerHTML = "Invalid authorization key (the system must have updated your authkey since you loaded the page).  Refresh the page and try again!<br>I strongly recommend rechecking your values, since it's possible (though unlikely) that some values updated while others didn't.  Sorry :(";
  272.                         }
  273.                     },
  274.                     onerror: function(e) {
  275.                         alert("some sort of error occured with the server.  Error occured with torrentID: \"" + allGroupNumbers[i] + "\" which had a new sort number of: \"" + allNewSortNumbers[i] + "\".  Recommend rechecking your values.");
  276.                         return;
  277.                     }
  278.                 });
  279.             }
  280.         }
  281.         // one more worthless request to reload the page after all previous requests finish
  282.         GM_xmlhttpRequest({
  283.             method: "POST",
  284.             url: URL.Host + "/collages.php",
  285.             data: "action=manage_handle&auth=" + authKey + "&collageid=" + activeCollageID + "&groupid=" + allGroupNumbers[i] + "&sort=" + allNewSortNumbers[i],
  286.             headers: { "Content-Type" : "application/x-www-form-urlencoded" },
  287.             onload: function(e) {
  288.                 if (e.responseText.match(/Invalid authorization key/)) {
  289.                     var temp = document.getElementById('content');
  290.                     temp.innerHTML = "Invalid authorization key (the system must have updated your authkey since you loaded the page).  Refresh the page and try again!<br>I strongly recommend rechecking your values, since it's possible (though unlikely) that some values updated while others didn't.  Sorry :(";
  291.                 } else {
  292.                     document.location.href = document.location.href;
  293.                 }
  294.             }
  295.         });
  296.     }, false);
  297.    
  298.     //insert blank space between edit all image and math range image
  299.     var oNewP = document.createElement("b");
  300.     var oText = document.createTextNode(" ");
  301.     oNewP.appendChild(oText);
  302.     var beforeMe = document.getElementsByTagName('h2')[0];
  303.     beforeMe.parentNode.insertBefore(oNewP, beforeMe);
  304.    
  305.     if (GM_getValue("checkBoxAlwaysOn", "0") == 0) {
  306.         var mathRangeButton = document.createElement('input');
  307.         mathRangeButton.type = 'button';
  308.         mathRangeButton.value = 'Math Range';
  309.        
  310.         mathRangeButton.addEventListener("click", function() {
  311.             mathArray();
  312.             mathRangeButton.style.display = 'none';
  313.         }, false);
  314.        
  315.         var bx = document.getElementById('content').getElementsByTagName('h2')[0];
  316.         bx.parentNode.insertBefore(mathRangeButton, bx);
  317.     } else {
  318.         mathArray();
  319.     }
  320.    
  321.     //catch 'Remove' clicks for torrentcache update
  322.     var inputs = document.querySelectorAll('input[name=submit][value=Remove]');
  323.     var groupidnode;
  324.     for(var ii = 0; ii < inputs.length; ++ii) {
  325.         groupidnode = inputs[ii].parentNode.querySelector('input[type=hidden][name=groupid]');
  326.         inputs[ii].setAttribute('torrentgroupid', groupidnode.value);
  327.         inputs[ii].addEventListener('click', function(e) { manage_remove_click(e); });
  328.     }
  329. }
  330.  
  331. // used for operations on manage page
  332. function mathArray() {
  333.     // math Array checkboxes
  334.     var box=new Array();
  335.     var lx = document.getElementsByName('sort');
  336.    
  337.     for (var i =0; i< lx.length; ++i) {
  338.         box[i] = document.createElement("input");
  339.         box[i].type="checkbox";
  340.         box[i].setAttribute('realChecked', "0");
  341.         box[i].setAttribute('arrayValue', i);
  342.         lx[i].parentNode.insertBefore(box[i], lx[i]);
  343.        
  344.         //check for max of two boxes
  345.         box[i].addEventListener("click", function() {
  346.             var unclickCheck = 0;
  347.             if (this.checked == true) {
  348.                 this.setAttribute('realChecked', "1");
  349.             } else  {
  350.                 // if you unselect the box do the following:
  351.                 this.setAttribute('realChecked', "0");
  352.                 for (var m =0; m< lx.length; ++m) {
  353.                     if (box[m].getAttribute('realChecked') != "1") {
  354.                         box[m].checked = false;
  355.                         box[m].disabled = false;
  356.                     }
  357.                 }
  358.             }
  359.             var counter = 0;
  360.                        
  361.             var firstValue, secondValue, thirdValue;
  362.             for (var z=0; z< lx.length; ++z) {
  363.                 if (box[z].getAttribute('realChecked') == "1") {
  364.                     counter++;
  365.                     if (counter == 1) {
  366.                         firstValue = parseInt(z);
  367.                     } else if (counter == 2) {
  368.                         secondValue = parseInt(z);
  369.                     } else if (counter == 3) {
  370.                         thirdValue = parseInt(z);
  371.                     }
  372.                 }
  373.             }
  374.             if (counter == 2) {
  375.                 //visibly show which boxes you checked
  376.                 for (var x = firstValue+1; x <= secondValue-1; ++x) {
  377.                     box[x].checked = true;
  378.                     box[x].disabled = true;
  379.                 }
  380.             } else if (counter == 3) {
  381.                 alert("You can only select TWO check boxes.  One for the top of your range, one for the bottom of your range.  Unselecting the checkbox.");
  382.                 // if you select below the current range
  383.                 if  (this.getAttribute('arrayValue') > secondValue) {
  384.                     for (var x = firstValue+1; x <= secondValue+1; ++x) {
  385.                         box[x].checked = false;
  386.                         box[x].disabled = false;
  387.                         box[x].setAttribute('realChecked', "0");
  388.                     }
  389.                     //uncheck current selection
  390.                     box[thirdValue].checked = false;
  391.                     box[thirdValue].setAttribute('realChecked', "0");
  392.  
  393.                 }
  394.                 // if you select above the current range
  395.                 else if (this.getAttribute('arrayValue') < secondValue) {
  396.                     for (var y = secondValue; y <= thirdValue-1; ++y) {
  397.                        
  398.                         box[y].checked = false;
  399.                         box[y].disabled = false;
  400.                         box[y].setAttribute('realChecked', "0");
  401.                     }
  402.                     //uncheck current selection
  403.                     box[firstValue].checked = false;
  404.                     box[firstValue].setAttribute('realChecked', "0");
  405.                 }
  406.             }
  407.         }, false);
  408.     }
  409.    
  410.     //execute the math range button
  411.     var operationButton = document.createElement('input');
  412.     operationButton.type = 'button';
  413.     operationButton.value = 'Operation';
  414.    
  415.     var yx = document.getElementById('content').getElementsByTagName('h2')[0];
  416.     yx.parentNode.insertBefore(operationButton, yx);
  417.    
  418.     operationButton.addEventListener("click", function(e){
  419.         var upperRangeValue, lowerRangeValue;
  420.        
  421.         var counter = 0;
  422.         // check if they have two check boxes
  423.         for (var q =0; q< lx.length; ++q) {
  424.             if (box[q].getAttribute('realChecked') == "1"){
  425.                 counter++;
  426.                 if (counter == 1) { upperRangeValue = parseInt(q); }
  427.                 else if (counter == 2) { lowerRangeValue = parseInt(q); }  
  428.             }
  429.         }
  430.         if (counter == 1) {
  431.             alert("You must select two checkboxes to include your entire range.\nExample- select the 3rd checkbox and 6th checkbox to perform a math operation on torrents 3, 4, 5, 6\nAnother option is to select NO checkboxes.  When you perform an operation, it will perform on ALL torrents.\nRemember: click edit all to update the changes.");
  432.         } else {
  433.             // We are ready to do the math operations
  434.             var userOperationMessage = "What operation do you want to perform:\nadd: +\nsubtract: -\nmultiply: *\ndivide: \/\nfind missing torrents: m\nexport to tab delimitted file: e\n\nRemember: click edit all to update the changes.";
  435.             if (counter == 0) {            
  436.                 // check all the boxes so you can see you're doing stuff on everything
  437.                 for (var c = 0; c < lx.length; ++c) {
  438.                     box[c].checked = true;
  439.                     box[c].disabled = true;
  440.                 }
  441.                
  442.                 upperRangeValue = 0;
  443.                 lowerRangeValue = parseInt(c);
  444.  
  445.                 var userOperation = prompt("Now performing an operation on ALL elements.\n\n" + userOperationMessage);
  446.             } else {
  447.                 var userOperation = prompt(userOperationMessage);
  448.             }
  449.            
  450.             if (userOperation != null && userOperation != '') {
  451.                 userOperation = userOperation.toUpperCase();
  452.                 if (userOperation == "+" || userOperation == "-" || userOperation == "*" || userOperation == "\/") {
  453.                     var adjustValue = prompt("Current operation: \"" + userOperation + "\".  Input an integer to adjust the selected range by the operation.");
  454.                     if (adjustValue != null && adjustValue != '') {
  455.                         adjustValue = parseInt(adjustValue);
  456.                        
  457.                         if (isNaN(adjustValue)) {
  458.                             alert("Please pick a valid integer!");
  459.                             return;
  460.                         }
  461.                     } else {
  462.                         return;
  463.                     }
  464.                 } else if (userOperation == "M") {
  465.                     var diffValue = prompt("Current operation: \"Find Missing Torrents\".  Input the difference of sort numbers.\nExample: Input 10 if the collage sort numbers are 10, 20, 30, ...");
  466.                     if (diffValue != null && diffValue != '') {
  467.                         diffValue = parseInt(diffValue);
  468.                         if (isNaN(diffValue)) {
  469.                             alert("Please pick a valid integer!");
  470.                             return;
  471.                         }
  472.                     } else {
  473.                         return;
  474.                     }
  475.                 } else if (userOperation == "E") {
  476.                 } else {
  477.                     // uncheck all the boxes assuming the user never selecting any
  478.                     if (counter == 0) {                
  479.                         for (var c =0; c< lx.length; ++c) {
  480.                             if (c >= upperRangeValue && c <= lowerRangeValue) {
  481.                                 box[c].checked = false;
  482.                                 box[c].disabled = false;
  483.                             }  
  484.                         }
  485.                     }
  486.                     alert("Please select only the following characters \"+\", \"-\", \"*\", \"\/\", \"m\" (no quotes)");
  487.                     return;
  488.                 }
  489.             } else {
  490.                 // user hits cancel
  491.  
  492.                 // uncheck all the boxes assuming the user never selecting any
  493.                 if (counter == 0) {
  494.                     for (var c = 0; c < lx.length; ++c) {
  495.                         if (c >= upperRangeValue && c <= lowerRangeValue) {
  496.                             box[c].checked = false;
  497.                             box[c].disabled = false;
  498.                         }  
  499.                     }
  500.                 }
  501.                 return;
  502.             }
  503.                        
  504.             var allNewSortNumbers = new Array();
  505.  
  506.             if (userOperation == "+") {
  507.                 for (var b = 0; b < lx.length; ++b) {      
  508.                     if (b >= upperRangeValue && b <= lowerRangeValue) {
  509.                         allNewSortNumbers[b] = parseInt(lx[b].value) + adjustValue;
  510.                         lx[b].value=allNewSortNumbers[b];
  511.                     }              
  512.                 }
  513.             } else if (userOperation == "-") {
  514.                 for (var b = 0; b < lx.length; ++b) {      
  515.                     if (b >= upperRangeValue && b <= lowerRangeValue) {
  516.                         allNewSortNumbers[b] = parseInt(lx[b].value) - adjustValue;
  517.                         lx[b].value=allNewSortNumbers[b];
  518.                     }              
  519.                 }
  520.             } else if (userOperation == "*") {
  521.                 for (var b = 0; b < lx.length; ++b) {      
  522.                     if (b >= upperRangeValue && b <= lowerRangeValue) {
  523.                         allNewSortNumbers[b] = parseInt(lx[b].value) * adjustValue;
  524.                         lx[b].value=allNewSortNumbers[b];
  525.                     }              
  526.                 }          
  527.             } else if (userOperation == "\/") {
  528.                 for (var b = 0; b < lx.length; ++b) {      
  529.                     if (b >= upperRangeValue && b <= lowerRangeValue) {
  530.                         allNewSortNumbers[b] = parseInt(lx[b].value) / adjustValue;
  531.                         lx[b].value=allNewSortNumbers[b];
  532.                     }              
  533.                 }
  534.             } else if (userOperation == "M") {
  535.                 //find missing numbers
  536.                 var missingValues=new Array();
  537.                 var extraValues=new Array();
  538.                 var missingCount = 0;
  539.                 var extraCount = 0;
  540.                 var zzb = document.getElementsByName('sort');
  541.                 var checkNumber = parseInt(zzb[upperRangeValue].value);
  542.                 var nextNumber =0;
  543.                 for (var i = upperRangeValue; i < lowerRangeValue-1; ++i) {
  544.                     checkNumber += diffValue;
  545.                    
  546.                     nextNumber = parseInt(zzb[i + 1].value);
  547.  
  548.                     if (checkNumber != nextNumber) {
  549.                         if (checkNumber < nextNumber) {
  550.                             i--;
  551.                             if (checkNumber != missingValues[missingCount-1]) {
  552.                                 missingValues[missingCount] = checkNumber;
  553.                                 missingCount++;
  554.                             }
  555.                         } else {
  556.                             extraValues[extraCount] = nextNumber;
  557.                             extraCount++;
  558.                             if (checkNumber != missingValues[missingCount-1]) {
  559.                                 missingValues[missingCount] = checkNumber;
  560.                                 missingCount++;
  561.                                 checkNumber -= diffValue;
  562.                             }
  563.                         }
  564.                     } else {
  565.                         if (checkNumber == missingValues[missingCount-1]) {
  566.                                 missingCount--;
  567.                                 missingValues.pop();
  568.                         }
  569.                     }
  570.                 }
  571.                 if (missingCount == 0) {
  572.                     if (extraCount == 0) {
  573.                         alert("No missing sort numbers.\nAlso, no extra sort numbers tucked inbetween.");
  574.                     } else {
  575.                         alert("No missing sort numbers.\nBut the extra sort numbers are: " + extraValues);
  576.                     }  
  577.                 } else {
  578.                     if (extraCount == 0) {
  579.                         alert("The missing sort numbers are: " + missingValues + "\nAlso, no extra sort numbers tucked inbetween.");
  580.                     } else {
  581.                         alert("The missing sort numbers are: " + missingValues + "\nAnd the extra sort numbers are: " + extraValues);
  582.                     }
  583.                 }
  584.             } else if (userOperation == "E") {
  585.                 var items = document.getElementById("content").getElementsByTagName("a");
  586.                 var names = new Array();
  587.                 var artist, album;
  588.                 var artistMatch, artistMatchSecond, albumMatch;
  589.                 var combined;
  590.  
  591.                 for (var i = 0; i < items.length; ++i) {
  592.                     albumMatch = items[i].href.match(/torrents\.php\?id=([0-9]+)$/);
  593.                     if (albumMatch) {
  594.                         album = items[i].innerHTML;
  595.                         artistMatch = items[i-1].href.match(/artist\.php\?id=([0-9]+)$/);
  596.                        
  597.                         if (artistMatch) {
  598.                             artist = items[i-1].innerHTML;
  599.                             //check for 2 artists (eg. "Billy Bragg" and "Wilco" - "Mermaid Avenue")
  600.                             artistMatchSecond = items[i-2].href.match(/artist\.php\?id=([0-9]+)$/);
  601.                             if (artistMatchSecond) { artist = items[i-2].innerHTML + " and " + artist; }
  602.                             // sort by artist - album
  603.                             if (userOperation == "E" ) { combined = "\"" + artist + "\",\"" + album+  "\""; }
  604.                             // sort by album - artist
  605.                             else {combined = "\"" + album + "\",\"" + artist + "\""; }
  606.                         } else {
  607.                             // case for no artist found (ie pdf, audiobook, Various Artists etc)
  608.                             combined = ",\"" + album + "\"";
  609.                            
  610.                             // super ugly way to handle Various Artists for sort by artist (if anyone has a better idea, I'm all ears :)
  611.                             var itemsx = document.getElementById("content").getElementsByTagName("tr");
  612.                             outerLoop: for (var z = 0; z < itemsx.length; ++z) {
  613.                                 var itemsInnerHTML = itemsx[z].innerHTML
  614.                                 var match = itemsInnerHTML.match(/torrents\.php/);
  615.                                 if (match) {
  616.                                     if (itemsx[z].innerHTML.match(/Various Artists/)) {
  617.                                         var tempAlbumCheck = itemsInnerHTML.substring(itemsInnerHTML.indexOf("Torrent\">")+9, itemsInnerHTML.indexOf("</a>"));
  618.                                         if (album == tempAlbumCheck) {
  619.                                             //put at end of sort list
  620.                                             combined = "\"Various Artits\",\"" + album + "\"";
  621.                                             break outerLoop;
  622.                                         }
  623.                                     }
  624.                                 }
  625.                             }
  626.                         }
  627.                         names.push(combined);
  628.                     }
  629.                 }
  630.                 var message = '';
  631.                 for (var x = 0; x < names.length; ++x) {
  632.                     message = message + names[x] + "<br>";
  633.                 }
  634.                 document.body.innerHTML = message;
  635.                
  636.             }
  637.  
  638.             // uncheck the boxes in the range (note: the above/below loops should be separate for speed issues
  639.             for (var c =0; c< lx.length; ++c) {
  640.                 if (c >= upperRangeValue && c <= lowerRangeValue) {
  641.                     box[c].checked = false;
  642.                     box[c].disabled = false;
  643.                 }  
  644.             }
  645.             box[upperRangeValue].setAttribute('realChecked', "0");
  646.             box[lowerRangeValue].setAttribute('realChecked', "0");
  647.         }
  648.     }, false);
  649. }
  650.  
  651.  
  652. // get the collage ID from stored file
  653. function getCollageID() {
  654.     collageID = GM_getValue('activeCollageID', '0');
  655.     collName = GM_getValue('activeCollageName', 'None');
  656. }
  657.  
  658. // write the collage ID to the stored file
  659. function setCollageID(linkref) {
  660.     if (linkref.getAttribute('collage-id') == '0') {
  661.         GM_deleteValue('activeCollageID');
  662.         GM_deleteValue('activeCollageName');
  663.         torrentCache.GM_delete();
  664.     } else {
  665.         GM_setValue('activeCollageID', linkref.getAttribute('collage-id'));
  666.         GM_setValue('activeCollageName', linkref.getAttribute('collage-name'));
  667.     }
  668.     window.location.reload();
  669. }
  670.  
  671. function image_click(e) {
  672.     var authKey = findAuthKey();
  673.  
  674.     //error checking on collageID in case user updates collage and doesn't refresh torrents.php page
  675.     if (GM_getValue('activeCollageID') != collageID) {
  676.         alert('Active collage has changed. Refresh the page and try again!');
  677.         return;
  678.     }
  679.  
  680.     var img = this; //necessary to be able to change the image's src attribute from within the onload/onerror closures
  681.  
  682.     var inCollage = torrentCache.contains(img.getAttribute('torrentgroupid'));
  683.  
  684.     img.src = ICON_LOADING;
  685.  
  686.     GM_xmlhttpRequest({
  687.         method: "POST",
  688.         url: URL.Host + "/collages.php",
  689.         data: (inCollage ?
  690.             'action=manage_handle&auth=' + authKey + '&collageid=' + collageID + '&groupid=' + img.getAttribute('torrentgroupid') + '&submit=Remove' :
  691.             'action=add_torrent&auth=' + authKey + '&collageid=' + collageID + '&url=' + img.getAttribute('torrent-url')),
  692.         headers: { "Content-Type" : "application/x-www-form-urlencoded" },
  693.         onload: function(response) {
  694.             // we get redirected if the action was successful, so if we are still on collages.php$, that means that something went wrong.
  695.             if (response.finalUrl.match(/\/collages\.php$/)) {
  696.                 // generically read out the error message. yes, this code isn't pretty :-/
  697.                 var title = response.responseText.substring(response.responseText.search('<h2>')+4);
  698.                 title = title.substring(0, title.search('</h2>'));
  699.                 var description = response.responseText.substring(response.responseText.search('<h2>Error</h2>'));
  700.                 description = description.substring(description.search('<p>')+3);
  701.                 description = description.substring(0, description.search('</p>'));
  702.                
  703.                 img.src = ICON_ERR;
  704.                 alert(title+"\n\n"+description);
  705.             } else {
  706.                 // Remember: inCollage is determined *before* sending the request. When inCollage is true, the torrent now isn't in the collage anymore!
  707.                 if (inCollage) {
  708.                     torrentCache.remove(img.getAttribute('torrentgroupid'));
  709.                 } else {
  710.                     torrentCache.add(img.getAttribute('torrentgroupid'));
  711.                 }
  712.                 torrentCache.GM_save();
  713.                 updateAddIcon(img);
  714.             }
  715.         },
  716.         onerror: function(f) {
  717.             img.src = ICON_ERR;
  718.             alert('Some unknown error occured. Refresh the page and try again!');
  719.         }
  720.     });
  721. }
  722.  
  723. function manage_remove_click(e) {
  724.     torrentCache.remove(e.target.getAttribute('torrentgroupid'));
  725.     torrentCache.GM_save();
  726.     return true;
  727. }
  728.  
  729. //find authkey
  730. function findAuthKey() {
  731.     return unsafeWindow.authkey;
  732. }
  733.  
  734. // preference for always showing checkboxes on manage page
  735. GM_registerMenuCommand("PTH.ME :: Collage Building Helper - MathRange checkboxes", function() {
  736.     var checkBoxQuestion;
  737.     for (var zz = 1; zz <= 3 && isNaN(checkBoxQuestion); ++zz) {
  738.         checkBoxQuestion = prompt("Do you want the checkboxes to always appear on the manage collage page?\nType \"1\" for yes and \"0\" for no.\nCurrent selection is: " + GM_getValue("checkBoxAlwaysOn", "0") + " (0 is default)");
  739.         if (checkBoxQuestion != null && checkBoxQuestion != '') {
  740.             checkBoxQuestion = parseInt(checkBoxQuestion);
  741.             if (isNaN(checkBoxQuestion)) {
  742.                 if (zz==3) {
  743.                     alert("Try harder!  Better luck next time!");
  744.                 } else {
  745.                     alert("Please pick \"1\" or \"0\" (no quotes)");
  746.                 }
  747.             } else if (checkBoxQuestion == 0 || checkBoxQuestion == 1) {
  748.                 GM_setValue("checkBoxAlwaysOn", checkBoxQuestion);
  749.             } else {
  750.                 alert("Please pick \"1\" or \"0\" (no quotes)");
  751.             }
  752.         }
  753.     }
  754. });
  755.  
  756. init();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement