package com.main;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.audio.music.Music;
import org.anddev.andengine.audio.music.MusicFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.ZoomCamera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.anddev.andengine.entity.particle.ParticleSystem;
import org.anddev.andengine.entity.particle.emitter.PointParticleEmitter;
import org.anddev.andengine.entity.particle.initializer.AccelerationInitializer;
import org.anddev.andengine.entity.particle.initializer.RotationInitializer;
import org.anddev.andengine.entity.particle.initializer.VelocityInitializer;
import org.anddev.andengine.entity.particle.modifier.AlphaModifier;
import org.anddev.andengine.entity.particle.modifier.ExpireModifier;
import org.anddev.andengine.entity.particle.modifier.ScaleModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.shape.Shape;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.input.touch.detector.ScrollDetector;
import org.anddev.andengine.input.touch.detector.SurfaceScrollDetector;
import org.anddev.andengine.input.touch.detector.ScrollDetector.IScrollDetectorListener;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.opengl.util.GLHelper;
import org.anddev.andengine.ui.activity.LayoutGameActivity;
import org.anddev.andengine.util.Debug;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.bc_game.R;
import com.commons.game_commons;
import com.engine.AsyncTaskLoader;
import com.engine.IAsyncCallback;
import com.engine.SpriteChain;
import com.game.commons.cGame_Commons;
import com.game.commons.cTools;
import com.game.commons.cGame_Commons.ACTION_PLAYER;
import com.game.objects.cGame_Arrow;
import com.game.objects.cGame_Object;
import com.game.objects.cGame_Object_Part;
import com.menu.*;
import com.loading.loading_progressbar;
import com.qwerjk.andengine.opengl.texture.region.PixelPerfectTextureRegionFactory;
import com.qwerjk.andengine.opengl.texture.region.PixelPerfectTiledTextureRegion;
import com.sound.game_mediaplayerEx;

public class progressbar_menu_Activity extends LayoutGameActivity implements IScrollDetectorListener, IOnSceneTouchListener  
{

	
	private PointParticleEmitter fire_emitter;
	private ParticleSystem fire_particle;
	
	// ************  LOADING SCREEN ***************
	public Scene loadscene;
	public Sprite lbackground;
	// ************ MENU SCREEN *******************
  	@SuppressWarnings("deprecation")
	protected Scene MenuScene = new Scene(1);
  	// ************ MENU SCREEN *******************
  	
	// ++++++++++++++++++++++++++++++++++++
	// ++++ DECLARACION :: ANDENGINE
	// ++++++++++++++++++++++++++++++++++++
	private ZoomCamera mCamera;
	private SurfaceScrollDetector mScrollDetector;
	
	// ++++++++++++++++++++++++++++++++++++
	// ++++ DECLARACION :: FONDO MENU ++++
	// ++++++++++++++++++++++++++++++++++++
	private TextureRegion Menu_background;
	private TextureRegion[] animals= new TextureRegion[10];
			
	// Totse el models es a dir wagons i maquina que composen el tren 
	private ArrayList<SpriteChain> animal_chains = new ArrayList<SpriteChain>();
	
	private Random rand;
	
	public String menu_path="images/menus_high/";
	public String animals_path="images/animals_high/";
	public String game_path="images/human_high/";
	
	private long startTime_fire_player=0;
	
    private int screen_user_width;
    private int screen_user_height;
    
	private Music mMusic;
	
	cGame_Object player;
	int key_code=2;
	
	// +++++++++++++++++
	// +++ ADS CODE ++++
	// +++++++++++++++++
	@Override
    protected int getLayoutID() {
            return R.layout.main;
    }

    @Override
    protected int getRenderSurfaceViewID() {
            return R.id.ads_adMob;
    }
	
 	// ++++++++++++++++++++++++++++++
    // +++ ONLINE DETECTION CODE ++++
 	// ++++++++++++++++++++++++++++++
    Handler online_handler = new Handler() 
    {
        @Override
        public void handleMessage(Message msg) 
        {

            if (msg.what != 1) 
            { 
            	// code if not connected
            	// showOfflineDialog();
            } 
        }
    };

    
    
	// Definicion de objetos del motor AndEngine
	public Engine onLoadEngine() 
	{			 
		
		// Determina la resolucio maxima
		DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        
        screen_user_width=displaymetrics.widthPixels;
        screen_user_height=displaymetrics.heightPixels;
        
        game_commons.cCamera_width=1024.0f;//displaymetrics.widthPixels;
        game_commons.cCamera_height=600.0f;//displaymetrics.heightPixels;
	
        // Calculamos el centro de la pantalla todos los objetos depanden de ello
        game_commons.screen_center_point_X=(game_commons.cCamera_width/2);
        game_commons.screen_center_point_Y=(game_commons.cCamera_height/2);
        
		this.mCamera = new ZoomCamera(0, 0, game_commons.cCamera_width , game_commons.cCamera_height );
		//this.mCamera.setZoomFactor(0.5f);
		this.mCamera.setBounds(0, game_commons.cCamera_width, 0, game_commons.cCamera_height);
		this.mCamera.setBoundsEnabled(true);
		
		EngineOptions eOptions=new EngineOptions(true, ScreenOrientation.LANDSCAPE, new FillResolutionPolicy(), this.mCamera).setNeedsMusic(true).setNeedsSound(true);
		eOptions.getTouchOptions().setRunOnUpdateThread(true);
		
		// AUDIO :: Per activar el audio posem al final .setNeedsSound(true)
		// BUG TREIEM --> new RatioResolutionPolicy(game_commons.cCamera_width , game_commons.cCamera_height ) 
		return new Engine(eOptions);
	}
	
	// Carga i asignacion de texturas i objetos.
	public void onLoadResources() 
	{
		// Ponemos los datos de las activities i el engine para ser utilizado desde cualquier sitio
		game_commons.gEngine=this.mEngine;
		game_commons.gActivity=this;

		// ********** LOADING SCREEN IMAGES **************
		//BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		/*FET*/
		game_commons.Loading_background 
		= BitmapTextureAtlasTextureRegionFactory.createFromAsset(
				game_commons.Loading_textureatlas, 
				this, menu_path+"loading_background_2.png"
				, 0, 0); // 1024x640
		
		/*NO FET*/
		game_commons.Loading_progress_bar = new loading_progressbar(game_commons.screen_center_point_X-50, game_commons.screen_center_point_Y-70, game_commons.loadToSpriteMap(game_commons.Loading_textureatlas,menu_path+"loading_progress.png", 0, 641, 1, 1, this),this,1,this.mEngine,100,100,1,1,false); //100x100
		/*FET*/
		game_commons.Loading_text = 
				BitmapTextureAtlasTextureRegionFactory.createFromAsset(
						game_commons.Loading_textureatlas, 
						this, menu_path+"loading_text.png"
						, 0, 740); // 100x24
		/*FET*/
		this.mEngine.getTextureManager().loadTextures(game_commons.Loading_textureatlas);
		// ********** LOADING SCREEN IMAGES **************
	}

	@SuppressWarnings("deprecation")
	public Scene onLoadScene() 
	{
        this.mEngine.registerUpdateHandler(new FPSLogger());
		
		// ************  NEW	 ************  
        loadscene = new Scene(1);
        
		// ************************ BACKGROUND DECLARATION ******************************************
        loadscene.setBackgroundEnabled(false);
        
        
        game_commons.Loading_background.setTextureRegionBufferManaged(false);
        
        // REPARA BUG THE LINIES EN EL BACKGROUND 
        lbackground = new Sprite(0,0,game_commons.Loading_background) {
            protected void onInitDraw(final GL10 pGL)
            {
               super.onInitDraw(pGL);
               GLHelper.enableTextures(pGL);
               GLHelper.enableTexCoordArray(pGL);
               GLHelper.enableDither(pGL);
            }
        };
        
        // Auto resize en funcion del tamaņo de la pantalla
        lbackground.registerEntityModifier(game_commons.getBackgroundScaleResolution(lbackground));
        lbackground.detachSelf();
        loadscene.attachChild(lbackground);
		// ************************ FIN BACKGROUND DECLARATION ******************************************
		 
        loadscene.attachChild(new Sprite(game_commons.Loading_progress_bar.getX(), game_commons.Loading_progress_bar.getY()+102, game_commons.Loading_text));
        loadscene.attachChild(game_commons.Loading_progress_bar);		
        // Ordena por layers
        //loadscene.sortChildren();
        
        
        
        /*
		 * Here's where the assets are loaded in the background behind the loading scene.
		 */
        // ***************** IAsyncCallback ****************************
		IAsyncCallback callback = new IAsyncCallback() {
 
			public void workToDo() 
			{
				load_resources_scene();
			}
 
			public void onComplete() 
			{
				     unload_loadingscene();
				     mEngine.setScene(MenuScene);
				     //isNetworkAvailable(online_handler);
	
			}
		};
		new AsyncTaskLoader().execute(callback);
		// ***************** IAsyncCallback ****************************
		
  		// Deixem un petit retard per que acabi de fer en scale del background
        return loadscene;
     
	}

	public void onLoadComplete() 
	{
		
   	}
	
	public void onPause()
	{
		 super.onPause();
		 try{
			 	mMusic.pause();
		 }
		 catch(NullPointerException e){
			 
		 }
		
	}
	
	public void onResume()
	{
		super.onResume();
		 try{
			 if (mMusic!=null) mMusic.resume();
		 }
		 catch(NullPointerException e){
			 
		 }
	}
	
	private void unload_loadingscene()
	{
	        /*!!!CAL POSAR AIXO SEMPRE QUE VOLEM ADD DETACH DETACHSELF SELF!!!*/
	    	// Codigo de que deixa remove durant el Update Thread
			this.runOnUpdateThread(new Runnable() 
			{
	            public void run() 
	            {
					// Per anar be tots les classes que s'extenen de Animated Sprite que es volem compartir
					// desde altres activitities s'han de desvincular amb .detachSelf();
					game_commons.Loading_progress_bar.detachSelf();
	            }
	         });
		
	}
 
 
	/**
	 * This is called when assets need to be loaded in the background.
	 */
	protected void load_resources_scene() 
	{
		rand = new Random();
		
		// Objeto animado
		// Creamos objetos de juego con is_animated a true.
		// Li passem el objecte que controla el boto
		Menu_background = BitmapTextureAtlasTextureRegionFactory.createFromAsset(game_commons.Menu_Background_textureatlas, this, menu_path+"menu_background_2.png", 0, 0); // 1024x640
		
		animals[0]=BitmapTextureAtlasTextureRegionFactory.createFromAsset(game_commons.AnimalChain_Main_textureatlas, game_commons.gActivity, animals_path+"animal1.png", 0, 0); //64x64
		animals[1]=BitmapTextureAtlasTextureRegionFactory.createFromAsset(game_commons.AnimalChain_Main_textureatlas, game_commons.gActivity, animals_path+"animal2.png", 0, 65);
		animals[2]=BitmapTextureAtlasTextureRegionFactory.createFromAsset(game_commons.AnimalChain_Main_textureatlas, game_commons.gActivity, animals_path+"animal3.png", 0, 129);
		animals[3]=BitmapTextureAtlasTextureRegionFactory.createFromAsset(game_commons.AnimalChain_Main_textureatlas, game_commons.gActivity, animals_path+"animal4.png", 0, 193);
		animals[4]=BitmapTextureAtlasTextureRegionFactory.createFromAsset(game_commons.AnimalChain_Main_textureatlas, game_commons.gActivity, animals_path+"animal5.png", 0, 257);
		animals[5]=BitmapTextureAtlasTextureRegionFactory.createFromAsset(game_commons.AnimalChain_Main_textureatlas, game_commons.gActivity, animals_path+"animal6.png", 0, 321);
		animals[6]=BitmapTextureAtlasTextureRegionFactory.createFromAsset(game_commons.AnimalChain_Main_textureatlas, game_commons.gActivity, animals_path+"animal7.png", 0, 385);
		animals[7]=BitmapTextureAtlasTextureRegionFactory.createFromAsset(game_commons.AnimalChain_Main_textureatlas, game_commons.gActivity, animals_path+"animal8.png", 0, 449);
		animals[8]=BitmapTextureAtlasTextureRegionFactory.createFromAsset(game_commons.AnimalChain_Main_textureatlas, game_commons.gActivity, animals_path+"animal9.png", 0, 513);
	
		// Add LineChain
		float setX=0,setY=0;
		for (int i=0;i<=2;i++)
		{
			 switch (rand.nextInt(4)) 
			 {
	            case 0:
	            	setX=10.0f;
	            	setY=10.0f;
	            break;
	            case 1: 
	            	setX=-10.0f;
	            	setY=10.0f;
	            break;
	            case 2: 
	            	setX=10.0f;
	            	setY=-10.0f;
	            break;
	            case 3:
	            	setX=-10.0f;
	            	setY=-10.0f;
	            break;
	            
			 }
			 animal_chains.add(new SpriteChain(animals,rand.nextInt(6)+1,rand.nextInt(400)+100,rand.nextInt(400)+100,setX,setY));	
		}
		
		
		 /*********************************  CARREGA MUSIC *************************************/
		
		MusicFactory.setAssetBasePath("music/");
        try {
                this.mMusic=MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "menu_background.ogg");
                this.mMusic.setLooping(true);
                
        } catch (final IOException e) {
                Debug.e("Error", e);
        }
        
        /*********************************  CARREGA MUSIC *************************************/
        
        
		
		//aninave.play(150,5.0f);
		
       
        // *******************************

		/*********************************  CARREGA AUDIO *************************************/
        
        /*********************************  CARREGA AUDIO *************************************/	 

		// Cargamos el sprite map
		this.mEngine.getTextureManager().loadTextures(game_commons.Menu_Background_textureatlas,game_commons.AnimalChain_Main_textureatlas,cGame_Commons.Game_Shoot_TextureAltas);
		
		// BUG :: Tornem a carregar les textures
		this.mEngine.getTextureManager().reloadTextures();
		
		 // ************************ BACKGROUND DECLARATION ******************************************
		
		MenuScene.setBackgroundEnabled(false);
		
		 // REPARA BUG THE LINIES EN EL BACKGROUND
        Sprite mbackground = new Sprite(0,0,Menu_background) {
            protected void onInitDraw(final GL10 pGL)
            {
               super.onInitDraw(pGL);
               GLHelper.enableTextures(pGL);
               GLHelper.enableTexCoordArray(pGL);
               GLHelper.enableDither(pGL);
            }
        };
        
        // Auto resize en funcion del tamaņo de la pantalla
		mbackground.registerEntityModifier(game_commons.getBackgroundScaleResolution(mbackground));
		
		// Deixem un petit retard per que acabi de fer en scale del background
		try 
		{
		 Thread.sleep(300);
		} 
		catch (InterruptedException e) 
		{
		  e.printStackTrace();
		}
		
		mbackground.detachSelf();
		MenuScene.attachChild(mbackground);
		
		for (SpriteChain current_chain : animal_chains )
		{
			current_chain.detachSelf();
			MenuScene.attachChild(current_chain);
		}
		// ************************ FIN BACKGROUND DECLARATION ******************************************
		
		MenuScene.setOnAreaTouchTraversalFrontToBack();
		   
		// Aņadimos manejador de Scroll
		this.mScrollDetector = new SurfaceScrollDetector(this);
		this.mScrollDetector.setEnabled(true);

		// Aņadimos manejador de Touch de la pantalla
		MenuScene.setOnSceneTouchListener(this);
		MenuScene.setTouchAreaBindingEnabled(true);
		
		// ***************** PLAY MUSIC *****************************
	    try
	    {
	    	 if(this.mMusic!=null && this.mMusic.isPlaying())
	    	 {
	    		 this.mMusic.stop();
	    		 this.mMusic.release();
	    	 }
	    	 else
	    	 {
	    		 this.mMusic.play();
	    	 }
	    }
	    catch(Exception e)
	    {
	    	
	    }
		

	    
	    // LOADING TEXTURAS DE SHOOT
	    cGame_Commons.ShootTextureRegion[0]=PixelPerfectTextureRegionFactory.createFromAsset(
	    		cGame_Commons.Game_Shoot_TextureAltas, 
	    		this, 
	    		game_path+"bow/arrow.png",
	    		0, 0);
	    
		// DECLARACION DEL PLAYER
        BitmapTextureAtlas Animated_textureatlas = new BitmapTextureAtlas(1024, 256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        PixelPerfectTiledTextureRegion tiledtexture=PixelPerfectTextureRegionFactory.createTiledFromAsset(Animated_textureatlas, this, game_path+"walkcycle/BODY_male.png",0, 0, 9, 4);
		player = new cGame_Object(460,470,64,64,tiledtexture,"Rajoy","0000000z",20);
		mEngine.getTextureManager().loadTexture(Animated_textureatlas);
		
		// DECLARACION PARTE 1
	    Animated_textureatlas = new BitmapTextureAtlas(1024, 256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
	    tiledtexture=PixelPerfectTextureRegionFactory.createTiledFromAsset(Animated_textureatlas, this, game_path+"walkcycle/TORSO_leather_armor_torso.png",0, 0, 9, 4);
	    cGame_Object_Part p1 = new cGame_Object_Part(460,470,64,64,tiledtexture,"AAAAFFFF",30);
	    mEngine.getTextureManager().loadTexture(Animated_textureatlas);
		
		// DECLARACION PARTE 2
	    Animated_textureatlas = new BitmapTextureAtlas(1024, 256,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
	    tiledtexture=PixelPerfectTextureRegionFactory.createTiledFromAsset(Animated_textureatlas, this, game_path+"walkcycle/HEAD_plate_armor_helmet.png",0, 0, 9, 4);
	    cGame_Object_Part p2 = new cGame_Object_Part(460,470,64,64,tiledtexture,"AAAAFFFF",31);
	    mEngine.getTextureManager().loadTexture(Animated_textureatlas);
		
	    player.addPart(p1);
	    player.addPart(p2);
	    
        player.addScene(MenuScene);
	    
		 // The actual collision-checking. 
		MenuScene.registerUpdateHandler(new IUpdateHandler() 
		{	
			long startTime_game_objects = System.currentTimeMillis();
			//long startTime_network_online = System.currentTimeMillis();
			
           public void reset() { }

           public void onUpdate(final float pSecondsElapsed) 
           {
           	
           	for (SpriteChain current_chain : animal_chains )
       		{
					 if(current_chain.getX() < 0) 
					 {
						 current_chain.speedX=+(rand.nextInt(4)+6); 
					 } 
					 else if(current_chain.getX() + 100 > game_commons.cCamera_width) 
					 {
						 current_chain.speedX=-(rand.nextInt(4)+6);
					 }
					
					 if(current_chain.getY() < 50) 
					 {
						 current_chain.speedY=+(rand.nextInt(4)+6);
					 } 
					 else if(current_chain.getY() + 100 > game_commons.cCamera_height) 
					 {
						 current_chain.speedY=-(rand.nextInt(4)+6);
					 }
       		}
           	
			 if (System.currentTimeMillis() - startTime_game_objects >= 30) 
			 {
				for (SpriteChain current_chain : animal_chains )
	        	{
					current_chain.setPosition(current_chain.getX()+(current_chain.speedX), current_chain.getY()+(current_chain.speedY));
	        	}
				startTime_game_objects = System.currentTimeMillis();
			 }
				// CHECK KEYCODE
				switch (key_code)
				{
					case 0:
						player.setPosition(player.getX()+7, player.getY());
						
						for (cGame_Object_Part c_Part : player.go_Parts )
						{
							c_Part.setPosition(c_Part.getX()+7, c_Part.getY());
						}
					break;
					case 1:
						player.setPosition(player.getX()-7, player.getY());
						
						for (cGame_Object_Part c_Part : player.go_Parts )
						{
							c_Part.setPosition(c_Part.getX()-7, c_Part.getY());
						}
					break;
					case 2:
						
					break;
					case 3:
						 if (System.currentTimeMillis() - startTime_fire_player >= 200) 
						 {
							 
							// DISPARA
							cGame_Arrow shoot = new cGame_Arrow(player.getX(),player.getY()-20,64,42,cGame_Commons.ShootTextureRegion[0]);
							shoot.setZIndex(2);
							shoot.setScale(3.0f);
							shoot.gop_PhysicsHandler.setVelocityY(-500);
							MenuScene.attachChild(shoot);
							MenuScene.sortChildren();
							
							startTime_fire_player=System.currentTimeMillis();
						}
					break;
					
				}
       		
           }
       });
		
		// LOADING PARTICLE 
	    TextureRegion fire =BitmapTextureAtlasTextureRegionFactory.createFromAsset(
	    		game_commons.AnimalChain_Main_textureatlas, 
	    		game_commons.gActivity, 
	    		game_path+"firesmoke0.png", 
	    		900,
	    		900
	    		);
		
		fire_emitter = new PointParticleEmitter(300, 300);
		fire_particle  = new ParticleSystem(fire_emitter, 20, 40, 50, fire);
		fire_particle.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);

		fire_particle.addParticleInitializer(new VelocityInitializer(-100, -200, 0, 0));
		fire_particle.addParticleInitializer(new AccelerationInitializer(-3, 3, -3, -5));
		fire_particle.addParticleInitializer(new RotationInitializer(0.0f, 180.0f));
		fire_particle.addParticleModifier(new ScaleModifier(4.0f, 7.0f, 0.0f, 1.5f));
		fire_particle.addParticleModifier(new ExpireModifier(1.5f));
		fire_particle.addParticleModifier(new AlphaModifier(2.0f, 0.0f, 0.0f, 1.5f));
		
		//fire_particle.setZIndex(6);

		fire_particle.setVisible(true);
		fire_particle.setParticlesSpawnEnabled(true);
		
		MenuScene.attachChild(fire_particle);

	}

	public void onScroll(ScrollDetector pScrollDetector, TouchEvent pTouchEvent,float pDistanceX, float pDistanceY) 
	{

	}
	
	// Evento que se desencadena al tocar la pantalla
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) 
	{
		  float ctot=com.commons.TrigonometryBasics.getTargetAngle(
					player.getX(),
					player.getY(),
					180,
					pSceneTouchEvent.getX(),
					pSceneTouchEvent.getY()
					);
		
		int CAMERA_WIDTH = (int) game_commons.cCamera_width;
		int CAMERA_HEIGHT = (int) game_commons.cCamera_height;
		
		
		if (pSceneTouchEvent.isActionDown() ) 
		{
			
			Log.d("Value X","Value X:" + screen_user_width);
			Log.d("Value Y","Value Y:" + screen_user_height);
			
			if (pSceneTouchEvent.getMotionEvent().getX() > screen_user_width / 2 + screen_user_width / 4) 
			{
				key_code=0;
				player.anima(50,ACTION_PLAYER.HIT_RIGHT);
			} 
			else if (pSceneTouchEvent.getMotionEvent().getX() < screen_user_width / 2 - screen_user_width / 4) 
			{
				player.anima(50,ACTION_PLAYER.HIT_LEFT);
				key_code=1;
			}
			else
			{
				//player.anima(50,ACTION_PLAYER.HIT_LEFT);
				key_code=3;
			}
			
		}
		else if (pSceneTouchEvent.isActionUp())
		{
			key_code=2;
			
			// Para todas las animaciones
			player.stopAnimation();
			for (cGame_Object_Part c_Part : player.go_Parts )
			{
				c_Part.stopAnimation();
			}
			
			// Vete a la Tile del player y de pieazs de vista frontal
			player.setCurrentTileIndex(1);
			for (cGame_Object_Part c_Part : player.go_Parts )
			{
				c_Part.setCurrentTileIndex(1);
			}
		}
		
		return true;
	}	

	// Important cal possar-ho per no generar instancies cada vegada que toquem el home button i tornem al joc
	public void onCreate(Bundle b)
	{
		super.onCreate(b);
	}
	
	// Deteccio de activity actual en segon pla
	public void onUserLeaveHint()
	{
		
	}
	
	public boolean onKeyDown(final int pKeyCode,final KeyEvent pEvent)
	{
		if(pKeyCode==82 || pKeyCode==84 || pKeyCode==2 || pKeyCode == KeyEvent.KEYCODE_BACK)
		{
			showExitDialog();
			return true;
		}
		return super.onKeyDown(pKeyCode, pEvent);
	}
	
	public void showExitDialog()
	{
		
		AlertDialog.Builder builder = new AlertDialog.Builder(progressbar_menu_Activity.this);
		
		builder.setMessage(":: Do you want to exit game? ::").setCancelable(false).setTitle(":: Exit key detected! ::")
		
		.setPositiveButton(" Yes please! ", 
				new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int id){
							System.exit(0);
							//progressbar_game_Activity.this.finish();
						}
		})
		
		.setNegativeButton(" Oops NO!  ", 
				new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,int id){
							dialog.cancel();
						}
		});
		
		AlertDialog alert = builder.create();
		alert.setIcon(android.R.drawable.ic_dialog_alert);
		alert.show();

	}

	public game_mediaplayerEx load_sound(game_mediaplayerEx tsound,String tpath)
	{
		   try
	        {
			   tsound.setDataSourceFromAsset(this.getAssets(), tpath);
			   tsound.prepareAsync();
			   tsound.setLooping(false);
	        }
	        catch (IOException e)
	        {
	        	tsound.release();
	        	tsound = null;
	            e.printStackTrace();
	        }
		   return tsound;
	}

}




