<commit_before>/** @preserve direction.js (c) 2015 Seun Ogedengbe, MIT*/
/**
 * @suppress {globalThis}
 */
direction = function(input, anchor, owrite, config) {
  //input - an object, list, or string
  //anchor - the html object to append
  //owrite - index of image to start carousel on
  //config - configuration options

  if (void 0 === input) return -1;
  owrite = owrite || 0;
  config = config || {};
  if (void 0 === anchor || anchor == null) anchor = document.body;

  //PROPERTIES - private
  var iimg = input.slice(),
    spinning = true, //is the spinner spinning?
    current = -1, //-1 for unset, corresponds to current page
    spinner = {
      lines: config.lines || 16,
      rate: config.rate || 1000 / 30,
      diameter: config.diameter || 250,
      back: config.loaderback || "#FFF",
      color: config.color || "#373737"
    },
    options = {
      dir: config.dir || "assets/",
      imgprebuffer: config.imgprebuffer || 5,
      imgpostbuffer: config.imgpostbuffer || 5,
      back: config.back || "#FFF"
    },
    pstload = [],
    preload = [],
    master = new Image(),
    skroll = true,
    layers = [
      document.createElement("canvas"),
      document.createElement("canvas")
    ],
    context = layers[1].getContext("2d"),
    //METHODS - private
    //n = function(){return 0},//this null fuction save us some bytes
    cb = {
      run: function(a) {
        for (var b = 0; b < cb[a].length; b++) {
          cb[a][b]();
        }
      },
      start: [],
      slidn: [],
      slidd: []
    },
    object = {
      context: layers[0].getContext("2d"),
      color: spinner.color,
      start: Date.now(),
      lines: spinner.lines,
      diameter: spinner.diameter,
      rate: spinner.rate
    },
    spin = function(a) {
      layers[0].style.paddingLeft = (layers[1].width - 300) / 2 + "px";
      var rotation =
          Math.floor((Date.now() - a.start) / 1000 * a.lines) / a.lines,
        c = a.color.substr(1);
      a.context.save();
      a.context.clearRect(0, 0, 300, layers[1].height);
      a.context.translate(150, layers[1].height / 2);
      a.context.rotate(Math.PI * 2 * rotation);

      if (c.length == 3) c = c[0] + C[0] + c[1] + c[1] + c[2] + c[2];
      var red = parseInt(c.substr(0, 2), 16).toString(),
        green = parseInt(c.substr(2, 2), 16).toString(),
        blue = parseInt(c.substr(4, 2), 16).toString();

      for (var i = 0; i < a.lines; i++) {
        a.context.beginPath();
        a.context.rotate(Math.PI * 2 / a.lines);
        a.context.moveTo(a.diameter / 10, 0);
        a.context.lineTo(a.diameter / 4, 0);
        a.context.lineWidth = a.diameter / 30;
        a.context.strokeStyle =
          "rgba(" + red + "," + green + "," + blue + "," + i / a.lines + ")";
        a.context.stroke();
      }
      a.context.restore();
      if (spinning) window.setTimeout(spin, a.rate, object);
      else a.context.clearRect(0, 0, 300, layers[1].height);
    },
    scrollit = function(to, time) {
      //format inputs
      if (to === null || void 0 === to) to = { x: 0, y: 0 };
      else if (!isNaN(to)) to = { x: 0, y: to };
      //if to is num assume its y
      else {
        if (to.y === null || void 0 === to.y) to.y = 0;
        if (to.x === null || void 0 === to.x) to.x = 0;
      }
      if (time === null || void 0 === time || time <= 0) time = 400; //ignore given zero time

      //if x or y is less than 0 then go to the bottom
      if (to.y < 0)
        to.y =
          window.innerHeight ||
          document.documentElement.clientHeight ||
          document.body.clientHeight;
      if (to.x < 0)
        to.x =
          window.innerWidth ||
          document.documentElement.clientWidth ||
          document.body.clientWidth;

      //calculate distance needed to travel
      var dis = {
        x:
          window.pageXOffset !== void 0
            ? to.x - window.pageXOffset
            : to.x - document.documentElement.scrollLeft,
        y:
          window.pageYOffset !== void 0
            ? to.y - window.pageYOffset
            : to.y - document.documentElement.scrollTop
      };

      /*
                dis.x = (window.pageXOffset === void 0) ? to.x - window.pageXOffset : to.x - document.documentElement.scrollLeft;
                dis.y = (window.pageYOffset === void 0) ? to.y - window.pageYOffset : to.y - document.documentElement.scrollTop;
                */
      //console.log("to", to, "dis" ,dis, "(x", window.pageXOffset, document.documentElement.scrollLeft, "| y", window.pageYOffset, document.documentElement.scrollTop, ")" , time, time/5);

      if (dis == { x: 0, y: 0 }) return dis; //if that distance is 0 on both x and y, no scrolling required
      var clock = function(c, b, a) {
        window.scrollBy(Math.floor(c.x) / b, Math.floor(c.y) / b);
        if (a + 1 < b * 5) window.setTimeout(clock, 5, c, b, a + 1);
      };
      window.setTimeout(clock, 5, dis, Math.floor(time / 5), 0);
      //window.clearInterval(clock);
      return dis;
    },
    preloadGeneric = function() {
      iimg[this.imaginaryID].loaded = true;
      /*possible implementation - Delete it when we are done, possibly saves memory, since its been cached?
                this.imaginaryID=-1;
                this.src="";*/
    },
    preloadMaster = function() {
      //actually a misnomer, master doesnt actually preload, it loads and draws
      if (iimg[this.imaginaryID].loaded)
        context.clearRect(0, 0, this.width, this.height);
      else iimg[this.imaginaryID].loaded = true;
      cb.run("slidn");
      //conviently, this callback draws the image as soon as master's src is changed and image loaded
      layers[1].width /*= layers[0].width = objref.acW */ = this.width;
      layers[1].height = layers[0].height /*= objref.acH*/ = this.height;
      context.drawImage(this, 0, 0);
      //current = this.imaginaryID;//do not wait on load for page change, do not change page on page load
      /*
                console.log("killing", intervall);
                window.clearInterval(intervall);
                intervall = -1;
                */
      spinning = 0;
      if (skroll) scrollit();
      cb.run("slidd");
    },
    assign = function(imagething, idd) {
      //assign helper, assigns an src and iid according to given id
      //console.log("World");
      /*console.log("dead",intervall);
                if(intervall<0) intervall = window.setInterval(spin, spinner.rate, object);
                console.log("started",intervall);*/
      spinning = true;
      window.setTimeout(spin, spinner.rate, object);
      cb.run("start"); //slidestart();
      if (idd < 0) idd = 0; //if lower than zero set to zero
      if (idd >= iimg.length) idd = iimg.length - 1; //can not be equal to our higher than the amount of pages
      if (!iimg[idd].loaded)
        context.clearRect(0, 0, layers[1].width, layers[1].height);
      imagething.imaginaryID = idd;
      imagething.src = options.dir + iimg[idd];
      current = idd; //we change page as soon as it is assigned, so that page still changes even if it never loads
      /*console.log("----");
            for(var q = idd-1;q>idd-self.config.imgprebuffer-1&&q>=0;q--){
                console.log(q);
            }
            console.log("//");
            for(var q = idd+1;q<self.config.imgpostbuffer+idd+1&&q<self.count;q++){
                console.log(q);
                continue;

            console.log("----");*/
      var r = 0;
      for (var q = idd - 1; q > idd - options.imgprebuffer - 1 && q >= 0; q--) {
        if (iimg[q].loaded) continue;
        preload[r].imaginaryID = q;
        preload[r].src = options.dir + iimg[q];
        r++;
      }
      r = 0;
      for (
        var q = idd + 1;
        q < options.imgpostbuffer + idd + 1 && q < iimg.length;
        q++
      ) {
        if (iimg[q].loaded) continue;
        pstload[r].imaginaryID = q;
        pstload[r].src = options.dir + iimg[q];
        r++;
      }
    },
    jq = function() {
      try {
        jQuery.fn.direction = function(a, b, c) {
          return this.each(function() {
            direction(a, $(this), b, c);
          });
        };
      } catch (e) {
        console.log("failed to attach to jQuery");
      }
    };
  if (window.jQuery) jq();

  //PROPERTIES - public
  this.iimg = iimg;
  this.canvi = layers;
  this.internals = input;
  this.cb = cb;
  //METHODS - public
  this.count = function() {
    return iimg.length;
  };
  this.current = function() {
    return current;
  };
  this.callback = function(type, callback, index) {
    if (type === null || void 0 === type) return cb.slidn;

    if (callback === null || void 0 === callback) {
      return index === null || void 0 === index
        ? type
          ? type > 0
            ? cb.slidd[index]
            : cb.start[index]
          : cb.slidn[index]
        : type
          ? type > 0
            ? cb.slidd
            : cb.start
          : cb.slidn;
    }

    if (type && (index === null || void 0 === index)) {
      if (type > 0) cb.slidd.push(callback);
      else cb.start.push(callback);
    } else if (index === null || void 0 === index) cb.slidn.push(callback);

    return 1;

    /*if(type===null||void 0===type) return sliding;
            if(callback===null||void 0===callback) return (type)?(type>0)?slidend:slidestart:sliding;
            if(type)
                if(type>0) slidend = callback;
                else slidestart = callback;
            else sliding = callback;
            return 1;*/
  };
  this.go = function(to) {
    var sre = to === null || void 0 === to ? 0 : parseInt(to, 10);
    //console.log(sre);
    sre = isNaN(sre) ? 0 : sre;
    assign(master, Math.floor(Math.max(0, Math.min(iimg.length - 1, sre))));
    return sre;
  };
  this.prev = function() {
    var sre = current - 1; //avoids possible race condition, assign loads in new image which can call preloadMaster which can change self.current before it gets to the return call. storing it premptively will preserve the value
    if (sre >= 0) assign(master, sre);
    return sre;
  };
  this.next = function() {
    //console.log("Hello");
    var sre = current + 1;
    if (sre < iimg.length) assign(master, sre);
    return sre;
  };
  this.frst = function() {
    if (current >= 0) assign(master, 0);
    return 0;
  };
  this.last = function() {
    assign(master, iimg.length - 1);
    return iimg.length - 1;
  };
  this.rand = function() {
    var sre = Math.floor(Math.random() * (iimg.length - 1));
    //console.log(sre);
    assign(master, sre);
    return sre;
  };
  this.data = function(to) {
    //returns info about slide
    var sre = to === null || void 0 === to ? current : parseInt(to, 10);
    return isNaN(sre)
      ? iimg[current]
      : iimg[Math.floor(Math.max(0, Math.min(iimg.length - 1, sre)))];
  };
  this.scroll = function(bool) {
    //toggles Auto Scrolling
    if (!(bool === null || void 0 === bool)) skroll = bool;
    return skroll;
  };
  this.scrollTo = function(to, time) {
    return scrollit(to, time);
  }; //public wrapper for scrollit
  //LOADER - setup
  layers[0].height = 480;
  //layers[0].width=640;
  layers[0].style.background = spinner.back;
  layers[0].style.paddingLeft = "170px";
  layers[0].style.zIndex = 0;
  layers[0].style.position = "absolute";

  //objref = object;
  //console.log(layers[1]);
  if (anchor) anchor.appendChild(layers[0]);
  else document.body.appendChild(layers[0]);
  //console.log(object);
  //intervall=window.setInterval(spin, spinner.rate, object);
  window.setTimeout(spin, spinner.rate, object);
  //DISPLAY - setup
  master = new Image();
  master.imaginaryID = -1; //unset to an imaginary image
  master.addEventListener("load", preloadMaster, false);
  //console.log(this.master);
  var q;
  for (q = 0; q < iimg.length; q++) {
    //iimg[q].btog = 0; a holdover from the old html based canvas
    iimg[q].desig = q ? (q == iimg.length - 1 ? 1 : 0) : -1; //-1 means first, 0 means middle, 1 means last: true if endpoint, false if middle
    iimg[q].loaded = false;
  }
  for (q = 0; q < options.imgprebuffer; q++) {
    preload.push(new Image());
    preload[q].imaginaryID = -1; //unset to an imaginary image
    preload[q].addEventListener("load", preloadGeneric, false);
  }
  for (q = 0; q < options.imgpostbuffer; q++) {
    pstload.push(new Image());
    pstload[q].imaginaryID = -1; //unset to an imaginary image
    pstload[q].addEventListener("load", preloadGeneric, false);
  }
  //preload[0].imaginaryID = 0;
  //preload[0].src = input.pages[0].url;
  //init
  assign(master, options.startpage || owrite);
  //end init
  layers[1].height = 480;
  layers[1].width = 640;
  layers[1].background = options.back;
  layers[1].style.zIndex = 1;
  layers[1].style.position = "relative";
  //layers[1].style.visibility="hidden";
  if (anchor) anchor.appendChild(layers[1]);
  else document.body.appendChild(layers[1]);
};
<commit_msg>final direction format<commit_after>/** @preserve direction.js (c) 2015 Seun Ogedengbe, MIT*/
/**
 * @suppress {globalThis}
 */
direction = function (input, anchor, owrite, config) {
    //input - an object, list, or string
    //anchor - the html object to append
    //owrite - index of image to start carousel on
    //config - configuration options

    if (void 0 === input) return -1;
    owrite = owrite || 0;
    config = config || {};
    if (void 0 === anchor || anchor == null) anchor = document.body;

    //PROPERTIES - private
    var iimg = input.slice(),
        spinning = true, //is the spinner spinning?
        current = -1, //-1 for unset, corresponds to current page
        spinner = {
            lines: config.lines || 16,
            rate: config.rate || 1000 / 30,
            diameter: config.diameter || 250,
            back: config.loaderback || "#FFF",
            color: config.color || "#373737"
        },
        options = {
            dir: config.dir || "assets/",
            imgprebuffer: config.imgprebuffer || 5,
            imgpostbuffer: config.imgpostbuffer || 5,
            back: config.back || "#FFF"
        },
        pstload = [],
        preload = [],
        master = new Image(),
        skroll = true,
        layers = [
            document.createElement("canvas"),
            document.createElement("canvas")
        ],
        context = layers[1].getContext("2d"),
        //METHODS - private
        //n = function(){return 0},//this null fuction save us some bytes
        cb = {
            run: function (a) {
                for (var b = 0; b < cb[a].length; b++) {
                    cb[a][b]();
                }
            },
            start: [],
            slidn: [],
            slidd: []
        },
        object = {
            context: layers[0].getContext("2d"),
            color: spinner.color,
            start: Date.now(),
            lines: spinner.lines,
            diameter: spinner.diameter,
            rate: spinner.rate
        },
        spin = function (a) {
            layers[0].style.paddingLeft = (layers[1].width - 300) / 2 + "px";
            var rotation =
                Math.floor((Date.now() - a.start) / 1000 * a.lines) / a.lines,
                c = a.color.substr(1);
            a.context.save();
            a.context.clearRect(0, 0, 300, layers[1].height);
            a.context.translate(150, layers[1].height / 2);
            a.context.rotate(Math.PI * 2 * rotation);

            if (c.length == 3) c = c[0] + C[0] + c[1] + c[1] + c[2] + c[2];
            var red = parseInt(c.substr(0, 2), 16).toString(),
                green = parseInt(c.substr(2, 2), 16).toString(),
                blue = parseInt(c.substr(4, 2), 16).toString();

            for (var i = 0; i < a.lines; i++) {
                a.context.beginPath();
                a.context.rotate(Math.PI * 2 / a.lines);
                a.context.moveTo(a.diameter / 10, 0);
                a.context.lineTo(a.diameter / 4, 0);
                a.context.lineWidth = a.diameter / 30;
                a.context.strokeStyle =
                    "rgba(" + red + "," + green + "," + blue + "," + i / a.lines + ")";
                a.context.stroke();
            }
            a.context.restore();
            if (spinning) window.setTimeout(spin, a.rate, object);
            else a.context.clearRect(0, 0, 300, layers[1].height);
        },
        scrollit = function (to, time) {
            //format inputs
            if (to === null || void 0 === to) to = { x: 0, y: 0 };
            else if (!isNaN(to)) to = { x: 0, y: to };
            //if to is num assume its y
            else {
                if (to.y === null || void 0 === to.y) to.y = 0;
                if (to.x === null || void 0 === to.x) to.x = 0;
            }
            if (time === null || void 0 === time || time <= 0) time = 400; //ignore given zero time

            //if x or y is less than 0 then go to the bottom
            if (to.y < 0)
                to.y =
                    window.innerHeight ||
                    document.documentElement.clientHeight ||
                    document.body.clientHeight;
            if (to.x < 0)
                to.x =
                    window.innerWidth ||
                    document.documentElement.clientWidth ||
                    document.body.clientWidth;

            //calculate distance needed to travel
            var dis = {
                x:
                    window.pageXOffset !== void 0
                        ? to.x - window.pageXOffset
                        : to.x - document.documentElement.scrollLeft,
                y:
                    window.pageYOffset !== void 0
                        ? to.y - window.pageYOffset
                        : to.y - document.documentElement.scrollTop
            };

            /*
                      dis.x = (window.pageXOffset === void 0) ? to.x - window.pageXOffset : to.x - document.documentElement.scrollLeft;
                      dis.y = (window.pageYOffset === void 0) ? to.y - window.pageYOffset : to.y - document.documentElement.scrollTop;
                      */
            //console.log("to", to, "dis" ,dis, "(x", window.pageXOffset, document.documentElement.scrollLeft, "| y", window.pageYOffset, document.documentElement.scrollTop, ")" , time, time/5);

            if (dis == { x: 0, y: 0 }) return dis; //if that distance is 0 on both x and y, no scrolling required
            var clock = function (c, b, a) {
                window.scrollBy(Math.floor(c.x) / b, Math.floor(c.y) / b);
                if (a + 1 < b * 5) window.setTimeout(clock, 5, c, b, a + 1);
            };
            window.setTimeout(clock, 5, dis, Math.floor(time / 5), 0);
            //window.clearInterval(clock);
            return dis;
        },
        preloadGeneric = function () {
            iimg[this.imaginaryID].loaded = true;
            /*possible implementation - Delete it when we are done, possibly saves memory, since its been cached?
                      this.imaginaryID=-1;
                      this.src="";*/
        },
        preloadMaster = function () {
            //actually a misnomer, master doesnt actually preload, it loads and draws
            if (iimg[this.imaginaryID].loaded)
                context.clearRect(0, 0, this.width, this.height);
            else iimg[this.imaginaryID].loaded = true;
            cb.run("slidn");
            //conviently, this callback draws the image as soon as master's src is changed and image loaded
            layers[1].width /*= layers[0].width = objref.acW */ = this.width;
            layers[1].height = layers[0].height /*= objref.acH*/ = this.height;
            context.drawImage(this, 0, 0);
            //current = this.imaginaryID;//do not wait on load for page change, do not change page on page load
            /*
                      console.log("killing", intervall);
                      window.clearInterval(intervall);
                      intervall = -1;
                      */
            spinning = 0;
            if (skroll) scrollit();
            cb.run("slidd");
        },
        assign = function (imagething, idd) {
            //assign helper, assigns an src and iid according to given id
            //console.log("World");
            /*console.log("dead",intervall);
                      if(intervall<0) intervall = window.setInterval(spin, spinner.rate, object);
                      console.log("started",intervall);*/
            spinning = true;
            window.setTimeout(spin, spinner.rate, object);
            cb.run("start"); //slidestart();
            if (idd < 0) idd = 0; //if lower than zero set to zero
            if (idd >= iimg.length) idd = iimg.length - 1; //can not be equal to our higher than the amount of pages
            if (!iimg[idd].loaded)
                context.clearRect(0, 0, layers[1].width, layers[1].height);
            imagething.imaginaryID = idd;
            imagething.src = options.dir + iimg[idd];
            current = idd; //we change page as soon as it is assigned, so that page still changes even if it never loads
            /*console.log("----");
                  for(var q = idd-1;q>idd-self.config.imgprebuffer-1&&q>=0;q--){
                      console.log(q);
                  }
                  console.log("//");
                  for(var q = idd+1;q<self.config.imgpostbuffer+idd+1&&q<self.count;q++){
                      console.log(q);
                      continue;

                  console.log("----");*/
            var r = 0,
                q = 0;
            for (q = idd - 1; q > idd - options.imgprebuffer - 1 && q >= 0; q--) {
                if (iimg[q].loaded) continue;
                preload[r].imaginaryID = q;
                preload[r].src = options.dir + iimg[q];
                r++;
            }
            r = 0;
            for (
                q = idd + 1;
                q < options.imgpostbuffer + idd + 1 && q < iimg.length;
                q++
            ) {
                if (iimg[q].loaded) continue;
                pstload[r].imaginaryID = q;
                pstload[r].src = options.dir + iimg[q];
                r++;
            }
        },
        jq = function () {
            try {
                jQuery.fn.direction = function (a, b, c) {
                    return this.each(function () {
                        direction(a, $(this), b, c);
                    });
                };
            } catch (e) {
                console.log("failed to attach to jQuery");
            }
        };
    if (window.jQuery) jq();

    //PROPERTIES - public
    this.iimg = iimg;
    this.canvi = layers;
    this.internals = input;
    this.cb = cb;
    //METHODS - public
    this.count = function () {
        return iimg.length;
    };
    this.current = function () {
        return current;
    };
    this.callback = function (type, callback, index) {
        if (type === null || void 0 === type) return cb.slidn;

        if (callback === null || void 0 === callback) {
            return index === null || void 0 === index
                ? type
                    ? type > 0
                        ? cb.slidd[index]
                        : cb.start[index]
                    : cb.slidn[index]
                : type
                    ? type > 0
                        ? cb.slidd
                        : cb.start
                    : cb.slidn;
        }

        if (type && (index === null || void 0 === index)) {
            if (type > 0) cb.slidd.push(callback);
            else cb.start.push(callback);
        } else if (index === null || void 0 === index) cb.slidn.push(callback);

        return 1;

        /*if(type===null||void 0===type) return sliding;
                if(callback===null||void 0===callback) return (type)?(type>0)?slidend:slidestart:sliding;
                if(type)
                    if(type>0) slidend = callback;
                    else slidestart = callback;
                else sliding = callback;
                return 1;*/
    };
    this.go = function (to) {
        var sre = to === null || void 0 === to ? 0 : parseInt(to, 10);
        //console.log(sre);
        sre = isNaN(sre) ? 0 : sre;
        assign(master, Math.floor(Math.max(0, Math.min(iimg.length - 1, sre))));
        return sre;
    };
    this.prev = function () {
        var sre = current - 1; //avoids possible race condition, assign loads in new image which can call preloadMaster which can change self.current before it gets to the return call. storing it premptively will preserve the value
        if (sre >= 0) assign(master, sre);
        return sre;
    };
    this.next = function () {
        //console.log("Hello");
        var sre = current + 1;
        if (sre < iimg.length) assign(master, sre);
        return sre;
    };
    this.frst = function () {
        if (current >= 0) assign(master, 0);
        return 0;
    };
    this.last = function () {
        assign(master, iimg.length - 1);
        return iimg.length - 1;
    };
    this.rand = function () {
        var sre = Math.floor(Math.random() * (iimg.length - 1));
        //console.log(sre);
        assign(master, sre);
        return sre;
    };
    this.data = function (to) {
        //returns info about slide
        var sre = to === null || void 0 === to ? current : parseInt(to, 10);
        return isNaN(sre)
            ? iimg[current]
            : iimg[Math.floor(Math.max(0, Math.min(iimg.length - 1, sre)))];
    };
    this.scroll = function (bool) {
        //toggles Auto Scrolling
        if (!(bool === null || void 0 === bool)) skroll = bool;
        return skroll;
    };
    this.scrollTo = function (to, time) {
        return scrollit(to, time);
    }; //public wrapper for scrollit
    //LOADER - setup
    layers[0].height = 480;
    //layers[0].width=640;
    layers[0].style.background = spinner.back;
    layers[0].style.paddingLeft = "170px";
    layers[0].style.zIndex = 0;
    layers[0].style.position = "absolute";

    //objref = object;
    //console.log(layers[1]);
    if (anchor) anchor.appendChild(layers[0]);
    else document.body.appendChild(layers[0]);
    //console.log(object);
    //intervall=window.setInterval(spin, spinner.rate, object);
    window.setTimeout(spin, spinner.rate, object);
    //DISPLAY - setup
    master = new Image();
    master.imaginaryID = -1; //unset to an imaginary image
    master.addEventListener("load", preloadMaster, false);
    //console.log(this.master);
    var q;
    for (q = 0; q < iimg.length; q++) {
        //iimg[q].btog = 0; a holdover from the old html based canvas
        iimg[q].desig = q ? (q == iimg.length - 1 ? 1 : 0) : -1; //-1 means first, 0 means middle, 1 means last: true if endpoint, false if middle
        iimg[q].loaded = false;
    }
    for (q = 0; q < options.imgprebuffer; q++) {
        preload.push(new Image());
        preload[q].imaginaryID = -1; //unset to an imaginary image
        preload[q].addEventListener("load", preloadGeneric, false);
    }
    for (q = 0; q < options.imgpostbuffer; q++) {
        pstload.push(new Image());
        pstload[q].imaginaryID = -1; //unset to an imaginary image
        pstload[q].addEventListener("load", preloadGeneric, false);
    }
    //preload[0].imaginaryID = 0;
    //preload[0].src = input.pages[0].url;
    //init
    assign(master, options.startpage || owrite);
    //end init
    layers[1].height = 480;
    layers[1].width = 640;
    layers[1].background = options.back;
    layers[1].style.zIndex = 1;
    layers[1].style.position = "relative";
    //layers[1].style.visibility="hidden";
    if (anchor) anchor.appendChild(layers[1]);
    else document.body.appendChild(layers[1]);
};
<|endoftext|>


<commit_before>import gh from 'hast-util-sanitize/lib/github';
import {merge} from 'lodash';
import React from 'react';
import remark from 'remark';
import emoji from 'remark-gemoji-to-emoji';
import vdom from 'remark-vdom';

import MarkdownLink from './markdown-link';
import MarkdownCode from './markdown-code';
import MarkdownHeadline from './markdown-headline';
import wrap from './wrap';

export default render;

function render(source, options) {
	const {base, hash, highlights, highlight, query, pathname, onHashChange} = options;
	const h = React.createElement;
	const headline = wrap(MarkdownHeadline);

	const link = {base, hash, query, pathname, onHashChange};
	const code = {highlights, highlight};

	const components = {
		a: wrap(MarkdownLink, link),
		code: wrap(MarkdownCode, code),
		h1: headline,
		h2: headline,
		h3: headline,
		h4: headline,
		h5: headline,
		h6: headline
	};

	const sanitize = merge({}, gh);
	sanitize.attributes = {
		a: ['href', 'title'],
		code: ['className'],
		img: ['src', 'alt']
	};

	const opts = {h, components, sanitize};

	return remark()
		.use(vdom, opts)
		.use(emoji)
		.process(source)
		.contents;
}
<commit_msg>fix: render markdown tables manually to avoid react markup warnings<commit_after>import gh from 'hast-util-sanitize/lib/github';
import {merge} from 'lodash';
import React, {Children} from 'react';
import remark from 'remark';
import emoji from 'remark-gemoji-to-emoji';
import vdom from 'remark-vdom';

import MarkdownLink from './markdown-link';
import MarkdownCode from './markdown-code';
import MarkdownHeadline from './markdown-headline';
import wrap from './wrap';

export default render;

function render(source, options) {
	const {base, hash, highlights, highlight, query, pathname, onHashChange} = options;
	const h = React.createElement;
	const headline = wrap(MarkdownHeadline);

	const table = wrap(strictChildren(MarkdownGeneric, ['thead', 'tbody']));
	const tbody = wrap(strictChildren(MarkdownGeneric, ['tr']));
	const tr = wrap(strictChildren(MarkdownGeneric, ['td', 'th']));
	const td = wrap(MarkdownGeneric);

	const link = {base, hash, query, pathname, onHashChange};
	const code = {highlights, highlight};

	const components = {
		a: wrap(MarkdownLink, link),
		code: wrap(MarkdownCode, code),
		h1: headline,
		h2: headline,
		h3: headline,
		h4: headline,
		h5: headline,
		h6: headline,
		table,
		thead: tbody,
		tbody,
		tr,
		th: td,
		td
	};

	const sanitize = merge({}, gh);
	sanitize.attributes = {
		a: ['href', 'title'],
		code: ['className'],
		img: ['src', 'alt']
	};

	const opts = {h, components, sanitize};

	return remark()
		.use(vdom, opts)
		.use(emoji)
		.process(source)
		.contents;
}

function MarkdownGeneric(props) {
	const Component = props.tagName;
	return <Component>{props.children}</Component>;
}

function strictChildren(Component, tagNames) {
	return props => {
		const children = Children.toArray(props.children)
			.filter(child => {
				return typeof child === 'object' && tagNames.includes(child.props.tagName);
			});
		return <Component {...props}>{children}</Component>;
	};
}
<|endoftext|>


<commit_before>Array.prototype.insert = function(index) {
    index = Math.min(index, this.length);
    arguments.length > 1
        && this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
        && this.insert.apply(this, arguments);
    return this;
};

(function($) {
	$.isMobile = function() {
		if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|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|phone)|xda|xiino/i.test(navigator.userAgent) || /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(navigator.userAgent.substr(0,4))) {
			return true;
		} else {
			return false;
		}
	}
	$.createWithID = function(tag, id) {
		var element = document.createElement(tag.toLowerCase());
		if(typeof(id) != "undefined") element.id = id;
		return $(element);
	}
	$.createParagraph = function(id, className, text) {
		var paragraph = document.createElement("p");
		if(typeof(id) != "undefined") paragraph.id = id;
		if(typeof(className) != "undefined") paragraph.className = className;
		if(typeof(text) != "undefined") {
			var text = document.createTextNode(text);
			paragraph.appendChild(text);
		}
		return $(paragraph);
	}
	$.createButton = function(id, className, text) {
		var button = document.createElement("button");
		button.type = "button";
		if(typeof(id) != "undefined") button.id = id;
		if(typeof(className) != "undefined") button.className = className;
		if(typeof(text) != "undefined") {
			var text = document.createTextNode(text);
			button.appendChild(text);
		}
		return $(button);

	}
	$.createCheckboxInput = function(id, className, name, text, value) {
		var label = document.createElement("label");
		var input = document.createElement("input");
		input.type = "checkbox";
		if(typeof(id) != "undefined") input.id = id;
		if(typeof(className) != "undefined") input.className = className;
		if(typeof(name) != "undefined") input.name = name;
		if(typeof(value) != "undefined") input.value = value;
		label.appendChild(input);
		if(typeof(text) != "undefined") {
			var text = document.createTextNode(text);
			label.appendChild(text);
		}
		return $(label);
	}
	$.createSubmit = function(id, className, value) {
		var input = document.createElement("input");
		input.type = "submit";
		if(typeof(id) != "undefined") input.id = id;
		if(typeof(className) != "undefined") input.className = className;
		if(typeof(value) != "undefined") input.value = value;
		return $(input);
	}
}(jQuery));

var index = 0;
var results = [];
var questions;
var distributions;
var scores = [];

function CheckResults() {
	for(var a = 0; a < distributions.length; a++) {
		distributions[a].score = 0;
		distributions[a ].maximum = 0;
		for(var b = 0; b < distributions[a].questions.length; b++) {
			for(var c = 0; c < results.length; c++) {
				if(distributions[a].questions[b].question == results[c].question) {
					for(var d = 0; d < distributions[d].question[b].answers.length; d++) {
						distributions[a].maximum++;
						for(var e = 0; e < results[c].answers.length; e++) {
							if(distributions[d].question[b].answers[d].replace(/[^a-ä0-9]/gi, '_') == results[c].answers[d]) {
								distributions[a].score;
							}
						}
					}
				}
			}
		}
	}
}

function LoadQuestion(question) {
	$("#selection").empty();
	$("#selection").append($.createWithID("h2", "question-header"));
	$("#question-header").text(question.question);
	$("#selection").append($.createWithID("form", "answers"));
	for(var x = 0; x < question.answers.length; x++) {
		var answerID = question.answers[x].answer.replace(/[^a-ä0-9]/gi, '_');
		$("#answers").append($.createCheckboxInput(answerID, "answer_inputs", "answers", question.answers[x].answer, question.answers[x].answer));
	}
	$("#answers").append($.createSubmit("answer-submit", "btn btn-primary btn-block", "Seuraava"));
	$("#answer-submit").click(function(evt) {
		evt.preventDefault();
		var answers = [];
		$(".answer_inputs").each(function() {
			if($(this).prop("checked") == true) {
				answers.push($(this).prop("id"));
			}
		});
		var result = { question : $("#question-header").text(), answers : answers };
		results.push(result);
		console.log(results);
		// load subquestions based on results if there are them.
		if(answers.length > 0) {
			for(var y = 0; y < answers.length; y++) {
				for(var x = 0; x < question.answers.length; x++) {
					var answerID = question.answers[x].answer.replace(/[^a-ä0-9]/gi, '_');
					if(answerID == answers[y]) {
						for(var d = 0; d < question.answers[x].subquestions.length; d++) {
							// needs to check if the question is not yet appended or has to do subquestion deletion on back button.
							questions.insert(index + 1 + d, question.answers[x].subquestions[d]);
						}
					}
				}
			}
		}
		var tmpIndex = index + 1;
		if(questions.length > tmpIndex) {
			index = tmpIndex;
			LoadQuestion(questions[index]);
			return;
		}
	});
	$("#answers").append($.createButton("answer-back", "btn btn-warning btn-block", "Edellinen"));
	$("#answer-back").click(function(evt) {
		evt.preventDefault();
		var tmpIndex = index - 1;
		if(tmpIndex >= 0) {
			index = tmpIndex;
			delete results[index];
			LoadQuestion(questions[index]);
		}
	});
	$("#answers").append($.createButton("answer-end", "btn btn-success btn-block", "Katso tulokset"));
	$("#answers").append($.createButton("answer-stop", "btn btn-danger btn-block", "Keskeytä testi"));
	$("#answer-stop").click(function(evt) {
		evt.preventDefault();
		index = 0;
		results = [];
		$.getJSON("questions.json", function(data) {
			questions = data.questions;
		});
		LoadSplash();
	});
}

function LoadSplash() {
	$("#selection").empty();
	$("#selection").append($.createParagraph("", "", "Tervetuloa. Olet saattanut kuulla käyttöjärjestelmästä nimeltä Linux ja huomannut niitä olevan paljon erilaisia kuten Mint, Debian ja Ubuntu. Distroserin tarkoitus on auttaa sinua valitsemaan sinulle sopiva GNU/Linux jakelu."));
	$("#selection").append($.createParagraph("", "", "Distroser on testi jonka avulla voimme ehdottaa sinulle GNU/Linux jakelua. Kysymme yhden kysymyksen kerralla ja voit keskeyttää testin koska tahansa tai saada tulokset."));
	$("#selection").append($.createButton("start-questions", "btn btn-success btn-block", "Aloita testi"));
	$("#start-questions").click(function(evt) {
		evt.preventDefault();
		LoadQuestion(questions[index]);
	});
}

$(document).ready(function() {
	if($.isMobile() == false) {
		if($(window).width() <= 1024) {
			$("#wrapper").css("width", "60%");
		} else if($(window).width() <= 1280) {
			$("#wrapper").css("width", "50%");
		} else if($(window).width() <= 1366) {
			$("#wrapper").css("width", "40%");
		} else if($(window).width() <= 1920) {
			$("#wrapper").css("width", "30%");
		}
		$("#wrapper").css("margin-left", "auto");
		$("#wrapper").css("margin-right", "auto");
	}
	$.getJSON("questions.json", function(data) {
		questions = data.questions;
	});
	$.getJSON("distributions.json", function(data) {
		distributions = data.distributions;
	});
	LoadSplash();
});<commit_msg>Fix the drunk result calculation.<commit_after>Array.prototype.insert = function(index) {
    index = Math.min(index, this.length);
    arguments.length > 1
        && this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
        && this.insert.apply(this, arguments);
    return this;
};

(function($) {
	$.isMobile = function() {
		if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|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|phone)|xda|xiino/i.test(navigator.userAgent) || /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(navigator.userAgent.substr(0,4))) {
			return true;
		} else {
			return false;
		}
	}
	$.createWithID = function(tag, id) {
		var element = document.createElement(tag.toLowerCase());
		if(typeof(id) != "undefined") element.id = id;
		return $(element);
	}
	$.createParagraph = function(id, className, text) {
		var paragraph = document.createElement("p");
		if(typeof(id) != "undefined") paragraph.id = id;
		if(typeof(className) != "undefined") paragraph.className = className;
		if(typeof(text) != "undefined") {
			var text = document.createTextNode(text);
			paragraph.appendChild(text);
		}
		return $(paragraph);
	}
	$.createButton = function(id, className, text) {
		var button = document.createElement("button");
		button.type = "button";
		if(typeof(id) != "undefined") button.id = id;
		if(typeof(className) != "undefined") button.className = className;
		if(typeof(text) != "undefined") {
			var text = document.createTextNode(text);
			button.appendChild(text);
		}
		return $(button);

	}
	$.createCheckboxInput = function(id, className, name, text, value) {
		var label = document.createElement("label");
		var input = document.createElement("input");
		input.type = "checkbox";
		if(typeof(id) != "undefined") input.id = id;
		if(typeof(className) != "undefined") input.className = className;
		if(typeof(name) != "undefined") input.name = name;
		if(typeof(value) != "undefined") input.value = value;
		label.appendChild(input);
		if(typeof(text) != "undefined") {
			var text = document.createTextNode(text);
			label.appendChild(text);
		}
		return $(label);
	}
	$.createSubmit = function(id, className, value) {
		var input = document.createElement("input");
		input.type = "submit";
		if(typeof(id) != "undefined") input.id = id;
		if(typeof(className) != "undefined") input.className = className;
		if(typeof(value) != "undefined") input.value = value;
		return $(input);
	}
}(jQuery));

var index = 0;
var results = [];
var questions;
var distributions;
var scores = [];

function CheckResults() {
	console.log(distributions);
	for(var a = 0; a < distributions.length; a++) {
		distributions[a].score = 0;
		distributions[a].maximum = 0;
		console.log(distributions[a]);
		for(var b = 0; b < distributions[a].questions.length; b++) {
			for(var c = 0; c < results.length; c++) {
				console.log(distributions[a].questions[b].question + " == " + results[c].question);
				if(distributions[a].questions[b].question == results[c].question) {
					for(var d = 0; d < distributions[a].questions[b].answers.length; d++) {
						distributions[a].maximum += 1;
						for(var e = 0; e < results[c].answers.length; e++) {
							if(distributions[a].questions[b].answers[d].replace(/[^a-ä0-9]/gi, '_') == results[c].answers[d]) {
								distributions[a].score += 1;
							}
						}
					}
				}
			}
		}
	}
	console.log(distributions);
}

function LoadQuestion(question) {
	$("#selection").empty();
	$("#selection").append($.createWithID("h2", "question-header"));
	$("#question-header").text(question.question);
	$("#selection").append($.createWithID("form", "answers"));
	for(var x = 0; x < question.answers.length; x++) {
		var answerID = question.answers[x].answer.replace(/[^a-ä0-9]/gi, '_');
		$("#answers").append($.createCheckboxInput(answerID, "answer_inputs", "answers", question.answers[x].answer, question.answers[x].answer));
	}
	$("#answers").append($.createSubmit("answer-submit", "btn btn-primary btn-block", "Seuraava"));
	$("#answer-submit").click(function(evt) {
		evt.preventDefault();
		var answers = [];
		$(".answer_inputs").each(function() {
			if($(this).prop("checked") == true) {
				answers.push($(this).prop("id"));
			}
		});
		var result = { question : $("#question-header").text(), answers : answers };
		results.push(result);
		console.log(results);
		// load subquestions based on results if there are them.
		if(answers.length > 0) {
			for(var y = 0; y < answers.length; y++) {
				for(var x = 0; x < question.answers.length; x++) {
					var answerID = question.answers[x].answer.replace(/[^a-ä0-9]/gi, '_');
					if(answerID == answers[y]) {
						for(var d = 0; d < question.answers[x].subquestions.length; d++) {
							// needs to check if the question is not yet appended or has to do subquestion deletion on back button.
							questions.insert(index + 1 + d, question.answers[x].subquestions[d]);
						}
					}
				}
			}
		}
		var tmpIndex = index + 1;
		if(questions.length > tmpIndex) {
			index = tmpIndex;
			LoadQuestion(questions[index]);
			return;
		}
	});
	$("#answers").append($.createButton("answer-back", "btn btn-warning btn-block", "Edellinen"));
	$("#answer-back").click(function(evt) {
		evt.preventDefault();
		var tmpIndex = index - 1;
		if(tmpIndex >= 0) {
			index = tmpIndex;
			delete results[index];
			LoadQuestion(questions[index]);
		}
	});
	$("#answers").append($.createButton("answer-end", "btn btn-success btn-block", "Katso tulokset"));
	$("#answer-end").click(function(evt) {
		evt.preventDefault();
		CheckResults();
		index = 0;
		results = [];
		$.getJSON("questions.json", function(data) {
			questions = data.questions;
		});
		LoadSplash();
	});
	$("#answers").append($.createButton("answer-stop", "btn btn-danger btn-block", "Keskeytä testi"));
	$("#answer-stop").click(function(evt) {
		evt.preventDefault();
		index = 0;
		results = [];
		$.getJSON("questions.json", function(data) {
			questions = data.questions;
		});
		LoadSplash();
	});
}

function LoadSplash() {
	$("#selection").empty();
	$("#selection").append($.createParagraph("", "", "Tervetuloa. Olet saattanut kuulla käyttöjärjestelmästä nimeltä Linux ja huomannut niitä olevan paljon erilaisia kuten Mint, Debian ja Ubuntu. Distroserin tarkoitus on auttaa sinua valitsemaan sinulle sopiva GNU/Linux jakelu."));
	$("#selection").append($.createParagraph("", "", "Distroser on testi jonka avulla voimme ehdottaa sinulle GNU/Linux jakelua. Kysymme yhden kysymyksen kerralla ja voit keskeyttää testin koska tahansa tai saada tulokset."));
	$("#selection").append($.createButton("start-questions", "btn btn-success btn-block", "Aloita testi"));
	$("#start-questions").click(function(evt) {
		evt.preventDefault();
		LoadQuestion(questions[index]);
	});
}

$(document).ready(function() {
	if($.isMobile() == false) {
		if($(window).width() <= 1024) {
			$("#wrapper").css("width", "60%");
		} else if($(window).width() <= 1280) {
			$("#wrapper").css("width", "50%");
		} else if($(window).width() <= 1366) {
			$("#wrapper").css("width", "40%");
		} else if($(window).width() <= 1920) {
			$("#wrapper").css("width", "30%");
		}
		$("#wrapper").css("margin-left", "auto");
		$("#wrapper").css("margin-right", "auto");
	}
	$.getJSON("questions.json", function(data) {
		questions = data.questions;
	});
	$.getJSON("distributions.json", function(data) {
		distributions = data.distributions;
	});
	LoadSplash();
});<|endoftext|>


<commit_before>var Node = function Node(value) {
    this.value = value;
    this.next = null;
};

// List type FIFO. Same as Queue.
var LinkedList = function LinkedList() {
    this.size = 0;
    this.first = null;
    this.last = null;
};

LinkedList.prototype =  {
    // Removes an item at the beginning of the list.
    pop: function() {
        if (this.size === 0) {
          console.log('Nothing in the list to pop');
        }

        var oldFirst = this.first;
        this.first = this.first.next;

        this.size -= 1;
        return oldFirst;
    },

    // Adds an item to the end of the list.
    push: function(value) {
        var node = new Node(value);

        if (this.first === null) {
            this.first = node;
            this.last = node;
        }
        else {
            if (this.first.next === null) {
              this.last = node;
              this.first.next = this.last;
            }
            else {
              this.last.next = node;
              this.last = node;
            }
        }
        this.size += 1;
    },

    isEmpty: function() {
        return this.first === null;
    }
};

<commit_msg>Cosmetic at Singly Linked List.<commit_after>var Node = function Node(value) {
    this.value = value;
    this.next = null;
};

// List type FIFO. Same as Queue.
var LinkedList = function LinkedList() {
    this.size = 0;
    this.first = null;
    this.last = null;
};

LinkedList.prototype =  {
    // Removes an item at the beginning of the list.
    pop: function() {
        var oldFist;

        if (this.size === 0) {
            console.log('Nothing in the list to pop');
        }

        oldFirst = this.first;
        this.first = this.first.next;

        this.size -= 1;
        return oldFirst;
    },

    // Adds an item to the end of the list.
    push: function(value) {
        var node = new Node(value);

        if (this.first === null) {
            this.first = node;
            this.last = node;
        }
        else {
            if (this.first.next === null) {
                this.last = node;
                this.first.next = this.last;
            }
            else {
                this.last.next = node;
                this.last = node;
            }
        }
        this.size += 1;
    },

    isEmpty: function() {
        return this.first === null;
    }
};

<|endoftext|>


<commit_before>var dns = require("dns");
var url = require("wurl");

var dnsIps = ["208.67.222.123","208.67.220.123"]
var blockIP = "146.112.61.106";

dns.setServers(dnsIps);

// dns lookup middleware
// pre-requisite parsed body available by using body-parser
// resolves a dns to it's ip and attaches it to the request of object as
// dnsIP property
function parseDnsIP (req, res, next) {
  if (req.body.url) {
    var hostname = url("hostname", req.body.url);
    dns.lookup(hostname, function (error, result) {
      if (error) {
        next(error);
      }
      if (result && typeof result == "string") {
        req.dnsIP = result;
      }
      next();
    });
  }
  else {
    console.log("no url available to parse");
    next();
  }
}

// checks against the block open dns ip and returns true if safe false if not
// safe

function isSafe (dnsIP) {
  if (dnsIP == blockIP) {
    return false;
  }
  else {
    return true;
  }
}

module.exports = {
  parseDnsIP: parseDnsIP,
  isSafe: isSafe
}
<commit_msg>blockIP fetching automated now<commit_after>var dns = require("dns");
var url = require("wurl");

var dnsIps = ["208.67.222.123","208.67.220.123"]

dns.lookup("youporn.com", function (error, result) {
  blockIP = result;
  console.log("blockIP=" + blockIP);
})

// dns lookup middleware
// pre-requisite parsed body available by using body-parser
// resolves a dns to it's ip and attaches it to the request of object as
// dnsIP property
function parseDnsIP (req, res, next) {
  dns.setServers(dnsIps);
  if (req.body.url) {
    var hostname = url("hostname", req.body.url);
    dns.lookup(hostname, function (error, result) {
      if (error) {
        next(error);
      }
      if (result) {
        req.dnsIP = result;
      }
      next();
    });
  }
  else {
    console.log("no url available to parse");
    next();
  }
}

// checks against the block open dns ip and returns true if safe false if not
// safe

function isSafe (dnsIP) {
  if (dnsIP == blockIP) {
    return false;
  }
  else {
    return true;
  }
}

module.exports = {
  parseDnsIP: parseDnsIP,
  isSafe: isSafe
}
<|endoftext|>


<commit_before>$(function()
{
    socket = io.connect('https://api.misskey.xyz:1207/streaming/home', { port: 1207 });

    socket.on('connected', function()
    {
        console.log('Connected');
    });

    socket.on('disconnect', function(client)
    {
    });

    socket.on('post', function(content)
    {
        console.log(content);
        var $post = TIMELINE.generatePostElement(content, conf).hide()
        TIMELINE.setEventPost($post);
        $post.prependTo($('#timeline > .timeline > .posts')).show(200);
    });

    $('#postForm').submit(function(event)
    {
        event.preventDefault();
        var $form = $(this);
        var $submitButton = $form.find('[type=submit]');

        $submitButton.attr('disabled', true);
        $submitButton.text('Updating...');

        $.ajax($form.attr('action'), {
            type: $form.attr('method'),
            processData: false,
            contentType: false,
            data: new FormData($form[0]),
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            }
        }).done(function(data)
        {
            $form[0].reset();
            $submitButton.attr('disabled', false);
            $submitButton.text('Update');
        }).fail(function(data)
        {
            $form[0].reset();
            /*alert('error');*/
            $submitButton.attr('disabled', false);
            $submitButton.text('Update');
        });
    });

    setInterval(function() {
		var now = new Date();
		$('time').each(function() {
			function pad2(n) { return n < 10 ? '0' + n : n }
			var date = new Date($(this).attr('datetime'));
			var ago = ~~((now - date) / 1000);
			var timeText =
				ago >= 31536000 ? ~~(ago / 31536000) + "年前":
				ago >= 2592000 ? ~~(ago / 2592000) + "ヶ月前":
				ago >= 604800 ? ~~(ago / 604800) + "週間前":
				ago >= 86400 ? ~~(ago / 86400) + "日前":
				ago >= 3600 ? ~~(ago / 3600) + "時間前":
				ago >= 60 ? ~~(ago / 60) + "分前":
				ago >= 5 ? ~~(ago % 60) + "秒前":
				ago < 5 ? 'いま' : "" ;
			$(this).text(timeText);
		});
	}, 1000);
});

<commit_msg>Fix selector<commit_after>$(function()
{
    socket = io.connect('https://api.misskey.xyz:1207/streaming/home', { port: 1207 });

    socket.on('connected', function()
    {
        console.log('Connected');
    });

    socket.on('disconnect', function(client)
    {
    });

    socket.on('post', function(content)
    {
        console.log(content);
        var $post = TIMELINE.generatePostElement(content, conf).hide()
        TIMELINE.setEventPost($post);
        $post.prependTo($('#timeline .timeline > .posts')).show(200);
    });

    $('#postForm').submit(function(event)
    {
        event.preventDefault();
        var $form = $(this);
        var $submitButton = $form.find('[type=submit]');

        $submitButton.attr('disabled', true);
        $submitButton.text('Updating...');

        $.ajax($form.attr('action'), {
            type: $form.attr('method'),
            processData: false,
            contentType: false,
            data: new FormData($form[0]),
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            }
        }).done(function(data)
        {
            $form[0].reset();
            $submitButton.attr('disabled', false);
            $submitButton.text('Update');
        }).fail(function(data)
        {
            $form[0].reset();
            /*alert('error');*/
            $submitButton.attr('disabled', false);
            $submitButton.text('Update');
        });
    });

    setInterval(function() {
		var now = new Date();
		$('time').each(function() {
			function pad2(n) { return n < 10 ? '0' + n : n }
			var date = new Date($(this).attr('datetime'));
			var ago = ~~((now - date) / 1000);
			var timeText =
				ago >= 31536000 ? ~~(ago / 31536000) + "年前":
				ago >= 2592000 ? ~~(ago / 2592000) + "ヶ月前":
				ago >= 604800 ? ~~(ago / 604800) + "週間前":
				ago >= 86400 ? ~~(ago / 86400) + "日前":
				ago >= 3600 ? ~~(ago / 3600) + "時間前":
				ago >= 60 ? ~~(ago / 60) + "分前":
				ago >= 5 ? ~~(ago % 60) + "秒前":
				ago < 5 ? 'いま' : "" ;
			$(this).text(timeText);
		});
	}, 1000);
});

<|endoftext|>


<commit_before>(function( $, undefined ) {
    $.KBWidget({
        name: "KBaseJgiDataImportView",
        parent: "kbaseAuthenticatedWidget",

        options: {
            ws: null,
            obj: null,
            loadingImage: "assets/img/ajax-loader.gif",
            ws_url: "https://kbase.us/services/ws"
//            ws_url:"https://dev04.berkeley.kbase.us/services/ws"
//            ws_url:"https://dev03.berkeley.kbase.us/services/ws"
        },

        ws: null, // the ws client

        $mainPanel: null,
        $errorPanel: null,
        $msgPanel: null,
        $copyDropdown: null,

        typereg: {'KBaseFile.SingleEndLibrary':
                       {nicetype: 'Single End Read Library',
                        app_name: 'Assembly and Annotation',
                        app: 'genome_assembly',
                        appParam: '1,read_library,'
                        },
                   'KBaseFile.PairedEndLibrary':
                       {nicetype: 'Paired End Read Library',
                        app_name: 'Assembly and Annotation',
                        app: 'genome_assembly',
                        appParam: '1,read_library,'
                        },
                   'KBaseFile.AssemblyFile':
                       {nicetype: 'Assembly File',
                        app_name: 'Assembly File to ContigSet',
                        method: 'convert_annotation_file_to_contig_set',
                        appParam: '1,input_assyfile,' //1 is ignored
                        },
//                   'KBaseFile.AnnotationFile':
//                       {nicetype: 'Annotation File',
//                        app_name: 'Annotation File to Genome',
//                        app: null
//                        },
                   'none':
                       {nicetype: null,
                        app: null
                       }
                    },

        init: function(options) {
            this._super(options);

            this.$errorPanel = $('
').addClass('alert alert-danger').hide();
            this.$elem.append(this.$errorPanel);

            this.$msgPanel = $('
');
            this.$elem.append(this.$msgPanel);

            this.$mainPanel = $("
");
            this.$elem.append(this.$mainPanel);

            // check if we are already logged in
            if (!this._attributes.auth.token) {
                this.notLoggedIn();
            } else {
                this.ws = new Workspace(this.options.ws_url, this._attributes.auth);
                this.getDataAndRender();
            }

            return this;
        },

        loggedInCallback: function(event, auth) {
            this.ws = new Workspace(this.options.ws_url, auth);
            this.getDataAndRender();
            return this;
        },
        loggedOutCallback: function(event, auth) {
            this.ws = null;
            this.notLoggedIn();
            return this;
        },

        refresh: function() {
            this.getDataAndRender();
        },

        objData: null,

        getDataAndRender: function() {
            var self = this;
            self.ws.get_object_info(
                    [{ref:self.options.ws+"/"+self.options.obj}],1,
                    function(objInfoList) {
                        if (objInfoList[0]) {
                            self.objData = {
                                    obj_id: objInfoList[0][0],
                                    name: objInfoList[0][1],
                                    type: objInfoList[0][2],
                                    save_date: objInfoList[0][3],
                                    version: objInfoList[0][4],
                                    saved_by: objInfoList[0][5],
                                    wsid: objInfoList[0][6],
                                    workspace: objInfoList[0][7],
                                    chsum: objInfoList[0][8],
                                    size: objInfoList[0][9],
                                    meta: objInfoList[0][10],
                                    };
                            console.log(self.objData);
                            self.render();
                        } else {
                            self.showError({error:{message:
                                'Could not fetch the data information for some reason.'}});
                        }
                    },
                    function(error) {
                        self.showError(error);
                    }
            );
        },

        render: function() {
            var self = this;
            if (self.objData) {
                // do things
                self.$mainPanel.empty();

                var typeName = self.objData.type.split('-')[0];
                if (typeName in self.typereg) {
                    self.renderType(self.typereg[typeName]);
                } else {
                    self.renderType(self.typereg.none);
                }
            }
        },

        renderType: function(typeInfo) {
            var self = this;
            var typeNameNice;
            if (typeInfo.nicetype != null) {
                typeNameNice = typeInfo.nicetype;
            } else {
                typeNameNice = self.objData.type;
            }
            var permref = self.objData.wsid + "/" + self.objData.obj_id + "/" +
                    self.objData.version;

            var $basicInfo =
                $('
').addClass('col-md-6')
                    .append($('
').append('
' + self.objData.name + '
'))
                    .append($('
').css({'color':'#555'})
                            .append('Workspace: ' +// '' +
                                    self.objData.workspace + ''))
                    .append($('
').css({'color':'#555'}) //todo: make this a real style somewhere
                            .append('' + typeNameNice + ''))
                    .append($('
').css({'color':'#555'})
                            .append('Imported on ' + self.getTimeStr(self.objData.save_date)))
                    .append($('
').css({'color':'#555'})
                            .append('Perm Ref: ' + permref))

            var $buttonDiv =
                $('
').css({'margin':'10px','margin-top':'20px'});
            if (typeInfo.app != null && typeInfo.method != null) {
                self.showError({error: {message:
                        "typeInfo app and method are mutally exclusive"}});
                return;
            }
            if (typeInfo.app != null || typeInfo.method != null) {
                var param = typeInfo.app ? '&app=' : '&method=';
                var app = typeInfo.app ? typeInfo.app : typeInfo.method;
                $buttonDiv.append($('').addClass('btn btn-info')
                            .css({'margin':'5px'})
                            .append('Launch ' + typeInfo.app_name + ' App'));
            }
            self.addCopyDropdown($buttonDiv);

            $basicInfo.append($buttonDiv);

            var $metaInfo = $('
').addClass('col-md-6').css({'margin-top':'20px'});

            var $metaTbl = $('
').addClass("table table-striped table-bordered").css({'width':'100%'});
            var k = Object.keys(self.objData.meta).sort();
            for(var i = 0; i < k.length; i++) {
                var key = k[i];
                if (self.objData.meta.hasOwnProperty(key)) {
                    $metaTbl.append($('
')
                                .append($('').append(key))
                                .append($('')
                                        .append(self.objData.meta[key])));
                }
            }
            $metaInfo.append($metaTbl)

            var $content = $('
').addClass('row')
                        .append($basicInfo)
                        .append($metaInfo);

            self.$mainPanel.append($content);
        },

        addCopyDropdown: function(element) {
            var self = this;
            self.ws.list_workspace_info({perm: 'w'},
                    function(workspaces) {
                        for (var i = workspaces.length - 1; i >= 0; i--) {
                            var narnnicename = workspaces[i][8]
                                    .narrative_nice_name;
                            if (narnnicename == null) {
                                workspaces.splice(i, 1);
                            }
                        }
                        self.fillCopyDropdown(element, workspaces);
                    },
                    function(error) {
                        self.showError(error);
                    }
            );
        },

        fillCopyDropdown: function(element, workspaces) {
            var self = this;
            var uniqueid = 'mycrazyuniqueidthatnooneshouldeveruse';
            var createfunc = function(wsinfo) {
                return function(event) {
                    self.copyData(event, wsinfo);
                };
            };
            workspaces.sort(function(a, b) {
                return a[8].narrative_nice_name
                        .localeCompare(b[8].narrative_nice_name);

            });
            var list = $('
').addClass('dropdown-menu').attr('role', 'menu')
                .attr('aria-labelledby', uniqueid);
            if (workspaces.length > 0) {
                for (var i = 0; i < workspaces.length; i++) {
                    var narname = workspaces[i][8].narrative_nice_name;
                    if (narname != null) {
                        list.append($('
').attr('role', 'presentation')
                                .append($('').attr('role', 'menuitem')
                                    .attr('tabindex', '-1')
                                    .append(narname + ' (' +
                                            self.getTimeStr(workspaces[i][3]) +
                                            ')')
                                    .click(createfunc(workspaces[i])) //save ws in closure
                                 )
                        );
                    }
                }
            } else {
                list.append($('
').attr('role', 'presentation')
                        .addClass('disabled')
                        .append($('').attr('role', 'menuitem')
                            .attr('tabindex', '-1')
                            .append('You have no writeable narratives')
                         )
                );
            }
            self.$copyDropdown = $('<button>')
                    .addClass("btn btn-default dropdown-toggle")
                    .attr('type', 'button').attr('id', uniqueid)
                    .attr('data-toggle', 'dropdown')
                    .attr('aria-expanded', 'true')
                    .append('Copy to Narrative')
                    .append($('').addClass('caret')
                            .css({'margin-left': '5px'}));

            element.append($('
').addClass('dropdown').css({margin: '5px'})
                .append(self.$copyDropdown)
                .append(list));
        },

        copyData: function(event, workspaceInfo) {
            var self = this;
            self.$copyDropdown.addClass('disabled');
            //copies are really fast, so I don't think a spinner is really needed
            self.ws.copy_object(
                    {from: {ref: self.objData.wsid + '/' + self.objData.obj_id},
                     to: {wsid: workspaceInfo[0], name: self.objData.name}
                    }, function(objInfo) {
                        self.$copyDropdown.removeClass('disabled');
                        self.successMsg('Copied object ' + self.objData.name +
                                ' to narrative ' +
                                workspaceInfo[8].narrative_nice_name);
                    }, function(error) {
                        self.$copyDropdown.removeClass('disabled');
                        self.showError(error);
                    }
            );
        },

        successMsg: function(message) {
            var self = this;
            self.$msgPanel.append($('
')
                  .addClass('alert alert-success alert-dismissible')
                  .attr('role', 'alert')
                  .append(message)
                  .append($('<button>').addClass('close')
                          .attr('type', 'button')
                          .attr('data-dismiss', 'alert')
                          .attr('aria-label', 'Close')
                          .append($('').attr('aria-hidden', 'true')
                                  .append('×'))
                          )
                  );
        },

        notLoggedIn: function() {
            this.$mainPanel.empty();
            this.$mainPanel.append("You must be logged in to view this data.");
        },

        showError: function(error) {
            this.$errorPanel.empty();
            this.$errorPanel.append('Error when retrieving imported JGI data.

');
            this.$errorPanel.append(error.error.message);
            this.$errorPanel.append('
');
            this.$errorPanel.show();
        },

        // edited from: http://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site
        getTimeStr: function (objInfoTimeStamp) {
            var date = new Date(objInfoTimeStamp);
            var seconds = Math.floor((new Date() - date) / 1000);
            // f-ing safari, need to add extra ':' delimiter to parse the timestamp
            if (isNaN(seconds)) {
                var tokens = objInfoTimeStamp.split('+');  // this is just the date without the GMT offset
                var newTimestamp = tokens[0] + '+' + tokens[0].substr(0,2) +
                        ":" + tokens[1].substr(2,2);
                date = new Date(newTimestamp);
                seconds = Math.floor((new Date() - date) / 1000);
                if (isNaN(seconds)) {
                    // just in case that didn't work either, then parse without the timezone offset, but
                    // then just show the day and forget the fancy stuff...
                    date = new Date(tokens[0]);
                    return this.monthLookup[date.getMonth()] + " " +
                            date.getDate() + ", " + date.getFullYear();
                }
            }
            // forget about time since, just show the date.
            return this.monthLookup[date.getMonth()] + " " + date.getDate() +
                    ", " + date.getFullYear();
        },

        monthLookup : ["Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct", "Nov", "Dec"],

    });
})( jQuery );<commit_msg>[JGI] use app and method terminology correctly<commit_after>(function( $, undefined ) {
    $.KBWidget({
        name: "KBaseJgiDataImportView",
        parent: "kbaseAuthenticatedWidget",

        options: {
            ws: null,
            obj: null,
            loadingImage: "assets/img/ajax-loader.gif",
            ws_url: "https://kbase.us/services/ws"
//            ws_url:"https://dev04.berkeley.kbase.us/services/ws"
//            ws_url:"https://dev03.berkeley.kbase.us/services/ws"
        },

        ws: null, // the ws client

        $mainPanel: null,
        $errorPanel: null,
        $msgPanel: null,
        $copyDropdown: null,

        typereg: {'KBaseFile.SingleEndLibrary':
                       {nicetype: 'Single End Read Library',
                        app_name: 'Assembly and Annotation app',
                        app: 'genome_assembly',
                        appParam: '1,read_library,'
                        },
                   'KBaseFile.PairedEndLibrary':
                       {nicetype: 'Paired End Read Library',
                        app_name: 'Assembly and Annotation app',
                        app: 'genome_assembly',
                        appParam: '1,read_library,'
                        },
                   'KBaseFile.AssemblyFile':
                       {nicetype: 'Assembly File',
                        app_name: 'Assembly File to ContigSet method',
                        method: 'convert_annotation_file_to_contig_set',
                        appParam: '1,input_assyfile,' //1 is ignored
                        },
//                   'KBaseFile.AnnotationFile':
//                       {nicetype: 'Annotation File',
//                        app_name: 'Annotation File to Genome',
//                        app: null
//                        },
                   'none':
                       {nicetype: null,
                        app: null
                       }
                    },

        init: function(options) {
            this._super(options);

            this.$errorPanel = $('
').addClass('alert alert-danger').hide();
            this.$elem.append(this.$errorPanel);

            this.$msgPanel = $('
');
            this.$elem.append(this.$msgPanel);

            this.$mainPanel = $("
");
            this.$elem.append(this.$mainPanel);

            // check if we are already logged in
            if (!this._attributes.auth.token) {
                this.notLoggedIn();
            } else {
                this.ws = new Workspace(this.options.ws_url, this._attributes.auth);
                this.getDataAndRender();
            }

            return this;
        },

        loggedInCallback: function(event, auth) {
            this.ws = new Workspace(this.options.ws_url, auth);
            this.getDataAndRender();
            return this;
        },
        loggedOutCallback: function(event, auth) {
            this.ws = null;
            this.notLoggedIn();
            return this;
        },

        refresh: function() {
            this.getDataAndRender();
        },

        objData: null,

        getDataAndRender: function() {
            var self = this;
            self.ws.get_object_info(
                    [{ref:self.options.ws+"/"+self.options.obj}],1,
                    function(objInfoList) {
                        if (objInfoList[0]) {
                            self.objData = {
                                    obj_id: objInfoList[0][0],
                                    name: objInfoList[0][1],
                                    type: objInfoList[0][2],
                                    save_date: objInfoList[0][3],
                                    version: objInfoList[0][4],
                                    saved_by: objInfoList[0][5],
                                    wsid: objInfoList[0][6],
                                    workspace: objInfoList[0][7],
                                    chsum: objInfoList[0][8],
                                    size: objInfoList[0][9],
                                    meta: objInfoList[0][10],
                                    };
                            console.log(self.objData);
                            self.render();
                        } else {
                            self.showError({error:{message:
                                'Could not fetch the data information for some reason.'}});
                        }
                    },
                    function(error) {
                        self.showError(error);
                    }
            );
        },

        render: function() {
            var self = this;
            if (self.objData) {
                // do things
                self.$mainPanel.empty();

                var typeName = self.objData.type.split('-')[0];
                if (typeName in self.typereg) {
                    self.renderType(self.typereg[typeName]);
                } else {
                    self.renderType(self.typereg.none);
                }
            }
        },

        renderType: function(typeInfo) {
            var self = this;
            var typeNameNice;
            if (typeInfo.nicetype != null) {
                typeNameNice = typeInfo.nicetype;
            } else {
                typeNameNice = self.objData.type;
            }
            var permref = self.objData.wsid + "/" + self.objData.obj_id + "/" +
                    self.objData.version;

            var $basicInfo =
                $('
').addClass('col-md-6')
                    .append($('
').append('
' + self.objData.name + '
'))
                    .append($('
').css({'color':'#555'})
                            .append('Workspace: ' +// '' +
                                    self.objData.workspace + ''))
                    .append($('
').css({'color':'#555'}) //todo: make this a real style somewhere
                            .append('' + typeNameNice + ''))
                    .append($('
').css({'color':'#555'})
                            .append('Imported on ' + self.getTimeStr(self.objData.save_date)))
                    .append($('
').css({'color':'#555'})
                            .append('Perm Ref: ' + permref))

            var $buttonDiv =
                $('
').css({'margin':'10px','margin-top':'20px'});
            if (typeInfo.app != null && typeInfo.method != null) {
                self.showError({error: {message:
                        "typeInfo app and method are mutally exclusive"}});
                return;
            }
            if (typeInfo.app != null || typeInfo.method != null) {
                var param = typeInfo.app ? '&app=' : '&method=';
                var app = typeInfo.app ? typeInfo.app : typeInfo.method;
                $buttonDiv.append($('').addClass('btn btn-info')
                            .css({'margin':'5px'})
                            .append('Launch ' + typeInfo.app_name));
            }
            self.addCopyDropdown($buttonDiv);

            $basicInfo.append($buttonDiv);

            var $metaInfo = $('
').addClass('col-md-6').css({'margin-top':'20px'});

            var $metaTbl = $('
').addClass("table table-striped table-bordered").css({'width':'100%'});
            var k = Object.keys(self.objData.meta).sort();
            for(var i = 0; i < k.length; i++) {
                var key = k[i];
                if (self.objData.meta.hasOwnProperty(key)) {
                    $metaTbl.append($('
')
                                .append($('').append(key))
                                .append($('')
                                        .append(self.objData.meta[key])));
                }
            }
            $metaInfo.append($metaTbl)

            var $content = $('
').addClass('row')
                        .append($basicInfo)
                        .append($metaInfo);

            self.$mainPanel.append($content);
        },

        addCopyDropdown: function(element) {
            var self = this;
            self.ws.list_workspace_info({perm: 'w'},
                    function(workspaces) {
                        for (var i = workspaces.length - 1; i >= 0; i--) {
                            var narnnicename = workspaces[i][8]
                                    .narrative_nice_name;
                            if (narnnicename == null) {
                                workspaces.splice(i, 1);
                            }
                        }
                        self.fillCopyDropdown(element, workspaces);
                    },
                    function(error) {
                        self.showError(error);
                    }
            );
        },

        fillCopyDropdown: function(element, workspaces) {
            var self = this;
            var uniqueid = 'mycrazyuniqueidthatnooneshouldeveruse';
            var createfunc = function(wsinfo) {
                return function(event) {
                    self.copyData(event, wsinfo);
                };
            };
            workspaces.sort(function(a, b) {
                return a[8].narrative_nice_name
                        .localeCompare(b[8].narrative_nice_name);

            });
            var list = $('
').addClass('dropdown-menu').attr('role', 'menu')
                .attr('aria-labelledby', uniqueid);
            if (workspaces.length > 0) {
                for (var i = 0; i < workspaces.length; i++) {
                    var narname = workspaces[i][8].narrative_nice_name;
                    if (narname != null) {
                        list.append($('
').attr('role', 'presentation')
                                .append($('').attr('role', 'menuitem')
                                    .attr('tabindex', '-1')
                                    .append(narname + ' (' +
                                            self.getTimeStr(workspaces[i][3]) +
                                            ')')
                                    .click(createfunc(workspaces[i])) //save ws in closure
                                 )
                        );
                    }
                }
            } else {
                list.append($('
').attr('role', 'presentation')
                        .addClass('disabled')
                        .append($('').attr('role', 'menuitem')
                            .attr('tabindex', '-1')
                            .append('You have no writeable narratives')
                         )
                );
            }
            self.$copyDropdown = $('<button>')
                    .addClass("btn btn-default dropdown-toggle")
                    .attr('type', 'button').attr('id', uniqueid)
                    .attr('data-toggle', 'dropdown')
                    .attr('aria-expanded', 'true')
                    .append('Copy to Narrative')
                    .append($('').addClass('caret')
                            .css({'margin-left': '5px'}));

            element.append($('
').addClass('dropdown').css({margin: '5px'})
                .append(self.$copyDropdown)
                .append(list));
        },

        copyData: function(event, workspaceInfo) {
            var self = this;
            self.$copyDropdown.addClass('disabled');
            //copies are really fast, so I don't think a spinner is really needed
            self.ws.copy_object(
                    {from: {ref: self.objData.wsid + '/' + self.objData.obj_id},
                     to: {wsid: workspaceInfo[0], name: self.objData.name}
                    }, function(objInfo) {
                        self.$copyDropdown.removeClass('disabled');
                        self.successMsg('Copied object ' + self.objData.name +
                                ' to narrative ' +
                                workspaceInfo[8].narrative_nice_name);
                    }, function(error) {
                        self.$copyDropdown.removeClass('disabled');
                        self.showError(error);
                    }
            );
        },

        successMsg: function(message) {
            var self = this;
            self.$msgPanel.append($('
')
                  .addClass('alert alert-success alert-dismissible')
                  .attr('role', 'alert')
                  .append(message)
                  .append($('<button>').addClass('close')
                          .attr('type', 'button')
                          .attr('data-dismiss', 'alert')
                          .attr('aria-label', 'Close')
                          .append($('').attr('aria-hidden', 'true')
                                  .append('×'))
                          )
                  );
        },

        notLoggedIn: function() {
            this.$mainPanel.empty();
            this.$mainPanel.append("You must be logged in to view this data.");
        },

        showError: function(error) {
            this.$errorPanel.empty();
            this.$errorPanel.append('Error when retrieving imported JGI data.

');
            this.$errorPanel.append(error.error.message);
            this.$errorPanel.append('
');
            this.$errorPanel.show();
        },

        // edited from: http://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site
        getTimeStr: function (objInfoTimeStamp) {
            var date = new Date(objInfoTimeStamp);
            var seconds = Math.floor((new Date() - date) / 1000);
            // f-ing safari, need to add extra ':' delimiter to parse the timestamp
            if (isNaN(seconds)) {
                var tokens = objInfoTimeStamp.split('+');  // this is just the date without the GMT offset
                var newTimestamp = tokens[0] + '+' + tokens[0].substr(0,2) +
                        ":" + tokens[1].substr(2,2);
                date = new Date(newTimestamp);
                seconds = Math.floor((new Date() - date) / 1000);
                if (isNaN(seconds)) {
                    // just in case that didn't work either, then parse without the timezone offset, but
                    // then just show the day and forget the fancy stuff...
                    date = new Date(tokens[0]);
                    return this.monthLookup[date.getMonth()] + " " +
                            date.getDate() + ", " + date.getFullYear();
                }
            }
            // forget about time since, just show the date.
            return this.monthLookup[date.getMonth()] + " " + date.getDate() +
                    ", " + date.getFullYear();
        },

        monthLookup : ["Jan", "Feb", "Mar","Apr", "May", "Jun", "Jul", "Aug", "Sep","Oct", "Nov", "Dec"],

    });
})( jQuery );<|endoftext|>


<commit_before>var creep_combat = {

    /** @param {Creep} creep **/
    run: function(creep) {
        //Defensive-focused attack
        //Only run this code if the room is being invaded, remain offline otherwise.
        //(Saves running excess finds in peacetime)
        if (creep.hits < creep.hitsMax) {
            creep.heal(creep);
        }

        if (Memory.roomsUnderAttack.indexOf(creep.room.name) != -1) {
            //Move towards Foe, stop at rampart
            var lookResult = creep.pos.lookFor(LOOK_STRUCTURES);
            var Foe = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 50, {
                filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
            });

            var closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
                filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
            });

            if (Foe.length) {
                Foe.sort(targetOther);
                var boostFlag = false;
                if ((Foe[0].getActiveBodyparts(ATTACK) > 0 || Foe[0].getActiveBodyparts(RANGED_ATTACK) > 0 || Foe[0].getActiveBodyparts(WORK) > 0) && Foe[0].owner.username != 'Invader') {
                    Foe[0].body.forEach(function(thisPart) {
                        if (thisPart.boost) {
                            boostFlag = true;
                        }
                    });
                }
                if (boostFlag && creep.room.controller.level >= 6) {
                    var attackLab = creep.room.find(FIND_MY_STRUCTURES, {
                        filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_UTRIUM_ACID)
                    });
                    var mineralCost = creep.getActiveBodyparts(ATTACK) * LAB_BOOST_MINERAL;
                    var energyCost = creep.getActiveBodyparts(ATTACK) * LAB_BOOST_ENERGY;
                    if (attackLab.length && attackLab[0].mineralAmount >= mineralCost && attackLab[0].energy >= energyCost) {
                        creep.memory.needBoosts = true;
                    } else {
                        creep.memory.needBoosts = false;
                    }
                } else {
                    creep.memory.needBoosts = false;
                }
            }

            var unboostedAttack = 0;
            if (creep.memory.needBoosts && creep.room.controller.level >= 6) {
                creep.body.forEach(function(thisPart) {
                    if (thisPart.type == ATTACK && !thisPart.boost) {
                        unboostedAttack = unboostedAttack + 1;
                    }
                });
            }

            if (creep.memory.needBoosts && unboostedAttack > 0) {
                var thisLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_UTRIUM_ACID)
                });
                if (thisLab.length) {
                    creep.travelTo(thisLab[0]);
                    thisLab[0].boostCreep(creep);
                } else {
                    creep.memory.needBoost = false;
                }
            } else if (closeFoe) {
                if (!creep.memory.waitingTimer) {
                    creep.memory.waitingTimer = 0
                }
                var lookResult = creep.pos.lookFor(LOOK_STRUCTURES);
                if (lookResult.length && creep.memory.waitingTimer < 50) {
                    var found = false;
                    for (var y = 0; y < lookResult.length; y++) {
                        if (lookResult[y].structureType == STRUCTURE_RAMPART) {
                        	if (creep.pos.inRangeTo(closeFoe, 3)) {
                        		creep.memory.waitingTimer = 0;
                        	} else {
                        		creep.memory.waitingTimer = creep.memory.waitingTimer + 1;
                        	}
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        creep.travelTo(closeFoe, {
                            maxRooms: 1
                        });
                    }
                } else {
                    creep.memory.waitingTimer = 0;
                    creep.travelTo(closeFoe, {
                        maxRooms: 1
                    });
                }
            }

            if (closeFoe) {
                if (creep.pos.inRangeTo(closeFoe, 3)) {
                    creep.rangedMassAttack();
                }
                if (creep.attack(closeFoe) == OK) {
                    creep.memory.waitingTimer = 0;
                }
            }
        }
    }
};

function targetOther(a, b) {
    if (a.getActiveBodyparts(HEAL) > b.getActiveBodyparts(HEAL))
        return 1;
    if (a.getActiveBodyparts(HEAL) < b.getActiveBodyparts(HEAL))
        return -1;
    return 0;
}

module.exports = creep_combat;
<commit_msg>THOU CAN WAIT<commit_after>var creep_combat = {

    /** @param {Creep} creep **/
    run: function(creep) {
        //Defensive-focused attack
        //Only run this code if the room is being invaded, remain offline otherwise.
        //(Saves running excess finds in peacetime)
        if (creep.hits < creep.hitsMax) {
            creep.heal(creep);
        }

        if (Memory.roomsUnderAttack.indexOf(creep.room.name) != -1) {
            //Move towards Foe, stop at rampart
            var lookResult = creep.pos.lookFor(LOOK_STRUCTURES);
            var Foe = creep.pos.findInRange(FIND_HOSTILE_CREEPS, 50, {
                filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
            });

            var closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
                filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username))
            });

            if (Foe.length) {
                Foe.sort(targetOther);
                var boostFlag = false;
                if ((Foe[0].getActiveBodyparts(ATTACK) > 0 || Foe[0].getActiveBodyparts(RANGED_ATTACK) > 0 || Foe[0].getActiveBodyparts(WORK) > 0) && Foe[0].owner.username != 'Invader') {
                    Foe[0].body.forEach(function(thisPart) {
                        if (thisPart.boost) {
                            boostFlag = true;
                        }
                    });
                }
                if (boostFlag && creep.room.controller.level >= 6) {
                    var attackLab = creep.room.find(FIND_MY_STRUCTURES, {
                        filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_UTRIUM_ACID)
                    });
                    var mineralCost = creep.getActiveBodyparts(ATTACK) * LAB_BOOST_MINERAL;
                    var energyCost = creep.getActiveBodyparts(ATTACK) * LAB_BOOST_ENERGY;
                    if (attackLab.length && attackLab[0].mineralAmount >= mineralCost && attackLab[0].energy >= energyCost) {
                        creep.memory.needBoosts = true;
                    } else {
                        creep.memory.needBoosts = false;
                    }
                } else {
                    creep.memory.needBoosts = false;
                }
            }

            var unboostedAttack = 0;
            if (creep.memory.needBoosts && creep.room.controller.level >= 6) {
                creep.body.forEach(function(thisPart) {
                    if (thisPart.type == ATTACK && !thisPart.boost) {
                        unboostedAttack = unboostedAttack + 1;
                    }
                });
            }

            if (creep.memory.needBoosts && unboostedAttack > 0) {
                var thisLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_UTRIUM_ACID)
                });
                if (thisLab.length) {
                    creep.travelTo(thisLab[0]);
                    thisLab[0].boostCreep(creep);
                } else {
                    creep.memory.needBoost = false;
                }
            } else if (closeFoe) {
                if (!creep.memory.waitingTimer) {
                    creep.memory.waitingTimer = 0
                }
                var lookResult = creep.pos.lookFor(LOOK_STRUCTURES);
                if (lookResult.length && creep.memory.waitingTimer < 300) {
                    var found = false;
                    for (var y = 0; y < lookResult.length; y++) {
                        if (lookResult[y].structureType == STRUCTURE_RAMPART) {
                        	if (creep.pos.inRangeTo(closeFoe, 3)) {
                        		creep.memory.waitingTimer = 0;
                        	} else {
                        		creep.memory.waitingTimer = creep.memory.waitingTimer + 1;
                        	}
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        creep.travelTo(closeFoe, {
                            maxRooms: 1
                        });
                    }
                } else {
                    creep.memory.waitingTimer = 0;
                    creep.travelTo(closeFoe, {
                        maxRooms: 1
                    });
                }
            }

            if (closeFoe) {
                if (creep.pos.inRangeTo(closeFoe, 3)) {
                    creep.rangedMassAttack();
                }
                if (creep.attack(closeFoe) == OK) {
                    creep.memory.waitingTimer = 0;
                }
            }
        }
    }
};

function targetOther(a, b) {
    if (a.getActiveBodyparts(HEAL) > b.getActiveBodyparts(HEAL))
        return 1;
    if (a.getActiveBodyparts(HEAL) < b.getActiveBodyparts(HEAL))
        return -1;
    return 0;
}

module.exports = creep_combat;
<|endoftext|>