var healthColours = new Array();
healthColours[0] = 'f50f0f';
healthColours[1] = 'ffa800';
healthColours[2] = '1aa41d';

var BATTLEID;
var MOVE;
var maxItems;

var PLAYERS;
var thisPlayer;

var FINISHED = false;
var LOADING = false;

var selected=0;

function startQuickBattle (petid, oppid, name, image) {
	// TODO: Starts a battle from scratch with ajax calls. For random events in the future
}

function launchQuickBattle (battleid) { // Launches battle given fact that id is already initiated
	
	showOverlay();
	new Effect.Appear('quickbattle', {duration: 0.75, queue: 'end'});
	
	new Ajax.Request("http://www.verpets.com/coliseum/ajax/quickbattle/loadBattle.php?battleid="+battleid+'&rand='+Math.random(),
	{
		method:'get',
		onSuccess: function (r) { gotQuickBattle(r); },
		onFailure: function(){ alert('Quick Battle Error!') }
	});
	
}

function closeQuickBattle () {
	
	new Effect.Fade('quickbattle', {duration: 0.75});
	hideOverlay();
	
}

function gotQuickBattle (r) {
	
	if (r.responseText.substr(0,5) == 'ERROR') {
		alert('An error occurred loading your battle: '+r.responseText.substr(7));
		return;
	}
	
	$('quickbattle-content-hold').style.height = '59px';
	
	new Effect.Fade('quickbattle-content', {duration: 0.25, queue: 'end', 
											afterFinish: function (effect) { 
												$('quickbattle-content').innerHTML = r.responseText;
												
												// hack: grab height by showing and then quickly hiding element
												$('quickbattle-content').style.display = 'block';
												var height = $('quickbattle-content').offsetHeight;
												$('quickbattle-content').style.display = 'none';

												new Effect.Morph('quickbattle-content-hold', {style: 'height: '+height+'px', duration: 0.75});
												new Effect.Appear('quickbattle-content', {duration: 0.5, queue: 'end', afterFinish: function (effect) {
													if ($('quickbattle-jstoeval')) eval($('quickbattle-jstoeval').innerHTML);
												}});
											
											}});
	
}

function initQuickBattle () {
	for (var i = 0; i<PLAYERS.length; i++) {
		setHealthBar(i, PLAYERS[i][1]);
	}
}

function quickBattle_selectItem (id) {
	if (LOADING == true) return;
	
	if ($('weaponuse['+id+']').value == 'no') {
		if (selected==maxItems) {
			alert('You can only select a maximum of '+maxItems+' items per move!');
		} else {
			$('item_'+id).style.padding='1px';
			$('item_'+id).style.border='2px solid #505050';
			$('weaponuse['+id+']').value='yes';
			selected=selected+1;
		}
	} else {
		$('item_'+id).style.padding='3px';
		$('item_'+id).style.border='0px';
		$('weaponuse['+id+']').value='no';
		selected=selected-1;
	}
}

function setHealthBar (player, health) {
	
	var max = PLAYERS[player][2];
	var percent = (health/max)*100;
	
	var numColours = healthColours.length;
	var colourDivision = 100/numColours;
	
	var division;
	
	for (var i = 1; i<=numColours; i++) {
		if (colourDivision*i >= percent && colourDivision*(i-1) <= percent) {
			division=(i-1);
			break;
		}
	}
	
	$('health_'+player).style.width = percent+'px';
	$('health_'+player).style.backgroundColor = '#'+healthColours[division];
	
	$('currHealth_'+player).style.color='#'+healthColours[division];
	$('currHealth_'+player).innerHTML=number_format(health);
	
	$('maxHealth_'+player).style.color='#'+healthColours[division];
	
	PLAYERS[player][1]=health;
	
}

function setHealthValue (player, health) {

	var max = PLAYERS[player][2];
	var percent = (health/max)*100;

	var numColours = healthColours.length;
	var colourDivision = 100/numColours;
	
	var division;
	
	for (var i = 1; i<=numColours; i++) {
		if (colourDivision*i >= percent && colourDivision*(i-1) <= percent) {
			division=(i-1);
			break;
		}
	}

	$('currHealth_'+player).style.color='#'+healthColours[division];
	$('currHealth_'+player).innerHTML=number_format(health);
	
	$('maxHealth_'+player).style.color='#'+healthColours[division];

}

function animateHealthChange (player, health) {
	
	var max = PLAYERS[player][2];
	var percent = (health/max)*100;
	
	var numColours = healthColours.length;
	var colourDivision = 100/numColours;
	
	var division;
	
	for (var i = 1; i<=numColours; i++) {
		if (colourDivision*i >= percent && colourDivision*(i-1) <= percent) {
			division=(i-1);
			break;
		}
	}
	
	new Effect.Morph('health_'+player, {
		style: 'width: '+percent+'px; background-color: #'+healthColours[division]+';', 
		duration: 0.5,
		queue: 'end',
		afterFinish: function (effect) { setHealthValue(player, health); }
	});
	
	new Effect.Pulsate('playerContain_'+player, { pulses: 2, duration: 0.75, queue: 'end' });
	
	PLAYERS[player][1]=health;
	
}

function quickBattle_startLoading () {
	LOADING=true;
	
	$('quickbattle-attackpanel').style.opacity = 0.5;
	$('quickbattle-attackpanel').style.filter  = "alpha(opacity=" + 50 + ")";
	$('quickbattle-loading').style.display = 'block';
}

function quickBattle_stopLoading () {
	LOADING=false;
	
	$('quickbattle-attackpanel').style.opacity = 1;
	$('quickbattle-attackpanel').style.filter  = "alpha(opacity=" + 100 + ")";
	$('quickbattle-loading').style.display = 'none';
}

function quickBattle_submitAttack () {
	
	if (FINISHED) return;
	if (LOADING) return;
	
	quickBattle_startLoading();
	
	$('quickbattle-loading-status').innerHTML = 'Submitting Attack';
	
	new Ajax.Request("http://www.verpets.com/coliseum/attack",
	{
		method:'post',
		parameters: Form.serialize("attack"),
		onSuccess: function (r) { quickBattle_submit_response(r); }, // because quickbattles are always vs 1 player opp, we know the response will be a log... hopefully, unless something went VERY wrong :(
		onFailure: function(){ alert('Quick Battle Error!') }
	});
	
	$('attack').disable();
	
}

function quickBattle_submit_response (r) {

	if (FINISHED == true) return;
	
	$('quickbattle-loading-status').innerHTML = 'Move in Progress! Watch Out!';
	
	MOVE++;
	
	var logs = r.responseXML;
	
	var i;
	var n;
	var h;
	var log;
	var text;
	var icon;
	var iconplayer;
	var iconhtml;
	var logid;
	var thisLog;
	var healthchange;
	var playerid;
	var newHealth;
	var playn;
	var image;
	
	for ( i = 0; i < logs.getElementsByTagName('log').length; i++) {
		
		log = logs.getElementsByTagName('log')[i];
		
		logid = log.getElementsByTagName('logid')[0].firstChild.nodeValue;
		text = log.getElementsByTagName('text')[0].firstChild.nodeValue;
		image = log.getElementsByTagName('image')[0].firstChild.nodeValue;
		
		thisLog = text;
		
		for (n = 0; n < log.getElementsByTagName('icons').length; n++) {
			
			icon = log.getElementsByTagName('icons')[n];
			
			iconplayer = icon.getElementsByTagName('playername')[0].firstChild.nodeValue;
			iconhtml = icon.getElementsByTagName('iconhtml')[0].firstChild.nodeValue;
			
			if (log.getElementsByTagName('icons').length > 1) {
				thisLog = thisLog + '<div class="spacer"></div>&nbsp;&nbsp;&nbsp;&nbsp;<b>' + iconplayer + '</b> [ ' + iconhtml + ' ] <br><div class="spacer"></div>';
			} else {
				thisLog = thisLog + '<br><div class="spacer"></div>&nbsp;&nbsp;&nbsp;&nbsp;[ ' + iconhtml + ' ] <br><div class="spacer"></div>';
			}
			
		}
		
		$('quickbattle-fightlog').insert({top: new Element("div", { id: 'log'+logid, style: 'display: none;' })});
		
		$('log'+logid).innerHTML='<table width="100%" style="margin-bottom: 4px;"><tr><td width="1%" valign="top"><img SRC="'+image+'" width="70" height="70"></td><td width="99%" valign="top">'+thisLog+'</td></tr></table>';
		
		if (i == (logs.getElementsByTagName('log').length-1)) {
			//console.log('last found');
			new Effect.BlindDown('log'+logid, {duration: 0.6, queue: 'end', afterFinish: function (effect) { quickBattle_refreshAttackPanel(); }});
		} else {
			//console.log('not last, '+logs.getElementsByTagName('log').length+' i = '+i);
			new Effect.BlindDown('log'+logid, {duration: 0.6, queue: 'end'});
		}
		
		for (h = 0; h < log.getElementsByTagName('healthchange').length; h++) {
			
			healthchange=log.getElementsByTagName('healthchange')[h];
			
			playerid=healthchange.getElementsByTagName('playerid')[0].firstChild.nodeValue;
			newHealth=healthchange.getElementsByTagName('newhealth')[0].firstChild.nodeValue;
			
			playn = window['player' + playerid];
			
			animateHealthChange(playn, newHealth);
			
		}
		
	}
	
}

function quickBattle_refreshAttackPanel() {
	
	new Ajax.Request("http://www.verpets.com/coliseum/ajax/quickbattle/battleAttackPanel.php?battleid="+BATTLEID+"&rand="+Math.random(),
	{
		method:'get',
		onSuccess: function (r) { 
			$('quickbattle-attackpanel').innerHTML=r.responseText;
			if ($('quickbattle-planner-jstoeval')) eval($('quickbattle-planner-jstoeval').innerHTML);
			quickBattle_stopLoading();
			selected=0;
		},
		onFailure: function(){ alert('Quick Battle Error!') }
	});
	
}