var altoAmpliado = 0;
var altoTotal = 401;
var URL = CONSTANTES['urlGeneral'];
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 preSeccion = null;
var preSubSeccion = null;
var preSubApartado = null;

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


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


var objetoDestino = "";
var objetoDestinoGeneral = "contenidoRowIn";

//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("opacity",1);
		$("#"+capa).css("visibility","visible");
	}else{
		$("#"+capa).stop(true);
		$("#"+capa).animate({ opacity: 1 }, {duration: 200,easing: 'easeInQuart'});
	}
	goTop();

}	



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 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;
	}

	$("#bajoLogo").css("visibility","visible");
/*	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 amplia(img,carpeta,ID) {
	if(puedeAmpliar==true){
		puedeAmpliar = false;
		ampliando(img,carpeta,ID)
	}
}

function ampliando(img,carpeta,ID) {
	resto = altoTotal-altoAmpliado
	if(resto>5){
		altoAmpliado = altoAmpliado + resto/2
	}else{
		altoAmpliado = altoTotal
	}
	var capa= document.getElementById("ampliado");
	capa.style.height = altoAmpliado+"px";
	capa.style.top = '64px';
	if(altoAmpliado>=altoTotal){
//		contenido = '<img src="http://www.inspirate.es/clientes/otazu/img/fotoBig/'+img+'" class="imgAmpliada"/>';
		valor = '<div id="imgAmpliada">';
		valor+= '	<div style='+'"'+'background:url('+URL+carpeta+img+")"+';width:750px;height:380px;"'+' id="imgAmpliadaIn">';
		valor+= '		<div id="cerrarAmpliado" onclick="cierra('+ID+')">'
		valor+= '			<div id="cerrarAmpliadoInBkg" onclick="cierra('+ID+')">'
		valor+= '			</div>'
		valor+= '			<div id="cerrarAmpliadoIn" onclick="cierra('+ID+')">'
		valor+= '				CERRAR'
		valor+= '			</div>'
		valor+= '			<div id="cerrarAmpliadoInSobre" onclick="cierra('+ID+')">'
		valor+= '			</div>'
		valor+= '			<div id="cerrarAmpliadoIn2" onclick="cierra('+ID+')">'
		valor+= '			</div>'
		valor+= '		</div>'
		valor+= '	</div>'
		valor+= '</div>'
		setContenido("ampliado",valor)
		$("#imgAmpliada").stop(true);
		$("#imgAmpliada").animate({ opacity: 100 }, {duration: 1200,easing: 'easeOutQuart'});
		if(ID!=null){
			obj = document.getElementById("menuGestor");
			previo = obj.innerHTML;
			obj.innerHTML = '<a href="" onclick="edit('+"'"+'galeria'+"'"+','+ID+');return false;" id="editBtn"><img src="'+URL+'img/iconos/entrar.jpg" title="Editar registro"/></a> ' + obj.innerHTML
		}
	}else{
		setTimeout(function () {ampliando(img,carpeta,ID)}, 50)
	}

}


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];
} 


//SUBMENU

function rollOver(obj,objSubM){
	if(CONSTANTES['idioma']=="ES"){idioma = "en"}else{idioma = "es"}
	var objeto = document.getElementById(obj);
	numObjeto = objeto.id.slice(1,2)
	objeto.estado = 1;
	valorID = objeto.id

	if(seccion=="" || seccion==" "){
		aComparar = seccionInicio;
	}else{
		aComparar = seccion;
	}

	if(aComparar!=numObjeto){
		var objeto = document.getElementById("am"+numObjeto);
		objeto.style.color = "#ffffff"
		Cufon.set("fontFamily", "Garamond LT LightCondensed").replace('#am'+numObjeto);
		$("#bkgMenu"+numObjeto).stop(true);
		$("#bkgMenu"+numObjeto).animate({right: '0px'}, {duration: 300,easing: 'easeOutQuart'});

	}
}

function rollOut(obj,objSubM){
	if(CONSTANTES['idioma']=="ES"){idioma = "en"}else{idioma = "es"}
	var objeto = document.getElementById(obj);
	numObjeto = objeto.id.slice(1,2)
	objeto.estado = 2;
	valorID = objeto.id
	if(seccion=="" || seccion==" "){
		aComparar = seccionInicio;
	}else{
		aComparar = seccion;
	}
	if(aComparar!=numObjeto){
		var objeto = document.getElementById("am"+numObjeto);
		objeto.style.color = "#4c4c4c"
		Cufon.set("fontFamily", "Garamond LT LightCondensed").replace('#am'+numObjeto);
		$("#bkgMenu"+numObjeto).stop(true);
		$("#bkgMenu"+numObjeto).animate({right: '-212px'}, {duration: 300,easing: 'easeOutQuart'});
	}
}

function initMenu(animame){

	if(seccion=="" || seccion==" "){
		var aComparar = seccionInicio;
	}else{
		var aComparar = seccion;
	}

	if(subSeccion=="" || subSeccion==" "){
		var aCompararSub = subSeccionInicio;
	}else{
		var aCompararSub = subSeccion;
	}

	if(animame!=true){  //NO LLEGA DESDE AJAX ASI K SOLO ESTUDIA PARA CERRAR
		for(i=1;i<=7;i++){
			if($("#subMenu_"+i)[0]!=null){
				if(aComparar!=i){
					$("#subMenu_"+i).attr("iniHeight",$("#subMenu_"+i).height())
					$("#subMenu_"+i).css("height","0px");
					$("#subMenu_"+i).css("padding-bottom","0px");
					$("#subMenu_"+i).css("visibility","hidden");
					$('.cont',$("#subMenu_"+i)).attr("class","cont")
				}
			}
		}
	}else{

		for(i=1;i<=7;i++){
			if($("#subMenu_"+i)[0]!=null){
				if(aComparar!=i){
					if($("#subMenu_"+i).attr("iniHeight")==null){
						$("#subMenu_"+i).attr("iniHeight",$("#subMenu_"+i).height())
					}
					$("#subMenu_"+i).css("padding-bottom","0px");
					$("#subMenu_"+i).stop().animate({height:0}, {duration: 500,easing: 'easeOutQuint', complete: function() {
						$("#subMenu_"+i).css("visibility","hidden");
					}});
					$('.cont',$("#subMenu_"+i)).attr("class","cont")
				}else{
					$("#subMenu_"+i).css("visibility","visible");
					$("#subMenu_"+i).css("padding-bottom","14px");
					if($("#subMenu_"+i).attr("iniHeight")!=null){
						$("#subMenu_"+i).stop().animate({height:$("#subMenu_"+i).attr("iniHeight")}, {duration: 500,easing: 'easeOutQuint'});
					}
					$(".cont",$("#subMenu_"+i)).css("background","#ffffff")
					$(".cont",$("#subMenu_"+i)).css("color","#4c4c4c");
					Cufon.set("fontFamily", "Garamond LT LightCondensed").replace(".cont");
					$("#a_sub_"+aComparar+"_"+aCompararSub).css("background","#000000")
					$("#a_sub_"+aComparar+"_"+aCompararSub).css("color","#ffffff");
					Cufon.set("fontFamily", "Garamond LT LightCondensed").replace('#a_sub_'+aComparar+'_'+aCompararSub);

				}
			}
		}

	}

/*	$(".cont",$("ul.subMenu")).mouseover(function() {
		$(this).css("background","#000000")
		$(this).css("color","#ffffff")
	}).mouseout(function(){
		$(this).css("background","#ffffff")
		$(this).css("color","#4c4c4c")
	})*/

	$(".bkgMenuBtn").unbind("click");		

	$(".bkgMenuBtn").click(function(event) {
		var agent = jQuery.browser;
		if(agent.msie) {
			event.cancelBubble = true;
		} else {
			event.stopPropagation();
		}
		var enlace = $("a",$(".interior",$(this).parent()))
		var direccion = enlace.attr("href");
		var direccionJS = enlace.attr("href").split(URL+"index.php/").join('')
//		alert(direccion+" "+direccionJS)
		if($(this).parent().attr("id")!="l5"){
			clickSec(direccion,direccionJS,$(this));
		}else{
			window.open('http://www.tiendasonsierra.com')
		}
	});



	$(".asubM").unbind("click");		
	
	$(".asubM").click(function(event) {
		var agent = jQuery.browser;
		if(agent.msie) {
			event.cancelBubble = true;
		} else {
			event.stopPropagation();
		}
		event.preventDefault();
		var enlace = $(this);
		var direccion = enlace.attr("href");
		var direccionJS = enlace.attr("href").split(URL+"index.php/").join('')
//		alert(direccion+" "+direccionJS)
		clickSec(direccion,direccionJS,$(this));
	});

}

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){

	pngFix(document.getElementById(objStr))
//	$("#"+objStr).css("opacity", 0)
	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";*/
}

function setFixed(){	//SE ENCAGA DE QUITAR LOS FIXED EN TAMAÑOS INADECUADOS O VERSIONES DEL NAVEGADOR QUE NO LO SOPORTAN

	valores = getWindowData();
	anchoTotal = valores[0];
	altoTotal = valores[1];
	minAncho = $("#cabecera").width();
	if(document.getElementById("control")!=null){
		minAlto = $("#control").height()+177;
	}else if(document.getElementById("menuCalcco")!=null){
		minAlto = $("#menuCalcco").height()+177;
	}else{
		minAlto = 0;
	}
	
	if( (anchoTotal<minAncho || altoTotal<minAlto || (isIE && (version <=6))) || CONSTANTES['FIXED']==false ){
		$("#cabeceraFila").css("position","relative");
		$("#cabeceraFila").css("top","0px");
		$("#topC").css("position","relative");
		$("#bajoCabecera").css("height","1px");
		$("#control").css("position","relative");
		$("#control").css("top","0px");
		$("#control").css("float","left");
		$("#control").css("display","inline");
		$("#menuCalcco").css("position","relative");
		$("#menuCalcco").css("top","0px");
		$("#menuCalcco").css("float","left");
		$("#menuCalcco").css("display","inline");
	}else{
		$("#cabeceraFila").css("position","fixed");
		$("#cabeceraFila").css("top","20px");
		$("#topC").css("position","fixed");
		$("#bajoCabecera").css("height","178px");
		$("#control").css("position","fixed");
		$("#control").css("top","177px");
		$("#control").css("float","none");
		$("#control").css("display","block");
		$("#menuCalcco").css("position","fixed");
		$("#menuCalcco").css("top","178px");
		$("#menuCalcco").css("float","none");
		$("#menuCalcco").css("display","block");
	}
}

function overIdioma(obj){
	numero = obj.id.split("_");
	numero = numero[(numero.length-1)]
	obj = $("#imgLang_"+numero)
	obj.stop(true);
	obj.animate({top: '0px'}, {duration: 100,easing: 'easeOutQuad'});
}

function outIdioma(obj){
	numero = obj.id.split("_");
	numero = numero[(numero.length-1)]
	obj = $("#imgLang_"+numero)
	obj.stop(true);
	obj.animate({top: '-16px'}, {duration: 100,easing: 'easeOutQuad'});

}

function overRed(num){
	$("#red_txt").html(CONSTANTES["TIT_RED_"+num]);
}

function outRed(num){
	$("#red_txt").html("");
}


///////////////////////////////////////////////////////////////////////////////////////////////
//SLIDER
///////////////////////////////////////////////////////////////////////////////////////////////

idInterval = 0;

function initSlide(desdeJS){
//	alert(desdeJS)
	if(seccion!=""){var miSeccion = seccion}else{var miSeccion = seccionInicio}
	
	if(preSeccion!=null || desdeJS!=true){  // Solo hay apagado y encendido cuando cambia de seccion o llegue desde php.
	
		salida = "";
		switch (miSeccion) {
			case "0":
				fotos = new Array("home1.jpg","home2.jpg","home3.jpg","home4.jpg","home5.jpg");
				salida += '		<div class="bgSlider"></div>';
				i=0;
					salida += '	<img class="imgSlider" src="'+URL+'img/cabeceras/home/'+fotos[i]+'" alt ="Cabecera"  onload="iniciarCicloSlide(true)"/>';
				for(i=1;i<fotos.length;i++){
					salida += '	<img class="imgSlider" src="'+URL+'img/cabeceras/home/'+fotos[i]+'" alt ="Cabecera" />';
				}
				fotoInicial = URL+'img/cabeceras/home/'+fotos[0];
				break;
		   case "1":
				salida += '	<img src="'+URL+'img/cabeceras/sonsierra/uno.jpg" alt ="Cabecera" onload="iniciarCicloSlide()"/>';
				fotoInicial = URL+'img/cabeceras/sonsierra/uno.jpg';
				break;
		   case "2":
				salida += '	<img src="'+URL+'img/cabeceras/vinedos/uno.jpg" alt ="Cabecera" onload="iniciarCicloSlide()"/>';
				fotoInicial = URL+'img/cabeceras/vinedos/uno.jpg';
				break;
		   case "3":
				salida += '	<img src="'+URL+'img/cabeceras/bodega/uno.jpg" alt ="Cabecera" onload="iniciarCicloSlide()"/>';
				fotoInicial = URL+'img/cabeceras/bodega/uno.jpg';
				break;
		   case "4":
				salida += '	<img src="'+URL+'img/cabeceras/vinos/uno.jpg" alt ="Cabecera" onload="iniciarCicloSlide()"/>';
				fotoInicial = URL+'img/cabeceras/vinos/uno.jpg';
				break;
		   case "6":
				salida += '	<img src="'+URL+'img/cabeceras/noticias/uno.jpg" alt ="Cabecera" onload="iniciarCicloSlide()"/>';
				fotoInicial = URL+'img/cabeceras/noticias/uno.jpg';
				break;
		   case "7":
				salida += '	<img src="'+URL+'img/cabeceras/descargas/uno.jpg" alt ="Cabecera" onload="iniciarCicloSlide()"/>';
				fotoInicial = URL+'img/cabeceras/descargas/uno.jpg';
				break;
		   case "8":
				salida += '	<img src="'+URL+'img/cabeceras/contacto/uno.jpg" alt ="Cabecera" onload="iniciarCicloSlide()"/>';
				fotoInicial = URL+'img/cabeceras/contacto/uno.jpg';
				break;
		   case "10":
				salida += '	<img src="'+URL+'img/cabeceras/aviso/uno.jpg" alt ="Cabecera" onload="iniciarCicloSlide()"/>';
				fotoInicial = URL+'img/cabeceras/aviso/uno.jpg';
				break;
		   default:
				salida += '	<img src="'+URL+'img/cabeceras/sonsierra/uno.jpg" alt ="Cabecera" onload="iniciarCicloSlide()"/>';
				fotoInicial = URL+'img/cabeceras/sonsierra/uno.jpg';
				break;
		}



	var img = new Image();

	  $(img)
		.load(function () {
				$("#slider").css("visibility","hidden")
				$("#slider").css("opacity",0)
				$("#sliderIn").html(salida)
				$(".imgSlider:eq(0)").css("position","absolute");
				$(".imgSlider:eq(0)").css("top","0px");
				$(".imgSlider:eq(0)").css("z-index","1");
		})
		.attr('src',fotoInicial);





	}
	clearInterval(idInterval);
}

function iniciarCicloSlide(iniciarSlide){
	$("#slider").css("visibility","visible")
	$("#slider").stop().animate({opacity:1}, {duration: 1500,easing: 'easeOutQuint'});
	if(iniciarSlide==true){
		idInterval = setInterval("mueveSlide2()",10000);
	}
}



function mueveSlide(){
	var objAmover = $(".imgSlider:eq(0)");
	posicion = objAmover.css("margin-left");
	posicion = posicion.slice(0,posicion.length-2)
	objAmover.css("margin-left",(posicion-1)+"px");
	var anchoObj = objAmover.width();
	var posicionObj = posicion-1;
	if(posicionObj<-anchoObj){
		var objCopiaHtml = '<img class="imgSlider" src="'+objAmover.attr("src")+'" alt ="Cabecera Img" />';
		objAmover.remove();
		$("#sliderIn").append(objCopiaHtml)
	}
}


function mueveSlide2(){
	var objDesap = $(".imgSlider:eq(0)");
	var objApar = $(".imgSlider:eq(1)");
	objApar.css("position","absolute");
	objApar.css("z-index","0");
	objApar.css("top","0px");
	objApar.css("left","0px");
//	objApar.css("height","0px");
//	objApar.css("width","0px");
	objApar.css("opacity","0");
	objDesap.css("z-index","1");

	var objCopiaHtml = '<img class="imgSlider" src="'+objDesap.attr("src")+'" alt ="Cabecera Img" />';

	objApar.stop().animate({opacity:1}, {duration: 500,easing: 'easeOutQuint'});
	objDesap.stop().animate({opacity:0}, {duration: 500,easing: 'easeOutQuint', complete: function() {
		objDesap.remove();
		$("#sliderIn").append(objCopiaHtml)
	}});

}

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


///////////////////////////////////
//	 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")
	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 initSubMenu(ajax,clase){		//FUNCION PARA INICIALIZAR EL SUBMENU DE LA SECCION CALCCO

/*	$("#lSec2").mouseover(function() {
		if((subSeccion!=2 && CONSTANTES['SEGUIMIENTOJS']==true) || (subSeccionInicio!=2 && CONSTANTES['SEGUIMIENTOJS']!=true)){
			$("#subSubMenu2").stop().animate({height: preHeightSM},500, 'easeInOutCubic');
		}
	}).mouseout(function(){
		if((subSeccion!=2 && CONSTANTES['SEGUIMIENTOJS']==true) || (subSeccionInicio!=2 && CONSTANTES['SEGUIMIENTOJS']!=true)){
			$("#subSubMenu2").stop().animate({height: 0},500, 'easeInOutCubic');
		}
	});*/


	if(ajax!=null && ajax==true){
		if(clase=="graph"){  //ESTO SE EJECUTA ANTES DE CARGAR EL CONTENIDO, XA LOS COLORES DE LOS BOTONES... 
			$("#amSec"+subSeccion).attr("class","inactivo");
			$("#amSec"+subSeccion).blur();
			if(preSubSeccion!=null && preSubSeccion!=""){
				$("#amSec"+preSubSeccion).attr("class","");
			}else if(subSeccion!=subSeccionInicio){
				$("#amSec"+subSeccionInicio).attr("class","");
			}
			if(preSubApartado!=null && preSubApartado!=""){
				$("#amTer"+subSeccion+"_"+preSubApartado).attr("class","");
			}else if(subApartado!=subApartadoInicio){
				$("#amTer"+subSeccion+"_"+subApartadoInicio).attr("class","");
			}

			if(subApartado!=0){
				$("#amTer"+subSeccion+"_"+subApartado).attr("class","inactivo");
				$("#amTer"+subSeccion+"_"+subApartado).blur();
			}
		}
		if(clase=="move"){
			if(subSeccion!=2){		//ESTO SE EJECUTA DESPUES DE CARGAR EL CONTENIDO, ASI NOS ASEGURAMOS DE QUE EXISTA EL SUBMENU
				$("#amTer"+preSubSeccion+"_"+preSubApartado).attr("class","");
				$("#subSubMenu2").slideUp("slow", function() {
					setFixed();
				});
			}else{
				$("#subSubMenu2").css("height","auto");
				$("#subSubMenu2").slideDown("slow", function() {
					setFixed();
				});

			}
		}
	}else{
		if(subSeccion!=""){    // PARA HACERLO DESDE PHP
			if(subSeccion!=2){
				$("#subSubMenu2").css("height","0px");
			}
		}else if(subSeccionInicio!=2){
			$("#subSubMenu2").css("height","0px");
		}
	}
}


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

}

function desactivaDestacados(){
	for(i=0;i<=5;i++){
		$("#ampliadoHome"+i).css("opacity", 0.55)
	}
}

function activaDestacado(obj){
	num = obj.id.slice(obj.id.length-1,obj.id.length)
	$("#flechaAmpliado"+num).css("top" , -39)
	$("#imagenAmpliado"+num).stop(true);
	$("#imagenAmpliado"+num).animate({ top: -202 }, {duration: 150,easing: 'easeOutSine'});
//	$("#imagen2Ampliado"+num).stop(true);
//	$("#imagen2Ampliado"+num).animate({ top: 0 }, {duration: 150,easing: 'easeOutSine'});
}

function desactivaDestacado(obj){
	num = obj.id.slice(obj.id.length-1,obj.id.length)
	$("#flechaAmpliado"+num).css("top" , 0)
	$("#imagenAmpliado"+num).stop(true);
	$("#imagenAmpliado"+num).animate({ top: 0 }, {duration: 250,easing: 'easeOutQuint'});
//	$("#imagen2Ampliado"+num).stop(true);
//	$("#imagen2Ampliado"+num).animate({ top: 202 }, {duration: 250,easing: 'easeOutQuint'});
}

function activaPortFolio(num){
//	num = obj.id.slice(9,obj.id.length)
	$("#listadoLiFoto"+num).stop(true);
	$("#listadoLiFoto"+num).animate({ top: -202 }, {duration: 150,easing: 'easeOutSine'});
	$("#listadoLiTexto"+num).stop(true);
	$("#listadoLiTexto"+num).animate({ top: 0 }, {duration: 150,easing: 'easeOutSine'});
	$("#flechaAmpliadoA"+num).stop(true);
	$("#flechaAmpliadoA"+num).animate({ bottom: 0 }, {duration: 150, delay:150, easing: 'easeOutSine'});
}

function desactivaPortFolio(num){
//	num = obj.id.slice(9,obj.id.length)
	$("#listadoLiFoto"+num).stop(true);
	$("#listadoLiFoto"+num).animate({ top: 0 }, {duration: 250,easing: 'easeOutQuint'});
	$("#listadoLiTexto"+num).stop(true);
	$("#listadoLiTexto"+num).animate({ top: 202 }, {duration: 250,easing: 'easeOutQuint'});
	$("#flechaAmpliadoA"+num).stop(true);
	$("#flechaAmpliadoA"+num).animate({ bottom: -241 }, {duration: 250,easing: 'easeOutSine'});
}


function activaFlecha(num){
	$("#flechaAmpliado"+num).css("position" , "absolute")
	$("#flechaAmpliado"+num).css("top" , "-39px")
}

function desactivaFlecha(num){
	$("#flechaAmpliado"+num).css("top" , "0px")
}

function overBlog(){
	$("#flechaAmpliado4").css("position" , "absolute")
	$("#flechaAmpliado4").css("top" , "-39px")
}

function outBlog(){
	$("#flechaAmpliado4").css("top" , "0px")
}

function sobreCorreo(obj,str){
	if(str==null){
		str="HOMETXT21"
	}
//	alert(CONSTANTES[str])
	valorCorreo = obj.value;
	if(CONSTANTES[str] == valorCorreo){
		obj.value = "";;
	}
}

function outCorreo(obj,str){
	if(str==null){
		str="HOMETXT21"
	}
	valorCorreo = obj.value;
	if(valorCorreo == ""){
		obj.value = CONSTANTES[str];
	}
}


function valida_newsletter(){
	document.getElementById("formError").innerHTML = "";
	if(document.newsForm.correo.value.length==0 || document.newsForm.correo.value==CONSTANTES["HOMETXT21"]){
		alert(CONSTANTES['ERROR3'])
		document.newsForm.correo.focus()
		document.getElementById("formError").innerHTML = CONSTANTES['ERROR3'];
	}else{
		correo = document.newsForm.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.newsForm.correo.focus()
			document.getElementById("formError").innerHTML = CONSTANTES['ERROR4'];
		}else{
			enviaAltaNews();
		}
	}

}



function enviaAltaNews(){ 
	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("formError").innerHTML = CONSTANTES['ENVIADO'];
				document.newsForm.correo.value=CONSTANTES['HOMETXT21'];
			}else{
				alert(CONSTANTES[resultado])
				document.getElementById("formError").innerHTML = CONSTANTES[resultado];
			}
			obj = document.newsForm;
			obj.submit.style.visibility="visible";
		}
	};
	obj = document.newsForm;
	obj.submit.style.visibility="hidden";
	document.getElementById("formError").innerHTML = "Enviando...";
	envio = URL+'inc/altaNews_JS.php?correo='+document.newsForm.correo.value+'&basico='+document.newsForm.basico.value+'&tipo='+document.newsForm.tipo.value+'&idioma='+document.newsForm.idioma.value+'&dSeccion='+document.newsForm.dSeccion.value;
//	alert(envio)
	oXMLHttpRequest.open( 'GET', envio, true );
	oXMLHttpRequest.send( null);
} 


function sobreCorreo2(obj){
	str="HOMETXT22"
//	alert(CONSTANTES[str])
	valorCorreo = obj.value;
	if(CONSTANTES[str] == valorCorreo){
		obj.value = "";;
	}
}

function outCorreo2(obj){
	str="HOMETXT22"
	valorCorreo = obj.value;
	if(valorCorreo == ""){
		obj.value = CONSTANTES[str];
	}
}

function valida_blog(){
	document.getElementById("formErrorBlog").innerHTML = "";
	if(document.blogForm.correo.value.length==0 || document.blogForm.correo.value==CONSTANTES["HOMETXT21"]){
		alert(CONSTANTES['ERROR3'])
		document.blogForm.correo.focus()
		document.getElementById("formErrorBlog").innerHTML = CONSTANTES['ERROR3'];
	}else{
		correo = document.blogForm.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.blogForm.correo.focus()
			document.getElementById("formErrorBlog").innerHTML = CONSTANTES['ERROR4'];
		}else{
			enviaAltaBlog();
		}
	}

}

function enviaAltaBlog(){ 
	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("formErrorBlog").innerHTML = CONSTANTES['ENVIADO'];
				document.blogForm.correo.value=CONSTANTES['HOMETXT22'];
			}else{
				alert(CONSTANTES[resultado])
				document.getElementById("formErrorBlog").innerHTML = CONSTANTES[resultado];
			}
			obj = document.blogForm;
			obj.submit.style.visibility="visible";
		}
	};
	obj = document.blogForm;
	obj.submit.style.visibility="hidden";
	document.getElementById("formErrorBlog").innerHTML = "Enviando...";
	envio = URL+'inc/altaNews_JS.php?correo='+document.blogForm.correo.value+'&basico='+document.blogForm.basico.value+'&tipo='+document.blogForm.tipo.value+'&idioma='+document.blogForm.idioma.value+'&dSeccion='+document.blogForm.dSeccion.value;
//	alert(envio)
	oXMLHttpRequest.open( 'GET', envio, true );
	oXMLHttpRequest.send( null);
} 


function overBtnSlide(obj){
}

function outBtnSlide(obj){
}


function overRedes(obj){
	num = obj.id.slice(6,7);
	objeto = document.getElementById('imgRedes'+num);
	objeto.src = URL+"img/b_redes"+num+".jpg";
}

function outRedes(obj){
	num = obj.id.slice(6,7);
	objeto = document.getElementById('imgRedes'+num);
	objeto.src = URL+"img/redes"+num+".jpg";
}


function overCompartir(obj){
	obj.style.backgroundPosition = '0px -16px'
	var trozos = $("img", obj).attr("src").split("/");
	imagenActual = trozos[(trozos.length-1)].split(".")[0];
	imagenDestino = URL+"img/"+imagenActual+"2.jpg"
	$("img", obj).attr("src",imagenDestino)
}

function outCompartir(obj){
	obj.style.backgroundPosition = '0px -16px'
	var trozos = $("img", obj).attr("src").split("/");
	imagenActual = trozos[(trozos.length-1)].split(".")[0];
	imagenActual = imagenActual.slice(0,(imagenActual.length-1))
	imagenDestino = URL+"img/"+imagenActual+".jpg"
	$("img", obj).attr("src",imagenDestino)
}

///////////////////////////////////
//	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];
	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;
	}


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

//	alert("SECCION "+SECCION)

	if(SECCION==4){
		objetoDestino = "contentHomeVinos";
	}else if(SECCION==6){
		objetoDestino = "contentNoticias";
	}else if(SECCION==7){
		if(subSeccion==SUBSECCION){
			objetoDestino = "contentDescargas";
		}else{
			objetoDestino = objetoDestinoGeneral;
		}
	}else{
		objetoDestino = objetoDestinoGeneral;
	}

//	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],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],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")
			cargaContenidoExterno(seccionInicio,subSeccionInicio,subApartadoInicio,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;
		}
	}
}

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


function cargaContenidoExterno(section,subsection,subapart,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("objDest "+objetoDestino)
	getCargando();
	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("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);
					clearInterval(idCargando);
				}});
			}
			document.title = str_replace("&nbsp;"," ",tituloPagina);
		}
	};
	if(idioma!=null){
		idiomaDestino = idioma
	}else{
		idiomaDestino = idiomaWeb
	}
	envio = URL+"inc/getContentAJAX.php?idiomaWeb="+idiomaDestino+"&seccion="+section+"&subSeccion="+subsection+"&subApartado="+subapart+"&seccionID="+sectionID+"&subSeccionID="+subsectionID+"&subApartadoID="+subapartID+"&direccionInicial="+direccionInicial+"&tipoNavegador="+tipoNavegador;
//	alert(envio);


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

		if(seccion!=""){
			$("#l"+seccion).attr("class","activo");
			$("#am"+seccion).css("color","#4c4c4c");
			Cufon.set("fontFamily", "Garamond LT LightCondensed").replace("#am"+seccion);
			$("#bkgMenu"+seccion).stop(true);
			$("#bkgMenu"+seccion).animate({right: '-212px'}, {duration: 300,easing: 'easeOutQuart'});

		}else{
			$("#l"+seccionInicio).attr("class","activo");
			$("#am"+seccionInicio).css("color","#4c4c4c");
			Cufon.set("fontFamily", "Garamond LT LightCondensed").replace("#am"+seccionInicio);
			$("#bkgMenu"+seccionInicio).stop(true);
			$("#bkgMenu"+seccionInicio).animate({right: '-212px'}, {duration: 300,easing: 'easeOutQuart'});
		}
			$("#l"+section).attr("class","inactivo");
			$("#am"+section).css("color","#ffffff");
			Cufon.set("fontFamily", "Garamond LT LightCondensed").replace("#am"+section);
			$("#bkgMenu"+section).stop(true);
			$("#bkgMenu"+section).animate({right: '0px'}, {duration: 300,easing: 'easeOutQuart'});

/*		if((section>=1 && section<=7) || (section>=9 && section<=10) ){
			$("#am"+section).attr("class","inactivo");
			$("#l"+section).css("background-position","bottom left");
		}*/

/*		if(seccion==0){	//INICIALIZAMOS VARIABLES DEL SLIDER CUANDO NOS VAMOS DE LA HOME, NO LO HACEMOS AL VOLVER XK ASI ELIMINAMOS EL TIMER
			clearInterval(idInterval);
		}*/

		
		preSeccion = seccion;
		seccion = section;
	}else{
		preSeccion = null;
	}
	if(subSeccion!=subsection){
		preSubSeccion = subSeccion;
		subSeccion = subsection;
		if(seccion<=4 || seccion==7){
			$("#a_sub_"+seccion+"_"+subSeccion).attr("class","cont inactivo")
			if(preSubSeccion!=""){
				$("#a_sub_"+seccion+"_"+preSubSeccion).attr("class","cont")
			}else{
				$("#a_sub_"+seccion+"_"+subSeccionInicio).attr("class","cont")
			}
			$(".botella_bn",$(".botella.num_"+preSubSeccion)).stop().animate({height:280}, {duration: 100,easing: 'easeOutQuad'})

		}
	}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();
		}
	}




	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");
//			alert(totalImgsCargadas+" de "+totalImgs+" initFade")
			initFade(objetoDestino)
//			alert(scriptJS)
			eval(scriptJS);
			Hyphenator.run()
			cargaCompleta = true;
			$("#cargandoGlobal").stop(true);
			$("#cargandoGlobal").animate({ opacity: 0 }, {duration: 1200,easing: 'easeInQuart', complete: function() {
				elemento=document.getElementById('cargandoGlobal');
				elemento.parentNode.removeChild(elemento);
				clearInterval(idCargando);
			}});
			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;
}


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


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

idCargando = 0;


function getCargando(){
	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').attr("miPos");
	if(posicion!=null){
		posicion = parseInt(posicion);
	}else{
		posicion = 0;
	}
	var posFin = -posicion*25;
	posicion++;
	if(posFin<=-200){posFin=0;posicion=1;}
	$('#cargandoGlobal').attr("miPos",posicion)
	$('#cargandoGlobal').css('background-position', posFin+'px 0px');
}



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


//////////////////////////
//  INCRUSTAR TWEETER CARGA AJAX
///////////////////////////

function incrustaTweetwer(scr1,scr2){
	cargaJSExterno(scr1)
	cargaJSExterno(scr2)
}


function introduceScriptExterno(b){
	e=document;
	var a=e.getElementsByTagName("head")[0];
	a|| (a=e.body.parentNode.appendChild(e.createElement(" head")));
	a.appendChild(b)}function _loadJs(b){var a=e.createElement("script");
	a.type="text/javascript";a.charset="UTF-8";a.src=b;f(a)
}

function cargaJSExterno(b){
	e=document;
	var a=e.createElement("script");
	a.type="text/javascript";
	a.charset="UTF-8";
	a.src=b;
	introduceScriptExterno(a)
}

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



//////////////////////////
//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.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+'&comment='+document.consultaForm.comment.value, true );
	oXMLHttpRequest.send( null);
} 


function valida_enviar_blog(idBlog){
	document.getElementById("formErrorBlogComs").innerHTML = "";
	if (document.commentForm.comment_contacto.value.length==0){
		alert(CONSTANTES['ERROR1'])
		document.commentForm.comment_contacto.focus()
		document.getElementById("formErrorBlogComs").innerHTML = CONSTANTES['ERROR1'];
	}else if(document.commentForm.nombre_contacto.value.length==0){
		alert(CONSTANTES['ERROR2'])
		document.commentForm.nombre_contacto.focus()
		document.getElementById("formErrorBlogComs").innerHTML = CONSTANTES['ERROR2'];
	}else{
		if(document.commentForm.correo_contacto.value.length!=0){
			correo = document.commentForm.correo_contacto.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.commentForm.correo_contacto.focus()
				document.getElementById("formErrorBlogComs").innerHTML = CONSTANTES['ERROR4'];
			}else{
				enviaCommentBlog(idBlog);
			}
		}else{
			enviaCommentBlog(idBlog);
		}
	}
}


function enviaCommentBlog(idBlog){
	if(CONSTANTES['idioma']=="ES"){idioma = "1"}else{idioma = "2"}
	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"){
				getCommentsBlog(idBlog);
			}else{
				alert(CONSTANTES['ERROR_ENVIO'])
				document.getElementById("formErrorBlogComs").innerHTML = CONSTANTES['ERROR_ENVIO'];
			}
			obj = document.commentForm;
			obj.submit.style.visibility="visible";
		}
	};
	obj = document.commentForm;
	obj.submit.style.visibility="hidden";
	document.getElementById("formErrorBlogComs").innerHTML = "Enviando...";
	consulta = URL+'inc/comentaBlog.php?nombre='+document.commentForm.nombre_contacto.value;
	consulta += '&correo='+document.commentForm.correo_contacto.value;
	consulta += '&comment='+escape(document.commentForm.comment_contacto.value);
	consulta += '&enlace='+document.URL;
	consulta += '&idBlog='+idBlog;
	consulta += '&idioma='+idioma;
//	alert(consulta)
	oXMLHttpRequest.open( 'GET', consulta, true );
	oXMLHttpRequest.send( null);
}


function getFecha(valor){
	meses = CONSTANTES['MESES'].split(","); 
	trozos = valor.split(" ");
	fecha = trozos[0];
	hora = trozos[1];
	trozos = fecha.split("-");
	fecha = trozos[2]+" de "+meses[parseInt(trozos[1])]+" del "+trozos[0]+" a las "+hora;
	return fecha;
}

function getCommentsBlog(idBlog){
	if(CONSTANTES['idioma']=="ES"){idioma = "1"}else{idioma = "2"}
	var oXMLHttpRequest = generaReqCom();
	oXMLHttpRequest.onreadystatechange = function(){
		if(oXMLHttpRequest.readyState == 4 && oXMLHttpRequest.status == 200)
		{
			var respuesta = oXMLHttpRequest.responseXML;
			var elementos = respuesta.getElementsByTagName("valor"); 

			var longitudXML = respuesta.getElementsByTagName("ncampos")[0].firstChild.data;
			entrada = respuesta.getElementsByTagName("valor")[0]
			nombre = entrada.getElementsByTagName("bcom_nombre")[0].firstChild.data
			fecha = getFecha(entrada.getElementsByTagName("bcom_fecha")[0].firstChild.data);
			comentario = entrada.getElementsByTagName("bcom_texto")[0].firstChild.data

			commentariosHtml = "";
			commentariosHtml += '<div id="newComment'+longitudXML+'" class="blogComentario noBorder">';
			commentariosHtml += '				<div class="blogComentarioUser">';
			commentariosHtml += '						<img class="blogImgUser" src="'+URL+'img/user.jpg" alt="User"/>';
			commentariosHtml += '				</div>';
			commentariosHtml += '				<div class="blogComentarioComment">';
			commentariosHtml += '					<div class="blogComentarioCommentFecha">';
			commentariosHtml += '						<span>'+nombre+'</span> '+fecha;
			commentariosHtml += '					</div>';
			commentariosHtml += '					<div class="blogComentarioCommentTexto">';
			commentariosHtml += '						'+comentario;
			commentariosHtml += '					</div>';
			commentariosHtml += '				</div>';
			commentariosHtml += '			</div>';

			if(longitudXML>1){
				obj = document.getElementsByClassName("noBorder")[0];
				obj.style.borderBottomWidth = "1px";
				document.getElementById("comentarios").innerHTML += commentariosHtml;
			}else{
				document.getElementById("comentarios").innerHTML = commentariosHtml;
			}
			objeto = $("#newComment"+longitudXML);
			objeto.css("position", "absolute");
			objeto.css("visibility", "hidden");
			objeto.css("opacity", 0);
			objeto.css("top", "0px");
			altoObjeto = objeto.height();

			$("#comentarios").stop(true);
			$("#comentarios").animate({ height: $("#comentarios").height()+15+objeto.height()}, {duration: 600,easing: 'easeOutQuint', complete: function() {
				$("#newComment"+longitudXML).css("position", "relative");
				$("#newComment"+longitudXML).css("top", "auto");
				$("#newComment"+longitudXML).css("visibility", "visible");
				$("#newComment"+longitudXML).animate({ opacity: 1}, {duration: 600,easing: 'easeOutQuart'});

			}});


//			alert(CONSTANTES['ENVIADO_BLOG'])
			document.getElementById("formErrorBlogComs").innerHTML = CONSTANTES['ENVIADO_BLOG'];
			document.commentForm.nombre_contacto.value="";
			document.commentForm.correo_contacto.value="";
			document.commentForm.comment_contacto.value="";

		}
	}

	camposStr = "bcom_nombre,bcom_texto,bcom_fecha"
	tabla = "bcom_blogComs"
	where = "bcom_blog_id="+idBlog+" and bcom_idioma="+idioma;
	order = "order by bcom_fecha desc"

	envio = URL+'admin/selectXML.php?&campos='+camposStr+'&tabla='+tabla+'&where='+where+'&order='+order+'&';
	oXMLHttpRequest.open( 'GET', envio, true );
	oXMLHttpRequest.send( null );

}



////////////////////////////////////
///BLOG
////////////////////////////////////

function usaList(num,num2,auto){
	if(listaIniciada!=true || auto==null){
//	alert("usalist "+num+" "+num2)
//	if(initHeightRight == ""){initHeightRight = $("#contRight").height();}
		if(num2==null){
			obj = document.getElementById("listaMeses"+num);
			objJQ = $("#listaMeses"+num);
			objFlecha = document.getElementById("flechaListadoBlogImg"+num);
			if(obj.pos!=null){
				altoDest = obj.altoInicial;
			}
		}else{
			obj = document.getElementById("listaMesesIn"+num+"_"+num2);
			objJQ = $("#listaMesesIn"+num+"_"+num2);
			objFlecha = document.getElementById("flechaListadoBlogImg"+num+"_"+num2);
			if(obj.pos!=null){
				altoDest = obj.altoInicial;
			}
			objPadreJQ = $("#listaMeses"+num);
			objPadreAlto = objPadreJQ.height();
		}


		if(obj.pos==null){
	//		alert("inicio")
			obj.altoInicial = obj.offsetHeight;
			obj.style.height = "0px";
			obj.pos = 0;
		}else if(obj.pos==1){
			objJQ.stop(true);
			objJQ.animate({ height: 0 }, {duration: 400,easing: 'easeInQuart'});
			obj.pos = 0;
			if(num2!=null){
				objPadreJQ.animate({ height: objPadreAlto-altoDest }, {duration: 400,easing: 'easeInQuart'});
			}else{
				obj.altoInicial = obj.offsetHeight;
			}
			objFlecha.src = URL+"img/liFlecha.jpg";
			objFlecha.parentNode.blur()
		}else{
			objJQ.stop(true);
			objJQ.animate({ height: altoDest }, {duration: 400,easing: 'easeInQuart'});
			obj.pos = 1;
			if(num2!=null){
				objPadreJQ.animate({ height: objPadreAlto+altoDest }, {duration: 400,easing: 'easeInQuart'});
			}
			objFlecha.src = URL+"img/liFlecha2.jpg";
			objFlecha.parentNode.blur()
		}
	}
}



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,fraseIni) {
	if(puedeAmpliar==true){
	    if (!isIE || version >=7){
			puedeAmpliar = false;
			putAmpliado(img,carpeta,imgs,fraseIni)
		}else{
			window.open(URL+carpeta+"/"+img)
		}
	}
}

function putAmpliado(img,carpeta,imgs,fraseIni){
	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() {


					if(fraseIni){
						objeto = document.createElement("div");
						objeto.id = "ampliadoTexto"
						ampliado.appendChild(objeto);
						$("#ampliadoTexto").css("width", anchoFinal-38+"px");
						$("#ampliadoTexto").html('<div id="ampliadoTextoBg"></div><p>'+unescape(fraseIni)+'</p>');
						altoBg = $("p",$("#ampliadoTexto")).height()+20
						$("#ampliadoTextoBg").css("width", $("#ampliadoTexto").width()+"px");
						$("#ampliadoTextoBg").css("height", altoBg+"px");
						$("#ampliadoTextoBg").css("opacity", 0.65);
						$("#ampliadoTexto").append('<a href="" id="controlTextoAmpliado" onclick="cambiaTxtAmpliado();this.blur();return false;"><img id="controlTextoAmpliadoImg" src="'+URL+'img/controlTxt.jpg"/></a>');
						var leftControlTexto = $("#ampliadoTexto").width()/2 - $("#controlTextoAmpliado").width()/2 ;
						var topControlTexto = altoBg - $("#controlTextoAmpliado").width()/2 +2 ;
						$("#controlTextoAmpliado").css("left", leftControlTexto+"px");
						$("#controlTextoAmpliado").css("bottom", topControlTexto+"px");
						$("#controlTextoAmpliadoImg").css("left", "0px");
						$("#controlTextoAmpliadoImg").css("bottom", "0px");
						$("#controlTextoAmpliadoImg").rotate(0)

						$("#controlTextoAmpliadoImg").rotate(0)
					}



					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();
				
				}});
			}});
		}});
	}
	objeto.src = URL+carpeta+"/"+img;
}

function cambiaTxtAmpliado(){
	estadoTexto = $("#controlTextoAmpliado").attr("estado")

	var elControl = $("#controlTextoAmpliado")
	var elP = $("p",$("#ampliadoTexto"))
	var elBg = $("#ampliadoTextoBg")
	var elDiv = $("#ampliadoTexto")


	if(estadoTexto==1){ //Ta cerrado, y hay que abrir
		$("#controlTextoAmpliado").attr("estado","0")
		var altoPre = parseInt(elBg.attr("preHeight"));
		var topControlTexto = altoPre - $("#controlTextoAmpliado").width()/2 +2 ;

		if(isIEOld()){
			elBg.stop().animate({height: altoPre},200, 'easeOutQuad');
			$("#ampliadoImg").animate({bottom:topControlTexto}, {duration: 200,easing: 'easeOutQuad', complete: function() {
					elP.css("visibility","visible");
			}});
		}else{
			elBg.stop().animate({height: altoPre},200, 'easeOutQuad');
			elControl.stop().animate({bottom: topControlTexto},200, 'easeOutQuad');
			elP.stop().delay(200).animate({opacity: 1},200, 'easeOutQuad');
		}

		$("#controlTextoAmpliadoImg").rotate(0)
		elDiv.css("height","auto")

	}else{  //Ta abierto, y hay que cerrar
		$("#controlTextoAmpliado").attr("estado","1")
		elBg.attr("preHeight",elBg.height());
		var topControlTexto = 0 - $("#controlTextoAmpliado").width()/2 +2 ;

		if(isIEOld()){
			elP.css("visibility","hidden");
			elBg.stop().animate({height: 0},200, 'easeOutQuad');
			elControl.stop().animate({bottom: topControlTexto},200, 'easeOutQuad');
		}else{
			elP.stop().animate({opacity: 0},200, 'easeOutQuad');
			elBg.stop().delay(200).animate({height: 0},200, 'easeOutQuad');
			elControl.stop().delay(200).animate({bottom: topControlTexto},200, 'easeOutQuad');
		}

		$("#controlTextoAmpliadoImg").rotate(180)
		elDiv.css("height","0px")

	}
	

}

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;
	if(frasesFotos!=null){
		frasesFotosArr = frasesFotos.split("0|0")
		fraseDest = frasesFotosArr[posicion];
		$("#ampliadoTexto").css("visibility","hidden")
		$("p",$("#ampliadoTexto")).css("visibility","hidden")

	}
	$("#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");
					$("#ampliadoTexto").css("width", anchoFinal-38+"px");

					$("#ampliadoFull").animate({ opacity: 1 }, {duration: 600,easing: 'easeOutQuart'});
					$("#ampliadoImg").animate({ opacity: 1 }, {duration: 600,easing: 'easeOutQuart',complete: function() {

						if(frasesFotos){
							$("#controlTextoAmpliado").attr("estado","0")
							$("#controlTextoAmpliadoImg").rotate(0)
							$("#ampliadoTexto").css("height","auto")

							$("p",$("#ampliadoTexto")).html(fraseDest);
							altoBg = $("p",$("#ampliadoTexto")).height()+20

							$("#ampliadoTextoBg").css("width", $("#ampliadoTexto").width()+"px");
							$("#ampliadoTextoBg").css("height", altoBg+"px");
							$("#ampliadoTexto").css("visibility","visible")
							$("p",$("#ampliadoTexto")).css("visibility","visible")
							$("p",$("#ampliadoTexto")).css("opacity",1)

							var leftControlTexto = $("#ampliadoTexto").width()/2 - $("#controlTextoAmpliado").width()/2 ;
							var topControlTexto = altoBg - $("#controlTextoAmpliado").width()/2 +2 ;
							$("#controlTextoAmpliado").css("left", leftControlTexto+"px");
							$("#controlTextoAmpliado").css("bottom", topControlTexto+"px");


						}
					}});
				}});
			}});

		}
		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
				}});
			}});
	}});
}

// grayscale

var modifyPixel = function(data,i) {
  var average = (data[i]+data[i+1]+data[i+2])/3;
  data[i]   = average;
  data[i+1] = average;
  data[i+2] = average;   
}

var rectangleToGray = function(context,left,top,width,height){
  var imageData = context.getImageData(left,top,width,height);
  var data   = imageData.data;
  var length = data.length;
  for (var i = 0;i<length;i+=4) {
    modifyPixel(data,i);
  }
  context.putImageData(imageData, left, top); 
}

var canvasToGray = function(canvas,deltay) {
  var context = canvas.getContext('2d'); 
  var width  = canvas.width;
  var height = canvas.height;
  var y  = 0;
  deltay = deltay || height;
  var step = function() {
    rectangleToGray(context,0,y,width,deltay); 
    y += deltay;
//    log(Math.round(100*y/height)+'%');
    if (y<height) {
      var rest = height-y;
      if ( rest < deltay) deltay = rest;
      setTimeout(step,0);
    }
    else {
      t = new Date().getTime()-t;
//      log('Proceso completado en '+t/1000+' segundos');
    }
  }
  var t = new Date().getTime();
  step();
}

var imageToGray = function(im) {
  var canvas = document.createElement("canvas");
  if(canvas.getContext){ 
    canvas.width  = im.width  || im.offsetWidth; 
    canvas.height = im.height || im.offsetHeight; 
    canvas.getContext('2d').drawImage(im,0,0); 
    im.parentNode.replaceChild(canvas,im); 
//    canvasToGray(canvas,2);
    canvasToGray(canvas);
  }
  else {
    var nit = 100;     
    var t = new Date().getTime();
    for (var j = 0;j<nit;j++)
       im.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)'; 
    t = new Date().getTime()-t;
//    log('Proceso completado en '+t/(1000*nit)+' segundos');
  }     
}  


function initClientes(){
	if(subSeccion!=""){
		var sub = subSeccion;
	}else{
		var sub = subSeccionInicio;
	}
	if(sub==3){
		var i=0;
		while(document.getElementById("imgCliente"+i)!=null){
			obj = document.getElementById("imgCliente"+i);
			imageToGray(obj)	
			obj = $("#imgClienteColor"+i);
			obj.css("opacity", 0)

			obj.mouseover(function() {
			     $(this).stop().animate({opacity: 1},500, 'easeOutQuad');
				 muestraNombre($(this).attr("alt"),$(this))
			}).mouseout(function(){
			     $(this).stop().animate({opacity: 0},500, 'easeOutQuad');
				 ocultaNombre();
			}).mousemove(function(){
				 posNombre();
			});

			i++;
		}
	}
}


function muestraNombre(nombre,obj){
    ocultaNombre();
	objeto = document.createElement("div");
	objeto.id = "cajaNombre"
	contenedor = document.body;
	contenedor.appendChild(objeto);

	offsetCont = $('#cuadroClientes').offset();
	posX = mouseX
	posY = mouseY + 20


	objeto = document.getElementById('cajaNombre');
	objeto.style.position = "absolute";
	objeto.style.zIndex = "10000";
	objeto.style.top = posY+"px";
	objeto.style.left = posX+"px";
	objeto.style.background = "#ffffff";
	objeto.style.color = "#000000";
//	objeto.style.width = "400px";
	objeto.style.padding = "5px";


	objetoTxt = document.createElement("div");
	objetoTxt.id = "cajaNombreTxt"
	contenedor = objeto;
	contenedor.appendChild(objetoTxt);


	objetoTxt.innerHTML = nombre;
	var property = objeto.filters ? 'filter' : 'opacity';
	objeto.style[property] = objeto.filters ? 'alpha(opacity=' + 0 + ')' : 0/100;

//	objeto.style.top = posY-($('#cajaNombre').height()/2)+"px";
//	objeto.style.left = posX-($('#cajaNombre').width()/2)+"px";
	anchoDest = $('#cajaNombre').width();


	$('#cajaNombre').css("width","0px");
	$('#cajaNombre').css("overflow","hidden");
	$('#cajaNombreTxt').css("width",anchoDest+"px");
	$('#cajaNombre').stop();
	$("#cajaNombre").animate({ opacity: 1, width: anchoDest}, {duration: 200,easing: 'easeOutQuad', complete: function() {
	}});

//contWidth = document.getElementById(container).offsetWidth;
}

function posNombre(){
	offsetCont = $('#cuadroClientes').offset();
	posX = mouseX
	posY = mouseY + 20
	objeto.style.top = posY+"px";
	objeto.style.left = posX+"px";
}


function ocultaNombre(rapido){
	if(document.getElementById("cajaNombre")!=null){
		$('#cajaNombre').stop();
//			$("#cajaNombre").animate({ opacity: 0}, {duration: 500,easing: 'easeOutQuad', complete: function() {
			objeto = document.getElementById("cajaNombre");
			objeto.parentNode.removeChild(objeto);
//			}});
	}
}

/*
var mouseX;
var mouseY;

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


function initBotellasHome(){

	$(".imagenVinoHomeIn").rotate(15);
	$(".imagenVinoHomeIn").css("top","-230px");
	$(".imagenVinoHomeIn").css("left","5px");
	$(".imagenVinoHomeIn",$(".vinosHomeFila.uno")).css("top","-200px");
	$(".imagenVinoHomeIn",$(".vinosHomeFila.uno")).css("left","0px");

	$(".imagenVinoHomeIn",$(".vinosHomeFila.dos")).attr("destTop",-192)
	$(".imagenVinoHomeIn",$(".vinosHomeFila.uno")).attr("destTop",-152)
	$(".imagenVinoHomeIn",$(".vinosHomeFila.dos")).attr("iniTop",-230)
	$(".imagenVinoHomeIn",$(".vinosHomeFila.uno")).attr("iniTop",-200)
	$(".imagenVinoHomeIn",$(".vinosHomeFila.dos")).attr("iniLeft",5)
	$(".imagenVinoHomeIn",$(".vinosHomeFila.uno")).attr("iniLeft",0)
	if(isIE){tiempoRot = 600}else{tiempoRot = 150}

	$(".imagenVinoHomeInBtn").mouseover(function() {
		var padre = $(this).parent();
		var destTop = $(".imagenVinoHomeIn",padre).attr("destTop");
		$(".imagenVinoHomeIn",padre).rotateAnimation({animateAngle:0,duration:tiempoRot});
		$(".imagenVinoHomeIn",padre).stop().animate({"left": -10, "top": destTop}, {duration:150, easing: "easeOutQuart"})
		padre.stop().animate({"height": 220}, {duration:150, easing: "easeOutQuart"})
		$(".nombreVinoHome",padre.parent()).stop().animate({"top": "240px"}, {duration:150, easing: "easeOutQuart"})
		$(this).animate({"height": 220}, {duration:150, easing: "easeOutQuart"})
	}).mouseout(function(){
		var padre = $(this).parent();
		var iniTop = $(".imagenVinoHomeIn",padre).attr("iniTop");
		var iniLeft = $(".imagenVinoHomeIn",padre).attr("iniLeft");
		$(".imagenVinoHomeIn",padre).rotateAnimation({animateAngle:15,duration:tiempoRot});
		$(".imagenVinoHomeIn",padre).stop().animate({"left": iniLeft, "top": iniTop, "rotate":15}, {duration:150, easing: "easeOutQuart"})
		padre.stop().animate({"height": 122}, {duration:150, easing: "easeOutQuart"})
		$(".nombreVinoHome",padre.parent()).stop().animate({"top": "140px"}, {duration:150, easing: "easeOutQuart"})
		$(this).animate({"height": 122}, {duration:150, easing: "easeOutQuart"})
	});
}


// grayscale

var modifyPixel = function(data,i) {
  var average = (data[i]+data[i+1]+data[i+2])/3;
  data[i]   = average;
  data[i+1] = average;
  data[i+2] = average;   
}

var rectangleToGray = function(context,left,top,width,height){
  var imageData = context.getImageData(left,top,width,height);
  var data   = imageData.data;
  var length = data.length;
  for (var i = 0;i<length;i+=4) {
    modifyPixel(data,i);
  }
  context.putImageData(imageData, left, top); 
}

var canvasToGray = function(canvas,deltay) {
  var context = canvas.getContext('2d'); 
  var width  = canvas.width;
  var height = canvas.height;
  var y  = 0;
  deltay = deltay || height;
  var step = function() {
    rectangleToGray(context,0,y,width,deltay); 
    y += deltay;
//    log(Math.round(100*y/height)+'%');
    if (y<height) {
      var rest = height-y;
      if ( rest < deltay) deltay = rest;
      setTimeout(step,0);
    }
    else {
      t = new Date().getTime()-t;
//      log('Proceso completado en '+t/1000+' segundos');
    }
  }
  var t = new Date().getTime();
  step();
}

var imageToGray = function(im) {
  var canvas = document.createElement("canvas");
  if(canvas.getContext){ 
    canvas.width  = im.width  || im.offsetWidth; 
    canvas.height = im.height || im.offsetHeight; 
    canvas.getContext('2d').drawImage(im,0,0); 
    im.parentNode.replaceChild(canvas,im); 
//    canvasToGray(canvas,2);
    canvasToGray(canvas);
  }
  else {
    var nit = 100;     
    var t = new Date().getTime();
    for (var j = 0;j<nit;j++)
       im.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)'; 
    t = new Date().getTime()-t;
//    log('Proceso completado en '+t/(1000*nit)+' segundos');
  }     
}  

function initBotellasVino(){


	if($(".botella_bn:eq(0)").attr("inited")!="true"){
		i=0;

		var i=0;
		while(document.getElementById("botella_num_"+i)!=null){
			obj = document.getElementById("botella_bn_"+i);
			imageToGray(obj)	
			numObj = $("#botella_num_"+i).attr("class")
			numObj = numObj.split("_");
			numObj = numObj[(numObj.length-1)];
//			alert("subSeccion="+subSeccion+" i="+i+" numObj="+numObj)

			if(subSeccion==numObj){
				$(".botella_bn",$(".botella.num_"+numObj)).css("height",0);
			}
			i++;
		}
		$(".botella_bn_in").css("opacity",0.75);
		$(".botella_bn").attr("inited","true")


		$(".botellaBtn").mouseover(function() {
			var padre = $(this).parent();
			var num = padre.attr("class").split("_")
			num = num[(num.length-1)]
			if(subSeccion!=(parseInt(num))){
				overBotella(num);
			}

		}).mouseout(function(){
			var padre = $(this).parent();
			var num = padre.attr("class").split("_")
			num = num[(num.length-1)]
			if(subSeccion!=(parseInt(num))){
				outBotella(num);
			}
		});
	}

	if(subSeccion!=0){
		var iniH = document.getElementById("imagenEtiq").offsetHeight;
		var iniW = document.getElementById("imagenEtiq").offsetWidth;
		$('#imagenEtiq').attr('iniH',iniH);
		$('#imagenEtiq').attr('iniW',iniW);

		$("#controlZoom").mouseup(function(event){
			$(this).attr('movil',false);
		}).mousedown(function(event){
			 event.stopPropagation();
			 event.preventDefault();
			$(this).attr('movil',true);
		});

		$('#controlZoom').mousemove(function(event) {
			var parentObj = $(this).parent();
			var parentPos = parentObj.offset();
			var posY = Math.abs(parentPos.top - event.pageY) - $(this).height()/2;
			var max = parentObj.height() - $(this).height();
			if($(this).attr('movil')=="true"){
				if(posY<0){posY=0;}else if(posY>max){posY=max;}
				makeZoom(posY,max);
			}

		});

		$('#contentInteriorVinosImgControlBarOut').mousemove(function(event) {
			var parentObj = $('#contentInteriorVinosImgControlBar');
			var parentPos = parentObj.offset();
			var max = parentObj.height() - $('#controlZoom').height();
			var posY = Math.abs(parentPos.top - event.pageY) - $('#controlZoom').height()/2;
			if($('#controlZoom').attr('movil')=="true"){
				if(posY<0){posY=0;}else if(posY>max){posY=max;}
				makeZoom(posY,max);
			}

		});

		$("#contentInteriorVinosImgControlBarOut").mouseup(function(event){
			$('#controlZoom').attr('movil',false);
		}).mousedown(function(event){
			 event.stopPropagation();
			 event.preventDefault();
			$('#controlZoom').attr('movil',true);
		});
		
		$('#contentInteriorVinosImgControlBarOut').mouseleave(function() {
			$('#controlZoom').attr('preMovil',$('#controlZoom').attr('movil'));
			$('#controlZoom').attr('movil',false);
		});

		$('#contentInteriorVinosImgControlBarOut').mouseenter(function() {
			$('#controlZoom').attr('movil',$('#controlZoom').attr('preMovil'));
		});


		$("#imagenEtiq").mouseup(function(event){
			$(this).attr('movil',false);
		}).mousedown(function(event){
			 event.stopPropagation();
			 event.preventDefault();
			var parentObj = $(this).parent();
			var parentPos = parentObj.offset();
			var posY = Math.abs(parentPos.top - event.pageY);
			var posX = Math.abs(parentPos.left - event.pageX);
			var miPos = $(this).position();

			$(this).attr('movil',true);
			$(this).attr('iniMovX',posX);
			$(this).attr('iniMovY',posY);
			$(this).attr('iniPosX',miPos.left);
			$(this).attr('iniPosY',miPos.top);

		});

		$('#imagenEtiq').mousemove(function(event) {
			if($(this).attr('movil')=="true"){
				var parentObj = $(this).parent();
				var parentPos = parentObj.offset();
				var posY = Math.abs(parentPos.top - event.pageY);
				var posX = Math.abs(parentPos.left - event.pageX);
				var posIniX = parseInt($(this).attr('iniMovX'));
				var posIniY = parseInt($(this).attr('iniMovY'));
				var iniPosY = parseInt($(this).attr('iniPosY'));
				var iniPosX =parseInt($(this).attr('iniPosX'));
				var movY = iniPosY + posY-posIniY;
				var movX = iniPosX + posX-posIniX;
				var anchoAct = $(this).width();
				var altoAct = $(this).height();
				var anchoCont = $("#imagenEtiqOut").width();
				var altoCont = $("#imagenEtiqOut").width();
				
				
				if(movX+anchoAct<anchoCont){movX = anchoCont - anchoAct;}else if(movX>0){movX = 0;}
				if(movY+altoAct<altoCont){movY = altoCont - altoAct;}else if(movY>0){movY = 0;}

				$(this).css("top",movY)
				$(this).css("left",movX)
			}

		});

		$('#imagenEtiqOut').mouseleave(function() {
			$('#imagenEtiq').attr('preMovil',$('#imagenEtiq').attr('movil'));
			$('#imagenEtiq').attr('movil',false);
		});

		$('#imagenEtiqOut').mouseenter(function() {
			$('#imagenEtiq').attr('movil',$('#imagenEtiq').attr('preMovil'));
		});

		$("body").mouseup(function(event){
			$('#imagenEtiq').attr('preMovil',false);
			$('#controlZoom').attr('preMovil',false);
		});


	}


}

function makeZoom(posSlide,maxSlide){

/*	$("#trazador").css("position","absolute")
	$("#trazador").css("background","#ffffff")
	$("#trazador").css("height","200px;")
	$("#trazador").css("width","200px;")
	$("#trazador").css("top","0px")
	$("#trazador").css("right","10px")
	$("#trazador").css("color","#000000")*/
	
	var maxRed = 80;  // Reduccion maxima permitida
	var porcentajeBarra = Math.round(posSlide*100 / maxSlide);
	var porcentajeFinal = Math.round(maxRed*porcentajeBarra /100);
	$('#controlZoom').css("top",posSlide)
	var iniH = parseInt($('#imagenEtiq').attr('iniH'))
	var iniW = parseInt($('#imagenEtiq').attr('iniW'))
	var destH = Math.floor(iniH * ((porcentajeFinal/100) + 1));
	var destW = Math.floor(iniW * ((porcentajeFinal/100) + 1));

	var difH = (destH - iniH)/2;
	var difW = (destW - iniW)/2;
/*
	var posAct = $('#imagenEtiq').position();
	var miTop = Math.floor(posAct.top);
	var miLeft = Math.floor(posAct.left);

//	$("#trazador").html(destH+" "+$('#imagenEtiq').height())


	if(destH>$('#imagenEtiq').height()){  //Toy creciendo

		$('#imagenEtiq').css("top", -difH+"px");
		$('#imagenEtiq').css("left", -difW+"px");

	}else{ //Toy decreciendo
		if(miLeft+destW<iniW){
			var destLeft = iniW - destW;
			$('#imagenEtiq').css("left", destLeft+"px");
		}
		if(miTop+destH<iniH){
			var destop = iniH - destH;
			$('#imagenEtiq').css("top", destop+"px");
		}
	}*/

	$('#imagenEtiq').height(destH);
	$('#imagenEtiq').width(destW);
	$('#imagenEtiq').css("left", -difW+"px");
	$('#imagenEtiq').css("top", -difH+"px");

}


function overBotella(num){
	$(".botella_bn",$(".botella.num_"+num)).stop().animate({height:0}, {duration: 100,easing: 'easeOutQuad'})
	$('#a_sub_4_'+num).css("background","#000000")
	$('#a_sub_4_'+num).css("color","#ffffff")
	Cufon.set("fontFamily", "Garamond LT LightCondensed").replace('#a_sub_4_'+num);
}

function outBotella(num){
	if(subSeccion!=parseInt(num)){
		$(".botella_bn",$(".botella.num_"+num)).stop().animate({height:280}, {duration: 100,easing: 'easeOutQuad'})
		$('#a_sub_4_'+num).css("background","#ffffff")
		$('#a_sub_4_'+num).css("color","#4c4c4c")
		Cufon.set("fontFamily", "Garamond LT LightCondensed").replace('#a_sub_4_'+num);
	}
}


function overSubM(num,num2){
	$('#a_sub_'+num+'_'+num2).css("background","#000000")
	$('#a_sub_'+num+'_'+num2).css("color","#ffffff")
	Cufon.set("fontFamily", "Garamond LT LightCondensed").replace('#a_sub_'+num+'_'+num2);
}

function outSubM(num,num2){
	if(!(seccion==parseInt(num) && subSeccion==parseInt(num2))){
		$('#a_sub_'+num+'_'+num2).css("background","#ffffff")
		$('#a_sub_'+num+'_'+num2).css("color","#4c4c4c")
		Cufon.set("fontFamily", "Garamond LT LightCondensed").replace('#a_sub_'+num+'_'+num2);
	}
}



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


function initMaps(){
	var mapObj = document.getElementById("mapsSpace");
	mapObj.innerHTML = '<iframe width="410" height="280" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.es/maps?hl=es&amp;q=bodegas+sonsierra&amp;ie=UTF8&amp;ll=42.563812,-2.7601&amp;spn=0.004425,0.008776&amp;z=16&amp;output=embed"></iframe>';
}


function overMapa(num){
	if($("#clonImgMapa")[0]==null){
		$("#contentInferiorGaleria").append('<img id="clonImgMapa" src=""/>');
		objOrigen = $(".imagenGaleriaWeb");
		posicion = objOrigen.position()
		$("#clonImgMapa").css("position","absolute")
		$("#clonImgMapa").css("top",posicion.top+1+"px")
		$("#clonImgMapa").css("left",posicion.left+1+"px")
		$("#clonImgMapa").css("opacity",0)
	}


	var misImagenes = new Array("","3_1.jpg","3_2.jpg","3_3.jpg")

	$('<img />')
	.load(function(){
		$("#clonImgMapa").attr('src', URL+"img/galeria/vinedos/"+misImagenes[num])
		$("#clonImgMapa").stop(true).animate({ opacity: 1 }, {duration: 600,easing: 'easeInQuart'});
	}).attr('src', URL+"img/galeria/vinedos/"+misImagenes[num])
	;

	if($("#mapDesc").attr("iniText")==null){
		$("#mapDesc").attr("iniText",$("#mapDesc").html())
	}
	$("#mapDesc").html(CONSTANTES['TXT_AREA'+num])
	
}

function outMapa(num){
	$("#clonImgMapa").stop(true).animate({ opacity: 0 }, {duration: 600,easing: 'easeInQuart'});
	$("#mapDesc").html($("#mapDesc").attr("iniText"))
}

function initNoticiasInt(){
	if($("#interior_tit")[0]!=null){
		altoTot = $("#notTop").height();
		altoAct = $("#interior_tit").height();
		diferencia = altoTot-altoAct;
		if(diferencia<=0){
			$("#interior_tit").css("margin-top","0px");
		}else{
			$("#interior_tit").css("margin-top",diferencia+"px");
		}
	}
}


function overMenuInf(obj){
		$(obj).css("color","#000000");
		Cufon.set("fontFamily", "Garamond LT LightCondensed").replace(obj);
}

function outMenuInf(obj){
		$(obj).css("color","#6d6d6d");
		Cufon.set("fontFamily", "Garamond LT LightCondensed").replace(obj);
}


function initDescargas(){
		
	$("a",$(".listadoLi")).click(function(event) {
		$(this).parent().click();
		var agent = jQuery.browser;
		if(agent.msie) {
			event.cancelBubble = true;
		} else {
			event.stopPropagation();
		}

		return false;
	});


	$(".listadoLi").click(function(event) {
		event.stopPropagation();
		var archivo = $(".nameFile",$(this)).attr("href").split(URL).join('')
		var extension = archivo.split("/");
		extension = extension[(extension.length-1)]
		extension = extension.split(".");
		extension = extension[(extension.length-1)]
		var nombre = $(".nameFile",$(this)).html();

		$.get(URL+'inc/getURLAmiga.php?laURL='+nombre, function(data) {
			var respuesta = data;
			var resultado = respuesta.getElementsByTagName("laURL")[0].firstChild.data;
			descargaFichero(archivo,resultado+"."+extension)
		});

	});

}


function initDescargasVino(){
	if($("#descarga_comparativa")[0]!=null){

		$("a",$("#descarga_comparativa")).click(function(event) {
			$(this).parent().parent().click();
			var agent = jQuery.browser;
			if(agent.msie) {
				event.cancelBubble = true;
			} else {
				event.stopPropagation();
			}

			return false;
		});
		
		$("#descarga_comparativa").click(function(event) {
			event.stopPropagation();
			var archivo = $(".nameFile",$(this)).attr("href").split(URL).join('')
			var extension = archivo.split("/");
			extension = extension[(extension.length-1)]
			extension = extension.split(".");
			extension = extension[(extension.length-1)]
			var nombre = CONSTANTES["COMPNAME"];
			$.get(URL+'inc/getURLAmiga.php?laURL='+nombre, function(data) {
				var respuesta = data;
				var resultado = respuesta.getElementsByTagName("laURL")[0].firstChild.data;
				descargaFichero(archivo,resultado+"."+extension)
			});

		});

		$("#descarga_comparativa").css("cursor","pointer")

		$("a",$("#descarga_familia")).click(function(event) {
			$(this).parent().parent().click();
			var agent = jQuery.browser;
			if(agent.msie) {
				event.cancelBubble = true;
			} else {
				event.stopPropagation();
			}

			return false;
		});
		
		$("#descarga_familia").click(function(event) {
			event.stopPropagation();
			var archivo = $(".nameFile",$(this)).attr("href").split(URL).join('')
			var extension = archivo.split("/");
			extension = extension[(extension.length-1)]
			extension = extension.split(".");
			extension = extension[(extension.length-1)]
			var nombre = CONSTANTES["CATNAME"];
			$.get(URL+'inc/getURLAmiga.php?laURL='+nombre, function(data) {
				var respuesta = data;
				var resultado = respuesta.getElementsByTagName("laURL")[0].firstChild.data;
				descargaFichero(archivo,resultado+"."+extension)
			});

		});

		$("#descarga_familia").css("cursor","pointer")





	}else{

		$("a",$("#contentHomeVinosSupDwnBot")).click(function(event) {
			$(this).parent().parent().click();
			var agent = jQuery.browser;
			if(agent.msie) {
				event.cancelBubble = true;
			} else {
				event.stopPropagation();
			}

			return false;
		});
		
		$("#contentHomeVinosSupDwnBot").click(function(event) {
			event.stopPropagation();
			var archivo = $(".nameFile",$(this)).attr("href").split(URL).join('')
			var extension = archivo.split("/");
			extension = extension[(extension.length-1)]
			extension = extension.split(".");
			extension = extension[(extension.length-1)]
			var nombre = $("#imagenEtiq").attr("alt");
			$.get(URL+'inc/getURLAmiga.php?laURL='+nombre, function(data) {
				var respuesta = data;
				var resultado = respuesta.getElementsByTagName("laURL")[0].firstChild.data;
				descargaFichero(archivo,resultado+"."+extension)
			});

		});

		$("#contentHomeVinosSupDwnBot").css("cursor","pointer")

		$("a",$("#descarga_fichaCata")).click(function(event) {
			$(this).parent().parent().click();
			var agent = jQuery.browser;
			if(agent.msie) {
				event.cancelBubble = true;
			} else {
				event.stopPropagation();
			}

			return false;
		});
		
		$("#descarga_fichaCata").click(function(event) {
			event.stopPropagation();
			var archivo = $(".nameFile",$(this)).attr("href").split(URL).join('')
			var extension = archivo.split("/");
			extension = extension[(extension.length-1)]
			extension = extension.split(".");
			extension = extension[(extension.length-1)]
			var nombre = $("#imagenEtiq").attr("alt");
			$.get(URL+'inc/getURLAmiga.php?laURL='+nombre, function(data) {
				var respuesta = data;
				var resultado = respuesta.getElementsByTagName("laURL")[0].firstChild.data;
				descargaFichero(archivo,resultado+"."+extension)
			});

		});

		$("#descarga_fichaCata").css("cursor","pointer")


	}
}
