Advertisement
Guest User

SpookyX v24

a guest
Mar 29th, 2015
1,967
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ==UserScript==
  2. // Displayable Name of your script
  3. // @name           SpookyX
  4.  
  5. // Brief description
  6. // @description    Enhances functionality of FoolFuuka boards. Devloped further for more comfortable ghost-posting on the moe archives.
  7.  
  8. // Your name, copyright  
  9. // @author          GNH
  10. // @copyright      2014, GNH
  11.  
  12. // Version Number
  13. // @version        24
  14.  
  15. // @include          https://*4plebs.org/*
  16. // @include          http://*4plebs.org/*
  17. // @include          https://archive.moe/*
  18. // @include          http://*loveisover.me/*
  19. // @include          https://*loveisover.me/*
  20. // @include          http://*imcute.yt/*
  21. // @include          https://*imcute.yt/*
  22. // @include          http://boards.foolz.us/*
  23. // @include          https://boards.foolz.us/*
  24. // @include          https://*nyafuu.org/*
  25. // @include          http://*nyafuu.org/*
  26. // @include          https://*fgts.jp/*
  27. // @include          http://*fgts.jp/*
  28. // @include          https://*not4plebs.org/*
  29. // @include          http://*not4plebs.org/*
  30.  
  31. // @grant       none
  32.  
  33. // ==/UserScript==
  34.  
  35. /* USER OPTIONS START */
  36. var imgSites = "puu.sh|i.imgur.com|data.archive.moe|i.4cdn.org|i0.kym-cdn.com|[\\S]*.deviantart.net|a.pomf.se|36.media.tumblr.com"; // Sites to embed images from
  37. var imgNumMaster = 1; // Max number of images to embed
  38. var autoplayVids = false; // Make embedded videos play automatically (they start muted, expanding unmutes)
  39. var hideQROptions = true; // Make the reply options hidden by default in the quick reply
  40. var favicon = {
  41.     "unlit": "http://i.imgur.com/xuadeJ2.png", // Choose which favicon is used normally. Default is "http://i.imgur.com/xuadeJ2.png"
  42.     "lit": 2, // Choose which favicon is used to indicate there are unread posts. Preset numbers are 0-4, replace with link to custom image if you desire such as: "http://i.imgur.com/XGsrewo.png"
  43.     "alert":"", // The favicon that indicates unread replies to your posts. Value is ignored if using a preset faviconLit
  44.     "alertOverlay":"http://i.imgur.com/6EfJyYA.png" // The favicon overlay that indicates unread replies. Default is "http://i.imgur.com/6EfJyYA.png"
  45. };
  46. var features = {
  47.     "postCounter":false,   // Add a post counter to the reply box
  48.     "inlineImages":true,   // Load full-size images in the thread, enable click to expand
  49.     "hidePosts":false,     // Allow user to hide posts manually
  50.     "newPosts":true,       // Reflect new posts in the tab name
  51.     "embedImages":true,    // Embed image links in thread
  52.     "inlineReplies":true,  // Click replies to expand them inline
  53.     "postQuote":true,      // Clicking the post number will insert highlighted text into the reply box
  54.     "filter":false,          // Hide undesirable posts from view
  55.     "labelYourPosts":true, // Add '(You)' to your posts and links that point to them
  56.     "favicon":true,        // Switch to a dynamic favicon that indicates unread posts and unread replies
  57.     "imageHover":true,     // Hovering over images with the mouse brings a full or window scaled version in view
  58.     "videoHover":true      // Hovering over videos with the mouse brings a full or window scaled version in view
  59. };
  60. var filterCharThreshold = 100; // Filter posts with less than this number of characters
  61. var filteredStringsT0 = [    // List of Tier 0 strings to filter for. Capitalisation sensitive
  62.     //"[\\S]*(a{4,}|b{4,}|c{4,}|d{4,}|e{4,}|f{4,}|g{4,}|h{4,}|i{4,}|j{4,}|k{4,}|l{4,}|m{4,}|n{4,}|o{4,}|p{4,}|q{4,}|r{4,}|s{4,}|t{4,}|u{4,}|v{4,}|w{4,}|x{4,}|y{4,}|z{4,})[\\S]*",
  63.     "[\\S]*(e{4,}|E{4,}|i{4,}|I{4,}|o{4,}|O{4,}|u{4,}|U{4,})[\\S]*",
  64.     "E(G|g)(O|o)(-kun|kun)?"
  65. ];
  66. var filteredStringsT1 = [    // List of Tier 1 strings to filter for
  67.     "daki[\\S]*",
  68.     "ded",
  69.     "ayy lmao",
  70.     "incest",
  71.     "imoutos?",
  72.     "moonrunes",
  73.     "tale[\\S]*[^( of witches)]",
  74.     "ree+[\\S]*",
  75.     "boogeyman",
  76.     "normies"
  77. ];
  78. var filteredStringsT2 = [    // List of Tier 2 strings to filter for
  79.     "quest whe?n[?]*",
  80.     "test",
  81.     "tsukaima"
  82. ];
  83. var filteredTrips = [       // List of tripcodes to filter for
  84.     "!!/90sanF9F3Z"
  85. ];
  86. var filteredNames = [       // List of names to filter for
  87.     "久保島のミズゴロウ"
  88. ];
  89. /* USER OPTIONS END */
  90.  
  91. var newPostCount = 0;
  92. var DocumentTitle = document.title;
  93. var ignoreInline = ['v'];
  94. var rulesBox = $(".rules_box").html();
  95. if(autoplayVids){var autoplayVid = "autoplay";}else{var autoplayVid="";}
  96. var queuedYouLabels = [];
  97.  
  98. var pattThreadAndID = new RegExp("thread\/[0-9]+\/");
  99. var pattThreadID = new RegExp("[0-9]+");
  100. var threadID; // Returns undefined if there's no thread
  101. if (pattThreadAndID.exec(document.URL) !== null){
  102.     threadID = pattThreadID.exec(pattThreadAndID.exec(document.URL))[0];
  103. }
  104.  
  105. function ThreadUpdate(features) {
  106.     if (features.postCounter){postCounter();}  
  107.     if (features.inlineImages){inlineImages();}
  108.     if (features.hidePosts){hidePosts();}
  109.     if (features.newPosts){newPosts();}
  110.     if (features.embedImages){embedImages();}
  111.     if (features.inlineReplies){inlineReplies();}
  112.     if (features.postQuote){postQuote();}
  113.     if (features.filter){filter();}
  114. }
  115.  
  116. switch(favicon.lit) {
  117.     case 0: favicon.lit = "http://i.imgur.com/7iTgtjy.png"; favicon.alert = "http://i.imgur.com/QrkQSo0.png"; break;
  118.     case 1: favicon.lit = "http://i.imgur.com/AWVjxfw.png"; favicon.alert = "http://i.imgur.com/KXIPcD9.png"; break;
  119.     case 2: favicon.lit = "http://i.imgur.com/S7uBSPZ.png"; favicon.alert = "http://i.imgur.com/7IxJvBN.png"; break;
  120.     case 3: favicon.lit = "http://i.imgur.com/Rt8dEaq.png"; favicon.alert = "http://i.imgur.com/tvJjpqF.png"; break;
  121.     case 4: favicon.lit = "http://i.imgur.com/3bRaVUl.png"; favicon.alert = "http://i.imgur.com/5Bv27Co.png"; break;
  122.     default: break;
  123. }
  124.  
  125. $.fn.elemText = function() {
  126.     var text = '';
  127.     this.each(function() {
  128.         $(this).contents().each(function() {
  129.             if (this.nodeType == Node.TEXT_NODE)
  130.                 text += this.textContent;
  131.         });
  132.     });
  133.     return text;
  134. };
  135.  
  136. var escapeRegExp;
  137.  
  138. $.fn.isOnScreen = function(){
  139.     var win = $(window);
  140.     var viewport = {
  141.         top : win.scrollTop(),
  142.         left : win.scrollLeft()
  143.     };
  144.     viewport.right = viewport.left + win.width();
  145.     viewport.bottom = viewport.top + win.height() - 200;
  146.  
  147.     var bounds = this.offset();
  148.     bounds.right = bounds.left + this.outerWidth();
  149.     bounds.bottom = bounds.top + this.outerHeight();
  150.  
  151.     return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
  152. };
  153.  
  154. (function () {
  155.     // Referring to the table here:
  156.     // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  157.     // these characters should be escaped
  158.     // \ ^ $ * + ? . ( ) | { } [ ]
  159.     // These characters only have special meaning inside of brackets
  160.     // they do not need to be escaped, but they MAY be escaped
  161.     // without any adverse effects (to the best of my knowledge and casual testing)
  162.     // : ! , =
  163.     // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
  164.  
  165.     var specials = [
  166.         // order matters for these
  167.         "-"
  168.         , "["
  169.         , "]"
  170.         // order doesn't matter for any of these
  171.         , "/"
  172.         , "{"
  173.         , "}"
  174.         , "("
  175.         , ")"
  176.         , "*"
  177.         , "+"
  178.         , "?"
  179.         , "."
  180.         , "\\"
  181.         , "^"
  182.         , "$"
  183.         , "|"
  184.     ]
  185.  
  186.     // I choose to escape every character with '\'
  187.     // even though only some strictly require it when inside of []
  188.     , regex = RegExp('[' + specials.join('\\') + ']', 'g')
  189.     ;
  190.     escapeRegExp = function (str) {
  191.         return str.replace(regex, "\\$&");
  192.     };
  193.  
  194.     // test escapeRegExp("/path/to/res?search=this.that")
  195. }());
  196.  
  197. shortcut = {
  198.     'all_shortcuts':{},//All the shortcuts are stored in this array
  199.     'add': function(shortcut_combination,callback,opt) {
  200.         //Provide a set of default options
  201.         var default_options = {
  202.             'type':'keydown',
  203.             'propagate':false,
  204.             'disable_in_input':false,
  205.             'target':document,
  206.             'keycode':false
  207.         };
  208.         if(!opt) opt = default_options;
  209.         else {
  210.             for(var dfo in default_options) {
  211.                 if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
  212.             }
  213.         }
  214.  
  215.         var ele = opt.target;
  216.         if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
  217.         var ths = this;
  218.         shortcut_combination = shortcut_combination.toLowerCase();
  219.  
  220.         //The function to be called at keypress
  221.         var func = function(e) {
  222.             e = e || window.event;
  223.  
  224.             if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
  225.                 var element;
  226.                 if(e.target) element=e.target;
  227.                 else if(e.srcElement) element=e.srcElement;
  228.                 if(element.nodeType==3) element=element.parentNode;
  229.  
  230.                 if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
  231.             }
  232.  
  233.             //Find Which key is pressed
  234.             if (e.keyCode) code = e.keyCode;
  235.             else if (e.which) code = e.which;
  236.             var character = String.fromCharCode(code).toLowerCase();
  237.  
  238.             if(code == 188) character=","; //If the user presses , when the type is onkeydown
  239.             if(code == 190) character="."; //If the user presses , when the type is onkeydown
  240.  
  241.             var keys = shortcut_combination.split("+");
  242.             //Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
  243.             var kp = 0;
  244.  
  245.             //Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
  246.             var shift_nums = {
  247.                 "`":"~",
  248.                 "1":"!",
  249.                 "2":"@",
  250.                 "3":"#",
  251.                 "4":"$",
  252.                 "5":"%",
  253.                 "6":"^",
  254.                 "7":"&",
  255.                 "8":"*",
  256.                 "9":"(",
  257.                 "0":")",
  258.                 "-":"_",
  259.                 "=":"+",
  260.                 ";":":",
  261.                 "'":"\"",
  262.                 ",":"<",
  263.                 ".":">",
  264.                 "/":"?",
  265.                 "\\":"|"
  266.             };
  267.             //Special Keys - and their codes
  268.             var special_keys = {
  269.                 'esc':27,
  270.                 'escape':27,
  271.                 'tab':9,
  272.                 'space':32,
  273.                 'return':13,
  274.                 'enter':13,
  275.                 'backspace':8,
  276.  
  277.                 'scrolllock':145,
  278.                 'scroll_lock':145,
  279.                 'scroll':145,
  280.                 'capslock':20,
  281.                 'caps_lock':20,
  282.                 'caps':20,
  283.                 'numlock':144,
  284.                 'num_lock':144,
  285.                 'num':144,
  286.  
  287.                 'pause':19,
  288.                 'break':19,
  289.  
  290.                 'insert':45,
  291.                 'home':36,
  292.                 'delete':46,
  293.                 'end':35,
  294.  
  295.                 'pageup':33,
  296.                 'page_up':33,
  297.                 'pu':33,
  298.  
  299.                 'pagedown':34,
  300.                 'page_down':34,
  301.                 'pd':34,
  302.  
  303.                 'left':37,
  304.                 'up':38,
  305.                 'right':39,
  306.                 'down':40,
  307.  
  308.                 'f1':112,
  309.                 'f2':113,
  310.                 'f3':114,
  311.                 'f4':115,
  312.                 'f5':116,
  313.                 'f6':117,
  314.                 'f7':118,
  315.                 'f8':119,
  316.                 'f9':120,
  317.                 'f10':121,
  318.                 'f11':122,
  319.                 'f12':123
  320.             };
  321.  
  322.             var modifiers = {
  323.                 shift: { wanted:false, pressed:false},
  324.                 ctrl : { wanted:false, pressed:false},
  325.                 alt  : { wanted:false, pressed:false},
  326.                 meta : { wanted:false, pressed:false} //Meta is Mac specific
  327.             };
  328.  
  329.             if(e.ctrlKey) modifiers.ctrl.pressed = true;
  330.             if(e.shiftKey)  modifiers.shift.pressed = true;
  331.             if(e.altKey)  modifiers.alt.pressed = true;
  332.             if(e.metaKey)   modifiers.meta.pressed = true;
  333.  
  334.             for(var i=0; k=keys[i],i<keys.length; i++) {
  335.                 //Modifiers
  336.                 if(k == 'ctrl' || k == 'control') {
  337.                     kp++;
  338.                     modifiers.ctrl.wanted = true;
  339.  
  340.                 } else if(k == 'shift') {
  341.                     kp++;
  342.                     modifiers.shift.wanted = true;
  343.  
  344.                 } else if(k == 'alt') {
  345.                     kp++;
  346.                     modifiers.alt.wanted = true;
  347.                 } else if(k == 'meta') {
  348.                     kp++;
  349.                     modifiers.meta.wanted = true;
  350.                 } else if(k.length > 1) { //If it is a special key
  351.                     if(special_keys[k] == code) kp++;
  352.  
  353.                 } else if(opt['keycode']) {
  354.                     if(opt['keycode'] == code) kp++;
  355.  
  356.                 } else { //The special keys did not match
  357.                     if(character == k) kp++;
  358.                     else {
  359.                         if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
  360.                             character = shift_nums[character];
  361.                             if(character == k) kp++;
  362.                         }
  363.                     }
  364.                 }
  365.             }
  366.  
  367.             if(kp == keys.length &&
  368.                modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
  369.                modifiers.shift.pressed == modifiers.shift.wanted &&
  370.                modifiers.alt.pressed == modifiers.alt.wanted &&
  371.                modifiers.meta.pressed == modifiers.meta.wanted) {
  372.                 callback(e);
  373.  
  374.                 if(!opt['propagate']) { //Stop the event
  375.                     //e.cancelBubble is supported by IE - this will kill the bubbling process.
  376.                     e.cancelBubble = true;
  377.                     e.returnValue = false;
  378.  
  379.                     //e.stopPropagation works in Firefox.
  380.                     if (e.stopPropagation) {
  381.                         e.stopPropagation();
  382.                         e.preventDefault();
  383.                     }
  384.                     return false;
  385.                 }
  386.             }
  387.         };
  388.         this.all_shortcuts[shortcut_combination] = {
  389.             'callback':func,
  390.             'target':ele,
  391.             'event': opt['type']
  392.         };
  393.         //Attach the function with the event
  394.         if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
  395.         else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
  396.         else ele['on'+opt['type']] = func;
  397.     },
  398.  
  399.     //Remove the shortcut - just specify the shortcut and I will remove the binding
  400.     'remove':function(shortcut_combination) {
  401.         shortcut_combination = shortcut_combination.toLowerCase();
  402.         var binding = this.all_shortcuts[shortcut_combination];
  403.         delete(this.all_shortcuts[shortcut_combination]);
  404.         if(!binding) return;
  405.         var type = binding['event'];
  406.         var ele = binding['target'];
  407.         var callback = binding['callback'];
  408.  
  409.         if(ele.detachEvent) ele.detachEvent('on'+type, callback);
  410.         else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
  411.         else ele['on'+type] = false;
  412.     }
  413. };
  414.  
  415. var getBoard = function() {
  416.     var URL = document.URL;
  417.     return URL.split("/")[3];
  418. };
  419.  
  420. var inlineImages = function()
  421. {
  422.     // I Believe because I'm setting the src of the thumbnail to the full image right away,
  423.     // it also causes the images to be prefetched
  424.     $('.thread_image_box').each(function(index,currentImage) {
  425.         if ($(currentImage).data("inline") != "true"){
  426.             //$(currentImage).find('a').each(function() {
  427.             $(currentImage).find('>a').each(function() {
  428.                 fullImage = $(this).attr('href');
  429.                 //    if (!fullImage.match(/thumb(-[23])?/)){
  430.                 //        if (!fullImage.match(/search(-[23])?/)){
  431.                 //            if (!fullImage.match(/redirect?/)){
  432.                 //                if (!fullImage.match(/download/)){
  433.                 if (fullImage.match(/\.webm$/)){ // Handle post webms
  434.                     $(currentImage).html('<video width="125" style="float:left" name="media" loop muted '+autoplayVid+'><source src="'+fullImage+'" type="video/webm"></video>');
  435.                 }else if (!fullImage.match(/(\.pdf|\.swf)$/)){
  436.                     $(currentImage).find('img').each(function()  {
  437.                         var thumbImage = $(this).attr('src');
  438.                         $(this).attr('src',fullImage);
  439.                         $(this).error(function(){$(this).attr('src',thumbImage);});
  440.                         $(this).removeAttr('width');
  441.                         $(this).removeAttr('height');
  442.                         if ($(this).data("handled") != "true"){
  443.                             if ($(this).hasClass("thread_image")){ // Handle OP images
  444.                                 $(this).data("handled","true");
  445.                                 $(this).addClass("smallImageOP");
  446.                                 $(this).click(function(e){
  447.                                     if (!e.originalEvent.ctrlKey && e.which == 1){
  448.                                         e.preventDefault();
  449.                                         $($(this)["0"]["previousSibling"]).toggle(); // Toggle the Spoiler text
  450.                                         $(this).toggleClass("smallImageOP");
  451.                                         $(this).toggleClass("bigImage");
  452.                                         $('#hoverUI').html('');
  453.                                         $(this).trigger("mouseenter");
  454.                                     }
  455.                                 });
  456.                             }else{ // Handle post images
  457.                                 $(this).addClass("smallImage");
  458.                                 $(this).click(function(e){
  459.                                     if (!e.originalEvent.ctrlKey && e.which == 1){
  460.                                         e.preventDefault();
  461.                                         $($(this)["0"]["previousSibling"]).toggle(); // Toggle the Spoiler text
  462.                                         $(this).toggleClass("smallImage");
  463.                                         $(this).toggleClass("bigImage");
  464.                                         $('#hoverUI').html('');
  465.                                         $(this).trigger("mouseenter");
  466.                                     }
  467.                                 });
  468.                             }
  469.                         }
  470.                     });
  471.                 }
  472.                 //              }
  473.                 //          }    
  474.                 $(currentImage).data("inline","true");
  475.                 //      }
  476.                 //  }
  477.             });
  478.             if(features.imageHover){imageHover();}
  479.         }
  480.     });
  481.  
  482.     $('video').each(function(index,currentVideo) {
  483.         if ($(currentVideo).data("inline") != "true"){
  484.             $(this).click(function(e){
  485.                 //e.preventDefault();
  486.                 if ($(this).hasClass("fullVideo")){
  487.                     this.pause();
  488.                     this.muted=true;
  489.                     $(this).attr('width',"125");
  490.                     $(this).removeAttr('controls');
  491.                     $(this).removeClass("fullVideo");
  492.                 }else{
  493.                     $(this).removeAttr('width');
  494.                     $(this).attr('controls',"");
  495.                     $(this).addClass("fullVideo");
  496.                     this.muted=false;
  497.                     this.play();
  498.                 }
  499.                 $('#hoverUI').html('');
  500.                 $(this).trigger("mouseenter");
  501.             });
  502.             $(currentVideo).data("inline","true");
  503.             if(features.videoHover){videoHover();}
  504.         }
  505.     });
  506. };
  507.  
  508. var inlineReplies = function(){
  509.     $('article.post').each(function(index,currentPost) {
  510.         if ($(currentPost).data("inline") != "true"){
  511.             $(this).addClass("base");
  512.         }
  513.         $(currentPost).data("inline","true");
  514.     });
  515.     $('.post_backlink > .backlink').each(function(index,currentPost) {
  516.         if ($(currentPost).data("inline") != "true"){
  517.             $(this).on("click", function(e){
  518.                 if (!e.originalEvent.ctrlKey && e.which == 1){
  519.                     e.preventDefault();
  520.                     //e.stopPropagation();
  521.                     var postID = $(this).attr("data-post");
  522.                     var rootPostID = $(e["target"].closest('article.base')).attr('id');
  523.                     if ($(e["target"]).hasClass("inlined")){
  524.                         $(e["target"]).removeClass("inlined");
  525.                         $('.sub'+rootPostID).each(function(index,currentPost){
  526.                             $("#"+currentPost.id.substr(1)+".forwarded").removeClass("forwarded");
  527.                         });
  528.                         $('#i'+postID+'.sub'+rootPostID).remove();
  529.                     }else{
  530.                         $(e["target"]).addClass("inlined");
  531.                         $(e["target"]["parentNode"]["parentNode"]).after('<div class="inline sub'+rootPostID+'" id="i'+postID+'"></div>');
  532.                         $("#"+postID).addClass("forwarded").clone().removeClass("forwarded base post").attr("id","r"+postID).appendTo($("#i"+postID+'.sub'+rootPostID));
  533.                         $("#"+rootPostID+'.base .inline').each(function(index,currentPost){
  534.                             if (!$(this).hasClass('sub'+rootPostID)){
  535.                                 $(this).attr("class","inline sub"+rootPostID);
  536.                             }
  537.                         });
  538.                         $("#i"+postID+" .post_wrapper").addClass("post_wrapperInline");
  539.                     }
  540.                 }
  541.             });
  542.             $(currentPost).data("inline","true");
  543.         }
  544.     });
  545.     $('.text .backlink').each(function(index,currentPost) {
  546.         if ($(currentPost).data("inline") != "true"){
  547.             $(this).on("click", function(e){
  548.                 if (!e.originalEvent.ctrlKey && e.which == 1){
  549.                     e.preventDefault();
  550.                     //e.stopPropagation();
  551.                     var postID = $(this).attr("data-post");
  552.                     var rootPostID = $(e["target"].closest('article.base')).attr('id');
  553.                     if ($(e["target"]).hasClass("inlined")){
  554.                         $(e["target"]).removeClass("inlined");
  555.                         $('.sub'+rootPostID).each(function(index,currentPost){
  556.                             $("#"+currentPost.id.substr(1)+".forwarded").removeClass("forwarded");
  557.                         });
  558.                         $('#i'+postID+'.sub'+rootPostID).remove();
  559.                     }else{
  560.                         $(e["target"]).addClass("inlined");
  561.                         $(e["target"]["parentNode"]).after('<div class="inline sub'+rootPostID+'" id="i'+postID+'"></div>');
  562.                         $("#"+postID).addClass("forwarded").clone().removeClass("forwarded base post").attr("id","r"+postID).appendTo($("#i"+postID+'.sub'+rootPostID));
  563.                         $("#"+rootPostID+'.base .inline').each(function(index,currentPost){
  564.                             if (!$(this).hasClass('sub'+rootPostID)){
  565.                                 $(this).attr("class","inline sub"+rootPostID);
  566.                             }
  567.                         });
  568.                         $("#i"+postID+" .post_wrapper").addClass("post_wrapperInline");
  569.                     }
  570.                 }
  571.             });
  572.             $(currentPost).data("inline","true");
  573.         }
  574.     });
  575. };
  576.  
  577. function getSelectionText() {
  578.     var text = "";
  579.     if (window.getSelection) {
  580.         text = window.getSelection().toString();
  581.     } else if (document.selection && document.selection.type != "Control") {
  582.         text = document.selection.createRange().text;
  583.     }
  584.     return text;
  585. }
  586.  
  587. var postQuote = function(){
  588.     $('.post_data > [data-function=quote]').each(function(index,currentPost) {
  589.         if ($(currentPost).data("quotable") != "true"){
  590.             $(this).removeAttr("data-function"); // Disable native quote function
  591.             $(this).on("click", function(e){
  592.                 if (!e.originalEvent.ctrlKey && e.which == 1){
  593.                     e.preventDefault();
  594.                     var postnum = $(this)["0"].innerHTML;
  595.                     var input = document.getElementById('reply_chennodiscursus');
  596.  
  597.                     if (input.selectionStart !== undefined)
  598.                     {
  599.                         var startPos = input.selectionStart;
  600.                         var endPos = input.selectionEnd;
  601.                         var startText = input.value.substring(0, startPos);
  602.                         var endText = input.value.substring(startPos);
  603.  
  604.                         var originalText = input.value;
  605.                         var selectedText = getSelectionText();
  606.                         var newText;
  607.                         if (selectedText === ""){
  608.                             newText = startText +">>"+postnum+"\n"+ endText;
  609.                         }else{
  610.                             newText = startText +">>"+postnum+"\n>"+ selectedText +"\n"+ endText;
  611.                         }
  612.                         document.getElementById('reply_chennodiscursus').value = originalText.replace(originalText,newText);
  613.                     }
  614.                 }
  615.             });
  616.             $(currentPost).data("quotable","true");
  617.         }
  618.     });
  619. };
  620.  
  621. var hidePosts = function(){
  622.     $('.pull-left').each(function(index, currentPost){
  623.         if ($(currentPost).hasClass('stub')) {
  624.             $(currentPost).removeClass('stub');
  625.         }
  626.     });
  627. };
  628.  
  629. var filter = function(){
  630.     var sieveStrT0 = new RegExp("\\b("+filteredStringsT0.join("|")+")\\b"); // \b or (^|\s) works
  631.     var sieveStrT1 = new RegExp("\\b("+filteredStringsT1.join("|")+")\\b","i"); // \b or (^|\s) works
  632.     var sieveStrT2 = new RegExp("(^|\\s)("+filteredStringsT2.join("|")+")($|\\s)","i");
  633.     var sieveTrip = new RegExp("("+filteredTrips.join("|")+")");
  634.     var sieveName = new RegExp("("+filteredNames.join("|")+")");
  635.  
  636.     $('article.post').each(function(index,currentPost){
  637.         if ($(currentPost).data("filtered") != "true"){
  638.             $(currentPost).data("filtered","true");
  639.             var postText = $(this).find('.text').elemText();
  640.             if (sieveTrip.test($(this).find('.post_tripcode').text()) || sieveName.test($(this).find('.post_author').text())){
  641.                 shitpostT2(currentPost, postText);
  642.             }else if(sieveStrT0.test(postText)){
  643.                 //console.log(postText.match(sieveStrT0));
  644.                 shitpostT0(currentPost, postText);
  645.             }else if (postText.length <= filterCharThreshold){
  646.                 if (sieveStrT1.test(postText)){
  647.                     //console.log(postText.match(sieveStrT1));
  648.                     shitpostT1(currentPost, postText);
  649.                 } else if (sieveStrT2.test(postText)){
  650.                     //console.log(postText.match(sieveStrT2));
  651.                     shitpostT2(currentPost, postText);
  652.                 }
  653.             }
  654.         }
  655.     });
  656. };
  657.  
  658. function shitpostT0(post, postText){
  659.     $(post).addClass("shitpost");
  660. }
  661. function shitpostT1(post, postText){
  662.     $(post).addClass("shitpost");
  663. }
  664. function shitpostT2(post, postText){
  665.     $(post).removeClass('stub');
  666.     $(post).find('.pull-left').removeClass('stub');
  667.     var docID = $(post).find('.pull-left > button').attr("data-doc-id");
  668.     $('.doc_id_'+docID).hide();
  669.     $('.stub_doc_id_'+docID).show();
  670. }
  671.  
  672. var embedImages = function() {
  673.     $('.posts article').each(function(index, currentArticle){
  674.         if ($(currentArticle).data('imgEmbed') != 'true'){
  675.             var patt = new RegExp("http[s]?://("+imgSites+")/[^\"]*");
  676.             var imgNum = imgNumMaster - $(currentArticle).find('.thread_image_box').length;
  677.             $(currentArticle).find(".text > a, .text > .spoiler, .text > strong").each(function(index, currentLink){
  678.                 if (imgNum === 0) {
  679.                     return false;
  680.                 }
  681.                 var imglink = patt.exec($(this).html());
  682.                 if (imglink !== null){
  683.                     imgNum--;
  684.                     // var patt2 = new RegExp(escapeRegExp(imglink["0"]), 'g'); Can't see what this does, uncomment if things break again
  685.                     imglink["0"] = imglink["0"].replace(/.gifv/g, ".webm"); // Only tested to work with Imgur
  686.                     var filename = '<div class="post_file embedded_post_file"><a href="'+imglink["0"]+'" class="post_file_filename" rel="tooltip" title="'+imglink["0"]+'">'+imglink["0"].match(/[^\/]*/g)[imglink["0"].match(/[^\/]*/g).length -2]+'</a></div>';
  687.                     var filestats = ""; //'<br><span class="post_file_metadata"> 937KiB, '+imglink["0"].naturalWidth+'x'+imglink["0"].naturalHeight+'</span>';
  688.                     if ((/.webm/g).test(imglink["0"])){
  689.                         $(currentArticle).find(".post_wrapper").prepend('<div class="thread_image_box"></div>');
  690.                         $(currentArticle).find(".thread_image_box:first-child").html(filename+'<video width="125" style="float:left" name="media" loop muted '+autoplayVid+'><source src="'+imglink["0"]+'" type="video/webm"></video>'+filestats);
  691.                     }else if ($(this).hasClass("spoiler")){
  692.                         $(currentArticle).find(".post_wrapper").prepend('<div class="thread_image_box">'+filename+'<a href="'+imglink["0"]+'" target="_blank" rel="noreferrer" class="thread_image_link"><div class="spoilerText">Spoiler</div><img src="'+imglink["0"]+'" class="lazyload post_image spoilerImage smallImage"></a>'+filestats+'</div>');
  693.                     }else{
  694.                         $(currentArticle).find(".post_wrapper").prepend('<div class="thread_image_box">'+filename+'<a href="'+imglink["0"]+'" target="_blank" rel="noreferrer" class="thread_image_link"><img src="'+imglink["0"]+'" class="lazyload post_image smallImage"></a>'+filestats+'</div>');
  695.                     }
  696.                     $(this).remove();
  697.                 }
  698.             });
  699.             $(currentArticle).data('imgEmbed', 'true');
  700.         }
  701.     });
  702. };
  703.  
  704. function imageHover(){
  705.     $('img').off("mouseenter");
  706.     $('img').off("mousemove");
  707.     $('img').off("mouseout");
  708.     $('img').on("mouseenter", function(e){
  709.         if(!$(this).hasClass("bigImage")){
  710.             $(this).clone().removeClass("smallImage smallImageOP spoilerImage").addClass("hoverImage").appendTo('#hoverUI');
  711.             $('#hoverUI > img').css({
  712.                 "max-height":window.innerHeight,
  713.                 "max-width":window.innerWidth - e.clientX - 50,
  714.                 "top": function(){
  715.                     return (e.clientY / window.innerHeight)*(window.innerHeight - $('#hoverUI > img')[0].height);
  716.                 },
  717.                 "left":e.clientX + 50
  718.             });
  719.         }
  720.     });
  721.     $('img').on("mousemove", function(e){
  722.         if(!$(this).hasClass("bigImage")){
  723.             $('#hoverUI > img').css({
  724.                 "max-width":window.innerWidth - e.clientX - 50,
  725.                 "top": function(){
  726.                     return (e.clientY / window.innerHeight)*(window.innerHeight - $('#hoverUI > img')[0].height);
  727.                 },
  728.                 "left":e.clientX + 50
  729.             });
  730.         }
  731.     });
  732.     $('img').on("mouseout", function(e){
  733.         $('#hoverUI').html('');
  734.     });
  735. }
  736.  
  737. function videoHover(){
  738.     $('video').off("mouseenter");
  739.     $('video').off("mousemove");
  740.     $('video').off("mouseout");
  741.     $('video').on("mouseenter", function(e){
  742.         if(!$(this).hasClass("fullVideo")){
  743.             $(this).clone().addClass("fullVideo hoverImage").appendTo('#hoverUI');
  744.             $('#hoverUI > video').removeAttr('width');
  745.             $('#hoverUI > video')[0].oncanplay = function(){
  746.                 if ($('#hoverUI > video').length){ // Check if video still exists. This is to prevent the problem where mousing out too soon still triggers the canplay event
  747.                     $('#hoverUI > video')[0].muted=false;
  748.                     $('#hoverUI > video')[0].play();
  749.                     $('#hoverUI > video').css({
  750.                         "max-height":window.innerHeight,
  751.                         "max-width":window.innerWidth - e.clientX - 50,
  752.                         "top": function(){
  753.                             return (e.clientY / window.innerHeight)*(window.innerHeight - $('#hoverUI > video')[0].videoHeight);
  754.                         },
  755.                         "left":e.clientX + 50
  756.                     });
  757.                     $('video').on("mousemove", function(e){
  758.                         $('#hoverUI > video').css({
  759.                             "top": function(){
  760.                                 return (e.clientY / window.innerHeight)*(window.innerHeight - $('#hoverUI > video')[0].videoHeight);
  761.                             },
  762.                             "left":e.clientX + 50
  763.                         });
  764.                     });
  765.                 }
  766.             }
  767.         }
  768.     });
  769.     $('video').on("mouseout", function(e){
  770.         $('#hoverUI').html('');
  771.     });
  772. }
  773.  
  774. var lastSeenPost;
  775. var unseenPosts = [];
  776. var seenPosts = function(){
  777.     $('article.backlink_container').attr('id',"0"); // Prevent error when it's undefined
  778.     $('article').each(function(index, currentArticle){ // Add unseen posts to array
  779.         if (parseInt($(currentArticle).attr('id').replace(/_/g, "")) > lastSeenPost){
  780.             unseenPosts.push($(currentArticle).attr('id'));
  781.         }
  782.     });
  783.     $('article.backlink_container').removeAttr('id'); // Remove id again
  784.     $('#'+unseenPosts[0]).addClass("unseenPost");
  785. };
  786.  
  787. var unseenReplies = [];
  788. var newPosts = function(){
  789.     if (features.favicon){
  790.         //console.log("newPosts called");
  791.         if (windowFocus === true){
  792.             $.each(unseenPosts, function(i,postID){
  793.                 if ($('#'+postID).isOnScreen() === true){
  794.                     lastSeenPost = postID.replace(/_/g, ""); // Update last seen post
  795.                     $.each(unseenReplies, function(i, unseenID){
  796.                         if (unseenID == postID){
  797.                             unseenReplies.splice(i,1); // Remove seen posts from the unseen replies
  798.                             return;
  799.                         }
  800.                     });
  801.                 }
  802.             });
  803.             $.each(unseenPosts.filter(function(el){
  804.                 return el.replace(/_/g, "") <= lastSeenPost;
  805.             }),function(i,postID){
  806.                 $('#'+postID).removeClass("unseenPost"); // Remove unseen class from all posts with lower ID than the last seen one
  807.             });
  808.             unseenPosts = unseenPosts.filter(function(el){
  809.                 return el.replace(/_/g, "") > lastSeenPost; // Remove posts from list of unseen ones if their ID is lower than the last seen one
  810.             });
  811.             $('#'+unseenPosts[0]).addClass("unseenPost"); // Add the unseen class to the first of the unseen posts
  812.         }
  813.         newPostCount = unseenPosts.length;
  814.         if (unseenReplies.length){
  815.             $('#favicon').attr("href", favicon.alert);
  816.         }else if (newPostCount > 0){
  817.             $('#favicon').attr("href", favicon.lit);
  818.         }else{
  819.             $('#favicon').attr("href", favicon.unlit);
  820.         }
  821.     }else{ // Original newpost counter code
  822.         $('article').each(function(index, currentArticle){
  823.             if ($(currentArticle).data('seen') != 'true')
  824.             {
  825.                 $(currentArticle).data('seen', 'true')
  826.                 newPostCount +=1
  827.             }
  828.         });
  829.         if (windowFocus == true){newPostCount = 0;}
  830.     }
  831.     document.title = "(" + newPostCount + ") " + DocumentTitle;
  832. };
  833.  
  834. var postCounter = function() {$(".rules_box").html("<h6>Posts: " + $('.post_wrapper').length + "/400 <br> Images: " + $(".thread_image_box").length + "/250</h6>" + rulesBox);};
  835.  
  836. var bindShortcuts = function()
  837. {
  838.  
  839. };
  840.  
  841. var pokemon = ["bulbasaur","ivysaur","venusaur","charmander","charmeleon","charizard","squirtle","wartortle","blastoise","caterpie","metapod","butterfree","weedle","kakuna","beedrill","pidgey","pidgeotto","pidgeot","rattata","raticate","spearow","fearow","ekans","arbok","pikachu","raichu","sandshrew","sandslash","nidoran♀","nidorina","nidoqueen","nidoran♂","nidorino","nidoking","clefairy","clefable","vulpix","ninetales","jigglypuff","wigglytuff","zubat","golbat","oddish","gloom","vileplume","paras","parasect","venonat","venomoth","diglett","dugtrio","meowth","persian","psyduck","golduck","mankey","primeape","growlithe","arcanine","poliwag","poliwhirl","poliwrath","abra","kadabra","alakazam","machop","machoke","machamp","bellsprout","weepinbell","victreebel","tentacool","tentacruel","geodude","graveler","golem","ponyta","rapidash","slowpoke","slowbro","magnemite","magneton","farfetch'd","doduo","dodrio","seel","dewgong","grimer","muk","shellder","cloyster","gastly","haunter","gengar","onix","drowzee","hypno","krabby","kingler","voltorb","electrode","exeggcute","exeggutor","cubone","marowak","hitmonlee","hitmonchan","lickitung","koffing","weezing","rhyhorn","rhydon","chansey","tangela","kangaskhan","horsea","seadra","goldeen","seaking","staryu","starmie","mr. mime","scyther","jynx","electabuzz","magmar","pinsir","tauros","magikarp","gyarados","lapras","ditto","eevee","vaporeon","jolteon","flareon","porygon","omanyte","omastar","kabuto","kabutops","aerodactyl","snorlax","articuno","zapdos","moltres","dratini","dragonair","dragonite","mewtwo","mew","chikorita","bayleef","meganium","cyndaquil","quilava","typhlosion","totodile","croconaw","feraligatr","sentret","furret","hoothoot","noctowl","ledyba","ledian","spinarak","ariados","crobat","chinchou","lanturn","pichu","cleffa","igglybuff","togepi","togetic","natu","xatu","mareep","flaaffy","ampharos","bellossom","marill","azumarill","sudowoodo","politoed","hoppip","skiploom","jumpluff","aipom","sunkern","sunflora","yanma","wooper","quagsire","espeon","umbreon","murkrow","slowking","misdreavus","unown","wobbuffet","girafarig","pineco","forretress","dunsparce","gligar","steelix","snubbull","granbull","qwilfish","scizor","shuckle","heracross","sneasel","teddiursa","ursaring","slugma","magcargo","swinub","piloswine","corsola","remoraid","octillery","delibird","mantine","skarmory","houndour","houndoom","kingdra","phanpy","donphan","porygon2","stantler","smeargle","tyrogue","hitmontop","smoochum","elekid","magby","miltank","blissey","raikou","entei","suicune","larvitar","pupitar","tyranitar","lugia","ho-oh","celebi","treecko","grovyle","sceptile","torchic","combusken","blaziken","mudkip","marshtomp","swampert","poochyena","mightyena","zigzagoon","linoone","wurmple","silcoon","beautifly","cascoon","dustox","lotad","lombre","ludicolo","seedot","nuzleaf","shiftry","taillow","swellow","wingull","pelipper","ralts","kirlia","gardevoir","surskit","masquerain","shroomish","breloom","slakoth","vigoroth","slaking","nincada","ninjask","shedinja","whismur","loudred","exploud","makuhita","hariyama","azurill","nosepass","skitty","delcatty","sableye","mawile","aron","lairon","aggron","meditite","medicham","electrike","manectric","plusle","minun","volbeat","illumise","roselia","gulpin","swalot","carvanha","sharpedo","wailmer","wailord","numel","camerupt","torkoal","spoink","grumpig","spinda","trapinch","vibrava","flygon","cacnea","cacturne","swablu","altaria","zangoose","seviper","lunatone","solrock","barboach","whiscash","corphish","crawdaunt","baltoy","claydol","lileep","cradily","anorith","armaldo","feebas","milotic","castform","kecleon","shuppet","banette","duskull","dusclops","tropius","chimecho","absol","wynaut","snorunt","glalie","spheal","sealeo","walrein","clamperl","huntail","gorebyss","relicanth","luvdisc","bagon","shelgon","salamence","beldum","metang","metagross","regirock","regice","registeel","latias","latios","kyogre","groudon","rayquaza","jirachi","deoxys","turtwig","grotle","torterra","chimchar","monferno","infernape","piplup","prinplup","empoleon","starly","staravia","staraptor","bidoof","bibarel","kricketot","kricketune","shinx","luxio","luxray","budew","roserade","cranidos","rampardos","shieldon","bastiodon","burmy","wormadam","mothim","combee","vespiquen","pachirisu","buizel","floatzel","cherubi","cherrim","shellos","gastrodon","ambipom","drifloon","drifblim","buneary","lopunny","mismagius","honchkrow","glameow","purugly","chingling","stunky","skuntank","bronzor","bronzong","bonsly","mime jr.","happiny","chatot","spiritomb","gible","gabite","garchomp","munchlax","riolu","lucario","hippopotas","hippowdon","skorupi","drapion","croagunk","toxicroak","carnivine","finneon","lumineon","mantyke","snover","abomasnow","weavile","magnezone","lickilicky","rhyperior","tangrowth","electivire","magmortar","togekiss","yanmega","leafeon","glaceon","gliscor","mamoswine","porygon-z","gallade","probopass","dusknoir","froslass","rotom","uxie","mesprit","azelf","dialga","palkia","heatran","regigigas","giratina","cresselia","phione","manaphy","darkrai","shaymin","arceus","victini","snivy","servine","serperior","tepig","pignite","emboar","oshawott","dewott","samurott","patrat","watchog","lillipup","herdier","stoutland","purrloin","liepard","pansage","simisage","pansear","simisear","panpour","simipour","munna","musharna","pidove","tranquill","unfezant","blitzle","zebstrika","roggenrola","boldore","gigalith","woobat","swoobat","drilbur","excadrill","audino","timburr","gurdurr","conkeldurr","tympole","palpitoad","seismitoad","throh","sawk","sewaddle","swadloon","leavanny","venipede","whirlipede","scolipede","cottonee","whimsicott","petilil","lilligant","basculin","sandile","krokorok","krookodile","darumaka","darmanitan","maractus","dwebble","crustle","scraggy","scrafty","sigilyph","yamask","cofagrigus","tirtouga","carracosta","archen","archeops","trubbish","garbodor","zorua","zoroark","minccino","cinccino","gothita","gothorita","gothitelle","solosis","duosion","reuniclus","ducklett","swanna","vanillite","vanillish","vanilluxe","deerling","sawsbuck","emolga","karrablast","escavalier","foongus","amoonguss","frillish","jellicent","alomomola","joltik","galvantula","ferroseed","ferrothorn","klink","klang","klinklang","tynamo","eelektrik","eelektross","elgyem","beheeyem","litwick","lampent","chandelure","axew","fraxure","haxorus","cubchoo","beartic","cryogonal","shelmet","accelgor","stunfisk","mienfoo","mienshao","druddigon","golett","golurk","pawniard","bisharp","bouffalant","rufflet","braviary","vullaby","mandibuzz","heatmor","durant","deino","zweilous","hydreigon","larvesta","volcarona","cobalion","terrakion","virizion","tornadus","thundurus","reshiram","zekrom","landorus","kyurem","keldeo","meloetta","genesect","chespin","quilladin","chesnaught","fennekin","braixen","delphox","froakie","frogadier","greninja","bunnelby","diggersby","fletchling","fletchinder","talonflame","scatterbug","spewpa","vivillon","litleo","pyroar","flabébé","floette","florges","skiddo","gogoat","pancham","pangoro","furfrou","espurr","meowstic","honedge","doublade","aegislash","spritzee","aromatisse","swirlix","slurpuff","inkay","malamar","binacle","barbaracle","skrelp","dragalge","clauncher","clawitzer","helioptile","heliolisk","tyrunt","tyrantrum","amaura","aurorus","sylveon","hawlucha","dedenne","carbink","goomy","sliggoo","goodra","klefki","phantump","trevenant","pumpkaboo","gourgeist","bergmite","avalugg","noibat","noivern","xerneas","yveltal","zygarde","diancie","hoopa","volcanion"];
  842. function notifyMe(title, image, body){
  843.     //console.log("notifyMe called");
  844.     if (!Notification){
  845.         alert('Please us a modern version of Chrome, Firefox, Opera or Firefox.');
  846.         return;
  847.     }
  848.  
  849.     if (Notification.permission !== "granted")
  850.         Notification.requestPermission();
  851.     var icon = image;
  852.     if(!Math.floor(Math.random()*8192)){
  853.         var ND = Math.floor(Math.random()*720);
  854.         icon = "http://img.pokemondb.net/sprites/black-white/shiny/"+pokemon[ND]+".png";
  855.     }
  856.  
  857.     var notification = new Notification(title, {
  858.         icon: icon,
  859.         body: body
  860.     });
  861.  
  862.     notification.onshow = function (){
  863.         setTimeout(notification.close.bind(notification), 5000);
  864.     };
  865.     notification.onclick = function (){
  866.         window.focus();
  867.     };
  868. }
  869.  
  870. if (features.labelYourPosts){
  871.     var yourPosts = localStorage.yourPosts;
  872.     if (yourPosts === undefined){
  873.         yourPosts = {};
  874.         console.log("Created post archive for the first time");
  875.     } else {
  876.         yourPosts = JSON.parse(localStorage.yourPosts);
  877.     }
  878. }
  879. if (features.favicon){
  880.     var lastSeenPosts = localStorage.lastSeenPosts;
  881.     if (lastSeenPosts === undefined){
  882.         lastSeenPosts = {};
  883.         console.log("Created unseen replies archive for the first time");
  884.     } else {
  885.         lastSeenPosts = JSON.parse(localStorage.lastSeenPosts);
  886.     }
  887.     lastSeenPost = lastSeenPosts[threadID];
  888. }
  889. window.addEventListener("beforeunload", function (e) { // After user leaves the page
  890.     if (features.labelYourPosts){ // Save the your posts object
  891.         if (localStorage.yourPosts === undefined){
  892.             localStorage.yourPosts = JSON.stringify(yourPosts);
  893.         } else {
  894.             localStorage.yourPosts = JSON.stringify($.extend(true, yourPosts, JSON.parse(localStorage.yourPosts)));
  895.         }
  896.     }
  897.     if (features.favicon){ // Save the last read posts object
  898.         lastSeenPosts[threadID] = lastSeenPost;
  899.         if (localStorage.lastSeenPosts === undefined){
  900.             localStorage.lastSeenPosts = JSON.stringify(lastSeenPosts);
  901.         } else {
  902.             latestLastSeenPosts = JSON.parse(localStorage.lastSeenPosts); // Get the most recent version of the stored object
  903.             if (latestLastSeenPosts[threadID] > lastSeenPosts[threadID]){
  904.                 localStorage.lastSeenPosts = JSON.stringify(latestLastSeenPosts); // Save it again
  905.             }else{
  906.                 localStorage.lastSeenPosts = JSON.stringify(lastSeenPosts); // Save it again
  907.             }
  908.         }
  909.     }
  910.     //var confirmationMessage = "\o/";
  911.  
  912.     //(e || window.event).returnValue = confirmationMessage; //Gecko + IE
  913.     //return confirmationMessage;                            //Webkit, Safari, Chrome
  914. });
  915.  
  916.  
  917. function labelYourPosts(firstcall){
  918.     $.each(queuedYouLabels, function(i, v){ // Parse all names on pageload and with each post submission
  919.         $('#'+v+' .post_author').after('<span> (You)</span>');
  920.     });
  921.     queuedYouLabels = [];
  922.  
  923.     if (firstcall){ // Parse all backlinks present on pageload
  924.         $.each(yourPosts[threadID], function(i,v){
  925.             $('.backlink[data-post='+v+']').each(function(){
  926.                 if ($(this).data('linkedYou') != 'true'){
  927.                     this.textContent += ' (You)';
  928.                     $(this).data('linkedYou','true');
  929.                 }
  930.             });
  931.         });
  932.     }
  933. }
  934.  
  935. function labelNewPosts(response){
  936.     var newPosts = Object.keys(response[threadID]["posts"]);
  937.     $.each(newPosts, function(i,postID){ // For each post returned by update
  938.         var notificationTriggered = false;
  939.         $('#'+postID+' .greentext > a').each(function(i, link){ // For each post content backlink
  940.             var linkID = $(link).attr('data-post');
  941.             if ($.inArray(linkID, yourPosts[threadID])+1){ // If the link points to your post
  942.                 if (!notificationTriggered){
  943.                     notifyMe($('#'+postID+' .post_poster_data').text().trim()+" replied to you","http://i.imgur.com/HTcKk4Y.png",$('#'+postID+' .text').text().trim());
  944.                     unseenReplies.push(postID); // add postID to list of unseen replies
  945.                     notificationTriggered = true;
  946.                 }
  947.                 link.textContent += ' (You)'; // Designate the link as such
  948.             }
  949.             if ($.inArray(postID, yourPosts[threadID])+1){ // If the post is your own
  950.                 var backlink = $('#'+linkID+' .post_backlink [data-post='+postID+']');
  951.                 if (backlink.data('linkedYou') != 'true'){
  952.                     backlink[0].textContent += ' (You)'; // Find your post's new reply backlink and designate it too
  953.                     backlink.data('linkedYou','true');
  954.                 }
  955.             }
  956.         });
  957.         unseenPosts.push(postID); // add postID to list of unseen posts
  958.     });
  959. }
  960.  
  961. var lastSubmittedContent;
  962. function postSubmitEvent(){
  963.     if ($('#reply [type=submit]').length){
  964.         window.MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
  965.         var target =  $('#reply [type=submit]')["0"],
  966.             observer = new MutationObserver(function(mutation) {
  967.                 //console.log("Post Submit Event Triggered");
  968.                 lastSubmittedContent = $('#reply_chennodiscursus')[0].value;
  969.             }),
  970.             config = {
  971.                 attributes: true
  972.             };
  973.         observer.observe(target, config);
  974.     }
  975. }
  976.  
  977. $(document).ready(function(){
  978.     $('head').after('<script src="https://cdn.rawgit.com/madapaja/jquery.selection/master/src/jquery.selection.js"></script>'); // Pull in selection plugin (http://madapaja.github.io/jquery.selection/)
  979.     $('head').after('<style type="text/css" id="FoolX-css">.unseenPost{border-top: red solid 1px;}.hoverImage{position:fixed;float:none!important;}.bigImage{opacity: 1!important; max-width:100%;}.smallImage{max-width:125px; max-height:125px}.smallImageOP{max-width:250px; max-height:250px}.spoilerImage{opacity: 0.1}.spoilerText{position: relative; height: 0px; font-size: 19px; top: 47px;}.forwarded{display:none}.inline{border:1px solid; display: table; margin: 2px 0;}.inlined{opacity:0.5}.post_wrapper{border-right: 1px solid #cccccc;}.post_wrapperInline{border-right:0!important; border-bottom:0!important;}.quickReply{position: fixed; top: 0; right: 0; margin: 3px !important;}.shitpost{opacity: 0.3}.embedded_post_file{margin: 0!important; width: 125px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}</style>');
  980.     if (features.favicon){
  981.         $('head').append('<link id="favicon" rel="shortcut icon" type="image/png" href="'+favicon.unlit+'">');
  982.         $('#reply fieldset .progress').after('<canvas id="myCanvas" width="64" height="64" style="float:left; display:none; position: relative; top: -10px; left: -10px;"></canvas>');
  983.     }
  984.     $('body').append('<div id="hoverUI"></div>');
  985.  
  986.     windowFocus = true;
  987.     $(window).focus(function(){windowFocus = true; ThreadUpdate(features);});
  988.     $(window).blur(function(){windowFocus = false;});
  989.     if (hideQROptions){
  990.         $('#reply').toggleClass("showQROptions"); // Make options hidden in QR by default
  991.     }
  992.     if (features.favicon){
  993.         if (lastSeenPosts[threadID] === undefined){
  994.             lastSeenPosts[threadID] = threadID;
  995.         }
  996.         lastSeenPost = lastSeenPosts[threadID];
  997.     }
  998.     if (features.labelYourPosts){
  999.         if (yourPosts[threadID] === undefined){
  1000.             yourPosts[threadID] = [];
  1001.         } else {
  1002.             queuedYouLabels = yourPosts[threadID].slice(0);
  1003.             //console.log(queuedYouLabels);
  1004.         }
  1005.         //console.log(yourPosts);
  1006.         postSubmitEvent();
  1007.  
  1008.         $(document).ajaxComplete(function(event, request, settings) {
  1009.             //console.log(event);
  1010.             //console.log(request);
  1011.             //console.log(settings);
  1012.             if (request.responseText !== ""){
  1013.                 response = JSON.parse(request.responseText);
  1014.             }else{
  1015.                 response = {"error":"No responseText"};
  1016.             }
  1017.             //console.log(response);
  1018.             if (response.error !== undefined){
  1019.                 //console.log(response.error);
  1020.             }else{
  1021.                 if (settings.type == "POST"){
  1022.                     if (response.error === undefined ){
  1023.                         for (var post in response[threadID]["posts"]) {
  1024.                             //console.log(lastSubmittedContent);                    
  1025.                             if(response[threadID]["posts"][post]["comment"].replace(/[\r\n]/g,'') == lastSubmittedContent.replace(/[\r\n]/g,'')){
  1026.                                 yourPosts[threadID].push(post);
  1027.                                 queuedYouLabels.push(post);
  1028.                                 //console.log(yourPosts);
  1029.                                 //console.log(queuedYouLabels);
  1030.                                 labelYourPosts();
  1031.                                 break;
  1032.                             }
  1033.                         }
  1034.                         labelNewPosts(response);
  1035.                     }else{
  1036.                         console.log(response.error);
  1037.                     }
  1038.                 }else{
  1039.                     if (response[threadID] !== undefined){
  1040.                         labelNewPosts(response);
  1041.                     }else{
  1042.                         //console.log("Not in a thread");
  1043.                     }
  1044.                 }
  1045.             }
  1046.         });
  1047.         labelYourPosts(true); // First call, add (You) to page content
  1048.     }
  1049.     if(features.imageHover){imageHover();}
  1050.     if(features.videoHover){videoHover();}
  1051. });
  1052.  
  1053. var executeShortcut = function(shortcut) {
  1054.     var input = document.getElementById('reply_chennodiscursus');
  1055.  
  1056.     if (input.selectionStart !== undefined){
  1057.         $('#reply_chennodiscursus').selection('insert', {
  1058.             text: "["+shortcut+"]",
  1059.             mode: 'before'
  1060.         });
  1061.         $('#reply_chennodiscursus').selection('insert', {
  1062.             text: "[/"+shortcut+"]",
  1063.             mode: 'after'
  1064.         });
  1065.     }
  1066. };
  1067.  
  1068. function quickReply(){
  1069.     $('#reply').toggleClass("quickReply");
  1070.     $('#reply fieldset > div:nth-child(1)').css("width","");
  1071.     if ($('#reply').hasClass("showQROptions")){
  1072.         $('#reply fieldset > div:nth-child(3)').toggle();
  1073.     }
  1074. }
  1075.  
  1076. function quickReplyOptions(){
  1077.     $('#reply').toggleClass("showQROptions");
  1078.     $('#reply.quickReply fieldset > div:nth-child(3)').toggle();
  1079. }
  1080.  
  1081. var favican = document.createElement("IMG");
  1082. favican.src=favicon.lit;
  1083. var exclam = document.createElement("IMG");
  1084. exclam.src=favicon.alertOverlay;
  1085.  
  1086. function canfav(){
  1087.     $('#myCanvas').toggle();
  1088.     $('#myCanvas')["0"].getContext("2d").drawImage(favican, 0, 0);
  1089.     $('#myCanvas')["0"].getContext("2d").drawImage(exclam, 0, 0);
  1090. }
  1091.  
  1092. $(function(){
  1093.     shortcut.add("ctrl+s", function(){ executeShortcut("spoiler");});
  1094.     shortcut.add("ctrl+i", function(){ executeShortcut("i");});
  1095.     shortcut.add("ctrl+b", function(){ executeShortcut("b");});
  1096.     shortcut.add("ctrl+u", function(){ executeShortcut("u");});
  1097.     shortcut.add("q", function(){quickReply();}, {"disable_in_input":true});
  1098.     shortcut.add("ctrl+q", function(){quickReplyOptions();}, {"disable_in_input":false});
  1099.     if (features.favicon){shortcut.add("f", function(){canfav();}, {"disable_in_input":true});}
  1100.  
  1101.     seenPosts();
  1102.     ThreadUpdate(features);
  1103.     getBoard();
  1104.     bindShortcuts();
  1105.     window.setInterval( function(){ ThreadUpdate(features); }, 500 );
  1106. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement