<commit_before>/*
 * This config is only used during development and build phase only
 * It will not be available on production
 *
 */

(function (global) {
	// wildcard paths
	var paths = {
		"*": "dist/*",
		"n:*": "node_modules/*"
	};

	// map tells the System loader where to look for things
	var map = {
		"app": "app",
		"test": "test",
		"rxjs": "n:rxjs",
		"@angular": "n:@angular",
		"@ssv": "n:@ssv",
		"lodash": "n:lodash",
		"ionic-angular": "n:ionic-angular",
	};

	// packages tells the System loader how to load when no filename and/or no extension
	var packages = {
		"app": { defaultExtension: "js" },
		"test": { defaultExtension: "js" },

		// angular
		"@angular/core": { main: "bundles/core.umd.min.js" },
		"@angular/compiler": { main: "bundles/compiler.umd.js" },
		"@angular/common": { main: "bundles/common.umd.min.js" },
		"@angular/forms": { main: "bundles/forms.umd.min.js" },
		"@angular/http": { main: "bundles/http.umd.min.js" },
		"@angular/platform-browser": { main: "bundles/platform-browser.umd.min.js" },
		"@angular/platform-browser-dynamic": { main: "bundles/platform-browser-dynamic.umd.min.js" },

		// vendors
		"raven-js": { main: "raven.min.js", defaultExtension: "js" },
		"ionic-angular": { main: "commonjs/index.js", defaultExtension: "js" },
		"rxjs": { defaultExtension: "js" },
		"@ssv/ng2-core": { main: "dist/amd/index.js", defaultExtension: "js" },
	};

	var packageNames = [
		"lodash",
	];

	// add package entries for angular packages in the form "@angular/common": { main: "index.js", defaultExtension: "js" }
	packageNames.forEach(function (pkgName) {
		packages[pkgName] = { main: "index.js", defaultExtension: "js" };
	});

	var config = {
		map: map,
		packages: packages,
		paths: paths
	};

	// filterSystemConfig - index.html"s chance to modify config before we register it.
	if (global.filterSystemConfig) { global.filterSystemConfig(config); }

	System.config(config);

})(this);
<commit_msg>update system.config<commit_after>/*
 * This config is only used during development and build phase only
 * It will not be available on production
 *
 */

(function (global) {
	// wildcard paths
	var paths = {
		"*": "dist/*",
		"n:*": "node_modules/*"
	};

	// map tells the System loader where to look for things
	var map = {
		"app": "app",
		"test": "test",
		"rxjs": "n:rxjs",
		"@angular": "n:@angular",
		"@ssv": "n:@ssv",
		"lodash": "n:lodash",
		"ionic-angular": "n:ionic-angular",
	};

	// packages tells the System loader how to load when no filename and/or no extension
	var packages = {
		"app": { defaultExtension: "js" },
		"test": { defaultExtension: "js" },

		// angular
		"@angular/core": { main: "bundles/core.umd.min.js" },
		"@angular/compiler": { main: "bundles/compiler.umd.js" },
		"@angular/common": { main: "bundles/common.umd.min.js" },
		"@angular/forms": { main: "bundles/forms.umd.min.js" },
		"@angular/http": { main: "bundles/http.umd.min.js" },
		"@angular/platform-browser": { main: "bundles/platform-browser.umd.min.js" },
		"@angular/platform-browser-dynamic": { main: "bundles/platform-browser-dynamic.umd.min.js" },

		// vendors
		"raven-js": { main: "raven.min.js", defaultExtension: "js" },
		"rxjs": { defaultExtension: "js" },
		"ionic-angular": { main: "commonjs/index.js", defaultExtension: "js" },
		"@ssv/ng2-core": { main: "dist/amd/index.js", defaultExtension: "js" },
	};

	var packageNames = [
		"lodash",
	];

	// add package entries for angular packages in the form "@angular/common": { main: "index.js", defaultExtension: "js" }
	packageNames.forEach(function (pkgName) {
		packages[pkgName] = { main: "index.js", defaultExtension: "js" };
	});

	var config = {
		map: map,
		packages: packages,
		paths: paths
	};

	// filterSystemConfig - index.html"s chance to modify config before we register it.
	if (global.filterSystemConfig) { global.filterSystemConfig(config); }

	System.config(config);

})(this);
<|endoftext|>


<commit_before>/*
 *     Copyright (c) 2008-2016 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud 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 Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global StyledElements */

(function (se, utils) {

    "use strict";

    var TextField, oninput, onfocus, onblur, onkeypress;

    oninput = function oninput() {
        this.events.change.dispatch(this);
    };

    onfocus = function onfocus() {
        this.events.focus.dispatch(this);
    };

    onblur = function onblur() {
        this.events.blur.dispatch(this);
    };

    onkeypress = function onkeypress(event) {
        if (utils.normalizeKey(event) === "Enter") {
            this.trigger('submit');
        }
    };

    /**
     * @constructor
     * @name StyledElements.TextField
     * @extends StyledElements.InputElement
     */
    TextField = function TextField(options) {
        var defaultOptions = {
            'initialValue': '',
            'class': '',
            'placeholder': null
        };
        options = StyledElements.Utils.merge(defaultOptions, options);

        StyledElements.InputElement.call(this, options.initialValue, ['change', 'focus', 'blur', 'submit', 'keydown']);

        this.inputElement = document.createElement("input");
        this.inputElement.setAttribute("type", "text");

        this.wrapperElement = this.inputElement;
        this.wrapperElement.className = "se-text-field";
        if (options['class'] !== "") {
            this.wrapperElement.className += " " + options['class'];
        }

        if (options.name) {
            this.inputElement.setAttribute("name", options.name);
        }

        if (options.placeholder != null) {
            this.setPlaceholder(options.placeholder);
        }

        if (options.id != null) {
            this.wrapperElement.setAttribute("id", options.id);
        }

        this.inputElement.setAttribute("value", options.initialValue);

        /* Internal events */
        this._oninput = oninput.bind(this);
        this._onfocus = onfocus.bind(this);
        this._onblur = onblur.bind(this);
        this._onkeypress = onkeypress.bind(this);

        this.inputElement.addEventListener('mousedown', StyledElements.Utils.stopPropagationListener, true);
        this.inputElement.addEventListener('click', StyledElements.Utils.stopPropagationListener, true);
        this.inputElement.addEventListener('input', this._oninput, true);
        this.inputElement.addEventListener('focus', this._onfocus, true);
        this.inputElement.addEventListener('blur', this._onblur, true);
        this.inputElement.addEventListener('keypress', this._onkeypress, true);

        this._onkeydown_bound = element_onkeydown.bind(this);
        this.inputElement.addEventListener('keydown', this._onkeydown_bound, false);
    };
    TextField.prototype = new StyledElements.InputElement();

    TextField.prototype.setPlaceholder = function setPlaceholder(placeholder) {
        this.inputElement.setAttribute('placeholder', placeholder);
    };

    TextField.prototype.destroy = function destroy() {

        this.inputElement.removeEventListener('mousedown', StyledElements.Utils.stopPropagationListener, true);
        this.inputElement.removeEventListener('click', StyledElements.Utils.stopPropagationListener, true);
        this.inputElement.removeEventListener('input', this._oninput, true);
        this.inputElement.removeEventListener('focus', this._onfocus, true);
        this.inputElement.removeEventListener('blur', this._onblur, true);
        this.inputElement.removeEventListener('keypress', this._onkeypress, true);
        this.inputElement.removeEventListener('keydown', this._onkeydown_bound, false);

        delete this._oninput;
        delete this._onfocus;
        delete this._onblur;
        delete this._onkeypress;
        delete this._onkeydown_bound;

        StyledElements.InputElement.prototype.destroy.call(this);
    };

    StyledElements.TextField = TextField;

    // ==================================================================================
    // PRIVATE MEMBERS
    // ==================================================================================

    var element_onkeydown = function element_onkeydown(event) {
        var modifiers, key;

        modifiers = utils.extractModifiers(event);
        key = utils.normalizeKey(event);

        if (!modifiers.altKey && !modifiers.metaKey && !modifiers.ctrlKey || key === 'Backspace') {
            event.stopPropagation();
        }

        if (this.enabled) {
            this.trigger('keydown', modifiers, key);
        }
    };

})(StyledElements, StyledElements.Utils);
<commit_msg>Allow listeners to use the preventDefault method. Fix #151<commit_after>/*
 *     Copyright (c) 2008-2016 CoNWeT Lab., Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud 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 Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global StyledElements */

(function (se, utils) {

    "use strict";

    var TextField, oninput, onfocus, onblur, onkeypress;

    oninput = function oninput() {
        this.events.change.dispatch(this);
    };

    onfocus = function onfocus() {
        this.events.focus.dispatch(this);
    };

    onblur = function onblur() {
        this.events.blur.dispatch(this);
    };

    onkeypress = function onkeypress(event) {
        if (utils.normalizeKey(event) === "Enter") {
            this.trigger('submit');
        }
    };

    /**
     * @constructor
     * @name StyledElements.TextField
     * @extends StyledElements.InputElement
     */
    TextField = function TextField(options) {
        var defaultOptions = {
            'initialValue': '',
            'class': '',
            'placeholder': null
        };
        options = StyledElements.Utils.merge(defaultOptions, options);

        StyledElements.InputElement.call(this, options.initialValue, ['change', 'focus', 'blur', 'submit', 'keydown']);

        this.inputElement = document.createElement("input");
        this.inputElement.setAttribute("type", "text");

        this.wrapperElement = this.inputElement;
        this.wrapperElement.className = "se-text-field";
        if (options['class'] !== "") {
            this.wrapperElement.className += " " + options['class'];
        }

        if (options.name) {
            this.inputElement.setAttribute("name", options.name);
        }

        if (options.placeholder != null) {
            this.setPlaceholder(options.placeholder);
        }

        if (options.id != null) {
            this.wrapperElement.setAttribute("id", options.id);
        }

        this.inputElement.setAttribute("value", options.initialValue);

        /* Internal events */
        this._oninput = oninput.bind(this);
        this._onfocus = onfocus.bind(this);
        this._onblur = onblur.bind(this);
        this._onkeypress = onkeypress.bind(this);

        this.inputElement.addEventListener('mousedown', StyledElements.Utils.stopPropagationListener, true);
        this.inputElement.addEventListener('click', StyledElements.Utils.stopPropagationListener, true);
        this.inputElement.addEventListener('input', this._oninput, true);
        this.inputElement.addEventListener('focus', this._onfocus, true);
        this.inputElement.addEventListener('blur', this._onblur, true);
        this.inputElement.addEventListener('keypress', this._onkeypress, true);

        this._onkeydown_bound = element_onkeydown.bind(this);
        this.inputElement.addEventListener('keydown', this._onkeydown_bound, false);
    };
    TextField.prototype = new StyledElements.InputElement();

    TextField.prototype.setPlaceholder = function setPlaceholder(placeholder) {
        this.inputElement.setAttribute('placeholder', placeholder);
    };

    TextField.prototype.destroy = function destroy() {

        this.inputElement.removeEventListener('mousedown', StyledElements.Utils.stopPropagationListener, true);
        this.inputElement.removeEventListener('click', StyledElements.Utils.stopPropagationListener, true);
        this.inputElement.removeEventListener('input', this._oninput, true);
        this.inputElement.removeEventListener('focus', this._onfocus, true);
        this.inputElement.removeEventListener('blur', this._onblur, true);
        this.inputElement.removeEventListener('keypress', this._onkeypress, true);
        this.inputElement.removeEventListener('keydown', this._onkeydown_bound, false);

        delete this._oninput;
        delete this._onfocus;
        delete this._onblur;
        delete this._onkeypress;
        delete this._onkeydown_bound;

        StyledElements.InputElement.prototype.destroy.call(this);
    };

    StyledElements.TextField = TextField;

    // ==================================================================================
    // PRIVATE MEMBERS
    // ==================================================================================

    var element_onkeydown = function element_onkeydown(event) {
        var modifiers, key;

        modifiers = utils.extractModifiers(event);
        key = utils.normalizeKey(event);

        if (!modifiers.altKey && !modifiers.metaKey && !modifiers.ctrlKey || key === 'Backspace') {
            event.stopPropagation();
        }

        if (this.enabled) {
            modifiers.preventDefault = event.preventDefault.bind(event);
            modifiers.key = key;
            this.trigger('keydown', modifiers, key);
        }
    };

})(StyledElements, StyledElements.Utils);
<|endoftext|>


<commit_before> $(document).ready(function(){
     setInterval(ajaxcall, 1000);
 });
 function ajaxcall(){
     $.ajax({
         url: 'resources/gettime.php',
         success: function(data) {
             data = data.split(':');
             $('#hours').html(data[0]);
             $('#minutes').html(data[1]);
             $('#seconds').html(data[2]);
         }
     });
 }
<commit_msg>Update clock.js<commit_after> $(document).ready(function(){
     setInterval(ajaxcall, 1000);
 });
 function ajaxcall(){
     $.ajax({
         url: location.protocol + "//" + location.host + "/resources/gettime.php",
         success: function(data) {
             data = data.split(':');
             $('#hours').html(data[0]);
             $('#minutes').html(data[1]);
             $('#seconds').html(data[2]);
         }
     });
 }
<|endoftext|>


<commit_before>// Output a range of 16 memory addresses
function view_memory(addr, memory) {
    addr = addr & 0xFFF0;
    var pad = '00';
    var str = addr.toString(16) + ':';
    for (var i = addr; i < addr + 0x10; i++) {
        if ((i & 0x1) == 0) {
            str += ' ';
        }
        var val = memory[i] || 0;

        val = val.toString(16);
        str += pad.substring(val.length) + val;
    }

    return str;
}

function view_tile(screen, index) {
    var tileData = screen.readTileData(index, 0b11100011);

    var pixelData = new Array(8 * 8)
    for (var line = 0; line < 8; line++) {
        var b1 = tileData.shift();
        var b2 = tileData.shift();

        for (var pixel = 0; pixel < 8; pixel++) {
            var mask = (1 << (7-pixel));
            var colorValue = ((b1 & mask) >> (7-pixel)) + ((b2 & mask) >> (7-pixel))*2;
            pixelData[line * 8 + pixel] = colorValue;
        }
    }

    var i = 0;
    while (pixelData.length) {
        console.log(i++ + ' ' + pixelData.splice(0, 8).join(''));
    }
}
<commit_msg>fix debug function<commit_after>// Output a range of 16 memory addresses
function view_memory(addr, memory) {
    addr = addr & 0xFFF0;
    var pad = '00';
    var str = addr.toString(16) + ':';
    for (var i = addr; i < addr + 0x10; i++) {
        if ((i & 0x1) == 0) {
            str += ' ';
        }
        var val = memory[i] || 0;

        val = val.toString(16);
        str += pad.substring(val.length) + val;
    }

    return str;
}

function view_tile(screen, index) {
    var tileData = screen.readTileData(index, 0x8800);

    var pixelData = new Array(8 * 8)
    for (var line = 0; line < 8; line++) {
        var b1 = tileData.shift();
        var b2 = tileData.shift();

        for (var pixel = 0; pixel < 8; pixel++) {
            var mask = (1 << (7-pixel));
            var colorValue = ((b1 & mask) >> (7-pixel)) + ((b2 & mask) >> (7-pixel))*2;
            pixelData[line * 8 + pixel] = colorValue;
        }
    }

    var i = 0;
    while (pixelData.length) {
        console.log(i++ + ' ' + pixelData.splice(0, 8).join(''));
    }
}
<|endoftext|>


<commit_before>(() => {
  let noggun,
      points,
      totalPoints = 0,
      totalHeight,
      scrollTimeout,
      scrollInterval;
      previousProgress = 0,
      scrollCount = 0;

  const
      songUp = new Audio("/sounds/drake-sftb-cut.mp3"),
      songDown = new Audio("/sounds/drake-sftb-cut-rev.mp3"),
      progress = () => {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop,
              percentage = (scrollTop / (totalHeight - window.innerHeight));

        return percentage;
      },
      normalize = (p) => {
        const low = -noggun.offsetHeight,
              high = window.innerHeight + noggun.offsetHeight;

        return high + (low - (high * p));
      },
      stop = (s) => {
        s.pause();
        s.currentTime = 0;
      },
      setIcons = (o) => {
        for (id of ["patron", "cash"]) {
          const e = document.getElementById(id);
          e.style.opacity = o;
        }
      },
      danceIcons = () => {
        for (id of ["patron", "cash"]) {
          const e = document.getElementById(id);
          e.classList.toggle("hey");
          e.classList.toggle("ho");
        }
      },
      bottom = () => {
        setPoints(-totalPoints);
        window.scrollTo(0, totalHeight);
      },
      setPoints = (n) => {
        totalPoints += n;

        points.innerHTML = totalPoints;
      },
      killUpSong = () => {
        scrollCount = 0;
        scrollInterval = setInterval(() => {
          if (progress() < 1) {
            setPoints(-1);
            window.scrollBy(0, 100);
          }
          else {
            bottom();
            setIcons(0);
            killDownSong();
          }
        }, 30);

        setIcons(0);
        songDown.play();
        stop(songUp);
      },
      killDownSong = () => {
        clearInterval(scrollInterval);
        stop(songDown);
      },
      play = () => {
        const currentProgress = progress(),
              nextProgress = normalize(currentProgress);

        if (currentProgress < previousProgress) {
          scrollCount++;

          if (scrollInterval) {
            killDownSong();
          }

          if (currentProgress == 0) {
            bottom();
          }

          if (songUp.paused) {
            songUp.play();
            stop(songDown);
            setIcons(1);
          }

          if (scrollCount % 20 == 0) {
            danceIcons();
          }

          setPoints(1);
          clearTimeout(scrollTimeout);
          scrollTimeout = setTimeout(killUpSong, 270);
        }

        if (nextProgress <= 0) {
          noggun.style.top = nextProgress + "px";
        }

        previousProgress = currentProgress;
      },
      start = () => {
        const body = document.body,
              html = document.documentElement,
              cont = document.getElementById("container");

        songUp.load();
        songDown.load();

        container.style.height = "40000px";

        points = document.getElementById("points");
        noggun = document.getElementById("drake");
        totalHeight = Math.max(body.scrollHeight, body.offsetHeight,
                             html.clientHeight, html.scrollHeight, html.offsetHeight);

        noggun.style.top = -window.innerHeight + "px";
        noggun.style.display = "block"

        bottom();
        window.addEventListener("scroll", play);
      },
      isMobile = () => { // Source: http://stackoverflow.com/questions/11381673/detecting-a-mobile-browser
        let check = false;

        ((a) => {if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor);

        return check;
      };

  window.addEventListener("load", () => {
    const loading = document.getElementById("loading");

    loading.remove();

    if (isMobile()) {
      const warmup = document.getElementById("warmup");

      warmup.style.display = "block"

      warmup.addEventListener("click", (e) => {
        e.preventDefault();

        warmup.remove();
        start();
      });
    } else {
      start();
    }
  });

  // Prevent endless music loop in Chrome on tab change.
  document.addEventListener("visibilitychange", bottom);

  // Prevent mid-page scroll on Chrome on page refresh.
  window.addEventListener("beforeunload", bottom);
})();
<commit_msg>Reset on hitting bottom<commit_after>(() => {
  let noggun,
      points,
      totalPoints = 0,
      totalHeight,
      scrollTimeout,
      scrollInterval;
      previousProgress = 0,
      scrollCount = 0;

  const
      songUp = new Audio("/sounds/drake-sftb-cut.mp3"),
      songDown = new Audio("/sounds/drake-sftb-cut-rev.mp3"),
      progress = () => {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop,
              percentage = (scrollTop / (totalHeight - window.innerHeight));

        return percentage;
      },
      normalize = (p) => {
        const low = -noggun.offsetHeight,
              high = window.innerHeight + noggun.offsetHeight;

        return high + (low - (high * p));
      },
      stop = (s) => {
        s.pause();
        s.currentTime = 0;
      },
      setIcons = (o) => {
        for (id of ["patron", "cash"]) {
          const e = document.getElementById(id);
          e.style.opacity = o;
        }
      },
      danceIcons = () => {
        for (id of ["patron", "cash"]) {
          const e = document.getElementById(id);
          e.classList.toggle("hey");
          e.classList.toggle("ho");
        }
      },
      reset = () => {
        setPoints(-totalPoints);
        bottom();
      },
      bottom = () => {
        window.scrollTo(0, totalHeight);
      },
      setPoints = (n) => {
        totalPoints += n;

        points.innerHTML = totalPoints;
      },
      killUpSong = () => {
        scrollCount = 0;
        scrollInterval = setInterval(() => {
          if (progress() < 1) {
            setPoints(-1);
            window.scrollBy(0, 100);
          }
          else {
            reset();
            setIcons(0);
            killDownSong();
          }
        }, 30);

        setIcons(0);
        songDown.play();
        stop(songUp);
      },
      killDownSong = () => {
        clearInterval(scrollInterval);
        stop(songDown);
      },
      play = () => {
        const currentProgress = progress(),
              nextProgress = normalize(currentProgress);

        if (currentProgress < previousProgress) {
          scrollCount++;

          if (scrollInterval) {
            killDownSong();
          }

          if (currentProgress == 0) {
            bottom();
          }

          if (songUp.paused) {
            songUp.play();
            stop(songDown);
            setIcons(1);
          }

          if (scrollCount % 20 == 0) {
            danceIcons();
          }

          setPoints(1);
          clearTimeout(scrollTimeout);
          scrollTimeout = setTimeout(killUpSong, 270);
        }

        if (nextProgress <= 0) {
          noggun.style.top = nextProgress + "px";
        }

        previousProgress = currentProgress;
      },
      start = () => {
        const body = document.body,
              html = document.documentElement,
              cont = document.getElementById("container");

        songUp.load();
        songDown.load();

        container.style.height = "40000px";

        points = document.getElementById("points");
        noggun = document.getElementById("drake");
        totalHeight = Math.max(body.scrollHeight, body.offsetHeight,
                             html.clientHeight, html.scrollHeight, html.offsetHeight);

        noggun.style.top = -window.innerHeight + "px";
        noggun.style.display = "block"

        reset();
        window.addEventListener("scroll", play);
      },
      isMobile = () => { // Source: http://stackoverflow.com/questions/11381673/detecting-a-mobile-browser
        let check = false;

        ((a) => {if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))check = true})(navigator.userAgent||navigator.vendor);

        return check;
      };

  window.addEventListener("load", () => {
    const loading = document.getElementById("loading");

    loading.remove();

    if (isMobile()) {
      const warmup = document.getElementById("warmup");

      warmup.style.display = "block"

      warmup.addEventListener("click", (e) => {
        e.preventDefault();

        warmup.remove();
        start();
      });
    } else {
      start();
    }
  });

  // Prevent endless music loop in Chrome on tab change.
  document.addEventListener("visibilitychange", reset);

  // Prevent mid-page scroll on Chrome on page refresh.
  window.addEventListener("beforeunload", reset);
})();
<|endoftext|>


<commit_before>var mainModule = angular.module('app', []).
	controller("forumCtrl", function forumCtrl($scope, $window, $timeout, $http){
		$scope.currentProject = null;
		$scope.currentThread = null;
		$scope.show = "login";
		$scope.newProjectName = "";
		$scope.newThreadSubject = "";
		$scope.newThreadMessage = "";
		$scope.newPost = "";

		$scope.openThreads = function(project){
			$scope.show = "threads";
			$scope.currentProject = project;
		}

		$scope.openPosts = function(thread){
			$scope.show = "posts";
			$scope.currentThread = thread;
		}

		$scope.createProject = function(){
			$scope.projects.push({id: $scope.projects.length, name: $scope.newProjectName, threads: []});
			$scope.newProjectName = "";
			$scope.show="projects";
		}

		$scope.createThread = function(){
			$scope.currentProject.threads.push({
				id: $scope.currentProject.threads.length,
				subject: $scope.newThreadSubject,
				posts: [{id: 0, userID: 0, message: $scope.newThreadMessage}]
			})
			$scope.newThreadSubject = "";
			$scope.newThreadMessage = "";
			$scope.show="threads";
		}

		$scope.sendPost = function(){
			$scope.currentThread.posts.push({
				id: $scope.currentThread.posts.length,
				userID: 2,
				message: $scope.newPost
			});

			$scope.newPost= "";
		}

		$scope.users = [
			{
				id: 0,
				firstName: "Michal",
				surname: "Paszkiewicz",
				imageURL: "http://www.gravatar.com/avatar/f8231ccab5f14c6499e32e17700399d9?d=wavatar",
				websiteURL: "http://www.michalpaszkiewicz.co.uk",
				experience: "8 years live guitar playing",
				skills: "Software",
				openToPublic: true
			},
			{
				id: 1,
				firstName: "Aaron",
				surname: "Dennis",
				imageURL: "https://avatars3.githubusercontent.com/u/9275082?v=3&amp",
				websiteURL: "https://aaronjden.github.io",
				experience: "Lots of good experience",
				skills: "Software",
				openToPublic: true
			},
			{
				id: 2,
				firstName: "Dave",
				surname: "Da rave",
				imageURL: "https://avatars2.githubusercontent.com/u/8076321?v=3&amp",
				websiteURL: "http://tametheboardgame.com/",
				experience: "40 years in the circus industry",
				skills: "Juggling",
				openToPublic: true
			}
		];

		$scope.getItemFromID = function(array, id)
		{
			for(var i = 0; i < array.length; i++){
				if(array[i].id == id){
					return array[i];
				}
			}
			return false;
		}

		$scope.getIndexFromID = function(array, id)
		{
			for(var i = 0; i < array.length; i++){
				if(array[i].id == id){
					return i;
				}
			}
			return false;
		}

		$scope.projects = [
			{
				id: 0,
				name: "Prince of Egypt",
				threads: [
					{
						id: 0,
						projectID: 0,
						subject: "when to do this",
						posts: [
							{
								id: 0,
								userID: 0,
								threadID: 0,
								projectID: 0,
								date: "2014",
								message: "hi"
							},
							{
								id: 1,
								userID: 2,
								threadID: 0,								threadID: 0,
								projectID: 0,
								date: "2014",
								message: "hi"
							}
						]
					},
					{
						id: 1,
						projectID: 0,
						subject: "stuff and things",
						posts: [
							{
								id: 2,
								userID: 1,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "yo"
							},
							{
								id: 3,
								userID: 2,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "kazaa"
							}
						]
					}
				]
			},
			{
				id: 1,
				name: "The Lion King",
				threads: [
					{
						id: 0,
						projectID: 0,
						subject: "when to do this",
						posts: [
							{
								id: 0,
								userID: 0,
								threadID: 0,
								projectID: 0,
								date: "2014",
								message: "hi"
							},
							{
								id: 1,
								userID: 2,
								threadID: 0,								threadID: 0,
								projectID: 0,
								date: "2014",
								message: "hi"
							}
						]
					},
					{
						id: 1,
						projectID: 0,
						subject: "stuff and things",
						posts: [
							{
								id: 2,
								userID: 1,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "yo"
							},
							{
								id: 3,
								userID: 2,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "kazaa"
							}
						]
					}
				]
			}
		];

		$scope.currentUser = null;
		$scope.loggedIn = false;
		$scope.loginFailed = false;

		$scope.login = function(){
			if(true){
				//todo: change this later to be assigned on login.
				$scope.currentUser = $scope.users[0];
				$scope.loginFailed = false;
				$scope.loggedIn = true;
				$scope.show = 'projects';
			}
			else{
				$scope.loginFailed = true;
			}
		}

		$scope.logout = function(){
			$scope.currentUser = null;
			$scope.loggedIn = false;
			$scope.show = 'login';
		}

	}).directive('selectOnClick', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click', function () {
                this.select();
            });
        }
    };
});
<commit_msg>Update forum.js<commit_after>var mainModule = angular.module('app', []).
	controller("forumCtrl", function forumCtrl($scope, $window, $timeout, $http){
		$scope.currentProject = null;
		$scope.currentThread = null;
		$scope.show = "login";
		$scope.newProjectName = "";
		$scope.newThreadSubject = "";
		$scope.newThreadMessage = "";
		$scope.newPost = "";

		$scope.openThreads = function(project){
			$scope.show = "threads";
			$scope.currentProject = project;
		}

		$scope.openPosts = function(thread){
			$scope.show = "posts";
			$scope.currentThread = thread;
		}

		$scope.createProject = function(){
			$scope.projects.push({id: $scope.projects.length, name: $scope.newProjectName, threads: []});
			$scope.newProjectName = "";
			$scope.show="projects";
		}

		$scope.createThread = function(){
			$scope.currentProject.threads.push({
				id: $scope.currentProject.threads.length,
				subject: $scope.newThreadSubject,
				posts: [{id: 0, userID: 0, message: $scope.newThreadMessage}]
			})
			$scope.newThreadSubject = "";
			$scope.newThreadMessage = "";
			$scope.show="threads";
		}

		$scope.sendPost = function(){
			$scope.currentThread.posts.push({
				id: $scope.currentThread.posts.length,
				userID: 2,
				message: $scope.newPost
			});

			$scope.newPost= "";
		}

		$scope.users = [
			{
				id: 0,
				firstName: "Michal",
				surname: "Paszkiewicz",
				imageURL: "http://www.gravatar.com/avatar/f8231ccab5f14c6499e32e17700399d9?d=wavatar",
				websiteURL: "http://www.michalpaszkiewicz.co.uk",
				experience: "8 years live guitar playing",
				skills: "Software",
				openToPublic: true
			},
			{
				id: 1,
				firstName: "Aaron",
				surname: "Dennis",
				imageURL: "https://avatars3.githubusercontent.com/u/9275082?v=3&amp",
				websiteURL: "https://aaronjden.github.io",
				experience: "Lots of good experience",
				skills: "Software",
				openToPublic: true
			},
			{
				id: 2,
				firstName: "Dave",
				surname: "Da rave",
				imageURL: "https://avatars2.githubusercontent.com/u/8076321?v=3&amp",
				websiteURL: "http://tametheboardgame.com/",
				experience: "40 years in the circus industry",
				skills: "Juggling",
				openToPublic: true
			}
		];

		$scope.getItemFromID = function(array, id)
		{
			for(var i = 0; i < array.length; i++){
				if(array[i].id == id){
					return array[i];
				}
			}
			return false;
		}

		$scope.getIndexFromID = function(array, id)
		{
			for(var i = 0; i < array.length; i++){
				if(array[i].id == id){
					return i;
				}
			}
			return false;
		}

		$scope.projects = [
			{
				id: 0,
				name: "Prince of Egypt",
				threads: [
					{
						id: 0,
						projectID: 0,
						subject: "when to do this",
						posts: [
							{
								id: 0,
								userID: 0,
								threadID: 0,
								projectID: 0,
								date: "2014",
								message: "hi"
							},
							{
								id: 1,
								userID: 2,
								threadID: 0,								threadID: 0,
								projectID: 0,
								date: "2014",
								message: "hi"
							}
						]
					},
					{
						id: 1,
						projectID: 0,
						subject: "stuff and things",
						posts: [
							{
								id: 2,
								userID: 1,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "yo"
							},
							{
								id: 3,
								userID: 2,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "kazaa"
							}
						]
					}
				]
			},
			{
				id: 1,
				name: "The Lion King",
				threads: [
					{
						id: 0,
						projectID: 0,
						subject: "when to do this",
						posts: [
							{
								id: 0,
								userID: 0,
								threadID: 0,
								projectID: 0,
								date: "2014",
								message: "hi"
							},
							{
								id: 1,
								userID: 2,
								threadID: 0,								threadID: 0,
								projectID: 0,
								date: "2014",
								message: "hi"
							}
						]
					},
					{
						id: 1,
						projectID: 0,
						subject: "stuff and things",
						posts: [
							{
								id: 2,
								userID: 1,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "yo"
							},
							{
								id: 3,
								userID: 2,
								threadID: 1,
								projectID: 0,
								date: "2014",
								message: "kazaa"
							}
						]
					}
				]
			}
		];

		$scope.currentUser = null;
		$scope.loggedIn = false;
		$scope.loginFailed = false;

		$scope.login = function(){
			var stringifiedPost = JSON.stringify(postObject);
			$http({method: "POST", url: serverURL + "/posts", data: stringifiedPost}).success(function(data, status){
				if(data){
					//todo: change this later to be assigned on login.
					$scope.currentUser = $scope.users[0];
					$scope.loginFailed = false;
					$scope.loggedIn = true;
					$scope.show = 'projects';
				}
				else{
					$scope.loginFailed = true;
				}

				console.log(data);
			});
		}

		$scope.logout = function(){
			$scope.currentUser = null;
			$scope.loggedIn = false;
			$scope.show = 'login';
		}

	}).directive('selectOnClick', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click', function () {
                this.select();
            });
        }
    };
});
<|endoftext|>


<commit_before>import fileSaver from 'file-Saver';
import CanvasClass from './CanvasClass';
import LocationLookup from './LocationLookup';
import Map from './Map.js';
import TextOverlay from './TextOverlay';
import keys from './keys';
import Styles from './Styles';
require('./manifest.json');
require('../images/manifest/icon-512x512.png');
require('../images/manifest/icon-192x192.png');
require('../images/manifest/icon-144x144.png');
require('../images/manifest/icon-96x96.png');
require('../images/manifest/icon-72x72.png');
require('../images/manifest/icon-48x48.png');

import html2canvas  from 'html2canvas';
import mapboxgl from 'mapbox-gl';
require('offline-plugin/runtime').install();

import '../css/font.css';
import '../css/input.css';
import '../css/main.css';
import '../css/main-overlay.css';

function updateDPI(dpi = 300) {
    Object.defineProperty(window, 'devicePixelRatio', {
        get: function () {
            return dpi / 96
        }
    });
}

updateDPI();

let map = new Map(keys().mapBox)

let  locationLookupCallback = ()=> {
    let textOverlay  = new TextOverlay;
    let locationLookup = new LocationLookup(textOverlay, map );
    locationLookup.locationLookupLoaded();
    let canvasClass = new CanvasClass(1800, 2400);
}

window.Buffer = null;

window.locationLookupCallback = locationLookupCallback;

document.addEventListener("DOMContentLoaded", function(event) {
    //set up the google maps api. We need to pass in the key from the keys.js file
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    let googlePlacesKey = keys().googlePlaces;
    script.src = `https://maps.googleapis.com/maps/api/js?key=${googlePlacesKey}&libraries=places&callback=locationLookupCallback`;
    console.log(script.src);
    document.getElementsByTagName('head')[0].appendChild(script);
});<commit_msg>Add images for manifest<commit_after>//Internal classes
import CanvasClass from './CanvasClass';
import LocationLookup from './LocationLookup';
import Map from './Map.js';
import PosterStyling from './PosterStyling';
import keys from './keys';
import Styles from './Styles';

//External libs
import fileSaver from 'file-Saver';
import html2canvas  from 'html2canvas';
import mapboxgl from 'mapbox-gl';
require('offline-plugin/runtime').install();

//App manifest for pwa
require('./manifest.json');
//css
import '../css/font.css';
import '../css/input.css';
import '../css/main.css';
import '../css/main-overlay.css';

//images
require('../images/manifest/icon-512x512.png');
require('../images/manifest/icon-192x192.png');
require('../images/manifest/icon-144x144.png');
require('../images/manifest/icon-96x96.png');
require('../images/manifest/icon-72x72.png');
require('../images/manifest/icon-48x48.png');

function updateDPI(dpi = 300) {
    Object.defineProperty(window, 'devicePixelRatio', {
        get: function () {
            return dpi / 96
        }
    });
}

updateDPI();

let map = new Map(keys().mapBox)

let  locationLookupCallback = ()=> {
    let posterStyling  = new PosterStyling(map);
    let locationLookup = new LocationLookup(posterStyling, map );
    locationLookup.locationLookupLoaded();
    let canvasClass = new CanvasClass(1800, 2400);
}

//set this to windows scope so the callback picks it up
window.locationLookupCallback = locationLookupCallback;

//set up some things for when the documnet loads
document.addEventListener("DOMContentLoaded", function(event) {
    //set up the google maps api. We need to pass in the key from the keys.js file
    let script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    let googlePlacesKey = keys().googlePlaces;
    script.src = `https://maps.googleapis.com/maps/api/js?key=${googlePlacesKey}&libraries=places&callback=locationLookupCallback`;
    console.log(script.src);
    document.getElementsByTagName('head')[0].appendChild(script);
});<|endoftext|>


<commit_before>function myFunction() {
    document.getElementsByClassName("navbar")[0].classList.toggle("responsive");
}

function myFunction(social_media_image) {
    var id = social_media_image.id;
    var new_src = "icons/" + id + "_clicked.png";
    social_media_image.src = new_src;
}

function mouseaway(my_image) {
    var id = my_image.id;
    my_image.src = "icons/" + id + ".png";

}

// jquery for skills section
// if ($(window).width() > 600) {
//     $("#skills_larger_browser").show();
//     $("#skills_smaller_browser").hide();
// } else {
//     $("#skills_larger_browser").hide();
//     $("#skills_smaller_browser").show();
// }

$("#tab1_content").hide();
$("#tab2_content").hide();
$("#tab3_content").hide();
$("#tab4_content").hide();

$("#tab1").click(function() {
    $("#tab1_content").show();
    $("#tab2_content").hide();
    $("#tab3_content").hide();
    $("#tab4_content").hide();
});

$("#tab2").click(function() {
    $("#tab2_content").show();
    $("#tab1_content").hide();
    $("#tab3_content").hide();
    $("#tab4_content").hide();
});

$("#tab3").click(function() {
    $("#tab3_content").show();
    $("#tab1_content").hide();
    $("#tab2_content").hide();
    $("#tab4_content").hide();
});

$("#tab4").click(function() {
    $("#tab4_content").show();
    $("#tab1_content").hide();
    $("#tab2_content").hide();
    $("#tab3_content").hide();
});

// --------------------------------------------------------------------------------

// $("#project1").hover(
//   function() {
//     $(this).attr("src", "http://cdn-6.dooziedog.com/dog_breeds/beagle/images/full/Beagle-Puppy.jpg");
//   },
//     function() {
//       $(this).attr("src", "http://i.imgur.com/Flk3FcN.png");
//   });
<commit_msg>progress!<commit_after>function myFunction() {
    document.getElementsByClassName("navbar")[0].classList.toggle("responsive");
}

function myFunction(social_media_image) {
    var id = social_media_image.id;
    var new_src = "icons/" + id + "_clicked.png";
    social_media_image.src = new_src;
}

function mouseaway(my_image) {
    var id = my_image.id;
    my_image.src = "icons/" + id + ".png";

}

// jquery for skills section
// if ($(window).width() > 600) {
//     $("#skills_larger_browser").show();
//     $("#skills_smaller_browser").hide();
// } else {
//     $("#skills_larger_browser").hide();
//     $("#skills_smaller_browser").show();
// }

$("#tab1_content").show();
$("#tab2_content").hide();
$("#tab3_content").hide();
$("#tab4_content").hide();

$("#tab1").click(function() {
    $("#tab1_content").show();
    $("#tab2_content").hide();
    $("#tab3_content").hide();
    $("#tab4_content").hide();
});

$("#tab2").click(function() {
    $("#tab2_content").show();
    $("#tab1_content").hide();
    $("#tab3_content").hide();
    $("#tab4_content").hide();
});

$("#tab3").click(function() {
    $("#tab3_content").show();
    $("#tab1_content").hide();
    $("#tab2_content").hide();
    $("#tab4_content").hide();
});

$("#tab4").click(function() {
    $("#tab4_content").show();
    $("#tab1_content").hide();
    $("#tab2_content").hide();
    $("#tab3_content").hide();
});

// --------------------------------------------------------------------------------

// $("#project1").hover(
//   function() {
//     $(this).attr("src", "http://cdn-6.dooziedog.com/dog_breeds/beagle/images/full/Beagle-Puppy.jpg");
//   },
//     function() {
//       $(this).attr("src", "http://i.imgur.com/Flk3FcN.png");
//   });
<|endoftext|>


<commit_before>var CORS_PROXY_URL = "https://cors-anywhere.herokuapp.com/";
var CHECK_DOWNLOADS_FINISHED_EVERY_MS = 100;

/* User options */
var subName;
var section;
var includeNsfw;
var includeImages;
var includeGifs;

var checkFinishedInterval;
var downloadRequests = new Set();
var downloadedCount;
var toDownloadCount;
var zip;

$(document).ready(function() {
    /*
        Puts a random subreddit as sub name inputbox placeholder,
        list taken from https://www.reddit.com/reddits
    */
    var subreddits = [
        "funny",
        "pics",
        "me_irl",
        "aww",
        "dankmemes",
        "mildlyinteresting",
        "AdviceAnimals",
        "CrappyDesign",
        "OldSchoolCool",
        "2007scape"
    ];
    $("#subNameInput").attr("placeholder",
        subreddits[Math.floor(Math.random() * subreddits.length)]);

    $('.ui.checkbox').checkbox();
    $('select.dropdown').dropdown();
    $('.ui.form').form({
        fields: {
            subNameInput : 'empty',
            imageAmountInput : 'integer[0..]'
        }
    });
});

$("#downloadButton").click(function() {
    if ($('.ui.form').form('validate form')) {
        /* Reset states */
        $('.ui.form').addClass("loading");
        $("#unknownSubredditErrorBox").hide();
        $("#downloadingInfoBox").show();
        downloadRequests.clear();
        downloadedCount = 0;
        toDownloadCount = 0;
        zip = new JSZip();
        updateUI();

        /* Read user options */
        subName = $("#subNameInput").val();
        section = $("#sectionInput").val();
        includeNsfw = $("#includeNsfwInput").is(':checked');
        includeImages = $("#includeImagesInput").is(':checked');
        includeGifs = $("#includeGifsInput").is(':checked');

        if (!includeImages && !includeGifs) {
            $("#includeImagesInput").prop("checked", true);
            includeImages = true;
        }

        /* Find images to scrape and start downloading */
        var maxImageCount = $("#imageAmountInput").val();
        download(maxImageCount);
    }
});

function updateUI() {
    $("#downloadedCountText").text(downloadedCount);
    $("#toDownloadCountText").text(toDownloadCount);
}

function download(maxImageCount, anchor) {
    /* Max 100 posts per request */
    var maxImageCountNow = Math.min(maxImageCount, 100);

    /* Prevent extreme amounts of requests in the case that maxImageCountNow is for example 1 */
    if (maxImageCountNow < 50) {
        maxImageCountNow = 50;
    }

    $.ajax({
        url: CORS_PROXY_URL
            + "https://www.reddit.com/r/" + subName
            + "/" + section + ".json?limit=" + maxImageCountNow
            + (anchor !== undefined ? "&after=" + anchor : ""),
        type: "GET",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(result, status, xhr) {
            /* Check if we have been redirected to the search page = subreddit doesn't exist */
            if (xhr.getResponseHeader("X-Final-Url").indexOf(section + ".json") !== -1) {
                var children = result.data.children;

                var downloadedCountNow = 0;

                if (children.length > 0) {
                    for (var i = 0; i < children.length; i++) {
                        var post = children[i].data;

                        /* Only download if there's a thumbnail */
                        if (post.thumbnail_width !== null) {
                            /* Respect user's nsfw option */
                            if (includeNsfw || !post.over_18) {
                                /* Check if there are any images, there should be, but let's make sure */
                                if (post.preview !== undefined && post.preview.images.length > 0) {
                                    var url = post.preview.images[0].source.url;

                                    if (isUrlFileFormatAccepted(url)) {
                                        /* Force https */
                                        if (url.startsWith("http:")) {
                                            url = url.replace("http:", "https:");
                                        }

                                        toDownloadCount++;
                                        downloadedCountNow++;
                                        updateUI();

                                        downloadImageAsBase64(url, function(url, data) {
                                            zip.file(url.replace(/(.+\/)/, "").replace(/(\?.+)/, ""), data, { base64: true });
                                            downloadedCount++;
                                            updateUI();
                                        });

                                        if (downloadedCountNow == maxImageCount) {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                maxImageCount -= downloadedCountNow;

                if (children.length === 0 || maxImageCount === 0) {
                    checkFinishedInterval = setInterval(function() {
                        if (downloadedCount == toDownloadCount) {
                            doneDownloading();
                        }
                    }, CHECK_DOWNLOADS_FINISHED_EVERY_MS);
                } else {
                    download(maxImageCount, result.data.after);
                }
            } else {
                $("#unknownSubredditErrorBox").show();
                $("#subNameText").text(subName);
                doneDownloading();
            }
        },
        error: function(error) {
            if (error.status === 404 || error.status === 403) {
                /* If HTTP status is 404 or 403, the subreddit probably doesn't exist */
                $("#unknownSubredditErrorBox").show();
                $("#subNameText").text(subName);
            } else if (error.status !== 200) {
                /* Notify user when a non-handled status code is received */
                alert("Unknown status code " + error.status + " received from lookup request.\nPlease contact the developer.");
            }
            doneDownloading();
        }
    });
}

function isUrlFileFormatAccepted(url) {
    return (includeImages && (url.indexOf(".jpg?") !== -1 || url.indexOf(".png?") !== -1))
        || (includeGifs && (url.indexOf(".gif?") !== -1 || url.indexOf(".gifv?") !== -1));
}

function doneDownloading() {
    for (var xhr in downloadRequests) {
        xhr.abort();
    }

    clearInterval(checkFinishedInterval);

    if (downloadedCount > 0) {
        zip.generateAsync({ type:"blob" })
            .then(function(content) {
                saveAs(content, subName + "_" + section + ".zip");
            });
    }

    $('.ui.form').removeClass("loading");
    $("#downloadingInfoBox").hide();
}

function downloadImageAsBase64(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        downloadRequests.delete(this);

        var reader = new FileReader();
        reader.onloadend = function() {
            callback(url, reader.result.split(',').pop());
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', CORS_PROXY_URL + url);
    xhr.responseType = 'blob';
    xhr.send();

    downloadRequests.add(xhr);
}

// https://stackoverflow.com/a/30949767/4313694
$('button').on('mousedown',
    function(event) {
        event.preventDefault();
    }
);
<commit_msg>Handle users entering /r/ or r/ before the sub name<commit_after>var CORS_PROXY_URL = "https://cors-anywhere.herokuapp.com/";
var CHECK_DOWNLOADS_FINISHED_EVERY_MS = 100;

/* User options */
var subName;
var section;
var includeNsfw;
var includeImages;
var includeGifs;

var checkFinishedInterval;
var downloadRequests = new Set();
var downloadedCount;
var toDownloadCount;
var zip;

$(document).ready(function() {
    /*
        Puts a random subreddit as sub name inputbox placeholder,
        list taken from https://www.reddit.com/reddits
    */
    var subreddits = [
        "funny",
        "pics",
        "me_irl",
        "aww",
        "dankmemes",
        "mildlyinteresting",
        "AdviceAnimals",
        "CrappyDesign",
        "OldSchoolCool",
        "2007scape"
    ];
    $("#subNameInput").attr("placeholder",
        subreddits[Math.floor(Math.random() * subreddits.length)]);

    $('.ui.checkbox').checkbox();
    $('select.dropdown').dropdown();
    $('.ui.form').form({
        fields: {
            subNameInput : 'empty',
            imageAmountInput : 'integer[0..]'
        }
    });
});

$("#downloadButton").click(function() {
    if ($('.ui.form').form('validate form')) {
        /* Reset states */
        $('.ui.form').addClass("loading");
        $("#unknownSubredditErrorBox").hide();
        $("#downloadingInfoBox").show();
        downloadRequests.clear();
        downloadedCount = 0;
        toDownloadCount = 0;
        zip = new JSZip();
        updateUI();

        /* Read user options */
        subName = $("#subNameInput").val();
        section = $("#sectionInput").val();
        includeNsfw = $("#includeNsfwInput").is(':checked');
        includeImages = $("#includeImagesInput").is(':checked');
        includeGifs = $("#includeGifsInput").is(':checked');

        /* Handle the user entering /r/ or r/ before the sub name */
        if (subName.startsWith("/r/")) {
            subName = subName.substring(3);
        } else if (subName.startsWith("r/")) {
            subName = subName.substring(2);
        }

        if (!includeImages && !includeGifs) {
            $("#includeImagesInput").prop("checked", true);
            includeImages = true;
        }

        /* Find images to scrape and start downloading */
        var maxImageCount = $("#imageAmountInput").val();
        download(maxImageCount);
    }
});

function updateUI() {
    $("#downloadedCountText").text(downloadedCount);
    $("#toDownloadCountText").text(toDownloadCount);
}

function download(maxImageCount, anchor) {
    /* Max 100 posts per request */
    var maxImageCountNow = Math.min(maxImageCount, 100);

    /* Prevent extreme amounts of requests in the case that maxImageCountNow is for example 1 */
    if (maxImageCountNow < 50) {
        maxImageCountNow = 50;
    }

    $.ajax({
        url: CORS_PROXY_URL
            + "https://www.reddit.com/r/" + subName
            + "/" + section + ".json?limit=" + maxImageCountNow
            + (anchor !== undefined ? "&after=" + anchor : ""),
        type: "GET",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(result, status, xhr) {
            /* Check if we have been redirected to the search page = subreddit doesn't exist */
            if (xhr.getResponseHeader("X-Final-Url").indexOf(section + ".json") !== -1) {
                var children = result.data.children;

                var downloadedCountNow = 0;

                if (children.length > 0) {
                    for (var i = 0; i < children.length; i++) {
                        var post = children[i].data;

                        /* Only download if there's a thumbnail */
                        if (post.thumbnail_width !== null) {
                            /* Respect user's nsfw option */
                            if (includeNsfw || !post.over_18) {
                                /* Check if there are any images, there should be, but let's make sure */
                                if (post.preview !== undefined && post.preview.images.length > 0) {
                                    var url = post.preview.images[0].source.url;

                                    if (isUrlFileFormatAccepted(url)) {
                                        /* Force https */
                                        if (url.startsWith("http:")) {
                                            url = url.replace("http:", "https:");
                                        }

                                        toDownloadCount++;
                                        downloadedCountNow++;
                                        updateUI();

                                        downloadImageAsBase64(url, function(url, data) {
                                            zip.file(url.replace(/(.+\/)/, "").replace(/(\?.+)/, ""), data, { base64: true });
                                            downloadedCount++;
                                            updateUI();
                                        });

                                        if (downloadedCountNow == maxImageCount) {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                maxImageCount -= downloadedCountNow;

                if (children.length === 0 || maxImageCount === 0) {
                    checkFinishedInterval = setInterval(function() {
                        if (downloadedCount == toDownloadCount) {
                            doneDownloading();
                        }
                    }, CHECK_DOWNLOADS_FINISHED_EVERY_MS);
                } else {
                    download(maxImageCount, result.data.after);
                }
            } else {
                $("#unknownSubredditErrorBox").show();
                $("#subNameText").text(subName);
                doneDownloading();
            }
        },
        error: function(error) {
            if (error.status === 404 || error.status === 403) {
                /* If HTTP status is 404 or 403, the subreddit probably doesn't exist */
                $("#unknownSubredditErrorBox").show();
                $("#subNameText").text(subName);
            } else if (error.status !== 200) {
                /* Notify user when a non-handled status code is received */
                alert("Unknown status code " + error.status + " received from lookup request.\nPlease contact the developer.");
            }
            doneDownloading();
        }
    });
}

function isUrlFileFormatAccepted(url) {
    return (includeImages && (url.indexOf(".jpg?") !== -1 || url.indexOf(".png?") !== -1))
        || (includeGifs && (url.indexOf(".gif?") !== -1 || url.indexOf(".gifv?") !== -1));
}

function doneDownloading() {
    for (var xhr in downloadRequests) {
        xhr.abort();
    }

    clearInterval(checkFinishedInterval);

    if (downloadedCount > 0) {
        zip.generateAsync({ type:"blob" })
            .then(function(content) {
                saveAs(content, subName + "_" + section + ".zip");
            });
    }

    $('.ui.form').removeClass("loading");
    $("#downloadingInfoBox").hide();
}

function downloadImageAsBase64(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function() {
        downloadRequests.delete(this);

        var reader = new FileReader();
        reader.onloadend = function() {
            callback(url, reader.result.split(',').pop());
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', CORS_PROXY_URL + url);
    xhr.responseType = 'blob';
    xhr.send();

    downloadRequests.add(xhr);
}

// https://stackoverflow.com/a/30949767/4313694
$('button').on('mousedown',
    function(event) {
        event.preventDefault();
    }
);
<|endoftext|>


<commit_before>(function(µ,SMOD,GMOD,HMOD,SC){

	var SC=SC({
	    Config:"Config",
	    form:"gui.form",
	    rq:"request",
	    dialog:"gui.dialog",
	    checkDB:"checkDbErrors"
	});

	var searchWrapper=document.getElementById("searchWrapper");

	var searchForm=SC.form({
	   type:"array",
	   model:{
		   type:"string",
		   pattern:/.+/
	   },
	   default:[""]
	}, undefined,"Search");
	searchForm.id="searchForm";
	var firstInput=searchForm.querySelector("input")
	firstInput.accessKey="f";
	firstInput.title="Accesskey F";
	firstInput.autofocus=true;
	searchWrapper.appendChild(searchForm);

	var searchSources;
	SC.rq.json("rest/config").then(function(data)
	{
		var sourcesConfig={};
		for(var sourceName in data["search sources"])
		{
			sourcesConfig[sourceName]={
				type:"boolean",
				default:false
			};
		}
		searchSources=SC.form(sourcesConfig,undefined,"Sources");
		searchSources.id="searchSources";
		searchSources.classList.add("hidden");
		searchWrapper.appendChild(searchSources);
		searchSources.firstElementChild.addEventListener("click",function()
		{
			searchSources.classList.toggle("hidden")
		})
	});

	var searchBtn=document.getElementById("searchBtn");
	searchForm.addEventListener("keydown",function(e)
	{
		if(e.key=="Enter")
		{
			searchBtn.focus();
			//searchBtn.click();
		}
	});
	searchForm.addEventListener("formAdd",function(e)
	{
		e.detail.element.querySelector("input").focus();
	});
	searchBtn.addEventListener("click",function()
	{
	    if(searchForm.isValid())
	    {
	        var data={query:searchForm.getConfig().get()};
	        if(!searchSources.classList.contains("hidden"))
	        {
	        	data.sources=Array.from(searchSources.querySelectorAll("input:checked")).map(e=>e.name);
	        }
	        document.getElementById("searchFrame").contentWindow.postMessage(data,"*");
	    }
	});

	document.getElementById("configBtn").addEventListener("click",function()
	{
	    SC.dialog(function(element)
	    {
	    	element.id="configDialog";
	    	element.classList.add("request");
			var closeBtn=document.createElement("button");
			closeBtn.textContent="ok";
			closeBtn.dataset.action="close";
			closeBtn.autofocus=true;
			element.appendChild(closeBtn);
	    	SC.rq.json({
	    		method:"OPTIONS",
	    		url:"rest/config"
			}).then(function(data)
			{
				element.classList.remove("request");
				element.insertBefore(SC.form(data.description,data.value),closeBtn);
				element.addEventListener("formChange",function(event)
				{
					var field=event.target;
					field.disabled=true;
					SC.rq.json({
						url:"rest/config",
						data:JSON.stringify({
							path:event.detail.path.concat(event.detail.key),
							value:event.detail.value
						})
					})
					.then(function(reply)
					{
						if(!reply.result)
						{
							field.setCustomValidity(reply.error);
						}
					})
					.always(()=>
					event.target.disabled=false);
				});
			});
	    },{modal:true});
	});

	SC.checkDB();

})(Morgas,Morgas.setModule,Morgas.getModule,Morgas.hasModule,Morgas.shortcut);<commit_msg>sort search sources<commit_after>(function(µ,SMOD,GMOD,HMOD,SC){

	var SC=SC({
	    Config:"Config",
	    form:"gui.form",
	    rq:"request",
	    dialog:"gui.dialog",
	    checkDB:"checkDbErrors"
	});

	var searchWrapper=document.getElementById("searchWrapper");

	var searchForm=SC.form({
	   type:"array",
	   model:{
		   type:"string",
		   pattern:/.+/
	   },
	   default:[""]
	}, undefined,"Search");
	searchForm.id="searchForm";
	var firstInput=searchForm.querySelector("input")
	firstInput.accessKey="f";
	firstInput.title="Accesskey F";
	firstInput.autofocus=true;
	searchWrapper.appendChild(searchForm);

	var searchSources;
	SC.rq.json("rest/config").then(function(data)
	{
		var sourcesConfig={};
		var names=Object.keys(data["search"]["search sources"]).sort((a,b)=>a.toLowerCase()>b.toLowerCase());
		for(var sourceName of names)
		{
			sourcesConfig[sourceName]={
				type:"boolean",
				default:false
			};
		}
		searchSources=SC.form(sourcesConfig,undefined,"Sources");
		searchSources.id="searchSources";
		searchSources.classList.add("hidden");
		searchWrapper.appendChild(searchSources);
		searchSources.firstElementChild.addEventListener("click",function()
		{
			searchSources.classList.toggle("hidden")
		})
	});

	var searchBtn=document.getElementById("searchBtn");
	searchForm.addEventListener("keydown",function(e)
	{
		if(e.key=="Enter")
		{
			searchBtn.focus();
			//searchBtn.click();
		}
	});
	searchForm.addEventListener("formAdd",function(e)
	{
		e.detail.element.querySelector("input").focus();
	});
	searchBtn.addEventListener("click",function()
	{
	    if(searchForm.isValid())
	    {
	        var data={query:searchForm.getConfig().get()};
	        if(!searchSources.classList.contains("hidden"))
	        {
	        	data.sources=Array.from(searchSources.querySelectorAll("input:checked")).map(e=>e.name);
	        }
	        document.getElementById("searchFrame").contentWindow.postMessage(data,"*");
	    }
	});

	document.getElementById("configBtn").addEventListener("click",function()
	{
	    SC.dialog(function(element)
	    {
	    	element.id="configDialog";
	    	element.classList.add("request");
			var closeBtn=document.createElement("button");
			closeBtn.textContent="ok";
			closeBtn.dataset.action="close";
			closeBtn.autofocus=true;
			element.appendChild(closeBtn);
	    	SC.rq.json({
	    		method:"OPTIONS",
	    		url:"rest/config"
			}).then(function(data)
			{
				element.classList.remove("request");
				element.insertBefore(SC.form(data.description,data.value),closeBtn);
				element.addEventListener("formChange",function(event)
				{
					var field=event.target;
					field.disabled=true;
					SC.rq.json({
						url:"rest/config",
						data:JSON.stringify({
							path:event.detail.path.concat(event.detail.key),
							value:event.detail.value
						})
					})
					.then(function(reply)
					{
						if(!reply.result)
						{
							field.setCustomValidity(reply.error);
						}
					})
					.always(()=>
					event.target.disabled=false);
				});
			});
	    },{modal:true});
	});

	SC.checkDB();

})(Morgas,Morgas.setModule,Morgas.getModule,Morgas.hasModule,Morgas.shortcut);<|endoftext|>


<commit_before>var list;

$(function () {
    list = $('#questions');
    addQuestion(false);
});

function toggleButton(button) {
    button = $(button);
    var value = button.hasClass('true');

    if (value) {
        button.removeClass('true');
        button.addClass('false');
        button.text('False');
    } else {
        button.removeClass('false');
        button.addClass('true');
        button.text('True');
    }
}

function removeQuestion(questionItem) {
    questionItem.remove();

    if (list.children.length !== 0) {
        return;
        var elements = list.children[list.children.length - 1].children;
        for (var i = 0; i < elements.length; i++) {
            var el = elements[i];

            if (el.prop('tagName') === 'INPUT') {
                el.focus();
                break;
            }
        }
    }
}

function addQuestion(removeable) {
    var item = $('

');
    item.addClass('question');

    var question = $('<input></input>');
    question.attr('placeholder', 'Enter your statement here...');

    var btnTrueFalseToggle = $('<button></button>');
    btnTrueFalseToggle.click(function () {
        toggleButton(btnTrueFalseToggle);
    });
    btnTrueFalseToggle.addClass('true');
    btnTrueFalseToggle.text('True');

    if (removeable) {
        var btnRemove = $('');
        btnRemove.addClass('btn-remove');
        btnRemove.click(function () {
            removeQuestion(item);
        });
        var btnRemoveText = $('');
        btnRemoveText.addClass('material-icons');
        btnRemoveText.text('delete');
        btnRemove.append(btnRemoveText);

        item.append(btnRemove);
    }

    item.append(question);
    item.append(btnTrueFalseToggle);

    list.append(item);

    return {
        giveFocus: function () {
            question.focus();
        }
    }
}

function done() {
    var questions = [];

    list.children().each(function (i, item) {
        item = $(item);

        var question = $(item).children('input').val().trim();
        var answer = item.children('button').text() === 'True';

        if (question.length !== 0) {
            questions.push([question, answer]);
        }
    });

    if (questions.length === 0) {
        $('#modal-error').modal();
    } else {
        var path = '/quiz.html?q=' + btoa(JSON.stringify(questions));
        var longLink = window.location.href + path;

        console.log("Window.location.host: " + window.location.host);
        console.log("path: " + path);

        shortenURL(longLink, function(url) {
            if(url != null){
                $('#text-done').text(url);
                $('#text-done').attr('href', url);
                $('#modal-done').modal();
            }
            else{
                $('#modal-error').modal();
            }
        });
    }
}<commit_msg>Update index.js<commit_after>var list;

$(function () {
    list = $('#questions');
    addQuestion(false);
});

function toggleButton(button) {
    button = $(button);
    var value = button.hasClass('true');

    if (value) {
        button.removeClass('true');
        button.addClass('false');
        button.text('False');
    } else {
        button.removeClass('false');
        button.addClass('true');
        button.text('True');
    }
}

function removeQuestion(questionItem) {
    questionItem.remove();

    if (list.children.length !== 0) {
        return;
        var elements = list.children[list.children.length - 1].children;
        for (var i = 0; i < elements.length; i++) {
            var el = elements[i];

            if (el.prop('tagName') === 'INPUT') {
                el.focus();
                break;
            }
        }
    }
}

function addQuestion(removeable) {
    var item = $('

');
    item.addClass('question');

    var question = $('<input></input>');
    question.attr('placeholder', 'Enter your statement here...');

    var btnTrueFalseToggle = $('<button></button>');
    btnTrueFalseToggle.click(function () {
        toggleButton(btnTrueFalseToggle);
    });
    btnTrueFalseToggle.addClass('true');
    btnTrueFalseToggle.text('True');

    if (removeable) {
        var btnRemove = $('');
        btnRemove.addClass('btn-remove');
        btnRemove.click(function () {
            removeQuestion(item);
        });
        var btnRemoveText = $('');
        btnRemoveText.addClass('material-icons');
        btnRemoveText.text('delete');
        btnRemove.append(btnRemoveText);

        item.append(btnRemove);
    }

    item.append(question);
    item.append(btnTrueFalseToggle);

    list.append(item);

    return {
        giveFocus: function () {
            question.focus();
        }
    }
}

function done() {
    var questions = [];

    list.children().each(function (i, item) {
        item = $(item);

        var question = $(item).children('input').val().trim();
        var answer = item.children('button').text() === 'True';

        if (question.length !== 0) {
            questions.push([question, answer]);
        }
    });

    if (questions.length === 0) {
        $('#modal-error').modal();
    } else {
        var path = '/quiz.html?q=' + btoa(JSON.stringify(questions));
        var longLink = window.location.href + path;

        shortenURL(longLink, function(url) {
            if(url != null){
                $('#text-done').text(url);
                $('#text-done').attr('href', url);
                $('#modal-done').modal();
            }
            else{
                $('#modal-error').modal();
            }
        });
    }
}
<|endoftext|>


<commit_before>var searchTerm = document.querySelector(".text");
var searchButton = document.querySelector(".search-btn");
var entries = document.querySelector(".entries");
var loader = document.querySelector(".loader");
var result = document.querySelector(".result");

// Send text to search
searchTerm.onkeypress = function(event){
  if(event.which === 13){
    event.preventDefault();
    setSearchText(searchTerm.value);
  }
};

searchButton.onclick = function(){
  setSearchText(searchTerm.value);
};

function setSearchText(searchValue) {
  if(searchValue == ""){
    result.innerHTML = "Please enter a text to search!";
  } else {
    entries.innerHTML = "";
    result.innerHTML = "";
    displayLoader(true);
    getArticles(searchValue);
  }
}

function truncateTitle(title, max) {
  if(title.length > max){
    return title.slice(0, max) + "...";
  }
  return title;
}

function checkHits(hits) {
  if(hits == 0){
    result.innerHTML = "No result found, please enter another request.";
    displayLoader(false);
  }
}

function displayLoader(isLoaderVisible) {
  loader.style.display = isLoaderVisible ? "block" : "none";
}

// Get article data
function getArticles(searchValue){
  $.ajax("https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&list=search&titles="+ searchValue +"&rvprop=content&srsearch="+ searchValue +"&srlimit=8&srinfo=totalhits&srprop=snippet", {
    dataType: "jsonp" })

    .done(function(data){

      var searchResults = data.query.search;
      var totalHits = data.query.searchinfo.totalhits;

      // Show message if article doesn't exist
      checkHits(totalHits);

      // Check length of the title
      for(var i = 0; i < searchResults.length; i++){
        var result = searchResults[i];
        var title = result.title;
        var url = "https://en.wikipedia.org/wiki/" + title.replace(/\s/g, "_");

        // Truncate article title
        var maxTitleLength = 34;
        var shortTitle = truncateTitle(title, maxTitleLength);

        // Display articles on the page
        var entryData = "
" + shortTitle + "
" + "
" + result.snippet + "..." + "
";

        // Create entry-container
        var entryContainer = document.createElement("div");
        entryContainer.className = "entry-container";
        entries.appendChild(entryContainer);

        // Create entry
        var div = document.createElement("div");
        div.className = "entry";
        div.innerHTML = entryData;
        entryContainer.appendChild(div);

        // Create entry-overly
        var entryOverly = document.createElement("div");
        entryOverly.className = "entry-overly";
        entryOverly.innerHTML = "Read Article";

        // Create article link
        var a = document.createElement("a");
        a.href = url;
        a.target ="_blank";
        entryContainer.appendChild(a);
        a.appendChild(entryOverly);
      }
      displayLoader(false);
    });
}
<commit_msg>Update index.js<commit_after>var searchTerm = document.querySelector(".text");
var searchButton = document.querySelector(".search-btn");
var entries = document.querySelector(".entries");
var loader = document.querySelector(".loader");
var result = document.querySelector(".result");

// Send text to search
searchTerm.onkeypress = function(event){
  if(event.which === 13){
    event.preventDefault();
    setSearchText(searchTerm.value);
  }
};

searchButton.onclick = function(){
  setSearchText(searchTerm.value);
};

function setSearchText(searchValue) {
  if(searchValue == ""){
    result.innerHTML = "Please enter a text to search!";
  } else {
    entries.innerHTML = "";
    result.innerHTML = "";
    displayLoader(true);
    getArticles(searchValue);
  }
}

function truncateTitle(title, max) {
  if(title.length > max){
    return title.slice(0, max) + "...";
  }
  return title;
}

function checkHits(hits) {
  if(hits == 0){
    result.innerHTML = "No result found, please enter another request.";
    displayLoader(false);
  }
}

function displayLoader(isLoaderVisible) {
  loader.style.display = isLoaderVisible ? "block" : "none";
}

// Get article data
function getArticles(searchValue){
  $.ajax("https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&list=search&titles="+ searchValue +"&rvprop=content&srsearch="+ searchValue +"&srlimit=8&srinfo=totalhits&srprop=snippet", {
    dataType: "jsonp" })

    .done(function(data){

      var searchResults = data.query.search;
      var totalHits = data.query.searchinfo.totalhits;

      // Show message if article doesn't exist
      checkHits(totalHits);

      // Check length of the title
      for(var i = 0; i < searchResults.length; i++){
        var result = searchResults[i];
        var title = result.title;
        var url = "https://en.wikipedia.org/wiki/" + title.replace(/\s/g, "_");

        // Truncate article title
        var maxTitleLength = 30;
        var shortTitle = truncateTitle(title, maxTitleLength);

        // Display articles on the page
        var entryData = "
" + shortTitle + "
" + "
" + result.snippet + "..." + "
";

        // Create entry-container
        var entryContainer = document.createElement("div");
        entryContainer.className = "entry-container";
        entries.appendChild(entryContainer);

        // Create entry
        var div = document.createElement("div");
        div.className = "entry";
        div.innerHTML = entryData;
        entryContainer.appendChild(div);

        // Create entry-overly
        var entryOverly = document.createElement("div");
        entryOverly.className = "entry-overly";
        entryOverly.innerHTML = "Read Article";

        // Create article link
        var a = document.createElement("a");
        a.href = url;
        a.target ="_blank";
        entryContainer.appendChild(a);
        a.appendChild(entryOverly);
      }
      displayLoader(false);
    });
}
<|endoftext|>


<commit_before>//Canvas version
$(function() {
  var ctx = clock.getContext('2d');
  var h = clock.height;
  var w = clock.width;
  var lmin = Math.min(h, w);
  var r = lmin/2 - lmin*0.05;
  var run = false;
  var workMin = $('#work-range').val();
  var pauseMin = $('#pause-range').val();
  var min = 1;
  var sec = 1;
  var timer = 0;
  var perc = 0;
  var pause = false;

  //Define canvas drawing style;
  ctx.strokeStyle = '#FFF';
  ctx.lineWidth = 2;
  ctx.fillStyle = '#FFF';
  ctx.textAlign = "center";

  //Initialize text. setTimeOut is needed in order to give enough time to the canvas for loading the font.
  setTimeout(function() {
    ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "ideographic";
    ctx.fillText(workMin+':00', w/2, h/2+lmin*0.075);
    ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "top";
    ctx.fillText(pauseMin+':00', w/2, h/2+lmin*0.075);
  }, 150);

  //IE doesn't seem to support the input event, however it work with the the change event.
  $('#work-range, #pause-range').on("input change", function() {
    workMin = $('#work-range').val();
    pauseMin = $('#pause-range').val();
    min = 1;
    sec = 1;
    perc = 0;

    //Clear the canvas before drawing on it;
    ctx.clearRect(0,0,250,250);

    //Update the text;
    ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "ideographic";
    ctx.fillText(workMin+':00', w/2, h/2+lmin*0.075);
    ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "top";
    ctx.fillText(pauseMin+':00', w/2, h/2+lmin*0.075);
    });

  $('#clock').click(function() {
  if(run === false) {
    run = true;

    $('#work-range, #pause-range').prop('disabled', true);

    //Update the timer;
    timer = setInterval(function() {
      //Clear the canvas before drawing on it;
      ctx.clearRect(0,0,250,250);

      //Work time...
      if(pause === false) {
        //Update the circle;
        ctx.beginPath();
        ctx.arc(w/2, h/2, r, -Math.PI/2, 2*(++perc/(workMin*60))*Math.PI-Math.PI/2);
        ctx.stroke();

        //Update the text;
        if(sec === 60 && min == workMin) {
          document.querySelector('#bell').play();

          ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "ideographic";
          ctx.fillText(pauseMin+':00', w/2, h/2+lmin*0.075);
          ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "top";
          ctx.fillText(workMin+':00', w/2, h/2+lmin*0.075);

          perc = 0;
          pause = true;
          sec = 1;
          min = 1;
        }
        else if(sec === 60){
          ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "ideographic";
          ctx.fillText(workMin-min+':00', w/2, h/2+lmin*0.075);
          ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "top";
          ctx.fillText(pauseMin+':00', w/2, h/2+lmin*0.075);

          min++;
          sec = 1;
        }
        else {
          ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "ideographic";
          ctx.fillText((workMin-min)+':'+(60-sec), w/2, h/2+lmin*0.075);
          ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "top";
          ctx.fillText(pauseMin+':00', w/2, h/2+lmin*0.075);

          sec++;
        }
      }

      //Pause time!
      else {
        //Update the circle;
        ctx.beginPath();
        ctx.arc(w/2, h/2, r, 2*(++perc/(pauseMin*60))*Math.PI-Math.PI/2, 2*Math.PI-Math.PI/2);
        ctx.stroke();

        //Update the text;
        if(sec === 60 && min == pauseMin) {
          document.querySelector('#bell').play();

          ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "ideographic";
          ctx.fillText(workMin+':00', w/2, h/2+lmin*0.075);
          ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "top";
          ctx.fillText(pauseMin+':00', w/2, h/2+lmin*0.075);

          perc = 0;
          pause = false;
          sec = 1;
          min = 1;
        }
        else if(sec === 60){
          ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "ideographic";
          ctx.fillText(pauseMin-min+':00', w/2, h/2+lmin*0.075);
          ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "top";
          ctx.fillText(workMin+':00', w/2, h/2+lmin*0.075);

          min++;
          sec = 1;
        }
        else {
          ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "ideographic";
          ctx.fillText((pauseMin-min)+':'+(60-sec), w/2, h/2+lmin*0.075);
          ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
          ctx.textBaseline = "top";
          ctx.fillText(workMin+':00', w/2, h/2+lmin*0.075);

          sec++;
        }
      }
    }, 1000);
  }
  else {
    run = false;
    $('#work-range, #pause-range').prop('disabled', false);
    return clearInterval(timer);
    }
  });
});
<commit_msg>Update index.js<commit_after>//Canvas version
$(function() {
  var ctx = clock.getContext('2d');
  var h = clock.height;
  var w = clock.width;
  var lmin = Math.min(h, w);
  var r = lmin/2 - lmin*0.05;
  var run = false;
  var workMin = $('#work-range').val();
  var restMin = $('#rest-range').val();
  var min = 1;
  var sec = 1;
  var timer = 0;
  var perc = 0;
  var rest = false;

  ctx.strokeStyle = '#FFF';
  ctx.lineWidth = 2;
  ctx.fillStyle = '#FFF';
  ctx.textAlign = "center";

  //Initialize text. setTimeOut is needed in order to give enough time to the canvas for loading the font.
  setTimeout(function() {
    ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "ideographic";
    ctx.fillText(workMin+':00', w/2, h/2+lmin*0.075);
    ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "top";
    ctx.fillText(restMin+':00', w/2, h/2+lmin*0.075);
  }, 150);

  //IE doesn't seem to support the input event, however it work with the the change event.
  $('#work-range, #rest-range').on("input change", function() {
    workMin = $('#work-range').val();
    restMin = $('#rest-range').val();
    min = 1;
    sec = 1;
    perc = 0;

    //Clear the canvas before drawing on it;
    ctx.clearRect(0,0,250,250);

    //Update the text;
    ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "ideographic";
    ctx.fillText(workMin+':00', w/2, h/2+lmin*0.075);
    ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
    ctx.textBaseline = "top";
    ctx.fillText(restMin+':00', w/2, h/2+lmin*0.075);
    });

  $('#clock').click(function() {
  if(run === false) {
    run = true;

    $('#work-range, #rest-range').prop('disabled', true);

    //Update the timer;
    timer = setInterval(function() {
      //Clear the canvas before drawing on it;
      ctx.clearRect(0,0,250,250);

      //Work time...
      if(rest === false) {
        //Update the circle;
        ctx.beginPath();
        ctx.arc(w/2, h/2, r, -Math.PI/2, 2*(++perc/(workMin*60))*Math.PI-Math.PI/2);
        ctx.stroke();

        //Update the text;
        if(sec === 60 && min == workMin) {
          document.querySelector('#bell').play();

          textUpdate(ctx, restMin, workMin, 0, sec, w, h, lmin);

          perc = 0;
          rest = true;
          sec = 1;
          min = 1;
        }
        else if(sec === 60){
          textUpdate(ctx, workMin, restMin, min, sec, w, h, lmin);

          min++;
          sec = 1;
        }
        else {
          textUpdate(ctx, workMin, restMin, min, sec, w, h, lmin);

          sec++;
        }
      }

      //rest time!
      else {
        //Update the circle;
        ctx.beginPath();
        ctx.arc(w/2, h/2, r, 2*(++perc/(restMin*60))*Math.PI-Math.PI/2, 2*Math.PI-Math.PI/2);
        ctx.stroke();

        //Update the text;
        if(sec === 60 && min == restMin) {
          document.querySelector('#bell').play();

          textUpdate(ctx, workMin, restMin, 0, sec, w, h, lmin);

          perc = 0;
          rest = false;
          sec = 1;
          min = 1;
        }
        else if(sec === 60){
          textUpdate(ctx, restMin, workMin, min, sec, w, h, lmin);

          min++;
          sec = 1;
        }
        else {
          textUpdate(ctx, restMin, workMin, min, sec, w, h, lmin);

          sec++;
        }
      }
    }, 1000);
  }
  else {
    run = false;
    $('#work-range, #rest-range').prop('disabled', false);
    return clearInterval(timer);
    }
  });
});

function textUpdate(ctx, bigTextMin, smallTextMin, min, sec, w, h, lmin) {
  var secStr = (60-sec).toString();

  ctx.font = lmin*0.15+"px 'Poiret One', 'Arial'";
  ctx.textBaseline = "ideographic";
  if(secStr.length == 2) ctx.fillText((bigTextMin-min)+':'+(60-sec), w/2, h/2+lmin*0.075);
  else ctx.fillText((bigTextMin-min)+':0'+(60-sec), w/2, h/2+lmin*0.075);
  ctx.font = lmin*0.075+"px 'Poiret One', 'Arial'";
  ctx.textBaseline = "top";
  ctx.fillText(smallTextMin+':00', w/2, h/2+lmin*0.075);

  return 0;
}
<|endoftext|>