<commit_before>//First get access to our canvas object we've defined in our html
var canvas = document.getElementById("gameCanvas");
var context = canvas.getContext("2d");

//sets a listener functions so we can get input from the player
window.addEventListener('keydown', function(evt) { onKeyDown(evt); }, false);
window.addEventListener('keyup', function(evt) { onKeyUp(evt); }, false);

////////////////////////////////////////////////////////////
//CONSTANTS
var SCREEN_WIDTH = canvas.width;
var SCREEN_HEIGHT = canvas.height;

var ASTEROID_SPEED = 0.8;
var PLAYER_SPEED = 5;
var PLAYER_TURN_SPEED = 0.09;
var BULLET_SPEED = 15;

//Constant
var KEY_SPACE 	= 32;
var KEY_LEFT 	= 37;
var KEY_UP 		= 38;
var KEY_RIGHT	= 39;
var KEY_DOWN 	= 40;

//GAME_STATE CONSTANTS
var STATE_SPLASH = 0;
var STATE_GAME = 1;
var STATE_GAMEOVER = 2;

var gameState = STATE_SPLASH;

//ALL OUR VARIABLES
////////////////////////////////////////////////////////////
//Grass Tiles
var Grass = document.createElement("img");

Grass.src = "grass.png";

var Background = [];

for (var y = 0; y < 15; y++)
{
	Background[y] = [];
	for (var x = 0; x < 20; x++)
	{
		Background[y][x] = Grass;
	}
}

////////////////////////////////////////////////////////////
//Player Values
var Player =
{
	image : document.createElement("img"),
	x : SCREEN_WIDTH/2,
	y : SCREEN_HEIGHT/2,
	width : 93,
	height : 80,
	directionX: 0,
	directionY: 0,
	Dead : false,
	angularDirection: 0,
	rotation: 0
};

//set the image for the player to use
Player.image.src = "ship.png";

////////////////////////////////////////////////////////////
//Asteroids

var Asteroids = [];
var AsteroidSpawnTimer = 0;

function spawnAsteroid()
{
	var type = rand(0 ,3);
	var newAsteroid = {};

	//gives the Asteroid large, medium or small depending on random number
	newAsteroid.image = document.createElement("img");
	if (type == 0)
	{
		newAsteroid.image.src = "rock_large.png";
		newAsteroid.width = 69;
		newAsteroid.height = 75;
	}
	if (type == 1)
	{
		newAsteroid.image.src = "rock_medium.png";
		newAsteroid.width = 40;
		newAsteroid.height = 50;
	}
	if (type == 2)
	{
		newAsteroid.image.src = "rock_small.png";
		newAsteroid.width = 22;
		newAsteroid.height = 20;
	}

	//starts the Asteroid in the middle of the screen
	newAsteroid.x = SCREEN_WIDTH/2;
	newAsteroid.y = SCREEN_HEIGHT/2;

	//start with a random vector
	var dirX = rand(-10, 10);
	var dirY = rand(-10, 10);
	//normalises it
	var Magnitude = Math.sqrt(dirX * dirX + dirY * dirY);
	if (Magnitude != 0)
	{
		dirX *= 1/ Magnitude;
		dirY *= 1/ Magnitude;
	}

	//taking the random vector we move outwards from the centre of the screen
	//in that direction
	var movY = dirY * SCREEN_HEIGHT;
	var movX = dirX * SCREEN_WIDTH;

	//Actually moves the asteroid
	newAsteroid.x += movX;
	newAsteroid.y += movY;

	//puts it on course towards the centre of the screen by reversing the vector
	newAsteroid.velocityX = -dirX * ASTEROID_SPEED;
	newAsteroid.velocityY = -dirY * ASTEROID_SPEED;

	//finally adds the newAsteroid to our Asteroids Array
	Asteroids.push(newAsteroid);
}

////////////////////////////////////////////////////////////
//Bullet Values
var Bullets = [];

//function fires a bullet in the diretcion the player is facing
function playerShoot()
{
	var Bullet =
	{
		image : document.createElement("img"),
		x : Player.x,
		y : Player.y,
		width : 5,
		height : 5,
		velocityX : 0,
		velocityY : 0
	}
	Bullet.image.src = "bullet.png"

	//start off with a direction straight up
	var dirX = 0;
	var dirY = 1;

	//rotates said direction by player rotation
	var s = Math.sin(Player.rotation);
	var c = Math.cos(Player.rotation);
	var xVel = (dirX * c) - (dirY * s);
	var yVel = (dirX * s) + (dirY * c);

	//gives the bullet calculated velocity times it's speed
	Bullet.velocityX = xVel * BULLET_SPEED;
	Bullet.velocityY = yVel * BULLET_SPEED;

	//starts the bullet at the player coordinates
	Bullet.x = Player.x;
	Bullet.y = Player.y;

	Bullets.push(Bullet);
}

////////////////////////////////////////////////////////////
//Misc Functions

//returns a random real value between floor and ceil
function rand(floor, ceil)
{
	return Math.floor( (Math.random() * (ceil - floor)) + floor );
}

//AABB Collision function
function intersects(x1, y1, w1, h1, x2, y2, w2, h2)
{
	if ( 	y2 + h2 < y1 ||
			x2 + w2 < x1 ||
				x2 > x1 + w1 ||
				y2 > y1 + h1)
		return false;

	return true;
}

////////////////////////////////////////////////////////////

var ShootTimer = 0;

//Function called when key is pressed down
function onKeyDown(event)
{
	if (event.keyCode == KEY_UP)
	{
		Player.directionY = 1;
	}
	if (event.keyCode == KEY_DOWN)
	{
		Player.directionY = -1;
	}
	if (event.keyCode == KEY_LEFT)
	{
		Player.angularDirection = -1;
	}
	if (event.keyCode == KEY_RIGHT)
	{
		Player.angularDirection = 1;
	}
	if (event.keyCode == KEY_SPACE && ShootTimer <= 0)
	{
		ShootTimer += .5;
		playerShoot();
	}
}

//Function called when key is released
function onKeyUp(event)
{
	if (event.keyCode == KEY_UP)
	{
		Player.directionY = 0;
	}
	if (event.keyCode == KEY_DOWN)
	{
		Player.directionY = 0;
	}
	if (event.keyCode == KEY_LEFT)
	{
		Player.angularDirection = 0;
	}
	if (event.keyCode == KEY_RIGHT)
	{
		Player.angularDirection = 0;
	}
}

//Here we define the variable that keeps track of the time between frames
var lastUpdate = Date.now();

//
var SplashTimer = 3;
function runSplash(dt)
{
	//counts down three seconds then switchs to the game
	SplashTimer -= dt;
	if (SplashTimer <= 0)
	{
		gameState = STATE_GAME;
		return;
	}

	context.fillStyle = "#000";
	context.font = "18px Arial";
	context.fillText("Asteroids", 200, 240);

}

function runGame(dt)
{
	//updates shoot timer
	if (ShootTimer > 0)
		ShootTimer -= dt;

	//draws our background tiles
	for (var y = 0; y < 15; y++)
	{
		for (var x = 0; x < 20; x++)
		{
			context.drawImage( Background[y][x],
							   x * 32, y * 32);
		}
	}

	////////////////////////////////////////////////////////////
	//Player Movement
	var s = Math.sin(Player.rotation);
	var c = Math.cos(Player.rotation);

	var xDir = (Player.directionX * c) - (Player.directionY * s);
	var yDir = (Player.directionX * s) + (Player.directionY * c);
	var xVel = xDir * PLAYER_SPEED;
	var yVel = yDir * PLAYER_SPEED;

	//adds our calculated velocity
	Player.x += xVel;
	Player.y += yVel;

	//Rotates the player
	Player.rotation += Player.angularDirection * PLAYER_TURN_SPEED;

	//draw the player adjusting player origin
	if(!Player.Dead)
	{
	context.save();
		context.translate( Player.x, Player.y);
		context.rotate(Player.rotation);
		context.drawImage(Player.image, -Player.width/2, -Player.height/2);
	context.restore();
	}

	////////////////////////////////////////////////////////////
	//Asteroid Movement
	for (var i = 0; i < Asteroids.length; i++)
	{
		//moves the Asteroid
		Asteroids[i].x += Asteroids[i].velocityX;
		Asteroids[i].y += Asteroids[i].velocityY;

		//Draws the Asteroid
		context.drawImage( Asteroids[i].image, Asteroids[i].x, Asteroids[i].y );

	}

	//spawns a new one every SECOND
	AsteroidSpawnTimer += dt;
	if (AsteroidSpawnTimer >= 1)
	{
		AsteroidSpawnTimer = 0;
		spawnAsteroid();
	}

	////////////////////////////////////////////////////////////
	//Bullet Movement
	//Moves and draws the Bullets if it's been fired
	for (var i = 0; i < Bullets.length; i++)
	{
		Bullets[i].x += Bullets[i].velocityX;
		Bullets[i].y += Bullets[i].velocityY;

		context.drawImage(Bullets[i].image,
						Bullets[i].x - Bullets[i].width/2,
						Bullets[i].y - Bullets[i].height/2);

		//checks if the Bullet is outside the screen
		if (Bullets[i].x > SCREEN_WIDTH || Bullets[i].x < 0 ||
			Bullets[i].y > SCREEN_HEIGHT || Bullets[i].y < 0)
		{
			Bullets.splice(i, 1); //removes it from out array
		}
		else //else checks if any of the bullets are hitting Asteroids
		{
			for (var j = 0; j < Asteroids.length; j++)
			{
				var hit = intersects(
								Bullets[i].x, Bullets[i].y,
								Bullets[i].width, Bullets[i].height,
								Asteroids[j].x, Asteroids[j].y,
								Asteroids[j].width, Asteroids[j].height);
				if (hit == true)
				{
					Bullets.splice(i,1);
					Asteroids.splice(j,1);
					break;
				}
			}
		}
	}
}

{
for (var j = 0; j < Asteroids.length; j++)

var hit = intersects
		(Player.x, Player.y,
		Player.width, Player.height,
		Asteroids[j].x, Asteroids[j].y,
		Asteroids[j].width, Asteroids[j].height);
	if (hit == true)

//Player.Dead = true
//gameState = STATE_GAMEOVER
};

function runEnd(dt)
{};
//callback function to run each frame
function run()
{
	//First we work out the difference in time between now and the last update
	//and chuck it into deltaTime
	var now = Date.now();
	var DeltaTime = (now - lastUpdate) * 0.001;
	lastUpdate = now;

	//Gray Background
	context.fillStyle = "#5C005C";
	context.fillRect(0, 0, canvas.width, canvas.height);

	//runs the current game state
	switch (gameState)
	{
		case STATE_SPLASH:
			runSplash(DeltaTime);
			break;
		case STATE_GAME:
			runGame(DeltaTime);
			break;

		case STATE_GAMEOVER:
			runEnd(DeltaTime);
			break;
	}
};

//DUNNA TOUCH ME BOYOO
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////

//essentially a function that sets our callback function run() to be called every frame
//with handling of different browsers
(function() {
	var onEachFrame;
	if (window.requestAnimationFrame)
	{
		onEachFrame = function(cb)
		{
			var _cb = function()
			{
				cb(); //ie or chrome
				window.requestAnimationFrame(_cb);
			}
		_cb();
		};
	}
	else if (window.mozRequestAnimationFrame)
	{
		onEachFrame = function(cb)
		{
			var _cb = function()
			{
				cb();	//mozilla
				window.mozRequestAnimationFrame(_cb);
			}
		_cb();
		};
	}
	else
	{
		onEachFrame = function(cb) //any ol browser
		{
			setInterval(cb, 1000 / 60);
		}
	}
	window.onEachFrame = onEachFrame;
})();

//call our function
window.onEachFrame(run);

///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
<commit_msg>FIXED<commit_after>//First get access to our canvas object we've defined in our html
var canvas = document.getElementById("gameCanvas");
var context = canvas.getContext("2d");

//sets a listener functions so we can get input from the player
window.addEventListener('keydown', function(evt) { onKeyDown(evt); }, false);
window.addEventListener('keyup', function(evt) { onKeyUp(evt); }, false);

////////////////////////////////////////////////////////////
//CONSTANTS
var SCREEN_WIDTH = canvas.width;
var SCREEN_HEIGHT = canvas.height;

var ASTEROID_SPEED = 0.8;
var PLAYER_SPEED = 5;
var PLAYER_TURN_SPEED = 0.09;
var BULLET_SPEED = 15;

//Constant
var KEY_SPACE 	= 32;
var KEY_LEFT 	= 37;
var KEY_UP 		= 38;
var KEY_RIGHT	= 39;
var KEY_DOWN 	= 40;

//GAME_STATE CONSTANTS
var STATE_SPLASH = 0;
var STATE_GAME = 1;
var STATE_GAMEOVER = 2;

var PlayerScore = 0;

var gameState = STATE_SPLASH;

//ALL OUR VARIABLES
////////////////////////////////////////////////////////////
//Grass Tiles
var Grass = document.createElement("img");

Grass.src = "grass.png";

var Background = [];

for (var y = 0; y < 15; y++)
{
	Background[y] = [];
	for (var x = 0; x < 20; x++)
	{
		Background[y][x] = Grass;
	}
}

////////////////////////////////////////////////////////////
//Player Values
var Player =
{
	image : document.createElement("img"),
	x : SCREEN_WIDTH/2,
	y : SCREEN_HEIGHT/2,
	width : 93,
	height : 80,
	directionX: 0,
	directionY: 0,
	Dead : false,
	angularDirection: 0,
	rotation: 0,
	lives: 3
};

//set the image for the player to use
Player.image.src = "ship.png";

////////////////////////////////////////////////////////////
//Asteroids

var Asteroids = [];
var AsteroidSpawnTimer = 0;

function spawnAsteroid()
{
	var type = rand(0 ,3);
	var newAsteroid = {};

	//gives the Asteroid large, medium or small depending on random number
	newAsteroid.image = document.createElement("img");
	if (type == 0)
	{
		newAsteroid.image.src = "rock_large.png";
		newAsteroid.width = 69;
		newAsteroid.height = 75;
	}
	if (type == 1)
	{
		newAsteroid.image.src = "rock_medium.png";
		newAsteroid.width = 40;
		newAsteroid.height = 50;
	}
	if (type == 2)
	{
		newAsteroid.image.src = "rock_small.png";
		newAsteroid.width = 22;
		newAsteroid.height = 20;
	}

	//starts the Asteroid in the middle of the screen
	newAsteroid.x = SCREEN_WIDTH/2;
	newAsteroid.y = SCREEN_HEIGHT/2;

	//start with a random vector
	var dirX = rand(-10, 10);
	var dirY = rand(-10, 10);
	//normalises it
	var Magnitude = Math.sqrt(dirX * dirX + dirY * dirY);
	if (Magnitude != 0)
	{
		dirX *= 1/ Magnitude;
		dirY *= 1/ Magnitude;
	}

	//taking the random vector we move outwards from the centre of the screen
	//in that direction
	var movY = dirY * SCREEN_HEIGHT;
	var movX = dirX * SCREEN_WIDTH;

	//Actually moves the asteroid
	newAsteroid.x += movX;
	newAsteroid.y += movY;

	//puts it on course towards the centre of the screen by reversing the vector
	newAsteroid.velocityX = -dirX * ASTEROID_SPEED;
	newAsteroid.velocityY = -dirY * ASTEROID_SPEED;

	//finally adds the newAsteroid to our Asteroids Array
	Asteroids.push(newAsteroid);
}

////////////////////////////////////////////////////////////
//Bullet Values
var Bullets = [];

//function fires a bullet in the diretcion the player is facing
function playerShoot()
{
	var Bullet =
	{
		image : document.createElement("img"),
		x : Player.x,
		y : Player.y,
		width : 5,
		height : 5,
		velocityX : 0,
		velocityY : 0
	}
	Bullet.image.src = "bullet.png"

	//start off with a direction straight up
	var dirX = 0;
	var dirY = 1;

	//rotates said direction by player rotation
	var s = Math.sin(Player.rotation);
	var c = Math.cos(Player.rotation);
	var xVel = (dirX * c) - (dirY * s);
	var yVel = (dirX * s) + (dirY * c);

	//gives the bullet calculated velocity times it's speed
	Bullet.velocityX = xVel * BULLET_SPEED;
	Bullet.velocityY = yVel * BULLET_SPEED;

	//starts the bullet at the player coordinates
	Bullet.x = Player.x;
	Bullet.y = Player.y;

	Bullets.push(Bullet);
}

////////////////////////////////////////////////////////////
//Misc Functions

//returns a random real value between floor and ceil
function rand(floor, ceil)
{
	return Math.floor( (Math.random() * (ceil - floor)) + floor );
}

//AABB Collision function
function intersects(x1, y1, w1, h1, x2, y2, w2, h2)
{
	if ( 	y2 + h2 < y1 ||
			x2 + w2 < x1 ||
				x2 > x1 + w1 ||
				y2 > y1 + h1)
		return false;

	return true;
}

////////////////////////////////////////////////////////////

var ShootTimer = 0;

//Function called when key is pressed down
function onKeyDown(event)
{
	if (event.keyCode == KEY_UP)
	{
		Player.directionY = 1;
	}
	if (event.keyCode == KEY_DOWN)
	{
		Player.directionY = -1;
	}
	if (event.keyCode == KEY_LEFT)
	{
		Player.angularDirection = -1;
	}
	if (event.keyCode == KEY_RIGHT)
	{
		Player.angularDirection = 1;
	}
	if (event.keyCode == KEY_SPACE && ShootTimer <= 0)
	{
		ShootTimer += .5;
		playerShoot();
	}
}

//Function called when key is released
function onKeyUp(event)
{
	if (event.keyCode == KEY_UP)
	{
		Player.directionY = 0;
	}
	if (event.keyCode == KEY_DOWN)
	{
		Player.directionY = 0;
	}
	if (event.keyCode == KEY_LEFT)
	{
		Player.angularDirection = 0;
	}
	if (event.keyCode == KEY_RIGHT)
	{
		Player.angularDirection = 0;
	}
}

//Here we define the variable that keeps track of the time between frames
var lastUpdate = Date.now();

//
var SplashTimer = 3;
function runSplash(dt)
{
	//counts down three seconds then switchs to the game
	SplashTimer -= dt;
	if (SplashTimer <= 0)
	{
		gameState = STATE_GAME;
		return;
	}

	context.fillStyle = "#000";
	context.font = "18px Arial";
	context.fillText("Asteroids", 200, 240);

}

function runGame(dt)
{
	//updates shoot timer
	if (ShootTimer > 0)
		ShootTimer -= dt;

	//draws our background tiles
	for (var y = 0; y < 15; y++)
	{
		for (var x = 0; x < 20; x++)
		{
			context.drawImage( Background[y][x],
							   x * 32, y * 32);
		}
	}

	//draw the player score to the screen
    context.font = "18px Arial";
    var TextMeasure = context.measureText("Score: " + PlayerScore);
    context.fillText("Score: " + PlayerScore, SCREEN_WIDTH/3 - (TextMeasure.width/3), SCREEN_HEIGHT/3);

	////////////////////////////////////////////////////////////
	//Player Movement
	var s = Math.sin(Player.rotation);
	var c = Math.cos(Player.rotation);

	var xDir = (Player.directionX * c) - (Player.directionY * s);
	var yDir = (Player.directionX * s) + (Player.directionY * c);
	var xVel = xDir * PLAYER_SPEED;
	var yVel = yDir * PLAYER_SPEED;

	//adds our calculated velocity
	Player.x += xVel;
	Player.y += yVel;

	//Rotates the player
	Player.rotation += Player.angularDirection * PLAYER_TURN_SPEED;

	//draw the player adjusting player origin
for (var i = 0 ; i < Asteroids.length; i++)
	{
		//if the player hits an Asteroid, takes out one life and the Asteroid
		if (intersects(	Player.x - Player.width/2, Player.y - Player.height/2,
						Player.width, Player.height,
						Asteroids[i].x - Asteroids[i].width/2, Asteroids[i].y - Asteroids[i].height/2,
						Asteroids[i].width, Asteroids[i].height))
		{
			Player.lives -= 1;
			Asteroids.splice(i, 1);
		}

	if (Player.lives <= 0)
		gameState = STATE_GAMEOVER;
	//draw the player adjusting player origin
	context.save();
		context.translate( Player.x, Player.y);
		context.rotate(Player.rotation);
		context.drawImage(Player.image, -Player.width/2, -Player.height/2);
	context.restore();
	}

	////////////////////////////////////////////////////////////
	//Asteroid Movement
	for (var i = 0; i < Asteroids.length; i++)
	{
		//moves the Asteroid
		Asteroids[i].x += Asteroids[i].velocityX;
		Asteroids[i].y += Asteroids[i].velocityY;

		//Draws the Asteroid
		context.drawImage( Asteroids[i].image, Asteroids[i].x, Asteroids[i].y );

	}

	//spawns a new one every SECOND
	AsteroidSpawnTimer += dt;
	if (AsteroidSpawnTimer >= 1)
	{
		AsteroidSpawnTimer = 0;
		spawnAsteroid();
	}

	////////////////////////////////////////////////////////////
	//Bullet Movement
	//Moves and draws the Bullets if it's been fired
	for (var i = 0; i < Bullets.length; i++)
	{
		Bullets[i].x += Bullets[i].velocityX;
		Bullets[i].y += Bullets[i].velocityY;

		context.drawImage(Bullets[i].image,
						Bullets[i].x - Bullets[i].width/2,
						Bullets[i].y - Bullets[i].height/2);

		//checks if the Bullet is outside the screen
		if (Bullets[i].x > SCREEN_WIDTH || Bullets[i].x < 0 ||
			Bullets[i].y > SCREEN_HEIGHT || Bullets[i].y < 0)
		{
			Bullets.splice(i, 1); //removes it from out array
		}
		else //else checks if any of the bullets are hitting Asteroids
		{
			for (var j = 0; j < Asteroids.length; j++)
			{
				var hit = intersects(
								Bullets[i].x, Bullets[i].y,
								Bullets[i].width, Bullets[i].height,
								Asteroids[j].x, Asteroids[j].y,
								Asteroids[j].width, Asteroids[j].height);
				if (hit == true)
				{
					PlayerScore ++;
					Bullets.splice(i,1);
					Asteroids.splice(j,1);
					break;
				}
			}
		}
	}
}

	//draw the player score to the screen
    context.font = "18px Arial";
    var TextMeasure = context.measureText("Score: " + PlayerScore);
    context.fillText("Score: " + PlayerScore, SCREEN_WIDTH/3 - (TextMeasure.width/3), SCREEN_HEIGHT/3);

function runEnd(dt)
{};
//callback function to run each frame
function run()
{
	//First we work out the difference in time between now and the last update
	//and chuck it into deltaTime
	var now = Date.now();
	var DeltaTime = (now - lastUpdate) * 0.001;
	lastUpdate = now;

	//Gray Background
	context.fillStyle = "#5C005C";
	context.fillRect(0, 0, canvas.width, canvas.height);

	//runs the current game state
	switch (gameState)
	{
		case STATE_SPLASH:
			runSplash(DeltaTime);
			break;
		case STATE_GAME:
			runGame(DeltaTime);
			break;

		case STATE_GAMEOVER:
			runEnd(DeltaTime);
			break;
	}
};

//DUNNA TOUCH ME BOYOO
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////

//essentially a function that sets our callback function run() to be called every frame
//with handling of different browsers
(function() {
	var onEachFrame;
	if (window.requestAnimationFrame)
	{
		onEachFrame = function(cb)
		{
			var _cb = function()
			{
				cb(); //ie or chrome
				window.requestAnimationFrame(_cb);
			}
		_cb();
		};
	}
	else if (window.mozRequestAnimationFrame)
	{
		onEachFrame = function(cb)
		{
			var _cb = function()
			{
				cb();	//mozilla
				window.mozRequestAnimationFrame(_cb);
			}
		_cb();
		};
	}
	else
	{
		onEachFrame = function(cb) //any ol browser
		{
			setInterval(cb, 1000 / 60);
		}
	}
	window.onEachFrame = onEachFrame;
})();

//call our function
window.onEachFrame(run);

///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>enchant();

var checked = 0;
var stage = 1;
var board, bar, game,
    score = 0, time = 0, rest = 400, size = 24;

var stages = {
    1: {width: 8, height: 8, bonus: 100},
    2: {width: 10, height: 8, bonus: 100},
    3: {width: 13, height: 8, bonus: 100},
    4: {width: 13, height: 10, bonus: 100},
    5: {width: 13, height: 10, bonus: 100},
    6: {width: 13, height: 10, bonus: 100},
    7: {width: 13, height: 10, bonus: 100},
    8: {width: 13, height: 10, bonus: 100},
    9: {width: 13, height: 10, bonus: 100},
    10: {width: 13, height: 10, bonus: 100}
};

window.onload = function() {
    game = new Game(320, 320);
    game.fps = 20;
    game.preload('fruits.png', 'bar.png', 'se2.wav', 'se6.wav', 'se7.wav', 'lock2.wav', 'jingle03.wav', 'bomb2.wav', 'bomb3.wav');

    game.onload = function() {
        resetBoard();

        bar = new Sprite(1, 12);
        bar.image = game.assets['bar.png'];
        bar.defaultpos = {x: 16, y: 40};
        rest = Math.max(0, rest);
        bar.width = rest / 2;

        game.rootScene.addChild(bar);
        game.texts = [];
        game.pinch = false;

        game.texts.score = new MutableText(16, 8, game.width, "Score:" + score);
        game.rootScene.addChild(game.texts.score);

        game.texts.time = new MutableText(16, 24, game.width, "Time:" + (rest / game.fps).toFixed(2) + 's');
        game.rootScene.addChild(game.texts.time);

        game.texts.bonus = new MutableText(16, 56, game.width, "");
        game.rootScene.addChild(game.texts.bonus);

        game.timer = [];
    };

    game.rootScene.addEventListener('enterframe',
        function() {
            for (var p in board) {
                for (var q in board[p]) {
                    var fruit = board[p][q];
                    if (fruit.x != fruit.target.x)fruit.x += Math.max(-8, Math.min(10, fruit.target.x - fruit.x));
                    if (fruit.y != fruit.target.y)fruit.y += Math.max(-8, Math.min(10, fruit.target.y - fruit.y));
                    if (rest < 100) {
                        if (!game.pinch) {
                            game.pinch = true;
                            game.assets['jingle03.wav'].play();
                        }
                        fruit.x += rand(3) - 1;
                    } else {
                        if (game.pinch) {
                            game.pinch = false;
                            game.assets['jingle03.wav'].stop();
                        }
                    }
                }
            }

            time++;
            rest--;
            rest = Math.min(rest, 400);
            bar.width = rest / 2;
            game.texts.time.setText("Time: " + (rest / game.fps).toFixed(2));
            game.texts.score.setText("Score: " + score);

            if (rest <= 0) {
                game.end(score, 'スコア: ' + score);
                game.assets['bomb3.wav'].play();
            }

        }
    );
    game.start();
};

function setBonus(bonus, time) {
    game.texts.bonus.setText(bonus)
    if (game.timer.bonus) clearTimeout(game.timer.bonus);
    game.timer.bonus = setTimeout(
        function() {
            game.texts.bonus.setText("");
        }
        , time);
}

function clearBoard() {
    for (var p in board) {
        for (var q in board[p]) {
            game.rootScene.removeChild(board[p][q]);
        }
    }
}

function getNumOfFruits() {
    var fruits = 0;
    for (var p in board) {
        for (var q in board[p]) {
            fruits++;
        }
    }
    return fruits;
}

function resetBoard() {
    width = stages[stage].width;
    height = stages[stage].height;

    board = new Array(width);
    for (var i = 0; i < width; i++) {
        board[i] = new Array(height);
        for (var j = 0; j < height; j++) {
            board[i][j] = new Sprite(16, 16);
            board[i][j].scaleX = size / 16;
            board[i][j].scaleY = size / 16;
            board[i][j].x = i * size + 5;
            board[i][j].y = (height - j - 1) * size + 64 - 240 - i * 10;

            board[i][j].target =
            { x: 0,
                y: 0};

            board[i][j].i = i;
            board[i][j].j = j;
            board[i][j].checked = false;
            board[i][j].image = game.assets['fruits.png'];
            board[i][j].frame = rand(4) + 1;

            //爆弾
            if (stage > 4 && rand(200) < stage * 2 + 5) {
//                if(true){
                board[i][j].frame = 0;
            }
            game.rootScene.addChild(board[i][j]);
            board[i][j].update = function() {
                this.target.x = this.i * size + 5;
                this.target.y = 320 - (this.j + 1) * size;
            }
            board[i][j].update();
        }
    }
    for (var i = 0; i < width; i++) {
        for (var j = 0; j < height; j++) {
            board[i][j].addEventListener(
                'touchstart',
                function() {
                    click(this.i, this.j)
                }
            );
        }
    }
}

function click(i, j) {
    clearcheck();

    checked = 0;
    check(i, j);

    if (board[i][j].frame == 0) {
        if (checked < 5) {
            damage = Math.ceil(rest / 2);
            rest -= damage;
            setBonus('BOMB!! -' + (damage / game.fps) + 's', 2000);
            var bomb = game.assets['bomb2.wav'].clone();
            bomb.play();
        }
    }

    if (checked > 1) {
        score += Math.pow(checked, 2) * 20;
        if (checked >= 5) {
            bonus = Math.pow(checked - 2, 2) * 10 / (stage + 2);
            rest += bonus;
            setBonus(checked + "Combo +" + (bonus / game.fps).toFixed(1) + 's', 1000);
            var se = game.assets['se6.wav'].clone();
            se.play();
        } else {
            var se = game.assets['se2.wav'].clone();
            se.play();
        }
        //    #("#log").text(score);

        for (var p = width - 1; p >= 0; p--) {
            if (board[p]) {
                if (board[p].length == 0) {
                    board.splice(p, 1);
                } else {
                    for (var q = height - 1; q >= 0; q--) {
                        if (board[p][q] && board[p][q].checked) {
                            game.rootScene.removeChild(board[p][q]);
                            board[p].splice(q, 1);
                        }
                    }
                }
            }
        }

        var newBoard = new Array();
        for (var p = 0; p < width; p++) {
            if (board[p] && board[p].length > 0) {
                for (var q in board[p]) {
                    board[p][q].i = newBoard.length;
                    board[p][q].update();
                }
                newBoard.push(board[p]);
            }
        }
        board = newBoard;
        newBoard = []

        for (var p in board) {
            newBoard[p] = new Array();
            for (var q = 0; q < height; q++) {
                if (board[p][q]) {
                    newBoard[p].push(board[p][q]);
                    board[p][q].j = q;
                    board[p][q].update();
                }
            }
        }
    } else {
        //お手つき
        var se = game.assets['lock2.wav'].clone();
        se.play();
        rest -= stage;
    }
    if (endcheck()) {
        //game.end(score,'スコア:' + score);
        var bonus = stages[stage].bonus;
        rest += bonus;

        stage++;
        game.assets['se7.wav'].play();
        setBonus('STAGE' + stage + ' +' + (bonus / game.fps).toFixed(1), 3000);

        if (!stages[stage]) {
            alert('Game Clear!!!')
        } else {
            clearBoard();
            resetBoard();
        }
    }
}

function clearcheck() {
    for (var p in board) {
        for (var q in board[p]) {
            board[p][q].checked = false;
        }
    }
    checked = 0;
}

function endcheck() {
    for (var p in board) {
        for (var q in board[p]) {
            if (board[p][q].frame == 0)continue;
            clearcheck();
            check(p, q);
            if (checked > 1) {
                return false;
            }
        }
    }
    return true;
}

function check(i, j) {
    if (board[i][j].checked) {
        return false;
    }

    board[i][j].checked = true;
    if (board[i - 1] && board[i - 1][j] && board[i][j].frame == board[i - 1][j].frame) check(i - 1, j);
    if (board[i] && board[i][j - 1] && board[i][j].frame == board[i][j - 1].frame) check(i, j - 1);
    if (board[i + 1] && board[i + 1][j] && board[i][j].frame == board[i + 1][j].frame) check(i + 1, j);
    if (board[i] && board[i][j + 1] && board[i][j].frame == board[i][j + 1].frame) check(i, j + 1);
    checked++;
    return true;
}

function rand(max) {
    return Math.floor(Math.random() * max)
}
<commit_msg>add groups<commit_after>enchant();

var checked = 0;
var stage = 1;
var board, bar, game, scoreGroup, boardGroup,
    score = 0, time = 0, rest = 400, size = 24;

var stages = {
    1: {width: 8, height: 8, bonus: 100},
    2: {width: 10, height: 8, bonus: 100},
    3: {width: 13, height: 8, bonus: 100},
    4: {width: 13, height: 10, bonus: 100},
    5: {width: 13, height: 10, bonus: 100},
    6: {width: 13, height: 10, bonus: 100},
    7: {width: 13, height: 10, bonus: 100},
    8: {width: 13, height: 10, bonus: 100},
    9: {width: 13, height: 10, bonus: 100},
    10: {width: 13, height: 10, bonus: 100}
};

window.onload = function() {
    game = new Core(320, 320);
    game.fps = 20;
    game.preload('fruits.png', 'bar.png', 'se2.wav', 'se6.wav', 'se7.wav', 'lock2.wav', 'jingle03.wav', 'bomb2.wav', 'bomb3.wav');
    scoreGroup = new Group();
    boardGroup = new Group();
    game.rootScene.addChild(boardGroup);
    game.rootScene.addChild(scoreGroup);

    game.onload = function() {
        resetBoard();

        bar = new Sprite(1, 12);
        bar.image = game.assets['bar.png'];
        bar.defaultpos = {x: 16, y: 40};
        rest = Math.max(0, rest);
        bar.width = rest / 2;

        scoreGroup.addChild(bar);
        game.texts = [];
        game.pinch = false;

        game.texts.score = new MutableText(16, 8, game.width, "Score:" + score);
        scoreGroup.addChild(game.texts.score);

        game.texts.time = new MutableText(16, 24, game.width, "Time:" + (rest / game.fps).toFixed(2) + 's');
        scoreGroup.addChild(game.texts.time);

        game.texts.bonus = new MutableText(16, 56, game.width, "");
        scoreGroup.addChild(game.texts.bonus);

        game.timer = [];
    };

    game.rootScene.addEventListener('enterframe',
        function() {
            for (var p in board) {
                for (var q in board[p]) {
                    var fruit = board[p][q];
                    if (fruit.x != fruit.target.x)fruit.x += Math.max(-8, Math.min(10, fruit.target.x - fruit.x));
                    if (fruit.y != fruit.target.y)fruit.y += Math.max(-8, Math.min(10, fruit.target.y - fruit.y));
                    if (rest < 100) {
                        if (!game.pinch) {
                            game.pinch = true;
                            game.assets['jingle03.wav'].play();
                        }
                        fruit.x += rand(3) - 1;
                    } else {
                        if (game.pinch) {
                            game.pinch = false;
                            game.assets['jingle03.wav'].stop();
                        }
                    }
                }
            }

            time ++;
            rest --;
            rest = Math.min(rest, 400);
            bar.width = rest / 2;
            game.texts.time.setText("Time: " + (rest / game.fps).toFixed(2));
            game.texts.score.setText("Score: " + score);

            if (rest == 0) {
                game.end(score, 'スコア: ' + score);
                game.assets['bomb3.wav'].play();
            }

        }
    );
    game.start();
};

function setBonus(bonus, time) {
    game.texts.bonus.setText(bonus)
    if (game.timer.bonus) clearTimeout(game.timer.bonus);
    game.timer.bonus = setTimeout(
        function() {
            game.texts.bonus.setText("");
        }
        , time);
}

function clearBoard() {
    for (var p in board) {
        for (var q in board[p]) {
            boardGroup.removeChild(board[p][q]);
        }
    }
}

function getNumOfFruits() {
    var fruits = 0;
    for (var p in board) {
        for (var q in board[p]) {
            fruits++;
        }
    }
    return fruits;
}

function resetBoard() {
    width = stages[stage].width;
    height = stages[stage].height;

    board = new Array(width);
    for (var i = 0; i < width; i++) {
        board[i] = new Array(height);
        for (var j = 0; j < height; j++) {
            board[i][j] = new Sprite(16, 16);
            board[i][j].scaleX = size / 16;
            board[i][j].scaleY = size / 16;
            board[i][j].x = i * size + 5;
            board[i][j].y = (height - j - 1) * size + 64 - 240 - i * 10;

            board[i][j].target =
            { x: 0,
                y: 0};

            board[i][j].i = i;
            board[i][j].j = j;
            board[i][j].checked = false;
            board[i][j].image = game.assets['fruits.png'];
            board[i][j].frame = rand(4) + 1;

            //爆弾
            if (stage > 4 && rand(200) < stage * 2 + 5) {
//                if(true){
                board[i][j].frame = 0;
            }
            boardGroup.addChild(board[i][j]);
            board[i][j].update = function() {
                this.target.x = this.i * size + 5;
                this.target.y = 320 - (this.j + 1) * size;
            }
            board[i][j].update();
        }
    }
    for (var i = 0; i < width; i++) {
        for (var j = 0; j < height; j++) {
            board[i][j].addEventListener(
                'touchstart',
                function() {
                    click(this.i, this.j)
                }
            );
        }
    }
}

function click(i, j) {
    clearcheck();

    checked = 0;
    check(i, j);

    if (board[i][j].frame == 0) {
        if (checked < 5) {
            damage = Math.ceil(rest / 2);
            rest -= damage;
            setBonus('BOMB!! -' + (damage / game.fps) + 's', 2000);
            var bomb = game.assets['bomb2.wav'].clone();
            bomb.play();
        }
    }

    if (checked > 1) {
        score += Math.pow(checked, 2) * 20;
        if (checked >= 5) {
            bonus = Math.pow(checked - 2, 2) * 10 / (stage + 2);
            rest += bonus;
            setBonus(checked + "Combo +" + (bonus / game.fps).toFixed(1) + 's', 1000);
            var se = game.assets['se6.wav'].clone();
            se.play();
        } else {
            var se = game.assets['se2.wav'].clone();
            se.play();
        }
        //    #("#log").text(score);

        for (var p = width - 1; p >= 0; p--) {
            if (board[p]) {
                if (board[p].length == 0) {
                    board.splice(p, 1);
                } else {
                    for (var q = height - 1; q >= 0; q--) {
                        if (board[p][q] && board[p][q].checked) {
                            boardGroup.removeChild(board[p][q]);
                            board[p].splice(q, 1);
                        }
                    }
                }
            }
        }

        var newBoard = [];
        for (var p = 0; p < width; p++) {
            if (board[p] && board[p].length > 0) {
                for (var q in board[p]) {
                    board[p][q].i = newBoard.length;
                    board[p][q].update();
                }
                newBoard.push(board[p]);
            }
        }
        board = newBoard;
        newBoard = []

        for (var p in board) {
            newBoard[p] = [];
            for (var q = 0; q < height; q++) {
                if (board[p][q]) {
                    newBoard[p].push(board[p][q]);
                    board[p][q].j = q;
                    board[p][q].update();
                }
            }
        }
    } else {
        //お手つき
        var se = game.assets['lock2.wav'].clone();
        se.play();
        rest -= stage;
    }
    if (endcheck()) {
        //game.end(score,'スコア:' + score);
        var bonus = stages[stage].bonus;
        rest += bonus;

        stage++;
        game.assets['se7.wav'].play();
        setBonus('STAGE' + stage + ' +' + (bonus / game.fps).toFixed(1), 3000);

        if (!stages[stage]) {
            alert('Game Clear!!!')
        } else {
            clearBoard();
            resetBoard();
        }
    }
}

function clearcheck() {
    for (var p in board) {
        for (var q in board[p]) {
            board[p][q].checked = false;
        }
    }
    checked = 0;
}

function endcheck() {
    for (var p in board) {
        for (var q in board[p]) {
            if (board[p][q].frame == 0)continue;
            clearcheck();
            check(p, q);
            if (checked > 1) {
                return false;
            }
        }
    }
    return true;
}

function check(i, j) {
    if (board[i][j].checked) {
        return false;
    }

    board[i][j].checked = true;
    if (board[i - 1] && board[i - 1][j] && board[i][j].frame == board[i - 1][j].frame) check(i - 1, j);
    if (board[i] && board[i][j - 1] && board[i][j].frame == board[i][j - 1].frame) check(i, j - 1);
    if (board[i + 1] && board[i + 1][j] && board[i][j].frame == board[i + 1][j].frame) check(i + 1, j);
    if (board[i] && board[i][j + 1] && board[i][j].frame == board[i][j + 1].frame) check(i, j + 1);
    checked++;
    return true;
}

function rand(max) {
    return Math.floor(Math.random() * max)
}
<|endoftext|>


<commit_before>var widgets = require('jupyter-js-widgets');
var _ = require('underscore');

var GoogleMapsLoader = require('google-maps');
GoogleMapsLoader.LIBRARIES = ["visualization"] ;

function gPointToList(gpoint) {
    return [gpoint.lat(), gpoint.lng()];
}

function gBoundsToList(gbounds) {
    var sw = gPointToList(gbounds.getSouthWest());
    var ne = gPointToList(gbounds.getNorthEast());
    return [sw, ne]
}

var GMapsLayerView = widgets.WidgetView.extend({
    initialize: function(parameters) {
        GMapsLayerView.__super__.initialize.apply(this, arguments);
        this.map_view = this.options.map_view ;
    }
});

var HeatmapLayerView = GMapsLayerView.extend({
    render: function() {
        this.model.on("change:point_radius", this.update_radius, this);
        this.model.on("change:max_intensity", this.update_max_intensity, this);
        var that = this ;
        GoogleMapsLoader.load(function(google) {
            var data = that.model.get("data");
            var data_as_google = new google.maps.MVCArray(
                _.map(data, function(point) {
                    return new google.maps.LatLng(point[0], point[1]);
                })
            );
            that.heatmap = new google.maps.visualization.HeatmapLayer({
                data: data_as_google,
                radius: that.model.get("point_radius"),
                maxIntensity: that.model.get("max_intensity")
            }) ;
        });
    },

    add_to_map_view: function(map_view) {
        this.heatmap.setMap(map_view.map) ;
    },

    update_radius: function() {
        this.heatmap.set('radius', this.model.get('point_radius'));
    },

    update_max_intensity: function() {
        console.log("max_intensity change");
        this.heatmap.set('maxIntensity', this.model.get('max_intensity'));
    }

});

var GMapsLayerModel = widgets.WidgetModel.extend({
    defaults: _.extend({}, widgets.WidgetModel.prototype.defaults, {
        _view_name : 'GMapsLayerView',
        _model_name : 'GMapsLayerModel',
        _view_module : 'jupyter-gmaps',
        _model_module : 'jupyter-gmaps',
        bottom : false,
        options : []
    })
});

var HeatmapLayerModel = GMapsLayerModel.extend({
    defaults: _.extend({}, GMapsLayerModel.prototype.defaults, {
        _view_name: "HeatmapLayerView",
        _model_name: "HeatmapLayerModel"
    })
})

var PlainmapView = widgets.DOMWidgetView.extend({
    render: function() {
        this.el.style["width"] = this.model.get("width");
        this.el.style["height"] = this.model.get("height");

        var initial_zoom = this.model.get("zoom");
        this.model.on("change:zoom", this.update_zoom, this);

        var initial_center = this.model.get("center");
        this.model.on("change:center", this.update_center, this);

        var initial_bounds = this.model.get("data_bounds");
        this.model.on("change:data_bounds", this.update_bounds, this);

        this.layer_views = new widgets.ViewList(this.add_layer_model, null, this);

        var that = this ;
        this.on("displayed", function() {
            GoogleMapsLoader.load(function(google) {
                that.map = new google.maps.Map(that.el) ;
                that.update_bounds(initial_bounds);

                that.layer_views.update(that.model.get("layers"));

                // hack to force the map to redraw
                window.setTimeout(function() {
                    google.maps.event.trigger(that.map, 'resize') ;
                }, 1000);
            }) ;
        });
    },

    update_bounds: function() {
        var model_bounds = this.model.get("data_bounds");
        var bounds_bl = new google.maps.LatLng(
            model_bounds[0][0], model_bounds[0][1]);
        var bounds_tr = new google.maps.LatLng(
            model_bounds[1][0], model_bounds[1][1]);
        var bounds = new google.maps.LatLngBounds(bounds_bl, bounds_tr)
        this.map.fitBounds(bounds);
    },

    add_layer_model: function(child_model) {
        var that = this;
        return this.create_child_view(child_model, {map_view: this}).then(function(child_view) {
            child_view.add_to_map_view(that) ;
            return child_view;
        })
    }

});

var PlainmapModel = widgets.DOMWidgetModel.extend({
    defaults: _.extend({}, widgets.DOMWidgetModel.prototype.defaults, {
        _view_name: "PlainmapView",
        _model_name: "PlainmapModel",
        _view_module : 'jupyter-gmaps',
        _model_module : 'jupyter-gmaps',
        width: "600px",
        height: "400px"

    })
}, {
    serializers: _.extend({
            layers: {deserialize: widgets.unpack_models}
    }, widgets.DOMWidgetModel.serializers)
});

module.exports = {
    HeatmapLayerModel: HeatmapLayerModel,
    HeatmapLayerView: HeatmapLayerView,
    PlainmapView: PlainmapView,
    PlainmapModel: PlainmapModel
};
<commit_msg>Refactor javascript.<commit_after>var widgets = require('jupyter-js-widgets');
var _ = require('underscore');

var GoogleMapsLoader = require('google-maps');
GoogleMapsLoader.LIBRARIES = ["visualization"] ;

function gPointToList(gpoint) {
    return [gpoint.lat(), gpoint.lng()];
}

function gBoundsToList(gbounds) {
    var sw = gPointToList(gbounds.getSouthWest());
    var ne = gPointToList(gbounds.getNorthEast());
    return [sw, ne]
}

var GMapsLayerView = widgets.WidgetView.extend({
    initialize: function(parameters) {
        GMapsLayerView.__super__.initialize.apply(this, arguments);
        this.map_view = this.options.map_view ;
    }
});

var HeatmapLayerView = GMapsLayerView.extend({
    render: function() {
        this.model_events() ;
        var that = this ;
        GoogleMapsLoader.load(function(google) {
            var data = that.model.get("data");
            var data_as_google = new google.maps.MVCArray(
                _.map(data, function(point) {
                    return new google.maps.LatLng(point[0], point[1]);
                })
            );
            that.heatmap = new google.maps.visualization.HeatmapLayer({
                data: data_as_google,
                radius: that.model.get("point_radius"),
                maxIntensity: that.model.get("max_intensity")
            }) ;
        });
    },

    add_to_map_view: function(map_view) {
        this.heatmap.setMap(map_view.map) ;
    },

    model_events: function() {
        this.model.on("change:point_radius", this.update_radius, this);
        this.model.on("change:max_intensity", this.update_max_intensity, this);
    },

    update_radius: function() {
        this.heatmap.set('radius', this.model.get('point_radius'));
    },

    update_max_intensity: function() {
        console.log("max_intensity change");
        this.heatmap.set('maxIntensity', this.model.get('max_intensity'));
    }

});

var GMapsLayerModel = widgets.WidgetModel.extend({
    defaults: _.extend({}, widgets.WidgetModel.prototype.defaults, {
        _view_name : 'GMapsLayerView',
        _model_name : 'GMapsLayerModel',
        _view_module : 'jupyter-gmaps',
        _model_module : 'jupyter-gmaps',
        bottom : false,
        options : []
    })
});

var HeatmapLayerModel = GMapsLayerModel.extend({
    defaults: _.extend({}, GMapsLayerModel.prototype.defaults, {
        _view_name: "HeatmapLayerView",
        _model_name: "HeatmapLayerModel"
    })
})

var PlainmapView = widgets.DOMWidgetView.extend({
    render: function() {
        this.el.style["width"] = this.model.get("width");
        this.el.style["height"] = this.model.get("height");

        var initial_bounds = this.model.get("data_bounds");

        this.layer_views = new widgets.ViewList(this.add_layer_model, null, this);
        this.model_events() ;

        var that = this ;
        this.on("displayed", function() {
            GoogleMapsLoader.load(function(google) {
                that.map = new google.maps.Map(that.el) ;
                that.update_bounds(initial_bounds);

                that.layer_views.update(that.model.get("layers"));

                // hack to force the map to redraw
                window.setTimeout(function() {
                    google.maps.event.trigger(that.map, 'resize') ;
                }, 1000);
            }) ;
        });
    },

    model_events: function() {
        this.model.on("change:data_bounds", this.update_bounds, this);
    },

    gmaps_events: function() {},

    update_bounds: function() {
        var model_bounds = this.model.get("data_bounds");
        var bounds_bl = new google.maps.LatLng(
            model_bounds[0][0], model_bounds[0][1]);
        var bounds_tr = new google.maps.LatLng(
            model_bounds[1][0], model_bounds[1][1]);
        var bounds = new google.maps.LatLngBounds(bounds_bl, bounds_tr)
        this.map.fitBounds(bounds);
    },

    add_layer_model: function(child_model) {
        var that = this;
        return this.create_child_view(child_model, {map_view: this}).then(function(child_view) {
            child_view.add_to_map_view(that) ;
            return child_view;
        })
    }

});

var PlainmapModel = widgets.DOMWidgetModel.extend({
    defaults: _.extend({}, widgets.DOMWidgetModel.prototype.defaults, {
        _view_name: "PlainmapView",
        _model_name: "PlainmapModel",
        _view_module : 'jupyter-gmaps',
        _model_module : 'jupyter-gmaps',
        width: "600px",
        height: "400px"

    })
}, {
    serializers: _.extend({
            layers: {deserialize: widgets.unpack_models}
    }, widgets.DOMWidgetModel.serializers)
});

module.exports = {
    HeatmapLayerModel: HeatmapLayerModel,
    HeatmapLayerView: HeatmapLayerView,
    PlainmapView: PlainmapView,
    PlainmapModel: PlainmapModel
};
<|endoftext|>


<commit_before>var os = require('os');

module.exports = exports = function (app, routeToBind,config) {
    app.use(routeToBind, function (request, response, next) {
            response.json(
                {
                    'current_time': (new Date().toLocaleString()),
                    'NODE_ENV': process.env.NODE_ENV,
                    'OS':{
                        'hostname':os.hostname(),
                        'arch':os.arch(),
                        'type':os.type(),
                        'platform':os.platform(),
                        'release':os.release(),
                        'NodeJS version':process.version
                    }
                });
            //next(); - there is no any other things to happen later
        }
    )
}
<commit_msg>more functions in example<commit_after>var os = require('os');

module.exports = exports = function (MWC) {

    //setting up the middleware
    MWC.app.use('/config', function (request, response, next) {
            response.json(
                {
                    'current_time': (new Date().toLocaleString()),
                    'NODE_ENV': process.env.NODE_ENV,
                    'OS':{
                        'hostname':os.hostname(),
                        'arch':os.arch(),
                        'type':os.type(),
                        'platform':os.platform(),
                        'release':os.release(),
                        'NodeJS version':process.version
                    }
                });
            //next(); - there is no any other things to happen later
            //so, the '/example/time' will never be executed
        }
    );

    //this route is not executed, because it is overlaped by middleware above
    MWC.app.get('/config/time',function(request,response){
        response.send('Current time is '+(new Date().toLocaleString()));
    });

    //but this route is executed
    MWC.app.get('/time',function(request,response){
        response.send('Current time is '+(new Date().toLocaleString()));
    });

    //setting index
    MWC.app.get('/',function(req,res){
        res.send('' +
            'MyWebClass Core Example' +
            '' +
            '
Hello, friend! You can do this things:

' +
            '
See current time
' +
            '
See team on this server
' +
            '
See all redis keys stored
' +
            '
See this server parameters
' +
            '
See users api endpoint on this server
' +
            '
See plugins installed on this server
' +
            '
See this application source on Github
' +
            '
' +
            '');
    });

    //we use Mongoose Model in this route
    MWC.app.get('/team',function(request,response){
        request.MODEL.Users.find({active:1},function(err,users){
           if(err) throw err;
           response.json({'Team':users});
        });
    });
    //we use exposed Redis client. In a rather stupid way.
    MWC.app.get('/redis',function(request,response){
       request.redisClient.keys('*',function(err,keys){
           response.json(keys);
       });
    });

    // making mechanical clock with artifical bird in it)
    // MWC emits event of 'coocoo' with current time every 5 seconds
    setInterval(function(){
        MWC.emit('Coocoo!','Time now is '+(new Date().toLocaleTimeString()));
    },5000);
}
<|endoftext|>


<commit_before>// We first require our express package
var express = require('express');
var bodyParser = require('body-parser');
var recipeData = require('./data_recipe.js');
var myData = require('./data_users.js');

// This package exports the function to create an express instance:
var app = express();

// We can setup Jade now!
app.set('view engine', 'ejs');

// This is called 'adding middleware', or things that will help parse your request
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

// This middleware will activate for every request we make to
// any path starting with /assets;
// it will check the 'static' folder for matching files
app.use('/assets', express.static('static'));

// Setup your routes here!

app.get("/home", function (request, response) {
    response.render("pages/product_category", { pageTitle: "Welcome Home" });

});

app.get("/", function (request, response) {
    // We have to pass a second parameter to specify the root directory
    // __dirname is a global variable representing the file directory you are currently in
    response.sendFile("./pages/index.html", { root: __dirname });
});

app.get("/product/category/:category",function (request, response){
    var category = request.params.category;
    recipeData.getCategory(category).then(function(result){
        for(var i=0; i<result.length; i++)
        {
            result[i] = recipeData.totalPrice(result[i]);
        }
        console.log(result);
        response.render("pages/product_category", {resultData : result})
    });
});

app.post("/search",function (request, response){
    var keyword = request.body.keyword;

    recipeData.searchDB(keyword).then(function(result) {

        for(var i=0; i<result.length; i++)
        {
            result[i] = recipeData.totalPrice(result[i]);
        }
        response.render("pages/search_results",{resultData : result, keyword : keyword})
    });
});

app.get("/products/:id", function(request,response){
    console.log(request.params.id);
    recipeData.getRecipe(request.params.id).then(function(recipe){
        response.render("pages/product",{resultData: recipe});
    },function(errorMessage) {
        response.status(500).json({ error: errorMessage });
    });
});

// We can now navigate to localhost:3000
app.listen(3000, function () {
    console.log('Your server is now listening on port 3000! Navigate to http://localhost:3000 to access it');
});
<commit_msg>Test Commit<commit_after>// We first require our express package
var express = require('express');
var bodyParser = require('body-parser');
var recipeData = require('./data_recipe.js');
var myData = require('./data_users.js');

// This package exports the function to create an express instance:
var app = express();

// We can setup Jade now!
app.set('view engine', 'ejs');

// This is called 'adding middleware', or things that will help parse your request
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

// This middleware will activate for every request we make to
// any path starting with /assets;
// it will check the 'static' folder for matching files
app.use('/assets', express.static('static'));

// Setup your routes here!

app.get("/home", function (request, response) {
    response.render("pages/search_results", { pageTitle: "Welcome Home" });

});

app.get("/", function (request, response) {
    // We have to pass a second parameter to specify the root directory
    // __dirname is a global variable representing the file directory you are currently in
    response.sendFile("./pages/index.html", { root: __dirname });
});

app.get("/product/category/:category",function (request, response){
    var category = request.params.category;
    recipeData.getCategory(category).then(function(result){
        for(var i=0; i<result.length; i++)
        {
            result[i] = recipeData.totalPrice(result[i]);
        }
        console.log(result);
        response.render("pages/product_category", {resultData : result})
    });
});

app.post("/search",function (request, response){
    var keyword = request.body.keyword;

    recipeData.searchDB(keyword).then(function(result) {

        for(var i=0; i<result.length; i++)
        {
            result[i] = recipeData.totalPrice(result[i]);
        }
        response.render("pages/search_results",{resultData : result, keyword : keyword})
    });
});

app.get("/products/:id", function(request,response){
    console.log(request.params.id);
    recipeData.getRecipe(request.params.id).then(function(recipe){
        response.render("pages/product",{resultData: recipe});
    },function(errorMessage) {
        response.status(500).json({ error: errorMessage });
    });
});

// We can now navigate to localhost:3000
app.listen(3000, function () {
    console.log('Your server is now listening on port 3000! Navigate to http://localhost:3000 to access it');
});
<|endoftext|>


<commit_before>"use strict";
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Authors
		Tobias Koppers @sokra
		Johannes Ewald @jhnns
*/
var less = require("less");
var fs = require("fs");
var loaderUtils = require("loader-utils");
var path = require("path");

var trailingSlash = /[\\\/]$/;

module.exports = function(source) {
	var loaderContext = this;
	var query = loaderUtils.parseQuery(this.query);
	var cb = this.async();
	var isSync = typeof cb !== "function";
	var finalCb = cb || this.callback;
	var configKey = query.config || 'lessLoader';
	var config = {
		filename: this.resource,
		paths: [],
		relativeUrls: true,
		compress: !!this.minimize
	};
	var webpackPlugin = {
		install: function(less, pluginManager) {
			var WebpackFileManager = getWebpackFileManager(less, loaderContext, query, isSync);

			pluginManager.addFileManager(new WebpackFileManager());
		},
		minVersion: [2, 1, 1]
	};

	this.cacheable && this.cacheable();

	Object.keys(query).forEach(function(attr) {
		config[attr] = query[attr];
	});

	// Now we're adding the webpack plugin, because there might have
	// been added some before via query-options.
	config.plugins = config.plugins || [];
	config.plugins.push(webpackPlugin);

	// If present, add custom LESS plugins.
	if (this.options[configKey]) {
		config.plugins = config.plugins.concat(this.options[configKey].lessPlugins || []);
	}

	// not using the `this.sourceMap` flag because css source maps are different
	// @see https://github.com/webpack/css-loader/pull/40
	if (query.sourceMap) {
		config.sourceMap = {
			outputSourceFiles: true
		};
	}

	less.render(source, config, function(e, result) {
		var parsedMap;
		var cb = finalCb;
		// Less is giving us double callbacks sometimes :(
		// Thus we need to mark the callback as "has been called"
		if(!finalCb) return;
		finalCb = null;
		if(e) return cb(formatLessRenderError(e));

		if (result.map) {
			parsedMap = JSON.parse(result.map);

			parsedMap.sources = parsedMap.sources.map(function(file) {
				return path.basename(file);
			});

			result.map = JSON.stringify(parsedMap);
		}

		cb(null, result.css, result.map);
	});
};

function getWebpackFileManager(less, loaderContext, query, isSync) {

	function WebpackFileManager() {
		less.FileManager.apply(this, arguments);
	}

	WebpackFileManager.prototype = Object.create(less.FileManager.prototype);

	WebpackFileManager.prototype.supports = function(filename, currentDirectory, options, environment) {
		// Our WebpackFileManager handles all the files
		return true;
	};

	WebpackFileManager.prototype.supportsSync = WebpackFileManager.prototype.supports;

	WebpackFileManager.prototype.loadFile = function(filename, currentDirectory, options, environment, callback) {
		// Unfortunately we don't have any influence on less to call `loadFile` or `loadFileSync`
		// thus we need to decide for ourselves.
		// @see https://github.com/less/less.js/issues/2325
		if (isSync) {
			try {
				callback(null, this.loadFileSync(filename, currentDirectory, options, environment));
			} catch (err) {
				callback(err);
			}

			return;
		}

		var moduleRequest = loaderUtils.urlToRequest(filename, query.root);
		// Less is giving us trailing slashes, but the context should have no trailing slash
		var context = currentDirectory.replace(trailingSlash, "");

		loaderContext.resolve(context, moduleRequest, function(err, filename) {
			if(err) {
				callback(err);
				return;
			}

			loaderContext.dependency && loaderContext.dependency(filename);
			// The default (asynchronous)
			loaderContext.loadModule("-!" + __dirname + "/stringify.loader.js!" + filename, function(err, data) {
				if(err) {
					callback(err);
					return;
				}

				callback(null, {
					contents: JSON.parse(data),
					filename: filename
				});
			});
		});
	};

	WebpackFileManager.prototype.loadFileSync = function(filename, currentDirectory, options, environment) {
		var moduleRequest = loaderUtils.urlToRequest(filename, query.root);
		// Less is giving us trailing slashes, but the context should have no trailing slash
		var context = currentDirectory.replace(trailingSlash, "");
		var data;

		filename = loaderContext.resolveSync(context, moduleRequest);
		loaderContext.dependency && loaderContext.dependency(filename);
		data = fs.readFileSync(filename, "utf8");

		return {
			contents: data,
			filename: filename
		};
	};

	return WebpackFileManager;
}

function formatLessRenderError(e) {
	// Example ``e``:
	//	{ type: 'Name',
	//		message: '.undefined-mixin is undefined',
	//		filename: '/path/to/style.less',
	//		index: 352,
	//		line: 31,
	//		callLine: NaN,
	//		callExtract: undefined,
	//		column: 6,
	//		extract:
	//		 [ '    .my-style {',
	//		 '      .undefined-mixin;',
	//		 '      display: block;' ] }
	var extract = e.extract? "\n near lines:\n   " + e.extract.join("\n   ") : "";
	var err = new Error(
		e.message + "\n @ " + e.filename +
		" (line " + e.line + ", column " + e.column + ")" +
		extract
	);
	err.hideStack = true;
	return err;
}
<commit_msg>Use double-quotes<commit_after>"use strict";
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Authors
		Tobias Koppers @sokra
		Johannes Ewald @jhnns
*/
var less = require("less");
var fs = require("fs");
var loaderUtils = require("loader-utils");
var path = require("path");

var trailingSlash = /[\\\/]$/;

module.exports = function(source) {
	var loaderContext = this;
	var query = loaderUtils.parseQuery(this.query);
	var cb = this.async();
	var isSync = typeof cb !== "function";
	var finalCb = cb || this.callback;
	var configKey = query.config || "lessLoader";
	var config = {
		filename: this.resource,
		paths: [],
		relativeUrls: true,
		compress: !!this.minimize
	};
	var webpackPlugin = {
		install: function(less, pluginManager) {
			var WebpackFileManager = getWebpackFileManager(less, loaderContext, query, isSync);

			pluginManager.addFileManager(new WebpackFileManager());
		},
		minVersion: [2, 1, 1]
	};

	this.cacheable && this.cacheable();

	Object.keys(query).forEach(function(attr) {
		config[attr] = query[attr];
	});

	// Now we're adding the webpack plugin, because there might have
	// been added some before via query-options.
	config.plugins = config.plugins || [];
	config.plugins.push(webpackPlugin);

	// If present, add custom LESS plugins.
	if (this.options[configKey]) {
		config.plugins = config.plugins.concat(this.options[configKey].lessPlugins || []);
	}

	// not using the `this.sourceMap` flag because css source maps are different
	// @see https://github.com/webpack/css-loader/pull/40
	if (query.sourceMap) {
		config.sourceMap = {
			outputSourceFiles: true
		};
	}

	less.render(source, config, function(e, result) {
		var parsedMap;
		var cb = finalCb;
		// Less is giving us double callbacks sometimes :(
		// Thus we need to mark the callback as "has been called"
		if(!finalCb) return;
		finalCb = null;
		if(e) return cb(formatLessRenderError(e));

		if (result.map) {
			parsedMap = JSON.parse(result.map);

			parsedMap.sources = parsedMap.sources.map(function(file) {
				return path.basename(file);
			});

			result.map = JSON.stringify(parsedMap);
		}

		cb(null, result.css, result.map);
	});
};

function getWebpackFileManager(less, loaderContext, query, isSync) {

	function WebpackFileManager() {
		less.FileManager.apply(this, arguments);
	}

	WebpackFileManager.prototype = Object.create(less.FileManager.prototype);

	WebpackFileManager.prototype.supports = function(filename, currentDirectory, options, environment) {
		// Our WebpackFileManager handles all the files
		return true;
	};

	WebpackFileManager.prototype.supportsSync = WebpackFileManager.prototype.supports;

	WebpackFileManager.prototype.loadFile = function(filename, currentDirectory, options, environment, callback) {
		// Unfortunately we don't have any influence on less to call `loadFile` or `loadFileSync`
		// thus we need to decide for ourselves.
		// @see https://github.com/less/less.js/issues/2325
		if (isSync) {
			try {
				callback(null, this.loadFileSync(filename, currentDirectory, options, environment));
			} catch (err) {
				callback(err);
			}

			return;
		}

		var moduleRequest = loaderUtils.urlToRequest(filename, query.root);
		// Less is giving us trailing slashes, but the context should have no trailing slash
		var context = currentDirectory.replace(trailingSlash, "");

		loaderContext.resolve(context, moduleRequest, function(err, filename) {
			if(err) {
				callback(err);
				return;
			}

			loaderContext.dependency && loaderContext.dependency(filename);
			// The default (asynchronous)
			loaderContext.loadModule("-!" + __dirname + "/stringify.loader.js!" + filename, function(err, data) {
				if(err) {
					callback(err);
					return;
				}

				callback(null, {
					contents: JSON.parse(data),
					filename: filename
				});
			});
		});
	};

	WebpackFileManager.prototype.loadFileSync = function(filename, currentDirectory, options, environment) {
		var moduleRequest = loaderUtils.urlToRequest(filename, query.root);
		// Less is giving us trailing slashes, but the context should have no trailing slash
		var context = currentDirectory.replace(trailingSlash, "");
		var data;

		filename = loaderContext.resolveSync(context, moduleRequest);
		loaderContext.dependency && loaderContext.dependency(filename);
		data = fs.readFileSync(filename, "utf8");

		return {
			contents: data,
			filename: filename
		};
	};

	return WebpackFileManager;
}

function formatLessRenderError(e) {
	// Example ``e``:
	//	{ type: 'Name',
	//		message: '.undefined-mixin is undefined',
	//		filename: '/path/to/style.less',
	//		index: 352,
	//		line: 31,
	//		callLine: NaN,
	//		callExtract: undefined,
	//		column: 6,
	//		extract:
	//		 [ '    .my-style {',
	//		 '      .undefined-mixin;',
	//		 '      display: block;' ] }
	var extract = e.extract? "\n near lines:\n   " + e.extract.join("\n   ") : "";
	var err = new Error(
		e.message + "\n @ " + e.filename +
		" (line " + e.line + ", column " + e.column + ")" +
		extract
	);
	err.hideStack = true;
	return err;
}
<|endoftext|>


<commit_before>function parseDate(dateString) {
	var datesArray =  dateString.match(/[^\d\s]+\s\d+/g);
	if (datesArray) {
		return datesArray.map(function(dateS) { return Date.parse(dateS) });
	}
	else {
		return [99,99];
	}
}
function helpLink() {
	var className = this.firstChild.className;
	var items = document.getElementsByClassName(className);

	for (i in items) {

		if ( i == items.length - 1) {items[0].parentNode.scrollIntoView(); return false;}

		if (items[i].parentNode.getBoundingClientRect().bottom - items[i].parentNode.getBoundingClientRect().height  > 0) {
		items[i].parentNode.scrollIntoView();
		return false;}

	};

}
function ms2days(ms) {
	return ms/1000/60/60/24;
}
function generateCss(from_delivery) {

	var css_result = "";

	function updateColorScheme(levels) {
		var count = 0
		var count2 = 0;
		for (l in levels) count++;
		scheme = {0 : '{color : limegreen}',
				  1 : '{color : gold}',
				  2 : '{color : orange}',
				  3 : '{color : red}',
				  4 : '{color : brown}'};

		if (count < 5) delete scheme[4]
		if (count < 4) delete scheme[2]
		if (count < 3) delete scheme[1]
		if (count < 2) delete scheme[3]

		scheme_list = [];
		for (color in scheme) scheme_list.push(scheme[color]);
		for (l in levels) {levels[l] = scheme_list[count2]; count2++};
	}

	var unique = {};
	from_delivery.forEach(function(item) {unique[item] = item});
	updateColorScheme(unique);

	for (item in unique) css_result += '.my_dynclass' + item + ' ' + unique[item] + ' ';

	return css_result;
}
function main() {

	var from_delivery = [];
	var results=document.getElementById("ResultSetItems").getElementsByTagName("table");

	var url;

	// array of all xhr ojects
	var xhr = [];

	// how much accual reuqests were initialized
	var requests_count = 0;

	for (var i = 0; i < results.length; i++) {

	// url to the item page
	url = results[i].getElementsByClassName("vip")[0].href;

	// helps reduce number of requests if there is no shipping anyway
	shipping_details = results[i].getElementsByClassName("ship")[0];
	if((!(shipping_details)) ||shipping_details.innerText.indexOf("not") != -1) continue;

	requests_count++;
	xhr.push(new XMLHttpRequest());

	// async requests
	xhr[xhr.length-1].open("GET", url, true);

	// there is need to assign the onreadystatechange this way
	// otherwise the function is contact with index = 0
	var waitinf_for_text=document.createElement("div");
	waitinf_for_text.className="waitfor";
	waitinf_for_text.innerText="waiting for data..";
	results[xhr.length-1].getElementsByClassName("dtl dtlsp")[0].appendChild(waitinf_for_text);
	xhr[xhr.length-1].onreadystatechange = function(index) {

		return function() {
			  if (xhr[index].readyState == 4 && xhr[index].status == 200) {

				results[index].getElementsByClassName("dtl dtlsp")[0].removeChild(results[index].getElementsByClassName("dtl dtlsp")[0].lastChild);
				var parser=new DOMParser();
				var res=parser.parseFromString(xhr[index].responseText,"text/html");

				if (!(res)){return;};
				var seller_node = res.getElementsByClassName("mbg-nw")[0];
				var item_desc = res.getElementById("vi-lkhdr-itmTitl").innerText;

				// add estimated date for delivery to the item
				var estimated_date = res.getElementsByClassName("sh-del-frst")[0].childNodes[1];
				estimated_date.style.lineHeight ="1.25em";

				// attach a dynamic class to the estimate date
				var fd = ms2days((parseDate(estimated_date.innerText)[0] - parseDate(Date())[0]));
				var td = ms2days((parseDate(estimated_date.innerText)[1] - parseDate(Date())[0]));
				var delivery_date = parseDate(estimated_date.innerText);

				var val = Math.round(Math.sqrt(Math.pow(fd,2) + Math.pow(td,2)));
				from_delivery.push(val);
				estimated_date.className += " my_dynclass" + val;
				results[index].getElementsByClassName("dtl dtlsp")[0].appendChild(estimated_date);

				// add seller rank to the item
				var rank = res.getElementById("si-fb");
				rank.className = "logos";
				results[index].getElementsByClassName("dtl dtlsp")[0].appendChild(rank);

				// add external url for a feed about the seller to the item
				var feedback_url=document.createElement("a");
				feedback_url.href = "http://www.feedbackselector.com/feedsearch.php?seller=" + seller_node.innerText + "&itemName=" + item_desc;
				feedback_url.innerText = "feedbacks";
				feedback_url.target = "blank";
				results[index].getElementsByClassName("dtl dtlsp")[0].appendChild(feedback_url);

			}
		}
		}(xhr.length-1);

		xhr[xhr.length-1].send();

	}
	console.log("Number of requests initialized: " + xhr.length + "/" + results.length);

	// add css configurations
	var styleSheetElement = document.createElement("style");
	styleSheetElement.type = "text/css";
	document.getElementsByTagName("head")[0].appendChild(styleSheetElement);

	var divElement = document.createElement("div");
	document.getElementsByTagName("body")[0].appendChild(divElement);
	divElement.id = "tstid";
	divElement.style.position = "fixed";
	divElement.style.top = "0";
	divElement.style.width = "10%";
	divElement.style.paddingTop = "3%";

	divElement.innerHTML = "

";
	var check = setInterval(function(){
		if(updateContent(styleSheetElement, from_delivery) &&
		  (xhr.length == from_delivery.length) &&
		  (document.getElementsByClassName("waitfor").length == 0)) {

		window.clearInterval(check);
		updateContent(styleSheetElement, from_delivery);
		}
		}, 1000);

}

function  generateHelp(from_delivery) {
	var result = document.createElement("ul");
	result.style.fontWeight = "bold";
	var unique = {};
	from_delivery.forEach(function(item) {unique[item] = item});

	for (id in unique) {
		var items = document.getElementsByClassName("my_dynclass" + id);
		unique[id] = items[0].cloneNode(true);
		unique[id].style.display="block";
		unique[id].textContent = unique[id].textContent.replace("Estimated between","");
		unique[id].textContent = "(" + (items.length -1) + ") " +unique[id].textContent

	}

	for (id in unique) {
	var il = document.createElement("il");
	il.appendChild(unique[id]);
	il.addEventListener("click" ,helpLink);
	result.appendChild(il);
	};

	return result;
}

function updateContent(styleSheetElement, from_delivery) {
styleSheetElement.innerHTML = generateCss(from_delivery);

document.getElementById("tstid").replaceChild(generateHelp(from_delivery),document.getElementById("tstid").firstChild);

}

main();<commit_msg>bug fix<commit_after>function parseDate(dateString) {
	var datesArray =  dateString.match(/[^\d\s]+\s\d+/g);
	if (datesArray) {
		return datesArray.map(function(dateS) { return Date.parse(dateS) });
	}
	else {
		return [99,99];
	}
}
function helpLink() {
	var className = this.firstChild.className;
	var items = document.getElementsByClassName(className);

	for (i in items) {

		if ( i == items.length - 1) {items[0].parentNode.scrollIntoView(); return false;}

		if (items[i].parentNode.getBoundingClientRect().bottom - items[i].parentNode.getBoundingClientRect().height  > 0) {
		items[i].parentNode.scrollIntoView();
		return false;}

	};

}
function ms2days(ms) {
	return ms/1000/60/60/24;
}
function generateCss(from_delivery) {

	var css_result = "";

	function updateColorScheme(levels) {
		var count = 0
		var count2 = 0;
		for (l in levels) count++;
		scheme = {0 : '{color : limegreen}',
				  1 : '{color : gold}',
				  2 : '{color : orange}',
				  3 : '{color : red}',
				  4 : '{color : brown}'};

		if (count < 5) delete scheme[4]
		if (count < 4) delete scheme[2]
		if (count < 3) delete scheme[1]
		if (count < 2) delete scheme[3]

		scheme_list = [];
		for (color in scheme) scheme_list.push(scheme[color]);
		for (l in levels) {levels[l] = scheme_list[count2]; count2++};
	}

	var unique = {};
	from_delivery.forEach(function(item) {unique[item] = item});
	updateColorScheme(unique);

	for (item in unique) css_result += '.my_dynclass' + item + ' ' + unique[item] + ' ';

	return css_result;
}
function main() {

	var from_delivery = [];
	var results=document.getElementById("ResultSetItems").getElementsByTagName("table");

	var url;

	// array of all xhr ojects
	var xhr = [];

	// how much accual reuqests were initialized
	var requests_count = 0;

	for (var i = 0; i < results.length; i++) {

	// url to the item page
	url = results[i].getElementsByClassName("vip")[0].href;

	// helps reduce number of requests if there is no shipping anyway
	shipping_details = results[i].getElementsByClassName("ship")[0];
	if((!(shipping_details)) ||shipping_details.innerText.indexOf("not") != -1) continue;

	requests_count++;
	xhr.push(new XMLHttpRequest());

	// async requests
	xhr[xhr.length-1].open("GET", url, true);

	// there is need to assign the onreadystatechange this way
	// otherwise the function is contact with index = 0
	var waitinf_for_text=document.createElement("div");
	waitinf_for_text.className="waitfor";
	waitinf_for_text.innerText="waiting for data..";
	results[xhr.length-1].getElementsByClassName("dtl dtlsp")[0].appendChild(waitinf_for_text);
	xhr[xhr.length-1].onreadystatechange = function(index) {

		return function() {
			  if (xhr[index].readyState == 4 && xhr[index].status == 200) {

				results[index].getElementsByClassName("dtl dtlsp")[0].removeChild(results[index].getElementsByClassName("dtl dtlsp")[0].lastChild);
				var parser=new DOMParser();
				var res=parser.parseFromString(xhr[index].responseText,"text/html");

				if (!(res)){return;};
				var seller_node = res.getElementsByClassName("mbg-nw")[0];
				var item_desc = res.getElementById("vi-lkhdr-itmTitl").innerText;

				// add estimated date for delivery to the item
				var estimated_date = res.getElementsByClassName("sh-del-frst")[0].childNodes[1];
				if(!(estimated_date)) {
					estimated_date = document.createElement("div");
					estimated_date.appendChild(document.createElement("span"));
					estimated_date.firstChild.className = "vi-acc-del-range";
					estimated_date.firstChild.textContent = "Unknown";
				}
				estimated_date.style.lineHeight ="1.25em";

				// attach a dynamic class to the estimate date
				var fd = ms2days((parseDate(estimated_date.innerText)[0] - parseDate(Date())[0]));
				var td = ms2days((parseDate(estimated_date.innerText)[1] - parseDate(Date())[0]));
				var delivery_date = parseDate(estimated_date.innerText);

				var val = Math.round(Math.sqrt(Math.pow(fd,2) + Math.pow(td,2)));
				from_delivery.push(val);
				estimated_date.className += " my_dynclass" + val;
				results[index].getElementsByClassName("dtl dtlsp")[0].appendChild(estimated_date);

				// add seller rank to the item
				var rank = res.getElementById("si-fb");
				rank.className = "logos";
				results[index].getElementsByClassName("dtl dtlsp")[0].appendChild(rank);

				// add external url for a feed about the seller to the item
				var feedback_url=document.createElement("a");
				feedback_url.href = "http://www.feedbackselector.com/feedsearch.php?seller=" + seller_node.innerText + "&itemName=" + item_desc;
				feedback_url.innerText = "feedbacks";
				feedback_url.target = "blank";
				results[index].getElementsByClassName("dtl dtlsp")[0].appendChild(feedback_url);

			}
		}
		}(xhr.length-1);

		xhr[xhr.length-1].send();

	}
	console.log("Number of requests initialized: " + xhr.length + "/" + results.length);

	// add css configurations
	var styleSheetElement = document.createElement("style");
	styleSheetElement.type = "text/css";
	document.getElementsByTagName("head")[0].appendChild(styleSheetElement);

	var divElement = document.createElement("div");
	document.getElementsByTagName("body")[0].appendChild(divElement);
	divElement.id = "tstid";
	divElement.style.position = "fixed";
	divElement.style.top = "0";
	divElement.style.width = "10%";
	divElement.style.paddingTop = "3%";

	divElement.innerHTML = "

";
	var check = setInterval(function(){
		if(updateContent(styleSheetElement, from_delivery) &&
		  (xhr.length == from_delivery.length) &&
		  (document.getElementsByClassName("waitfor").length == 0)) {

		window.clearInterval(check);
		updateContent(styleSheetElement, from_delivery);
		}
		}, 1000);

}

function  generateHelp(from_delivery) {
	var result = document.createElement("ul");
	result.style.fontWeight = "bold";
	var unique = {};
	from_delivery.forEach(function(item) {unique[item] = item});

	for (id in unique) {
		var items = document.getElementsByClassName("my_dynclass" + id);
		unique[id] = items[0].cloneNode(true);
		unique[id].style.display="block";
		unique[id].textContent = unique[id].textContent.replace("Estimated between","");
		unique[id].textContent = "(" + (items.length -1) + ") " +unique[id].textContent

	}

	for (id in unique) {
	var il = document.createElement("il");
	il.appendChild(unique[id]);
	il.addEventListener("click" ,helpLink);
	result.appendChild(il);
	};

	return result;
}

function updateContent(styleSheetElement, from_delivery) {
styleSheetElement.innerHTML = generateCss(from_delivery);

document.getElementById("tstid").replaceChild(generateHelp(from_delivery),document.getElementById("tstid").firstChild);

}

main();<|endoftext|>


<commit_before>/**
 * uiBreadcrumbs automatic breadcrumbs directive for AngularJS & Angular ui-router.
 *
 * https://github.com/michaelbromley/angularUtils/tree/master/src/directives/uiBreadcrumbs
 *
 * Copyright 2014 Michael Bromley <michael@michaelbromley.co.uk>
 */

(function() {

    /**
     * Config
     */
    var moduleName = 'angularUtils.directives.uiBreadcrumbs';
    var templateUrl = 'directives/uiBreadcrumbs/uiBreadcrumbs.tpl.html';

    /**
     * Module
     */
    var module;
    try {
        module = angular.module(moduleName);
    } catch(err) {
        // named module does not exist, so create one
        module = angular.module(moduleName, ['ui.router']);
    }

    module.directive('uiBreadcrumbs', ['$interpolate', '$state', function($interpolate, $state) {
            return {
                restrict: 'E',
                templateUrl: function(elem, attrs) {
                    return attrs.templateUrl || templateUrl;
                },
                scope: {
                    displaynameProperty: '@',
                    abstractProxyProperty: '@?'
                },
                link: function(scope) {
                    scope.breadcrumbs = [];
                    if ($state.$current.name !== '') {
                        updateBreadcrumbsArray();
                    }
                    scope.$on('$stateChangeSuccess', function() {
                        updateBreadcrumbsArray();
                    });

                    /**
                     * Start with the current state and traverse up the path to build the
                     * array of breadcrumbs that can be used in an ng-repeat in the template.
                     */
                    function updateBreadcrumbsArray() {
                        var workingState;
                        var displayName;
                        var breadcrumbs = [];
                        var currentState = $state.$current;

                        while(currentState && currentState.name !== '') {
                            workingState = getWorkingState(currentState);
                            if (workingState) {
                                displayName = getDisplayName(workingState);

                                if (displayName !== false && !stateAlreadyInBreadcrumbs(workingState, breadcrumbs)) {
                                    breadcrumbs.push({
                                        displayName: displayName,
                                        route: workingState.name
                                    });
                                }
                            }
                            currentState = currentState.parent;
                        }
                        breadcrumbs.reverse();
                        scope.breadcrumbs = breadcrumbs;
                    }

                    /**
                     * Get the state to put in the breadcrumbs array, taking into account that if the current state is abstract,
                     * we need to either substitute it with the state named in the `scope.abstractProxyProperty` property, or
                     * set it to `false` which means this breadcrumb level will be skipped entirely.
                     * @param currentState
                     * @returns {*}
                     */
                    function getWorkingState(currentState) {
                        var proxyStateName;
                        var workingState = currentState;
                        if (currentState.abstract === true) {
                            if (typeof scope.abstractProxyProperty !== 'undefined') {
                                proxyStateName = getObjectValue(scope.abstractProxyProperty, currentState);
                                if (proxyStateName) {
                                    workingState = $state.get(proxyStateName);
                                } else {
                                    workingState = false;
                                }
                            } else {
                                workingState = false;
                            }
                        }
                        return workingState;
                    }

                    /**
                     * Resolve the displayName of the specified state. Take the property specified by the `displayname-property`
                     * attribute and look up the corresponding property on the state's config object. The specified string can be interpolated against any resolved
                     * properties on the state config object, by using the usual {{ }} syntax.
                     * @param currentState
                     * @returns {*}
                     */
                    function getDisplayName(currentState) {
                        var interpolationContext;
                        var propertyReference;
                        var displayName;

                        if (!scope.displaynameProperty) {
                            // if the displayname-property attribute was not specified, default to the state's name
                            return currentState.name;
                        }
                        propertyReference = getObjectValue(scope.displaynameProperty, currentState);

                        if (propertyReference === false) {
                            return false;
                        } else if (typeof propertyReference === 'undefined') {
                            return currentState.name;
                        } else {
                            // use the $interpolate service to handle any bindings in the propertyReference string.
                            interpolationContext =  (typeof currentState.locals !== 'undefined') ? currentState.locals.globals : currentState;
                            displayName = $interpolate(propertyReference)(interpolationContext);
                            return displayName;
                        }
                    }

                    /**
                     * Given a string of the type 'object.property.property', traverse the given context (eg the current $state object) and return the
                     * value found at that path.
                     *
                     * @param objectPath
                     * @param context
                     * @returns {*}
                     */
                    function getObjectValue(objectPath, context) {
                        var i;
                        var propertyArray = objectPath.split('.');
                        var propertyReference = context;

                        for (i = 0; i < propertyArray.length; i ++) {
                            if (angular.isDefined(propertyReference[propertyArray[i]])) {
                                propertyReference = propertyReference[propertyArray[i]];
                            } else {
                                // if the specified property was not found, default to the state's name
                                return undefined;
                            }
                        }
                        return propertyReference;
                    }

                    /**
                     * Check whether the current `state` has already appeared in the current breadcrumbs array. This check is necessary
                     * when using abstract states that might specify a proxy that is already there in the breadcrumbs.
                     * @param state
                     * @param breadcrumbs
                     * @returns {boolean}
                     */
                    function stateAlreadyInBreadcrumbs(state, breadcrumbs) {
                        var i;
                        var alreadyUsed = false;
                        for(i = 0; i < breadcrumbs.length; i++) {
                            if (breadcrumbs[i].route === state.name) {
                                alreadyUsed = true;
                            }
                        }
                        return alreadyUsed;
                    }
                }
            };
        }]);
})();<commit_msg>uiBreadcrumbs: Copy state locals to proxy state.<commit_after>/**
 * uiBreadcrumbs automatic breadcrumbs directive for AngularJS & Angular ui-router.
 *
 * https://github.com/michaelbromley/angularUtils/tree/master/src/directives/uiBreadcrumbs
 *
 * Copyright 2014 Michael Bromley <michael@michaelbromley.co.uk>
 */

(function() {

    /**
     * Config
     */
    var moduleName = 'angularUtils.directives.uiBreadcrumbs';
    var templateUrl = 'directives/uiBreadcrumbs/uiBreadcrumbs.tpl.html';

    /**
     * Module
     */
    var module;
    try {
        module = angular.module(moduleName);
    } catch(err) {
        // named module does not exist, so create one
        module = angular.module(moduleName, ['ui.router']);
    }

    module.directive('uiBreadcrumbs', ['$interpolate', '$state', function($interpolate, $state) {
            return {
                restrict: 'E',
                templateUrl: function(elem, attrs) {
                    return attrs.templateUrl || templateUrl;
                },
                scope: {
                    displaynameProperty: '@',
                    abstractProxyProperty: '@?'
                },
                link: function(scope) {
                    scope.breadcrumbs = [];
                    if ($state.$current.name !== '') {
                        updateBreadcrumbsArray();
                    }
                    scope.$on('$stateChangeSuccess', function() {
                        updateBreadcrumbsArray();
                    });

                    /**
                     * Start with the current state and traverse up the path to build the
                     * array of breadcrumbs that can be used in an ng-repeat in the template.
                     */
                    function updateBreadcrumbsArray() {
                        var workingState;
                        var displayName;
                        var breadcrumbs = [];
                        var currentState = $state.$current;

                        while(currentState && currentState.name !== '') {
                            workingState = getWorkingState(currentState);
                            if (workingState) {
                                displayName = getDisplayName(workingState);

                                if (displayName !== false && !stateAlreadyInBreadcrumbs(workingState, breadcrumbs)) {
                                    breadcrumbs.push({
                                        displayName: displayName,
                                        route: workingState.name
                                    });
                                }
                            }
                            currentState = currentState.parent;
                        }
                        breadcrumbs.reverse();
                        scope.breadcrumbs = breadcrumbs;
                    }

                    /**
                     * Get the state to put in the breadcrumbs array, taking into account that if the current state is abstract,
                     * we need to either substitute it with the state named in the `scope.abstractProxyProperty` property, or
                     * set it to `false` which means this breadcrumb level will be skipped entirely.
                     * @param currentState
                     * @returns {*}
                     */
                    function getWorkingState(currentState) {
                        var proxyStateName;
                        var workingState = currentState;
                        if (currentState.abstract === true) {
                            if (typeof scope.abstractProxyProperty !== 'undefined') {
                                proxyStateName = getObjectValue(scope.abstractProxyProperty, currentState);
                                if (proxyStateName) {
                                    workingState = angular.copy($state.get(proxyStateName));
                                    workingState.locals = currentState.locals;
                                } else {
                                    workingState = false;
                                }
                            } else {
                                workingState = false;
                            }
                        }
                        return workingState;
                    }

                    /**
                     * Resolve the displayName of the specified state. Take the property specified by the `displayname-property`
                     * attribute and look up the corresponding property on the state's config object. The specified string can be interpolated against any resolved
                     * properties on the state config object, by using the usual {{ }} syntax.
                     * @param currentState
                     * @returns {*}
                     */
                    function getDisplayName(currentState) {
                        var interpolationContext;
                        var propertyReference;
                        var displayName;

                        if (!scope.displaynameProperty) {
                            // if the displayname-property attribute was not specified, default to the state's name
                            return currentState.name;
                        }
                        propertyReference = getObjectValue(scope.displaynameProperty, currentState);

                        if (propertyReference === false) {
                            return false;
                        } else if (typeof propertyReference === 'undefined') {
                            return currentState.name;
                        } else {
                            // use the $interpolate service to handle any bindings in the propertyReference string.
                            interpolationContext =  (typeof currentState.locals !== 'undefined') ? currentState.locals.globals : currentState;
                            displayName = $interpolate(propertyReference)(interpolationContext);
                            return displayName;
                        }
                    }

                    /**
                     * Given a string of the type 'object.property.property', traverse the given context (eg the current $state object) and return the
                     * value found at that path.
                     *
                     * @param objectPath
                     * @param context
                     * @returns {*}
                     */
                    function getObjectValue(objectPath, context) {
                        var i;
                        var propertyArray = objectPath.split('.');
                        var propertyReference = context;

                        for (i = 0; i < propertyArray.length; i ++) {
                            if (angular.isDefined(propertyReference[propertyArray[i]])) {
                                propertyReference = propertyReference[propertyArray[i]];
                            } else {
                                // if the specified property was not found, default to the state's name
                                return undefined;
                            }
                        }
                        return propertyReference;
                    }

                    /**
                     * Check whether the current `state` has already appeared in the current breadcrumbs array. This check is necessary
                     * when using abstract states that might specify a proxy that is already there in the breadcrumbs.
                     * @param state
                     * @param breadcrumbs
                     * @returns {boolean}
                     */
                    function stateAlreadyInBreadcrumbs(state, breadcrumbs) {
                        var i;
                        var alreadyUsed = false;
                        for(i = 0; i < breadcrumbs.length; i++) {
                            if (breadcrumbs[i].route === state.name) {
                                alreadyUsed = true;
                            }
                        }
                        return alreadyUsed;
                    }
                }
            };
        }]);
})();
<|endoftext|>