
var multipliers = 
[
	3.0,
	2.0,
	1.5,
	1.25,
	1.0,
	0.5,

];

var play_grade_sfx_flag = true;

var vfx_textures = [];
vfx_textures[STAT_TYPE_ENUM.WEAPON] = new Image();
vfx_textures[STAT_TYPE_ENUM.WEAPON].src = "img/vfx/weapon.png";
vfx_textures[STAT_TYPE_ENUM.MAGIC] = new Image();
vfx_textures[STAT_TYPE_ENUM.MAGIC].src = "img/vfx/magic.png";
vfx_textures[STAT_TYPE_ENUM.FAITH] = new Image();
vfx_textures[STAT_TYPE_ENUM.FAITH].src = "img/vfx/faith.png";
vfx_textures[STAT_TYPE_ENUM.SNEAK] = new Image();
vfx_textures[STAT_TYPE_ENUM.SNEAK].src = "img/vfx/sneak.png";
vfx_textures[STAT_TYPE_ENUM.HEAL] = new Image();
vfx_textures[STAT_TYPE_ENUM.HEAL].src = "img/vfx/heal.png";
vfx_textures[STAT_TYPE_ENUM.ARMOR] = new Image();
vfx_textures[STAT_TYPE_ENUM.ARMOR].src = "img/vfx/shield.png";
vfx_textures[STAT_TYPE_ENUM.BUFF] = new Image();
vfx_textures[STAT_TYPE_ENUM.BUFF].src = "img/vfx/buff.png";

VFX_INSTANCE = function (type, sz, x, y) {
    var self = {};

    self.type = type;
    self.size = sz;
    self.x = x;
    self.y = y;
    self.frame = random_int(-4, 1);

    return self;
}

var vfx_instances = [];
var vfx_timer = 0.0;

var current_selection = -1;

var enemy_field = [];
var dying_enemy_list = [];

var room_counter = 0;
//var max_rooms = 0;

var adventurer_field = [];
var item_field = [];

var level_timer = 0.0;

var arrow_texture = new Image();
arrow_texture.src = "img/ui/arrow.png";
var red_arrow_texture = new Image();
red_arrow_texture.src = "img/ui/arrow_red.png";


var tut_image_texture = new Image();
tut_image_texture.src = "img/ui/tut_image.png";
var tut_text_texture = new Image();
tut_text_texture.src = "img/ui/tut_text.png";


var frame_texture = new Image();
frame_texture.src = "img/ui/frame.png";

var quit_button = new Image();
quit_button.src = "img/ui/quit_button.png";

var burst_texture = new Image();
burst_texture.src = "img/ui/burst.png";

var speed_buttons = [];
speed_buttons[0] = new Image();
speed_buttons[0].src = "img/ui/speed1.png";
speed_buttons[1] = new Image();
speed_buttons[1].src = "img/ui/speed2.png";
speed_buttons[2] = new Image();
speed_buttons[2].src = "img/ui/speed3.png";

var speed_scalar = 1;

var tutorial_mode = false;
var tutorial_timer = 0.0;
var tutorial_lock_dismissal_timer = 0.0;

DAMAGE_NUMBER = function(x, y, size, value, style)
{
  var self = {};
  self.x = x;
  self.y = y;
  self.size = size;
  self.value = value;
  self.timer = random_float(1.0, 1.5);
  self.max_timer = self.timer;
  self.style = style;

  return self;
}

var damage_numbers = [];
var level_complete = false;
var win_state_timer = 0.0;

function new_room()
{
	enemy_field = []; //clear
	//enemy_field[0] = create_enemy(ENEMY_ENUM.BOULDER);//Object.assign({}, __enemy_list[ENEMY_ENUM.BOULDER]);
	//enemy_field[1] = create_enemy(ENEMY_ENUM.BOULDER);//Object.assign({}, __enemy_list[ENEMY_ENUM.BOULDER]);
	//enemy_field[2] = create_enemy(ENEMY_ENUM.BOULDER);//Object.assign({}, __enemy_list[ENEMY_ENUM.BOULDER]);

//*
	//var count = random_int(1, 9);
	//console.log( current_level + " " + room_counter);
	//console.log( __floor_list[current_level].rooms[room_counter].monsters);

	//var i = 0;

	var scaling_value = Math.floor(1.0 / 3.0 * current_level);
	
	console.log("scaling    values" + scaling_value);

//var enemy_position_index = [3, 0, 4, 1, 6, 2, 7, 5, 8];
	tutorial_lock_dismissal_timer = 0.0;

	if (!__level_completed[current_level]) {
	    if (__floor_list[current_level].rooms[room_counter].messages.length > 0)
	        tutorial_mode = true;
	}

	for(var i in __floor_list[current_level].rooms[room_counter].monsters)//while(i < count)
	{
		var index = __floor_list[current_level].rooms[room_counter].monsters[i];//random_int(0, ENEMY_ENUM.NUM_ENEMY);
		var en = create_enemy(index);

		if(!en)
			continue;

		enemy_field[i] = en;
		//debugger;
		//for(var j in enemy_field[enemy_position_index[i]])
		{
			for(var k in enemy_field[i].defenses)
				enemy_field[i].defenses[k] += scaling_value;
				
			for(var k in enemy_field[i].max_defenses)
				enemy_field[i].max_defenses[k] += scaling_value;

				for(var k in enemy_field[i].defenses_display)
					enemy_field[i].defenses_display[k] += scaling_value;

			for(var k in enemy_field[i].attacks)
				enemy_field[i].attacks[k].strength += scaling_value;
		}//i += 1;
	}
	//*/
}

var current_level = 0;
var previous_level = -1;

var auto_ko = true; //automatically ko the first time, for tutorial reasons

var room_difficulty_level = 0;

function init_dungeon_gamestate()
{
    //in the future we may need something more robust than this
    if (current_level % 6 == 4)
        switch_bgm(SONG_ENUM.BGM_BOSS);
    else if (current_level % 6 == 5)
        switch_bgm(SONG_ENUM.BGM_BONUS);
    else
		switch_bgm(SONG_ENUM.BGM_MAIN);

	previous_level = current_level;

	speed_scalar = 1.0;
	/*
	xml.open('GET', 'data/floor_1.xml', false);
	xml.send();
	var xml_data = xml.responseXML;
	if(!xml_data)
	{

	}*/
	win_state_timer = 0.0;
	level_complete = false;
  room_counter = 0;
  level_timer = 0.0;

  new_room();
  //max_rooms = random_int(3, 6);

  
for(var i in adventurer_field)
{
	adventurer_field[i].current_stats[STAT_TYPE_ENUM.ATTACK_TIMER] = 0.0;
	adventurer_field[i].shield = 0;
	adventurer_field[i].buff_value = 0;

	adventurer_field[i].level_start_weight = adventurer_field[i].current_stats[STAT_TYPE_ENUM.WEIGHT];

	for(var j in adventurer_field[i].current_stats)
	{
		if(j == STAT_TYPE_ENUM.ATTACK_TIMER)
		  continue;
		if(j == STAT_TYPE_ENUM.FULLNESS)
		  continue;
		if(j == STAT_TYPE_ENUM.WEIGHT)
		  continue;

		  adventurer_field[i].debuff_timers[j] = 0.0;
		  adventurer_field[i].max_debuff_timers[j] = 0.0;

		adventurer_field[i].current_stats[j] = adventurer_field[i].get_actual_stat(j);
	
	}
}

}

function exit_dungeon_gamestate()
{

}

function support_ally(i, preview)
{
    if (i < 0 || i > 3)
        return 0;

    if (i == current_selection)
        return 0;

    var w = 270.0 / 300.0 * CANVAS_HEIGHT * (220.0 / 600.0);

    var preview_value = 0;

    //heal is 5, buff is 6, armor is 7 
    for (var counter = STAT_TYPE_ENUM.HEAL; counter <= STAT_TYPE_ENUM.ARMOR; ++counter) {
        //fav food buff
        if (!preview) {
            if (current_selection >= 4) {
                adventurer_field[i].temporary_favorite_food = item_field[current_selection - 4].food_type;
                if (item_field[current_selection - 4].food_type != FOOD_TYPE_ENUM.NUM_FOOD_TYPE)
                    type_change_sfx.play();
            }
        }

        //healing stuff
        var value;
        if (current_selection < 4)
            value = adventurer_field[current_selection].current_stats[counter];
        else
            value = item_field[current_selection - 4].stats[counter] * item_field[current_selection - 4].strength;

        if (value > 0 ||
            (current_selection >= 4 && item_field[current_selection - 4].food_type != FOOD_TYPE_ENUM.NUM_FOOD_TYPE)) //value is how much we're healing /buffer/armoring with
        {



            //clamp cost to current fullness
            var cost = value;
            if (cost > adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS])
                cost = adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS];

            preview_value += cost;

            var ax, ay;

            if (i % 2 == 0)
                ax = (140.0 / 1080.0) * CANVAS_WIDTH;
            else
                ax = (400.0 / 1080.0) * CANVAS_WIDTH;

            if (Math.floor(i / 2) == 0)
                ay = (125.0 / 600) * CANVAS_HEIGHT;
            else
                ay = (370.0 / 600) * CANVAS_HEIGHT;

            //subtract from fullness
            if (!preview) {


                vfx_instances.push(VFX_INSTANCE(counter, 150.0 , ax + random_float(-.3, .3) * w,
                            ay + random_float(-.3, .3) * w));

                adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS] -= cost;

                //if(adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS] < 0)
                //{
                //adventurer_field[i].current_stats[STAT_TYPE_ENUM.WEIGHT] += adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS];
                //adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS] = 0;
                //if(adventurer_field[i].current_stats[STAT_TYPE_ENUM.WEIGHT] < 0)
                //adventurer_field[i].current_stats[STAT_TYPE_ENUM.WEIGHT] = 0;
                //}

                if (current_selection < 4) {
                    adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.FULLNESS] += cost;

                    //engage healer attack timer
                    adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.ATTACK_TIMER] = adventurer_field[current_selection].get_actual_stat(STAT_TYPE_ENUM.MAX_ATTACK_TIMER);
                }
                else
                    item_field[current_selection - 4].cooldown = 2.0;

                //debugger;

                //reduce target attack timer
                adventurer_field[i].current_stats[STAT_TYPE_ENUM.ATTACK_TIMER] -= value;


                //healing
                if (counter == STAT_TYPE_ENUM.HEAL) {
                    heal_sfx.play();
                    for (var j in adventurer_field[i].current_stats) {
                        if (j >= NUM_ATTACKS_ABILITIES)
                            break;

                        if (adventurer_field[i].debuff_values[j] < 0) {
                            //adventurer_field[i].debuff_timers[j] = 0.0;
                            /*if(adventurer_field[i].current_stats[j] + value > adventurer_field[i].get_actual_stat(j))
                                value = adventurer_field[i].get_actual_stat(j) - adventurer_field[i].current_stats[j];

                            adventurer_field[i].current_stats[j] += value;
    */
                            adventurer_field[i].debuff_values[j] += value;
                            if (adventurer_field[i].debuff_values[j] > 0) {
                                adventurer_field[i].debuff_values[j] = 0;
                                adventurer_field[i].debuff_timers[j] = 0.0;
                                adventurer_field[i].max_debuff_timers[j] = 0.0;

                            }


                            if (value > 0)
                                damage_numbers.push(DAMAGE_NUMBER(ax + w * random_float(-.3, .3), ay + h * random_float(-.3, .3), 40, value, TEXT_COLOR_ENUM.GREEN));

                        }
                    }
                }
                else if (counter == STAT_TYPE_ENUM.ARMOR) {
					armor_sfx.play();
					var old_shield = adventurer_field[i].shield;
					adventurer_field[i].shield += value;
					if (adventurer_field[i].shield > 3 * value)//armor can stack 3 times
						adventurer_field[i].shield = 3 * value;
					if (adventurer_field[i].shield < old_shield) //do not reduce shield to lower than current amount
						adventurer_field[i].shield = old_shield
                }
                else if (counter == STAT_TYPE_ENUM.BUFF) {
                    buff_sfx.play();
                    if (value > adventurer_field[i].buff_value)
                        adventurer_field[i].buff_value = value;
                }


                if (current_selection < 4 && adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.FULLNESS] > adventurer_field[current_selection].get_actual_stat(STAT_TYPE_ENUM.MAX_FULLNESS)) {

                    var f = adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.FULLNESS];
                    var m = adventurer_field[current_selection].get_actual_stat(STAT_TYPE_ENUM.MAX_FULLNESS);

                    if (auto_ko || Math.random() < (f - m) / m) {
                        auto_ko = false;
                        adventurer_field[current_selection].ko = true;//console.log("KO");
                    }
                }
            }

        }
    }

    return preview_value;
}

function damage_enemy(i, preview)
{
	if(i < 0 || i >= 9)
		return 0 ;

	if(!enemy_field[i])
		return 0 ;

		
	preview = preview || false; //default value

	var preview_value = 0;

	var p_index = i;

	var w = Math.min(CANVAS_WIDTH / 6.0, CANVAS_HEIGHT / 3.0);
	var h = w;

	var x = .5 * CANVAS_WIDTH + .5 * w + (p_index % 3) * w;
	var y = 0 + .5 * h + Math.floor(p_index / 3) * h;

	var total_damage = 0;

	if(!preview)
	{
		if(current_selection < 4) //if this is not an item
			adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.ATTACK_TIMER] = adventurer_field[current_selection].get_actual_stat(STAT_TYPE_ENUM.MAX_ATTACK_TIMER);
		else
		{
			
			item_field[current_selection - 4].cooldown = 2.0;

			if (item_field[current_selection - 4].food_type != FOOD_TYPE_ENUM.NUM_FOOD_TYPE) {
			    type_change_sfx.play();
			    enemy_field[i].food_type.push(item_field[current_selection - 4].food_type);
			}
		}			
	}

    //console.log("attack");
	var was_rendered = false;

	for(var j in enemy_field[i].defenses)
	{
		if(enemy_field[i].defenses[j] < 999)
		{
			//console.log(enemy_field[i].defenses[j] + " vx " + adventurer_field[current_selection].attacks[j])
		    var damage;
		    var render = false;
			
		    if (current_selection < 4) {
		        damage = adventurer_field[current_selection].current_stats[j];

		        if (damage == 0)
		            damage = 1;
		        else
		            render = true;

		    }
		    else {

		        damage = item_field[current_selection - 4].stats[j] * item_field[current_selection - 4].strength;
		        if(damage > 0)

		            render = true;
		    }

				var t_s = 30.0; 
			
				if(current_selection < 4)
				{
					if( adventurer_field[current_selection].temporary_favorite_food == FOOD_TYPE_ENUM.NUM_FOOD_TYPE)
					{
						if(enemy_field[i].food_type.indexOf( adventurer_field[current_selection].favorite_food) >= 0)
						{				
							t_s *= 2.0;	  
							damage *= 4.0;
							//("fav food");
						}
					}
					else
					{ //temporary fav food change buff
						if(enemy_field[i].food_type.indexOf( adventurer_field[current_selection].temporary_favorite_food) >= 0)
						{				
							t_s *= 2.0;	  
							damage *= 4.0;
							//("fav food");
						}

					}
				}
			
			damage = Math.min(enemy_field[i].defenses[j], damage);

			total_damage += damage;
            
			if(!preview)
			{
			    if (render) {
			        was_rendered = true;

			        vfx_instances.push(VFX_INSTANCE(j, 100, x + random_float(-.3, .3) * w,
						y + random_float(-.4, -.1) * h));

			        if (j == STAT_TYPE_ENUM.WEAPON)
			            weapon_sfx.play();
			        if (j == STAT_TYPE_ENUM.MAGIC)
			            magic_sfx.play();
                    if (j == STAT_TYPE_ENUM.FAITH)
                        faith_sfx.play();
                    if (j == STAT_TYPE_ENUM.SNEAK)
                        sneak_sfx.play();
			    }

				enemy_field[i].defenses[j] -= damage;
				if(current_selection < 4)
					adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.FULLNESS] += damage;

					if(damage > 0)
					{
						damage_numbers.push(DAMAGE_NUMBER(x + random_float(-.4, .4) * w, 
						y + random_float(-.4, .4) * h, t_s, damage, TEXT_COLOR_ENUM.RED));

					enemy_field[i].damage_animation = .5;
				}
			}
		}
		
	}

	
	if(total_damage > 0)
		enemy_field[i].preview_burst = true;

	if(!preview)
	{
	    if (!was_rendered)
	        no_hit_sfx.play();

	    for(var j in enemy_field[i].defenses)
	    {
	        if(enemy_field[i].defenses[j] <= 0)
	        {
	            enemy_death_sfx.play();
	            dying_enemy_list.push(enemy_field[i]);
	            delete enemy_field[i];
	            break;
	        }

	    }

	    //if no remaining enemies have defenses, then kill all enemies
        {
	        var kill = true;
	        for (var k in enemy_field)
	        {
	            if (enemy_field[k])
	            {
	                for(l in enemy_field[k].defenses)
	                {
	                    if (enemy_field[k].defenses[l] < 999)
	                        kill = false;
	                }
	            }
	        }

	        if (kill)
	            for (var k in enemy_field) {

	                enemy_death_sfx.play();
	                dying_enemy_list.push(enemy_field[k]);
	                delete enemy_field[k];
	            }
	    }



		if(current_selection < 4 && adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.FULLNESS] > adventurer_field[current_selection].get_actual_stat(STAT_TYPE_ENUM.MAX_FULLNESS))
		{
			//adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.MAX_FULLNESS] += .1;
			//adventurer_field[current_selection].stomach_level += 1;

			var f = adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.FULLNESS];
			var m = adventurer_field[current_selection].get_actual_stat(STAT_TYPE_ENUM.MAX_FULLNESS);

			if(auto_ko || Math.random() < (f - m) / m)
			{
			    ko_sfx.play();
				auto_ko = false;
				adventurer_field[current_selection].ko = true;//console.log("KO");
			}
		}
	}

	  
	return total_damage;
}

function update_dungeon_gamestate()
{
	var clear_selection = true; //we will mark this flag false if we release the mouse button over an interactable

    //process vfx
    vfx_timer += get_frame_time();
    if (vfx_timer > 1.0 / 60.0)
    {
        for(var i in vfx_instances)
        {
            vfx_instances[i].frame += 1;

            if (vfx_instances[i].frame >= 30)
                delete vfx_instances[i];
        }

        vfx_timer = 0.0;
    }

	draw_center(title_image, .5 * CANVAS_WIDTH, .5 * CANVAS_HEIGHT, CANVAS_WIDTH, CANVAS_HEIGHT);
	draw_center(fade_texture, .5 * CANVAS_WIDTH, .5 * CANVAS_HEIGHT, CANVAS_WIDTH, CANVAS_HEIGHT);
	draw_center(fade_texture, .5 * CANVAS_WIDTH, .5 * CANVAS_HEIGHT, CANVAS_WIDTH, CANVAS_HEIGHT);

	draw_center(frame_texture, CANVAS_WIDTH * .5, CANVAS_HEIGHT * .5, CANVAS_WIDTH, CANVAS_HEIGHT);

	if (!level_complete && !tutorial_mode)
  		level_timer += speed_scalar * get_frame_time();



	//if(place > 0)
	//debugger;
	//draw_text("teststring", 525, CANVAS_HEIGHT - 80);

	//console.log(adventurer_field);

//if(enemy_field.length == 0)
{
    //detect remaining enemies
    var enemy_count = 0;
    for(var i in enemy_field)
    {
        if(enemy_field[i])// == enemy_field[i])
          enemy_count +=1;
    }
    if(enemy_count == 0)
    {    
		//debugger;
		if(room_counter  == __floor_list[current_level].rooms.length - 1)
		{


		    current_extractions = total_extracts;
			
		    level_complete = true;

		    if (!__level_completed[current_level])//if this the first time we completed the level, set the cutscene to trigger
		    {

		        enter_cutscene(1);
		    }
		    __level_completed[current_level] = true;
			//unlocked_levels += 1;
            //next_gamestate = GAMESTATE_ENUM.UPGRADES;
		
			//return;

		}
		else
        {
		    ++room_counter;
		    advance_sfx.play();
            new_room();
        }
    }
}


draw_text(  (room_counter + 1) + "/" + __floor_list[current_level].rooms.length, 
CANVAS_WIDTH * .5 + 60* frame_scale, 
CANVAS_HEIGHT - 10* frame_scale, 35* frame_scale);

draw_text("Room", 
CANVAS_WIDTH * .5 + 60* frame_scale, 
CANVAS_HEIGHT - 50* frame_scale, 40* frame_scale);


var minutes = Math.floor(level_timer / 60.0);
var seconds = Math.floor(level_timer - minutes * 60.0);
var milliseconds = Math.floor(1000 * (level_timer - minutes * 60.0 - seconds));

if (milliseconds < 100) {milliseconds = "0" + milliseconds;}
if (milliseconds < 10) {milliseconds = "0" + milliseconds;}

if (seconds < 10) {seconds = "0" + seconds;}

draw_text(minutes + "\'" + seconds + "\"" + milliseconds, 
CANVAS_WIDTH * .75 - 80* frame_scale, CANVAS_HEIGHT - 20* frame_scale, 35* frame_scale);

draw_text("   TIME", 
CANVAS_WIDTH * .75 - 80* frame_scale, CANVAS_HEIGHT - 60* frame_scale, 40* frame_scale);


//console.log(enemy_field.length);

var arrow_alpha = .5;
//var enemy_position_index = [4, 3, 5, 1, 0, 7, 2, 6, 8];

//var enemy_position_index = [3, 0, 4, 1, 6, 2, 7, 5, 8];

//move units
//debugger;

if(!enemy_field[0])
{
	enemy_field[0] = enemy_field[1];
	enemy_field[1] = null;
}
if(!enemy_field[1])
{
	enemy_field[1] = enemy_field[2];
	enemy_field[2] = null;
}

if(!enemy_field[3])
{
	enemy_field[3] = enemy_field[4];
	enemy_field[4] = null;
}
if(!enemy_field[4])
{
	enemy_field[4] = enemy_field[5];
	enemy_field[5] = null;
}

if(!enemy_field[6])
{
	enemy_field[6] = enemy_field[7];
	enemy_field[7] = null;
}
if(!enemy_field[7])
{
	enemy_field[7] = enemy_field[8];
	enemy_field[8] = null;
}

var preview_damage_value = 0;

for(var i in enemy_field)
{ 
	if(!enemy_field[i])
	 continue;

	var w = CANVAS_WIDTH * (125.0 / 1080.0);
	var h = w;

	var p_index = i;//enemy_position_index[i];

	var x = .75 * CANVAS_WIDTH + (p_index % 3 - 1) * 1.5 * w;
	var y = 0 + .6 * h + Math.floor(p_index / 3) * 1.25 * h;

	var ui_mult = 1.0;
//console.log(x + " " + y + " " + w + " " + h);

	enemy_field[i].damage_animation -= get_frame_time();
	if(enemy_field[i].damage_animation < 0.0)
		enemy_field[i].damage_animation = 0.0;

		enemy_field[i].attack_animation -= 2.0 * get_frame_time();
		if(enemy_field[i].attack_animation < 0.0)
			enemy_field[i].attack_animation = 0.0;

			enemy_field[i].heal_animation -= 1.0 * get_frame_time();
			if(enemy_field[i].heal_animation < 0.0)
				enemy_field[i].heal_animation = 0.0;
	

	
			if (!tutorial_mode)
   enemy_field[i].timer -= speed_scalar * get_frame_time();
//console.log(i + " " + enemy_field[i].timer + " " + get_frame_time());


if(enemy_field[i].timer < 0.0 && enemy_field[i].attacks.length > 0)
{
	//console.log(i + " attacks!");
	enemy_field[i].timer = enemy_field[i].max_timer;

	//select target //
	var current_attack = enemy_field[i].attacks[enemy_field[i].current_attack % enemy_field[i].attacks.length];
	enemy_field[i].current_attack += 1;

	if(current_attack.enemy)
	{
		var lowest_value = 1000;
		var highest_value = -1;
		var lowest_index = -1;
		var highest_index = -1;

			//find target for enemy attack
		for(var j in adventurer_field)
		{
			var val = adventurer_field[j].current_stats[current_attack.type]
			if(val > highest_value)
			{
				highest_value = val;
				highest_index = j;
			}
			if(val < lowest_value && val > 0)//@TODO: this >0 check doesn't work with attacking fullness
			{
				lowest_value = val;
				lowest_index = j;
			}
		}

		var index;
		if(current_attack.greatest && highest_index != -1)
			index = highest_index;
		if(!current_attack.greatest && lowest_index != -1)
			index = lowest_index;

		if(index != -1)
		{
			enemy_field[i].attack_animation = .5;
			var ax, ay;
			var w = 270.0 / 300.0 * CANVAS_HEIGHT * (220.0 / 600.0);

			if (index % 2 == 0)
			    ax = (140.0 / 1080.0) * CANVAS_WIDTH;
			else
			    ax = (400.0 / 1080.0) * CANVAS_WIDTH;

			if (Math.floor(index / 2) == 0)
			    ay = (125.0 / 600) * CANVAS_HEIGHT;
			else
			    ay = (370.0 / 600) * CANVAS_HEIGHT;


			if (current_attack.type < NUM_ATTACKS_ABILITIES) {
			    vfx_instances.push(VFX_INSTANCE(current_attack.type, 150.0, ax + random_float(-.3, .3) * w,
                        ay + random_float(-.3, .3) * w));
			}


			if (current_attack.type == STAT_TYPE_ENUM.WEAPON)
			    weapon_sfx.play();
			if (current_attack.type == STAT_TYPE_ENUM.MAGIC)
			    magic_sfx.play();
            if (current_attack.type == STAT_TYPE_ENUM.FAITH)
			    faith_sfx.play();
            if (current_attack.type == STAT_TYPE_ENUM.SNEAK)
                sneak_sfx.play();

		damage_numbers.push(DAMAGE_NUMBER(ax + random_float(-.3, .3) * w,
            ay + random_float(-.3, .3) * w,
            40, -current_attack.strength, TEXT_COLOR_ENUM.RED));

			var attack_value = current_attack.strength;

			if(adventurer_field[index].shield > 0)
			{
				attack_value -= adventurer_field[index].shield;
				adventurer_field[index].shield -= current_attack.strength;
				if(adventurer_field[index].shield < 0)
					adventurer_field[index].shield = 0;
			}


			adventurer_field[index].damage_animation = .5;
			//adventurer_field[index].current_stats[current_attack.type] -= current_attack.strength;
				 
			//deal damage to abilities
			if(attack_value > 0)
			{
				if(current_attack.type == STAT_TYPE_ENUM.WEIGHT)
				{
					adventurer_field[index].current_stats[STAT_TYPE_ENUM.WEIGHT] -= attack_value;
					if(adventurer_field[index].current_stats[STAT_TYPE_ENUM.WEIGHT] < 0)
					adventurer_field[index].current_stats[STAT_TYPE_ENUM.WEIGHT] = 0;
				}
				else if(current_attack.type == STAT_TYPE_ENUM.FULLNESS)
				{
				    adventurer_field[index].current_stats[STAT_TYPE_ENUM.FULLNESS] += attack_value;
				}
                else
				{
				adventurer_field[index].debuff_values[current_attack.type] -= attack_value;
				adventurer_field[index].debuff_timers[current_attack.type] = current_attack.timer;

				if(current_attack.timer > adventurer_field[index].max_debuff_timers[current_attack.type])
					adventurer_field[index].max_debuff_timers[current_attack.type] = current_attack.timer;
				}
			}
			
			//console.log(i + " attacks " + index + " sets timer:" + current_attack.timer);

		//if(adventurer_field[index].current_stats[current_attack.type] < 0)
		//adventurer_field[index].current_stats[current_attack.type] = 0;
			
			if(current_attack.type == STAT_TYPE_ENUM.FULLNESS && current_attack.strength)
		{
			if(adventurer_field[index].current_stats[STAT_TYPE_ENUM.FULLNESS] > adventurer_field[index].get_actual_stat(STAT_TYPE_ENUM.MAX_FULLNESS))
			{

				var f = adventurer_field[index].current_stats[STAT_TYPE_ENUM.FULLNESS];
				var m = adventurer_field[index].get_actual_stat(STAT_TYPE_ENUM.MAX_FULLNESS);

				if(auto_ko || Math.random() < (f - m) / m)
				{
				    ko_sfx.play();
					auto_ko = false;
					adventurer_field[index].ko = true;//console.log("KO");
				}
			}
		}
		}

	}
	else
	{ //probably healing or buffing an ally

		var lowest_value = 1000;
		var highest_value = -1;
		var lowest_index = -1;
		var highest_index = -1;

		for(var j in enemy_field)
		{
			if(!enemy_field[j])
				continue;

			for(var k in enemy_field[j].defenses)
			{
				var val = enemy_field[j].defenses[k];
				if(val > highest_value)
				{
					highest_value = val;
					highest_index = j;
				}
				if(val < lowest_value && val > 0 && val != enemy_field[j].max_defenses[k])//@TODO: this >0 check doesn't work with attacking fullness
				{
					lowest_value = val;
					lowest_index = j;
				}
			}
		}

		var index = -1;
		if(current_attack.greatest && highest_index != -1)
			index = highest_index;
		if(!current_attack.greatest && lowest_index != -1)
			index = lowest_index;

			//console.log(index + " " + highest_index + " " + highest_value + 
		//" " + lowest_index + " " + lowest_value);

		if(index != -1)
		{

		    var w = Math.min(CANVAS_WIDTH / 6.0, CANVAS_HEIGHT / 3.0);
		    var h = w;

		    var x = .5 * CANVAS_WIDTH + .5 * w + (index % 3) * w;
		    var y = 0 + .5 * h + Math.floor(index / 3) * h;

		    vfx_instances.push(VFX_INSTANCE(current_attack.type, 100, x + random_float(-.3, .3) * w,
                    y + random_float(-.4, -.1) * h));

			for(var k in enemy_field[index].defenses)
			{
				if(!enemy_field[index])
					continue;

			   var h_value = current_attack.strength;
			
			  if(enemy_field[index].defenses[k] + h_value > enemy_field[index].max_defenses[k])
			    h_value =  enemy_field[index].max_defenses[k] - enemy_field[index].defenses[k];
				  
				  enemy_field[index].defenses[k] += h_value;

				  if(h_value > 0)
				  {
					var p = i;;//enemy_position_index[index];

					var tx = .5 * CANVAS_WIDTH + .5 * w + (p % 3) * w;
					var ty = 0 + .5 * h + Math.floor(p / 3) * h;

					enemy_field[index].heal_animation = 1.0;
					enemy_field[i].heal_animation = 1.0;

					damage_numbers.push(DAMAGE_NUMBER(tx + random_float(-.3, .3) * w, 
					ty + random_float(-.3, .3) * h, 40, h_value, TEXT_COLOR_ENUM.GREEN));
				  }
			}
		}
	}


    //if enemy have no defenses, it dies after it gets off one attack
	var kill = true;
	for(var k in enemy_field[i].defenses)
        {
	    if (enemy_field[i].defenses[k] < 999)
	        kill = false;
	}

	if (kill) {
	 
	    enemy_death_sfx.play();
	    dying_enemy_list.push(enemy_field[i]);
	    delete enemy_field[i];
	}

}
else if(enemy_field[i].timer < 0.0 && enemy_field[i].attacks.length == 0)
{

	var p = i;//enemy_position_index[index];
	var tx = .5 * CANVAS_WIDTH + .5 * w + (p % 3) * w;
	var ty = 0 + .5 * h + Math.floor(p / 3) * h;

	damage_numbers.push(DAMAGE_NUMBER(tx + random_float(-.3, .3) * w, 
	ty + random_float(-.3, .3) * h, 40, "ESCAPED!", TEXT_COLOR_ENUM.RED));

	run_sfx.play();

	dying_enemy_list.push(enemy_field[i]);
	delete enemy_field[i];
	
    //if no remaining enemies have defenses, then kill all enemies
	{
	    var kill = true;
	    for (var k in enemy_field) {
	        if (enemy_field[k]) {
	            for (l in enemy_field[k].defenses) {
	                if (enemy_field[k].defenses[l] < 999)
	                    kill = false;
	            }
	        }
	    }

	    if (kill)
	        for (var k in enemy_field) {
	            if (enemy_field[k]) {
	                enemy_death_sfx.play();
	                dying_enemy_list.push(enemy_field[k]);
	                delete enemy_field[k];
	            }
	        }
	}

	break;
}


	if(current_selection != -1 && point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x, y, w, h) && current_selection < 4 && i % 3 < adventurer_field[current_selection].range)
	{	
		arrow_alpha = 1.0;
		ui_mult = 1.05;

		if(point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x, y, w, h))
		//if() 
		{
			//player attacks here
			{//player attack enemy!

				var preview = !INPUT.left_released;

				if(adventurer_field[current_selection].aoe_type == AOE_TYPE_ENUM.AOE_SINGLE)
					preview_damage_value += damage_enemy(i, preview);
				else if(adventurer_field[current_selection].aoe_type == AOE_TYPE_ENUM.AOE_PIERCE)
				{
					preview_damage_value += damage_enemy(parseInt(i), preview);
					
					if(i % 3 < 2) //if no extreme right border
					preview_damage_value += damage_enemy(parseInt(i)+1, preview);
				}
				else if(adventurer_field[current_selection].aoe_type == AOE_TYPE_ENUM.AOE_AREA)
				{
					preview_damage_value += damage_enemy(parseInt(i), preview);

					if(i % 3 < 2) //if no extreme right border
					preview_damage_value += damage_enemy(parseInt(i)+1, preview);
					if(i % 3 > 0) //if not extreme left border
					preview_damage_value += damage_enemy(parseInt(i)-1, preview);

					preview_damage_value += damage_enemy(parseInt(i)+3, preview);
					preview_damage_value += damage_enemy(parseInt(i)-3, preview);
				}
				else if (adventurer_field[current_selection].aoe_type == AOE_TYPE_ENUM.AOE_COLUMN) {

					if (i == 0 || i == 3 || i == 6) // left
					{
						preview_damage_value += damage_enemy(0, preview);
						preview_damage_value += damage_enemy(3, preview);
						preview_damage_value += damage_enemy(6, preview);
					}
					else if (i == 1 || i == 4 || i == 5) // middle
					{
						preview_damage_value += damage_enemy(1, preview);
						preview_damage_value += damage_enemy(4, preview);
						preview_damage_value += damage_enemy(7, preview);
					}
					else if (i == 2 || i == 5 || i == 8) // right
					{
						preview_damage_value += damage_enemy(2, preview);
						preview_damage_value += damage_enemy(5, preview);
						preview_damage_value += damage_enemy(8, preview);
					}
				}
				else if (adventurer_field[current_selection].aoe_type == AOE_TYPE_ENUM.AOE_ROW) {

					if (i == 0 || i == 1 || i == 2) // top
					{
						preview_damage_value += damage_enemy(0, preview);
						preview_damage_value += damage_enemy(1, preview);
						preview_damage_value += damage_enemy(2, preview);
					}
					else if (i == 3 || i == 4 || i == 5) // mid
					{
						preview_damage_value += damage_enemy(3, preview);
						preview_damage_value += damage_enemy(4, preview);
						preview_damage_value += damage_enemy(5, preview);
					}
					else if (i == 6 || i == 7 || i == 8) // bot
					{
						preview_damage_value += damage_enemy(6, preview);
						preview_damage_value += damage_enemy(7, preview);
						preview_damage_value += damage_enemy(8, preview);
					}
				}
				else if(adventurer_field[current_selection].aoe_type == AOE_TYPE_ENUM.AOE_ALL)
				{
					//for(var i = 0; i < 9; ++i)
						//preview_damage_value += damage_enemy(parseInt(i), preview);
					preview_damage_value += damage_enemy(parseInt(0), preview);
					preview_damage_value += damage_enemy(parseInt(1), preview);
					preview_damage_value += damage_enemy(parseInt(2), preview);
					preview_damage_value += damage_enemy(parseInt(3), preview);
					preview_damage_value += damage_enemy(parseInt(4), preview);
					preview_damage_value += damage_enemy(parseInt(5), preview);
					preview_damage_value += damage_enemy(parseInt(6), preview);
					preview_damage_value += damage_enemy(parseInt(7), preview);
					preview_damage_value += damage_enemy(parseInt(8), preview);
				}
				
				if(!preview)
				{
					if(current_selection < 4) //clear the temp fav food buff
						adventurer_field[current_selection].temporary_favorite_food = FOOD_TYPE_ENUM.NUM_FOOD_TYPE;

							//buff is only good for one attack
						adventurer_field[current_selection].buff_value = 0;
							//clear current selection, because this adventurer has already acted
							current_selection = -1;
				}
			}
			
		}
	}
	if(current_selection >= 4 && point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x, y, w, h))
	{
		arrow_alpha = 1.0;
		ui_mult = 1.05;

		if (INPUT.left_released) 
		{
			damage_enemy(i);
			current_selection = -1;
		}
	}

	if(enemy_field[i])
	{
		var fade = false;
		if(current_selection < 4 && current_selection >= 0) //adventurer selected
		{
		  if(adventurer_field[current_selection].range < 3)
		  {
			  if(i == 2 || i == 5 || i == 8)
			 	 fade = true;
		  }
		  if(adventurer_field[current_selection].range < 2)
		  {
			  if(i == 1 || i == 4 || i == 7)
			 	 fade = true;
		  }
		}
		
		if(enemy_field[i].preview_burst)
			draw_center(burst_texture, x, y, 
				1.5 * ui_mult *(350.0 / 300.0) * w, 
				1.5 * ui_mult *(350.0 / 300.0) * h)

		var speed = i / 30.0 + .2;

		enemy_field[i].display_x = enemy_field[i].display_x * (1.0-speed) + x * speed;
		enemy_field[i].display_y = enemy_field[i].display_y * (1.0 - speed) + y * speed;

		enemy_field[i].draw(
			enemy_field[i].display_x + enemy_field[i].damage_animation * random_float(-1.0, 1.0) * .1 * w - enemy_field[i].attack_animation * .5 * w,
		enemy_field[i].display_y + enemy_field[i].damage_animation * random_float(-1.0, 1.0) * .1 * h - .3 * w * enemy_field[i].heal_animation,
		ui_mult * w, ui_mult * h, fade);

		enemy_field[i].preview_burst = false;
	}
}

for (var i in dying_enemy_list)
{
    if (!dying_enemy_list[i])
        delete dying_enemy_list[i];
    else if (dying_enemy_list[i].death_fade_timer < 0.0)
        delete dying_enemy_list[i];
    else
    {
        dying_enemy_list[i].draw(
        dying_enemy_list[i].display_x + dying_enemy_list[i].damage_animation * random_float(-1.0, 1.0) * .1 * w - dying_enemy_list[i].attack_animation * .5 * w,
    dying_enemy_list[i].display_y + dying_enemy_list[i].damage_animation * random_float(-1.0, 1.0) * .1 * h - .3 * w * dying_enemy_list[i].heal_animation,
    ui_mult * w, ui_mult * h, fade);
    dying_enemy_list[i].death_fade_timer -= 3.0 * get_frame_time();
    }

}

var arrow_endpoint = [];
arrow_endpoint.x = 0;
arrow_endpoint.y = 0;

for(var i in item_field)
{
	
	if(item_field[i])//.unlocked)
	{
		var w = 75 * frame_scale;//Math.min(CANVAS_WIDTH / 6.0, CANVAS_HEIGHT / 5.0);
		var h = w;


		var x = .05 * CANVAS_WIDTH + (i % 4  + .1) * (1.5 * w);
		var y = CANVAS_HEIGHT - 40* frame_scale;

        if(!tutorial_mode)
		item_field[i].cooldown -= speed_scalar * get_frame_time();
		item_field[i].draw(x, y, w, h);

		if (point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x, y, w, h))
		{
			clear_selection = false;
		if(INPUT.left_triggered && item_field[i].cooldown < 0.0)
		{
			//console.log("Trig");
			current_selection = parseInt(i, 10) + 4;

			}
		}
		if(current_selection >= 0 )//&& )
		{
			//debugger;
			var val = parseInt(i, 10);
			if(current_selection == val + 4)
			{
						arrow_endpoint.x = x;
			arrow_endpoint.y = y;
			}
		}

	}

	console.log(current_selection);
}

for(var i in adventurer_field)
{
	if(adventurer_field[i] != adventurer_field[i]) //is null
		continue;


	var x, y;

	var w = 270.0 / 300.0 * CANVAS_HEIGHT * (220.0 / 600.0);
	var h = CANVAS_HEIGHT * (220.0 / 600.0);

	var ui_mult = 1.0;

	if(i % 2 == 0)
		x = (140.0 / 1080.0) * CANVAS_WIDTH;
	else
		x = (400.0 / 1080.0) * CANVAS_WIDTH;

	if(Math.floor(i / 2)  == 0)
		y = (125.0 / 600) * CANVAS_HEIGHT;
	else
		y = (370.0 / 600) * CANVAS_HEIGHT;
		adventurer_field[i].damage_animation -= get_frame_time();

	if(adventurer_field[i].damage_animation < 0.0)
		adventurer_field[i].damage_animation = 0.0;



    //digest
	if (!tutorial_mode) {
	    if (adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS] > 0) {
	        var speed = adventurer_field[i].get_actual_stat(STAT_TYPE_ENUM.DIGESTION_RATE)
	        if (level_complete)
	            speed = 10.0 * adventurer_field[i].get_actual_stat(STAT_TYPE_ENUM.MAX_FULLNESS);

	        var amount = speed * speed_scalar * get_frame_time();
	        if (amount > adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS])
	            amount = adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS];

	        adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS] -= amount;
	        adventurer_field[i].current_stats[STAT_TYPE_ENUM.WEIGHT] += amount;
	    }
	    else
	        adventurer_field[i].ko = false;
	}

		//debuffs + timers
	for(var j in adventurer_field[i].current_stats)
	{
		if(j == STAT_TYPE_ENUM.ATTACK_TIMER)
		  continue;
		if(j == STAT_TYPE_ENUM.FULLNESS)
		  continue;
		if(j == STAT_TYPE_ENUM.WEIGHT)
		  continue;

		  if(j < NUM_ATTACKS_ABILITIES)
		  {
				//recompute current stats
				var fat_bonus = 0;
				var threshold = 50;
				var count = adventurer_field[i].current_stats[STAT_TYPE_ENUM.WEIGHT];
				while(count > 0)
				{
				  count -= threshold;
				  if(count >= 0)
				  fat_bonus += 1;
				  threshold += 10;
				}
				
				if(fat_bonus > 1.0 * adventurer_field[i].get_actual_stat(j))
				  fat_bonus = 1.0 * adventurer_field[i].get_actual_stat(j)
				
				  if(adventurer_field[i].debuff_values[j]  < -(adventurer_field[i].get_actual_stat(j) + fat_bonus))
				  adventurer_field[i].debuff_values[j]  = -(adventurer_field[i].get_actual_stat(j) + fat_bonus);

				  adventurer_field[i].current_stats[j] = adventurer_field[i].get_actual_stat(j) + adventurer_field[i].debuff_values[j] + fat_bonus;
				  
				  if (j != STAT_TYPE_ENUM.BUFF)
				 if(adventurer_field[i].get_actual_stat(j) > 0)
				 	adventurer_field[i].current_stats[j] += adventurer_field[i].buff_value;
					
				 // if(adventurer_field[i].current_stats[j] < 0)
					//adventurer_field[i].current_stats[j] = 0;
				}

        if(!tutorial_mode)
		  adventurer_field[i].debuff_timers[j] -= speed_scalar * get_frame_time();
		if(adventurer_field[i].debuff_timers[j] < 0.0)
		{
			if(adventurer_field[i].debuff_values[j] < 0.0)  //adventurer_field[i].current_stats[j] != adventurer_field[i].get_actual_stat(j)) 
  			{	
				adventurer_field[i].debuff_values[j] = 0.0;
				adventurer_field[i].max_debuff_timers[j] = 0.0;
				//console.log(i + " resets " + j);
		    	//adventurer_field[i].current_stats[j] = adventurer_field[i].get_actual_stat(j);
		    }
		}	
	}


		//select
	if(INPUT.left_triggered)
	{
			//console.log("Trig");
		if (current_selection == -1 && !adventurer_field[i].ko && adventurer_field[i].current_stats[STAT_TYPE_ENUM.ATTACK_TIMER] < 0 && point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x, y, w, h))
			current_selection = i;

	}
		if(current_selection == i)
		{
			//debugger;
			arrow_endpoint.x = x;
			arrow_endpoint.y = y;
		}

		//use abilities (heal & buff) @TODO:BUFF
		if(current_selection != -1 && current_selection < 4 && 
			(adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.HEAL] > 0 ||
				adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.ARMOR] > 0 ||
					adventurer_field[current_selection].current_stats[STAT_TYPE_ENUM.BUFF] > 0)
		
		)
		{
			if(point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x, y, w, h) && i != current_selection)
			{
				clear_selection = false
				ui_mult = 1.05;
				arrow_alpha = 1.0;
			}
		}
		else if(current_selection >= 4 && item_field[current_selection - 4].stats[STAT_TYPE_ENUM.HEAL] > 0)
		{
			if(point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x, y, w, h))
			{
				clear_selection = false
				arrow_alpha = 1.0;
				ui_mult = 1.05;
			}	

		}
		else if(current_selection >= 4 && item_field[current_selection - 4].food_type != FOOD_TYPE_ENUM.NUM_FOOD_TYPE)
		{
			if(point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x, y, w, h))
			{
				clear_selection = false
				ui_mult = 1.05;
				arrow_alpha = 1.0;
			}	
		}

	if( current_selection != -1)
	{
		if(point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x, y, w, h) && i != current_selection)
		{
			clear_selection = false
			var preview = !INPUT.left_released;

			if (current_selection >= 4)
			    preview_damage_value += support_ally(parseInt(i), preview);
			else if (adventurer_field[current_selection].aoe_type == AOE_TYPE_ENUM.AOE_SINGLE)
			    preview_damage_value += support_ally(parseInt(i), preview);
			else if (adventurer_field[current_selection].aoe_type == AOE_TYPE_ENUM.AOE_PIERCE) {
			    preview_damage_value += support_ally(parseInt(i), preview);

			    if (i % 2 < 1) //if no extreme right border
			        preview_damage_value += support_ally(parseInt(i) + 1, preview);
			}
			else if (adventurer_field[current_selection].aoe_type == AOE_TYPE_ENUM.AOE_AREA) {
			    preview_damage_value += support_ally(parseInt(i), preview);

			    if (i % 2 < 1) //if no extreme right border
			        preview_damage_value += support_ally(parseInt(i) + 1, preview);
			    if (i % 2 > 0) //if not extreme left border
			        preview_damage_value += support_ally(parseInt(i) - 1, preview);

			    preview_damage_value += support_ally(parseInt(i) + 2, preview);
			    preview_damage_value += support_ally(parseInt(i) - 2, preview);
			}
			else if (adventurer_field[current_selection].aoe_type == AOE_TYPE_ENUM.AOE_ALL) {
			    preview_damage_value += support_ally(parseInt(0), preview);
			    preview_damage_value += support_ally(parseInt(1), preview);
			    preview_damage_value += support_ally(parseInt(2), preview);
			    preview_damage_value += support_ally(parseInt(3), preview);
			}

			if(!preview)
			{

						if(current_selection < 4)
					adventurer_field[current_selection].buff_value = 0;
					//clear current selection, because this adventurer has already acted
				current_selection = -1;
			}
		}
	}

		//attack timer
    ///if(adventurer_field[i].timer > 0)
    if(!tutorial_mode)
	{
        adventurer_field[i].current_stats[STAT_TYPE_ENUM.ATTACK_TIMER] -= speed_scalar * get_frame_time();

        var all_zero = true;
        for (var j = 0; j < STAT_TYPE_ENUM.ATTACK_TIMER; ++j) {
            if (adventurer_field[i].current_stats[j] > 0)
                all_zero = false;
        }

        if (all_zero || adventurer_field[i].current_stats[STAT_TYPE_ENUM.ATTACK_TIMER] > 0)

            adventurer_field[i]._ready_sfx_signal = true;
        else if(!all_zero && adventurer_field[i]._ready_sfx_signal  && adventurer_field[i].current_stats[STAT_TYPE_ENUM.ATTACK_TIMER] < 0)
        {

            adventurer_field[i]._ready_sfx_signal = false;
            ready_sfx.play();
            
        }
	}

		//draw
	//if(current_selection != i)

}

for(var i in adventurer_field)
{
	if(adventurer_field[i] != adventurer_field[i]) //is null
		continue;


	var x, y;

	var w = 270.0 / 300.0 * CANVAS_HEIGHT * (220.0 / 600.0);
	var h = CANVAS_HEIGHT * (220.0 / 600.0);

	var ui_mult = 1.0;

	if(i % 2 == 0)
		x = (140.0 / 1080.0) * CANVAS_WIDTH;
	else
		x = (400.0 / 1080.0) * CANVAS_WIDTH;

	if(Math.floor(i / 2)  == 0)
		y = (125.0 / 600) * CANVAS_HEIGHT;
	else
		y = (370.0 / 600) * CANVAS_HEIGHT;

	if (adventurer_field[i].ko)
		ui_mult = 1.0;
	else if (current_selection == i)
		ui_mult = 1.05;
	else if (current_selection == -1 && point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x, y, w, h)) {

		ui_mult = 1.05;
	}
	if(point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x, y, w, h))
		clear_selection = false

		var temp_preview = preview_damage_value;
		if(current_selection != i)
		temp_preview = 0;

	//console.log(i);
	//console.log(adventurer_field);
	adventurer_field[i].draw(
		x + adventurer_field[i].damage_animation * random_float(-1.0, 1.0) * .1 * w,
		 y + adventurer_field[i].damage_animation * random_float(-1.0, 1.0) * .1 * h, 
		 ui_mult * w,  ui_mult * h, 1.0, temp_preview, 
		 current_selection == i
		||
		point_rect_collision(INPUT.mouse_screen.x, INPUT.mouse_screen.y, x,  y, w, h)
		);//, ., , );

}
/*
if(current_selection == 0) 
adventurer_field[0].draw(INPUT.mouse_screen.x, INPUT.mouse_screen.y, 270.0 / 300.0 * CANVAS_HEIGHT / 2.0, CANVAS_HEIGHT / 2.0);
  if(current_selection == 1) 
  adventurer_field[1].draw(INPUT.mouse_screen.x, INPUT.mouse_screen.y, 270.0 / 300.0 * CANVAS_HEIGHT / 2.0, CANVAS_HEIGHT / 2.0);
if(current_selection == 2) 
adventurer_field[2].draw(INPUT.mouse_screen.x, INPUT.mouse_screen.y, 270.0 / 300.0 * CANVAS_HEIGHT / 2.0, CANVAS_HEIGHT / 2.0);
if(current_selection == 3)
adventurer_field[3].draw(INPUT.mouse_screen.x, INPUT.mouse_screen.y, 270.0 / 300.0 * CANVAS_HEIGHT / 2.0, CANVAS_HEIGHT / 2.0);
*/

if(current_selection != -1)
{
	//debugger;
	var x = .5 * arrow_endpoint.x + INPUT.mouse_screen.x * .5;
	var y = .5 * arrow_endpoint.y + INPUT.mouse_screen.y * .5;
	var len = Math.sqrt(Math.pow((arrow_endpoint.x - INPUT.mouse_screen.x), 2) + Math.pow(arrow_endpoint.y - INPUT.mouse_screen.y, 2));
	var ang = Math.atan((arrow_endpoint.y - INPUT.mouse_screen.y) / (arrow_endpoint.x - INPUT.mouse_screen.x));
	
	if(arrow_endpoint.x > INPUT.mouse_screen.x)
	{
		//ang *= -1.0;
		ang -= Math.PI;
	}

	//console.log(ang);
	if(arrow_alpha < 1.0)
	
	draw_center_rotation(red_arrow_texture,x,  y, len, 50,  ang, arrow_alpha);
	else
	draw_center_rotation(arrow_texture,x,  y, len, 50,  ang, arrow_alpha);
	//draw_center(arrow_texture,CANVAS_WIDTH * .5,  CANVAS_HEIGHT * .5, 200, 50);	
}


	/*if (INPUT.left_released)
{
	//if(current_selection != -1)
	//adventurer_field[current_selection].anim_delay_timer = .25;

  current_selection = -1;
}*/

for (var i in vfx_instances)
{
    if (vfx_instances[i].frame >= 0) {
        draw_center_tex_coord(vfx_textures[vfx_instances[i].type], vfx_instances[i].x, vfx_instances[i].y,
            vfx_instances[i].size * frame_scale, vfx_instances[i].size * frame_scale, 1,
            1500.0 * Math.floor(vfx_instances[i].frame / 6) / 5,
            1800.0 * (vfx_instances[i].frame % 6) / 6,
            300, 300);
    }

//        1500.0 * Math.floor(vfx_instances[i].frame / 6), 1500.0 * (Math.floor(vfx_instances[i].frame / 6) + 1.0 / 6.0),
  //      1800.0 * (vfx_instances[i].frame % 6) / 6, 1800.0 * ((vfx_instances[i].frame % 6) + 1) / 6);
}

for(var i in damage_numbers)
{
	//debugger;
	//context.globalAlpha = damage_numbers[i].timer / damage_numbers[i].max_timer;
	draw_text(damage_numbers[i].value.toString(), 
	damage_numbers[i].x, damage_numbers[i].y, damage_numbers[i].size,  damage_numbers[i].style);

	damage_numbers[i].y -= 3.0 * get_frame_time() * damage_numbers[i].timer / damage_numbers[i].max_timer * damage_numbers[i].size;
	damage_numbers[i].timer -= get_frame_time();
	if(damage_numbers[i].timer < 0.0)
	  delete damage_numbers[i];


}
context.globalAlpha  = 1.0;
//console.log(current_selection);

if(level_complete)
{
    switch_bgm(SONG_ENUM.BGM_VICTORY);

	win_state_timer += get_frame_time();


	

	//draw_text("  ", .55 * CANVAS_WIDTH, .05 * CANVAS_HEIGHT, 90* frame_scale);
	draw_text("Floor Complete!", .55 * CANVAS_WIDTH, .15 * CANVAS_HEIGHT, 70* frame_scale);

	var timer_f = 2.0 * (win_state_timer - .5);
	timer_f = clamp(timer_f, 0.0, 1.0);
	timer_f = Math.sqrt(timer_f);

	var timer_animation_value = timer_f * level_timer;

	var minutes = Math.floor(timer_animation_value / 60.0);
	var seconds = Math.floor(timer_animation_value - minutes * 60.0);
	var milliseconds = Math.floor(1000 * (timer_animation_value - minutes * 60.0 - seconds));

	if (milliseconds < 100) {milliseconds = "0" + milliseconds;}
	if (milliseconds < 10) {milliseconds = "0" + milliseconds;}

	if (seconds < 10) {seconds = "0" + seconds;}

	draw_text(minutes + "\'" + seconds + "\"" + milliseconds, 
	.55 * CANVAS_WIDTH, .3 * CANVAS_HEIGHT, 60* frame_scale);

	if (best_times[current_level] > level_timer) {

		best_times[current_level] = level_timer;
		for (var i = 0; i < 4; ++i)
			best_teams[current_level][i] = adventurer_field[i].id;
	}

    var rank = RANK_ENUM.F_RANK;
    for(var i in __floor_list[current_level].clear_times)
    {
        if(level_timer <= __floor_list[current_level].clear_times[i])
        {
            rank = i;
            break;
        }
	}
	
	var rank_f = 2.0 * (win_state_timer - 1.5);
	rank_f = clamp(rank_f, 0.0, 1.0);
	rank_f = Math.sqrt(rank_f);


	draw_center(rank_icons[rank], .85 * CANVAS_WIDTH, .3 * CANVAS_HEIGHT, 
		(2.0 - rank_f) * 100* frame_scale, (2.0 - rank_f) * 100* frame_scale, rank_f);

		
	var mult_f = 2.0 * (win_state_timer - 2.5);
	mult_f = clamp(mult_f, 0.0, 1.0);
	mult_f = Math.pow(mult_f, 2.0);

	draw_text("Multiplier : x" + multipliers[rank], .55 * CANVAS_WIDTH + .5 * CANVAS_WIDTH * (1.0 - mult_f),
	 .475 * CANVAS_HEIGHT, 60* frame_scale);

	 //weight up
	
	 var weight_f = .66 * (win_state_timer - 3.0);
	 weight_f = clamp(weight_f, 0.0, 1.0);
	 weight_f = Math.sqrt(weight_f);

	 if(win_state_timer < 2.0)
	{
		for(var i in adventurer_field)
		{
			adventurer_field[i].level_end_weight = 
			adventurer_field[i].current_stats[STAT_TYPE_ENUM.WEIGHT];

		}
	}

	if(win_state_timer > 2.0)
	{
		for(var i in adventurer_field)
		{
		    if (adventurer_field[i].level_end_weight > adventurer_field[i].level_start_weight)
		    {
		        adventurer_field[i].current_stats[STAT_TYPE_ENUM.WEIGHT] =
                adventurer_field[i].level_end_weight
                +
                weight_f * (multipliers[rank] - 1.0) *
                (adventurer_field[i].level_end_weight - adventurer_field[i].level_start_weight);
		    }
		}
	}

	for(var i in __floor_list[current_level].clear_rewards)
	{
		if(i < rank)
			continue;

			
		var reward_f = 2.0 * (win_state_timer - 3.0);
		reward_f = clamp(reward_f, 0.0, 1.0);
		reward_f = Math.pow(reward_f, 2.0);

		if(__floor_list[current_level].clear_rewards[i].type == REWARD_TYPE_ENUM.ITEM)
		{
		    if (reward_f >= 1.0 && play_grade_sfx_flag) {
		        grade_sfx.play();
		        play_grade_sfx_flag = false;
		    }
			if(!__reward_unlocked[current_level])
			{
				__item_list[__floor_list[current_level].clear_rewards[i].subtype].strength += 1;
				__reward_unlocked[current_level] = true;
			}

			if(__item_list[__floor_list[current_level].clear_rewards[i].subtype].strength == 1)
			{
				draw_text("New Item:", .6 * CANVAS_WIDTH+ .5 * CANVAS_WIDTH * (1.0 - reward_f), 
				.6 * CANVAS_HEIGHT, 60* frame_scale);
			}
			else
			{
				draw_text("Item Upgraded:", .6 * CANVAS_WIDTH+ .5 * CANVAS_WIDTH * (1.0 - reward_f), 
				.6 * CANVAS_HEIGHT, 60* frame_scale);
			}

			__item_list[__floor_list[current_level].clear_rewards[i].subtype].draw(
				.6 * CANVAS_WIDTH+ .5 * CANVAS_WIDTH * (1.0 - reward_f), .7 * CANVAS_HEIGHT, 60* frame_scale, 60* frame_scale);
				
			draw_text(__item_list[__floor_list[current_level].clear_rewards[i].subtype].name,
				.65 * CANVAS_WIDTH+ .5 * CANVAS_WIDTH * (1.0 - reward_f), .7 * CANVAS_HEIGHT, 60* frame_scale)

			//__item_list[__floor_list[current_level].clear_rewards[i].subtype].unlocked = true;
		}		

		if(__floor_list[current_level].clear_rewards[i].type == REWARD_TYPE_ENUM.CHARACTER)
		{
		    if (reward_f >= 1.0 && play_grade_sfx_flag) {
		        grade_sfx.play();
		        play_grade_sfx_flag = false;
		    }

			draw_text("Hero Unlocked:", .6 * CANVAS_WIDTH+ .5 * CANVAS_WIDTH * (1.0 - reward_f), 
			.6 * CANVAS_HEIGHT, 60* frame_scale);

			draw_center(__adventurer_list[__floor_list[current_level].clear_rewards[i].subtype].unlock_image,
				.6 * CANVAS_WIDTH+ .5 * CANVAS_WIDTH * (1.0 - reward_f), .7 * CANVAS_HEIGHT, 60* frame_scale, 60* frame_scale);
				
			draw_text(__adventurer_list[__floor_list[current_level].clear_rewards[i].subtype].name,
				.65 * CANVAS_WIDTH+ .5 * CANVAS_WIDTH * (1.0 - reward_f), .7 * CANVAS_HEIGHT, 60* frame_scale)

				__adventurer_list[__floor_list[current_level].clear_rewards[i].subtype].unlocked = true;

		}	
		
		if(__floor_list[current_level].clear_rewards[i].type == REWARD_TYPE_ENUM.BONUS_EXTRACT)
		{
		    if (reward_f >= 1.0 && play_grade_sfx_flag) {
		        grade_sfx.play();
		        play_grade_sfx_flag = false;
		    }
			draw_text("Bonus Extract", .6 * CANVAS_WIDTH+ .5 * CANVAS_WIDTH * (1.0 - reward_f), 
			.6 * CANVAS_HEIGHT, 60* frame_scale);

			draw_center(fat_texture,
				.6 * CANVAS_WIDTH+ .5 * CANVAS_WIDTH * (1.0 - reward_f), .7 * CANVAS_HEIGHT, 60* frame_scale, 60* frame_scale);
				
			
			draw_text("Unlocked!",
				.65 * CANVAS_WIDTH+ .5 * CANVAS_WIDTH * (1.0 - reward_f), .7 * CANVAS_HEIGHT, 60* frame_scale)
		
			if(!__reward_unlocked[current_level])
			{
				total_extracts -= 1;
				__reward_unlocked[current_level] = true;
			}
				//__adventurer_list[__floor_list[current_level].clear_rewards[i].subtype].unlocked = true;

		}	

	}

	if(win_state_timer > 5.0 && INPUT.left_triggered)
	{
		for(var i in __floor_list[current_level].clear_rewards)
		{
			if(i < rank)
				break;

			if(__floor_list[current_level].clear_rewards[i].type == REWARD_TYPE_ENUM.ITEM)
			{
				__item_list[__floor_list[current_level].clear_rewards[i].subtype].unlocked = true;
			}
		}

		//if(current_level == unlocked_levels)
			//unlocked_levels += 1;
		
		next_gamestate = GAMESTATE_ENUM.UPGRADES;
		save();

	}
}
else
{
    play_grade_sfx_flag = true;
}

//exit button

//for(var i = 0; i < 3; ++i)
if(!level_complete)
{
	var x =  CANVAS_WIDTH - (75)* frame_scale;
	var y = CANVAS_HEIGHT - 60 * frame_scale;

	var sz = 80* frame_scale;
	//if (speed_scalar == 2 * i + 1)
		//sz *= 1.5;

	if(draw_button(quit_button, i, x, y, (132.0 / 82.0) * sz, sz, ""))
	{
	    for (var i in item_field)
	    {
	        if (item_field[i])
	            item_field[i].cooldown = 0.0;
	    }

		for(var i in adventurer_field)
		{
			adventurer_field[i].current_stats[STAT_TYPE_ENUM.WEIGHT] += adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS];
			adventurer_field[i].current_stats[STAT_TYPE_ENUM.FULLNESS] = 0.0;
			adventurer_field[i].current_stats[STAT_TYPE_ENUM.ATTACK_TIMER] = 0.0;

			for(var j in adventurer_field[i].debuff_values)
			{
				adventurer_field[i].debuff_timers[j] = 0.0;
				adventurer_field[i].max_debuff_timers[j] = 0.0;
				adventurer_field[i].debuff_values[j] = 0;

			}
		}

		next_gamestate = GAMESTATE_ENUM.UPGRADES;
		save();
	}//	speed_scalar = 2 * i + 1;


	if (tutorial_mode)
	    tutorial_timer += 3.0 * get_frame_time();
	else
	    tutorial_timer -= 6.0 * get_frame_time();

	tutorial_lock_dismissal_timer += get_frame_time();
	if (tutorial_lock_dismissal_timer > 1.0 && INPUT.left_triggered)
	    tutorial_mode = false;

	tutorial_timer = clamp(tutorial_timer, 0.0, 1.0);


    if(tutorial_timer > 0.05)
    {
        var d = .75 * CANVAS_WIDTH * Math.sqrt(1.0 - tutorial_timer);

        draw_center(fade_texture, CANVAS_WIDTH * .5, CANVAS_HEIGHT * .5, CANVAS_WIDTH, CANVAS_HEIGHT, tutorial_timer);
        draw_center(fade_texture, CANVAS_WIDTH * .5, CANVAS_HEIGHT * .5, CANVAS_WIDTH, CANVAS_HEIGHT, tutorial_timer);

	    draw_center(tut_image_texture, CANVAS_WIDTH * .25-d, CANVAS_HEIGHT * .5, CANVAS_HEIGHT * .75, CANVAS_HEIGHT * .75, 1.0);
	    draw_center(__floor_list[current_level].rooms[room_counter].image, CANVAS_WIDTH * .25-d, CANVAS_HEIGHT * .5, CANVAS_HEIGHT * .68, CANVAS_HEIGHT * .68, 1.0);

	    draw_center(tut_text_texture, CANVAS_WIDTH * .725+d, CANVAS_HEIGHT * .5, CANVAS_WIDTH * .5, CANVAS_WIDTH * .5 * (201.0 / 545.0), 1.0);

	

	    var text_w = Math.sqrt((.8 * CANVAS_WIDTH * .5 * CANVAS_WIDTH * .5 * (201.0 / 545.0)) /
            (.75 * __floor_list[current_level].rooms[room_counter].messages.length));

	    //for(var i in __floor_list[current_level].rooms[room_counter].messages)
	    var room_text = __floor_list[current_level].rooms[room_counter].messages;
	    var text_counter = 0;
	    var place = 0;
	    var wrapped_text = [];
	    var threshold = 1.9 * (CANVAS_WIDTH * .45) / text_w;
	    var previous_space = 0;

	    for (var i in room_text) 
	    {
	        if (room_text[i] == ' ')
	            previous_space = i;

	        if (text_counter > threshold) {
	            wrapped_text.push(room_text.slice(place, previous_space))
	            place = previous_space;
	            text_counter = 0;
	            i = previous_space;

	            ++place;
	            //debugger;
	        }
	        else {


	            ++text_counter;
	        }
	    }

	    wrapped_text.push(room_text.slice(place));

	    for (var i in wrapped_text) {
	        //if(current_level == 0)
	        draw_text(wrapped_text[i],
              CANVAS_WIDTH * .725 - .4 * (CANVAS_WIDTH * .5)+d,
              CANVAS_HEIGHT * .5 - .4 * (CANVAS_WIDTH * .5 * (201.0 / 545.0)) + (i) * text_w + text_w,
              text_w);
	        //else
	        //draw_text(wrapped_text[i], 550* frame_scale, CANVAS_HEIGHT - 150* frame_scale + 30 * i* frame_scale, 22* frame_scale);
	    }

	    var title_w = 2.0 * .4 * CANVAS_WIDTH / __floor_list[current_level].rooms[room_counter].title.length;
	    
	    if(1.5 * text_w < title_w)
	        title_w = 1.5 * text_w;

	    draw_text(__floor_list[current_level].rooms[room_counter].title,
              CANVAS_WIDTH * .725 - .4 * (CANVAS_WIDTH * .5)+d,
              CANVAS_HEIGHT * .5 - .55 * (CANVAS_WIDTH * .5 * (201.0 / 545.0)),
              title_w);
	}

}

/*
adventurer_field[3].draw(INPUT.mouse_screen.x, INPUT.mouse_screen.y, 20, 20);
  if(INPUT.left_triggered)
    adventurer_field[3].draw(INPUT.mouse_screen.x, INPUT.mouse_screen.y, 50, 50);
  if(INPUT.left_pressed)
    adventurer_field[3].draw(INPUT.mouse_screen.x, INPUT.mouse_screen.y, 30, 30);
*/

	//for(var key in adventurer_field)
	//{
	//	adventurer_field[key].draw(300, 300, 400, 600);
	//}
	// context
	//context.Rect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);


	if (clear_selection && INPUT.left_released)
		current_selection = -1;
}