<commit_before>// ----------------------------------------
// SVG images
// ----------------------------------------

// Replace all SVG images with inline SVG
function svgReplace() {
	$('img.svg').each(function(){
		var $img = jQuery(this);
		var imgID = $img.attr('id');
		var imgClass = $img.attr('class');
		var imgURL = $img.attr('src');

		jQuery.get(imgURL, function(data) {
			// Get the SVG tag, ignore the rest
			var $svg = jQuery(data).find('svg');

			// Add replaced image's ID to the new SVG
			if(typeof imgID !== 'undefined') {
				$svg = $svg.attr('id', imgID);
			}

			// Add replaced image's classes to the new SVG
			if(typeof imgClass !== 'undefined') {
				$svg = $svg.attr('class', imgClass+' replaced-svg');
			}

			// Remove any invalid XML tags as per http://validator.w3.org
			$svg = $svg.removeAttr('xmlns:a');

			// Replace image with new SVG
			$img.replaceWith($svg);

			setUpClickHandlers();
			setUpTooltips();
		}, 'xml');

	});
}

$(function() {
  svgReplace();
});

//----------------
//VARS
//----------------
var hourOfBreak,minsOfBreak,secsOfBreak;

// ----------------------------------------
// Display Time
// ----------------------------------------

function checkTime(i) {
	if (i < 10) {
		i = "0" + i;
	}
	return i;
}

function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var ampm = h >= 12 ? 'pm' : 'am';
    // add a zero in front of numbers<10
    m = checkTime(m);
    h = h % 12;
    h = h ? h : 12; // the hour '0' should be '12'
    document.getElementById('time').innerHTML = h + ":" + m + " " + ampm;
    t = setTimeout(function () {
        startTime()
    }, 500);
}

startTime();

// ----------------------------------------
// Keep track of time
// ----------------------------------------

function setGreeting(){
	refTime = new Date();
	refH = refTime.getHours();
	if (refH>=5 && refH<12){
		$('#content').attr('class', 'morning')
		$('.good-day h3').html('Good Morning!')
		$('.good-day p').html('Grab a cup of coffee and start your day off right!')
	} else if (refH>=12 && refH<18){
		$('#content').attr('class', 'afternoon')
		$('.good-day h3').html('Good Afternoon!')
		$('.good-day p').html('Grab a cup of coffee and continue your day off right!')
	}else if (refH>=18){
		$('#content').attr('class', 'evening')
		$('.good-day h3').html('Good Evening!')
		$('.good-day p').html('Grab a cup of coffee and end your day right!')
	}
}
setGreeting();
var greetInterval = setInterval(setGreeting, 10000);

// ----------------------------------------
// Toggle Visibility Of Different Templates
// ----------------------------------------

$('#Icon').click(function(){
	$('#settings').show(200);
	$('#Icon i').toggleClass('icon-settings icon-close');
});

// $('#setwork').click(function(){
// 	$('#workslider').append("<input type='range' min='0' max='12' step='1' />");
// })
//---------------------------------
//Get and set break time for user
//---------------------------------

$('#startDay').click(function(){
	$('.good-day h3, .good-day p, #startDay').css('display', 'none');
	$('.icon-info').css('display', 'block')
	var s = new Date();
	var dayBreak = new Date(s.getFullYear(), s.getMonth(), s.getDay(), s.getHours(), s.getMinutes(), (s.getSeconds()+5));
	hourOfBreak = dayBreak.getHours();
	minsOfBreak = checkTime(dayBreak.getMinutes());
	secsOfBreak = dayBreak.getSeconds();
	$('#info p').html("You should take a break in two hours at "+hourOfBreak+":"+minsOfBreak).fadeIn(1000).delay(5000).fadeOut(1000);
});

$('.icon-info').click(function(){
	$('#info p').fadeToggle();
});

function breakTime(){
	d = new Date();
	if(d.getSeconds() == secsOfBreak){
		$('#content').attr('class', 'break')
		clearInterval(greetInterval);
	}
}
//setInterval(breakTime, 1000)

<commit_msg>fixed fadetoggle<commit_after>// ----------------------------------------
// SVG images
// ----------------------------------------

// Replace all SVG images with inline SVG
function svgReplace() {
	$('img.svg').each(function(){
		var $img = jQuery(this);
		var imgID = $img.attr('id');
		var imgClass = $img.attr('class');
		var imgURL = $img.attr('src');

		jQuery.get(imgURL, function(data) {
			// Get the SVG tag, ignore the rest
			var $svg = jQuery(data).find('svg');

			// Add replaced image's ID to the new SVG
			if(typeof imgID !== 'undefined') {
				$svg = $svg.attr('id', imgID);
			}

			// Add replaced image's classes to the new SVG
			if(typeof imgClass !== 'undefined') {
				$svg = $svg.attr('class', imgClass+' replaced-svg');
			}

			// Remove any invalid XML tags as per http://validator.w3.org
			$svg = $svg.removeAttr('xmlns:a');

			// Replace image with new SVG
			$img.replaceWith($svg);

			setUpClickHandlers();
			setUpTooltips();
		}, 'xml');

	});
}

$(function() {
  svgReplace();
});

//----------------
//VARS
//----------------
var hourOfBreak,minsOfBreak,secsOfBreak;

// ----------------------------------------
// Display Time
// ----------------------------------------

function checkTime(i) {
	if (i < 10) {
		i = "0" + i;
	}
	return i;
}

function startTime() {
    var today = new Date();
    var h = today.getHours();
    var m = today.getMinutes();
    var ampm = h >= 12 ? 'pm' : 'am';
    // add a zero in front of numbers<10
    m = checkTime(m);
    h = h % 12;
    h = h ? h : 12; // the hour '0' should be '12'
    document.getElementById('time').innerHTML = h + ":" + m + " " + ampm;
    t = setTimeout(function () {
        startTime()
    }, 500);
}

startTime();

// ----------------------------------------
// Keep track of time
// ----------------------------------------

function setGreeting(){
	refTime = new Date();
	refH = refTime.getHours();
	if (refH>=5 && refH<12){
		$('#content').attr('class', 'morning')
		$('.good-day h3').html('Good Morning!')
		$('.good-day p').html('Grab a cup of coffee and start your day off right!')
	} else if (refH>=12 && refH<18){
		$('#content').attr('class', 'afternoon')
		$('.good-day h3').html('Good Afternoon!')
		$('.good-day p').html('Grab a cup of coffee and continue your day off right!')
	}else if (refH>=18){
		$('#content').attr('class', 'evening')
		$('.good-day h3').html('Good Evening!')
		$('.good-day p').html('Grab a cup of coffee and end your day right!')
	}
}
setGreeting();
var greetInterval = setInterval(setGreeting, 10000);

// ----------------------------------------
// Toggle Visibility Of Different Templates
// ----------------------------------------

$('#Icon').click(function(){
	$('#settings').fadeToggle(200);
	$('#Icon i').toggleClass('icon-settings icon-close');
});

// $('#setwork').click(function(){
// 	$('#workslider').append("<input type='range' min='0' max='12' step='1' />");
// })
//---------------------------------
//Get and set break time for user
//---------------------------------

$('#startDay').click(function(){
	$('.good-day h3, .good-day p, #startDay').css('display', 'none');
	$('.icon-info').css('display', 'block')
	var s = new Date();
	var dayBreak = new Date(s.getFullYear(), s.getMonth(), s.getDay(), s.getHours(), s.getMinutes(), (s.getSeconds()+5));
	hourOfBreak = dayBreak.getHours();
	minsOfBreak = checkTime(dayBreak.getMinutes());
	secsOfBreak = dayBreak.getSeconds();
	$('#info p').html("You should take a break in two hours at "+hourOfBreak+":"+minsOfBreak).fadeIn(1000).delay(5000).fadeOut(1000);
});

$('.icon-info').click(function(){
	$('#info p').fadeToggle();
});

function breakTime(){
	d = new Date();
	if(d.getSeconds() == secsOfBreak){
		$('#content').attr('class', 'break')
		clearInterval(greetInterval);
	}
}
//setInterval(breakTime, 1000)

<|endoftext|>


<commit_before>
// pull letter from database and update offscreen content
function setLetter(data) {
  // convert description to html
  var lines = data.rows[0].description_en.split('\n\n');
  var paras = [];
  for (var i = 0; i < lines.length; i++) {
    paras[i] = "
" + lines[i] + "
";
  }
  html = paras.join('\n');
  $('#letter .is-offscreen .text').html(html);

  //set signature
  $('#letter .is-offscreen .signature').text(data.rows[0].signature);

  //set address
  $('#letter .is-offscreen .addr').text(data.rows[0].location);
}

function headerBoxHeight() {
  var intro = $('#intro');
  // Ugh. Must be a cleaner way to accomplish the collapsing effect...
  return (
          intro.height()
          + parseInt(intro.css('padding-top'))
          + parseInt(intro.css('padding-bottom'))
         );
}

// from http://css-tricks.com/snippets/javascript/get-url-variables/
function getQueryVariable(variable)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}
  }
  return(false);
}

$(document).ready(function() {
  // Handler for .ready() called.

  // Revert to a previously saved state
  // TODO: test on IE
  window.addEventListener('popstate', function(event) {
    // popstate event occurs on page load but we may or may not have a state to work with.
    if (event.state && event.state.story_id) { // if provided a state, we can return to that state's story
      console.log('popstate fired; loading story ' + event.state.story_id);
      loadStory(event.state.story_id);
    }
    else { // even without a state, we may have a story in the url; if so, load it.
      id_from_url = getQueryVariable('photo');
      if (id_from_url) {
        loadStory(id_from_url);
      }
    }
  });

  adjust_heights();

  // clicking page title toggles intro text
  var header = $('header');
  $('header h1 a').click(function() {
      // if collapsed, expand
      if (parseInt(header.css('margin-top')) < 0) {
        header.css('margin-top', 0).removeClass('is-collapsed');
      } else {
      // was expanded; collapse
        header.css('margin-top', 0 - headerBoxHeight()).addClass('is-collapsed');
      }
    });

  // update module sizes on window resize
  $(window).on('resize', function (e) {
    // console.log('resized...');

    // update collapsed header
    // if collapsed, adjust collapsed size
    var header = $('header');
    if (header.hasClass('is-collapsed')) {
        header.css('margin-top', 0 - headerBoxHeight());
        // console.log('set header margin to: ' +  -headerBoxHeight());
    }
    // if expanded, do nothing.

    adjust_heights();
  });

});

function adjust_heights() {
  // Update map size
  var photo_height = $('#photo').height();
  //var photo_height = $('#photo img.is-onscreen').height();
  if (!photo_height) return; // don't adjust size if image isn't loaded
  var remainder = $(window).height() - photo_height;
  //$('#photo').height(photo_height); // resize container according to child img
  $('#map').css('height', remainder + 'px');
  console.log("#map height set to " + $('#map').height());
}

var sql = new cartodb.SQL({ user: 'techieshark' });

cartodb.createVis('map', 'http://techieshark.cartodb.com/api/v2/viz/519b0a24-f1a0-11e2-b27e-dbfe355cb68f/viz.json', {
    shareable: false,
    title: false,
    description: false,
    search: false,
    tiles_loader: true,
    center_lat: 45.519820,
    center_lon: -123.022499,
    zoom: 11,
    infowindow: false
  })
  .done(function(vis, layers) {

     // preload images
    sql.execute("SELECT img FROM photovoice").done(function(data) {
      preloader = $('#preloader');
      data.rows.forEach(function(row) {
        if (row['img'] != '') {
          preloader.append($(''));
        }
      });
    });

    // get sublayer 0 and set the infowindow template
    var sublayer = layers[1].getSubLayer(0);
    sublayer.infowindow.set('template', $('#infowindow_template').html());

    layers[1].on('featureClick', function(e, latlng, pos, data, subLayerIndex) {
      // console.log("mouse over polygon with data: " + data);
      // console.log("mouse over cartodb_id: " + data.cartodb_id);

      //set new history state so we can come back to this item later. (TODO: test on IE < 10)
      var state = { story_id: data.cartodb_id };
      history.pushState(state, "", "?photo=" + state.story_id);

      loadStory(data.cartodb_id);
    });
  });

function loadStory(story_id) {
      // hide page intro text
      $('header').css('margin-top', 0 - headerBoxHeight()).addClass('is-collapsed').delay(500);

      sql.execute("SELECT * FROM photovoice WHERE cartodb_id = {{id}}", { id: story_id })
        .done(function(data) {
          console.log(data.rows[0]);
          // set image
          // $('#photo img').attr('src', data.rows[0].img);

          // set image caption
          var caption = data.rows[0].location_description;
          var last_caption = $('#photo .caption .is-onscreen').animate({'margin-left':'-33em'}, 500).hide().removeClass('is-onscreen');
          $('#photo .caption .is-offscreen').text(caption).css('margin-left', '1000px').show()
            .animate({'margin-left':0}, 500).addClass('is-onscreen').removeClass('is-offscreen');
          last_caption.addClass('is-offscreen');

         setLetter(data);

        // animate letter
        var last_letter = $('#letter .is-onscreen');
        last_letter.animate({'margin-left':'-33em'},500).hide().removeClass('is-onscreen');
        $('#letter .is-offscreen').css('width', $('#letter').width()).css('position','absolute')
          .css('margin-left', '1000px').show()
          .animate(
            {'margin-left':0},
            { duration: 500,
              complete: function() {
                 // width is fixed during animation to prevent scrollbar from appearing mid-animation,
                // but needs to be set back to auto after complete so it will update if user adjusts page
                // size later.
                $(this).css('width', 'auto').css('position', 'static');
              }
            }).addClass('is-onscreen').removeClass('is-offscreen');
        last_letter.addClass('is-offscreen');

        // and once letter slides in, we'll animate photo
        last_photo = $('#photo img.is-onscreen');
        $('#photo img.is-offscreen').css('z-index', 1).css('margin-left', '1000px')
          .addClass('is-onscreen').removeClass('is-offscreen').attr('src', data.rows[0].img)
          .animate(
            {'margin-left':0},
            { duration: 500,
              complete: function () {
                last_photo.removeClass('is-onscreen').addClass('is-offscreen');
                $(this).css('z-index', 0);
              }
            });

          // var active = $('#photo span.is-onscreen');
          //Slider Animation
          // $('#photo span.is-offscreen').css('margin-left', '1000em').show()
          // .animate(
          //   { 'margin-left': 0 },
          //   {
          //    duration: 'slow',
          //    easing: 'easeOutBounce'
          //   });

           // .animate(
           //  { left: 0 }, {
           //   duration: 'slow',
           //   easing: 'easeOutBounce'
           //  });

          // $('#photo .caption span');
          // $('#photo .caption').text(data.rows[0].location_description);

        })
        .error(function(errors) {
          // errors contains a list of errors
          console.log("error:" + errors);
        });
}

<commit_msg>Parse height as float, not int, to avoid rounding error<commit_after>
// pull letter from database and update offscreen content
function setLetter(data) {
  // convert description to html
  var lines = data.rows[0].description_en.split('\n\n');
  var paras = [];
  for (var i = 0; i < lines.length; i++) {
    paras[i] = "
" + lines[i] + "
";
  }
  html = paras.join('\n');
  $('#letter .is-offscreen .text').html(html);

  //set signature
  $('#letter .is-offscreen .signature').text(data.rows[0].signature);

  //set address
  $('#letter .is-offscreen .addr').text(data.rows[0].location);
}

function headerBoxHeight() {
  var intro = $('#intro');
  // Ugh. Must be a cleaner way to accomplish the collapsing effect...
  return (
          intro.height()
          + parseFloat(intro.css('padding-top'))
          + parseFloat(intro.css('padding-bottom'))
         );
}

// from http://css-tricks.com/snippets/javascript/get-url-variables/
function getQueryVariable(variable)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}
  }
  return(false);
}

$(document).ready(function() {
  // Handler for .ready() called.

  // Revert to a previously saved state
  // TODO: test on IE
  window.addEventListener('popstate', function(event) {
    // popstate event occurs on page load but we may or may not have a state to work with.
    if (event.state && event.state.story_id) { // if provided a state, we can return to that state's story
      console.log('popstate fired; loading story ' + event.state.story_id);
      loadStory(event.state.story_id);
    }
    else { // even without a state, we may have a story in the url; if so, load it.
      id_from_url = getQueryVariable('photo');
      if (id_from_url) {
        loadStory(id_from_url);
      }
    }
  });

  adjust_heights();

  // clicking page title toggles intro text
  var header = $('header');
  $('header h1 a').click(function() {
      // if collapsed, expand
      if (parseInt(header.css('margin-top')) < 0) {
        header.css('margin-top', 0).removeClass('is-collapsed');
      } else {
      // was expanded; collapse
        header.css('margin-top', 0 - headerBoxHeight()).addClass('is-collapsed');
      }
    });

  // update module sizes on window resize
  $(window).on('resize', function (e) {
    // console.log('resized...');

    // update collapsed header
    // if collapsed, adjust collapsed size
    var header = $('header');
    if (header.hasClass('is-collapsed')) {
        header.css('margin-top', 0 - headerBoxHeight());
        // console.log('set header margin to: ' +  -headerBoxHeight());
    }
    // if expanded, do nothing.

    adjust_heights();
  });

});

function adjust_heights() {
  // Update map size
  var photo_height = $('#photo').height();
  //var photo_height = $('#photo img.is-onscreen').height();
  if (!photo_height) return; // don't adjust size if image isn't loaded
  var remainder = $(window).height() - photo_height;
  //$('#photo').height(photo_height); // resize container according to child img
  $('#map').css('height', remainder + 'px');
  console.log("#map height set to " + $('#map').height());
}

var sql = new cartodb.SQL({ user: 'techieshark' });

cartodb.createVis('map', 'http://techieshark.cartodb.com/api/v2/viz/519b0a24-f1a0-11e2-b27e-dbfe355cb68f/viz.json', {
    shareable: false,
    title: false,
    description: false,
    search: false,
    tiles_loader: true,
    center_lat: 45.519820,
    center_lon: -123.022499,
    zoom: 11,
    infowindow: false
  })
  .done(function(vis, layers) {

     // preload images
    sql.execute("SELECT img FROM photovoice").done(function(data) {
      preloader = $('#preloader');
      data.rows.forEach(function(row) {
        if (row['img'] != '') {
          preloader.append($(''));
        }
      });
    });

    // get sublayer 0 and set the infowindow template
    var sublayer = layers[1].getSubLayer(0);
    sublayer.infowindow.set('template', $('#infowindow_template').html());

    layers[1].on('featureClick', function(e, latlng, pos, data, subLayerIndex) {
      // console.log("mouse over polygon with data: " + data);
      // console.log("mouse over cartodb_id: " + data.cartodb_id);

      //set new history state so we can come back to this item later. (TODO: test on IE < 10)
      var state = { story_id: data.cartodb_id };
      history.pushState(state, "", "?photo=" + state.story_id);

      loadStory(data.cartodb_id);
    });
  });

function loadStory(story_id) {
      // hide page intro text
      $('header').css('margin-top', 0 - headerBoxHeight()).addClass('is-collapsed').delay(500);

      sql.execute("SELECT * FROM photovoice WHERE cartodb_id = {{id}}", { id: story_id })
        .done(function(data) {
          console.log(data.rows[0]);
          // set image
          // $('#photo img').attr('src', data.rows[0].img);

          // set image caption
          var caption = data.rows[0].location_description;
          var last_caption = $('#photo .caption .is-onscreen').animate({'margin-left':'-33em'}, 500).hide().removeClass('is-onscreen');
          $('#photo .caption .is-offscreen').text(caption).css('margin-left', '1000px').show()
            .animate({'margin-left':0}, 500).addClass('is-onscreen').removeClass('is-offscreen');
          last_caption.addClass('is-offscreen');

         setLetter(data);

        // animate letter
        var last_letter = $('#letter .is-onscreen');
        last_letter.animate({'margin-left':'-33em'},500).hide().removeClass('is-onscreen');
        $('#letter .is-offscreen').css('width', $('#letter').width()).css('position','absolute')
          .css('margin-left', '1000px').show()
          .animate(
            {'margin-left':0},
            { duration: 500,
              complete: function() {
                 // width is fixed during animation to prevent scrollbar from appearing mid-animation,
                // but needs to be set back to auto after complete so it will update if user adjusts page
                // size later.
                $(this).css('width', 'auto').css('position', 'static');
              }
            }).addClass('is-onscreen').removeClass('is-offscreen');
        last_letter.addClass('is-offscreen');

        // and once letter slides in, we'll animate photo
        last_photo = $('#photo img.is-onscreen');
        $('#photo img.is-offscreen').css('z-index', 1).css('margin-left', '1000px')
          .addClass('is-onscreen').removeClass('is-offscreen').attr('src', data.rows[0].img)
          .animate(
            {'margin-left':0},
            { duration: 500,
              complete: function () {
                last_photo.removeClass('is-onscreen').addClass('is-offscreen');
                $(this).css('z-index', 0);
              }
            });

          // var active = $('#photo span.is-onscreen');
          //Slider Animation
          // $('#photo span.is-offscreen').css('margin-left', '1000em').show()
          // .animate(
          //   { 'margin-left': 0 },
          //   {
          //    duration: 'slow',
          //    easing: 'easeOutBounce'
          //   });

           // .animate(
           //  { left: 0 }, {
           //   duration: 'slow',
           //   easing: 'easeOutBounce'
           //  });

          // $('#photo .caption span');
          // $('#photo .caption').text(data.rows[0].location_description);

        })
        .error(function(errors) {
          // errors contains a list of errors
          console.log("error:" + errors);
        });
}

<|endoftext|>


<commit_before>'use strict';

var exec = require('child_process').exec;

module.exports = function reboot(controller) {
  controller.hears('reboot', ['direct_mention'], function(bot, message) {
    bot.reply(message, 'codybot is going down and hopefully coming back up.');
    exec('pm2 restart codybotScheduler', function (err, stdout, stderr) {
      console.error(err);
      console.error(stderr);
      console.log(stdout);

      exec('pm2 restart codybot', function (err, stdout, stderr) {
        console.error(err);
        console.error(stderr);
        console.log(stdout);
      });

    });

    // console.log(message._client.channels.C0LFUN4F2.name);
  })
}
<commit_msg>Update reboot.js<commit_after>'use strict';

var exec = require('child_process').exec;

module.exports = function reboot(controller) {
  controller.hears('reboot', ['direct_mention'], function(bot, message) {
    bot.reply(message, 'codybot is going down and hopefully coming back up.');
    exec('ssh codybot@scheduler.codybot.com "pm2 restart scheduler"', function (err, stdout, stderr) {
      console.error(err);
      console.error(stderr);
      console.log(stdout);

      exec('pm2 restart codybotv2', function (err, stdout, stderr) {
        console.error(err);
        console.error(stderr);
        console.log(stdout);

        exec('pm2 restart codybot', function (err, stdout, stderr) {
          console.error(err);
          console.error(stderr);
          console.log(stdout);
        });
      });

    });

    // console.log(message._client.channels.C0LFUN4F2.name);
  })
}
<|endoftext|>


<commit_before>/*
Generates a deck of cards
Sebastian Lenton 2013
*/

"use strict";

//globals
var cardValues = [ 'ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king' ];
var suits = [ 'hearts', 'diamonds', 'spades', 'clubs' ];

var deckCardOffset = 2;

function Card( suit, value, index ) {
	this.index = index;
	this.suit = suit;
	this.value = value;
	this.flipped = false;
	this.getCardString = function( offset ) {
		return '

' + this.value + '

';
	};
	this.identify = function() {
		return this.suit + ' ' + this.value + ' ' + this.index;
	}
}

function Deck( name ) {
	this.cards = [];
	this.name = name;
	this.generate = function() {
		var counter = 0;
		for( var j = 0; j < suits.length; j++ ) {
			for( var i = 0; i < cardValues.length; i++ ) {
				this.cards.push( new Card( suits[ j ], cardValues[ i ], counter ) );
				//console.log( this.cards[ this.howMany( true ) ].identify() );
			}
		}
	};
	this.shuffle = function() {
		this.cards = shuffle( this.cards );
	};
	this.howMany = function( countFromZero ) {
		var length = this.cards.length;
		if( countFromZero ) {
			return length - 1;
		} else {
			return length;
		}
	};
	this.passCards = function( deck, amount ) {							//could merge passcard and passcards
		if( !amount ) {
			amount = 1;
		}
		for( var i = 0; i < amount; i++ ) {
			var cardToPass = this.cards.pop();
			deck.cards.push( cardToPass );
		}
	}
	this.renderAll = function() {										//this should be deleted and inherited from Deck
		var deckString = '';
		for( var j = 0; j < this.cards.length; j++ ) {
			deckString += this.cards[ j ].getCardString( j );
		}
		deckString = '
' + deckString + '
';
		$( 'body' ).append( deckString );
	}
}

var deck = new Deck( 'DefaultDeck' );
var startDeck = new Deck( 'StartDeck' );
var eggDeck = new Deck( 'EggDeck' );

deck.generate();

deck.passCards( eggDeck, 20 );
//deck.passCards( startDeck );			//need to stop too large amounts throwing errors

deck.renderAll();
startDeck.renderAll();
eggDeck.renderAll();

$( '.card' ).click( function() {
	console.log( 'clicked;' );

	$( this ).toggleClass( 'flipped' );
} )

/*********************
HELPERS
*********************/

function shuffle(array) {
    var counter = array.length, temp, index;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        index = (Math.random() * counter--) | 0;

        // And swap the last element with it
        temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}<commit_msg>tiny bit of comment cleanup<commit_after>/*
Generates a deck of cards. You can swap cards between the "main" deck and other decks (which can represent players, dealers etc)
Sebastian Lenton 2013
*/

"use strict";

//globals
var cardValues = [ 'ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king' ];
var suits = [ 'hearts', 'diamonds', 'spades', 'clubs' ];

var deckCardOffset = 2;

function Card( suit, value, index ) {
	this.index = index;
	this.suit = suit;
	this.value = value;
	this.flipped = false;
	this.getCardString = function( offset ) {
		return '

' + this.value + '

';
	};
	this.identify = function() {
		return this.suit + ' ' + this.value + ' ' + this.index;
	}
}

function Deck( name ) {
	this.cards = [];
	this.name = name;
	this.generate = function() {
		var counter = 0;
		for( var j = 0; j < suits.length; j++ ) {
			for( var i = 0; i < cardValues.length; i++ ) {
				this.cards.push( new Card( suits[ j ], cardValues[ i ], counter ) );
				//console.log( this.cards[ this.howMany( true ) ].identify() );
			}
		}
	};
	this.shuffle = function() {
		this.cards = shuffle( this.cards );
	};
	this.howMany = function( countFromZero ) {
		var length = this.cards.length;
		if( countFromZero ) {
			return length - 1;
		} else {
			return length;
		}
	};
	this.passCards = function( deck, amount ) {							//this could be more efficient
		if( !amount ) {
			amount = 1;
		}
		for( var i = 0; i < amount; i++ ) {
			var cardToPass = this.cards.pop();
			deck.cards.push( cardToPass );
		}
	}
	this.renderAll = function() {
		var deckString = '';
		for( var j = 0; j < this.cards.length; j++ ) {
			deckString += this.cards[ j ].getCardString( j );
		}
		deckString = '
' + deckString + '
';
		$( 'body' ).append( deckString );
	}
}

var deck = new Deck( 'DefaultDeck' );
var startDeck = new Deck( 'StartDeck' );
var eggDeck = new Deck( 'EggDeck' );

deck.generate();

deck.passCards( eggDeck, 20 );
//deck.passCards( startDeck );			//need to stop too large amounts throwing errors

deck.renderAll();
startDeck.renderAll();
eggDeck.renderAll();

$( '.card' ).click( function() {
	console.log( 'clicked;' );

	$( this ).toggleClass( 'flipped' );
} )

/*********************
HELPERS
*********************/

function shuffle(array) {
    var counter = array.length, temp, index;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        index = (Math.random() * counter--) | 0;

        // And swap the last element with it
        temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}<|endoftext|>


<commit_before>const typeOf = require('../utils/typeof');
const Task = require('../libs/task');
const valueChain = require('value-chain');

function isFunc(obj) {
  return typeOf(obj).is('function');
}
function isString(obj) {
  return typeOf(obj).is('string');
}
function handleConfig(configArg, req, res) {
  const stage = req.stage;
  // 删除了config属性，这里必须克隆，避免影响原对象
  let config = configArg;
  let router = configArg;

  if (!config) {
    return router;
  }

  if (isFunc(config)) {
    config = router = config(req, res);
  }

  let api = config.api;
  const isInterceptor = config.type === 'interceptor';

  // 统一api配置数据结构
  // api可以是字符串，字符串数组，对象混合字符串数组，函数(返回前面3中类型数据)
  if (isFunc(api)) {
    api = api.call(config, req, res);
  }

  // 无api配置，直接执行下一个stage
  if (!api) {
    if (isInterceptor && config.handle) {
      const data = config.handle(res.apiData, req, res);

      if (data) {
        valueChain.set(data);
      }

      if (config.name) {
        res.apiData[config.name] = data;
      } else {
        res.apiData = data || res.apiData;
      }
    }
    return config;
  }

  // 统一格式
  const query = req.query;
  const body = req.body;
  const name = config.name;
  const cache = config.cache;
  const excute = func => func.call(config, req, res);
  // 如果是拦截器，需要把handle合并进来
  // 拦截器api为非字符串型时，仅支持数组项内的handle，不支持全局handle
  if (isString(api)) {
    const handle = isInterceptor ? config.handle : null;
    api = [{ api, handle }];
  }

  if (! Array.isArray(api)) {
    throw new TypeError('The type of api must be String or Array or Function');
  }

  const isSeries = config.series;
  const taskName = isSeries ? 'series' : 'parallel';
  let task = req.apisTask[taskName];

  if (!task) {
    task = new Task(isSeries).context({ req, res });
  }
  /*
   * 统一格式为： [{api, query, body}...]，转为apiTask， 过滤掉item为函数情况下返回false
   */
  req.apis = api.map(item => {
    let apiItem = item;

    if (isString(item)) {
      apiItem = { 'api': item };
    } else if (isFunc(item)) {
      apiItem = excute(item);

      if (!apiItem) {
        return false;
      }

      if (isString(apiItem)) {
        apiItem = { 'api': apiItem };
      }
    }

    // 默认为对象类型，合并第一级配置的参数处理器
    apiItem = Object.assign({ query, body, name, cache }, apiItem);

    // 参数处理
    if (config.query) {
      apiItem.query = excute(config.query);
    }
    if (config.body) {
      apiItem.body = excute(config.body);
    }
    // 数据名
    if (!apiItem.name) {
      apiItem.name = stage.get('apiDataName').call(router, apiItem.api);
    }
    // 缓存
    if (isFunc(apiItem.cache)) {
      apiItem.cache = excute(apiItem.cache);
    }

    task.addApiTask(apiItem);

    return apiItem;
  });

  req.apisTask[taskName] = task;

  return router;
}
/**
 * 处理路由
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
 */
function handleRouter(req, res, next) {
  req.router = handleConfig(req.router, req, res);

  return next();
}
handleRouter.handleConfig = handleConfig;

module.exports = handleRouter;
<commit_msg>fix default query and body<commit_after>const typeOf = require('../utils/typeof');
const Task = require('../libs/task');
const valueChain = require('value-chain');

function isFunc(obj) {
  return typeOf(obj).is('function');
}
function isString(obj) {
  return typeOf(obj).is('string');
}
function handleConfig(configArg, req, res) {
  const stage = req.stage;
  // 删除了config属性，这里必须克隆，避免影响原对象
  let config = configArg;
  let router = configArg;

  if (!config) {
    return router;
  }

  if (isFunc(config)) {
    config = router = config(req, res);
  }

  let api = config.api;
  const isInterceptor = config.type === 'interceptor';

  // 统一api配置数据结构
  // api可以是字符串，字符串数组，对象混合字符串数组，函数(返回前面3中类型数据)
  if (isFunc(api)) {
    api = api.call(config, req, res);
  }

  // 无api配置，直接执行下一个stage
  if (!api) {
    if (isInterceptor && config.handle) {
      const data = config.handle(res.apiData, req, res);

      if (data) {
        valueChain.set(data);
      }

      if (config.name) {
        res.apiData[config.name] = data;
      } else {
        res.apiData = data || res.apiData;
      }
    }
    return config;
  }

  // 统一格式
  const query = config.query || req.query;
  const body = config.body || req.body;
  const name = config.name;
  const cache = config.cache;
  const excute = func => func.call(config, req, res);
  // 如果是拦截器，需要把handle合并进来
  // 拦截器api为非字符串型时，仅支持数组项内的handle，不支持全局handle
  if (isString(api)) {
    const handle = isInterceptor ? config.handle : null;
    api = [{ api, handle }];
  }

  if (! Array.isArray(api)) {
    throw new TypeError('The type of api must be String or Array or Function');
  }

  const isSeries = config.series;
  const taskName = isSeries ? 'series' : 'parallel';
  let task = req.apisTask[taskName];

  if (!task) {
    task = new Task(isSeries).context({ req, res });
  }
  /*
   * 统一格式为： [{api, query, body}...]，转为apiTask， 过滤掉item为函数情况下返回false
   */
  req.apis = api.map(item => {
    let apiItem = item;

    if (isString(item)) {
      apiItem = { 'api': item };
    } else if (isFunc(item)) {
      apiItem = excute(item);

      if (!apiItem) {
        return false;
      }

      if (isString(apiItem)) {
        apiItem = { 'api': apiItem };
      }
    }

    // 默认为对象类型，合并第一级配置的参数处理器
    apiItem = Object.assign({ query, body, name, cache }, apiItem);

    // 参数处理
    if (isFunc(apiItem.query)) {
      apiItem.query = excute(apiItem.query);
    }
    if (isFunc(apiItem.body)) {
      apiItem.body = excute(apiItem.body);
    }
    // 数据名
    if (!apiItem.name) {
      apiItem.name = stage.get('apiDataName').call(router, apiItem.api);
    }
    // 缓存
    if (isFunc(apiItem.cache)) {
      apiItem.cache = excute(apiItem.cache);
    }

    task.addApiTask(apiItem);

    return apiItem;
  });

  req.apisTask[taskName] = task;

  return router;
}
/**
 * 处理路由
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
 */
function handleRouter(req, res, next) {
  req.router = handleConfig(req.router, req, res);

  return next();
}
handleRouter.handleConfig = handleConfig;

module.exports = handleRouter;
<|endoftext|>


<commit_before>function Checkers() {
  this.board = [];
  this.redTeam = [];
  this.whiteTeam = [];
  // WHY DOESN'T THIS WORK WHEN this.currentSquare IS undefined?
  this.currentSquare = true;
  this.destinationSquare = undefined;
  this.team = undefined;
  this.selectedPiece = undefined;
  this.possibleSquareOne = false;
  this.p1jumped = undefined;
  this.possibleSquareTwo = false;
  this.p2jumped = undefined;
  this.turn = 'red';
};

function Square(row, column, playable) {
  this.row = row;
  this.column = column;
  this.playable = playable;
  this.occupied = false;
  this.destination = false;
  this.isCurrentSquare = false;
};

function Piece(team, idNum, row, column) {
  this.team = team;
  this.id = idNum;
  this.row = row;
  this.column = column;
  this.king = false;
};

// This function updates the squares in the board array with destination values
// when a .man is clicked
Piece.prototype.availableMoves = function() {
  // Determine 'king' value

  if (game.selectedPiece.team === 'red') {
    if (game.selectedPiece.column === 0) {
      // only look for one possible destination
      game.possibleSquareTwo = game.board[this.row + 1][this.column + 1];
    } else if (game.selectedPiece.column === 7) {
      // only look for one possible destination
      game.possibleSquareOne = game.board[this.row + 1][this.column - 1];
    } else {
      game.possibleSquareOne = game.board[this.row + 1][this.column - 1];
      game.possibleSquareTwo = game.board[this.row + 1][this.column + 1];
    };

    // NEED TO FIND IF THE SECOND DESTINATION IS ALSO ON THE BOARD
    if (game.possibleSquareOne.occupied === true) {
      // Check if the possible square is occupied by a piece of the same team
      // This needs to check the Piece{} that is in the possibleSquare, not the
      // team value of the possibleSquare, because that doesn't exist...
      if (game.selectedPiece.team === game.possibleSquareOne.occupiedBy.team) {
        game.possibleSquareOne.destination = false;
      } else {
        game.possibleSquareOne = game.board[this.row + 2][this.column - 2];
        if (game.possibleSquareOne.occupied === true) {
          game.possibleSquareOne.destination = false;
        } else {
          game.possibleSquareOne.destination = true;
          game.currentSquare.isCurrentSquare = true;
        }
      }
    } else {
      game.possibleSquareOne.destination = true;
      game.currentSquare.isCurrentSquare = true;
    };

    if (game.possibleSquareTwo.occupied === true) {
      // Check if the possible square is occupied by a piece of the same team
      if (game.selectedPiece.team === game.possibleSquareTwo.occupiedBy.team) {
        game.possibleSquareTwo.destination = false;
      } else {
        game.possibleSquareTwo = game.board[this.row + 2][this.column + 2];
        if (game.possibleSquareTwo.occupied === true) {
          game.possibleSquareTwo.destination = false;
        } else {
          game.possibleSquareTwo.destination = true;
          game.currentSquare.isCurrentSquare = true;
        }
      }
    } else {
      game.possibleSquareTwo.destination = true;
      game.currentSquare.isCurrentSquare = true;
    };
  };

  if (game.selectedPiece.team === 'white') {
    if (game.selectedPiece.column === 0) {
      game.possibleSquareOne = game.board[this.row - 1][this.column + 1];
    } else if (game.selectedPiece.column === 7) {
      game.possibleSquareTwo = game.board[this.row - 1][this.column - 1];
    } else {
      game.possibleSquareOne = game.board[this.row - 1][this.column + 1];
      game.possibleSquareTwo = game.board[this.row - 1][this.column - 1];
    };

    if (game.possibleSquareOne.occupied === true) {
      if (game.selectedPiece.team === game.possibleSquareOne.occupiedBy.team) {
        game.possibleSquareOne.destination = false;
      } else {
        game.possibleSquareOne = game.board[this.row - 2][this.column + 2];
        if (game.possibleSquareOne.occupied === true) {
          game.possibleSquareOne.destination = false;
        } else {
          game.possibleSquareOne.destination = true;
          game.currentSquare.isCurrentSquare = true;
        }
      }
    } else {
      game.possibleSquareOne.destination = true;
      game.currentSquare.isCurrentSquare = true;
    };

    if (game.possibleSquareTwo.occupied === true) {
      if (game.selectedPiece.team === game.possibleSquareTwo.occupiedBy.team) {
        game.possibleSquareTwo.destination = false;
      } else {
        game.possibleSquareTwo = game.board[this.row - 2][this.column - 2];
        if (game.possibleSquareTwo.occupied === true) {
          game.possibleSquareTwo.destination = false;
        } else {
          game.possibleSquareTwo.destination = true;
          game.currentSquare.isCurrentSquare = true;
        }
      }
    } else {
      game.possibleSquareTwo.destination = true;
      game.currentSquare.isCurrentSquare = true;
    };
  };
};

// This function moves the selected man from its current square into the
// destination square
Piece.prototype.moveMan = function() {
  // Changing coordinates of the man
  this.row = game.destinationSquare.row;
  this.column = game.destinationSquare.column;

  // Capturing relevant pieces

  // Unoccupy previous square
  game.currentSquare.occupied = false;

  // Occupy destination square
  game.destinationSquare.occupied = true;

  // Check for possible chained moves

  // Clear destinations and current square
  // MAYBE MAKE THIS INTO ITS OWN FUNCTION, OTHER PLACES COULD USE IT
  game.possibleSquareOne.destination = false;
  game.possibleSquareTwo.destination = false;
  game.currentSquare.isCurrentSquare = false;

  // Update relevant values:
  // Last square > unoccupied
  // New square > occupied
  // Captured piece > out of play
  // Kinged man > kinged
};

// A simple looping function that puts eight arrays, representing rows, into
// the board array
function fillBoard() {
  for (var i = 0; i < 8; i++) {
    game.board[i] = fillRow(i);
  };
};

// This function is called by fillBoard() in order to fill each row that is
// created while filling the board array
function fillRow(rowNumber) {
  var row = [];
  // If the row is odd, reverse the black/white(playable/not) scheme
  if (isOdd(rowNumber)) {
    // Creates 8 squares in the row array, following the correct scheme of
    // playable/unplayable squares
    for (var i = 0; i < 8; i++) {
      if (isOdd(i)) {
        row[i] = new Square(rowNumber, i, false);
      } else {
        row[i] = new Square(rowNumber, i, true);
      }
    }
    // If the row is even, the normal scheme of black/white squares is followed
  } else {
    // Creates eight squares, following the correct scheme
    for (var i = 0; i < 8; i++) {
      if (isOdd(i)) {
        row[i] = new Square(rowNumber, i, true);
      } else {
        row[i] = new Square(rowNumber, i, false);
      }
    }
  }
  // Returns the row back to the loop in the fillBoard() function, which puts
  // this new row into its place in the board array
  return row;
};

// A simple function that returns true when a given number is odd, and false
// if it is not
function isOdd(num) {
  return (num % 2) == 1;
};

function drawBoard() {
  // Creates the div for the board to be drawn in
  $('body').empty();
  $('body').prepend('

');
  // Creates divs for each row array in the board array
  for (i = 0; i < game.board.length; i++) {
    $('#board').append('

');
    // Creates divs for each square object in the board array
    for (n = 0; n < game.board[i].length; n++) {
      // Checks if the square is a playable square and adds a class if it is
      if (game.board[i][n].playable) {
        $('#row' + i).append(
            '

'
            );
        if (game.board[i][n].destination) {
          $('#' + i + n).addClass('destination');
        };
        if (game.board[i][n].isCurrentSquare) {
          $('#' + i + n).addClass('currentSquare');
        };
      } else {
        $('#row' + i).append(
            '

'
            );
      };
    };
  };
};

// This will create all the pieces for both teams
// Currently it just creates one piece and gives it the desires values
// MAKE THIS MORE SUCCINCT
function createPieces(team) {
  var row = 0;
  var column = 1;
  // Creates 12 pieces for the team
  if (team === 'red') {
    for (i = 0; i < 12; i++) {
      game.redTeam[i] = new Piece(team, i, row, column);
    };
    for (i = 0; i < 3; i++) {
      game.redTeam[i*4].row = i;
      game.redTeam[i*4 + 1].row = i;
      game.redTeam[i*4 + 2].row = i;
      game.redTeam[i*4 + 3].row = i;
    };
    var n = 0;
    for (i = 0; i < 12; i++) {
      if (isOdd(game.redTeam[i].row)) {
        game.redTeam[i].column = n;
      } else {
        game.redTeam[i].column = n + 1;
      };
      if (n < 6) {
        n = n + 2;
      } else {
        n = 0;
      };
    };
  } else if (team === 'white') {
    for (i = 0; i < 12; i++) {
      game.whiteTeam[i] = new Piece(team, i, row, column);
    };
    for (i = 0; i < 3; i++) {
      game.whiteTeam[i*4].row = 7 - i;
      game.whiteTeam[i*4 + 1].row = 7 - i;
      game.whiteTeam[i*4 + 2].row = 7 - i;
      game.whiteTeam[i*4 + 3].row = 7 - i;
    };
    var n = 0;
    for (i = 0; i < 12; i++) {
      if (isOdd(game.whiteTeam[i].row)) {
        game.whiteTeam[i].column = n;
      } else {
        game.whiteTeam[i].column = n + 1;
      };
      if (n < 6) {
        n = n + 2;
      } else {
        n = 0;
      };
    };
  }
};

// This clears all the pieces off the board and then redraws the pieces in
// their current positions.
function drawPieces() {
  $('.man').remove();
  for (i = 0; i < game.redTeam.length; i++) {
    game.board[game.redTeam[i].row][game.redTeam[i].column].occupied = true;
    game.board[game.redTeam[i].row][game.redTeam[i].column].occupiedBy =
      game.redTeam[i];
    $('#' + game.redTeam[i].row + game.redTeam[i].column).append(
        '

');
  };
  for (i = 0; i < game.whiteTeam.length; i++) {
    game.board[game.whiteTeam[i].row][game.whiteTeam[i].column].occupied = true;
    game.board[game.whiteTeam[i].row][game.whiteTeam[i].column].occupiedBy =
      game.whiteTeam[i];
    $('#' + game.whiteTeam[i].row + game.whiteTeam[i].column).append(
        '

');
  };
};

function getPiece(event, team) {
  if (team === 'red') {
    return game.redTeam[event.target.id];
  } else if (team === 'white') {
    return game.whiteTeam[event.target.id];
  };
};

function getSquare(thisSquare) {
  var row = thisSquare.charAt(0);
  var column = thisSquare.charAt(1);

  return game.board[row][column];
};

var game = new Checkers();

$(document).ready(function() {
  fillBoard();
  drawBoard();
  createPieces('red');
  createPieces('white');
  drawPieces();
  $('body').on('click', '.man', function(event) {
    // Grab the ID of the piece clicked
    // Make sure the piece matches the player moving
    // Check for available moves
    // Highlight open squares
    // Move piece selected to square clicked
    // Remove captured men
    // Check for additional moves

    // This prevents more than one .man from being selected
    if ($('.currentSquare').length === 1) {
      return;
    }

    // Gets the Piece{} that corresponds with the .man element that has been
    // clicked by the player
    game.team = $(this).attr('class').split(' ')[0];
    game.selectedPiece = getPiece(event, game.team);

    // Gets the Square{} that corresponds with the .playable element that has
    // been clicked by the player
    // MAYBE JUST GET THE COORDINATES OF THE SELECTED PIECE? IDK
    game.currentSquare = getSquare($(this).closest('.playable').attr('id'));

    game.selectedPiece.availableMoves();

    drawBoard();
    drawPieces();
  });

  $('body').on('click', '.currentSquare', function(event) {
    game.currentSquare.isCurrentSquare = false;

    game.possibleSquareOne.destination = false;
    game.possibleSquareTwo.destination = false;

    drawBoard();
    drawPieces();
  });

  $('body').on('click', '.destination', function(event) {
    game.destinationSquare = getSquare(event.currentTarget.id);

    game.selectedPiece.moveMan();

    drawBoard();
    drawPieces();
  });
});

// To Do:
// Comment more of the code
//
// Clean up Piece.prototype.availableMoves()
// - Currently works for non-king men, but it feels redundant to list moves for
//   red and white teams
// - Add king movement. This should be easier when the function is simplified
//   and condensed.
//
// Add capture logic
//
// Remove redundant variables/trackers
//
// createPieces{} needs to be cleaner
// - There's gotta be a more graceful way to correctly fill in the variables
//   on the men, without weird loops and repeated code
//
// Make the .destination 'x' look nicer... probably with CSS, not JS, but I
// don't have a to do list in the CSS
//
// Organize functions
//
// Add kinging logic
//
// Add team turn function
//
// Add animations
//
// Add a scoreboard(?)
//
// Create failsafes that prevent:
// - Multiple pieces in the same square
// - Multiple selectedPieces or currentSquares
//   - Currently, there is both the game object's variable for these values
//     AND properties in the Piece{} and Square{} objects. This may be
//     unnecessary?
// - These failsafes will be easier with cleaner code
//
// Maybe I don't need to completely redraw the board and pieces every click...
// I'll work on this after everything else is a little cleaner
<commit_msg>Turns are now working<commit_after>function Checkers() {
  this.board = [];
  this.redTeam = [];
  this.whiteTeam = [];
  // WHY DOESN'T THIS WORK WHEN this.currentSquare IS undefined?
  this.currentSquare = true;
  this.destinationSquare = undefined;
  this.team = undefined;
  this.selectedPiece = undefined;
  this.possibleSquareOne = false;
  this.p1jumped = undefined;
  this.possibleSquareTwo = false;
  this.p2jumped = undefined;
  this.turn = 'red';
};

function Square(row, column, playable) {
  this.row = row;
  this.column = column;
  this.playable = playable;
  this.occupied = false;
  this.destination = false;
  this.isCurrentSquare = false;
};

function Piece(team, idNum, row, column) {
  this.team = team;
  this.id = idNum;
  this.row = row;
  this.column = column;
  this.king = false;
};

// This function updates the squares in the board array with destination values
// when a .man is clicked
Piece.prototype.availableMoves = function() {
  // Determine 'king' value

  if (game.selectedPiece.team === 'red') {
    if (game.selectedPiece.column === 0) {
      // only look for one possible destination
      game.possibleSquareTwo = game.board[this.row + 1][this.column + 1];
    } else if (game.selectedPiece.column === 7) {
      // only look for one possible destination
      game.possibleSquareOne = game.board[this.row + 1][this.column - 1];
    } else {
      game.possibleSquareOne = game.board[this.row + 1][this.column - 1];
      game.possibleSquareTwo = game.board[this.row + 1][this.column + 1];
    };

    // NEED TO FIND IF THE SECOND DESTINATION IS ALSO ON THE BOARD
    if (game.possibleSquareOne.occupied === true) {
      // Check if the possible square is occupied by a piece of the same team
      // This needs to check the Piece{} that is in the possibleSquare, not the
      // team value of the possibleSquare, because that doesn't exist...
      if (game.selectedPiece.team === game.possibleSquareOne.occupiedBy.team) {
        game.possibleSquareOne.destination = false;
      } else {
        game.possibleSquareOne = game.board[this.row + 2][this.column - 2];
        if (game.possibleSquareOne.occupied === true) {
          game.possibleSquareOne.destination = false;
        } else {
          game.possibleSquareOne.destination = true;
          game.currentSquare.isCurrentSquare = true;
        }
      }
    } else {
      game.possibleSquareOne.destination = true;
      game.currentSquare.isCurrentSquare = true;
    };

    if (game.possibleSquareTwo.occupied === true) {
      // Check if the possible square is occupied by a piece of the same team
      if (game.selectedPiece.team === game.possibleSquareTwo.occupiedBy.team) {
        game.possibleSquareTwo.destination = false;
      } else {
        game.possibleSquareTwo = game.board[this.row + 2][this.column + 2];
        if (game.possibleSquareTwo.occupied === true) {
          game.possibleSquareTwo.destination = false;
        } else {
          game.possibleSquareTwo.destination = true;
          game.currentSquare.isCurrentSquare = true;
        }
      }
    } else {
      game.possibleSquareTwo.destination = true;
      game.currentSquare.isCurrentSquare = true;
    };
  };

  if (game.selectedPiece.team === 'white') {
    if (game.selectedPiece.column === 0) {
      game.possibleSquareOne = game.board[this.row - 1][this.column + 1];
    } else if (game.selectedPiece.column === 7) {
      game.possibleSquareTwo = game.board[this.row - 1][this.column - 1];
    } else {
      game.possibleSquareOne = game.board[this.row - 1][this.column + 1];
      game.possibleSquareTwo = game.board[this.row - 1][this.column - 1];
    };

    if (game.possibleSquareOne.occupied === true) {
      if (game.selectedPiece.team === game.possibleSquareOne.occupiedBy.team) {
        game.possibleSquareOne.destination = false;
      } else {
        game.possibleSquareOne = game.board[this.row - 2][this.column + 2];
        if (game.possibleSquareOne.occupied === true) {
          game.possibleSquareOne.destination = false;
        } else {
          game.possibleSquareOne.destination = true;
          game.currentSquare.isCurrentSquare = true;
        }
      }
    } else {
      game.possibleSquareOne.destination = true;
      game.currentSquare.isCurrentSquare = true;
    };

    if (game.possibleSquareTwo.occupied === true) {
      if (game.selectedPiece.team === game.possibleSquareTwo.occupiedBy.team) {
        game.possibleSquareTwo.destination = false;
      } else {
        game.possibleSquareTwo = game.board[this.row - 2][this.column - 2];
        if (game.possibleSquareTwo.occupied === true) {
          game.possibleSquareTwo.destination = false;
        } else {
          game.possibleSquareTwo.destination = true;
          game.currentSquare.isCurrentSquare = true;
        }
      }
    } else {
      game.possibleSquareTwo.destination = true;
      game.currentSquare.isCurrentSquare = true;
    };
  };
};

// This function moves the selected man from its current square into the
// destination square
Piece.prototype.moveMan = function() {
  // Changing coordinates of the man
  this.row = game.destinationSquare.row;
  this.column = game.destinationSquare.column;

  // Capturing relevant pieces

  // Unoccupy previous square
  game.currentSquare.occupied = false;

  // Occupy destination square
  game.destinationSquare.occupied = true;

  // Check for possible chained moves

  // Clear destinations and current square
  // MAYBE MAKE THIS INTO ITS OWN FUNCTION, OTHER PLACES COULD USE IT
  game.possibleSquareOne.destination = false;
  game.possibleSquareTwo.destination = false;
  game.currentSquare.isCurrentSquare = false;

  if (game.turn === 'red') {
    game.turn = 'white';
    console.log(game.turn + "'s turn to play.");
  } else if (game.turn === 'white') {
    game.turn = 'red';
    console.log(game.turn + "'s turn to play.");
  };

  // Update relevant values:
  // Last square > unoccupied
  // New square > occupied
  // Captured piece > out of play
  // Kinged man > kinged
  // Turn > other team
};

// A simple looping function that puts eight arrays, representing rows, into
// the board array
function fillBoard() {
  for (var i = 0; i < 8; i++) {
    game.board[i] = fillRow(i);
  };
};

// This function is called by fillBoard() in order to fill each row that is
// created while filling the board array
function fillRow(rowNumber) {
  var row = [];
  // If the row is odd, reverse the black/white(playable/not) scheme
  if (isOdd(rowNumber)) {
    // Creates 8 squares in the row array, following the correct scheme of
    // playable/unplayable squares
    for (var i = 0; i < 8; i++) {
      if (isOdd(i)) {
        row[i] = new Square(rowNumber, i, false);
      } else {
        row[i] = new Square(rowNumber, i, true);
      }
    }
    // If the row is even, the normal scheme of black/white squares is followed
  } else {
    // Creates eight squares, following the correct scheme
    for (var i = 0; i < 8; i++) {
      if (isOdd(i)) {
        row[i] = new Square(rowNumber, i, true);
      } else {
        row[i] = new Square(rowNumber, i, false);
      }
    }
  }
  // Returns the row back to the loop in the fillBoard() function, which puts
  // this new row into its place in the board array
  return row;
};

// A simple function that returns true when a given number is odd, and false
// if it is not
function isOdd(num) {
  return (num % 2) == 1;
};

function drawBoard() {
  // Creates the div for the board to be drawn in
  $('body').empty();
  $('body').prepend('

');
  // Creates divs for each row array in the board array
  for (i = 0; i < game.board.length; i++) {
    $('#board').append('

');
    // Creates divs for each square object in the board array
    for (n = 0; n < game.board[i].length; n++) {
      // Checks if the square is a playable square and adds a class if it is
      if (game.board[i][n].playable) {
        $('#row' + i).append(
            '

'
            );
        if (game.board[i][n].destination) {
          $('#' + i + n).addClass('destination');
        };
        if (game.board[i][n].isCurrentSquare) {
          $('#' + i + n).addClass('currentSquare');
        };
      } else {
        $('#row' + i).append(
            '

'
            );
      };
    };
  };
};

// This will create all the pieces for both teams
// Currently it just creates one piece and gives it the desires values
// MAKE THIS MORE SUCCINCT
function createPieces(team) {
  var row = 0;
  var column = 1;
  // Creates 12 pieces for the team
  if (team === 'red') {
    for (i = 0; i < 12; i++) {
      game.redTeam[i] = new Piece(team, i, row, column);
    };
    for (i = 0; i < 3; i++) {
      game.redTeam[i*4].row = i;
      game.redTeam[i*4 + 1].row = i;
      game.redTeam[i*4 + 2].row = i;
      game.redTeam[i*4 + 3].row = i;
    };
    var n = 0;
    for (i = 0; i < 12; i++) {
      if (isOdd(game.redTeam[i].row)) {
        game.redTeam[i].column = n;
      } else {
        game.redTeam[i].column = n + 1;
      };
      if (n < 6) {
        n = n + 2;
      } else {
        n = 0;
      };
    };
  } else if (team === 'white') {
    for (i = 0; i < 12; i++) {
      game.whiteTeam[i] = new Piece(team, i, row, column);
    };
    for (i = 0; i < 3; i++) {
      game.whiteTeam[i*4].row = 7 - i;
      game.whiteTeam[i*4 + 1].row = 7 - i;
      game.whiteTeam[i*4 + 2].row = 7 - i;
      game.whiteTeam[i*4 + 3].row = 7 - i;
    };
    var n = 0;
    for (i = 0; i < 12; i++) {
      if (isOdd(game.whiteTeam[i].row)) {
        game.whiteTeam[i].column = n;
      } else {
        game.whiteTeam[i].column = n + 1;
      };
      if (n < 6) {
        n = n + 2;
      } else {
        n = 0;
      };
    };
  }
};

// This clears all the pieces off the board and then redraws the pieces in
// their current positions.
function drawPieces() {
  $('.man').remove();
  for (i = 0; i < game.redTeam.length; i++) {
    game.board[game.redTeam[i].row][game.redTeam[i].column].occupied = true;
    game.board[game.redTeam[i].row][game.redTeam[i].column].occupiedBy =
      game.redTeam[i];
    $('#' + game.redTeam[i].row + game.redTeam[i].column).append(
        '

');
  };
  for (i = 0; i < game.whiteTeam.length; i++) {
    game.board[game.whiteTeam[i].row][game.whiteTeam[i].column].occupied = true;
    game.board[game.whiteTeam[i].row][game.whiteTeam[i].column].occupiedBy =
      game.whiteTeam[i];
    $('#' + game.whiteTeam[i].row + game.whiteTeam[i].column).append(
        '

');
  };
};

function getPiece(event, team) {
  if (team === 'red') {
    return game.redTeam[event.target.id];
  } else if (team === 'white') {
    return game.whiteTeam[event.target.id];
  };
};

function getSquare(thisSquare) {
  var row = thisSquare.charAt(0);
  var column = thisSquare.charAt(1);

  return game.board[row][column];
};

var game = new Checkers();

$(document).ready(function() {
  fillBoard();
  drawBoard();
  createPieces('red');
  createPieces('white');
  drawPieces();
  $('body').on('click', '.man', function(event) {
    // Grab the ID of the piece clicked
    // Make sure the piece matches the player moving
    // Check for available moves
    // Highlight open squares
    // Move piece selected to square clicked
    // Remove captured men
    // Check for additional moves

    // This prevents more than one .man from being selected
    if ($('.currentSquare').length === 1) {
      return;
    }

    // Gets the Piece{} that corresponds with the .man element that has been
    // clicked by the player
    game.team = $(this).attr('class').split(' ')[0];
    game.selectedPiece = getPiece(event, game.team);

    if (game.team === game.turn) {

      // Gets the Square{} that corresponds with the .playable element that has
      // been clicked by the player
      // MAYBE JUST GET THE COORDINATES OF THE SELECTED PIECE? IDK
      game.currentSquare = getSquare($(this).closest('.playable').attr('id'));

      game.selectedPiece.availableMoves();

      drawBoard();
      drawPieces();
    } else {
      console.log("Wrong team, wait your turn!");
    };
  });

  $('body').on('click', '.currentSquare', function(event) {
    game.currentSquare.isCurrentSquare = false;

    game.possibleSquareOne.destination = false;
    game.possibleSquareTwo.destination = false;

    drawBoard();
    drawPieces();
  });

  $('body').on('click', '.destination', function(event) {
    game.destinationSquare = getSquare(event.currentTarget.id);

    game.selectedPiece.moveMan();

    drawBoard();
    drawPieces();
  });
});

// To Do:
// Comment more of the code
//
// Clean up Piece.prototype.availableMoves()
// - Currently works for non-king men, but it feels redundant to list moves for
//   red and white teams
// - Add king movement. This should be easier when the function is simplified
//   and condensed.
//
// Add capture logic
//
// Remove redundant variables/trackers
//
// createPieces{} needs to be cleaner
// - There's gotta be a more graceful way to correctly fill in the variables
//   on the men, without weird loops and repeated code
//
// Make the .destination 'x' look nicer... probably with CSS, not JS, but I
// don't have a to do list in the CSS
//
// Organize functions
//
// Add kinging logic
//
// Add team turn function
//
// Add animations
//
// Add a scoreboard(?)
//
// Create failsafes that prevent:
// - Multiple pieces in the same square
// - Multiple selectedPieces or currentSquares
//   - Currently, there is both the game object's variable for these values
//     AND properties in the Piece{} and Square{} objects. This may be
//     unnecessary?
// - These failsafes will be easier with cleaner code
//
// Maybe I don't need to completely redraw the board and pieces every click...
// I'll work on this after everything else is a little cleaner
<|endoftext|>


<commit_before>
// =============================================
// declare vars and functions

var api_key;
var page_url;

function handleAvailabilityResponse(response) {
  // The main extension logic - do different things depending on what the API returns about URL's status
  oab.debugLog('API response: ' + JSON.stringify(response.data));

  document.getElementById('buttonstatus').className = document.getElementById('buttonstatus').className.replace('collapse','').replace('  ',' ');
  document.getElementById('loading_area').className = 'row collapse';

  // Change the UI depending on availability, existing requests, and the data types we can open new requests for.
  if (response.data.availability.length > 0) {
    var title = 'We found it! Click to open';
    for ( var avail_entry of response.data.availability ) {
      document.getElementById('icon'+avail_entry.type).style.backgroundColor = '#398bc5';
      document.getElementById('icon'+avail_entry.type).setAttribute('alt',title);
      document.getElementById('icon'+avail_entry.type).setAttribute('title',title);
      document.getElementById('icon'+avail_entry.type).setAttribute('href',avail_entry.url);
      var nd = document.getElementById('icon'+avail_entry.type).innerHTML;
      nd = nd.replace('Unavailable','Open '+avail_entry.type);
      document.getElementById('icon'+avail_entry.type).innerHTML = nd;
    }
  }
  if (response.data.requests.length > 0) {
    for (var requests_entry of response.data.requests) {
      if (requests_entry.usupport) {
        document.getElementById('icon'+requests_entry.type).setAttribute('data-action','supported');
      } else if (requests_entry.ucreated) {
        document.getElementById('icon'+requests_entry.type).setAttribute('data-action','created');
      } else {
        document.getElementById('icon'+requests_entry.type).setAttribute('data-action','support');
      }
      document.getElementById('icon'+requests_entry.type).setAttribute('data-support',requests_entry._id);
      var rnd = document.getElementById('icon'+requests_entry.type).innerHTML;
      rnd = rnd.replace('Unavailable','Support request');
      document.getElementById('icon'+requests_entry.type).innerHTML = rnd;
    }
  }
  if (response.data.accepts.length > 0) {
    for (var accepts_entry of response.data.accepts) {
      document.getElementById('icon'+accepts_entry.type).setAttribute('data-action','create');
      if (api_key) {
        var and = document.getElementById('icon'+accepts_entry.type).innerHTML;
        and = and.replace('Unavailable','Request '+accepts_entry.type);
        document.getElementById('icon'+accepts_entry.type).innerHTML = and;
      }
    }
  }
}

function handleRequestResponse(response) {
  document.getElementById('icon_submitting').className = 'collapse';
  document.getElementById('story_div').className += ' collapse';
  document.getElementById('story').value = "";
  var url = oab.site_address + '/request/' + response._id;
  var msg = "
Thank you for ";
  msg += document.getElementById('submit').getAttribute('data-action') === 'create' ? 'creat' : 'support';
  msg += "ing this request!
";
  msg += "
Please go and view the request, it may need additional details.
"
  msg += '
It should be open in a new tab, but if you do not see it click here';
  document.getElementById('message').innerHTML = msg;
  try {
    chrome.tabs.create({url: url, active: false});
  } catch(err) {
    // try opening direct with js
    oab.debugLog('Cannot open new tab for ' + url + ' - probably in the test page. Trying to open directly with js')
    window.open(url,'_blank');
  }
}

// =============================================
// These are run when the extension loads

try {
  chrome.tabs.executeScript({
    code: 'chrome.storage.local.set({dom: document.all[0].outerHTML });'
  });
} catch(err) {}

var noapimsg = "You don't appear to be signed up. If you sign up you can create and support requests.";
noapimsg += '
Please signup or login now.';

var start = function() {
  try {
    chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
      // Start by checking the status of the URL for the current tab
      page_url = tabs[0].url.split('#')[0];
      oab.debugLog('Sending availability query via chrome tabs for URL ' + page_url);
      var qry = {url:page_url};
      try {
        chrome.storage.local.get({dom : ''}, function(items) {
          if (items.dom !== '') qry.dom = items.dom;
          oab.sendAvailabilityQuery(api_key, qry, handleAvailabilityResponse, oab.handleAPIError);
        });
      } catch (err) {
        oab.sendAvailabilityQuery(api_key, qry, handleAvailabilityResponse, oab.handleAPIError);
      }
    });
  } catch (err) {
    oab.debugLog('Sending availability query direct from within test page');
    page_url = window.location.href.split('#')[0];
    if (page_url.indexOf('apikey=') !== -1) page_url = page_url.split('?apikey=')[0].split('&apikey=')[0].split('apikey=')[0];
    oab.sendAvailabilityQuery(api_key, {url:page_url, dom: document.all[0].outerHTML}, handleAvailabilityResponse, oab.handleAPIError);
  }
}

try {
  chrome.storage.local.get({api_key : ''}, function(items) {
    if (items.api_key === '') {
      oab.displayMessage(noapimsg);
      document.getElementById('noapikey').onclick = function () {
        chrome.tabs.create({'url': oab.site_address + oab.register_address});
      };
      start();
    } else {
      api_key = items.api_key;
      oab.debugLog('api key is available from chrome storage: ' + api_key);
      start();
    }
  });
} catch (err) {
  var apik;
  try {
    apik = window.location.href.split('apikey=')[1].split('&')[0].split('#')[0];
  } catch(err) {}
  if (apik) {
    // this is just useful for testing...
    oab.debugLog('Got api key ' + apik + ' direct from url param for testing');
    api_key = apik;
  } else {
    oab.displayMessage('(you are on the test page - you can provide an apikey url param to override this msg).
' + noapimsg);
  }
  start();
}

// =============================================
// bind actions to the elements

var needs = document.getElementsByClassName('need');
for ( var n in needs ) {
  needs[n].onclick = function(e) {
    var href = e.target.getAttribute('href');
    if (href === undefined || href === null) href = e.target.parentNode.getAttribute('href');
    var type = e.target.getAttribute('data-type');
    if (type === undefined || type === null) type = e.target.parentNode.getAttribute('data-type');
    var supports = e.target.getAttribute('data-support');
    if (supports === undefined || supports === null) supports = e.target.parentNode.getAttribute('data-support');
    document.getElementById('story_div').className = 'collapse';
    oab.displayMessage('');
    if ( href === '#' && api_key ) {
      e.preventDefault();
      var action = e.target.getAttribute('data-action');
      if (action === undefined || action === null) action = e.target.parentNode.getAttribute('data-action');
      if (action === 'created' || action === 'supported') {
        var u = oab.site_address + '/request/' + supports;
        var dm = '
You already ' + action + ' a request for this ' + type + '.
';
        dm += 'open the request
';
        oab.displayMessage(dm);
        if (chrome && chrome.tabs) {
          document.getElementById('goto_request').onclick = function () {
            chrome.tabs.create({'url': oab.site_address + '/request/' + rid});
          };
        }
      } else {
        var ask = action === 'support' ? 'Someone else has started a request for this ' + type + '. Add your support. ' : 'Create a new ' + type + ' request. ';
        ask += 'How would getting access to this ' + type + ' help you?';
        if (action !== 'support') ask += 'This message will be sent to the author.';
        document.getElementById('story').setAttribute('placeholder',ask);
        document.getElementById('submit').setAttribute('data-type',type);
        document.getElementById('submit').setAttribute('data-support',supports);
        document.getElementById('submit').setAttribute('data-action',action);
        if ( action === 'support' ) {
          document.getElementById('submit').innerHTML = document.getElementById('submit').innerHTML.replace('create','support');
        } else {
          document.getElementById('submit').innerHTML = document.getElementById('submit').innerHTML.replace('support','create');
        }
        document.getElementById('story_div').className = '';
      }
    } else if (chrome && chrome.tabs && api_key) {
      chrome.tabs.create({'url': href});
    } else {
      e.preventDefault();
    }
  }
}

document.getElementById('submit').onclick = function (e) {
  document.getElementById('submit').className = 'collapse';
  document.getElementById('icon_submitting').className = '';
  var data = {
    story: document.getElementById('story').value
  };
  var action = document.getElementById('submit').getAttribute('data-action');
  if ( action === 'create' ) {
    data.type = document.getElementById('submit').getAttribute('data-type');
    data.url = page_url;
    try {
      chrome.storage.local.get({dom : ''}, function(items) {
        if (items.dom !== '') data.dom = items.dom;
        oab.sendRequestPost(api_key, data, handleRequestResponse, oab.handleAPIError);
      });
    } catch (err) {
      oab.sendRequestPost(api_key, data, handleRequestResponse, oab.handleAPIError);
    }
  } else {
    data._id = document.getElementById('submit').getAttribute('data-support');
    oab.sendSupportPost(api_key, data, handleRequestResponse, oab.handleAPIError);
  }
};

document.getElementById('story').onkeyup = function () {
  var length = document.getElementById('story').value.replace(/  +/g,' ').split(' ').length;
  var left = 25 - length;
  if (left < 0) {
    left = 0;
  }
  if (length === 0) {
    document.getElementById('submit').innerHTML = 'Say why you need this in up to
25 words to support this request';
    document.getElementById('submit').style.backgroundColor = '#f04717';
  }
  if (length <= 5) {
    document.getElementById('submit').innerHTML = 'Tell us your reason with up to
 more words to support this request';
    document.getElementById('submit').style.backgroundColor = '#f04717';
  }
  if ( left < 25 && length > 5 ) {
    document.getElementById('submit').removeAttribute('disabled');
  } else {
    document.getElementById('submit').setAttribute('disabled',true);
  }
  if (length > 5 && length <= 10) {
    document.getElementById('submit').innerHTML = 'Great,  words remaining!
Write a few more?';
    document.getElementById('submit').style.backgroundColor = '#ffff66';
  }
  if (length > 10 && length <= 20) {
    document.getElementById('submit').innerHTML = ' words left! Or click to submit
now and create your request!';
    document.getElementById('submit').style.backgroundColor = '#99ff99';
  }
  if (length > 20) {
    document.getElementById('submit').innerHTML = '... Click now to submit your
reason and create your request';
    document.getElementById('submit').style.backgroundColor = '#99ff99';
  }
  document.getElementById('counter').innerHTML = left;
};
<commit_msg>bugfix<commit_after>
// =============================================
// declare vars and functions

var api_key;
var page_url;

function handleAvailabilityResponse(response) {
  // The main extension logic - do different things depending on what the API returns about URL's status
  oab.debugLog('API response: ' + JSON.stringify(response.data));

  document.getElementById('buttonstatus').className = document.getElementById('buttonstatus').className.replace('collapse','').replace('  ',' ');
  document.getElementById('loading_area').className = 'row collapse';

  // Change the UI depending on availability, existing requests, and the data types we can open new requests for.
  if (response.data.availability.length > 0) {
    var title = 'We found it! Click to open';
    for ( var avail_entry of response.data.availability ) {
      document.getElementById('icon'+avail_entry.type).style.backgroundColor = '#398bc5';
      document.getElementById('icon'+avail_entry.type).setAttribute('alt',title);
      document.getElementById('icon'+avail_entry.type).setAttribute('title',title);
      document.getElementById('icon'+avail_entry.type).setAttribute('href',avail_entry.url);
      var nd = document.getElementById('icon'+avail_entry.type).innerHTML;
      nd = nd.replace('Unavailable','Open '+avail_entry.type);
      document.getElementById('icon'+avail_entry.type).innerHTML = nd;
    }
  }
  if (response.data.requests.length > 0) {
    for (var requests_entry of response.data.requests) {
      if (requests_entry.usupport) {
        document.getElementById('icon'+requests_entry.type).setAttribute('data-action','supported');
      } else if (requests_entry.ucreated) {
        document.getElementById('icon'+requests_entry.type).setAttribute('data-action','created');
      } else {
        document.getElementById('icon'+requests_entry.type).setAttribute('data-action','support');
      }
      document.getElementById('icon'+requests_entry.type).setAttribute('data-support',requests_entry._id);
      var rnd = document.getElementById('icon'+requests_entry.type).innerHTML;
      rnd = rnd.replace('Unavailable','Support request');
      document.getElementById('icon'+requests_entry.type).innerHTML = rnd;
    }
  }
  if (response.data.accepts.length > 0) {
    for (var accepts_entry of response.data.accepts) {
      document.getElementById('icon'+accepts_entry.type).setAttribute('data-action','create');
      if (api_key) {
        var and = document.getElementById('icon'+accepts_entry.type).innerHTML;
        and = and.replace('Unavailable','Request '+accepts_entry.type);
        document.getElementById('icon'+accepts_entry.type).innerHTML = and;
      }
    }
  }
}

function handleRequestResponse(response) {
  document.getElementById('icon_submitting').className = 'collapse';
  document.getElementById('story_div').className += ' collapse';
  document.getElementById('story').value = "";
  var url = oab.site_address + '/request/' + response._id;
  var msg = "
Thank you for ";
  msg += document.getElementById('submit').getAttribute('data-action') === 'create' ? 'creat' : 'support';
  msg += "ing this request!
";
  msg += "
Please go and view the request, it may need additional details.
"
  msg += '
It should be open in a new tab, but if you do not see it click here';
  document.getElementById('message').innerHTML = msg;
  try {
    chrome.tabs.create({url: url, active: false});
  } catch(err) {
    // try opening direct with js
    oab.debugLog('Cannot open new tab for ' + url + ' - probably in the test page. Trying to open directly with js')
    window.open(url,'_blank');
  }
}

// =============================================
// These are run when the extension loads

try {
  chrome.tabs.executeScript({
    code: 'chrome.storage.local.set({dom: document.all[0].outerHTML });'
  });
} catch(err) {}

var noapimsg = "You don't appear to be signed up. If you sign up you can create and support requests.";
noapimsg += '
Please signup or login now.';

var start = function() {
  try {
    chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
      // Start by checking the status of the URL for the current tab
      page_url = tabs[0].url.split('#')[0];
      oab.debugLog('Sending availability query via chrome tabs for URL ' + page_url);
      var qry = {url:page_url};
      try {
        chrome.storage.local.get({dom : ''}, function(items) {
          if (items.dom !== '') qry.dom = items.dom;
          oab.sendAvailabilityQuery(api_key, qry, handleAvailabilityResponse, oab.handleAPIError);
        });
      } catch (err) {
        oab.sendAvailabilityQuery(api_key, qry, handleAvailabilityResponse, oab.handleAPIError);
      }
    });
  } catch (err) {
    oab.debugLog('Sending availability query direct from within test page');
    page_url = window.location.href.split('#')[0];
    if (page_url.indexOf('apikey=') !== -1) page_url = page_url.split('?apikey=')[0].split('&apikey=')[0].split('apikey=')[0];
    oab.sendAvailabilityQuery(api_key, {url:page_url, dom: document.all[0].outerHTML}, handleAvailabilityResponse, oab.handleAPIError);
  }
}

try {
  chrome.storage.local.get({api_key : ''}, function(items) {
    if (items.api_key === '') {
      oab.displayMessage(noapimsg);
      document.getElementById('noapikey').onclick = function () {
        chrome.tabs.create({'url': oab.site_address + oab.register_address});
      };
      start();
    } else {
      api_key = items.api_key;
      oab.debugLog('api key is available from chrome storage: ' + api_key);
      start();
    }
  });
} catch (err) {
  var apik;
  try {
    apik = window.location.href.split('apikey=')[1].split('&')[0].split('#')[0];
  } catch(err) {}
  if (apik) {
    // this is just useful for testing...
    oab.debugLog('Got api key ' + apik + ' direct from url param for testing');
    api_key = apik;
  } else {
    oab.displayMessage('(you are on the test page - you can provide an apikey url param to override this msg).
' + noapimsg);
  }
  start();
}

// =============================================
// bind actions to the elements

var needs = document.getElementsByClassName('need');
for ( var n in needs ) {
  needs[n].onclick = function(e) {
    var href = e.target.getAttribute('href');
    if (href === undefined || href === null) href = e.target.parentNode.getAttribute('href');
    var type = e.target.getAttribute('data-type');
    if (type === undefined || type === null) type = e.target.parentNode.getAttribute('data-type');
    var supports = e.target.getAttribute('data-support');
    if (supports === undefined || supports === null) supports = e.target.parentNode.getAttribute('data-support');
    document.getElementById('story_div').className = 'collapse';
    oab.displayMessage('');
    if ( href === '#' && api_key ) {
      e.preventDefault();
      var action = e.target.getAttribute('data-action');
      if (action === undefined || action === null) action = e.target.parentNode.getAttribute('data-action');
      if (action === 'created' || action === 'supported') {
        var u = oab.site_address + '/request/' + supports;
        var dm = '
You already ' + action + ' a request for this ' + type + '.
';
        dm += 'open the request
';
        oab.displayMessage(dm);
        if (chrome && chrome.tabs) {
          document.getElementById('goto_request').onclick = function () {
            chrome.tabs.create({'url': oab.site_address + '/request/' + supports});
          };
        }
      } else {
        var ask = action === 'support' ? 'Someone else has started a request for this ' + type + '. Add your support. ' : 'Create a new ' + type + ' request. ';
        ask += 'How would getting access to this ' + type + ' help you?';
        if (action !== 'support') ask += 'This message will be sent to the author.';
        document.getElementById('story').setAttribute('placeholder',ask);
        document.getElementById('submit').setAttribute('data-type',type);
        document.getElementById('submit').setAttribute('data-support',supports);
        document.getElementById('submit').setAttribute('data-action',action);
        if ( action === 'support' ) {
          document.getElementById('submit').innerHTML = document.getElementById('submit').innerHTML.replace('create','support');
        } else {
          document.getElementById('submit').innerHTML = document.getElementById('submit').innerHTML.replace('support','create');
        }
        document.getElementById('story_div').className = '';
      }
    } else if (chrome && chrome.tabs && api_key) {
      chrome.tabs.create({'url': href});
    } else {
      e.preventDefault();
    }
  }
}

document.getElementById('submit').onclick = function (e) {
  document.getElementById('submit').className = 'collapse';
  document.getElementById('icon_submitting').className = '';
  var data = {
    story: document.getElementById('story').value
  };
  var action = document.getElementById('submit').getAttribute('data-action');
  if ( action === 'create' ) {
    data.type = document.getElementById('submit').getAttribute('data-type');
    data.url = page_url;
    try {
      chrome.storage.local.get({dom : ''}, function(items) {
        if (items.dom !== '') data.dom = items.dom;
        oab.sendRequestPost(api_key, data, handleRequestResponse, oab.handleAPIError);
      });
    } catch (err) {
      oab.sendRequestPost(api_key, data, handleRequestResponse, oab.handleAPIError);
    }
  } else {
    data._id = document.getElementById('submit').getAttribute('data-support');
    oab.sendSupportPost(api_key, data, handleRequestResponse, oab.handleAPIError);
  }
};

document.getElementById('story').onkeyup = function () {
  var length = document.getElementById('story').value.replace(/  +/g,' ').split(' ').length;
  var left = 25 - length;
  if (left < 0) {
    left = 0;
  }
  if (length === 0) {
    document.getElementById('submit').innerHTML = 'Say why you need this in up to
25 words to support this request';
    document.getElementById('submit').style.backgroundColor = '#f04717';
  }
  if (length <= 5) {
    document.getElementById('submit').innerHTML = 'Tell us your reason with up to
 more words to support this request';
    document.getElementById('submit').style.backgroundColor = '#f04717';
  }
  if ( left < 25 && length > 5 ) {
    document.getElementById('submit').removeAttribute('disabled');
  } else {
    document.getElementById('submit').setAttribute('disabled',true);
  }
  if (length > 5 && length <= 10) {
    document.getElementById('submit').innerHTML = 'Great,  words remaining!
Write a few more?';
    document.getElementById('submit').style.backgroundColor = '#ffff66';
  }
  if (length > 10 && length <= 20) {
    document.getElementById('submit').innerHTML = ' words left! Or click to submit
now and create your request!';
    document.getElementById('submit').style.backgroundColor = '#99ff99';
  }
  if (length > 20) {
    document.getElementById('submit').innerHTML = '... Click now to submit your
reason and create your request';
    document.getElementById('submit').style.backgroundColor = '#99ff99';
  }
  document.getElementById('counter').innerHTML = left;
};
<|endoftext|>


<commit_before><commit_msg>update<commit_after><|endoftext|>


<commit_before>PlayState = {};

PlayState.preload = function() {
  this.game.load.image('background', 'images/background.png');
};

PlayState.create = function() {
  this.game.add.image(0, 0, 'background');
};

window.onload = function() {
  let game = new Phaser.Game(960, 600, Phaser.AUTO, 'game');
  game.state.add('play', PlayState);
  game.state.start('play');
};
<commit_msg>Create platforms<commit_after>PlayState = {};

PlayState.preload = function() {
  this.game.load.json('level:1', 'data/level01.json');
  this.game.load.image('background', 'images/background.png');
  this.game.load.image('ground', 'images/ground.png');
  this.game.load.image('grass:8x1', 'images/grass_8x1.png');
  this.game.load.image('grass:6x1', 'images/grass_6x1.png');
  this.game.load.image('grass:4x1', 'images/grass_4x1.png');
  this.game.load.image('grass:2x1', 'images/grass_2x1.png');
  this.game.load.image('grass:1x1', 'images/grass_1x1.png');
};

PlayState.create = function() {
  this.game.add.image(0, 0, 'background');
  this._loadLevel(this.game.cache.getJSON('level:1'));
};

PlayState._loadLevel = function(data) {
  data.platforms.forEach(this._spawnPlatform, this);
};

PlayState._spawnPlatform = function(platform) {
  this.game.add.sprite(platform.x, platform.y, platform.image);
};

window.onload = function() {
  let game = new Phaser.Game(960, 600, Phaser.AUTO, 'game');
  game.state.add('play', PlayState);
  game.state.start('play');
};
<|endoftext|>


<commit_before>function memoryTestInit()
{
    var delay = 33,
        step = 648,
        curMemory = 0,
        memory = 26732;

    $("#output").append("
Memory Test : 0K
");

    function updateMemory()
    {
        curMemory += step;
        $("#memoryTestNumber").html(curMemory+"K");
        if (curMemory < memory)
        {
            window.setTimeout(updateMemory, delay);
        }
        else
        {
            $("#memoryTest").append(" OK");
            $("#output").append("
");
            randomStuff();
        };
    }

    updateMemory();
}

function randomStuff()
{
    var delay = 300,
        strings = ["Setting parameters of disk 1", "Loading kernel modules","Cleaning up temporary files","Scanning for devices","Waiting for devices to settle","
 Starting SpookyOS"],
        current = 0,
        dots = 0;

    $("#output").append("
");

    function showStuff()
    {
        var temp = "";
        if (!$("#random"+current).length)
        {
            $("#output").append("
"+strings[current]+"
");
        }
        for (var i = 0; i < dots; i++)
        {
            //$("#dots"+devices[current]).append(".");
            temp+=".";
        }
        $("#dots"+current).html(temp);
        if (dots < 4)
        {
            dots++;
            window.setTimeout(showStuff, delay+Math.random()*100-50);
        }
        else
        {
            dots = 0;
            $("#random"+current).append("  DONE");
            if (current < strings.length-1)
            {
                current++
                window.setTimeout(showStuff, delay+Math.random()*100-50);
            }
            else
            {
                window.setTimeout(spookyOs, 1000);
            }
        }
    }
    showStuff();
}
function spookyOs()
{
    $("#output").append("
");
    $("#output").append("

Welcome To SpookyOS

");
    $("#output").append("

SpookyOS [Version 2.4.3600] Copyright (c) 2015 Spooky Corporation. All Rights Reserved.

");
    showCommands();
}
function showCommands()
{
    $("#output").append("
Commands
");
    $("#output").append("
help    - Show this help
");
    $("#output").append("
about    - Some information about me
");
    $("#output").append("
projects - Show projects I've worked on
");
    $("#output").append("
github  - Open My Github Page
");
    $("#output").append("
twitter - Open My Twitter Page
");
    $("#output").append("
reddit  - Open My Reddit Page
");
    $("#output").append("
steam   - Open My Steam Page

");
    $("#inputContainer").css("visibility","visible")
    $('#i')[0].focus();
}

function showProjects()
{
    $("#output").append("
ChromeBait - <https://github.com/Rabrennie/ChromeBait>
");
    $("#output").append("
- A chrome extension that turns the clickbait dial to 11.

");
    $("#output").append("
Spookie Clicker - <http://rabrennie.com/spookies>
");
    $("#output").append("
- A Small incremental game about Bill Murray, Spiders and Spooky Skellingtons

");
}
function showInfo()
{
    $("#output").append("
Hi, I am a 17 year old Software Development Student in Scotland. You can find my projects on github. You can contact me through email at rennierab@gmail.com or through any of the sites I have provided links for.

");
}
function openURL(url)
{
    $("#output").append("
Opening "+url+"

");
    window.open(url);
}
function showSkellington()
{
    $("#output").append("
▒▒▒░░░░░░░░░░▄▐░░░░
");
    $("#output").append("
▒░░░░░░▄▄▄░░▄██▄░░░
");
    $("#output").append("
░░░░░░▐▀█▀▌░░░░▀█▄░
");
    $("#output").append("
░░░░░░▐█▄█▌░░░░░░▀█▄
");
    $("#output").append("
░░░░░░░▀▄▀░░░▄▄▄▄▄▀▀
");
    $("#output").append("
░░░░░▄▄▄██▀▀▀▀░░░░░
");
    $("#output").append("
░░░░█▀▄▄▄█░▀▀░░░░░░
");
    $("#output").append("
░░░░▌░▄▄▄▐▌▀▀▀░░░░░
");
    $("#output").append("
░▄░▐░░░▄▄░█░▀▀░░░░░
");
    $("#output").append("
░▀█▌░░░▄░▀█▀░▀░░░░░
");
    $("#output").append("
░░░░░░░░▄▄▐▌▄▄░░░░░
");
    $("#output").append("
░░░░░░░░▀███▀█░▄░░░
");
    $("#output").append("
░░░░░░░▐▌▀▄▀▄▀▐▄░░░
");
    $("#output").append("
░░░░░░░▐▀░░░░░░▐▌░░
");
    $("#output").append("
░░░░░░░█░░░░░░░░█░░
");
    $("#output").append("
░░░░░░▐▌░░░░░░░░░█░

");
}
function inputHandler(s)
{
    if (s != "")
    {
        $("#output").append("
> "+s+"
");
        switch (s)
        {
            case "help":
                showCommands();
                break;
            case "about":
                showInfo();
                break;
            case "github":
                openURL("https://github.com/Rabrennie");
                break;
            case "twitter":
                openURL("https://twitter.com/SpookyCo");
                break;
            case "reddit":
                openURL("https://www.reddit.com/user/SpookyCo/");
                break;
            case "steam":
                openURL("http://steamcommunity.com/id/spookyco");
                break;
            case "projects":
                showProjects();
                break;
            case "spooky":
                showSkellington();
                break;
            default: $("#output").append("
Unknown Command
");
        }
    }
}

$( "#i" ).keypress(function(e)
{
	if (e.keyCode == 13)
	{
		inputHandler(this.value);
		this.value = "";
        $("html, body").animate({ scrollTop: $(document).height()-$(window).height()});
	};
});

//keeps focus on input element
var el = $('#i')[0];
el.focus();
el.onblur = function () {
    setTimeout(function () {
        el.focus();
    });
};

memoryTestInit();
<commit_msg>Added different screens to the boot proccess<commit_after>function biosTestInit()
{
    var delay = 33,
        step = 648,
        curMemory = 0,
        memory = 26732,
        counter = 0,
        lines = ["SpookyBIOS V2.42 (c) 2015 Spooky Corporation.",
                "BIOS Date : 22/07/2015, 20:05:45",
                "
",
                "Main Processor : Qualvidia III 2GHz",
                "CPU Power : 1.21 Jiggawatts",
                "
",
                "Total Memory : 27216K"];

    function printLines()
    {

        $("#output").append("
"+lines[counter]+"
");
        if (counter < lines.length-1)
        {
            counter++
            window.setTimeout(printLines, 300);
        }
        else
        {
            window.setTimeout(initMemory, 300);
        };
    }

    function initMemory()
    {
        $("#output").append("
Memory Test : 0K
");
        updateMemory();
    }

    function updateMemory()
    {
        curMemory += step;
        $("#memoryTestNumber").html(curMemory+"K");
        if (curMemory < memory)
        {
            window.setTimeout(updateMemory, delay);
        }
        else
        {
            $("#memoryTest").append(" OK");
            $("#output").append("
");

            window.setTimeout(function(){clearScreen(randomStuff);}, 500);
        };
    }

    printLines();
}

function clearScreen(callback)
{
    $("#output").html("");
    callback();
}

function randomStuff()
{
    var delay = 300,
        strings = ["Setting parameters of disk 1", "Loading kernel modules","Cleaning up temporary files","Scanning for devices","Waiting for devices to settle","
 Starting SpookyOS"],
        current = 0,
        dots = 0;

    function showStuff()
    {
        var temp = "";
        if (!$("#random"+current).length)
        {
            $("#output").append("
"+strings[current]+"
");
        }
        for (var i = 0; i < dots; i++)
        {
            //$("#dots"+devices[current]).append(".");
            temp+=".";
        }
        $("#dots"+current).html(temp);
        if (dots < 4)
        {
            dots++;
            window.setTimeout(showStuff, delay+Math.random()*100-50);
        }
        else
        {
            dots = 0;
            $("#random"+current).append("  DONE");
            if (current < strings.length-1)
            {
                current++
                window.setTimeout(showStuff, delay+Math.random()*100-50);
            }
            else
            {
                window.setTimeout(function(){clearScreen(spookyOs);}, 500);
            }
        }
    }
    showStuff();
}
function spookyOs()
{
    $("#output").append("

Welcome To SpookyOS

");
    $("#output").append("

SpookyOS [Version 2.4.3600] Copyright (c) 2015 Spooky Corporation. All Rights Reserved.

");
    showCommands();
}
function showCommands()
{
    $("#output").append("
Commands
");
    $("#output").append("
help    - Show this help
");
    $("#output").append("
about    - Some information about me
");
    $("#output").append("
projects - Show projects I've worked on
");
    $("#output").append("
github  - Open My Github Page
");
    $("#output").append("
twitter - Open My Twitter Page
");
    $("#output").append("
reddit  - Open My Reddit Page
");
    $("#output").append("
steam   - Open My Steam Page

");
    $("#inputContainer").css("visibility","visible")
    $('#i')[0].focus();
}

function showProjects()
{
    $("#output").append("
ChromeBait - <https://github.com/Rabrennie/ChromeBait>
");
    $("#output").append("
- A chrome extension that turns the clickbait dial to 11.

");
    $("#output").append("
Spookie Clicker - <http://rabrennie.com/spookies>
");
    $("#output").append("
- A Small incremental game about Bill Murray, Spiders and Spooky Skellingtons

");
}
function showInfo()
{
    $("#output").append("
Hi, I am a 17 year old Software Development Student in Scotland. You can find my projects on github. You can contact me through email at rennierab@gmail.com or through any of the sites I have provided links for.

");
}
function openURL(url)
{
    $("#output").append("
Opening "+url+"

");
    window.open(url);
}
function showSkellington()
{
    $("#output").append("
▒▒▒░░░░░░░░░░▄▐░░░░
");
    $("#output").append("
▒░░░░░░▄▄▄░░▄██▄░░░
");
    $("#output").append("
░░░░░░▐▀█▀▌░░░░▀█▄░
");
    $("#output").append("
░░░░░░▐█▄█▌░░░░░░▀█▄
");
    $("#output").append("
░░░░░░░▀▄▀░░░▄▄▄▄▄▀▀
");
    $("#output").append("
░░░░░▄▄▄██▀▀▀▀░░░░░
");
    $("#output").append("
░░░░█▀▄▄▄█░▀▀░░░░░░
");
    $("#output").append("
░░░░▌░▄▄▄▐▌▀▀▀░░░░░
");
    $("#output").append("
░▄░▐░░░▄▄░█░▀▀░░░░░
");
    $("#output").append("
░▀█▌░░░▄░▀█▀░▀░░░░░
");
    $("#output").append("
░░░░░░░░▄▄▐▌▄▄░░░░░
");
    $("#output").append("
░░░░░░░░▀███▀█░▄░░░
");
    $("#output").append("
░░░░░░░▐▌▀▄▀▄▀▐▄░░░
");
    $("#output").append("
░░░░░░░▐▀░░░░░░▐▌░░
");
    $("#output").append("
░░░░░░░█░░░░░░░░█░░
");
    $("#output").append("
░░░░░░▐▌░░░░░░░░░█░

");
}
function inputHandler(s)
{
    if (s != "")
    {
        $("#output").append("
> "+s+"
");
        switch (s)
        {
            case "help":
                showCommands();
                break;
            case "about":
                showInfo();
                break;
            case "github":
                openURL("https://github.com/Rabrennie");
                break;
            case "twitter":
                openURL("https://twitter.com/SpookyCo");
                break;
            case "reddit":
                openURL("https://www.reddit.com/user/SpookyCo/");
                break;
            case "steam":
                openURL("http://steamcommunity.com/id/spookyco");
                break;
            case "projects":
                showProjects();
                break;
            case "spooky":
                showSkellington();
                break;
            default: $("#output").append("
Unknown Command
");
        }
    }
}

$( "#i" ).keypress(function(e)
{
	if (e.keyCode == 13)
	{
		inputHandler(this.value);
		this.value = "";
        $("html, body").animate({ scrollTop: $(document).height()-$(window).height()});
	};
});

//keeps focus on input element
var el = $('#i')[0];
el.focus();
el.onblur = function () {
    setTimeout(function () {
        el.focus();
    });
};

biosTestInit();
<|endoftext|>