var altoAmpliado = 0;
var altoTotal = 401;
//var URL = CONSTANTES['urlGeneral'];
var URL = CONSTANTES["dominio"];
var ventanaMusica = "";
var fotos = "";
var cambio = "";
var alt = "";
var carpetaCabecera = "";
var numFoto = 0;
var puedeAmpliar = true;
var letra = "";

var previo = "";
var fotos = "";
var cambio = "";
var alt = "";
var carpetaCabecera = "";
var numFoto = 0;
var interTime = 10000;
var timerId = "";
var puedeActuar = false;
var sentidoSlide = 0;
var slideAuto = false;
var idCambio = "";

var seccion = "";
var subSeccion = "";
var subApartado = "";
var subSubApartado = "";
var preSeccion = null;
var preSubSeccion = null;
var preSubApartado = null;
var preSubSubApartado = null;

if(CONSTANTES['SEGUIMIENTOJS']!=true){		//AÑADIMOS EL LISTENER PARA LA FUNCION ANTERIOR
	seccion = seccionInicio;
	subSeccion = subSeccionInicio;
	subApartado = subApartadoInicio;
	subSubApartado = subSubApartadoInicio;
}


function trackAnalytics(pathName) {
	var event = ['_trackPageview'];
	if (pathName) {
		event.push(pathName);
	}
	_gaq.push(event);
};


var objetoDestino = "";
var objetoDestinoGeneral = "contenidoMarmotas";

//eval("alert('eo')")

var nodesactivar = false;
var barraBlock = false;

var listaIniciada = false;

var arVersion = navigator.appVersion.split("MSIE")
var version = parseFloat(arVersion[1])

if (navigator.appName.indexOf("Netscape") != -1) {var isNN = true;}
else{var isNN = false;}

if (navigator.appName.indexOf("Microsoft Internet Explorer") != -1) {var isIE = true;}
else{var isIE = false;}

function pngFix(imagen){
//	if ((version >= 5.5) && (document.body.filters)) 
	if ((version >= 5.5 & version <7) && (document.body.filters)) 
	{
	  var img = imagen;
	  var imgName = img.src.toUpperCase()
		 var imgID = (img.id) ? "id='" + img.id + "' " : ""
		 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
		 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
		 var imgStyle = "display:inline-block;" + img.style.cssText 
		 if (img.align == "left") imgStyle = "float:left;" + imgStyle
		 if (img.align == "right") imgStyle = "float:right;" + imgStyle
		 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
		 var strNewHTML = "<span " + imgID + imgClass + imgTitle
		 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
		 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
		 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
		 img.outerHTML = strNewHTML
	}
}

if(typeof(document.getElementsByClassName) != 'function') {	    // Sirve para que funcione el getElementsByClassName en todos los navegadores
  	document.getElementsByClassName = function (cn) {
		var rx = new RegExp("\\b" + cn + "\\b"), allT = document.getElementsByTagName("*"), allCN = [], i = 0, a;
			while (a = allT[i++]) {
			  if (a.className && a.className.indexOf(cn) + 1) {
				if(a.className===cn){ allCN[allCN.length] = a; continue;   }
				rx.test(a.className) ? (allCN[allCN.length] = a) : 0;
			  }
			}
		return allCN;
	}
}



function setContenido(objeto,texto) {
	document.getElementById(objeto).innerHTML = texto
}


function initFade(capa){
	var content = document.getElementById(capa);
	if(isIEOld()){
		$("#"+capa).css("visibility","visible");
	}else{
		$("#"+capa).stop(true);
		$("#"+capa).animate({ opacity: 1 }, {duration: 200,easing: 'easeInQuart'});
	}
	goTop();

}	

function initDinamics(desdeJava){
	obj = document.getElementsByClassName("imgDinamica");
	for(i=0;i<obj.length;i++){
		obj[i].onload = function (){
			objName = this.id
			pngFix(this);
		}
		obj[i].src = obj[i].src;
	}

/*	if(desdeJava!=true){
		obj = document.getElementsByClassName("txtIncrustado");
		alert("oculto incrustados")
		for(i=0;i<obj.length;i++){
			if(obj[i].style.visibility=="") obj[i].style.visibility = "hidden";
		}
	}*/
}

function aparecerElementos(nameElementos){
	obj = document.getElementsByClassName(nameElementos);
//	alert(obj)
	for(i=0;i<obj.length;i++){
		obj[i].style.visibility = "visible";
	}
}

function desaparecerObjeto(obj){
	if(typeof obj == 'object'){
		var content = obj
	}else{
		var content = document.getElementById(obj);
	}
	var property = content.filters ? 'filter' : 'opacity';
	content.style[property] = content.filters ? 'alpha(opacity=' + 0 + ')' : 0/100;
}



function cierra(ID){
	setContenido("ampliado","")
	var capa= document.getElementById("ampliado");
	resto = 0 - altoAmpliado;
	if(resto<-2){
		altoAmpliado = altoAmpliado + resto/2
	}else{
		altoAmpliado = 0
		capa.style.top = '-30px';
	}
	capa.style.height = altoAmpliado+"px";
	if(altoAmpliado>0){
		setTimeout(function () {cierra(ID)}, 50)
	}else{
		puedeAmpliar = true;
		if(ID!=null){
			obj = document.getElementById("menuGestor");
			obj.innerHTML = previo;
		}
	}
}

function getWindowData(){
    var widthViewport,heightViewport,xScroll,yScroll,widthTotal,heightTotal;
    if (typeof window.innerWidth != 'undefined'){
        widthViewport= window.innerWidth-17;
        heightViewport= window.innerHeight-17;
    }else if(typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth !='undefined' && document.documentElement.clientWidth != 0){
        widthViewport=document.documentElement.clientWidth;
        heightViewport=document.documentElement.clientHeight;
    }else{
        widthViewport= document.getElementsByTagName('body')[0].clientWidth;
        heightViewport=document.getElementsByTagName('body')[0].clientHeight;
    }
    xScroll=self.pageXOffset || (document.documentElement.scrollLeft+document.body.scrollLeft);
    yScroll=self.pageYOffset || (document.documentElement.scrollTop+document.body.scrollTop);
    widthTotal=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth,widthViewport);
    heightTotal=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,heightViewport);
    return [widthViewport,heightViewport,xScroll,yScroll,widthTotal,heightTotal];
} 



function abajo(e) {
  var keyCode=0 ;

  if (isIE){
    keyCode=event.keyCode
  }else{
    keyCode=e.which;
  }
  letra = keyCode;
}

function arriba(e) {
  letra = "";
}

document.onkeydown = abajo;
document.onkeyup = arriba;

function detenerPropagacion(){
	var e=window.event||arguments.callee.caller.arguments[0];
	e.cancelBubble = true;
	e.returnValue = false;
	if (e.stopPropagation) e.stopPropagation();
	if (e.preventDefault) e.preventDefault();
}

function str_replace(busca, repla, orig)
{
	str 	= new String(orig);

	rExp	= "/"+busca+"/g";
	rExp	= eval(rExp);
	newS	= String(repla);

	str = new String(str.replace(rExp, newS));

	return str;
}



function generaImg(variables){



	var oXMLHttpRequest = generaReqCom();
	oXMLHttpRequest.onreadystatechange = function(){
		if(oXMLHttpRequest.readyState == 4 && oXMLHttpRequest.status == 200)
		{
			var respuesta = oXMLHttpRequest.responseXML;
			var elementos = respuesta.getElementsByTagName("valor"); 
			var resultado = elementos[0].getElementsByTagName("imgTag")[0].firstChild.data;
			var tag = elementos[0].getElementsByTagName("aTag")[0].firstChild.data;
			var objStr = elementos[0].getElementsByTagName("objStr")[0].firstChild.data;


				resultado = escape(resultado);
				eval(objStr+tag+"='"+resultado+"'");
				eval("objetoTit = "+objStr+tag)
//				alert(objStr+tag+"="+objetoTit)


//			alert("objStr "+objStr+"   tag "+tag)
///			alert("titFin "+titulosFinales)
//			alert("txtFin "+textosFinales)
//			alert("existia "+elementos[0].getElementsByTagName("existia")[0].firstChild.data)
//			alert("archivo "+elementos[0].getElementsByTagName("archivo")[0].firstChild.data)
//			aTag = document.getElementById(tag)
//			aTag.innerHTML = resultado;
		}
	};


	sender = URL+'inc/generaImgXML.php?texto='+escape(variables["texto"]);
	if(variables["tagA"]!=null){sender += "&tagA="+variables["tagA"];}
	if(variables["objStr"]!=null){sender += "&objStr="+variables["objStr"];}
	if(variables["iniLeft"]!=null){sender += "&iniLeft="+variables["iniLeft"];}
	if(variables["iniRight"]!=null){sender += "&iniRight="+variables["iniRight"];}
	if(variables["fuente"]!=null){sender += "&fuente="+variables["fuente"];}
	if(variables["ancho"]!=null){sender += "&ancho="+variables["ancho"];}
	if(variables["alto"]!=null){sender += "&alto="+variables["alto"];}
	if(variables["bgCol"]!=null){sender += "&bgCol="+variables["bgCol"];}
	if(variables["textoCol"]!=null){sender += "&textoCol="+variables["textoCol"];}
	if(variables["fontSize"]!=null){sender += "&fontSize="+variables["fontSize"];}
	if(variables["sombraCol"]!=null){sender += "&sombraCol="+variables["sombraCol"];}
	if(variables["angulo"]!=null){sender += "&angulo="+variables["angulo"];}
	if(variables["saltoLinea"]!=null){sender += "&saltoLinea="+variables["saltoLinea"];}
	if(variables["alineamiento"]!=null){sender += "&alineamiento="+variables["alineamiento"];}
	if(variables["alineamientoV"]!=null){sender += "&alineamientoV="+variables["alineamientoV"];}
	if(variables["x"]!=null){sender += "&x="+variables["x"];}
	if(variables["y"]!=null){sender += "&y="+variables["y"];}




//	alert("sender "+sender)
	oXMLHttpRequest.open( 'GET', sender, true);
	oXMLHttpRequest.send( null);



}

function apareceElemento(objStr,iniLeft,iniRight){

//	$("#"+objStr).css("opacity", 0)
	pngFix(document.getElementById(objStr))
	cuentaElementosTextoSlide ++;
	if(cuentaElementosTextoSlide==2){
		$("#tituloSlide").stop(true);
		$("#tituloSlide").animate({ opacity: 100 }, {duration: 600,easing: 'easeInQuart'});
		$("#textoSlide").stop(true);
		$("#textoSlide").animate({ opacity: 100 }, {duration: 600,easing: 'easeInQuart'});
	}
//	obj = document.getElementById(objStr)
//	obj.style.visibility = "visible";*/
}


///////////////////////////////////
//	 MENUS
///////////////////////////////

function clickSec(destino,destinoJS,objeto){	//FUNCION PARA EL CLICK EN TODOS LOS ENLACES
//	alert("clickSec")

//	alert("preSeccion "+preSeccion)
/*	if(seccion!=null){
		if(seccion!=0){
			$("#am"+seccion).blur();
		}else{
			$("#aLogo").blur();
		}
	}*/
//	alert("clickSec")
	if(objeto!=null){ objeto.blur();}
	if(letra!=17 && letra!=224){
		if(CONSTANTES['SEGUIMIENTOJS']==true && destinoJS!=null && CONSTANTES['admin']!=1){
//			valor = seccion+"/"+subseccion+"/"+subapartado;
			valor = destinoJS;
//			alert("adress "+valor)
			SWFAddress.setValue(valor)
		}else{
			document.location = destino;
		}
	}else{
		window.open(destino)
		letra = "";
	}
}


function openNew(destino){	//FUNCION PARA EL CLICK EN TODOS LOS ENLACES
	window.open(destino)
}



function goTop(){		//FUNCION PARA IR AL TOP
//	window.scrollTo(0,0)
    $("#am11").blur();
	var destination = 0;
     $("html,body").stop().animate({scrollTop: destination},500, 'easeInOutCubic');

}

//////////////////////////////////
//	CARGA DE CONTENIDOS MEDIANTE AJAX
///////////////////////////////


///////////////////////////////////
//	SWF ADRESS  -  DEEP LINKING
///////////////////////////////
var primeraCarga = false;

function strpos (haystack, needle, offset) {	//DEVUELVE LA POSICION EN UN ARRAY DE UN ELEMENTO DADO O -1 SI NO EXISTE EN EL ARRAY LO USAMOS PARA COMPROBAR SI EL PERMALINK ES UN IDIOMA
    var i = (haystack+'').indexOf(needle, (offset || 0));
    return i === -1 ? false : i;
}

	
function calculaRuta(direccion){			//SACAMOS LOS TROZOS DE LA RUTA PARA CALCULAR EL NUMERO Y EL ID DE CADA SECCION,SUBSECCION,Y SUBAPARTADO, como paginacion e id
	nuevaDir = "";
	trozosRuta = direccion.split("/");
	valorSeccion = trozosRuta[1];
	valorSubseccion = trozosRuta[2];
	valorSubapartado = trozosRuta[3];
	valorSubSubapartado = trozosRuta[4];
	IDIOMA = trozosRuta[trozosRuta.length-1];
	
	//CALCULO DE LA SECCION

	if(valorSeccion!="" && valorSeccion!=null){
		SECCIONID = valorSeccion;
		if(strpos(CONSTANTES["IDIOMASPOSIBLES"],valorSeccion)!==false){
			SECCIONID = "home";
			SECCION = 0;
		}else{
			i=0;
			encontrado = false;
			while(CONSTANTES["MENU"+i+"LINK"]!=null){
				if(CONSTANTES["MENU"+i+"LINK"]==SECCIONID){
					SECCION = i;
					encontrado = true;
					break;
				}
				i++;
			}

			if(encontrado == false){
				SECCION = 0;
			}
		}
	}else{
		SECCIONID = "home";
		SECCION = 0;
	}

	//CALCULO DE LA SUBSECCION

	if(valorSubseccion!="" && valorSubseccion!=null){
		SUBSECCIONID = valorSubseccion;
		if(strpos(CONSTANTES["IDIOMASPOSIBLES"],valorSubseccion)!==false){
			SUBSECCIONID = 0;
		}
	}else{
		SUBSECCIONID = 0;
	}


	if(SECCION!=0){
		encontrado = false;
		i=1;
		while(CONSTANTES["MENU_"+SECCION+"_"+i+"_LINK"]!=null){
			if(CONSTANTES["MENU_"+SECCION+"_"+i+"_LINK"]==SUBSECCIONID){
				SUBSECCION = i;
				encontrado = true;
				break;
			}

			i++;
		}
		if(encontrado == false){
			SUBSECCION = SUBSECCIONID;
		}
	}else{
		SUBSECCION = 0;
	}


	//CALCULO DEL SUBAPARTADO
	if(valorSubapartado!="" && valorSubapartado!=null){
		SUBAPARTADOID = valorSubapartado;
		if(strpos(CONSTANTES["IDIOMASPOSIBLES"],valorSubapartado)!==false){
//			alert("ENTRO Y LO PONGO A 0")
			SUBAPARTADOID = 0;
		}
	}else{
		SUBAPARTADOID = 0;
	}

	if(SECCION!=0){
		encontrado = false;
		i=1;
		while(CONSTANTES["MENU_"+SECCION+"_"+SUBSECCION+"_"+i+"_LINK"]!=null){
			if(CONSTANTES["MENU_"+SECCION+"_"+SUBSECCION+"_"+i+"_LINK"]==SUBAPARTADOID){
				SUBAPARTADO = i;
				encontrado = true;
				break;
			}

			i++;
		}
		if(encontrado == false){
			SUBAPARTADO = SUBAPARTADOID;
		}
	}else{
		SUBAPARTADO = 0;
	}


	//CALCULO DEL SUBSUBAPARTADO
	SUBSUBAPARTADO = valorSubSubapartado;
	if(strpos(CONSTANTES["IDIOMASPOSIBLES"],valorSubSubapartado)!==false){
		SUBSUBAPARTADO = 0;
	}

	nuevaDir = "/"+SECCION+"/"+SUBSECCION+"/"+SUBAPARTADO+"/"+SUBSUBAPARTADO+"/"+IDIOMA

	objetoDestino = objetoDestinoGeneral;

	return new Array(nuevaDir,SECCIONID,SUBSECCIONID,SUBAPARTADOID);
}


function handleChange(event) {		//ESTE ES EL EVENTO QUE SE DISPARA CADA VEZ K SE CAMBIA LA URL
//	alert("path "+event.path+" "+tipoNavegador)
//	alert(event.path)
	trackAnalytics('#/'+event.path)

	if(event.path!="/"){
		retornoDireccion = calculaRuta(event.path);
		miDireccion = retornoDireccion[0];
//		alert(retornoDireccion[1]+" "+retornoDireccion[2]+" "+retornoDireccion[3])
		if(primeraCarga!=false){
//			alert("carga contenido normal desde AJAX")
			trozos = miDireccion.split("/")
			cargaContenidoExterno(trozos[1],trozos[2],trozos[3],trozos[4],retornoDireccion[1],retornoDireccion[2],retornoDireccion[3],idiomaWeb,event.path,tipoNavegador)
		}else{
//			alert("tiene datos pero es la primera vez k cargamos")
//			alert(window.onload)
			window.onload = function(){
			}
//			alert(window.onload)
			$("#"+objetoDestino).stop(true);
			$("#"+objetoDestino).css("opacity",0);
			$("#"+objetoDestino).css("visibility","visible");
			trozos = miDireccion.split("/")
			cargaContenidoExterno(trozos[1],trozos[2],trozos[3],trozos[4],retornoDireccion[1],retornoDireccion[2],retornoDireccion[3],idiomaWeb,event.path,tipoNavegador)
		}
//		alert("carga contenido")
	}else{		//SI EL PATH ESTÁ VACIO PUEDE SER POR DOS COSAS, K SEA LA PRIMERA CARGA O XK LLENDO HACIA ATRAS SE HA VUELTO A LA URL INICIAL QUE NO TIENE DIRECCION AJAX
		if(primeraCarga!=false){				//HEMOS VUELTO DANDO ATRAS
//			alert("carga contenido inicial "+idiomaWeb)
			cargaContenidoExterno(seccionInicio,subSeccionInicio,subApartadoInicio,subSubApartadoInicio,seccionInicioID,subSeccionInicioID,subApartadoInicioID,idiomaWeb,URLINICIO,tipoNavegador)
		}else{		//ES LA PRIMERA VEZ QUE SE CARGA Y NO HAY DIRECCION AJAX
//			alert("no ejecuto accion por ser la primera carga")
			primeraCarga=true;
			seccion = seccionInicio;
			subSeccion = subSeccionInicio;
			subApartado = subApartadoInicio;
			subSubApartado = subSubApartadoInicio;
		}
	}
}

if(CONSTANTES['SEGUIMIENTOJS']==true){		//AÑADIMOS EL LISTENER PARA LA FUNCION ANTERIOR
	SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);
}


function cargaContenidoExterno(section,subsection,subapart,subSubapart,sectionID,subsectionID,subapartID,idioma,direccionInicial,tipoNavegador){	//ESTA FUNCION LLAMA AL PHP DE LA CONSULTA, METE EL CONTENIDO Y ESPERA AL PRELOAD, O SI NO HAY IMGS HACE EL FADE



	ele = document.createElement('div');
	ele.id = 'cargandoGlobal'; 
	if(objetoDestino==""){objetoDestino=objetoDestinoGeneral}
//	alert("cargaContenidoExterno objDest "+objetoDestino)
	getCargando();
	var oXMLHttpRequest = generaReqCom();

	oXMLHttpRequest.onreadystatechange = function(){
		if(oXMLHttpRequest.readyState == 4 && oXMLHttpRequest.status == 200)
		{
//			alert("complete")
			var respuesta = oXMLHttpRequest.responseXML;
			var elementos = respuesta.getElementsByTagName("valor"); 
			var resultado = elementos[0].getElementsByTagName("contenido")[0].firstChild.data;
			if (objetoDestino!=objetoDestinoGeneral){
				objeto = document.createElement("div");
				objeto.id = "test"
				objeto.innerHTML = resultado;
//				alert("antes "+resultado)
				if($("#"+objetoDestino, objeto).html()!=null && document.getElementById(objetoDestino)!=null){
					resultado = $("#"+objetoDestino, objeto).html();
//					alert("resultado 1 cambio parte "+resultado)
				}else{
					objetoDestino = objetoDestinoGeneral;
//					alert("resultado 2 cambio general  "+resultado)
				}
			}

//			alert("resultado final  "+resultado)
			if(!isIEOld()){
					$("#"+objetoDestino).css("opacity",0);
			}

			$("#"+objetoDestino).css("visibility","hidden");
			resultado = insertaOnload(escape(resultado))
			document.getElementById(objetoDestino).innerHTML = resultado;


			scriptJS = elementos[0].getElementsByTagName("scriptJS")[0].firstChild.data;
			var tituloPagina = elementos[0].getElementsByTagName("tituloPagina")[0].firstChild.data;
//			var menuLang = elementos[0].getElementsByTagName("menuLang")[0].firstChild.data;

//			objetoLenguaje = document.createElement("div");
//			objetoLenguaje.id = "langHid"
//			objetoLenguaje.innerHTML = menuLang;
//			alert(menuLang)

//			for(i=1;i<=CONSTANTES["IDIOMASPOSIBLES"].split("/").length;i++){		
//				$("#botLang_"+i).attr("href",$("#botLang_"+i, objetoLenguaje).attr("href"));
//			}
//			document.getElementById("botonesIdioma").innerHTML = menuLang;

//			var existe = elementos[0].getElementsByTagName("existe")[0].firstChild.data;
//			alert("existe "+existe)



			cargaCompleta = false;
			elements = document.getElementById(objetoDestino).getElementsByTagName("img");
			if(elements[0]!="undefined" && elements[0]==null){
				$("#"+objetoDestino).css("visibility","visible");
				initFade(objetoDestino)
				eval(scriptJS);
				Hyphenator.run()
				if(seccion==12){listaIniciada = true;}else{listaIniciada = false;}
				$("#cargandoGlobal").stop(true);
				$("#cargandoGlobal").animate({ opacity: 0 }, {duration: 1200,easing: 'easeInQuart', complete: function() {
//					elemento=document.getElementById('cargandoGlobal');
//					elemento.parentNode.removeChild(elemento);
				}});
			}
			document.title = str_replace("&nbsp;"," ",tituloPagina);
//			document.getElementById("dSeccionNews").value = document.location;
//			document.getElementById("dSeccion").value = document.location;
		}
	};

//	alert("idioma "+idioma)
	if(idioma!=null){
		idiomaDestino = idioma
	}else{
		idiomaDestino = idiomaWeb
	}
	envio = URL+"inc/getContentAJAX.php?idiomaWeb="+idiomaDestino+"&seccion="+section+"&subSeccion="+subsection+"&subApartado="+subapart+"&subSubApartado="+subSubapart+"&seccionID="+sectionID+"&subSeccionID="+subsectionID+"&subApartadoID="+subapartID+"&direccionInicial="+direccionInicial+"&tipoNavegador="+tipoNavegador;
//	alert("lala "+envio);

	clearTimeout(intervalEntreFrases)
	clearTimeout(intervalEntreHome)
		
	numeroFrase = 0;
	posHome = 0

	//CALCULO DE SECCIONES  CAMBIO DE MENUUUUU
	if(seccion!=section){

		if(seccion!=""){
			aActivar = seccion;
		}else{
			aActivar = seccionInicio;
		}


			
	
			$("#l"+aActivar).removeClass("inactivo");
			$("#l"+section).addClass("inactivo");
			$("#selector").removeClass("sec_"+aActivar);
			$("#selector").addClass("sec_"+section);
//			alert(aActivar+" "+section)
		
		preSeccion = seccion;
		seccion = section;
	}else{
		preSeccion = null;
	}
	if(subSeccion!=subsection){
		preSubSeccion = subSeccion;
		subSeccion = subsection;
	}else{
		preSubSeccion = null;
	}
	if(subApartado!=subapart){
		preSubApartado = subApartado;
		subApartado = subapart;
	}else{
		preSubApartado = null;
	}

	if(seccion!=null){						///QUITO EL FOCUUUUS
		if(seccion!=0){
			$("#am"+seccion).blur();
		}else{
			$("#aLogo").blur();
			$("#am1").blur();
		}
	}




	oXMLHttpRequest.open( 'GET', envio, true );
	oXMLHttpRequest.send( null);
}

//////////////////////////
//	PRELOAD DE IMGS PARA CARGA DE CONTENIDO MEDIANTE AJAX
/////////////////////////

totalImgs = 0;
totalImgsCargadas = 0;
scriptJS = "";
cargaCompleta = false;

function cagaImg(){		//SE DISPARA CUANDO CARGA UNA IMAGEN DE UN CONTENIDO CARGADO X AJAX. CUANDO CARGA TODAS HACE FADE IN
	if(cargaCompleta == false){
		totalImgsCargadas++;
		if(totalImgsCargadas>=totalImgs){
			$("#"+objetoDestino).css("visibility","visible");
			initFade(objetoDestino)
//			alert(totalImgsCargadas+" de "+totalImgs+" initFade")
//			alert(scriptJS)
			eval(scriptJS);
			Hyphenator.run()
			if(seccion==12){listaIniciada = true;}else{listaIniciada = false;}
			cargaCompleta = true;
			$("#cargandoGlobal").stop(true);
			$("#cargandoGlobal").animate({ opacity: 0 }, {duration: 1200,easing: 'easeInQuart', complete: function() {
//				elemento=document.getElementById('cargandoGlobal');
//				elemento.parentNode.removeChild(elemento);
			}});
			totalImgs = 0;
			totalImgsCargadas = 0;
		}else{
//								alert(totalImgsCargadas+" de "+totalImgs)
		}
	}
}

function insertaOnload(resultado){   //METE A LOS TAGS IMG DEL CONTENIDO CARGADO MEDIANTE AJAX EL EVENTO ONLOAD
	trozos = resultado.split(escape("<img"));
	cantidad = trozos.length;
	if(cantidad<2){
//		alert("entro")
		trozos = resultado.split(escape("<IMG"));
		cantidad = trozos.length;
	}
	nuevoRes = "";
//	alert("logn "+cantidad)
	totalImgs = cantidad-1;
	for(i=0;i<cantidad;i++){
		if(i!=0){
			nuevoRes += "<img onload='cagaImg()' onerror='cagaImg()'";
		}
		nuevoRes += unescape(trozos[i]);
	}
	return nuevoRes;
}


//////////////////////////


//////////////////////////


function getCargando(){

	if($("#cargandoGlobal")[0]==null){
		var miPreload = '<div id="cargandoGlobal"><!-- --></div>'
		$("#pie").append(miPreload)
	}

	$('#cargandoGlobal').css('opacity',1);

/*	document.body.appendChild(ele);
	$("#cargandoGlobal").css("position","absolute");
	$("#cargandoGlobal").css("top","50%");
	$("#cargandoGlobal").css("left","50%");
	$("#cargandoGlobal").css("height","25px");
	$("#cargandoGlobal").css("width","25px");
	$("#cargandoGlobal").css("z-index","10000");
	$('#cargandoGlobal').css('background-color', 'transparent');
	$('#cargandoGlobal').css('background-image', 'url("'+URL+'img/miPreload.png")');
	$('#cargandoGlobal').css('background-position', '0px 0px');
	$('#cargandoGlobal').css('background-repeat', 'no-repeat');
	idCargando = setInterval("animaCargando()",200);*/
}

function animaCargando(){
	var posicion = $('#cargandoGlobal').css('background-position');
	var trozos = posicion.split(" ")
	var trozos = trozos[0].split("px")
	var posFin = parseInt(trozos[0])-25;
	if(posFin<=-200){posFin=0}
	$('#cargandoGlobal').css('background-position', posFin+'px 0px');
}



//////////////////////////////////////////////




//////////////////////////
//FORMULARIOS
//////////////////////////

function valida_enviar(){

	document.getElementById("formErrorConsulta").innerHTML = "";
	if (document.consultaForm.comment.value.length==0){
		alert(CONSTANTES['ERROR1'])
		document.consultaForm.comment.focus()
		document.getElementById("formErrorConsulta").innerHTML = CONSTANTES['ERROR1'];
	}else if(document.consultaForm.nombre.value.length==0){
		alert(CONSTANTES['ERROR2'])
		document.consultaForm.nombre.focus()
		document.getElementById("formErrorConsulta").innerHTML = CONSTANTES['ERROR2'];
	}else if(document.consultaForm.asunto.value.length==0){
		alert(CONSTANTES['ERROR6'])
		document.consultaForm.asunto.focus()
		document.getElementById("formErrorConsulta").innerHTML = CONSTANTES['ERROR6'];
	}else if(document.consultaForm.correo.value.length==0){
		alert(CONSTANTES['ERROR3'])
		document.consultaForm.correo.focus()
		document.getElementById("formErrorConsulta").innerHTML = CONSTANTES['ERROR3'];
	}else{
		correo = document.consultaForm.correo.value;
		if(correo.split("@").length!=2 || correo.split("@")[0]=="" || correo.split("@")[1]=="" || correo.split("@")[1].split(".").length!=2 || correo.split("@")[1].split(".")[0]=="" || correo.split("@")[1].split(".")[1]==""){
			alert(CONSTANTES['ERROR4'])
			document.consultaForm.correo.focus()
			document.getElementById("formErrorConsulta").innerHTML = CONSTANTES['ERROR4'];
		}else{
			enviaComment();
		}
	}
}



function generaReqCom(){
	var oXMLHttpRequest; 
	if(window.XMLHttpRequest) { // no es IE 
		oXMLHttpRequest = new XMLHttpRequest(); 
	} else { // Es IE o no tiene el objeto 
		try { 
			oXMLHttpRequest = new ActiveXObject('Microsoft.XMLHTTP'); 
		} catch (e) { 
			alert('El navegador utilizado no está soportado'); 
		} 
	} 
	return oXMLHttpRequest;
}

function enviaComment(){ 
	var oXMLHttpRequest = generaReqCom();
	oXMLHttpRequest.onreadystatechange = function(){
		if(oXMLHttpRequest.readyState == 4 && oXMLHttpRequest.status == 200)
		{
			var respuesta = oXMLHttpRequest.responseXML;
			var elementos = respuesta.getElementsByTagName("valor"); 
			var resultado = elementos[0].getElementsByTagName("enviado")[0].firstChild.data;
			if(resultado=="true"){
				alert(CONSTANTES['ENVIADO'])
				document.getElementById("formErrorConsulta").innerHTML = CONSTANTES['ENVIADO'];
				document.consultaForm.comment.value="";
				document.consultaForm.nombre.value="";
				document.consultaForm.correo.value="";
			}else{
				alert(CONSTANTES['ERROR_ENVIO'])
				document.getElementById("formErrorConsulta").innerHTML = CONSTANTES['ERROR_ENVIO'];
			}
			obj = document.consultaForm;
			obj.submit.style.visibility="visible";
		}
	};
	obj = document.consultaForm;
	obj.submit.style.visibility="hidden";
	document.getElementById("formErrorConsulta").innerHTML = "Enviando...";
//	alert(URL+'inc/enviaCorreo_js.php?nombre='+document.consultaForm.nombre.value+'&correo='+document.consultaForm.correo.value+'&comment='+document.consultaForm.comment.value)
	oXMLHttpRequest.open( 'GET', URL+'inc/enviaCorreo_js.php?nombre='+document.consultaForm.nombre.value+'&correo='+document.consultaForm.correo.value+'&asunto='+document.consultaForm.asunto.value+'&comment='+document.consultaForm.comment.value, true );
	oXMLHttpRequest.send( null);
} 


var BrowserDetect = { 
	init: function () { 
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS"; 
	}, 
	searchString: function (data) { 
		for (var i=0;i<data.length;i++) { 
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) { if (dataString.indexOf(data[i].subString) != -1) return data[i].identity; } else if (dataProp) return data[i].identity; 
		} 
	}, 
	searchVersion: function (dataString) { 
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ string: navigator.userAgent, subString: "Chrome", identity: "Chrome" },
		{ string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" },
		{ string: navigator.vendor, subString: "Apple", identity: "Safari" },
		{ prop: window.opera, identity: "Opera" }, { string: navigator.vendor, subString: "iCab", identity: "iCab" },
		{ string: navigator.vendor, subString: "KDE", identity: "Konqueror" },
		{ string: navigator.userAgent, subString: "Firefox", identity: "Firefox" },
		{ string: navigator.vendor, subString: "Camino", identity: "Camino" },
		 // for newer Netscapes (6+) 
		{ string: navigator.userAgent, subString: "Netscape", identity: "Netscape" },
		{ string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" },
		{ string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" },
		// for older Netscapes (4-)
		{ string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" } 
	],
	dataOS : [
		{ string: navigator.platform, subString: "Win", identity: "Windows" },
		{ string: navigator.platform, subString: "Mac", identity: "Mac" },
		{ string: navigator.platform, subString: "Linux", identity: "Linux" } 
	] 
}; 


function arraySearch(arr,val) {
	for (var i=0; i<arr.length; i++)
	if (arr[i] == val)
	return i;
	return false;
}

function compruebaNavegador(){
	if(navAlerta!=1){
		BrowserDetect.init();
		navegadores = new Array("Firefox","Opera","Safari","Explorer","Chrome")
		versiones = new Array(3,9,525,7,7)
//		versiones = new Array(100,100,1525,100,100)
		enlacesNav = new Array("http://www.mozilla-europe.org/es/firefox/","http://www.opera.com/","http://www.apple.com/es/safari/","http://www.microsoft.com/spain/windows/internet-explorer/","http://www.google.com/chrome?hl=es")
		indice = arraySearch(navegadores,BrowserDetect.browser)
		if(indice!==false){
			minVer = versiones[indice];
			if(minVer>BrowserDetect.version){
				alarmaVersion(BrowserDetect.browser,BrowserDetect.version,minVer,enlacesNav[indice]);
			}
		}
	}
}

function alarmaVersion(nav,ver,minVer,enlace){
	objeto = document.createElement("div");
	objeto.className = "alertaVersion"
	objeto.id = "alertaVersion"
	contenedor = document.body;
	contenedor.appendChild(objeto);
	obj = document.getElementById("alertaVersion");
	$("#alertaVersion").css("position","absolute");
	$("#alertaVersion").css("top","0px");
	$("#alertaVersion").css("z-index","100000");
	$("#alertaVersion").css("width","100%");
	$("#alertaVersion").css("height","35px");
	$("#alertaVersion").css("text-align","center");
	$("#alertaVersion").css("color","#ffffff");
	obj.innerHTML = "<div id='alertaVersionBkg'></div><div id='alertaVersionTxt'>"+CONSTANTES['VALID1']+nav+" "+minVer+CONSTANTES['VALID2']+"<a style='color:#ffffff' href='"+enlace+"' title='"+CONSTANTES['DESCARGAR']+"' target='_blank'>"+nav+"</a><a style='color:#ffffff;margin-left:10px;' href='' onclick='cierraAlarmaVer();return false' title='"+CONSTANTES['CERRAR']+"'>"+CONSTANTES['CERRAR']+"</a></div>";
	$("#alertaVersionBkg").css("position","absolute");
	$("#alertaVersionBkg").css("left","0px");
	$("#alertaVersionBkg").css("width","100%");
	$("#alertaVersionBkg").css("height","100%");
	$("#alertaVersionBkg").css("background","#a81029");
	$("#alertaVersionBkg").css("opacity",0.8);
	$("#alertaVersionTxt").css("position","relative");
	$("#alertaVersionTxt").css("top","0px");
	$("#alertaVersionTxt").css("left","0px");
	$("#alertaVersionTxt").css("width","100%");
	$("#alertaVersionTxt").css("padding","8px 0px");
	$("#alertaVersionTxt").css("font-family","Arial");
	$("#alertaVersionTxt").css("font-size","90%");
	$("#alertaVersion").css("top","-"+$("#alertaVersion").css("height"));
	$("#alertaVersion").stop().animate({top: 0},500, 'easeInOutCubic');

//	alert("La version "+ver+" del navegador "+nav+" no es valida");

}

function cierraAlarmaVer(){
	$("#alertaVersion").stop().animate({top: "-"+$("#alertaVersion").height()},500, 'easeInOutCubic');
	cookieNavegador();
}


function cookieNavegador(){
	var oXMLHttpRequest; 
	if(window.XMLHttpRequest) { // no es IE 
		oXMLHttpRequest = new XMLHttpRequest(); 
	} else { // Es IE o no tiene el objeto 
		try { 
			oXMLHttpRequest = new ActiveXObject('Microsoft.XMLHTTP'); 
		} catch (e) { 
			alert('El navegador utilizado no está soportado'); 
		} 
	} 
	oXMLHttpRequest.open( 'GET', URL+'inc/cookieNavegador.php', true );
	oXMLHttpRequest.send( null );


}







//ampliado dinamico


function ampliaImgTodo(img,carpeta,imgs,descarga) {
	if(puedeAmpliar==true){
	    if (!isIE || version >=7){
			puedeAmpliar = false;
			putAmpliado(img,carpeta,imgs,descarga)
		}else{
			window.open(URL+carpeta+"/"+img)
		}
	}
}

function putAmpliado(img,carpeta,imgs,descarga){
	dimensionesWindow =  getWindowData();
	altoWin = dimensionesWindow[1];
	anchoWin = dimensionesWindow[0];
	cantidad = imgs.split(",").length;
	
	objeto = document.createElement("div");
	objeto.id = "ampliadoBkg"
	document.body.appendChild(objeto);
	$("#ampliadoBkg").css("height", "100%");
	$("#ampliadoBkg").css("width", "100%");

	$("#ampliadoBkg").css("position", "fixed");
	$("#ampliadoBkg").css("top", "0px");
	$("#ampliadoBkg").css("left", "0px");
	$("#ampliadoBkg").css("opacity", 0);
	$("#ampliadoBkg").animate({ opacity: 0.8 }, {duration: 600,easing: 'easeOutQuart'});

	
	objeto = document.createElement("div");
	objeto.id = "ampliadoFull"
	document.body.appendChild(objeto);
	$("#ampliadoFull").css("height", "40px");
	$("#ampliadoFull").css("width", "40px");
	$("#ampliadoFull").css("position", "fixed");
	$("#ampliadoFull").css("top", altoWin/2-15+"px");
	$("#ampliadoFull").css("left", anchoWin/2-15+"px");
//	$("#ampliadoFull").corners("8px transparent");

//	$("#ampliado").css("opacity", 0.50);
	var ampliado= document.getElementById("ampliadoFull");

	objeto = new Image();
	objeto.id = "ampliadoImg"
	objeto.style.visibility = "hidden"
	objeto.onload = function(){
		ampliado.appendChild(objeto);
		anchoFinal = $("#ampliadoImg").width();
		altoFinal = $("#ampliadoImg").height();

		if(altoFinal>altoWin-50){
			proporcion = anchoFinal / altoFinal;
			altoFinal = altoWin - 50;
			anchoFinal = proporcion*altoFinal;
		}
		if(anchoFinal>anchoWin-50){
			proporcion = altoFinal / anchoFinal;
			anchoFinal = anchoWin - 50;
			altoFinal = proporcion*anchoFinal;
		}

		$("#ampliadoImg").css("height", "10px");
		$("#ampliadoImg").css("width", "10px");
		$("#ampliadoImg").css("visibility", "");
		$("#ampliadoImg").css("opacity", 0);


//		$("#ampliadoImg").css("margin", "5px");

		leftFinal = anchoWin/2 - anchoFinal/2
		topFinal = altoWin/2 - altoFinal/2
//		$("#ampliadoImg").animate({ height: altoFinal, width: anchoFinal}, {duration: 600,easing: 'easeOutQuart'});

		$("#ampliadoFull").hover( 
				//over
			function () {
				$("#ampliadoBar").stop(true);
				$("#ampliadoBar").animate({ opacity: 1 }, {duration: 600,easing: 'easeOutQuart'});
			},
			//out
			function () {
				$("#ampliadoBar").stop(true);
				$("#ampliadoBar").animate({ opacity: 0 }, {duration: 600,easing: 'easeOutQuart'});
			}
		);
		
		
		
		$("#ampliadoFull").animate({top: topFinal, height: altoFinal}, {duration: 600,easing: 'easeInQuart',complete: function() {
			$("#ampliadoFull").animate({ left: leftFinal, width: anchoFinal}, {duration: 600,easing: 'easeOutQuart',complete: function() {
//				$("#ampliadoImg").css("top", "25px");
				$("#ampliadoImg").css("top", "20px");
				$("#ampliadoImg").css("left", "20px");
				$("#ampliadoImg").css("height", altoFinal-40+"px");
				$("#ampliadoImg").css("width", anchoFinal-40+"px");
				$("#ampliadoFull").animate({ opacity: 1 }, {duration: 600,easing: 'easeOutQuart'});
				$("#ampliadoImg").animate({ opacity: 1 }, {duration: 600,easing: 'easeOutQuart',complete: function() {

					objeto = document.createElement("div");
					objeto.id = "ampliadoBar"
					ampliado.appendChild(objeto);
//					$("#ampliadoBar").css("opacity", 0);
					var ampliadoBar= document.getElementById("ampliadoBar");

					objeto = document.createElement("div");
					objeto.id = "ampliadoBarIn"
					ampliadoBar.appendChild(objeto);
					var ampliadoBarIn= document.getElementById("ampliadoBarIn");


	if(cantidad>1){
					objeto = document.createElement("div");
					objeto.id = "ampliadoLeft"
					objeto.innerHTML = '<a href="" onclick="cambiaAmpliado(1,'+"'"+imgs+"','"+carpeta+"'"+');return false"><img id="ampliadoLeftBkg" src="'+URL+'/img/izqAmpliado.png" onload="arrancaIconosAmpliado(this)"/></a>'
					ampliadoBarIn.appendChild(objeto);
					$("#ampliadoLeftBkg").css("opacity", 0);
	}

					objeto = document.createElement("div");
					objeto.id = "ampliadoClose"
					objeto.innerHTML = '<a href="" onclick="cierraAmpliado2();return false"><img id="ampliadoCloseBkg" src="'+URL+'/img/closeAmpliado.png"  onload="arrancaIconosAmpliado(this)"/></a>'
					ampliadoBarIn.appendChild(objeto);
					$("#ampliadoCloseBkg").css("opacity", 0);


	if(descarga==true){
					objeto = document.createElement("div");
					objeto.id = "ampliadoDownLoad"
					objeto.innerHTML = '<a href="" onclick="descargaAmpliado();return false"><img id="ampliadoDownLoadBkg" src="'+URL+'/img/downAmpliado.png"  onload="arrancaIconosAmpliado(this)"/></a>'
					ampliadoBarIn.appendChild(objeto);
					$("#ampliadoDownLoadBkg").css("opacity", 0);
	}



	if(cantidad>1){
					objeto = document.createElement("div");
					objeto.id = "ampliadoRight"
					objeto.innerHTML = '<a href="" onclick="cambiaAmpliado(2,'+"'"+imgs+"','"+carpeta+"'"+');return false"><img id="ampliadoRightBkg" src="'+URL+'/img/derAmpliado.png" onload="arrancaIconosAmpliado(this)"/></a>'
					objeto.imagen = img;
					ampliadoBarIn.appendChild(objeto);
					$("#ampliadoRightBkg").css("opacity", 0);
	}
//					var cierre= document.getElementById("ampliadoClose");
//					cierre.onclick = cierraAmpliado();
				
				}});
			}});
		}});
	}
//	alert(URL+carpeta+"/"+img)
	objeto.src = URL+carpeta+"/"+img;
}

function descargaAmpliado(){
	objeto = document.getElementById('ampliadoImg');
//	alert(objeto.src);
	
	trozos = objeto.src.split("/");
	nuevaRuta = "";
	for(i=4;i<trozos.length;i++){
		if(i!=4){nuevaRuta += "/"}
		nuevaRuta += trozos[i];
	}
	destino = URL+"inc/descargaFile.php?file="+nuevaRuta;
//	alert(destino);
//	window.open(destino)
	document.location.href= destino
}

function descargaFichero(archivo,nombre){
	destino = URL+"inc/descargaFile.php?file="+archivo+"&fileNombre="+nombre;
	trackAnalytics('#/descarga_archivo/'+nombre);

//	alert(destino);
	document.location.href= destino
//	window.open(destino)
}


function arrancaIconosAmpliado(obj){
	pngFix(obj);
	$("#"+obj.id).stop(true);
	$("#"+obj.id).animate({opacity:1}, {duration: 400,easing: 'easeInQuint'});
}

function cambiaAmpliado(sentido,imgs,carpeta){
	objeto = document.getElementById('ampliadoRight');
	img = objeto.imagen;
	imagenes = imgs.split(",");
	for(i=0;i<imagenes.length;i++){
		if(img == imagenes[i]){
			posicion = i;
			break;
		}
	}

	if(sentido==1){posicion --;}else{posicion ++;}
	if(posicion<0){posicion = imagenes.length-1}
	if(posicion>imagenes.length-1){posicion = 0}
	imgCarga = imagenes[posicion];
	objeto.imagen = imgCarga;
	$("#ampliadoImg").animate({opacity:0}, {duration: 400,easing: 'easeInQuint', complete: function() {
		elemento=document.getElementById('ampliadoImg');
		elemento.parentNode.removeChild(elemento);

		objeto = new Image();
		objeto.id = "ampliadoImg"
		objeto.style.visibility = "hidden"
		objeto.onload = function(){
			var ampliado= document.getElementById("ampliadoFull");
			ampliado.appendChild(objeto);
			anchoFinal = $("#ampliadoImg").width();
			altoFinal = $("#ampliadoImg").height();
			var ampliadoImg= document.getElementById("ampliadoImg");
//			ampliadoImg.onmouseover = apareceBar();
//			ampliadoImg.onmouseout = desapareceBar();

			if(altoFinal>altoWin-50){
				proporcion = anchoFinal / altoFinal;
				altoFinal = altoWin - 50;
				anchoFinal = proporcion*altoFinal;
			}
			if(anchoFinal>anchoWin-50){
				proporcion = altoFinal / anchoFinal;
				anchoFinal = anchoWin - 50;
				altoFinal = proporcion*anchoFinal;
			}

			$("#ampliadoImg").css("height", "10px");
			$("#ampliadoImg").css("width", "10px");
			$("#ampliadoImg").css("visibility", "");
			$("#ampliadoImg").css("opacity", 0);
			leftFinal = anchoWin/2 - anchoFinal/2
			topFinal = altoWin/2 - altoFinal/2
	//		$("#ampliadoImg").animate({ height: altoFinal, width: anchoFinal}, {duration: 600,easing: 'easeOutQuart'});
			$("#ampliadoFull").animate({top: topFinal, height: altoFinal}, {duration: 600,easing: 'easeInQuart',complete: function() {
				$("#ampliadoFull").animate({ left: leftFinal, width: anchoFinal}, {duration: 600,easing: 'easeOutQuart',complete: function() {
					$("#ampliadoImg").css("top", "20px");
					$("#ampliadoImg").css("left", "20px");
					$("#ampliadoImg").css("height", altoFinal-40+"px");
					$("#ampliadoImg").css("width", anchoFinal-40+"px");
					$("#ampliadoFull").animate({ opacity: 1 }, {duration: 600,easing: 'easeOutQuart'});
					$("#ampliadoImg").animate({ opacity: 1 }, {duration: 600,easing: 'easeOutQuart',complete: function() {
					}});
				}});
			}});

		}
		objeto.src = URL+carpeta+"/"+imgCarga;
	}});

}

function cierraAmpliado2(){
	dimensionesWindow =  getWindowData();
	altoWin = dimensionesWindow[1];
	anchoWin = dimensionesWindow[0];
	elemento=document.getElementById('ampliadoClose');
	elemento.parentNode.removeChild(elemento);

	if(cantidad>1){
		elemento=document.getElementById('ampliadoLeft');
		elemento.parentNode.removeChild(elemento);
		elemento=document.getElementById('ampliadoRight');
		elemento.parentNode.removeChild(elemento);
	}

	puedeAmpliar=true
	$("#ampliadoImg").css("position", "absolute");
	altoImg = $("#ampliadoFull").height();
	anchoImg = $("#ampliadoFull").width();

	$("#ampliadoImg").animate({top: altoImg/2-15, height: 30, left: anchoImg/2-15, width: 30, opacity:0}, {duration: 400,easing: 'easeInQuint',complete: function() {
		$("#ampliado").animate({top: altoWin/2-15, height: 30, left: anchoWin/2-15, width: 30, opacity:0.5}, {duration: 400,easing: 'easeInQuart',complete: function() {
		}});
			$("#ampliadoFull").animate({opacity:0}, {duration: 400,easing: 'easeInQuart',complete: function() {
				elemento=document.getElementById('ampliadoFull');
				elemento.parentNode.removeChild(elemento);
				$("#ampliadoBkg").animate({opacity:0}, {duration: 400,easing: 'easeOutQuart',complete: function() {
					elemento=document.getElementById('ampliadoBkg');
					elemento.parentNode.removeChild(elemento);
					puedeAmpliar=true
				}});
			}});
	}});
}

/*
var mouseX;
var mouseY;

$().mousemove( function(e) {
	mouseX = e.pageX;
	mouseY = e.pageY;
});
*/



function modSubMenu(numSec){
	numSubSec = 1;
	$("a",$("#subMenu_"+numSec)).attr("class","cont")
	$('#a_sub_'+numSec+'_'+numSubSec).attr("class","cont inactivo")
}


function clickSubMenu(destino,destinoJS,objeto,numSec,numSubSec){
	$("a",$("#subMenu_"+numSec)).attr("class","cont")
	$('#a_sub_'+numSec+'_'+numSubSec).attr("class","cont inactivo")

	if(letra!=17 && letra!=224){
		clickSec(destino,destinoJS,objeto)
	}else{
		window.open(destino)
		letra = "";
	}


}


function initMaps(){
	if (!isIEOld(6))
	{
		var mapObj = document.getElementById("mapSpace");
		var urlMaps = 'http://maps.google.es/maps/ms?hl=es&amp;ie=UTF8&amp;msa=0&amp;msid=212679265854641439045.0004a597e435a0b63d0cd&amp;ll=42.462418,-2.447087&amp;spn=0.001741,0.003208&amp;z=17&amp;output=embed';
		mapObj.innerHTML = '<iframe id="mapsIframe" width="300" height="220" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="'+urlMaps+'"></iframe>';
	}
}


function centrame(){
	

	if($("#separaSuperior")[0]=!null){
		$("#separaSuperior").css("height","0px")
		$("#separaInferior").css("height","0px")
	}
	var datos = getWindowData();
	var altura = datos[5];
//	alert(altura)
	var alturaContenido = $("#contenidoRow").height();
	var exceso = altura - alturaContenido;



//	var alturaPie = $("#pie").height();
//	var altoRealContent = altura - alturaPie;
	if(exceso>1){
		if($("#separaSuperior")[0]==null){
			$("#contenidoRow").prepend('<div id="separaSuperior"></div>');
			$("#contenidoRow").append('<div id="separaInferior"></div>');
			$("#separaSuperior").css("width","100%")
			$("#separaInferior").css("width","100%")
		}
		$("#separaSuperior").css("height",exceso/2+"px")
		$("#separaInferior").css("height",exceso/2+"px")
//		$("#contenidoRowIn").css("height","525px")
//		$("#contenidoNenuca").css("height","525px")
	}
}




function isIEOld(numMax,numMin){
	if(numMax==null){numMax=7}
	if(numMin==null){numMin=5.5}
	if ((version >= numMin & version <=numMax) && (document.body.filters) && isIE){
		return true;
	}else{
		return false;
	}
}

function overFCB(){
	$("#btFacebookA").css("top","-13px")
}

function outFCB(){
	$("#btFacebookA").css("top","0px")
}

function clickFCB(){
	window.open($("#btFacebookA").attr("href"));
}



function initLogo(){
	if($("#logo").attr("inited")!="true"){
		$("h1",$("#logo")).hover( 
				//over
			function () {
				$("#pie").css("padding-bottom","40px")
				$("#bajoLogo").stop(true);
				$("#bajoLogo").animate({ bottom: "-33px" }, {duration: 600,easing: 'easeOutQuart'});
			},
			//out
			function () {
				$("#bajoLogo").stop(true);
				$("#bajoLogo").animate({ bottom: "0px" }, {duration: 600,easing: 'easeOutQuart',complete:function(){
					$("#pie").css("padding-bottom","0px")
				}});
			}
		);
		$("#logo").attr("inited","true");
	}
}



var intervalEntreFrases = 0;
var timeEntreFrases = 20000;

var numeroFrase = 0;


function initFrase(){


//	alert("init")
		
}

function cambiaFrase(){
	var lasFrases = frasesSeccion.split("0|0");
	numeroFrase ++;
//	alert(numeroFrase+" "+lasFrases.length)
	if(numeroFrase>=lasFrases.length){numeroFrase=0}
	var laFrase = lasFrases[numeroFrase].replace(/&#34;/gi, '"');
//	alert("cambiaFrase "+laFrase)


	if(!isIEOld(8)){
		$("#fraseGrandeIn").stop(true).animate({ opacity: 0 }, {duration: 400,easing: 'easeInQuart',complete:function(){
			$("#fraseGrandeIn").html(laFrase);
			$("#fraseGrandeIn").animate({ opacity: 1 }, {duration: 600,easing: 'easeOutQuart'});
			intervalEntreFrases = setTimeout("cambiaFrase()",timeEntreFrases);

		}});
	}else{
		$("#fraseGrandeIn").html(laFrase);
	}



}




function str_split(s, l)
	{
	        if(l <= 0) return false;
	        if(l == void(0)) return s.split('');
	        var i = 0, k = 0, f = s.length - 1, a = [];
	        while(i<=f) a[k++] = s.slice(i, i+l), i+=l;
	        return a;
	};


/*  Control FPS   */
// Tratamos de conocer cuantos frames por segundo se están mostrando.
// Como no hay animacion no necesitamos el control, pero funciona perfectamente.

var filterStrength = 20;
var frameTime = 0, lastLoop = new Date, thisLoop;
var fpsGlobal = 0;

function initFPS(ciclica){
//	alert("initFPS")

/*	
	if($("#myFps")[0]==null || ciclica==true){
		if($("#myFps")[0]==null){
//			alert("creo trazer")
			var myTracer = '<div id="myFps">frames per seccond</div>';
			$("body").prepend(myTracer)
		}

//		alert("inicio tween fps")
		$("#myFps").animate({ opacity: 1 }, {duration: 1000, step: function() { 
	//		alert("step")
			gameLoop()

		}, complete: function() {
			fpsGlobal = (1000/frameTime).toFixed(1) ;

			if(fpsGlobal<minFPS){
				puedoAnimar = false;
			}

			$(this).html(fpsGlobal+ " fps")
			initFPS(true);
		}});
	}

*/

}

function gameLoop(){
  // ...
  var thisFrameTime = (thisLoop=new Date) - lastLoop;
  frameTime+= (thisFrameTime - frameTime) / filterStrength;
  lastLoop = thisLoop;
}





var puedoCambiarArt = true;

function cambiaFotoArticulo(num,lasFotos,carpeta){
	if(puedoCambiarArt==true){
		var fotosArr = lasFotos.split(",");
		var imagen = fotosArr[num];
		var img = new Image();

		var miPreload = '<div id="preloadFoto"><!-- --></div>'
		$("#pie").append(miPreload)

		$("#selectorFoto").attr("className","");
		$("#selectorFoto").addClass("fot_"+num);

	  
	  // wrap our new image in jQuery, then:
	  $(img)
		// once the image has loaded, execute this code
		.load(function () {
			$("#contenidoMarmotas").prepend($(this))
			$("#fotoArticulo_clon").css("opacity",0)
			$("#fotoArticulo_clon").css("visibility","visible")
			$("#fotoArticulo").stop(true).animate({ opacity: 0 }, {duration: 600,easing: 'easeInQuart'});
			$("#fotoArticulo_clon").stop(true).animate({ opacity: 1 }, {duration: 600,easing: 'easeInQuart',complete:function(){
				$("#fotoArticulo").remove();
				$("#preloadFoto").stop(true).animate({ opacity: 0 }, {duration: 300,easing: 'easeInQuart',complete:function(){$("#preloadFoto").remove();}});
				$(this).attr("id","fotoArticulo");
				puedoCambiarArt = true;
			}});

	//		alert("cargada")
		})
		
		// if there was an error loading the image, react accordingly
		.error(function () {
		  // notify the user that the image could not be loaded
		})
		
		// *finally*, set the src attribute of the new image to our image
		.attr({'src': URL+'lib/'+carpeta+"/"+imagen , 'id': 'fotoArticulo_clon'});
		puedoCambiarArt = false;
	}
}


function cambiaArticulo(sentido,nombres,fotos,carpetaArticulos){
	if(puedoCambiarArt==true){
		var articulos = nombres.split(",");
		var fotosArrays = fotos.split(",");

		var numArticuloAct = $("#controlador1").attr("artActual");
		if(numArticuloAct==null){
			numArticuloAct = 0;
		}else{
			numArticuloAct = parseInt(numArticuloAct);
		}

	//	alert("actual "+numArticuloAct)

		if(sentido==1){
			numArticuloNew = numArticuloAct-1;
		}else{
			numArticuloNew = numArticuloAct+1;
		}

		if(numArticuloNew<0){
			numArticuloNew = articulos.length - 1;
		}else if(numArticuloNew>=articulos.length){
			numArticuloNew = 0;
		}
		
	 
		$("#nameArticulo").html(articulos[numArticuloNew]);
		$("#articuloActual").html((numArticuloNew+1)+" de "+articulos.length);

		var fotosArticulo = fotosArrays[numArticuloNew];
		fotosArticulo = fotosArticulo.split("0|0")
	//	alert(fotosArticulo)

		var botoneraImagenes = "";
		for(i=0;i<fotosArticulo.length;i++){
			myNum = i+1;
			botoneraImagenes += '<div class="numFoto" onclick="cambiaFotoArticulo('+i+','+"'"+fotosArticulo.join(",")+"'"+','+"'"+carpetaArticulos+"'"+')">'+myNum+'</div>';

		}

		botoneraImagenes += '<div id="selectorFoto" class="fot_0"><!-- --></div>';

		$("#controlador2").html(botoneraImagenes)

	//	alert("nuevo "+numArticuloNew)
		
		$("#controlador1").attr("artActual",numArticuloNew);

		cambiaFotoArticulo(0,fotosArticulo.join(","),carpetaArticulos);
	}

}

function abreDest(destino){
	window.open(destino)
}



var posHome = 0;
var intervalEntreHome = 0;
var timeEntreHome = 5000;
var puedoCambiarHome = true;

function cambiaHome(){

	if(puedoCambiarHome==true){
//		alert("cambio")
		posHome++;
		if(posHome==3){posHome=0;}
		var numFoto = posHome + 1;

		var imagen = "Cimg_home_"+numFoto+".jpg";
		var img = new Image();

		var miPreload = '<div id="preloadFoto"><!-- --></div>'
		$("#pie").append(miPreload)


	  
	  // wrap our new image in jQuery, then:
	  $(img)
		// once the image has loaded, execute this code
		.load(function () {
			$("#contenidoMarmotas").prepend($(this))
			$("#fotoArticulo_clon").css("opacity",0)
			$("#fotoArticulo_clon").css("visibility","visible")
			$("#fotoArticulo").stop(true).animate({ opacity: 0 }, {duration: 600,easing: 'easeInQuart'});
			$("#fotoArticulo_clon").stop(true).animate({ opacity: 1 }, {duration: 600,easing: 'easeInQuart',complete:function(){
				$("#fotoArticulo").remove();
				$("#preloadFoto").stop(true).animate({ opacity: 0 }, {duration: 300,easing: 'easeInQuart',complete:function(){$("#preloadFoto").remove();}});
				$(this).attr("id","fotoArticulo");
				puedoCambiarHome = true;
				intervalEntreHome = setTimeout("cambiaHome()",timeEntreHome);
			}});

	//		alert("cargada")
		})
		
		// if there was an error loading the image, react accordingly
		.error(function () {
		  // notify the user that the image could not be loaded
		})
		.click(function () {
			if(CONSTANTES['mobile']==0){
			  clickHome()
			}
		})		
		// *finally*, set the src attribute of the new image to our image
		.attr({'src': URL+'lib/home/'+imagen , 'id': 'fotoArticulo_clon' , 'class': 'puntero'});
		puedoCambiarHome = false;
	}



}

function clickHome(){
	switch(posHome){
		case 0:
			clickSec(URL+"index.php/"+CONSTANTES['MENU1LINK']+"/"+idiomaWeb,CONSTANTES['MENU1LINK']+"/"+idiomaWeb);
			break;
		case 1:
			clickSec(URL+"index.php/"+CONSTANTES['MENU3LINK']+"/"+idiomaWeb,CONSTANTES['MENU3LINK']+"/"+idiomaWeb);
			break;
		case 2:
			clickSec(URL+"index.php/"+CONSTANTES['MENU5LINK']+"/"+idiomaWeb,CONSTANTES['MENU5LINK']+"/"+idiomaWeb);
			break;
	}
}
