ImageFAQs

Converts image and webm URLs into their embedded form

目前为 2016-05-03 提交的版本。查看 最新版本

// ==UserScript==
// @name        ImageFAQs
// @namespace   FightingGames@gfaqs
// @include     http://www.gamefaqs.com
// @include     http://www.gamefaqs.com*
// @icon        http://fightinggames.bitbucket.org/imagefaqs/icon.png
// @description Converts image and webm URLs into their embedded form
// @version     1.18.5
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_log
// @grant       GM_xmlhttpRequest
// @require     http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
// @require     https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js
// @resource    jqueryuibaseCSS https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.base.css
// @resource    jqueryuithemeCSS https://code.jquery.com/ui/1.11.4/themes/cupertino/jquery-ui.css
// ==/UserScript==



/* 
    The MIT License (MIT)

    This greasemonkey script for GameFAQs converts image and webm
    links into their embedded form. It can be considered as a spiritual successor
    to text-to-image for GameFAQs. Many of its features are inspired from appchan x
    by zixaphir at http://zixaphir.github.io/appchan-x/.
    
    Copyright (c) 2015 FightingGames@gamefaqs <[email protected]>
    Copyright (c) 2015 FeaturingDante@gamefaqs <[email protected]>

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.

*/

/*
Get number of keys in a primitive java object
*/
Object.size = function(obj) {
    var size = 0
    var key;
    
    for (key in obj) {
        if (obj.hasOwnProperty(key)) 
            size++;
    }
    return size;
};


/*
Below is a collection of functions to iterate through HTML objects (e.g. step from <b></b> to <img/>)
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Whitespace_in_the_DOM
*/


/*
 * Determine whether a node's text content is entirely whitespace.
 *
 * @param nod  A node implementing the |CharacterData| interface (i.e.,
 *             a |Text|, |Comment|, or |CDATASection| node
 * @return     True if all of the text content of |nod| is whitespace,
 *             otherwise false.
 */
function is_all_ws( nod )
{
  // Use ECMA-262 Edition 3 String and RegExp features
  return !(/[^\t\n\r ]/.test(nod.textContent));
}


/*
 * Determine if a node should be ignored by the iterator functions.
 *
 * @param nod  An object implementing the DOM1 |Node| interface.
 * @return     true if the node is:
 *                1) A |Text| node that is all whitespace
 *                2) A |Comment| node
 *             and otherwise false.
 */

function is_ignorable( nod )
{
  return ( nod.nodeType == 8) || // A comment node
         ( (nod.nodeType == 3) && is_all_ws(nod) ); // a text node, all ws
}

/*
 * Version of |previousSibling| that skips nodes that are entirely
 * whitespace or comments.  (Normally |previousSibling| is a property
 * of all DOM nodes that gives the sibling node, the node that is
 * a child of the same parent, that occurs immediately before the
 * reference node.)
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The closest previous sibling to |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function node_before( sib )
{
  while ((sib = sib.previousSibling)) {
    if (!is_ignorable(sib)) return sib;
  }
  return null;
}

/*
 * Version of |nextSibling| that skips nodes that are entirely
 * whitespace or comments.
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The closest next sibling to |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function node_after( sib )
{
  while ((sib = sib.nextSibling)) {
    if (!is_ignorable(sib)) return sib;
  }
  return null;
}

/*
 * Version of |lastChild| that skips nodes that are entirely
 * whitespace or comments.  (Normally |lastChild| is a property
 * of all DOM nodes that gives the last of the nodes contained
 * directly in the reference node.)
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The last child of |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function last_child( par )
{
  var res=par.lastChild;
  while (res) {
    if (!is_ignorable(res)) return res;
    res = res.previousSibling;
  }
  return null;
}

/*
 * Version of |firstChild| that skips nodes that are entirely
 * whitespace and comments.
 *
 * @param sib  The reference node.
 * @return     Either:
 *               1) The first child of |sib| that is not
 *                  ignorable according to |is_ignorable|, or
 *               2) null if no such node exists.
 */
function first_child( par )
{
  var res=par.firstChild;
  while (res) {
    if (!is_ignorable(res)) return res;
    res = res.nextSibling;
  }
  return null;
}

/*
 * Version of |data| that doesn't include whitespace at the beginning
 * and end and normalizes all whitespace to a single space.  (Normally
 * |data| is a property of text nodes that gives the text of the node.)
 *
 * @param txt  The text node whose data should be returned
 * @return     A string giving the contents of the text node with
 *             whitespace collapsed.
 */
function data_of( txt )
{
  var data = txt.textContent;
  // Use ECMA-262 Edition 3 String and RegExp features
  data = data.replace(/[\t\n\r ]+/g, " ");
  if (data.charAt(0) == " ")
    data = data.substring(1, data.length);
  if (data.charAt(data.length - 1) == " ")
    data = data.substring(0, data.length - 1);
  return data;
}

/*End of HTML object iterator functions*/







/*Get our own unique jQuery library instance*/
this.$ = this.jQuery = jQuery.noConflict(true);






/*
Display a notification on the bottom-right of the browser.

@param msg :: string to put between <span></span>
@param duration :: number of milliseconds to display message before it disappears. Default 1000
*/
function showNotification(msg, duration)
{
    var notificationBox = $("#imagefaqs_notificationBox");
    notificationBox.remove();
    
    $("body").append(
        "<div id='imagefaqs_notificationBox'>" +
            "<span style='color: black'>" +
                msg +
            "</span>" +
        "</div>"
    );
    
    notificationBox = $("#imagefaqs_notificationBox");

    notificationBox.css({
        "position": "absolute",
        "top": ($(window).scrollTop() + $(window).height() - notificationBox.height())+"px",
        "left": ($(window).scrollLeft() + $(window).width() - notificationBox.find("span").width())+"px",
        "background": "white",
    });

    if (duration === undefined) 
        duration = 1000;
    
    notificationBox.effect("highlight").delay(duration).fadeOut(500);
}






/*This top portion of the script handles the settings box and local storage*/

var thumbnailImgWidth = 150;
var thumbnailImgHeight = 150;
var thumbnailImgWidthSig = 75;
var thumbnailImgHeightSig = 75;
var settingsJSON = localStorage.getItem("imagefaqs");        
var settings;       /*key-value array of JSON*/
var sessionResizeHotkey;
var sessionHideToggleHotkey;
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;      /*osdep*/

function setSettingsToDefault() {
    
    settings = {
        enable_sigs: true,
        enable_floatingImg: true,
        includeSigWhenExpanding: false,
        hideSigsWhenHideMode: false,
        show_imgURLspan: true,
        show_imgResolutionSpan: true,
        show_imgFilesizeSpan: false,
        show_imgGoogle: true,
        show_imgIqdb: true,
        show_blacklistToggle: true,
        show_imgAllResizeToggles: true,
        show_hideToggle: true,
        show_hideAllToggle: true,
        imgContainerStyle: "sideBySideSig",
        auto_scroll_when_thumbnail_clicked: true,
        thumbnailWidth: thumbnailImgWidth,
        thumbnailHeight: thumbnailImgHeight,
        thumbnailWidthSig: thumbnailImgWidthSig,
        thumbnailHeightSig: thumbnailImgHeightSig,
        expandedWidth: 0,
        expandedHeight: 0,
        imgContainerBackgroundColor: "#DFE6F7",
        isHideMode: false,
        hideToggleHotkey: {115: 115},  /*F4*/
        resizeHotkey: {113: 113},  /*F2*/
        blacklistStr: ""
    };
}

/*if imageFAQs was freshly installed*/
if (settingsJSON === null)
{
    setSettingsToDefault();
    
    localStorage.setItem("imagefaqs", JSON.stringify(settings));    /*save default settings*/
    
    /*gfaqsdep for URL*/
    showNotification("ImageFAQs "+GM_info.script.version+" has successfully been installed.<br/><br/>Settings can be accessed under 'Quick Links' at <a target='_blank' href='http://www.gamefaqs.com/user'>http://www.gamefaqs.com/user</a>", 10000);
}
else 
{
    settings = $.parseJSON(settingsJSON);
    
    if (settings.expandedWidth === undefined)
        settings.expandedWidth = 0;
    
    if (settings.expandedHeight === undefined)
        settings.expandedHeight = 0;
    
    if (settings.show_imgURLspan === undefined)
        settings.show_imgURLspan = true;
    
    if (settings.show_imgResolutionSpan === undefined)
        settings.show_imgResolutionSpan = true;
    
    if (settings.show_imgFilesizeSpan === undefined)
        settings.show_imgFilesizeSpan = true;
    
    if (settings.show_imgGoogle === undefined)
        settings.show_imgGoogle = true;
    
    if (settings.show_imgIqdb === undefined)
        settings.show_imgIqdb = true;
    
    if (settings.show_blacklistToggle === undefined)
        settings.show_blacklistToggle = true;
    
    if (settings.show_imgAllResizeToggles === undefined)
        settings.show_imgAllResizeToggles = true;
    
    if (settings.show_hideToggle === undefined)
        settings.show_hideToggle = true;
    
    if (settings.show_hideAllToggle === undefined)
        settings.show_hideAllToggle = true;
    
    if (settings.isHideMode === undefined)
        settings.isHideMode = false;
    
    if (settings.enable_floatingImg === undefined)
        settings.enable_floatingImg = true;
    
    if (settings.imgContainerStyle === undefined)
        settings.imgContainerStyle = "sideBySideSig";
    
    if (settings.auto_scroll_when_thumbnail_clicked === undefined)
        settings.auto_scroll_when_thumbnail_clicked = true;
    
    if (settings.resizeHotkey === undefined || $.isEmptyObject(settings.resizeHotkey))
        settings.resizeHotkey = {113: 113};
    
    if (settings.hideToggleHotkey === undefined || $.isEmptyObject(settings.hideToggleHotkey))
        settings.hideToggleHotkey = {115: 115};
    
    if (settings.includeSigWhenExpanding === undefined)
        settings.includeSigWhenExpanding = false;
    
    if (settings.hideSigsWhenHideMode === undefined)
        settings.hideSigsWhenHideMode = false;
    
    if (settings.thumbnailWidth === undefined)
        settings.thumbnailWidth = thumbnailImgWidth;
    
    if (settings.thumbnailHeight === undefined)
        settings.thumbnailHeight = thumbnailImgHeight;
    
    if (settings.thumbnailWidthSig === undefined)
        settings.thumbnailWidthSig = thumbnailImgWidthSig;
    
    if (settings.thumbnailHeightSig === undefined)
        settings.thumbnailHeightSig = thumbnailImgHeightSig;
    
    localStorage.setItem("imagefaqs", JSON.stringify(settings));  
}



/*
Convert an ASCII numeric representation of a keyboard character to its full string name

e.g. keyCodeToString(16) === "shift"
*/
function keyCodeToString(keyCode)
{
    keyCode = parseInt(keyCode);
    
    if (keyCode === 16)
    {
        return "shift";
    }
    else if (keyCode === 17)
    {
        return "ctrl";
    }
    else if (keyCode === 18)
    {
        return "alt";
    }
    else if (keyCode >= 112 && keyCode <= 123)       /*F keys*/
    {
        return "F" + (keyCode - 111);
    }
    else
    {
        return String.fromCharCode(keyCode);
    }
}


/*
Convert an array of KV ASCII numeric representation of keyboard characters to its
full string representation

e,g, keyCodeKVArrayToString([{68:68},{77:77}]) === "DM"
*/
function keyCodeKVArrayToString(array)
{
    var string = "";
    
    for (var key in array)
    {
        string += keyCodeToString(key) + " ";
    }
    
    return string;
}


/*
Get a copy of an array of KV's using 1-level deep cloning.
*/
function cloneKVArray(KVArray)
{
    var newKVArray = {};
    
    for (var key in KVArray)
    {
        newKVArray[key] = KVArray[key];
    }
    
    return newKVArray;
}



sessionHideToggleHotkey = cloneKVArray(settings.hideToggleHotkey);
sessionResizeHotkey = cloneKVArray(settings.resizeHotkey);



/*Event where user opens up settings menu*/
$("body").on("click", "#imagefaqs_settings_but", function(event) {

    var popupBox = $("#imagefaqs_settings_popup");
    event.preventDefault();
    
    if (popupBox.length === 0)
    {
        $("body").append(
            "<div id='imagefaqs_settings_popup' title='ImageFAQs Settings. Version "+GM_info.script.version+"'>" +
            
                "Update history: <a target='_blank' href='http://fightinggames.bitbucket.org/imagefaqs/' style='outline: 0'>http://fightinggames.bitbucket.org/imagefaqs/</a>" +
                "<br/>" +
                "<span id='feedback_bugreport_info'>" +
                    "Feedback and bug reporting: <a target='_blank' href='http://www.gamefaqs.com/boards/565885-blood-money'>http://www.gamefaqs.com/boards/565885-blood-money</a>" +
                    "<br/>" +
                "</span>" +
                
                "<fieldset>" +
                    "<legend>Main</legend>" + 
                    "<label><input id='enable_floatingImg' type='checkbox'>Enable floating expanded image upon cursor hover</label>" +
                    "<br/>" +
                    "<label><input id='auto_scroll_when_thumbnail_clicked_checkbox' type='checkbox'>Auto-scroll to top of image after toggling visibility or size</label>" +
                "</fieldset>" +
                
                "<fieldset>" +
                    "<legend>Signature-specific</legend>" + 
                    "<label><input id='enable_sigs_checkbox' type='checkbox'>Embed signature images</label>" +
                    "<br/>" +
                    "<label><input id='includeSigWhenExpanding_checkbox' type='checkbox'>Affect signature images when expanding and contracting all images</label>" +
                    "<br/>" +
                    "<label><input id='hideSigsWhenHideMode_checkbox' type='checkbox'>Affect signature images when toggling hide mode</label>" +
                "</fieldset>" +
                
                "<fieldset>" +
                    "<legend>Image Container Toggles and Information Visibility</legend>" + 
                    "<label><input id='show_ImgURLspan_checkbox' type='checkbox'>Show image URL</label>" +
                    "<br/>" +
                    "<label><input id='show_ImgResolutionSpan_checkbox' type='checkbox'>Show image resolution</label>" +
                    "<br/>" +
                    "<label><input id='show_imgFilesizeSpan_checkbox' type='checkbox'>Show image filesize (Currently slow for Chrome)</label>" +
                    "<br/>" +
                    "<label><input id='show_imgGoogle_checkbox' type='checkbox'>Show google reverse image search button</label>" +
                    "<br/>" +
                    "<label><input id='show_imgIqdb_checkbox' type='checkbox'>Show iqdb reverse image search button</label>" +
                    "<br/>" +
                    "<label><input id='show_blacklistToggle_checkbox' type='checkbox'>Show blacklist toggle button</label>" +
                    "<br/>" +
                    "<label><input id='show_imgAllResizeToggles_checkbox' type='checkbox'>Show all-resize toggle buttons</label>" +
                    "<br/>" +
                    "<label><input id='show_hideAllToggle_checkbox' type='checkbox'>Show all-hide/expose toggle buttons</label>" +
                    "<br/>" +
                    "<label><input id='show_hideToggle_checkbox' type='checkbox'>Show individual hide/expose toggle button</label>" +
                "</fieldset>" +
                
                "<fieldset>" +
                    "<legend>Image Container Style</legend>" + 
                    "<label><input type='radio' name='imgContainerStyle' value='stacked' checked='checked'>Stacked and Verbose</label>" +
                    "<br>" +
                    "<label><input type='radio' name='imgContainerStyle' value='sideBySide'>Side-By-Side and Succinct</label>" +
                    "<br>" +
                    "<label><input type='radio' name='imgContainerStyle' value='sideBySideSig'>Side-By-Side and Succinct (Signatures Only)</label>" +
                "</fieldset>" +
                
                "<label><input id='thumbnailImgWidth_text' type='text'>Thumbnail Max-Width (150 default)</label>" +
                "<br/>" +
                "<label><input id='thumbnailImgHeight_text' type='text'>Thumbnail Max-Height (150 default)</label>" +
                "<br/>" +
                "<label><input id='thumbnailImgWidthSig_text' type='text'>Signature Thumbnail Max-Width (75 default)</label>" +
                "<br/>" +
                "<label><input id='thumbnailImgHeightSig_text' type='text'>Signature Thumbnail Max-Height (75 default)</label>" +
                "<br/>" +
                "<label><input id='expandedWidth_text' type='text'>Expanded max-width (0 default)</label>" +
                "<br/>" +
                "<label><input id='expandedHeight_text' type='text'>Expanded max-height (0 default)</label>" +
                "<br/ style='margin-bottom: 5px'>" +
                "<span>Tip: Use 0 to specify no length restriction.</span>" +
                "<br/><br/>" +
                
                "<input id='imgContainerBackgroundColor_color' type='color' value='#DFE6F7' size=4 ><label>Image container background color (RGB={223,230,247} default)</label>" +
                "<br/ style='margin-bottom: 5px'>" +
                "<span>Tip: Use RGB={0,0,0} for no background color.</span>" +
                "<br/><br/>" +
                
                "<label>Newline separated list of blacklisted image URLs</label>" +
                "<br/>" +
                "<textarea id='blacklist_text'></textarea>" +
                "<br/ style='margin-bottom: 5px'>" +
                "<span>Tip: You can blacklist an entire domain (e.g. pbsrc.com).</span>" +
                "<br/><br/>" +
                
                "<label><input id='resizeHotkey_text' class='hotkeyInput' type='text'>Toggle image size hotkey (F2 default)</label>" +
                "<br/>" +
                "<label><input id='hideToggleHotkey_text' class='hotkeyInput' type='text'>Toggle hide mode hotkey (F4 default)</label>" +
                "<br/ style='margin-bottom: 5px'>" +
                "<span>Tip: You can disable a hotkey with the backspace.</span>" +
                "<br/><br/>" +
                
                "<button id='saveImagefaqsSettingsBut' type='button'>Save</button> " +
                "<button id='cancelImagefaqsSettingsBut' type='button'>Cancel</button> " +
                "<span id='responseSpan'>&nbsp;&nbsp;</span>" +     /*for reporting success or failure*/
                
                "<button id='defaultSettingsBut' type='button' style='float: right'>Reset Settings</button> " +
            "</div>"
        );
        
        popupBox = $("#imagefaqs_settings_popup");
    }

    /*Show user's custom settings*/
    
    popupBox.find("#enable_sigs_checkbox").prop("checked", settings.enable_sigs);
    popupBox.find("#enable_floatingImg").prop("checked", settings.enable_floatingImg);
    
    popupBox.find("#includeSigWhenExpanding_checkbox").prop("checked", settings.includeSigWhenExpanding);
    popupBox.find("#hideSigsWhenHideMode_checkbox").prop("checked", settings.hideSigsWhenHideMode);
    
    popupBox.find("#show_ImgURLspan_checkbox").prop("checked", settings.show_imgURLspan);
    popupBox.find("#show_ImgResolutionSpan_checkbox").prop("checked", settings.show_imgResolutionSpan);
    popupBox.find("#show_imgFilesizeSpan_checkbox").prop("checked", settings.show_imgFilesizeSpan);
    popupBox.find("#show_imgGoogle_checkbox").prop("checked", settings.show_imgGoogle);
    popupBox.find("#show_blacklistToggle_checkbox").prop("checked", settings.show_blacklistToggle);
    popupBox.find("#show_imgIqdb_checkbox").prop("checked", settings.show_imgIqdb);
    popupBox.find("#show_imgAllResizeToggles_checkbox").prop("checked", settings.show_imgAllResizeToggles);
    popupBox.find("#show_hideToggle_checkbox").prop("checked", settings.show_hideToggle);
    popupBox.find("#show_hideAllToggle_checkbox").prop("checked", settings.show_hideAllToggle);
    
    popupBox.find("input[value="+settings.imgContainerStyle+"]").prop("checked", true);
    popupBox.find("#auto_scroll_when_thumbnail_clicked_checkbox").prop("checked", settings.auto_scroll_when_thumbnail_clicked);
    
    popupBox.find("#thumbnailImgWidth_text").val(settings.thumbnailWidth);
    popupBox.find("#thumbnailImgHeight_text").val(settings.thumbnailHeight);
    popupBox.find("#thumbnailImgWidthSig_text").val(settings.thumbnailWidthSig);
    popupBox.find("#thumbnailImgHeightSig_text").val(settings.thumbnailHeightSig);
    popupBox.find("#expandedWidth_text").val(settings.expandedWidth);
    popupBox.find("#expandedHeight_text").val(settings.expandedHeight);
    
    /*"#000000" will be changed to "0" for transparency in the imgContainerBackgroundColor global var*/
    popupBox.find("#imgContainerBackgroundColor_color").val(settings.imgContainerBackgroundColor);
    
    popupBox.find("#resizeHotkey_text").val( keyCodeKVArrayToString(settings.resizeHotkey) );
    popupBox.find("#hideToggleHotkey_text").val( keyCodeKVArrayToString(settings.hideToggleHotkey) );
    popupBox.find("#blacklist_text").val( settings.blacklistStr );
    $("#imagefaqs_settings_popup").children("#responseSpan").html("&nbsp;");
    
    popupBox.dialog({
        width: 630,
        height: 800     /*adds a scrollbar*/
    });
    
    popupBox.find("#blacklist_text").width(popupBox.width());
});




$("body").on("click", "#defaultSettingsBut", function(event) {
    event.preventDefault();
    
    var settingsPopup = $("#imagefaqs_settings_popup");
    
    setSettingsToDefault();
    
    settingsPopup.find("#enable_sigs_checkbox").prop("checked", settings.enable_sigs);
    settingsPopup.find("#enable_floatingImg").prop("checked", settings.enable_floatingImg);
    
    settingsPopup.find("#includeSigWhenExpanding_checkbox").prop("checked", settings.includeSigWhenExpanding);
    settingsPopup.find("#hideSigsWhenHideMode_checkbox").prop("checked", settings.hideSigsWhenHideMode);
    
    settingsPopup.find("#show_ImgURLspan_checkbox").prop("checked", settings.show_imgURLspan);
    settingsPopup.find("#show_ImgResolutionSpan_checkbox").prop("checked", settings.show_imgResolutionSpan);
    settingsPopup.find("#show_imgFilesizeSpan_checkbox").prop("checked", settings.show_imgFilesizeSpan);
    settingsPopup.find("#show_imgGoogle_checkbox").prop("checked", settings.show_imgGoogle);
    settingsPopup.find("#show_blacklistToggle_checkbox").prop("checked", settings.show_blacklistToggle);
    settingsPopup.find("#show_imgIqdb_checkbox").prop("checked", settings.show_imgIqdb);
    settingsPopup.find("#show_imgAllResizeToggles_checkbox").prop("checked", settings.show_imgAllResizeToggles);
    settingsPopup.find("#show_hideToggle_checkbox").prop("checked", settings.show_hideToggle);
    settingsPopup.find("#show_hideAllToggle_checkbox").prop("checked", settings.show_hideAllToggle);
    
    settingsPopup.find("input[value="+settings.imgContainerStyle+"]").prop("checked", true);
    settingsPopup.find("#auto_scroll_when_thumbnail_clicked_checkbox").prop("checked", settings.auto_scroll_when_thumbnail_clicked);
    
    settingsPopup.find("#thumbnailImgWidth_text").val(settings.thumbnailWidth);
    settingsPopup.find("#thumbnailImgHeight_text").val(settings.thumbnailHeight);
    settingsPopup.find("#thumbnailImgWidthSig_text").val(settings.thumbnailWidthSig);
    settingsPopup.find("#thumbnailImgHeightSig_text").val(settings.thumbnailHeightSig);
    settingsPopup.find("#expandedWidth_text").val(settings.expandedWidth);
    settingsPopup.find("#expandedHeight_text").val(settings.expandedHeight);
    
    settingsPopup.find("#imgContainerBackgroundColor_color").val(settings.imgContainerBackgroundColor);
    settingsPopup.find("#resizeHotkey_text").val( keyCodeKVArrayToString(settings.resizeHotkey) );
    settingsPopup.find("#hideToggleHotkey_text").val( keyCodeKVArrayToString(settings.hideToggleHotkey) );
    settingsPopup.find("#blacklist_text").val( settings.blacklistStr );
    $("#imagefaqs_settings_popup").children("#responseSpan").html("&nbsp;");
    
    localStorage.setItem("imagefaqs", JSON.stringify(settings));
    reportResponseMsgInImagefaqsSettingsPopupBox("Default settings saved.", settingsPopup);
});



/*Event where users clicks on the "Save Settings" button*/
$("body").on("click", "#saveImagefaqsSettingsBut", function(event) {

    event.preventDefault();
    
    var settingsPopup = $("#imagefaqs_settings_popup");
   
    /*if valid thumbnail dimensions*/
    if (
        !isNaN($("#thumbnailImgWidth_text").val()) && $("#thumbnailImgWidth_text").val() >= 0 &&
        !isNaN($("#thumbnailImgHeight_text").val()) && $("#thumbnailImgHeight_text").val() >= 0 &&
        !isNaN($("#thumbnailImgWidthSig_text").val()) && $("#thumbnailImgWidthSig_text").val() >= 0 &&
        !isNaN($("#thumbnailImgHeightSig_text").val()) && $("#thumbnailImgHeightSig_text").val() >= 0)
    {
        settings.thumbnailWidth = $("#thumbnailImgWidth_text").val();
        settings.thumbnailHeight = $("#thumbnailImgHeight_text").val();
        settings.thumbnailWidthSig = $("#thumbnailImgWidthSig_text").val();
        settings.thumbnailHeightSig = $("#thumbnailImgHeightSig_text").val();
    }
    else 
    {
        reportResponseMsgInImagefaqsSettingsPopupBox("Error: Invalid thumbnail dimensions. Use non-negative integers only.", settingsPopup);
        return;
    }
    
    /*if valid expanded dimensions*/
    if (
        !isNaN($("#expandedWidth_text").val()) && $("#expandedWidth_text").val() >= 0 &&
        !isNaN($("#expandedHeight_text").val()) && $("#expandedHeight_text").val() >= 0)
    {
        settings.expandedWidth = $("#expandedWidth_text").val();
        settings.expandedHeight = $("#expandedHeight_text").val();
    }
    else 
    {
        reportResponseMsgInImagefaqsSettingsPopupBox("Error: Invalid expanded dimensions. Use non-negative integers only.", settingsPopup);
        return;
    }
    
    /*if valid image container background color*/
    if (settingsPopup.find("#imgContainerBackgroundColor_color").val().search(/^(#[a-zA-Z0-9]{6})|0$/i) >= 0)
    {
        settings.imgContainerBackgroundColor = settingsPopup.find("#imgContainerBackgroundColor_color").val();
    }
    else 
    {
        reportResponseMsgInImagefaqsSettingsPopupBox("Error: Invalid image container background color.", settingsPopup);
        return;
    }
    
    settings.enable_sigs = settingsPopup.find("#enable_sigs_checkbox").prop("checked");
    settings.enable_floatingImg = settingsPopup.find("#enable_floatingImg").prop("checked");
    
    settings.includeSigWhenExpanding = settingsPopup.find("#includeSigWhenExpanding_checkbox").prop("checked");
    settings.hideSigsWhenHideMode = settingsPopup.find("#hideSigsWhenHideMode_checkbox").prop("checked");
    
    settings.show_imgURLspan = settingsPopup.find("#show_ImgURLspan_checkbox").prop("checked");
    settings.show_imgResolutionSpan = settingsPopup.find("#show_ImgResolutionSpan_checkbox").prop("checked");
    settings.show_imgFilesizeSpan = settingsPopup.find("#show_imgFilesizeSpan_checkbox").prop("checked");
    settings.show_imgGoogle = settingsPopup.find("#show_imgGoogle_checkbox").prop("checked");
    settings.show_imgIqdb = settingsPopup.find("#show_imgIqdb_checkbox").prop("checked");
    settings.show_blacklistToggle = settingsPopup.find("#show_blacklistToggle_checkbox").prop("checked");
    settings.show_imgAllResizeToggles = settingsPopup.find("#show_imgAllResizeToggles_checkbox").prop("checked");
    settings.show_hideToggle = settingsPopup.find("#show_hideToggle_checkbox").prop("checked");
    settings.show_hideAllToggle = settingsPopup.find("#show_hideAllToggle_checkbox").prop("checked");
    
    settings.imgContainerStyle = settingsPopup.find("input[name=imgContainerStyle]:checked").val();
    settings.auto_scroll_when_thumbnail_clicked = settingsPopup.find("#auto_scroll_when_thumbnail_clicked_checkbox").prop("checked");
    
    settings.resizeHotkey = cloneKVArray(sessionResizeHotkey);
    settings.hideToggleHotkey = cloneKVArray(sessionHideToggleHotkey);
    settings.blacklistStr = settingsPopup.find("#blacklist_text").val();
    
    localStorage.setItem("imagefaqs", JSON.stringify(settings));
    
    reportResponseMsgInImagefaqsSettingsPopupBox("Settings saved.", settingsPopup);
});



/*
Display a notification in the settings window

@param msg :: message string to show to the user
@param box :: $("#imagefaqs_settings_popup")
*/
function reportResponseMsgInImagefaqsSettingsPopupBox(msg, box)
{
    var msgBox = box.children("#responseSpan");
    
    msgBox.html(msg);
    msgBox.effect("highlight");
}


/*Event when users clicks on the "Cancel" button the settings window.*/
$("body").on("click", "#cancelImagefaqsSettingsBut", function(event) {

    event.preventDefault();
    $("#imagefaqs_settings_popup").dialog("close");
});






/*Begin main scripting*/
(function(){

var isHideMode = settings.isHideMode;
var enable_floatingImg = settings.enable_floatingImg;

var includeSigWhenExpanding = settings.includeSigWhenExpanding;
var hideSigsWhenHideMode = settings.hideSigsWhenHideMode;

var show_imgURLspan = settings.show_imgURLspan;
var show_imgResolutionSpan = settings.show_imgResolutionSpan;
var show_imgFilesizeSpan = settings.show_imgFilesizeSpan;
var show_imgGoogle = settings.show_imgGoogle;
var show_imgIqdb = settings.show_imgIqdb;
var show_blacklistToggle = settings.show_blacklistToggle;
var show_imgResizeToggles = settings.show_imgAllResizeToggles;
var show_hideToggle = settings.show_hideToggle;
var show_hideAllToggle = settings.show_hideAllToggle;

var imgContainerStyle = settings.imgContainerStyle;
var autoScrollWhenThumbnailClicked = settings.auto_scroll_when_thumbnail_clicked;

var thumbnailImgWidth = settings.thumbnailWidth;
var thumbnailImgHeight = settings.thumbnailHeight;
var thumbnailImgWidthSig = settings.thumbnailWidthSig;
var thumbnailImgHeightSig = settings.thumbnailHeightSig;
var expandedImgWidth = settings.expandedWidth;
var expandedImgHeight = settings.expandedHeight;

var imgContainerBackgroundColor = settings.imgContainerBackgroundColor;
if (imgContainerBackgroundColor === "#000000") {
    imgContainerBackgroundColor = 0;
}

var blacklist = settings.blacklistStr.split("\n");    /*array of URLs to block*/
var currentURL;
var pageType;       /* "topic" or "postPreview" or "other" */
var allowImgInSig = settings.enable_sigs;
var floatingImgWidth;
var floatingImgRightOffset = 50;
var floatingImgBorder = 10;
var currentHoveredThumbnail = null;
var imgAnchorTags = [];

var expandedImgWidth_css = expandedImgWidth == 0 ? "" : expandedImgWidth+"px";
var expandedImgHeight_css = expandedImgHeight == 0 ? "" : expandedImgHeight+"px";


var heldDownKeys = {};
$("body").on("keydown", "#imagefaqs_settings_popup #hideToggleHotkey_text", function(event){
   
    heldDownKeys[event.which] = event.which;
    sessionHideToggleHotkey = cloneKVArray(heldDownKeys);
    
    $(this).val(
        keyCodeKVArrayToString(sessionHideToggleHotkey)
    );

    return false;
});

$("body").on("keydown", "#imagefaqs_settings_popup #resizeHotkey_text", function(event){
   
    heldDownKeys[event.which] = event.which;
    sessionResizeHotkey = cloneKVArray(heldDownKeys);
    
    $(this).val(
        keyCodeKVArrayToString(sessionResizeHotkey)
    );

    return false;
});


$("body").on("keyup", "#imagefaqs_settings_popup .hotkeyInput", function(event){
    delete heldDownKeys[event.which];
    return false;
});

$("body").on("keypress", "#imagefaqs_settings_popup .hotkeyInput", function(event){
    event.preventDefault();
});



/*
Toggle between "display" and "hide" images.
*/
function toggleImageVisiblity(embeddedImgContainers, via)
{
    if (via === "hotkey")
        isHideMode = !isHideMode;

    /*If set images to be hidden...*/
    if ((via === "hotkey" && isHideMode) ||
        via === "closeAnchor")
    {
        if (pageType !== "other")
        {
            embeddedImgContainers.each(function(index, element) {
                if ($(this).hasClass("isHidable") && !$(this).hasClass("hidden")) {
                    hideMedia($(this), false);
                }
            });

            if (via === "hotkey")
                showNotification("ImageFAQs: All images hidden.");
        }
        else 
        {
            if (via === "hotkey")
                showNotification("ImageFAQs: Images will be hidden.");
        }
    }
    else 
    {
        if (pageType !== "other")
        {
            embeddedImgContainers.each(function(index, element) {
                if ($(this).hasClass("hidden")) {
                    showMedia($(this), false);
                }
            });
            
            if (via === "hotkey")
                showNotification("ImageFAQs: All images exposed.");
        }
        else 
        {
            if (via === "hotkey")
                showNotification("ImageFAQs: Images will be exposed.");
        }
    }
    
    settings.isHideMode = isHideMode;
    localStorage.setItem("imagefaqs", JSON.stringify(settings));
}





var nextImageSize = "expanded";
$("body").keydown(function(event){

    var key;
    var numMatchingPressedHotkeys;
    var desiredAction = "";
    heldDownKeys[event.which] = event.which;

    
    /*if backspace, ignore*/
    if (heldDownKeys[8] === 8)
    {
        return;
    }
    

    /*are every hide mode hotkey pressed?*/
    numMatchingPressedHotkeys = 0;
    for (key in settings.hideToggleHotkey)
    {
        if (settings.hideToggleHotkey[key] !== heldDownKeys[key])
        {
            break;
        }
        
        numMatchingPressedHotkeys++;
    }
    if (numMatchingPressedHotkeys === Object.size(settings.hideToggleHotkey) && numMatchingPressedHotkeys > 0)
    {
        desiredAction = "toggleHideMode";
    }
    
    
    

    /*is every resize hotkey pressed?*/
    if (desiredAction === "")
    {
        numMatchingPressedHotkeys = 0;
        for (key in settings.resizeHotkey)
        {
            if (settings.resizeHotkey[key] !== heldDownKeys[key])
            {
                break;
            }
            numMatchingPressedHotkeys++;
        }
        if (numMatchingPressedHotkeys === Object.size(settings.resizeHotkey) && numMatchingPressedHotkeys > 0)
        {
            desiredAction = "toggleImageResize";
        }
    }
    
    
    
    if (desiredAction === "toggleHideMode")
    {
        toggleImageVisiblity($(".embeddedImgContainer"), "hotkey");
    }
    else if (desiredAction === "toggleImageResize")
    {
        if (nextImageSize === "expanded")
        {
            toggleSizesOfImages($(".embeddedImg"), true);
            nextImageSize = "thumbnail";
            showNotification("ImageFAQs: Expanded all images.");
        }
        else 
        {
            toggleSizesOfImages($(".embeddedImg.expandedImg"), false);
            nextImageSize = "expanded";
            showNotification("ImageFAQs: Shrunk all images.");
        }
    }
});




$("body").keyup(function(event){
    delete heldDownKeys[event.which];
});







if (blacklist.length === 1 && blacklist[0] === "")
{
    blacklist = [];
}
else 
{
    /*trim white space*/
    for (var i = 0; i < blacklist.length; i++)
    {
        blacklist[i].trim();
    }
}







function isURLmatchBlacklistedURL(url, blacklistedURL)
{
    blacklistedURL = blacklistedURL.trim();
    
    /*escape everything*/
    var blacklistedURLregex = 
        new RegExp( blacklistedURL.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") );

    if (blacklistedURLregex.exec(url) !== null)
    {
        return true;
    }
    else
    {
        return false;
    }
}


/*
Is the url string in the blacklist?

@url :: string of the url to check 
@blacklist :: array of blacklisted urls

Returns true or false
*/
function isURLinBlacklist(url, blacklist)
{
    for (var i = 0; i < blacklist.length; i++)
    {
        if (isURLmatchBlacklistedURL(url, blacklist[i]))
        {
            return true;
        }
    }
    
    return false;
}




$(window).scroll(function() {
    
    var notificationBoxes = $("body").children("#imagefaqs_notificationBox");
    
    notificationBoxes.each(function(index, element) {
        $(this).css({
            "top": ($(window).scrollTop() + $(window).height() - $(this).height())+"px",
            "left": ($(window).scrollLeft() + $(window).width() - $(this).find("span").width())+"px"
        });
    });
});





currentURL = window.location.href;
pageType = currentURL.search(/.*gamefaqs\.com\/boards\/.*\/.*/i);               /*gfaqsdep*/
if (currentURL.search(/.*gamefaqs\.com\/boards\/.*\/.*/i) >= 0)                 /*gfaqsdep*/
{
    pageType = "topic";
}
else if (currentURL.search(/.*gamefaqs\.com\/boards\/post/i) >= 0)              /*gfaqsdep*/
{
    pageType = "postPreview";
}
else if (currentURL.search(/.*gamefaqs\.com\/user[^\/]*$/i) >= 0)               /*gfaqsdep*/
{
    /*add settings link*/  /*gfaqsdep*/
    $("div.body tbody:eq(2)").append("<tr><td colspan='2'><a id='imagefaqs_settings_but' href='#'>ImageFAQs Options</a> - Change thumbnail size, enable signature embedding, and more.</td></tr>");
}
else 
{
    pageType = "other";
}




if (pageType === "other")
{
    return;
}



GM_addStyle (GM_getResourceText("jqueryuibaseCSS"));
GM_addStyle (GM_getResourceText("jqueryuithemeCSS"));





GM_addStyle (
    ".embeddedImgContainer {" +
        "background: "+imgContainerBackgroundColor+";" +
    "}" +
    ".embeddedImgAnchor {"+
        "display: inline-block;"+
    "}" +
    ".thumbnailImg {"+
        "display: inline-block;"+  /*prevents parent anchor from stretching horizontally*/
        "vertical-align: bottom;"+ /*eliminates small gap between bottom of image and parent div*/
    "}" +
    ".expandedImg {" +
        "display: inline-block;" +
        "vertical-align: bottom;" +
    "}" +
    ".imgMenuButton {" +
        "overflow: hidden;" +
        "position: absolute;" +
        "text-align: center;" +
        "z-index: 90;" +
        "background-color: #99FFCC;" +
        "opacity: 0.5;" +
        "pointer-events: none;" +
    "}" +
    ".imgMenuButton_symbol {" +
        "display: table-cell;" +
        "vertical-align: middle;" +
    "}" +
    ".imgMenuItem {" +
        "display: block;" +
    "}" +
    ".imgMenuItemAnchor {" +
        "display: block;" +
    "}" +
    ".imgMenu {" +
        "background-color: #CCFFFF;" +
        "opacity: 0.9;" +
        "border-style: solid;" +
        "border-width: 1px;" +
    "}" +
    ".ui-widget { " +       /*shrink font size in the settings menu*/
        "font-size:96%;" +
    "}" +
    "#imagefaqs_settings_popup input { " +
        "margin-right: 5px;" +
    "}" +
    "#imagefaqs_settings_popup a { " +
        "color: blue;" +
    "}"
);





$("body").css("position", "relative");
var posts = null;

posts = $("div.msg_body");                  /*gfaqsdep*/




/*for each user post*/
posts.each(function(index, element) {

    var postHtml;
    var unanchoredImgURLMatches;
    var sigStrIdx;
    var anchorTags;
    var idxAfterAnchorTagInPostHtml = 0;
    
    postHtml = $(this).html();
    
    /*if in post preview mode, need to manually parse through the preview message body and 
    replace every plain-text image URL in its anchor form*/
    if (pageType === "postPreview")
    {
        postHtml = postHtml.replace(/https?:\/\/[^<>\s]*?\.(?:png|jpg|gif|jpeg|webm|gifv)[^<>\s]*/ig, "<a href='$&'>$&</a>");
        
        $(this).html(postHtml);
    }
    
    /*get all anchor tags*/
    anchorTags = $(this).find("a");

    /*filter in anchor tags that refer to images*/
    anchorTags.each(function(index, element) {
        
        var anchorURL = $(this).attr("href");
        var anchorTagStrIdx = postHtml.indexOf(anchorURL + "</a>", idxAfterAnchorTagInPostHtml);
        idxAfterAnchorTagInPostHtml = anchorTagStrIdx + anchorURL.length + 4;
        
        if (anchorURL.search(/https?:\/\/[^<>\s]*?\.(?:png|jpg|gif|jpeg|webm|gifv)/i) >= 0)
        {
            /*if anchor is within of sig*/                  
            if ($(this).parent().hasClass("sig_text"))  /*gfaqsdep*/
            {
                if (allowImgInSig)
                    $(this).addClass("withinSig");
                else
                    return;
            }
            
            $(this).addClass("imgAnchor");
            imgAnchorTags.push($(this));
        }
    });
});





var imgAnchorIdx = 0;

/*for each valid image URL anchor tag, replace with template div for embedded image*/
for (var imgAnchor of imgAnchorTags)
{
    var imgURL = imgAnchor.html();
    var imageType = imgURL.split(".").pop();
    var imgWithinSig_class = imgAnchor.hasClass("withinSig") ? "withinSig" : "";
    var imgIsHidable_class = allowImgInSig && imgAnchor.hasClass("withinSig") && !hideSigsWhenHideMode ? "" : "isHidable";
    var imgInitiallyBlacklisted_class = "";
    var imgSpoilersTagged_class = imgAnchor.closest("s").length > 0 ? "spoilersTagged" : "";
    var imgSize;
    var imgInfoEleStr;
    var postID;
    var isBlacklisted;
    var imgContainerStyle_attr;
    
    isBlacklisted = isURLinBlacklist(imgURL, blacklist);
    if (isBlacklisted)
        imgInitiallyBlacklisted_class = "initiallyBlacklisted";
    
    imgContainerStyle_attr = imgContainerStyle;
    if (imgContainerStyle_attr === "sideBySideSig") 
    {
        if (imgWithinSig_class === "withinSig")
            imgContainerStyle_attr = "sideBySide";
        else
            imgContainerStyle_attr = "stacked";
    }
    
    if (imageType === "gifv")
        imgURL = imgURL.replace(/gifv$/i, "webm");

    if (pageType === "topic")
    {
        postID = imgAnchor.closest(".msg_body_box").siblings(".msg_infobox").children("a").attr("name");           /*gfaqsdep*/
    }
    else    /*if in post preview mode, need to provide missing message ID*/ 
    {
        imgAnchor.closest("td").addClass("msg_body");                   /*gfaqsdep*/
        imgAnchor.closest(".msg_body").attr("name", 0);                 /*gfaqsdep*/
        postID = 0;
    }
    
    var imgURLspan = "";
    var imgResolutionSpan = "";
    var imgFilesizeSpan = "";
    var imgGoogleReverse = "";
    var imgIQDBreverse = "";
    var imgBlacklistToggle = "";
    var imgCloseAll = "";
    var imgClosePost = "";
    var imgExpandPost = "";
    var imgExpandAll = "";
    var imgHideToggle = "";
    var imgHideAllToggles = "";
    
    if (imgContainerStyle_attr === "stacked")
    {
        if (show_imgURLspan)
        {
            imgURLspan = 
                "<span style='margin-right: 5px'>" +
                    "<a target='_blank' href="+imgURL+">"+imgURL+"</a>" +
                "</span>";
        }
            
        if (show_imgResolutionSpan)
        {
            imgResolutionSpan = 
                "<span class='imgResolution' style='margin-right: 5px'>" +
                "</span>";
        }
        
        if (show_imgFilesizeSpan)
        {
            imgFilesizeSpan = 
                "<span class='imgFilesize' style='margin-right: 5px'>" +
                "</span>";
        }
        
        if (show_imgGoogle)
        {
            imgGoogleReverse = 
                "<a target='_blank' title='Reverse image search on general images' style='margin-right: 5px' href='https://www.google.com/searchbyimage?image_url="+imgURL+"'>" +
                    "google" +
                "</a>";
        }

        if (show_imgIqdb)
        {
            imgIQDBreverse = 
                "<a target='_blank' title='Reverse image search on weeb images' style='margin-right: 5px' href='http://iqdb.org/?url="+imgURL+"'>" +
                    "iqdb" +
                "</a>";
        }
            
        if (show_blacklistToggle)
        {
            if (isBlacklisted)
            {
                imgBlacklistToggle =
                    "<a class='imgBlacklistToggle' href='#' title='Whitelist image' style='margin-right: 5px'>whitelist</a>"; 
            }
            else 
            {
                imgBlacklistToggle =
                    "<a class='imgBlacklistToggle' href='#' title='Blacklist image' style='margin-right: 5px'>blacklist</a>"; 
            }
        }
        
        if (show_imgResizeToggles)
        {
            imgCloseAll =
                "<a class='imgCloseAll' href='#' title='Close all images in page' style='margin-right: 5px'>&lt;&lt;</a>";
            
            imgClosePost =
                "<a class='imgClosePost' href='#' data-postID='"+postID+"' title='Close all images in post' style='margin-right: 5px'>&lt;</a>";
            
            imgExpandPost = 
                "<a class='imgExpandPost' href='#' data-postID='"+postID+"' title='Expand all images in post' style='margin-right: 5px'>&gt;</a>";
            
            imgExpandAll =
                "<a class='imgExpandAll' href='#' title='Expand all images in page' style='margin-right: 5px'>&gt;&gt;</a>";
        }

        if (show_hideAllToggle)
        {
            imgHideAllToggles = 
                "<a class='imgHideAll' href='#' title='Hide all images in page' style='margin-right: 5px'>--</a>" +
                "<a class='imgHidePost' href='#' data-postID='"+postID+"' title='Hide all images in post' style='margin-right: 5px'>-</a>" +
                "<a class='imgShowPost' href='#' data-postID='"+postID+"' title='Show all images in post' style='margin-right: 5px'>+</a>" +
                "<a class='imgShowAll' href='#' title='Show all images in page' style='margin-right: 5px'>++</a>";
        }
        
        if (show_hideToggle)
        {
            if (isBlacklisted || imgSpoilersTagged_class === "spoilersTagged" || (isHideMode &&  imgIsHidable_class))
            {
                imgHideToggle = 
                    "<a class='imgHideToggle' href='#' title='Show image' style='margin-right: 5px'>show</a>";
            }
            else 
            {
                imgHideToggle = 
                    "<a class='imgHideToggle' href='#' title='Hide image' style='margin-right: 5px'>hide</a>";
            }
        }
    }
     
    var optionalBreakAfterImgHeader;
    if ((!show_imgURLspan && !show_imgResolutionSpan && !show_imgFilesizeSpan && !show_imgGoogle && !show_imgIqdb && !show_blacklistToggle && !show_imgResizeToggles && !show_hideToggle && !show_hideAllToggle) 
            || 
        imgContainerStyle_attr === "sideBySide")
    {
        optionalBreakAfterImgHeader = "";
    }
    else 
    {
        optionalBreakAfterImgHeader = "<br/>";
    }
    
    imgAnchor.replaceWith(
        "<div class='embeddedImgContainer "+imgWithinSig_class+" "+imgIsHidable_class+" "+imgInitiallyBlacklisted_class+" "+imgSpoilersTagged_class+"' data-postID='"+postID+"' data-style='"+imgContainerStyle_attr+"'>" +
            imgURLspan +
            imgResolutionSpan +
            imgFilesizeSpan +
            imgGoogleReverse +
            imgIQDBreverse +
            imgBlacklistToggle +
            imgCloseAll + 
            imgClosePost + 
            imgExpandPost +
            imgExpandAll +
            imgHideAllToggles +
            imgHideToggle +
            optionalBreakAfterImgHeader +
            "<a class='embeddedImgAnchor' href='" + imgURL + "' data-backup-href='" + imgURL + "' data-idx='"+imgAnchorIdx+"'>" +
            "</a>" +
        "</div>"
    );
    
    var embeddedImgAnchor = $(".embeddedImgAnchor[data-idx='"+imgAnchorIdx+"']");
    var embeddedImgContainer = embeddedImgAnchor.parent();
    
    imgAnchorIdx++;

    /*keep iterating through the next sibling elements until find an element that's 
    not whitespace*/
    var curNextEleJS = embeddedImgContainer[0].nextSibling;
    while (curNextEleJS !== null &&
           ($(curNextEleJS).is("br") || is_ignorable(curNextEleJS)))
    {
        curNextEleJS = curNextEleJS.nextSibling;
    }
    
    /*now do the same thing, but iterating through the previous siblings*/
    var curPrevEleJS = embeddedImgContainer[0].previousSibling;
    while (curPrevEleJS !== null &&
           is_ignorable(curPrevEleJS))
    {
        curPrevEleJS = curPrevEleJS.previousSibling;
    }
    
    /*remove the next br elements if next non-whitespace sibling is a going-to-be image*/
    
    var curNextEle;
    if (curNextEleJS !== null && $(curNextEleJS).hasClass("imgAnchor"))
    {
        curNextEle = embeddedImgContainer.next();
        while (curNextEle.length !== 0 && curNextEle.is("br"))
        {
            if (curNextEle.next().length === 0)
            {
                curNextEle.remove();
                break;
            }
            else 
            {
                curNextEle = curNextEle.next();
                curNextEle.prev().remove();
            }
        }
    }
    /*if sig separator after image, remove <br> in between*/
    else if (curNextEleJS !== null && curNextEleJS.nodeType === 3 && curNextEleJS.nodeValue === "---")
    {
        curNextEle = embeddedImgContainer.next();
        if (curNextEle.is("br"))
            curNextEle.remove();
    }
    /*if text after image*/
    else if (curNextEleJS !== null && curNextEleJS.nodeType === 3 && curNextEleJS.nodeValue !== "---")
    {
        curNextEle = embeddedImgContainer.next();
        if (curNextEle.is("br"))
            curNextEle.remove();
    }
    
    if (imgContainerStyle_attr === "sideBySide")
    {
        /*if the next non-whitespace sibling not going to be an image, create a newline to
        set the cursor below this image*/
        if (curNextEleJS !== null && !$(curNextEleJS).hasClass("imgAnchor"))
        {
            $(curNextEleJS).before(
                "<div style='display: block;'></div>"
            );
        }
        
        /*do same with previous non-whitespace sibling*/
        if (curPrevEleJS !== null && !$(curPrevEleJS).hasClass("embeddedImgContainer"))
        {
            $(curPrevEleJS).after(
                "<div style='display: block;'></div>"
            );
        }
       
        /*set container to float*/
        embeddedImgContainer.css("display", "inline-block");
        embeddedImgContainer.css("vertical-align", "top");
        embeddedImgContainer.css("margin-right", "5px");
        embeddedImgContainer.css("margin-bottom", "5px");
    }
    else 
    {
        embeddedImgContainer.css("margin-bottom", "10px");
    }
}



function getFileSize(url, span)
{
    GM_xmlhttpRequest({
        method: "GET",
        url: url,
        onload: function(response) {
            
            var contentLengthStr = response.responseHeaders.match(/Content-Length: \d+/)[0];
            var fileSizeBytes = parseInt(contentLengthStr.substring(16));
            
            var fileSizeDisplayStr;
            
            if (fileSizeBytes < 1000000)    /*if less than 1.0MB*/
            {
                fileSizeDisplayStr = Math.round(fileSizeBytes / 1000) + "KB";
            }
            else
            {
                fileSizeDisplayStr = (fileSizeBytes / 1000000).toFixed(2) + "MB";
            }

            span.html("("+fileSizeDisplayStr+")");
        }
    });
}



function showMedia(mediaContainer, isToWhitelist)
{
    var mediaAnchor = mediaContainer.children(".embeddedImgAnchor");
    var mediaURL = mediaAnchor.attr("href");
    var mediaContainerStyle = mediaContainer.attr("data-style");
    
    if (!mediaContainer.hasClass("loaded"))
        loadMedia(mediaContainer);
    
    mediaContainer.removeClass("hidden");
    
    /*remove url from blacklist*/        
    var urlIdx = blacklist.indexOf(mediaURL);
    if (urlIdx > -1)
    {
        blacklist.splice(urlIdx, 1);
    }
    
    if (isToWhitelist)
    {
        mediaAnchor.removeClass("blacklisted");
        
        if (mediaContainerStyle === "stacked" && show_blacklistToggle)
        {
            mediaAnchor.siblings(".imgBlacklistToggle").html("blacklist");
            mediaAnchor.siblings(".imgBlacklistToggle").attr("title", "Blacklist image");
        }
    }
    
    mediaAnchor.show();
    
    if (mediaContainerStyle === "sideBySide")
    {
        mediaAnchor.siblings("a.imgMenuItem").remove();
        mediaAnchor.siblings("div.imgMenuItem").remove();
        
        mediaAnchor.attr("style", "");
        mediaAnchor.parent().css("max-width", "");
    }
    else 
    {
        if (show_hideToggle)
        {
            var imgHideToggle = mediaAnchor.siblings(".imgHideToggle");
            
            imgHideToggle.html("hide");
            imgHideToggle.attr("title", "Hide image");
        }
    }
    
    settings.blacklistStr = blacklist.join("\n");
    localStorage.setItem("imagefaqs", JSON.stringify(settings));
}



function hideMedia(mediaContainer, isToBlacklist)
{
    var mediaAnchor = mediaContainer.children(".embeddedImgAnchor");
    var media = mediaAnchor.children(".embeddedImg");
    var mediaURL = mediaAnchor.attr("href");
    var postID = mediaContainer.attr("data-postID");
    var mediaContainerStyle = mediaContainer.attr("data-style");
    var isSig = mediaContainer.hasClass("withinSig");
    var mediaThumbnailImgWidth = isSig ? thumbnailImgWidthSig : thumbnailImgWidth;
    var mediaThumbnailImgHeight = isSig ? thumbnailImgHeightSig : thumbnailImgHeight;
    var mediaThumbnailImgWidth_css = mediaThumbnailImgWidth == 0 ? "" : mediaThumbnailImgWidth+"px";
    var mediaThumbnailImgHeight_css = mediaThumbnailImgHeight == 0 ? "" : mediaThumbnailImgHeight+"px";
    
    /*shrink image*/
    if (media.hasClass("expandedImg"))
        toggleSizesOfImages(media, false);
    
    mediaContainer.addClass("hidden");
    mediaAnchor.hide();
    
    if (isToBlacklist)
    {
        mediaAnchor.addClass("blacklisted");
        
        if (blacklist.indexOf(mediaURL) === -1)
            blacklist.push(mediaURL);
    }
    
    if (mediaContainerStyle === "sideBySide")
    {
        mediaContainer.css("max-width", mediaThumbnailImgWidth_css);
        
        mediaContainer.append("<a target='_blank' class='imgMenuItem' href="+mediaURL+">"+mediaURL+"</a>");
        
        if (mediaAnchor.hasClass("blacklisted"))
        {
            if (show_blacklistToggle) 
            {
                mediaContainer.append(
                    "<div class='imgMenuItem'><a class='imgBlacklistToggle' href='#' title='Whitelist image'>whitelist</a></div>"
                );
            }
        }
        
        if (show_hideAllToggle)
        {
            mediaContainer.append(
                "<div class='imgMenuItem'>" +
                    "<a class='imgHideAll' href='#' title='Hide all images in page' style='margin-right: 5px'>--</a>" +
                    "<a class='imgHidePost' href='#' data-postID='"+postID+"' title='Hide all images in post' style='margin-right: 5px'>-</a>" +
                    "<a class='imgShowPost' href='#' data-postID='"+postID+"' title='Show all images in post' style='margin-right: 5px'>+</a>" +
                    "<a class='imgShowAll' href='#' title='Show all images in page' style='margin-right: 5px'>++</a>" +
                "</div>"
            );
        }
        
        if (show_hideToggle)
        {
            mediaContainer.append(
                "<div class='imgMenuItem'><a class='imgHideToggle' href='#' title='Show image'>show</a></div>"
            );
        }

        hideImgMenu();
    }
    else 
    {
        if (show_blacklistToggle && isToBlacklist) 
        {
            mediaAnchor.siblings(".imgBlacklistToggle").html("whitelist");
            mediaAnchor.siblings(".imgBlacklistToggle").attr("title", "Whitelist image");
        }
    }
    
    if (mediaContainerStyle === "sideBySide")
    {
        
    }
    else
    {
        if (show_hideToggle)
        {
            var imgHideToggle = mediaAnchor.siblings(".imgHideToggle");
            
            imgHideToggle.html("show");
            imgHideToggle.attr("title", "Show image");
        }
    }
    
    settings.blacklistStr = blacklist.join("\n");
    localStorage.setItem("imagefaqs", JSON.stringify(settings));
}





function loadMedia(mediaContainer)
{
    var mediaAnchor = mediaContainer.children(".embeddedImgAnchor");
    var mediaResolutionSpan = mediaContainer.children(".imgResolution");
    var imgFilesize = mediaContainer.children(".imgFilesize");
    var mediaURL = mediaAnchor.attr("href");
    var postID = mediaContainer.attr("data-postID");
    var mediaIdx = mediaContainer.attr("data-idx");
    var isSig = mediaContainer.hasClass("withinSig");
    var mediaThumbnailImgWidth = isSig ? thumbnailImgWidthSig : thumbnailImgWidth;
    var mediaThumbnailImgHeight = isSig ? thumbnailImgHeightSig : thumbnailImgHeight;
    var mediaThumbnailImgWidth_css = mediaThumbnailImgWidth == 0 ? "" : mediaThumbnailImgWidth+"px";
    var mediaThumbnailImgHeight_css = mediaThumbnailImgHeight == 0 ? "" : mediaThumbnailImgHeight+"px";
    
    mediaContainer.addClass("loaded");
    
    if (imgFilesize.length > 0)
        getFileSize(mediaURL, imgFilesize);
    
    var mediaType = mediaURL.split(".").pop();  
    if (mediaType.search(/(webm)/i) == -1)      /*if image, and not a video*/
    {
        var image = new Image();
        
        /*on event that image cannot be loaded, post the error*/
        image.onerror = function() {
            mediaAnchor.html("Image cannot be loaded.");
        };
        
        /*on event that image loaded successfully in memory*/
        $(image).load(function() {
            /*write down image's natural dimensions*/
            
            if (mediaResolutionSpan.length > 0)
            {
                mediaResolutionSpan.html(
                    "(" + image.naturalWidth + "x" + image.naturalHeight + ")"
                );
            }
        });
          
        image.src = mediaURL;
        
        $(image).addClass("embeddedImg thumbnailImg");
        $(image).attr("data-postID", postID);
        $(image).attr("alt", "");
        $(image).attr("display", "none");
        
        mediaAnchor.html(image);
        
        $(image).css("max-width",  getOptimalImgMaxWidth($(image), mediaThumbnailImgWidth) + "px");
        $(image).css("max-height", mediaThumbnailImgHeight_css); 
        
        $(image).attr("display", "");
    }
    else
    {
        var htmlVideoSrcTag =
            "<video id='embeddedImg_"+mediaIdx+"' data-postID='"+postID+"' " +
            "class='embeddedImg webmExt thumbnailImg' " +
            "style=''>" +
                "<source src='" + mediaURL + "' type='video/webm'>" +
            "</video>"; 
          
        mediaAnchor.html(htmlVideoSrcTag);
        
        var video = $("#embeddedImg_"+mediaIdx);

        video.css("max-width",  getOptimalImgMaxWidth(video, mediaThumbnailImgWidth) + "px");
        video.css("max-height", mediaThumbnailImgHeight_css); 
        
        video.attr("display", "");

        /*when video's metadata has been loaded, record its natural width and resolution*/
        $("#embeddedImg_"+mediaIdx+"")[0].onloadedmetadata = function() {
            
            var video = this;
            
            if (mediaResolutionSpan.length > 0)
            {
                mediaResolutionSpan.html(
                    "(" + video.videoWidth + "x" + video.videoHeight + ")"
                );
            }
        };
        
        $("#embeddedImg_"+mediaIdx+"")[0].addEventListener('error', function(event) {
            mediaAnchor.html("Video cannot be loaded.");
        }, true);
    }
    
    if (mediaContainer.hasClass("withinSig"))
        mediaContainer.find(".embeddedImg").addClass("withinSig");
}


/*for each template div, insert an embedded image*/
$(".embeddedImgContainer").each(function(index, element) {
    
    var curEmbeddedImgContainer = $(this);
    curEmbeddedImgContainer.attr("data-idx", index);
    
    if (isHideMode)
    {
        if (curEmbeddedImgContainer.hasClass("isHidable"))
            hideMedia(curEmbeddedImgContainer, false);
        else 
            loadMedia(curEmbeddedImgContainer, false);
    }
    else
    {
        var isBlacklisted = curEmbeddedImgContainer.hasClass("initiallyBlacklisted");
        var isSpoilersTagged = curEmbeddedImgContainer.hasClass("spoilersTagged");
        
        if (isBlacklisted)
            hideMedia(curEmbeddedImgContainer, true);
        else if (isSpoilersTagged)
            hideMedia(curEmbeddedImgContainer, false);
        else
            loadMedia(curEmbeddedImgContainer, false);
    }
});


/*
Get the natural width of an embedded image.

@image :: jQuery object with the class "embeddedImg"
*/
function getNatWidthOfEmbeddedImg(image)
{
    if (image.hasClass("webmExt"))
    {
        return image[0].videoWidth;
    }
    else 
    {
        return image[0].naturalWidth;
    }
}



/*
Get the natural width of an embedded image.

@image :: jQuery object with the class "embeddedImg"
*/
function getNatHeightOfEmbeddedImg(image)
{
    if (image.hasClass("webmExt"))
    {
        return image[0].videoHeight;
    }
    else 
    {
        return image[0].naturalHeight;
    }
}





$("body").append(
    "<div class='imgMenuButton' style='display: none'>" +
        "<div class='imgMenuButton_symbol'>" +
            "+" +
        "</div>" +
    "</div>"
);
var imgMenuButton = $("body div.imgMenuButton");


/*
Show a transparent button in the top-right corner of a thumbnail image.

@param thumbnail :: embedded thumbnail image
@param isShow :: true if the button should appear
*/
function showImgMenuButton(thumbnail, isShow)
{   
    if (!show_imgURLspan && !show_imgResolutionSpan && !show_imgFilesizeSpan && !show_imgGoogle && !show_imgIqdb &&
        !show_blacklistToggle && !show_imgResizeToggles) 
    {
        return;
    }

    if (isShow)
    {
        if (imgMenu !== null && 
            thumbnail.parent().attr("data-idx") === imgMenu.attr("data-idx"))
        {
            imgMenuButton.children().html("-");
        }
        else 
        {
            imgMenuButton.children().html("+");
        }
        
        imgMenuButton.css("display", "table");
        imgMenuButton.css("left", (thumbnail.offset().left + thumbnail.width() - 18) + "px");
        imgMenuButton.css("top", thumbnail.offset().top - 1 + "px");
        imgMenuButton.css("width", imgMenuButton.height());
    }
    else 
    {
        imgMenuButton.css("display", "none");
    }
}

function isHoverOverImgMenuButton(clickEvent)
{
    if (!show_imgURLspan && !show_imgResolutionSpan && !show_imgFilesizeSpan && !show_imgGoogle && !show_imgIqdb &&
        !show_blacklistToggle && !show_imgResizeToggles) 
    {
        return false;
    }
    
   var isCursorInButton =
        imgMenuButton.css("display") === "table" &&
        clickEvent.pageX > imgMenuButton.offset().left &&
        clickEvent.pageX < imgMenuButton.offset().left + imgMenuButton.width() &&
        clickEvent.pageY > imgMenuButton.offset().top &&
        clickEvent.pageY < imgMenuButton.offset().top + imgMenuButton.height();
    
   return isCursorInButton;
}







var imgMenu = null;
function showImgMenu(image)
{
    var imgURL = image.parent().attr("data-backup-href");
    
    var imgURL_menuItem = "";
    
    var imgResolution_span = "";
    var imgFilesize_span = "";
    var imgResolutionAndFilesize_menuItem = "";
    
    var imgGoogleReverse_menuItem = "";
    var imgIQDBreverse_menuItem = "";
    var imgBlacklistToggle_menuItem = "";
    var imgResizeToggles_menuItem = "";
    var imgHideToggle_menuItem = "";
    var imgHideAllToggle_menuItem = "";
    
    var postID = image.attr("data-postID");
    
   if (show_imgURLspan)
    {
        imgURL_menuItem = 
            "<div class='imgMenuItem'><span>" +
                "<a target='_blank' class='imgMenuItemAnchor_url' href="+imgURL+">"+imgURL+"</a>" +
            "</span></div>";
    }
        
    if (show_imgResolutionSpan)
    {
        imgResolution_span = 
            "<span class='imgResolution' style='margin-right: 5px'>" +
            "</span>";
    }
    
    if (show_imgFilesizeSpan)
    {
        imgFilesize_span = 
            "<span class='imgFilesize'>" +
            "</span>";
    }
    
    imgResolutionAndFilesize_menuItem = imgResolution_span + imgFilesize_span;
    if (imgResolutionAndFilesize_menuItem !== "")
    {
        imgResolutionAndFilesize_menuItem = 
            "<div class='imgMenuItem'>" +
                imgResolutionAndFilesize_menuItem +
            "</div>";
    }
    
    if (show_imgGoogle)
    {
        imgGoogleReverse_menuItem = 
            "<div class='imgMenuItem'><a target='_blank' class='imgMenuItemAnchor_google' title='Reverse image search on general images' href='https://www.google.com/searchbyimage?image_url="+imgURL+"'>" +
                "google" +
            "</a></div>";
    }

    if (show_imgIqdb)
    {
        imgIQDBreverse_menuItem = 
            "<div class='imgMenuItem'><a target='_blank' class='imgMenuItemAnchor_iqdb' title='Reverse image search on weeb images' href='http://iqdb.org/?url="+imgURL+"'>" +
                "iqdb" +
            "</a></div>";
    }
        
    if (show_blacklistToggle)
    {
        if (isBlacklisted)
        {
            imgBlacklistToggle_menuItem =
                "<div class='imgMenuItem'><a class='imgBlacklistToggle' href='#' title='Whitelist image'>whitelist</a></div>"; 
        }
        else 
        {
            imgBlacklistToggle_menuItem =
                "<div class='imgMenuItem'><a class='imgBlacklistToggle' href='#' title='Blacklist image'>blacklist</a></div>"; 
        }
    }
    
    if (show_imgResizeToggles)
    {
        imgResizeToggles_menuItem =
            "<div class='imgMenuItem'>" +
                "<a class='imgCloseAll' href='#' title='Close all images in page'>&lt;&lt;&nbsp;</a>" +
                "<a class='imgClosePost' href='#' data-postID='"+postID+"' title='Close all images in post'>&lt;&nbsp;</a>" +
                "<a class='imgExpandPost' href='#' data-postID='"+postID+"' title='Expand all images in post'>&gt;&nbsp;</a>" +
                "<a class='imgExpandAll' href='#' title='Expand all images in page'>&gt;&gt;</a>" +
            "</div>";
    }
    
    if (show_hideAllToggle) 
    {
        imgHideAllToggle_menuItem =
            "<div class='imgMenuItem'>" +
                "<a class='imgHideAll' href='#' title='Hide all images in page' style='margin-right: 5px'>--</a>" +
                "<a class='imgHidePost' href='#' data-postID='"+postID+"' title='Hide all images in post' style='margin-right: 5px'>-</a>" +
                "<a class='imgShowPost' href='#' data-postID='"+postID+"' title='Show all images in post' style='margin-right: 5px'>+</a>" +
                "<a class='imgShowAll' href='#' title='Show all images in page' style='margin-right: 5px'>++</a>" +
            "</div>";
    }
    
    if (show_hideToggle) 
    {
        imgHideToggle_menuItem =
            "<div class='imgMenuItem'><a class='imgHideToggle' href='#' title='Hide image'>hide</a></div>"; 
    }
    
    if (imgMenu !== null)
        imgMenu.remove();
        
    $("body").append(
        "<div class='imgMenu' data-idx='"+image.parent().attr("data-idx")+"' style='display: none; position: absolute; z-index: 90;'>" +
            imgURL_menuItem +
            imgResolutionAndFilesize_menuItem +
            imgGoogleReverse_menuItem +
            imgIQDBreverse_menuItem +
            imgBlacklistToggle_menuItem +
            imgResizeToggles_menuItem +
            imgHideAllToggle_menuItem +
            imgHideToggle_menuItem +
        "</div>"
    );
    
    imgMenu = $("body > .imgMenu");
    var imgFilesizeSpan = imgMenu.find(".imgFilesize");
    var imgResolutionSpan = imgMenu.find(".imgResolution");
    
    getFileSize(imgURL, imgFilesizeSpan);

    /*if plain image (i.e. not a webm video)*/
    if (! image.hasClass("webmExt"))
    {
        image.load(function() {
            if (imgResolutionSpan.length > 0)
            {
                imgResolutionSpan.html(
                    "(" + image[0].naturalWidth + "x" + image[0].naturalHeight + ")"
                );
            }
        });
        
        /*if image already loaded*/
        if (image[0].naturalWidth !== 0)
        {
            if (imgResolutionSpan.length > 0)
            {
                imgResolutionSpan.html(
                    "(" + image[0].naturalWidth + "x" + image[0].naturalHeight + ")"
                );
            }
        }
    }
    else    /*if webm*/
    {
        /*when video's metadata has been loaded, record its natural width and resolution*/
        image[0].onloadedmetadata = function() {
            
            var video = this;
            
            if (imgResolutionSpan.length > 0)
            {
                imgResolutionSpan.html(
                    "(" + video.videoWidth + "x" + video.videoHeight + ")"
                );
            }
        };
        
        if (image[0].videoWidth !== 0)
        {
            imgResolutionSpan.html(
                "(" + image[0].videoWidth + "x" + image[0].videoHeight + ")"
            );
        }
    }
    
    var img_rightOffset = image.offset().left + image.width();
    var imgMenu_rightOffset = img_rightOffset + imgMenu.width();
    
    /*if imgMenu right offset exceeds beyond window's right offset*/
    if (imgMenu_rightOffset > $(window).scrollLeft() + $(window).width())
        imgMenu.css("left", ($(window).scrollLeft() + $(window).width() - imgMenu.width()) + "px");
    else 
        imgMenu.css("left", img_rightOffset + "px");
    
    imgMenu.css("top", image.offset().top + "px");
    imgMenu.css("display", "inline");
    
    imgMenuButton.children().html("-");
}

function hideImgMenu()
{
    if (imgMenu !== undefined && imgMenu !== null)
    {
        imgMenu.remove();
        imgMenu = null;
    }
}

function getImageAnchorOfImgMenu()
{
    var imgIdx = $("body > .imgMenu").attr("data-idx");
    
    return $(".embeddedImgAnchor[data-idx='"+imgIdx+"']");
}

function isHovered(jQueryObj)
{
    return !!$(jQueryObj).filter(function() { return $(this).is(":hover"); }).length;
}



$(document).on("click", function(event) {
    
    if (imgMenu !== null &&
        !isHovered(imgMenu) ||
        isHovered($(".imgMenuItemAnchor_url")) ||
        isHovered($(".imgMenuItemAnchor_google")) ||
        isHovered($(".imgMenuItemAnchor_iqdb")) ||
        isHovered($(".imgBlacklistToggle")) ||
        isHovered($(".imgCloseAll")) ||
        isHovered($(".imgClosePost")) ||
        isHovered($(".imgExpandPost"))||
        isHovered($(".imgExpandAll")) ||
        isHovered($(".imgHideAll")) ||
        isHovered($(".imgHidePost")) ||
        isHovered($(".imgShowPost"))||
        isHovered($(".imgShowAll")) ||
        isHovered($(".imgHideToggle"))
        )
    {
        hideImgMenu();
    }
});



function handleFloatingImage(event)
{
    if (!enable_floatingImg)
        return;
    
    var floatingImgLeft;
    var floatingImgTop;
    var floatingImgWidth;
    var floatingImgHeight;
    var floatingImgStyleStr;
    
    /*if user is hovering over thumbnail, prepare floating image size and position*/
    if (currentHoveredThumbnail !== null)
    {
        floatingImgWidth = parseInt(getNatWidthOfEmbeddedImg(currentHoveredThumbnail));

        floatingImgLeft = event.pageX + floatingImgRightOffset;
        
        /*if right of image exceeds beyond right of window, restrict max width*/
        if (floatingImgLeft + floatingImgWidth > $(window).scrollLeft() + $(window).width() - floatingImgBorder)
        {
            floatingImgWidth = $(window).scrollLeft() + $(window).width() - floatingImgBorder - floatingImgLeft;
        }
        
        if (floatingImgWidth < 0)
            floatingImgWidth = 0;
        
        floatingImgHeight = Math.round(getNatHeightOfEmbeddedImg(currentHoveredThumbnail) * (floatingImgWidth / getNatWidthOfEmbeddedImg(currentHoveredThumbnail)));
        
        floatingImgTop = event.pageY - (floatingImgHeight / 2);
        
        /*if bottom of image exceeds beyond the window, shift top upwards*/
        if (floatingImgTop + floatingImgHeight > $(window).scrollTop() + $(window).height() - floatingImgBorder)
        {
            floatingImgTop = $(window).scrollTop() + $(window).height() - floatingImgBorder - floatingImgHeight;
        }
        
        /*if top of image expands beyond top of window, lower top of image*/
        if (floatingImgTop < $(window).scrollTop() + floatingImgBorder)
        {
            floatingImgTop = $(window).scrollTop() + floatingImgBorder;
        }
        
        /*if bottom of image exceeds beyond the window, restrict max height*/
        if (floatingImgTop + floatingImgHeight > $(window).scrollTop() + $(window).height() - floatingImgBorder)
        {
            floatingImgHeight = $(window).scrollTop() + $(window).height() - floatingImgBorder - floatingImgTop;
        }
        
        if (curFloatingImg !== null &&   
            curFloatingImg.attr("data-idx") !== currentHoveredThumbnail.parent().attr("data-idx"))
        {
            curFloatingImg.attr("data-href", "");
            
            if (curFloatingImg.prop("tagName") === "video")
                curFloatingImg.children("source").attr("src", "");
            else 
                curFloatingImg.attr("src", "");
        }
        
        /*if floating image doesn't exist or doesn't have an image yet...*/
        if (curFloatingImg === null || curFloatingImg.attr("data-href") === "")
        {
            var floatingImgStyleStr = 
                "position: absolute;" +
                "left: " + floatingImgLeft + "px;" +
                "top: " + floatingImgTop + "px;" +
                "max-width: " + floatingImgWidth + "px;" +
                "max-height: " + floatingImgHeight + "px;" +
                "z-index: 100;";
            
            var imgIdx = currentHoveredThumbnail.parent().attr("data-idx");
            var imgContainerStyle_this = currentHoveredThumbnail.closest(".embeddedImgContainer").attr("data-style");
            
            /*if webm video*/
            if (currentHoveredThumbnail.hasClass("webmExt"))
            {
                srcURL = currentHoveredThumbnail.children("source").attr("src");
                
                floatingImgSrc = 
                    "<video id='floatingImg' data-idx='"+imgIdx+"' data-href='"+srcURL+"' style='" + floatingImgStyleStr + "'>" +
                        "<source src='"+srcURL+"' type='video/webm'>" +
                    "</video>";
            }
            else 
            {
                srcURL = currentHoveredThumbnail.attr("src");
                
                floatingImgSrc = 
                    "<img id='floatingImg' data-idx='"+imgIdx+"' data-href='"+srcURL+"' style='" + floatingImgStyleStr + "' src='"+srcURL+"'>";
            }
            
            /*create the floating image element if haven't so*/
            if (curFloatingImg === null)
            {
                $("body").append(
                    floatingImgSrc
                );
                
                curFloatingImg = $("body").children("#floatingImg");
            }
            else 
            {
                curFloatingImg.attr("data-href", srcURL);
                curFloatingImg.attr("data-idx", imgIdx);
                curFloatingImg.attr("style", floatingImgStyleStr);
                
                if (curFloatingImg.prop("tagName") === "video")
                    curFloatingImg.children("source").attr("src", srcURL);
                else 
                    curFloatingImg.attr("src", srcURL);
            }

            /*if webm video*/
            if (currentHoveredThumbnail.hasClass("webmExt"))
            {
                var video = curFloatingImg;

                video.attr("loop", "");
                video[0].play();
            }
            
            if (imgContainerStyle_this === "sideBySide")
                showImgMenuButton(currentHoveredThumbnail, true);
        }
        else    /*if floating image already exists, update its size and position*/
        {
            $("body").children("#floatingImg").css({
                "left": floatingImgLeft + "px",
                "top": floatingImgTop + "px",
                "max-width": floatingImgWidth + "px",
                "max-height": floatingImgHeight + "px",
            });
        }
    }
    /*if user is not hovering over thumbnail and floating image still exists*/
    else if (currentHoveredThumbnail === null && curFloatingImg !== null)
    {
        showImgMenuButton(null, false);
        
        curFloatingImg.remove();
        curFloatingImg = null;
    } 
}



var curFloatingImg = null;
/*if cursor is hovering inside a thumbnail image, display expanded image as floating div
Also show a transparent button to expand the image menu (side-by-side image view only)
*/
$(document).on("mousemove", function(event) {
    
    handleFloatingImage(event);
});




/*if mouse hovers inside the image, change cursor to pointer*/
$(document).on("mouseover", ".embeddedImg", function(event){
    $("html").css("cursor", "pointer");
    
    if (! $(this).hasClass("expandedImg"))
    {
        currentHoveredThumbnail = $(event.target); 
    }
});

/*if mouse hovers outside the image, restore cursor to default graphic*/
$(document).on("mouseout", ".embeddedImg", function(){
    $("html").css("cursor", "default");
    
    currentHoveredThumbnail = null;
});



/*if clicked on the image URL anchor that's surrounding the embedded image, prevent default
behaviour of anchor, unless it's a middle click*/
$("body").on("click", ".embeddedImgAnchor", function(event){
    
    /*left-click*/
    if (event.which === 1)
    {
        
    }
    else 
    {
        $(this).attr("href", $(this).attr("data-backup-href"));
    }
});

$("body").on("mousedown", ".embeddedImgAnchor", function(event){
    
    /*left-click*/
    if (event.which === 1)
    {
        event.preventDefault();
    }
    else 
    {
        $(this).attr("href", $(this).attr("data-backup-href"));
    }
});

/* jshint -W107 */
    
/*toggle image size on left-click*/
$("body").on("click", ".embeddedImg", function(event){
    
    /*left-click*/
    if (event.which === 1)
    {
        if (isHoverOverImgMenuButton(event) && imgMenu === null)
        {
            showImgMenu($(this));
            return false;
        }
        else if (isHoverOverImgMenuButton(event) && imgMenu !== null)
        {
            /*if referring to same thumbnail*/
            if (imgMenu.attr("data-idx") === $(this).parent().attr("data-idx"))
            {
                hideImgMenu();
            }
            else 
            {
                showImgMenu($(this));
            }
            
            showImgMenuButton($(this), true);
            return false;
        }
        else if (imgMenu !== null)
        {
            hideImgMenu();
        }

        showImgMenuButton($(this), false);

        var mouseRelativeY = event.pageY - $(this).offset().top;
        
        /*if expanded webm file, don't shrink to thumbnail if clicked on its controls*/
        if ($(this).hasClass("webmExt") && $(this).hasClass("expandedImg") &&
             (mouseRelativeY > ($(this).height() - 28)))
        {
            $(this).parent().attr("href", "javascript:void(0);");
        }
        else
        {
            toggleEmbeddedImgSize($(this), false);

            if (autoScrollWhenThumbnailClicked)
                $(window).scrollTop( $(this).parent().parent().offset().top );
            
            return false;
        }
    }
});






/*
@param isAll :: true if your intention is to expand/shrink all images
*/
function toggleEmbeddedImgSize(embeddedImg, isAll)
{
    var embeddedImgContainer = embeddedImg.closest(".embeddedImgContainer");
    var isSig = embeddedImgContainer.hasClass("withinSig");
    
    var thumbnailImgWidth_this = isSig ? thumbnailImgWidthSig : thumbnailImgWidth;
    var thumbnailImgHeight_this = isSig ? thumbnailImgHeightSig : thumbnailImgHeight;
    var thumbnailImgWidth_this_css = thumbnailImgWidth_this == 0 ? "" : thumbnailImgWidth_this+"px";
    var thumbnailImgHeight_this_css = thumbnailImgHeight_this == 0 ? "" : thumbnailImgHeight_this+"px";
    
    if (!includeSigWhenExpanding && embeddedImg.hasClass("withinSig") && isAll)
    {
    }
    else 
    {
        embeddedImg.toggleClass("thumbnailImg expandedImg");
    }
    
    /*if going to expand image*/
    if (embeddedImg.hasClass("expandedImg"))
    {
        if (!includeSigWhenExpanding && embeddedImg.hasClass("withinSig") && isAll)
        {
            return;
        }
        
        currentHoveredThumbnail = null;
        $("#floatingImg").remove();

        embeddedImg.css("max-width", getOptimalImgMaxWidth(embeddedImg, expandedImgWidth) + "px");
        embeddedImg.css("max-height", expandedImgHeight_css);
        
        /*if webm file, start playing it*/
        if (embeddedImg.hasClass("webmExt"))
        {
            embeddedImg[0].play();
            embeddedImg.attr("controls", "");
        }
    }
    else    /*if shrinking image back to thumbnail*/
    {
        embeddedImg.css("max-width", getOptimalImgMaxWidth(embeddedImg, thumbnailImgWidth_this) + "px");
        embeddedImg.css("max-height", thumbnailImgHeight_this_css);
        
        /*if webm file, stop playing it*/
        if (embeddedImg.hasClass("webmExt"))
        {
            embeddedImg[0].pause();
            embeddedImg.removeAttr("controls");
        }
        
        if (isHovered(embeddedImg) && !isFirefox) /*osdep*/ 
        {
            currentHoveredThumbnail = embeddedImg; 
        }
        else 
        {
            $("html").css("cursor", "default");     /*osdep for firefox*/
            currentHoveredThumbnail = null;
        }
    }
}


/*
Get the optimal max-width for an image.

The width will be one of the following:
    - until the right of the browser windows border
    - until the right of the parent container of the image container
    - until the user-defined width limit

The smallest of the 3 will be chosen.    

@param embeddedImg :: jQuery object of the image
@param userDefinedWidthLimit :: use 0 if no limit

The returned width will be the smaller of the three.
*/
function getOptimalImgMaxWidth(embeddedImg, userDefinedWidthLimit)
{
    var optimalWidth;
    var toContainerWidth;
    var toWindowWidth;
    
    toContainerWidth = 
        embeddedImg.closest(".msg_body, blockquote").width();        /*gfaqsdep*/
        
    toWindowWidth =
        $(window).width() - embeddedImg.closest(".msg_body, blockquote").offset().left;     /*gfaqsdep*/
  
    if (toContainerWidth > toWindowWidth)
        optimalWidth = toWindowWidth;
    else 
        optimalWidth = toContainerWidth;

    /*if no user-defined limit on the width*/
    if (userDefinedWidthLimit == 0)
    {
        return optimalWidth;
    }
    else 
    {
        if (optimalWidth > userDefinedWidthLimit)
            return userDefinedWidthLimit;
        else 
            return optimalWidth;    
    }
}










function toggleSizesOfImages(embeddedImages, isExpanding) {

    embeddedImages.each(function(index, element) {
        
        if ($(this).closest(".embeddedImgContainer").hasClass("hidden")) {
            return false;
        }
        
        if (isExpanding && $(this).hasClass("expandedImg"))
        {
            /*update its max-width*/
            $(this).css("max-width", getOptimalImgMaxWidth($(this)));
        }
        else 
        {
            toggleEmbeddedImgSize($(this), true);
        }
    });
}

$("body").on("click", ".imgCloseAll", function(event) {
    event.preventDefault();
    toggleSizesOfImages($(".embeddedImg.expandedImg"), false);
    nextImageSize = "expanded";
    
    var isContainerStacked = $(this).parent().attr("data-style");
    
    if (autoScrollWhenThumbnailClicked) {
        if (isContainerStacked)
            $(window).scrollTop( $(this).parent().offset().top );
        else
            $(window).scrollTop( getImageAnchorOfImgMenu().parent().offset().top );
    }
});

$("body").on("click", ".imgClosePost", function(event) {
    
    var postID = $(this).attr("data-postID");
    
    event.preventDefault();
    toggleSizesOfImages($(".embeddedImg[data-postID="+postID+"].expandedImg"), false);

    var isContainerStacked = $(this).parent().attr("data-style");
    
    if (autoScrollWhenThumbnailClicked) {
        if (isContainerStacked)
            $(window).scrollTop( $(this).parent().offset().top );
        else
            $(window).scrollTop( getImageAnchorOfImgMenu().parent().offset().top );
    }
});

$("body").on("click", ".imgExpandPost", function(event) {
    
    var postID = $(this).attr("data-postID");

    event.preventDefault();
    toggleSizesOfImages($(".embeddedImg[data-postID='"+postID+"']"), true);

    var isContainerStacked = $(this).parent().attr("data-style");
    
    if (autoScrollWhenThumbnailClicked) {
        if (isContainerStacked)
            $(window).scrollTop( $(this).parent().offset().top );
        else
            $(window).scrollTop( getImageAnchorOfImgMenu().parent().offset().top );
    }
});

$("body").on("click", ".imgExpandAll", function(event) {
    event.preventDefault();
    toggleSizesOfImages($(".embeddedImg"), true);
    nextImageSize = "thumbnail";
    
    var isContainerStacked = $(this).parent().attr("data-style");
    
    if (autoScrollWhenThumbnailClicked) {
        if (isContainerStacked)
            $(window).scrollTop( $(this).parent().offset().top );
        else
            $(window).scrollTop( getImageAnchorOfImgMenu().parent().offset().top );
    }
});










$("body").on("click", ".imgBlacklistToggle", function(event) {
    
    event.preventDefault();
    
    var imgURL;
    var imgAnchor;
    
    var isContainerStacked = $(this).parent().attr("data-style");
    
    if (!isContainerStacked)
    {
        if ($(this).html() === "blacklist")
            imgAnchor = getImageAnchorOfImgMenu();
        else 
            imgAnchor = $(this).parent().siblings(".embeddedImgAnchor");
    }
    else 
    {
        imgAnchor = $(this).siblings(".embeddedImgAnchor");
    }
    
    imgURL = imgAnchor.attr("data-backup-href");
    imgURL.trim();
    
    /*if image isn't blacklisted (but going to blacklist)*/
    if (! imgAnchor.hasClass("blacklisted"))
    {
        /*for every embedded image anchor*/
        $(".embeddedImgAnchor").each(function(index, element) {
            
            /*if has URL that was just blacklisted, hide it*/
            if (isURLmatchBlacklistedURL(imgURL, $(this).attr("data-backup-href")))
            {
                hideMedia($(this).parent(), true);
            }
        });
    }
    else /*if image is blacklisted (but going to whitelist)*/
    {
        /*for every embedded image anchor*/
        $(".embeddedImgAnchor").each(function(index, element) {

            /*if has URL that was just whitelisted, show it*/
            if ($(this).attr("data-backup-href") === imgURL)
            {
                showMedia($(this).parent(), true);
            }
        });
    }
});



$("body").on("click", "a.imgHideToggle", function(event) {
    
    event.preventDefault();

    var curEmbeddedImgContainer;
    var isContainerStacked = $(this).parent().attr("data-style");
    
    /*if image is going to be hidden*/
    if ($(this).html() === "hide")
    {
        if (!isContainerStacked)
            curEmbeddedImgContainer = getImageAnchorOfImgMenu().parent(); 
        else 
            curEmbeddedImgContainer = $(this).parent();
        
        hideMedia(curEmbeddedImgContainer, false);
    }
    else    /*if image is going to be shown*/
    {
        if (!isContainerStacked)
            curEmbeddedImgContainer = $(this).closest(".embeddedImgContainer");
        else 
            curEmbeddedImgContainer = $(this).parent();

        showMedia(curEmbeddedImgContainer, false);
    }
});



$("body").on("click", "a.imgHideAll", function(event) {
    event.preventDefault();
    
    toggleImageVisiblity($(".embeddedImgContainer"), "closeAnchor");
    
    var isContainerStacked = $(this).parent().attr("data-style");
    
    if (autoScrollWhenThumbnailClicked) {
        if (isContainerStacked)
            $(window).scrollTop( $(this).parent().offset().top );
        else
            $(window).scrollTop( getImageAnchorOfImgMenu().parent().offset().top );
    }
});
$("body").on("click", "a.imgHidePost", function(event) {
    event.preventDefault();
    
    var postID = $(this).attr("data-postID");
    var isContainerStacked = $(this).parent().attr("data-style");
    
    toggleImageVisiblity($(".embeddedImgContainer[data-postID="+postID+"]"), "closeAnchor");

    if (autoScrollWhenThumbnailClicked) {
        if (isContainerStacked)
            $(window).scrollTop( $(this).parent().offset().top );
        else
            $(window).scrollTop( getImageAnchorOfImgMenu().parent().offset().top );
    }
});
$("body").on("click", "a.imgShowPost", function(event) {
    event.preventDefault();

    var postID = $(this).attr("data-postID");
    var isContainerStacked = $(this).parent().attr("data-style");
    
    toggleImageVisiblity($(".embeddedImgContainer[data-postID="+postID+"]"), "showAnchor");
    
    if (autoScrollWhenThumbnailClicked) {
        if (isContainerStacked)
            $(window).scrollTop( $(this).parent().offset().top );
        else
            $(window).scrollTop( getImageAnchorOfImgMenu().parent().offset().top );
    }
});
$("body").on("click", "a.imgShowAll", function(event) {
    event.preventDefault();
    
    var isContainerStacked = $(this).parent().attr("data-style");
    
    toggleImageVisiblity($(".embeddedImgContainer"), "showAnchor");
    
    if (autoScrollWhenThumbnailClicked) {
        if (isContainerStacked)
            $(window).scrollTop( $(this).parent().offset().top );
        else
            $(window).scrollTop( getImageAnchorOfImgMenu().parent().offset().top );
    }
});


})();   /*end of greasemonkey script*/

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址