/*
- make sure all filenames are clean, e.g. no spaces and umlauts
*/

var rootMesh = null;
var shadowGenerator;
var babylonUI;
var arcBallCamera;
var globalAnimationList = [];



const STARTING_GOLD = 20;

const GROUNDWIDTH = 12;
const GROUNDHEIGHT = 5;

const EMPTY = 0;
const CORE = 1;
const GOLDMINE = 2;
const SPAWNER = 3;
const TURRET = 4;
const FLYING_SPAWNER = 5;
const ARCHER_SPAWNER = 6;

const GOLDMINE_PRICE = 15;
const SPAWNER_PRICE = 25;
const TURRET_PRICE = 40;
const FLYING_SPAWNER_PRICE = 40;
const ARCHER_SPAWNER_PRICE = 30;

const MOUSE_DEFAULT = 0;
const MOUSE_BUILD = 1;
var mouseMode = MOUSE_DEFAULT;
var selectedBuilding;

var map;
var player;
var aiPlayer;
var tileHoverQuad;

var buildings = [];
var entities = [];


var backgroundMusic = new Audio( "sounds/music_1.ogg" );
var backgroundMusicIsPlaying = false;

var sound_building = new Audio( "sounds/building.ogg" );
var sound_buildingDestroyed = new Audio( "sounds/building_destroyed.ogg" );
var sound_victory = new Audio( "sounds/victory.ogg" );
var sound_defeat = new Audio( "sounds/defeat.ogg" );
var sound_buttonHover = new Audio( "sounds/button_hover.ogg" );
var sound_coreHit = new Audio( "sounds/core_hit.ogg" );
var sound_minerDead = new Audio( "sounds/miner_dead.ogg" );
var sound_wyvernDead = new Audio( "sounds/wyvern_dead.ogg" );
var sound_archerDead = new Audio( "sounds/archer_dead.ogg" );
var sound_upgrade = new Audio( "sounds/upgrade.ogg" );



function createScene()
{
    // Create a basic BJS Scene object
    var scene = new BABYLON.Scene( engine );
    // scene.clearColor = BABYLON.Color3.FromHexString( "#dddddd" );
    scene.clearColor = new BABYLON.Color3( 0 , 0 , 0 );

    scene.environmentTexture = new BABYLON.CubeTexture("environment.env", scene);

    // fog 
    // scene.fogMode = BABYLON.Scene.FOGMODE_EXP;
    // scene.fogDensity = 0.01;
    // scene.fogColor = BABYLON.Color3.FromHexString( "#C8E1FF" );

    scene.fogMode = BABYLON.Scene.FOGMODE_LINEAR;
    scene.fogStart = 7.0;
    scene.fogEnd = 15.0;
    scene.fogColor = BABYLON.Color3.FromHexString( "#555555" );
	

    // arc ball camera
    arcBallCamera = new BABYLON.ArcRotateCamera( 'arcRotateCamera' , -Math.PI/2 , Math.PI/2-1 , 7 , new BABYLON.Vector3( -3 , 0.1 , 0 ) , scene );
    arcBallCamera.attachControl( canvas , true );
    arcBallCamera.allowUpsideDown = false;
    arcBallCamera.lowerRadiusLimit = 3;
    arcBallCamera.upperRadiusLimit = 8;
    arcBallCamera.wheelPrecision = 50;
    arcBallCamera.speed = 0.01;
    // dont allow rotating below the ground
    arcBallCamera.upperBetaLimit = Math.PI/2-0.8;
    arcBallCamera.lowerBetaLimit = Math.PI/2-1.2;
    arcBallCamera.upperAlphaLimit = -Math.PI/2+1;
    arcBallCamera.lowerAlphaLimit = -Math.PI/2-1;
    // lower the near plane
    arcBallCamera.minZ = 0.01;
    // collisions
    arcBallCamera.checkCollisions = true;
    arcBallCamera.ellipsoid = new BABYLON.Vector3(.5 , .5 , .5 );
	
	// disable camera movement completely, now it can only rotate
	// arcBallCamera.panningSensibility = 0;



	// directional light
    var lightDirection = new BABYLON.Vector3( -0.5 , -1 , 0.3 );
    var light = new BABYLON.DirectionalLight( "DirectionalLight" , lightDirection , scene );
    // position is needed for shadows ...
    light.position = new BABYLON.Vector3( 0 , 10 , 0 );
    light.intensity = 0.8;
	
	// ambient light
    var ambientLight = new BABYLON.HemisphericLight( "AmbientLight" , new BABYLON.Vector3( 0 , 10 , 0 ) , scene );
    ambientLight.intensity = 0.8;
	
	

    shadowGenerator = new BABYLON.ShadowGenerator( 2048 , light );
    shadowGenerator.usePercentageCloserFiltering = true;
    // [0,1] > 0 = strong shadow , 1 = no shadow
    shadowGenerator.setDarkness( 0 );
    shadowGenerator.bias = 0.000001;
	
	
	// // test sphere
	// var sphere = BABYLON.MeshBuilder.CreateSphere( "Sphere" , {} , scene );
	// sphere.position.y = 0.7;
	// sphere.scaling.x = 0.5;
	// sphere.scaling.y = 0.5;
	// sphere.scaling.z = 0.5;
	// sphere.setEnabled( true ); // false == hidden
	
	// // make the sphere cast a shadow
	// shadowGenerator.getShadowMap().renderList.push( sphere );
	
	// ground material
    var groundMaterial = new BABYLON.StandardMaterial( "groundMaterial" , scene );
    // groundMaterial.ambientColor = new BABYLON.Color3( .5 , .5 , .5 );
    // groundMaterial.diffuseColor = new BABYLON.Color3( .3 , .3 , .3 );
    groundMaterial.specularColor = new BABYLON.Color3( 0 , 0 , 0 );
    groundMaterial.diffuseTexture = new BABYLON.Texture( "img/ground_texture.png" , scene );

    // ground plane
    var ground = BABYLON.Mesh.CreateGround( "Ground" , GROUNDWIDTH , GROUNDHEIGHT , 2 , scene , false );
    ground.receiveShadows = true;
    ground.material = groundMaterial;
	
	// ui
    // babylonUI = BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI( "UI" );	


    // // tests
	// var wall = BABYLON.MeshBuilder.CreateBox( "Box" , {} , scene );
	// wall.position.x = -3;
	// wall.scaling.x = 0.1;
	// wall.scaling.y = 0.5;
	// wall.scaling.z = 5;
	// var wall2 = BABYLON.MeshBuilder.CreateBox( "Box" , {} , scene );
	// wall2.position.x = 3;
	// wall2.scaling.x = 0.1;
	// wall2.scaling.y = 0.5;
	// wall2.scaling.z = 5;

    // INIT
    map = new Map( GROUNDWIDTH*2 , GROUNDHEIGHT*2 );

    player = new Player( 1 );
    aiPlayer = new Player( 2 );
    player.spawnCore( scene , -5.5 );
    aiPlayer.spawnCore( scene , 5.5 );

    // TMP build a spawner for the enemy player
    //constructBuilding( 20 , 3 , aiPlayer , SPAWNER , scene );
    //constructBuilding( 20 , 3 , aiPlayer , ARCHER_SPAWNER , scene );
    // player.gold = 100;
    // constructBuilding( 3 , 3 , player , SPAWNER , scene );
    // constructBuilding( 3 , 2 , player , SPAWNER , scene );
    // constructBuilding( 3 , 1 , player , SPAWNER , scene );
    // constructBuilding( 3 , 4 , player , SPAWNER , scene );

    tileHoverQuad = BABYLON.MeshBuilder.CreatePlane( "tileHoverQuad" , { size: 0.5 } , scene );
    tileHoverQuad.rotation.x = Math.PI/2;
    tileHoverQuad.position.y = 0.01;
    tileHoverQuad.isPickable = false;
    var tileHoverQuadMaterial = new BABYLON.StandardMaterial( "tileHoverQuadMaterial" , scene );
    tileHoverQuadMaterial.diffuseColor = new BABYLON.Color3( .7 , 0 , 0 );
    tileHoverQuadMaterial.specularColor = new BABYLON.Color3( 0 , 0 , 0 );
    tileHoverQuad.material = tileHoverQuadMaterial;
    tileHoverQuad.setEnabled( false );

    // SOUNDS
	// background music
	backgroundMusic.loop = true;
	backgroundMusic.volume = 0.4;
	// this doesn't work anymore due to the new chrome autoplay policy, instead start the music when the user does something, starts the game for example
	//backgroundMusic.play();

	
    scene.beforeRender = function()
    {
        // glue the arc ball camera to the ground
        arcBallCamera.target.y = 0;
		
		// limit the camera in an area
		var bounds = 3;
        var xBounds = 4.5;
		if ( arcBallCamera.target.x < -xBounds ) arcBallCamera.target.x = -xBounds;
		if ( arcBallCamera.target.x > xBounds ) arcBallCamera.target.x = xBounds;
		if ( arcBallCamera.target.z < -bounds/2 ) arcBallCamera.target.z = -bounds/2;
		if ( arcBallCamera.target.z > bounds ) arcBallCamera.target.z = bounds;

        update();
    };

    // Return the created scene
    return scene;
}


var lasttime = Date.now();
function update()
{
    if ( b_paused ) return;

    var now = Date.now();
    var dt = (now-lasttime)/1000;
    lasttime = now;

    player.update();
    aiPlayer.update();

    // update buildings
    for ( var i = 0 ; i < buildings.length ; ++i )
    {
        buildings[i].update();
    }
    // update entities 
    for ( var i = 0 ; i < entities.length ; ++i )
    {
        entities[i].update( dt );
    }

    // remove entities that have been dead for a while
    for ( var i = 0 ; i < entities.length ; ++i )
    {
        if ( entities[i].deathCounter >= 300 )
        {
            entities.splice( i , 1 );
            break;
        }
    }

    // remove buildings that have been dead for a while
    for ( var i = 0 ; i < buildings.length ; ++i )
    {
        if ( buildings[i].building.isDead() )
        {
            if ( !buildings[i].building.isModelRemoved() )
            {
                sound_buildingDestroyed.play();
                buildings[i].remove();
                map.setObstructed( buildings[i].building.x , buildings[i].building.z , EMPTY );
            }
        }
        if ( buildings[i].building.deathCounter >= 300 )
        {
            buildings[i].remove();
            buildings.splice( i , 1 );
            break;
        }
    }

    updateAI();
}



const canvas = document.getElementById( "renderCanvas" ); 

// create engine, true = anti aliasing
const engine = new BABYLON.Engine( canvas , true );

const scene = createScene(); 



// var monkey;
// loadModel( "monkey.glb" , "monkey" , scene , function( model )
// {
// 	monkey = model;
// 	model.scaling.x = 0.3;
// 	model.scaling.y = 0.3;
// 	model.scaling.z = 0.3;
// } );

var mapModel;
loadModel( "models/map.glb" , "mapModel" , scene , function( model )
{
	mapModel = model;
} );


// Register a render loop to repeatedly render the scene
engine.runRenderLoop( function () 
{
    scene.render();
} );

// Watch for browser/canvas resize events
window.addEventListener("resize" , function () 
{
    engine.resize();
} );



var mouseX;
var mouseY;
var b_mouseMoved = false;

// renderCanvas.addEventListener( "mousemove" , function( e ) 
renderCanvas.addEventListener( "mousemove" , function( e ) 
{
	mouseX = e.offsetX;
	mouseY = e.offsetY;
	b_mouseMoved = true;

    var ray = scene.createPickingRay( scene.pointerX , scene.pointerY , BABYLON.Matrix.Identity() , arcBallCamera );

	var hit = scene.pickWithRay( ray );

	if ( hit.pickedMesh && hit.pickedMesh.name == "Ground" )
	{
        var x = hit.pickedPoint.x;
        var z = hit.pickedPoint.z;
        // convert to tile coords
        x += GROUNDWIDTH/2;
        z += GROUNDHEIGHT/2;
        var tileX = Math.floor( x*2 );
        var tileZ = Math.floor( z*2 );
        tileHoverQuad.position.x = tileX/2-GROUNDWIDTH/2+0.25;
        tileHoverQuad.position.z = tileZ/2-GROUNDHEIGHT/2+0.25;
        if ( map.isObstructed( tileX , tileZ ) || tileX > 5 )
        {
            tileHoverQuad.material.diffuseColor = new BABYLON.Color3( 0.7 , 0 , 0 );
        }
        else
        {
            tileHoverQuad.material.diffuseColor = new BABYLON.Color3( 0 , 0.7 , 0 );
        }
	}
} );

renderCanvas.addEventListener( "click" , function( e ) 
{
    if ( mouseMode == MOUSE_DEFAULT )
    {
        var ray = scene.createPickingRay( scene.pointerX , scene.pointerY , BABYLON.Matrix.Identity() , arcBallCamera );	

        var hit = scene.pickWithRay( ray );

        if ( hit.pickedMesh )
        {
            console.log( hit.pickedMesh.name );
            // if a buildings is hit // only they should have integer names
            if ( Number.isInteger( hit.pickedMesh.name ) )
            {
                var buildingID = hit.pickedMesh.name;
                for ( var i = 0 ; i < buildings.length ; ++i )
                {
                    if ( buildings[i].building.ID == buildingID )
                    {
                        var buildingType = buildings[i].building.type;
                        console.log( buildings[i] );
                        if ( buildingType == GOLDMINE )
                        {
                            showBuildingWindow( GOLDMINE , buildings[i] );
                        }
                        else if ( buildingType == SPAWNER )
                        {
                            showBuildingWindow( SPAWNER , buildings[i] );
                        }
                        else if ( buildingType == FLYING_SPAWNER )
                        {
                            showBuildingWindow( FLYING_SPAWNER , buildings[i] );
                        }
                        else if ( buildingType == ARCHER_SPAWNER )
                        {
                            showBuildingWindow( ARCHER_SPAWNER , buildings[i] );
                        }
                        else if ( buildingType == TURRET )
                        {
                            showBuildingWindow( TURRET , buildings[i] );
                        }
                    }
                }
            }
        }

        // if ( hit.pickedMesh && hit.pickedMesh.name == "Ground" )
        // {
        //     var x = hit.pickedPoint.x;
        //     var z = hit.pickedPoint.z;
        //     // convert to tile coords
        //     x += GROUNDWIDTH/2;
        //     z += GROUNDHEIGHT/2;
        //     var tileX = Math.floor( x*2 );
        //     var tileZ = Math.floor( z*2 );
        // }
    }
    else if ( mouseMode == MOUSE_BUILD )
    {
        var ray = scene.createPickingRay( scene.pointerX , scene.pointerY , BABYLON.Matrix.Identity() , arcBallCamera );	

        var hit = scene.pickWithRay( ray );

        if ( hit.pickedMesh && hit.pickedMesh.name == "Ground" )
        {
            var x = hit.pickedPoint.x;
            var z = hit.pickedPoint.z;
            // convert to tile coords
            x += GROUNDWIDTH/2;
            z += GROUNDHEIGHT/2;
            var tileX = Math.floor( x*2 );
            var tileZ = Math.floor( z*2 );
            if ( map.isObstructed( tileX , tileZ ) || tileX > 5 )
            {
                mouseMode = MOUSE_DEFAULT;
                tileHoverQuad.setEnabled( false );
            }
            else
            {
                // build the building
                constructBuilding( tileX , tileZ , player , selectedBuilding , scene );
                mouseMode = MOUSE_DEFAULT;
                tileHoverQuad.setEnabled( false );
                if ( tutorialCounter == 0 )
                {
                    if ( selectedBuilding == GOLDMINE )
                    {
                        ++tutorialCounter;
                        changeTutorial();
                    }
                }
                else if ( tutorialCounter == 1 )
                {
                    if ( selectedBuilding == GOLDMINE )
                    {
                        ++tutorialCounter;
                        changeTutorial();
                    }
                }
                else if ( tutorialCounter == 2 )
                {
                    if ( selectedBuilding == SPAWNER )
                    {
                        ++tutorialCounter;
                        changeTutorial();
                    }
                }
            }
        }
    }
} );

var b_paused = true;
renderCanvas.addEventListener( "keyup" , function(e) 
{
    if ( e.keyCode == 80 )
    {
        b_paused = !b_paused;
        if ( b_paused == false )
        {
            lasttime = Date.now();
        }
    }
    else if ( e.keyCode == 77 )
	{
		toggleMusic();
	}
} );

function toggleMusic()
{
	if ( backgroundMusicIsPlaying ) 
	{
		backgroundMusic.pause();
		backgroundMusicIsPlaying = false;
	}
	else
	{
		backgroundMusic.play();
		backgroundMusicIsPlaying = true;
	}
}



function loadModel( filename , name , scene , onloadFunction )
{
	var model = null;
	BABYLON.SceneLoader.ImportMesh( undefined , "" , filename , scene , function ( meshes , particleSystems , skeletons , animationList )
	{
		for ( var i = 0 ; i < meshes.length ; ++i )
		{
			if ( i == 0 ) 
			{
				model = meshes[i];
				model.name = name;
			}
			meshes[i].receiveShadows = true;
			shadowGenerator.getShadowMap().renderList.push( meshes[i] );
		}
		onloadFunction( model );
	} );
}



var lasttime = Date.now();



window.onbeforeunload = function () 
{

};




function buildGoldMine()
{
    mouseMode = MOUSE_BUILD;
    selectedBuilding = GOLDMINE;
    tileHoverQuad.setEnabled( true );
}
function buildSpawner()
{
    mouseMode = MOUSE_BUILD;
    selectedBuilding = SPAWNER;
    tileHoverQuad.setEnabled( true );
}
function buildTurret()
{
    mouseMode = MOUSE_BUILD;
    selectedBuilding = TURRET;
    tileHoverQuad.setEnabled( true );
}
function buildFlyingSpawner()
{
    mouseMode = MOUSE_BUILD;
    selectedBuilding = FLYING_SPAWNER;
    tileHoverQuad.setEnabled( true );
}
function buildArcherSpawner()
{
    mouseMode = MOUSE_BUILD;
    selectedBuilding = ARCHER_SPAWNER;
    tileHoverQuad.setEnabled( true );
}

function constructBuilding( x , z , playerVariable , building , scene )
{
    if ( building == GOLDMINE )
    {
        if ( playerVariable.gold >= GOLDMINE_PRICE )
        {
            var building = new GoldMine( x , z , playerVariable ); 
            building.build( scene );
            buildings.push( building );
            map.setObstructed( x , z , building );
            playerVariable.takeGold( GOLDMINE_PRICE );
            if ( playerVariable.ID == player.ID ) sound_building.play();
        }
    }
    else if ( building == SPAWNER )
    {
        if ( playerVariable.gold >= SPAWNER_PRICE )
        {
            var building = new Spawner( x , z , playerVariable ); 
            building.build( scene );
            buildings.push( building );
            map.setObstructed( x , z , building );
            playerVariable.takeGold( SPAWNER_PRICE );
            if ( playerVariable.ID == player.ID ) sound_building.play();
        }
    }
    else if ( building == TURRET )
    {
        if ( playerVariable.gold >= TURRET_PRICE )
        {
            var enemyPlayer = aiPlayer;
            if ( playerVariable.ID == aiPlayer.ID ) enemyPlayer = player;
            var building = new Turret( x , z , playerVariable , enemyPlayer ); 
            building.build( scene );
            buildings.push( building );
            map.setObstructed( x , z , building );
            playerVariable.takeGold( TURRET_PRICE );
            if ( playerVariable.ID == player.ID ) sound_building.play();
        }
    }
    else if ( building == FLYING_SPAWNER )
    {
        if ( playerVariable.gold >= FLYING_SPAWNER_PRICE )
        {
            var building = new FlyingSpawner( x , z , playerVariable );
            building.build( scene );
            buildings.push( building );
            map.setObstructed( x , z , building );
            playerVariable.takeGold( FLYING_SPAWNER_PRICE );
            if ( playerVariable.ID == player.ID ) sound_building.play();
        }
    }
    else if ( building == ARCHER_SPAWNER )
    {
        if ( playerVariable.gold >= ARCHER_SPAWNER_PRICE )
        {
            var building = new ArcherSpawner( x , z , playerVariable );
            building.build( scene );
            buildings.push( building );
            map.setObstructed( x , z , building );
            playerVariable.takeGold( ARCHER_SPAWNER_PRICE );
            if ( playerVariable.ID == player.ID ) sound_building.play();
        }
    }
}

function xToWorldCoords( x )
{
    return x/2-GROUNDWIDTH/2+0.25;
}
function zToWorldCoords( z )
{
    return z/2-GROUNDHEIGHT/2+0.25;
}





function makeTextPlane( text , color , size , scene ) 
{
    var font = "bold 16px Arial";
    var tmpTexture = new BABYLON.DynamicTexture( "DynamicTexture" , 128 , scene , true );
    var tmpCtx = tmpTexture.getContext();
    tmpCtx.font = font;
    var DTWidth = tmpCtx.measureText(text).width;

    var planeHeight = 1;
    var DTHeight = 128; //or set as wished
    var ratio = planeHeight/DTHeight;
    var planeWidth = DTWidth * ratio;

    var dynamicTexture = new BABYLON.DynamicTexture( "DynamicTexture" , { width:DTWidth , height:DTHeight } , scene , true );
    dynamicTexture.hasAlpha = true;
    dynamicTexture.drawText( text , null , null , font , color , "transparent" , true );

    var plane = BABYLON.MeshBuilder.CreatePlane( "TextPlane" , {width:planeWidth, height:planeHeight} , scene );
    plane.material = new BABYLON.StandardMaterial( "TextPlaneMaterial" , scene );
    plane.material.backFaceCulling = false;
    plane.material.specularColor = new BABYLON.Color3( 0 , 0 , 0 );
    plane.material.diffuseTexture = dynamicTexture;
    plane.billboardMode = BABYLON.Mesh.BILLBOARDMODE_ALL;
    // plane.billboardMode = BABYLON.Mesh.BILLBOARDMODE_Y;
    return plane;
}



function showBuildingHover( building )
{
    document.getElementById("buildingButtonHover").style.display = "block";

    var titleElement = document.getElementById("buildingHoverTitle");
    var priceElement = document.getElementById("buildingHoverPrice");
    var descriptionElement = document.getElementById("buildingHoverDescription");

    if ( building == GOLDMINE )
    {
        titleElement.innerHTML = "<b>Goldmine</b>";
        priceElement.innerHTML = "<b>"+GOLDMINE_PRICE+"</b> Gold";
        descriptionElement.innerHTML = "The Goldmine will mine for gold. This can give you a basic income.";
    }
    else if ( building == SPAWNER )
    {
        titleElement.innerHTML = "<b>Mining Camp</b>";
        priceElement.innerHTML = "<b>"+SPAWNER_PRICE+"</b> Gold";
        descriptionElement.innerHTML = "The Mining Camp will spawn Miners. Miners will go out and mine your opponents gold. They are effective against buildings and the core, but relatively weak fighters.";
    }
    else if ( building == FLYING_SPAWNER )
    {
        titleElement.innerHTML = "<b>Wyvern Nest</b>";
        priceElement.innerHTML = "<b>"+FLYING_SPAWNER_PRICE+"</b> Gold";
        descriptionElement.innerHTML = "The Wyvern Nest will spawn Wyverns. Wyverns love gold and want to steal more from your opponent. They are flying and cannot be attacked by Miners.";
    }
    else if ( building == ARCHER_SPAWNER )
    {
        titleElement.innerHTML = "<b>Archer Camp</b>";
        priceElement.innerHTML = "<b>"+ARCHER_SPAWNER_PRICE+"</b> Gold";
        descriptionElement.innerHTML = "The Archer Camp will spawn Archers. Archers are ranged and can attack flying units. They don't do a lot of damage against buildings though.";
    }
    else if ( building == TURRET )
    {
        titleElement.innerHTML = "<b>Arrow Tower</b>";
        priceElement.innerHTML = "<b>"+TURRET_PRICE+"</b> Gold";
        descriptionElement.innerHTML = "The Arrow Tower is a strong defensive buildings that can help protect your gold.";
    }

    sound_buttonHover.play();
}
function hideBuildingHover()
{
    document.getElementById("buildingButtonHover").style.display = "none";
}

function showGameOver( loserID )
{
    document.getElementById("gameOver").style.display = "block";
    if ( loserID == 1 )
    {
        document.getElementById("gameOverText").innerHTML = "<b>Game Over!</b><br><br>Better luck next time.";
        sound_defeat.play();
    }
    else 
    {
        document.getElementById("gameOverText").innerHTML = "<b>Victory!</b><br><br>Thanks for playing.";
        sound_victory.play();
    }
}

function restart()
{
    map.clear();
    // remove all entities
    for ( var i = 0 ; i < entities.length ; ++i )
    {
        entities[i].remove();
    }
    entities = [];

    // remove all buildings
    for ( var i = 0 ; i < buildings.length ; ++i )
    {
        buildings[i].remove();
    }
    buildings = [];

    player.restart();
    aiPlayer.restart();

    restartAI();

    document.getElementById("gameOver").style.display = "none";
    b_paused = false;
}

function start()
{
    document.getElementById("intro").style.display = "none";
    b_paused = false;
    // start the background music with the first button press
    toggleMusic();
    showTutorial();
}

var tutorialCounter = 0;
function showTutorial()
{
    document.getElementById("tutorial").style.display = "block";
}
function changeTutorial()
{
    if ( tutorialCounter == 1 )
    {
        document.getElementById("tutorial").innerHTML = "And another one";
    }
    else if ( tutorialCounter == 2 )
    {
        document.getElementById("tutorial").innerHTML = "Next build a Mining Camp";
        document.getElementById("tutorial").style.right = "230px";
    }
    else if ( tutorialCounter == 3 )
    {
        document.getElementById("tutorial").innerHTML = "Build more buildings and collect all of your opponent's gold<br><b>Tip</b>: Try upgrading some of your buildings (you can click on them)";
        document.getElementById("tutorial").style.right = "30px";
        document.getElementById("tutorial").style.bottom = "160px";
    }
}
function closeTutorial()
{
    document.getElementById("tutorial").style.display = "none";
}



var clickedBuilding = null;
function showBuildingWindow( buildingType , building )
{
    document.getElementById("buildingWindow").style.display = "block";

    var titleElement = document.getElementById("buildingWindowTitleText");
    var contentElement = document.getElementById("buildingWindowContent");

    clickedBuilding = building;

    if ( buildingType == GOLDMINE )
    {
        titleElement.innerHTML = "<b>Goldmine</b>";
        contentElement.innerHTML = "<button onclick=\"updateGoldMine(15)\">+1 Gold Per Tick (15)</button>";
    }
    else if ( buildingType == SPAWNER )
    {
        titleElement.innerHTML = "<b>Mining Camp</b>";
        contentElement.innerHTML = "<button onclick=\"updateSpawnerDamage(25)\">+1 Entity Damage (25)</button><br><button onclick=\"updateSpawnerHP(15)\">+5 Entity HP (15)</button>";
    }
    else if ( buildingType == FLYING_SPAWNER )
    {
        titleElement.innerHTML = "<b>Wyvern Nest</b>";
        contentElement.innerHTML = "<button onclick=\"updateSpawnerDamage(25)\">+1 Entity Damage (25)</button><br><button onclick=\"updateSpawnerHP(15)\">+5 Entity HP (15)</button><br><button onclick=\"updateSpawnerSpeed(20)\">+0.2 Entity Speed (20)</button>";
    }
    else if ( buildingType == ARCHER_SPAWNER )
    {
        titleElement.innerHTML = "<b>Archer Camp</b>";
        contentElement.innerHTML = "<button onclick=\"updateSpawnerDamage(25)\">+1 Entity Damage (25)</button><br><button onclick=\"updateSpawnerHP(15)\">+5 Entity HP (15)</button><br><button onclick=\"updateSpawnerSpeed(20)\">+0.2 Entity Speed (20)</button>";
    }
    else if ( buildingType == TURRET )
    {
        titleElement.innerHTML = "<b>Arrow Tower</b>";
        contentElement.innerHTML = "<button onclick=\"updateTurretDamage(15)\">+1 Damage (15)</button>";
    }

    sound_buttonHover.play();
}



function closeWindow()
{
    document.getElementById("buildingWindow").style.display = "none";
    clickedBuilding = null;
}


function updateGoldMine( price )
{
    if ( clickedBuilding != null )
    {
        if ( player.gold >= price )
        {
            clickedBuilding.goldReward += 1;
            player.takeGold( price );
            sound_upgrade.play();
        }
    }
}
function updateSpawnerDamage( price )
{
    if ( clickedBuilding != null )
    {
        if ( player.gold >= price )
        {
            clickedBuilding.entityDamageUpgrade += 1;
            player.takeGold( price );
            sound_upgrade.play();
        }
    }
}
function updateSpawnerHP( price )
{
    if ( clickedBuilding != null )
    {
        if ( player.gold >= price )
        {
            clickedBuilding.entityHPUpgrade += 5;
            player.takeGold( price );
            sound_upgrade.play();
        }
    }
}
function updateSpawnerSpeed( price )
{
    if ( clickedBuilding != null )
    {
        if ( player.gold >= price )
        {
            clickedBuilding.entitySpeedUpgrade += 0.2;
            player.takeGold( price );
            sound_upgrade.play();
        }
    }
}
function updateTurretDamage( price )
{
    if ( clickedBuilding != null )
    {
        if ( player.gold >= price )
        {
            clickedBuilding.damage += 1;
            player.takeGold( price );
            sound_upgrade.play();
        }
    }
}