var canvas;
var context;
var levelData;
var imgData;
var imgSize;
var audioData;
var levelWidth;
var levelHeight;
var camera;
var player;
var pressed_arrow = 'none';
var pressed_jump = false;
var pressed_control = false;
var respawn;
var running_speed = 500;
var paused = false;
var on_cutscene = false;
var loaded = false;
var loaded_elements = 0;
var ivan;
var offscreen_canvas = document.createElement('canvas');
var offscreen_ctx = offscreen_canvas.getContext('2d');
var current_time;
var prev_time;
var perf;
var dt;
var cutscene;
var backup;
var musicVolume = 100;
var fade = new Fade ();
var ending = new endScreen ();
function init () {
	window.performance = window.performance || {};
	performance.now = (function() {
		return performance.now||
        performance.mozNow    ||
        performance.msNow     ||
        performance.oNow      ||
        performance.webkitNow ||
        function() { return new Date().getTime(); };
	})();
	window.onblur = function pausa () {
		if(!paused&&!on_cutscene&&loaded){
			paused = true;
			pauseScreen();
		}
	};
	perf = performance;
	canvas = document.getElementById('canvas');
	context = canvas.getContext('2d');
	initLevel ();
	//Game Assets
	loadImages();
	loadAudio();
	tick();
}

function tick () {
	if(!loaded) {
		loadingScreen();
	} else {
		prev_time = current_time;
		current_time = perf.now();
		dt = (current_time-prev_time)/1000;
		logic ();
		draw ();
	}
	requestAnimationFrame(tick);
	//setTimeout(tick, 35);
}

function logic () {
	levelData.logic ();
	if(!paused) {
		levelMusic();
		if(!on_cutscene){
			key ();
			player.move ();
			ivan.move();
			camera.move ();
		}
	}
}

function draw () {
	if(!paused){
		//context.clearRect (0, 0, canvas.width, canvas.height);
		camera.draw();
		levelData.draw();
		//context.fillText(dt, 50, 50);
		if(cutscene != undefined){
			if(!cutscene.finished)
				cutscene.run();
		}
		fade.draw();
		ending.draw();
	}
	//context.drawImage(offscreen_canvas, 0, 0);
}

function loadingScreen () {
	context.fillStyle="#FFFFFF";
	context.fillRect(0, 0, canvas.width, canvas.height);
	context.fillStyle="#000000";
	context.font= "normal 30px Verdana";
	context.fillText("Cargando... " + Math.round(loaded_elements*100/(imgData.length+audioData.length)) + "%", 341, 231);
	context.fillStyle="#777777";
	context.beginPath();
	context.arc(609,271,15,0,2*Math.PI);
	context.closePath();
	context.fillRect(331, 256, 278, 30);
	context.fill();
	context.fillStyle="#3a85f6";
	context.beginPath();
	context.arc(331,271,15,0,2*Math.PI);
	context.arc(331+278*loaded_elements/(imgData.length+audioData.length),271,15,0,2*Math.PI);
	context.closePath();
	context.fill();
	context.fillRect(331, 256, 278*loaded_elements/(imgData.length+audioData.length), 30);
	if(loaded_elements==imgData.length+audioData.length){
		getImgSize();
		levelData.init();
		loaded = true;
		audioData[0].play();
		audioData[0].loop = true;
		current_time = perf.now();
		fade.in();
	}
}

function pauseScreen () {
	audioData[0].pause();
	audioData[audioData.length-3].play();
	context.save();
	context.globalAlpha = 0.5;
	context.fillStyle="#000000";
	context.fillRect(0, 0, canvas.width, canvas.height);
	context.restore();
	context.fillStyle="#FFFFFF";
	context.font= "normal 42px Verdana";
	context.fillText("PAUSA", 400, 275);
}

function key () {
	if(pressed_arrow == 'left') {
		player.x_speed = -running_speed;
		player.facing = 'left';

	} else if (pressed_arrow == 'right') {
		player.x_speed = running_speed;
		player.facing = 'right';
	}
	else if (pressed_arrow == 'none') {
		player.x_speed = 0;
	}
	if (pressed_jump&& player.state!='jumping') {
		player.jump();
		if(player.jump_speed>0)
			audioData[audioData.length-2].play();
	} 
	
}

function Camera (camera_alignment) {
	this.x_pos = 0;
	this.y_pos = 0;
	this.x_speed = 0;
	this.y_speed = 0;
	var vertical_ratio = 3/4;
	this.move = function () {
		alignment ();
		this.x_pos = player.width/2 - canvas.width/2 + player.x_pos;
		this.y_pos = player.height/2 - vertical_ratio*canvas.height + player.y_pos;
		if(this.x_pos + canvas.width > levelWidth) {
			this.x_speed = 0;
			this.x_pos = levelWidth - canvas.width;
		} else if (this.x_pos < 0) {
			this.x_pos = 0;
			this.x_speed = 0;
		} else
			this.x_speed = player.x_speed;
		if(this.y_pos + canvas.height > levelHeight) {
			this.y_pos = levelHeight - canvas.height;
			this.y_speed = 0;
		} else if (this.y_pos < 0) {
			this.y_pos = 0;
			this.y_speed = 0;
		} else
			this.y_speed = player.y_speed;
	}
	this.draw = function () {
		var displacementRatio;
		var x;
		var y;
		var width;
		var height;
		var obj;
		for(var i=0, l=levelData.length; i<l; i++) {
			displacementRatio = levelData[i][0][0];
			//levelData.draw(i, displacementRatio);
			for(var j=1, l1=levelData[i].length; j<l1; j++) {
				obj = levelData[i][j];
				if(obj.length == undefined){
					x = obj.x_pos;
					y = obj.y_pos;
					if(obj.width != undefined){
						width = obj.width;
						height = obj.height;
					}
					else{
						width = getWidth(obj.imageCode);
						height =  getHeight(obj.imageCode);
					}
					if(onScreen(x, y, width, height, displacementRatio))
					{
						obj.draw(displacementRatio);
					}
				}
				else if(obj.length == 3) {
					x = obj[1];
					y = obj[2];
					width = getWidth(obj[0]);
					height = getHeight(obj[0]);
					if(onScreen(x, y, width, height, displacementRatio))
					{
						drawOnCanvas(imgData[obj[0]], x - this.x_pos*displacementRatio, y - this.y_pos*displacementRatio);
					}
				}
			}
		}
	}
	var alignment = function () {
		if(camera_alignment==undefined)
			return;
		var new_alignment = 3/4;
		for(var i=0; i<camera_alignment.length; i++) {
			if(player.x_pos>camera_alignment[i][0])
				new_alignment = camera_alignment[i][1];
		}
		if(new_alignment != vertical_ratio) {
			var ratio_displacement = (vertical_ratio-new_alignment)/7;
			if(ratio_displacement>0.03)
				ratio_displacement = 0.03;
			else if (ratio_displacement<-0.03)
				ratio_displacement = -0.03;
			vertical_ratio -= ratio_displacement;
			if(Math.abs(vertical_ratio-new_alignment)<0.001)
				vertical_ratio = new_alignment;
		}
	}
}

function levelMusic () {
	var volume = audioData[0].volume;
	if(volume!=musicVolume/100){
		if(volume<musicVolume/100){
			volume+=0.03;
			if(volume>musicVolume/100)
				volume=musicVolume/100;
		}	
		else{
			volume-=0.03;
			if(volume<musicVolume/100)
				volume=musicVolume/100;
		}
		audioData[0].volume = volume;
	}
}

function Player (imageCode, animData, width, height, x_pos, y_pos) {
	this.x_pos = x_pos;
	this.y_pos = y_pos;
	this.imageCode = imageCode;
	this.image = imgData[imageCode];
	this.facing = 'right';
	this.state = 'jumping';
	this.width = width;
	this.height = height;
	this.jump_speed = 1000;
	this.x_speed = 0;
	this.y_speed = 0;
	this.animData = animData;
	this.anim_timer = 0.1;
	var gravity = 2100;
	var anim_x = 0;
	var anim_y = 0;
	var no_loops = 0;
	var time = 0;
	
	this.isColliding = function (x, y, width, height) {
		if(this.x_pos<x+width&&this.x_pos+this.width>x&&this.y_pos<y+height&&this.y_pos+this.height>y)
			return true;
		return false;
	}

	this.move = function () {
		this.y_speed -= gravity*dt;
		this.y_pos -= this.y_speed*dt;
		var x;
		var y;
		var imageCode;
		var width;
		var height;
		var obj;
		for(var i=levelData.length; i--;) {
			if(levelData[i][0][1]) {
				for(var j=levelData[i].length; j--;) {
					obj = levelData[i][j];
					if(obj.length == 3){
						x = obj[1];
						y = obj[2];
						imageCode = obj[0];
						height = getHeight(imageCode);
						width = getWidth(imageCode);
					} else {
						x = obj[0];
						y = obj[1];
						height = obj[3];
						width = obj[2];
					}
					if(this.isColliding(x, y, width, height))
					{
						if(this.y_pos+this.height-y < y+height-this.y_pos) {
							this.y_pos = y - this.height;
							this.y_speed = 0;
							if(this.state=="jumping")
								audioData[audioData.length-1].play();
						} else {
							this.y_pos = y + height;
							this.y_speed = -1;
						}
					}
				}
			}
		}

		this.x_pos += this.x_speed*dt;
		
		for(var i=levelData.length; i--;) {
			if(levelData[i][0][1]) {
				for(var j=levelData[i].length; j--;) {
					obj = levelData[i][j];
					if(obj.length == 3){
						x = obj[1];
						y = obj[2];
						imageCode = obj[0];
						height = getHeight(imageCode);
						width = getWidth(imageCode);
					} else {
						x = obj[0];
						y = obj[1];
						height = obj[3];
						width = obj[2];
					}
					if(this.isColliding(x, y, width, height))
					{
						this.x_speed = 0;
						if (x+width-this.x_pos < this.x_pos+this.width-x) {
							this.x_pos = x + width;
						} else {
							this.x_pos = x - this.width;
						}
					}
				}
			}
		}

		if(this.y_pos > levelHeight + this.height + 400) {
			var i = findClosestRespawn (this.x_pos);
			this.x_pos = respawn[i][0];
			this.y_pos = respawn[i][1];
		}
		this.animate();
	}

	this.jump = function () {
		this.y_speed = this.jump_speed;
	}

	this.draw = function () {
		context.drawImage (this.image, this.width*anim_x, this.height*anim_y, this.width, this.height, Math.round(this.x_pos - camera.x_pos), Math.round(this.y_pos - camera.y_pos), this.width, this.height);
	}

	var findClosestRespawn = function(x_pos) {
		for(var i=0; i<respawn.length; i++) {
			if(respawn[i][0] > x_pos) {
				if (respawn[i-1] != undefined) {
					if(respawn[i][0]-x_pos < x_pos-respawn[i-1][0]){
						return i;
					}
					return i-1;
				}
				return i;
			}
			if(i == respawn.length -1) {
				return i;
			}
		}
	}

	this.animate = function () {
		if(Math.abs(this.y_speed)>0) {
			if(this.state!='jumping') {
				this.state='jumping';
				anim_x = 0;
			} 
			if(this.y_speed>0){
				if(this.facing=='right')
					anim_y = 4;
				else
					anim_y = 6;
			} else {
				if(this.facing=='right')
					anim_y = 5;
				else
					anim_y = 7;
			}
				
		} else if(Math.abs(this.x_speed)>0) {
			if(this.state!='running') {
				this.state='running';
				anim_x = 0;
			}
			if(this.facing=='right')
				anim_y = 2;
			else
				anim_y = 3;
		} else {
			if(this.state!='idle') {
				this.state='idle';
				anim_x = 0;
				if(this.facing=='right')
					anim_y = 0;
				else
					anim_y = 1;
			}
		}
		time += dt;
		if(time >= this.anim_timer){
			anim_x++;
			time = 0;
		}
		if(anim_x > this.animData[anim_y]-1)
			anim_x = 0;
	}
	this.cutscene_animation = function  (imageCode, frames, loops) {
		if(this.state=='finished')
			return;
		else if(this.state!='cutscene') {
			no_loops=0;
			anim_x = 0;
			anim_y = 0;
			this.state='cutscene';
			on_cutscene = true;
			this.image = imgData[imageCode];
		}
		time += dt;
		if(time >= 0.33){
			anim_x++;
			time = 0;
		}
		if(anim_x > frames-1) {
			anim_x = 0;
			no_loops++;
		}
		if(loops==no_loops) {
			this.state='finished';
			this.image = imgData[this.imageCode];
			on_cutscene = false;
		}
	}
}

function Cutscene (coordinates, text) {
	var speed_x = 1200;
	var speed_y = 1200;
	this.finished = false;
	this.started = false;
	this.textBox;
	var i = 0;
	if(text!=undefined)
		this.textBox = new TextBox(text[i]);
	this.run = function () {
		if(!this.started) {
			on_cutscene = true;
			this.started = true;
			coordinates = coordinates.concat([[camera.x_pos, camera.y_pos]]);
			pressed_arrow = 'none';
			if(text!=undefined)
				this.textBox.finished = false;
			pressed_control = false;
		}
		if(text!=undefined)
				this.textBox.draw();
		var distance_x = Math.abs(coordinates[i][0]-camera.x_pos);
		var distance_y = Math.abs(coordinates[i][1]-camera.y_pos);
		if(distance_x<360)
			speed_x = distance_x*4;
		if(distance_y<360)
			speed_y = distance_y*4;
		if(distance_x<1)
			camera.x_pos = coordinates[i][0];
		else if(coordinates[i][0]>camera.x_pos)
			camera.x_pos += speed_x*dt;
		else
			camera.x_pos -= speed_x*dt;
		if(distance_y<1)
			camera.y_pos = coordinates[i][1];
		else if(coordinates[i][1]>camera.y_pos)
			camera.y_pos += speed_y*dt;
		else
			camera.y_pos -= speed_y*dt;
		if(camera.x_pos==coordinates[i][0]&&camera.y_pos==coordinates[i][1]) {
			if(i+1<coordinates.length) {
				if(pressed_control) {
					pressed_control = false;
					speed_x = 1200;
					speed_y = 1200;
					if(text!=undefined) {
						this.textBox.control();
						if(this.textBox.finished) {
							i++;
							if(i<coordinates.length-1&&text[i].length>0) {
								this.textBox = new textBox(text[i]);
								this.textBox.finished = false;
							}	
						}
					} 
					else {
						i++;
					}
				}
			}
			else {
				this.started = false;
				this.finished = true;
				on_cutscene = false;
			}
		}
	}
}

function TextBox (string) {
	var char_i = 0;
	var string_i = 0;
	var lines = 0;
	var charArr = string[string_i].split("");
	var x_pos = 30;
	var y_pos = 395;
	var height = 35;
	var stringArr = new Array ();
	stringArr[0] = "";
	var image_size = 0;
	this.finished = true;
	this.control = function () {
		string_i++;
		if(string_i<string.length) {
			char_i = 0;
			lines = 0;
			charArr = string[string_i].split("");
			stringArr = new Array ();
			stringArr[0] = "";
		} else {
			musicVolume = 100;
			this.finished = true;
			//lastPress=0;
		}
	}
	this.draw = function () {
		if(this.finished)
			return;
		musicVolume = 10;
		if(image_size == 0)
			audioData[audioData.length-4].play();
		if(image_size>1)
			image_size = 1;
		else if(image_size<1)
			image_size += 0.1;
		
		context.drawImage(imgData[imgData.length-1], 0, 390, imgData[imgData.length-1].width*image_size, imgData[imgData.length-1].height*image_size);
		
		if(char_i<charArr.length) {
			context.font= "normal 25px Verdana";
			context.fillStyle = "#000000";
			if(charArr[char_i]=="|"){
				char_i++;
				lines++;
				stringArr[lines] = "";
			} 
			stringArr[lines] += charArr[char_i];
			char_i++;
		}
		for(var j=0, k=stringArr.length; j<k; j++)
			context.fillText(stringArr[j], x_pos, y_pos+height*(j+1));
	}
	
}

function Ivan (x_pos, y_pos) {
	this.imageCode = imgData.length - 3;
	this.x_pos = x_pos;
	this.y_pos = y_pos;
	this.flutter_disp = 0;
	this.moving_to = false;
	var x_speed = 5;
	var y_speed = 0;
	var x_accel = 0;
	var y_accel = 0;
	var flutter_speed = 0;
	var flutter_gap =15;
	var width = imgData[this.imageCode].width;
	var height = imgData[this.imageCode].height;
	this.particles = Array();
	particle.prototype.getImage();
	for(var i=0; i<25; i++)
		this.particles[i] = new particle();
	
	this.move = function () {
		if(this.moving_to)
			return;
		if(this.x_pos+50+width<player.x_pos) {
			x_accel += 1500*dt;
			if(x_speed>500) {
				x_speed=500;
				x_accel=0;
			}
		}
		else if(this.x_pos>player.x_pos+player.width+50) {
			x_accel -= 1500*dt;
			if(x_speed<-500){
				x_speed=-500;
				x_accel=0;
			}
		}
		else {
			x_accel=0;
			x_speed=0;
		}
		if(this.y_pos+10+height<player.y_pos) {
			y_accel += 900*dt;
			if(y_speed>300)
				y_speed=300;
		}
		else if(this.y_pos>player.y_pos+20) {
			y_accel -= 900*dt;
			if(y_speed<-300)
				y_speed=-300;
		}
		else {
			y_accel=0;
			y_speed=0;
		}
		x_speed += x_accel*dt;
		this.x_pos += x_speed*dt;
		y_speed += y_accel*dt;
		this.y_pos += y_speed*dt;
	}
	this.move_to = function (dest_x, dest_y) {
		if(!this.moving_to)
			return;
		var speed = 600;
		if(Math.abs(dest_x-this.x_pos)<speed*dt)
			this.x_pos = dest_x;
		else if(dest_x>this.x_pos)
			this.x_pos += speed*dt;
		else
			this.x_pos -= speed*dt;
		if(Math.abs(dest_y-this.y_pos)<speed*dt)
			this.y_pos = dest_y;
		else if(dest_y>this.y_pos)
			this.y_pos += speed*dt;
		else
			this.y_pos -= speed*dt;
		if(dest_y==this.y_pos&&dest_x==this.x_pos){
			x_speed=0;
			y_speed=0;
			x_accel=0;
			y_accel=0;
		}
	}
	this.flutter = function () {
		//flutter
		if(paused)
			return;
		flutter_speed += (0.7+Math.abs(x_speed)/400)*dt;
		if(flutter_speed>2)
			flutter_speed-=2;
		if(Math.abs(x_speed)>0)
			flutter_gap++;
		else
			flutter_gap--;
		if(flutter_gap>40)
			flutter_gap=40;
		else if(flutter_gap<15)
			flutter_gap=15;
		this.flutter_disp = Math.sin(Math.PI*flutter_speed)*flutter_gap;
	}
	this.draw = function () {
		context.save();
		for(var i=0, j=this.particles.length; i<j; i++)
			this.particles[i].move(this.x_pos+width/2, this.y_pos+this.flutter_disp+height/2);
		context.restore ();
		this.flutter();
		drawOnCanvas(imgData[this.imageCode], this.x_pos - camera.x_pos, this.y_pos + this.flutter_disp - camera.y_pos);
	}
}
function particle () {
	this.x_accel = 0;
	this.y_accel = 0;
	this.y_speed = 0;
	this.x_speed = 0;
	this.alpha = 0;
	this.x_pos = 0;
	this.y_pos = 0;
}

particle.prototype = {
	getImage: function () {
		particle.prototype.image = getImage (imgData.length-2);
		particle.prototype.width = this.image.width;
		particle.prototype.height = this.image.height;
	},
	init: function (x, y) {
		var angle = Math.random()*2*Math.PI;
		var speed = Math.random()*50+70;
		this.x_pos = x;
		this.y_pos = y;
		this.alpha = 1;
		this.y_speed=0;
		this.x_speed=0;
		this.x_accel = speed*Math.cos(angle);
		this.y_accel = speed*Math.sin(angle);
	}, 
	move: function (x, y) {
		if(!onScreen(this.x_pos, this.y_pos, this.width, this.height))
			this.init(x-this.width/2,y-this.height/2);
		else if(Math.sqrt(Math.pow(this.x_speed, 2)+Math.pow(this.y_speed, 2))*dt>1.3)
			this.alpha -= 4*dt;
		if(this.alpha<=0)
			this.init(x-this.width/2,y-this.height/2);
		this.x_speed +=this.x_accel*dt;
		this.y_speed +=this.y_accel*dt;
		this.x_pos += this.x_speed*dt;
		this.y_pos += this.y_speed*dt;
		this.draw();
	},
	draw: function () {
		context.globalAlpha = this.alpha;
		drawOnCanvas(this.image, this.x_pos-camera.x_pos, this.y_pos-camera.y_pos);
	}
};

function Counter (x_pos, y_pos, imageCode) {
	this.counter = 0;
	this.x_pos = x_pos;
	this.y_pos = y_pos;
	this.imageCode = imageCode;
	this.canvas = document.createElement('canvas');
	this.canvas.width = getWidth(this.imageCode) + 200;
	this.canvas.height = getHeight(this.imageCode);
	this.context = this.canvas.getContext('2d');
	this.context.font= "normal 20px Verdana";
	this.context.fillStyle = "#FFFFFF";
	this.context.drawImage(imgData[this.imageCode], 0, 0);
	this.drawNumber();
}

Counter.prototype = {
	draw: function () {
		context.drawImage(this.canvas, this.x_pos, this.y_pos);
	},
	add: function () {
		this.counter+=1;
		this.drawNumber();
	},
	substract: function () {
		this.counter-=1;
		this.drawNumber();
	},
	drawNumber: function () {
		this.context.clearRect(getWidth(this.imageCode), 0, this.canvas.width - getWidth(this.imageCode), this.canvas.height);
		this.context.fillText("x " + this.counter, getWidth(this.imageCode) + 9, getHeight(this.imageCode)/2 + 7);
	}
};

function Fade () {
	this.state = 'idle';
	var opacity = 100;
	this.out = function() {
		if(opacity<100){
			this.state = 'fadeout';
			musicVolume = 50;
		}
		else
			this.state = 'idle';
	}
	this.in = function() {
		if(opacity>0)
			this.state = 'fadein';
		else
			this.state = 'idle';
			
	}
	this.draw = function () {
		if(this.state == 'idle'&&opacity!=100)
			return;
		if(this.state == 'fadeout')
			opacity += 200*dt;
		else if(this.state == 'fadein')
			opacity -= 200*dt;
		on_cutscene = true;
		
		if(opacity < 0){
			opacity = 0;
			on_cutscene = false;
			this.state = 'idle';
			musicVolume = 100;
		}
		else if(opacity > 100){
			opacity = 100;
			on_cutscene = false;
			this.state = 'idle';
		}
		var alpha = opacity/100;
		context.fillStyle="#FFFFFF";
		context.save();
		context.globalAlpha = alpha;
		context.fillRect(0, 0, canvas.width, canvas.height);
		context.restore();
	}
}

function rotate (image, degrees) {
	var width = image.width;
	offscreen_canvas.width = width;
	offscreen_canvas.height = width;
	offscreen_ctx.save();
	offscreen_ctx.translate(width/2, width/2);
	offscreen_ctx.rotate(degrees*Math.PI/180);
	offscreen_ctx.drawImage(image,-width/2,-width/2)
	offscreen_ctx.restore();
	return offscreen_canvas;
}
function Clouds (x_pos, y_pos, width, height) {
	imgData = imgData.concat("00.png", "01.png", "04.png");
	this.width = width;
	this.height = height;
	this.x_pos = 80;
	this.y_pos = y_pos;
	var x1 = 0;
	var x2 = 0;
	var x3 = 0;
	var i1;
	var i2;
	var i3;
	var w1;
	var w2;
	var w3;
	var speed = 80;
	this.init = function (){
		i1 = imgData[imgData.length-6];
		i2 = imgData[imgData.length-5];
		i3 = imgData[imgData.length-4];
		w1 = i1.width;
		w2 = i2.width;
		w3 = i3.width;
	}
	this.draw = function (displacementRatio) {
		if(i1==undefined)
			this.init();
		x1 -= (speed + camera.x_speed)*displacementRatio*dt;
		x2 -= (speed + camera.x_speed)*displacementRatio*.7*dt;
		x3 -= (speed + camera.x_speed)*displacementRatio*.5*dt;
		if(x1<0)
			x1 += w1;
		else if (x1 > w1)
			x1 -= w1;
		drawOnCanvas(i1, x1, y_pos);
		drawOnCanvas(i1, x1 - w1, y_pos);
		drawOnCanvas(i1, x1 + w1, y_pos);
		if(x2<0)
			x2 += w2;
		else if (x2 > w2)
			x2 -= w2;
		drawOnCanvas(i2, x2, y_pos);
		drawOnCanvas(i2, x2 - w2, y_pos);
		drawOnCanvas(i2, x2 + w2, y_pos);
		if(x3<0)
			x3 += w3;
		else if (x1 > w3)
			x3 -= w3;
		drawOnCanvas(i3, x3, y_pos);
		drawOnCanvas(i3, x3 - w3, y_pos);
		drawOnCanvas(i3, x3 + w3, y_pos);
	}
}
function Wave (imageCode, x_pos, y_pos, width, height, alpha) {
	this.x_pos = x_pos;
	this.y_pos = y_pos;
	this.x_coord = 0;
	this.width = width;
	this.height = height;
	this.alpha = (alpha == undefined) ? 1 : alpha;
	this.imageCode = imageCode;
	this.x_disp=0;
	this.y_disp=0;
	this.x_speed=0;
	this.y_speed=0;
}
Wave.prototype = {
	draw: function (displacementRatio) {
		this.x_disp = Math.sin(this.x_speed*Math.PI)*displacementRatio*100;
		this.y_disp = Math.sin(this.y_speed*Math.PI)*displacementRatio*10;
		this.x_speed += displacementRatio*0.3*dt;
		this.y_speed += displacementRatio*1.3*dt;
		if(this.x_speed>2)
			this.x_speed-=2;
		if(this.y_speed>2)
			this.y_speed-=2;
		this.x_coord -= (camera.x_speed*displacementRatio + this.x_disp)*dt;
		if(this.x_coord < -getWidth(this.imageCode))
			this.x_coord += getWidth(this.imageCode);
		else if (this.x_coord > getWidth(this.imageCode))
			this.x_coord -= getWidth(this.imageCode);
		if(this.alpha!=1) {
			context.save();
			context.globalAlpha = this.alpha;
		}
		drawOnCanvas(imgData[this.imageCode], this.x_coord, this.y_pos + this.y_disp - camera.y_pos);
		drawOnCanvas(imgData[this.imageCode], this.x_coord + getWidth(this.imageCode), this.y_pos + this.y_disp - camera.y_pos);
		drawOnCanvas(imgData[this.imageCode], this.x_coord - getWidth(this.imageCode), this.y_pos + this.y_disp - camera.y_pos);
		if(this.alpha!=1) {
			context.restore();
		}
	}
};
function NPC (imageCode, x_pos, y_pos, dialog) {
	this.imageCode = imageCode;
	this.x_pos = x_pos;
	this.y_pos = y_pos;
	this.dialog = dialog;
	this.started = false;
}
NPC.prototype = {
	draw: function (){
		drawOnCanvas(imgData[this.imageCode], this.x_pos-camera.x_pos, this.y_pos-camera.y_pos);
		if(player.isColliding(this.x_pos, this.y_pos, getWidth(this.imageCode), getHeight(this.imageCode))&&pressed_control&&!on_cutscene){
			cutscene = new Cutscene([[this.x_pos-480+getWidth(this.imageCode)/2, this.y_pos-290+getHeight(this.imageCode)/2]], [this.dialog]);
			this.started = true;
		}
	}
};
function endScreen () {
	this.message;
	this.canvas = document.createElement('canvas');
	this.canvas.width = 960;
	this.canvas.height = 540;
	this.context = this.canvas.getContext('2d');
	this.context.font= "normal 30px Verdana";
	this.context.fillStyle = "#000000";
	var initialized = false;
	var alpha = 0;
	this.init = function (nombre, message) {
		fade.out();
		this.message = (message == undefined) ? "" : message;
		var string = ["¡Haz completado el nivel de " + nombre + "!"];
		string = string.concat(this.message);
		string = string.concat(["Muchas gracias por jugar, si deseas visitar otro", "pueblo presiona el botón retroceder de tu navegador."]);
		for (var i=0; i < string.length; i++) {
			this.context.fillText(string[i], 100, 200 + 35*i);
		}
		initialized = true;
	}
	this.draw = function () {
		if(!initialized){
			return;
		} else if(fade.state == 'idle'){
			console.log(alpha);
			context.save();
			context.globalAlpha = alpha;
			context.drawImage(this.canvas, 0, 0);
			context.restore();
			alpha += .5*dt;
			if(alpha>1)
				alpha = 1;
		}
	}
}
function loadImages () {
	imgData = imgData.concat('ivan.png', 'ivan_particle.png', 'textbox.png');
	for(var i = 0; i < imgData.length; i++) {
		var image = new Image ();
		image.onload = function() {
			loaded_elements++;
		};
		image.src = imgData[i];
		imgData[i] = image;
	}
}
function getImgSize() {
	imgSize = new Array(imgData.length*2);
	for(var i=0; i<imgData.length; i++){
		imgSize[i*2] = imgData[i].width;
		imgSize[i*2+1] = imgData[i].height;
	}
}
function loadAudio () {
	audioData = audioData.concat('text', 'pause', 'jump', 'fall');
	var support = document.createElement('audio');
	var extension;
	if(support.canPlayType('audio/ogg; codecs="vorbis"')=='probably')
		extension = ".ogg";
	else
		extension = ".mp3";
	for(var i=0; i<audioData.length; i++){
		var audio = new Audio();
		audio.oncanplaythrough = loaded_elements++;
		audio.src = audioData[i].concat(extension);
		audioData[i] = audio;
	}
}

function backupLevel (level) {
	backup = [levelWidth, levelHeight, levelData, respawn, player, ivan, camera];
	level();
	levelData.init();
	fade.in();
	//loaded = false;
	//loaded_elements = audioData.length;
}

function restoreLevel () {
	levelWidth = backup[0];
	levelHeight = backup[1];
	levelData = backup[2];
	respawn = backup[3];
	player = backup[4];
	ivan = backup[5];
	camera = backup[6];
	backup = undefined;
}

function drawOnCanvas (image, x, y) {
	context.drawImage(image, Math.floor(x), Math.floor(y));
}

function getImage (imageCode){
	return imgData[imageCode];
}

function getWidth (imageCode){
	return imgSize[imageCode*2];
}

function getHeight (imageCode){
	return imgSize[imageCode*2+1];
}

function onScreen (x, y, width, height, displacementRatio) {
	if(displacementRatio==undefined)
		displacementRatio = 1;
	return (x+width>=camera.x_pos*displacementRatio && x<=canvas.width+camera.x_pos*displacementRatio
		&&y+height>=camera.y_pos*displacementRatio && y<=camera.y_pos*displacementRatio+canvas.height);
}

function insertTiles (imageCode, x, y, horTiles, verTiles, horSpace, verSpace) {
	var tempData = new Array (horTiles*verTiles);
	var i=0;
	var image = imgData[imageCode];
	var width = image.width + horSpace;
	var height = image.height + verSpace;
	for(var j=0; j<verTiles; j++) {
		for(var k=0; k<horTiles; k++) {
			tempData[i] = new Array (3);
			tempData[i][0] = imageCode;
			tempData[i][1] = x + width*k;
			tempData[i][2] = y;
			i++;
		}
		y+= height;
	}
	return tempData;
}

document.addEventListener('keydown',function(evt){
	//lastPress=evt.keyCode;
	if(evt.keyCode==37){
		pressed_arrow = 'left';
	}else if(evt.keyCode==39){
		pressed_arrow = 'right';
	}else if(evt.keyCode==32){
		pressed_jump = true;
	}else if(evt.keyCode==16){
		pressed_control = true;
	}
},false);

document.addEventListener('keyup',function(evt){
	if(evt.keyCode==37||evt.keyCode==39){
		pressed_arrow = 'none';
	}else if(evt.keyCode==32) {
		pressed_jump = false;
	}else if (evt.keyCode == 13&&!on_cutscene){
		paused = !paused;
		if(paused)
			pauseScreen();
		else
			audioData[0].play();
	}else if(evt.keyCode==16){
		pressed_control = false;
	}

/*if(evt.keyCode==32) {
	lastPress = 0;
} else if(evt.keyCode==16) {
	lastPress = 1;
}
else if (evt.keyCode == 13&&!on_cutscene)
{
	paused = !paused;
	lastPress = 0;
}*/
//else
	//lastPress=null;
},false);