var GameStatus = {
	start : 0,
	running : 1,
	end : 2
};

var GamePhase = {
	distribute : 'Einheiten verteilen',
	attack : 'Angriff',
	move : 'Bewegen'
};

var alert = function(str) {
	$('#Ausgabe').text(str);
	$('#Ausgabe').animate({
		'font-size': '3em'
	}, 250).delay(250).animate({
		'font-size': '1.5em'
	}, 250);
};

var Game = function() {
	this.currentPlayer = undefined;
	this.status = GameStatus.start;
	this.phase = GameStatus.distribute;
	this.counties = [];
	this.county_attack= undefined;
	this.county_get_attacked=undefined;
	this.county_moveable= undefined;
	this.count = 0;
	this.players = [];
};

Game.prototype.attack_cmd = function(phase) {
	$('#Ausgabe').empty();
	this.phase = GamePhase.attack;
	$('#Laender_angreifen').prop("disabled", true);
};
Game.prototype.units_move_cmd = function(phase) {
	$('#Ausgabe').empty();
	this.phase = GamePhase.move;
	this.currentPlayer.units=0;
	this.updateInfo();
	$('#Laender_angreifen').prop("disabled", true);
	$('#Einheiten_bewegen').prop("disabled", true);
};

Game.prototype.updateInfo = function() {
	$('#aktueller_Spieler').val(this.currentPlayer.name);
	$('#Spieler_farbe').text("_____").css({
		width: 50,
		backgroundColor: this.currentPlayer.color,
		color: this.currentPlayer.color
	});
	$('#Anfangs_Einheiten').val(this.currentPlayer.units);
};

Game.prototype.victory_prove = function(){
	var test=0;
	for (var i = this.counties.length - 1; i >= 0; i--)
			if(this.counties[i].owner === this.currentPlayer){
					test++;
			}
	if(test===13){
		alert('Sie haben gewonnen!');
		this.status = GameStatus.end;
		$('#Laender_angreifen').prop("disabled", true);
		$('#Einheiten_bewegen').prop("disabled", true);
		$('#Naechster_Spieler').prop("disabled", true);
	}	

}

Game.prototype.addPlayer = function(player) {
	this.players.push(player);

	if (this.currentPlayer === undefined)
		this.currentPlayer = player;
};

Game.prototype.addCounty = function(county) {
	this.counties.push(county);
};

Game.prototype.removeUnits = function(county) {
			if(county.owner===this.currentPlayer && county.units>1)
			{   county.owner.units++;
				county.units--;
				$('#Anfangs_Einheiten').val(this.currentPlayer.units);
				$('#Einheiten').val(county.units);
				county.updateText();
		    }else alert('Sie haben nur eine Einheit in diesem land oder es ist nicht ihr Land!')
};

Game.prototype.revert = function(county) {
	switch (this.status) {
		case GameStatus.start:
			if (county.freeunits.length !== 0){
						    county.freeunits.splice(county.freeunits.length-1, 1);
							this.removeUnits(county);

					} else 
							alert('Sie können nur die Einheiten zurück nehmen die sie in dieser Runde verteilen dürfen!');

					break;

		case GameStatus.running:
			switch (this.phase) {
				case GamePhase.distribute:
					if (county.freeunits.length !== 0){
						    county.freeunits.splice(county.freeunits.length-1, 1);
							this.removeUnits(county);

					} else 
							alert('Sie können nur die Einheiten zurück nehmen die sie in dieser Runde verteilen dürfen!');

					break;

				case GamePhase.attack:
					if(county.owner===this.currentPlayer && county.units >= 2)
					{	this.county_attack=county;
				
					}else alert("Sie haben in " +county.id + " zu wenig Einheiten um von diesem Land angreifen zu können oder" +county.id +" ist nicht ihr Land!");
					
					break;
				
				case GamePhase.move:
					if(county.units>1 && county.owner === this.currentPlayer){	
						if(this.county_moveable === undefined || this.county_moveable === county){	
							this.county_moveable = county;
							this.currentPlayer.units++;
							county.units--;
							this.updateInfo();
							$('#Einheiten').val(county.units);
							county.updateText();
						}
					}else alert("Sie haben in " +county.id + " zu wenig Einheiten um von diesem Land Einheiten zu verschieben oder" +county.id +" ist nicht ihr Land!");
					break;

			}

			break;
	}	
};

Game.prototype.distribute = function(county) {
	if (this.currentPlayer !== county.owner) {
		alert('Dies ist nicht Ihr Land!');
		return false;
	}

	return county.distribute();
};

Game.prototype.createHandlers = function(county) {
	var game = this;
	county.handlers['contextmenu'] = function(ev) {
		ev.preventDefault();
		$('#Ausgabe').empty();
		game.revert(county);
	};

	county.handlers['click'] = function(ev) {
		$('#Ausgabe').empty();
		switch (game.status) {
			case GameStatus.start:
				var test1=game.distribute(county);
				if (test1)
							county.freeunits.push(1);
				break;

			case GameStatus.running:
				switch (game.phase) {
					case GamePhase.distribute: 
						var test2 = game.distribute(county);
						if (test2)
							county.freeunits.push(1);
					break;
					case GamePhase.attack:
						if(game.county_attack.neighbors.indexOf(county.id)!==-1 && game.county_attack.units > 1 && game.county_attack.owner === game.currentPlayer) {	
							county.attack(game.county_attack,county);
						}
						break;
					case GamePhase.move:
						if(game.county_moveable!== undefined){
							if(game.currentPlayer.units>0 && game.currentPlayer === county.owner){									
									if(game.county_moveable === county || game.county_moveable.neighbors.indexOf(county.id)!==-1 ){
										game.currentPlayer.units--;
										county.units++;
										game.updateInfo();
										$('#Einheiten').val(county.units);
										county.updateText();
										if(game.currentPlayer.units===0){
											game.county_moveable=undefined;
										}
									}else alert("Kein Nachbarland ausgewählt!");
							}else alert("Sie haben keine Einheiten mehr um sie zu bewegen oder es ist nicht ihr Land!");	
						}else alert("Sie müssen erst Einheiten aus einem Land auswählen!");
					break;	
				}
				
				break;
		}
	};

	county.handlers['mouseover'] = function(ev) {
		if (game.status === GameStatus.start)
			$('#Anfangs_Einheiten').val(game.currentPlayer.units);

		$('#Land').val(county.id);
		$('#Besitzer').val(county.owner.name);
		$('#Einheiten').val(county.units);
	};
};

Game.prototype.bindEvents = function() {
	for (var i = this.counties.length; i--; ) {
		var county = this.counties[i];
		this.createHandlers(county);
		var handlerKeys = Object.keys(county.handlers);

		for (var j = handlerKeys.length; j--; ) {
			var key = handlerKeys[j];
			$(county.svg_element).bind(key, county.handlers[key]);
		}
	}
};

Game.prototype.unbindEvents = function() {
	for (var i = this.counties.length; i--; ) {
		var county = this.counties[i];
		var handlerKeys = Object.keys(county.handlers);

		for (var j = handlerKeys.length; j--; ) {
			var key = handlerKeys[j];
			$(county.svg_element).unbind(key, county.handlers[key]);
		}
	}
};

Game.prototype.changePlayer = function() {
	$('#Ausgabe').empty();

	var index = this.players.indexOf(this.currentPlayer);
	this.currentPlayer = this.players[(index + 1) % this.players.length];
	this.count++;

	if (this.count === 2) {
		this.status = GameStatus.running;

		for (var i = this.players.length - 1; i >= 0; i--)
			this.players[i].units = $('#EinheitenProRunde').val();
	}

	if (this.count >= 2) {
		this.phase = GamePhase.distribute;
		for (var i = this.players.length - 1; i >= 0; i--)
			this.players[i].units = $('#EinheitenProRunde').val();
		$('#Laender_angreifen').prop("disabled", false);
		$('#Einheiten_bewegen').prop("disabled", false);
		for(var i= this.counties.length-1;i>=0;i--)
		{
			this.counties[i].freeunits.splice(0,this.counties[i].freeunits.length);
		}
	}

	this.updateInfo();
};

Game.prototype.start = function() {
	this.bindEvents();
	this.updateInfo();
};

var Player = function(name, color){
	this.name = name;
	this.color = color;
	this.units = $('#StartEinheiten').val();;	
};

var County = function(id, owner, neighbors){
	this.id = id;
	this.owner = owner;
	this.freeunits = [];
	this.units = $('#StartEinheitenProLand').val();
	this.neighbors = neighbors;
	this.svg_element = $('#'+this.id)[0];
	this.svg_element.style.fill = this.owner.color;
	this.svg_Text = $("#"+this.id+"_Text");
	this.handlers = { };

	this.updateText = function()
	{
		if(this.owner.color == '#F00')
			this.svg_Text.css({fill: '#000'});
		else
			this.svg_Text.css({fill: '#CCC'});
		this.svg_Text.text(this.units);
	};

	this.updateText();

};	

County.prototype.distribute = function() {
	if (this.owner.units === 0) {
		alert('Sie haben keine Einheiten mehr zu verteilen!');
		return false;
	}

	$('#Anfangs_Einheiten').val(--this.owner.units);
	$('#Einheiten').val(++this.units);
	this.updateText();
	return true;
};

County.prototype.attack = function(county_attack,county) {
	
if(county_attack.owner !== county.owner)
{	
	game.county_get_attacked=county;
	toggleKampf();
	$('#KampfMusik').get(0).play();
	if(county_attack.owner.color==="#F00")
	$('#KampfUeberschrift').html('Kampf<br> <span style="color: ' + county_attack.owner.color + '; background-color: '+ county_attack.owner.color + '">____</span> vs. <span style="color: ' + county.owner.color + '; background-color: '+ county.owner.color + '">____</span><br>'+ county_attack.id + ' vs. ' + county.id+ '<br>' +county_attack.units+ ' vs. ' + county.units);
	if(county_attack.owner.color==="#00F")
	$('#KampfUeberschrift').html('Kampf<br> <span style="color: ' + county.owner.color + '; background-color: '+ county.owner.color + '">____</span> vs. <span style="color: ' + county_attack.owner.color + '; background-color: '+ county_attack.owner.color + '">____</span><br>'+ county.id + ' vs. ' + county_attack.id+ '<br>' +county.units+ ' vs. ' + county_attack.units);	
	
	$('#WeiterKaempfen').prop("disabled", false);

	attackStep(county_attack,county);
	}
	
};
var attackStep= function(county_attack,county) {
		var att_before,att_lost,def_before,def_lost;
		var def= county.units;
		var att = county_attack.units;
		var def_cube=[0,0,0];
		var att_cube=[0,0,0];
	
		if(def*1 === 1){
		def_cube[0]= Math.round(Math.random()*5+1);
		}				
		if(def*1>1){
			def_cube[0]= Math.round(Math.random()*5+1);
			def_cube[1]= Math.round(Math.random()*5+1);
			def_cube.sort(function(a,b) {
	    				return b-a;
			});
		}
		if(att*1 ===2){
			att_cube[0]= Math.round(Math.random()*5+1);
		}
		if(att*1 ===3){
			att_cube[0]= Math.round(Math.random()*5+1);
			att_cube[1]= Math.round(Math.random()*5+1);
			att_cube.sort(function(a,b) {
	    				return b-a;
			});
		}
		if(att*1 >3){
			att_cube[0]= Math.round(Math.random()*5+1);
			att_cube[1]= Math.round(Math.random()*5+1);
			att_cube[2]= Math.round(Math.random()*5+1);
			att_cube.sort(function(a,b) {
	    				return b-a;
			});
		}
		
		att_before=att*1;
		def_before=def*1;
		if(def_cube[0]>=att_cube[0]){
			att--;
		}else def--;
		if(def_cube[1] !== 0 && att_cube[1] !== 0){
			if(def_cube[1]>=att_cube[1]){
				att--;
			}else def--;
		}
		att_lost= att-att_before;
		def_lost=def-def_before;
	
		if(county_attack.owner.color ==="#F00")
		{
			if(att_before===2 && def_before===1)$('#AngriffMitteText').html(att_cube[0] + '	 	vs. 		' + def_cube[0] + '<br>'+att_lost+' 					 	'+def_lost);
			if(att_before===2 && def_before>=2)$('#AngriffMitteText').html(att_cube[0] + '	 	vs. 		' + def_cube[0] + '<br>-	 	vs. 		' + def_cube[1] + '<br>'+att_lost+' 					 	'+def_lost);
			if(att_before===3 && def_before===1)$('#AngriffMitteText').html(att_cube[0] + ' 		vs. 		' + def_cube[0] + '<br>' + att_cube[1] + ' 		vs. 		-<br>'+att_lost+' 					 	'+def_lost);
			if(att_before===3 && def_before>=2)$('#AngriffMitteText').html(att_cube[0] + ' 		vs. 		' + def_cube[0] + '<br>' + att_cube[1] + ' 		vs. 		'+def_cube[1]+'<br>'+att_lost+' 					 	'+def_lost);
			if(att_before>3 && def_before===1)$('#AngriffMitteText').html(att_cube[0] + ' 		vs. 		' + def_cube[0] + '<br>' + att_cube[1] + ' 		vs. 		-<br>' + att_cube[2] + ' 		vs. 		-<br>'+att_lost+' 					 	'+def_lost);
			if(att_before>3 && def_before>=2)$('#AngriffMitteText').html(att_cube[0] + ' 		vs. 		' + def_cube[0] + '<br>' + att_cube[1] + ' 		vs. 		'+def_cube[1]+'<br>' + att_cube[2] + ' 		vs. 		-<br>'+att_lost+' 					 	'+def_lost);

			$('#Angriff1Text').html(att);
			$('#Angriff2Text').html(def);
		}
		if(county_attack.owner.color === "#00F")
		{
			if(att_before===2 && def_before===1)$('#AngriffMitteText').html(def_cube[0] + '	 	vs. 		' + att_cube[0] + '<br>'+def_lost+' 					 	'+att_lost);
			if(att_before===2 && def_before>=2)$('#AngriffMitteText').html(def_cube[0] + '	 	vs. 		' + att_cube[0] + '<br>'+def_cube[1] + '	 	vs. 		-<br>'+def_lost+' 					 	'+att_lost);
			if(att_before===3 && def_before===1)$('#AngriffMitteText').html(def_cube[0] + ' 		vs. 		' + att_cube[0] + '<br>- 		vs. 		' + att_cube[1] + '<br>'+def_lost+' 					 	'+att_lost);
			if(att_before===3 && def_before>=2)$('#AngriffMitteText').html(def_cube[0] + ' 		vs. 		' + att_cube[0] + '<br>'+def_cube[1]+' 		vs. 		' + att_cube[1] + '<br>'+def_lost+' 					 	'+att_lost);
			if(att_before>3 && def_before===1)$('#AngriffMitteText').html(def_cube[0] + ' 		vs. 		' + att_cube[0] + '<br>- 		vs. 		' + att_cube[1] + '<br>- 		vs. 		' + att_cube[2] + '<br>'+def_lost+' 					 	'+att_lost);
			if(att_before>3 && def_before>=2)$('#AngriffMitteText').html(def_cube[0] + ' 		vs. 		' + att_cube[0] + '<br>' + def_cube[1] + ' 		vs. 		' + att_cube[1] + '<br>- 		vs. 		' + att_cube[2] + '<br>'+def_lost+' 					 	'+att_lost);
			$('#Angriff1Text').html(def);
			$('#Angriff2Text').html(att);
		}
		
		$('#AngriffMitteText').animate({
		'font-size': '1.5em'
			}, 250).delay(250).animate({
		'font-size': '1em'
			}, 250);
			$('#Angriff1Text').animate({
		'font-size': '2.4em'
			}, 250).delay(250).animate({
		'font-size': '2.4em'
			}, 250);
			$('#Angriff2Text').animate({
		'font-size': '2.4em'
			}, 250).delay(250).animate({
		'font-size': '2.4em'
			}, 250);

		
		if (att>1 && def>0) {
			$('#WeiterKaempfen').prop("disabled", false);
			$('#Close').prop("disabled", false);
			county.units=def;
			county_attack.units=att;
			county.updateText();
			county_attack.updateText();
			
		} else {
			
			$('#Close').prop("disabled", false);
			$('#WeiterKaempfen').prop("disabled", true);
			if(def *1 ===0){
				county.owner = county_attack.owner; 
				county.svg_element.style.fill = county.owner.color;
				county.units = att-1;
				county_attack.units=1;
				game.victory_prove();
				$('#Einheiten').val(county.units);
				county.updateText();
				county_attack.updateText();
			}else{		
				county.units=def;
				county_attack.units=att;
				county.updateText();
				county_attack.updateText();
			}	
		}
		def_cube=[0,0,0];
		att_cube=[0,0,0];
};


function toggleKampf() {
	var kampf = $("#Kampf");
	$('#KampfMusik').get(0).pause();
	$('#Close').prop("disabled", true);
	kampf.toggleClass("hidden");
	kampf.toggleClass("visible");

}

$('#Close').click(function(){
	toggleKampf();
	game.county_get_attacked=undefined;

});

$('#WeiterKaempfen').click(function(){
			attackStep(game.county_attack,game.county_get_attacked);
		});

function toggleAnleitung() {
	var Anleitung = $("#Anleitung");
	Anleitung.toggleClass("hidden");
	Anleitung.toggleClass("visible2");

}
$('#SpielAnleitung').click(function(){
	toggleAnleitung();
});
$('#CloseAnleitung').click(function(){
	toggleAnleitung();
});
