<commit_before>/**
 * Main AngularJS Web Application
 */
var app = angular.module('ApparelApp', [
  'ngRoute'
]);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "partials/home.html", controller: "HomeCtrl"})
    // Pages
    .when("/house", {templateUrl: "partials/house.html", controller: "HouseCtrl"})
    .when("/articles", {templateUrl: "partials/articles.html", controller: "ArticleCtrl"})
    .when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
    .when("/contact/success", {templateUrl: "partials/contact_success.html", controller: "PageCtrl"})

    //PROJECTS
    .when('/projectDetail/:link', {
        templateUrl: function(params) {
            if (params.link != "") {
                return 'partials/'+params.link+'.html';
            }

            return 'partials/404.html';
        },
       controller: 'ProjectDetailCtrl'
    })
    // else 404
    .when("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"})
    .otherwise({redirectTo: '/404'});

}]);

app.controller("ArticleCtrl", function($scope, $http) {
      var store = this;
      store.articles = [];

      $http({
        method: 'GET',
        url: 'http://localhost/ERP-Apparel-Back/web/app_dev.php/articles/website/7'
      }).then(function successCallback(response) {
          // this callback will be called asynchronously
          // when the response is available

        store.articles = response.data;
        console.log(response);
        console.log(store.articles);

        }, function errorCallback(response) {
          // called asynchronously if an error occurs
          // or server returns response with an error status.
        });
});

app.controller('HouseCtrl', function ($scope) {
    $scope.load = function() {
        $(document).ready(function(){
            $('.parallax').parallax();
        });
    };

   //don't forget to call the load function
   $scope.load();
});
/**
 * Controls Home Page.
 */
app.controller('HomeCtrl', function (/* $scope, $location, $http */) {

});

app.controller('PageCtrl', function (/* $scope, $location, $http */) {
    console.log('Page Generale');
});

<commit_msg>adaptation à la base de matt!<commit_after>/**
 * Main AngularJS Web Application
 */
var app = angular.module('ApparelApp', [
  'ngRoute'
]);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "partials/home.html", controller: "HomeCtrl"})
    // Pages
    .when("/house", {templateUrl: "partials/house.html", controller: "HouseCtrl"})
    .when("/articles", {templateUrl: "partials/articles.html", controller: "ArticleCtrl"})
    .when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
    .when("/contact/success", {templateUrl: "partials/contact_success.html", controller: "PageCtrl"})

    //PROJECTS
    .when('/projectDetail/:link', {
        templateUrl: function(params) {
            if (params.link != "") {
                return 'partials/'+params.link+'.html';
            }

            return 'partials/404.html';
        },
       controller: 'ProjectDetailCtrl'
    })
    // else 404
    .when("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"})
    .otherwise({redirectTo: '/404'});

}]);

app.controller("ArticleCtrl", function($scope, $http) {
      var store = this;
      store.articles = [];

      $http({
        method: 'GET',
        url: 'http://localhost/ERP-Apparel-Back/web/app_dev.php/articles/website/1'
      }).then(function successCallback(response) {
          // this callback will be called asynchronously
          // when the response is available

        store.articles = response.data;
        console.log(response);
        console.log(store.articles);

        }, function errorCallback(response) {
          // called asynchronously if an error occurs
          // or server returns response with an error status.
        });
});

app.controller('HouseCtrl', function ($scope) {
    $scope.load = function() {
        $(document).ready(function(){
            $('.parallax').parallax();
        });
    };

   //don't forget to call the load function
   $scope.load();
});
/**
 * Controls Home Page.
 */
app.controller('HomeCtrl', function (/* $scope, $location, $http */) {

});

app.controller('PageCtrl', function (/* $scope, $location, $http */) {
    console.log('Page Generale');
});
<|endoftext|>


<commit_before>var $ = document.querySelectorAll.bind(document);

var GAME = {
	board: new Board()
}

var $grid = $('.grid')[0]
Events.on('move', function(move) {
	if (move.fromRow === move.toRow && move.fromCol === move.toCol) return;
	var $tiles = $('.tile-'+move.fromRow+'-'+move.fromCol)
	var $old = $('.tile-'+move.toRow+'-'+move.toCol)[0]
	for(var i=0;i<$tiles.length;i++) {
		$tiles[i].className = $tiles[i].className.replace(/tile-\d-\d/, 'tile-'+move.toRow+'-'+move.toCol)
	}

	if ($old) {
		setTimeout(function() {
			try {
				for(var i=0;i<$tiles.length;i++) {
						$tiles[i].parentElement.removeChild($tiles[i])
				}
			} catch(e) {
			}
		}, 1000)
	}
})

Events.on('spawn', function(spawn) {
	var $div = document.createElement('div')
	var $tile = document.createElement('div')
	$tile.setAttribute('class', 'tile '+'tile-'+spawn.row+'-'+spawn.col+' tile-phase-'+(spawn.color-1))
	$div.setAttribute('class', 'tile-inner')
	$tile.appendChild($div)
	$grid.appendChild($tile)
})

var maxColor = 1
Events.on('setColor', function(elem) {
	var $tiles = $('.tile-'+elem.row+'-'+elem.col)
	try {
		for(var i=0;i<$tiles.length;i++) {
			$tiles[i].className = $tiles[i].className.replace(/tile-phase-\d/, 'tile-phase-'+(elem.color-1))
		}

		if (elem.color > maxColor) {
			maxColor = elem.color
			$progress = $('#progress-cover')[0]
			$progress.className = $progress.className.replace(/progress-\d/, 'progress-'+(maxColor-1))
		}
	} catch (e) {}
})

// super hack to prevent multiple buttons spawning end of game
var gameOverOnce = false
Events.on('gameOver', function() {
	maxColor = 0
	var $infoScreen = document.getElementById('info-screen')
	$infoScreen.className = 'show'
	var $gameOverBox = document.getElementById('game-over-box')
	$gameOverBox.style.display = 'block'

	var $challengeButton = document.createElement('button')
	$challengeButton.innerHTML = 'Challenge a Friend'
	// Should add some sort of fastclick here... (touch first)
	$challengeButton.addEventListener('click', function() {
		Events.emit('challengeFriend')
	})

	// move the score element inside this div, we move back to it's original spot when a new game is started
	var $scoreWrapperEle = $('.bubble-wrapper')[0]
	if($scoreWrapperEle) {
		$scoreWrapperEle.style.zIndex = 10 // show above game over box. we want it below the tutorial tips at start though
		$gameOverBox.appendChild($scoreWrapperEle)
	}

	var $shareBubble = $('.share-bubble')[0]
	if($shareBubble)
		$shareBubble.style.display = 'none'

	if (!gameOverOnce) {
		var $gameOverButton = document.createElement('button')
		$gameOverButton.innerHTML = 'Play Again'
		$gameOverButton.className = 'play-again'
		// Should add some sort of fastclick here... (touch first)
		$gameOverButton.addEventListener('click', function() {
			Events.emit('restartGame')
		})

		$gameOverBox.appendChild($challengeButton)
		$gameOverBox.appendChild($gameOverButton)
		gameOverOnce = true
	}

	// move the score element inside this div, we move back to it's original spot when a new game is started
	var $scoreWrapperEle = $('.bubble-wrapper')[0]
	if($scoreWrapperEle)
		$gameOverBox.appendChild($scoreWrapperEle)
})

Events.on('challengeFriend', function() {
	var score = GAME.board.score;
	Clay.Social.smartShare({
		message: 'I just scored ' + score + ' in Prism! Think you can beat my score?',
		title: 'Prism',
		link: 'http://prism.clay.io',
		//image: screenshotURL,
		ignoreScreenshot: true,
		data: {},
		//respond: // the username of our opponent // cards.kik.returnToConversation
	})
})

Events.on('restartGame', function() {
	$('.grid')[0].innerHTML = ''
	document.getElementById('progress-cover').className = 'progress-0'
	document.getElementById('info-screen').className = 'hide'
	// move the score element back to where it was before
	var $scoreWrapperEle = $('.bubble-wrapper')[0]
	if($scoreWrapperEle)
		document.body.appendChild($scoreWrapperEle)

	var $shareBubble = $('.share-bubble')[0]
	if($shareBubble)
		$shareBubble.style.display = 'inline-block'

	GAME.board.newGame()
})

$scoreEle = $('#score')[0]
Events.on('score', function(score) {
	$scoreEle.innerHTML = score;
})

// keybindings
var move = 'left';
Hammer(window, {
	drag_min_distance:5,
	drag_block_horizontal:true,
	drag_block_vertical:true
}).on("dragleft", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='left'
}).on("dragright", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='right'
}).on("dragup", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='up'
}).on("dragdown", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='down'
}).on('dragend', function(e) {
	GAME.board.move(move)
})

Mousetrap.bind(['up', 'down', 'left', 'right'], function(e) {
	e.preventDefault()
	var key = e.keyIdentifier
	if(!key) { // firefox
		switch(e.which) {
			case 40:
				key = 'Down';
				break;
			case 39:
				key = 'Right';
				break;
			case 37:
				key = 'Left';
				break;
			case 38:
				key = 'Up';
				break;
		}
	}
	GAME.board.move(key.toLowerCase())
});

if (typeof kik !== 'undefined') {
    kik.browser.back(function() {
        if (GAME.board.isGameOver) {
            Events.emit('restartGame')
            return false
        }
        return true
    });
}

// init
// Run the tutorial for first-time visitors
if(!localStorage['tutorial-shown']) {

	// row, col, color
	GAME.board.newGame([[2,1,1],[2,2,1]])
	GAME.tutorial = new Tutorial([2, 1])
	localStorage['tutorial-shown'] = 1
} else {
	GAME.board.newGame()
}

window.addEventListener('load', function() {
	// Load clay API
	window.Clay = window.Clay || {};
	Clay.gameKey = "prism";
	Clay.readyFunctions = [];
	Clay.ready = function( fn ) {
		Clay.readyFunctions.push( fn );
	};
	( function() {
		var clay = document.createElement("script"); clay.async = true;
		//clay.src = ( "https:" == document.location.protocol ? "https://" : "http://" ) + "clay.io/api/api.js";
		clay.src = "http://cdn.clay.io/api.js";
		var tag = document.getElementsByTagName("script")[0]; tag.parentNode.insertBefore(clay, tag);
	} )();

	// Load GA
	(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

	ga('create', 'UA-27992080-1', 'clay.io');
	ga('send', 'pageview');

	// Load in sharing buttons
	if(cards.kik) {
		kik.metrics.enableGoogleAnalytics() // track messages sent
		var $brand = $('.brand')[0]
		$brand.style.display = 'none'
		var $share = document.createElement('a')
		$share.className = 'kik-share'
		$share.href = '#'
		$share.id = 'kik-share'
		$share.innerHTML = "share!"
		$share.addEventListener('touchstart', function() {
			Clay.Kik.post({
				message: 'Come play Prism, the most addicting game on Kik!',
				title: 'Prism',
				data: {}
			})
		})
		document.getElementById('share').appendChild($share)
	}
	else {
		var html = ''
		html += ''
		document.getElementById('share').innerHTML = html

		var html = ''
		html += ""
		html += "
"
		html += "	We ♥ HTML5 Games"
		html += "	· We're hiring"
		html += "	· contact@clay.io"
		html += "
"
		document.getElementById('brand').innerHTML = html
	}
})

function sizing() {
	var gridWidth = window.innerWidth
	var gridHeight = window.innerHeight - $('.grid-inner')[0].offsetTop * 2 // .grid-outer padding
	var boxSize = Math.min(gridWidth, gridHeight) * 0.94 // 3% css padding
	$('.grid-background')[0].style.width = boxSize + 'px'
	$('.grid-background')[0].style.height = (boxSize - 14) + 'px' // 7px  padding
}
sizing()
$grid.style.visibility = 'visible'
$('.grid-background')[0].style.visibility = 'visible'
window.onresize = sizing
<commit_msg>kik back button tweak;<commit_after>var $ = document.querySelectorAll.bind(document);

var GAME = {
	board: new Board()
}

var $grid = $('.grid')[0]
Events.on('move', function(move) {
	if (move.fromRow === move.toRow && move.fromCol === move.toCol) return;
	var $tiles = $('.tile-'+move.fromRow+'-'+move.fromCol)
	var $old = $('.tile-'+move.toRow+'-'+move.toCol)[0]
	for(var i=0;i<$tiles.length;i++) {
		$tiles[i].className = $tiles[i].className.replace(/tile-\d-\d/, 'tile-'+move.toRow+'-'+move.toCol)
	}

	if ($old) {
		setTimeout(function() {
			try {
				for(var i=0;i<$tiles.length;i++) {
						$tiles[i].parentElement.removeChild($tiles[i])
				}
			} catch(e) {
			}
		}, 1000)
	}
})

Events.on('spawn', function(spawn) {
	var $div = document.createElement('div')
	var $tile = document.createElement('div')
	$tile.setAttribute('class', 'tile '+'tile-'+spawn.row+'-'+spawn.col+' tile-phase-'+(spawn.color-1))
	$div.setAttribute('class', 'tile-inner')
	$tile.appendChild($div)
	$grid.appendChild($tile)
})

var maxColor = 1
Events.on('setColor', function(elem) {
	var $tiles = $('.tile-'+elem.row+'-'+elem.col)
	try {
		for(var i=0;i<$tiles.length;i++) {
			$tiles[i].className = $tiles[i].className.replace(/tile-phase-\d/, 'tile-phase-'+(elem.color-1))
		}

		if (elem.color > maxColor) {
			maxColor = elem.color
			$progress = $('#progress-cover')[0]
			$progress.className = $progress.className.replace(/progress-\d/, 'progress-'+(maxColor-1))
		}
	} catch (e) {}
})

// super hack to prevent multiple buttons spawning end of game
var gameOverOnce = false
Events.on('gameOver', function() {
	maxColor = 0
	var $infoScreen = document.getElementById('info-screen')
	$infoScreen.className = 'show'
	var $gameOverBox = document.getElementById('game-over-box')
	$gameOverBox.style.display = 'block'

	var $challengeButton = document.createElement('button')
	$challengeButton.innerHTML = 'Challenge a Friend'
	// Should add some sort of fastclick here... (touch first)
	$challengeButton.addEventListener('click', function() {
		Events.emit('challengeFriend')
	})

	// move the score element inside this div, we move back to it's original spot when a new game is started
	var $scoreWrapperEle = $('.bubble-wrapper')[0]
	if($scoreWrapperEle) {
		$scoreWrapperEle.style.zIndex = 10 // show above game over box. we want it below the tutorial tips at start though
		$gameOverBox.appendChild($scoreWrapperEle)
	}

	var $shareBubble = $('.share-bubble')[0]
	if($shareBubble)
		$shareBubble.style.display = 'none'

	if (!gameOverOnce) {
		var $gameOverButton = document.createElement('button')
		$gameOverButton.innerHTML = 'Play Again'
		$gameOverButton.className = 'play-again'
		// Should add some sort of fastclick here... (touch first)
		$gameOverButton.addEventListener('click', function() {
			Events.emit('restartGame')
		})

		$gameOverBox.appendChild($challengeButton)
		$gameOverBox.appendChild($gameOverButton)
		gameOverOnce = true
	}

	// move the score element inside this div, we move back to it's original spot when a new game is started
	var $scoreWrapperEle = $('.bubble-wrapper')[0]
	if($scoreWrapperEle)
		$gameOverBox.appendChild($scoreWrapperEle)
})

Events.on('challengeFriend', function() {
	var score = GAME.board.score;
	Clay.Social.smartShare({
		message: 'I just scored ' + score + ' in Prism! Think you can beat my score?',
		title: 'Prism',
		link: 'http://prism.clay.io',
		//image: screenshotURL,
		ignoreScreenshot: true,
		data: {},
		//respond: // the username of our opponent // cards.kik.returnToConversation
	})
})

Events.on('restartGame', function() {
	$('.grid')[0].innerHTML = ''
	document.getElementById('progress-cover').className = 'progress-0'
	document.getElementById('info-screen').className = 'hide'
	// move the score element back to where it was before
	var $scoreWrapperEle = $('.bubble-wrapper')[0]
	if($scoreWrapperEle)
		document.body.appendChild($scoreWrapperEle)

	var $shareBubble = $('.share-bubble')[0]
	if($shareBubble)
		$shareBubble.style.display = 'inline-block'

	GAME.board.newGame()
})

$scoreEle = $('#score')[0]
Events.on('score', function(score) {
	$scoreEle.innerHTML = score;
})

// keybindings
var move = 'left';
Hammer(window, {
	drag_min_distance:5,
	drag_block_horizontal:true,
	drag_block_vertical:true
}).on("dragleft", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='left'
}).on("dragright", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='right'
}).on("dragup", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='up'
}).on("dragdown", function(e) {
	e.preventDefault()
	e.gesture.preventDefault()
	move='down'
}).on('dragend', function(e) {
	GAME.board.move(move)
})

Mousetrap.bind(['up', 'down', 'left', 'right'], function(e) {
	e.preventDefault()
	var key = e.keyIdentifier
	if(!key) { // firefox
		switch(e.which) {
			case 40:
				key = 'Down';
				break;
			case 39:
				key = 'Right';
				break;
			case 37:
				key = 'Left';
				break;
			case 38:
				key = 'Up';
				break;
		}
	}
	GAME.board.move(key.toLowerCase())
});

// init
// Run the tutorial for first-time visitors
if(!localStorage['tutorial-shown']) {

	// row, col, color
	GAME.board.newGame([[2,1,1],[2,2,1]])
	GAME.tutorial = new Tutorial([2, 1])
	localStorage['tutorial-shown'] = 1
} else {
	GAME.board.newGame()
}

window.addEventListener('load', function() {
	// Load clay API
	window.Clay = window.Clay || {};
	Clay.gameKey = "prism";
	Clay.readyFunctions = [];
	Clay.ready = function( fn ) {
		Clay.readyFunctions.push( fn );
	};
	( function() {
		var clay = document.createElement("script"); clay.async = true;
		//clay.src = ( "https:" == document.location.protocol ? "https://" : "http://" ) + "clay.io/api/api.js";
		clay.src = "http://cdn.clay.io/api.js";
		var tag = document.getElementsByTagName("script")[0]; tag.parentNode.insertBefore(clay, tag);
	} )();

	// Load GA
	(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
	m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

	ga('create', 'UA-27992080-1', 'clay.io');
	ga('send', 'pageview');

	// Load in sharing buttons
	if(cards.kik) {
		kik.browser.back(function() {
		  if (GAME.board.isGameOver) {
			Events.emit('restartGame')
			return false
		  }
		  return true
		})

		kik.metrics.enableGoogleAnalytics() // track messages sent
		var $brand = $('.brand')[0]
		$brand.style.display = 'none'
		var $share = document.createElement('a')
		$share.className = 'kik-share'
		$share.href = '#'
		$share.id = 'kik-share'
		$share.innerHTML = "share!"
		$share.addEventListener('touchstart', function() {
			Clay.Kik.post({
				message: 'Come play Prism, the most addicting game on Kik!',
				title: 'Prism',
				data: {}
			})
		})
		document.getElementById('share').appendChild($share)
	}
	else {
		var html = ''
		html += ''
		document.getElementById('share').innerHTML = html

		var html = ''
		html += ""
		html += "
"
		html += "	We ♥ HTML5 Games"
		html += "	· We're hiring"
		html += "	· contact@clay.io"
		html += "
"
		document.getElementById('brand').innerHTML = html
	}
})

function sizing() {
	var gridWidth = window.innerWidth
	var gridHeight = window.innerHeight - $('.grid-inner')[0].offsetTop * 2 // .grid-outer padding
	var boxSize = Math.min(gridWidth, gridHeight) * 0.94 // 3% css padding
	$('.grid-background')[0].style.width = boxSize + 'px'
	$('.grid-background')[0].style.height = (boxSize - 14) + 'px' // 7px  padding
}
sizing()
$grid.style.visibility = 'visible'
$('.grid-background')[0].style.visibility = 'visible'
window.onresize = sizing
<|endoftext|>


<commit_before>function Square(row, column, playable) {
  this.row = row;
  this.column = column;
  this.playable = playable;
  this.occupied = false;
};

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

Piece.prototype.availableMoves = function() {
  // Highlights the moves available to the man
  // Determine direction the man is moving (team, basically)
  // Determine 'king' value
  // Determine if possible destinations are occupied

  // Loop that finds the squares?
  var possibleSquare1 = board[this.row + 1][this.column - 1];
  var possibleSquare2 = board[this.row + 1][this.column + 1];
  if (possibleSquare1.occupied === true) {
    possibleSquare1 = board[this.row + 2][this.column - 2];
  };
  if (possibleSquare2.occupied === true) {
    possibleSquare2 = board[this.row + 2][this.column + 2];
  };

  $('#' + possibleSquare1.row + possibleSquare1.column).addClass('highlighted');
  $('#' + possibleSquare2.row + possibleSquare2.column).addClass('highlighted');
  $('#' + this.row + this.column).addClass('highlighted');

};

Piece.prototype.moveMan = function(destination) {
  // This will move the man
  // Changing coordinates
  // Capturing relevant pieces
  // Updating drawn position
  // Checking for possible chained moves
  // Occupy destination square
  // Unoccupy previous square
  board[this.row][this.column].occupied = false;
  this.row = destination.row;
  this.column = destination.column;
  board[this.row][this.column].occupied = true;
  // Update relevant values:
  // Last square > unoccupied
  // New square > occupied
  // Captured piece > out of play
  // Kinged man > kinged
};

var board = [];
var redTeam = [];
var whiteTeam = [];

// A simple looping function that puts eight arrays, representing rows, into
// the board array
function fillBoard() {
  for (var i = 0; i < 8; i++) {
    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').prepend('

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

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

'
            );
      } 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() {
  var team = 'red';
  var row = 0;
  var column = 1;
  // Creates 12 pieces for the team
  for (i = 0; i < 12; i++) {
    var idNum = i;
    redTeam[i] = new Piece(team, idNum, row, column);
  };
  for (i = 0; i < 3; i++) {
    redTeam[i*4].row = i;
    redTeam[i*4 + 1].row = i;
    redTeam[i*4 + 2].row = i;
    redTeam[i*4 + 3].row = i;
  };
  var n = 0;
  for (i = 0; i < 12; i++) {
    if (isOdd(redTeam[i].row)) {
      redTeam[i].column = n;
    } else {
      redTeam[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 < redTeam.length; i++) {
    board[redTeam[i].row][redTeam[i].column].occupied = true;
    $('#' + redTeam[i].row + redTeam[i].column).append(
        '

');
    // console.log(redTeam[i].id + ' is now at ' + redTeam[i].row + redTeam[i].column);
  };
  for (i = 0; i < whiteTeam.length; i++) {
    board[whiteTeam[i].row][whiteTeam[i].column].occupied = true;
    $('#' + whiteTeam[i].row + whiteTeam[i].column).append(
        '

');
  };
};

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

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

  return board[row][column];
};

$(document).ready(function() {
  // I DON'T LIKE THAT I DECLARE THESE HERE
  // TEMPORARY, MOVE THESE SOMEWHERE BETTER LATER
  var team = undefined;
  var selectedPiece = undefined;
  var currentSquare = undefined;
  var destinationSquare = undefined;

  $('.button').click(function() {
    $('.button').hide();
    fillBoard();
    drawBoard();
    createPieces();
    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
    // ******************************************
    // MOVE MOST ALL OF THIS TO THE PIECE OBJECTS

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

    selectedPiece.availableMoves();

    // Gets the Square{} that corresponds with the .playable element that has
    // been clicked by the player
    currentSquare = getSquare($(this).closest('.playable').attr('id'));

  });

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

    // ON SELF-CLICK, REMOVE HIGHLIGHTING
    if (currentSquare == destinationSquare) {
      $('.highlighted').removeClass('highlighted');
      return;
    };

    selectedPiece.moveMan(destinationSquare);

    $('.highlighted').removeClass('highlighted');

    // REDRAW THE BOARD FOR EACH UPDATE?
    // MAYBE AFTER I ADD BETTER HIGHLIGHTING LOGIC AND CLEAR THE BOARD
    // AT THE BEGINNING OF drawBoard()
    // drawBoard();
    drawPieces();
  });
});
<commit_msg>Added Checkers{}<commit_after>function Checkers() {
  this.board = [];
  this.redTeam = [];
  this.whiteTeam = [];
  this.currentSquare = undefined;
  this.destinationSquare = undefined;
  this.team = undefined;
  this.selectedPiece = undefined;
};

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

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

Piece.prototype.availableMoves = function() {
  // Highlights the moves available to the man
  // Determine direction the man is moving (team, basically)
  // Determine 'king' value
  // Determine if possible destinations are occupied

  // Loop that finds the squares?
  var possibleSquare1 = game.board[this.row + 1][this.column - 1];
  var possibleSquare2 = game.board[this.row + 1][this.column + 1];
  if (possibleSquare1.occupied === true) {
    possibleSquare1 = game.board[this.row + 2][this.column - 2];
  };
  if (possibleSquare2.occupied === true) {
    possibleSquare2 = game.board[this.row + 2][this.column + 2];
  };

  $('#' + possibleSquare1.row + possibleSquare1.column).addClass('highlighted');
  $('#' + possibleSquare2.row + possibleSquare2.column).addClass('highlighted');
  $('#' + this.row + this.column).addClass('highlighted');

};

Piece.prototype.moveMan = function(destination) {
  // This will move the man
  // Changing coordinates
  // Capturing relevant pieces
  // Updating drawn position
  // Checking for possible chained moves
  // Occupy destination square
  // Unoccupy previous square
  game.board[this.row][this.column].occupied = false;
  this.row = destination.row;
  this.column = destination.column;
  game.board[this.row][this.column].occupied = true;
  // 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(
            '

'
            );
      } 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() {
  var team = 'red';
  var row = 0;
  var column = 1;
  // Creates 12 pieces for the team
  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;
    };
  };
};

// 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.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.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() {
  // I DON'T LIKE THAT I DECLARE THESE HERE
  // TEMPORARY, MOVE THESE SOMEWHERE BETTER LATER
  /*
  var team = undefined;
  var selectedPiece = undefined;
  var currentSquare = undefined;
  var destinationSquare = undefined;
  */

  $('.button').click(function() {
    $('.button').hide();
    fillBoard();
    drawBoard();
    createPieces();
    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
    // ******************************************
    // MOVE MOST ALL OF THIS TO THE PIECE OBJECTS

    // 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);

    game.selectedPiece.availableMoves();

    // Gets the Square{} that corresponds with the .playable element that has
    // been clicked by the player
    game.currentSquare = getSquare($(this).closest('.playable').attr('id'));

  });

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

    // ON SELF-CLICK, REMOVE HIGHLIGHTING
    if (game.currentSquare == game.destinationSquare) {
      $('.highlighted').removeClass('highlighted');
      return;
    };

    game.selectedPiece.moveMan(game.destinationSquare);

    $('.highlighted').removeClass('highlighted');

    drawBoard();
    drawPieces();
  });
});
<|endoftext|>


<commit_before>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.get('https://api.github.com/users/' + $('#inputText').val(), "", function(data){
         var Avatar = data['avatar_url'];
         var Username = data['login'];
         var Location = data['location'];
         var Repository = data['public_repos'];
         var Company = data['company'];
         var Followers = data['followers'];
         var Url = data['html_url'];
         var joined = data['created_at'];
         var html = '';
         html += '
' + Username + '
';
         html += '
Followers: ' + Followers +'';
         html += '
Company: ' + Company +'';
         html += '
Repositorys: ' + Repository +'';
         html += '
Location: ' + Location +'';
         html += '
Joined: ' + joined +'';
         // Center
                   html += '
Url Link: GitHub.com/'+ Username +'';
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Github user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<commit_msg>Update main.js<commit_after>$(document).ready(function(event){
   $('#submit').click(function(event){
      getData();

   });
   $('#formThing').submit(function(event){
      event.preventDefault();
      getData();
   });
});
function getData(){
    $.getJSON('https://api.github.com/users/' + $('#inputText').val(),  function(data){
         var Avatar = data.avatar_url;
         var Username = data.login;
         var Location = data.location;
         var Repository = data.public_repos;
         var Company = data.company;
         var Followers = data.followers;
         var Url = data.html_url;
         var joined = data.created_at;
         var html = '';
         html += '
' + Username + '
';
         html += '
Followers: ' + Followers +'';
         html += '
Company: ' + Company +'';
         html += '
Repositorys: ' + Repository +'';
         html += '
Location: ' + Location +'';
         html += '
Joined: ' + joined +'';
         // Center
                   html += '
Url Link: GitHub.com/'+ Username +'';
         $('.profile').html(html);
      }).fail(function(data){
            html = '
A Github user with that name does not exist.';
             $('.profile').html(html);
            return;
      });;
}
<|endoftext|>


<commit_before>function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    if (response.status === 'connected') {
      document.getElementById('status').innerHTML = 'you are logged into this app.';
    } else if (response.status === 'not_authorized') {
      document.getElementById('status').innerHTML = 'Please log into this app.';
    } else {
      document.getElementById('status').innerHTML = 'Please log into Facebook.';
    }
  }

window.fbAsyncInit = function() {
  FB.init({
    appId      : '971388552927772',
    xfbml      : true,
    version    : 'v2.5'
  });
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
};

//facebook initialization

(function(d, s, id){
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) {return;}
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
<commit_msg>Update main.js<commit_after>function statusChangeCallback(response) {
    if (response.status === 'connected') {
      testAPI();
    } else if (response.status === 'not_authorized') {
      document.getElementById('status').innerHTML = 'Please log into this app.';
    } else {
      document.getElementById('status').innerHTML = 'Please log into Facebook.';
    }
  }
  // This function is called when someone finishes with the Login button.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }
  window.fbAsyncInit = function() {
  FB.init({
    appId      : '971388552927772',
    cookie     : true,  // enable cookies to allow the server to access the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.5' // use version 2.2
  });
  // Now that we've initialized the JavaScript SDK, we call
  // FB.getLoginStatus().  This function gets the state of the
  // person visiting this page and can return one of three states to
  // the callback you provide.
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
  };
  // Load the SDK asynchronously
  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.
  function testAPI() {
    FB.api('/me', function(response) {
      document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.name + '!';
    });
  }
<|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    // If mouse down, draw current unsaved box.
    if(core_mouse['down-0']){
        canvas_draw_path({
          'style': 'stroke',
          'vertices': [
            {
              'type': 'rect',
              'radius': core_mouse['x'] - core_mouse['down-x'],
              'startAngle': core_mouse['y'] - core_mouse['down-y'],
              'x': core_mouse['down-x'],
              'y': core_mouse['down-y'],
            },
          ],
        });
    }

    entity_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          canvas_draw_path({
            'style': 'stroke',
            'vertices': [
              {
                'type': 'rect',
                'radius': entity_entities[entity]['width'],
                'startAngle': entity_entities[entity]['height'],
                'x': entity_entities[entity]['x'],
                'y': entity_entities[entity]['y'],
              },
            ],
          });
      },
    });
}

function repo_init(){
    core_repo_init({
      'events': {
        'clear': {
          'onclick': core_repo_reset,
        },
      },
      'info': '<input id=clear type=button value="Clear Boxen"> Click + Drag',
      'mousebinds': {
        'mouseup': {
          'todo': function(){
              if(core_menu_open){
                  return;
              }

              entity_create({
                'properties': {
                  'height': core_mouse['y'] - core_mouse['down-y'],
                  'width': core_mouse['x'] - core_mouse['down-x'],
                  'x': core_mouse['down-x'],
                  'y': core_mouse['down-y'],
                },
              });
          },
        },
      },
      'reset': canvas_setmode,
      'title': 'RTS-Boxing.htm',
    });
    canvas_init();
}
<commit_msg>updated repo function naming<commit_after>'use strict';

function repo_drawlogic(){
    // If mouse down, draw current unsaved box.
    if(core_mouse['down-0']){
        canvas_draw_path({
          'style': 'stroke',
          'vertices': [
            {
              'type': 'rect',
              'radius': core_mouse['x'] - core_mouse['down-x'],
              'startAngle': core_mouse['y'] - core_mouse['down-y'],
              'x': core_mouse['down-x'],
              'y': core_mouse['down-y'],
            },
          ],
        });
    }

    entity_group_modify({
      'groups': [
        'canvas',
      ],
      'todo': function(entity){
          canvas_draw_path({
            'style': 'stroke',
            'vertices': [
              {
                'type': 'rect',
                'radius': entity_entities[entity]['width'],
                'startAngle': entity_entities[entity]['height'],
                'x': entity_entities[entity]['x'],
                'y': entity_entities[entity]['y'],
              },
            ],
          });
      },
    });
}

function repo_init(){
    core_repo_init({
      'events': {
        'clear': {
          'onclick': core_repo_reset,
        },
      },
      'info': '<input id=clear type=button value="Clear Boxen"> Click + Drag',
      'mousebinds': {
        'mouseup': {
          'todo': function(){
              if(core_menu_open){
                  return;
              }

              entity_create({
                'properties': {
                  'height': core_mouse['y'] - core_mouse['down-y'],
                  'width': core_mouse['x'] - core_mouse['down-x'],
                  'x': core_mouse['down-x'],
                  'y': core_mouse['down-y'],
                },
              });
          },
        },
      },
      'reset': canvas_setmode,
      'title': 'RTS-Boxing.htm',
    });
    canvas_init();
}
<|endoftext|>


<commit_before>var map;
function initialize() {
  var mapOptions = {
    zoom: 10,
    center: new google.maps.LatLng(34.399, -77.755),
    scaleControl: true,
    zoomControl: true,
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL,
        position: google.maps.ControlPosition.RIGHT_TOP
    },
    panControl: false,
    streetViewControl: true,
    streetViewControlOptions: {
    	position: google.maps.ControlPosition.RIGHT_TOP
    }
  };

  google.maps.visualRefresh=true;
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  // Load a GeoJSON from the same server as our demo.
  var jsonData = "data/ncVacationData.json";
  map.data.loadGeoJson(jsonData);

  // Add some style
  map.data.setStyle(function(feature) {
    var color = feature.getProperty("Color");
    if(color == "blue"){
      return{
        marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
      }
    },
    if(color == "blueviolet"){
      return{
        marker.setIcon('http://maps.google.com/mapfiles/ms/icons/purple-dot.png')
    }

  });

  var infoWindow = new google.maps.InfoWindow({
    pixelOffset: new google.maps.Size(0,-25),
  });

  // Set mouseover event for each feature.
  map.data.addListener('click', function(event) {
    fam = event.feature.getProperty("Family");
    name = event.feature.getProperty("Name");
    address = event.feature.getProperty("Address");
    city = event.feature.getProperty("City");
    phone = event.feature.getProperty("Phone");
    web = event.feature.getProperty("Website");

    content = "" + name + "" + "
" + address + "
" + city + "
" + phone + "
" + "Website";

    infoWindow.setContent(content);

    var anchor = new google.maps.MVCObject();
	anchor.set("position",event.latLng);
	infoWindow.open(map,anchor);
  });

}
// Load google map
google.maps.event.addDomListener(window, 'load', initialize);
// resize google map on screen change
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center);
});
<commit_msg>Update main.js<commit_after>var map;
function initialize() {
  var mapOptions = {
    zoom: 10,
    center: new google.maps.LatLng(34.399, -77.755),
    scaleControl: true,
    zoomControl: true,
    zoomControlOptions: {
        style: google.maps.ZoomControlStyle.SMALL,
        position: google.maps.ControlPosition.RIGHT_TOP
    },
    panControl: false,
    streetViewControl: true,
    streetViewControlOptions: {
    	position: google.maps.ControlPosition.RIGHT_TOP
    }
  };

  google.maps.visualRefresh=true;
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  // Load a GeoJSON from the same server as our demo.
  var jsonData = "data/ncVacationData.json";
  map.data.loadGeoJson(jsonData);

  // Add some style
  map.data.setStyle(function(feature) {
    var color = feature.getProperty("Color");
    if(color == "blue"){
      return{
        setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
      }
    },
    if(color == "blueviolet"){
      return{
        setIcon('http://maps.google.com/mapfiles/ms/icons/purple-dot.png')
    }

  });

  var infoWindow = new google.maps.InfoWindow({
    pixelOffset: new google.maps.Size(0,-25),
  });

  // Set mouseover event for each feature.
  map.data.addListener('click', function(event) {
    fam = event.feature.getProperty("Family");
    name = event.feature.getProperty("Name");
    address = event.feature.getProperty("Address");
    city = event.feature.getProperty("City");
    phone = event.feature.getProperty("Phone");
    web = event.feature.getProperty("Website");

    content = "" + name + "" + "
" + address + "
" + city + "
" + phone + "
" + "Website";

    infoWindow.setContent(content);

    var anchor = new google.maps.MVCObject();
	anchor.set("position",event.latLng);
	infoWindow.open(map,anchor);
  });

}
// Load google map
google.maps.event.addDomListener(window, 'load', initialize);
// resize google map on screen change
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center);
});
<|endoftext|>


<commit_before>console.log("J U I loaded");

var timer;
var timer2;
var timer3;
var counter;
var cell;
var curCount = 0;
var gameLost = false;
var multiUp = 0;
var total = 10;
var score = 0;
var points = 100;

var board = [ 0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0];

var cellTypes = [
  {name: "empty", type: 0, color: "white"},
  {name: "normal", type: 1, color: "black"},
  {name: "freeze", type: 2, color: "blue"},
  {name: "multi", type: 3, color: "green"},
  {name: "max", type: 4, color: "yellow"},
  {name: "super", type: 5, color: "red"},
];

// EFFECTS -------------------------------------------------------------
var freezeEffect = function() {
  clearInterval(timer2);
  setTimeout(function() {
    timer2 = setInterval(tickCell, counter);
  }, 2000);
};
var multiEffect = function() {
  multiUp++;
  points = Math.floor((1 + (multiUp * 0.1)) * points);
};
var maxEffect = function() {
  total++;
};
var superEffect = function() {
  for (var i = 0; i < board.length; i++) {
    if (board[i] < 2) board[i] = 0;
  };
};

// LOSING & PRINTSTATE ------------------------------------------------
var hasLost = function() {
  var count = 0;
  for (var i = 0; i < board.length; i++) {
    if (board[i] > 0 && board[i] < 2) count++;
    if (count > total) break;
  };
  curCount = count;
  return count > total;
};
var printState = function() {
  $("#max2").text(curCount);
  $("#max4").text(total);
  $("#score2").text(score);
};

// PICKCELL & FADE ----------------------------------------------------
var pickCell = function() {
  var randomIndex;
  var randomType = function() {
    var randomNum = Math.floor((Math.random() * 100) + 1);
    if (randomNum < 88) {
      return randomType = 1;
    } else if (randomNum < 91) {
      return randomType = 2;
    } else if (randomNum < 94) {
      return randomType = 3;
    } else if (randomNum < 97) {
      return randomType = 4;
    } else {
      return randomType = 5;
    };
  };
  do {
    randomIndex = Math.floor(Math.random() * board.length);
  }
  while (board[randomIndex] !== 0);
  board[randomIndex] = randomType();

  var $fade = $("#cell" + randomIndex);
  if (randomType > 1) {
    setTimeout(function() {
      $fade.animate({backgroundColor: "white"}, 1200);
      setTimeout(function() {
        board[randomIndex] = 0;
      }, 1180);
    }, 1000);
  };
};

// CLICK MOVE ---------------------------------------------------------
var click = function(evt) {
  clickValue = parseInt(this.id.substr(4));
  if (board[clickValue] === 1) {
    score += points;
  } else if (board[clickValue] === 2) {
    freezeEffect();
    // this.hide("explode", 200);
    // this.show("puff", 150);
  } else if (board[clickValue] === 3) {
    multiEffect();
    // this.hide("explode", 200);
    // this.show("puff", 150);
  } else if (board[clickValue] === 4) {
    maxEffect();
    // this.hide("explode", 200);
    // this.show("puff", 150);
  } else if (board[clickValue] === 5) {
    superEffect();
    // this.hide("explode", 200);
    // this.show("puff", 150);
  }
  board[clickValue] = 0;
  render();
};

// RENDER -------------------------------------------------------------
var render = function() {
  if (gameLost === false) renderBoard();
  function renderBoard() {
    board.forEach(function(cell, idx) {
      var el = $('#cell' + idx);
      el.css('background-color', cellTypes[cell].color);
    });
  };
};

// TICKS --------------------------------------------------------------
var tick = function() {
  printState();
  if (hasLost()) {
    clearInterval(timer);
    clearInterval(timer2);
    gameLost = true;
    var lose = function() {
      $(".lose").css({opacity:1});
      setTimeout(function() {
        $(".lose").css({opacity:0});
      }, 400);
    };
    timer3 = setInterval(lose, 800);
  };
  printState();
};
var tickCell = function() {
  pickCell();
  render();
  clearInterval(timer2);
  counter *= 0.99;
  timer2 = setInterval(tickCell, counter);
};

// STARTGAME ----------------------------------------------------------
var startGame = function() {
  for (var i = 0; i < board.length; i++) {
    board[i] = 0;
  };
  curCount = 0;
  gameLost = false;
  multiUp = 0;
  total = 10;
  score = 0;
  points = 100;
  counter = 800;
  printState();
  render();
  clearInterval(timer3);
  clearInterval(timer2);
  clearInterval(timer);
  timer = setInterval(tick, 10);
  timer2 = setInterval(tickCell, counter);
};

// BUTTONS ------------------------------------------------------------
$("#startgame").on('click', function() {
  $(".one").css("display", "none");
  $(".two").css("display","inline");
  $(".three").css("display","none");
  startGame();
});
$("#restart").on('click', function() {
  startGame();
});
$("#mainmenu").on('click', function() {
  $(".one").css("display", "inline");
  $(".two").css("display","none");
  $(".three").css("display","none");
});
$("#howtoplay").on('click', function() {
  $(".one").css("display", "none");
  $(".two").css("display","none");
  $(".three").css("display","inline");
});
$("#mainmenu2").on('click', function() {
  $(".one").css("display", "inline");
  $(".two").css("display","none");
  $(".three").css("display","none");
});
$("#startgame2").on('click', function() {
  $(".one").css("display", "none");
  $(".two").css("display","inline");
  $(".three").css("display","none");
  startGame();
});

// EVENTLISTENERS -----------------------------------------------------
document.addEventListener("DOMContentLoaded", function(evt) {

  var cellEls = document.querySelectorAll("td");
  cellEls[0].addEventListener("click", click);
  cellEls[1].addEventListener("click", click);
  cellEls[2].addEventListener("click", click);
  cellEls[3].addEventListener("click", click);
  cellEls[4].addEventListener("click", click);
  cellEls[5].addEventListener("click", click);
  cellEls[6].addEventListener("click", click);
  cellEls[7].addEventListener("click", click);
  cellEls[8].addEventListener("click", click);
  cellEls[9].addEventListener("click", click);
  cellEls[10].addEventListener("click", click);
  cellEls[11].addEventListener("click", click);

  cellEls[12].addEventListener("click", click);
  cellEls[13].addEventListener("click", click);
  cellEls[14].addEventListener("click", click);
  cellEls[15].addEventListener("click", click);
  cellEls[16].addEventListener("click", click);
  cellEls[17].addEventListener("click", click);
  cellEls[18].addEventListener("click", click);
  cellEls[19].addEventListener("click", click);
  cellEls[20].addEventListener("click", click);
  cellEls[21].addEventListener("click", click);
  cellEls[22].addEventListener("click", click);
  cellEls[23].addEventListener("click", click);

  cellEls[24].addEventListener("click", click);
  cellEls[25].addEventListener("click", click);
  cellEls[26].addEventListener("click", click);
  cellEls[27].addEventListener("click", click);
  cellEls[28].addEventListener("click", click);
  cellEls[29].addEventListener("click", click);
  cellEls[30].addEventListener("click", click);
  cellEls[31].addEventListener("click", click);
  cellEls[32].addEventListener("click", click);
  cellEls[33].addEventListener("click", click);
  cellEls[34].addEventListener("click", click);
  cellEls[35].addEventListener("click", click);

  cellEls[36].addEventListener("click", click);
  cellEls[37].addEventListener("click", click);
  cellEls[38].addEventListener("click", click);
  cellEls[39].addEventListener("click", click);
  cellEls[40].addEventListener("click", click);
  cellEls[41].addEventListener("click", click);
  cellEls[42].addEventListener("click", click);
  cellEls[43].addEventListener("click", click);
  cellEls[44].addEventListener("click", click);
  cellEls[45].addEventListener("click", click);
  cellEls[46].addEventListener("click", click);
  cellEls[47].addEventListener("click", click);

  cellEls[48].addEventListener("click", click);
  cellEls[49].addEventListener("click", click);
  cellEls[50].addEventListener("click", click);
  cellEls[51].addEventListener("click", click);
  cellEls[52].addEventListener("click", click);
  cellEls[53].addEventListener("click", click);
  cellEls[54].addEventListener("click", click);
  cellEls[55].addEventListener("click", click);
  cellEls[56].addEventListener("click", click);
  cellEls[57].addEventListener("click", click);
  cellEls[58].addEventListener("click", click);
  cellEls[59].addEventListener("click", click);

  cellEls[60].addEventListener("click", click);
  cellEls[61].addEventListener("click", click);
  cellEls[62].addEventListener("click", click);
  cellEls[63].addEventListener("click", click);
  cellEls[64].addEventListener("click", click);
  cellEls[65].addEventListener("click", click);
  cellEls[66].addEventListener("click", click);
  cellEls[67].addEventListener("click", click);
  cellEls[68].addEventListener("click", click);
  cellEls[69].addEventListener("click", click);
  cellEls[70].addEventListener("click", click);
  cellEls[71].addEventListener("click", click);

  cellEls[72].addEventListener("click", click);
  cellEls[73].addEventListener("click", click);
  cellEls[74].addEventListener("click", click);
  cellEls[75].addEventListener("click", click);
  cellEls[76].addEventListener("click", click);
  cellEls[77].addEventListener("click", click);
  cellEls[78].addEventListener("click", click);
  cellEls[79].addEventListener("click", click);
  cellEls[80].addEventListener("click", click);
  cellEls[81].addEventListener("click", click);
  cellEls[82].addEventListener("click", click);
  cellEls[83].addEventListener("click", click);

  cellEls[84].addEventListener("click", click);
  cellEls[85].addEventListener("click", click);
  cellEls[86].addEventListener("click", click);
  cellEls[87].addEventListener("click", click);
  cellEls[88].addEventListener("click", click);
  cellEls[89].addEventListener("click", click);
  cellEls[90].addEventListener("click", click);
  cellEls[91].addEventListener("click", click);
  cellEls[92].addEventListener("click", click);
  cellEls[93].addEventListener("click", click);
  cellEls[94].addEventListener("click", click);
  cellEls[95].addEventListener("click", click);

  // cellEls[i].addEventListener("touchstart", click);
});
<commit_msg>refactor random cell gen and stop fadeout with click<commit_after>console.log("J U I loaded");

var timer;
var timer2;
var timer3;
var counter;
var cell;
var curCount = 0;
var gameLost = false;
var multiUp = 0;
var total = 10;
var score = 0;
var points = 100;

var board = [ 0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0,
              0,0,0,0,0,0,0,0,0,0,0,0];

var cellTypes = [
  {name: "empty",  color: "white"},
  {name: "normal", color: "black"},
  {name: "freeze", color: "blue"},
  {name: "multi",  color: "green"},
  {name: "max",    color: "yellow"},
  {name: "super",  color: "red"}
];

var WHITE  = 0,
    BLACK  = 1,
    BLUE   = 2,
    GREEN  = 3,
    YELLOW = 4,
    RED    = 5;

var randomType = function() {
  var randomNum = Math.floor((Math.random() * 100) + 1);
  if      (randomNum < 88) return BLACK;  // 88%
  else if (randomNum < 91) return BLUE;   // 3%
  else if (randomNum < 94) return GREEN;  // 3%
  else if (randomNum < 97) return YELLOW; // 3%
  else                     return RED;    // 3%
};

// EFFECTS -------------------------------------------------------------
var freezeEffect = function() {
  clearInterval(timer2);
  setTimeout(function() {
    timer2 = setInterval(tickCell, counter);
  }, 2000);
};
var multiEffect = function() {
  multiUp++;
  points = Math.floor((1 + (multiUp * 0.1)) * points);
};
var maxEffect = function() {
  total++;
};
var superEffect = function() {
  for (var i = 0; i < board.length; i++) {
    if (board[i] < 2) board[i] = 0;
  };
};

// LOSING & PRINTSTATE ------------------------------------------------
var hasLost = function() {
  var count = 0;
  for (var i = 0; i < board.length; i++) {
    if (board[i] > 0 && board[i] < 2) count++;
    if (count > total) break;
  };
  curCount = count;
  return count > total;
};
var printState = function() {
  $("#max2").text(curCount);
  $("#max4").text(total);
  $("#score2").text(score);
};

// PICKCELL & FADE ----------------------------------------------------
var pickCell = function() {
  var randomIndex;

  do {
    randomIndex = Math.floor(Math.random() * board.length);
  }
  while (board[randomIndex] !== 0);

  board[randomIndex] = randomType();

  var $fade = $("#cell" + randomIndex);
  if (board[randomIndex] > BLACK) {
    setTimeout(function() {
      $fade.animate({backgroundColor: "white"}, 1200);
      setTimeout(function() {
        board[randomIndex] = 0;
      }, 1180);
    }, 1000);
  };
};

// CLICK MOVE ---------------------------------------------------------
var click = function(evt) {
  $(this).stop();
  clickValue = parseInt(this.id.substr(4));
  if (board[clickValue] === 1) {
    score += points;
  } else if (board[clickValue] === 2) {
    freezeEffect();
    // this.hide("explode", 200);
    // this.show("puff", 150);
  } else if (board[clickValue] === 3) {
    multiEffect();
    // this.hide("explode", 200);
    // this.show("puff", 150);
  } else if (board[clickValue] === 4) {
    maxEffect();
    // this.hide("explode", 200);
    // this.show("puff", 150);
  } else if (board[clickValue] === 5) {
    superEffect();
    // this.hide("explode", 200);
    // this.show("puff", 150);
  }
  board[clickValue] = 0;
  render();
};

// RENDER -------------------------------------------------------------
var render = function() {
  if (gameLost === false) renderBoard();
  function renderBoard() {
    board.forEach(function(cell, idx) {
      var el = $('#cell' + idx);
      el.css('background-color', cellTypes[cell].color);
    });
  };
};

// TICKS --------------------------------------------------------------
var tick = function() {
  printState();
  if (hasLost()) {
    clearInterval(timer);
    clearInterval(timer2);
    gameLost = true;
    var lose = function() {
      $(".lose").css({opacity:1});
      setTimeout(function() {
        $(".lose").css({opacity:0});
      }, 400);
    };
    timer3 = setInterval(lose, 800);
  };
  printState();
};

var tickCell = function() {
  pickCell();
  render();
  clearInterval(timer2);
  counter *= 0.99;
  timer2 = setInterval(tickCell, counter);
};

// STARTGAME ----------------------------------------------------------
var startGame = function() {
  for (var i = 0; i < board.length; i++) {
    board[i] = 0;
  };
  curCount = 0;
  gameLost = false;
  multiUp = 0;
  total = 10;
  score = 0;
  points = 100;
  counter = 800;
  printState();
  render();
  clearInterval(timer3);
  clearInterval(timer2);
  clearInterval(timer);
  timer = setInterval(tick, 10);
  timer2 = setInterval(tickCell, counter);
};

// BUTTONS ------------------------------------------------------------
$("#startgame").on('click', function() {
  $(".one").css("display", "none");
  $(".two").css("display","inline");
  $(".three").css("display","none");
  startGame();
});
$("#restart").on('click', function() {
  startGame();
});
$("#mainmenu").on('click', function() {
  $(".one").css("display", "inline");
  $(".two").css("display","none");
  $(".three").css("display","none");
});
$("#howtoplay").on('click', function() {
  $(".one").css("display", "none");
  $(".two").css("display","none");
  $(".three").css("display","inline");
});
$("#mainmenu2").on('click', function() {
  $(".one").css("display", "inline");
  $(".two").css("display","none");
  $(".three").css("display","none");
});
$("#startgame2").on('click', function() {
  $(".one").css("display", "none");
  $(".two").css("display","inline");
  $(".three").css("display","none");
  startGame();
});

// EVENTLISTENERS -----------------------------------------------------
document.addEventListener("DOMContentLoaded", function(evt) {

  var cellEls = document.querySelectorAll("td");
  cellEls[0].addEventListener("click", click);
  cellEls[1].addEventListener("click", click);
  cellEls[2].addEventListener("click", click);
  cellEls[3].addEventListener("click", click);
  cellEls[4].addEventListener("click", click);
  cellEls[5].addEventListener("click", click);
  cellEls[6].addEventListener("click", click);
  cellEls[7].addEventListener("click", click);
  cellEls[8].addEventListener("click", click);
  cellEls[9].addEventListener("click", click);
  cellEls[10].addEventListener("click", click);
  cellEls[11].addEventListener("click", click);

  cellEls[12].addEventListener("click", click);
  cellEls[13].addEventListener("click", click);
  cellEls[14].addEventListener("click", click);
  cellEls[15].addEventListener("click", click);
  cellEls[16].addEventListener("click", click);
  cellEls[17].addEventListener("click", click);
  cellEls[18].addEventListener("click", click);
  cellEls[19].addEventListener("click", click);
  cellEls[20].addEventListener("click", click);
  cellEls[21].addEventListener("click", click);
  cellEls[22].addEventListener("click", click);
  cellEls[23].addEventListener("click", click);

  cellEls[24].addEventListener("click", click);
  cellEls[25].addEventListener("click", click);
  cellEls[26].addEventListener("click", click);
  cellEls[27].addEventListener("click", click);
  cellEls[28].addEventListener("click", click);
  cellEls[29].addEventListener("click", click);
  cellEls[30].addEventListener("click", click);
  cellEls[31].addEventListener("click", click);
  cellEls[32].addEventListener("click", click);
  cellEls[33].addEventListener("click", click);
  cellEls[34].addEventListener("click", click);
  cellEls[35].addEventListener("click", click);

  cellEls[36].addEventListener("click", click);
  cellEls[37].addEventListener("click", click);
  cellEls[38].addEventListener("click", click);
  cellEls[39].addEventListener("click", click);
  cellEls[40].addEventListener("click", click);
  cellEls[41].addEventListener("click", click);
  cellEls[42].addEventListener("click", click);
  cellEls[43].addEventListener("click", click);
  cellEls[44].addEventListener("click", click);
  cellEls[45].addEventListener("click", click);
  cellEls[46].addEventListener("click", click);
  cellEls[47].addEventListener("click", click);

  cellEls[48].addEventListener("click", click);
  cellEls[49].addEventListener("click", click);
  cellEls[50].addEventListener("click", click);
  cellEls[51].addEventListener("click", click);
  cellEls[52].addEventListener("click", click);
  cellEls[53].addEventListener("click", click);
  cellEls[54].addEventListener("click", click);
  cellEls[55].addEventListener("click", click);
  cellEls[56].addEventListener("click", click);
  cellEls[57].addEventListener("click", click);
  cellEls[58].addEventListener("click", click);
  cellEls[59].addEventListener("click", click);

  cellEls[60].addEventListener("click", click);
  cellEls[61].addEventListener("click", click);
  cellEls[62].addEventListener("click", click);
  cellEls[63].addEventListener("click", click);
  cellEls[64].addEventListener("click", click);
  cellEls[65].addEventListener("click", click);
  cellEls[66].addEventListener("click", click);
  cellEls[67].addEventListener("click", click);
  cellEls[68].addEventListener("click", click);
  cellEls[69].addEventListener("click", click);
  cellEls[70].addEventListener("click", click);
  cellEls[71].addEventListener("click", click);

  cellEls[72].addEventListener("click", click);
  cellEls[73].addEventListener("click", click);
  cellEls[74].addEventListener("click", click);
  cellEls[75].addEventListener("click", click);
  cellEls[76].addEventListener("click", click);
  cellEls[77].addEventListener("click", click);
  cellEls[78].addEventListener("click", click);
  cellEls[79].addEventListener("click", click);
  cellEls[80].addEventListener("click", click);
  cellEls[81].addEventListener("click", click);
  cellEls[82].addEventListener("click", click);
  cellEls[83].addEventListener("click", click);

  cellEls[84].addEventListener("click", click);
  cellEls[85].addEventListener("click", click);
  cellEls[86].addEventListener("click", click);
  cellEls[87].addEventListener("click", click);
  cellEls[88].addEventListener("click", click);
  cellEls[89].addEventListener("click", click);
  cellEls[90].addEventListener("click", click);
  cellEls[91].addEventListener("click", click);
  cellEls[92].addEventListener("click", click);
  cellEls[93].addEventListener("click", click);
  cellEls[94].addEventListener("click", click);
  cellEls[95].addEventListener("click", click);

  // cellEls[i].addEventListener("touchstart", click);
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Mats & Myles
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

// Based of Burger Vitrine
var dataTypes = {
    data: new HashMap(),
    registerTypes: function () {
        this.data.put("byte", "writeByte");
        this.data.put("boolean", "writeBoolean");
        this.data.put("short", "writeShort");
        this.data.put("int", "writeInt");
        this.data.put("varint", "writeVarInt");
        this.data.put("chatcomponent", "writeChatComponent");
        this.data.put("position", "writePosition");
        this.data.put("enum", "writeVarIntEnum");
        this.data.put("float", "writeFloat");
        this.data.put("long", "writeLong");
        this.data.put("double", "writeDouble");
        this.data.put("string16", "writeString");
        this.data.put("string8", "writeStringUTF");
        this.data.put("byte[]", "writeBytes");
        this.data.put("itemstack", "writeItemStack");
        this.data.put("metadata", "writeMetadata");
        this.data.put("uuid", "writeUUID");
    },

    contains: function (name) {
        var contains = typeof this.data.get(name) != 'undefined';
        if (!contains) console.error("UNKNOWN TYPE " + name);

        return contains;
    },

    get: function (name) {
        return this.data.get(name);
    }
};

var htmlParser = {
    getInstructions: function (instructions, level) {
        var close = false;
        var caz = false;

        var html = [];
        for (var instr in instructions) {
            var output = this.getInstruction(instructions[instr], close, caz, level);
            close = output.close;
            caz = output.caz;
            html.push(output.data);
        }
        if (close)
            this.addLine(html, level, true, "}");

        return html.join("");
    },
    getInstruction: function (instruction, close, caz, level) {
        var html = [];
        if (caz)
            level += 1;
        if (close && !caz)
            this.addLine(html, level, true, "}");
        close = true;
        switch (instruction.operation) {
            case "write":
                this.addLine(html, level, true, "{0}({1});",
                    [
                        dataTypes.contains(instruction.type) ? dataTypes.get(instruction.type) : instruction.type,
                        instruction.field
                    ]);
                close = false;
                break;
            case "if":
                this.addLine(html, level, true, "if({0}) {", [instruction.condition]);
                this.addLine(html, level, false, this.getInstructions(instruction.instructions, level + 1));
                break;
            case "else":
                this.addLine(html, level, true, "} else {");
                this.addLine(html, level, false, this.getInstruction(instruction.instructions, level + 1));
                break;
            case "yloop":
            case "loop":
                this.addLine(html, level, true, "while({0}) {", [instruction.condition]);

                this.addLine(html, level, false, this.getInstructions(instruction.instructions, level + 1));
                break;
            case "switch":
                this.addLine(html, level, true, "switch({0}) {", [instruction.field]);
                this.addLine(html, level, false, this.getInstructions(instruction.instructions, level + 1));
                break;
            case "case":
                if (caz)
                    level -= 1;
                this.addLine(html, level, true, "case {0}:", [instruction.value]);
                close = false;
                caz = true;
                break;
            case "increment":
                if (instruction.amount == 1)
                    this.addLine(html, level, true, "{0}++;", [instruction.field]);
                else
                    this.addLine(html, level, true, "{0} += {1};", [instruction.field, instruction.amount]);
                close = false;
                break;
            case "store":
                this.addLine(html, level, true, "{0} {1} = {2};", [instruction.type, instruction.var, instruction.value]);
                close = false;
                break;
            case "break":
                this.addLine(html, level, true, "break;");
                break;
            default:
                this.addLine(html, level, true, "// {0}", [instruction]);
                break;
        }
        return {data: html.join(""), close: close, caz: caz};
    },
    // TODO is there a better way to do this?
    addLine: function (html, level, newLine, s, objs) {
        html.push(this.getSpaces(level, s.formatArg(objs)));
        if (newLine)
            html.push("
");
    },
    getSpaces: function (amount, value) {
        if (amount > 0) {
            value = "{0}".formatArg([value]);
            return this.getSpaces(--amount, value);
        }
        return value;
    }
};

dataTypes.registerTypes();<commit_msg>Fix 1.8<commit_after>/*
 * Copyright (c) 2016 Mats & Myles
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

// Based of Burger Vitrine
var dataTypes = {
    data: new HashMap(),
    registerTypes: function () {
        this.data.put("byte", "writeByte");
        this.data.put("boolean", "writeBoolean");
        this.data.put("short", "writeShort");
        this.data.put("int", "writeInt");
        this.data.put("varint", "writeVarInt");
        this.data.put("chatcomponent", "writeChatComponent");
        this.data.put("position", "writePosition");
        this.data.put("enum", "writeVarIntEnum");
        this.data.put("float", "writeFloat");
        this.data.put("long", "writeLong");
        this.data.put("double", "writeDouble");
        this.data.put("string16", "writeString");
        this.data.put("string8", "writeStringUTF");
        this.data.put("byte[]", "writeBytes");
        this.data.put("itemstack", "writeItemStack");
        this.data.put("metadata", "writeMetadata");
        this.data.put("uuid", "writeUUID");
    },

    contains: function (name) {
        var contains = typeof this.data.get(name) != 'undefined';
        if (!contains) console.error("UNKNOWN TYPE " + name);

        return contains;
    },

    get: function (name) {
        return this.data.get(name);
    }
};

var htmlParser = {
    getInstructions: function (instructions, level) {
        var close = false;
        var caz = false;

        var html = [];
        for (var instr in instructions) {
            var output = this.getInstruction(instructions[instr], close, caz, level);
            close = output.close;
            caz = output.caz;
            html.push(output.data);
        }
        if (close)
            this.addLine(html, level, true, "}");

        return html.join("");
    },
    getInstruction: function (instruction, close, caz, level) {
        var html = [];
        if (caz)
            level += 1;
        if (close && !caz)
            this.addLine(html, level, true, "}");
        close = true;
        switch (instruction.operation) {
            case "write":
                this.addLine(html, level, true, "{0}({1});",
                    [
                        dataTypes.contains(instruction.type) ? dataTypes.get(instruction.type) : instruction.type,
                        instruction.field
                    ]);
                close = false;
                break;
            case "if":
                this.addLine(html, level, true, "if({0}) {", [instruction.condition]);
                this.addLine(html, level, false, this.getInstructions(instruction.instructions, level + 1));
                break;
            case "else":
                this.addLine(html, level, true, "} else {");
                console.log(this.getInstruction(instruction.instructions, level + 1));
                this.addLine(html, level, false, this.getInstructions(instruction.instructions, level + 1));
                break;
            case "yloop":
            case "loop":
                this.addLine(html, level, true, "while({0}) {", [instruction.condition]);

                this.addLine(html, level, false, this.getInstructions(instruction.instructions, level + 1));
                break;
            case "switch":
                this.addLine(html, level, true, "switch({0}) {", [instruction.field]);
                this.addLine(html, level, false, this.getInstructions(instruction.instructions, level + 1));
                break;
            case "case":
                if (caz)
                    level -= 1;
                this.addLine(html, level, true, "case {0}:", [instruction.value]);
                close = false;
                caz = true;
                break;
            case "increment":
                if (instruction.amount == 1)
                    this.addLine(html, level, true, "{0}++;", [instruction.field]);
                else
                    this.addLine(html, level, true, "{0} += {1};", [instruction.field, instruction.amount]);
                close = false;
                break;
            case "store":
                this.addLine(html, level, true, "{0} {1} = {2};", [instruction.type, instruction.var, instruction.value]);
                close = false;
                break;
            case "break":
                this.addLine(html, level, true, "break;");
                break;
            default:
                this.addLine(html, level, true, "// {0}", [instruction]);
                break;
        }
        return {data: html.join(""), close: close, caz: caz};
    },
    // TODO is there a better way to do this?
    addLine: function (html, level, newLine, s, objs) {
        html.push(this.getSpaces(level, s.formatArg(objs)));
        if (newLine)
            html.push("
");
    },
    getSpaces: function (amount, value) {
        if (amount > 0) {
            value = "{0}".formatArg([value]);
            return this.getSpaces(--amount, value);
        }
        return value;
    }
};

dataTypes.registerTypes();<|endoftext|>


<commit_before>/**
 * Main AngularJS Web Application
 */
var app = angular.module('zachGlassmanApp', [
  'ngRoute'
]);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"})
    // Pages
    .when("/about", {templateUrl: "partials/about.html", controller: "PageCtrl"})
    .when("/research", {templateUrl: "partials/research.html", controller: "PageCtrl"})
    .when("/notes", {templateUrl: "partials/notes.html", controller: "PageCtrl"})
    .when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
    .when("/projects", {templateUrl: "partials/projects.html", controller: "PageCtrl"})
    // Blog
    .when("/blog", {templateUrl: "partials/blog.html", controller: "BlogCtrl"})
    // else 404
    .otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);

/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function (/* $scope, $location, $http */) {
  console.log("Page Controller reporting for duty.");

  // Activates the Carousel
  $('.carousel').carousel({
    interval: 5000
  });

  // Activates Tooltips for Social Links
  $('.tooltip-social').tooltip({
    selector: "a[data-toggle=tooltip]"
  })
});

/**
 * Controls the Blog
 */
app.controller('BlogCtrl', function ($scope) {
  $scope.posts = [
//begin replace
{'name': 'Visualizing Riemann Sums', 'content': $scope.trustedHTML = $sce.trustAsHtml('
\nThis is my first post\n\n# will be bout Riemann sums\n\n
'), 'date': 'June 20, 2015'},
{'name': 'Welcome to my Blog', 'content': '
\nThis is my first post\n\n# will be bout my blog\n\n
', 'date': 'June 20, 2015'},
//end replace
      ];

});

app.directive('markdown', function () {
    var converter = new Showdown.converter();
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var htmlText = converter.makeHtml(element.text());
            element.html(htmlText);
        }
    };

});<commit_msg>new blog stuff<commit_after>/**
 * Main AngularJS Web Application
 */
var app = angular.module('zachGlassmanApp', [
  'ngRoute'
]);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"})
    // Pages
    .when("/about", {templateUrl: "partials/about.html", controller: "PageCtrl"})
    .when("/research", {templateUrl: "partials/research.html", controller: "PageCtrl"})
    .when("/notes", {templateUrl: "partials/notes.html", controller: "PageCtrl"})
    .when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
    .when("/projects", {templateUrl: "partials/projects.html", controller: "PageCtrl"})
    // Blog
    .when("/blog", {templateUrl: "partials/blog.html", controller: "BlogCtrl"})
    // else 404
    .otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);

/**
 * Controls all other Pages
 */
app.controller('PageCtrl', function (/* $scope, $location, $http */) {
  console.log("Page Controller reporting for duty.");

  // Activates the Carousel
  $('.carousel').carousel({
    interval: 5000
  });

  // Activates Tooltips for Social Links
  $('.tooltip-social').tooltip({
    selector: "a[data-toggle=tooltip]"
  })
});

/**
 * Controls the Blog
 */
app.controller('BlogCtrl', ['$scope', '$sce', function ($scope, $sce) {
  $scope.posts = [
//begin replace
{'name': 'Visualizing Riemann Sums', 'content': $scope.trustedHTML = $sce.trustAsHtml('
\nThis is my first post\n\n# will be bout Riemann sums\n\n
'), 'date': 'June 20, 2015'},
{'name': 'Welcome to my Blog', 'content': '
\nThis is my first post\n\n# will be bout my blog\n\n
', 'date': 'June 20, 2015'},
//end replace
      ];

}]);

app.directive('markdown', function () {
    var converter = new Showdown.converter();
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var htmlText = converter.makeHtml(element.text());
            element.html(htmlText);
        }
    };

});<|endoftext|>