enchant();

canvas_width = 1600;
canvas_height = 900;
canvas_half_width = canvas_width / 2;
canvas_half_height = canvas_height / 2;

tile_size = 32;

player_height = 64;
player_width = 46;
player_walk_rate = 5;
player_move_speed = 20;
player = null;
gravity = 1;
jump_delta = -13;
tiles = [];
tileImage = 0;
cur_level = 0;
camera_x = 0;
player_image = "MainCharacter.png";
player_frames = 3;
player_ground = 0;
currentLevel = null;


energy = 0.01;
stress = 0.01;

points = 0;

function jump_apex_time() { return -jump_delta / gravity; }
function max_jump_height() { return jump_delta * jump_apex_time() + gravity * jump_apex_time() * jump_apex_time() / 2.0; }
function jump_apex_displacement() { return jump_apex_time() * player_move_speed; }
level_width = 500;
max_jump_length_tiles = 7;
easy_jump_height_delta = 80;
max_platform_width = 30;
min_platform_width = 6;
max_enemy_per_tile = 1.0 / 4.0;
max_gap_width = Math.floor((canvas_width / tile_size) / 3.0);
min_gap_width = 4;

dialog = false; //if dialog is displayed or not
non_selected_color = "#7D440B";
selected_color = "#0BD251"

background = null;
meadow_index = 1;

arrows = [];
attack_period = 20;

sword_rotate_acceleration = 0.6;
sword_sweep_angle = 150;
clouds = [];

is_raining = false;
is_snowing = false;
rain_slant = 3;
rain_timer = 0;
rain_period = 3;

cloud_bias = 1;

lives_left = 2;

farmerTimer = null;
veggies = [];

Tile = Class.create(Sprite, {
	initialize: function() {
		Sprite.call(this, tile_size, tile_size);
		tiles.push(this);
		this.x = 0;
		this.y = 0;
		this.global_x = 0;
	},

	onenterframe: function() {
		this.x = this.global_x - player.global_x + canvas_half_width;
	},

	collidedWithPlayer: function() {

	}
});

Ground = Class.create(Tile, {
	initialize: function() {
		Tile.call(this);
		this.image = game.assets['Platorms.png'];
		this.frame = tileImage;
	}
});

WrapLabel = Class.create(Group, {
	initialize: function(x, y, width, height, size, align, offset, text) {
		Group.call(this);
		var texts = text.split("\n");
		this.labels = [];
		this.lines = texts.length;
		y += offset * this.lines;
		for(var i = 0; i < texts.length; i++) {
			var label = new Label(texts[i]);
			this.addChild(label);
			label.font = size+"px PixelFont";
			label.x = x;
			label.y = y + height*i;
			label.width = width;
			label.textAlign = align;
			this.labels.push(label);
		}
		
		game.currentScene.addChild(this);
	},
	remove: function() {
		game.currentScene.removeChild(this);
	},
	setColor: function(color) {
		for(var i = 0; i < this.labels.length; i++) {
			this.labels[i].color = color;
		}
	}
});

FallBlock = Class.create(Ground, {
	initialize: function() {
		Ground.call(this);
		this.dy = 0;
		this.gravity = 0;
		this.collision_timer = 20;
		this.countdown = false;
	},
	collidedWithPlayer: function() {
		this.countdown = true;
	},
	onenterframe: function() {
		if (this.countdown && --this.collision_timer <= 0) {
			this.gravity = gravity;
			this.countdown = false;
		}
		Tile.prototype.onenterframe.call(this);
		this.dy += this.gravity;
		this.y += this.dy;
		if (this.y > canvas_height) {
			game.currentScene.removeChild(this);
			tiles.splice(tiles.indexOf(this), 1);
		}
	}
});

Player = Class.create(Sprite, {
	initialize: function() {
		Sprite.call(this, player_width, player_height);
		this.global_x = 50;
		this.x = canvas_half_width;
		this.y = 0;
		this.dy = 0;
		this.frameCount = player_walk_rate;
		this.image = game.assets[player_image];
		this.collision = [];
		this.dialog = false;
		this.resting = false;
		this.arrowStart = false;
		this.arrow = null;
		this.attackTimer = 0;
		this.flipped = false;
		this.shootArrowWhenTimerDone = false;
    	this.attackType = "Sword";
	},

	onenterframe: function() {
		if(dialog) {
			return;
		}

		if (this.resting && game.input["space"]) {
			this.dy += jump_delta;
			game.assets["Jump.wav"].play();
		}

		if(farmerTimer) {
			this.global_x += player_move_speed;
			if(game.input["d"]) {
				this.global_x += player_move_speed/2;
			}
			if(game.input["a"]) {
				this.global_x -= player_move_speed/2;
			}

		} else {

			if (game.input["a"]) {
				this.global_x -= player_move_speed;
				if (!this.flipped) {
					this.flipped = true;
					this.frame += player_frames;
				}
			}
			if (game.input["d"]) {
				this.global_x += player_move_speed;
				if (this.flipped) {
					this.flipped = false;
					this.frame -= player_frames;
				}
			}
		}
		if (--this.frameCount <= 0) {
			this.frameCount = player_walk_rate;
			this.frame = (this.frame + 1) % player_frames + (this.flipped ? player_frames : 0);
		}

		

		this.x = canvas_half_width;
		this.dy += gravity / 2.0;
		this.y += this.dy;
		this.dy += gravity / 2.0;

		if (this.y > canvas_height) {
			this.ondie();
		}

		this.resting = false;
		if(player_ground && this.y >= player_ground) {
			this.y = player_ground;
			this.resting = true;
			this.dy = 0;
		}
		else {
			for (var i = 0; i < tiles.length; i++) {
				if (this.intersect(tiles[i])) {
          if (this.y + player_height - this.dy < tiles[i].y) {
					  this.y = tiles[i].y - player_height;
					  this.dy = 0;
					  this.resting = true;
					  tiles[i].collidedWithPlayer();
				  	break;
          }
          else {
            if (this.global_x < tiles[i].global_x) {
              this.global_x -= player_move_speed;
            }
            else {
              this.global_x += player_move_speed;
            }
            this.dx = 0;
          }
				}
			}
		}
    this.processAttack();
	},

  processAttack: function() {
    switch(this.attackType) {
    case "Sword":
      this.processSword();
      break;
    case "Bow":
      this.processArchery();
      break;
    }
  },

  processSword: function() {
    if (--this.attackTimer < 0 && keyPressed.shift) {
      this.sword = new Sword();
      this.attackTimer = attack_period;
    }
  },

  processArchery: function() {
		if(this.attackTimer > 0) {
			this.attackTimer--;
			if(keyPressed.shift) {
				this.shootArrowWhenTimerDone = true;
			}
		}
		if(this.attackTimer <= 0 && (keyPressed.shift || this.shootArrowWhenTimerDone)) {
			this.arrow = new Arrow(this.global_x + 16, this.y + 16);
			this.shootArrowWhenTimerDone = false;
		}
		if(this.arrow) {
			this.arrow.global_x = this.global_x + (player_width - tile_size) / 2;
			if (tile_size > player_height) {
				this.arrow.y = this.y + (player_height / 2 - tile_size);
			} else {
				this.arrow.y = this.y + (player_height - tile_size) / 2;
			}
			if(keyReleased.shift) {
				this.arrow.start();
				this.arrow = null;
				this.attackTimer = attack_period;
			}
		}
  },

	ondie: function() {
		if (dialog) {
			return;
		}
		game.assets["Die.wav"].play();
		if (lives_left > 0) {
			new Dialog("You have died", ["You have " + lives_left + " lives left"], function() {
				lives_left -= 1;
				player.y = 0;
				currentLevel();
			});
		}
		else {
			new Dialog("Game Over", ["Restart"], function() {
				player.y = 0;
				lives_left = 3;
				points = 0;
				SetupOverworld();
			});
		}
	}
});



FarmerTimer = Class.create(Group, {
	initialize: function(image) {
		Group.call(this);
		this.timer = new Label("Time: 30");
		this.timer.font = "50px PixelFont";
		this.timer.x = canvas_half_width - 200;
		this.timer.y = 50;
		this.timerValue = 30;
		this.timerTimer = 30;
		this.addChild(this.timer);
		this.numVeggies = 0;
		this.numVeggiesCollected = 0;
		this.collectedLabel = new Label("");
		this.collectedLabel.font = "50px PixelFont";
		this.collectedLabel.x = canvas_width - 300;
		this.collectedLabel.width = 500;
		this.collectedLabel.y = 50;
		this.sprite = new Sprite(76,68);
		this.sprite.image = game.assets[image];
		this.sprite.x = canvas_width - 375;
		this.sprite.y = 55;
		this.addChild(this.sprite);
		this.addChild(this.collectedLabel);
		game.currentScene.addChild(this);
	},
	onenterframe: function() {
		if(!dialog && this.timerValue > 0 && --this.timerTimer <= 0) {
			this.timerTimer = 30;
			this.decreaseTime(1);
		}
	},
	setVeggies: function(value) {
		this.numVeggiesCollected = value;
		this.collectedLabel.text = "" + (this.numVeggies - value);
		if(this.numVeggiesCollected >= this.numVeggies) {
			new Dialog("You collected the vegetables!", ["ok"], function() {
				gameWin();
				SetupOverworld();
			});
		}
	},
	removeVeggie: function() {
		this.setVeggies(this.numVeggiesCollected+1);
	},
	addVeggie: function() {
		this.setVeggies(this.numVeggiesCollected-1);
	},
	decreaseTime: function(amount) {
		this.timer.text = "Time: " + (this.timerValue-=amount);
		if(this.timerValue <= 0 && !dialog) {
			new Dialog("You have died", ["You have " + lives_left + " lives left"], function() {
				lives_left -= 1;
				player.y = 0;
				currentLevel();
			});
		}
	}
});


function resetPlayerDefaults() {
	player_height = 64;
	player_width = 46;
	player_walk_rate = 5;
	player_move_speed = 20;
	gravity = 1;
	jump_delta = -13;
	player_image = "MainCharacter.png";
	player_frames = 3;
	player_ground = 0;
}

function rainProc() {
	if (--rain_timer <= 0 && is_raining) {
		new Rain();
		rain_tier = rain_period;
	}
	if (--rain_timer <= 0 && is_snowing) {
		var r = new Rain();
    r.image = game.assets["Snow.png"];
		rain_tier = rain_period;
	}
}

function clearLevel() {
  player = null;
  tileImage = 0;
  if(background) {
  	background.removeEffect(background.currentBackground);
  }
  farmerTimer = null;
  background = null;
	dialog = false;
	tiles = [];
	arrows = [];
	game.replaceScene(new Scene());
  game.currentScene.addEventListener('enterframe', rainProc);
}

function SetupMainMenu() {
	new MainMenu();
}

MainMenu = Class.create(Sprite,{
	initialize: function() {
		Sprite.call(this,canvas_width,canvas_height);
		this.image = game.assets["TitleScreen.png"];
		game.currentScene.addChild(this);
	},
	onenterframe: function() {
		if(keyPressed.e) {
			SetupOverworld();
			new Dialog("Controls:\nWASD: Move\nSpace: Jump\nE: Talk\nShift: Attack",["ok"])
		}
	}
});

function SetupOverworld() {
	currentLevel = SetupOverworld;
	clearLevel();

	energy = 0.01;
	stress = 0.01;

	background = new Background(0,
		[["OverWorld_0.png"],
		["OverWorld_1_Background.png","OverWorld_1_Foreground.png"],
		["OverWorld_2.png"],
		["OverWorld_3.png"]], 
		[[1],[1,1],[1],[1]],0,0);

	resetPlayerDefaults();
	player = new Player();
	player_ground = 725;
	player_move_speed = 10;

  if (points > 3) {
  var dragon = new NPC('dragon.png', 64, 64, player.global_x, 675, 0, 50, 1000, false, function() { 
    new Dialog("Dragon\nGreetings, you have triumphed over many trials.\n I will help you save your sister.\n", ["Thank You!"], function() {
      new Dialog("Dragon\nWhat do you want to do?", ["Credits", "Replay"], function(index) {
        if (index == 0) {
          var credits = new Sprite(0, 0);
          credits.image = game.assets['Credits.png'];
          credits.width = canvas_width;
          credits.height = canvas_height;
          credits.x = 0;
          credits.y = 0;
          game.currentScene.addChild(credits);
        }
        else {
          points = 0;
          SetupOverworld();
        }
      });
    });
  });
  dragon.scaleX = 5;
  dragon.scaleY = 5;
  game.currentScene.addChild(dragon);
  }

	var wizard = new NPC('wizahd.png', 58, 88, 7000, 675, 0, 50, 1000, false, function() {

		new Dialog("Wizard\nHello adventurer. I am Andor the Angry. I'm\nnot fond of strangers entering my town.\nYou'd best be off on your journey. On\nsecond thought I could use a new pet...",
			["Don't croak Old Man",
			"You're in my way, be gone with you",
			"Great to meet you, Andor. I will prove myself\nloyal to this city.",
			"What?"],
			function(index) {
			    if(index == 0) {
			        return ["Wizard\nI'm not going to be the one who croaks",["ok"],function(){
			        	resetPlayerDefaults()
                player.attackType = "none";
			        	stress = 0.25;
			        	energy = 0.75;
		    				player_move_speed = 30;
    						gravity = 0.7;
				    		jump_delta = -13;
				    		player_height = 64;
				    		player_width = 64;
				        meadow_index = 1;
                		player_image = "frogspite.png";
			        	SetupWizardLevel();
			        	
			        }];
			    } else if(index == 1) {
			        return ["Wizard\nHow about BEE gone with you.",["ok"],function(){
			        	resetPlayerDefaults()
                player.attackType = "none";
			        	stress = 0.75;
			        	energy = 0.5;
			    			player_move_speed = 10;
				    		gravity = 0.1;
					    	jump_delta = -5;
						    player_height = 51;
						    player_width = 58;
						    player_walk_rate = 2;
						    player_image = "bee.png";
						    player_frames = 2;
				        meadow_index = 2;
			        	SetupWizardLevel();			        	
			        }];
			    } else if(index == 2) {
			        return ["Wizard\nYou'll prove your loyalty to me",["ok"],function(){
			        	resetPlayerDefaults()
                player.attackType = "none";
			        	stress = 0.5;
			        	energy = 0.9;
    						player_move_speed = 20;
		    				gravity = 0.9;
				    		jump_delta = -13;
					    	player_height = 39;
					    	player_width = 64;
					    	player_image = "dogspritesheet.png";
				        meadow_index = 3;
			        	SetupWizardLevel();
			        }];
			//turns the player into a dog
			    } else if(index == 3) {
			        return ["Wizard\nFeeling sheepish are we?",["ok"],function(){
			        	resetPlayerDefaults()
                player.attackType = "none";
			        	stress = 0.25;
                energy = 0.25;
						    player_move_speed = 15;
						    gravity = 1.5;
						    jump_delta = -13;
						    player_height = 64;
						    player_width = 64;
                player_image = "sheepspritesheet.png";
				        meadow_index = 4;
			        	SetupWizardLevel();
			        }];
			//turns the player into a sheep

			    }
		});
	});

	game.currentScene.addChild(wizard);

	game.currentScene.addChild(new NPC('archergirl.png',58,64,1000, 675, 0, 50, 1000, false, function() {

		new Dialog("Ranger\nHello adventurer. I am Sygalla the Sad. Can\nyou help me? I was injured while tracking a\nwild beast. I need to hunt in order to feed my\nbreathren or they will starve. Take my bow\nand you'll see through the eyes of a ranger. ",
			["I can't bear to hear the news.",
			"It would be terrible if something happened to\nyour family. If something happened to my child,\nI could never say bye son.",
			"You poor dear.",
			"If that happened to me, I would be pulling my\nhair out."],
			function(answer){
          currentLevel = function() {
            player_ground = 0;
	          var index = background.currentBackground + background.effectOffset;
            clearLevel();
            stress = 0.6;
            energy = 0.8;
            tileImage = 3;
	          background = new Background(0,
          	  [["Forest_"+index+"_Midground.png", "Forest_"+index+"_Foreground.png"]],
          	  [[0.3,                       0.6                       ]],
          	  index,
          	  2
        	  );
            var boss_height = GenerateLevel(true, function(x, y, startX, endX, speed) {
  				    var enemy = new Enemy(x, y, startX, endX, speed);
              if (Math.random() > 0.5) {
                enemy.image = game.assets["wolfSS2.png"];
                enemy.width = 218 / 4;
                enemy.height = 41;
              }
              else {
                enemy.image = game.assets["BIRDYss2.png"];
                enemy.width = 40;
                enemy.height = 17;
              }
              enemy.frames = 2;
            }, null);
            player.attackType = "Bow";
            spawnPortal((level_width + 80) * tile_size, boss_height - 50);
            var boss = RangerBossSection(boss_height);
            switch (answer) {
            case 0:
              boss.image = game.assets["bearSS2.png"];
              boss.height = 42;
              boss.width = 48;
              game.assets["Bear.wav"].play();
              break;
            case 1:
              boss.image = game.assets["bisonSS2.png"];
              boss.height = 44;
              boss.width = 56;
              game.assets["Bison.wav"].play();
              break;
            case 2:
              boss.image = game.assets["deerSS2.png"];
              boss.height = 64;
              boss.width = 50;
              game.assets["Dear.wav"].play();
              break;
            case 3:
              boss.image = game.assets["BunnySS.png"];
              boss.height = 48;
              boss.width = 262 / 4;
              game.assets["Rabbit.wav"].play();
              break;
            }
          };
          currentLevel();
        }
      )
	}));

	game.currentScene.addChild(new NPC('knight.png',54,76, 5000, 675, 0, 50, 1000, false, function() {
		new Dialog("Knight\nHello adventurer. I am Balor the brave. I'm\nlooking for a young squire to assist me while I\ngo off to fight a far away dragon. There are\nmany dangers that need to be eridicated to\nprotect this village. If you take my sword you\nwill have the bravey of a knight",
			["I have a bone to pick already.",
			"Don't troll me with a bogus quest.",
			"You guys sure gobble up these fantasy ideas.",
			"This could be a sticky situation."],
			function(index){
          currentLevel = function() {
            stress = 0.6;
            energy = 0.8;
            player_ground = 0;
	          var index = background.currentBackground + background.effectOffset;
            clearLevel();
            tileImage = 2;
	          background = new Background(0,
          	  [["Ruins_" + index + "_Background.png", "Ruins_"+index+"_Midground.png", "Ruins_"+index+"_Foreground.png"]],
          	  [[0.1, 0.3,                       0.6                       ]],
          	  index,
          	  2
        	  );
            var boss_height = GenerateLevel(true, function(x, y, startX, endX, speed) {
  				    var enemy = new Enemy(x, y, startX, endX, speed);
              switch (index) {
              case 0:
                enemy.image = game.assets["skeleSS.png"];
                enemy.height = 69 / 2;
                enemy.width = 23;
                break;
              case 1:
                enemy.image = game.assets["trollss.png"];
                enemy.height = 88 / 2;
                enemy.width = 95 / 3;
                break;
              case 2:
                enemy.image = game.assets["Goblin.png"];
                enemy.height = 64;
                enemy.width = 192 / 3;
                break;
              case 3:
                enemy.image = game.assets["Ooze.png"];
                enemy.height = 77;
                enemy.width = 197 / 3;
                break;
              }
              enemy.frames = 3;
            }, null);
            player.attackType = "Sword";
            spawnPortal(level_width * tile_size, boss_height - 50);
          };
          currentLevel();
			},false,50);
	}));

	game.currentScene.addChild(new NPC('farmer.png',60,68, 3000, 675, 0, 50, 1000, false, function() {
		new Dialog("Farmer\nHello adventurer. I am Haphlin the Happy. My\ngarden is full of vegetables that need to be\nharvested before the winter comes. And winter\nis coming. Take my gloves and you'll see which\nvegetables are ready to be picked.",
			["Let us solve this problem.",
			"I can help you out. I feel good from my head\nto my toes.",
			"It was good fortune I was able to turn up\nhere in time.",
			"I can't believe you have so many vegetables in\nthis area, there isn't much room."],
			function(index){
			    if(index == 0) {
			//turns the hunted sprite in the level into a bear
					SetupFarmerLevel("lettuce.png");
			    } else if(index == 1) {
			//turns the hunted sprite in the level into a bison
					SetupFarmerLevel("tomato.png");
			    } else if(index == 2) {
			//turns the hunted sprite in the level into a deer
					SetupFarmerLevel("turnip.png");
			    } else if(index == 3) {
			//turns the hunted sprite in the level into a rabbit
					SetupFarmerLevel("Mushroom.png");
			    }
			});
	}));

	for(var i = 0; i < 2; i++) {

		game.currentScene.addChild(new NPC('peasant.png',64,64,150+ Math.random()*650, 500, Math.random()*5, 50, 1000, true, function() {
			new Dialog("Hello adventurer, how's the weather today?",
			["Bright and sunny.",
			"The weather won't affect my journey.",
			"Snowing.",
			"Dark and stormy."],
			function(index) {
			    background.changeBackground(index);
			}, true);
		}));

		game.currentScene.addChild(new NPC('peasantblondorange.png',64,64,150+ Math.random()*650, 500, Math.random()*5, 50, 1000, true, function() {
			new Dialog("There are many animals just outside\nAnellu Moore, which one is your favorite?",
			["Monkey.",
			"Lion." ,
			"Panda.",
			"Bull."],
			function(index) {
			    background.changeBackground(index);
			}, true);
		}));

		game.currentScene.addChild(new NPC('peasantblondpink.png',64,64,150+ Math.random()*650, 500, Math.random()*5, 50, 1000, true, function() {
			new Dialog("Be careful as there are many dangerous\nfolk in Anellu Moore." ,
			["Sounds exciting",
			"I'm not afraid.",
			"This place is depressing.",
			"I hate everyone here."],
			function(index) {
			    background.changeBackground(index);
			}, true);
		}));

		game.currentScene.addChild(new NPC('peasantbrownblue.png',64,64,150+ Math.random()*650, 500, Math.random()*5, 50, 1000, true, function() {
			new Dialog("Good day to you traveler.",
			["Good day to you!",
			"I must save my sister!",
			"What makes it a good day?",
			"Go away."],
			function(index) {
			    background.changeBackground(index);
			}, true);
		}));

		game.currentScene.addChild(new NPC('peasantbrownpink.png',64,64,150+ Math.random()*650, 500, Math.random()*5, 50, 1000, true, function() {
			new Dialog("Where did you come from before getting\nto Anellu Moore?",
			["A beautiful village.",
			"A town of fearless adventurers.",
			"A dingy, dirty, little town.",
			"None of your business."],
			function(index) {
			    background.changeBackground(index);
			}, true);
		}));

		game.currentScene.addChild(new NPC('peasantbrownyellow.png',64,64,150+ Math.random()*650, 500, Math.random()*5, 50, 1000, true, function() {
			new Dialog("How goes your journey?",
			["Great!",
			"Treacherous, but I can handle it.",
			"I don't think I can make it.",
			"Stop bothering me."],
			function(index) {
			    background.changeBackground(index);
			}, true);
		}));

		game.currentScene.addChild(new NPC('peasantredblue.png',64,64,150+ Math.random()*650, 500, Math.random()*5, 50, 1000, true, function() {
			new Dialog("What do you think of Anellu Moore?",
			["It's beautiful.",
			"It's full of brave folk.",
			"It's cold and unfriendly.",
			"I want to burn it down."],
			function(index) {
			    background.changeBackground(index);
			}, true);
		}));

		game.currentScene.addChild(new NPC('peasantredorange.png',64,64,150+ Math.random()*650, 500, Math.random()*5, 50, 1000, true, function() {
			new Dialog("What do you think of the market place?",
			["What a fun place!",
			"The people are noble, but I don't have time\nto shop.",
			"I don't like anything here.",
			"I want to burn it down."],
			function(index) {
			    background.changeBackground(index);
			}, true);
		}));

		game.currentScene.addChild(new NPC('peasantredpink.png',64,64,150+ Math.random()*650, 500, Math.random()*5, 50, 1000, true, function() {
			new Dialog("Where are you headed?",
			["To wherever the road takes me.",
			"To save my sister!",
			"Anywhere that's our of this miserable place.",
			"Off to burn your house down."],
			function(index) {
			    background.changeBackground(index);
			}, true);
		}));

		game.currentScene.addChild(new NPC('peasantredyellow.png',64,64,150 + Math.random()*650, 500, Math.random()*5, 50, 1000, true, function() {
			new Dialog("What will you do after your finish\nyour quest?",
			["Find more adventures!",
			"I just have to get to the end.",
			"To find a corner to cry in whilst eating\nchocolate.",
			"To find your house, so I can burn it down."],
			function(index) {
			    background.changeBackground(index);
			}, true);
		}));
	}

	game.currentScene.addChild(player);
}

function RangerBossSection(height) {
  //floor
  for (var i = 0; i < 50; i++) {
    var ground = new Ground();
    ground.global_x = (i + level_width) * tile_size;
    ground.y = height;
    game.currentScene.addChild(ground);
  }

  return new RangerBoss(level_width * tile_size, height - 60, (level_width + 5) * tile_size, (level_width + 45) * tile_size);
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

function maxJumpHeight(dx) {
	if (dx < 0) {
		alert("Levels cannot go backwards at this time");
	}
	if (dx <= jump_apex_displacement()) {
		return max_jump_height() + player_height;
	}
	post_apex_time = (dx - jump_apex_displacement()) / player_move_speed;
	return max_jump_height() + gravity * post_apex_time * post_apex_time / 2.0 + player_height;
}

function GenerateLevel(crumbleEnabled, randomObjectCallback, numEnemiesPerTile) {
  if (aud) {
  	aud.adaptpattern(energy,stress);
  }

	player = new Player();
	game.currentScene.addChild(player);

	var curHeight = canvas_height / 2;
	var runLength = 10;
	var gapWidth = -1;
	var crumbling = false;
	for (var x = 0; x < level_width; x++) {
		if (--runLength > 0) {
			var ground = !crumbling ? new Ground() : new FallBlock();
			ground.global_x = x * tile_size;
			ground.y = curHeight;
			game.currentScene.addChild(ground);
		}
		else if (--gapWidth > 0) {
			continue;
		}
		else {
			crumbling = crumbleEnabled && (Math.random() < energy);
			runLength = min_platform_width + Math.floor(max_platform_width * (1.0 - (energy * (1.0 - Math.random()))));
			heightDeltaMagnitude = Math.abs(max_jump_height() * (energy + 4 * (1 - Math.pow(Math.random(), 4))) / 5);
			var startingHeight = curHeight;
			if (heightDeltaMagnitude + curHeight > canvas_height - tile_size) {
				curHeight -= heightDeltaMagnitude;
			}
			else if (curHeight - heightDeltaMagnitude < canvas_half_height) {
				curHeight += heightDeltaMagnitude;
			}
			else if (Math.random() > 0.5) {
				curHeight -= heightDeltaMagnitude;
			}
			else {
				curHeight += heightDeltaMagnitude;
			}

			for (gapWidth = 1; maxJumpHeight(gapWidth * tile_size) + startingHeight < curHeight; gapWidth++);
			gapWidth -= 2 * (player_width / tile_size);
      if (gapWidth > min_gap_width) {
  			gapWidth = Math.max(min_gap_width, Math.min(max_gap_width, Math.floor(gapWidth * (energy + 3 * Math.random()) / 4)));
      }

	  var enemyCount = numEnemiesPerTile ? numEnemiesPerTile : Math.floor(max_enemy_per_tile * runLength * stress * Math.random());
      if (enemyCount > 0) {
        crumbling = false;
      }
			for (var i = 0; i < enemyCount; i++) {
				if(randomObjectCallback) {
					randomObjectCallback(x * tile_size + runLength * tile_size * Math.random(), curHeight - tile_size, x * tile_size, (x + runLength) * tile_size, Math.random() * 8);
				} else {
					new Enemy(x * tile_size + runLength * tile_size * Math.random(), curHeight - tile_size, x * tile_size, (x + runLength) * tile_size, Math.random() * 8);
				}
			}
		}
	}
  return curHeight;
}

function spawnPortal(x, y) {
  new Portal(x, y);
}

function SetupWizardLevel() {
	player_ground = 0;
	tileImage = 0;
	currentLevel = SetupWizardLevel;
	var index = background.currentBackground + background.effectOffset;
	clearLevel();
	  background = new Background(0,
	    [["Pond_"+index+"_Background.png", "Pond_"+index+"_Midground.png", "Pond_"+index+"_Foreground.png"]],
	    [[0.1,                        0.3,                       0.6                       ]],
	    index,
	    0
	  );

	var end_height = GenerateLevel();
  player.attackType = "None";
  spawnPortal(level_width * tile_size, end_height - 50);
}


function SetupFarmerLevel(image) {
	resetPlayerDefaults();

	player_ground = 0;
	currentLevel = function() {
		SetupFarmerLevel(image);
	}
	var index = background.currentBackground + background.effectOffset;

	clearLevel();

	tileImage = 1;

	  background = new Background(0,
	    [["Meadow_"+index+"_Background.png", "Meadow_"+index+"_Midground.png", "Meadow_"+index+"_Foreground.png"]],
	    [[0.1,                        0.3,                       0.6                       ]],
	    index,
	    2
	  );

	veggies = [];

	farmerTimer = new FarmerTimer(image);
	var count = 0;

	var end_height = GenerateLevel(false, function(x,y) {
		var dummy = Math.random()<0.2;
		var veg = new Veggie(x,y-36,dummy,farmerTimer,image);
		if(!dummy) {
			count++;
		}
		game.currentScene.addChild(veg);
		veggies.push(veg);
	},2);
  spawnPortal(level_width * tile_size, end_height - 50);

	player.attackType = "None";

	farmerTimer.numVeggies = Math.floor(count/2);
	farmerTimer.setVeggies(0);

	
}


Veggie = Class.create(Sprite,
{
	initialize: function(x, y, dummy, farmerTimer, image) {
		Sprite.call(this, 76,68); //initialize the sprite object
		this.image = game.assets[dummy?'carrot.png':image];
		this.global_x = x;
		this.x = this.global_x - player.global_x + canvas_half_width;
		this.y = y;
		this.dummy = dummy;
		this.farmerTimer = farmerTimer;
	},
	onenterframe: function() {
		this.x = this.global_x - player.global_x + canvas_half_width;
		if(player.intersect(this)) {
			game.rootScene.removeChild(this);
			removeList(this,veggies);
			if(!this.dummy) {
				this.farmerTimer.removeVeggie();
				game.assets["Farm_Good.wav"].play();
			} else {
				this.farmerTimer.addVeggie();
				//this.farmerTimer.decreaseTime(3);
				game.assets["Farm_Error.wav"].play();
			}
		}
	}
});



Dialog = Class.create(Sprite, // extend the sprite class
{
	initialize: function(text, buttons, callback, randomize, offset) { //initialization
		Sprite.call(this, 1068, 600); //initialize the sprite object
		this.image = game.assets['Textbox_2.png'];
		this.x = 266;
		this.y = 150;
		game.currentScene.addChild(this);
		this.selectedArrow = new Sprite(32,32);
		this.selectedArrow.image = game.assets["Arrow.png"];
		
		game.currentScene.addChild(this.selectedArrow);
		this.buttons = [];
		this.offset = (offset===undefined)?0:offset;
		this.loadData(text,buttons,callback,randomize);
		dialog = true;

		game.assets["Talk.wav"].play();
	},

	onenterframe: function(event) {
		if(keyPressed.s && this.selectedIndex < this.buttons.length - 1) {
			this.buttons[this.selectedIndex].setColor(non_selected_color);
			this.buttons[++this.selectedIndex].setColor(selected_color);
			this.selectedArrow.y = this.buttons[this.selectedIndex].labels[0].y;
		}

		if(keyPressed.w && this.selectedIndex > 0) {
			this.buttons[this.selectedIndex].setColor(non_selected_color);
			this.buttons[--this.selectedIndex].setColor(selected_color);
			this.selectedArrow.y = this.buttons[this.selectedIndex].labels[0].y;
		}

		if(keyPressed.e) {
			keyPressed.e = false; //prevent this keypress from being used later in the frame to initiate more dialog
			var results;
			if(this.callback && (results = this.callback(this.indexMap[this.selectedIndex]))) {
				this.loadData(results[0],results[1],results[2],results[3]);
			} else {
				for(var i = 0; i < this.buttons.length; i++) {
					this.buttons[i].remove();
				}
				this.message.remove();
				game.currentScene.removeChild(this);
				game.currentScene.removeChild(this.selectedArrow);
				dialog = false;
			}
		}
	},

	loadData: function(text, buttons, callback, randomize) {
		if(this.message) {
			this.message.remove();
		}
		this.message = new WrapLabel(336,395 + this.offset,933,40,30,"center",-32,text);
		this.message.setColor(non_selected_color);
		this.selectedArrow.x = 394;
		this.selectedArrow.y = 450;
		this.callback = callback;
		for(var i = 0; i < this.buttons.length; i++) {
			this.buttons[i].remove();			
		}
		this.indexMap = [];
		for(var i = 0; i < buttons.length; i++) {
			this.indexMap.push(i);
		}
		if(randomize) {
			shuffle(this.indexMap);
		}
		this.buttons = [];
		var height = 0;
		for(var i = 0; i < buttons.length; i++)
		{
			this.buttons[i] = new WrapLabel(440,450+height + this.offset,734,24,24,"left",0,buttons[this.indexMap[i]]);
			this.buttons[i].setColor(non_selected_color);
			height += 35 + (this.buttons[i].lines - 1)*25;
		}
		this.selectedIndex = 0;
		this.buttons[0].setColor(selected_color);
	}
});

Sword = Class.create(Sprite,
{
  initialize: function() {
    Sprite.call(this, 23, 49);
    this.image = game.assets['sword.png'];
    this.originX = 12;
    this.originY = 40;
    this.rotation = 0;
    this.facing = player.flipped;
    this.x = player.x + 30 * (this.facing ? 0 : 1);
    this.y = player.y + 5;
    this.rotation_swept = 0;
    this.rotation_speed = 10;
    this.intersect_rect = {
      width: 40,
      height: player_height,
      x: player.x + (this.facing ? -40 : 30),
      y: player.y
    };
    game.currentScene.addChild(this);
    game.assets["Swing_Sword.wav"].play();
  },

  onenterframe: function() {
    this.rotation_speed += sword_rotate_acceleration;
    this.rotate((this.rotation_speed * (this.facing ? -1 : 1) + 360) % 360);
    this.rotation_swept += this.rotation_speed;
    this.y = player.y + 5;
    this.intersect_rect.y = player.y;
    if (this.rotation_swept > sword_sweep_angle) {
      game.currentScene.removeChild(this);
      player.sword = null;
    }
  }
});

Arrow = Class.create(Sprite, // extend the sprite class
{
	initialize: function(x,y, angle) { //initialization
		Sprite.call(this, 32, 32); //initialize the sprite object
		this.image = game.assets['Arrow.png'];
		this.global_x = x;
		this.x = this.global_x - player.global_x + canvas_half_width;
		this.y = y;
		this.timer = 100;
		this.angleCounter = 0;
		this.started = false;
		this.dx = 1;
		this.dy = 0;
		addList(this,arrows);
		this.arrowMarkers = [];
		for(var i = 0; i < 20; i++) {
			addList(new ArrowMarker(),this.arrowMarkers);
		}
		this.updateArrowMarkers();
	},
	onenterframe: function() {
		if(this.started) {
			this.global_x += this.dx;
			this.y += this.dy;
			this.dy += gravity;
			this.x = this.global_x - player.global_x + canvas_half_width;
			if(--this.timer <= 0 || collideList(this,tiles)) {
				removeList(this,arrows);
			}
		}
		else {
			this.updateArrowMarkers();
		}
		this.rotation = 180*Math.atan2(this.dy,this.dx)/3.14;
	},
	start: function() {
		for(var i = 0; i < 20; i++) {
			game.currentScene.removeChild(this.arrowMarkers[i]);
		}
		this.arrowMarkers = [];
		this.started = true;
		game.assets["Arrow_Launch.wav"].play();

	},
	updateArrowMarkers: function() {
		if(this.angleCounter < 30)
			this.angleCounter += (30-this.angleCounter)/15.0;
		this.dy = -(100 - this.angleCounter/5)/3*Math.sin(this.angleCounter/50.0);
		this.dx = (100 - this.angleCounter/5)/3*Math.cos(this.angleCounter/50.0);
		if(player.flipped) {
			this.dx = -this.dx;
		}
		for(var i = 0; i < 20; i++) {
			this.arrowMarkers[i].x = this.x + i*this.dx + 13;
			this.arrowMarkers[i].y = this.y + i*this.dy + i*i/2.0*(gravity) + 13;
		}
	}
});

ArrowMarker = Class.create(Sprite, // extend the sprite class
{
	initialize: function() { //initialization
		Sprite.call(this, 5, 5); //initialize the sprite object
		this.image = game.assets['dot.png'];
	},
	onenterframe: function() {
	}
});


NPCImages = ["peasant.png",
		"peasantblondorange.png",
		"peasantblondpink.png",
		"peasantbrownpink.png",
		"peasantbrownyellow.png",
		"peasantredblue.png",
		"peasantredorange.png",
		"peasantredpink.png",
		"peasantredyellow.png",
		"peasantbrownblue.png",
		"boypeasantbrowngreen.png",
		"boypeasantblackblue.png",
		"boypeasantblondblue.png",
		"boypeasantbrownblue.png",
		"boypeasantbrownred.png"];

NPC = Class.create(Sprite, // extend the sprite class
{
	initialize: function(image,sizex,sizey,x,y,speed,startX,endX,hasFrames,callback) { //initialization
		if(hasFrames) {
			var index = Math.floor(Math.random()*NPCImages.length);
			Sprite.call(this, index > 9 ? 65 : 64, index > 9 ? 77 : 64); //initialize the sprite object
			this.image = game.assets[NPCImages[index]];
		} else {
			Sprite.call(this, sizex, sizey); //initialize the sprite object
			this.image = game.assets[image];
		}
		this.global_x = x;
		this.x = this.global_x - player.global_x + canvas_half_width;
		this.y = y;
		this.callback = callback;
		this.speed = speed;
		this.selected = false;
		this.direction = 1;
		this.startX = startX;
		this.endX = endX;
		this.hasFrames = hasFrames;
		this.frameCount = 5;
		//temp - to give random values to the animated npcs
		if(hasFrames) {

			this.global_x = Math.random() * 10000;
			this.startX = this.global_x - Math.random()*500;
			this.endX = this.global_x + Math.random()*500;
			this.speed = player_move_speed + Math.random() * 3;
			this.y = 725;
		}
	},
	onenterframe: function() {
		this.x = this.global_x - player.global_x + canvas_half_width;
		if(!dialog) {
			this.selected = false;
		}
		if(this.selected) {
			return;
		}
		if(this.hasFrames && --this.frameCount <= 0) {
			this.frame = (this.frame + 1) % 3 + ((this.direction == -1) ? 3 : 0);
			this.frameCount = 5;
		}
		this.global_x += this.direction * this.speed;
		if(this.global_x > this.endX) {
			this.direction = -1;
		}
		if(this.global_x < this.startX) {
			this.direction = 1;
		}
		if(keyPressed.e) {
			if(!dialog && this.intersect(player)) {
				this.callback();
				//if our callback set up dialog, set ourselves to selected so we
				//stop moving.
				if(dialog) {
					this.selected = true;
				}
				//this may not happen if our callback does something other
				//than dialog.
			}
		}
		//and reset selected whenever dialog stops
		
	}
});

Background = Class.create(Group,
{
	initialize: function(startIndex,backgrounds,parallax,effectOffset,cloudsInsertPosition) {
		Group.call(this);
		this.backgrounds = [];
		for(var i = 0; i < backgrounds.length; i++) {
			this.backgrounds.push([]);
			for(var j = 0; j < backgrounds[i].length; j++) {
				var sprite = new Sprite(3200,900);
				this.backgrounds[i].push(sprite);
				sprite.image = game.assets[backgrounds[i][j]];
				sprite.visible = false;
				this.addChild(sprite);

				if(i + effectOffset == 1 && j == cloudsInsertPosition) {
					for(var k = 0; k < 5; k++) {
						var cloud = new Cloud();
						cloud.visible = false;
						this.backgrounds[i].push(cloud);
						this.addChild(cloud);
						parallax[i].splice(cloudsInsertPosition+1,0,0);
					}
				}
			}
			//add in clouds if we're at the clouds index (which is 1, or 0 if they set effectOffset)

			
		}
		this.effectOffset = effectOffset;
		//this uses indices to calculate the effect (rain, etc)
		//but in case they only pass in one background,
		//just allow them to set an offset which we will
		//calculate the effect from
		this.currentBackground = startIndex;
		this.targetBackground = startIndex;
		this.startTransitionTimer = 10;
		this.parallax = parallax;
		this.clouds = [];
		this.addEffect(startIndex);
		game.currentScene.addChild(this);
	},
	onenterframe: function() {
		this.updateBackgroundPosition(this.currentBackground);

		if(this.targetBackground != this.currentBackground && --this.startTransitionTimer <= 0) {
			this.updateBackgroundPosition(this.targetBackground);
			for(var i = 0; i < this.backgrounds[this.targetBackground].length; i++) {
				this.backgrounds[this.targetBackground][i].opacity += 0.05;
			}
			if(this.backgrounds[this.targetBackground][0].opacity >= 1) {
				for(var i = 0; i < this.backgrounds[this.targetBackground].length; i++) {
					this.backgrounds[this.targetBackground][i].opacity = 1;
				}
				for(var i = 0; i < this.backgrounds[this.currentBackground].length; i++) {
					this.backgrounds[this.currentBackground][i].visible = false;
				}
				this.currentBackground = this.targetBackground;
			}
			
			
		}
	},
	updateBackgroundPosition: function(index) {
		var background = this.backgrounds[index];
		for(var i = 0; i < background.length; i++) {
			background[i].visible = true;
			var multiplier = this.parallax[index][i];
			if(multiplier) {
				background[i].x = -player.global_x * multiplier % canvas_width;
				if(background[i].x > 0) {
					background[i].x -= canvas_width;
				}
			}
		}
	},
	changeBackground: function(index) {
		if(this.currentBackground == index) {
			return;
		}
		this.removeEffect(this.currentBackground);
		this.targetBackground = index;
		this.addEffect(this.targetBackground);
		for(var i = 0; i < this.backgrounds[this.currentBackground].length; i++) {
			this.removeChild(this.backgrounds[this.currentBackground][i]);
			this.insertBefore(this.backgrounds[this.currentBackground][i],this.backgrounds[this.targetBackground][0]);
			
		}
		for(var i = 0; i < this.backgrounds[this.targetBackground].length; i++) {
			this.backgrounds[this.targetBackground][i].opacity = 0;
			this.backgrounds[this.targetBackground][i].visible = true;
		}
		

		this.startTransitionTimer = 5;
	},
	removeEffect: function(index) {
		index += this.effectOffset;
		if(index == 1) {
			/*for(var i = 0; i < this.clouds.length; i++) {
				game.currentScene.removeChild(this.clouds[i]);
			}*/
		} else if(index == 3) {
			is_raining = false;
		} else if(index == 2) {
			is_snowing = false;
		}
	},
	addEffect: function(index) {
		index += this.effectOffset;
		if(index == 1) {
			stress = 0.5;
			energy = 0.75;
      if (aud) {
  			aud.adaptpattern(energy,stress);	
      }
		} else if(index == 3) {
			is_raining = true;
			stress = 0.8;
			energy = 0.8;
      if (aud) {
  			aud.adaptpattern(energy,stress);	
      }
		} else if(index == 2) {
			is_snowing = true;
			stress = 0.6;
			energy = 0.2;
      if (aud) {
  			aud.adaptpattern(energy,stress);	
      }
		} else if(index == 0) {
			stress = 0.2;
			energy = 0.7;
      if (aud) {
  			aud.adaptpattern(energy,stress);	
      }
		}
	}
});

Cloud = Class.create(Sprite,
{
	initialize: function() {
		Sprite.call(this, 230, 150);
		this.image = game.assets["Clouds_230x150.png"];
		this.frame = Math.floor(Math.random() * 4.99);
		this.x = canvas_width * Math.random();
		this.y = (canvas_half_height - 150) * Math.random();
		this.dx = 0;
		this.dy = 0;
		this.direction_timer = 0;
		//game.currentScene.addChild(this);
	},

	onenterframe: function() {
		if (--this.direction_timer <= 0) {
			this.dx = Math.random() * cloud_bias;
			this.dy = (Math.random() - 0.5) * 0.8;
			this.direction_timer = 1000;
		}
		this.x += this.dx;
		this.y += this.dy;
		if (this.x - 230 > canvas_width) {
			this.x = -230;
			this.y = (canvas_half_height - 150) * Math.random();
		}
		if (this.y < 0) {
			this.dy = Math.abs(this.dy);
		}
		if (this.y + 150 > canvas_half_height) {
			this.dy = -Math.abs(this.dy);
		}
	},
});

Rain = Class.create(Sprite,
{
	initialize: function() {
		Sprite.call(this, 64, 64);
		this.image = game.assets["Rain_6.png"];
		this.x = canvas_width * Math.random();
		this.y = -30;
		this.dx = rain_slant * Math.random() * 2;
		this.dy = 25;
		game.currentScene.addChild(this);
	},

	onenterframe: function() {
		this.x += this.dx;
		this.dy += gravity;
		this.y += this.dy;
		if (this.y > canvas_height) {
			game.currentScene.removeChild(this);
		}
	},
});

Portal = Class.create(Sprite,
{
  initialize: function(x, y) {
    Sprite.call(this, 288, 192);
    this.image = game.assets['Portal.png'];
    this.global_x = x;
    this.y = y;
    game.currentScene.addChild(this);
  },

  onenterframe: function() {
    if (this.intersect(player)) {
      gameWin();
      
      SetupOverworld();
    }

    this.x = this.global_x - player.global_x;
  }
});


function gameWin() {
	++points;
}

Enemy = Class.create(Sprite,
{
	initialize: function(x, y, startX, endX, speed) {
		Sprite.call(this, 32, 32); //initialize the sprite object
		this.image = game.assets['wolfSS2.png'];
    this.width = 218 / 4;
    this.height = 41;
    this.frames = 2;
		this.global_x = x;
		this.x = this.global_x - player.global_x + canvas_half_width;
		this.y = y;
		this.startX = startX;
		this.endX = endX;
		this.direction = 1;
		this.health = 2;
		this.speed = speed;
    this.frames = 0;
    this.frame_timer = 0;
    this.flipped = false;
		game.currentScene.addChild(this);
	},
	onenterframe: function() {
		this.global_x += this.direction * this.speed;
		if(this.global_x > this.endX) {
			this.direction = -1;
      this.flipped = true;
      this.frame += this.frames;
		}
		if(this.global_x < this.startX) {
			this.direction = 1;
      this.flipped = false;
      this.frame -= this.frames;
		}
    if (--this.frame_timer <= 0) {
      this.frame_timer = player_walk_rate;
      this.frame = (this.frame + 1) % this.frames + (this.flipped ? this.frames : 0);
    }
		this.x = this.global_x - player.global_x + canvas_half_width;
		var arrow;
		if(arrow = collideList(this,arrows)) {
			removeList(arrow,arrows);
			if(--this.health <= 0) {
				game.currentScene.removeChild(this);
			}
		}
    if (player.sword != null) {
      var s = player.sword.intersect_rect;
      if (this.x < s.x + s.width && s.x < this.x + this.width && this.y < s.y + s.height && s.y < this.y + this.height) {
        game.currentScene.removeChild(this);
      }
    }
		if(player.intersect(this)) {
			player.ondie();
		}
	}
});

RangerBoss = Class.create(Enemy, {
  initialize: function(x, y, startX, endX) {
    Enemy.call(this, x, y, startX, endX, 6);
    this.health = 6;
    this.frames = 2;
    this.width = 50;
    this.height = 64;
    this.scaleX = 2;
    this.scaleY = 2;
  },
});

function collideList(obj,list) {
	for (var item in list) {
		if (obj.intersect(list[item])) {
			return list[item];
		}
	}
	return null;
}

function removeList(obj,list) {
	list.splice(list.indexOf(obj),1);
	game.currentScene.removeChild(obj);
}

function addList(obj,list) {
	list.push(obj);
	game.currentScene.addChild(obj);
}

function keyBindings() {
	game.keybind(65, 'a');
	game.keybind(68, 'd');
	game.keybind(87, 'w');
	game.keybind(83, 's');
	game.keybind(32, 'space');
	game.keybind(69, 'e');
	game.keybind(16, 'shift');
	keyReleased = {space: true, a: true, d: true, w: true, s: true, e: true, shift: true};
	keyPressed = {space: false, a: false, d: false, w: false, s: false, e: false, shift: false};
	game.addEventListener('enterframe', function() {
		for(var key in keyPressed) {
			if(game.input[key]) {
				keyPressed[key] = keyReleased[key];
				keyReleased[key] = false;
			} else {
				keyReleased[key] = true;
				keyPressed[key] = false;
			}
		}
	});
}

window.onload = function() {
	game = new Game(canvas_width, canvas_height);
	game.preload(
		'Platorms.png',
		'dialog.png',
		'MainCharacter.png',
		'dot.png',
		'lettuce.png',
		'tomato.png',
		'turnip.png',
		'Mushroom.png',
		'carrot.png',
		"Arrow_Launch.wav",
		"Bear.wav",
		"Bison.wav",
		"Dear.wav",
		"Die.wav",
		"Farm_Error.wav",
		"Farm_Good.wav",
		"Jump.wav",
		"Rabbit.wav",
		"Skeleton.wav",
		"Swing_Sword.wav",
		"Talk.wav",
		"Meadow_1_Background.png",
		"Meadow_1_Midground.png",
		"Meadow_1_Foreground.png",
		"Meadow_2_Background.png",
		"Meadow_2_Midground.png",
		"Meadow_2_Foreground.png",
		"Meadow_3_Background.png",
		"Meadow_3_Midground.png",
		"Meadow_3_Foreground.png",
		"Meadow_0_Background.png",
		"Meadow_0_Midground.png",
		"Meadow_0_Foreground.png",
		"Pond_1_Background.png",
		"Pond_1_Midground.png",
		"Pond_1_Foreground.png",
		"Pond_2_Background.png",
		"Pond_2_Midground.png",
		"Pond_2_Foreground.png",
		"Pond_3_Background.png",
		"Pond_3_Midground.png",
		"Pond_3_Foreground.png",
		"Pond_0_Background.png",
		"Pond_0_Midground.png",
		"Pond_0_Foreground.png",
		"Textbox.png",
		"Textbox_2.png",
		"Rain_6.png",
		"wizahd.png",
		"frogspite.png",
		"sheepspritesheet.png",
		"dogspritesheet.png",
		"Clouds_230x150.png",
		"peasant.png",
		"peasantblondorange.png",
		"peasantblondpink.png",
		"peasantbrownpink.png",
		"peasantbrownyellow.png",
		"peasantredblue.png",
		"peasantredorange.png",
		"peasantredpink.png",
		"peasantredyellow.png",
		"peasantbrownblue.png",
		"bee.png",
   		 "sword.png",
		"OverWorld_1_Foreground.png",
		"OverWorld_1_Background.png",
		"OverWorld_0.png",
		"OverWorld_2.png",
		"OverWorld_3.png",
		"Arrow.png",
		"Snow.png",
		"boypeasantbrowngreen.png",
		"archergirl.png",
		"farmer.png",
    "bearSS2.png",
    "bisonSS2.png",
    "deerSS2.png",
    "BunnySS.png",
		"knight.png",
		"boypeasantblackblue.png",
		"boypeasantblondblue.png",
		"boypeasantbrownblue.png",
    "wolfSS2.png",
    "BIRDYss2.png",
    "Forest_0_Foreground.png",
    "Forest_1_Foreground.png",
    "Forest_2_Foreground.png",
    "Forest_3_Foreground.png",
    "Forest_0_Midground.png",
    "Forest_1_Midground.png",
    "Forest_2_Midground.png",
    "Forest_3_Midground.png",
    "Portal.png",
    "skeleSS.png",
    "trollss.png",
    "Goblin.png",
    "Ooze.png",
    "Ruins_0_Foreground.png",
    "Ruins_1_Foreground.png",
    "Ruins_2_Foreground.png",
    "Ruins_3_Foreground.png",
    "Ruins_0_Midground.png",
    "Ruins_1_Midground.png",
    "Ruins_2_Midground.png",
    "Ruins_3_Midground.png",
    "Ruins_0_Background.png",
    "Ruins_1_Background.png",
    "Ruins_2_Background.png",
    "Ruins_3_Background.png",
		"boypeasantbrownred.png",
		"TitleScreen.png",
    "dragon.png",
    "Credits.png",
		"boypeasantbrownred.png"
	);
	game.fps = 30;
	keyBindings();

	game.onload = function() {
		game.pushScene(new Scene());
		clearLevel();
		SetupMainMenu();
	};

	game.start();
	if (aud) {
  	aud.generatepattern(energy, stress, 20, 20, Math.floor(Math.random() * 10000));
	  aud.playstop();
  }
}
