<commit_before>var canvas;
var ctx;

var alpha = 1.0 / 3.0;

var colors = [
	new Color(255, 0, 0, alpha),
	new Color(0, 255, 0, alpha),
	new Color(0, 0, 255, alpha),
];

var keys = {
	'a': 65,
	'd': 68,
	's': 83,

	'up': 38,
	'down': 40,
}

var player = {x: 50, y: 50, width: 30, height: 30, color: 0};
player.draw = function() {
	ctx.beginPath();
	ctx.fillStyle = colors[this.color % colors.length].toString();
	ctx.rect(this.x, this.y, this.width, this.height);
	ctx.fill();
}

function init() {
	canvas = document.getElementById("game");
	ctx = canvas.getContext("2d");

	registerListeners();

	player.draw();
}

function registerListeners() {
	document.addEventListener('keydown', handleKeyDown);
}

function handleKeyDown(e) {
	console.log(e);
	document.getElementById("keycode").innerHTML = e.keyCode;

	switch (e.keyCode) {
		case keys.up:
			player.color++;
			e.preventDefault();
			break;
		case keys.down:
			player.color--;
			e.preventDefault();
			break;
	}
}

function drawTestShapes() {
	// draw some test shapes
	ctx.fillStyle = "rgba(255, 0, 0, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(40, 40, 60, 30);
	ctx.fill();

	ctx.fillStyle = "rgba(0, 255, 0, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(60, 40, 60, 30);
	ctx.fill();

	ctx.fillStyle = "rgba(0, 0, 255, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(50, 50, 60, 30);
	ctx.fill();
}

function Color(r, g, b, a) {
	this.r = r;
	this.g = g;
	this.b = b;
	this.a = a;
}

Color.prototype.toString = function() {
	return 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + this.a + ')';
}
<commit_msg>Render multiple frames - yay, color shifting!<commit_after>var canvas;
var ctx;
var gameLoop;

var alpha = 1.0 / 3.0;

var colors = [
	new Color(255, 0, 0, alpha),
	new Color(0, 255, 0, alpha),
	new Color(0, 0, 255, alpha),
];

var keys = {
	'a': 65,
	'd': 68,
	's': 83,

	'up': 38,
	'down': 40,
}

var player = {x: 50, y: 50, width: 30, height: 30, color: 0};
player.draw = function() {
	ctx.beginPath();
	ctx.fillStyle = colors[this.color % colors.length].toString();
	ctx.rect(this.x, this.y, this.width, this.height);
	ctx.fill();
}

function init() {
	canvas = document.getElementById("game");
	ctx = canvas.getContext("2d");

	registerListeners();

	gameLoop = setInterval(runGame, 25);
}

function runGame() {
	player.draw();
}

function registerListeners() {
	document.addEventListener('keydown', handleKeyDown);
}

function handleKeyDown(e) {
	console.log(e);
	document.getElementById("keycode").innerHTML = e.keyCode;

	switch (e.keyCode) {
		case keys.up:
			player.color++;
			e.preventDefault();
			break;
		case keys.down:
			player.color--;
			e.preventDefault();
			break;
	}
}

function drawTestShapes() {
	// draw some test shapes
	ctx.fillStyle = "rgba(255, 0, 0, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(40, 40, 60, 30);
	ctx.fill();

	ctx.fillStyle = "rgba(0, 255, 0, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(60, 40, 60, 30);
	ctx.fill();

	ctx.fillStyle = "rgba(0, 0, 255, " + alpha + ")";
	ctx.beginPath()
	ctx.rect(50, 50, 60, 30);
	ctx.fill();
}

function Color(r, g, b, a) {
	this.r = r;
	this.g = g;
	this.b = b;
	this.a = a;
}

Color.prototype.toString = function() {
	return 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + this.a + ')';
}
<|endoftext|>


<commit_before>// Document ready
$(function() {

  // initialize Parse
  Parse.initialize("ESlRgOz3V1xyLJOsfIHG93enDoVYZZGhNxJe3SXk", "cp2EJqkQMu1Dbv9htMoZ7caQbiqe5AIkYKpRGzW6");

  // scroll the window back to the top
  // $('body').scrollTop(0);

  // pick a random background
  bgs = ['yay', 'sleep', 'hallway', 'chrysler', 'ceremony', 'breakout', 'big_house', 'big_house_2'];
  img = bgs[Math.floor(Math.random() * bgs.length)]
  $('body').css('background-image', 'url(/img/photos/' + img +'.jpg)')

  // set the upload trigger for a keypress
  $("#email-input").keypress(function(e) {
    if (e.keyCode == 13) {
      submitEmail();
      e.preventDefault();
    }
  });

  // set the upload trigger on the button
  $("#email-button").on('click', submitEmail);

  // Reset the logo for drawing
  $('.logo-animated path').each(function() {
    resetPathDrawing(this);
  });

  // Detect if the current browser is Firefox, and if it is,
  // use the much less cool version of this animation which
  // looks exactly the same.
  // In case you're curious: we had to make two methods to
  // scale the dots because Safari (and probably others)
  // don't let you set the radius (claiming it is read-only).
  if (typeof InstallTrigger !== 'undefined') {
    $('.logo-animated circle').each(function() {
      var t = $(this);
      t.attr('len', t.attr('r'));
      t.attr('r', '0');
      t.attr('class', '');
    });
  }

  // The path has been reset, so show the div
  $('#logo-wrapper').removeClass('invisible');

  // Drag the elements of the logo in 300ms from load
  window.setTimeout(function() {
    $('.logo-animated circle').attr('class', 'grow-animated');
    // this fixes the circles on firefox
    if (typeof InstallTrigger !== 'undefined') {
      $('.logo-animated circle').each(function() {
        var t = $(this);
        TweenMax.set(t, 1, {scale: 1, transformOrigin: "50% 50% 0"});
        TweenMax.to(t, 1, { attr:{ r: t.attr('len') } });
      });
    }
  }, 300);

  // Then, 100ms later, start drawing the lines
  window.setTimeout(function() {
    $('.logo-animated path').each(function() {
      simulatePathDrawing(this, 4.4);
    });
    // The border needs to be drawn more quickly
    simulatePathDrawing($('#logo-outline-path')[0], 3.0);
  }, 400);

  // enable smooth scrolling to anchors
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - $('#main-nav').height()
        }, 400);
        return false;
      }
    }
  });

  // affix the navbar, and
  // fix the width when resized
  $(window).resize(fixNavWidth);
  fixNavWidth();
});

function fixNavWidth() {
  $('nav').affix({
    offset: {
      top: $('nav').offset().top
    }
  });
  $('section#faq').css('margin-top', $('#main-nav').height() + "px")
  $('#main-nav').width($('#main-container').outerWidth());
}

function validateEmail(email) {
  // jk I typed it out
  var re = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
  return re.test(email);
  // ...not
}

function daysBetween(date1, date2) {
  var oneDay = 24*60*60*1000;
  console.log(date1.getTime());
  console.log(date2.getTime());
  return Math.round(Math.abs((date1.getTime() - date2.getTime())/(oneDay)));
}

// Reset the drawing before starting
function resetPathDrawing(path) {
  // we need to hardcode the lengths because of Firefox
  length = $(path).attr('length');
  // Clear any previous transition
  path.style.transition = path.style.WebkitTransition = path.style.MozTransition =
  'none';
  // Set up the starting positions
  path.style.strokeDasharray = length + ' ' + length;
  path.style.strokeDashoffset = length;
  return length;
};

// For drawing the MHacks logo
function simulatePathDrawing(path, duration) {
  // grab the original values
  strokeDashoffset = path.style.getPropertyValue('stroke-dash-offset');
  strokeWidth = path.style.getPropertyValue('stroke-width');
  fill = path.style.getPropertyValue('fill');

  // do the stuff
  var length = resetPathDrawing(path);
  path.getBoundingClientRect();
  // Define our transition
  path.style.transition = path.style.WebkitTransition = path.style.MozTransition =
  'all ' + duration + 's ease-in';
  // Go!
  path.style.strokeDashoffset = strokeDashoffset;
  path.style.strokeWidth = strokeWidth;
  path.style.fill = fill;
};

function submitEmail() {
  var email = $("#email-input").val();
  if (validateEmail(email)) {
    swapForm(false);
    $("#upload-progress h2").text("Yeah, you're ready.");
    $("#upload-progress").removeClass('faded');
    var EmailDrop = Parse.Object.extend("EmailDrop");
    var obj = new EmailDrop();
    obj.set("email", email);
    obj.save(null, {
      success: function(obj) {
        // nuthin'
      },
      error: function(obj) {
        window.alert("I don't know what happened, but you should try that again.");
      }
    });
  }
  else if (email.length != 0) {
    swapForm(true);
    $("#upload-progress h2").text("I didn't Google that regex for nothing.");
    $("#upload-progress").removeClass('faded');
  }
}

function swapForm(unswap) {
  $("#email-form").addClass('faded');
  $("#email-input").val("");
  if(unswap) window.setTimeout(function() {
    $("#upload-progress").addClass('faded');
    $("#email-form").removeClass('faded');
  }, 5000);
}
<commit_msg>fixed height for navbar<commit_after>// Document ready
$(function() {

  // initialize Parse
  Parse.initialize("ESlRgOz3V1xyLJOsfIHG93enDoVYZZGhNxJe3SXk", "cp2EJqkQMu1Dbv9htMoZ7caQbiqe5AIkYKpRGzW6");

  // scroll the window back to the top
  // $('body').scrollTop(0);

  // pick a random background
  bgs = ['yay', 'sleep', 'hallway', 'chrysler', 'ceremony', 'breakout', 'big_house', 'big_house_2'];
  img = bgs[Math.floor(Math.random() * bgs.length)]
  $('body').css('background-image', 'url(/img/photos/' + img +'.jpg)')

  // set the upload trigger for a keypress
  $("#email-input").keypress(function(e) {
    if (e.keyCode == 13) {
      submitEmail();
      e.preventDefault();
    }
  });

  // set the upload trigger on the button
  $("#email-button").on('click', submitEmail);

  // Reset the logo for drawing
  $('.logo-animated path').each(function() {
    resetPathDrawing(this);
  });

  // Detect if the current browser is Firefox, and if it is,
  // use the much less cool version of this animation which
  // looks exactly the same.
  // In case you're curious: we had to make two methods to
  // scale the dots because Safari (and probably others)
  // don't let you set the radius (claiming it is read-only).
  if (typeof InstallTrigger !== 'undefined') {
    $('.logo-animated circle').each(function() {
      var t = $(this);
      t.attr('len', t.attr('r'));
      t.attr('r', '0');
      t.attr('class', '');
    });
  }

  // The path has been reset, so show the div
  $('#logo-wrapper').removeClass('invisible');

  // Drag the elements of the logo in 300ms from load
  window.setTimeout(function() {
    $('.logo-animated circle').attr('class', 'grow-animated');
    // this fixes the circles on firefox
    if (typeof InstallTrigger !== 'undefined') {
      $('.logo-animated circle').each(function() {
        var t = $(this);
        TweenMax.set(t, 1, {scale: 1, transformOrigin: "50% 50% 0"});
        TweenMax.to(t, 1, { attr:{ r: t.attr('len') } });
      });
    }
  }, 300);

  // Then, 100ms later, start drawing the lines
  window.setTimeout(function() {
    $('.logo-animated path').each(function() {
      simulatePathDrawing(this, 4.4);
    });
    // The border needs to be drawn more quickly
    simulatePathDrawing($('#logo-outline-path')[0], 3.0);
  }, 400);

  // enable smooth scrolling to anchors
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('.navbar-toggle').click();
        $('html,body').animate({
          scrollTop: target.offset().top - getNavHeight()
        }, 400);
        return false;
      }
    }
  });

  // affix the navbar, and
  // fix the width when resized
  $(window).resize(fixNavWidth);
  fixNavWidth();
});

function fixNavWidth() {
  $('nav').affix({
    offset: {
      top: $('nav').offset().top
    }
  });
  $('section#faq').css('margin-top', getNavHeight() + "px")
  $('#main-nav').width($('#main-container').outerWidth());
}

function getNavHeight() {
  if ($('.navbar-header').outerHeight() === 0)
    return $('#main-nav').outerHeight()
  return $('.navbar-header').outerHeight();
}

function validateEmail(email) {
  // jk I typed it out
  var re = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
  return re.test(email);
  // ...not
}

function daysBetween(date1, date2) {
  var oneDay = 24*60*60*1000;
  console.log(date1.getTime());
  console.log(date2.getTime());
  return Math.round(Math.abs((date1.getTime() - date2.getTime())/(oneDay)));
}

// Reset the drawing before starting
function resetPathDrawing(path) {
  // we need to hardcode the lengths because of Firefox
  length = $(path).attr('length');
  // Clear any previous transition
  path.style.transition = path.style.WebkitTransition = path.style.MozTransition =
  'none';
  // Set up the starting positions
  path.style.strokeDasharray = length + ' ' + length;
  path.style.strokeDashoffset = length;
  return length;
};

// For drawing the MHacks logo
function simulatePathDrawing(path, duration) {
  // grab the original values
  strokeDashoffset = path.style.getPropertyValue('stroke-dash-offset');
  strokeWidth = path.style.getPropertyValue('stroke-width');
  fill = path.style.getPropertyValue('fill');

  // do the stuff
  var length = resetPathDrawing(path);
  path.getBoundingClientRect();
  // Define our transition
  path.style.transition = path.style.WebkitTransition = path.style.MozTransition =
  'all ' + duration + 's ease-in';
  // Go!
  path.style.strokeDashoffset = strokeDashoffset;
  path.style.strokeWidth = strokeWidth;
  path.style.fill = fill;
};

function submitEmail() {
  var email = $("#email-input").val();
  if (validateEmail(email)) {
    swapForm(false);
    $("#upload-progress h2").text("Yeah, you're ready.");
    $("#upload-progress").removeClass('faded');
    var EmailDrop = Parse.Object.extend("EmailDrop");
    var obj = new EmailDrop();
    obj.set("email", email);
    obj.save(null, {
      success: function(obj) {
        // nuthin'
      },
      error: function(obj) {
        window.alert("I don't know what happened, but you should try that again.");
      }
    });
  }
  else if (email.length != 0) {
    swapForm(true);
    $("#upload-progress h2").text("I didn't Google that regex for nothing.");
    $("#upload-progress").removeClass('faded');
  }
}

function swapForm(unswap) {
  $("#email-form").addClass('faded');
  $("#email-input").val("");
  if(unswap) window.setTimeout(function() {
    $("#upload-progress").addClass('faded');
    $("#email-form").removeClass('faded');
  }, 5000);
}
<|endoftext|>


<commit_before>$(function() {
    $('.j-tooltip').tooltip();
    var gem_install_message_pre = "\
Fetching: addressable-2.3.5.gem (100%)\
\nFetching: launchy-2.3.0.gem (100%)\
\nFetching: require_all-1.3.2.gem (100%)\
\nFetching: thor-0.18.1.gem (100%)\
\nFetching: artii-2.0.3.gem (100%)\
\nFetching: rainbow-1.1.4.gem (100%)\
\nFetching: wedding-0.0.1.gem (100%)\
\n ";
    var gem_install_message_post = "\
\n[[b;#d33682;]==== Release notes for wedding gem ====]\
\n\
\nNow that you have installed this gem, you earn our immense respect.\
\nYou are the star guest of our wedding, you will receive our special\
\nattention.\
\n    Go ahead and type [[b;#859900;]wedding] on the command prompt to see the\
\nlist of commands available with it. Print your personal invitation,\
\nand fire your browser to see the location of the event.\
\n\
\nWe love you!\
\n\
\n[[b;#b58900;]Prerita and Jai]\
\n\
\n[[b;#d33682;]=======================================]\
\n\
\nSuccessfully installed addressable-2.3.5\
\nSuccessfully installed launchy-2.3.0\
\nSuccessfully installed require_all-1.3.2\
\nSuccessfully installed thor-0.18.1\
\nSuccessfully installed artii-2.0.3\
\nSuccessfully installed rainbow-1.1.4\
\nSuccessfully installed wedding-0.0.1\
\n7 gems installed\
\n    ";
    var prompt = "[[b;#d33682;]root]@[[b;#6c71c4;]wedding] ~$ ";
    var wedding_url = "http://goo.gl/4tqfMs";
    var rsvp_url = "https://twitter.com/jaipandya";
    var venue_address = "\
Gandhi Nagar Club Gardens\
\n(Near Gandhi Nagar Girls' School),\
\nGandhi Nagar, Jaipur\
\nPin - 302015\
    "
    var ganesha = "\
\n                 _.!._             \
\n                /O*@*O\\           \
\n              <\\@(_)@/>           \
\n      ,;,   .--;`     `;--.   ,    \
\n      O@O_ /   |d     b|   \\ _hnn \
\n      | `/ \\   |       |   / \\` |\
\n      &&&&  :##;\\     /;##;  &&&& \
\n      |  \\ / `##/|   |##'  \\ /  |\
\n      \\   %%`</|   |#'`%%   / \
\n       '._|_ \\   |   |'  / _|_.'  \
\n         _/  /   \\   \\   \\  \\  \
\n        / (\\(     '.  '-._&&&&    \
\n       (  ()##,    o'--.._`\\-)    \
\n        '-():`##########'()()()    \
\n         /:::::/()`Y`()\\:::::\\   \
\n         \\::::( () | () )::::/    \
\n          `\"\"\"`\\().'.()/'\"\"\"`     \
\n          \
  ";
  var invitation_pre = "\
\n[[b;#d33682;]========= Wedding invitation ==========]\
  ";
  var jai_weds_prerita = "\
\n       __      _    \
\n      / /___ _(_)   \
\n __  / / __ `/ /    \
\n/ /_/ / /_/ / /     \
\n\____/\\__,_/_/      \
\n\
\n    weds                             \
\n    ____                 _ __        \
\n   / __ \\________  _____(_) /_____ _ \
\n  / /_/ / ___/ _ \\/ ___/ / __/ __ `/ \
\n / ____/ /  /  __/ /  / / /_/ /_/ /  \
\n/_/   /_/   \\___/_/  /_/\\__/\\__,_/   \
\n                                     \
  ";
  var invitation_post = "\
\nHi,\
\n\
\nWe are getting married on 29 November 13. It will \
\nbe a great pleasure for us to have your presence  \
\nin the wedding ceremony.                          \
\n                                                  \
\nEvent schedule:                                   \
\n\
\n 7:00 pm Barat starts from Home                   \
\n 8:00 pm Barat reaches venue                      \
\n12:00 am Phere                                    \
\n\
\nPack your bags! Only [[b;#cb4b16;]" + (29 - (new Date()).getDate()) + "] days left.                 \
\n\
  ";
    var wedding_help = "\
Commands: \
\n\t[[b;#268bd2;]wedding invitation]      [[b;#2aa198;]# Your invitation card is inside this envelope] \
\n\t[[b;#268bd2;]wedding bride]           [[b;#2aa198;]# Glory words about the bride] \
\n\t[[b;#268bd2;]wedding groom]           [[b;#2aa198;]# Glory words about the groom] \
\n\t[[b;#268bd2;]wedding location]        [[b;#2aa198;]# Google maps link to the wedding venue] \
\n\t[[b;#268bd2;]wedding rsvp]            [[b;#2aa198;]# RSVP for the event]\
  ";
    var bride = "\
\n[[b;#d33682;]========= Bride ==========]\
\n\
\nThe bride's name is Prerita\
\nShe is a Banker, Traveller, Dancer, Painter, Dreamer\
\nShe works as Asst. Manager at Bank of Baroda\
\nIf you want to contact her, her email ID\
\nis preritayadav@gmail.com\
\n\
  ";
    var groom = "\
\n[[b;#d33682;]========= Groom ==========]\
\n\
\nThe groom's name is Jai\
\nHe is a Programmer, Traveller, Photographer, Biker, SlideShare Engineer\
\nHe works as a Hacker at SlideShare\
\nemail - jaipandya@gmail.com\
\nlinkedin - https://www.linkedin.com/in/jaipandya \
\ntwitter - https://twitter.com/jaipandya \
\ngithub - https://github.com/jaipandya \
\n\
  ";
    var rsvp = "\
\nYou can RSVP to the event by sending an email to\
\nJai (jaipandya@gmail.com)\
\nor Prerita (preritayadav@gmail.com)\
\n        \
  ";
    var greetings = jai_weds_prerita + "\
\n\nWelcome to Prerita and Jai's wedding website. In order to retrieve your \
\ninvitation, first install wedding gem using [[b;#859900;]gem install wedding] command.\
\nOnce the gem is installed, type [[b;#859900;]wedding] in the terminal to see the list of\
\navailable commands. \
\n \
\nThe gem is available for download at https://rubygems.org/gems/wedding \
\n \
\nPress [[b;#859900;]enter (↩)] to install the gem on this terminal.\
\n  ";

    var gem_list_empty = '\n*** LOCAL GEMS ***\n';
    var gem_list_full = '\n*** LOCAL GEMS ***\n\naddressable (2.3.5)\nlaunchy (2.3.0)\nrequire_all (1.3.2)\nthor (0.18.1)\nartii (2.0.3)\nrainbow (1.1.4)\nwedding (0.0.1)\n';

    var print_gem = 'RubyGems is a sophisticated package manager for Ruby.  This is a\nbasic help message containing pointers to more information.\n\n  Usage:\n    gem -v\n    gem command [arguments...] [options...]\n\n  Examples:\n    gem install rake\n    gem list --local\n    gem build package.gemspec\n    gem help install\n\n  Further help:\n    gem help commands            list all \'gem\' commands\n    gem help examples            show some examples of usage\n    gem help platforms           show information about platforms\n    gem help <COMMAND>           show help on COMMAND\n                                   (e.g. \'gem help install\')\n    gem server                   present a web page at\n                                 http://localhost:8808/\n                                 with info about installed gems\n  Further information:\n    http://rubygems.rubyforge.org';

    function print_slowly(term, paragraph, callback) {
      var foo, i, lines;
      lines = paragraph.split("\n");
      term.pause();
      i = 0;
      foo = function(lines) {
        return setTimeout((function() {
          if (i < lines.length -1) {
            term.echo(lines[i]);
            i++;
            return foo(lines);
          } else {
            term.resume();
            return callback();
          }
        }), 1000);
      };
      return foo(lines);
    };
    function require_command(command_regex, terminal_history) {
      var executed = false;
      $.each(terminal_history, function(index, value){
        if (command_regex.test(value)) {
          executed = true
        }
      });
      return executed;

    }
    var gem_install_regex = /gem +install +wedding */ig;

    // Handle gem command
    function gem(inputs, term){
      // No second argument
      if (!inputs[1]) {
        term.echo(print_gem);
      } else if (inputs[1] === 'install' && inputs[2] === 'wedding') {
        print_slowly(term, gem_install_message_pre, function(){
          term.echo(gem_install_message_post)
        });
      } else if (inputs[1] === '-v') {
        term.echo('1.3.6');
      } else if (inputs[1] == 'list') {
        // if history has install wedding
        term.echo(gem_list_full);
        // else
        // term.echo(gem_list_empty)
      } else {
        term.echo(inputs.join(" ") + " is not a valid command")
      }
    }

    // Handle wedding command
    function wedding(inputs, term){
      if (!inputs[1]) {
        term.echo(wedding_help);
      } else if (inputs[1] === "bride") {
        term.echo(bride);
      } else if (inputs[1] === "groom") {
        term.echo(groom)
      } else if (inputs[1] === "invitation") {
        term.echo("[[;#b58900;]"+ganesha+ "]");
        term.echo(invitation_pre);
        term.pause();
        setTimeout(function(){
          term.resume();
          term.echo(jai_weds_prerita);
          term.pause();
          setTimeout(function(){
            term.resume();
            term.echo(invitation_post);
          }, 400)
        }, 1500)

      } else if (inputs[1] === "location") {
        term.echo(venue_address);
        term.echo(wedding_url);
        term.push(function(command, term) {
          if (/y(es){0,1}/.test(command)) {
            window.open(
              wedding_url,
              '_blank'
            );
          }
          term.pop();
        }, {
          prompt: 'Do you want to open this link in the browser? (yes/no) ',
          greetings: null
        });
      } else if (inputs[1] === "rsvp") {
        term.echo(rsvp)
        term.push(function(command, term) {
          window.open(
              rsvp_url,
              '_blank'
          );
          term.pop();
        }, {
          prompt: 'alternatively send me a tweet in a new window when you press [[b;#859900;]enter (↩)]',
          greetings: null
        });
      } else {
        term.error(inputs.join(" ") + " is not a valid command")
      }
    }

    // Main interpreter function
    function interpreter(input, term) {
      var command, inputs;
      inputs = input.split(/ +/)
      command = inputs[0];
      if (command === "gem") {
        gem(inputs, term);
      } else if (command === "wedding" || command === "help") {
        window.terminal = term;
        if (require_command(gem_install_regex, term.history().data())) {
          wedding(inputs, term);
        } else {
          term.error('Please install the gem first by executing\ngem install wedding');
        }
      } else if (/(cd)|(ls)|(cat)/.test(command)) {
        bash(inputs, term);
      } else if (input === "ruby -v"){
        term.echo("1.9.3");
      } else if (/which +wedding/.test(input)) {
        if (require_command(gem_install_regex, term.history().data())) {
          term.echo("/usr/bin/wedding");
        } // else do nothing
      } else if (/whoami/.test(input)) {
        term.echo("root");
      } else if (command.length === 0) {
        // do nothing
      } else {
        term.error(command + " is not a valid command");
      }
    }

    // Handle bash commands
    function bash(inputs, term) {
      var argument, echo, insert;

      echo = term.echo;
      insert = term.insert;
      if (!inputs[1]) {
        return console.log("none");
      } else {
        argument = inputs[1];
        if (/^\.\./.test(argument)) {
          return echo("-bash: cd: " + argument + ": Permission denied");
        } else {
          return echo("-bash: cd: " + argument + ": No such file or directory");
        }
      }
    };

    $('#terminal').terminal( interpreter, {
      prompt: prompt,
      name: 'wedding',
      greetings: greetings,
      height: 600,
      onInit: function(term){
        term.insert("gem install wedding");
        term.history().clear();
      },
      completion: function(term, string, callback){
        callback(['gem install wedding',
          'wedding invitation',
          'wedding location',
          'wedding groom',
          'wedding rsvp',
          'wedding bride']);
      },
      tabcompletion: true
    });

});<commit_msg>handle the message after the wedding date<commit_after>$(function() {
    $('.j-tooltip').tooltip();
    var gem_install_message_pre = "\
Fetching: addressable-2.3.5.gem (100%)\
\nFetching: launchy-2.3.0.gem (100%)\
\nFetching: require_all-1.3.2.gem (100%)\
\nFetching: thor-0.18.1.gem (100%)\
\nFetching: artii-2.0.3.gem (100%)\
\nFetching: rainbow-1.1.4.gem (100%)\
\nFetching: wedding-0.0.1.gem (100%)\
\n ";
    var gem_install_message_post = "\
\n[[b;#d33682;]==== Release notes for wedding gem ====]\
\n\
\nNow that you have installed this gem, you earn our immense respect.\
\nYou are the star guest of our wedding, you will receive our special\
\nattention.\
\n    Go ahead and type [[b;#859900;]wedding] on the command prompt to see the\
\nlist of commands available with it. Print your personal invitation,\
\nand fire your browser to see the location of the event.\
\n\
\nWe love you!\
\n\
\n[[b;#b58900;]Prerita and Jai]\
\n\
\n[[b;#d33682;]=======================================]\
\n\
\nSuccessfully installed addressable-2.3.5\
\nSuccessfully installed launchy-2.3.0\
\nSuccessfully installed require_all-1.3.2\
\nSuccessfully installed thor-0.18.1\
\nSuccessfully installed artii-2.0.3\
\nSuccessfully installed rainbow-1.1.4\
\nSuccessfully installed wedding-0.0.1\
\n7 gems installed\
\n    ";
    var prompt = "[[b;#d33682;]root]@[[b;#6c71c4;]wedding] ~$ ";
    var days_left = Math.round((new Date('2013 11 29') - new Date())/(1000*60*60*24));
    var wedding_url = "http://goo.gl/4tqfMs";
    var rsvp_url = "https://twitter.com/jaipandya";
    var venue_address = "\
Gandhi Nagar Club Gardens\
\n(Near Gandhi Nagar Girls' School),\
\nGandhi Nagar, Jaipur\
\nPin - 302015\
    "
    var ganesha = "\
\n                 _.!._             \
\n                /O*@*O\\           \
\n              <\\@(_)@/>           \
\n      ,;,   .--;`     `;--.   ,    \
\n      O@O_ /   |d     b|   \\ _hnn \
\n      | `/ \\   |       |   / \\` |\
\n      &&&&  :##;\\     /;##;  &&&& \
\n      |  \\ / `##/|   |##'  \\ /  |\
\n      \\   %%`</|   |#'`%%   / \
\n       '._|_ \\   |   |'  / _|_.'  \
\n         _/  /   \\   \\   \\  \\  \
\n        / (\\(     '.  '-._&&&&    \
\n       (  ()##,    o'--.._`\\-)    \
\n        '-():`##########'()()()    \
\n         /:::::/()`Y`()\\:::::\\   \
\n         \\::::( () | () )::::/    \
\n          `\"\"\"`\\().'.()/'\"\"\"`     \
\n          \
  ";
  var invitation_pre = "\
\n[[b;#d33682;]========= Wedding invitation ==========]\
  ";
  var jai_weds_prerita = "\
\n       __      _    \
\n      / /___ _(_)   \
\n __  / / __ `/ /    \
\n/ /_/ / /_/ / /     \
\n\____/\\__,_/_/      \
\n\
\n    weds                             \
\n    ____                 _ __        \
\n   / __ \\________  _____(_) /_____ _ \
\n  / /_/ / ___/ _ \\/ ___/ / __/ __ `/ \
\n / ____/ /  /  __/ /  / / /_/ /_/ /  \
\n/_/   /_/   \\___/_/  /_/\\__/\\__,_/   \
\n                                     \
  ";
  var invitation_post = "\
\nHi,\
\n\
\nWe are getting married on 29 November 13. It will \
\nbe a great pleasure for us to have your presence  \
\nin the wedding ceremony.                          \
\n                                                  \
\nEvent schedule:                                   \
\n\
\n 7:00 pm Barat starts from Home                   \
\n 8:00 pm Barat reaches venue                      \
\n12:00 am Phere                                    \
\n\
\nPack your bags! Only [[b;#cb4b16;]" + days_left + "] days left.                 \
\n\
  ";
    var wedding_help = "\
Commands: \
\n\t[[b;#268bd2;]wedding invitation]      [[b;#2aa198;]# Your invitation card is inside this envelope] \
\n\t[[b;#268bd2;]wedding bride]           [[b;#2aa198;]# Glory words about the bride] \
\n\t[[b;#268bd2;]wedding groom]           [[b;#2aa198;]# Glory words about the groom] \
\n\t[[b;#268bd2;]wedding location]        [[b;#2aa198;]# Google maps link to the wedding venue] \
\n\t[[b;#268bd2;]wedding rsvp]            [[b;#2aa198;]# RSVP for the event]\
  ";
    var bride = "\
\n[[b;#d33682;]========= Bride ==========]\
\n\
\nThe bride's name is Prerita\
\nShe is a Banker, Traveller, Dancer, Painter, Dreamer\
\nShe works as Asst. Manager at Bank of Baroda\
\nIf you want to contact her, her email ID\
\nis preritayadav@gmail.com\
\n\
  ";
    var groom = "\
\n[[b;#d33682;]========= Groom ==========]\
\n\
\nThe groom's name is Jai\
\nHe is a Programmer, Traveller, Photographer, Biker, SlideShare Engineer\
\nHe works as a Hacker at SlideShare\
\nemail - jaipandya@gmail.com\
\nlinkedin - https://www.linkedin.com/in/jaipandya \
\ntwitter - https://twitter.com/jaipandya \
\ngithub - https://github.com/jaipandya \
\n\
  ";
    var rsvp = "\
\nYou can RSVP to the event by sending an email to\
\nJai (jaipandya@gmail.com)\
\nor Prerita (preritayadav@gmail.com)\
\n        \
  ";
    var you_are_late = "\
Sorry, you are slightly late for attending the event. \
\nJai and Prerita have already got married on 29th November \
\nBut this site will remain here for archival purpose. \
\nRoam around happily :-) \
\n  "
    if (days_left >= 0) {
      you_are_late = ''
    }
    var greetings = you_are_late + jai_weds_prerita + "\
\n\nWelcome to Prerita and Jai's wedding website. In order to retrieve your \
\ninvitation, first install wedding gem using [[b;#859900;]gem install wedding] command.\
\nOnce the gem is installed, type [[b;#859900;]wedding] in the terminal to see the list of\
\navailable commands. \
\n \
\nThe gem is available for download at https://rubygems.org/gems/wedding \
\n \
\nPress [[b;#859900;]enter (↩)] to install the gem on this terminal.\
\n  ";

    var gem_list_empty = '\n*** LOCAL GEMS ***\n';
    var gem_list_full = '\n*** LOCAL GEMS ***\n\naddressable (2.3.5)\nlaunchy (2.3.0)\nrequire_all (1.3.2)\nthor (0.18.1)\nartii (2.0.3)\nrainbow (1.1.4)\nwedding (0.0.1)\n';

    var print_gem = 'RubyGems is a sophisticated package manager for Ruby.  This is a\nbasic help message containing pointers to more information.\n\n  Usage:\n    gem -v\n    gem command [arguments...] [options...]\n\n  Examples:\n    gem install rake\n    gem list --local\n    gem build package.gemspec\n    gem help install\n\n  Further help:\n    gem help commands            list all \'gem\' commands\n    gem help examples            show some examples of usage\n    gem help platforms           show information about platforms\n    gem help <COMMAND>           show help on COMMAND\n                                   (e.g. \'gem help install\')\n    gem server                   present a web page at\n                                 http://localhost:8808/\n                                 with info about installed gems\n  Further information:\n    http://rubygems.rubyforge.org';

    function print_slowly(term, paragraph, callback) {
      var foo, i, lines;
      lines = paragraph.split("\n");
      term.pause();
      i = 0;
      foo = function(lines) {
        return setTimeout((function() {
          if (i < lines.length -1) {
            term.echo(lines[i]);
            i++;
            return foo(lines);
          } else {
            term.resume();
            return callback();
          }
        }), 1000);
      };
      return foo(lines);
    };
    function require_command(command_regex, terminal_history) {
      var executed = false;
      $.each(terminal_history, function(index, value){
        if (command_regex.test(value)) {
          executed = true
        }
      });
      return executed;

    }
    var gem_install_regex = /gem +install +wedding */ig;

    // Handle gem command
    function gem(inputs, term){
      // No second argument
      if (!inputs[1]) {
        term.echo(print_gem);
      } else if (inputs[1] === 'install' && inputs[2] === 'wedding') {
        print_slowly(term, gem_install_message_pre, function(){
          term.echo(gem_install_message_post)
        });
      } else if (inputs[1] === '-v') {
        term.echo('1.3.6');
      } else if (inputs[1] == 'list') {
        // if history has install wedding
        term.echo(gem_list_full);
        // else
        // term.echo(gem_list_empty)
      } else {
        term.echo(inputs.join(" ") + " is not a valid command")
      }
    }

    // Handle wedding command
    function wedding(inputs, term){
      if (!inputs[1]) {
        term.echo(wedding_help);
      } else if (inputs[1] === "bride") {
        term.echo(bride);
      } else if (inputs[1] === "groom") {
        term.echo(groom)
      } else if (inputs[1] === "invitation") {
        term.echo("[[;#b58900;]"+ganesha+ "]");
        term.echo(invitation_pre);
        term.pause();
        setTimeout(function(){
          term.resume();
          term.echo(jai_weds_prerita);
          term.pause();
          setTimeout(function(){
            term.resume();
            term.echo(invitation_post);
          }, 400)
        }, 1500)

      } else if (inputs[1] === "location") {
        term.echo(venue_address);
        term.echo(wedding_url);
        term.push(function(command, term) {
          if (/y(es){0,1}/.test(command)) {
            window.open(
              wedding_url,
              '_blank'
            );
          }
          term.pop();
        }, {
          prompt: 'Do you want to open this link in the browser? (yes/no) ',
          greetings: null
        });
      } else if (inputs[1] === "rsvp") {
        term.echo(rsvp)
        term.push(function(command, term) {
          window.open(
              rsvp_url,
              '_blank'
          );
          term.pop();
        }, {
          prompt: 'alternatively send me a tweet in a new window when you press [[b;#859900;]enter (↩)]',
          greetings: null
        });
      } else {
        term.error(inputs.join(" ") + " is not a valid command")
      }
    }

    // Main interpreter function
    function interpreter(input, term) {
      var command, inputs;
      inputs = input.split(/ +/)
      command = inputs[0];
      if (command === "gem") {
        gem(inputs, term);
      } else if (command === "wedding" || command === "help") {
        window.terminal = term;
        if (require_command(gem_install_regex, term.history().data())) {
          wedding(inputs, term);
        } else {
          term.error('Please install the gem first by executing\ngem install wedding');
        }
      } else if (/(cd)|(ls)|(cat)/.test(command)) {
        bash(inputs, term);
      } else if (input === "ruby -v"){
        term.echo("1.9.3");
      } else if (/which +wedding/.test(input)) {
        if (require_command(gem_install_regex, term.history().data())) {
          term.echo("/usr/bin/wedding");
        } // else do nothing
      } else if (/whoami/.test(input)) {
        term.echo("root");
      } else if (command.length === 0) {
        // do nothing
      } else {
        term.error(command + " is not a valid command");
      }
    }

    // Handle bash commands
    function bash(inputs, term) {
      var argument, echo, insert;

      echo = term.echo;
      insert = term.insert;
      if (!inputs[1]) {
        return console.log("none");
      } else {
        argument = inputs[1];
        if (/^\.\./.test(argument)) {
          return echo("-bash: cd: " + argument + ": Permission denied");
        } else {
          return echo("-bash: cd: " + argument + ": No such file or directory");
        }
      }
    };

    $('#terminal').terminal( interpreter, {
      prompt: prompt,
      name: 'wedding',
      greetings: greetings,
      height: 600,
      onInit: function(term){
        term.insert("gem install wedding");
        term.history().clear();
      },
      completion: function(term, string, callback){
        callback(['gem install wedding',
          'wedding invitation',
          'wedding location',
          'wedding groom',
          'wedding rsvp',
          'wedding bride']);
      },
      tabcompletion: true
    });

});<|endoftext|>


<commit_before>/**
 * JavaScript for luzmcosta.com
 *
 * @author Luz M. Costa <luzmcosta@gmail.com>
 * @updated 12.07.2014
 * @version 0.1
 */

"use strict";

var Tracker, Phrases;

Tracker = {
    initialize: function() {
        // Bind methods to events.
        $( "#email" ).click( this.email );
        $( "#linkedin" ).click( this.linkedin );
        $( "#twitter" ).click( this.twitter );
    },
    email: function() {
        this.send( "contact", "click", "Email" );
    },
    linkedin: function() {
        this.send( "social", "go", "LinkedIn" );
    },
    twitter: function() {
        this.send( "social", "go", "Twitter" );
    },
    send: function( category, action, label ) {
        var ga = ga || {};

        ga( "send", "event", category, action, label );
    }
};

Phrases = {
    el: $( "#summary" ),
    initialize: function() {
        // Set content to scroll.
        this.scroll();

        // Set click events on options.
        this.setOptions();
    },
    /**
     * Toggles the options in and out of view.
     */
    animate: function( el, classes ) {
        // Toggle options in/out of view.
        $( el ).toggleClass( classes );
    },
    setOptions: function() {
        // Set click events on play option.
        $( ".fa-play" )
            .off()
            .on( "click", this.play.call( this, true ) );

        // Set click events on pause option.
        $( ".fa-pause" )
            .off()
            .on( "click", this.stop.bind( this ) )
            .on( "click", this.togglePlay );

        // Set event on list option
        $( ".fa-list" ).off().on( "click", this.list.bind( this ) );

        // Set event on refresh option
        $( ".fa-refresh" ).off().on( "click", this.reset.bind( this ) );
    },
    /**
     * Toggle the pause/play button's icon and functionality.
     */
    togglePlay: function( play, pause ) {
        // Set classes on the view.
        $( ".play" )
            .toggleClass( "fa-pause", pause )
            .toggleClass( "fa-play", play );
    },
    /**
     * Toggles the options in and out of view.
     */
    options: function() {
        console.log("OPTIONS");
        // Toggle options in/out of view.
        this.animate( "#options", "visuallyhidden" );
    },
    /**
     * Stores the return value of the interval.
     */
    interval: 0,
    /**
     * Stores the state of the view.
     */
    playing: false,
    /**
     * Toggles between the pause and play buttons.
     */
    play: function( start ) {
        console.log("PLAY", start );
        // If starting event, set pause button.
        // If stopping event, set play button.
        var pause = ( start ? true : false ),
            play = ( !start ? true : false );

        // Set classes on the view.
        this.togglePlay( play, pause );

        // Set the view's state;
        this.playing = start;

        return this.playing;
    },
    /**
     * Stop the interval counter from continuing.
     */
    stop: function( e ) {
        console.log("STOP", e );

        var isPlay = $( ".play" ).is( ".fa-play" ),
            isRefresh = $( ".list" ).is( ".fa-refresh" );

        // Set method to execute at set interval.
        clearInterval( this.interval );

        // Set the view's state;
        this.playing = false;

        // If starting...
        if ( isPlay || isRefresh ) {
            // Set the view to update at intervals.
            this.scroll();
        }

        // Set random phrase on view.
        return true;
    },
    /**
     * Restart the process.
     */
    reset: function() {
        // Stop all scrolling.
        this.stop();

        // Set play button.
        // Passes condition circa L125, if $(".play").is(".fa-play"), scroll.
        this.togglePlay( false );

        // Reset index to 0.
        this.current = 0;

        // Start scrolling.
        this.scroll();
    },
    /**
     * Updates the view every 2 seconds with a new phrase.
     */
    scroll: function() {
        // Set method to execute at set interval.
        // Save the return value to this.interval.
        this.interval = setInterval( this.render.bind( this ), 2000 );

        // Return setInterval's return value.
        return this.interval;
    },
    /**
     * Saves state.
     */
    save: function( i ) {
        this.current = i || 0;
    },
    /**
     * The index of the current phrase in the view.
     */
    current: 0,
    /**
     * List of phrases.
     *
     * @todo Replace with a data storage solution.
     */
    phrases: {
        default: "designs user experiences.",
        apps: "builds proprietary web applications.",
        bloat: "enjoys sweeping away the cruft in her free time",
        freeTime: "jokes about having free time",
        posts: "doesn't have time for posts",
        style: "likes Bauhaus",
        sites: "designs websites.",
        designui: "designs user interfaces.",
        users: "is getting to know her users.",
        staging: "always stages on the production server.",
        cli: "doesn't mind writing shell scripts.",
        gplus: "has a Google+ page, kinda...",
        facebook: "remembers when Facebook still posted statuses in the third-person",
        opensource: "s open source.",
        js: "s JavaScript.",
        sourceCode: "reads source code over morning coffee",
        requirejs: "uses RequireJS.",
        grunt: "uses Grunt.",
        backbone: "uses Backbone.",
        jquery: "uses jQuery.",
        qunit: "uses QUnit.",
        bodhi: "has a cat named Bodhi.",
        scrolling: "thought to herself, \" I better give users a button to stop this scrolling.\"",
        owls: "thinks the lobotomized owl is brilliant! * + *",
        es6: "is perusing the latest ECMAScript 6 draft.",
        raygun: "is playing around with RayGun for error logging.",
        wip: "has some work to do"
    },
    /**
     * Provide the index of a random property of this.phrases.
     */
    random: function( phrases ) {
        var i, list, phrase;

        // Get a list of all phrases' keys.
        list = Object.keys( phrases );

        // Get a random number to use as the index.
        i = Math.floor( Math.random( 0, list.length - 1 ) * 10 );

        // Prevent replacing a phrase w/ the same phrase.
        if ( i === this.current ) {
            i += 1;
        }

        // Get the phrase at the random index.
        phrase = list[ i ];

        // Save state.
        this.save( i );

        return phrase;
    },
    /**
     * Chooses, from the list of phrases, the phrase following the current.
     */
    next: function( phrases ) {
        var list, phrase;

        // Get a list of all phrases' keys.
        list = Object.keys( phrases );

        // Increment the current
        this.current = this.current + 1;

        // If this is the last phrase in the list...
        if ( this.current > list.length ) {
            // Restart from the first phrase.
            this.current = 0;
        }

        // Get the phrase at the next index.
        phrase = list[ this.current ];

        return phrase;
    },
    /**
     * Return a random phrase from the stored list of phrases.
     */
    phrase: function() {
        // Get the phrase at the random index.
        // @note To select phrases randomly, replace next w/ the random method.
        var phrase = this.next( this.phrases );

        return this.phrases[ phrase ];
    },
    /**
     * Set a random phrase on the view.
     */
    render: function() {
        // Get the phrase at the random index.
        var phrase = this.phrase();

        // Set random phrase on view.
        $( this.el ).html( phrase );

        // Set play button.
        // Passes condition circa L125, if $(".play").is(".fa-play"), scroll.
        this.togglePlay( false, true );

        // Set view.
        $( ".fa-refresh" ).addClass( "fa-list" ).removeClass( "fa-refresh" );

        return this;
    },
    /**
     * Lists every phrase.
     */
    list: function() {
        // Stop other events.
        this.stop();

        // Get the view.
        var $el = $( this.el );

        // Prepare view.
        $el.empty();

        // Get the phrase at the random index.
        var phrases = this.phrases;

        // Set random phrase on view.
        $.each( phrases, function( name, phrase ) {
            $el.append( "" + phrase + "" );
        });

        // Set view.
        $( ".list" ).toggleClass( "fa-list" ).toggleClass( "fa-refresh" );

        // Set play button.
        // Passes condition circa L125, if $(".play").is(".fa-play"), scroll.
        this.togglePlay( true, false );

        return this;
    }
};

Phrases.initialize();
Tracker.initialize();
<commit_msg>Fixes lobotomized owl's broken link.<commit_after>/**
 * JavaScript for luzmcosta.com
 *
 * @author Luz M. Costa <luzmcosta@gmail.com>
 * @updated 12.07.2014
 * @version 0.1
 */

"use strict";

var Tracker, Phrases;

Tracker = {
    initialize: function() {
        // Bind methods to events.
        $( "#email" ).click( this.email );
        $( "#linkedin" ).click( this.linkedin );
        $( "#twitter" ).click( this.twitter );
    },
    email: function() {
        this.send( "contact", "click", "Email" );
    },
    linkedin: function() {
        this.send( "social", "go", "LinkedIn" );
    },
    twitter: function() {
        this.send( "social", "go", "Twitter" );
    },
    send: function( category, action, label ) {
        var ga = ga || {};

        ga( "send", "event", category, action, label );
    }
};

Phrases = {
    el: $( "#summary" ),
    initialize: function() {
        // Set content to scroll.
        this.scroll();

        // Set click events on options.
        this.setOptions();
    },
    /**
     * Toggles the options in and out of view.
     */
    animate: function( el, classes ) {
        // Toggle options in/out of view.
        $( el ).toggleClass( classes );
    },
    setOptions: function() {
        // Set click events on play option.
        $( ".fa-play" )
            .off()
            .on( "click", this.play.call( this, true ) );

        // Set click events on pause option.
        $( ".fa-pause" )
            .off()
            .on( "click", this.stop.bind( this ) )
            .on( "click", this.togglePlay );

        // Set event on list option
        $( ".fa-list" ).off().on( "click", this.list.bind( this ) );

        // Set event on refresh option
        $( ".fa-refresh" ).off().on( "click", this.reset.bind( this ) );
    },
    /**
     * Toggle the pause/play button's icon and functionality.
     */
    togglePlay: function( play, pause ) {
        // Set classes on the view.
        $( ".play" )
            .toggleClass( "fa-pause", pause )
            .toggleClass( "fa-play", play );
    },
    /**
     * Toggles the options in and out of view.
     */
    options: function() {
        console.log("OPTIONS");
        // Toggle options in/out of view.
        this.animate( "#options", "visuallyhidden" );
    },
    /**
     * Stores the return value of the interval.
     */
    interval: 0,
    /**
     * Stores the state of the view.
     */
    playing: false,
    /**
     * Toggles between the pause and play buttons.
     */
    play: function( start ) {
        console.log("PLAY", start );
        // If starting event, set pause button.
        // If stopping event, set play button.
        var pause = ( start ? true : false ),
            play = ( !start ? true : false );

        // Set classes on the view.
        this.togglePlay( play, pause );

        // Set the view's state;
        this.playing = start;

        return this.playing;
    },
    /**
     * Stop the interval counter from continuing.
     */
    stop: function( e ) {
        console.log("STOP", e );

        var isPlay = $( ".play" ).is( ".fa-play" ),
            isRefresh = $( ".list" ).is( ".fa-refresh" );

        // Set method to execute at set interval.
        clearInterval( this.interval );

        // Set the view's state;
        this.playing = false;

        // If starting...
        if ( isPlay || isRefresh ) {
            // Set the view to update at intervals.
            this.scroll();
        }

        // Set random phrase on view.
        return true;
    },
    /**
     * Restart the process.
     */
    reset: function() {
        // Stop all scrolling.
        this.stop();

        // Set play button.
        // Passes condition circa L125, if $(".play").is(".fa-play"), scroll.
        this.togglePlay( false );

        // Reset index to 0.
        this.current = 0;

        // Start scrolling.
        this.scroll();
    },
    /**
     * Updates the view every 2 seconds with a new phrase.
     */
    scroll: function() {
        // Set method to execute at set interval.
        // Save the return value to this.interval.
        this.interval = setInterval( this.render.bind( this ), 2000 );

        // Return setInterval's return value.
        return this.interval;
    },
    /**
     * Saves state.
     */
    save: function( i ) {
        this.current = i || 0;
    },
    /**
     * The index of the current phrase in the view.
     */
    current: 0,
    /**
     * List of phrases.
     *
     * @todo Replace with a data storage solution.
     */
    phrases: {
        default: "designs user experiences.",
        apps: "builds proprietary web applications.",
        bloat: "enjoys sweeping away the cruft in her free time",
        freeTime: "jokes about having free time",
        posts: "doesn't have time for posts",
        style: "likes Bauhaus",
        sites: "designs websites.",
        designui: "designs user interfaces.",
        users: "is getting to know her users.",
        staging: "always stages on the production server.",
        cli: "doesn't mind writing shell scripts.",
        gplus: "has a Google+ page, kinda...",
        facebook: "remembers when Facebook still posted statuses in the third-person",
        opensource: "s open source.",
        js: "s JavaScript.",
        sourceCode: "reads source code over morning coffee",
        requirejs: "uses RequireJS.",
        grunt: "uses Grunt.",
        backbone: "uses Backbone.",
        jquery: "uses jQuery.",
        qunit: "uses QUnit.",
        bodhi: "has a cat named Bodhi.",
        scrolling: "thought to herself, \" I better give users a button to stop this scrolling.\"",
        owls: "thinks the lobotomized owl is brilliant! * + *",
        es6: "is perusing the latest ECMAScript 6 draft.",
        raygun: "is playing around with RayGun for error logging.",
        wip: "has some work to do"
    },
    /**
     * Provide the index of a random property of this.phrases.
     */
    random: function( phrases ) {
        var i, list, phrase;

        // Get a list of all phrases' keys.
        list = Object.keys( phrases );

        // Get a random number to use as the index.
        i = Math.floor( Math.random( 0, list.length - 1 ) * 10 );

        // Prevent replacing a phrase w/ the same phrase.
        if ( i === this.current ) {
            i += 1;
        }

        // Get the phrase at the random index.
        phrase = list[ i ];

        // Save state.
        this.save( i );

        return phrase;
    },
    /**
     * Chooses, from the list of phrases, the phrase following the current.
     */
    next: function( phrases ) {
        var list, phrase;

        // Get a list of all phrases' keys.
        list = Object.keys( phrases );

        // Increment the current
        this.current = this.current + 1;

        // If this is the last phrase in the list...
        if ( this.current > list.length ) {
            // Restart from the first phrase.
            this.current = 0;
        }

        // Get the phrase at the next index.
        phrase = list[ this.current ];

        return phrase;
    },
    /**
     * Return a random phrase from the stored list of phrases.
     */
    phrase: function() {
        // Get the phrase at the random index.
        // @note To select phrases randomly, replace next w/ the random method.
        var phrase = this.next( this.phrases );

        return this.phrases[ phrase ];
    },
    /**
     * Set a random phrase on the view.
     */
    render: function() {
        // Get the phrase at the random index.
        var phrase = this.phrase();

        // Set random phrase on view.
        $( this.el ).html( phrase );

        // Set play button.
        // Passes condition circa L125, if $(".play").is(".fa-play"), scroll.
        this.togglePlay( false, true );

        // Set view.
        $( ".fa-refresh" ).addClass( "fa-list" ).removeClass( "fa-refresh" );

        return this;
    },
    /**
     * Lists every phrase.
     */
    list: function() {
        // Stop other events.
        this.stop();

        // Get the view.
        var $el = $( this.el );

        // Prepare view.
        $el.empty();

        // Get the phrase at the random index.
        var phrases = this.phrases;

        // Set random phrase on view.
        $.each( phrases, function( name, phrase ) {
            $el.append( "" + phrase + "" );
        });

        // Set view.
        $( ".list" ).toggleClass( "fa-list" ).toggleClass( "fa-refresh" );

        // Set play button.
        // Passes condition circa L125, if $(".play").is(".fa-play"), scroll.
        this.togglePlay( true, false );

        return this;
    }
};

Phrases.initialize();
Tracker.initialize();
<|endoftext|>


<commit_before>//var elements = document.getElementsByTagName('script')

//Array.prototype.forEach.call(elements, function(element) {
//  if (element.type.indexOf('math/tex') != -1) {
     // Extract math markdown
  //   var textToRender = element.innerText || element.textContent;

     // Create span for KaTeX
    // var katexElement = document.createElement('span');

     // Support inline and display math
     //if (element.type.indexOf('mode=display') != -1){
      // katexElement.className += "math-display";
      // textToRender = '\\displaystyle {' + textToRender + '}';
    // } else {
    //   katexElement.className += "math-inline";
    // }

    // katex.render(textToRender, katexElement);
  //   element.parentNode.insertBefore(katexElement, element);
  //}
//});

$(document).ready(function() {
    // Test if we're doing a/b testing on tl;dr
    if ((abTestingId == 'Subscribehead') && !abTestingValue)) {
      document.getElementById('subscribehead').style.display = "none";
      console.log("Removed")
    }else{
      console.log("Still there.")
    }
}
<commit_msg>Google A/b<commit_after>//var elements = document.getElementsByTagName('script')

//Array.prototype.forEach.call(elements, function(element) {
//  if (element.type.indexOf('math/tex') != -1) {
     // Extract math markdown
  //   var textToRender = element.innerText || element.textContent;

     // Create span for KaTeX
    // var katexElement = document.createElement('span');

     // Support inline and display math
     //if (element.type.indexOf('mode=display') != -1){
      // katexElement.className += "math-display";
      // textToRender = '\\displaystyle {' + textToRender + '}';
    // } else {
    //   katexElement.className += "math-inline";
    // }

    // katex.render(textToRender, katexElement);
  //   element.parentNode.insertBefore(katexElement, element);
  //}
//});

$(document).ready(function(){
    // Test if we're doing a/b testing on tl;dr
    if ((abTestingId == 'Subscribehead') && (!abTestingValue)) {
      document.getElementById('subscribehead').style.display = "none";
      console.log("Removed")
    }else{
      console.log("Still there.")
    }
})
<|endoftext|>


<commit_before>// replace snake case with camel case
// _([a-zA-Z])([a-zA-Z]*)
// \U$1\L$2

$(document).ready(function(){
    // If we ever host this, we can enable sharing this way,
    // as long as the code is short enough to fit in a url.
    var urlParams = getURLParameters();
    ///////////////////////////////////////////////////
    // Mips Emulator Setup
    ///////////////////////////////////////////////////
    var me = mips_emulator({
        debug: false,
        /*
         * Changes the registers visual representation when the mips emulator changes its value
         * @param  {String} regName the register name
         * @param  {String/Number} value    The new value of the register
         * @return {null}
         */
        onRegisterChange: function(regName, value){
            var reg = $("#" + regName.replace('$', '') + " .regSpacer");
            $(".lastRegChanged").removeClass('lastRegChanged');
            reg.html(value);
            reg.addClass('lastRegChanged');
            // change to correct tab
            var regLetter = regName.replace('$', '').replace(/\s/, '').charAt(0);
            $('#registers a[href="#'+regLetter+'-registers"]').tab('show')
        },
        /*
         * runs when the emulator has pushed past the last line
         * @return {null}
         */
        onFinish: function(){
            alert("Emulation complete, returning to line 1");
            me.setLine(1);
            setHighlights({lineRan: lastLineNoRun, nextLine: me.get_line_number()});
            running = false;
        },
        /*
         * This is run when *the users* program encounters a mips error.
         * @param  {String} message     The error message
         * @param  {Number} lineNumber Which line the error occured on
         * @return {null}
         */
        onError: function(message, lineNumber){
            if(!_.isNumber(lineNumber)) return false;
            editor.markText(
                {line: lineNumber-1, ch: 0},
                {line: lineNumber, ch: 0},
                {title: message, className: 'errorLine', clearOnEnter: true}
            );
        },
        // Set the starting code to be the defualt in the editor.
        starting_code: $("#editor").val()
    });
    var running = false;
    // the active line, is the one whose results are being examined.
    var lastLineNoRun;
    var nextLine;

    ///////////////////////////////////////////////////
    // Code Mirror Setup
    ///////////////////////////////////////////////////

    // Code Mirror lines do not match with displayed line number
    // they start at zero and so are off by  -1
    var editor = CodeMirror.fromTextArea(
        document.getElementById("editor"),{
          lineNumbers: true,
          mode: "text/css",
          matchBrackets: true,
    });

    // When the editor changes, we need to mark it as invalid
    // so it will be reanalyzed upon a step or run
    editor.on('change', markEditorAsInvalid);

    // Keeps track of the last line we ran. To start with we want it
    // to be null becuase we have not run anything yet.
    var lastRunMarker;
    // Keeps track of the next line we will run, we want to set it to the
    // first valid line.
    var nextMarker = editor.markText(
        {line: me.get_line_number()-1, ch: 0},
        {line: me.get_line_number(), ch: 0},
        {title: "Next line to be run", className: 'nextLine'}
    );

    ///////////////////////////////////////////////////
    // Event Handlers setup
    ///////////////////////////////////////////////////
    $(".registers-container li").each(setupRegisters);
    $('.regSpacer').on('input', manualRegistryValidate);
    $('.regSpacer').on('blur', manualRegistryEditSave);
    $('#codeLoaders button').on('click', loadCustomCode);
    $("#step").click(step);
    $("#goToLineButton").on('click', setLine);
    $("#run").click(run);

    // Functions to respond to events.
    function setLine(){
        var newLine = $("#currentLineInput").val();
        // if(debug) console.log("Setting new line: "+ newLine);
        me.setLine(Number(newLine));
        // if(debug) console.log("nextLine"+ me.getLineNumber());
        setHighlights({lineRan: null, nextLine: me.get_line_number()})
        return false;
    };
    function markEditorAsInvalid(){
        me.valid = false;
    };
    function step(){
        // if this code is no longer valid, reanalyze.
        if(!me.valid){
            mipsAnalyze();
        }

        lineResult = me.step();
        if(lineResult){
           setHighlights(lineResult);
        }
    };
    function loadCustomCode(e){
        if(!confirm("This will erase what is in the code editor, are you sure?")) return;
        var target = $(e.target);
        var loadTarget = target.attr('load');
        var newContent = $(loadTarget).html();
        newContent = newContent.replace(/^\s+|\s+$/g, '');
        //newContent = newContent.replace(/\n\s+/g, '\n');
        editor.setValue(newContent);
        mipsAnalyze();
        setLine(1);
        setHighlights();
    };
    function manualRegistryEditSave(e){
        var newVal = $(e.target).html();
        var target =  $(e.target);
        var regName = target.attr("reg");
        me.setRegister(regName, Number(newVal), false);
    };
    function manualRegistryValidate(e){
        var newVal = $(e.target).html();
        var target =  $(e.target);
        var regName = target.attr("reg");
        if(newVal.search(/[^-\d]/) >= 0){
            target.html(newVal.replace(/[\D\s]/g, ''));
            alert("You cannot enter in characters into registers");
        }
        if(newVal.length > 11){
            if(newVal.length == 12 && newVal.charAt(0) == '-'){
                return true;
            } else {
                target.html(newVal.substring(0, 11));
                alert("The 32 bit integers can only be 11 digits long.");
            }

        }

        return true;
    };
    function setHighlights(lines){
        lines = lines || {};
        lastLineNoRun = lines.line_ran || null;
        nextLine = lines.nextLine || me.get_line_number();
        // if(debug) console.log("Active line: " + lastLineNoRun);
        // if(debug) console.log("Next line: " + nextLine);
        $("#currentLineInput").val(nextLine);
        if(lastRunMarker) lastRunMarker.clear();
        if(lastLineNoRun)
            lastRunMarker = editor.markText(
                {line: lastLineNoRun-1, ch: 0},
                {line: lastLineNoRun, ch: 0},
                {title: "last line ran", className: 'lastLineNoRun', clearOnEnter: true}
            );
        if(nextMarker) nextMarker.clear();
        nextMarker = editor.markText(
            {line: nextLine-1, ch: 0},
            {line: nextLine, ch: 0},
            {title: "Next line to be run", className: 'nextLine', clearOnEnter: true}
        );

    };
    function setupRegisters(index){
        var reg = $(this);
        var regName = reg.attr('id');
        reg.html(
            ""+regName +": "
            + ""
            + me.getRegisterVal('$' + regName)
            + ""
        );
    }
    function run(){
        // if this code is no longer valid, reanalyze.
        if(!me.valid){
            editor.save();
            me.setCode($("#editor").val());
            me.valid = true;
        }
        running = true;
        while(running) step();

    };
    function mipsAnalyze(){
        editor.save();
        me.setCode($("#editor").val());
        me.valid = true;
    };
    function getCodeAsString(){
        editor.save();
        return $("#editor").val();
    };
    function unsignInt(num){
        return (num << 31) >>> 0;
    }

});
// from http://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter
// Could be improved on.
function getURLParameters()
{
    var sURL = window.document.URL.toString();
    var params = {};
    if (sURL.indexOf("?") > 0)
    {
        var arrParams = sURL.split("?");
        var arrURLParams = arrParams[1].split("&");
        for (var i=0;i<arrURLParams.length;i++)
        {
            var sParam =  arrURLParams[i].split("=");
            if (sParam[1] != "")
                params[sParam[0]] = unescape(sParam[1]);
            else
                params[sParam[0]] = null;
        }
    }
    return params;

}
<commit_msg>switched to match mips_emulator camel case<commit_after>// replace snake case with camel case
// _([a-zA-Z])([a-zA-Z]*)
// \U$1\L$2

$(document).ready(function(){
    // If we ever host this, we can enable sharing this way,
    // as long as the code is short enough to fit in a url.
    var urlParams = getURLParameters();
    ///////////////////////////////////////////////////
    // Mips Emulator Setup
    ///////////////////////////////////////////////////
    var me = mipsEmulator({
        debug: false,
        /*
         * Changes the registers visual representation when the mips emulator changes its value
         * @param  {String} regName the register name
         * @param  {String/Number} value    The new value of the register
         * @return {null}
         */
        onRegisterChange: function(regName, value){
            var reg = $("#" + regName.replace('$', '') + " .regSpacer");
            $(".lastRegChanged").removeClass('lastRegChanged');
            reg.html(value);
            reg.addClass('lastRegChanged');
            // change to correct tab
            var regLetter = regName.replace('$', '').replace(/\s/, '').charAt(0);
            $('#registers a[href="#'+regLetter+'-registers"]').tab('show')
        },
        /*
         * runs when the emulator has pushed past the last line
         * @return {null}
         */
        onFinish: function(){
            alert("Emulation complete, returning to line 1");
            me.setLine(1);
            setHighlights({lineRan: lastLineNoRun, nextLine: me.getLineNumber()});
            running = false;
        },
        /*
         * This is run when *the users* program encounters a mips error.
         * @param  {String} message     The error message
         * @param  {Number} lineNumber Which line the error occured on
         * @return {null}
         */
        onError: function(message, lineNumber){
            if(!_.isNumber(lineNumber)) return false;
            editor.markText(
                {line: lineNumber-1, ch: 0},
                {line: lineNumber, ch: 0},
                {title: message, className: 'errorLine', clearOnEnter: true}
            );
        },
        // Set the starting code to be the defualt in the editor.
        startingCode: $("#editor").val()
    });
    var running = false;
    // the active line, is the one whose results are being examined.
    var lastLineNoRun;
    var nextLine;

    ///////////////////////////////////////////////////
    // Code Mirror Setup
    ///////////////////////////////////////////////////

    // Code Mirror lines do not match with displayed line number
    // they start at zero and so are off by  -1
    var editor = CodeMirror.fromTextArea(
        document.getElementById("editor"),{
          lineNumbers: true,
          mode: "text/css",
          matchBrackets: true,
    });

    // When the editor changes, we need to mark it as invalid
    // so it will be reanalyzed upon a step or run
    editor.on('change', markEditorAsInvalid);

    // Keeps track of the last line we ran. To start with we want it
    // to be null becuase we have not run anything yet.
    var lastRunMarker;
    // Keeps track of the next line we will run, we want to set it to the
    // first valid line.
    var nextMarker = editor.markText(
        {line: me.getLineNumber()-1, ch: 0},
        {line: me.getLineNumber(), ch: 0},
        {title: "Next line to be run", className: 'nextLine'}
    );

    ///////////////////////////////////////////////////
    // Event Handlers setup
    ///////////////////////////////////////////////////
    $(".registers-container li").each(setupRegisters);
    $('.regSpacer').on('input', manualRegistryValidate);
    $('.regSpacer').on('blur', manualRegistryEditSave);
    $('#codeLoaders button').on('click', loadCustomCode);
    $("#step").click(step);
    $("#goToLineButton").on('click', setLine);
    $("#run").click(run);

    // Functions to respond to events.
    function setLine(){
        var newLine = $("#currentLineInput").val();
        // if(debug) console.log("Setting new line: "+ newLine);
        me.setLine(Number(newLine));
        // if(debug) console.log("nextLine"+ me.getLineNumber());
        setHighlights({lineRan: null, nextLine: me.getLineNumber()})
        return false;
    };
    function markEditorAsInvalid(){
        me.valid = false;
    };
    function step(){
        // if this code is no longer valid, reanalyze.
        if(!me.valid){
            mipsAnalyze();
        }

        lineResult = me.step();
        if(lineResult){
           setHighlights(lineResult);
        }
    };
    function loadCustomCode(e){
        if(!confirm("This will erase what is in the code editor, are you sure?")) return;
        var target = $(e.target);
        var loadTarget = target.attr('load');
        var newContent = $(loadTarget).html();
        newContent = newContent.replace(/^\s+|\s+$/g, '');
        //newContent = newContent.replace(/\n\s+/g, '\n');
        editor.setValue(newContent);
        mipsAnalyze();
        setLine(1);
        setHighlights();
    };
    function manualRegistryEditSave(e){
        var newVal = $(e.target).html();
        var target =  $(e.target);
        var regName = target.attr("reg");
        me.setRegisterVal(regName, Number(newVal), false);
    };
    function manualRegistryValidate(e){
        var newVal = $(e.target).html();
        var target =  $(e.target);
        var regName = target.attr("reg");
        if(newVal.search(/[^-\d]/) >= 0){
            target.html(newVal.replace(/[\D\s]/g, ''));
            alert("You cannot enter in characters into registers");
        }
        if(newVal.length > 11){
            if(newVal.length == 12 && newVal.charAt(0) == '-'){
                return true;
            } else {
                target.html(newVal.substring(0, 11));
                alert("The 32 bit integers can only be 11 digits long.");
            }

        }

        return true;
    };
    function setHighlights(lines){
        lines = lines || {};
        lastLineNoRun = lines.lineRan || null;
        nextLine = lines.nextLine || me.getLineNumber();
        // if(debug) console.log("Active line: " + lastLineNoRun);
        // if(debug) console.log("Next line: " + nextLine);
        $("#currentLineInput").val(nextLine);
        if(lastRunMarker) lastRunMarker.clear();
        if(lastLineNoRun)
            lastRunMarker = editor.markText(
                {line: lastLineNoRun-1, ch: 0},
                {line: lastLineNoRun, ch: 0},
                {title: "last line ran", className: 'lastLineNoRun', clearOnEnter: true}
            );
        if(nextMarker) nextMarker.clear();
        nextMarker = editor.markText(
            {line: nextLine-1, ch: 0},
            {line: nextLine, ch: 0},
            {title: "Next line to be run", className: 'nextLine', clearOnEnter: true}
        );

    };
    function setupRegisters(index){
        var reg = $(this);
        var regName = reg.attr('id');
        reg.html(
            ""+regName +": "
            + ""
            + me.getRegisterVal('$' + regName)
            + ""
        );
    }
    function run(){
        // if this code is no longer valid, reanalyze.
        if(!me.valid){
            editor.save();
            me.setCode($("#editor").val());
            me.valid = true;
        }
        running = true;
        while(running) step();

    };
    function mipsAnalyze(){
        editor.save();
        me.setCode($("#editor").val());
        me.valid = true;
    };
    function getCodeAsString(){
        editor.save();
        return $("#editor").val();
    };
    function unsignInt(num){
        return (num << 31) >>> 0;
    }

});
// from http://stackoverflow.com/questions/979975/how-to-get-the-value-from-url-parameter
// Could be improved on.
function getURLParameters()
{
    var sURL = window.document.URL.toString();
    var params = {};
    if (sURL.indexOf("?") > 0)
    {
        var arrParams = sURL.split("?");
        var arrURLParams = arrParams[1].split("&");
        for (var i=0;i<arrURLParams.length;i++)
        {
            var sParam =  arrURLParams[i].split("=");
            if (sParam[1] != "")
                params[sParam[0]] = unescape(sParam[1]);
            else
                params[sParam[0]] = null;
        }
    }
    return params;

}
<|endoftext|>


<commit_before>var main = function(game) {
};

var object_computer_code , object_computer_art , object_logo;
var body_computer;
var code_display , art_display;
var player;
var background;

var state_game;

var idea_generated = false;
var idea = "";

var hoursLeft = 48;
var code_points = 0;
var art_points = 0;

var hoursLeft_text;
var start_text;
var log_text;
var log_string = "\n";

var left = false;

main.prototype = {
    preload: function() {
        console.log("Main state :)");
        state_game = this.game;
        console.log("Loading assets...");
        this.game.load.spritesheet('meatly' , "res/meatly.png" , 128 , 128);
        this.game.load.spritesheet('code' , "res/code.png" , 300 , 300);
        this.game.load.spritesheet('art' , "res/art.png" , 300 , 300);
        this.game.load.image('white' , "res/white.png");
        this.game.load.image('floor' , "res/floor.png");
        this.game.load.image('prog' , "res/progParticle.png");
        console.log("Assets loaded.");
    },

    create: function() {

        this.game.physics.startSystem(Phaser.Physics.ARCADE);

        background = this.game.add.sprite(0,0,'white');
        background.scale.setTo(31.5,18.75);

        player = this.game.add.sprite((this.game.width / 2) ,this.game.height,'meatly');
        player.anchor.set(.5);
        player.animations.add('idle', [16 , 17 , 19] , .3 , true);
        player.animations.add('left', [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7] , 11 , true);
        player.animations.add('right', [15 , 14 , 13 , 12 , 11 , 10 , 9 , 8] , 11 , true);
        player.animations.add('code' , [17 , 21 , 17] , .6 , true)
        this.game.physics.arcade.enable(player);
        player.body.gravity.y = 300;
        player.body.bounce.x = 25;
        player.body.setSize(30,128);
        player.body.collideWorldBounds = true;

        object_computer_code = this.game.add.sprite(this.game.width - 128 , this.game.height -128 , 'meatly');
        object_computer_code.animations.add('single' , [49]);
        object_computer_code.animations.play('single' , 1);
        this.game.physics.arcade.enable(object_computer_code);
        object_computer_code.body.setSize(80,128);
        object_computer_code.body.offset = new Phaser.Point(25 , 0);
        object_computer_code.body.immovable = true;

        this.game.add.text(object_computer_code.x + 25 , object_computer_code.y - 50 , "Code!" , {font:"20px Arial"});

        object_computer_art = this.game.add.sprite(0 , this.game.height -128 , 'meatly');
        object_computer_art.animations.add('single' , [48]);
        object_computer_art.animations.play('single' , 1);
        this.game.physics.arcade.enable(object_computer_art);
        object_computer_art.body.setSize(80,128);
        object_computer_art.body.offset = new Phaser.Point(25 , 0);
        object_computer_art.body.immovable = true;

        this.game.add.text(object_computer_art.x + 30 , object_computer_code.y - 50 , "Art!" , {font:"20px Arial"});

        object_logo = this.game.add.sprite((this.game.width / 2) , 64 , 'meatly');
        object_logo.anchor.set(.5);
        object_logo.animations.add('single' , [61]);
        object_logo.animations.play('single' , 1);

        hoursLeft_text = this.game.add.text((this.game.width / 2) , 75 , "Hours left: " + hoursLeft);
        hoursLeft_text.anchor.set(.5,0);
        log_text = this.game.add.text((this.game.width / 2) , 90 , "" , {font:"10px Arial"});
        log_text.anchor.set(.5,0);

        start_text = this.game.add.text(this.game.width /2 , this.game.height / 2 , "Press ENTER to generate your brilliant game idea!");
        start_text.anchor.set(.5);
    },

    update: function() {
        var startKey = this.game.input.keyboard.addKey(Phaser.Keyboard.ENTER);

        if(!idea_generated) {
            player.animations.play('idle');
            if(startKey.isDown) {
                reduceHours("idea");
                var rand = state_game.rnd.integerInRange(0, 10);

                switch(rand) {
                    case 1:
                        idea = "Rainbow pony!";
                        break;
                    case 2:
                        idea = "Cyborg cow.";
                        break;
                    case 3:
                        idea = "French toast comes to life?";
                        break;
                    case 4:
                        idea = "Killer cats.";
                        break;
                    case 5:
                        idea = "The inside of an ant's body!";
                        break;
                    case 6:
                        idea = "Strange letters from your creepy neighbor.";
                        break;
                    case 7:
                        idea = "A game without an idea.";
                        break;
                    case 8:
                        idea = "British fishing boats!";
                        break;
                    case 9:
                        idea = "Sharpie sniffing.";
                        break;
                    default:
                        idea = "Gameception...";
                        break;

                }

                var ideaText = this.game.add.text(this.game.width / 2 , 120 , "Game idea: " + idea , {font:"12px Arial"});
                ideaText.anchor.set(.5);

                idea_generated = true;
                start_text.destroy();
                player.x = (this.game.width / 2);
            }
            return;
        }

        cursors = this.game.input.keyboard.createCursorKeys();

        hoursLeft_text.text = "Hours left: " + hoursLeft;

        if(cursors.left.isDown) {
            player.body.velocity.x = -200;
            player.animations.play('left');
        } else if(cursors.right.isDown) {
            player.body.velocity.x = 200;
            player.animations.play('right');
        } else {
            player.body.velocity.x = 0;
            player.animations.play('idle');
        }

         this.game.physics.arcade.collide(player , object_computer_code , function() { //Collison: Player -> computer(code)
            code_display = state_game.add.sprite(state_game.width - 300,0,'code');
            code_display.animations.add('code' , [1 , 2 , 3 , 0] , 2 , false);
            code_display.animations.play('code');
            code_points++;
            reduceHours("coding");
            player.animations.play('code');
        });

        this.game.physics.arcade.collide(player , object_computer_art , function() { //Collison: Player -> computer(art)
            art_display = state_game.add.sprite(0 , 0 , 'art');
            var rand = state_game.rnd.integerInRange(0, 4);
            if(rand == 1)
                art_display.animations.add('art' , [1,2,0,3] , 2 , false);
            else if(rand == 2)
                art_display.animations.add('art' , [1,0,2,3] , 2 , false);
            else
                art_display.animations.add('art' , [0,1,2,3] , 2 , false);

            art_display.animations.play('art');
            art_points++;
            reduceHours("art");
            player.animations.play('code');
        });

    }
}

var reduceHours = function(reason) {
    hoursLeft--;
    player.x = (state_game.width / 2);
    if(left) {
        log_string = log_string + "\t" + "- 1hr. for " + reason;
        left = false;
    } else {
        log_string = log_string + "\n" + "- 1hr. for " + reason;
        left = true;
    }

    if(hoursLeft % 5 == 0 && hoursLeft != 5) {
        hoursLeft -=2; //For sleep
        if(left) {
        log_string = log_string + "\t" + "- 2hr. for sleep";
        left = false;
    } else {
        log_string = log_string + "\n" + "- 2hr. for sleep";
        left = true;
    }
    }

    log_text.text = log_string;

    if(hoursLeft <= 0) state_game.state.start('over');
}<commit_msg>Randomized hours<commit_after>var main = function(game) {
};

var object_computer_code , object_computer_art , object_logo;
var body_computer;
var code_display , art_display;
var player;
var background;

var state_game;

var idea_generated = false;
var idea = "";

var hoursLeft = 48;
var code_points = 0;
var art_points = 0;

var hoursLeft_text;
var start_text;
var log_text;
var log_string = "\n";

var left = false;

main.prototype = {
    preload: function() {
        console.log("Main state :)");
        state_game = this.game;
        console.log("Loading assets...");
        this.game.load.spritesheet('meatly' , "res/meatly.png" , 128 , 128);
        this.game.load.spritesheet('code' , "res/code.png" , 300 , 300);
        this.game.load.spritesheet('art' , "res/art.png" , 300 , 300);
        this.game.load.image('white' , "res/white.png");
        this.game.load.image('floor' , "res/floor.png");
        this.game.load.image('prog' , "res/progParticle.png");
        console.log("Assets loaded.");
    },

    create: function() {

        this.game.physics.startSystem(Phaser.Physics.ARCADE);

        background = this.game.add.sprite(0,0,'white');
        background.scale.setTo(31.5,18.75);

        player = this.game.add.sprite((this.game.width / 2) ,this.game.height,'meatly');
        player.anchor.set(.5);
        player.animations.add('idle', [16 , 17 , 19] , .3 , true);
        player.animations.add('left', [0 , 1 , 2 , 3 , 4 , 5 , 6 , 7] , 11 , true);
        player.animations.add('right', [15 , 14 , 13 , 12 , 11 , 10 , 9 , 8] , 11 , true);
        player.animations.add('code' , [17 , 21 , 17] , .6 , true)
        this.game.physics.arcade.enable(player);
        player.body.gravity.y = 300;
        player.body.bounce.x = 25;
        player.body.setSize(30,128);
        player.body.collideWorldBounds = true;

        object_computer_code = this.game.add.sprite(this.game.width - 128 , this.game.height -128 , 'meatly');
        object_computer_code.animations.add('single' , [49]);
        object_computer_code.animations.play('single' , 1);
        this.game.physics.arcade.enable(object_computer_code);
        object_computer_code.body.setSize(80,128);
        object_computer_code.body.offset = new Phaser.Point(25 , 0);
        object_computer_code.body.immovable = true;

        this.game.add.text(object_computer_code.x + 25 , object_computer_code.y - 50 , "Code!" , {font:"20px Arial"});

        object_computer_art = this.game.add.sprite(0 , this.game.height -128 , 'meatly');
        object_computer_art.animations.add('single' , [48]);
        object_computer_art.animations.play('single' , 1);
        this.game.physics.arcade.enable(object_computer_art);
        object_computer_art.body.setSize(80,128);
        object_computer_art.body.offset = new Phaser.Point(25 , 0);
        object_computer_art.body.immovable = true;

        this.game.add.text(object_computer_art.x + 30 , object_computer_code.y - 50 , "Art!" , {font:"20px Arial"});

        object_logo = this.game.add.sprite((this.game.width / 2) , 64 , 'meatly');
        object_logo.anchor.set(.5);
        object_logo.animations.add('single' , [61]);
        object_logo.animations.play('single' , 1);

        hoursLeft_text = this.game.add.text((this.game.width / 2) , 75 , "Hours left: " + hoursLeft);
        hoursLeft_text.anchor.set(.5,0);
        log_text = this.game.add.text((this.game.width / 2) , 90 , "" , {font:"10px Arial"});
        log_text.anchor.set(.5,0);

        start_text = this.game.add.text(this.game.width /2 , this.game.height / 2 , "Press ENTER to generate your brilliant game idea!");
        start_text.anchor.set(.5);
    },

    update: function() {
        var startKey = this.game.input.keyboard.addKey(Phaser.Keyboard.ENTER);

        if(!idea_generated) {
            player.animations.play('idle');
            if(startKey.isDown) {
                reduceHours(1, "idea");
                var rand = state_game.rnd.integerInRange(0, 10);

                switch(rand) {
                    case 1:
                        idea = "Rainbow pony!";
                        break;
                    case 2:
                        idea = "Cyborg cow.";
                        break;
                    case 3:
                        idea = "French toast comes to life?";
                        break;
                    case 4:
                        idea = "Killer cats.";
                        break;
                    case 5:
                        idea = "The inside of an ant's body!";
                        break;
                    case 6:
                        idea = "Strange letters from your creepy neighbor.";
                        break;
                    case 7:
                        idea = "A game without an idea.";
                        break;
                    case 8:
                        idea = "British fishing boats!";
                        break;
                    case 9:
                        idea = "Sharpie sniffing.";
                        break;
                    default:
                        idea = "Gameception...";
                        break;

                }

                var ideaText = this.game.add.text(this.game.width / 2 , 120 , "Game idea: " + idea , {font:"12px Arial"});
                ideaText.anchor.set(.5);

                idea_generated = true;
                start_text.destroy();
                player.x = (this.game.width / 2);
            }
            return;
        }

        cursors = this.game.input.keyboard.createCursorKeys();

        hoursLeft_text.text = "Hours left: " + hoursLeft;

        if(cursors.left.isDown) {
            player.body.velocity.x = -200;
            player.animations.play('left');
        } else if(cursors.right.isDown) {
            player.body.velocity.x = 200;
            player.animations.play('right');
        } else {
            player.body.velocity.x = 0;
            player.animations.play('idle');
        }

         this.game.physics.arcade.collide(player , object_computer_code , function() { //Collison: Player -> computer(code)
            code_display = state_game.add.sprite(state_game.width - 300,0,'code');
            code_display.animations.add('code' , [1 , 2 , 3 , 0] , 2 , false);
            code_display.animations.play('code');
            code_points++;
            reduceHours(state_game.rnd.integerInRange(1, 3) , "coding");
            player.animations.play('code');
        });

        this.game.physics.arcade.collide(player , object_computer_art , function() { //Collison: Player -> computer(art)
            art_display = state_game.add.sprite(0 , 0 , 'art');
            var rand = state_game.rnd.integerInRange(0, 4);
            if(rand == 1)
                art_display.animations.add('art' , [1,2,0,3] , 2 , false);
            else if(rand == 2)
                art_display.animations.add('art' , [1,0,2,3] , 2 , false);
            else
                art_display.animations.add('art' , [0,1,2,3] , 2 , false);

            art_display.animations.play('art');
            art_points++;
            reduceHours(state_game.rnd.integerInRange(1, 3) , "art");
            player.animations.play('code');
        });

    }
}

var reduceHours = function(amount , reason) {
    hoursLeft-= amount;
    player.x = (state_game.width / 2);
    if(left) {
        log_string = log_string + "\t" + "- " + amount +"hr. for " + reason;
        left = false;
    } else {
        log_string = log_string + "\n" + "- " + amount + "hr. for " + reason;
        left = true;
    }

    if(hoursLeft % 5 == 0 && hoursLeft != 5) {
        hoursLeft -=2; //For sleep
        if(left) {
        log_string = log_string + "\t" + "- 2hr. for sleep";
        left = false;
    } else {
        log_string = log_string + "\n" + "- 2hr. for sleep";
        left = true;
    }
    }

    log_text.text = log_string;

    if(hoursLeft <= 0) state_game.state.start('over');
}<|endoftext|>