// ==UserScript==
// @name	Page Width Resizer
// @namespace	http://www-ui.is.s.u-tokyo.ac.jp/~kobayash/
// @description	Adds translucent borders to both sides of the page. By dragging one of the borders, you can change the width of each page without resizing the window (preserving the page sizes in other tabs).
// @include	*
// ==/UserScript==

(function () {
  const generalName = 'Page Width Resizer';
  const containerID = (generalName + new Date()).replace(/\W/g, '');
  
  GM_addStyle('div#' + containerID + ' { opacity: 0 !important; } div#' + containerID + ':hover { opacity: 1 !important; } div#' + containerID + ' div { position: absolute !important; top: 0 !important; width: 4px !important; height: 100% !important; background: #808080 !important; z-index: 65535 !important; opacity: 0.5 !important; } div#' + containerID + ':active div { background: #ff8080 !important; } div#' + containerID + ' #L { left: 0 !important; cursor: e-resize !important; } div#' + containerID + ' #R { right: 0 !important; cursor: w-resize !important; }');

  const panel = document.body.appendChild(document.createElement('DIV'));
  
  panel.id = containerID;
  panel.title = generalName;

  const lEdge = panel.appendChild(document.createElement('DIV')); lEdge.id = 'L';
  const rEdge = panel.appendChild(document.createElement('DIV')); rEdge.id = 'R';

  var activeNode;
  
  document.addEventListener('mousedown', function (e) {
    activeNode = e.target;
  }, true);
  
  document.addEventListener('mouseup', function (e) {
    activeNode = null;
  }, true);
  
  document.addEventListener('mousemove', function (e) {
    if (activeNode != lEdge && activeNode != rEdge) {
      return true;
    }
    
    var d = document.documentElement;
    var s = d.style;

    s.marginLeft = s.marginRight = Math.min(e.pageX - lEdge.offsetWidth / 2, d.offsetWidth + (parseInt(s.marginLeft) || 0) + (parseInt(s.marginRight) || 0) - e.pageX - rEdge.offsetWidth / 2) + 'px';
    
    e.preventDefault(); return false;
  }, true);

  document.addEventListener('scroll', function (e) {
    lEdge.style.marginTop = rEdge.style.marginTop = document.documentElement.offsetTop + document.documentElement.scrollTop + document.body.offsetTop + document.body.scrollTop + 'px';
  }, true);
})()

