<commit_before>/*global jQuery, Kinetic, MAPJS, window, document*/
jQuery.fn.mapWidget = function (activityLog, mapModel, touchEnabled, imageRendering) {
	'use strict';
	return this.each(function () {
		var element = jQuery(this),
			stage = new Kinetic.Stage({
				container: 'container',
				draggable: true
			}),
			mediator = new MAPJS.KineticMediator(mapModel, stage, imageRendering),
			setStageDimensions = function () {
				stage.setWidth(element.width());
				stage.setHeight(element.height());
				stage.draw();
			},
			simulateTouch = function (touchType, hammerEvent) {
				var center;
				if (!hammerEvent.gesture) {
					return; // not a hammer event, instead simulated doubleclick
				}
				center = hammerEvent.gesture.center;
				stage.simulate(touchType, {
					offsetX: center.pageX - element.offset().left,
					offsetY: center.pageY - element.offset().top
				});
			},
			lastGesture,
			discrete = function (gesture) {
				var result = (lastGesture && lastGesture.type !== gesture.type && (gesture.timeStamp - lastGesture.timeStamp < 250));
				lastGesture = gesture;
				return !result;
			},
			keyboardEventHandlers = {
				13: mapModel.addSiblingIdea.bind(mapModel, 'keyboard'),
				8: mapModel.removeSubIdea.bind(mapModel, 'keyboard'),
				9: mapModel.addSubIdea.bind(mapModel, 'keyboard'),
				37: mapModel.selectNodeLeft.bind(mapModel, 'keyboard'),
				38: mapModel.selectNodeUp.bind(mapModel, 'keyboard'),
				39: mapModel.selectNodeRight.bind(mapModel, 'keyboard'),
				40: mapModel.selectNodeDown.bind(mapModel, 'keyboard'),
				46: mapModel.removeSubIdea.bind(mapModel, 'keyboard'),
				32: mapModel.editNode.bind(mapModel, 'keyboard'),
				191: mapModel.toggleCollapse.bind(mapModel, 'keyboard'),
				67: mapModel.cut.bind(mapModel, 'keyboard'),
				80: mapModel.paste.bind(mapModel, 'keyboard'),
				89: mapModel.copy.bind(mapModel, 'keyboard'),
				85: mapModel.undo.bind(mapModel, 'keyboard')
			},
			shiftKeyboardEventHandlers = {
				9: mapModel.insertIntermediate.bind(mapModel, 'keyboard'),
				38: mapModel.toggleCollapse.bind(mapModel, 'keyboard')
			},
			metaKeyboardEventHandlers = {
				48: mapModel.resetView.bind(mapModel, 'keyboard'),
				90: mapModel.undo.bind(mapModel, 'keyboard'),
				89: mapModel.redo.bind(mapModel, 'keyboard'),
				187: mapModel.scaleUp.bind(mapModel, 'keyboard'),
				189: mapModel.scaleDown.bind(mapModel, 'keyboard'),
				38: mapModel.moveRelative.bind(mapModel, 'keyboard', -1),
				40: mapModel.moveRelative.bind(mapModel, 'keyboard', 1),
				88: mapModel.cut.bind(mapModel, 'keyboard'),
				67: mapModel.copy.bind(mapModel, 'keyboard'),
		//		86: mapModel.paste.bind(mapModel, 'keyboard')
			},
			onKeydown = function (evt) {
				var eventHandler = ((evt.metaKey || evt.ctrlKey) ? metaKeyboardEventHandlers :
						(evt.shiftKey ? shiftKeyboardEventHandlers : keyboardEventHandlers))[evt.which];
				if (/input|textarea|select/i.test(evt.target.nodeName)) {
					return;
				}
				if (eventHandler) {
					eventHandler();
					evt.preventDefault();
				}
			},
			onScroll = function (event, delta, deltaX, deltaY) {
				mapModel.move('mousewheel', -1 * deltaX, deltaY);
				if (event.preventDefault) { // stop the back button
					event.preventDefault();
				}
			};
		mapModel.addEventListener('inputEnabledChanged', function (canInput) {
			stage.setDraggable(!canInput);
		});
		jQuery(document).keydown(onKeydown);
		jQuery(document).keydown("ctrl+shift+v meta+shift+v", function () {
			mapModel.pasteStyle('keyboard');
		});
		jQuery(document).keydown("ctrl+v meta+v", function () {
			mapModel.paste('keyboard');
		});
		activityLog.log('Creating canvas Size ' + element.width() + ' ' + element.height());
		setStageDimensions();
		stage.attrs.x = 0.5 * stage.getWidth();
		stage.attrs.y = 0.5 * stage.getHeight();
		jQuery(window).resize(setStageDimensions);
		jQuery('.modal')
			.on('show', mapModel.setInputEnabled.bind(mapModel, false))
			.on('hidden', mapModel.setInputEnabled.bind(mapModel, true));
		if (!touchEnabled) {
			jQuery(window).mousewheel(onScroll);
		} else {
			element.find('canvas').hammer().on("pinch", function (event) {
				if (discrete(event)) {
					mapModel.scale('touch', event.gesture.scale, {
						x: event.gesture.center.pageX - element.offset().left,
						y: event.gesture.center.pageY - element.offset().top
					});
				}
			}).on("swipe", function (event) {
				if (discrete(event)) {
					mapModel.move('touch', event.gesture.deltaX, event.gesture.deltaY);
				}
			}).on("doubletap", function (event) {
				mapModel.resetView();
			}).on("touch", function (evt) {
				jQuery('.topbar-color-picker:visible').hide();
				jQuery('.ideaInput:visible').blur();
			});
		}
	});
};
<commit_msg>change keyboard events to be set up using jQuery hotkeys for greater clarity<commit_after>/*global _, jQuery, Kinetic, MAPJS, window, document*/
jQuery.fn.mapWidget = function (activityLog, mapModel, touchEnabled, imageRendering) {
	'use strict';
	return this.each(function () {
		var element = jQuery(this),
			stage = new Kinetic.Stage({
				container: 'container',
				draggable: true
			}),
			mediator = new MAPJS.KineticMediator(mapModel, stage, imageRendering),
			setStageDimensions = function () {
				stage.setWidth(element.width());
				stage.setHeight(element.height());
				stage.draw();
			},
			simulateTouch = function (touchType, hammerEvent) {
				var center;
				if (!hammerEvent.gesture) {
					return; // not a hammer event, instead simulated doubleclick
				}
				center = hammerEvent.gesture.center;
				stage.simulate(touchType, {
					offsetX: center.pageX - element.offset().left,
					offsetY: center.pageY - element.offset().top
				});
			},
			lastGesture,
			discrete = function (gesture) {
				var result = (lastGesture && lastGesture.type !== gesture.type && (gesture.timeStamp - lastGesture.timeStamp < 250));
				lastGesture = gesture;
				return !result;
			},
			keyboardEventHandlers = {
				'return': mapModel.addSiblingIdea.bind(mapModel, 'keyboard'),
				'del backspace': mapModel.removeSubIdea.bind(mapModel, 'keyboard'),
				'tab': mapModel.addSubIdea.bind(mapModel, 'keyboard'),
				'left': mapModel.selectNodeLeft.bind(mapModel, 'keyboard'),
				'up': mapModel.selectNodeUp.bind(mapModel, 'keyboard'),
				'right': mapModel.selectNodeRight.bind(mapModel, 'keyboard'),
				'down': mapModel.selectNodeDown.bind(mapModel, 'keyboard'),
				'space': mapModel.editNode.bind(mapModel, 'keyboard'),
				'/ shift+up': mapModel.toggleCollapse.bind(mapModel, 'keyboard'),
				'c meta+x ctrl+x': mapModel.cut.bind(mapModel, 'keyboard'),
				'p meta+v ctrl+v': mapModel.paste.bind(mapModel, 'keyboard'),
				'y meta+c ctrl+c': mapModel.copy.bind(mapModel, 'keyboard'),
				'u meta+z ctrl+z': mapModel.undo.bind(mapModel, 'keyboard'),
				'shift+tab': mapModel.insertIntermediate.bind(mapModel, 'keyboard'),
				'meta+0 ctrl+0': mapModel.resetView.bind(mapModel, 'keyboard'),
				'r meta+shift+z meta+y ctrl+y': mapModel.redo.bind(mapModel, 'keyboard'),
				'meta+plus ctrl+plus': mapModel.scaleUp.bind(mapModel, 'keyboard'),
				'meta+minus ctrl+minus': mapModel.scaleDown.bind(mapModel, 'keyboard'),
				'meta+up ctrl+up': mapModel.moveRelative.bind(mapModel, 'keyboard', -1),
				'meta+down ctrl+down': mapModel.moveRelative.bind(mapModel, 'keyboard', 1),
				'ctrl+shift+v meta+shift+v': mapModel.pasteStyle.bind(mapModel, 'keyboard')
			},
			onScroll = function (event, delta, deltaX, deltaY) {
				mapModel.move('mousewheel', -1 * deltaX, deltaY);
				if (event.preventDefault) { // stop the back button
					event.preventDefault();
				}
			};
		jQuery.hotkeys.specialKeys[187] = 'plus';
		jQuery.hotkeys.specialKeys[189] = 'minus';
		_.each(keyboardEventHandlers, function (mappedFunction, keysPressed) {
			jQuery(document).keydown(keysPressed, function (event) {
				event.preventDefault();
				mappedFunction();
			});
		});
		mapModel.addEventListener('inputEnabledChanged', function (canInput) {
			stage.setDraggable(!canInput);
		});
		activityLog.log('Creating canvas Size ' + element.width() + ' ' + element.height());
		setStageDimensions();
		stage.attrs.x = 0.5 * stage.getWidth();
		stage.attrs.y = 0.5 * stage.getHeight();
		jQuery(window).resize(setStageDimensions);
		jQuery('.modal')
			.on('show', mapModel.setInputEnabled.bind(mapModel, false))
			.on('hidden', mapModel.setInputEnabled.bind(mapModel, true));
		if (!touchEnabled) {
			jQuery(window).mousewheel(onScroll);
		} else {
			element.find('canvas').hammer().on("pinch", function (event) {
				if (discrete(event)) {
					mapModel.scale('touch', event.gesture.scale, {
						x: event.gesture.center.pageX - element.offset().left,
						y: event.gesture.center.pageY - element.offset().top
					});
				}
			}).on("swipe", function (event) {
				if (discrete(event)) {
					mapModel.move('touch', event.gesture.deltaX, event.gesture.deltaY);
				}
			}).on("doubletap", function (event) {
				mapModel.resetView();
			}).on("touch", function (evt) {
				jQuery('.topbar-color-picker:visible').hide();
				jQuery('.ideaInput:visible').blur();
			});
		}
	});
};
<|endoftext|>


<commit_before>var STATS = {};
var PLOT_DATA = [];
var STATS_PLOT = null;

window.onload = function() {
  createPlot();
  collectPlotData();
}

/**
 * Draws a plot.
 */
function createPlot() {
  var options = {
    xaxis: { mode: "time", timeformat: "%b %d" },
    selection: { mode: "x" },
    //grid: { markings: weekendAreas }
  };
  STATS_PLOT = $.plot($("#plot"), [], options);
}

function redrawPlot(data) {
  STATS_PLOT.setData(data);
  STATS_PLOT.setupGrid();
  STATS_PLOT.draw();
}

function addPlotRow(domain, hits_by_date) {
  var row = hits_by_date;
  // Convert a histogram hash to a list of pairs.
  var keys = [];
  for (var k in row) {
    if (row.hasOwnProperty(k)) {
      keys.push(k);
    }
  }
  var sorted_keys = keys.sort();
  var d = [];
  for (var i = 0; i < sorted_keys.length; i++) {
    d.push([sorted_keys[i], row[sorted_keys[i]]]);
  }

  // TODO: ensure order stability
  PLOT_DATA.push({
    label: domain,
    data: d
  });
  redrawPlot(PLOT_DATA);
}

function collectPlotData() {
  var place = document.getElementById('statsplaceholder')
  var junkDomains = getLocal('junkDomains');
  junkDomains.forEach(function(domain) {
    findDirectHits(domain, function(visitItems) {
      var hitsByDate = {};
      visitItems.forEach(function(item) {
        if (item.transition === 'typed') {
          // TODO(gintas): Also count non-typed transitions?
          var dt = new Date(item.visitTime);
          clearTime(dt);
          var histKey = dt.getTime();
          if (!hitsByDate.hasOwnProperty(histKey)) {
            hitsByDate[histKey] = 0;
          }
          hitsByDate[histKey] += 1;
        }
      });
      addPlotRow(domain, hitsByDate);
    });
  });
}

function clearTime(dt) {
  dt.setUTCMilliseconds(0);
  dt.setUTCSeconds(0);
  dt.setUTCMinutes(0);
  dt.setUTCHours(0);
}

/**
 * Finds hits to a given domain.
 *
 * Checks common variants of the domain.
 */
function findDirectHits(domain, visitsHandler) {
  var variants = domainVariants(domain);
  var outstandingRequests = variants.length;
  var cumulativeVisits = [];
  variants.forEach(function(url) {
    chrome.history.getVisits({ url: url }, function(visits) {
      cumulativeVisits = cumulativeVisits.concat(visits);
      outstandingRequests--;
      if (outstandingRequests === 0) {
        visitsHandler(cumulativeVisits);
      }
    });
  });
}

/**
 * Returns variants of a given domain with.
 */
function domainVariants(domain) {
  return [
    'http://' + domain,
    'http://www.' + domain,
    'https://' + domain,
    'https://www.' + domain
  ];
}

/**
 * Finds history items by text-matching on the given domain.
 */
function findHistoryItems(domain) {
  var monthAgo = new Date().getTime() - 1000*3600*24*7*30;
  chrome.history.search({
    text: domain,
    startTime: monthAgo,
    maxResults: 1000
  }, function(historyitems) {
    RESULT = historyitems;
  });
}
<commit_msg>Semicolon fixes.<commit_after>var STATS = {};
var PLOT_DATA = [];
var STATS_PLOT = null;

window.onload = function() {
    createPlot();
    collectPlotData();
};

/**
 * Draws a plot.
 */
function createPlot() {
  var options = {
    xaxis: { mode: "time", timeformat: "%b %d" },
    selection: { mode: "x" }
    //grid: { markings: weekendAreas }
  };
  STATS_PLOT = $.plot($("#plot"), [], options);
}

function redrawPlot(data) {
  STATS_PLOT.setData(data);
  STATS_PLOT.setupGrid();
  STATS_PLOT.draw();
}

function addPlotRow(domain, hits_by_date) {
  var row = hits_by_date;
  // Convert a histogram hash to a list of pairs.
  var keys = [];
  for (var k in row) {
    if (row.hasOwnProperty(k)) {
      keys.push(k);
    }
  }
  var sorted_keys = keys.sort();
  var d = [];
  for (var i = 0; i < sorted_keys.length; i++) {
    d.push([sorted_keys[i], row[sorted_keys[i]]]);
  }

  // TODO: ensure order stability
  PLOT_DATA.push({
    label: domain,
    data: d
  });
  redrawPlot(PLOT_DATA);
}

function collectPlotData() {
  var place = document.getElementById('statsplaceholder');
  var junkDomains = getLocal('junkDomains');
  junkDomains.forEach(function(domain) {
    findDirectHits(domain, function(visitItems) {
      var hitsByDate = {};
      visitItems.forEach(function(item) {
        if (item.transition === 'typed') {
          // TODO(gintas): Also count non-typed transitions?
          var dt = new Date(item.visitTime);
          clearTime(dt);
          var histKey = dt.getTime();
          if (!hitsByDate.hasOwnProperty(histKey)) {
            hitsByDate[histKey] = 0;
          }
          hitsByDate[histKey] += 1;
        }
      });
      addPlotRow(domain, hitsByDate);
    });
  });
}

function clearTime(dt) {
  dt.setUTCMilliseconds(0);
  dt.setUTCSeconds(0);
  dt.setUTCMinutes(0);
  dt.setUTCHours(0);
}

/**
 * Finds hits to a given domain.
 *
 * Checks common variants of the domain.
 */
function findDirectHits(domain, visitsHandler) {
  var variants = domainVariants(domain);
  var outstandingRequests = variants.length;
  var cumulativeVisits = [];
  variants.forEach(function(url) {
    chrome.history.getVisits({ url: url }, function(visits) {
      cumulativeVisits = cumulativeVisits.concat(visits);
      outstandingRequests--;
      if (outstandingRequests === 0) {
        visitsHandler(cumulativeVisits);
      }
    });
  });
}

/**
 * Returns variants of a given domain with.
 */
function domainVariants(domain) {
  return [
    'http://' + domain,
    'http://www.' + domain,
    'https://' + domain,
    'https://www.' + domain
  ];
}

/**
 * Finds history items by text-matching on the given domain.
 */
function findHistoryItems(domain) {
  var monthAgo = new Date().getTime() - 1000*3600*24*7*30;
  chrome.history.search({
    text: domain,
    startTime: monthAgo,
    maxResults: 1000
  }, function(historyitems) {
    RESULT = historyitems;
  });
}
<|endoftext|>


<commit_before>class MapFactory {
    constructor(canvasName, mapCols, mapRows, tileWidth, tileHeight) {
        var _self = this;

        this.tileWidth = typeof tileWidth === "number" ? Math.abs(tileWidth) : 0;
        this.tileHeight = typeof tileHeight === "number" ? Math.abs(tileHeight) : 0;
        this.mapCols = typeof mapCols === "number" ? Math.abs(mapCols) : 0;
        this.mapRows = typeof mapRows === "number" ? Math.abs(mapRows) : 0;
        this.viewOffsetI = 0;
        this.viewOffsetJ = 0;

        this.minVisibleRows = Math.min(Math.trunc(document.body.clientHeight / this.tileHeight) /*- 1*/, this.mapRows);
        this.minVisibleCols = 0;
        this.maxVisibleRows = this.minVisibleRows; // Default behavior is fixed rows.
        this.maxVisibleCols = 0;

        this.mode = "mapDragging";

        var currOffsetI = 0;
        var currOffsetJ = 0;
        var crsrOffsetI = 0;
        var crsrOffsetJ = 0;

        var canvas = this["canvas"] = document.getElementById(canvasName);
        var context = this["context"] = canvas.getContext('2d');

        var assetBackground = this["assetBackground"] = new Image();
        var assetForeground = this["assetForeground"] = new Image();
        var assetCursor = this["assetCursor"] = new Image();

        var showCursor = function (ev) {
            var newI = Math.trunc(ev.offsetX / _self.tileWidth) + _self.viewOffsetI;
            var newJ = Math.trunc(ev.offsetY / _self.tileHeight) + _self.viewOffsetJ;
            var oldI = parseInt(canvas.dataset.offsetI);
            var oldJ = parseInt(canvas.dataset.offsetJ);

            if (newI !== oldI || newJ !== oldJ) {
                canvas.dataset.offsetI = newI;
                canvas.dataset.offsetJ = newJ;

                var cac = _self["cac"];

                if (assetCursor.src && cac && typeof cac === "function") {
                    var coor = cac(newI, newJ);
                    if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
                        _self.drawCursorTile(coor.x, coor.y, newI, newJ);
                    } else {
                        canvas.style.cursor = "auto";
                        return true; // Cursor asset is not working. No needs to continue.
                    }
                } else {
                    canvas.style.cursor = "auto";
                    return true; // Same as above.
                }
                canvas.style.cursor = "none";
                _self.restoreTile(oldI, oldJ);
            }
            return true;
        };
        var hideCursor = function (ev) { // Hide cursor when mouse leaves
            var oldI = parseInt(canvas.dataset.offsetI);
            var oldJ = parseInt(canvas.dataset.offsetJ);

            _self.restoreTile(oldI, oldJ);
        };
        var mapDragging = function (ev) { // Dragging map
            var tempOffsetI = Math.trunc(ev.offsetX / _self.tileWidth);
            var tempOffsetJ = Math.trunc(ev.offsetY / _self.tileHeight);

            var mapVisibleCols = _self["mapVisibleCols"];
            var mapVisibleRows = _self["mapVisibleRows"];

            var update = false;

            if (crsrOffsetI !== tempOffsetI) {
                var tempI = crsrOffsetI - tempOffsetI + currOffsetI;

                if (tempI < 0) {
                    tempI = 0;
                } else if (tempI + mapVisibleCols >= _self.mapCols) {
                    tempI = _self.mapCols - mapVisibleCols;
                }
                if (_self.viewOffsetI !== tempI) {
                    _self.viewOffsetI = tempI;
                    update = true;
                }
            }
            if (crsrOffsetJ !== tempOffsetJ) {
                var tempJ = crsrOffsetJ - tempOffsetJ + currOffsetJ;

                if (tempJ < 0) {
                    tempJ = 0;
                } else if (tempJ + mapVisibleRows >= _self.mapRows) {
                    tempJ = _self.mapRows - mapVisibleRows;
                }
                if (_self.viewOffsetJ !== tempJ) {
                    _self.viewOffsetJ = tempJ;
                    update = true;
                }
            }
            if (update) {
                _self.drawBackground();
                _self.drawForeground();
            }
            canvas.style.cursor = "move";
        };
        var rangeOperation = function (ev) {
            // TODO:
        }
        //-------------------------------//
        canvas.addEventListener("mousedown", function (ev) {
            if (ev.button !== 0) {
                return true;
            }
            crsrOffsetI = Math.trunc(ev.offsetX / _self.tileWidth);
            crsrOffsetJ = Math.trunc(ev.offsetY / _self.tileHeight);
            currOffsetI = _self.viewOffsetI;
            currOffsetJ = _self.viewOffsetJ;

            canvas.style.cursor = "move";
        });
        canvas.addEventListener("mousemove", function (ev) {
            if (ev.which !== 1) {
                return true;
            }
            switch (_self.mode) {
                case "mapDragging":
                    mapDragging(ev);
                    break;
                case "rangeOperation":
                    rangeOperation(ev);
                    break;
            }
        });
        canvas.addEventListener("mouseup", function (ev) {
            canvas.style.cursor = "initial";

            var tempOffsetI = Math.trunc(ev.offsetX / _self.tileWidth);
            var tempOffsetJ = Math.trunc(ev.offsetY / _self.tileHeight);

            if (crsrOffsetI === tempOffsetI && crsrOffsetJ === tempOffsetJ) { // Position doesn't change.
                var callback = _self["mousedown"];
                if (callback) {
                    callback(ev, tempOffsetI + _self.viewOffsetI, tempOffsetJ + _self.viewOffsetJ);
                }
            }
        });
        //-------------------------------//
        window.addEventListener("resize", function (ev) {
            _self.update();
        });
        //-------------------------------//
        assetBackground.onload = function (ev) {
            _self.drawBackground();
        };
        assetForeground.onload = function (ev) {
            _self.drawForeground();
        };
        assetCursor.onload = function (ev) {
            canvas.addEventListener("mousemove", showCursor);
            canvas.addEventListener("mouseleave", hideCursor);
        };
        //-------------------------------//
        this.updateMapVisibleSize();
        //-------------------------------//
    }
}

MapFactory.prototype.foregroundAsset = function (url) {
    var assetForeground = this["assetForeground"];
    if (typeof url === 'string') {
        assetForeground.src = url;
        return this;
    }
    return assetForeground.src;
};

MapFactory.prototype.backgroundAsset = function (url) {
    var assetBackground = this["assetBackground"];
    if (typeof url === 'string') {
        assetBackground.src = url;
        return this;
    }
    return assetBackground.src;
};

MapFactory.prototype.cursorAsset = function (url) {
    var assetCursor = this["assetCursor"];
    if (typeof url === 'string') {
        assetCursor.src = url;
        return this;
    }
    return assetCursor.src;
};

MapFactory.prototype.backgroundAssetMapping = function (callback) {
    if (typeof callback === 'function') {
        this["bac"] = callback;
        return this;
    }
    return this["bac"];
};

MapFactory.prototype.foregroundAssetMapping = function (callback) {
    if (typeof callback === 'function') {
        this["fac"] = callback;
        return this;
    }
    return this["fac"];
};

MapFactory.prototype.cursorAssetMapping = function (callback) {
    if (typeof callback === 'function') {
        this["cac"] = callback;
        return this;
    }
    return this["cac"];
};

MapFactory.prototype.mousedown = function (callback) {
    if (typeof callback === 'function') {
        this["mousedown"] = callback;
        return this;
    }
    return this["mousedown"];
};

MapFactory.prototype.updateMapVisibleSize = function () {
    var bb = this["canvas"].parentNode.getBoundingClientRect();
    var rows = Math.min(Math.trunc(document.body.clientHeight / this.tileHeight) /*- 1*/, this.mapRows);
    var cols = Math.min(Math.trunc((bb.right - bb.left) / this.tileWidth) - 1, this.mapCols);

    if (this.minVisibleRows > 0 && rows < this.minVisibleRows) {
        rows = this.minVisibleRows;
    }
    else if (this.maxVisibleRows > 0 && this.maxVisibleRows >= this.minVisibleRows && rows > this.maxVisibleRows) {
        rows = this.maxVisibleRows;
    }
    if (this.minVisibleCols > 0 && cols < this.minVisibleCols) {
        cols = this.minVisibleCols;
    }
    else if (this.maxVisibleCols > 0 && this.maxVisibleCols >= this.minVisibleCols && cols > this.maxVisibleCols) {
        cols = this.maxVisibleCols;
    }

    this["mapVisibleCols"] = cols;
    this["mapVisibleRows"] = rows;

    this["canvas"].width = cols * this.tileWidth;
    this["canvas"].height = rows * this.tileHeight;
};

MapFactory.prototype.drawBackground = function () {
    var mapVisibleCols = this["mapVisibleCols"];
    var mapVisibleRows = this["mapVisibleRows"];
    var bac = this["bac"];

    if (this["assetBackground"].src && bac && typeof bac === "function") {
        for (var i = this.viewOffsetI; i < mapVisibleCols + this.viewOffsetI; i++) {
            for (var j = this.viewOffsetJ; j < mapVisibleRows + this.viewOffsetJ; j++) {
                var coor = bac(i, j);
                if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
                    this.drawBackgroundTile(coor.x, coor.y, i, j);
                }
            }
        }
    }
};

MapFactory.prototype.drawForeground = function() {
    var mapVisibleCols = this["mapVisibleCols"];
    var mapVisibleRows = this["mapVisibleRows"];
    var fac = this["fac"];

    if (this["assetForeground"].src && fac && typeof fac === "function") {
        for (var i = this.viewOffsetI; i < mapVisibleCols + this.viewOffsetI; i++) {
            for (var j = this.viewOffsetJ; j < mapVisibleRows + this.viewOffsetJ; j++) {
                var coor = fac(i, j);
                if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
                    this.drawForegroundTile(coor.x, coor.y, i, j);
                }
            }
        }
    }
};

MapFactory.prototype.drawCursor = function (viewI, viewJ, cols, rows) {
    var cac = this["cac"];

    cols = isNaN(cols) ? 1 : parseInt(cols);
    rows = isNaN(rows) ? 1 : parseInt(rows);

    if (this["assetCursor"].src && cac && typeof cac === "function") {
        for (var i = viewI; i < viewI + cols; i++) {
            for (var j = viewI; j < viewI + rows; j++) {
                var coor = cac(i + this.viewOffsetI, j + this.viewOffsetJ);
                if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
                    this.drawCursorTile(coor.x, coor.y, i, j);
                }
            }
        }
    }
};

MapFactory.prototype.drawBackgroundTile = function (sourceX, sourceY, i, j) {
    var destX = (i - this.viewOffsetI) * this.tileWidth;
    var destY = (j - this.viewOffsetJ) * this.tileHeight;
    var asset = this["assetBackground"];

    this["context"].drawImage(asset,
        sourceX, sourceY, this.tileWidth, this.tileHeight, destX, destY, this.tileWidth, this.tileHeight);
};

MapFactory.prototype.drawForegroundTile = function (sourceX, sourceY, i, j) {
    var destX = (i - this.viewOffsetI) * this.tileWidth;
    var destY = (j - this.viewOffsetJ) * this.tileHeight;
    var asset = this["assetForeground"];
    this["context"].drawImage(asset,
        sourceX, sourceY, this.tileWidth, this.tileHeight, destX, destY, this.tileWidth, this.tileHeight);
};

MapFactory.prototype.drawCursorTile = function (sourceX, sourceY, i, j) {
    var destX = (i - this.viewOffsetI) * this.tileWidth;
    var destY = (j - this.viewOffsetJ) * this.tileHeight;
    var asset = this["assetCursor"];
    this["context"].drawImage(asset,
        sourceX, sourceY, this.tileWidth, this.tileHeight, destX, destY, this.tileWidth, this.tileHeight);
};

MapFactory.prototype.clearTile = function (i, j) {
    var destX = (i - this.viewOffsetI) * this.tileWidth;
    var destY = (j - this.viewOffsetJ) * this.tileHeight;
    this["context"].clearRect(destX, destY, this.tileWidth, this.tileHeight);
};

MapFactory.prototype.restoreTile = function (i, j) {
    var bac = this["bac"];
    var fac = this["fac"];

    var assetBackground = this["assetBackground"];
    var assetForeground = this["assetForeground"];

    this.clearTile(i, j);
    if (assetBackground.src && bac && typeof bac === "function") {
        var coor = bac(i, j);
        if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
            this.drawBackgroundTile(coor.x, coor.y, i, j);
        }
    }
    if (assetForeground.src && fac && typeof fac === "function") {
        var coor = fac(i, j);
        if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
            this.drawForegroundTile(coor.x, coor.y, i, j);
        }
    }
}

MapFactory.prototype.update = function () {
    this.updateMapVisibleSize();
    this.drawBackground();
    this.drawForeground();
}
<commit_msg>Update mapFactory.js<commit_after>class MapFactory {
    constructor(canvasName, mapCols, mapRows, tileWidth, tileHeight) {
        var _self = this;

        this.tileWidth = typeof tileWidth === "number" ? Math.abs(tileWidth) : 0;
        this.tileHeight = typeof tileHeight === "number" ? Math.abs(tileHeight) : 0;
        this.mapCols = typeof mapCols === "number" ? Math.abs(mapCols) : 0;
        this.mapRows = typeof mapRows === "number" ? Math.abs(mapRows) : 0;
        this.viewOffsetI = 0;
        this.viewOffsetJ = 0;

        this.minVisibleRows = Math.min(Math.trunc(document.body.clientHeight / this.tileHeight) /*- 1*/, this.mapRows);
        this.minVisibleCols = 0;
        this.maxVisibleRows = this.minVisibleRows; // Default behavior is fixed rows.
        this.maxVisibleCols = 0;

        this.mode = "mapDragging";

        var currOffsetI = 0;
        var currOffsetJ = 0;
        var crsrOffsetI = 0;
        var crsrOffsetJ = 0;

        var canvas = this["canvas"] = document.getElementById(canvasName);
        var context = this["context"] = canvas.getContext('2d');

        var assetBackground = this["assetBackground"] = new Image();
        var assetForeground = this["assetForeground"] = new Image();
        var assetCursor = this["assetCursor"] = new Image();

        var showCursor = function (ev) {
            var newI = Math.trunc(ev.offsetX / _self.tileWidth) + _self.viewOffsetI;
            var newJ = Math.trunc(ev.offsetY / _self.tileHeight) + _self.viewOffsetJ;
            var oldI = parseInt(canvas.dataset.offsetI);
            var oldJ = parseInt(canvas.dataset.offsetJ);

            if (newI !== oldI || newJ !== oldJ) {
                canvas.dataset.offsetI = newI;
                canvas.dataset.offsetJ = newJ;

                var cac = _self["cac"];

                if (assetCursor.src && cac && typeof cac === "function") {
                    var coor = cac(newI, newJ);
                    if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
                        _self.drawCursorTile(coor.x, coor.y, newI, newJ);
                    } else {
                        canvas.style.cursor = "auto";
                        return true; // Cursor asset is not working. No needs to continue.
                    }
                } else {
                    canvas.style.cursor = "auto";
                    return true; // Same as above.
                }
                canvas.style.cursor = "none";
                _self.restoreTile(oldI, oldJ);
            }
            return true;
        };
        var hideCursor = function (ev) { // Hide cursor when mouse leaves
            var oldI = parseInt(canvas.dataset.offsetI);
            var oldJ = parseInt(canvas.dataset.offsetJ);

            _self.restoreTile(oldI, oldJ);
        };
        var mapDragging = function (ev) { // Dragging map
            var tempOffsetI = Math.trunc(ev.offsetX / _self.tileWidth);
            var tempOffsetJ = Math.trunc(ev.offsetY / _self.tileHeight);

            var mapVisibleCols = _self["mapVisibleCols"];
            var mapVisibleRows = _self["mapVisibleRows"];

            var update = false;

            if (crsrOffsetI !== tempOffsetI) {
                var tempI = crsrOffsetI - tempOffsetI + currOffsetI;

                if (tempI < 0) {
                    tempI = 0;
                } else if (tempI + mapVisibleCols >= _self.mapCols) {
                    tempI = _self.mapCols - mapVisibleCols;
                }
                if (_self.viewOffsetI !== tempI) {
                    _self.viewOffsetI = tempI;
                    update = true;
                }
            }
            if (crsrOffsetJ !== tempOffsetJ) {
                var tempJ = crsrOffsetJ - tempOffsetJ + currOffsetJ;

                if (tempJ < 0) {
                    tempJ = 0;
                } else if (tempJ + mapVisibleRows >= _self.mapRows) {
                    tempJ = _self.mapRows - mapVisibleRows;
                }
                if (_self.viewOffsetJ !== tempJ) {
                    _self.viewOffsetJ = tempJ;
                    update = true;
                }
            }
            if (update) {
                _self.drawBackground();
                _self.drawForeground();
            }
            canvas.style.cursor = "move";
        };
        var rangeOperating = function (ev, callbackName) {
            var tempOffsetI = Math.trunc(ev.offsetX / _self.tileWidth);
            var tempOffsetJ = Math.trunc(ev.offsetY / _self.tileHeight);

            if (crsrOffsetI !== tempOffsetI || crsrOffsetJ !== tempOffsetJ) {
                var newI = tempOffsetI + _self.viewOffsetI;
                var newJ = tempOffsetJ + _self.viewOffsetJ;
                var oldI = parseInt(canvas.dataset.offsetI);
                var oldJ = parseInt(canvas.dataset.offsetJ);

                for (var i = Math.min(crsrOffsetI, oldI); i <= Math.max(crsrOffsetI, oldI); i++) {
                    for (var j = Math.min(crsrOffsetJ, oldJ); j <= Math.max(crsrOffsetJ, oldJ); j++) {
                        _self.restoreTile(i, j);
                    }
                }
                var callback = _self[callbackName];
                if (callback && typeof callback === "function") {
                    callback(ev, Math.min(crsrOffsetI, newI), Math.min(crsrOffsetJ, newJ), Math.abs(crsrOffsetI - newI), Math.abs(crsrOffsetJ - newJ));
                }
            }
        };
        //-------------------------------//
        canvas.addEventListener("mousedown", function (ev) {
            if (ev.button !== 0) {
                return true;
            }
            crsrOffsetI = Math.trunc(ev.offsetX / _self.tileWidth);
            crsrOffsetJ = Math.trunc(ev.offsetY / _self.tileHeight);
            currOffsetI = _self.viewOffsetI;
            currOffsetJ = _self.viewOffsetJ;

            canvas.style.cursor = "move";
        });
        canvas.addEventListener("mousemove", function (ev) {
            if (ev.which !== 1) {
                return true;
            }
            switch (_self.mode) {
                case "mapDragging":
                    mapDragging(ev);
                    return true;
                case "rangeOperating":
                    rangeOperating(ev, "rangeselecting");
                    return true;
            }
        });
        canvas.addEventListener("mouseup", function (ev) {
            canvas.style.cursor = "initial";

            var tempOffsetI = Math.trunc(ev.offsetX / _self.tileWidth);
            var tempOffsetJ = Math.trunc(ev.offsetY / _self.tileHeight);

            if (crsrOffsetI === tempOffsetI && crsrOffsetJ === tempOffsetJ) { // Position doesn't change.
                var callback = _self["mousedown"];
                if (callback) {
                    callback(ev, tempOffsetI + _self.viewOffsetI, tempOffsetJ + _self.viewOffsetJ);
                }
            }
            else {
                switch (_self.mode) {
                    case "mapDragging":
                        // TODO:
                        break;
                    case "rangeOperating":
                        rangeOperating(ev, "rangeselected");
                        break;
                }
            }
        });
        //-------------------------------//
        window.addEventListener("resize", function (ev) {
            _self.update();
        });
        //-------------------------------//
        assetBackground.onload = function (ev) {
            _self.drawBackground();
        };
        assetForeground.onload = function (ev) {
            _self.drawForeground();
        };
        assetCursor.onload = function (ev) {
            canvas.addEventListener("mousemove", showCursor);
            canvas.addEventListener("mouseleave", hideCursor);
        };
        //-------------------------------//
        this.updateMapVisibleSize();
        //-------------------------------//
    }
}

MapFactory.prototype.foregroundAsset = function (url) {
    var assetForeground = this["assetForeground"];
    if (typeof url === 'string') {
        assetForeground.src = url;
        return this;
    }
    return assetForeground.src;
};

MapFactory.prototype.backgroundAsset = function (url) {
    var assetBackground = this["assetBackground"];
    if (typeof url === 'string') {
        assetBackground.src = url;
        return this;
    }
    return assetBackground.src;
};

MapFactory.prototype.cursorAsset = function (url) {
    var assetCursor = this["assetCursor"];
    if (typeof url === 'string') {
        assetCursor.src = url;
        return this;
    }
    return assetCursor.src;
};

MapFactory.prototype.backgroundAssetMapping = function (callback) {
    if (typeof callback === 'function') {
        this["bac"] = callback;
        return this;
    }
    return this["bac"];
};

MapFactory.prototype.foregroundAssetMapping = function (callback) {
    if (typeof callback === 'function') {
        this["fac"] = callback;
        return this;
    }
    return this["fac"];
};

MapFactory.prototype.cursorAssetMapping = function (callback) {
    if (typeof callback === 'function') {
        this["cac"] = callback;
        return this;
    }
    return this["cac"];
};

MapFactory.prototype.mousedown = function (callback) {
    if (typeof callback === 'function') {
        this["mousedown"] = callback;
        return this;
    }
    return this["mousedown"];
};

MapFactory.prototype.rangeselecting = function (callback) {
    if (typeof callback === 'function') {
        this["rangeselecting"] = callback;
        return this;
    }
    return this["rangeselecting"];
};

MapFactory.prototype.rangeselected = function (callback) {
    if (typeof callback === 'function') {
        this["rangeselected"] = callback;
        return this;
    }
    return this["rangeselected"];
};

MapFactory.prototype.updateMapVisibleSize = function () {
    var bb = this["canvas"].parentNode.getBoundingClientRect();
    var rows = Math.min(Math.trunc(document.body.clientHeight / this.tileHeight) /*- 1*/, this.mapRows);
    var cols = Math.min(Math.trunc((bb.right - bb.left) / this.tileWidth) - 1, this.mapCols);

    if (this.minVisibleRows > 0 && rows < this.minVisibleRows) {
        rows = this.minVisibleRows;
    }
    else if (this.maxVisibleRows > 0 && this.maxVisibleRows >= this.minVisibleRows && rows > this.maxVisibleRows) {
        rows = this.maxVisibleRows;
    }
    if (this.minVisibleCols > 0 && cols < this.minVisibleCols) {
        cols = this.minVisibleCols;
    }
    else if (this.maxVisibleCols > 0 && this.maxVisibleCols >= this.minVisibleCols && cols > this.maxVisibleCols) {
        cols = this.maxVisibleCols;
    }

    this["mapVisibleCols"] = cols;
    this["mapVisibleRows"] = rows;

    this["canvas"].width = cols * this.tileWidth;
    this["canvas"].height = rows * this.tileHeight;
};

MapFactory.prototype.drawBackground = function () {
    var mapVisibleCols = this["mapVisibleCols"];
    var mapVisibleRows = this["mapVisibleRows"];
    var bac = this["bac"];

    if (this["assetBackground"].src && bac && typeof bac === "function") {
        for (var i = this.viewOffsetI; i < mapVisibleCols + this.viewOffsetI; i++) {
            for (var j = this.viewOffsetJ; j < mapVisibleRows + this.viewOffsetJ; j++) {
                var coor = bac(i, j);
                if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
                    this.drawBackgroundTile(coor.x, coor.y, i, j);
                }
            }
        }
    }
};

MapFactory.prototype.drawForeground = function() {
    var mapVisibleCols = this["mapVisibleCols"];
    var mapVisibleRows = this["mapVisibleRows"];
    var fac = this["fac"];

    if (this["assetForeground"].src && fac && typeof fac === "function") {
        for (var i = this.viewOffsetI; i < mapVisibleCols + this.viewOffsetI; i++) {
            for (var j = this.viewOffsetJ; j < mapVisibleRows + this.viewOffsetJ; j++) {
                var coor = fac(i, j);
                if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
                    this.drawForegroundTile(coor.x, coor.y, i, j);
                }
            }
        }
    }
};

MapFactory.prototype.drawCursor = function (i, j, cols, rows) {
    var cac = this["cac"];

    cols = isNaN(cols) ? 1 : parseInt(cols);
    rows = isNaN(rows) ? 1 : parseInt(rows);

    if (this["assetCursor"].src && cac && typeof cac === "function") {
        for (var tempI = i; tempI < i + cols; tempI++) {
            for (var tempJ = j; tempJ < j + rows; tempJ++) {
                var coor = cac(tempI, tempJ);
                if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
                    this.drawCursorTile(coor.x, coor.y, tempI, tempJ);
                }
            }
        }
    }
};

MapFactory.prototype.drawBackgroundTile = function (sourceX, sourceY, i, j) {
    var destX = (i - this.viewOffsetI) * this.tileWidth;
    var destY = (j - this.viewOffsetJ) * this.tileHeight;
    var asset = this["assetBackground"];

    this["context"].drawImage(asset,
        sourceX, sourceY, this.tileWidth, this.tileHeight, destX, destY, this.tileWidth, this.tileHeight);
};

MapFactory.prototype.drawForegroundTile = function (sourceX, sourceY, i, j) {
    var destX = (i - this.viewOffsetI) * this.tileWidth;
    var destY = (j - this.viewOffsetJ) * this.tileHeight;
    var asset = this["assetForeground"];
    this["context"].drawImage(asset,
        sourceX, sourceY, this.tileWidth, this.tileHeight, destX, destY, this.tileWidth, this.tileHeight);
};

MapFactory.prototype.drawCursorTile = function (sourceX, sourceY, i, j) {
    var destX = (i - this.viewOffsetI) * this.tileWidth;
    var destY = (j - this.viewOffsetJ) * this.tileHeight;
    var asset = this["assetCursor"];
    this["context"].drawImage(asset,
        sourceX, sourceY, this.tileWidth, this.tileHeight, destX, destY, this.tileWidth, this.tileHeight);
};

MapFactory.prototype.clearTile = function (i, j) {
    var destX = (i - this.viewOffsetI) * this.tileWidth;
    var destY = (j - this.viewOffsetJ) * this.tileHeight;
    this["context"].clearRect(destX, destY, this.tileWidth, this.tileHeight);
};

MapFactory.prototype.restoreTile = function (i, j) {
    var bac = this["bac"];
    var fac = this["fac"];

    var assetBackground = this["assetBackground"];
    var assetForeground = this["assetForeground"];

    this.clearTile(i, j);
    if (assetBackground.src && bac && typeof bac === "function") {
        var coor = bac(i, j);
        if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
            this.drawBackgroundTile(coor.x, coor.y, i, j);
        }
    }
    if (assetForeground.src && fac && typeof fac === "function") {
        var coor = fac(i, j);
        if (coor && typeof coor.x === 'number' && typeof coor.y === 'number') {
            this.drawForegroundTile(coor.x, coor.y, i, j);
        }
    }
}

MapFactory.prototype.update = function () {
    this.updateMapVisibleSize();
    this.drawBackground();
    this.drawForeground();
}
<|endoftext|>


<commit_before>var m = new Buffer([ 0x80, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 ])
  , pa = 3
  , ca = 5
  , sa = 6
  , noop = 0x03

module.exports = {
  command: function (code) {
    m.writeUInt8(code, ca)
    return m
  },
  position: function (number) {
    m.writeUInt8(noop, ca)
    m.writeInt16LE(parseInt(number*100), pa)
    return m
  },
  state: function (number) {
    m.writeUInt8(noop, ca)
    m.writeInt16LE(number, sa)
    return m
  }
}
<commit_msg>Noop fix<commit_after>var m = new Buffer([ 0x80, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00 ])
  , pa = 3
  , ca = 5
  , sa = 6
  , noop = 0x02

module.exports = {
  command: function (code) {
    m.writeUInt8(code, ca)
    return m
  },
  position: function (number) {
    m.writeUInt8(noop, ca)
    m.writeInt16LE(parseInt(number*100), pa)
    return m
  },
  state: function (number) {
    m.writeUInt8(noop, ca)
    m.writeInt16LE(number, sa)
    return m
  }
}
<|endoftext|>


<commit_before>(function() {
	var Metadog = (function() {

		function isEmpty(obj) {
			for (var prop in obj) {
				if (obj.hasOwnProperty(prop))
					return false;
			}
			return true;
		}

		var Metadog = function(options) {
			//options takes in a document tree
			this._document = options;
			this._metadata = {};
			this._metadata.schema = [];
			this._metadata.extra = {};
			this._metadata.extra.errors = [];
		};

		Metadog.prototype.scrape = function scrape() {
			this._fetchOpenGraph();
			this._fetchSchema();
			this._mapToModel();
			return this._metadata;
		};

		Metadog.prototype._checkCanonical = function() {
			var link = this._document.querySelector('link[rel="canonical"]');
			if (link)
				return link.href;
			else
				return false;
		};

		Metadog.prototype._fetchOpenGraph = function() {
			var tags = this._document.querySelectorAll('[property*="og:"]');
			this._openGraphData = {};
			for (var i = 0; i < tags.length; i++) {
				this._openGraphData[tags[i].getAttribute('property')] = tags[i].content;
			}
		};

		Metadog.prototype._fetchSchema = function() {
			this._schemaData = {};
			function setProps(set) {
				for (var i = 0; i < set.length; i++) {
					var itemprop = set[i].getAttribute('itemprop');
					if (this._schemaData[itemprop]){
						itemprop = set[i].getAttribute('itemprop') + i;
					}
					if (set[i].getAttribute('content')) {
						this._schemaData[itemprop] = set[i].getAttribute('content');
					} else if (set[i].getAttribute('href') || set[i].getAttribute('src')) {

						this._schemaData[itemprop] = set[i].href? set[i].href: set[i].src;
					} else {
						this._schemaData[itemprop] = set[i].textContent;
					}
				}
			}
			var itemprops = this._document.querySelectorAll('[itemprop]');
			setProps.call(this, itemprops);
		};

		Metadog.prototype._mapToModel = function() {

			function setParam(ogParam, schemaParam, metaParam, optional) {
				if (!optional) {
					if (opengraph && this._openGraphData[ogParam]) {
						this._metadata[metaParam] = this._openGraphData[ogParam];
					} else if (schema && this._schemaData[schemaParam]) {
							this._metadata[metaParam] = this._schemaData[schemaParam];
					} else {
						this._metadata.extra.errors.push(metaParam + ' not found');
					}
				} else {
					if (opengraph && this._openGraphData[ogParam]) {
						this._metadata.extra[metaParam] = this._openGraphData[ogParam];
					} else if (schema && this._schemaData[schemaParam]) {
						this._metadata.extra[metaParam] = this._schemaData[schemaParam];
					} else {
						this._metadata.extra.errors.push(metaParam + ' not found');
					}
				}
			}

			var opengraph = false;
			var schema = false;

			if (!isEmpty(this._openGraphData)) {
				this._metadata.schema.push(0);
				opengraph = true;
			}

			if (!isEmpty(this._schemaData)) {
				this._metadata.schema.push(1);
				schema = true;
			}

			if (this._checkCanonical() ){
				this._metadata.url = this._checkCanonical();
			} else if (opengraph) {
				this._metadata.url = this._openGraphData['og:url'];
			} else if (schema) {
				this._metadata.url = this._schemaData.url;
			} else {
				this._metadata.extra.errors.push('url not found');
			}

			//get base parameters
			setParam.apply(this, ['og:title', 'name', 'name']);
			setParam.apply(this, ['og:description', 'description', 'description']);
			setParam.apply(this, ['og:image', 'image', 'image']);
			setParam.apply(this, ['og:type', 'type', 'type']);

			//get extra parameters
			setParam.apply(this, ['og:price', 'price', 'price', true]);
			setParam.apply(this, ['og:priceCurrency', 'priceCurrency', 'priceCurrency', true]);
			setParam.apply(this, ['og:availability', 'availability', 'availability', true]);
		};

		Metadog.prototype._deepCompare = function(proposed, current) {
			//TODO: currently checks against values directly. Need to implement check for Array types and Object types
			//Objects will have the same method called on them recursively
			function isEqual(arr1, arr2) {
				if(arr1.length !== arr2.length)
					return false;
				arr1.sort();
				arr2.sort();
				for(var j = 0; j < arr1.length; j++) {
					if(arr2[j].constructor === Array) {
						isEqual(arr1[j], arr2[j]);
					} else if(arr2.indexOf(arr1[j]) < 0) {
						return false;
					}
				}
				return true;
			}
			var proposedProps = Object.getOwnPropertyNames(proposed);
			var currentProps = Object.getOwnPropertyNames(current);

			if (proposedProps.length !== currentProps.length)
				return false;

			for(var i = 0; i < proposedProps.length; i++) {
				var ignored = ['created', 'updated', 'ip', 'brand'];
				var propToCheck = proposedProps[i];
				//skips over ignored properties
				if (ignored.indexOf(propToCheck) > 0 ) {
					continue;
				}
				var prop1 = proposed[propToCheck];
				var prop2 = current[propToCheck];
				if(prop1.constructor === Array) {
					if (!isEqual(prop1, prop2))
						return false;
				} else if (typeof prop1 === "object") {
					if (this._deepCompare(prop1, prop2)){
						continue;
					} else {
						return false;
					}
				} else if(prop1 !== prop2) {
					return false;
				}
			}
			return true;
		};

		return Metadog;

	})();

	if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
		// Check for Node.js
		module.exports = Metadog;
	} else {
		//  For AMD Support.
		if (typeof define === 'function' && define.amd) {
			define([], function() {

				return Metadog;
			});
		} else {

			// Export to the window scope, for Browser Support.
			window.Metadog = Metadog;
		}
	}
})();
<commit_msg>Adjusting deepCompare function to take a ananymous function as filters parameter<commit_after>(function() {
	var Metadog = (function() {

		function isEmpty(obj) {
			for (var prop in obj) {
				if (obj.hasOwnProperty(prop))
					return false;
			}
			return true;
		}

		var Metadog = function(document) {
			//options takes in a document tree
			this._document = document;
			this._metadata = {};
			this._metadata.schema = [];
			this._metadata.extra = {};
			this._metadata.extra.errors = [];
		};

		Metadog.prototype.scrape = function scrape() {
			this._fetchOpenGraph();
			this._fetchSchema();
			this._mapToModel();
			return this._metadata;
		};

		Metadog.prototype._checkCanonical = function() {
			var link = this._document.querySelector('link[rel="canonical"]');
			if (link)
				return link.href;
			else
				return false;
		};

		Metadog.prototype._fetchOpenGraph = function() {
			var tags = this._document.querySelectorAll('[property*="og:"]');
			this._openGraphData = {};
			for (var i = 0; i < tags.length; i++) {
				this._openGraphData[tags[i].getAttribute('property')] = tags[i].content;
			}
		};

		Metadog.prototype._fetchSchema = function() {
			this._schemaData = {};
			function setProps(set) {
				for (var i = 0; i < set.length; i++) {
					var itemprop = set[i].getAttribute('itemprop');
					if (this._schemaData[itemprop]){
						itemprop = set[i].getAttribute('itemprop') + i;
					}
					if (set[i].getAttribute('content')) {
						this._schemaData[itemprop] = set[i].getAttribute('content');
					} else if (set[i].getAttribute('href') || set[i].getAttribute('src')) {

						this._schemaData[itemprop] = set[i].href? set[i].href: set[i].src;
					} else {
						this._schemaData[itemprop] = set[i].textContent;
					}
				}
			}
			var itemprops = this._document.querySelectorAll('[itemprop]');
			setProps.call(this, itemprops);
		};

		Metadog.prototype._mapToModel = function() {

			function setParam(ogParam, schemaParam, metaParam, optional) {
				if (!optional) {
					if (opengraph && this._openGraphData[ogParam]) {
						this._metadata[metaParam] = this._openGraphData[ogParam];
					} else if (schema && this._schemaData[schemaParam]) {
							this._metadata[metaParam] = this._schemaData[schemaParam];
					} else {
						this._metadata.extra.errors.push(metaParam + ' not found');
					}
				} else {
					if (opengraph && this._openGraphData[ogParam]) {
						this._metadata.extra[metaParam] = this._openGraphData[ogParam];
					} else if (schema && this._schemaData[schemaParam]) {
						this._metadata.extra[metaParam] = this._schemaData[schemaParam];
					} else {
						this._metadata.extra.errors.push(metaParam + ' not found');
					}
				}
			}

			var opengraph = false;
			var schema = false;

			if (!isEmpty(this._openGraphData)) {
				this._metadata.schema.push(0);
				opengraph = true;
			}

			if (!isEmpty(this._schemaData)) {
				this._metadata.schema.push(1);
				schema = true;
			}

			if (this._checkCanonical() ){
				this._metadata.url = this._checkCanonical();
			} else if (opengraph) {
				this._metadata.url = this._openGraphData['og:url'];
			} else if (schema) {
				this._metadata.url = this._schemaData.url;
			} else {
				this._metadata.extra.errors.push('url not found');
			}

			//get base parameters
			setParam.apply(this, ['og:title', 'name', 'name']);
			setParam.apply(this, ['og:description', 'description', 'description']);
			setParam.apply(this, ['og:image', 'image', 'image']);
			setParam.apply(this, ['og:type', 'type', 'type']);

			//get extra parameters
			setParam.apply(this, ['og:price', 'price', 'price', true]);
			setParam.apply(this, ['og:priceCurrency', 'priceCurrency', 'priceCurrency', true]);
			setParam.apply(this, ['og:availability', 'availability', 'availability', true]);
		};

		Metadog.prototype._isEqual = function(arr1, arr2) {
			if(arr1.length !== arr2.length)
				return false;
			arr1.sort();
			arr2.sort();
			for(var j = 0; j < arr1.length; j++) {
				if(arr2[j].constructor === Array) {
					this._isEqual(arr1[j], arr2[j]);
				} else if(arr2.indexOf(arr1[j]) < 0) {
					return false;
				}
			}
			return true;
		};

		Metadog.prototype._filter = function(propToCheck) {
			// List of fields to ignore.
			var ignored = ['created', 'updated', 'ip', 'brand'];

			// Check the data passed in to see if we need to ignore that field.
			return (ignored.indexOf(propToCheck) > 0 );
		};

		/**
		 * Internal deep compare method.
		 *
		 * @param proposed
		 * @param current
		 * @param comparator
		 * @param filters
		 * @returns {Boolean}
		 */
		Metadog.prototype._deepCompare = function(proposed, current, comparator, filters) {
			//TODO: currently checks against values directly. Need to implement check for Array types and Object types
			//Objects will have the same method called on them recursively
			var proposedProps = Object.getOwnPropertyNames(proposed);
			var currentProps = Object.getOwnPropertyNames(current);

			if (proposedProps.length !== currentProps.length)
				return false;

			for(var i = 0; i < proposedProps.length; i++) {

				var propToCheck = proposedProps[i];
				//skips over ignored properties
				if (filters(propToCheck))
					continue;

				var prop1 = proposed[propToCheck];
				var prop2 = current[propToCheck];
				if(prop1.constructor === Array) {
					if (!comparator(prop1, prop2))
						return false;
				}
				else if (typeof prop1 === "object") {
					if (this._deepCompare(prop1, prop2, comparator, filters)){
						continue;
					}
					else {
						return false;
					}
				}
				else if(prop1 !== prop2) {
					return false;
				}
			}
			return true;
		};

		/**
		 * This method performs a deep compare between two objects.
		 * If comparator and/or filter parameters are not set, then the default class comparator object _isEqual is used
		 * and the default class filter object _filter is used.
		 *
		 * @method deepCompare
		 * @param {Object} proposed New Object to compare
		 * @param {Object} current Current (or old) object to compare
		 * @param {Function} comparator Function that performs the comparing
		 * @param {Function} filters Function the performs filtering on fields to ignore
		 * @returns {Boolean}
		 */
		Metadog.prototype.deepCompare = function(proposed, current, comparator, filters) {
			// We need to make sure that comparator and filters is set as an object Function.
			var theFilterType = {};
			var myComparator = this._isEqual;
			var myFilters = this._filter;

			if (comparator && theFilterType.toString.call(comparator) === '[object Function]') {
				myComparator = comparator;
			}

			if (filters && theFilterType.toString.call(filters) === '[object Function]') {
				myFilters = filters;
			}

			return this._deepCompare(proposed, current, myComparator, myFilters);
		};

		return Metadog;

	})();

	if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
		// Check for Node.js
		module.exports = Metadog;
	} else {
		//  For AMD Support.
		if (typeof define === 'function' && define.amd) {
			define([], function() {

				return Metadog;
			});
		} else {

			// Export to the window scope, for Browser Support.
			window.Metadog = Metadog;
		}
	}
})();
<|endoftext|>


<commit_before>#! /usr/bin/env node

var logger = require('./logger.js');
var Migrator = require("./lib/Migrator.js");
logger.log('info', "Creating new migrator");
var migrator = new Migrator();
//migrator.migrateCGH("/home/massi/Projects/aCGH/FileBIT",".xlsx")
migrator.migrateAllSubjects()
//migrator.migrateCompleteSubject(5)
.then(function() {
    logger.log('info', 'migrate: done!');
})
.catch(function(err) {
    logger.log('error', err);
});
<commit_msg>added exit code to process<commit_after>#! /usr/bin/env node

var logger = require('./logger.js');
var Migrator = require("./lib/Migrator.js");
logger.log('info', "Creating new migrator");
var migrator = new Migrator();
//migrator.migrateCGH("/home/massi/Projects/aCGH/FileBIT",".xlsx")
migrator.migrateAllSubjects()
//migrator.migrateCompleteSubject(5)
.then(function() {
    logger.log('info', 'migrate: done!');
    process.exit(0);
})
.catch(function(err) {
    logger.log('error', err);
    process.exit(1);
});
<|endoftext|>


<commit_before>/*
 *  Modular - JavaScript AMD framework
 *  Copyright (c) 2012 http://ovms.co. All Rights Reserved.
 *
 *  ====
 *
 *  This file is part of Modular.
 *
 *  Modular is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Modular is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Modular.  If not, see <http://www.gnu.org/licenses/>.
 */

/*global define, require */

(function () {
    "use strict";

    var global = new Function("return this;")(),
        defaults = {},
        pendings = {},
        modules = {};

    function each(obj, callback) {
        var key;

        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                callback.call(obj[key], obj[key], key);
            }
        }

        return obj;
    }

    function extend(target) {
        each([].slice.call(arguments, 1), function () {
            each(this, function (val, key) {
                target[key] = val;
            });
        });

        return target;
    }

    function getType(obj) {
        return {}.toString.call(obj).match(/\[object ([\s\S]*)\]/)[1];
    }

    function isString(str) {
        return typeof str === "string" || getType(str) === "String";
    }

    function isPlainObject(obj) {
        return getType(obj) === "Object";
    }

    function isArray(str) {
        return getType(str) === "Array";
    }

    function isFunction(str) {
        return getType(str) === "Function";
    }

    function getBasePath(path) {
        path = path.replace(/[^\/]+$/, "");

        if (path.charAt(path.length - 1) !== "/") {
            path += "/";
        }

        return path;
    }

    function makePath(path1, path2, pathMappings) {
        var path,
            previousPath = "",
            components = path2.split("/");

        each(pathMappings || {}, function (to, from) {
            if (components[0] === from) {
                components[0] = to;
            }
        });

        path2 = components.join("/");

        path = getBasePath(path1) + path2;

        path = path.replace(/\/\.\//g, "/"); // Resolve same-directory symbols

        // Resolve parent-directory symbols
        while (previousPath !== path) {
            previousPath = path;
            path = path.replace(/[^\/]*\/\.\.\//, "");
        }

        // Append implicit ".js" extension
        if (path.substr(path.length - 3) !== ".js") {
            path += ".js";
        }

        return path;
    }

    function parse(arg1, arg2, arg3, arg4) {
        var config = {},
            path = null,
            dependencies = [],
            closure = function () {};

        if (isPlainObject(arg1)) {
            config = arg1;
        } else if (isString(arg1)) {
            path = arg1;
        } else if (isArray(arg1)) {
            dependencies = arg1;
        } else if (isFunction(arg1)) {
            closure = arg1;
        }

        if (isString(arg2)) {
            path = arg2;
        } else if (isArray(arg2)) {
            dependencies = arg2;
        } else if (isFunction(arg2)) {
            closure = arg2;
        }

        if (isArray(arg3)) {
            dependencies = arg3;
        } else if (isFunction(arg3)) {
            closure = arg3;
        }

        if (isFunction(arg4)) {
            closure = arg4;
        }

        config = extend({}, defaults, config);

        return {
            config: config,
            path: path,
            dependencies: dependencies,
            closure: closure
        };
    }

    function ready(config, path, dependencies, closure) {
        var fetched = false;

        function allDependenciesLoaded() {
            var moduleValue = null;

            function processDependents() {
                var callbacks;

                modules[path] = moduleValue;

                if (pendings[path]) {
                    callbacks = pendings[path];

                    delete pendings[path];

                    each(callbacks, function (dependencyLoaded) {
                        dependencyLoaded();
                    });
                }
            }

            function evaluateModule() {
                var args = [];

                each(dependencies, function (dependencyPath) {
                    var fullPath = makePath(path, dependencyPath, config.paths);

                    if (dependencyPath === "require") {
                        // TODO: Scoped require
                        args.push(function (arg1, arg2, arg3, arg4) {
                            var args = parse(arg1, arg2, arg3, arg4);

                            global.require(extend({}, args.config, {
                                baseUrl: path
                            }), args.path, args.dependencies, args.closure);
                        });
                    } else {
                        args.push(modules[dependencyPath] || modules[fullPath]);
                    }
                });

                return closure.apply(global, args);
            }

            moduleValue = evaluateModule();

            if (path) {
                // Modules may have no path (eg. an anonymous require(...))
                processDependents();
            }
        }

        function checkDependencies() {
            var allResolved = true;

            each(dependencies, function (dependencyPath) {
                var fullPath = makePath(path, dependencyPath, config.paths);

                if (dependencyPath !== "require" && !modules[dependencyPath] && !modules[fullPath]) {
                    if (!fetched) {
                        if (!pendings[fullPath]) {
                            pendings[fullPath] = [];

                            config.fetch(fullPath, ready);
                        }

                        pendings[fullPath].push(checkDependencies);
                    }

                    allResolved = false;
                }
            });

            fetched = true;

            if (allResolved) {
                allDependenciesLoaded();
            }
        }

        checkDependencies();
    }

    // Exports
    global.require = function (arg1, arg2, arg3, arg4) {
        var args = parse(arg1, arg2, arg3, arg4);

        ready(args.config, args.path || args.config.baseUrl, args.dependencies, args.closure);
    };
    global.define = function (arg1, arg2, arg3, arg4) {
        var args = parse(arg1, arg2, arg3, arg4);

        if (args.path) {
            ready(args.config, args.path, args.dependencies, args.closure);
        } else {
            args.config.anonymous(args);
        }
    };

    // Publish support for the AMD pattern
    global.define.amd = {
        jQuery: true
    };

    extend(defaults, (function () {
        var head = global.document.getElementsByTagName("head")[0],
            anonymouses = [];

        return {
            baseUrl: global.location.pathname,
            // Overridable - called when a module needs to be loaded
            fetch: function fetch(path, ready) {
                var script = global.document.createElement("script");

                script.setAttribute("type", "text/javascript");
                script.setAttribute("src", path);

                script.onload = script.onreadystatechange = function () {
                    var args;

                    if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
                        args = anonymouses.pop();

                        ready(args.config, args.path || path, args.dependencies, args.closure);
                    }

                    script.onload = script.onreadystatechange = null;
                };

                head.insertBefore(script, head.firstChild);
            },
            anonymous: function (args) {
                anonymouses.push(args);
            }
        };
    }()));
}());
<commit_msg>Cleaned up commenting<commit_after>/*
 *  Modular - JavaScript AMD framework
 *  Copyright (c) 2012 http://ovms.co. All Rights Reserved.
 *
 *  ====
 *
 *  This file is part of Modular.
 *
 *  Modular is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Modular is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Modular.  If not, see <http://www.gnu.org/licenses/>.
 */

/*global define, require */

(function () {
    "use strict";

    var global = new Function("return this;")(),
        defaults = {},
        pendings = {},
        modules = {};

    function each(obj, callback) {
        var key;

        for (key in obj) {
            if (obj.hasOwnProperty(key)) {
                callback.call(obj[key], obj[key], key);
            }
        }

        return obj;
    }

    function extend(target) {
        each([].slice.call(arguments, 1), function () {
            each(this, function (val, key) {
                target[key] = val;
            });
        });

        return target;
    }

    function getType(obj) {
        return {}.toString.call(obj).match(/\[object ([\s\S]*)\]/)[1];
    }

    function isString(str) {
        return typeof str === "string" || getType(str) === "String";
    }

    function isPlainObject(obj) {
        return getType(obj) === "Object";
    }

    function isArray(str) {
        return getType(str) === "Array";
    }

    function isFunction(str) {
        return getType(str) === "Function";
    }

    function getBasePath(path) {
        path = path.replace(/[^\/]+$/, "");

        if (path.charAt(path.length - 1) !== "/") {
            path += "/";
        }

        return path;
    }

    function makePath(path1, path2, pathMappings) {
        var path,
            previousPath = "",
            components = path2.split("/");

        each(pathMappings || {}, function (to, from) {
            if (components[0] === from) {
                components[0] = to;
            }
        });

        path2 = components.join("/");

        path = getBasePath(path1) + path2;

        path = path.replace(/\/\.\//g, "/"); // Resolve same-directory symbols

        // Resolve parent-directory symbols
        while (previousPath !== path) {
            previousPath = path;
            path = path.replace(/[^\/]*\/\.\.\//, "");
        }

        // Append implicit ".js" extension
        if (path.substr(path.length - 3) !== ".js") {
            path += ".js";
        }

        return path;
    }

    function parse(arg1, arg2, arg3, arg4) {
        var config = {},
            path = null,
            dependencies = [],
            closure = function () {};

        if (isPlainObject(arg1)) {
            config = arg1;
        } else if (isString(arg1)) {
            path = arg1;
        } else if (isArray(arg1)) {
            dependencies = arg1;
        } else if (isFunction(arg1)) {
            closure = arg1;
        }

        if (isString(arg2)) {
            path = arg2;
        } else if (isArray(arg2)) {
            dependencies = arg2;
        } else if (isFunction(arg2)) {
            closure = arg2;
        }

        if (isArray(arg3)) {
            dependencies = arg3;
        } else if (isFunction(arg3)) {
            closure = arg3;
        }

        if (isFunction(arg4)) {
            closure = arg4;
        }

        config = extend({}, defaults, config);

        return {
            config: config,
            path: path,
            dependencies: dependencies,
            closure: closure
        };
    }

    function ready(config, path, dependencies, closure) {
        var fetched = false;

        function allDependenciesLoaded() {
            var moduleValue = null;

            function processDependents() {
                var callbacks;

                modules[path] = moduleValue;

                if (pendings[path]) {
                    callbacks = pendings[path];

                    delete pendings[path];

                    each(callbacks, function (dependencyLoaded) {
                        dependencyLoaded();
                    });
                }
            }

            function evaluateModule() {
                var args = [];

                each(dependencies, function (dependencyPath) {
                    var fullPath = makePath(path, dependencyPath, config.paths);

                    // Scoped require support
                    if (dependencyPath === "require") {
                        args.push(function (arg1, arg2, arg3, arg4) {
                            var args = parse(arg1, arg2, arg3, arg4);

                            global.require(extend({}, args.config, {
                                baseUrl: path
                            }), args.path, args.dependencies, args.closure);
                        });
                    } else {
                        args.push(modules[dependencyPath] || modules[fullPath]);
                    }
                });

                return closure.apply(global, args);
            }

            moduleValue = evaluateModule();

            if (path) {
                // Modules may have no path (eg. an anonymous require(...))
                processDependents();
            }
        }

        function checkDependencies() {
            var allResolved = true;

            each(dependencies, function (dependencyPath) {
                var fullPath = makePath(path, dependencyPath, config.paths);

                if (dependencyPath !== "require" && !modules[dependencyPath] && !modules[fullPath]) {
                    if (!fetched) {
                        if (!pendings[fullPath]) {
                            pendings[fullPath] = [];

                            config.fetch(fullPath, ready);
                        }

                        pendings[fullPath].push(checkDependencies);
                    }

                    allResolved = false;
                }
            });

            fetched = true;

            if (allResolved) {
                allDependenciesLoaded();
            }
        }

        checkDependencies();
    }

    // Exports
    global.require = function (arg1, arg2, arg3, arg4) {
        var args = parse(arg1, arg2, arg3, arg4);

        ready(args.config, args.path || args.config.baseUrl, args.dependencies, args.closure);
    };
    global.define = function (arg1, arg2, arg3, arg4) {
        var args = parse(arg1, arg2, arg3, arg4);

        if (args.path) {
            ready(args.config, args.path, args.dependencies, args.closure);
        } else {
            args.config.anonymous(args);
        }
    };

    // Publish support for the AMD pattern
    global.define.amd = {
        jQuery: true
    };

    extend(defaults, (function () {
        var head = global.document.getElementsByTagName("head")[0],
            anonymouses = [];

        return {
            baseUrl: global.location.pathname,
            // Overridable - called when a module needs to be loaded
            fetch: function fetch(path, ready) {
                var script = global.document.createElement("script");

                script.setAttribute("type", "text/javascript");
                script.setAttribute("src", path);

                script.onload = script.onreadystatechange = function () {
                    var args;

                    if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
                        args = anonymouses.pop();

                        ready(args.config, args.path || path, args.dependencies, args.closure);
                    }

                    script.onload = script.onreadystatechange = null;
                };

                head.insertBefore(script, head.firstChild);
            },
            anonymous: function (args) {
                anonymouses.push(args);
            }
        };
    }()));
}());
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Re-Pagination, based on Paste-and-Go.
 *
 * The Initial Developer of the Original Code is Nils Maier.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *  Jens Bannmann <jens.b@web.de>
 *  Oliver Aeberhard <aeberhard@gmx.ch>
 *  Nils Maier <maierman@web.de>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

const EXPORTED_SYMBOLS = ['AntiPagination'];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const reportError = Cu.reportError;

const regxNumber = /[0-9]+/;
const regx2Numbers = /[0-9]+[^0-9][0-9]+/;

function getFirstSnapshot(doc,node,query) doc
	.evaluate(query, node, null, 7, null)
	.snapshotItem(0);

if (!'setTimeout' in this) {
	let Timer = Components.Constructor('@mozilla.org/timer;1', 'nsITimer', 'init');
	this.setTimeout = function(fun, timeout) new Timer({observe: function() fun()}, timeout, 0);
}

function AntiPagination(window) {
	var document = window.document;

	function $(id) document.getElementById(id);

	var antipagination = {
		blast: function(num,isslide) {
			var focusElement = document.commandDispatcher.focusedElement;
			if (focusElement == null) {
				throw new Error("No focus element");
			}
			var doc = focusElement.ownerDocument;
			var repaginator = new Repaginator();

			if(isslide != null && num != null) {
				repaginator.seconds = num;
				repaginator.slideshow = true;
				repaginator.nolimit = true;
			}
			else if(num != null) {
				repaginator.slideshow = false;
				repaginator.pagelimit = num;
				repaginator.nolimit = false;
			}
			else {
				repaginator.slideshow = false;
				repaginator.nolimit = true;
			}
			var searchpathtext = '';
			var range = doc.createRange();
			range.selectNode(focusElement);
			searchpathtext = range.toString();

			repaginator.query = '//body';
			if (searchpathtext) {
				repaginator.query = '//a[.=\''+searchpathtext+'\'][position()=last()]';
			}
			else {
				if (focusElement.getAttribute('value'))	{
					var input_value = focusElement.getAttribute('value');

					if (input_value) {
						repaginator.query = '//input[@value=\''+input_value+'\'][position()=last()]/ancestor::a';
					}
				}
				else if (focusElement.getAttribute('src')) {
					var img_src = focusElement.getAttribute('src');

					if (img_src)	{
						repaginator.query = '//img[@src=\''+img_src+'\'][position()=last()]/ancestor::a';
					}
				}
				else if (focusElement instanceof window.HTMLAnchorElement) {
					var srcObj = getFirstSnapshot(doc, focusElement, 'child::*[@src]');
					if (srcObj) {
						var img_src = srcObj.getAttribute('src');
						if (img_src) {
							repaginator.query = '//img[@src=\''+img_src+'\'][position()=last()]/ancestor::a';
						}
					}
				}
			}

			repaginator.numberToIncrement = null;
			repaginator.attemptToIncrement = false;

			if (!regx2Numbers.test(repaginator.query))	{
				var test = regxNumber.exec(repaginator.query);
				if (test)	{
					repaginator.attemptToIncrement = true;
					repaginator.numberToIncrement = test[0];
				}
			}

			repaginator.blast(doc.defaultView);
		},

		stop: function() {
			if(window.gContextMenu == null
				|| window.gContextMenu.target == null) {
				var body = window._content.document.getElementsByTagName('body')[0];
				if(body != null) {
					body.setAttribute('antipagination','isOff');
				}
			}
			else {
				var doc = window.gContextMenu.target.ownerDocument;
				var body = doc.getElementsByTagName('body')[0];

				if(body != null) {
					body.setAttribute('antipagination','isOff');
				}
			}
		}
	};

	let menu = $('antipagination_menu');
	let contextMenu = $('contentAreaContextMenu');
	contextMenu.addEventListener('popupshowing', function() {
		if (window.gContextMenu.onLink) {
			menu.hidden = false;
			return;
		}

		var doc = window.gContextMenu.target.ownerDocument;
		var body = doc.getElementsByTagName('body')[0];
		if (!body) {
			menu.hidden = true;
			return;
		}

		var result = body.getAttribute('antipagination');
		if (!result) {
			menu.hidden = true;
			return;
		}
		if(result == 'isOn') {
			menu.hidden = false;
			return;
		}
		menu.hidden = true;
	}, true);

	return antipagination;
}

function Repaginator() {}
Repaginator.prototype = {
	enabled: false,
	pagecounter: 0,
	beforeNum: '',
	afterNum: '',
	numStr: '',
	isSelect: true,

	// Get last item in a container
	getLast: function(container) {
		var item =  container.iterateNext();
		var temp = item;
		while(temp != null) {
			temp = container.iterateNext();
			if(temp != null) {
				item = temp;
			}
		}
		return item;
	},

	blast: function(win) {
		try	{
			var xresult = win.document.evaluate(
				this.query,
				win.document,
				null,
				0,
				null
				);
			var node = this.getLast(xresult);
			if (node == null) {
				throw new Error("No node");
			}

			win.document.body.setAttribute('antipagination','isOn');

			var iframe = win.document.createElement('iframe');
			iframe.style.display = 'none';
			iframe.setAttribute('src',node.href);
			let self = this;
			iframe.addEventListener('load', function(event) {
				this.removeEventListener('load', arguments.callee, true);
				self.loadNext(this);
			}, true);
			win.document.body.setAttribute('antipagination','isOn');
			win.document.body.appendChild(iframe);
		}
		catch(ex) {
			win.document.body.setAttribute('antipagination','isOff');
			reportError(ex);
		}
	},

	increment: function() {
		this.query = this.query.replace(
			new RegExp(this.numberToIncrement, 'g'),
			new Number(this.numberToIncrement) + 1
			);
		this.numberToIncrement++;
	},

	// Append all children of source to target
	appendChildren: function(source, target) {
		for (var child = source.firstChild; child != null; child = child.nextSibling)	{
			target.appendChild(child.cloneNode(true));
		}
	},
	loadNext: function(element) {
		try {
			let ownerDoc = element.ownerDocument;
			if (ownerDoc.body.getAttribute('antipagination') != 'isOn')	{
				throw new Error("Not running");
			}

			var doc = element.contentDocument;
			this.pagecounter++;

			if (this.slideshow) {
				ownerDoc.body.style.display = 'none';
				var cloner = doc.body.cloneNode(true);
				ownerDoc.documentElement.appendChild(cloner);
				ownerDoc.body = cloner;
				ownerDoc.body.setAttribute('antipagination', 'isOn');
			}
			else {
				this.appendChildren(doc.body, ownerDoc.body);
			}

			var savedQuery;
			if (this.attemptToIncrement) {
				savedQuery = this.query;
				this.increment();
			}
			else if (this.numberToIncrement != null) {
				this.increment();
			}

			let xresult = doc.evaluate(
				this.query,
				doc,
				null,
				0,
				null
				);

			let node = this.getLast(xresult);

			let location = (doc.location || {}).href || null;

			if (this.attemptToIncrement
				&& (!node || node.href == location)) {
				this.query = savedQuery;
				this.numberToIncrement = null;

				xresult = doc.evaluate(
					this.query,
					doc,
					null,
					0,
					null
					);
				node = this.getLast(xresult);
			}

			this.attemptToIncrement = false;

			if (!node) {
				throw new Error("No next node found");
			}
			if (location && location == node.href) {
				throw new Error("Location match (nothing new): " + location + ", " + node.href);
			}

			if (!this.nolimit && this.pagecounter >= this.pagelimit) {
				throw new Error("Done");
			}

			var niframe = ownerDoc.createElement('iframe');
			niframe.style.display = 'none';
			niframe.setAttribute('src', node.href);

			let self = this;
			niframe.addEventListener('load',function() {
				this.removeEventListener('load', arguments.callee, true);
				if(self.slideshow) {
					setTimeout(function() self.loadNext(niframe), self.seconds * 1000);
				}
				else {
					self.loadNext(this);
				}
			}, true);

			ownerDoc.body.appendChild(niframe);
		}
		catch (ex) {
			ownerDoc.body.setAttribute('antipagination','isOff');
			reportError(ex);
		}

		// kill the frame again
		setTimeout(function() element.parentNode.removeChild(element), 0);
	}
};<commit_msg>Use .content instead of ._content<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Re-Pagination, based on Paste-and-Go.
 *
 * The Initial Developer of the Original Code is Nils Maier.
 * Portions created by the Initial Developer are Copyright (C) 2010
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *  Jens Bannmann <jens.b@web.de>
 *  Oliver Aeberhard <aeberhard@gmx.ch>
 *  Nils Maier <maierman@web.de>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

const EXPORTED_SYMBOLS = ['AntiPagination'];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const reportError = Cu.reportError;

const regxNumber = /[0-9]+/;
const regx2Numbers = /[0-9]+[^0-9][0-9]+/;

function getFirstSnapshot(doc,node,query) doc
	.evaluate(query, node, null, 7, null)
	.snapshotItem(0);

if (!'setTimeout' in this) {
	let Timer = Components.Constructor('@mozilla.org/timer;1', 'nsITimer', 'init');
	this.setTimeout = function(fun, timeout) new Timer({observe: function() fun()}, timeout, 0);
}

function AntiPagination(window) {
	var document = window.document;

	function $(id) document.getElementById(id);

	var antipagination = {
		blast: function(num,isslide) {
			var focusElement = document.commandDispatcher.focusedElement;
			if (focusElement == null) {
				throw new Error("No focus element");
			}
			var doc = focusElement.ownerDocument;
			var repaginator = new Repaginator();

			if(isslide != null && num != null) {
				repaginator.seconds = num;
				repaginator.slideshow = true;
				repaginator.nolimit = true;
			}
			else if(num != null) {
				repaginator.slideshow = false;
				repaginator.pagelimit = num;
				repaginator.nolimit = false;
			}
			else {
				repaginator.slideshow = false;
				repaginator.nolimit = true;
			}
			var searchpathtext = '';
			var range = doc.createRange();
			range.selectNode(focusElement);
			searchpathtext = range.toString();

			repaginator.query = '//body';
			if (searchpathtext) {
				repaginator.query = '//a[.=\''+searchpathtext+'\'][position()=last()]';
			}
			else {
				if (focusElement.getAttribute('value'))	{
					var input_value = focusElement.getAttribute('value');

					if (input_value) {
						repaginator.query = '//input[@value=\''+input_value+'\'][position()=last()]/ancestor::a';
					}
				}
				else if (focusElement.getAttribute('src')) {
					var img_src = focusElement.getAttribute('src');

					if (img_src)	{
						repaginator.query = '//img[@src=\''+img_src+'\'][position()=last()]/ancestor::a';
					}
				}
				else if (focusElement instanceof window.HTMLAnchorElement) {
					var srcObj = getFirstSnapshot(doc, focusElement, 'child::*[@src]');
					if (srcObj) {
						var img_src = srcObj.getAttribute('src');
						if (img_src) {
							repaginator.query = '//img[@src=\''+img_src+'\'][position()=last()]/ancestor::a';
						}
					}
				}
			}

			repaginator.numberToIncrement = null;
			repaginator.attemptToIncrement = false;

			if (!regx2Numbers.test(repaginator.query))	{
				var test = regxNumber.exec(repaginator.query);
				if (test)	{
					repaginator.attemptToIncrement = true;
					repaginator.numberToIncrement = test[0];
				}
			}

			repaginator.blast(doc.defaultView);
		},

		stop: function() {
			if(window.gContextMenu == null
				|| window.gContextMenu.target == null) {
				var body = window.content.document.getElementsByTagName('body')[0];
				if(body != null) {
					body.setAttribute('antipagination','isOff');
				}
			}
			else {
				var doc = window.gContextMenu.target.ownerDocument;
				var body = doc.getElementsByTagName('body')[0];

				if(body != null) {
					body.setAttribute('antipagination','isOff');
				}
			}
		}
	};

	let menu = $('antipagination_menu');
	let contextMenu = $('contentAreaContextMenu');
	contextMenu.addEventListener('popupshowing', function() {
		if (window.gContextMenu.onLink) {
			menu.hidden = false;
			return;
		}

		var doc = window.gContextMenu.target.ownerDocument;
		var body = doc.getElementsByTagName('body')[0];
		if (!body) {
			menu.hidden = true;
			return;
		}

		var result = body.getAttribute('antipagination');
		if (!result) {
			menu.hidden = true;
			return;
		}
		if(result == 'isOn') {
			menu.hidden = false;
			return;
		}
		menu.hidden = true;
	}, true);

	return antipagination;
}

function Repaginator() {}
Repaginator.prototype = {
	enabled: false,
	pagecounter: 0,
	beforeNum: '',
	afterNum: '',
	numStr: '',
	isSelect: true,

	// Get last item in a container
	getLast: function(container) {
		var item =  container.iterateNext();
		var temp = item;
		while(temp != null) {
			temp = container.iterateNext();
			if(temp != null) {
				item = temp;
			}
		}
		return item;
	},

	blast: function(win) {
		try	{
			var xresult = win.document.evaluate(
				this.query,
				win.document,
				null,
				0,
				null
				);
			var node = this.getLast(xresult);
			if (node == null) {
				throw new Error("No node");
			}

			win.document.body.setAttribute('antipagination','isOn');

			var iframe = win.document.createElement('iframe');
			iframe.style.display = 'none';
			iframe.setAttribute('src',node.href);
			let self = this;
			iframe.addEventListener('load', function(event) {
				this.removeEventListener('load', arguments.callee, true);
				self.loadNext(this);
			}, true);
			win.document.body.setAttribute('antipagination','isOn');
			win.document.body.appendChild(iframe);
		}
		catch(ex) {
			win.document.body.setAttribute('antipagination','isOff');
			reportError(ex);
		}
	},

	increment: function() {
		this.query = this.query.replace(
			new RegExp(this.numberToIncrement, 'g'),
			new Number(this.numberToIncrement) + 1
			);
		this.numberToIncrement++;
	},

	// Append all children of source to target
	appendChildren: function(source, target) {
		for (var child = source.firstChild; child != null; child = child.nextSibling)	{
			target.appendChild(child.cloneNode(true));
		}
	},
	loadNext: function(element) {
		try {
			let ownerDoc = element.ownerDocument;
			if (ownerDoc.body.getAttribute('antipagination') != 'isOn')	{
				throw new Error("Not running");
			}

			var doc = element.contentDocument;
			this.pagecounter++;

			if (this.slideshow) {
				ownerDoc.body.style.display = 'none';
				var cloner = doc.body.cloneNode(true);
				ownerDoc.documentElement.appendChild(cloner);
				ownerDoc.body = cloner;
				ownerDoc.body.setAttribute('antipagination', 'isOn');
			}
			else {
				this.appendChildren(doc.body, ownerDoc.body);
			}

			var savedQuery;
			if (this.attemptToIncrement) {
				savedQuery = this.query;
				this.increment();
			}
			else if (this.numberToIncrement != null) {
				this.increment();
			}

			let xresult = doc.evaluate(
				this.query,
				doc,
				null,
				0,
				null
				);

			let node = this.getLast(xresult);

			let location = (doc.location || {}).href || null;

			if (this.attemptToIncrement
				&& (!node || node.href == location)) {
				this.query = savedQuery;
				this.numberToIncrement = null;

				xresult = doc.evaluate(
					this.query,
					doc,
					null,
					0,
					null
					);
				node = this.getLast(xresult);
			}

			this.attemptToIncrement = false;

			if (!node) {
				throw new Error("No next node found");
			}
			if (location && location == node.href) {
				throw new Error("Location match (nothing new): " + location + ", " + node.href);
			}

			if (!this.nolimit && this.pagecounter >= this.pagelimit) {
				throw new Error("Done");
			}

			var niframe = ownerDoc.createElement('iframe');
			niframe.style.display = 'none';
			niframe.setAttribute('src', node.href);

			let self = this;
			niframe.addEventListener('load',function() {
				this.removeEventListener('load', arguments.callee, true);
				if(self.slideshow) {
					setTimeout(function() self.loadNext(niframe), self.seconds * 1000);
				}
				else {
					self.loadNext(this);
				}
			}, true);

			ownerDoc.body.appendChild(niframe);
		}
		catch (ex) {
			ownerDoc.body.setAttribute('antipagination','isOff');
			reportError(ex);
		}

		// kill the frame again
		setTimeout(function() element.parentNode.removeChild(element), 0);
	}
};
<|endoftext|>