<commit_before>var screenWidth = 1024;
var screenHeight = 768;
var loseText = 'You lost. You are a loser.';

var lzs = new Phaser.Game(screenWidth, screenHeight, Phaser.AUTO, 'lzs', { preload: preload, create: create, update: update, render: render });

function preload() {
	// Load sounds and sprites

	lzs.load.spritesheet('ray', 'assets/sprites/ray-sheet.png', 145, 128);
	lzs.load.spritesheet('zombie', 'assets/sprites/zombie-sheet.png', 119, 128);
	lzs.load.image('beam', 'assets/sprites/beam-01.png');
	lzs.load.image('background', 'assets/sprites/grass-dirt-mix-pixeled-gray.png');
	lzs.load.image('zombie', 'assets/sprites/placeholder_zombie.png');

	lzs.load.audio('alive', 'assets/sounds/angel1.mp3');
	lzs.load.audio('hit', 'assets/sounds/grunt1.mp3');
	lzs.load.audio('pew', 'assets/sounds/raygun1.mp3');
	lzs.load.audio('soundtrack', 'assets/sounds/soundtrack.mp3');
	lzs.load.audio('zombie', 'assets/sounds/zombie1.mp3');
}

// Game vars

var alive;
var bulletSpeed = 1500;
var cursors;
var fireButton;
var fireDelay =200;
var fireTime = 0;
var gameLost = false;
var hit;
var pew;
var ray;
var raySpeed = 1000;
var score = 0;
var scoreString = 'Score: ';
var soundtrack;
var scoreText;
var zombieHitPoints = 3;
var zombies;
var zombieSpawn;
var zombieSpeed = 50;
var zombieWidth;

function create() {
	lzs.add.tileSprite(0, 0, screenWidth, screenHeight, 'background');

	lzs.physics.startSystem(Phaser.Physics.ARCADE);

	ray = lzs.add.sprite(screenWidth * 0.5, screenHeight * 0.8, 'ray');

	//rays
	bullets = lzs.add.group();
	bullets.enableBody = true;
	bullets.physicsBodyType = Phaser.Physics.ARCADE;
	bullets.createMultiple(30, 'beam');
	bullets.setAll('anchor.x', 0.5);
	bullets.setAll('anchor.y', 1);
	bullets.setAll('outOfBoundsKill', true);
	bullets.setAll('checkWorldBounds', true);

	lzs.physics.enable(ray, Phaser.Physics.ARCADE);

	//controls
	cursors = lzs.input.keyboard.createCursorKeys();
	fireButton = lzs.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

	zombieWidth = lzs.cache.getImage('zombie').width;
	createZombies();

	//audio
	alive = lzs.add.audio('alive');
	hit = lzs.add.audio('hit');
	pew = lzs.add.audio('pew');
	zombieSpawn = lzs.add.audio('zombie');
	soundtrack = lzs.add.audio('soundtrack',1,true);

	soundtrack.play('',0,0.3,true);
	setTimeout(function() {zombieSpawn.play()}, 2000);

	//text
	stateText = lzs.add.text(lzs.world.centerX, lzs.world.centerY, ' ', { font: '84px Arial', fill: '#de57d5', textShadow: '#fff'  });
    stateText.anchor.setTo(0.5, 0.5);
    stateText.visible = false;

	scoreText = lzs.add.text(10, screenHeight - 30, scoreString + score, { font: '24px Arial', fill: '#de57d5', textShadow: '#fff' });
}

function update() {
	if (ray.alive) {
		ray.body.velocity.setTo(0, 0);

		if (cursors.left.isDown) {
			if (ray.position.x > 0) {
				ray.body.velocity.x = -raySpeed;
			}
		}
		if (cursors.right.isDown) {
			if (ray.position.x < (lzs.world.width - ray.width)) {
				ray.body.velocity.x = raySpeed;
			}
		}
		if (cursors.up.isDown) {
			if (ray.position.y > (lzs.world.height / 2)) {
				ray.body.velocity.y = -raySpeed;
			}
		}
		if (cursors.down.isDown) {
			if (ray.position.y < (lzs.world.height - ray.height)) {
				ray.body.velocity.y = raySpeed;
			}
		}

		if (fireButton.isDown) {
			fireRay();
		}

		//collision detection
		lzs.physics.arcade.overlap(bullets, zombies, zombieBulletCollisionHandler);
		lzs.physics.arcade.overlap(ray, zombies, loseGame);

		zombies.forEach(function(zombie) {
			if (zombie.position.y > (lzs.world.height - zombie.height)) {
				gameLost = true;
			}
		}, this);

		if (gameLost) {
			loseGame();
		}
	}
}

function fireRay() {
	if (lzs.time.now > fireTime) {
		pew.play();

		bullet = bullets.getFirstExists(false);

		if (bullet) {
			bullet.reset(ray.x + 65, ray.y + 8);
			bullet.body.velocity.y = -bulletSpeed;
			fireTime = lzs.time.now + fireDelay;
		}
	}
}

function createZombies() {
	zombies = lzs.add.group();
	zombies.enableBody = true;
	zombies.physicsBodyType = Phaser.Physics.ARCADE;
	zombies.setAll('outOfBoundsKill', true);

	lzs.time.events.loop(2000, createZombie, this);
}

function createZombie() {
	var position = Math.min(screenWidth * Math.random(), screenWidth - zombieWidth);

	var zombie = zombies.create(position, -150, 'zombie');

	zombie.body.velocity.y = zombieSpeed;
	zombie.hits = 0;
	zombie.alive = false;
}

function zombieBulletCollisionHandler(bullet, zombie) {
	if (!zombie.alive) {
		bullet.kill();
		zombie.hits++;

		if (zombie.hits < zombieHitPoints) {
			hit.play('',0,0.7);
		}

		if (zombie.hits == zombieHitPoints) {
			zombie.alive = true;
			zombie.body.velocity.y = 0;

			if (zombie.position.x > (lzs.world.width * 0.5)) {
				zombie.body.velocity.x = zombieSpeed * 3;
			}
			else {
				zombie.body.velocity.x = -zombieSpeed * 3;
			}

			alive.play('',0,1);
			score += 20;
			scoreText.text = scoreString + score;
		}
	}
}

function loseGame() {
	stateText.text = loseText;
	stateText.visible = true;
	zombies.destroy();
	bullets.destroy();
	ray.destroy();
}

function render() {
	// debug
}<commit_msg>Fix zombie sprite width<commit_after>var screenWidth = 1024;
var screenHeight = 768;
var loseText = 'You lost. You are a loser.';

var lzs = new Phaser.Game(screenWidth, screenHeight, Phaser.AUTO, 'lzs', { preload: preload, create: create, update: update, render: render });

function preload() {
	// Load sounds and sprites

	lzs.load.spritesheet('ray', 'assets/sprites/ray-sheet.png', 145, 128);
	lzs.load.spritesheet('zombie', 'assets/sprites/zombie-sheet.png', 119, 128);
	lzs.load.image('beam', 'assets/sprites/beam-01.png');
	lzs.load.image('background', 'assets/sprites/grass-dirt-mix-pixeled-gray.png');

	lzs.load.audio('alive', 'assets/sounds/angel1.mp3');
	lzs.load.audio('hit', 'assets/sounds/grunt1.mp3');
	lzs.load.audio('pew', 'assets/sounds/raygun1.mp3');
	lzs.load.audio('soundtrack', 'assets/sounds/soundtrack.mp3');
	lzs.load.audio('zombie', 'assets/sounds/zombie1.mp3');
}

// Game vars

var alive;
var bulletSpeed = 1500;
var cursors;
var fireButton;
var fireDelay =200;
var fireTime = 0;
var gameLost = false;
var hit;
var pew;
var ray;
var raySpeed = 1000;
var score = 0;
var scoreString = 'Score: ';
var soundtrack;
var scoreText;
var zombieHitPoints = 3;
var zombies;
var zombieSpawn;
var zombieSpeed = 50;
var zombieWidth = 119;

function create() {
	lzs.add.tileSprite(0, 0, screenWidth, screenHeight, 'background');

	lzs.physics.startSystem(Phaser.Physics.ARCADE);

	ray = lzs.add.sprite(screenWidth * 0.5, screenHeight * 0.8, 'ray');

	//rays
	bullets = lzs.add.group();
	bullets.enableBody = true;
	bullets.physicsBodyType = Phaser.Physics.ARCADE;
	bullets.createMultiple(30, 'beam');
	bullets.setAll('anchor.x', 0.5);
	bullets.setAll('anchor.y', 1);
	bullets.setAll('outOfBoundsKill', true);
	bullets.setAll('checkWorldBounds', true);

	lzs.physics.enable(ray, Phaser.Physics.ARCADE);

	//controls
	cursors = lzs.input.keyboard.createCursorKeys();
	fireButton = lzs.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

	createZombies();

	//audio
	alive = lzs.add.audio('alive');
	hit = lzs.add.audio('hit');
	pew = lzs.add.audio('pew');
	zombieSpawn = lzs.add.audio('zombie');
	soundtrack = lzs.add.audio('soundtrack',1,true);

	soundtrack.play('',0,0.3,true);
	setTimeout(function() {zombieSpawn.play()}, 2000);

	//text
	stateText = lzs.add.text(lzs.world.centerX, lzs.world.centerY, ' ', { font: '84px Arial', fill: '#de57d5', textShadow: '#fff'  });
    stateText.anchor.setTo(0.5, 0.5);
    stateText.visible = false;

	scoreText = lzs.add.text(10, screenHeight - 30, scoreString + score, { font: '24px Arial', fill: '#de57d5', textShadow: '#fff' });
}

function update() {
	if (ray.alive) {
		ray.body.velocity.setTo(0, 0);

		if (cursors.left.isDown) {
			if (ray.position.x > 0) {
				ray.body.velocity.x = -raySpeed;
			}
		}
		if (cursors.right.isDown) {
			if (ray.position.x < (lzs.world.width - ray.width)) {
				ray.body.velocity.x = raySpeed;
			}
		}
		if (cursors.up.isDown) {
			if (ray.position.y > (lzs.world.height / 2)) {
				ray.body.velocity.y = -raySpeed;
			}
		}
		if (cursors.down.isDown) {
			if (ray.position.y < (lzs.world.height - ray.height)) {
				ray.body.velocity.y = raySpeed;
			}
		}

		if (fireButton.isDown) {
			fireRay();
		}

		//collision detection
		lzs.physics.arcade.overlap(bullets, zombies, zombieBulletCollisionHandler);
		lzs.physics.arcade.overlap(ray, zombies, loseGame);

		zombies.forEach(function(zombie) {
			if (zombie.position.y > (lzs.world.height - zombie.height)) {
				gameLost = true;
			}
		}, this);

		if (gameLost) {
			loseGame();
		}
	}
}

function fireRay() {
	if (lzs.time.now > fireTime) {
		pew.play();

		bullet = bullets.getFirstExists(false);

		if (bullet) {
			bullet.reset(ray.x + 65, ray.y + 8);
			bullet.body.velocity.y = -bulletSpeed;
			fireTime = lzs.time.now + fireDelay;
		}
	}
}

function createZombies() {
	zombies = lzs.add.group();
	zombies.enableBody = true;
	zombies.physicsBodyType = Phaser.Physics.ARCADE;
	zombies.setAll('outOfBoundsKill', true);

	lzs.time.events.loop(2000, createZombie, this);
}

function createZombie() {
	var position = Math.min(screenWidth * Math.random(), screenWidth - zombieWidth);

	var zombie = zombies.create(position, -150, 'zombie');

	zombie.body.velocity.y = zombieSpeed;
	zombie.hits = 0;
	zombie.alive = false;
}

function zombieBulletCollisionHandler(bullet, zombie) {
	if (!zombie.alive) {
		bullet.kill();
		zombie.hits++;

		if (zombie.hits < zombieHitPoints) {
			hit.play('',0,0.7);
		}

		if (zombie.hits == zombieHitPoints) {
			zombie.alive = true;
			zombie.body.velocity.y = 0;

			if (zombie.position.x > (lzs.world.width * 0.5)) {
				zombie.body.velocity.x = zombieSpeed * 3;
			}
			else {
				zombie.body.velocity.x = -zombieSpeed * 3;
			}

			alive.play('',0,1);
			score += 20;
			scoreText.text = scoreString + score;
		}
	}
}

function loseGame() {
	stateText.text = loseText;
	stateText.visible = true;
	zombies.destroy();
	bullets.destroy();
	ray.destroy();
}

function render() {
	// debug
}<|endoftext|>


<commit_before>'use strict';

var LZW = {
	INITIAL_DICT_SIZE : 256,
	MAX_DICT_SIZE : 65536,

	Compress : function(string, dictionnary_max_size) {
		var i, length;
		//build dictionary
		var dictionary = {};
		for(i = 0; i < 256; i++) {
			dictionary[String.fromCharCode(i)] = i;
		}

		var current_code = LZW.INITIAL_DICT_SIZE;
		var out = [];

		var character;
		var phrase = '', new_phrase;
		//build output array
		for(i = 0, length = string.length; i < length; i++) {
			character = string.charAt(i);
			new_phrase = phrase + character;

			//there is a match in dictionary
			if(dictionary.hasOwnProperty(new_phrase)) {
				phrase = new_phrase;
			}
			else {
				out.push(dictionary[phrase]);
				//add new sequence to the dictionary
				if(!dictionnary_max_size || current_code < LZW.MAX_DICT_SIZE) {
					dictionary[new_phrase] = current_code;
					current_code++;
				}
				phrase = String(character);
			}
		}
		if(phrase.length > 0) {
			out.push(dictionary[phrase]);
		}
		return out;
	},

	/*Compress : function(string, dictionnary_max_size) {
		var dictionary = {};
		var out = [];
		var current_code = LZW.INITIAL_DICT_SIZE;
		var data = (string + '').split('');
		var phrase = data[0];
		var i, length;
		var character;
		//build output array
		for(i = 1, length = data.length; i < length; i++) {
			character = data[i];
			//there is a match in dictionary
			if(dictionary[.hasOwnProperty(phrase + character)) {
				phrase += character;
			}
			else {
				out.push(phrase.length > 1 ? dictionary[phrase] : phrase.charCodeAt(0));
				if(!dictionnary_max_size || current_code < LZW.MAX_DICT_SIZE) {
					dictionary[phrase + character] = current_code;
					current_code++;
				}
				phrase = character;
			}
		}
		out.push(phrase.length > 1 ? dictionary[phrase] : phrase.charCodeAt(0));
		return out;
	},*/

	CompressToString : function(string) {
		return LZW.Compress(string, LZW.MAX_DICT_SIZE).map(function(charcode) {return String.fromCharCode(charcode);}).join('');
	},

	Decompress : function(integers, dictionnary_max_size) {
		var dictionary = {};
		var character = String.fromCharCode(integers[0]);
		var phrase;
		var previous_phrase = character;
		var out = [character];
		var current_code = LZW.INITIAL_DICT_SIZE;
		var i, length;
		for(i = 1, length = integers.length; i < length; i++) {
			var code = integers[i];
			if(code < LZW.INITIAL_DICT_SIZE) {
				phrase = String.fromCharCode(integers[i]);
			}
			else {
				phrase = dictionary[code] || (previous_phrase + character);
			}
			out.push(phrase);
			character = phrase.charAt(0);
			if(!dictionnary_max_size || current_code < dictionnary_max_size) {
				dictionary[current_code] = previous_phrase + character;
				current_code++;
			}
			previous_phrase = phrase;
		}
		return out.join('');
	},

	DecompressString : function(string) {
		var integers = string.split('').map(function(character) {return character.charCodeAt(0);})
		return LZW.Decompress(integers, LZW.MAX_DICT_SIZE);
	}
};
<commit_msg>Remove magic value from LZW tool<commit_after>'use strict';

var LZW = {
	INITIAL_DICT_SIZE : 256,
	MAX_DICT_SIZE : 65536,

	Compress : function(string, dictionnary_max_size) {
		var i, length;
		//build dictionary
		var dictionary = {};
		for(i = 0; i < LZW.INITIAL_DICT_SIZE; i++) {
			dictionary[String.fromCharCode(i)] = i;
		}

		var current_code = LZW.INITIAL_DICT_SIZE;
		var out = [];

		var character;
		var phrase = '', new_phrase;
		//build output array
		for(i = 0, length = string.length; i < length; i++) {
			character = string.charAt(i);
			new_phrase = phrase + character;

			//there is a match in dictionary
			if(dictionary.hasOwnProperty(new_phrase)) {
				phrase = new_phrase;
			}
			else {
				out.push(dictionary[phrase]);
				//add new sequence to the dictionary
				if(!dictionnary_max_size || current_code < LZW.MAX_DICT_SIZE) {
					dictionary[new_phrase] = current_code;
					current_code++;
				}
				phrase = String(character);
			}
		}
		if(phrase.length > 0) {
			out.push(dictionary[phrase]);
		}
		return out;
	},

	/*Compress : function(string, dictionnary_max_size) {
		var dictionary = {};
		var out = [];
		var current_code = LZW.INITIAL_DICT_SIZE;
		var data = (string + '').split('');
		var phrase = data[0];
		var i, length;
		var character;
		//build output array
		for(i = 1, length = data.length; i < length; i++) {
			character = data[i];
			//there is a match in dictionary
			if(dictionary.hasOwnProperty(phrase + character)) {
				phrase += character;
			}
			else {
				out.push(phrase.length > 1 ? dictionary[phrase] : phrase.charCodeAt(0));
				if(!dictionnary_max_size || current_code < LZW.MAX_DICT_SIZE) {
					dictionary[phrase + character] = current_code;
					current_code++;
				}
				phrase = character;
			}
		}
		out.push(phrase.length > 1 ? dictionary[phrase] : phrase.charCodeAt(0));
		return out;
	},*/

	CompressToString : function(string) {
		return LZW.Compress(string, LZW.MAX_DICT_SIZE).map(function(charcode) {return String.fromCharCode(charcode);}).join('');
	},

	Decompress : function(integers, dictionnary_max_size) {
		var dictionary = {};
		var character = String.fromCharCode(integers[0]);
		var phrase;
		var previous_phrase = character;
		var out = [character];
		var current_code = LZW.INITIAL_DICT_SIZE;
		var i, length;
		for(i = 1, length = integers.length; i < length; i++) {
			var code = integers[i];
			if(code < LZW.INITIAL_DICT_SIZE) {
				phrase = String.fromCharCode(integers[i]);
			}
			else {
				phrase = dictionary[code] || (previous_phrase + character);
			}
			out.push(phrase);
			character = phrase.charAt(0);
			if(!dictionnary_max_size || current_code < dictionnary_max_size) {
				dictionary[current_code] = previous_phrase + character;
				current_code++;
			}
			previous_phrase = phrase;
		}
		return out.join('');
	},

	DecompressString : function(string) {
		var integers = string.split('').map(function(character) {return character.charCodeAt(0);})
		return LZW.Decompress(integers, LZW.MAX_DICT_SIZE);
	}
};
<|endoftext|>


<commit_before>
        var dictionary = function(){

            var result = {};
            for (var i=0; i < 256; i++) {
                var ch = String.fromCharCode(i);
                result[ch] = i;
            };
            return result;
        };

        var dic = false;
        function getDic(){

            return dictionary();

        }

        function encode(str){
          var index = 256;
          var dictionary = getDic();
          var outStr = [];
          var s = '';

          var len = str.length;
          s = str[0];
          for(var i=1; i < len; i++){
              var c = str[i];
              if(dictionary[s+c]){
                  s = s+c;
              }else{
                  //console.log(ch + 'sec');
                  var code = ++index;
                  outStr.push(String.fromCharCode(dictionary[s]));
                  dictionary[s+c] = code;
                  s = c;
              }
          }
          for(var c in s ){
              outStr.push(s[c]);
          }

          return outStr.join('');
        };

        function tTable(){
            var result = {};
            for (var i=0; i < 256; i++) {
                var ch = String.fromCharCode(i);
                result[i] = ch;
            };
            return result;
        }

        function decode(str){

            var table = tTable(),
            buffer = '',
            outStr = [];

            outStr.push(str[0]);
            var first_code = str[0].charCodeAt(0);
            var len = str.length;
            var counter = 255;
            for (var i=1; i < len; i++) {
                var next_code = str[i].charCodeAt(0);

                if(table[next_code]){
                    buffer = table[next_code]

                    table[++counter] = table[first_code] +
                                       table[next_code];
                    first_code = next_code;
                }else{
                    console.log('else');
                    buffer = table[first_code].charCodeAt(0);
                    buffer = buffer + next_code;
                    buffer = String.fromCharCode(buffer);
                    console.log(buffer);
;                }

                outStr.push(buffer);
            };
            return outStr.join('');

        }

        function size(str){

            return encodeURIComponent(str).replace(/%../g, 'x').length;
        }<commit_msg>it all works!<commit_after>
        var dictionary = function(){

            var result = {};
            for (var i=0; i < 256; i++) {
                var ch = String.fromCharCode(i);
                result[ch] = i;
            };
            return result;
        };

        var dic = false;
        function getDic(){

            return dictionary();

        }

        function encode(str){
          var index = 256;
          var dictionary = getDic();
          var outStr = [];
          var s = '';

          var len = str.length;
          s = str[0];
          for(var i=1; i < len; i++){
              var c = str[i];
              if(dictionary[s+c]){
                  s = s+c;
              }else{
                  //console.log(ch + 'sec');
                  var code = ++index;
                  outStr.push(String.fromCharCode(dictionary[s]));
                  dictionary[s+c] = code;
                  s = c;
              }
          }
          for(var c in s ){
              outStr.push(s[c]);
          }

          return outStr.join('');
        };

        function tTable(){
            var result = {};
            for (var i=0; i < 256; i++) {
                var ch = String.fromCharCode(i);
                result[i] = ch;
            };
            return result;
        }

        function decode(str){

            var table = tTable(),
            buffer = '',
            outStr = [];

           // outStr.push(str[0]);
            var first_code = str[0].charCodeAt(0);
            var len = str.length;
            var counter = 255;
            var character = '';
            for (var i=0; i < len; i++) {
                var next_code = str[i].charCodeAt(0);

                if(!table[next_code]){
                    buffer = table[first_code];
                    buffer = buffer + character;
                }else{
                    buffer = table[next_code];

                }

                outStr.push(buffer);
                character = buffer[0];
                table[++counter] = table[first_code] +
                                   character;

                first_code = next_code;

            };

            return outStr.join('');

        }

        function size(str){

            return encodeURIComponent(str).replace(/%../g, 'x').length;
        }<|endoftext|>


<commit_before>enchant();
var maxWidth = 800; //画面サイズ（幅）
var maxHeight = 600; //画面サイズ（高さ）
var image = [];
var user = null;

window.onload = function(){
	var core = new Core(maxWidth, maxHeight);
	core.fps = 16;
	image.push("../image/chara.png");
	image.push("../image/arrow_top.png");
	image.push("../image/arrow_left.png");
	image.push("../image/arrow_right.png");
	image.push("../image/arrow_bottom.png");
	image.push("../image/arrow_1.png");
	image.push("../image/arrow_2.png");
	image.push("../image/arrow_3.png");
	image.push("../image/arrow_4.png");
	image.push("../image/minmap1.png");
	core.preload(image);
	core.onload = function(){
		var mapMove = new Scene();
		var direct = new Array();

		var evcontroller = new Event_Controller();

//		var mapdata = [[0,1,1], [1, 1, 1], [1, 1, 0],[0, 1, 2]];
//5×7
		var mapdata = [[1,1,1], [1, 0, 1], [1, 0, 1],[2, 0, 2]];
		var x = 0;
		var y = mapdata[0].length - 1;
		var Bgimage = new Sprite(maxWidth, maxHeight);
		var now_position = 1;

		addChild_to_scene(mapMove, Bgimage);
		for (i = 0; i < 4; i++){
			direct[i] = new Sprite(100, 100);
			direct[i].visible = true;
//			direct[i].addEventListener(EVENT.onClick, clickEvent);
			addChild_to_scene(mapMove, direct[i]);
		}
		next_map(mapdata,x,y);
		first_message(mapMove, "目的：敵を全滅せよ");
		direct[0].ontouchstart = function (){
			var e = new enchant.Event("moveUp");
			this.dispatchEvent(e);
		};

		direct[0].onmoveUp = function (){
			move_xy(x, y-1);
			next_map(mapdata, x, y);
		};

		direct[1].ontouchstart = function (){
			var e = new enchant.Event("moveRight");
			this.dispatchEvent(e);
		};

		direct[1].onmoveRight = function (){
			move_xy(x + 1, y);
			next_map(mapdata, x, y);
		};

		direct[2].ontouchstart = function (){
			var e = new enchant.Event("moveDown");
			this.dispatchEvent(e);
		};
		direct[2].onmoveDown = function (){
			move_xy(x, y + 1);
			next_map(mapdata, x, y);
		};

		direct[3].ontouchstart = function (){
			var e = new enchant.Event("moveLeft");
			this.dispatchEvent(e);
		};
		direct[3].onmoveLeft = function (){
			move_xy(x - 1, y);
			next_map(mapdata, x, y);
		};

		function next_map(mapdata, now_x, now_y, EventFlag){
			direction = new Array();
			console.log(mapdata[now_x][now_y], now_x, now_y);
			for (i = 0; i < 4; i++){
				direction[i] = 0;
			}
			if (now_x == 0){
				direction[3] = 0;
			}
			else if (mapdata[now_x - 1][now_y] != 0){
				direction[3] = 1;
			}

			if (now_y == 0){
				direction[0] = 0;
			}
			else if (mapdata[now_x][now_y - 1] != 0){
				direction[0] = 1;
			}

			if (now_x == mapdata.length - 1){
				direction[1] = 0;
			}
			else if (mapdata[now_x + 1][now_y] != 0){
				direction[1] = 1;
			}

			if (now_y == mapdata[0].length - 1){
				direction[2] = 0;
			}
			else if (mapdata[now_x][now_y + 1] != 0){
				direction[2] = 1;
			}
			for (i = 0;i < 4; i++){
				if (direction[i]){
					direct[i].visible = true;
				}
				else {
					direct[i].visible = false;
				}
			}
			EventFlag = mapdata[now_x][now_y];
			if (EventFlag == 3){
				battleScene();
			}
			if (EventFlag == 4){
				ClearScene();
			}
		}
		function move_xy(next_x, next_y){
			x = next_x;
			y = next_y;
		}

/*		var top = new Sprite(100,100);
		var left = new Sprite(100,100);
		var right = new Sprite(100,100);
		var bottom = new Sprite(100,100);
*/
		var character = new Sprite(150,150);

		Sprite_info(direct[0], 350, 50, "../image/arrow_top.png");
		Sprite_info(direct[3], 50, 250, "../image/arrow_left.png");
		Sprite_info(direct[1], 650, 250, "../image/arrow_right.png");
		Sprite_info(direct[2], 350, 450, "../image/arrow_bottom.png");
		Sprite_info(character, 325, 225, "../image/chara.png");

/*		addChild_to_scene(mapMove, top);
		addChild_to_scene(mapMove, left);
		addChild_to_scene(mapMove, right);
		addChild_to_scene(mapMove, bottom);
*/
		addChild_to_scene(mapMove, character);

		/* Spriteの場所を設定する関数 */
		function Sprite_info(sprite, x, y, img){
			sprite.moveTo(x, y);
			sprite.image = core.assets[img.toString()];
		}

		function addChild_to_scene(scene, sprite){
			scene.addChild(sprite);
		}

		var minMap = enchant.Class.create(Sprite, {
			mapData: [],
			direction: [],
			initialize: function (scene, mapdata){
				Sprite.call(this, 250, 150);
				var text = new Label();
				text.text = "ミニマップ";
				text.x = 520;
				text.y = 420;
				scene.addChild(text);
				this.x = 500;
				this.y = 400;
				this.backgroundColor = "#ccc";
				this.img = core.assets["../image/minmap1.png"];
				this.opacity = 0.5;
				scene.addChild(this);
//				this.addEventListener(EVENT.ENTER_FRAME, onClickEvent);
			},

			toMoving: function(){
				for (i=0;i<4;i++){
					if(direction[i]){

					}
				}
			}
		});

		function first_message(scene, msg){
			var msg_box = new Sprite(400, 50);
			msg_box.moveTo(maxWidth / 2 - 200, 25);
			msg_box.backgroundColor = "rgba(200,200,200,0.4)";
			var message = new Label();
			message.text = msg;
			message.moveTo(maxWidth / 2 - 150, 40);
			addChild_to_scene(scene, msg_box);
			addChild_to_scene(scene, message);

/*			msg_box.tl.fadeOut(40, enchant.Easing.EASEINOUT);
			message.tl.fadeOut(40, enchant.Easing.EASEINOUT);
            scene.addEventListener(enchant.Event.ENTER_FRAME, function() {
                var time = 4.5 - parseInt(core.frame / core.fps) + "";
                if (time <= 0) {
                    scene.removeChild(msg_box);
                    scene.removeChild(message);
                    //scene.removeEventListner(enchant.Event.ENTER_FRAME);
                }

            });
*/
		}

		var minmap = new minMap(mapMove, "../image/minmap1.png");

		function Event_Controller(trueFlag){
			if (trueFlag == true){
				battleScene();
			}
		}
		core.pushScene(mapMove);
	}
	core.start();
}
<commit_msg>Revert "ダンジョン画面"<commit_after><|endoftext|>


<commit_before>/* this part must be in global namespace */
// fetch taxonomy, containing all translations, and implicit affiliations
// taken from Wikipedia:JSON
var url = "taxonomy.json";
var taxonomy;
var http_request = new XMLHttpRequest();
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
      var done = 4, ok = 200;
      if (http_request.readyState === done && http_request.status === ok) {
          taxonomy = JSON.parse(http_request.responseText);
      }
  };
http_request.send(null);

function initMap(defaultlayer,base_maps,overlay_maps) {
  map = new L.Map('map', {
    center: new L.LatLng(47.07, 15.43),
      zoom: 13,
      layers: defaultlayer,
  });

  var ctrl = new L.Control.Layers(base_maps,overlay_maps)
  map.addControl(ctrl);

  L.LatLngBounds.prototype.toOverpassBBoxString = function (){
    var a = this._southWest,
        b = this._northEast;
    return [a.lat, a.lng, b.lat, b.lng].join(",");
  }

  var path_style = L.Path.prototype._updateStyle;
  L.Path.prototype._updateStyle = function () {
    path_style.apply(this);
    for (k in this.options.svg) {
      this._path.setAttribute(k, this.options.svg[k]);
    }
  }

  return map;
}

function addSearch() {
  map.addControl( new L.Control.Search({
    url: 'http://nominatim.openstreetmap.org/search?format=json&q={s}',
    jsonpParam: 'json_callback',
    propertyName: 'display_name',
    propertyLoc: ['lat','lon'],
    circleLocation: false,
    markerLocation: false,
    autoType: false,
    autoCollapse: false,
    minLength: 2,
    zoom:12
  }) );

}
function addLocate() {
lc = L.control.locate({
        position: 'topleft',
        showPopup: false,
        strings: {
                title: "Jump to my location!"
            }
      }
      ).addTo(map);
}

var marker_table = {};

function loadPoi() {
  if (map.getZoom() < 12 ) {
    return;
  }

  var iconsize = 24;

  function fillPopup(tags,type,id) {

    var r = $('
');
    var tags_to_ignore = [ "name" , "ref", "needs" ];

    for (key in tags) {
      if ( tags_to_ignore.indexOf(key) >= 0) {
        continue;
      } else if ( key == 'website' || key == 'url' || key == 'contact:website' ||  key == 'contact:url') { //TODO: , facebook, …
        var value = tags[key];
        var teststr=/^http/; //http[s] is implicit here
        if ( ! teststr.test(value) )
          value = "http://" + value;

        var htlink = '' + value + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));
      } else if (key == 'wikipedia') { // wikipedia - TODO key="wikipedia:de"
        var value = tags[key];
        var begin = "";
        var teststr=/^http/; //http[s] is implicit here
        if ( ! teststr.test(value) )
          begin = "https://wikipedia.org/wiki/";

        var htlink = '' + value + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));
      } else if (key == 'contact:email' || key == 'email') {
        var value = tags[key];
        var teststr=/^mailto:/;
        if ( ! teststr.test(value) )
          value = "mailto:" + value;
        var htlink = '' + tags[key] + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));

      } else {
        var keytext = key;
        var valuetext = tags[key];

        /* display label:* instead of key */
        var found = 0; // use for break outer loops

        for ( groupname in taxonomy ) { // e.g. "fulfils_needs" : {}=group
          group = taxonomy[groupname];

          var count_items = group["items"].length;
          for (var i = 0; i < count_items; i++) { // loop over each item in group["items"]
            item = group["items"][i];
            if(item["osm:key"] == keytext) {
              keytext = "" + item.label["en"] + ""; // for displaying a translated value
              found = 1;
              break;
            }
          }
          if(found == 1)
            break; // for ( groupname in taxonomy )
        }

        r.append($('
').append($('').append(keytext)).append($('').text(valuetext)));
      }

    } // end for (key in tags)
    r.append($('
').append($('').append(" ")).append($('').append(" "))); // spacer

    r.append($('
').append($('').text("OSM-Type:")).append($('').text(type)));
    r.append($('
').append($('').text("OSM-ID:")).append($('').append('' + id + '')));

    var s = $('
');
    s.append(r);
    var retval = $('
').append(s);
    retval.prepend($('
').text(tags["name"]));
    return retval.html();
  }

  function bindPopupOnData(data) {
    // first: check if no item with this osm-id exists...
    var hashtable_key = data.type + data.id; // e.g. "node1546484546"
    if(marker_table[hashtable_key] == 1) //object already there
      return;
    marker_table[hashtable_key] = 1;

    // set icon dependent on tags
    var icon_tag = ""; //OSM key for choosing icon
    for (var i = 0; i < icon_tags.length; i++) {
      var key = icon_tags[i];
      if(data.tags[key]) {
        icon_tag = key;
        break;
      }
    }

    var icon_url = "";
    if(!icon_tag) {
      icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/unknown.png";
    } else {

      if (data.tags[icon_tag].indexOf(";") >= 0) // more than one item, take generic icon
        icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/generic.png";
      else
        icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/" + icon_tag + "=" + data.tags[icon_tag] + ".png";
    }

    var needs_icon = L.icon({
      iconUrl: icon_url,
      iconSize: new L.Point(iconsize, iconsize),
      iconAnchor: new L.Point(iconsize / 2, iconsize / 2),
    });

    var lmarker = L.marker([data.lat, data.lon], {
      icon: needs_icon,
      title: data.tags.name
    });
    lmarker.bindPopup(fillPopup(data.tags,data.type,data.id));
    return lmarker;
  }

  function nodeFunction(data) {
    if (! data.tags || ! data.tags.name || data.tags.entrance ) // no retval if node is just member of a way
      return null;
    return bindPopupOnData(data);
  }
  function wayFunction(data) {
    //calculate centre of polygon

    var centroid = $.geo.centroid(data.geometry);
    //var style = {};
    centroid.tags = data.tags;
    centroid.id = data.id;
    centroid.type = data.type;
    centroid.lon = centroid.coordinates[0];
    centroid.lat = centroid.coordinates[1];
    return bindPopupOnData(centroid);
  };
  function relationFunction(data) {
    // calculate mean coordinates as center
    // for all members, calculate centroid
    // then calculate mean over all nodes and centroids.
    var centroids = [];
    var sum_lon = 0;
    var sum_lat = 0;
    console.log(data);
    for (var i = 0; i < data.members.length; i++) {
      var p = data.members[i];
      var centroid;
      switch (p.type) {
        case 'node':
          centroid = p.obj.coordinates;
          centroids.push(centroid);
          break;
        case 'way':
          console.log(p);
          if (p.role == "outer") {// FIXME add handling of rel members
            var centroid_point = $.geo.centroid(p.obj.geometry);
            centroid = centroid_point.coordinates;
            centroids.push(centroid);
          }
          break;
      }
      if(centroid.length != 0) {
        sum_lon += centroid[0];
        sum_lat += centroid[1];
      } else
        console.log("centroid empty!");
    }
    //console.log(centroids);
    var sum_centroid = {
      id : data.id,
      lon : sum_lon / data.members.length,
      lat : sum_lat / data.members.length,
      tags : data.tags,
      type : data.type
    }

    //console.log(sum_centroid);
    return bindPopupOnData(sum_centroid);
    // todo: in the long term, all areas should be displayed as areas (as in overpass turbo)
  }

  function handleNodes(overpassJSON) {
    console.log("handleNodes called");
    var new_markers = [];
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      p.coordinates = [p.lon, p.lat];
      p.geometry = {type: 'Point', coordinates: p.coordinates};

      var retval = nodeFunction(p);
      if (retval)
        new_markers.push(retval);
    }
    markers.addLayers(new_markers);
    new_markers = [];
  }

  function handleWays(overpassJSON) {
    console.log("handleWays called");
    var new_markers = [];
    var nodes = {};
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      switch (p.type) {
        case 'node':
          p.coordinates = [p.lon, p.lat];
          p.geometry = {type: 'Point', coordinates: p.coordinates};
          nodes[p.id] = p;
          break;
        case 'way':
          p.coordinates = p.nodes.map(function (id) {
            return nodes[id].coordinates;
          });
          p.geometry = {type: 'LineString', coordinates: p.coordinates};

          var retval = wayFunction(p);
          if (retval)
            new_markers.push(retval);
      }
    }

    markers.addLayers(new_markers);
    new_markers = [];
  }

  function handleRelations(overpassJSON) {
    console.log("handleRelations called");
    var nodes = {}, ways = {};

    //overpass returns elements unsorted: rels, nodes, ways - should be nodes, ways, rels
    var rels = []; // to handle them last

    var new_markers = [];
    console.log(overpassJSON.elements);
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      switch (p.type) {
        case 'node':
          p.coordinates = [p.lon, p.lat];
          p.geometry = {type: 'Point', coordinates: p.coordinates};
          nodes[p.id] = p;
          break;
        case 'way':
          p.coordinates = p.nodes.map(function (id) {
            return nodes[id].coordinates;
          });
          p.geometry = {type: 'LineString', coordinates: p.coordinates};
          ways[p.id] = p;
          break;
        case 'relation':
          rels.push(p);
          break;
      }
    }
    console.log("nodes count:" + Object.keys(nodes).length + "; ways count:" + Object.keys(ways).length + "; rel count: " + rels.length);

    // handle relations last
    for (var i = 0; i < rels.length; i++) {
      var p = rels[i];
      p.members.map(function (mem) {
          if (mem.type == 'node') {

            if(!nodes[mem.ref])
              console.log("mem.type=node missing: " + mem.ref);

            mem.obj = nodes[mem.ref];
          } else if (mem.type == 'way') {

            if(!ways[mem.ref])
              console.log("mem.type=way missing: " + mem.ref); //FIXME this seems to come from overpass query not returning childs of rels... change query!

            mem.obj = ways[mem.ref];
          } else
            console.log("mem.type=" + mem.type);// FIXME handle rels of rels
      });
      // p has type=relaton, id, tags={k:v}, members=[{role, obj}]
      var retval = relationFunction(p);
      if (retval)
        new_markers.push(retval);

    }

    markers.addLayers(new_markers);
    new_markers = [];
  }

  var query = overpass_query;

  var node_query = overpass_query_nodes;
  var way_query = overpass_query_ways;
  var rel_query = overpass_query_rels;

  var allUrl = query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());

  var node_url = node_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());
  var way_url = way_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());
  var rel_url = rel_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());

  $.getJSON(node_url, handleNodes);
  $.getJSON(way_url, handleWays);
  $.getJSON(rel_url, handleRelations);

  console.log("loadPOI called");

}
<commit_msg>map.js - debug statements added<commit_after>/* this part must be in global namespace */
// fetch taxonomy, containing all translations, and implicit affiliations
// taken from Wikipedia:JSON
var url = "taxonomy.json";
var taxonomy;
var http_request = new XMLHttpRequest();
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
      var done = 4, ok = 200;
      if (http_request.readyState === done && http_request.status === ok) {
          taxonomy = JSON.parse(http_request.responseText);
      }
  };
http_request.send(null);

function initMap(defaultlayer,base_maps,overlay_maps) {
  map = new L.Map('map', {
    center: new L.LatLng(47.07, 15.43),
      zoom: 13,
      layers: defaultlayer,
  });

  var ctrl = new L.Control.Layers(base_maps,overlay_maps)
  map.addControl(ctrl);

  L.LatLngBounds.prototype.toOverpassBBoxString = function (){
    var a = this._southWest,
        b = this._northEast;
    return [a.lat, a.lng, b.lat, b.lng].join(",");
  }

  var path_style = L.Path.prototype._updateStyle;
  L.Path.prototype._updateStyle = function () {
    path_style.apply(this);
    for (k in this.options.svg) {
      this._path.setAttribute(k, this.options.svg[k]);
    }
  }

  return map;
}

function addSearch() {
  map.addControl( new L.Control.Search({
    url: 'http://nominatim.openstreetmap.org/search?format=json&q={s}',
    jsonpParam: 'json_callback',
    propertyName: 'display_name',
    propertyLoc: ['lat','lon'],
    circleLocation: false,
    markerLocation: false,
    autoType: false,
    autoCollapse: false,
    minLength: 2,
    zoom:12
  }) );

}
function addLocate() {
lc = L.control.locate({
        position: 'topleft',
        showPopup: false,
        strings: {
                title: "Jump to my location!"
            }
      }
      ).addTo(map);
}

var marker_table = {};

function loadPoi() {
  if (map.getZoom() < 12 ) {
    return;
  }
  console.log("loadPOI called");

  var iconsize = 24;

  function fillPopup(tags,type,id) {

    var r = $('
');
    var tags_to_ignore = [ "name" , "ref", "needs" ];

    for (key in tags) {
      if ( tags_to_ignore.indexOf(key) >= 0) {
        continue;
      } else if ( key == 'website' || key == 'url' || key == 'contact:website' ||  key == 'contact:url') { //TODO: , facebook, …
        var value = tags[key];
        var teststr=/^http/; //http[s] is implicit here
        if ( ! teststr.test(value) )
          value = "http://" + value;

        var htlink = '' + value + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));
      } else if (key == 'wikipedia') { // wikipedia - TODO key="wikipedia:de"
        var value = tags[key];
        var begin = "";
        var teststr=/^http/; //http[s] is implicit here
        if ( ! teststr.test(value) )
          begin = "https://wikipedia.org/wiki/";

        var htlink = '' + value + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));
      } else if (key == 'contact:email' || key == 'email') {
        var value = tags[key];
        var teststr=/^mailto:/;
        if ( ! teststr.test(value) )
          value = "mailto:" + value;
        var htlink = '' + tags[key] + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));

      } else {
        var keytext = key;
        var valuetext = tags[key];

        /* display label:* instead of key */
        var found = 0; // use for break outer loops

        for ( groupname in taxonomy ) { // e.g. "fulfils_needs" : {}=group
          group = taxonomy[groupname];

          var count_items = group["items"].length;
          for (var i = 0; i < count_items; i++) { // loop over each item in group["items"]
            item = group["items"][i];
            if(item["osm:key"] == keytext) {
              keytext = "" + item.label["en"] + ""; // for displaying a translated value
              found = 1;
              break;
            }
          }
          if(found == 1)
            break; // for ( groupname in taxonomy )
        }

        r.append($('
').append($('').append(keytext)).append($('').text(valuetext)));
      }

    } // end for (key in tags)
    r.append($('
').append($('').append(" ")).append($('').append(" "))); // spacer

    r.append($('
').append($('').text("OSM-Type:")).append($('').text(type)));
    r.append($('
').append($('').text("OSM-ID:")).append($('').append('' + id + '')));

    var s = $('
');
    s.append(r);
    var retval = $('
').append(s);
    retval.prepend($('
').text(tags["name"]));
    return retval.html();
  }

  function bindPopupOnData(data) {
    // first: check if no item with this osm-id exists...
    var hashtable_key = data.type + data.id; // e.g. "node1546484546"
    if(marker_table[hashtable_key] == 1) //object already there
      return;
    marker_table[hashtable_key] = 1;

    // set icon dependent on tags
    var icon_tag = ""; //OSM key for choosing icon
    for (var i = 0; i < icon_tags.length; i++) {
      var key = icon_tags[i];
      if(data.tags[key]) {
        icon_tag = key;
        break;
      }
    }

    var icon_url = "";
    if(!icon_tag) {
      icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/unknown.png";
    } else {

      if (data.tags[icon_tag].indexOf(";") >= 0) // more than one item, take generic icon
        icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/generic.png";
      else
        icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/" + icon_tag + "=" + data.tags[icon_tag] + ".png";
    }

    var needs_icon = L.icon({
      iconUrl: icon_url,
      iconSize: new L.Point(iconsize, iconsize),
      iconAnchor: new L.Point(iconsize / 2, iconsize / 2),
    });

    var lmarker = L.marker([data.lat, data.lon], {
      icon: needs_icon,
      title: data.tags.name
    });
    lmarker.bindPopup(fillPopup(data.tags,data.type,data.id));
    return lmarker;
  }

  function nodeFunction(data) {
    if (! data.tags || ! data.tags.name || data.tags.entrance ) // no retval if node is just member of a way
      return null;
    return bindPopupOnData(data);
  }
  function wayFunction(data) {
    //calculate centre of polygon

    var centroid = $.geo.centroid(data.geometry);
    //var style = {};
    centroid.tags = data.tags;
    centroid.id = data.id;
    centroid.type = data.type;
    centroid.lon = centroid.coordinates[0];
    centroid.lat = centroid.coordinates[1];
    return bindPopupOnData(centroid);
  };
  function relationFunction(data) {
    // calculate mean coordinates as center
    // for all members, calculate centroid
    // then calculate mean over all nodes and centroids.
    var centroids = [];
    var sum_lon = 0;
    var sum_lat = 0;
    //console.log(data);
    for (var i = 0; i < data.members.length; i++) {
      var p = data.members[i];
      var centroid;
      switch (p.type) {
        case 'node':
          centroid = p.obj.coordinates;
          centroids.push(centroid);
          break;
        case 'way':
          //console.log(p);
          if (p.role == "outer") {// FIXME add handling of rel members
            var centroid_point = $.geo.centroid(p.obj.geometry);
            centroid = centroid_point.coordinates;
            centroids.push(centroid);
          }
          break;
      }
      if(centroid.length != 0) {
        sum_lon += centroid[0];
        sum_lat += centroid[1];
      } else
        console.log("centroid empty!");
    }
    //console.log(centroids);
    var sum_centroid = {
      id : data.id,
      lon : sum_lon / data.members.length,
      lat : sum_lat / data.members.length,
      tags : data.tags,
      type : data.type
    }

    //console.log(sum_centroid);
    return bindPopupOnData(sum_centroid);
    // todo: in the long term, all areas should be displayed as areas (as in overpass turbo)
  }

  function handleNodes(overpassJSON) {
    console.log("handleNodes called");
    var new_markers = [];
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      p.coordinates = [p.lon, p.lat];
      p.geometry = {type: 'Point', coordinates: p.coordinates};

      var retval = nodeFunction(p);
      if (retval)
        new_markers.push(retval);
    }
    var number = new_markers.length;
    markers.addLayers(new_markers);
    new_markers = [];
    console.log("handleNodes done, " + number + " added.");
  }

  function handleWays(overpassJSON) {
    console.log("handleWays called");
    var new_markers = [];
    var nodes = {};
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      switch (p.type) {
        case 'node':
          p.coordinates = [p.lon, p.lat];
          p.geometry = {type: 'Point', coordinates: p.coordinates};
          nodes[p.id] = p;
          break;
        case 'way':
          p.coordinates = p.nodes.map(function (id) {
            return nodes[id].coordinates;
          });
          p.geometry = {type: 'LineString', coordinates: p.coordinates};

          var retval = wayFunction(p);
          if (retval)
            new_markers.push(retval);
      }
    }

    var number = new_markers.length;
    markers.addLayers(new_markers);
    new_markers = [];
    console.log("handleWays done, " + number + " added.");
  }

  function handleRelations(overpassJSON) {
    console.log("handleRelations called");
    var nodes = {}, ways = {};

    //overpass returns elements unsorted: rels, nodes, ways - should be nodes, ways, rels
    var rels = []; // to handle them last

    var new_markers = [];
    //console.log(overpassJSON.elements);
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      switch (p.type) {
        case 'node':
          p.coordinates = [p.lon, p.lat];
          p.geometry = {type: 'Point', coordinates: p.coordinates};
          nodes[p.id] = p;
          break;
        case 'way':
          p.coordinates = p.nodes.map(function (id) {
            return nodes[id].coordinates;
          });
          p.geometry = {type: 'LineString', coordinates: p.coordinates};
          ways[p.id] = p;
          break;
        case 'relation':
          rels.push(p);
          break;
      }
    }
    //console.log("nodes count:" + Object.keys(nodes).length + "; ways count:" + Object.keys(ways).length + "; rel count: " + rels.length);

    // handle relations last
    for (var i = 0; i < rels.length; i++) {
      var p = rels[i];
      p.members.map(function (mem) {
          if (mem.type == 'node') {

            if(!nodes[mem.ref])
              console.log("mem.type=node missing: " + mem.ref);

            mem.obj = nodes[mem.ref];
          } else if (mem.type == 'way') {

            if(!ways[mem.ref])
              console.log("mem.type=way missing: " + mem.ref); //FIXME this seems to come from overpass query not returning childs of rels... change query!

            mem.obj = ways[mem.ref];
          } else
            console.log("mem.type=" + mem.type);// FIXME handle rels of rels
      });
      // p has type=relaton, id, tags={k:v}, members=[{role, obj}]
      var retval = relationFunction(p);
      if (retval)
        new_markers.push(retval);

    }

    var number = new_markers.length;
    markers.addLayers(new_markers);
    new_markers = [];
    console.log("handleRelations done, " + number + " added.");
  }

  var query = overpass_query;

  var node_query = overpass_query_nodes;
  var way_query = overpass_query_ways;
  var rel_query = overpass_query_rels;

  var allUrl = query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());

  var node_url = node_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());
  var way_url = way_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());
  var rel_url = rel_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());

  var progress_div = document.getElementById('loading');
  //  node: getJSON [x] |
  console.log("loadPOI: before JSON calls");
  $.getJSON(node_url, handleNodes);
  $.getJSON(way_url, handleWays);
  $.getJSON(rel_url, handleRelations);

}
<|endoftext|>


<commit_before>/* this part must be in global namespace */
// fetch taxonomy, containing all translations, and implicit affiliations
// taken from Wikipedia:JSON
var url = "taxonomy.json";
var taxonomy;
var http_request = new XMLHttpRequest();
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
      var done = 4, ok = 200;
      if (http_request.readyState === done && http_request.status === ok) {
          taxonomy = JSON.parse(http_request.responseText);
      }
  };
http_request.send(null);

function initMap(defaultlayer,base_maps,overlay_maps) {
  map = new L.Map('map', {
    center: new L.LatLng(47.07, 15.43),
      zoom: 13,
      layers: defaultlayer,
  });

  var ctrl = new L.Control.Layers(base_maps,overlay_maps)
  map.addControl(ctrl);

  L.LatLngBounds.prototype.toOverpassBBoxString = function (){
    var a = this._southWest,
        b = this._northEast;
    return [a.lat, a.lng, b.lat, b.lng].join(",");
  }

  var path_style = L.Path.prototype._updateStyle;
  L.Path.prototype._updateStyle = function () {
    path_style.apply(this);
    for (k in this.options.svg) {
      this._path.setAttribute(k, this.options.svg[k]);
    }
  }

  return map;
}

function addSearch() {
  map.addControl( new L.Control.Search({
    url: 'http://nominatim.openstreetmap.org/search?format=json&q={s}',
    jsonpParam: 'json_callback',
    propertyName: 'display_name',
    propertyLoc: ['lat','lon'],
    circleLocation: false,
    markerLocation: false,
    autoType: false,
    autoCollapse: false,
    minLength: 2,
    zoom:12
  }) );

}
function addLocate() {
lc = L.control.locate({
        position: 'topleft',
        showPopup: false,
        strings: {
                title: "Jump to my location!"
            }
      }
      ).addTo(map);
}

var marker_table = {};

function loadPoi() {
  if (map.getZoom() < 12 ) {
    return;
  }

  var iconsize = 24;

  function fillPopup(tags,type,id) {

    var r = $('
');
    var tags_to_ignore = [ "name" , "ref", "needs" ];

    for (key in tags) {
      if ( tags_to_ignore.indexOf(key) >= 0) {
        continue;
      } else if ( key == 'website' || key == 'url' || key == 'contact:website' ||  key == 'contact:url') { //TODO: , facebook, …
        var value = tags[key];
        var teststr=/^http/; //http[s] is implicit here
        if ( ! teststr.test(value) )
          value = "http://" + value;

        var htlink = '' + value + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));
      } else if (key == 'wikipedia') { // wikipedia - TODO key="wikipedia:de"
        var value = tags[key];
        var begin = "";
        var teststr=/^http/; //http[s] is implicit here
        if ( ! teststr.test(value) )
          begin = "https://wikipedia.org/wiki/";

        var htlink = '' + value + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));
      } else if (key == 'contact:email' || key == 'email') {
        var value = tags[key];
        var teststr=/^mailto:/;
        if ( ! teststr.test(value) )
          value = "mailto:" + value;
        var htlink = '' + tags[key] + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));

      } else {
        var keytext = key;
        var valuetext = tags[key];

        /* display label:* instead of key */
        var found = 0; // use for break outer loops

        for ( groupname in taxonomy ) { // e.g. "fulfils_needs" : {}=group
          group = taxonomy[groupname];

          var count_items = group["items"].length;
          for (var i = 0; i < count_items; i++) { // loop over each item in group["items"]
            item = group["items"][i];
            if(item["osm:key"] == keytext) {
              keytext = "" + item.label["en"] + ""; // for displaying a translated value
              found = 1;
              break;
            }
          }
          if(found == 1)
            break; // for ( groupname in taxonomy )
        }

        r.append($('
').append($('').append(keytext)).append($('').text(valuetext)));
      }

    } // end for (key in tags)
    r.append($('
').append($('').append(" ")).append($('').append(" "))); // spacer

    r.append($('
').append($('').text("OSM-Type:")).append($('').text(type)));
    r.append($('
').append($('').text("OSM-ID:")).append($('').append('' + id + '')));

    var s = $('
');
    s.append(r);
    var retval = $('
').append(s);
    retval.prepend($('
').text(tags["name"]));
    return retval.html();
  }

  function bindPopupOnData(data) {
    // first: check if no item with this osm-id exists...
    var hashtable_key = data.type + data.id; // e.g. "node1546484546"
    if(marker_table[hashtable_key] == 1) //object already there
      return;
    marker_table[hashtable_key] = 1;

    // set icon dependent on tags
    var icon_tag = ""; //OSM key for choosing icon
    for (var i = 0; i < icon_tags.length; i++) {
      var key = icon_tags[i];
      if(data.tags[key]) {
        icon_tag = key;
        break;
      }
    }

    var icon_url = "";
    if(!icon_tag) {
      icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/unknown.png";
    } else {

      if (data.tags[icon_tag].indexOf(";") >= 0) // more than one item, take generic icon
        icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/generic.png";
      else
        icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/" + icon_tag + "=" + data.tags[icon_tag] + ".png";
    }

    var needs_icon = L.icon({
      iconUrl: icon_url,
      iconSize: new L.Point(iconsize, iconsize),
      iconAnchor: new L.Point(iconsize / 2, iconsize / 2),
    });

    var lmarker = L.marker([data.lat, data.lon], {
      icon: needs_icon,
      title: data.tags.name
    });
    lmarker.bindPopup(fillPopup(data.tags,data.type,data.id));
    return lmarker;
  }

  function nodeFunction(data) {
    if (! data.tags || ! data.tags.name || data.tags.entrance ) // no retval if node is just member of a way
      return null;
    return bindPopupOnData(data);
  }
  function wayFunction(data) {
    //calculate centre of polygon

    var centroid = $.geo.centroid(data.geometry);
    //var style = {};
    centroid.tags = data.tags;
    centroid.id = data.id;
    centroid.type = data.type;
    centroid.lon = centroid.coordinates[0];
    centroid.lat = centroid.coordinates[1];
    return bindPopupOnData(centroid);
  };
  function relationFunction(data) {
    // calculate mean coordinates as center
    // for all members, calculate centroid
    // then calculate mean over all nodes and centroids.
    var centroids = [];
    var sum_lon = 0;
    var sum_lat = 0;
    console.log(data);
    for (var i = 0; i < data.members.length; i++) {
      var p = data.members[i];
      var centroid;
      switch (p.type) {
        case 'node':
          centroid = p.obj.coordinates;
          centroids.push(centroid);
          break;
        case 'way':
          console.log(p);
          if (p.role == "outer") {// FIXME add handling of rel members
            var centroid_point = $.geo.centroid(p.obj.geometry);
            centroid = centroid_point.coordinates;
            centroids.push(centroid);
          }
          break;
      }
      if(centroid.length != 0) {
        sum_lon += centroid[0];
        sum_lat += centroid[1];
      } else
        console.log("centroid empty!");
    }
    //console.log(centroids);
    var sum_centroid = {
      id : data.id,
      lon : sum_lon / data.members.length,
      lat : sum_lat / data.members.length,
      tags : data.tags,
      type : data.type
    }

    //console.log(sum_centroid);
    return bindPopupOnData(sum_centroid);
    // todo: in the long term, all areas should be displayed as areas (as in overpass turbo)
  }

  function handleNodes(overpassJSON) {
    console.log("handleNodes called");
    var new_markers = [];
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      p.coordinates = [p.lon, p.lat];
      p.geometry = {type: 'Point', coordinates: p.coordinates};

      var retval = nodeFunction(p);
      if (retval)
        new_markers.push(retval);
    }
    markers.addLayers(new_markers);
    new_markers = [];
  }

  function handleWays(overpassJSON) {
    console.log("handleWays called");
    var new_markers = [];
    var nodes = {};
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      switch (p.type) {
        case 'node':
          p.coordinates = [p.lon, p.lat];
          p.geometry = {type: 'Point', coordinates: p.coordinates};
          nodes[p.id] = p;
          break;
        case 'way':
          p.coordinates = p.nodes.map(function (id) {
            return nodes[id].coordinates;
          });
          p.geometry = {type: 'LineString', coordinates: p.coordinates};

          var retval = wayFunction(p);
          if (retval)
            new_markers.push(retval);
      }
    }

    markers.addLayers(new_markers);
    new_markers = [];
  }

  function handleRelations(overpassJSON) {
    console.log("handleRelations called");
    var nodes = {}, ways = {};

    //overpass returns elements unsorted: rels, nodes, ways - should be nodes, ways, rels
    var rels = []; // to handle them last

    var new_markers = [];
    console.log(overpassJSON.elements);
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      switch (p.type) {
        case 'node':
          p.coordinates = [p.lon, p.lat];
          p.geometry = {type: 'Point', coordinates: p.coordinates};
          nodes[p.id] = p;
          break;
        case 'way':
          p.coordinates = p.nodes.map(function (id) {
            return nodes[id].coordinates;
          });
          p.geometry = {type: 'LineString', coordinates: p.coordinates};
          ways[p.id] = p;
          break;
        case 'relation':
          rels.push(p);
          break;
      }
    }
    console.log("nodes count:" + Object.keys(nodes).length + "; ways count:" + Object.keys(ways).length + "; rel count: " + rels.length);

    // handle relations last
    for (var i = 0; i < rels.length; i++) {
      var p = rels[i];
      p.members.map(function (mem) {
          if (mem.type == 'node') {

            if(!nodes[mem.ref])
              console.log("mem.type=node missing: " + mem.ref);

            mem.obj = nodes[mem.ref];
          } else if (mem.type == 'way') {

            if(!ways[mem.ref])
              console.log("mem.type=way missing: " + mem.ref); //FIXME this seems to come from overpass query not returning childs of rels... change query!

            mem.obj = ways[mem.ref];
          } else
            console.log("mem.type=" + mem.type);// FIXME handle rels of rels
      });
      // p has type=relaton, id, tags={k:v}, members=[{role, obj}]
      var retval = relationFunction(p);
      if (retval)
        new_markers.push(retval);

    }

    markers.addLayers(new_markers);
    new_markers = [];
  }

  var query = overpass_query;

  var node_query = overpass_query_nodes;
  var way_query = overpass_query_ways;
  var rel_query = overpass_query_rels;

  var allUrl = query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());

  var node_url = node_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());
  var way_url = way_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());
  var rel_url = rel_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());

// $.getJSON(allUrl, handleNodeWayRelations);

  $.getJSON(node_url, handleNodes);
  $.getJSON(way_url, handleWays);
  $.getJSON(rel_url, handleRelations);

  console.log("loadPOI called");

}
<commit_msg>remove old refactored js code<commit_after>/* this part must be in global namespace */
// fetch taxonomy, containing all translations, and implicit affiliations
// taken from Wikipedia:JSON
var url = "taxonomy.json";
var taxonomy;
var http_request = new XMLHttpRequest();
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
      var done = 4, ok = 200;
      if (http_request.readyState === done && http_request.status === ok) {
          taxonomy = JSON.parse(http_request.responseText);
      }
  };
http_request.send(null);

function initMap(defaultlayer,base_maps,overlay_maps) {
  map = new L.Map('map', {
    center: new L.LatLng(47.07, 15.43),
      zoom: 13,
      layers: defaultlayer,
  });

  var ctrl = new L.Control.Layers(base_maps,overlay_maps)
  map.addControl(ctrl);

  L.LatLngBounds.prototype.toOverpassBBoxString = function (){
    var a = this._southWest,
        b = this._northEast;
    return [a.lat, a.lng, b.lat, b.lng].join(",");
  }

  var path_style = L.Path.prototype._updateStyle;
  L.Path.prototype._updateStyle = function () {
    path_style.apply(this);
    for (k in this.options.svg) {
      this._path.setAttribute(k, this.options.svg[k]);
    }
  }

  return map;
}

function addSearch() {
  map.addControl( new L.Control.Search({
    url: 'http://nominatim.openstreetmap.org/search?format=json&q={s}',
    jsonpParam: 'json_callback',
    propertyName: 'display_name',
    propertyLoc: ['lat','lon'],
    circleLocation: false,
    markerLocation: false,
    autoType: false,
    autoCollapse: false,
    minLength: 2,
    zoom:12
  }) );

}
function addLocate() {
lc = L.control.locate({
        position: 'topleft',
        showPopup: false,
        strings: {
                title: "Jump to my location!"
            }
      }
      ).addTo(map);
}

var marker_table = {};

function loadPoi() {
  if (map.getZoom() < 12 ) {
    return;
  }

  var iconsize = 24;

  function fillPopup(tags,type,id) {

    var r = $('
');
    var tags_to_ignore = [ "name" , "ref", "needs" ];

    for (key in tags) {
      if ( tags_to_ignore.indexOf(key) >= 0) {
        continue;
      } else if ( key == 'website' || key == 'url' || key == 'contact:website' ||  key == 'contact:url') { //TODO: , facebook, …
        var value = tags[key];
        var teststr=/^http/; //http[s] is implicit here
        if ( ! teststr.test(value) )
          value = "http://" + value;

        var htlink = '' + value + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));
      } else if (key == 'wikipedia') { // wikipedia - TODO key="wikipedia:de"
        var value = tags[key];
        var begin = "";
        var teststr=/^http/; //http[s] is implicit here
        if ( ! teststr.test(value) )
          begin = "https://wikipedia.org/wiki/";

        var htlink = '' + value + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));
      } else if (key == 'contact:email' || key == 'email') {
        var value = tags[key];
        var teststr=/^mailto:/;
        if ( ! teststr.test(value) )
          value = "mailto:" + value;
        var htlink = '' + tags[key] + '';
        r.append($('
').append($('').text(key)).append($('').append(htlink)));

      } else {
        var keytext = key;
        var valuetext = tags[key];

        /* display label:* instead of key */
        var found = 0; // use for break outer loops

        for ( groupname in taxonomy ) { // e.g. "fulfils_needs" : {}=group
          group = taxonomy[groupname];

          var count_items = group["items"].length;
          for (var i = 0; i < count_items; i++) { // loop over each item in group["items"]
            item = group["items"][i];
            if(item["osm:key"] == keytext) {
              keytext = "" + item.label["en"] + ""; // for displaying a translated value
              found = 1;
              break;
            }
          }
          if(found == 1)
            break; // for ( groupname in taxonomy )
        }

        r.append($('
').append($('').append(keytext)).append($('').text(valuetext)));
      }

    } // end for (key in tags)
    r.append($('
').append($('').append(" ")).append($('').append(" "))); // spacer

    r.append($('
').append($('').text("OSM-Type:")).append($('').text(type)));
    r.append($('
').append($('').text("OSM-ID:")).append($('').append('' + id + '')));

    var s = $('
');
    s.append(r);
    var retval = $('
').append(s);
    retval.prepend($('
').text(tags["name"]));
    return retval.html();
  }

  function bindPopupOnData(data) {
    // first: check if no item with this osm-id exists...
    var hashtable_key = data.type + data.id; // e.g. "node1546484546"
    if(marker_table[hashtable_key] == 1) //object already there
      return;
    marker_table[hashtable_key] = 1;

    // set icon dependent on tags
    var icon_tag = ""; //OSM key for choosing icon
    for (var i = 0; i < icon_tags.length; i++) {
      var key = icon_tags[i];
      if(data.tags[key]) {
        icon_tag = key;
        break;
      }
    }

    var icon_url = "";
    if(!icon_tag) {
      icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/unknown.png";
    } else {

      if (data.tags[icon_tag].indexOf(";") >= 0) // more than one item, take generic icon
        icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/generic.png";
      else
        icon_url = "assets/transformap/pngs/" + icon_foldername + "/" + iconsize + "/" + icon_tag + "=" + data.tags[icon_tag] + ".png";
    }

    var needs_icon = L.icon({
      iconUrl: icon_url,
      iconSize: new L.Point(iconsize, iconsize),
      iconAnchor: new L.Point(iconsize / 2, iconsize / 2),
    });

    var lmarker = L.marker([data.lat, data.lon], {
      icon: needs_icon,
      title: data.tags.name
    });
    lmarker.bindPopup(fillPopup(data.tags,data.type,data.id));
    return lmarker;
  }

  function nodeFunction(data) {
    if (! data.tags || ! data.tags.name || data.tags.entrance ) // no retval if node is just member of a way
      return null;
    return bindPopupOnData(data);
  }
  function wayFunction(data) {
    //calculate centre of polygon

    var centroid = $.geo.centroid(data.geometry);
    //var style = {};
    centroid.tags = data.tags;
    centroid.id = data.id;
    centroid.type = data.type;
    centroid.lon = centroid.coordinates[0];
    centroid.lat = centroid.coordinates[1];
    return bindPopupOnData(centroid);
  };
  function relationFunction(data) {
    // calculate mean coordinates as center
    // for all members, calculate centroid
    // then calculate mean over all nodes and centroids.
    var centroids = [];
    var sum_lon = 0;
    var sum_lat = 0;
    console.log(data);
    for (var i = 0; i < data.members.length; i++) {
      var p = data.members[i];
      var centroid;
      switch (p.type) {
        case 'node':
          centroid = p.obj.coordinates;
          centroids.push(centroid);
          break;
        case 'way':
          console.log(p);
          if (p.role == "outer") {// FIXME add handling of rel members
            var centroid_point = $.geo.centroid(p.obj.geometry);
            centroid = centroid_point.coordinates;
            centroids.push(centroid);
          }
          break;
      }
      if(centroid.length != 0) {
        sum_lon += centroid[0];
        sum_lat += centroid[1];
      } else
        console.log("centroid empty!");
    }
    //console.log(centroids);
    var sum_centroid = {
      id : data.id,
      lon : sum_lon / data.members.length,
      lat : sum_lat / data.members.length,
      tags : data.tags,
      type : data.type
    }

    //console.log(sum_centroid);
    return bindPopupOnData(sum_centroid);
    // todo: in the long term, all areas should be displayed as areas (as in overpass turbo)
  }

  function handleNodes(overpassJSON) {
    console.log("handleNodes called");
    var new_markers = [];
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      p.coordinates = [p.lon, p.lat];
      p.geometry = {type: 'Point', coordinates: p.coordinates};

      var retval = nodeFunction(p);
      if (retval)
        new_markers.push(retval);
    }
    markers.addLayers(new_markers);
    new_markers = [];
  }

  function handleWays(overpassJSON) {
    console.log("handleWays called");
    var new_markers = [];
    var nodes = {};
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      switch (p.type) {
        case 'node':
          p.coordinates = [p.lon, p.lat];
          p.geometry = {type: 'Point', coordinates: p.coordinates};
          nodes[p.id] = p;
          break;
        case 'way':
          p.coordinates = p.nodes.map(function (id) {
            return nodes[id].coordinates;
          });
          p.geometry = {type: 'LineString', coordinates: p.coordinates};

          var retval = wayFunction(p);
          if (retval)
            new_markers.push(retval);
      }
    }

    markers.addLayers(new_markers);
    new_markers = [];
  }

  function handleRelations(overpassJSON) {
    console.log("handleRelations called");
    var nodes = {}, ways = {};

    //overpass returns elements unsorted: rels, nodes, ways - should be nodes, ways, rels
    var rels = []; // to handle them last

    var new_markers = [];
    console.log(overpassJSON.elements);
    for (var i = 0; i < overpassJSON.elements.length; i++) {
      var p = overpassJSON.elements[i];
      switch (p.type) {
        case 'node':
          p.coordinates = [p.lon, p.lat];
          p.geometry = {type: 'Point', coordinates: p.coordinates};
          nodes[p.id] = p;
          break;
        case 'way':
          p.coordinates = p.nodes.map(function (id) {
            return nodes[id].coordinates;
          });
          p.geometry = {type: 'LineString', coordinates: p.coordinates};
          ways[p.id] = p;
          break;
        case 'relation':
          rels.push(p);
          break;
      }
    }
    console.log("nodes count:" + Object.keys(nodes).length + "; ways count:" + Object.keys(ways).length + "; rel count: " + rels.length);

    // handle relations last
    for (var i = 0; i < rels.length; i++) {
      var p = rels[i];
      p.members.map(function (mem) {
          if (mem.type == 'node') {

            if(!nodes[mem.ref])
              console.log("mem.type=node missing: " + mem.ref);

            mem.obj = nodes[mem.ref];
          } else if (mem.type == 'way') {

            if(!ways[mem.ref])
              console.log("mem.type=way missing: " + mem.ref); //FIXME this seems to come from overpass query not returning childs of rels... change query!

            mem.obj = ways[mem.ref];
          } else
            console.log("mem.type=" + mem.type);// FIXME handle rels of rels
      });
      // p has type=relaton, id, tags={k:v}, members=[{role, obj}]
      var retval = relationFunction(p);
      if (retval)
        new_markers.push(retval);

    }

    markers.addLayers(new_markers);
    new_markers = [];
  }

  var query = overpass_query;

  var node_query = overpass_query_nodes;
  var way_query = overpass_query_ways;
  var rel_query = overpass_query_rels;

  var allUrl = query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());

  var node_url = node_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());
  var way_url = way_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());
  var rel_url = rel_query.replace(/BBOX/g, map.getBounds().toOverpassBBoxString());

  $.getJSON(node_url, handleNodes);
  $.getJSON(way_url, handleWays);
  $.getJSON(rel_url, handleRelations);

  console.log("loadPOI called");

}
<|endoftext|>


<commit_before>(function() {
    /*
        Constants
    */
    var WOUNDED = "wounded";
    var KILLED = "killed";
    var VALUE = "value";
    var KEY = "key";

    /*
        IDs
    */
    var mapId = "#statesvg";
    var containerId = "#chartcontainer";
    var chartId = "#chart";

    /*
        Global Data
    */
    var currentYear = 2013;
    var text;
    var currentSelection = KILLED;
    var stateData;
    var barHeight;
    var margin = {top: 20, right: 30, bottom: 30, left: 40};

    /*
        Scales
    */
    var quantize;
    var barScale;
    var yScale;

    function tooltipHtml(stateName, id, dataObject, selection) {
        return "
" + stateName + "
" +
        "

 Affected(per million): " + dataObject[id][selection] + "
</table";
    }

    function mouseOver(d) {
        d3.select("#tooltip")
            .transition()
            .duration(100)
            .style("opacity", 0.9);

        d3.select("#tooltip").html(tooltipHtml(d.n, d.id, mouseOver.dataObject, mouseOver.selection))
            .style("left", (d3.event.pageX) + "px")
            .style("top", (d3.event.pageY) + "px");

        d3.select("#" + d.id)
            .transition()
            .duration(100)
            .style("opacity", 0.4);
    }

    function mouseOut(d) {
        d3.select("#tooltip")
            .transition()
            .duration(500)
            .style("opacity", 0);

        d3.select("#" + d.id)
            .transition()
            .duration(100)
            .style("opacity", 1);

    }

    function setUpScale(data) {
        // Calculate the maximum
        // of the killed and wounded for each year for each state
        var max = 0;

        for (year in data) {
            for (state in data[year]) {
                if (data[year] && data[year][state]) {
                    wounded = data[year][state][KILLED];
                    killed = data[year][state][WOUNDED];
                    thisMax = Math.max.apply(null, [killed, wounded]);

                    if (thisMax > max) {
                        max = thisMax;
                    }
                }
            }
        }

        // Set up the scale for the bar chart
        var width = d3.select(containerId).node().width.baseVal.value;
        var height = d3.select(containerId).node().height.baseVal.value;

        barScale = d3.scale.linear()
            .domain([0, max])
            .range([0, width - margin.left - margin.right]);

        yScale = d3.scale.ordinal()
            .domain(d3.range(uStatePaths.length))
            .rangeBands([0, height - margin.top - margin.bottom]);

        // Set up the color scale
        quantize = d3.scale.quantize()
            .domain([1, max])
            .range(d3.range(8).map(function (i) {
                return "q" + i + "-8";
            }));
    }

    function drawMap(stateData, year, selection) {
        // Enter selection
        d3.select(mapId)
            .selectAll(".state")
            .data(uStatePaths)
            .enter()
            .append("path");

        mouseOver.dataObject = stateData[year];
        mouseOver.selection = selection;

        // Update attributes for the enter and update selection
        d3.select(mapId)
            .selectAll("path")
            .attr("class", function (d) {
                if (stateData[year][d.id][selection] == 0) {
                    return "state zero";
                }
                return "state " + quantize(stateData[year][d.id][selection]);
            })
            .attr("d", function (d) {
                return d.d;
            })
            .on("mouseover", mouseOver)
            .on("mouseout", mouseOut);

        drawLegend();
    }

    function setupBarChart() {
        /*
         Container properties
        */
        var container = d3.select(containerId);
        var width = container.node().width.baseVal.value;
        var height = container.node().height.baseVal.value;

        barHeight = Math.floor((height - margin.top - margin.bottom) / 51.0);
        /*
            Chart Element within the container
        */
        var barChart = container
            .append("g")
            .attr("id", "chart")
            .attr("width", width - margin.left - margin.right)
            .attr("height", height - margin.top - margin.bottom)
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        var xAxis = d3.svg.axis()
            .scale(barScale)
            .orient("top");

        barChart.append("g")
            .attr("class", "x axis")
            .call(xAxis);

        barChart.append("text")      // text label for the x axis
            .attr("transform", "translate(" + ((width - margin.left - margin.right) /  2) + " ," + margin.top * 1.2 + ")")
            .text("Affected per million");

        var yAxis = d3.svg.axis()
            .scale(yScale)
            .orient("left");

        barChart.append("g")
            .attr("class", "x axis")
            .call(yAxis)
            .selectAll("text").remove();
    }

    function drawBarChart(data, year, selection) {
        var bars = d3.select(chartId).selectAll(".bar");

        var sortedData = d3.entries(data[year])
            .sort(function (first, second) {
                return second[VALUE][selection] - first[VALUE][selection];
            });

        // Enter Selection
        enterSelection = bars.data(sortedData)
            .enter()
            .append("g")
            .attr("transform", function (d, i) {
                return "translate(0," + i * barHeight + ")";
            })
            .append("rect");

        // Update attributes for the enter and update selections
        d3.select(chartId)
            .selectAll("rect")
            .data(sortedData)
            .attr("height", barHeight - 1)
            .attr("width", function (d) { return barScale(+d[VALUE][selection]);})
            .attr("id", function (d) { return d[KEY]; });

    }

    function drawLegend() {

        var legend = d3.select("#legend").selectAll("g.legendEntry")
            .data(["zero"].concat(quantize.range()))
            .enter()
            .append("g")
            .attr("transform", "translate(700, 15)");

        legend.append("text")
            .text("Affected per million")
            .attr("transform", "translate(0, -3)");

        legend
            .append("rect")
            .attr("x", "10px")
            .attr("y", function (d, i) {
                return i * 15;
            })
            .attr("width", 10)
            .attr("height", 10)
            .style("stroke", "black")
            .style("stroke-width", 1)
            .attr("class", function (d) {
                return d;
            });
        //the data objects are the fill colors

        if (!text) {
            text = legend
                .append("text");
        }

        text.attr("x", "25px")
            .attr("y", function (d, i) {
                return i * 15;
            })
            .attr("dy", "0.8em")
            .text(function (d,i) {
                if (d == "zero") {
                    return "0";
                }

                var extent = quantize.invertExtent(d);
                var format = d3.format("0.0f");
                return format(+extent[0]) + " - " + format(+extent[1]);
            });
    }

    function draw(data, year, selection) {
        drawMap(data, year, selection);
        drawBarChart(data, year, selection);
    }

    function init() {

        d3.select("#type").on("change", function () {
            currentSelection = this.value;
            draw(stateData, currentYear, currentSelection);
        });
        d3.select("#year").on("change", function () {
            currentYear = this.value;
            draw(stateData, currentYear, currentSelection);
        });

        d3.json("out.json", function (error, data) {
            stateData = data;
            setUpScale(stateData);
            setupBarChart();
            draw(stateData, currentYear, currentSelection);
        });
    }

    init();
})();
<commit_msg>feature: highlight state and show tooltip when the user focuses on a particular bar<commit_after>(function() {
    /*
        Constants
    */
    var WOUNDED = "wounded";
    var KILLED = "killed";
    var VALUE = "value";
    var KEY = "key";

    /*
        IDs
    */
    var mapId = "#statesvg";
    var containerId = "#chartcontainer";
    var chartId = "#chart";

    /*
        Global Data
    */
    var currentYear = 2013;
    var text;
    var currentSelection = KILLED;
    var stateData;
    var barHeight;
    var margin = {top: 20, right: 30, bottom: 30, left: 40};

    /*
        Scales
    */
    var quantize;
    var barScale;
    var yScale;

    function tooltipHtml(stateName, id, dataObject, selection) {
        return "
" + stateName + "
" +
        "

 Affected(per million): " + dataObject[id][selection] + "
</table";
    }

    function mouseOver(d) {
        d3.select("#tooltip")
            .transition()
            .duration(100)
            .style("opacity", 0.9);

        d3.select("#tooltip").html(tooltipHtml(d.n, d.id, mouseOver.dataObject, mouseOver.selection))
            .style("left", (d3.event.pageX) + "px")
            .style("top", (d3.event.pageY) + "px");

        d3.select("#" + d.id + "_state")
            .transition()
            .duration(100)
            .style("opacity", 0.4);
    }

    function mouseOut(d) {
        d3.select("#tooltip")
            .transition()
            .duration(500)
            .style("opacity", 0);

        d3.select("#" + d.id + "_state")
            .transition()
            .duration(100)
            .style("opacity", 1);

    }

    function setUpScale(data) {
        // Calculate the maximum
        // of the killed and wounded for each year for each state
        var max = 0;

        for (year in data) {
            for (state in data[year]) {
                if (data[year] && data[year][state]) {
                    wounded = data[year][state][KILLED];
                    killed = data[year][state][WOUNDED];
                    thisMax = Math.max.apply(null, [killed, wounded]);

                    if (thisMax > max) {
                        max = thisMax;
                    }
                }
            }
        }

        // Set up the scale for the bar chart
        var width = d3.select(containerId).node().width.baseVal.value;
        var height = d3.select(containerId).node().height.baseVal.value;

        barScale = d3.scale.linear()
            .domain([0, max])
            .range([0, width - margin.left - margin.right]);

        yScale = d3.scale.ordinal()
            .domain(d3.range(uStatePaths.length))
            .rangeBands([0, height - margin.top - margin.bottom]);

        // Set up the color scale
        quantize = d3.scale.quantize()
            .domain([1, max])
            .range(d3.range(8).map(function (i) {
                return "q" + i + "-8";
            }));
    }

    function drawMap(stateData, year, selection) {
        // Enter selection
        d3.select(mapId)
            .selectAll(".state")
            .data(uStatePaths)
            .enter()
            .append("path");

        mouseOver.dataObject = stateData[year];
        mouseOver.selection = selection;

        // Update attributes for the enter and update selection
        d3.select(mapId)
            .selectAll("path")
            .attr("class", function (d) {
                if (stateData[year][d.id][selection] == 0) {
                    return "state zero";
                }
                return "state " + quantize(stateData[year][d.id][selection]);
            })
            .attr("d", function (d) {
                return d.d;
            })
            .attr("id", function (d) {
                return d.id + "_state";
            })
            .on("mouseover", mouseOver)
            .on("mouseout", mouseOut);

        drawLegend();
    }

    function setupBarChart() {
        /*
         Container properties
        */
        var container = d3.select(containerId);
        var width = container.node().width.baseVal.value;
        var height = container.node().height.baseVal.value;

        barHeight = Math.floor((height - margin.top - margin.bottom) / 51.0);
        /*
            Chart Element within the container
        */
        var barChart = container
            .append("g")
            .attr("id", "chart")
            .attr("width", width - margin.left - margin.right)
            .attr("height", height - margin.top - margin.bottom)
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        var xAxis = d3.svg.axis()
            .scale(barScale)
            .orient("top");

        barChart.append("g")
            .attr("class", "x axis")
            .call(xAxis);

        barChart.append("text")      // text label for the x axis
            .attr("transform", "translate(" + ((width - margin.left - margin.right) /  2) + " ," + margin.top * 1.2 + ")")
            .text("Affected per million");

        var yAxis = d3.svg.axis()
            .scale(yScale)
            .orient("left");

        barChart.append("g")
            .attr("class", "x axis")
            .call(yAxis)
            .selectAll("text").remove();
    }

    function drawBarChart(data, year, selection) {
        var bars = d3.select(chartId).selectAll(".bar");

        var sortedData = d3.entries(data[year])
            .sort(function (first, second) {
                return second[VALUE][selection] - first[VALUE][selection];
            });

        // Enter Selection
        enterSelection = bars.data(sortedData)
            .enter()
            .append("g")
            .attr("transform", function (d, i) {
                return "translate(0," + i * barHeight + ")";
            })
            .append("rect");

        // Update attributes for the enter and update selections
        d3.select(chartId)
            .selectAll("rect")
            .data(sortedData)
            .attr("height", barHeight - 1)
            .attr("width", function (d) { return barScale(+d[VALUE][selection]);})
            .attr("id", function (d) { return d[KEY]; })
            .on("mouseover", function (d) {

                var stateData = uStatePaths.filter(function (value) {
                    return value.id == d[KEY];
                })[0];
                mouseOver(stateData);
            })
            .on("mouseout", function (d) {
                var stateData = uStatePaths.filter(function (value) {
                    return value.id == d[KEY];
                })[0];
                mouseOut(stateData);
            });

    }

    function drawLegend() {

        var legend = d3.select("#legend").selectAll("g.legendEntry")
            .data(["zero"].concat(quantize.range()))
            .enter()
            .append("g")
            .attr("transform", "translate(700, 15)");

        legend.append("text")
            .text("Affected per million")
            .attr("transform", "translate(0, -3)");

        legend
            .append("rect")
            .attr("x", "10px")
            .attr("y", function (d, i) {
                return i * 15;
            })
            .attr("width", 10)
            .attr("height", 10)
            .style("stroke", "black")
            .style("stroke-width", 1)
            .attr("class", function (d) {
                return d;
            });
        //the data objects are the fill colors

        if (!text) {
            text = legend
                .append("text");
        }

        text.attr("x", "25px")
            .attr("y", function (d, i) {
                return i * 15;
            })
            .attr("dy", "0.8em")
            .text(function (d,i) {
                if (d == "zero") {
                    return "0";
                }

                var extent = quantize.invertExtent(d);
                var format = d3.format("0.0f");
                return format(+extent[0]) + " - " + format(+extent[1]);
            });
    }

    function draw(data, year, selection) {
        drawMap(data, year, selection);
        drawBarChart(data, year, selection);
    }

    function init() {

        d3.select("#type").on("change", function () {
            currentSelection = this.value;
            draw(stateData, currentYear, currentSelection);
        });
        d3.select("#year").on("change", function () {
            currentYear = this.value;
            draw(stateData, currentYear, currentSelection);
        });

        d3.json("out.json", function (error, data) {
            stateData = data;
            setUpScale(stateData);
            setupBarChart();
            draw(stateData, currentYear, currentSelection);
        });
    }

    init();
})();
<|endoftext|>


<commit_before>
App.Map = function(tiles, player) {
  this.tiles     = tiles;
  this.width     = tiles.length;
  this.height    = tiles[0].length;
  this.scheduler = new ROT.Scheduler.Simple();
  this.engine    = new ROT.Engine(this.scheduler);
  this.entities  = [];
  // add entities:
  this.addEntityAtRandPos(player);
  for (var i=0; i<50; i++) {
    var fungus;
    if (Math.random()>0.25) {
      fungus = new App.Entity(App.Templates.fungus);
    } else {
      fungus = new App.Entity(App.Templates.poisonousFungus);
    }
    this.addEntityAtRandPos(fungus);
  }
};

// tiles:

App.Map.prototype.getTile = function(x, y) {
  if (x<0 || x>=this.width || y<0 || y>=this.height) {
    return App.Tiles.null;
  }
  return this.tiles[x][y] || App.Tiles.null;
};

App.Map.prototype.getRandOpenPos = function() {
  var x, y;
  do {
    x = Math.floor(Math.random()*this.width);
    y = Math.floor(Math.random()*this.height);
  } while (!this.isOpen(x, y));
  return {x:x, y:y};
};

App.Map.prototype.dig = function(x, y) {
  if (this.getTile(x,y).isDiggable) {
    this.tiles[x][y] = App.Tiles.floor;
  }
};

App.Map.prototype.isOpen = function(x, y) {
  return this.getTile(x,y).isWalkable && !this.getEntityAt(x,y);
};

// entities:

App.Map.prototype.getEntityAt = function(x, y) {
  for (var i=0; i<this.entities.length; i++) {
    var entity = this.entities[i];
    if (entity.x==x && entity.y==y) {
      return entity;
    }
  }
  return null;
};

App.Map.prototype.addEntity = function(entity) {
  if (entity.x<0 || entity.x>=this.width || entity.y<0 || entity.y>=this.height) {
    throw new Error('addEntity: entity out of map bounds');
  }
  entity.map = this;
  this.entities.push(entity);
  if (entity.hasMixin('Acting')) {
    this.scheduler.add(entity, true);
  }
};

App.Map.prototype.addEntityAtRandPos = function(entity) {
  var pos  = this.getRandOpenPos();
  entity.x = pos.x;
  entity.y = pos.y;
  this.addEntity(entity);
};

App.Map.prototype.removeEntity = function(entity) {
  for (var i=0; i<this.entities.length; i++) {
    if (this.entities[i] == entity) {
      this.entities.splice(i, 1);
      break;
    }
  }
  if (entity.hasMixin('Acting')) {
    this.scheduler.remove(entity);
  }
};

App.Map.prototype.getEntitiesWithinRadius = function(x, y, radius) {
  var entities = [];
  var left   = x-radius;
  var right  = x+radius;
  var top    = y-radius;
  var bottom = y+radius;
  for (var i=0; i<this.entities.length; i++) {
    var e = this.entities[i];
    if (e.x>=left && e.x<=right && e.y>=top && e.y<=bottom) {
      entities.push(e);
    }
  }
  return entities;
};
<commit_msg>added depth to Map (x,y,z)<commit_after>
App.Map = function(tiles, player) {
  this.tiles     = tiles;
  this.depth     = tiles.length;
  this.width     = tiles[0].length;
  this.height    = tiles[0][0].length;
  this.scheduler = new ROT.Scheduler.Simple();
  this.engine    = new ROT.Engine(this.scheduler);
  this.entities  = [];
  // add entities:
  this.addEntityAtRandPos(player);
  for (var i=0; i<50; i++) {
    var fungus;
    if (Math.random()>0.25) {
      fungus = new App.Entity(App.Templates.fungus);
    } else {
      fungus = new App.Entity(App.Templates.poisonousFungus);
    }
    this.addEntityAtRandPos(fungus);
  }
};

// tiles:

App.Map.prototype.getTile = function(x, y, z) {
  if (x<0 || x>=this.width || y<0 || y>=this.height || z<0 || z>=this.depth) {
    return App.Tiles.null;
  }
  return this.tiles[z][x][y] || App.Tiles.null;
};

App.Map.prototype.getRandOpenPos = function(z) {
  var x, y;
  do {
    x = Math.floor(Math.random()*this.width);
    y = Math.floor(Math.random()*this.height);
  } while (!this.isOpen(x,y,z));
  return {x:x, y:y, z:z};
};

App.Map.prototype.dig = function(x, y, z) {
  if (this.getTile(x,y,z).isDiggable) {
    this.tiles[z][x][y] = App.Tiles.floor;
  }
};

App.Map.prototype.isOpen = function(x, y, z) {
  return this.getTile(x,y,z).isWalkable && !this.getEntityAt(x,y,z);
};

// entities:

App.Map.prototype.getEntityAt = function(x, y, z) {
  for (var i=0; i<this.entities.length; i++) {
    var entity = this.entities[i];
    if (entity.z==z && entity.x==x && entity.y==y) {
      return entity;
    }
  }
  return null;
};

App.Map.prototype.addEntity = function(entity) {
  var e = entity;
  if (e.x<0 || e.x>=this.width || e.y<0 || e.y>=this.height || e.z<0 || e.z>=this.depth) {
    throw new Error('addEntity: entity out of map bounds');
  }
  entity.map = this;
  this.entities.push(entity);
  if (entity.hasMixin('Acting')) {
    this.scheduler.add(entity, true);
  }
};

App.Map.prototype.addEntityAtRandPos = function(entity, z) {
  var pos  = this.getRandOpenPos(z);
  entity.x = pos.x;
  entity.y = pos.y;
  entity.z = pos.z;
  this.addEntity(entity);
};

App.Map.prototype.removeEntity = function(entity) {
  for (var i=0; i<this.entities.length; i++) {
    if (this.entities[i] == entity) {
      this.entities.splice(i, 1);
      break;
    }
  }
  if (entity.hasMixin('Acting')) {
    this.scheduler.remove(entity);
  }
};

App.Map.prototype.getEntitiesWithinRadius = function(x, y, z, radius) {
  var entities = [];
  var left   = x-radius;
  var right  = x+radius;
  var top    = y-radius;
  var bottom = y+radius;
  for (var i=0; i<this.entities.length; i++) {
    var e = this.entities[i];
    if (e.z==z && e.x>=left && e.x<=right && e.y>=top && e.y<=bottom) {
      entities.push(e);
    }
  }
  return entities;
};
<|endoftext|>