/* MUCHIGAME DHTML & AJAX ENGINE :: ORIGINALLY FROM :::
           ISOGAME:
	Isometric Game Engine for Javascript & HTML
	Released under GNU GPL License 
	by Francisco Javier Nieto <frjanibo@gmail.com> 2006 
	PLEASE SEND ME A MAIL ME IF YOU USE THIS!!! ;)
	Note: //<<< and //>>> are my fold methods for vim ;)
	----------
** Modificado por Juan Belon para el proyecto MuchiGame ( 2006-2007 ) :: http://www.agenciaq4.com/muchigame/ **
*/
var moz =(navigator.appName.indexOf("Netscape")>=0);
var mie =(navigator.appName.indexOf("Explorer")>=0);
var gid = document.getElementById;
// Metodos para acceder a los objetos por su id...
Array.prototype.$=function( id ){for(var f=0; f<this.length; f++){if( this[f].id == id) return this[f];}return false;};
Array.prototype._=function( id ){for(var f=0; f<this.length; f++) if( this[f].id == id) this.splice(f,1)};

var muchigame={
"config":{ //<<<
	"mie":(navigator.appName.indexOf("Explorer")>=0),
	"moz":(navigator.appName.indexOf("Netscape")>=0),
	"origen_x":500,
	"origen_y":150,
	"tile_w":72,
	"tile_h":36
	}, //>>>

//Classes
"Sprite":function( id, orientacion ){ //<<<
	//<<< Constructor de la clase Sprite
	var instancia = this;
	this.id = id;
	this.o = orientacion;
	this.x = 0;
	this.y = 0;
	this.z = 0;
	this.dim_x=1;
	this.dim_y=1;
	this.dim_z=1;
	this.src = new Array();
	this.src['n'] = "";
	this.src['s'] = "";
	this.src['w'] = "";
	this.src['e'] = "";
	this.offset = new Array();
	this.offset['s'] = new Array(0,0);
	this.offset['w'] = new Array(0,0);
	this.offset['n'] = new Array(0,0);
	this.offset['e'] = new Array(0,0);
	this.img = document.createElement("img");
	this._dibujado = false;
	//>>>
	this.colision=function( x, y ){ //<<<
		x = parseInt(x);
		y = parseInt(y);
		if(( x >= this.x ) && ( x <= (this.x+this.dim_x) ) && ( y >= this.y ) && ( y <= (this.y+this.dim_y) )) {
			return true;
		}
		else 
			return false;
	} //>>>
	this.establecerXYZ=function( x,y,z ){ //<<<
		if(x!=undefined) this.x = parseInt(x);
		if(y!=undefined) this.y = parseInt(y);
		if(z!=undefined) this.z = parseInt(z);
	}; //>>>
	this.establecerDimensiones=function( x, y, z ){ //<<<
		this.dim_x = parseInt(x);
		this.dim_y = parseInt(y);
		this.dim_z = parseInt(z);
	} //>>>
	this.obtenerPosPantalla=function(){ //<<<
		var x = this.x;
		var y = this.y;
		var x_pantalla = (y*(muchigame.config.tile_w/2) - x*(muchigame.config.tile_w/2)) + muchigame.config.origen_x;
		var y_pantalla = (y*(muchigame.config.tile_h/2) + x*(muchigame.config.tile_h/2)) + muchigame.config.origen_y - parseInt(this.z);
		return new Array(x_pantalla, y_pantalla);
	}; //>>>
	this.establecerOffset=function( o, offset ){ //<<<
		this.offset[o] = new Array( parseInt(offset[0]), parseInt(offset[1]) );
	}; //>>>
	this.dibujar = function( lugar ){ //<<<
		this.img.id = this.id;
		if(!mie){
			if(this.img.getAttribute("src") == null) this.img.setAttribute("src", this.src[ this.o ]);
			if(this.img.src.indexOf(this.src[this.o]) == -1) this.img.src= this.src[this.o];
		}
		
		if(mie) {
			if(this.img.src=="") this.img.src=this.src[ this.o ];
			if(this.img.src.indexOf(this.src[this.o]) == -1) this.img.src= this.src[this.o];
		}
		
		this.img.style.position = "absolute";
		var posicion = this.obtenerPosPantalla();
		this.img.style.left= posicion[0] + this.offset[this.o.charAt(0)][0];
		this.img.style.top = posicion[1] + this.offset[this.o.charAt(0)][1];	
		if(!this._dibujado)	{
			document.getElementById(lugar).appendChild(this.img);
			this._dibujado = true;
		}
	}; //>>>
	this.eliminar = function(){ //<<<
		if(this._dibujado) {
			if(this.img.parentNode)	this.img.parentNode.removeChild( this.img );
			this._dibujado = false;
		}
	}; //>>>
	this.actualizar = function(){ //<<<
		var posicion = this.obtenerPosPantalla();
		this.img.style.left= posicion[0] + this.offset[this.o.charAt(0)][0];
		this.img.style.top = posicion[1] + this.offset[this.o.charAt(0)][1] - this.dim_z;
		this.img.style.zIndex = this.z_calc();
	}; //>>>
	this.z_calc = function(){ //<<<
		var x = parseInt( this.x );
		var y = parseInt( this.y );
		var z = parseInt( this.z );
		var inc_tamanio = (this.dim_x>this.dim_y)?this.dim_x:this.dim_y;
		var z_index = (y+x)*z+inc_tamanio;
		if((parseInt(y)==-1) || (parseInt(x)==-1)) var z_index = 2;
		return (z_index>0)?z_index:0;
	} //>>>
	this.publicar = function( ev ){ //<<<		
		this.x = ev.eventoOriginal.coords[0];
		this.y = ev.eventoOriginal.coords[1];
	}; //>>>
} //>>>
,"Celda":function( id, img, x, y ){ //<<<
	muchigame.Sprite.apply(this,new Array(id, "s" ));
	this.src['s'] = "img/suelo.gif";
	this.offset['s'] = new Array(0,0);
	this.establecerXYZ( x, y );
	this.dibujar = function( lugar ){ //<<<
		this.img.id = this.id;
		if(mie) {
			if(this.img.src != this.src[this.o]) this.img.src = this.src[this.o];
		} else
			if(this.img.getAttribute("src") == null) this.img.setAttribute("src", this.src[ this.o ]);
		
		this.img.style.position = "absolute";
		var posicion = this.obtenerPosPantalla();
		this.img.style.left= posicion[0] + this.offset[this.o][0];
		this.img.style.top = posicion[1] + this.offset[this.o][1];
		
		this.img.style.zIndex = this.z_calc();
		if( !this._dibujado )	{
			document.getElementById(lugar).appendChild(this.img);
			this._dibujado = true;
		}
	}; //>>>
} //>>>
,"Grupo":function(){ //<<<
	var instancia=this;
	this.elements = new Array();
	this.length = 0;
	this.$=function( id ){ //<<<
		return this.elements.$( id );
	} //>>>
	this.anadir=function( sprite ){ //<<<
		if( !this.elements.$( sprite.id ) )
			this.elements.push( sprite );
		this.length = this.elements.length;
	} //>>>
	this.eliminar=function( sprite ){ //<<<
		this.elements._( sprite.id );
		this.length = this.elements.length;
	} //>>>
	this.item=function( key ){ //<<<
		return this.elements[key];
	} //>>>
	this.actualizar=function(){ //<<<
		for(var f=0; f<this.elements.length; f++) this.elements[f].actualizar();
	} //>>>
	this.dibujar=function(lugar){ //<<<
		for(var f=0; f<this.elements.length; f++) this.elements[f].dibujar( lugar );
	} //>>>
	this.colision=function( grupo_o_Sprite ){ //<<<
		if( grupo_o_Sprite instanceof muchigame.Sprite ) return this.spriteColision( grupo_o_Sprite );
		if( grupo_o_Sprite instanceof muchigame.Grupo ) return this.grupoColision( grupo_o_Sprite );
	} //>>>
	this.spriteColision=function( sprite ){ //<<<
		var colisiones = new Array();
		for(var f=0; f<this.elements.length; f++){
			if( sprite.colision( this.elements[f].x, this.elements[f].y ) )
				colisiones.push( this.elements[f] );
		}
		return colisiones;
	} //>>>
	this.grupoColision=function( grupo ){ //<<<
		var colisiones = new Array();
		for(var f=0; f<this.elements.length; f++){
			if( grupo.colision( this.elements[f].x, this.elements[f].y ) )
				colisiones.push( this.elements[f] );
		}
		return colisiones;
	} //>>>
	this.publicar = function( ev ){ //<<<	
	}; //>>>
} //>>>
,"Escena":function(){ //<<<
	var instancia = this;
	instancia.jugador = null;
	instancia.avatares= new muchigame.Grupo();
	instancia.objetos= new muchigame.Grupo();
	instancia.celdas =  new muchigame.Grupo();

	instancia.paredes=new muchigame.Grupo();
	instancia.puertas=new muchigame.Grupo();

	this.dibujar=function( lugar ){ //<<<
		instancia.celdas.dibujar( lugar );
		instancia.objetos.dibujar( lugar );
		for(var f=0; f< instancia.paredes.length; f++) instancia.paredes[f].dibujar( lugar );
		for(var f=0; f< instancia.puertas.length; f++) instancia.puertas[f].dibujar( lugar );
		for(var f=0; f< instancia.avatares.length; f++) instancia.avatares[f].dibujar( lugar );
	} //>>>
	this.anadirCelda=function( celda ){ //<<<
		instancia.celdas.anadir(celda);
	} //>>>
	this.anadirObjeto=function( sprite ){ //<<<
		instancia.objetos.anadir( sprite );
	} //>>>
	this.anadirAvatar=function( avatar ){ //<<<
		if( !this.avatares.$( avatar.id )) this.avatares.push( avatar );
	} //>>>
	this.anadirPared = function( pared ){ //<<<
		this.paredes.push( pared );
	} //>>>
	this.queHayEn=function( x, y ){ //<<<
		var ret = Array();
		for(var f=0; f< instancia.celdas.length; f++){
			var obj = instancia.celdas.item(f);
			//if( (obj.x==x) && (obj.y==y) ) ret.push( instancia.celdas.item(f) );
			if( (obj.x <= x) && (obj.x+obj.dim_x > x) && (obj.y <= y) && (obj.y+obj.dim_y > y ) )
				ret.push( obj )
		}
		if( ret.length == 0 ){
			throw "muchigame.Escena.queHayEn: coordenadas no validas ("+x+","+y+")";
			return ret;
		}

		for(var f=0; f< instancia.objetos.length; f++){
			var obj = instancia.objetos.item(f);
			if( obj.colision(x,y) ) ret.push( obj );
		}
		
		var seguir=true;
		while(seguir){
			seguir=false;
			for(var f=0; f< obj.length; f++){
				if(obj[f].z > obj[f+1].z) {
					var o1 = obj[f];
					obj[f] = obj[f+1];
					obj[f+1] = o1;
					//intercambio
					seguir=true;
				}
				
			}
		}

		return ret;
	} //>>>
	this.publicar = function( ev ){ //<<<
	}; //>>>
} //>>>

// Eventos
,"ManejadorEventos": new function(){ //<<<
	this.manejadores = new Array();
	this.eventos = new Array();

	this.registrar=function( ob ){ //<<<
		if( ! this.manejadores.$( ob.id ) ) this.manejadores[this.manejadores.length]=ob;
	} //>>>
	this.borrar=function( ob ){ //<<<
		this.manejadores._( ob.id );
	} //>>>
	this.enviar=function( ev ){ //<<<
		if( ev.tipo == "mousemove" || ev.tipo == "mouseleftdown") 
			this.evento_raton = ev;
		else		
			this.eventos.push( ev );
		this.procesar(); //FALTABA ESTA LLAMADA PARA QUE REALMENTE SE PROCESARAN LOS EVENTOS...
	} //>>>
	this.procesar=function(){ //<<<
		while( this.eventos.length > 0 ){
			var e = this.eventos.pop();
			for(var i=0; i< this.manejadores.length; i++)	this.manejadores[i].publicar( e );
		}
		if( this.evento_raton ) {
			for(var i=0; i< this.manejadores.length; i++)	{
				this.manejadores[i].publicar( this.evento_raton );
			}
			this.evento_raton = false;
			}

	} //>>>
} //>>>
,"Evento":function( tipo, evento ){ //<<<
	this.tipo = tipo;
	this.eventoOriginal = evento;
} //>>>

// Functions
,"bucle_principal":function ( func, delay ){ //<<<
	if( typeof func != "function" ) {
		throw "MUCHIGAME error: Se debe llamar a muchigame.bucle_principal con una function como primer argumento.";
		return false;
	}
	window.onmousemove=muchigame.ControladorMovRaton;
	window.onmousedown=muchigame.ControladorMouseDown;
	window.onmouseup=muchigame.ControladorMouseUp;
	if(muchigame.config.mie)
		document.onkeydown=muchigame.ControladorTeclado;
	else
		window.onkeydown=muchigame.ControladorTeclado;
	if(delay == undefined) delay = 250;
	return setInterval( func, delay );
} //>>>
,"ControladorMouseUp":function(evento){ //<<<
	//window.alert("ARRIBA");
	return false;
} //>>>
,"ControladorMouseDown":function(evento){ //<<<
	//window.alert("ABAJO");
	if(moz)	{
		var coords = new Array( evento.pageX, evento.pageY );
		dcho = (evento.which == 3 || evento.which == 2);
		}
	else {
		var coords = new Array( evento.clientX, evento.clientY );
		dcho = (evento.button == 2 || evento.button == 3);
	 }
	 //window.alert(coords);
	 if (dcho) {
 	  return false;
	 } else {
	  evento.coords = coords;
	  var e = new muchigame.Evento( "mouseleftdown", evento );
	  muchigame.ManejadorEventos.enviar( e );
	}
} //<<<
,"ControladorMovRaton":function(evento){ //<<<
	if(moz)	
		var coords = new Array( evento.pageX, evento.pageY );
	else 
		var coords = new Array( evento.clientX, evento.clientY );

	evento.coords = coords;
	var e= new muchigame.Evento( "mousemove", evento );
	
	muchigame.ManejadorEventos.enviar( e );
} //>>>

,"ControladorTeclado":function(ev){ //<<<
	var key = undefined;
	if(muchigame.config.mie) {
		var ev = window.event;
		key = window.event.keyCode;
	} else key = ev.which;
	
	var keychar = String.fromCharCode( key );	
	if(key==37) { keychar = "IZQUIERDA";  /* s.establecerXYZ(s.x,s.y-1); */ }
	if(key==38) { keychar = "ARRIBA";    /* s.establecerXYZ(s.x-1,s.y); */ }
	if(key==39) { keychar = "DERECHA"; /* s.establecerXYZ(s.x-1,s.y+1);  */}
	if(key==40) { keychar = "ABAJO";  /* s.establecerXYZ(s.x+1,s.y); */ }
	ev.key = key;
	ev.keychar = keychar;
	var e= new muchigame.Evento( "keydown", ev );
	muchigame.ManejadorEventos.enviar( e );
	if(( key > 36) && (key < 41) )return false;
} //>>>

,"obtener_coordenadasPantalla_a_3D":function( x, y ){ //<<<
	x-= muchigame.config.origen_x;
	y-= muchigame.config.origen_y;
	var w = muchigame.config.tile_w;
	var h = muchigame.config.tile_h;

	var x_3d = Math.round( ((w*y) - (h*x)) / (w*h) );
	var y_3d = Math.round( ((w*y) + (h*x)) / (w*h) )-1;
	return new Array(x_3d,y_3d);
} //>>>
,"obtener_coordenadas3D_a_Pantalla":function ( x,y ){ //<<<
	var w = muchigame.config.tile_w;
	var h = muchigame.config.tile_h;

	var x_pantalla = (x*Math.round(w/2) - y*Math.round(w/2)) + muchigame.config.origen_x;
	var y_pantalla = (x*Math.round(h/2) + y*Math.round(h/2)) + muchigame.config.origen_y;
	return new Array(x_pantalla, y_pantalla);
} //>>>
};
