<commit_before>function Feed(feed_urls)
{
  this.feed_urls = feed_urls;
  this.el = document.createElement('div'); this.el.id = "feed";
  this.tabs_el = document.createElement('div'); this.tabs_el.id = "tabs";
  this.wr_el = document.createElement('div'); this.wr_el.id = "tabs_wrapper";

  this.tab_timeline_el = document.createElement('t'); this.tab_timeline_el.id = "tab_timeline";
  this.tab_mentions_el = document.createElement('t'); this.tab_mentions_el.id = "tab_mentions";
  this.tab_whispers_el = document.createElement('t'); this.tab_whispers_el.id = "tab_whispers";
  this.tab_portals_el = document.createElement('t'); this.tab_portals_el.id = "tab_portals";
  this.tab_discovery_el = document.createElement('t'); this.tab_discovery_el.id = "tab_discovery";
  this.tab_services_el = document.createElement('t'); this.tab_services_el.id = "tab_services";

  this.tab_portals_el.setAttribute("data-operation","filter:portals");
  this.tab_portals_el.setAttribute("data-validate","true");
  this.tab_mentions_el.setAttribute("data-operation","filter:mentions");
  this.tab_mentions_el.setAttribute("data-validate","true");
  this.tab_whispers_el.setAttribute("data-operation","filter:whispers");
  this.tab_whispers_el.setAttribute("data-validate","true");
  this.tab_timeline_el.setAttribute("data-operation","clear_filter");
  this.tab_timeline_el.setAttribute("data-validate","true");
  this.tab_discovery_el.setAttribute('data-operation', 'filter:discovery');
  this.tab_discovery_el.setAttribute('data-validate', "true");

  this.el.appendChild(this.tabs_el);
  this.tabs_el.appendChild(this.tab_timeline_el);
  this.tabs_el.appendChild(this.tab_mentions_el);
  this.tabs_el.appendChild(this.tab_whispers_el);
  this.tabs_el.appendChild(this.tab_portals_el);
  this.tabs_el.appendChild(this.tab_discovery_el);
  this.tabs_el.appendChild(this.tab_services_el);

  this.wr_timeline_el = document.createElement('div'); this.wr_timeline_el.id = "wr_timeline";
  this.wr_portals_el = document.createElement('div'); this.wr_portals_el.id = "wr_portals";
  this.wr_discovery_el = document.createElement('div'); this.wr_discovery_el.id = "wr_discovery";

  this.el.appendChild(this.wr_el);
  this.wr_el.appendChild(this.wr_timeline_el);
  this.wr_el.appendChild(this.wr_portals_el);
  this.wr_el.appendChild(this.wr_discovery_el);

  this.queue = [];
  this.portals = [];

  this.urls = {};
  this.filter = "";
  this.target = window.location.hash ? window.location.hash.replace("#","") : "";
  this.timer = null;
  this.mentions = 0;

  this.page = 0;
  this.page_size = 20;
  this.page_target = null;
  this.page_filter = null;

  this.install = function()
  {
    r.el.appendChild(r.home.feed.el);
    r.home.feed.start();
  }

  this.start = function()
  {
    this.queue.push(r.home.portal.url);
    for(id in r.home.portal.json.port){
      var url = r.home.portal.json.port[id];
      this.queue.push(url)
    }
    this.next();

    this.timer = setInterval(r.home.feed.next, 500);
  }

  this.next = async function()
  {
    if(r.home.feed.queue.length < 1){ console.log("Reached end of queue"); r.home.feed.update_log(); return; }

    var url = r.home.feed.queue[0];

    r.home.feed.queue = r.home.feed.queue.splice(1);

    var portal = new Portal(url);
    portal.connect()
    r.home.feed.update_log();
  }

  this.register = async function(portal)
  {
    console.info("connected to ",portal.json.name,this.portals.length+"|"+this.queue.length);

    // Fix the URL of the registered portal.
    for (var id = 0; id < r.home.portal.json.port.length; id++) {
      var port_url = r.home.portal.json.port[id];
      if (port_url != portal.url) continue;
      port_url = portal.archive.url || portal.url;
      if (!port_url.replace("dat://", "").indexOf("/") > -1)
        port_url = port_url + "/";
      r.home.portal.json.port[id] = port_url;
      break;
    }

    this.portals.push(portal);
    var activity = portal.archive.createFileActivityStream();
    activity.addEventListener("invalidated", e => {
      r.home.feed.refresh(portal.json.name+" invalidated");
      portal.refresh().then(() => {
        r.home.update();
        r.home.feed.refresh(portal.json.name+" refreshed");
      });
    });
    r.home.update();
    r.home.feed.refresh(portal.json.name+" registered");
  }

  this.update_log = function()
  {
    if(r.home.feed.queue.length == 0){
      r.home.log("Idle.");
      clearInterval(r.home.feed.timer)
    }
    else{
      var progress = (r.home.feed.portals.length/parseFloat(r.home.portal.json.port.length)) * 100;
      r.home.log("Connecting to "+r.home.feed.portals.length+"/"+r.home.portal.json.port.length+" portals.. "+parseInt(progress)+"%");
    }
  }

  this.page_prev = async function()
  {
    r.home.feed.page--;
    r.home.update();
    await r.home.feed.refresh('page prev');
    window.scrollTo(0, document.body.scrollHeight);
  }

  this.page_next = async function()
  {
    r.home.feed.page++;
    r.home.update();
    await r.home.feed.refresh('page next');
    window.scrollTo(0, 0);
  }

  this.page_jump = async function(page)
  {
    r.home.feed.page = page;
    r.home.update();
    await r.home.feed.refresh('page jump ' + r.home.feed.page);
  }

  this.refresh = function(why)
  {
    if (why && why.startsWith("delay: ")) {
      why = why.replace("delay: ", "");
      // Delay the refresh to occur again after all portals refreshed.
      setTimeout(async function() {
        for (var id in r.home.feed.portals) {
          var portal = r.home.feed.portals[id];
          await portal.refresh();
        }
        r.home.feed.refresh('delayed: ' + why);
      }, 250);
      return;
    }
    if(!why) { console.error("unjustified refresh"); }
    console.log("refreshing feed..", "#" + r.home.feed.target, "→"+why);

    if (this.page_target != r.home.feed.target ||
        this.page_filter != r.home.feed.filter) {
      // Jumping between tabs? Switching filters? Reset!
      this.page = 0;
    }
    this.page_target = r.home.feed.target;
    this.page_filter = r.home.feed.filter;

    var entries = [];

    for(id in r.home.feed.portals){
      var portal = r.home.feed.portals[id];
      entries = entries.concat(portal.entries())
    }

    this.mentions = entries.filter(function (e) { return e.is_visible("", "mentions") }).length
    this.whispers = entries.filter(function (e) { return e.is_visible("", "whispers") }).length

    var sorted_entries = entries.sort(function (a, b) {
      return a.timestamp < b.timestamp ? 1 : -1;
    });

    var timeline = r.home.feed.wr_timeline_el;

    var ca = 0;
    var cmin = this.page * this.page_size;
    var cmax = cmin + this.page_size;

    if (this.page > 0) {
      // Create page_prev_el if missing.
      if (!this.page_prev_el) {
        this.page_prev_el = document.createElement('div');
        this.page_prev_el.className = 'entry paginator page-prev';
        this.page_prev_el.setAttribute('data-operation', 'page:--');
        this.page_prev_el.setAttribute('data-validate', 'true');
        this.page_prev_el.innerHTML = "<t class='message' dir='auto'>↑</t>";
        timeline.appendChild(this.page_prev_el);
      }
    } else {
      // Remove page_prev_el.
      if (this.page_prev_el) {
        timeline.removeChild(this.page_prev_el);
        this.page_prev_el = null;
      }
    }

    var now = new Date();
    for (id in sorted_entries){
      var entry = sorted_entries[id];
      var c = ca;
      if (!entry || entry.timestamp > now)
        c = -1;
      else if (!entry.is_visible(r.home.feed.filter, r.home.feed.target))
        c = -2;
      var elem = !entry ? null : entry.to_element(timeline, c, cmin, cmax);
      if (c >= 0)
        ca++;
    }

    var pages = Math.ceil(ca / this.page_size);

    if (ca >= cmax) {
      // Create page_next_el if missing.
      if (!this.page_next_el) {
        this.page_next_el = document.createElement('div');
        this.page_next_el.className = 'entry paginator page-next';
        this.page_next_el.setAttribute('data-operation', 'page:++');
        this.page_next_el.setAttribute('data-validate', 'true');
        this.page_next_el.innerHTML = "<t class='message' dir='auto'>↓</t>";
      }
      // Always append as last.
      timeline.appendChild(this.page_next_el);
    } else {
      // Remove page_next_el.
      if (this.page_next_el) {
        timeline.removeChild(this.page_next_el);
        this.page_next_el = null;
      }
    }

    r.home.feed.tab_timeline_el.innerHTML = entries.length+" Entries";
    r.home.feed.tab_mentions_el.innerHTML = this.mentions+" Mention"+(this.mentions == 1 ? '' : 's')+"";
    r.home.feed.tab_whispers_el.innerHTML = this.whispers+" Whisper"+(this.whispers == 1 ? '' : 's')+"";
    r.home.feed.tab_portals_el.innerHTML = r.home.feed.portals.length+" Portal"+(r.home.feed.portals.length == 1 ? '' : 's')+"";
    r.home.feed.tab_discovery_el.innerHTML = (r.home.discovery_enabled?r.home.discovered_count+"/":"")+r.home.network.length+" Network"+(r.home.network.length == 1 ? '' : 's')+"";

    r.home.feed.tab_mentions_el.className = r.home.feed.target == "mentions" ? "active" : "";
    r.home.feed.tab_whispers_el.className = r.home.feed.target == "whispers" ? "active" : "";
    r.home.feed.tab_portals_el.className = r.home.feed.target == "portals" ? "active" : "";
    r.home.feed.tab_discovery_el.className = r.home.feed.target == "discovery" ? "active" : "";
    r.home.feed.tab_timeline_el.className = r.home.feed.target == "" ? "active" : "";
  }
}

function to_hash(url)
{
  if (!url)
    return null;

  if (url.startsWith("//"))
    url = url.substring(2);

  url = url.replace("dat://", "");

  var index = url.indexOf("/");
  url = index == -1 ? url : url.substring(0, index);

  url = url.toLowerCase().trim();
  return url;
}

function has_hash(hashes_a, hashes_b)
{
  // Passed a portal (or something giving hashes) as hashes_a or hashes_b.
  if (hashes_a && typeof(hashes_a.hashes) == "function")
    hashes_a = hashes_a.hashes();
  if (hashes_b && typeof(hashes_b.hashes) == "function")
    hashes_b = hashes_b.hashes();

  // Passed a single url or hash as hashes_b. Let's support it for convenience.
  if (typeof(hashes_b) == "string")
    return hashes_a.findIndex(hash_a => to_hash(hash_a) == to_hash(hashes_b)) > -1;

  for (var a in hashes_a) {
    var hash_a = to_hash(hashes_a[a]);
    if (!hash_a)
      continue;

    for (var b in hashes_b) {
      var hash_b = to_hash(hashes_b[b]);
      if (!hash_b)
        continue;

      if (hash_a == hash_b)
        return true;
    }

  }

  return false;
}

function portal_from_hash(url)
{
  var hash = to_hash(url);

  for(id in r.home.feed.portals){
    if(has_hash(r.home.feed.portals[id], hash)){ return "@"+r.home.feed.portals[id].json.name; }
  }
  if(has_hash(r.home.portal, hash)){
    return "@"+r.home.portal.json.name;
  }
  return hash.substr(0,12)+".."+hash.substr(hash.length-3,2);
}

function create_rune(context, type)
{
  context = r.escape_attr(context);
  type = r.escape_attr(type);
  return `<i class='rune rune-${context} rune-${context}-${type}'></i>`;
}

r.confirm("script","feed");
<commit_msg>Remove redundant refresh on update<commit_after>function Feed(feed_urls)
{
  this.feed_urls = feed_urls;
  this.el = document.createElement('div'); this.el.id = "feed";
  this.tabs_el = document.createElement('div'); this.tabs_el.id = "tabs";
  this.wr_el = document.createElement('div'); this.wr_el.id = "tabs_wrapper";

  this.tab_timeline_el = document.createElement('t'); this.tab_timeline_el.id = "tab_timeline";
  this.tab_mentions_el = document.createElement('t'); this.tab_mentions_el.id = "tab_mentions";
  this.tab_whispers_el = document.createElement('t'); this.tab_whispers_el.id = "tab_whispers";
  this.tab_portals_el = document.createElement('t'); this.tab_portals_el.id = "tab_portals";
  this.tab_discovery_el = document.createElement('t'); this.tab_discovery_el.id = "tab_discovery";
  this.tab_services_el = document.createElement('t'); this.tab_services_el.id = "tab_services";

  this.tab_portals_el.setAttribute("data-operation","filter:portals");
  this.tab_portals_el.setAttribute("data-validate","true");
  this.tab_mentions_el.setAttribute("data-operation","filter:mentions");
  this.tab_mentions_el.setAttribute("data-validate","true");
  this.tab_whispers_el.setAttribute("data-operation","filter:whispers");
  this.tab_whispers_el.setAttribute("data-validate","true");
  this.tab_timeline_el.setAttribute("data-operation","clear_filter");
  this.tab_timeline_el.setAttribute("data-validate","true");
  this.tab_discovery_el.setAttribute('data-operation', 'filter:discovery');
  this.tab_discovery_el.setAttribute('data-validate', "true");

  this.el.appendChild(this.tabs_el);
  this.tabs_el.appendChild(this.tab_timeline_el);
  this.tabs_el.appendChild(this.tab_mentions_el);
  this.tabs_el.appendChild(this.tab_whispers_el);
  this.tabs_el.appendChild(this.tab_portals_el);
  this.tabs_el.appendChild(this.tab_discovery_el);
  this.tabs_el.appendChild(this.tab_services_el);

  this.wr_timeline_el = document.createElement('div'); this.wr_timeline_el.id = "wr_timeline";
  this.wr_portals_el = document.createElement('div'); this.wr_portals_el.id = "wr_portals";
  this.wr_discovery_el = document.createElement('div'); this.wr_discovery_el.id = "wr_discovery";

  this.el.appendChild(this.wr_el);
  this.wr_el.appendChild(this.wr_timeline_el);
  this.wr_el.appendChild(this.wr_portals_el);
  this.wr_el.appendChild(this.wr_discovery_el);

  this.queue = [];
  this.portals = [];

  this.urls = {};
  this.filter = "";
  this.target = window.location.hash ? window.location.hash.replace("#","") : "";
  this.timer = null;
  this.mentions = 0;

  this.page = 0;
  this.page_size = 20;
  this.page_target = null;
  this.page_filter = null;

  this.install = function()
  {
    r.el.appendChild(r.home.feed.el);
    r.home.feed.start();
  }

  this.start = function()
  {
    this.queue.push(r.home.portal.url);
    for(id in r.home.portal.json.port){
      var url = r.home.portal.json.port[id];
      this.queue.push(url)
    }
    this.next();

    this.timer = setInterval(r.home.feed.next, 500);
  }

  this.next = async function()
  {
    if(r.home.feed.queue.length < 1){ console.log("Reached end of queue"); r.home.feed.update_log(); return; }

    var url = r.home.feed.queue[0];

    r.home.feed.queue = r.home.feed.queue.splice(1);

    var portal = new Portal(url);
    portal.connect()
    r.home.feed.update_log();
  }

  this.register = async function(portal)
  {
    console.info("connected to ",portal.json.name,this.portals.length+"|"+this.queue.length);

    // Fix the URL of the registered portal.
    for (var id = 0; id < r.home.portal.json.port.length; id++) {
      var port_url = r.home.portal.json.port[id];
      if (port_url != portal.url) continue;
      port_url = portal.archive.url || portal.url;
      if (!port_url.replace("dat://", "").indexOf("/") > -1)
        port_url = port_url + "/";
      r.home.portal.json.port[id] = port_url;
      break;
    }

    this.portals.push(portal);
    var activity = portal.archive.createFileActivityStream();
    activity.addEventListener("invalidated", e => {
      portal.refresh().then(() => {
        r.home.update();
        r.home.feed.refresh(portal.json.name+" refreshed");
      });
    });
    r.home.update();
    r.home.feed.refresh(portal.json.name+" registered");
  }

  this.update_log = function()
  {
    if(r.home.feed.queue.length == 0){
      r.home.log("Idle.");
      clearInterval(r.home.feed.timer)
    }
    else{
      var progress = (r.home.feed.portals.length/parseFloat(r.home.portal.json.port.length)) * 100;
      r.home.log("Connecting to "+r.home.feed.portals.length+"/"+r.home.portal.json.port.length+" portals.. "+parseInt(progress)+"%");
    }
  }

  this.page_prev = async function()
  {
    r.home.feed.page--;
    r.home.update();
    await r.home.feed.refresh('page prev');
    window.scrollTo(0, document.body.scrollHeight);
  }

  this.page_next = async function()
  {
    r.home.feed.page++;
    r.home.update();
    await r.home.feed.refresh('page next');
    window.scrollTo(0, 0);
  }

  this.page_jump = async function(page)
  {
    r.home.feed.page = page;
    r.home.update();
    await r.home.feed.refresh('page jump ' + r.home.feed.page);
  }

  this.refresh = function(why)
  {
    if (why && why.startsWith("delay: ")) {
      why = why.replace("delay: ", "");
      // Delay the refresh to occur again after all portals refreshed.
      setTimeout(async function() {
        for (var id in r.home.feed.portals) {
          var portal = r.home.feed.portals[id];
          await portal.refresh();
        }
        r.home.feed.refresh('delayed: ' + why);
      }, 250);
      return;
    }
    if(!why) { console.error("unjustified refresh"); }
    console.log("refreshing feed..", "#" + r.home.feed.target, "→"+why);

    if (this.page_target != r.home.feed.target ||
        this.page_filter != r.home.feed.filter) {
      // Jumping between tabs? Switching filters? Reset!
      this.page = 0;
    }
    this.page_target = r.home.feed.target;
    this.page_filter = r.home.feed.filter;

    var entries = [];

    for(id in r.home.feed.portals){
      var portal = r.home.feed.portals[id];
      entries = entries.concat(portal.entries())
    }

    this.mentions = entries.filter(function (e) { return e.is_visible("", "mentions") }).length
    this.whispers = entries.filter(function (e) { return e.is_visible("", "whispers") }).length

    var sorted_entries = entries.sort(function (a, b) {
      return a.timestamp < b.timestamp ? 1 : -1;
    });

    var timeline = r.home.feed.wr_timeline_el;

    var ca = 0;
    var cmin = this.page * this.page_size;
    var cmax = cmin + this.page_size;

    if (this.page > 0) {
      // Create page_prev_el if missing.
      if (!this.page_prev_el) {
        this.page_prev_el = document.createElement('div');
        this.page_prev_el.className = 'entry paginator page-prev';
        this.page_prev_el.setAttribute('data-operation', 'page:--');
        this.page_prev_el.setAttribute('data-validate', 'true');
        this.page_prev_el.innerHTML = "<t class='message' dir='auto'>↑</t>";
        timeline.appendChild(this.page_prev_el);
      }
    } else {
      // Remove page_prev_el.
      if (this.page_prev_el) {
        timeline.removeChild(this.page_prev_el);
        this.page_prev_el = null;
      }
    }

    var now = new Date();
    for (id in sorted_entries){
      var entry = sorted_entries[id];
      var c = ca;
      if (!entry || entry.timestamp > now)
        c = -1;
      else if (!entry.is_visible(r.home.feed.filter, r.home.feed.target))
        c = -2;
      var elem = !entry ? null : entry.to_element(timeline, c, cmin, cmax);
      if (c >= 0)
        ca++;
    }

    var pages = Math.ceil(ca / this.page_size);

    if (ca >= cmax) {
      // Create page_next_el if missing.
      if (!this.page_next_el) {
        this.page_next_el = document.createElement('div');
        this.page_next_el.className = 'entry paginator page-next';
        this.page_next_el.setAttribute('data-operation', 'page:++');
        this.page_next_el.setAttribute('data-validate', 'true');
        this.page_next_el.innerHTML = "<t class='message' dir='auto'>↓</t>";
      }
      // Always append as last.
      timeline.appendChild(this.page_next_el);
    } else {
      // Remove page_next_el.
      if (this.page_next_el) {
        timeline.removeChild(this.page_next_el);
        this.page_next_el = null;
      }
    }

    r.home.feed.tab_timeline_el.innerHTML = entries.length+" Entries";
    r.home.feed.tab_mentions_el.innerHTML = this.mentions+" Mention"+(this.mentions == 1 ? '' : 's')+"";
    r.home.feed.tab_whispers_el.innerHTML = this.whispers+" Whisper"+(this.whispers == 1 ? '' : 's')+"";
    r.home.feed.tab_portals_el.innerHTML = r.home.feed.portals.length+" Portal"+(r.home.feed.portals.length == 1 ? '' : 's')+"";
    r.home.feed.tab_discovery_el.innerHTML = (r.home.discovery_enabled?r.home.discovered_count+"/":"")+r.home.network.length+" Network"+(r.home.network.length == 1 ? '' : 's')+"";

    r.home.feed.tab_mentions_el.className = r.home.feed.target == "mentions" ? "active" : "";
    r.home.feed.tab_whispers_el.className = r.home.feed.target == "whispers" ? "active" : "";
    r.home.feed.tab_portals_el.className = r.home.feed.target == "portals" ? "active" : "";
    r.home.feed.tab_discovery_el.className = r.home.feed.target == "discovery" ? "active" : "";
    r.home.feed.tab_timeline_el.className = r.home.feed.target == "" ? "active" : "";
  }
}

function to_hash(url)
{
  if (!url)
    return null;

  if (url.startsWith("//"))
    url = url.substring(2);

  url = url.replace("dat://", "");

  var index = url.indexOf("/");
  url = index == -1 ? url : url.substring(0, index);

  url = url.toLowerCase().trim();
  return url;
}

function has_hash(hashes_a, hashes_b)
{
  // Passed a portal (or something giving hashes) as hashes_a or hashes_b.
  if (hashes_a && typeof(hashes_a.hashes) == "function")
    hashes_a = hashes_a.hashes();
  if (hashes_b && typeof(hashes_b.hashes) == "function")
    hashes_b = hashes_b.hashes();

  // Passed a single url or hash as hashes_b. Let's support it for convenience.
  if (typeof(hashes_b) == "string")
    return hashes_a.findIndex(hash_a => to_hash(hash_a) == to_hash(hashes_b)) > -1;

  for (var a in hashes_a) {
    var hash_a = to_hash(hashes_a[a]);
    if (!hash_a)
      continue;

    for (var b in hashes_b) {
      var hash_b = to_hash(hashes_b[b]);
      if (!hash_b)
        continue;

      if (hash_a == hash_b)
        return true;
    }

  }

  return false;
}

function portal_from_hash(url)
{
  var hash = to_hash(url);

  for(id in r.home.feed.portals){
    if(has_hash(r.home.feed.portals[id], hash)){ return "@"+r.home.feed.portals[id].json.name; }
  }
  if(has_hash(r.home.portal, hash)){
    return "@"+r.home.portal.json.name;
  }
  return hash.substr(0,12)+".."+hash.substr(hash.length-3,2);
}

function create_rune(context, type)
{
  context = r.escape_attr(context);
  type = r.escape_attr(type);
  return `<i class='rune rune-${context} rune-${context}-${type}'></i>`;
}

r.confirm("script","feed");
<|endoftext|>


<commit_before>var game=game||{};
game.resources = {};
game.tick = function() {
  for(var count=0;count<this.resources;count++) {
    this.resources[count].update();
  }
};
game.tick.bind(game);
game.interval = window.setInterval(game.tick,100);
function increase(event) {
 event = event || window.event;
 if(game.resources["gold"].value > 100*Math.pow(1.1,game.resources["house"].value)) {
    game.resources["gold"].decrease(100*Math.pow(1.1,game.resources["house"].value));
    game.resources["house"].increase();
    event.target.innerHTML = "Buy House: " + 100*Math.pow(1.1,game.resources["house"].value);
 }
}
function tick() {
  game.resources["gold"].value+=0.1*game.resources["house"].value+0.0001;
}
function add(){
  game.resources["gold"].value++;
}

game.resource = function(name,startingValue,onTick,onClick,label) {
  this.name = name;
  this.onTick = onTick?onTick:function(){};
  this.onTick.bind(this);
  this.format=function(value) {
    if(value>1000000000000000) {
      return this.format(value/1000000000000000)+"qi";
    }
    if(value>1000000000000) {
      return this.format(value/1000000000000)+"qa";
    }
    if(value>1000000000) {
      return this.format(value/1000000000)+"b";
    }
    if(value>1000000) {
      return this.format(value/1000000)+"m";
    }
    if(value>1000) {
      return this.format(value/1000)+"k";
    }
    return Math.floor(value)+"."+Math.floor(value*10)%10;
  };
  this.update = function() {
    this.onTick();
    this.label.lastChild.innerHTML=this.format(this.value);
  };
  this.update.bind(this);
  this.value = startingValue?startingValue:0;
  this.increase = function(amount) {
    this.value += amount?amount:1;
  }
  this.decrease = function(amount) {
    if(amount>this.value) {
      throw "Not enough "+this.name;
    }
    this.value -= amount;
  }
  this.button = document.createElement('button');
  this.button.innerHTML = label?label:name+"-action";
  this.button.onclick = onClick?onClick:function(){};
  this.label = document.createElement('div');
  this.label.setAttribute('class','resource');
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.name;
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.format(this.value);
  game.labels.appendChild(this.label);
  game.buttons.appendChild(this.button);
  game.resources[this.name] = this;
}
game.resource('gold',50,tick, add,'Mine gold')
game.resource('house',0,null, increased,'Buy House')
<commit_msg>Update game.js<commit_after>var game=game||{};
game.resources = {};
game.tick = function() {
  for(var count=0;count<this.resources;count++) {
    this.resources[count].update();
  }
};
game.tick.bind(game);
game.interval = window.setInterval(game.tick,100);
game.buttons = document.getElementsByTagName('body')[0];
game.labels = document.getElementsByTagName('body')[0];
function increase(event) {
 event = event || window.event;
 if(game.resources["gold"].value > 100*Math.pow(1.1,game.resources["house"].value)) {
    game.resources["gold"].decrease(100*Math.pow(1.1,game.resources["house"].value));
    game.resources["house"].increase();
    event.target.innerHTML = "Buy House: " + 100*Math.pow(1.1,game.resources["house"].value);
 }
}
function tick() {
  game.resources["gold"].value+=0.1*game.resources["house"].value+0.0001;
}
function add(){
  game.resources["gold"].value++;
}

game.resource = function(name,startingValue,onTick,onClick,label) {
  this.name = name;
  this.onTick = onTick?onTick:function(){};
  this.onTick.bind(this);
  this.format=function(value) {
    if(value>1000000000000000) {
      return this.format(value/1000000000000000)+"qi";
    }
    if(value>1000000000000) {
      return this.format(value/1000000000000)+"qa";
    }
    if(value>1000000000) {
      return this.format(value/1000000000)+"b";
    }
    if(value>1000000) {
      return this.format(value/1000000)+"m";
    }
    if(value>1000) {
      return this.format(value/1000)+"k";
    }
    return Math.floor(value)+"."+Math.floor(value*10)%10;
  };
  this.update = function() {
    this.onTick();
    this.label.lastChild.innerHTML=this.format(this.value);
  };
  this.update.bind(this);
  this.value = startingValue?startingValue:0;
  this.increase = function(amount) {
    this.value += amount?amount:1;
  }
  this.decrease = function(amount) {
    if(amount>this.value) {
      throw "Not enough "+this.name;
    }
    this.value -= amount;
  }
  this.button = document.createElement('button');
  this.button.innerHTML = label?label:name+"-action";
  this.button.onclick = onClick?onClick:function(){};
  this.label = document.createElement('div');
  this.label.setAttribute('class','resource');
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.name;
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.format(this.value);
  game.labels.appendChild(this.label);
  game.buttons.appendChild(this.button);
  game.resources[this.name] = this;
}
game.resource('gold',50,tick, add,'Mine gold')
game.resource('house',0,null, increased,'Buy House')
<|endoftext|>


<commit_before>var game= {
  resources: {},
  tick: function() {
  for(var res in game.resources) {
    game.resources[res].update();
  }
}
};
game.tick.bind(game);
game.interval = window.setInterval(game.tick,100);
game.buttons = document.getElementById('buttons');
game.labels = document.getElementById('stats');

game.resource = function(name,startingValue,onTick,onClick,label) {
  this.name = name;
  this.onTick = onTick?onTick:function(){};
  this.onTick.bind(this);
  this.format=function(value) {
    if(value>1000000000000000) {
      return this.format(value/1000000000000000)+"qi";
    }
    if(value>1000000000000) {
      return this.format(value/1000000000000)+"qa";
    }
    if(value>1000000000) {
      return this.format(value/1000000000)+"b";
    }
    if(value>1000000) {
      return this.format(value/1000000)+"m";
    }
    if(value>1000) {
      return this.format(value/1000)+"k";
    }
    return Math.floor(value)+"."+Math.floor(value*10)%10;
  };
  this.update = function() {
    this.onTick();
    this.label.lastChild.innerHTML=this.format(this.value);
  };
  this.update.bind(this);
  this.value = startingValue?startingValue:0;
  this.increase = function(amount) {
    this.value += amount?amount:1;
  }
  this.decrease = function(amount) {
    if(amount>this.value) {
      throw "Not enough "+this.name;
    }
    this.value -= amount;
  }
  if(onClick){
  this.button = document.createElement('button');
  this.button.innerHTML = label?label:name+"-action";
  this.button.onclick = onClick;
  game.buttons.appendChild(this.button);
  }
  this.label = document.createElement('div');
  this.label.setAttribute('class','resource');
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.name;
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.format(this.value);
  game.labels.appendChild(this.label);
  game.resources[this.name] = this;
}
game.resources.gold = new game.resource('gold',50,
              function(){ game.resources["gold"].value+=0.1*game.resources.house.value+0.01*game.resources.human.value+0.0001;},
              function(){ game.resources["gold"].value++;},
              'Mine gold')
game.resources.house = new game.resource('house',0,function(){
game.resources.house.derease(Math.round(Math.random())*0.001);
}, function(event) {
 event = event || window.event;
 if(game.resources.gold.value > 100*Math.pow(1.1,game.resources.house.value)) {
    game.resources.gold.decrease(100*Math.pow(1.1,game.resources.house.value));
    game.resources.house.increase();
    event.target.innerHTML = "Buy House: " + game.resources.house.format(100*Math.pow(1.1,game.resources.house.value));
 }
},'Buy House');
game.resources.human = new game.resource('human',1,function(){
  game.resources.human+=Math.round(Math.random(0,game.resources.house));
});
<commit_msg>Update game.js<commit_after>var game= {
  resources: {},
  tick: function() {
  for(var res in game.resources) {
    game.resources[res].update();
  }
}
};
game.tick.bind(game);
game.interval = window.setInterval(game.tick,100);
game.buttons = document.getElementById('buttons');
game.labels = document.getElementById('stats');

game.resource = function(name,startingValue,onTick,onClick,label) {
  this.name = name;
  this.onTick = onTick?onTick:function(){};
  this.onTick.bind(this);
  this.format=function(value) {
    if(value>1000000000000000) {
      return this.format(value/1000000000000000)+"qi";
    }
    if(value>1000000000000) {
      return this.format(value/1000000000000)+"qa";
    }
    if(value>1000000000) {
      return this.format(value/1000000000)+"b";
    }
    if(value>1000000) {
      return this.format(value/1000000)+"m";
    }
    if(value>1000) {
      return this.format(value/1000)+"k";
    }
    return Math.floor(value)+"."+Math.floor(value*10)%10;
  };
  this.update = function() {
    this.onTick();
    this.label.lastChild.innerHTML=this.format(this.value);
  };
  this.update.bind(this);
  this.value = startingValue?startingValue:0;
  this.increase = function(amount) {
    this.value += amount?amount:1;
  }
  this.decrease = function(amount) {
    if(amount>this.value) {
      throw "Not enough "+this.name;
    }
    this.value -= amount;
  }
  if(onClick){
  this.button = document.createElement('button');
  this.button.innerHTML = label?label:name+"-action";
  this.button.onclick = onClick;
  game.buttons.appendChild(this.button);
  }
  this.label = document.createElement('div');
  this.label.setAttribute('class','resource');
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.name;
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.format(this.value);
  game.labels.appendChild(this.label);
  game.resources[this.name] = this;
}
game.resources.gold = new game.resource('gold',50,
              function(){ game.resources["gold"].value+=0.1*game.resources.house.value+0.01*game.resources.human.value+0.0001;},
              function(){ game.resources["gold"].value++;},
              'Mine gold')
game.resources.house = new game.resource('house',0,function(){
  try{
game.resources.house.decrease(Math.round(Math.random())*0.001);
  }catch(e){
  //no issue here
  }
}, function(event) {
 event = event || window.event;
 if(game.resources.gold.value > 100*Math.pow(1.1,game.resources.house.value)) {
    game.resources.gold.decrease(100*Math.pow(1.1,game.resources.house.value));
    game.resources.house.increase();
    event.target.innerHTML = "Buy House: " + game.resources.house.format(100*Math.pow(1.1,game.resources.house.value));
 }
},'Buy House');
game.resources.human = new game.resource('human',1,function(){
  game.resources.human+=Math.round(Math.random(0,game.resources.house));
});
<|endoftext|>


<commit_before>var game=game||{};
game.resources = {};
game.tick = function() {
  for(var count=0;count<this.resources;count++) {
    this.resources[count].update();
  }
};
game.tick.bind(game);
game.interval = window.setInterval(game.tick,100);
house=0;
gold=50;
function increase(event) {
 event = event || window.event;
 if(gold > 100*Math.pow(1.1,house)) {
    gold-=100*Math.pow(1.1,house);
    house++;
    event.target.innerHTML =100*Math.pow(1.1,house);
    document.getElementById("gold").firstChild.innerHTML=gold;
    document.getElementById("house").firstChild.innerHTML=house;
 }
}
function tick() {
  this.value+=0.1*game.resources["house"].value+0.0001;
}

game.resource = function(name,startingValue,onTick,onClick,label) {
  this.name = name;
  this.onTick = onTick?onTick:function(){};
  this.onTick.bind(this);
  this.format=function(value) {
    if(value>1000000000000000) {
      return this.format(value/1000000000000000)+"qi";
    }
    if(value>1000000000000) {
      return this.format(value/1000000000000)+"qa";
    }
    if(value>1000000000) {
      return this.format(value/1000000000)+"b";
    }
    if(value>1000000) {
      return this.format(value/1000000)+"m";
    }
    if(value>1000) {
      return this.format(value/1000)+"k";
    }
    return Math.floor(value)+"."+Math.floor(value*10)%10;
  };
  this.update = function() {
    this.onTick();
    this.label.lastChild.innerHTML=this.format(this.value);
  };
  this.update.bind(this);
  this.value = startingValue?startingValue:0;
  this.increase = function(amount) {
    this.value += amount?amount:1;
  }
  this.decrease = function(amount) {
    if(amount>this.value) {
      throw "Not enough "+this.name;
    }
    this.value -= amount;
  }
  this.button = document.createElement('button');
  this.button.innerHTML = label?label:name+"-action";
  this.button.onclick = onClick?onClick:function(){};
  this.label = document.createElement('div');
  this.label.setAttribute('class','resource');
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.name;
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.format(this.value);
}
<commit_msg>Update game.js<commit_after>var game=game||{};
game.resources = {};
game.tick = function() {
  for(var count=0;count<this.resources;count++) {
    this.resources[count].update();
  }
};
game.tick.bind(game);
game.interval = window.setInterval(game.tick,100);
house=0;
gold=50;
function increase(event) {
 event = event || window.event;
 if(gold > 100*Math.pow(1.1,house)) {
    gold-=100*Math.pow(1.1,house);
    house++;
    event.target.innerHTML =100*Math.pow(1.1,house);
    document.getElementById("gold").firstChild.innerHTML=gold;
    document.getElementById("house").firstChild.innerHTML=house;
 }
}
function tick() {
  this.value+=0.1*game.resources["house"].value+0.0001;
}

game.resource = function(name,startingValue,onTick,onClick,label) {
  this.name = name;
  this.onTick = onTick?onTick:function(){};
  this.onTick.bind(this);
  this.format=function(value) {
    if(value>1000000000000000) {
      return this.format(value/1000000000000000)+"qi";
    }
    if(value>1000000000000) {
      return this.format(value/1000000000000)+"qa";
    }
    if(value>1000000000) {
      return this.format(value/1000000000)+"b";
    }
    if(value>1000000) {
      return this.format(value/1000000)+"m";
    }
    if(value>1000) {
      return this.format(value/1000)+"k";
    }
    return Math.floor(value)+"."+Math.floor(value*10)%10;
  };
  this.update = function() {
    this.onTick();
    this.label.lastChild.innerHTML=this.format(this.value);
  };
  this.update.bind(this);
  this.value = startingValue?startingValue:0;
  this.increase = function(amount) {
    this.value += amount?amount:1;
  }
  this.decrease = function(amount) {
    if(amount>this.value) {
      throw "Not enough "+this.name;
    }
    this.value -= amount;
  }
  this.button = document.createElement('button');
  this.button.innerHTML = label?label:name+"-action";
  this.button.onclick = onClick?onClick:function(){};
  this.label = document.createElement('div');
  this.label.setAttribute('class','resource');
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.name;
  this.label.appendChild(document.createElement('div'));
  this.label.lastChild.innerHTML=this.format(this.value);
}
game.resources.push('gold',50,tick, null,'Mine gold')
game.resources.push('house',0,null, increased,'Buy House')
<|endoftext|>


<commit_before>'use strict';

//declare button id's
var hitButton = document.getElementById('hitButton');
var stayButton = document.getElementById('stayButton');
var splitButton = document.getElementById('splitButton');
var dealButton = document.getElementById('dealButton');
var computer0Hand = document.getElementById('dealerhand');
var playerHand = document.getElementById('playerhand');
Player.computer1Hand = document.getElementById('computer1Hand');
Player.computer2Hand = document.getElementById('computer2Hand');
Player.computer3Hand = document.getElementById('computer3Hand');
Player.computer4Hand = document.getElementById('computer4Hand');
Player.computer5Hand = document.getElementById('computer5Hand');
Player.computer6Hand = document.getElementById('computer6Hand');

//constructor for players
function Player(name, handLoc){
  this.name = name;
  this.handLoc = handLoc;
  this.handCards = [];
  this.gameOutcome = [];
  this.gamesPlayed = 0;
  this.handValue = 0 ;
  this.wins = 0;
  this.losses = 0;
  this.ties = 0;
  Player.playerObjectArray.push(this);
  localStorage.playerObjectArray = JSON.stringify(Player.playerObjectArray);
}

(Player.localStorageAlign = function(){
//checks to see if dealer and standinplayers were created and creates if needed
  if(!localStorage.playerObjectArray){
    Player.playerObjectArray = [];
    Player.staticPlayerNameArray = function(){
      var staticPlayerNameArray = ['Dealer', 'Player1', 'Player2', 'Player3', 'Player4', 'Player5', 'Player6'];
      for (var i in staticPlayerNameArray){
        new Player(staticPlayerNameArray[i], eval('Player.computer' + i + 'Hand'));
      }
    };
    Player.staticPlayerNameArray();
  }else{
    Player.playerObjectArray = JSON.parse(localStorage.playerObjectArray);
  }

  // if username does not have an object, creates one with name of username
  if(localStorage.userName && !localStorage.playerObjectArray.includes(localStorage.userName)){
    // console.log('creating new user object');
    new Player(localStorage.userName, playerHand);
  }
})();

//function to store the i variable of the current user for reference in Player.playerObjectArray[i];
Player.currentUser = function(){
  for(var i in Player.playerObjectArray){
    // console.log(i);
    if(Player.playerObjectArray[i].name === localStorage.userName){
      // console.log('worked');
      return i;
    }
  }
};

//constructor function for cards
Card.all = [];
function Card(name, suit, value){
  this.name = name;
  this.suit = suit;
  this.value = value;
  Card.all.push(this);
}

//card values and names
Card.valueArray = [2,3,4,5,6,7,8,9,10,10,10,10,11];
Card.nameArray = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'];

//builds all the cards
(Card.cardCreator = function(){
  Card.all = [];
  for(var i in Card.valueArray){
    new Card(Card.nameArray[i], 'hearts', Card.valueArray[i]);
    new Card(Card.nameArray[i], 'diamonds', Card.valueArray[i]);
    new Card(Card.nameArray[i], 'spades', Card.valueArray[i]);
    new Card(Card.nameArray[i], 'clubs', Card.valueArray[i]);
  }
})();

// function newElement(type, content, parent){
//   var newEl = document.createElement(type);
//   newEl.textContent = content;
//   parent.appendChild(newEl);
// };

//print a card to the screen
Card.printCard = function(hand, suit, name){
  var outerDiv = document.createElement('div');
  var innerDiv = document.createElement('div');
  var topLeftP = document.createElement('p');
  var topRightP = document.createElement('p');
  var bottomLeftP = document.createElement('p');
  var bottomRightP = document.createElement('p');

  hand.appendChild(outerDiv);
  outerDiv.appendChild(innerDiv);
  innerDiv.appendChild(topLeftP);
  innerDiv.appendChild(topRightP);
  innerDiv.appendChild(bottomLeftP);
  innerDiv.appendChild(bottomRightP);

  topLeftP.classList.add('topleft');
  topRightP.classList.add('topright');
  bottomLeftP.classList.add('bottomleft');
  bottomRightP.classList.add('bottomright');
  topLeftP.classList.add('corner');
  topRightP.classList.add('corner');
  bottomLeftP.classList.add('corner');
  bottomRightP.classList.add('corner');

  topRightP.classList.add('bigger');
  bottomLeftP.classList.add('bigger');
  outerDiv.classList.add('outerbox');

  switch (suit) {
  case 'diamonds':
    topRightP.innerHTML = '♦';
    bottomLeftP.innerHTML = '♦';
    innerDiv.classList.add('innerboxr');
    break;
  case 'clubs':
    topRightP.innerHTML = '♣';
    bottomLeftP.innerHTML = '♣';
    innerDiv.classList.add('innerbox');
    break;
  case 'hearts':
    topRightP.innerHTML = '♥';
    bottomLeftP.innerHTML = '♥';
    innerDiv.classList.add('innerboxr');
    break;
  default:
    topRightP.innerHTML = '♠';
    bottomLeftP.innerHTML = '♠';
    innerDiv.classList.add('innerbox');
  }
  topLeftP.innerHTML = '<' + name + '>';
  bottomRightP.innerHTML = '</' + name + '>';
};

//selects a random card's integer and checks to make sure it is unique
Card.randomCard = function(){
  var cardInteger = Math.floor(Math.random() * (Card.all.length - 1));
  return Card.all.splice(cardInteger, 1);
};

//populates gives dealer and standin players cards and Player cards
Card.dealerFunction = function(){
  Card.cardsPickedThisHand = [];
  for (var i = 0; i < 7; i++){
    Player.playerObjectArray[i].handCards = [];
    Player.playerObjectArray[i].handCards.push(Card.randomCard());
    Player.playerObjectArray[i].handCards.push(Card.randomCard());
  }
  Player.playerObjectArray[Player.currentUser()].handCards = [];
  Player.playerObjectArray[Player.currentUser()].handCards.push(Card.randomCard());
  Player.playerObjectArray[Player.currentUser()].handCards.push(Card.randomCard());

  Card.printCard(computer0Hand, Player.playerObjectArray[0].handCards[1][0].suit , Player.playerObjectArray[0].handCards[1][0].name);

  for (var j = 1; j < 7; i++){
    Card.printCard(eval('Player.computer' + j + 'Hand'), Player.playerObjectArray[j].handCards[1][0].suit , Player.playerObjectArray[j].handCards[1][0].name);
  }

  Card.printCard(playerHand, Player.playerObjectArray[Player.currentUser()].handCards[0][0].suit, Player.playerObjectArray[Player.currentUser()].handCards[0][0].name);
  Card.printCard(playerHand, Player.playerObjectArray[Player.currentUser()].handCards[1][0].suit, Player.playerObjectArray[Player.currentUser()].handCards[1][0].name);
};
//TODO: add event listener to a button for dealing

//Iterates on dealer and all standin players to play their hand by vegas dealer rules
Player.computerPlaysHand = function(){
  for(var i = 0; i < 7; i++){
    Player.handSum(i);
    while (Player.playerObjectArray[i].handValue < 17){
      Player.playerObjectArray[i].handCards.push(Card.randomCard());
      Card.printCard(eval('Player.computer' + i + 'Hand'), Player.playerObjectArray[i].handCards[Player.playerObjectArray[i].handCards.length - 1][0].suit, Player.playerObjectArray[i].handCards[Player.playerObjectArray[i].handCards.length - 1][0].name);
      Player.handSum(i);
    }
  }
};
//function that reEvaluates the hand's value
Player.handSum = function(i){
  Player.playerObjectArray[i].handValue = 0;
  // console.log('reset is Success');
  for(var j in Player.playerObjectArray[i].handCards){
    // console.log('sums handCards');
    Player.playerObjectArray[i].handValue += Player.playerObjectArray[i].handCards[j][0].value;
  }
};

Player.userGuideRules = function(){
  Player.handSum(Player.currentUser());
  if([2,3].includes(Player.playerObjectArray[0].handCards[0][0].value)){
    if(Player.playerObjectArray[Player.currentUser()].handValue < 13){
      // console.log('hit lower than 13');
    }else{
      // console.log('stay');
    }
  }
  if([4,5,6].includes(Player.playerObjectArray[0].handCards[0][0].value)){
    if(Player.playerObjectArray[Player.currentUser()].handValue < 12){
      // console.log('hit lower than 12');
    }else{
      // console.log('stay');
    }
  }
  if([7,8,9].includes(Player.playerObjectArray[0].handCards[0][0].value)){
    if(Player.playerObjectArray[Player.currentUser()].handValue < 17){
      // console.log('hit lower than 17');
    }else{
      // console.log('stay');
    }
  }
  if([10,11].includes(Player.playerObjectArray[0].handCards[0][0].value)){
    if(Player.playerObjectArray[Player.currentUser()].handValue < 17 ){
      // console.log('hit lower than 17, split if able');
    }else{
      // console.log('stay');
    }
  }
};

//occurs when player ends turn (stays, busts, gets blackjack). Others play then currentUser compares to dealer
Player.gameResolution = function(){
  // console.log('gameReslolutionInvoked');
  Player.toggleGameEventListenersOff();
  // console.log('EListeners off');
  Player.computerPlaysHand();
  // console.log('computerPlaysHandInvoked');
  Player.handSum(Player.currentUser());
  // console.log('players hand is ' + Player.playerObjectArray[Player.currentUser()].handValue);
  if (Player.playerObjectArray[Player.currentUser()].handValue > 21 || Player.playerObjectArray[0].handValue > Player.playerObjectArray[Player.currentUser()].handvalue){
    console.log('loss');
    Player.playerObjectArray[Player.currentUser()].gameOutcome.push('loss');
    Player.playerObjectArray[Player.currentUser()].losses++;
    Player.playerObjectArray[Player.currentUser()].gamesPlayed++;
  }else if(Player.playerObjectArray[0].handValue > 21){
    console.log('win');
    Player.playerObjectArray[Player.currentUser()].gameOutcome.push('win');
    Player.playerObjectArray[Player.currentUser()].wins++;
    Player.playerObjectArray[Player.currentUser()].gamesPlayed++;
  }else if(Player.playerObjectArray[Player.currentUser()].handValue <= 21 && Player.playerObjectArray[0].handValue < Player.playerObjectArray[Player.currentUser()].handValue){
    console.log('win');
    Player.playerObjectArray[Player.currentUser()].gameOutcome.push('win');
    Player.playerObjectArray[Player.currentUser()].wins++;
    Player.playerObjectArray[Player.currentUser()].gamesPlayed++;
  }else {
    console.log('tie');
    Player.playerObjectArray[Player.currentUser()].gameOutcome.push('tie');
    Player.playerObjectArray[Player.currentUser()].ties++;
    Player.playerObjectArray[Player.currentUser()].gamesPlayed++;
  }
  localStorage.playerObjectArray = JSON.stringify(Player.playerObjectArray);
};

Player.hitHandler = function(){
  console.log('hit');
  Player.playerObjectArray[Player.currentUser()].handCards.push(Card.randomCard());
  //takes the last card in the hand and writes it to the page
  Card.printCard(playerHand, Player.playerObjectArray[Player.currentUser()].handCards[Player.playerObjectArray[Player.currentUser()].handCards.length - 1][0].suit, Player.playerObjectArray[Player.currentUser()].handCards[Player.playerObjectArray[Player.currentUser()].handCards.length - 1][0].name);
  // console.log('dealer hand is ' + Player.playerObjectArray[0].handValue);
  Player.handSum(Player.currentUser());
  // console.log(Player.playerObjectArray[Player.currentUser()]);
  if (Player.playerObjectArray[Player.currentUser()].handValue >= 21){
    // console.log('player hand busts');
    Player.gameResolution();
  }

};

Player.stayHandler = function(){
  console.log('stay');
  Player.gameResolution();
};

Player.splitHandler = function(){
  console.log('split');
  alert('Please upgrade your Flash player!');
};

//deals out cards and turns on hit/stay
Player.dealHandler = function(){
  Card.cardCreator();
  playerHand.innerHTML = null;
  computer0Hand.innerHTML = null;
  console.log('deal');
  Player.toggleGameEventListenersOn();
  Card.dealerFunction();
};

dealButton.addEventListener('click', Player.dealHandler);

Player.toggleGameEventListenersOn = function(){
  hitButton.addEventListener('click', Player.hitHandler);
  stayButton.addEventListener('click', Player.stayHandler);
  splitButton.addEventListener('click', Player.splitHandler);
};
Player.toggleGameEventListenersOff = function(){
  hitButton.removeEventListener('click', Player.hitHandler);
  stayButton.removeEventListener('click', Player.stayHandler);
  splitButton.removeEventListener('click', Player.splitHandler);
};
//todo add a card box with number and color of card type absoluted into corners
<commit_msg>worked on looping through all computer players for things that need to be applied globally.<commit_after>'use strict';

//declare button id's
var hitButton = document.getElementById('hitButton');
var stayButton = document.getElementById('stayButton');
var splitButton = document.getElementById('splitButton');
var dealButton = document.getElementById('dealButton');
var playerHand = document.getElementById('playerhand');
Player.computer0Hand = document.getElementById('dealerhand');
Player.computer1Hand = document.getElementById('computer1Hand');
Player.computer2Hand = document.getElementById('computer2Hand');
Player.computer3Hand = document.getElementById('computer3Hand');
Player.computer4Hand = document.getElementById('computer4Hand');
Player.computer5Hand = document.getElementById('computer5Hand');
Player.computer6Hand = document.getElementById('computer6Hand');

//constructor for players
function Player(name, handLoc){
  this.name = name;
  this.handLoc = handLoc;
  this.handCards = [];
  this.gameOutcome = [];
  this.gamesPlayed = 0;
  this.handValue = 0 ;
  this.wins = 0;
  this.losses = 0;
  this.ties = 0;
  Player.playerObjectArray.push(this);
  localStorage.playerObjectArray = JSON.stringify(Player.playerObjectArray);
}

(Player.localStorageAlign = function(){
//checks to see if dealer and standinplayers were created and creates if needed
  if(!localStorage.playerObjectArray){
    Player.playerObjectArray = [];
    Player.staticPlayerNameArray = function(){
      var staticPlayerNameArray = ['Dealer', 'Player1', 'Player2', 'Player3', 'Player4', 'Player5', 'Player6'];
      for (var i in staticPlayerNameArray){
        new Player(staticPlayerNameArray[i], eval('Player.computer' + i + 'Hand'));
      }
    };
    Player.staticPlayerNameArray();
  }else{
    Player.playerObjectArray = JSON.parse(localStorage.playerObjectArray);
  }

  // if username does not have an object, creates one with name of username
  if(localStorage.userName && !localStorage.playerObjectArray.includes(localStorage.userName)){
    // console.log('creating new user object');
    new Player(localStorage.userName, playerHand);
  }
})();

//function to store the i variable of the current user for reference in Player.playerObjectArray[i];
Player.currentUser = function(){
  for(var i = 7; i < Player.playerObjectArray.length; i++){
    if(Player.playerObjectArray[i].name === localStorage.userName){
      return i;
    }
  }
};

//constructor function for cards
Card.all = [];
function Card(name, suit, value){
  this.name = name;
  this.suit = suit;
  this.value = value;
  Card.all.push(this);
}

//card values and names
Card.valueArray = [2,3,4,5,6,7,8,9,10,10,10,10,11];
Card.nameArray = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'];

//builds all the cards
(Card.cardCreator = function(){
  Card.all = [];
  for(var i in Card.valueArray){
    new Card(Card.nameArray[i], 'hearts', Card.valueArray[i]);
    new Card(Card.nameArray[i], 'diamonds', Card.valueArray[i]);
    new Card(Card.nameArray[i], 'spades', Card.valueArray[i]);
    new Card(Card.nameArray[i], 'clubs', Card.valueArray[i]);
  }
})();

// function newElement(type, content, parent){
//   var newEl = document.createElement(type);
//   newEl.textContent = content;
//   parent.appendChild(newEl);
// };

//print a card to the screen
Card.printCard = function(hand, suit, name){
  var outerDiv = document.createElement('div');
  var innerDiv = document.createElement('div');
  var topLeftP = document.createElement('p');
  var topRightP = document.createElement('p');
  var bottomLeftP = document.createElement('p');
  var bottomRightP = document.createElement('p');

  hand.appendChild(outerDiv);
  outerDiv.appendChild(innerDiv);
  innerDiv.appendChild(topLeftP);
  innerDiv.appendChild(topRightP);
  innerDiv.appendChild(bottomLeftP);
  innerDiv.appendChild(bottomRightP);

  topLeftP.classList.add('topleft');
  topRightP.classList.add('topright');
  bottomLeftP.classList.add('bottomleft');
  bottomRightP.classList.add('bottomright');
  topLeftP.classList.add('corner');
  topRightP.classList.add('corner');
  bottomLeftP.classList.add('corner');
  bottomRightP.classList.add('corner');

  topRightP.classList.add('bigger');
  bottomLeftP.classList.add('bigger');
  outerDiv.classList.add('outerbox');

  switch (suit) {
  case 'diamonds':
    topRightP.innerHTML = '♦';
    bottomLeftP.innerHTML = '♦';
    innerDiv.classList.add('innerboxr');
    break;
  case 'clubs':
    topRightP.innerHTML = '♣';
    bottomLeftP.innerHTML = '♣';
    innerDiv.classList.add('innerbox');
    break;
  case 'hearts':
    topRightP.innerHTML = '♥';
    bottomLeftP.innerHTML = '♥';
    innerDiv.classList.add('innerboxr');
    break;
  default:
    topRightP.innerHTML = '♠';
    bottomLeftP.innerHTML = '♠';
    innerDiv.classList.add('innerbox');
  }
  topLeftP.innerHTML = '<' + name + '>';
  bottomRightP.innerHTML = '</' + name + '>';
};

//selects a random card's integer and checks to make sure it is unique
Card.randomCard = function(){
  var cardInteger = Math.floor(Math.random() * (Card.all.length - 1));
  return Card.all.splice(cardInteger, 1);
};

//populates gives dealer and standin players cards and Player cards
Card.dealerFunction = function(){
  Card.cardsPickedThisHand = [];
  for (var i = 0; i < 7; i++){
    Player.playerObjectArray[i].handCards = [];
    Player.playerObjectArray[i].handCards.push(Card.randomCard());
    Player.playerObjectArray[i].handCards.push(Card.randomCard());
  }
  Player.playerObjectArray[Player.currentUser()].handCards = [];
  Player.playerObjectArray[Player.currentUser()].handCards.push(Card.randomCard());
  Player.playerObjectArray[Player.currentUser()].handCards.push(Card.randomCard());

  for (var j = 0; j < 7; i++){
    Card.printCard(eval('Player.computer' + j + 'Hand'), Player.playerObjectArray[j].handCards[1][0].suit , Player.playerObjectArray[j].handCards[1][0].name);
  }

  Card.printCard(playerHand, Player.playerObjectArray[Player.currentUser()].handCards[0][0].suit, Player.playerObjectArray[Player.currentUser()].handCards[0][0].name);
  Card.printCard(playerHand, Player.playerObjectArray[Player.currentUser()].handCards[1][0].suit, Player.playerObjectArray[Player.currentUser()].handCards[1][0].name);
};
//TODO: add event listener to a button for dealing

//Iterates on dealer and all standin players to play their hand by vegas dealer rules
Player.computerPlaysHand = function(){
  for(var i = 0; i < 7; i++){
    Player.handSum(i);
    while (Player.playerObjectArray[i].handValue < 17){
      Player.playerObjectArray[i].handCards.push(Card.randomCard());
      Card.printCard(eval('Player.computer' + i + 'Hand'), Player.playerObjectArray[i].handCards[Player.playerObjectArray[i].handCards.length - 1][0].suit, Player.playerObjectArray[i].handCards[Player.playerObjectArray[i].handCards.length - 1][0].name);
      Player.handSum(i);
    }
  }
};
//function that reEvaluates the hand's value
Player.handSum = function(i){
  Player.playerObjectArray[i].handValue = 0;
  // console.log('reset is Success');
  for(var j in Player.playerObjectArray[i].handCards){
    // console.log('sums handCards');
    Player.playerObjectArray[i].handValue += Player.playerObjectArray[i].handCards[j][0].value;
  }
};

Player.userGuideRules = function(){
  Player.handSum(Player.currentUser());
  if([2,3].includes(Player.playerObjectArray[0].handCards[0][0].value)){
    if(Player.playerObjectArray[Player.currentUser()].handValue < 13){
      // console.log('hit lower than 13');
    }else{
      // console.log('stay');
    }
  }
  if([4,5,6].includes(Player.playerObjectArray[0].handCards[0][0].value)){
    if(Player.playerObjectArray[Player.currentUser()].handValue < 12){
      // console.log('hit lower than 12');
    }else{
      // console.log('stay');
    }
  }
  if([7,8,9].includes(Player.playerObjectArray[0].handCards[0][0].value)){
    if(Player.playerObjectArray[Player.currentUser()].handValue < 17){
      // console.log('hit lower than 17');
    }else{
      // console.log('stay');
    }
  }
  if([10,11].includes(Player.playerObjectArray[0].handCards[0][0].value)){
    if(Player.playerObjectArray[Player.currentUser()].handValue < 17 ){
      // console.log('hit lower than 17, split if able');
    }else{
      // console.log('stay');
    }
  }
};

//occurs when player ends turn (stays, busts, gets blackjack). Others play then currentUser compares to dealer
Player.gameResolution = function(){
  // console.log('gameReslolutionInvoked');
  Player.toggleGameEventListenersOff();
  // console.log('EListeners off');
  Player.computerPlaysHand();
  // console.log('computerPlaysHandInvoked');
  Player.handSum(Player.currentUser());
  // console.log('players hand is ' + Player.playerObjectArray[Player.currentUser()].handValue);
  if (Player.playerObjectArray[Player.currentUser()].handValue > 21 || Player.playerObjectArray[0].handValue > Player.playerObjectArray[Player.currentUser()].handvalue){
    console.log('loss');
    Player.playerObjectArray[Player.currentUser()].gameOutcome.push('loss');
    Player.playerObjectArray[Player.currentUser()].losses++;
    Player.playerObjectArray[Player.currentUser()].gamesPlayed++;
  }else if(Player.playerObjectArray[0].handValue > 21){
    console.log('win');
    Player.playerObjectArray[Player.currentUser()].gameOutcome.push('win');
    Player.playerObjectArray[Player.currentUser()].wins++;
    Player.playerObjectArray[Player.currentUser()].gamesPlayed++;
  }else if(Player.playerObjectArray[Player.currentUser()].handValue <= 21 && Player.playerObjectArray[0].handValue < Player.playerObjectArray[Player.currentUser()].handValue){
    console.log('win');
    Player.playerObjectArray[Player.currentUser()].gameOutcome.push('win');
    Player.playerObjectArray[Player.currentUser()].wins++;
    Player.playerObjectArray[Player.currentUser()].gamesPlayed++;
  }else {
    console.log('tie');
    Player.playerObjectArray[Player.currentUser()].gameOutcome.push('tie');
    Player.playerObjectArray[Player.currentUser()].ties++;
    Player.playerObjectArray[Player.currentUser()].gamesPlayed++;
  }
  localStorage.playerObjectArray = JSON.stringify(Player.playerObjectArray);
};

Player.hitHandler = function(){
  console.log('hit');
  Player.playerObjectArray[Player.currentUser()].handCards.push(Card.randomCard());
  //takes the last card in the hand and writes it to the page
  Card.printCard(playerHand, Player.playerObjectArray[Player.currentUser()].handCards[Player.playerObjectArray[Player.currentUser()].handCards.length - 1][0].suit, Player.playerObjectArray[Player.currentUser()].handCards[Player.playerObjectArray[Player.currentUser()].handCards.length - 1][0].name);
  // console.log('dealer hand is ' + Player.playerObjectArray[0].handValue);
  Player.handSum(Player.currentUser());
  // console.log(Player.playerObjectArray[Player.currentUser()]);
  if (Player.playerObjectArray[Player.currentUser()].handValue >= 21){
    // console.log('player hand busts');
    Player.gameResolution();
  }

};

Player.stayHandler = function(){
  console.log('stay');
  Player.gameResolution();
};

Player.splitHandler = function(){
  console.log('split');
  alert('Please upgrade your Flash player!');
};

//deals out cards and turns on hit/stay
Player.dealHandler = function(){
  Card.cardCreator();
  playerHand.innerHTML = null;
  for (var i in staticPlayerNameArray){
    eval('Player.computer' + i + 'Hand').innerHTML = null;
  }
  console.log('deal');
  Player.toggleGameEventListenersOn();
  Card.dealerFunction();
};

dealButton.addEventListener('click', Player.dealHandler);

Player.toggleGameEventListenersOn = function(){
  hitButton.addEventListener('click', Player.hitHandler);
  stayButton.addEventListener('click', Player.stayHandler);
  splitButton.addEventListener('click', Player.splitHandler);
};
Player.toggleGameEventListenersOff = function(){
  hitButton.removeEventListener('click', Player.hitHandler);
  stayButton.removeEventListener('click', Player.stayHandler);
  splitButton.removeEventListener('click', Player.splitHandler);
};
<|endoftext|>


<commit_before>'use strict'
document.getElementById('right-click-menu').style.top = -(document.getElementById('right-click-menu').clientHeight) + 'px'; // hide menu by defult
var active = undefined, // does save the index number of the app taht is active
    windowCount = 0; // number of open windows for cicked app
var apps = [];
apps.length = document.getElementsByClassName('app').length; // set lenght of array

function getOffset(el) {
    el = el.getBoundingClientRect();
    return {
        left: el.left + window.scrollX,
        top: el.top + window.scrollY
    }
}

function getStyleRuleValue(style, selector) {
    for (var i = 0; i < document.styleSheets.length; i++) {
        var mysheet = document.styleSheets[i];
        var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
        if (myrules === undefined || myrules === null || myrules.length <= 0) {
            continue;
        }
        for (var j = 0; j < myrules.length; j++) {
            if (myrules[j].selectorText && myrules[j].selectorText.toLowerCase() === selector.toLowerCase()) {
                return myrules[j].style[style];
            }
        }
    }
};

/** Module to controloh my preview
 */
var preview = (function() {
    var pub = {};

    function _centerWindows(buttons, previewTag) {
        setTimeout(function() {
            var attValue = buttons[0].getAttribute("breakpoint");
            var num;

            if (attValue > 6) {
                num = getStyleRuleValue("left", "#main #preview .window");
            } else {
                num = getStyleRuleValue("left", "#main #preview .window[breakpoint=\"" + attValue + "\"]");
            }
            wrapper.style.left = -Number(num.slice(0, num.length - 2)) + 20 + "px";

            setTimeout(function() {
                previewTag.style.transition = '140ms';
                document.getElementById('preview').setAttribute("boolean", "true");
            }, 10);
        }, 100);
    }

    function _checkKey(e) {
        var lel; // helper
        e = e || window.event;

        if (e.key == 'ArrowUp') {
            lel = 'ArrowLeft'
        } else if (e.key == 'ArrowDown') {
            lel = 'ArrowRight'
        } else if (e.key == 'ArrowLeft') {
            lel = 'ArrowLeft';
        } else if (e.key == 'ArrowRight') {
            lel = 'ArrowRight';
        }
        preview.scroll(lel);
    }

    /** Initializes preview.
     * Remove the wrapper with all divs(windows) in it
     * and create new one. Do for loop and create as much windows
     * as specified in the windowCount property(or the windowCount attribute).
     * Right now there is needed: window wrapper with header wrapper with
     * textnode inside.
     */
    function _initialize(pos) {
        var previewTag = document.getElementById('preview');
        var appClass = document.getElementsByClassName('app')[pos],
            num = (getOffset(appClass).left) + (appClass.offsetWidth / 2);
        var btn,
            header,
            text,
            wrapper = document.getElementById('wrapper'), // TODO: Make this more specific
            buttons;

        previewTag.style.transition = '0ms';
        if ((num - (previewTag.offsetWidth / 2)) > 0) {
            previewTag.style.left = (num - (previewTag.offsetWidth / 2)) + 'px';
        } else { // prevent preview to go outside the (left side of the) screen
            previewTag.style.left = 0;
        }

        if (wrapper != null) {
            previewTag.removeChild(wrapper); // Remove old wrapper(and all DIVs inside)
        }
        wrapper = document.createElement('DIV');
        wrapper.setAttribute("id", "wrapper");
        previewTag.appendChild(wrapper);
        buttons = wrapper.getElementsByClassName('window');
        for (var i = 0; i < apps[pos].windowCount; i++) {
            btn = document.createElement('DIV');
            header = document.createElement('DIV')
            text = document.createTextNode('Make me active!');

            header.appendChild(text);
            header.setAttribute("class", "header");
            btn.appendChild(header);
            btn.setAttribute("class", "window");
            btn.setAttribute("onclick", "");

            wrapper.appendChild(btn);
        }
        setTimeout(function() {
            for (var i = 0; i < buttons.length; i++) {
                buttons[i].setAttribute("breakpoint", ((buttons.length + 1) - i)); // +1 to avoid breakpoint 1
            }
        }, 22);

        _centerWindows(buttons, previewTag)
        document.onkeydown = _checkKey;
    }

    pub.visible = false;
    pub.position = undefined;
    pub.lastPosition = undefined;
    pub.hide = function() {
        if (preview.visible) {
            preview.visible = 0; // set boolean to "not open" TODO: Use boolean strings ('true', 'false')
            preview.position = undefined; // set preview position to undefined
            document.getElementById('preview').setAttribute("boolean", "false");
            document.onkeydown = "";
        } else {
            console.log("ERR: Conflict: preview already hidden.");
        }
    };
    pub.show = function(pos) {
        if (preview.visible == 0) {
            preview.visible = 1;
            preview.lastPosition = preview.position;
            preview.position = pos;
            _initialize(pos);
        } else {
            console.log("ERR: Conflict: preview already shown.");
        }
    };
    pub.scroll = function(lel) {
        var temp; // stores the new breakpoint value
        var buttons = document.getElementsByClassName('window');
        var help = buttons.length,
            num,
            attValue = buttons[0].getAttribute("breakpoint");
        var previewId = document.getElementById('preview');

        if (lel == 'ArrowLeft' && (Number(buttons[buttons.length - 1].getAttribute("breakpoint")) + 1) < 5) {
            for (var i = 0; i < buttons.length; i++) { // get the ones that needs to get scrolled
                if (buttons[i].getAttribute("breakpoint") == 1) {
                    help = i + 1;
                    break;
                }
            }
            for (var i = 0; i < help; i++) { // actually scroll them
                temp = Number(buttons[i].getAttribute("breakpoint")) + 1;
                buttons[i].setAttribute("breakpoint", temp);
                //_centerWindows(buttons, previewId);
                if (attValue > 6) {
                    num = getStyleRuleValue("left", "#main #preview .window");
                } else {
                    num = getStyleRuleValue("left", "#main #preview .window[breakpoint=\"" + attValue + "\"]");
                }
                wrapper.style.left = -Number(num.slice(0, num.length - 2)) + 20 + "px";
            }

        } else if (lel == 'ArrowRight' && (Number(buttons[0].getAttribute("breakpoint")) - 1) > 3) {
            for (var i = 0; i < buttons.length; i++) { // get the ones that needs to get scrolled
                if (buttons[i].getAttribute("breakpoint") == 1) {
                    help = i;
                    break;
                }
            }
            for (var i = 0; i < help; i++) { // actually scroll them
                temp = Number(buttons[i].getAttribute("breakpoint")) - 1;
                buttons[i].setAttribute("breakpoint", temp);
                //_centerWindows(buttons, previewId);
                if (attValue > 6) {
                    num = getStyleRuleValue("left", "#main #preview .window");
                } else {
                    num = getStyleRuleValue("left", "#main #preview .window[breakpoint=\"" + attValue + "\"]");
                }
                wrapper.style.left = -Number(num.slice(0, num.length - 2)) + 20 + "px";
            }
        }

        return false;
    }

    return pub;
})();

/** Module to control menu (right-click-menu)
 */
var menu = (function() {
    var pub = {};

    function _initialize(pos) {
        var menuId = document.getElementById('right-click-menu');
        var appClass = document.getElementsByClassName('app')[pos];
        var num = (getOffset(appClass).left) + (appClass.offsetWidth / 2);

        menuId.style.transition = "0ms";
        if ((num - (menuId.offsetWidth / 2)) > 0) {
            menuId.style.left = num - (menuId.offsetWidth / 2) + "px";
        } else {
            menuId.style.left = 0;
        }
        num = apps[pos].windowCount;
        if (num < 1) {
            document.getElementsByClassName('entry')[1].setAttribute("clickable", "false");
            document.getElementsByClassName('entry')[1].setAttribute("onclick", "");
        } else {
            document.getElementsByClassName('entry')[1].setAttribute("clickable", 'true');
            document.getElementsByClassName('entry')[1].setAttribute("onclick", "apps[menu.position].closeAllWindows();");
        }

        setTimeout(function() {
            menuId.style.transition = "140ms";
            document.getElementById('right-click-menu').setAttribute("boolean", "true");
            document.getElementById('right-click-menu').style.top = 0;
        }, 10);
    }
    pub.visible = 0;
    pub.position = undefined;
    pub.lastPosition = undefined;
    pub.hide = function() {
        if (menu.visible) {
            document.getElementById('right-click-menu').setAttribute("boolean", "false");
            document.getElementById('right-click-menu').style.top = -(document.getElementById('right-click-menu').clientHeight) + 'px';
            menu.visible = 0;
            menu.lastPosition = menu.position;
            menu.position = undefined;
        } else {
            console.log("ERR: Conflict: Menu already hidden.");
        }
        return false;
    };
    pub.show = function(pos) {
        if (menu.visible == 0) {
            _initialize(pos);
            menu.visible = 1;
            menu.lastPosition = menu.position;
            menu.position = pos;
        } else {
            console.log("ERR: Conflict: Menu already shown.");
        }
        return false;
    };

    return pub;
})();
var app = {};

/**Create object with propertys and methods for every index of "apps" array.
 *That is so every app (visible on the taskbar) has its own propertys and methods
 */
for (var i = 0; i < apps.length; i++) {

    apps[i] = (function() {
        var pub = {};
        var h = i;
        var elem = document.getElementsByClassName('app')[h];

        pub.active = false;
        pub.windowCount = elem.getAttribute('windowCount');
        pub.menu = false; // if is opened on that app
        pub.preview = false; // if preview is opened on that app
        pub.pinned = true; // if app is pinned
        pub.closeAllWindows = function() {
            elem.setAttribute("windowCount", "0"); // reset windowCount
            pub.windowCount = 0;

            if (pub.active) { // if app was active
                console.log("active?: " + pub.active);
                active = undefined; // no active app anymore
                pub.active = true;
                console.log(pub.active);
                elem.setAttribute("active", "false"); // make app inactive
            }
            menu.hide();
            console.log("winCount: " + pub.windowCount);
            console.log("active: " + pub.active);
        };
        pub.addWindow = function() {
            pub.windowCount++;

            elem.setAttribute("windowCount", pub.windowCount);
            elem.setAttribute("active", "true");

            if ((active != h) && (active != undefined)) { // When there was already an active app
                document.getElementsByClassName('app')[active].setAttribute("active", "false"); // old active
            }
            active = h;
            pub.active = true;

            if (preview.visible)
                preview.hide();

            if (menu.visible)
                menu.hide();

        };
        pub.closeWindow = function() {};
        pub.pinToPanel = function() {};

        return pub;
    })();
}

/** Gets triggered on left-click on an app.
 * Does all the fancy logic behind the preview behaviour
 */
function previewAction(clicked) {
    var elem = document.getElementsByClassName('app');
    windowCount = elem[clicked].getAttribute("windowCount");

    if (windowCount == 0) { // If there is no instance already open
        apps[clicked].addWindow();

    } else if (windowCount == 1) {
        elem[clicked].setAttribute("active", "true");
        if (active !== undefined) { // When there was already an (other) active app
            elem[active].setAttribute("active", "false");
        }
        if (active == clicked) { // if clicked app is active one
            active = undefined; // set clicked app to inactive
        } else {
            active = clicked;
            apps[clicked].active = true;
        }
        if (preview.visible) {
            preview.hide();
        }

    } else if (windowCount > 1) {
        if ((preview.position != clicked) && preview.visible) {
            preview.hide(); // Do it twice for reopening with updated content
            setTimeout(function() {
                preview.show(clicked);
            }, 300);
        } else if (preview.visible) { // TODO: Use the preview property from apps module
            preview.hide();
        } else {
            preview.show(clicked);
        }
        if (menu.visible) {
            menu.hide();
        }
    }
}

/** Gets triggered on right-click on an app.
 * Does all the fancy logic behind the right-click-menu behaviour
 */
function menuAction(clicked) {
    if (menu.visible && (menu.position != clicked)) { // looks if menu from other app is open
        menu.hide(); // closes menu from other app
        setTimeout(function() {
            menu.show(clicked);
        }, 300);
    } else if (menu.visible) { // when menu open from clicked app TODO: Use the menu property from apps module
        menu.hide(); // opens/shriks menu
    } else {
        menu.show(clicked);
    }

    if (preview.visible) {
        preview.hide();
    }
    return false;
}

/** Rezises the panel according to the cssRules
 */
function panelSize(size) {
    var rules = document.styleSheets[0]['cssRules'];
    //var selector = rule[].selectorText;
    //var value = rule[].value;
    /** Make object that holds all selectors that should be modified and it holds also what properties should change and with what values
     * Example: '#panel': {height: 2}
     * In this case #panel is the selecor and holds an object that contains height with value 2.
     * This means that the property that should change in the CSS selector #panel is height.
     * The value, in this case 2, references at the "dimensions" object.
     */
    /*var dimensions = {menuButtonSize: 9, menuButtonMargin: 2, appSize: 13, iconSize: 7, margin: 3, marginSmall: 1, indicatorWidth: 6};
    var ruleQuery = {'#panel': {height: 2}, '#panel #menu-button': {height: 0, width: 0, margin: 1}, '#panel #icon-task-list .app': {height: 2, width: 2}, '#panel #icon-task-list .app .indicator': {width: 6, height: 5, margin: 5},
                    '#panel #icon-task-list .app .indicator .blob': {width: 5, height: 5, borderRadius: null}, '#panel #icon-task-list .app .indicator .blob:nth-child(2)': {marginLeft: 5}, '#panel #icon-task-list .app[windowCount="1"] .indicator',
                    '#panel #icon-task-list .app[windowCount="2"] .indicator', '#panel #icon-task-list .app[active="true"] .indicator .blob:nth-child(1)',
                    '#panel #icon-task-list .app[active="true"] .indicator', '#panel #icon-task-list .app .icon', '#panel #icon-task-list .app .icon img'};*/
    // rules[2].style.height = 13 * size + "px";
    document.getElementById('panel').setAttribute("size", size);
}
var background = (function() {
    var pub = {};

    pub.change = function(value) {
        document.getElementsByTagName('body')[0].style.backgroundImage = "url(../SolusDesignConcept/" + value + ")";
    }

    return pub;
})();
<commit_msg>Add some panel documentation<commit_after>'use strict'
document.getElementById('right-click-menu').style.top = -(document.getElementById('right-click-menu').clientHeight) + 'px'; // hide menu by defult
var active = undefined, // does save the index number of the app taht is active
    windowCount = 0; // number of open windows for cicked app
var apps = [];
apps.length = document.getElementsByClassName('app').length; // set lenght of array

function getOffset(el) {
    el = el.getBoundingClientRect();
    return {
        left: el.left + window.scrollX,
        top: el.top + window.scrollY
    }
}

function getStyleRuleValue(style, selector) {
    for (var i = 0; i < document.styleSheets.length; i++) {
        var mysheet = document.styleSheets[i];
        var myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
        if (myrules === undefined || myrules === null || myrules.length <= 0) {
            continue;
        }
        for (var j = 0; j < myrules.length; j++) {
            if (myrules[j].selectorText && myrules[j].selectorText.toLowerCase() === selector.toLowerCase()) {
                return myrules[j].style[style];
            }
        }
    }
};

/** Module to controloh my preview
 */
var preview = (function() {
    var pub = {};

    function _centerWindows(buttons, previewTag) {
        setTimeout(function() {
            var attValue = buttons[0].getAttribute("breakpoint");
            var num;

            if (attValue > 6) {
                num = getStyleRuleValue("left", "#main #preview .window");
            } else {
                num = getStyleRuleValue("left", "#main #preview .window[breakpoint=\"" + attValue + "\"]");
            }
            wrapper.style.left = -Number(num.slice(0, num.length - 2)) + 20 + "px";

            setTimeout(function() {
                previewTag.style.transition = '140ms';
                document.getElementById('preview').setAttribute("boolean", "true");
            }, 10);
        }, 100);
    }

    function _checkKey(e) {
        var lel; // helper
        e = e || window.event;

        if (e.key == 'ArrowUp') {
            lel = 'ArrowLeft'
        } else if (e.key == 'ArrowDown') {
            lel = 'ArrowRight'
        } else if (e.key == 'ArrowLeft') {
            lel = 'ArrowLeft';
        } else if (e.key == 'ArrowRight') {
            lel = 'ArrowRight';
        }
        preview.scroll(lel);
    }

    /** Initializes preview.
     * Remove the wrapper with all divs(windows) in it
     * and create new one. Do for loop and create as much windows
     * as specified in the windowCount property(or the windowCount attribute).
     * Right now there is needed: window wrapper with header wrapper with
     * textnode inside.
     */
    function _initialize(pos) {
        var previewTag = document.getElementById('preview');
        var appClass = document.getElementsByClassName('app')[pos],
            num = (getOffset(appClass).left) + (appClass.offsetWidth / 2);
        var btn,
            header,
            text,
            wrapper = document.getElementById('wrapper'), // TODO: Make this more specific
            buttons;

        previewTag.style.transition = '0ms';
        if ((num - (previewTag.offsetWidth / 2)) > 0) {
            previewTag.style.left = (num - (previewTag.offsetWidth / 2)) + 'px';
        } else { // prevent preview to go outside the (left side of the) screen
            previewTag.style.left = 0;
        }

        if (wrapper != null) {
            previewTag.removeChild(wrapper); // Remove old wrapper(and all DIVs inside)
        }
        wrapper = document.createElement('DIV');
        wrapper.setAttribute("id", "wrapper");
        previewTag.appendChild(wrapper);
        buttons = wrapper.getElementsByClassName('window');
        for (var i = 0; i < apps[pos].windowCount; i++) {
            btn = document.createElement('DIV');
            header = document.createElement('DIV')
            text = document.createTextNode('Make me active!');

            header.appendChild(text);
            header.setAttribute("class", "header");
            btn.appendChild(header);
            btn.setAttribute("class", "window");
            btn.setAttribute("onclick", "");

            wrapper.appendChild(btn);
        }
        setTimeout(function() {
            for (var i = 0; i < buttons.length; i++) {
                buttons[i].setAttribute("breakpoint", ((buttons.length + 1) - i)); // +1 to avoid breakpoint 1
            }
        }, 22);

        _centerWindows(buttons, previewTag)
        document.onkeydown = _checkKey;
    }

    pub.visible = false;
    pub.position = undefined;
    pub.lastPosition = undefined;
    pub.hide = function() {
        if (preview.visible) {
            preview.visible = 0; // set boolean to "not open" TODO: Use boolean strings ('true', 'false')
            preview.position = undefined; // set preview position to undefined
            document.getElementById('preview').setAttribute("boolean", "false");
            document.onkeydown = "";
        } else {
            console.log("ERR: Conflict: preview already hidden.");
        }
    };
    pub.show = function(pos) {
        if (preview.visible == 0) {
            preview.visible = 1;
            preview.lastPosition = preview.position;
            preview.position = pos;
            _initialize(pos);
        } else {
            console.log("ERR: Conflict: preview already shown.");
        }
    };
    pub.scroll = function(lel) {
        var temp; // stores the new breakpoint value
        var buttons = document.getElementsByClassName('window');
        var help = buttons.length,
            num,
            attValue = buttons[0].getAttribute("breakpoint");
        var previewId = document.getElementById('preview');

        if (lel == 'ArrowLeft' && (Number(buttons[buttons.length - 1].getAttribute("breakpoint")) + 1) < 5) {
            for (var i = 0; i < buttons.length; i++) { // get the ones that needs to get scrolled
                if (buttons[i].getAttribute("breakpoint") == 1) {
                    help = i + 1;
                    break;
                }
            }
            for (var i = 0; i < help; i++) { // actually scroll them
                temp = Number(buttons[i].getAttribute("breakpoint")) + 1;
                buttons[i].setAttribute("breakpoint", temp);
                //_centerWindows(buttons, previewId);
                if (attValue > 6) {
                    num = getStyleRuleValue("left", "#main #preview .window");
                } else {
                    num = getStyleRuleValue("left", "#main #preview .window[breakpoint=\"" + attValue + "\"]");
                }
                wrapper.style.left = -Number(num.slice(0, num.length - 2)) + 20 + "px";
            }

        } else if (lel == 'ArrowRight' && (Number(buttons[0].getAttribute("breakpoint")) - 1) > 3) {
            for (var i = 0; i < buttons.length; i++) { // get the ones that needs to get scrolled
                if (buttons[i].getAttribute("breakpoint") == 1) {
                    help = i;
                    break;
                }
            }
            for (var i = 0; i < help; i++) { // actually scroll them
                temp = Number(buttons[i].getAttribute("breakpoint")) - 1;
                buttons[i].setAttribute("breakpoint", temp);
                //_centerWindows(buttons, previewId);
                if (attValue > 6) {
                    num = getStyleRuleValue("left", "#main #preview .window");
                } else {
                    num = getStyleRuleValue("left", "#main #preview .window[breakpoint=\"" + attValue + "\"]");
                }
                wrapper.style.left = -Number(num.slice(0, num.length - 2)) + 20 + "px";
            }
        }

        return false;
    }

    return pub;
})();

/** Module to control menu (right-click-menu)
 */
var menu = (function() {
    var pub = {};

    function _initialize(pos) {
        var menuId = document.getElementById('right-click-menu');
        var appClass = document.getElementsByClassName('app')[pos];
        var num = (getOffset(appClass).left) + (appClass.offsetWidth / 2);

        menuId.style.transition = "0ms";
        if ((num - (menuId.offsetWidth / 2)) > 0) {
            menuId.style.left = num - (menuId.offsetWidth / 2) + "px";
        } else {
            menuId.style.left = 0;
        }
        num = apps[pos].windowCount;
        if (num < 1) {
            document.getElementsByClassName('entry')[1].setAttribute("clickable", "false");
            document.getElementsByClassName('entry')[1].setAttribute("onclick", "");
        } else {
            document.getElementsByClassName('entry')[1].setAttribute("clickable", 'true');
            document.getElementsByClassName('entry')[1].setAttribute("onclick", "apps[menu.position].closeAllWindows();");
        }

        setTimeout(function() {
            menuId.style.transition = "140ms";
            document.getElementById('right-click-menu').setAttribute("boolean", "true");
            document.getElementById('right-click-menu').style.top = 0;
        }, 10);
    }
    pub.visible = 0;
    pub.position = undefined;
    pub.lastPosition = undefined;
    pub.hide = function() {
        if (menu.visible) {
            document.getElementById('right-click-menu').setAttribute("boolean", "false");
            document.getElementById('right-click-menu').style.top = -(document.getElementById('right-click-menu').clientHeight) + 'px';
            menu.visible = 0;
            menu.lastPosition = menu.position;
            menu.position = undefined;
        } else {
            console.log("ERR: Conflict: Menu already hidden.");
        }
        return false;
    };
    pub.show = function(pos) {
        if (menu.visible == 0) {
            _initialize(pos);
            menu.visible = 1;
            menu.lastPosition = menu.position;
            menu.position = pos;
        } else {
            console.log("ERR: Conflict: Menu already shown.");
        }
        return false;
    };

    return pub;
})();
var app = {};

/**Create object with propertys and methods for every index of "apps" array.
 *That is so every app (visible on the taskbar) has its own propertys and methods
 */
for (var i = 0; i < apps.length; i++) {

    apps[i] = (function() {
        var pub = {};
        var h = i;
        var elem = document.getElementsByClassName('app')[h];

        pub.active = false;
        pub.windowCount = elem.getAttribute('windowCount');
        pub.menu = false; // if is opened on that app
        pub.preview = false; // if preview is opened on that app
        pub.pinned = true; // if app is pinned
        pub.closeAllWindows = function() {
            elem.setAttribute("windowCount", "0"); // reset windowCount
            pub.windowCount = 0;

            if (pub.active) { // if app was active
                console.log("active?: " + pub.active);
                active = undefined; // no active app anymore
                pub.active = true;
                console.log(pub.active);
                elem.setAttribute("active", "false"); // make app inactive
            }
            menu.hide();
            console.log("winCount: " + pub.windowCount);
            console.log("active: " + pub.active);
        };
        pub.addWindow = function() {
            pub.windowCount++;

            elem.setAttribute("windowCount", pub.windowCount);
            elem.setAttribute("active", "true");

            if ((active != h) && (active != undefined)) { // When there was already an active app
                document.getElementsByClassName('app')[active].setAttribute("active", "false"); // old active
            }
            active = h;
            pub.active = true;

            if (preview.visible)
                preview.hide();

            if (menu.visible)
                menu.hide();

        };
        pub.closeWindow = function() {};
        pub.pinToPanel = function() {};

        return pub;
    })();
}

/** Gets triggered on left-click on an app.
 * Does all the fancy logic behind the preview behaviour
 */
function previewAction(clicked) {
    var elem = document.getElementsByClassName('app');
    windowCount = elem[clicked].getAttribute("windowCount");

    if (windowCount == 0) { // If there is no instance already open
        apps[clicked].addWindow();

    } else if (windowCount == 1) {
        elem[clicked].setAttribute("active", "true");
        if (active !== undefined) { // When there was already an (other) active app
            elem[active].setAttribute("active", "false");
        }
        if (active == clicked) { // if clicked app is active one
            active = undefined; // set clicked app to inactive
        } else {
            active = clicked;
            apps[clicked].active = true;
        }
        if (preview.visible) {
            preview.hide();
        }

    } else if (windowCount > 1) {
        if ((preview.position != clicked) && preview.visible) {
            preview.hide(); // Do it twice for reopening with updated content
            setTimeout(function() {
                preview.show(clicked);
            }, 300);
        } else if (preview.visible) { // TODO: Use the preview property from apps module
            preview.hide();
        } else {
            preview.show(clicked);
        }
        if (menu.visible) {
            menu.hide();
        }
    }
}

/** Gets triggered on right-click on an app.
 * Does all the fancy logic behind the right-click-menu behaviour
 */
function menuAction(clicked) {
    if (menu.visible && (menu.position != clicked)) { // looks if menu from other app is open
        menu.hide(); // closes menu from other app
        setTimeout(function() {
            menu.show(clicked);
        }, 300);
    } else if (menu.visible) { // when menu open from clicked app TODO: Use the menu property from apps module
        menu.hide(); // opens/shriks menu
    } else {
        menu.show(clicked);
    }

    if (preview.visible) {
        preview.hide();
    }
    return false;
}

/** Rezises the panel according to the cssRules
 */
function panelSize(size) {
    //var rules = document.styleSheets[0]['cssRules'];
    //var selector = rule[].selectorText;
    //var value = rule[].value;
    /** Make object that holds all selectors that should be modified and it holds also what properties should change and with what values
     * Example: '#panel': {height: 2}
     * In this case #panel is the selecor and holds an object that contains height with value 2.
     * This means that the property that should change in the CSS selector #panel is height.
     * The value, in this case 2, references at the "dimensions" object.
     */
    /*var dimensions = {menuButtonSize: 9, menuButtonMargin: 2, appSize: 13, iconSize: 7, margin: 3, marginSmall: 1, indicatorWidth: 6};
    var ruleQuery = {'#panel': {height: 2}, '#panel #menu-button': {height: 0, width: 0, margin: 1}, '#panel #icon-task-list .app': {height: 2, width: 2}, '#panel #icon-task-list .app .indicator': {width: 6, height: 5, margin: 5},
                    '#panel #icon-task-list .app .indicator .blob': {width: 5, height: 5, borderRadius: null}, '#panel #icon-task-list .app .indicator .blob:nth-child(2)': {marginLeft: 5}, '#panel #icon-task-list .app[windowCount="1"] .indicator',
                    '#panel #icon-task-list .app[windowCount="2"] .indicator', '#panel #icon-task-list .app[active="true"] .indicator .blob:nth-child(1)',
                    '#panel #icon-task-list .app[active="true"] .indicator', '#panel #icon-task-list .app .icon', '#panel #icon-task-list .app .icon img'};*/
    // rules[2].style.height = 13 * size + "px";
    document.getElementById('panel').setAttribute("size", size);
}
var background = (function() {
    var pub = {};

    pub.change = function(value) {
        document.getElementsByTagName('body')[0].style.backgroundImage = "url(../SolusDesignConcept/" + value + ")";
    }

    return pub;
})();
<|endoftext|>