Artex / FA Fit to Screen

// ==UserScript==
// @name        FA Fit to Screen
// @namespace   Artex
// @description Fit large submissions to screen.
// @include     http://www.furaffinity.net/full/*
// @include     https://www.furaffinity.net/full/*
// @include     http://www.furaffinity.net/view/*
// @include     https://www.furaffinity.net/view/*
// @run-at      document-end
// @version     1.4
// @grant       none
// ==/UserScript==
var isResized = false;

function ResizeImage(img) {
  var viewportX = window.innerWidth;
  var viewportY = window.innerHeight;
  var imageX = img.naturalWidth;
  var imageY = img.naturalHeight;
  if (isResized) { //if resized, return normal dimensions.
    img.width = imageX;
    img.height = imageY;
    isResized = false;
  } else {
    if (imageX > viewportX) {
      img.width = viewportX;
      img.height = imageY * (viewportX/imageX);
    }
    if (imageY > viewportY) { //image is larger then window
      img.width = imageX * (viewportY/imageY);
      img.height = viewportY;
    }
    isResized = true;
  }
}
//gets the last child of the first group of 2 or more tags
function getLastChildOfTagGroup(tag, n) {
    var nodeList = n.childNodes;
    var isTag = false;
    var last
    for (i = 0; i < nodeList.length; i++) {
        if (nodeList[i].nodeName == tag) {
          isTag = true
          last = nodeList[i];
        } else if (isTag === true && nodeList[i].nodeType == 1) {
          return last
        }
    }
}

(function() {
  isResized = false;
  var image = document.getElementById('submissionImg');
  if (image) {
    var actionBar = document.getElementsByClassName('actions')[0] || document.getElementsByClassName('navitemscontainer')[0];
    var divider = document.createTextNode(' | ');
    var button = document.createElement('a');
    button.setAttribute('href', "javascript:void(0);");
    button.setAttribute('class', "navitems");
    button.innerHTML = 'Fit to Screen';

    var insertAt = getLastChildOfTagGroup('B', actionBar);
    actionBar.insertBefore(button, insertAt.nextSibling);
    actionBar.insertBefore(divider, button);
    
    button.onclick = function() {
        window.location.hash = '#submissionImg';
        ResizeImage(image);
    };
  }
})();