// JavaScript Document
var _interval = 0;

$(document).ready(function() {	
	if ($('#slideshow SCRIPT').size() == 0) {
		$('#slideshow').cycle({
			fx: 'fade',
			slideResize: 1,
			fit: 1,
			pager:  '#nav',
			slideExpr: 'img'
		});
	}
	
	if ($('#slideshow').css("padding") != "0px") {
		$('#slideshow').css("padding", "0px");
	}
	
	if ($('#slideshow').css("margin") != "0px") {
		$('#slideshow').css("margin", "0px");
	}
	
	
	$("#foo1").carouFredSel({
		auto : false,
		prev : "#foo1_prev",
		next : "#foo1_next"
	});
	
	$("#foo2").carouFredSel({
		auto : false,
		prev : "#foo2_prev",
		next : "#foo2_next"
	});

    
    $(".sections .item").click(function () {
        document.location.href = "index.asp" + $(this).attr("rel");
    });
    
    $(".sections .itemselected").click(function () {
        document.location.href = "index.asp" + $(this).attr("rel");
    });
    
    /*if (!($(".sections .itemselected").attr("rel").indexOf($("#sectionpage").val()) > -1)) {
        $(".sections .itemselected").attr("class", "item");
    }
    $(".sections .item").each(function () {
        if ($("#sectionpage").val() != "" && $(this).attr("rel").indexOf($("#sectionpage").val()) > -1) {
            $(this).attr("class", "itemselected");
        }
    });
    
    $(".sections .item").hover( 
        function (){
            $(this).attr("class", "itemselected");
        },
        function () {
            $(this).attr("class", "item");
        }
    );*/
    
    /*$("H3").click(function(){
        $("DIV.familiaAbierta").each(function() {
            $(this).removeClass("familiaAbierta");                                    
        });                
        if($(this).next().hasClass("familiaAbierta")) {
            $(this).next().removeClass("familiaAbierta");
        }
        else {
            $(this).next().addClass("familiaAbierta");
        }
    });*/
    
    setTimeout('ResizeColumns();', 500);
	
	if ($("#sectionId").val() == "empresa") {
		//$("#foo").carouFredSel();  
		// Using custom configuration  
		$("#foo").carouFredSel({
			circular: false,
			infinite: false,
			auto	: {
				items 			: 1,
				duration		: 1000,
				easing			: "linear",
				pauseDuration	: 0
			}
		}).trigger("pause");
		
		$("#foo_prev").hover(function() {
			CarouselEmpresa(false);
		}, function() {
			clearTimeout(_interval);
		});
		
		$("#foo_next").hover(function() {
			CarouselEmpresa(true);
		}, function() {
			clearTimeout(_interval);
		});
		
		$(".contenidoNoticia").carouFredSel({
			items : 1,
			auto : false,
			prev : ".flechaNoticiaPrevious",
			next : ".flechaNoticiaNext"
		});
		$(".carruselFotoAmpliada").carouFredSel({
			items : 1,
			auto : false,
			prev : ".flechaNoticiaPrevious",
			next : ".flechaNoticiaNext"
		});
	}
	
	$(".chzn-select").chosen();
	$(".productselector #color").chosen().change(function () {
		ChangeImage($("DIV.miniaturas A[name='" + $(this).find("OPTION:selected").attr("rel") + "']"));
	});
	
	$(".upitem").click( function(){
		var fila = $(this).parent().parent();
		var unidades = parseFloat($(".numUnidades",fila).val()) + 1;
		var precio = $(".precio SPAN",fila).html();
		precio = replace(precio,",",".");
		precio = parseFloat(precio);
		var total = unidades * precio;
		total = Math.round(total * Math.pow(10, 2)) / Math.pow(10, 2);
		total = replace(total.toFixed(2).toString(),",",".");
		$(".numUnidades",fila).val(unidades);
		$(".total SPAN",fila).html(total);
		UpdateTotalPrice();
	});
	
	$(".downitem").click( function(){
		var fila = $(this).parent().parent();
		var unidades = parseFloat($(".numUnidades",fila).val()) - 1;
		if(unidades < 1) {
			unidades = 1;	
		}
		var precio = $(".precio SPAN",fila).html();
		precio = replace(precio,",",".");
		precio = parseFloat(precio);
		var total = unidades * precio;
		total = Math.round(total * Math.pow(10, 2)) / Math.pow(10, 2);
		total = replace(total.toFixed(2).toString(),",",".");		
		$(".numUnidades",fila).val(unidades);
		$(".total SPAN",fila).html(total);
		UpdateTotalPrice();
	});
	
	$(".numUnidades").keyup( function(){
		if ($(this).val() == undefined || $(this).val() == "" || isNaN($(this).val())) {
			$(this).val("0");
		}
		var fila = $(this).parent().parent();
		var unidades = parseFloat($(".numUnidades",fila).val());
		var precio = $(".precio SPAN",fila).html();
		precio = replace(precio,",",".");
		precio = parseFloat(precio);
		var total = unidades * precio;
		total = Math.round(total * Math.pow(10, 2)) / Math.pow(10, 2);
		total = replace(total.toFixed(2).toString(),",",".");
		$(".numUnidades",fila).val(unidades);
		$(".total SPAN",fila).html(total);
		UpdateTotalPrice();
	});
	
	$("UL.data LI.total A.deleteItem").click(function(){
		var padre = $(this).parent().parent();
		UpdateCart(padre,1);
		$(this).parent().parent().remove();
		UpdateTotalPrice();
		var numArticulos = $("#migasCarrito SPAN.numarticulos SPAN").html();
		numArticulos = parseInt(numArticulos);
		numArticulos -= 1;
		$("#migasCarrito SPAN.numarticulos SPAN").html(numArticulos);
	});	
	
	$("UL.cartActions A.updateCart").click(function(){
		$(".shoppingcartlayer1 UL.data").each(function(){
			linea = $(this);
			UpdateCart(linea,0);
		});
	});
	
	LoadCustomerAddressEvents();
	
	$(".shoppingcartlayer2 .confirm").click(function () {
		ConfirmOrder();
	});
	
	
	/*$(".imagenpeque").click(function () {
		ChangeImage($(this));
	});*/
	
	$("a.fancyboxToSlide").fancybox();
	$("a.fancyboxthumb").fancybox();
	
	if($("#birthday").length){
		$("#birthday").datepicker(
			$.datepicker.regional['es'] = {
				closeText: 'Cerrar',
				prevText: '<Ant',
				nextText: 'Sig>',
				currentText: 'Hoy',
				monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
				monthNamesShort: ['Ene','Feb','Mar','Abr', 'May','Jun','Jul','Ago','Sep', 'Oct','Nov','Dic'],
				dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
				dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'],
				dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sá'],
				weekHeader: 'Sm',
				dateFormat: 'dd/mm/yy',
				firstDay: 1,
				isRTL: false,
				showMonthAfterYear: false,
				yearSuffix: '',
				changeYear: true,
				changeMonth: true,
				yearRange: "1900:2100"
			}
		);
	}
	
	if($("DIV.fichaYear").length > 0){
		$("DIV.fichaYear A").click(function(){
			var codigo = $("INPUT.codigonoticia",this).val();
			var fecha = $("INPUT.fechayear",this).val();
			ChangeYearNews(codigo,fecha,this);
		});
	}
	
	if($("DIV.categories UL LI").length > 0){
		$("DIV.categories UL LI").click(function(){
			document.location = $("A",this).attr("href");
		});
	}
	
	$("A.voidOrder").click(function () {
		$.ajax({
			type: "POST",
			url: "AjaxResponse/shop/DeleteCart_ajax.asp",
			data: "",
			success: function(data){
				document.location.reload();
			} 
		});
	});
});

/****************************************************************
/ Nombre: 		CarouselEmpresa
/ Implentacion: Jordi Darijo
/ Revision: 	17/08/2011
/ Descripcion: 	Mueve la capa de los años como si fuera un carousel
/				to = true 	-> mueve hacia la derecha
/				to = false 	-> mueve hacia la izquierda
'***************************************************************/
function CarouselEmpresa(to) {
	if ($("#foo").css("left") == "auto") {
		$("#foo").css("left", "0px");
	}
	
	var left = parseInt(replace($("#foo").css("left"), "px", ""));
	var tope = left;
	if ($("#foo DIV.fichaYear").size() <= 6) {
	}
	else {
		tope = ($("#foo DIV.fichaYear").size() - 6) * 87 * (-1);
	}
	
	if (to) {
		if (left > tope) {
			left -= 10;
			$("#foo").css("left", left + "px");
			_interval = setTimeout( function() { CarouselEmpresa(to); }, 50);
		}
		else {
			//alert("Tope:" + tope);
		}
	}
	else {
		if (left < 0) {
			left += 10;
			$("#foo").css("left", left + "px");
			_interval = setTimeout( function() { CarouselEmpresa(to); }, 50);
		}
	}
}

function ResizeColumns() {
    try {
        if ($("#sectionId").val() == "empresa" || $("#sectionId").val() == "noticias") {
            if ($("#zonaEnlaces").height() > $("#contenidos").height()) {
                diferencia = $("#zonaEnlaces").height() - $("#contenidos").height();
                $("#contenidos").children(0).next().height($("#contenidos").children(0).next().height() + diferencia);
            }
            else if($("#zonaEnlaces").height() < $("#contenidos").height()) {
                diferencia = $("#contenidos").height() - $("#zonaEnlaces").height();
                $("#zonaEnlaces .temas").height($("#zonaEnlaces .temas").height() + diferencia);
            }
        }
        
        if ($("#sectionId").val() == "contacto") {
            
            if ($("#zonaEnlaces").height() > $("#contenidos").height()) {
                diferencia = $("#zonaEnlaces").height() - $("#contenidos").height();
                $("#contenidos .cont").height($("#contenidos .cont").height() + diferencia);
            }
            else if($("#zonaEnlaces").height() < $("#contenidos").height()){
                diferencia = $("#contenidos").height() - $("#zonaEnlaces").height();
                $("#zonaEnlaces .temas").height($("#zonaEnlaces .temas").height() + diferencia);
            }
        }
        
        if ($("#sectionId").val() == "productos") {
            if ($("#zonaEnlaces").height() > $("#contenidos").height()) {
                diferencia = $("#zonaEnlaces").height() - $("#contenidos").height();
                $("#contenidos UL").height($("#contenidos UL").height() + diferencia);
                $("#contenidos .productoFicha").height($("#contenidos .productoFicha").height() + diferencia);
            }
            else if($("#zonaEnlaces").height() < $("#contenidos").height()) {
                diferencia = $("#contenidos").height() - $("#zonaEnlaces").height();
                $("#zonaEnlaces .temas").height($("#zonaEnlaces .temas").height() + diferencia);
            }
        }
        
        if($("#sectionId").val() == "terminados") {
            if ($("#zonaEnlaces").height() > $("#contenidos").height()) {
                diferencia = $("#zonaEnlaces").height() - $("#contenidos").height();
                
                $("#contenidos .categories").height($("#contenidos .categories").height() + diferencia);
                $("#contenidos .productoFicha").height($("#contenidos .productoFicha").height() + diferencia);
            }
            else if($("#zonaEnlaces").height() < $("#contenidos").height()) {
                diferencia = $("#contenidos").height() - $("#zonaEnlaces").height();
                $("#zonaEnlaces .temas").height($("#zonaEnlaces .temas").height() + diferencia);
            }
        }
                
    } catch(err) {}
}

/****************************************************************
/ Nombre: check
/ Implentacion: 
/ Revision: 260111
/ Descripcion: Cambia la imagen en el check para clickarla
'***************************************************************/

function check(){
    
    if($("#registro #checkbox").attr("src") == "images/background-check.png"){
        $("#registro #checkbox").attr("src", "images/background-check-cheked.png");
        $("#registro #checkvalue").val(1);
    }else{
        $("#registro #checkbox").attr("src", "images/background-check.png");
        $("#registro #checkvalue").val(0);
    }
}

/****************************************************************
/ Nombre: checkC
/ Implentacion: 
/ Revision: 260111
/ Descripcion: Cambia la imagen en el check para clickarla
'***************************************************************/

function checkC(){
    
    if($("#contacto #checkbox").attr("src") == "images/background-check-contacto.png"){
        $("#contacto #checkbox").attr("src", "images/background-check-contacto-checked.png");
        $("#contacto #checkvalue").val(1);
    }else{
        $("#contacto #checkbox").attr("src", "images/background-check-contacto.png");
        $("#contacto #checkvalue").val(0);
    }
}


/****************************************************************
/ Nombre: restablecer
/ Implentacion: 
/ Revision: 250211
/ Descripcion: Resetear los campos del formulario de contacto
'***************************************************************/

function restablecer(){
    
    $("#nombre").val("");
    $("#email").val("");
    $("#telefono").val("");
    $("#fax").val("");
    $("#comentarios").val("");
}

/****************************************************************
/ Nombre: getHTTPObject
/ Implentacion: 
/ Revision: 301106
/ Descripcion: Manejo del AJAX
'***************************************************************/
function getHTTPObject() {
    var xmlhttp;      
  
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {  
        try {
          xmlhttp = new XMLHttpRequest();
        } catch (e) {
          xmlhttp = false;
        }
    }
    return xmlhttp;
}
    
//--
var http = getHTTPObject(); 
var _loading = "<img class=\"loading\" src=\"images/loading.gif\" alt=\"Cargando\">";

//************ SECCION PRODCUTOS **************************************************
//*********************************************************************************
function ampliaProducto(pagina,id,tipo,galeria){
    if (tipo == 1){
//      alert(tipo);
        var ref = document.getElementById("pk_info"+id).value;
        if (ref != ""){
            document.getElementById("formularioAmplia" + id).action = document.getElementById("formularioAmplia" + id).action + "&ref="+ref;
        }
    }
    document.getElementById("formularioAmplia" + id).numPagina.value=pagina
    document.getElementById("formularioAmplia" + id).numGaleria.value=galeria
    document.getElementById("formularioAmplia" + id).submit();
}


/****************************************************************
/ Nombre: Paginacion
/ Implentacion: 
/ Revision: 301106
/ Descripcion: funcion para realizar la paginacion de los productos
'***************************************************************/
function paginacion(pagina){
    document.getElementById("formularioPaginacion").numPagina.value=pagina
    document.getElementById("formularioPaginacion").submit();
}

function volverCatalogo(pagina){
    document.getElementById("formularioVolver").numPagina.value=pagina
    document.getElementById("formularioVolver").submit();
}


/****************************************************************
/ Nombre: cambiaFondo
/ Implentacion: JBernalte
/ Revision: 301106
/ Descripcion: Cambia el fondo del obj como ID
'***************************************************************/
function cambiaFondo(pagina, obj){
        switch(pagina){
            case 1: 
                cambiaFondoByName('images/top-background-grupo.jpg', obj);
                break;
            default:
                cambiaFondoByName('images/top-background.jpg', obj);
        }
    }

function cambiaFondoByName(url, obj){
    var element = document.getElementById(obj); 
        element.style.backgroundImage = "url(" + url + ")";
        return element;
    }

/****************************************************************
/ Nombre: cambiaClaseFamilia
/ Implentacion
/ Revision: 301106
/ Descripcion: Cambia ela clase del obj pasado como ID
'***************************************************************/
function cambiaClaseFamilia(obj){
    
    switch(obj){
            
            case 1: 
                clase= "x";
                break;
            default:
                clase= "x";
        }
    
    document.getElementById(obj).className=clase;
}


function quitaClaseFamilia(familia,marcado){
    
    if (familia==1 && marcado==0){
        clase="x";
    }
    
    document.getElementById("familia" + familia).className=clase;
}

//****************** SECCION CONTACTO ******************************************************************************************************************************/

/****************************************************************
/ Nombre: validarEmail
/ Implentacion
/ Revision: 301106
/ Descripcion: Valida el formato del email
'***************************************************************/
function validarEmail(valor){
//funcion para validar el formato del email
    return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor));
    
}

/****************************************************************
/ Nombre: validar
/ Implentacion
/ Revision: 301106
/ Descripcion: Valida los campos del formulario
'***************************************************************/
function validar(idioma, op){
//Funcion para la validar los datos enviados desde el formulario de contacto
    var texto,texto_en,texto_fr,texto_val;
    texto = "";
    texto_en = "";
    texto_fr = "";
    texto_val = "";
    texto_de = "";

    var cadenaEnvio;
    cadenaEnvio = "";
    
    //Aqui validamos que los campos obligatorios tengan valor y se añaden a la cadena de envio
    if ( document.getElementById("formularioContacto").nombre.value == "" ) {
        texto+=" * Debe indicar su nombre.<br>";
        texto_en+=" * You must enter your name.<br>";
        texto_fr+=" * Vous devez indiquer votre nom.<br>";
        texto_val+=" * Deu indicar el seu nom.<br>";
        texto_de+=" * Ihren Namen bitte.\n";
    }else{
        cadenaEnvio="nombre=" + encodeURIComponent(document.getElementById("formularioContacto").nombre.value);
    }
	
	if ( document.getElementById("formularioContacto").apellidos.value == "" ) {
        texto+=" * Debe indicar sus apellidos.<br>";
        texto_en+=" * You must enter your second name.<br>";
        texto_fr+=" * Vous devez indiquer votre nom.<br>";
        texto_val+=" * Deu indicar el seu nom.<br>";
        texto_de+=" * Ihren Namen bitte.\n";
    }else{
        cadenaEnvio += "&apellidos=" + encodeURIComponent(document.getElementById("formularioContacto").apellidos.value);
    }
    
    if ( document.getElementById("formularioContacto").email.value == "" ) {
        texto+=" * Debe indicar su e-mail.<br>";
        texto_en+=" * You must enter your e-mail.<br>";
        texto_fr+=" * Vous devez indiquer votre email.<br>";
        texto_val+=" * Deu indicar el seu e-mail.<br>";
        texto_de+=" * Ihre E-Mail Adresse bitte.\n";
    }
    
    if(document.getElementById("formularioContacto").email.value!=""){
        if(!validarEmail(document.getElementById("formularioContacto").email.value)){
                texto+=" * Formato de E-mail incorrecto.<br>";
                texto_en+=" * The E-mail format is wrong.<br>";
                texto_fr+=" * Format d'email incorrect.<br>";
                texto_val+=" * Format de E-mail incorrecte.<br>";
                texto_de+=" * E-Mail Format ist nicht richtig.\n";
        }else{
            cadenaEnvio+="&email=" + document.getElementById("formularioContacto").email.value;
        }
    }
    if ( document.getElementById("formularioContacto").mensaje.value == "" ){
        texto+=" * Debe incluir el motivo de su consulta.<br>";
        texto_en+=" * You must enter your comments.<br>";
        texto_fr+=" * Vous devez indiquer l'objet de votre demande.<br>";
        texto_val+=" * Deu incloure el motiu de la seua consulta.<br>";
    }else{
        cadenaEnvio+="&mensaje=" + encodeURIComponent(document.getElementById("formularioContacto").mensaje.value);
    }
	
	if (document.getElementById("formularioContacto").asunto.value != "") {
		if ( document.getElementById("formularioContacto").cif.value == "" && document.getElementById("formularioContacto").asunto.value.indexOf("0|") == 0) {
			texto+=" * Debe indicar su CIF.<br>";
			texto_en+=" * You must enter your CIF.<br>";
			texto_fr+=" * Vous devez indiquer votre CIF.<br>";
			texto_val+=" * Deu indicar el seu CIF.<br>";
			texto_de+=" * Ihren CIF bitte.\n";
		}
		else {
			cadenaEnvio+="&cif=" + encodeURIComponent(document.getElementById("formularioContacto").cif.value);
		}
	}
	else {
		if (document.getElementById("formularioContacto").cif.value != "") {
			cadenaEnvio+="&cif=" + encodeURIComponent(document.getElementById("formularioContacto").cif.value);
		}
	}
	
	if (!($("#acceptprivacypolicy").attr("checked"))) {
		texto += " * Debe aceptar las condiciones de uso.<br>";
		texto_en += " * You must accept terms of use.<br>";
		texto_fr += " * You must accept terms of use.<br>";
		texto_val += " * Deu acceptar les condicions d'ús.<br>";
		texto_de += " * You must accept terms of use.\n";
	}
    
    //Aqui vamos añadiendo los demas campos sino estan vacion
    
    /*if ( document.getElementById("formularioContacto").direccion.value != "" ){
        cadenaEnvio+="&direccion=" + document.getElementById("formularioContacto").direccion.value;
    }
    
    if ( document.getElementById("formularioContacto").poblacion.value != "" ){
        cadenaEnvio+="&poblacion=" + document.getElementById("formularioContacto").poblacion.value;
    }
    
    if ( document.getElementById("formularioContacto").provincia.value != "" ){
        cadenaEnvio+="&provincia=" + document.getElementById("formularioContacto").provincia.value;
    }
    */
    if (document.getElementById("formularioContacto").telefono.value != "") {
        cadenaEnvio+="&telefono=" + document.getElementById("formularioContacto").telefono.value;
    }
	
	if (document.getElementById("formularioContacto").telefono.value != "") {
        cadenaEnvio+="&telefono2=" + document.getElementById("formularioContacto").telefono2.value;
    }
    
    /*if ( document.getElementById("formularioContacto").movil.value != "" ){
        cadenaEnvio+="&movil=" + document.getElementById("formularioContacto").movil.value;
    }
    
    if ( document.getElementById("formularioContacto").cpostal.value != "" ){
        cadenaEnvio+="&cpostal=" + document.getElementById("formularioContacto").cpostal.value;
    }
    */
    if (document.getElementById("formularioContacto").fax.value != "") {
        cadenaEnvio+="&fax=" + document.getElementById("formularioContacto").fax.value;
    }

	if (document.getElementById("formularioContacto").empresa.value != "") {
        cadenaEnvio+="&empresa=" + encodeURIComponent(document.getElementById("formularioContacto").empresa.value);
    }
	
	if (document.getElementById("formularioContacto").asunto.value != "") {
        cadenaEnvio+="&asunto=" + encodeURIComponent(document.getElementById("formularioContacto").asunto.value);
    }
    /*
    try{
        if ( document.getElementById("formularioContacto").reference.value != "" ){
            cadenaEnvio+="&reference=" + document.getElementById("formularioContacto").reference.value;
        }
    }catch(e){
            cadenaEnvio+="&reference=";
    }*/
    /*
    //if ( document.getElementById("formularioContacto").pais2.value != "" ){
        cadenaEnvio+="&pais=" + document.getElementById("formularioContacto").pais.options[document.getElementById("formularioContacto").pais.selectedIndex].text
    //}
    cadenaEnvio += "&op=" + op;
    cadenaEnvio += "&empresa=" + document.getElementById("formularioContacto").empresa.value;
    //Si falta algun campo obligatorio o el email no tiene un formato correcto
    //mostramos un mensaje de avios
    */
	
    if ( texto != "" ){
            switch (idioma) { 
                case 101: 
                    document.getElementById("mensajeError").innerHTML=texto_en;
                   break 
                default: 
                    document.getElementById("mensajeError").innerHTML=texto;
            } 
        document.getElementById("capaError").style.display='block';
        
    }else{
        document.getElementById("mensaje-respuesta").innerHTML="";
        document.getElementById("mensajeError").innerHTML="";
        document.getElementById("capaError").style.display='none';
        http.open("GET", "actualizer/formcorreosMultiple/envioSinBd.asp?" + cadenaEnvio, true);
        http.onreadystatechange = handleHttpResponseContacto;
        http.send(null);
    }
    
}




function validarAnunciate(idioma){
//Funcion para la validar los datos enviados desde el formulario de contacto
    var texto,texto_en,texto_fr,texto_val;
    texto = "";
    texto_en = "";
    texto_fr = "";
    texto_val = "";
    texto_de = "";

    var cadenaEnvio;
    cadenaEnvio = "";
    
    //Aqui validamos que los campos obligatorios tengan valor y se añaden a la cadena de envio
    if (!document.getElementById('acepto').checked){
        if (idioma == 100){
            texto+="* Debe aceptar los términos.<br>";
        }else{
            texto+="* You must accept terms.<br>";
        }
    }


    if ( document.getElementById("formImag").nombre.value == "" ) {
        texto+=" * Debe indicar su nombre.<br>";
        texto_en+=" * You must enter your name.<br>";
        texto_fr+=" * Vous devez indiquer votre nom.<br>";
        texto_val+=" * Deu indicar el seu nom.<br>";
        texto_de+=" * Ihren Namen bitte.\n";

    }
    
    if ( document.getElementById("formImag").email.value == "" ) {
        texto+=" * Debe indicar su e-mail.<br>";
        texto_en+=" * You must enter your e-mail.<br>";
        texto_fr+=" * Vous devez indiquer votre email.<br>";
        texto_val+=" * Deu indicar el seu e-mail.<br>";
        texto_de+=" * Ihre E-Mail Adresse bitte.\n";
    }
    
    if(document.getElementById("formImag").email.value!=""){
        if(!validarEmail(document.getElementById("formImag").email.value)){
                texto+=" * Formato de E-mail incorrecto.<br>";
                texto_en+=" * The E-mail format is wrong.<br>";
                texto_fr+=" * Format d'email incorrect.<br>";
                texto_val+=" * Format de E-mail incorrecte.<br>";
                texto_de+=" * E-Mail Format ist nicht richtig.\n";
        }
    }
    if ( document.getElementById("formImag").telefono.value == "" ){
        texto+=" * Debe indicar su teléfono.<br>";
        texto_en+=" * You must enter your phone.<br>";
        texto_fr+=" * Vous devez indiquer l'objet de votre demande.<br>";
        texto_val+=" * Deu incloure el motiu de la seua consulta.<br>";
    }   
    
    if ( texto != "" ){
        switch (idioma) { 
            case 101: 
                document.getElementById("mensajeError").innerHTML=texto_en;
               break 
            default: 
                document.getElementById("mensajeError").innerHTML=texto;
        } 
    document.getElementById("capaError").style.display='block';
        
    }else{
        document.getElementById("formImag").submit();
    }
    
}




/****************************************************************
/ Nombre: cerrarAviso
/ Implentacion: 

/ Revision:
/ Descripcion: Cierra la capa del aviso del formulario
'***************************************************************/
function cerrarAviso(){
    document.getElementById("mensajeError").innerHTML="";
    document.getElementById("capaError").style.display='none';
}

function handleHttpResponseContacto() {
    if (http.readyState == 4) {     
        //Aqui va el nombre de la capa donde queramos cargar el contenido
        document.getElementById("mensaje-respuesta").innerHTML = http.responseText; 
        document.getElementById("formularioContacto").reset();
    }    
}

/****************************************************************
/ Nombre: validar
/ Implentacion
/ Revision: 301106
/ Descripcion: Valida los campos del formulario
'***************************************************************/
function validarIns(tipo){
//Funcion para la validar los datos enviados desde el formulario de contacto
    var texto;
    texto = "";

    var cadenaEnvio;
    cadenaEnvio = "";
    
    //Aqui validamos que los campos obligatorios tengan valor y se añaden a la cadena de envio
    
/*  if ( document.getElementById("formRegistro").nombre.value == "" ) {
        texto+=" * Debe indicar su nombre.\n";
    }else{
        cadenaEnvio="nombre=" + document.getElementById("formRegistro").nombre.value;
    }*/
    
    if ( document.getElementById("formRegistro").email.value == "" ) {
        texto+=" * Debe indicar su e-mail.\n";
    }
    
    if(document.getElementById("formRegistro").email.value!=""){
        if(!validarEmail(document.getElementById("formRegistro").email.value)){
                texto+=" * Formato de E-mail incorrecto.\n";
        }else{
            cadenaEnvio+="&email=" + document.getElementById("formRegistro").email.value;
        }
    }
    if (( document.getElementById("formRegistro").telefono.value != "" ) && ( isNaN(document.getElementById("formRegistro").telefono.value)) ){
        document.getElementById("formRegistro").telefono.value = ""
        document.getElementById("formRegistro").telefono.focus();
        texto+=" * El número de teléfono debe ser numérico.\n";
    }
    if (( document.getElementById("formRegistro").movil.value != "" ) && ( isNaN(document.getElementById("formRegistro").movil.value)) ){
        document.getElementById("formRegistro").movil.value = ""
        document.getElementById("formRegistro").movil.focus();
        texto+=" * El número de móvil debe ser numérico.\n";
    }
    if ( isNaN(document.getElementById("formRegistro").cpostal.value) ){
        document.getElementById("formRegistro").cpostal.value = ""
        document.getElementById("formRegistro").cpostal.focus();
        texto+=" * El código postal debe ser numérico.\n";
    }

    if ( document.getElementById("formRegistro").nick.value == "" ) {
        texto+=" * Debe indicar su nick.\n";
    }else if ( document.getElementById("formRegistro").nick.value.length < 4 ) {
                texto+=" * El nick debe ser de al menos 4 carácteres.\n";
    }
    if ( document.getElementById("formRegistro").dia.value == "0" ) {
        texto+=" * Debe seleccionar el día de su fecha de nacimiento.\n";
    }
    if ( document.getElementById("formRegistro").mes.value == "0" ) {
        texto+=" * Debe seleccionar el mes de su fecha de nacimiento.\n";
    }
    if ( document.getElementById("formRegistro").anyo.value == "0" ) {
        texto+=" * Debe seleccionar el año de su fecha de nacimiento.\n";
    }
    
    //para controlar que las fechas sean correctas
    var dia, mes, anyo;
    
    dia = document.getElementById('formRegistro').dia.value;
    mes = document.getElementById('formRegistro').mes.value;
    anyo = document.getElementById('formRegistro').anyo.value;
    
    if (!compruebaFecha(dia, mes, anyo)){
        texto+=" * La fecha intorducida es incorrecta.\n";
    }

        cadenaEnvio+="&=" + document.getElementById("formRegistro").preferencias.value;

    if ( document.getElementById("formRegistro").condiciones.checked == false ) {
        texto+=" * Debe aceptar las condiciones legales para registrarse.\n";
    }
    
    var email = document.getElementById("formRegistro").email.value;
    var nick = document.getElementById("formRegistro").nick.value;
    
        if ( texto != "" ){
                alert(texto);
        }else{
            http.open("GET", "registro/compruebaEmail.asp?email=" + email +"&nick=" + nick, true);
            http.onreadystatechange = handleHttpResponseComprobar;
            http.send(null);
        }
    
    
}

function handleHttpResponseComprobar() {
    if (http.readyState == 4) {     
        //Aqui va el nombre de la capa donde queramos cargar el contenido
            var t =  http.responseText; 
        if ( t != "" ){
                alert(t);
        }else{
                document.getElementById("formRegistro").op.value = 0;
                document.formRegistro.submit();
        }
    }    
}


/****************************************************************
/ Nombre: compruebaFecha()
/ Implentacion: Fperez

/ Revision:
/ Descripcion: Comprueba que las fechas sean correctas
'***************************************************************/
function compruebaFecha(dia, mes, anyo){
    var error;
    if ((dia > 30) && ((mes == 2) || (mes == 4) || (mes == 6) || (mes == 9) || (mes == 11))){
        return false;
    }
    if ((dia > 29) && (mes == 2)){
        return false;
    }
    var resto = parseInt(anyo)%4;
    if (resto != 0){
        if ((dia > 28) && (mes == 2)){
            return false;
        }
    }
    
    return true;
}




/*********************************************************************************
/ Nombre: mostrarReferencia
/ Implentacion: FPEREZ
/ Revision: 05-10-07
/ Descripcion: Cambia el precio y los datos de cada referencia
*********************************************************************************/
function showReference(id){
    var element = document.getElementById("referencias"+id);
    var pagina = QueryStringParam("pagina");
    var temaId = QueryStringParam("subpagina");
    var galeriaId = QueryStringParam("galeria");
    var url="index.asp?pagina=" + pagina + "&subpagina=" + temaId + "&galeria=" + galeriaId + "&producto=" + element.value;
    window.location.href = url;
}

function mostrarReferencia(id){
        if (document.getElementById("pk_info"+id).value == ""){
            document.getElementById("referencia").innerHTML = "";
            document.getElementById("referencia").style.display = "block";  
            return false;
        }
        var idReferencia = document.getElementById("pk_info"+id).value;
        document.getElementById("enlace_"+id).href = document.getElementById("enlace_"+id).href + "&ref=" + idReferencia
        document.getElementById("enlace_imagen_"+id).href = document.getElementById("enlace_imagen_"+id).href + "&ref=" + idReferencia
        document.getElementById("enlace_titulo_"+id).href = document.getElementById("enlace_titulo_"+id).href + "&ref=" + idReferencia
        http.open("GET", "./includes/getReferencia.asp?id=" + idReferencia, true);
        http.onreadystatechange = handleHttpResponseReferencia;
        http.send(null);
    
}

function handleHttpResponseReferencia() {
    if (http.readyState == 4) {     
        //Aqui va el nombre de la capa donde queramos cargar el contenido
        var contenido = http.responseText.split("|");
        var id = contenido[1];
        
        if (contenido[0] != ""){
            document.getElementById("precio_referencia"+id).innerHTML = "POR&nbsp;<big><big><b>" +  contenido[0] + "</b></big></big>&nbsp;&euro;";  
        }
        document.getElementById("precio_referencia"+id).style.display = "block";    
    }    
}

/****************************************************************
/ Nombre: openWindow
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Abre un popup
'***************************************************************/
    function openWindow(theURL,winName,features){
        window.open(theURL,winName,features);
        return
    }


/****************************************************************
/ Nombre: muestraTema
/ Implentacion:
/ Revision:
/ Descripcion: Muestra los temas
'***************************************************************/
function muestraTema(id,numero) {
    for (i=1;i<=numero;i++){
        if (id != i){
            
            if (document.getElementById("filaContenidoTema"+ i).style.display == "block"){
                document.getElementById("filaContenidoTema"+ i).style.display = "none";
            }
                document.getElementById("enlaceTema"+ i).className = "desmarcado";
        }
    }
    if (document.getElementById("filaContenidoTema"+ id).style.display == "block") { 
        document.getElementById("filaContenidoTema"+ id).style.display = "none"; }
    else { 
        document.getElementById("filaContenidoTema"+ id).style.display = "block";
        document.getElementById("enlaceTema"+ id).className = "marcado";
        }

}


/****************************************************************
/ Nombre: capaPosition
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Posiciona una capa en el centro de la pantalla +- los pixeles deseados
'***************************************************************/
function capaPosition(layer, position){
        element = document.getElementById(layer);
        screenCenterX = document.body.clientWidth / 2;
        element.style.left = screenCenterX + position;
        element.style.display = 'inline';
    }


/****************************************************************************************
/ Nombre: ampliaImagen
/ Implentacion: PACO
/ Revision:
/ Descripcion: Muestra el PopUp de ampliacion de las imagenes y lo redimensiona
'***************************************************************************************/
function ampliaImagen(url){
    document.getElementById('imagenAmpliada').src = "images/" + url;
    }

function redimensionarImagen(img){
    var anchoImagen,altoImagen,anchoPantalla,altoPantalla;
    img1 = new Image(); 
    img1.src = img.src;
    anchoImagen = img1.width;
    altoImagen = img1.height;
//  anchoPantalla = window.screen.width;
    anchoPantalla = 930
    altoPantalla = window.screen.height - 240;
    posicionx = (anchoPantalla/2) - (anchoImagen/2);
    posiciony = (altoPantalla/2) - (altoImagen/2);
    
    // coloca la capa de la imagen y la redimensiona
    document.getElementById('capaImagenAmpliada').style.top = posiciony + 'px';
    document.getElementById('capaImagenAmpliada').style.left = posicionx + 'px';
    document.getElementById('capaImagenAmpliada').style.width = anchoImagen + 'px';
    document.getElementById('capaImagenAmpliada').style.height = altoImagen + 'px';
    // coloca un poco más arriba la capa del enlace para cerrar
    posicionCerrar = posiciony - 19;
    document.getElementById('cerrarImagenAmpliada').style.top = posicionCerrar + 'px';
    document.getElementById('cerrarImagenAmpliada').style.left = posicionx + 'px';

    document.getElementById('capaImagenAmpliada').style.display = 'block';
    document.getElementById('cerrarImagenAmpliada').style.display = 'block';
    // en caso del formulario de contacto, ocultamos el combo
    document.getElementById('pais').style.visibility = 'hidden';
}

function cerrarImagenAmpliada(){
    document.getElementById('imagenAmpliada').src = "";
    document.getElementById('capaImagenAmpliada').style.display = 'none';
    document.getElementById('cerrarImagenAmpliada').style.display = 'none';
    document.getElementById('pais').style.visibility = 'visible';
}

/****************************************************************************************
/ Nombre: 		DoLogin
/ Implentacion: Jordi Darijo
/ Revision:		22/08/2011
/ Descripcion: 	Hace el login cuando pulsa ENTER en el campo password
'***************************************************************************************/
function DoLogin(e, type, id) {
	var key;
	if (e.which == undefined) {
		key = e.keyCode;
	}
	else {
		key = e.which;
	}
	
	if (key == 13) {
		Login(type, id);
	}
}

/****************************************************************************************
/ Nombre: Login
/ Implentacion: JBERNALTE
/Parametros: [Type] (off) desautentifica (otra cosa) autentifica
/ Revision:
/ Descripcion: Login de usuario en la zona privada
'***************************************************************************************/
var _id = 0;

function Login(type, id) {
    _id = id;
    var msg = document.getElementById("Login_" + _id + "_Msg");
    msg.innerHTML = "";
    var params = "";
    var valid = true;
    try {
        var page = document.getElementById("page_" + _id).value;
    }
    catch (e) {

    }

	$(".loginlayer .rememberpassword").css("display", "none");
	
    if (type != "off") {

        params += "login=on"

        var campos = new Array();
        var mensajes = new Array();


        /* DEFINE CAMPO A VALIDAR MENSAJE*/
        //Se entiende que si no tiene mensaje de validacion, es porque el campo no es obligatorio
        campos[0] = "user"; mensajes[0] = "Indique su usuario";
        campos[1] = "password"; mensajes[1] = "Indique su contraseña";

        valid = true;

        for (i = 0; i < campos.length; i++) {
            var element = document.getElementById("Login_" + _id + "_" + campos[i])
            if (mensajes[i] != '') {

                if ((element.value == '') && (mensajes[i] != '')) {
                    msg.innerHTML += mensajes[i] + "<br/>";
                    valid = false;
                } else {
                    params += "&" + campos[i] + "=" + element.value;
                }
            } else {
                params += "&" + campos[i] + "=" + element.value;
            }
        }

    } 
	else {
        params += "login=off";
    }
    
    if (valid) {
        params += "&page=" + page;
        url = "AjaxResponse/loginEngine.asp?" + params;
        http.open("GET", url, true);
        http.onreadystatechange = handleHttpResponseReload;
        http.send(null);
    } else {
		$(".loginlayer #Login_1_Msg").css("display", "block");
        return false;
    }
}



function Login_Keypress(e, type, id){
    _id = id;
    var ascii; 
    if (e.keyCode) 
        ascii = e.keyCode; 
    else if (e.which) 
        ascii = e.which; 
    else 
        return false; 
         
    if (ascii == 13) {
        Login(type, _id);
        return true; 
    }
    
}


function autentificaFlash(user, pass) {
//  alert(user); 
//  alert(pass);
    if (user=="" && pass==""){
        url = "AjaxResponse/loginEngine.asp?login=off";
        http.open("GET", url , true);
        http.onreadystatechange = handleHttpResponseReloadFlash;
        http.send(null);
    }else{
        url = "AjaxResponse/loginEngine.asp?login=on&user=" + user + "&password=" + pass;
        http.open("GET", url , true);
        http.onreadystatechange = handleHttpResponseReloadFlash;
        http.send(null);    
    }   
}


/****************************************************************************************
/ Nombre: edit, handleHttpResponseEdit
/ Implentacion: JBERNALTE
/Parametros: [Type] (off) previsualiza (otra cosa) edita
/ Revision:
/ Descripcion: Cambia a modo edicion en la zona privada
'***************************************************************************************/
function edit(type){
    var strEnvio = '';
    

        strEnvio += "edicionMode=" + type;


        url = "includes/loginEngine.asp?" + strEnvio;
        http.open("GET", url , true);
        http.onreadystatechange = handleHttpResponseReload;
        http.send(null);        
}


/****************************************************************************************
/ Nombre: edit, handleHttpResponseReload
/ Implentacion: JBERNALTE
/ Revision:13/06/2007
/ Descripcion: Recarga la pagina despues de ejecutar AJAX
'***************************************************************************************/
function handleHttpResponseReload() {
	var loginincorrect = $("#loginincorrect").val();
    var msg = document.getElementById("Login_" + _id + "_Msg");
	if (document.getElementById("Login_" + _id + "_user") != undefined) {
		var user = document.getElementById("Login_" + _id + "_user").value;	
	}
	if (document.getElementById("Login_" + _id + "_password") != undefined) {
    	var pass = document.getElementById("Login_" + _id + "_password").value;
	}
    
    if (http.readyState == 4) {
        //window.location.reload();
        var respuesta=http.responseText;
        if (respuesta=="no"){
            if (!valTexto(user) || !valTexto(pass)){
				msg.style.display='block';
                msg.innerHTML = loginincorrect;                                                 
            }else{
				msg.style.display='block';
                msg.innerHTML = loginincorrect;
            }
			$(".loginlayer #Login_1_Msg").css("display", "block");
        }
        //Autentificado ON
        if (respuesta=="si"){
                
            var pagina=document.getElementById("Login_" + _id + "_pagina").value;
            var producto=document.getElementById("Login_" + _id + "_producto").value;
            var tema=document.getElementById("Login_" + _id + "_tema").value;
            reloadUrl = replace(window.location.href, "#", "" );
            reloadUrl = replace(reloadUrl, "&shoppingcart=1", "" );
            
            document.location = "index.asp?pagina="+ pagina;
        }
        //Autentificado OFF
        if (respuesta=="salir"){
            reloadUrl = replace(window.location.href, "#", "" );
            reloadUrl = replace(reloadUrl, "&shoppingcart=1", "" );
            document.location = reloadUrl;
        }
    }    
}


function handleHttpResponseReloadFlash() {
    if (http.readyState == 4) {
        //window.location.reload();
        var respuesta=http.responseText;
        if (respuesta=="no"){
            //document.getElementById("mensaje-alerta").style.display='block';
        }
        if (respuesta=="salir"){
            document.location="index.asp?pagina=home";
        }
        if (respuesta=="si"){
            //var pagina=document.getElementById("login").pagina.value;
            //var subpagina=document.getElementById("login").subpagina.value;
            //var c=document.getElementById("login").c.value;
            document.location.href ="index.asp?pagina=zona-privada";
        }
    }    
}
/****************************************************************************************
/ Nombre: edit, handleHttpResponseEdit
/ Implentacion: JBERNALTE
/Parametros: [Type] (off) previsualiza (otra cosa) edita
/ Revision:
/ Descripcion: Cambia a modo edicion en la zona privada
'***************************************************************************************/
function edit2(type){
    var strEnvio = '';
    

        strEnvio += "edicionMode=" + type;


        url = "includes/loginEngine.asp?" + strEnvio;
        http.open("GET", url , true);
        http.onreadystatechange = handleHttpResponseReload2;
        http.send(null);        
}


/****************************************************************************************
/ Nombre: edit, handleHttpResponseReload
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Recarga la pagina despues de ejecutar AJAX
'***************************************************************************************/
function handleHttpResponseReload2() {
    if (http.readyState == 4) {
        window.location.href= "index.asp?pagina=ficha-de-usuario";
    }    
}


/****************************************************************************************
/ Nombre: changeAccountData, handleHttpResponseAccount
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Actualiza los datos del usuario
'***************************************************************************************/
function changeAccount(type){
    
    alert("GUAU! ( o )( o )");
    
    
    strEnvio='';
    
    //FALTA MONTAR EL ENVIO
    
    if(type == 'new'){
        strEnvio += "account=new"
    }else{
        strEnvio += "account=update"
    }
    
    url = "includes/AccountEngine.asp?" + strEnvio;
    http.open("GET", url , true);
    http.onreadystatechange = handleHttpResponseAccount;
    http.send(null);
}


function handleHttpResponseAccount() {
    if (http.readyState == 4) {     
        document.getElementById("resultado").innerHTML = http.responseText;
    }    
}

/****************************************************************************************
/ Nombre: changePicture
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Cambia una imagen
'***************************************************************************************/
function changePicture(id, picture){
        
        document.getElementById(id).src = picture;
}

function muestraCapa(){
    document.getElementById('recordarPassword').style.display = 'block';
}
/****************************************************************************************
/ Nombre: enviarEmail
/ Implentacion: Fperez
/ Revision:
/ Descripcion: Envia el recordatorio de la contraseña por email
'***************************************************************************************/

function Login_Remember_Password_show(id){
    _id = id;
    var element  = document.getElementById('recordarPassword_' + _id);
    element.style.display = element.style.display=="block" ? "none" : "block";
}

function Login_Remember_Password_KeyPress(e, id){
    _id = id;
    var ascii; 
    if (e.keyCode) 
        ascii = e.keyCode; 
    else if (e.which) 
        ascii = e.which; 
    else 
        return false; 
         
    if (ascii == 13) {
        Login_Remember_Password(_id);
        return true; 
    }
}



function Login_Remember_Password(id) {
	_id = id;
	var element = document.getElementById("Login_" + _id + "_Email");
	var msg 	= document.getElementById("rememberpassword_" + _id + "_msg");         
	if (validarEmail(element.value)) {
		cadenaEnvio = "email=" + element.value;
		http.open("GET", "AjaxResponse/Users/sendDataAccessToUser.asp?" + cadenaEnvio, true);
		http.onreadystatechange = handleHttpResponseLogin_Remember_Password;
		http.send(null);
	}
	else {
		//var element2 = document.getElementById("rememberText");
		//element2.style.display = "none";
		msg.style.display = "block";
		msg.innerHTML = "* Formato incorrecto";
	}
}

function handleHttpResponseLogin_Remember_Password() {
    var msg 	= document.getElementById("rememberpassword_" + _id + "_msg");
    var element = document.getElementById("Login_" + _id + "_Email");

    if (http.readyState == 4) {   
        //Aqui va el nombre de la capa donde queramos cargar el contenido
        msg.style.display = 'block';    
        msg.innerHTML = http.responseText;  
        element.value = "";
    }    
}


var _subMenu = false;

/****************************************************************************************
/ Nombre: submenuPosition
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Central el menu a partir del centro de la resolucion de pantalla
'***************************************************************************************/

    function submenuPosition(layer, position){
        subMenuHide();
        _subMenu = true;
        element = document.getElementById(layer);
        screenCenterX = document.body.clientWidth / 2;
        element.style.left = screenCenterX + position;
        element.style.display = 'inline';
    }
    

/****************************************************************************************
/ Nombre: subMenuHide
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Oculta el submenu, necesitamos definir cuantos existen
'***************************************************************************************/
    function subMenuHide(){
        _subMenu = false;
        setTimeout("subMenuHideTime()", 500);
    }
    
    
    function subMenuHideTime(){

        if(!_subMenu){
            cuantos = 1;
            
            //OCULTAMOS TODOS
            for(i=1; i<=cuantos; i++){
                document.getElementById('submenu' + i).style.display = "none";
            }
        }
        
    }
    
    
/****************************************************************************************
/ Nombre: buscadorWeb
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Envia el formulario de busqueda
'***************************************************************************************/
function searchOnWeb(e){            
    if(e.witch == 13) {
        if (document.getElementById("textobusqueda").value.length < 1){
            alert("Introduzca el texto de búsqueda");
        }
        else{
            document.getElementById("busqueda").submit();
        }
    }
}




/****************************************************************
/ Nombre: validarvalidarSuscripcion
/ Implentacion: JBERNALTE
/ Revision: 11-03-09
            Se ha quitado la etiqueta form
/ Descripcion: Valida los campos del formulario de suscripcion
'***************************************************************/
function NewsLetter(idioma){


    var texto,texto_en,texto_fr,texto_val,texto_de;
    texto = "";
    texto_en = "";
    texto_fr = "";
    texto_val = "";
    texto_de = "";
    
    var nombre = document.getElementById("newslettername");
    var apellidos = document.getElementById("newslettersurname");
    var email = document.getElementById("newsletteremail");
    var msg = document.getElementById("newsletter_msg");
    var url = "actualizer/suscripcion/suscripcion.asp?";
    var params = "";
    msg.style.display="none";
    if (nombre.value == "" ) {
        texto       +=  " * Debe indicar su nombre.<br>";
        texto_en    +=  " * You must enter your name.<br>";
        texto_fr    +=  " * Vous devez indiquer votre nom.<br>";
        texto_val   +=  " * Deu indicar el seu nom.<br>";
        texto_de    +=  " * Ihren Namen bitte.<br>";
    }else{
        params="nombre=" + escape(nombre.value);
    }
    
    if (email.value == "" ) {
        texto       +=" - Debe indicar su email.<br>";
        texto_en    +=" * You must enter your e-mail.<br>";
        texto_fr    +=" * Vous devez indiquer votre email.<br>";
        texto_val   +=" * Deu indicar el seu e-mail.<br>";
        texto_de    +=" * Ihre E-Mail Adresse bitte.<br>";
    }else{
        if(!validarEmail(email.value)){
            texto       +=" * Formato de E-mail incorrecto.<br>";
            texto_en    +=" * The E-mail format is wrong.<br>";
            texto_fr    +=" * Format d'email incorrect.<br>";
            texto_val   +=" * Format de E-mail incorrecte.<br>";
            texto_de    +=" * E-Mail Format ist nicht richtig.<br>";
        }else{
            params  +="&email=" + escape(email.value);
        }
    }


    //Apellidos no obligatorios
    if (apellidos.value != "" ) {
        params  +="&surname=" + apellidos.value;
    }

    if (texto != "") {
        //var sus = document.getElementById("sus");
        //sus.style.display = "none"
        var cerrarMsg = document.getElementById("cerrarMsg");
        cerrarMsg.style.display = "block"
        
        msg.innerHTML="";
        
        switch (idioma) { 
            case 101:
                msg.innerHTML=texto_en;
               break 
            case "fr": 
                msg.innerHTML=texto_fr;
               break 
            case "val": 
                msg.innerHTML=texto_val;
               break 
            case "de": 
                msg.innerHTML=texto_de;
               break 
            default: 
                msg.innerHTML=texto;
        } 
        msg.style.display="block";
    }else{
        
        http.open("GET", url + params, true);
        http.onreadystatechange = handleHttpResponseSuscripcion;
        http.send(null);
    }   
}
function handleHttpResponseSuscripcion() {
    
    var msg = document.getElementById("newsletter_msg");
    var nombre = document.getElementById("newslettername");
    var email = document.getElementById("newsletteremail");
    var apellidos = document.getElementById("newslettersurname");
    var sus = document.getElementById("sus");
    if (http.readyState == 4) {  
        //Aqui va el nombre de la capa donde queramos cargar el contenido
        var cerrarMsg = document.getElementById("cerrarMsg");
        cerrarMsg.style.display = "block"
        sus.style.display = "none"
        msg.innerHTML = http.responseText;
        msg.style.display="block";
        nombre.value = "";
        email.value = "";
        apellidos.value ="";
    }    
}
function blanco(){
    if (document.getElementById('nombre').value == ' nombre') {
        document.getElementById('nombre').value = '';
    }
    if (document.getElementById('email').value == ' e-mail') {
        document.getElementById('email').value = '';
    }
}

/****************************************************************************************
/ Nombre: ReferenceInformation
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Envia el formulario de solicituda de la ficha de producto
'***************************************************************************************/
function ReferenceInformation(language, section){

    
    var url = "";
    //Parametros del producto
        var params = "language="+ language + "&section=" + section;
        var error = false;
        var objects = document.getElementsByTagName("INPUT");

        for (var i=0; i < objects.length; i++) {
            obj = objects[i];
            var fieldMsg = document.getElementById(obj.id + "_msg");
            if(obj.id.indexOf("referenceForm_") >= 0){
                
                //var fieldTitle = document.getElementById(obj.id + "_title");
                //alert(id + " " + obj.id)
                //fieldMsg.style.display = "none";      
                if((obj.value != obj.title) && (obj.name != 'email' || (obj.name == 'email' && validarEmail(obj.value)) )){
                        //params += fieldTitle.innerHTML + ": " +  obj.options[obj.selectedIndex].text + " ";
                        fieldName = obj.id.replace("referenceForm_","");
                        fieldName = fieldName.split("_");
                        params += "&" + fieldName[0]  + "=" + escape(obj.value);
                        fieldMsg.innerHTML = "";
                        fieldMsg.style.display = "none";
                }else{
                    error = true;
                    
                    if (obj.name == 'email' && !validarEmail(obj.value)){
                        fieldMsg.innerHTML = "* Formato incorrecto";
                    }else{
                        fieldMsg.innerHTML = "* Campo obligatorio";
                    }
                    
                    fieldMsg.style.color = "#FF0000";
                    fieldMsg.style.display = "block";
                }
            }
        }
        
        var objects = document.getElementsByTagName("TEXTAREA");
        for (var i=0; i < objects.length; i++) {
            obj = objects[i];
            var fieldMsg = document.getElementById(obj.id + "_msg");
            if(obj.id.indexOf("referenceForm_") >= 0){
                
                //var fieldTitle = document.getElementById(obj.id + "_title");
                //alert(id + " " + obj.id)
                //fieldMsg.style.display = "none";      
                if(obj.value != obj.title){
                        fieldName = obj.id.replace("referenceForm_","");
                        fieldName = fieldName.split("_");
                        params += "&" + fieldName[0]  + "=" + escape(obj.value);
                        fieldMsg.innerHTML = "";
                        fieldMsg.style.display = "none";
                }else{
                    error = true;
                    fieldMsg.innerHTML = "* Campo obligatorio";
                    fieldMsg.style.color = "#FF0000";
                    fieldMsg.style.display = "block";
                }
            }
        }


        if(!error){
            //alert(params)
            var msj = document.getElementById("referenceForm_msg")
            url = "./AjaxResponse/Shop/ajax_saveRrefenceInformation.asp";
            http.open("POST", url , true);
            
            http.onreadystatechange = function() {
            if (http.readyState==1) {
                              
                              msj.innerHTML="<br/><br/><br/><br/>Enviando consulta. Espere";
                              
            }else if (http.readyState==4){
                       if(http.status==200)
                       {
                           msj.innerHTML="";
                            msj.innerHTML =  http.responseText;
                       }
                       else if(http.status==404){
                                msj.innerHTML = "La direccion no existe";
                            }else{
                                msj.innerHTML = "Error: " + http.status;
                            }
                       }
             }
             http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
             http.send(params);
        }
         return;    
}


/****************************************************************************************
/ Nombre: getProvincia
/ Implentacion: JDolz
/ Revision:
/ Descripcion: recoje el id de la provincia y muestra el contenido
'***************************************************************************************/
function getProvincia(provincia){
    
    http.open("GET", "includes/getDistribuidores.asp?provincia=" + provincia , true);
    http.onreadystatechange = handleHttpResponseDistribuidor;
    http.send(null);

}
function handleHttpResponseDistribuidor() {
    if (http.readyState == 4) { //   alert(http.responseText);  
        //Aqui va el nombre de la capa donde queramos cargar el contenido
        document.location = http.responseText;  
    }    
}


/****************************************************************
/ Nombre: validarContacto
/ Implentacion
/ Revision: 301106
/ Descripcion: Valida los campos del formulario de contacto con adjunto
'***************************************************************/
function validarContacto(){
//Funcion para la validar los datos enviados desde el formulario de contacto
    var texto;
    texto = "";
    
    var cadenaEnvio;
    cadenaEnvio = "";
    
    //Aqui validamos que los campos obligatorios tengan valor y se añaden a la cadena de envio
    
    if ( document.getElementById("formularioContacto").nombre.value == "" ) {
        texto+=" - Debe indicar su nombre.<br>";

    }else{
        cadenaEnvio="nombre=" + document.getElementById("formularioContacto").nombre.value;
    }
    
    if ( document.getElementById("formularioContacto").email.value == "" ) {
        texto+=" - Debe indicar su email.<br>";
    }
    
    if(document.getElementById("formularioContacto").email.value!=""){
        if(!validarEmail(document.getElementById("formularioContacto").email.value)){
                texto+=" - Formato de E-mail incorrecto.<br>";
        }else{
            cadenaEnvio+="&email=" + document.getElementById("formularioContacto").email.value;
        }
    }
    if ( document.getElementById("formularioContacto").comentarios.value == "" ){
        texto+=" - Debe incluir su presentación.<br>";
    }else{
        cadenaEnvio+="&comentarios=" + document.getElementById("formularioContacto").comentarios.value;
    }   
    
    if ( texto != "" ){
        document.getElementById("mensajeError").innerHTML=texto;
        document.getElementById("capaError").style.display='block';
    }else{
        //alert(cadenaEnvio);
        document.formularioContacto.submit();
    }
    
}


/****************************************************************
/ Nombre: borrarFormulario
/ Implentacion
/ Revision: 301106
/ Descripcion: borra los campos del formulario de contacto
'***************************************************************/

function borrarFormulario(){
    document.getElementById("formularioContacto").reset();
}

//*******************************************************************************
//******** PARA LAS SOLICITUDES DE INFORMACIÓN ******************************************
/****************************************************************
/ Implentacion FPerez
/ Revision: 280807
/ Descripcion: abre el formulario para solicitar informacion
'***************************************************************/

function formulario_solicitud(ref,depar){
    window.open("solicitud-informacion.asp?ref="+ref+"&depar="+depar,"Info","width=500 height=380 ");

}

/****************************************************************
/ Nombre: validarSolicitud
/ Implentacion FPerez
/ Revision: 280807
/ Descripcion: Valida los campos del formulario de solicitud de informacion
'***************************************************************/
function validarSolicitud(idioma){
//Funcion para la validar los datos enviados desde el formulario de contacto
    var texto,texto_en,texto_fr,texto_val;
    texto = "";
    texto_en = "";
    texto_fr = "";
    texto_val = "";
    texto_de = "";

    var cadenaEnvio;
    cadenaEnvio = "";
    
    //Aqui validamos que los campos obligatorios tengan valor y se añaden a la cadena de envio
    
    if ( document.getElementById("formularioSolicitud").nombre.value == "" ) {
        texto+=" * Debe indicar su nombre.<br>";
        texto_en+=" * You must enter your name.<br>";
        texto_fr+=" * Vous devez indiquer votre nom.<br>";
        texto_val+=" * Deu indicar el seu nom.<br>";
        texto_de+=" * Ihren Namen bitte.\n";
    }else{
        cadenaEnvio="nombre=" + document.getElementById("formularioSolicitud").nombre.value;
    }
    
    if ( document.getElementById("formularioSolicitud").email.value == "" ) {
        texto+=" * Debe indicar su e-mail.<br>";
        texto_en+=" * You must enter your e-mail.<br>";
        texto_fr+=" * Vous devez indiquer votre email.<br>";
        texto_val+=" * Deu indicar el seu e-mail.<br>";
        texto_de+=" * Ihre E-Mail Adresse bitte.\n";
    }
    
    if(document.getElementById("formularioSolicitud").email.value!=""){
        if(!validarEmail(document.getElementById("formularioSolicitud").email.value)){
                texto+=" * Formato de E-mail incorrecto.<br>";
                texto_en+=" * The E-mail format is wrong.<br>";
                texto_fr+=" * Format d'email incorrect.<br>";
                texto_val+=" * Format de E-mail incorrecte.<br>";
                texto_de+=" * E-Mail Format ist nicht richtig.\n";
        }else{
            cadenaEnvio+="&email=" + document.getElementById("formularioSolicitud").email.value;
        }
    }
    if ( document.getElementById("formularioSolicitud").comentarios.value == "" ){
        texto+=" * Debe incluir el motivo de su consulta.<br>";
        texto_en+=" * You must enter your comments.<br>";
        texto_fr+=" * Vous devez indiquer l'objet de votre demande.<br>";
        texto_val+=" * Deu incloure el motiu de la seua consulta.<br>";
    }else{
        cadenaEnvio+="&comentarios=" + document.getElementById("formularioSolicitud").comentarios.value;
    }   
    
    
    if ( document.getElementById("formularioSolicitud").telefono.value != "" ){
        cadenaEnvio+="&telefono=" + document.getElementById("formularioSolicitud").telefono.value;
    }
    
    if ( document.getElementById("formularioSolicitud").departamento.value != "" ){
        cadenaEnvio+="&departamento=" + document.getElementById("formularioSolicitud").departamento.value;
    }
    
    if ( document.getElementById("formularioSolicitud").referencia.value != "" ){
        cadenaEnvio+="&referencia=" + document.getElementById("formularioSolicitud").referencia.value;
    }
    //Si falta algun campo obligatorio o el email no tiene un formato correcto
    //mostramos un mensaje de avios
    
    if ( texto != "" ){
            switch (idioma) { 
                case 'en': 
                    document.getElementById("mensajeError").innerHTML=texto_en;
                   break 
                case 'fr': 
                    document.getElementById("mensajeError").innerHTML=texto_fr;
                   break 
                case 'val': 
                    document.getElementById("mensajeError").innerHTML=texto_val;
                   break 
                case 'de': 
                    document.getElementById("mensajeError").innerHTML=texto_de;
                   break 
                default: 
                    document.getElementById("mensajeError").innerHTML=texto;
            } 
        document.getElementById("capaError").style.display='block';
        
    }else{
        //alert(cadenaEnvio);
//      document.getElementById("mensaje-respuesta").innerHTML="";
        document.getElementById("mensajeError").innerHTML="";
        document.getElementById("capaError").style.display='none';
        http.open("GET", "actualizer/formcorreosMultiple/envioSinBD-solicitud-info.asp?" + cadenaEnvio, true);
        http.onreadystatechange = handleHttpResponseSolicitud;
        http.send(null);
    }
    
}

function handleHttpResponseSolicitud() {
    if (http.readyState == 4) {     
        //Aqui va el nombre de la capa donde queramos cargar el contenido
//          alert(http.responseText);
        document.getElementById("mensaje-respuesta").innerHTML = "";    
        document.getElementById("mensaje-respuesta2").innerHTML = http.responseText;    
        document.getElementById("respuesta").style.display = "block";   
        document.getElementById("formularioSolicitud").reset();
    }    
}


/****************************************************************
/ Nombre: ajustaImagen
/ Implentacion FPerez
/ Revision: 120907
/ Descripcion: Ajusta el ancho maximo de una imagen al 'ancho'
'***********************************************F****************/

function ajustaImagen(ancho,id,img){
    
//  alert(img);
    
    var anchoImagen,altoImagen,anchoPantalla,altoPantalla;
    img1 = new Image(); 
    img1.src = img;
    anchoImagen = img1.width;
    altoImagen = img1.height;
//  alert(anchoImagen + ' | ' + ancho);
    if (anchoImagen > ancho ){
            document.getElementById('image'+id).width = ancho;
            document.getElementById('image'+id).height = altoImagen * ancho / anchoImagen;

    }
}
/***************************************************************/

/****************************************************************
/ Nombre: imprimirCV
/ Implentacion 
/ Revision: 120907
/ Descripcion: imprimir el cv
'***************************************************************/
function imprimirCV(id){
    var base=document.getElementById("base").innerHTML;
    var estilo=document.getElementById("estilosPrincipal").href
    document.getElementById("estilosPrincipal").href="css/imprimir.css";
    var v=document.getElementById("capaImprimir").innerHTML;
    document.getElementById("base").innerHTML=v;
    document.getElementById("capaOcultar").style.display='none';
    window.print();
    document.getElementById("estilosPrincipal").href=estilo;
    document.getElementById("base").innerHTML=base;
}

/****************************************************************
/ Nombre: FUNCIONES PARA VALIDAR EL CIF
/ Implentacion FPEREZ
/ Revision: 281207
/ Descripcion:valida el CIF
'***************************************************************/
function validarCIF(texto){ 
         
        var pares = 0; 
        var impares = 0; 
        var suma; 
        var ultima; 
        var unumero; 
        var uletra = new Array("J", "A", "B", "C", "D", "E", "F", "G", "H", "I"); 
        var xxx; 
         
        texto = texto.toUpperCase(); 
         
        var regular = new RegExp(/^[ABCDEFGHKLMNPQS]\d\d\d\d\d\d\d[0-9,A-J]$/g); 
         if (!regular.exec(texto)) return false; 
              
         ultima = texto.substr(8,1); 

         for (var cont = 1 ; cont < 7 ; cont ++){ 
             xxx = (2 * parseInt(texto.substr(cont++,1))).toString() + "0"; 
             impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1)); 
             pares += parseInt(texto.substr(cont,1)); 
         } 
         xxx = (2 * parseInt(texto.substr(cont,1))).toString() + "0"; 
         impares += parseInt(xxx.substr(0,1)) + parseInt(xxx.substr(1,1)); 
          
         suma = (pares + impares).toString(); 
         unumero = parseInt(suma.substr(suma.length - 1, 1)); 
         unumero = (10 - unumero).toString(); 
         if(unumero == 10) unumero = 0; 
          
         if ((ultima == unumero) || (ultima == uletra[unumero])) 
             return true; 
         else 
             return false; 

    } 
    
function validarNIF(dni) {
  numero = dni.substr(0,dni.length-1);
  let = dni.substr(dni.length-1,1).toUpperCase();
  numero = numero % 23;
  letra='TRWAGMYFPDXBNJZSQVHLCKET';
  letra=letra.substring(numero,numero+1);
  if (letra!=let) {
//    alert('Dni erroneo');
    return false;
  }else{
//    alert('Dni correcto');
    return true;
  }
}



/****************************************************************************************
/ Nombre: ShowFilmFrame, ShowFilmFrameOver
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Amplia una imagen de la cartelera
//Al pasar el mouse por encima si esta visible la capa cambia de imagen
'***************************************************************************************/
function ShowFilmFrame(picture){
        
        var url = picture;
        var element = document.getElementById('bigPicture');
          
        if (picture != ''){
                index = url.indexOf('.jpg');
                url = url.substring(0, index + 4);
                url += "&Width=450&Height=250";
                document.getElementById("bigPictureImage").src = '';
                document.getElementById("bigPictureImage").src = url;
                element.style.display = 'block';
                document.getElementById('CloseBigPicture').style.display = 'block';
        }else{
            element.style.display = 'none';
            document.getElementById('CloseBigPicture').style.display = 'none';
        }
}


function ShowFilmFrameOver(picture){

    var element = document.getElementById('bigPicture');
    
    if(element.style.display != 'none'){
        ShowFilmFrame(picture);
    }

}



/****************************************************************************************
/ Nombre: SendToFriend
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Envia un contenido a un amigo
'***************************************************************************************/
function SendToFriend(){
    
        var element = document.getElementById("friendEmail");

        var elementMessage = document.getElementById("message");
        elementMessage.innerHTML = '';
        if(element.value !=''){
            if(validarEmail(element.value)){
                 url = "AjaxResponse/SendToFriend.ashx?Email=" + element.value;
                 element.value = '';             
                 http.open("GET", url , true);
                 http.onreadystatechange = handleHttpResponseSendToFriend;
                 http.send(null);
    
            }else{
                elementMessage.innerHTML = "* Formato de e-mail incorrecto";
                elementMessage.style.color = "#666666";
            }
        }else{
                elementMessage.innerHTML = "* Introduzca un email";
                elementMessage.style.color = "#666666"; 
        }
        

}


function handleHttpResponseSendToFriend() {
    if (http.readyState == 4) {
        var elementMessage = document.getElementById("message");
        elementMessage.innerHTML = http.responseText;
        elementMessage.style.color = "#666666";
    }    
}


/****************************************************************************************
/ Nombre: ShowConfirm(), RentingFilm(), handleHttpResponseRentingFilm
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Proceso de alquiler de una pelicula
'***************************************************************************************/

function ShowConfirm(){
    
    var element = document.getElementById("ConfirmMessage");
    
    
    if(element.style.display == 'block'){
        element.style.display = 'none'; 
    }else{
        element.style.display = 'block';
    }
    
}

function RentingFilm(id, user){
        var element = document.getElementById("ConfirmMessage");
        var elementMessage = document.getElementById("message");
        
        if (user != null) {
    
            
        if (localizacion.match("SPAIN")=="SPAIN")
        {
            element.style.display = 'none'; 
            elementMessage.innerHTML = '';
    
            url = "AjaxResponse/rentFilm.asp?Id=" + id;
            
            http.open("GET", url , true);
            http.onreadystatechange = handleHttpResponseRentingFilm;
            http.send(null);
        }
        else
        {
          document.getElementById("plataforma").style.display='block';
        }
            
                          
        }else{
            elementMessage.innerHTML = 'No esta autentificado como usuario';
            elementMessage.style.color = 'Red';
        }
}


function handleHttpResponseRentingFilm() {
    if (http.readyState == 4) {
        var elementMessage = document.getElementById("message");
        elementMessage.innerHTML = http.responseText;
        elementMessage.style.color = "#666666";
        if (http.responseText=="<br/>Portal sólo para España.")
        {url = "index.asp"; }
        else
        {url = "index.asp?pagina=login";}
        setTimeout("ChangeLocation('" + url + "')", 500);
    }    
}


/****************************************************************************************
/ Nombre: SendComment(), handleHttpResponseSendComment()
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Comentarios de la pelicula
'***************************************************************************************/

function SendComment(producto){
        var elementMessage = document.getElementById("elementMessage");
        var textBoxTitle = document.getElementById("titulo");
        var textBoxComment = document.getElementById("comentario");
    
        if (textBoxTitle.value != '' && textBoxComment.value != '') {
            url = "AjaxResponse/comentariosPelicula.asp?Title=" + textBoxTitle.value+ "&Comment=" + textBoxComment.value + "&producto=" + producto;
            http.open("GET", url , true);
            http.onreadystatechange = handleHttpResponseSendComment;
            http.send(null);
            textBoxTitle.value = '';
            textBoxComment.value = '';
        }else{
            elementMessage.innerHTML = '* El t&iacute;tulo y el comentario deben cumplimentarse';
            elementMessage.style.color = 'Red';
        }
}


function handleHttpResponseSendComment() {
    if (http.readyState == 4) {
        if(http.responseText != 'Error'){
            var elementMessage = document.getElementById("comentarios");
            elementMessage.innerHTML = http.responseText;
        }else{
            var elementMessage = document.getElementById("elementMessage");
            elementMessage.innerHTML = "No se ha podido insertar el comentario";
        }
    }    
}


/****************************************************************************************
/ Nombre: MarkStar, unMarkStar, VoteFilm, handleHttpResponseVoteFilm
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Manejo de la votacion de la pelicula
'***************************************************************************************/

function MarkStar(starNumber){
        for (i=1; i<=starNumber; i++){
            star =  document.getElementById("star" + i);
            star.src = "images/voto.png";
        }
}

function unMarkStar(starNumber){    
        for (i=1; i<=starNumber; i++){
            star =  document.getElementById("star" + i);
            star.src = "images/voto-void.png";
        }
}

function Vote(vote, id){
    url = "AjaxResponse/Shop/vote.asp?Id=" + id+ "&Vote=" + vote;
    http.open("GET", url , true);
    http.onreadystatechange = handleHttpResponseVote;
    http.send(null);
}




function validar_compra(id){
  if (localizacion.match("SPAIN")=="SPAIN")
    {
      window.location.href = 'index.asp?pagina=login&subpagina=compra&id='+id;
    }
 else
    {
     document.getElementById("plataforma").style.display='block';
    }   
}



function handleHttpResponseVote() {
    if (http.readyState == 4) {
            var elementMessage = document.getElementById("stars");
            if(http.responseText != 'Error'){
                    var valoracion = document.getElementById("valoracion");
                    
                    valor = http.responseText
                    if (valor.length > 3){
                        valor = valor.substr(0, 3);
                    }
                    valoracion.innerHTML = valor;
                
                elementMessage.innerHTML = "Gracias por votar";
                //elementMessage.innerHTML = "Gracias por votar";
            }else{
                elementMessage.innerHTML = "No se ha podido insertar su voto";
            }
    }    
}



/****************************************************************************************
/ Nombre: FilmView
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Visualizacion y descarga de la pelicula
'***************************************************************************************/
function FilmView(id){
    
    if (localizacion.match("SPAIN")=="SPAIN")
        {
            window.open("FilmView.asp?Id=" + id);
        }
        else
        {
          document.getElementById("plataforma").style.display='block';
        }
    
}

function FilmDownload(id){
    if (localizacion.match("SPAIN")=="SPAIN")
        {
    window.open("FilmDownload.asp?Id=" + id);
    }
        else
        {
          document.getElementById("plataforma").style.display='block';
        }
}

/****************************************************************************************
/ Nombre: ChangeLocation
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: CAmbia de página por la pasada
'***************************************************************************************/
function ChangeLocation(url){
    document.location = url;
}



/****************************************************************************************
/ Nombre: Paypal, Bancaja
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Pagos online
'***************************************************************************************/
/*PAYPAL*/
function Paypal(){
    document._xclick.submit();
}

/*BANCAJA*/
function Bancaja(){
    document.bancaja.submit();
}


/****************************************************************************************
/ Nombre: CopyCode
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Copia el codigo de visualizacion
'***************************************************************************************/
function CopyCode(id){
    
    var element = document.getElementById(id);
    //window.clipboardData.setData("Text", element.value); 
    
    
    if (window.clipboardData) 
    { 

    // IE
     window.clipboardData.setData("Text", element.value); 
  
   } 
   else  
   {
    
   }    
}



/****************************************************************************************
/ Nombre: Mp3RemoteControl
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Control de WM desde Flash
'***************************************************************************************/
playerOperation = "stop";

//Control del Flash
function Mp3RemoteControl(instruction, id){
    
    playerOperation = instruction;
    var flash = document.getElementById("mp3");

    if(id!=""){
        flash.SetVariable("_root.music", id);
    }
    
    switch (playerOperation) {
        
        case "stop":
            flash.SetVariable("_root.remote", "stop");
            break;
        case "play":
            flash.SetVariable("_root.remote", "play");
            break;
    }

}


//Control del Windows media
function Mp3RemoteControlAudio(instruction, id){
    
    playerOperation = instruction;
    
    getAudioPlayer('wmLayer', id);
    
    var wmplayer = document.getElementById("wm");
    
    switch (playerOperation) {
        
        case "stop":
            try{
                wmplayer.controls.stop();
            }catch(e){}
            break;
        case "play":
            try{
                wmplayer.controls.play()
            }catch(e){}
            break;
    }
}

//PINTA EL REPRODUCTOR WM
function getAudioPlayer(div, urlStreaming){
    player ="";     
        player +='<embed type="application/x-mplayer2" id="wm" name="wm" src="' + urlStreaming + '" autostart="true" volume="10" showStatusBar="true" showControls="false" kioskmode="false" height="20" width="105" scale="ASPECT"></embed>'; 
     document.getElementById(div).innerHTML= player;
     
}



/****************************************************************************************
/ Nombre: DinamicFlashText
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Permite que un flash adquiera el texto de una capa
'***************************************************************************************/
function DinamicFlashText(div){
        
    var element = document.getElementById(div);
    var texto = element.innerHTML;
    texto = texto.replace("&amp;", "##ampersand##");
    texto = texto.replace("&", "##ampersand##");
    var pelicula = new FlashObject("swf/dinamic-title.swf?texto=" + texto, div + "Text", "500", "40", "8", "");
    pelicula.addParam("wmode", "transparent");
    pelicula.addParam("quality", "high");
    pelicula.write(div);

}



/****************************************************************************************
/ Nombre: checkwhere
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Cordenadas del mouse
'***************************************************************************************/
var xCoord = 0;
var yCoord = 0;

function checkwhere(e) {
        if (document.layers){
        xCoord = e.x;
        yCoord = e.y;
}
        else if (document.all){
        xCoord = event.clientX;
        yCoord = event.clientY;
}
        else if (document.getElementById){
        xCoord = e.clientX;
        yCoord = e.clientY;
}
        //self.status = "X= "+ xCoord + "  Y= " + yCoord; 
        }


document.onmousemove = checkwhere;
if(document.captureEvents) {document.captureEvents(Event.MOUSEMOVE);}



/****************************************************************************************
/ Nombre: changeLayerTime
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Cambia la capa por otra pasado un tiempo. Las capas se engloban en un vector
'***************************************************************************************/

function changeLayerTime(elementName, number, current, time){
    
    if (current==0)  current=1;
    for(i=1; i <= number; i++){
        document.getElementById(elementName + i).style.display = 'none';        
    }
    
    document.getElementById(elementName + current).style.display = 'block';
    current++
    
    if (current>number)  current=0;
    
    setTimeout("changeLayerTime('" + elementName + "'," + number + "," + current + "," + time + ")", time);
}


//***************************************************************************
//***************************************************************************

//* GOOGLE MAPS *//

    var uniqueId = "autolamina";
    var width = 516;
    var height = 397;
    var iconUrl = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    var address = "Madrid";
    //var googlePoint = "37.4419, -122.1419";
    googlePoint = "37.4419, -122.1419";
    
    


 function loadMap() {
     
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map_" + uniqueId), { size:new GSize(width, height)});
    
    map.setCenter(new GLatLng(37.4419, -122.1419), 13);
    
    map.addControl(new GLargeMapControl());

    //ICONO
    var gIcon = new GIcon(G_DEFAULT_ICON);
    gIcon.image = iconUrl;
    gIcon.iconSize = new GSize(30, 30);
    markerOptions = { icon:gIcon };
    var marker = new GMarker(new GLatLng(37.4419, -122.1419), markerOptions);
    map.addOverlay(marker);
  }
}

function showAddress() {
         var map = new GMap2(document.getElementById("map_" + uniqueId), { size:new GSize(width, height)} );
         //var address = document.getElementById("AddressText").value;
           if (geocoder) {
                    geocoder.getLatLng(address, 
                                        function(point) {
                                                if (!point) {
                                                    var element = document.getElementById("map_" + uniqueId);
                                                    element.innerHTML = "<div style=\"background-color:Red; color:White; width:" + width + ";height:" + height + "\">La dirección '" + address + "' no se ha podido situar correctamente. Disculpe</div>";
                                                } else {
                                                      map.clearOverlays();
                                                      map.setCenter(point, 13);
                                                      //marker = new GMarker(point, {draggable:true});
                                                      marker = new GMarker(point, {draggable:false});
                                                      map.addControl(new GLargeMapControl());
                                                      map.addOverlay(marker);
                                                }
                                        }
                   );
            }
           
       }

//FUNCIONES NUEVAS DE GOOGLE MAPS
function InsertGoogleMaps2(id) {
    $("#map_" + id).css("display", "block");
    _geocoder = new google.maps.Geocoder();

    //if ($("#" + id).css("display") == "none") {
    //$("#" + id).html("");
    // var map = new google.maps.Map2(document.getElementById(id));
    //map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
    //$("#" + id).show();
    /*} else {
    $("#" + id).hide();
    }*/

    latlng = new google.maps.LatLng(39.477676,-0.455737);

    var googleMapOptions = {
        zoom: 14,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_" + id), googleMapOptions);
}

function GoogleCodeAddress(address, id) {
    if (_geocoder) {
        _geocoder.geocode({ 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
                $("#map_" + id).css("display", "block");
            }
            else {
                //alert("Geocodee was not successful for the following reason: " + status);
                $("#map_" + id).css("display", "none");
            }
        });
    }
}
//FIN DE LAS FUNCIONES NUEVAS DE GOOGLE MAPS




/****************************************************************************************
/ Nombre: validarTexto
/ Implentacion: FPEREZ
/ Revision: 
/ Descripcion: Valida el texto de los campos de un formulario, para evitar caracteres propios de scriptInjection
'***************************************************************************************/

function validarTexto(eltexto){

    var cval="abcçdefghijklmnñopqrstuvwxyzABCÇDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789 ÁÀÄÂÉÈËÊÍÌÏÎÓÒÖÔÚÙÜÛáàäâéèëêíìïîóòöôúùüû@-.,¿?";
    var aux,n=0;    
    aux=eltexto;
    
    if(aux!=""){
        for(i=0;i<aux.length;i++){  
            for(j=0;j<cval.length;j++){             
                if(cval.charAt(j)==aux.charAt(i)){
                    n++;
                }               
            }        
        }
    }

    if(n==aux.length){
        return true;
    }else{
        return false;
    }
}

/********************************************************/


/*-
function bodyClick() {
    alert("fsdfsd");
}

document.body.onclick = bodyClick;
//if(document.captureEvents) {document.captureEvents(Event.LOAD);}
*/

//Contiene la capa donde se muestra el carrito
_shoppingCartLayer ="shoppingcartlayer";
//Booleano si se mostrara el carro
_showShoppingCartAfter = false;

//Muestra el carrito de la compra
function ShoppingCart(shoppingCartLayer){
    if(shoppingCartLayer !='') _shoppingCartLayer=shoppingCartLayer;
    var element = document.getElementById(_shoppingCartLayer);
    url = "./AjaxResponse/Shop/showShoppingCart.asp";
    http.open("GET", url , true);
    http.onreadystatechange = handleHttpResponseShoppingCart;
    http.send(null);
}

function handleHttpResponseShoppingCart() {
    if (http.readyState == 4) {
        var element = document.getElementById(_shoppingCartLayer);
        element.style.display = 'block';
        element.innerHTML = http.responseText;
        elementblack = document.getElementById("black");
        elementblack.style.display = 'block';
        
        //elementblack = generateCoverDiv("black", "#000000", "87");
        
        createEvent(elementblack, "click", function(){
            HideShoppingCart(_shoppingCartLayer)
        });
    }    
}

function ShoppingConfirm(shoppingCartLayer,transaccionEstado) {
        if(shoppingCartLayer !='') _shoppingCartLayer=shoppingCartLayer;
        var element = document.getElementById(_shoppingCartLayer);
        var msj = '<br/><br/><a href="javascript:HideShoppingCart(\''+shoppingCartLayer+'\');">Cerrar</a>';
        switch (transaccionEstado){
            case 0: 
                msj= "<br/><br/><br/><br/>Ha escogido la modalidad de pago tarjeta de crédito. Su pedido ha sido realizado con éxito.<br/>Agradecemos su confianza." + msj;
                break;
            case 1: 
                msj= "<br/><br/><br/><br/>Ha escogido la modalidad de pago tarjeta de crédito. Su pedido ha sido cancelado." + msj;
                break;
            case 2: 
                msj= "<br/><br/><br/><br/>Ha escogido la modalidad de pago tarjeta de crédito. Se ha producido un error al realizar el pedido.<br/>Inténtelo de nuevo más tarde." + msj;
                break;
            case 4: 
                msj= "<br/><br/><br/><br/>Ha escogido la modalidad de pago transferencia bancaria. Acaba de recibir en su correo un e-mail indicándole los pasos a seguir.<br/>Agradecemos su confianza." + msj;
                break;
        }
        element.innerHTML = msj;
        element.style.display = 'block';
}

//Oculta el carrito de la compra
function HideShoppingCart(shoppingCartLayer){
    if(shoppingCartLayer !='') _shoppingCartLayer=shoppingCartLayer;
    var element = document.getElementById(_shoppingCartLayer);
    element.style.display = 'none'; 
    
    elementblack = document.getElementById("black");
    elementblack.style.display = 'none';
}




//Añade un producto al carrito
function ShoppingCart_AddProduct(id){
	var size 				= $("#size").val();
	var color 				= $("#color").val();
	var amount 				= $("#amount").val();
	var minAmount 			= $("#minamount").val();
	var minAmountBill 		= $("#minamountbill").val().replace(",", ".");
	var productprice 		= $("#productprice").val().replace(",", ".");
	var minAmountText 		= $("#minamounttext").val();
	var minAmountBillText 	= $("#minamountbilltext").val();
	
	if (parseInt(amount) < parseInt(minAmount)) {
		$(".msg-cart").html(minAmountText);
		return false;
	}
	else {
		if ((parseFloat(productprice) * parseFloat(amount)) < parseFloat(minAmountBill)) {
			$(".msg-cart").html(minAmountBillText);
			return false;
		}
	}
	
	var url = "./AjaxResponse/Shop/addProductToShoppingCart.asp";
	var params = "id=" + id + "&size=" + size + "&color=" + color + "&amount=" + amount;
	
	$(".msg-cart").html(_loading);
	$.ajax({
		type: "POST",
		url: url,
		data: params,
		success: function(data){
			var result = data.split("|");
			if (result[0] == "1") {
				$(".mycarttext .numcartelements").html(result[1]);
				$(".msg-cart").html(result[2]);
			}
			else {
				$(".msg-cart").html("");
			}
		},
		error: function(data){	
		}
	});
}


/*function ShoppingCart_AddProductKeypress(){
    
    ShoppingCart_AddProduct(id, false, amount, changeamount, showShoppingCartAfter, shoppingCartLayer)

}*/

function ShoppingCart_AddProductKeypress(e, id, amount, changeamount, showShoppingCartAfter, shoppingCartLayer){ 
    var ascii; 
     
    if (e.keyCode) 
        ascii = e.keyCode; 
    else if (e.which) 
        ascii = e.which; 
    else 
        return false; 
         
    if (ascii == 13) {
        ShoppingCart_AddProduct(id, false, amount, changeamount, showShoppingCartAfter, shoppingCartLayer); 
        return true; 
    }
} 


function handleHttpResponseShoppingCart_AddProduct() {
    if (http.readyState == 4) {
        var element = document.getElementById(_shoppingCartLayer);
        element.style.display = 'block';

        //Si se muestra el carrito
        if(_showShoppingCartAfter)
        {
            //element.innerHTML = http.responseText;
            ShoppingCart(_shoppingCartLayer);
            _showShoppingCartAfter = false;
        
        }else{
            //Sino se ha mensaje    
            element.innerHTML = http.responseText;
        }
        
    }    
}


//Vacia el carrito de productos
function CancelShoppingCart(showShoppingCartAfter, shoppingCartLayer){
    if(shoppingCartLayer !='') _shoppingCartLayer=shoppingCartLayer;
    _showShoppingCartAfter = showShoppingCartAfter;
    
    url = "./AjaxResponse/Shop/cancelShoppingCart.asp";
    http.open("GET", url , true);
    http.onreadystatechange = handleHttpResponseShoppingCart;
    http.send(null);
}


function handleHttpResponseCancelShoppingCart() {
    if (http.readyState == 4) {
        if(_showShoppingCartAfter)
        {
            var element = document.getElementById(_shoppingCartLayer);
            element.style.display = 'block';
            ShoppingCart(_shoppingCartLayer);
            _showShoppingCartAfter = false;
        }else{
            
            //setTimeout("document.getElementById(_shoppingCartLayer).style.display ='none'", 2000);
        }
    }    
}


function createEvent(element, evento, funcion) {

      if (element.addEventListener) {
            element.addEventListener(evento, funcion, false);
      } else {
            element.attachEvent("on" + evento, funcion);
      }
}


function validarFecha(value) {  
    patron = /^\d{1,2}\/\d{2}\/\d{4}$/ 
     if (!patron.test(value)) {   
        return false;  
     }  
     if (!validateMonth(value)){
         return false;
     }
     if (!validateDay(value)){
         return false;
     }
    /* if(!validateYear(value)){
         return false;
     }*/
     return true;
}



function validateMonth(value){  
    var result = false;  
    var mes = parseInt(value.substr(3, 2), 10);  
    result = result || ((mes >= 1) && (mes <= 12));  
    return result;  
   }  
   
   
function monthEnd(value){  
    var mes = parseInt(value.substr(3, 2), 10);  
    var anno = parseInt(value.substr(6, 4), 10);  
    var result = 0;  
    switch (mes){  
     case 1: result = 31; break;  
     case 2: result = 28; break;  
     case 3: result = 31; break;  
     case 4: result = 30; break;  
     case 5: result = 31; break;  
     case 6: result = 30; break;  
     case 7: result = 31; break;  
     case 8: result = 31; break;  
     case 9: result = 30; break;  
     case 10: result = 31; break;  
     case 11: result = 30; break;  
     case 12: result = 31; break;  
    }  
    return result + (((mes == 2) && (anno % 4) == 0)? 1: 0);  
}  

function validateDay(value){  
    var result = false;  
    var dia = parseInt(value.substr(0, 2), 10);  
    result = result || ((dia >= 1) && (dia <= monthEnd(value)));  
    return result;  
   }
   
   function validateYear(value){  
    var result = true;  
    var anno = parseInt(value.substr(6, 4), 10);
    /*var anno = parseInt(value.substr(0));*/  
    result = result && ((anno.length == 2) || (anno.length == 4));  
    if (result){  
     for (var i = 0; i < anno.length; i++){  
      result = result && isDigit(anno.charAt(i));  
     }
     
     if(result){
         //alert(getDate())
//      if anno <= year(getDate())
     }
     return false;
    }  
    
   }  
   
   function isDigit(char){  
    var code = char.charCodeAt(0);  
    return ((code > 47) && (code < 58));  
   }  


/* REGISTRO DE USUARIOS

    Captura todos los campos con id register_(IDDELCAMPO)
    Los mensajes son span derras de cada campo <SPAN id="register_(IDDELCAMPO)_msg"></SPAN>
    Los campos con name="norequired" no pasan validación
    con class="email" hace validacion de email
    con class="date" hace validacion de fecha

*/
function NewCustomer() {
    
    var message = document.getElementById("register_message");
    var news = document.getElementById("checkvalue");
    //Primero debe aceptar las condiciones
    if ($("#checkvalue").attr("checked")) {
        
        message.innerHTML= "";
        message.style.color = "#000";
		
		document.getElementById("register_checkvalue_msg").style.display = "none";
		
        var element = document.getElementById("register")
        var objects = document.getElementsByTagName("INPUT");
        var params = "";
        error = false;
        
        //INPUT
        for (var i=0; i < objects.length; i++) {
            
            obj = objects[i];
            if(obj.type=="checkbox") continue;
    
            var fieldMsg = document.getElementById("register_" + obj.id + "_msg");
            if(fieldMsg != null){
                fieldMsg.style.display = "none";
                //Validacion para que todos los campos esten llenos
    
                if(obj.value != "" || obj.name == "norequired"){
                    //Valida el email del campo email
                    if(obj.className=="email" && !validarEmail(obj.value)){
                        error = true;
                        fieldMsg.innerHTML = "* Formato incorrecto";
                        fieldMsg.style.color = "#FF0000";
                        fieldMsg.style.display = "block";
                    }else{
                        if( (obj.className=="date" && !validarFecha(obj.value) && obj.name != "norequired") || (obj.className=="date" && obj.value!="" && obj.name == "norequired" && !validarFecha(obj.value))){
                            error = true;
                            fieldMsg.innerHTML = "* Formato incorrecto fecha";
                            fieldMsg.style.color = "#FF0000";
                            fieldMsg.style.display = "block";
                        }else{
                                //equal-nombre de campo. Hace que un campo tenga que ser igual que otro: Ej. Confirmar contraseña
                                if(obj.name.indexOf("equal") >-1 && (obj.value != document.getElementById(obj.name.split("-")[1]).value )){
                                    error = true;
                                    fieldMsg.innerHTML = "* Contraseña incorrecta";
                                    fieldMsg.style.color = "#FF0000";
                                    fieldMsg.style.display = "block";
                                }else{
                                    if(i!=0) params+="&"; //Segundo parametro añade &
                                    params += obj.id + "=" + obj.value;
                                    fieldMsg.innerHTML = "";
                                }
                        }
                        //Crea para ASP el nombre de los parametros
                        //params2 += obj.id  + "=" + 'Request("' + obj.id + '")';
                    }
        
                }else{
					if(obj.name != "apellido2" && obj.name != "company"  && obj.name != "mobile"  && obj.name != "faxNumber"){
						error = true;
						fieldMsg.innerHTML = "* Obligatorio";
						fieldMsg.style.color = "#FF0000";
						fieldMsg.style.display = "block";
					}
                }
            }else{
                if(i!=0) params+="&"; //Segundo parametro añade &
                params += obj.id + "=" + obj.value;
            }
        }
		params += "&country=" + $("#country").val();
        
		if (news.checked) {
			params += "&news=1";
		}
		
        if(!error){
            url = "./AjaxResponse/Shop/addNewCustomer.asp?" + params;
            http.open("GET", url , true);
            http.onreadystatechange = handleHttpResponseNewCustomer;
            http.send(null);
        }
    }else{
        message.innerHTML = "* Debe aceptar las condiciones";
        message.style.color = "#FF0000";
    }
}

function handleHttpResponseNewCustomer() {
    if (http.readyState == 4) {
        var message = document.getElementById("register_message");
        message.innerHTML = http.responseText;
    }    
}



function ConfirmOrder() {
	$("SPAN.error").remove();

	var canContinue = true;
	var promotionalcode = "";
	if ($("#codigopromocional") != null && $("#codigopromocional").val() != undefined && $("#codigopromocional").val() != "undefined" && $("#codigopromocional").val() != "") {
		promotionalcode = $("#codigopromocional").val();
	}
	
	var url 	= "AjaxResponse/shop/ConfirmOrder.asp";
	var params 	= "promotionalcode=" + promotionalcode;
	
	var textrequired = $("#textrequired").val();
	if ($("#name").val() == "") {
		canContinue = false;
		$("#name").parent().after('<span class="error">' + textrequired + '</span>');
	}
	if ($("#address").val() == "") {
		canContinue = false;
		$("#address").parent().after('<span class="error">' + textrequired + '</span>');
	}
	if ($("#code").val() == "") {
		canContinue = false;
		$("#code").parent().after('<span class="error">' + textrequired + '</span>');
	}
	if ($("#province").val() == "") {
		canContinue = false;
		$("#province").parent().after('<span class="error">' + textrequired + '</span>');
	}
	if ($("#city").val() == "") {
		canContinue = false;
		$("#city").parent().after('<span class="error">' + textrequired + '</span>');
	}
	if ($("#phone").val() == "") {
		canContinue = false;
		$("#phone").parent().after('<span class="error">' + textrequired + '</span>');
	}
	
	params += "&name=" + encodeURIComponent($("#name").val());
	params += "&address=" + encodeURIComponent($("#address").val());
	params += "&cp=" + encodeURIComponent($("#code").val());
	params += "&city=" + encodeURIComponent($("#city").val());
	params += "&province=" + encodeURIComponent($("#province").val());
	params += "&provinceId=" + encodeURIComponent($("#provinceId").val());
	params += "&country=" + encodeURIComponent($("#country").val());
	params += "&phone=" + encodeURIComponent($("#phone").val());
	params += "&comments=" + encodeURIComponent($("#comentarios").val());
	
	
	if (canContinue) {
		$.ajax({
			type: "POST",
			url: url,
			data: params,
			success: function(data){
				$(".shoppingcartlayer3").html(data);
				$(".shoppingcartlayer2").hide();
				$(".shoppingcartlayer3").show();
			} 
		});
	}
}


/*function handleHttpResponseConfirmOrder() {
    if (http.readyState == 4) {
        var element = document.getElementById(_shoppingCartLayer);
        element.innerHTML = http.responseText;
    }    
}*/



function changeOrderAddress(object){
    
    var element = document.getElementById("orderAddressData");
    element.style.display = object.checked ? "block" : "none";
}



function PayOrder(shoppingCartLayer, transaccion, email)
{       
        if(shoppingCartLayer !='') _shoppingCartLayer=shoppingCartLayer;

        var element = document.getElementById(_shoppingCartLayer);
        var msj = document.getElementById("shoppingCartMsg");
        var orderHtml = document.getElementById("orderHtml");

        //alert(element)
        bodyContent = replace(orderHtml.innerHTML, "&", "-@AmP@-");
                
        var params =  "body=" + encodeURI(bodyContent);
//      params += "&emailTo=" + email;
        url = "./AjaxResponse/Shop/insertShoppingCartLines.asp";
        http.open("POST", url , true);
        
        http.onreadystatechange = function() {
        if (http.readyState==1) {
                          
                          msj.innerHTML="<br/><br/><br/><br/>Guardando datos de su pedido. Espere";
                          
        }else if (http.readyState==4){
                   if(http.status==200)
                   {
                       msj.innerHTML="";
                        response =  http.responseText;
                        if (response == 1) {
                            if (transaccion == 5){
                                document.tpv.submit();
                            } else {
                                document.transferencia.submit();
                            }
                        }
                   }
                   else if(http.status==404){
                            msj.innerHTML = "La direccion no existe";
                        }else{
                            msj.innerHTML = "Error: " + http.status;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(params);
         return;

}



/*envía un producto a un amigo, aparece la capa con el campo email*/
function SendProductToFriend(id){
    var element = document.getElementById("sendproducttofriendLayer" + id)
    element.style.display = element.style.display == "block"? "none" : "block";
}

/*boton enviar*/
function SendProductToFriendSend(id) {
        var obj = document.getElementById("textboxsendproducttofriend" + id);
        
        var bodyContent = document.getElementById("producto" + id).innerHTML;
        var msg = document.getElementById("textboxsendproducttofriend_msg" + id)
        msg.style.display ="none";
        msg.innerHTML = "";
                        
        if(obj.value.length > 0){
            if(validarEmail(obj.value)){
                bodyContent = replace(bodyContent, "&", "-@AmP@-");
                
                var params =  "body=" + encodeURI(bodyContent);
                    params += "&email=" + obj.value;
                    params += "&id=" + id;
                url = "./AjaxResponse/Shop/sendProductToFriend.asp";
                http.open("POST", url , true);
                http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                
                http.onreadystatechange = handleHttpResponseSendProductToFriendSend;
                http.send(params);
                
            }else{
                msg.innerHTML = " * Formato incorrecto";
                msg.style.display ="block";
            }
        }else{
            msg.innerHTML = " *Obligatorio";
            msg.style.display ="block";
        }
}


function handleHttpResponseSendProductToFriendSend() {
    if (http.readyState == 4) {
        response =  http.responseText;
        responses = response.split("|");
        var msg = document.getElementById("textboxsendproducttofriend_msg" + responses[1])
        document.getElementById("textboxsendproducttofriend" + responses[1]).style.display="none";
        msg.innerHTML = responses[0];
        msg.style.display ="block";
    }     
}


/*boton eniar*/
function ProductPrint(id) {
        //OCULTA
        //document.getElementById("pieContent").style.display = "none";
        var head = document.getElementById("logo");
        var foot = document.getElementById("pie");

        var headImage = head.style.backgroundImage;
        head.style.backgroundImage = "none";
        
        var headContent = head.innerHTML;
        var footerContent = foot.innerHTML;
        
        var printHeaderContent = '<img src="images/cabeceraimpresion.jpg" />';
        
        var printFooterContent = "";
        
        
        head.innerHTML = printHeaderContent;
        foot.innerHTML = printFooterContent;
        
        //IMPRIME
        window.print();
        
        head.style.backgroundImage = headImage;
        head.innerHTML = headContent;
        foot.innerHTML = footerContent;
        //MUESTRA
        //document.getElementById("pieContent").style.display = "block";
}

function filtrar(subpagina,galeria){
    
    marca=document.getElementById("filtro").marcaId.options[document.getElementById("filtro").marcaId.selectedIndex].value;
    ListId=document.getElementById("ListId").value;

    var url="index.asp?pagina=productos&subpagina=" + subpagina + "&galeria=" + galeria + "&marca=" + marca + "&ListId="+ListId;
    window.location.href = url;
}


function replace(texto,s1,s2){
    return texto.split(s1).join(s2);
}

function showProvinces() {
    var id = $("#country").val();
    url = "./includes/ajax_showProvinces.asp"
    
	$.ajax({
		type: "POST",
		url: url,
		data: "id=" + id,
		success: function(data){
			$("#provinceId").remove();
			$("LABEL.province").next("DIV.input").remove();
			$("LABEL.province").after(data);
		} 
	});
}

/*
function handleHttpResponseShowProvinces() {
    var element = document.getElementById("provinceField");
    if (http.readyState == 4) {
        element.innerHTML = http.responseText;
    }     
}
*/
function showProvincesContact() {
    var id=document.getElementById("pais").options[document.getElementById("pais").selectedIndex].value;
    url = "./includes/ajax_showProvincesContact.asp?id="+ id;
    http.open("GET", url , true);
    http.onreadystatechange = handleHttpResponseshowProvincesContact;
    http.send(null);
}


function handleHttpResponseshowProvincesContact() {
    var element = document.getElementById("provinciaContacto");
    if (http.readyState == 4) {
        element.innerHTML = http.responseText;
    }     
}

function showProvincesOrderData() {
    var id=document.getElementById("finalCountry").options[document.getElementById("finalCountry").selectedIndex].value;
    url = "./AjaxResponse/Shop/ajax_showProvincesOrderData.asp?id="+ id;
    http.open("GET", url , true);
    http.onreadystatechange = handleHttpResponseshowProvincesOrderData;
    http.send(null);
}


function handleHttpResponseshowProvincesOrderData() {
    var element = document.getElementById("finalProvinceField");
    if (http.readyState == 4) {
        element.innerHTML = http.responseText;
    }     
}

function generateCoverDiv(id, color, opacity)
{
    var navegador=1;
    if(navigator.userAgent.indexOf("MSIE")>=0) navegador=0;
    
    var element = document.createElement("div");
    element.id=id;
    element.style.width=document.body.offsetWidth+'px';
    element.style.height=document.body.offsetHeight+'px';
    element.style.backgroundColor=color;
    element.style.position='absolute';
    element.style.top=0;
    element.style.left=0;
    element.style.zIndex=3;
    element.style.display="block";
    if(navegador==0) element.style.filter='alpha(opacity='+opacity+')';
    else element.style.opacity=opacity/100;
    
    
    createEvent(element, "click", function(){
            element.style.display ="none";                                         
            HideShoppingCart(_shoppingCartLayer)
        });
    
    
    document.body.appendChild(element);
    return element;
} 

//Retorna el valor de un parametro pasado por querystring
function QueryStringParam(paramName){  
    paramName = paramName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
    var regexS = "[\\?&]" + paramName + "=([^&#]*)";  
    var regex = new RegExp( regexS );  
    var results = regex.exec( window.location.href );  
    if( results == null )    
        return "";  
    else    
        return results[1];
}



function SearchProducts(){
    url = "?pagina=" + QueryStringParam("pagina") + "&search=" + document.getElementById("search").value;
    window.location = url;
}

function valTexto(txt){

    var cval="abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ0123456789$&+-_*çÇ ";   
    var aux,n=0;
    aux=txt;    
    if(aux!=""){
        for(i=0;i<aux.length;i++){
            for(j=0;j<cval.length;j++){
                if(cval.charAt(j)==aux.charAt(i)){
                    n++;
                }
            }
        }
    }
    if(n==aux.length){
        return true;
    }else{
        return false;
    }

}

/****************************************************************
/ Nombre: FUNCIONES PARA VALIDAR EL MENSAJE DLE FORO
/ Implentacion FPEREZ
/ Revision: 200209
/ Descripcion:valida los campos del mensaje del foro
'***************************************************************/
function validarMsjForo(){
    var nom,texto,extension;
    texto="";
    extension = Right(document.form1.men_imagen.value,3);
    if (extension != ""){
        if ((extension != "jpg") && (extension != "bmp")){
            alert("La extensión de la imagen debe ser JPG o BMP.");
            return;
        }
    }

    nom=window.parent.parent.parent.nomusuW;
    document.form1.nomusuW.value=nom;
    if(document.form1.men_nusuario.value=="") texto+="- Usuario.\n";
    if(document.form1.men_resumen.value=="") texto+="- Resumen.\n";

    var textarea = FCKeditorAPI.GetInstance('men_texto') ;
    if(textarea.GetHTML=="") texto+="- Mensaje.\n";

    if(texto==""){
        document.form1.submit();
    }else{
        alert("Debe rellenar los siguientes campos:\n"+texto);
    }
    
}

/****************************************************************
/ Nombre: FUNCIONES PARA MOSTRAR UNA PARTE DE UN STRING
/ Implentacion FPEREZ
/ Revision: 060309
/ Descripcion:muestra los n primeros o ultimos caracteres de un string
'***************************************************************/
function Left(str, n){
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0,n);
}
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}



/*BANNERS */
function bannerClick(id, linkUrl, target){
    var url = "./AjaxResponse/bannerClick.asp";
    var params = "id=" + id + "&link=" + escape(linkUrl);
    http.open("POST", url , true);
    
    http.onreadystatechange = function() {
    if (http.readyState==1) {
                      
    }else if (http.readyState==4){
               if(http.status==200)
               {
                  if(http.responseText !="http://" && http.responseText !=""){
                      //0Externo - 1 Interno              
                      if(target == 0){
                            window.open(http.responseText,'Publicidad','');
                      }else{
                          document.location.href = http.responseText;
                      }
                  }
               }
               else if(http.status==404){
                    }else{
                    }
               }
     }
     
     http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
     http.send(params);
}




function AP3_theme_News_Select(id, seccion, layer){

    var url = "./AjaxResponse/AP3_theme_News_Select.asp";
    var params = "id=" + id + "&section=" + seccion;
    var element = document.getElementById(layer);
    
    http.open("POST", url , true);
    
    http.onreadystatechange = function() {
    if (http.readyState==1) {
            element.innerHTML = "Cagando...";
    }else if (http.readyState==4){
               if(http.status==200)
               {
                  element.innerHTML = http.responseText;
               }
               else if(http.status==404){
                        element.innerHTML = "Pagina no disponible";
                    }else{
                        element.innerHTML = "Se ha producido un error"; 
                    }
               }
     }
     
     http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
     http.send(params); 
}

function RoundNumber(number, decimals){
    number = number.toString(); 
    index = number.indexOf(".");
    if(index > 0){      
        number = number.substr(0, index) + "." +  number.substr(index + 1 , decimals);
    }
    return number           
}


function Clock(){
    var now = new Date() 
    minute = new String (now.getMinutes()) 
    if (minute.length == 1) 
    minute = "0" + minute;
    document.getElementById("clock").innerHTML = now.getHours() + ":" + minute + " h";
    setTimeout('Clock()', 1000);
}

function Votar()
{
    var objects = document.getElementsByTagName('INPUT');
    var obj, objSeleccionado = null;
    
    for (var i=0; i < objects.length; i++)
    {
        obj = objects[i];
        if(obj.id.indexOf('encuesta') > -1)
        {
            if (obj.checked)
            {
                objSeleccionado = obj;
            }
        }
    }
    
    if (objSeleccionado != null)
    {
        var idEncuesta = document.getElementById("idEncuesta").value;

        //Guardamos la respuesta, comprobando que no haya respondido en la sesion actual
        var url = "includes/ajax_savePollResponse.asp";
        var params = "id=" + idEncuesta + "&responseId=" + objSeleccionado.value;
        //alert(params);
        http.open("POST", url , true);
        
        http.onreadystatechange = function (){
            var element = document.getElementById("encuestas");
            if (http.readyState==1)
            { element.innerHTML = _loading; }
            else 
            {
                if (http.readyState==4)
                {
                    if(http.status==200)
                    {
                        if (http.responseText == "1")
                        {
                            element.innerHTML = document.getElementById("pollTitle").innerHTML + "<div style='padding:10px; font-size:12px; font-family:Tahoma; display:block;'><br /><br /><b>Respuesta enviada.</div>";
                            
                        }
                        else
                        {
                            
                            element.innerHTML = http.responseText;
                            
                        }
                    }
                    else 
                    {
                        if(http.status==404)
                        {
                            element.innerHTML = "La direccion no existe";
                        }
                        else
                        {
                            element.innerHTML = "Error: " +  http.status;
                        }
                    }
                }
            }
        }
        
        http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
        http.send(params);
        
        return;
    }
    else
    {
        alert("Seleccione una respuesta para votar.");
    }
}


/*EMPRESAS ASOCIADAS*/
function SearchCompanies(){
    var msg = document.getElementById("rapida_msg");
    var url = "AjaxResponse/Companies/SearchCompanies.asp";
    var letter = document.getElementById("letter").value;
    var searchText = document.getElementById("searchText").value;
    var sector = document.getElementById("sector").value;
    var params = "search=true";
    if (searchText == 'Buscar por nombre o marca'){ searchText='';}
        
    
    var objects = document.getElementsByTagName("INPUT");
    var obj, objSeleccionado = null;
    var categories = "";
    var subcategories = "";
    for (var i=0; i < objects.length; i++)
    {
        obj = objects[i];
        if(obj.type == "checkbox"){
            if (obj.checked)
            {
                if (obj.className == 'category')
                {
                    categories += obj.value + ',';
                }else{
                
                    if (obj.className == 'subcategory')
                    {
                        subcategories += obj.value + ',';
                    }
                    
                }
            }
        }
    }
    
    
    
    if (letter != '')   params += "&letter=" + letter;
    if (searchText != '' ) params += "&searchText=" + escape(searchText);
    //if (sector != '') params += "&sector=" + sector;
    
    if (subcategories != ''){
        params += "&subcategories=" + subcategories + 'del,';
    }else{
        if (categories != '')   params += "&categories=" + categories + 'del,';
    }

    //alert(params);
    http.open("POST", url , true);
    var element = document.getElementById("results");

    http.onreadystatechange = function (){
        if (http.readyState==1)
        { 
            element.innerHTML = _loading;   
        }
        else 
        {
            if (http.readyState==4)
            {
                if(http.status==200)
                {
                    element.innerHTML = http.responseText;
                }
                else 
                {
                    if(http.status==404)
                    {
                        element.innerHTML = "La direccion no existe";
                    }
                    else
                    {
                        element.innerHTML = "Error: " +  http.status;
                    }
                }
            }
        }
    }
    
    http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
    http.send(params);
    
    return;
    
    
}



function changeLetter(letter, element){
    

    var hidden = document.getElementById("letter");
    
    if (hidden.value != letter){
        hidden.value = letter;
    
        var objects = document.getElementsByTagName("A");
    
        for (var i=0; i < objects.length; i++) {
            obj = objects[i];
            
            if(obj.className == 'letter'){
                obj.style.backgroundColor = "White";
                obj.style.color = '#0B6BAB';
            }
        }
        element.style.backgroundColor = '#0B6BAB';
        element.style.color = 'White';
        
    }else{
        
        hidden.value = '';
        element.style.backgroundColor = 'White';
        element.style.color = '#0B6BAB';
    }
    
    SearchCompanies();
    
}


function CompanieClearField(field, message){
        
        if(field.value==message) {
            field.value = '';
        }else{
            if(field.value=="") field.value = message;
        }
}



function SearchCompanies_Keypress(e){
    var ascii; 
    if (e.keyCode) 
        ascii = e.keyCode; 
    else if (e.which) 
        ascii = e.which; 
    else 
        return false; 
         
    if (ascii == 13) {
        SearchCompanies();
        return true; 
    }
    
}



/*EMPRESAS ASOCIADAS*/
function Sector(obj){
    
    var element = document.getElementById("subcategories_" + obj.value);
    
    if(!obj.checked){
        element.style.display = 'none'; 
        SearchCompanies();
    }else{
        //Si no tiene los elementos, los carga
        if(element.innerHTML ==''){
            var url = "AjaxResponse/Companies/Subcategories.asp";
            var params = "id=" + obj.value;
            //alert(params);
            http.open("POST", url , true);
            
            http.onreadystatechange = function (){
                if (http.readyState==1)
                { 
                    element.innerHTML = _loading;   
                }
                else 
                {
                    if (http.readyState==4)
                    {
                        if(http.status==200)
                        {
                            element.innerHTML = http.responseText;
                            SearchCompanies();
                        }
                        else 
                        {
                            if(http.status==404)
                            {
                                element.innerHTML = "La direccion no existe";
                            }
                            else
                            {
                                element.innerHTML = "Error: " +  http.status;
                            }
                        }
                    }
                }
            }
            
            http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
            http.send(params);
        }else{
            SearchCompanies();
        }
        element.style.display = 'block';
    }
    return;
    
    
}



//INMUEBLES

function changeVentaAlquiler(ventaAlquiler, priceFrom, priceTo, typeProperty, provinceLeft, cityLeft, roomsLeft, bathroomsLeft, m2, referenceLeft, keyword){
    var element = document.getElementById("ventaAlquilerLayer");
        url ="includes/inmuebles/ajax_venta_alquiler.asp";
        fields="ventaAlquiler=" + ventaAlquiler;
        http.open("POST", url , true);
        
        http.onreadystatechange = function() {
        if (http.readyState==4){
                   if(http.status==200)
                   {
                        element.innerHTML=http.responseText;
                        changePriceFrom(ventaAlquiler, priceFrom, priceTo, typeProperty, provinceLeft, cityLeft, roomsLeft, bathroomsLeft, m2, referenceLeft, keyword);
                   }
                   else if(http.status==404){
                            element.innerHTML = "La direccion no existe";
                        }else{
                            element.innerHTML = "Error: "+ http.status;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(fields);
         return;

}

function changePriceFrom(ventaAlquiler, priceFrom, priceTo, typeProperty, provinceLeft, cityLeft, roomsLeft, bathroomsLeft, m2, referenceLeft, keyword){
    var element = document.getElementById("priceFromLayer");
    var ventaAlquiler = document.getElementById("ventaAlquiler").value; 
    url ="includes/inmuebles/ajax_price_from.asp";
    fields="priceFrom=" + priceFrom + "&ventaAlquiler=" + ventaAlquiler;
    http.open("POST", url , true);
    
    http.onreadystatechange = function() {
    if (http.readyState==4){
               if(http.status==200)
               {
                    element.innerHTML=http.responseText;
                    changePriceTo(typeProperty, provinceLeft, cityLeft, roomsLeft, bathroomsLeft, m2, referenceLeft, keyword);
               }
               else if(http.status==404){
                        element.innerHTML = "La direccion no existe";
                    }else{
                        element.innerHTML = "Error: "+ http.status;
                    }
               }
     }
     http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
     http.send(fields);
     return;
}


function changePriceTo(priceTo, typeProperty, provinceLeft, cityLeft, roomsLeft, bathroomsLeft, m2, referenceLeft, keyword){
    var element = document.getElementById("priceToLayer");
    var priceFrom = document.getElementById("priceFrom").value; 
    var ventaAlquiler = document.getElementById("ventaAlquiler").value; 
        url ="includes/inmuebles/ajax_price_to.asp";
        fields="priceTo=" + priceTo + "&ventaAlquiler=" + ventaAlquiler;
        http.open("POST", url , true);
        http.onreadystatechange = function() {
        if (http.readyState==4){
                   if(http.status==200)
                   {
                        element.innerHTML=http.responseText;
                        changeTypeProperty(typeProperty, provinceLeft, cityLeft, roomsLeft, bathroomsLeft, m2, referenceLeft, keyword);
                   }
                   else if(http.status==404){
                            element.innerHTML = "La direccion no existe";
                        }else{
                            element.innerHTML = "Error: "+ http.status;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(fields);
         return;

}

function changeTypeProperty(typeProperty, provinceLeft, cityLeft, roomsLeft, bathroomsLeft, m2, referenceLeft, keyword){
    
    var element = document.getElementById("typePropertyLayer");
    var ventaAlquiler = document.getElementById("ventaAlquiler").value; 
    var priceFrom = document.getElementById("priceFrom").value; 
    var priceTo = document.getElementById("priceTo").value; 
        url ="includes/inmuebles/ajax_type_property.asp";
        fields="priceFrom=" + priceFrom + "&priceTo=" + priceTo + "&typeProperty=" + escape(typeProperty) + "&ventaAlquiler=" + ventaAlquiler;
        http.open("POST", url , true);
        
        http.onreadystatechange = function() {
        if (http.readyState==4){
                   if(http.status==200)
                   {
                        element.innerHTML=http.responseText;
                        changeProvinceLeft(provinceLeft, cityLeft, roomsLeft, bathroomsLeft, m2, referenceLeft, keyword);
                   }
                   else if(http.status==404){
                            element.innerHTML = "La direccion no existe";
                        }else{
                            element.innerHTML = "Error: "+ http.status;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(fields);
         return;

}


function changeProvinceLeft(provinceLeft, cityLeft, roomsLeft, bathroomsLeft, m2, referenceLeft, keyword){
    
    var element = document.getElementById("provinceLeftLayer");
    var ventaAlquiler = document.getElementById("ventaAlquiler").value; 
    var priceFrom = document.getElementById("priceFrom").value; 
    var priceTo = document.getElementById("priceTo").value; 
    var typeProperty = document.getElementById("typeProperty").value;   
        url ="includes/inmuebles/ajax_province_left.asp";
        fields="priceFrom=" + priceFrom + "&priceTo=" + priceTo + "&typeProperty=" + escape(typeProperty) + "&provinceLeft=" + escape(provinceLeft) + "&ventaAlquiler=" + ventaAlquiler;
        http.open("POST", url , true);
        
        http.onreadystatechange = function() {
        if (http.readyState==4){
                   if(http.status==200)
                   {
                        element.innerHTML=http.responseText;
                        changeCityLeft(cityLeft, roomsLeft, bathroomsLeft, m2, referenceLeft, keyword);
                   }
                   else if(http.status==404){
                            element.innerHTML = "La direccion no existe";
                        }else{
                            element.innerHTML = "Error: "+ http.status;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(fields);
         return;

}

function changeCityLeft(cityLeft, roomsLeft, bathroomsLeft, m2, referenceLeft, keyword){
    
    var element = document.getElementById("cityLeftLayer");
    var ventaAlquiler = document.getElementById("ventaAlquiler").value; 
    var priceFrom = document.getElementById("priceFrom").value; 
    var priceTo = document.getElementById("priceTo").value; 
    var typeProperty = document.getElementById("typeProperty").value;   
    var provinceLeft= document.getElementById("provinceLeft").value;    
        url ="includes/inmuebles/ajax_city_left.asp";
        fields="priceFrom=" + priceFrom + "&priceTo=" + priceTo + "&typeProperty=" + escape(typeProperty) + "&provinceLeft=" + escape(provinceLeft) + "&cityLeft=" + escape(cityLeft) + "&ventaAlquiler=" + ventaAlquiler;
        http.open("POST", url , true);
        
        http.onreadystatechange = function() {
        if (http.readyState==4){
                   if(http.status==200)
                   {
                        element.innerHTML=http.responseText;
                        changeRoomsLeft(roomsLeft, bathroomsLeft, m2, referenceLeft, keyword);
                   }
                   else if(http.status==404){
                            element.innerHTML = "La direccion no existe";
                        }else{
                            element.innerHTML = "Error: "+ http.status;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(fields);
         return;

}

function changeRoomsLeft(roomsLeft, bathroomsLeft, m2, referenceLeft, keyword){
    
        var element = document.getElementById("roomsLeftLayer");
        url ="includes/inmuebles/ajax_rooms_left.asp";
        fields = "roomsLeft=" + roomsLeft;
        http.open("POST", url , true);
        
        http.onreadystatechange = function() {
        if (http.readyState==4){
                   if(http.status==200)
                   {
                        element.innerHTML=http.responseText;
                        changeBathrooms(bathroomsLeft, m2, referenceLeft, keyword);
                   }
                   else if(http.status==404){
                            element.innerHTML = "La direccion no existe";
                        }else{
                            element.innerHTML = "Error: "+ http.status + http.responseText;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(fields);
         return;

}

function changeBathrooms(bathroomsLeft, m2, referenceLeft, keyword){
    
    var element = document.getElementById("bathroomsLayer");

        url ="includes/inmuebles/ajax_bathrooms.asp";
        fields = "bathroomsLeft=" + bathroomsLeft;
        http.open("POST", url , true);
        
        http.onreadystatechange = function() {
        if (http.readyState==4){
                   if(http.status==200)
                   {
                        element.innerHTML=http.responseText;
                        changeM2From(m2, referenceLeft, keyword);
                   }
                   else if(http.status==404){
                            element.innerHTML = "La direccion no existe";
                        }else{
                            element.innerHTML = "Error: "+ http.status;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(fields);
         return;

}

function changeM2From(m2, referenceLeft, keyword){
    
    var element = document.getElementById("m2Layer");

        url ="includes/inmuebles/ajax_m2_from.asp";
        fields = "m2=" + m2;
        http.open("POST", url , true);
        
        http.onreadystatechange = function() {
        if (http.readyState==4){
                   if(http.status==200)
                   {
                        element.innerHTML=http.responseText;
                        changeReferenceLeft(referenceLeft, keyword);
                   }
                   else if(http.status==404){
                            element.innerHTML = "La direccion no existe";
                        }else{
                            element.innerHTML = "Error: "+ http.status;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(fields);
         return;

}

function changeReferenceLeft(referenceLeft, keyword){
    
    var element = document.getElementById("referenceLeftLayer");

        url ="includes/inmuebles/ajax_reference_left.asp";
        fields = "referenceLeft=" + referenceLeft;
        http.open("POST", url , true);
        
        http.onreadystatechange = function() {
        if (http.readyState==4){
                   if(http.status==200)
                   {
                        element.innerHTML=http.responseText;
                        changeKeyword(keyword);
                   }
                   else if(http.status==404){
                            element.innerHTML = "La direccion no existe";
                        }else{
                            element.innerHTML = "Error: "+ http.status;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(fields);
         return;

}

function changeKeyword(keyword){
    
    var element = document.getElementById("keywordLayer");

        url ="includes/inmuebles/ajax_keyword.asp";
        fields = "keyword=" + keyword;
        http.open("POST", url , true);
        
        http.onreadystatechange = function() {
        if (http.readyState==4){
                   if(http.status==200)
                   {
                        element.innerHTML=http.responseText;
                   }
                   else if(http.status==404){
                            element.innerHTML = "La direccion no existe";
                        }else{
                            element.innerHTML = "Error: "+ http.status;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(fields);
         return;

}
function searchLeft(){

    var page = document.getElementById("ventaAlquiler").value;
    var form = document.getElementById("searchLeft");
    form.action = "index.asp?pagina=inmuebles&res=1";
    form.submit();
    
}

function changeOrder(order){
    var element = document.getElementById("properties");
    var regimen = document.getElementById("mode").value;
    var tipo = document.getElementById("type").value;
    var provincia = document.getElementById("province").value;
    var poblacion = document.getElementById("city").value;
    var precio = document.getElementById("price").value;
    var dormitorios = document.getElementById("rooms").value;
    var referencia = document.getElementById("reference").value;

    var priceFrom = document.getElementById("priceFrom").value;
    var priceTo = document.getElementById("priceTo").value;
    var typeProperty = document.getElementById("typeProperty").value;
    var provinceLeft = document.getElementById("provinceLeft").value;
    var cityLeft = document.getElementById("cityLeft").value;
    var roomsLeft = document.getElementById("roomsLeft").value;
    var bathroomsLeft = document.getElementById("bathroomsLeft").value;
    var m2 = document.getElementById("m2").value;
    var referenceLeft = document.getElementById("referenceLeft").value;
    var keyword = document.getElementById("keyword").value;
    var numPagina = document.getElementById("numPagina").value;
    
    var fields = "order=" + order + "&mode=" + regimen + "&type=" + tipo + "&province=" + escape(provincia) + "&city=" + escape(poblacion) + "&price=" + precio + "&rooms=" + dormitorios + "&reference=" + referencia + "&numPagina=" + numPagina + "&res=1&priceFrom=" + priceFrom + "&priceTo=" + priceTo + "&typeProperty=" + typeProperty + "&provinceLeft=" + provinceLeft + "&cityLeft=" + cityLeft + "&roomsLeft=" + roomsLeft + "&bathroomsLeft=" + bathroomsLeft + "&m2=" + m2 + "&referenceLeft=" + referenceLeft + "&keyword=" + keyword;
    url ="includes/inmuebles/resultadoInmueble2.asp";
    http.open("POST", url , true);
    
    http.onreadystatechange = function() {
    if (http.readyState==4){
               if(http.status==200)
               {
                    element.innerHTML=http.responseText;
               }
               else if(http.status==404){
                        element.innerHTML = "La direccion no existe";
                    }else{
                        element.innerHTML = "Error: "+ http.status;
                    }
               }
     }
    http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    http.send(fields);
    return;

}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

//es la funcion validar para el formulario de contacto de las fichas del producto
//Edgar Tebar
function fichaProductoValidar(idioma, ref){
//Funcion para la validar los datos enviados desde el formulario de contacto
    var texto;
    texto = "";
    texto_en = "";

    var cadenaEnvio;
    cadenaEnvio = "";
    //alert(idioma + ref);
    
    //Aqui validamos que los campos obligatorios tengan valor y se añaden a la cadena de envio
    if(!document.getElementById("formularioContacto").acepto.checked)
        {
            texto=" * Debe aceptar los términos.<br>"
            }
            
    if ( document.getElementById("formularioContacto").nombre.value == "" ) {
        texto+=" * Debe indicar su nombre.<br>";
        texto_en+=" * You must enter your name.<br>";
    }else{
        cadenaEnvio="nombre=" + encodeURI(document.getElementById("formularioContacto").nombre.value);
    }
    
    if ( document.getElementById("formularioContacto").email.value == "" ) {
        texto+=" * Debe indicar su e-mail.<br>";
        texto_en+=" * You must enter your e-mail.<br>";
    }
    
    if(document.getElementById("formularioContacto").email.value!=""){
        if(!validarEmail(document.getElementById("formularioContacto").email.value)){
                texto+=" * Formato de E-mail incorrecto.<br>";
                texto_en+=" * The E-mail format is wrong.<br>";
        }else{
            cadenaEnvio+="&email=" + encodeURI(document.getElementById("formularioContacto").email.value);
        }
    }
    if ( document.getElementById("formularioContacto").comentarios.value == "" ){
        texto+=" * Debe incluir el motivo de su consulta.<br>";
        texto_en+=" * You must enter your comments.<br>";
    }else{
        cadenaEnvio+="&comentarios=" + encodeURI(document.getElementById("formularioContacto").comentarios.value);
    }   
    
    //Aqui vamos añadiendo los demas campos sino estan vacios

    if ( document.getElementById("formularioContacto").telefono.value == "" ) {
        texto+=" * Debe indicar su telefono.<br>";
        texto_en+=" * You must enter your phone number.<br>";
    }else{
        cadenaEnvio+="&telefono=" + encodeURI(document.getElementById("formularioContacto").telefono.value);
    }
        if ( document.getElementById("formularioContacto").fax.value == "" ) {
    }else{
        cadenaEnvio+="&fax=" + encodeURI(document.getElementById("formularioContacto").fax.value);
    }
    cadenaEnvio+="&ref=" + encodeURI(ref);

if ( texto != "" ){
            switch (idioma) { 
                case '101': 
                    document.getElementById("mensajeError").innerHTML=texto_en;
                   break 
                default: 
                    document.getElementById("mensajeError").innerHTML=texto;
            } 
        document.getElementById("capaError").style.display='block';
        
    }else{
        //alert(cadenaEnvio);
        document.getElementById("mensaje-respuesta").innerHTML="";
        document.getElementById("mensajeError").innerHTML="";
        document.getElementById("capaError").style.display='none';
        http.open("GET", "actualizer/formcorreosMultiple/envioSinBdSolicitudes.asp?" + cadenaEnvio, true);
        http.onreadystatechange = handleHttpResponseContacto;
        http.send(null);
    }
    
}

function changeOrder(order){
    var element = document.getElementById("properties");
    var regimen = document.getElementById("mode").value;
    var tipo = document.getElementById("type").value;
    var provincia = document.getElementById("province").value;
    var poblacion = document.getElementById("city").value;
    var precio = document.getElementById("price").value;
    var dormitorios = document.getElementById("rooms").value;
    var referencia = document.getElementById("reference").value;

    var priceFrom = document.getElementById("priceFrom").value;
    var priceTo = document.getElementById("priceTo").value;
    var typeProperty = document.getElementById("typeProperty").value;
    var provinceLeft = document.getElementById("provinceLeft").value;
    var cityLeft = document.getElementById("cityLeft").value;
    var roomsLeft = document.getElementById("roomsLeft").value;
    var bathroomsLeft = document.getElementById("bathroomsLeft").value;
    var m2 = document.getElementById("m2").value;
    var referenceLeft = document.getElementById("referenceLeft").value;
    var keyword = document.getElementById("keyword").value;
    var numPagina = document.getElementById("numPagina").value;
    
    var fields = "order=" + order + "&mode=" + regimen + "&type=" + tipo + "&province=" + escape(provincia) + "&city=" + escape(poblacion) + "&price=" + precio + "&rooms=" + dormitorios + "&reference=" + referencia + "&numPagina=" + numPagina + "&res=1&priceFrom=" + priceFrom + "&priceTo=" + priceTo + "&typeProperty=" + typeProperty + "&provinceLeft=" + provinceLeft + "&cityLeft=" + cityLeft + "&roomsLeft=" + roomsLeft + "&bathroomsLeft=" + bathroomsLeft + "&m2=" + m2 + "&referenceLeft=" + referenceLeft + "&keyword=" + keyword;
    url ="includes/inmuebles/resultadoInmueble2.asp";
    http.open("POST", url , true);
    
    http.onreadystatechange = function() {
    if (http.readyState==4){
               if(http.status==200)
               {
                    element.innerHTML=http.responseText;
               }
               else if(http.status==404){
                        element.innerHTML = "La direccion no existe";
                    }else{
                        element.innerHTML = "Error: "+ http.status;
                    }
               }
     }
    http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    http.send(fields);
    return;

}
function mostrarTiempo(opcion){
    
    switch(opcion){
        
        case 1:
            document.getElementById("tiempoMadrid").style.display="block";
            document.getElementById("madrid").style.color="#FFFFFF";
            
            document.getElementById("tiempoParis").style.display="none";
            document.getElementById("paris").style.color="#CCCCCC";
            
            document.getElementById("tiempoRoma").style.display="none";
            document.getElementById("roma").style.color="#CCCCCC";
            
        break;
        
        case 2:
            document.getElementById("tiempoMadrid").style.display="none";
            document.getElementById("madrid").style.color="#CCCCCC";
        
            document.getElementById("tiempoParis").style.display="block";
            document.getElementById("paris").style.color="#FFFFFF";

            document.getElementById("tiempoRoma").style.display="none";
            document.getElementById("roma").style.color="#CCCCCC";
            
        break;
        
        case 3:
            document.getElementById("tiempoMadrid").style.display="none";
            document.getElementById("madrid").style.color="#CCCCCC";
            
            document.getElementById("tiempoParis").style.display="none";
            document.getElementById("paris").style.color="#CCCCCC";

            document.getElementById("tiempoRoma").style.display="block";
            document.getElementById("roma").style.color="#FFFFFF";

    break;
    
    }
}

function votar()
{
    var objects = document.getElementsByTagName('INPUT');
    var obj, objSeleccionado = null;
    
    for (var i=0; i < objects.length; i++)
    {
        obj = objects[i];
        if(obj.id.indexOf('encuesta') > -1)
        {
            if (obj.checked)
            {
                objSeleccionado = obj;
            }
        }
    }
    
    if (objSeleccionado != null)
    {
        var idEncuesta = document.getElementById("idEncuesta_" + objSeleccionado.value).value;
        var titlePoll = document.getElementById("pollTitle").innerHTML;

        //Guardamos la respuesta, comprobando que no haya respondido en la sesion actual
        var url = "includes/ajax_savePollResponse.asp";
        var params = "id=" + idEncuesta + "&responseId=" + objSeleccionado.value;
        //alert(params);
        http.open("POST", url , true);
        
        http.onreadystatechange = function (){
            var element = document.getElementById("encuestas");
            if (http.readyState==1)
            { element.innerHTML = _loading; }
            else 
            {
                if (http.readyState==4)
                {
                    if(http.status==200)
                    {
                        if (http.responseText == "1")
                        {
                            element.innerHTML = titlePoll + "<span style='padding-top:60px; text-align:center; display:block;'><br /><br />Respuesta enviada.</span>";
                        }
                        else
                        {
                            element.innerHTML = http.responseText;
                        }
                    }
                    else 
                    {
                        if(http.status==404)
                        {
                            element.innerHTML = "La direccion no existe";
                        }
                        else
                        {
                            element.innerHTML = "Error: " +  http.status;
                        }
                    }
                }
            }
        }
        
        http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
        http.send(params);
        
        return;
    }
    else
    {
        alert("Seleccione una respuesta para votar.");
    }
}


/****************************************************************************************
/ Nombre: buscadorWeb
/ Implentacion: ETEBAR
/ Revision:
/ Descripcion: Envia el formulario de busqueda
'***************************************************************************************/
function searchOnNotices(op){
    var params = "";
    var url = "index.asp?pagina=buscador-news";

    if ($("#competition") != null && $("#competition") != undefined && $("#competition").val() != "")
    {
        switch($("#competition").val())
        {
            case '223':
                url += "-international";
                break;
            case '230':
                url += "-espana-gt";
                break;
            case '299':
                url += "-f3";
                break;
            case '302':
                url += "-otros-campeonatos";
                break;
        }
    }
    
    if (op == 0){       
    
        if (document.getElementById("textobusquedaNoticias").value.length > 0){
            params += "&text=" + document.getElementById("textobusquedaNoticias").value;
        }
        params += "&theme=" + document.getElementById("themes").value;
        params += "&year=" + document.getElementById("year").value;     
        params += "&month=" + document.getElementById("month").value;   
        params += "&paginaAnt=" + document.getElementById("paginaAnt").value;   
        url += params;

        document.getElementById("busquedaNoticias").action = url;
        document.getElementById("busquedaNoticias").submit();

    }else{
        var element = document.getElementById("resultadosBusqueda");
        
        url ="includes/buscador_resultados_ajax.asp?";
        if (document.getElementById("textobusquedaNoticias").value.length > 0){
            params += "text=" + document.getElementById("textobusquedaNoticias").value;
        }
        params += "&theme=" + document.getElementById("themes").value;
        params += "&year=" + document.getElementById("year").value;     
        params += "&month=" + document.getElementById("month").value;   
        

        http.open("POST", url , true);
        
        http.onreadystatechange = function() {
        if (http.readyState==4){
                    
                   if(http.status==200)
                   {    
                        element.innerHTML = http.responseText;
                   }
                   else if(http.status==404){
                            element.innerHTML = "La direccion no existe";
                        }else{
                            alert(http.responseText)
                            element.innerHTML = "Error: "+ http.status;
                        }
                   }
         }
         http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
         http.send(params);
         return;
        
    }
}



/****************************************************************************************
/ Nombre: AddToBookMarks
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Añade la página a favoritos
'***************************************************************************************/
function AddToBookMarks(){
    
    var url = "http://www.todociclismo.com";
    var title = document.title;
    
    //IE
    if ((navigator.appName=="Microsoft Internet Explorer") && (parseInt(navigator.appVersion)>=4)) {
        window.external.AddFavorite(url,title);
    }
    //Para Firefox
    else {
        if(navigator.appName == "Netscape")
            //Hay que modificar el nombre por el de vuestra pagina
            window.sidebar.addPanel(title, url,"");
    }
}


/****************************************************************************************
/ Nombre: SetAsHomePage
/ Implentacion: JBERNALTE
/ Revision:
/ Descripcion: Establece pcomo página de inicio
'***************************************************************************************/
function SetAsHomePage(obj){
    if(navigator.appName == "Netscape"){
        alert ("Opcion disponible solamente para Internet explorer"); 
    }else{
        obj.style.behavior='url(#default#homepage)'; 
        obj.setHomePage("http://www.todociclismo.com");  
    }
}

function changeModalities(){
    var element = document.getElementById("clasifications");
    var params = ""
    id=document.getElementById("modalities").value;
    url ="includes/ajax_TemasClasificaciones.asp?";

    params = "id=" + id;
    url+=params;
    http.open("POST", url , true);
    
    http.onreadystatechange = function() {
    if (http.readyState==4){
                
               if(http.status==200)
               {    
                    element.innerHTML = http.responseText;
               }
               else if(http.status==404){
                        element.innerHTML = "La direccion no existe";
                    }else{
                        element.innerHTML = "Error: "+ http.status;
                    }
               }
     }
     http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
     http.send(params);
     return;
}

/****************************************************************************************
/ Nombre:       ChangeGalleryModalities
/ Implentacion: Jordi Darijo
/ Revision:     30/12/2009
/ Descripcion:  Carga por ajax el getTemas de la galeria general
/***************************************************************************************/
function ChangeGalleryModalities(pagina)
{
    var element = document.getElementById("temasFotosCompeticion");
    var params = "";
    var url = "includes/catalogo/getTemasGallery_ajax.asp";
    
    var id = document.getElementById("modalities").value;

    params = "id=" + id;
    params += "&pagina=" + pagina
    http.open("POST", url , true);
    http.onreadystatechange = function(){
        if (http.readyState == 1)
        {
            element.innerHTML = _loading;
        }
        else
        {
            if (http.readyState == 4)
            {
                if(http.status == 200)
                {   
                    element.innerHTML = http.responseText;
                }
                else
                {
                    if(http.status == 404)
                    {
                        element.innerHTML = "La direccion no existe";
                    }
                    else
                    {
                        element.innerHTML = "Error: " + http.status;
                    }
                }
            }
        }
    }
    
    http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    http.send(params);
    
    return;
}

function changeSection(op){

    switch(op){
        case 1:
            window.location.href="index.asp?pagina=participa&sectionParticipa=1";
        break;

        case 2:
            window.location.href="index.asp?pagina=participa&sectionParticipa=2";
        break;

        case 3:
            window.location.href="index.asp?pagina=participa&sectionParticipa=3";
        break;

        case 4:
            window.location.href="index.asp?pagina=participa&sectionParticipa=4";
        break;

        case 5:
            window.location.href="index.asp?pagina=participa&sectionParticipa=5";
        break;

        case 6:
            window.location.href="index.asp?pagina=participa&sectionParticipa=6";
        break;

        case 7:
            window.location.href="index.asp?pagina=participa&sectionParticipa=7";
        break;
    }
}

function validarContactoAlbum(){
//Funcion para la validar los datos enviados desde el formulario de contacto
    var texto;
    texto = "";
    
    var cadenaEnvio;
    cadenaEnvio = "";
    
    //Aqui validamos que los campos obligatorios tengan valor y se añaden a la cadena de envio
    
    if ( document.getElementById("formImag").descripcion.value == "" ) {
        texto+=" - Debe indicar la descripción.<br>";

    }else{
        cadenaEnvio="descripcion=" + document.getElementById("formImag").descripcion.value;
    }

    cadenaEnvio+="&nombre=" + document.getElementById("formImag").nombre.value;
    
    if ( texto != "" ){
        alert("Debe indicar la descripción")
    }else{
        //alert(cadenaEnvio);
        document.formImag.submit();
    }
    
}

function getContinente(id){
    var params = "id=" + id;
    var url = "includes/noticias_calendario_inter_ajax.asp"
    var element = document.getElementById("noticiasLayer");
    http.open("POST", url , true);
    http.onreadystatechange = function(){
        if (http.readyState == 1)
        {
            element.innerHTML = _loading;
        }
        else
        {
            if (http.readyState == 4)
            {
                if(http.status == 200)
                {   
                    element.innerHTML = http.responseText;
                }
                else
                {
                    if(http.status == 404)
                    {
                        element.innerHTML = "La direccion no existe";
                    }
                    else
                    {
                        element.innerHTML = "Error: " + http.status;
                    }
                }
            }
        }
    }
    
    http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    http.send(params);
    
    return;
    


}
function getProvincia(id){
    var params = "id=" + id;
    var url = "includes/noticias_calendario_inter_ajax.asp"
    var element = document.getElementById("noticiasLayer");
    http.open("POST", url , true);
    http.onreadystatechange = function(){
        if (http.readyState == 1)
        {
            element.innerHTML = _loading;
        }
        else
        {
            if (http.readyState == 4)
            {
                if(http.status == 200)
                {   
                    element.innerHTML = http.responseText;
                }
                else
                {
                    if(http.status == 404)
                    {
                        element.innerHTML = "La direccion no existe";
                    }
                    else
                    {
                        element.innerHTML = "Error: " + http.status;
                    }
                }
            }
        }
    }
    
    http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    http.send(params);
    
    return;
    


}


function enviarNoticia(idioma){
    var texto="";
    var texto_ing="";
    var idioma=idioma;
    
    if (document.getElementById("cajaEnvioEmail").value==""){
        texto+=" * Debe insertar un email.<br/>"
        texto_ing+=" * You must enter your email.<br/>"
    }
    
    if(document.getElementById("cajaEnvioEmail").value!=""){
        if(!validarEmail(document.getElementById("cajaEnvioEmail").value)){
                texto+=" * Formato de E-mail incorrecto.<br/>";
                texto_ing+=" * The E-mail format is wrong.<br/>";
        }
    }
    
    if (idioma == 100)
        if (texto!=""){
            document.getElementById("mensajeError").innerHTML=texto;
        }else{
            
            http.open("GET", "includes/enviarEmail.asp?email=" + document.getElementById("cajaEnvioEmail").value, true);
            http.onreadystatechange = handleHttpResponseEnviarEmail;
            http.send(null);
        }           
    
    else
        if (texto_ing!=""){
            document.getElementById("mensajeError").innerHTML=texto_ing;
        }else{
            
            http.open("GET", "includes/enviarEmail.asp?email=" + document.getElementById("cajaEnvioEmail").value, true);
            http.onreadystatechange = handleHttpResponseEnviarEmail;
            http.send(null);
        }           
}

function handleHttpResponseEnviarEmail() {
    if (http.readyState == 4) {    
        document.getElementById("mensajeError").innerHTML=http.ResponseText;
        document.getElementById("cajaEnvioEmail").value="";
        // window.print() 
        //document.location="index.asp?pagina=candidatos&subpagina=vista-previa"
    }    
}

function changeFlag(lang, overOut){
    if(overOut == 0){
        if (lang == 100){
            var flag = document.getElementById("espanyol");
            flag.src = "images/espanyol-over.gif"
        }else{
            var flag = document.getElementById("english");
            flag.src = "images/english-over.gif"
        }
    }else{
        if (lang == 100){
            var flag = document.getElementById("espanyol");
            flag.src = "images/espanyol.gif"
        }else{
            var flag = document.getElementById("english");
            flag.src = "images/english.gif"
        }
    }
}
function cerrarSus(){

    var sus = document.getElementById("newsletter_msg");
    sus.style.display = "none";
    var cerrarMsg = document.getElementById("cerrarMsg");
    cerrarMsg.style.display = "none"
    var sus = document.getElementById("sus");
    sus.style.display = "block"
    document.getElementById("newslettername").value = "Nombre"
    document.getElementById("newsletteremail").value = "E-mail"
}

/****************************************************************
/ Nombre: saveComments
/ Implentacion: Jordi Darijo
/ Revision: 18/01/2010
/ Descripcion: Guarda un comentario de la noticia
'***************************************************************/
function saveComments(idNoticia, idUser)
{
    //alert("Guardando... idNoticia = " + idNoticia);
    if (document.getElementById("comentarios").innerHTML != "" && document.getElementById("comentarios").innerHTML != "Escribe aquí tu comentario")
    {
        var url = "includes/SaveComment_ajax.asp";
        var params = "idNoticia=" + idNoticia + "&usuario=" + idUser + "&comments=" + encodeURIComponent(document.getElementById("comentarios").innerHTML);
        
        var element = document.getElementById("comentarios_msg");
        element.style.color = "#FF0000";
        
        //alert(params);
        http.open("POST", url , true);
        
        http.onreadystatechange = function (){
            if (http.readyState==1)
            { 
                element.innerHTML = _loading;   
            }
            else 
            {
                if (http.readyState==4)
                {
                    if(http.status==200)
                    {
                        if (http.responseText == "1")
                        {
                            element.style.color = "#00BB88";
                            element.innerHTML = "Comentario guardado correctamente.";
                        }
                        else
                        {
                            element.innerHTML = http.responseText;
                        }
                    }
                    else 
                    {
                        if(http.status==404)
                        {
                            element.innerHTML = "La direccion no existe";
                        }
                        else
                        {
                            element.innerHTML = "Error: " +  http.status;
                        }
                    }
                }
            }
        }
        
        http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
        http.send(params);
    }
    else
    {
        document.getElementById("comentarios_msg").style.color = "#FF0000";
        document.getElementById("comentarios_msg").innerHTML = "Debe de escribir algun comentario antes de poder guardar.";
    }
    setTimeout("showComments('"+idNoticia+"')", 500);
    ;
}

function showComments(idNoticia){
        var url = "includes/showComments.asp?";
        var params = "id=" + idNoticia
        
        var element = document.getElementById("commentsList");
    
        
        //alert(url + "--"+params);
        http.open("POST", url , true);
        
        http.onreadystatechange = function (){
            if (http.readyState==1)
            { 
                element.innerHTML = _loading;   
            }
            else 
            {
                if (http.readyState==4)
                {
                    if(http.status==200)
                    {
                        element.innerHTML = http.responseText;

                    }
                    else 
                    {
                        if(http.status==404)
                        {
                            element.innerHTML = "La direccion no existe";
                        }
                        else
                        {
                            element.innerHTML = "Error: " +  http.status;
                        }
                    }
                }
            }
        }
        
        http.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
        http.send(params);
    
}

/****************************************************************************************
/ Nombre: buscadorWeb
/ Implentacion: ETEBAR
/ Revision:
/ Descripcion: Envia el formulario de busqueda
'***************************************************************************************/
function searchOnHistorical(){
    var params = "";
    var element = document.getElementById("historico");
    
    url ="includes/buscador_resultados_historico_ajax.asp?";

    params += "result=" + document.getElementById("result").value;
    params += "&year=" + document.getElementById("year").value;     
    params += "&classification=" + document.getElementById("classification").value; 
    

    http.open("POST", url , true);
    
    http.onreadystatechange = function() {
    if (http.readyState==4){
                
               if(http.status==200)
               {    
                    element.innerHTML = http.responseText;
               }
               else if(http.status==404){
                        element.innerHTML = "La direccion no existe";
                    }else{
                        //alert(http.responseText)
                        element.innerHTML = "Error: "+ http.status;
                    }
               }
     }
     http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
     http.send(params);
     return;

}

/****************************************************************************************
/ Nombre: buscadorWeb
/ Implentacion: ETEBAR
/ Revision:
/ Descripcion: Envia el formulario de busqueda
'***************************************************************************************/
function searchOnGallery(pagina){
    var params = "";
    var element = document.getElementById("busquedaGallery");
    
    var gallery =document.getElementById("gallery").value;
    var year = document.getElementById("year").value;       
    
    element.action = "index.asp?pagina=" + pagina + "&gallery=" + gallery + "&year=" + year;
    element.submit();
    
}

function cargarGalerias(filtro, gallery){
    var params = "";
    var element = document.getElementById("galleries");
    
    url ="includes/cargarGalerias_ajax.asp?";
    params += "year=" + document.getElementById("year").value;  
    params += "&filtro=" + filtro;
    params += "&gallery=" + gallery;
    
    http.open("POST", url , true);
    http.onreadystatechange = function() {
    if (http.readyState==4){
                
               if(http.status==200)
               {    
                    element.innerHTML = http.responseText;
               }
               else if(http.status==404){
                        element.innerHTML = "La direccion no existe";
                    }else{
                        //alert(http.responseText)
                        element.innerHTML = "Error: "+ http.status;
                    }
               }
     }
     http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
     http.send(params);
     return;
    
    }
function cargarMesNoticias(){
    var params = "";
    var element = document.getElementById("monthDiv");
    
    url ="includes/buscadorNoticiasMes_ajax.asp?";
    params += "year=" + document.getElementById("year").value;  
    params += "&filtro=" + document.getElementById("filtro").value; 
    
    http.open("POST", url , true);
    http.onreadystatechange = function() {
    if (http.readyState==4){
                
               if(http.status==200)
               {    
                    element.innerHTML = http.responseText;
                    cargarTemasNoticias();
               }
               else if(http.status==404){
                        element.innerHTML = "La direccion no existe";
                    }else{
                        //alert(http.responseText)
                        element.innerHTML = "Error: "+ http.status;
                    }
               }
     }
     http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
     http.send(params);
     return;
    
    }
    
function cargarTemasNoticias(){
    
    var params = "";
    var element = document.getElementById("themesDiv");
    
    url ="includes/buscadorNoticiasTema_ajax.asp?";
    params += "year=" + document.getElementById("year").value;  
    params += "&month=" + document.getElementById("month").value;   

    http.open("POST", url , true);
    http.onreadystatechange = function() {
    if (http.readyState==4){
                
               if(http.status==200)
               {    
                    element.innerHTML = http.responseText;
               }
               else if(http.status==404){
                        element.innerHTML = "La direccion no existe";
                    }else{
                        //alert(http.responseText)
                        element.innerHTML = "Error: "+ http.status;
                    }
               }
     }
     http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
     http.send(params);
     return;
    
    }
    
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}


function SendToPhoto(){
        url = $("#downloadphotos DIV").css("background-image");
        
        quitar = "includes/catalogo/ajustaImagenFotosUsuarios.asp?img=../../";
        url = url.replace(quitar, "");
        url = url.replace("url(", "");
        url = url.replace(")", "");
        
        window.open(url, "Foto");
}


function ChangeSize(producto, subpagina, galeria, oferta) {
	var color 	= $(".productselector #color").val();
	var size 	= $("#size").val();
	if (oferta == 1) {
		document.location = "index.asp?pagina=catalogo&producto=" + producto + "&subpagina=" + subpagina + "&galeria=" + galeria + "&size=" + size + "&color=" + color + "&ofertas=true";
	}
	else {
		document.location = "index.asp?pagina=catalogo&producto=" + producto + "&subpagina=" + subpagina + "&galeria=" + galeria + "&size=" + size + "&color=" + color;
	}
}


function SearchProducts(){

	if($("#SearchTextProduct").val() != "" && $("#SearchTextProduct").val() != "Escriba algo..." && $("#SearchTextProduct").val() != "Write something..."){
		$('#formSearchProducts').submit();
	}
}

function PaginationSearchResults(numPagina){
	var SearchTextProduct = $("#SearchText").val();
	
	$.ajax({
		type: "POST",
		url: "includes/buscadorProductos-resultados.asp",
		data: "SearchTextProduct=" + SearchTextProduct +"&numPagina=" + numPagina,
		success: function(data){
			$("#contenidos").html(data);
		}
	});
}

function PaginationSearchResultsProd(numPagina){
	var SearchTextProduct = $("#SearchText").val();
	
	$.ajax({
		type: "POST",
		url: "includes/buscadorGeneralProductos-resultados.asp",
		data: "SearchTextProduct=" + SearchTextProduct +"&numPagina=" + numPagina,
		success: function(data){
			$(".BusquedaProductos").html(data);
		}
	});
}

function PaginationSearchResultsNews(numPagina){
	var SearchTextProduct = $("#SearchText").val();
	
	$.ajax({
		type: "POST",
		url: "includes/buscadorGeneralNoticias-resultados.asp",
		data: "SearchTextProduct=" + SearchTextProduct +"&numPagina2=" + numPagina,
		success: function(data){
			$(".BusquedaNoticias").html(data);
		}
	});
}

function UpdateCart(cartItem,deleteItem){
	var product = $("INPUT.hiddenId",cartItem).val();
	var talla 	= $("INPUT.hiddenTalla",cartItem).val();
	var color	= $("INPUT.hiddenColor",cartItem).val();
	var amount 	= $("INPUT.numUnidades",cartItem).val();
	$.ajax({
		type: "POST",
		url: "AjaxResponse/Shop/updateCart.asp",
		data: "product=" + product + "&size=" + talla + "&color=" + color + "&amount=" + amount + "&deleteItem=" + deleteItem,
		success: function(data){
			$(".mycarttext .numcartelements").html(data);
		},
		error: function(data){
		}
	});
}

function UpdateTotalPrice(){
	var totalAcumulado = 0;
	$("DIV.shoppingcartlayer1 UL.data LI.total SPAN").each( function(){
		var totalFila = $(this).html();
		totalFila = replace(totalFila,",",".");
		totalAcumulado += 	parseFloat(totalFila);
	});
	totalAcumulado = Math.round(totalAcumulado * Math.pow(10, 2)) / Math.pow(10, 2);
	totalAcumulado = replace(totalAcumulado.toFixed(2).toString(),",",".");
	$("UL.cartActions LI.totalAcumulado SPAN").html(totalAcumulado);
}

function sendOpinion() {
	if ($("#opiniontext").val() != "") {
		
		var opinion 	= encodeURIComponent($("#opiniontext").val());
		var producto 	= encodeURIComponent($("#opinionTitle").val());
		var ref 		= encodeURIComponent($("#opinionRef").val());
		
		$.ajax({
			type: "POST",
			url: "actualizer/formcorreosMultiple/envioSinBD.asp",
			data: "opinion=" + opinion + "&producto=" + producto + "&ref=" + ref,
			success: function(data){
				$("#opiniontext").val("")
				$("#msg").html(data);
			}
		});
	}
}


function SolicitarPedido(){
	$(".shoppingcartlayer1").hide();
	$(".shoppingcartlayer2").show();
}

function ModificarPedido(){
	$(".shoppingcartlayer2").hide();
	$(".shoppingcartlayer1").show();
}

function ModificarPedido2(){
	$(".shoppingcartlayer3").hide();
	$(".shoppingcartlayer2").show();
}

function EnviarPedido(){
	error = false;
	$("#msg").html("");
	
	// COMPROBAMOS QUE LOS CAMPOS NO ESTAN VACIOS
	if($("#name").val() == "") 		{ error = true; }
	if($("#address").val() == "") 	{ error = true; }	
	if($("#code").val() == "") 		{ error = true; }	
	if($("#city").val() == "") 		{ error = true; }	
	if($("#province").val() == "") 	{ error = true; }	
	if($("#phone").val() == "") 	{ error = true; }
	
	if (error) {
		msg = $("#msgerror").val();
		$("#msg").html(msg);
	}
	else {
		params = "name=" + $("#name").val() + "&address=" + $("#address").val() + "&code=" + $("#code").val() + "&city=" + $("#city").val() + "&province=" + $("#province").val() + "&phone=" + $("#phone").val();
		$.ajax({
			type: "POST",
			url: "AjaxResponse/shop/sendOrder.asp",
			data: params + "&html=" + $("UL.cartTitle").html() + $("UL.data").html(),
			success: function(data){
				alert(data);
			} 
		});
	}
}


function EditShippingAddress(id){
	
	$.ajax({
		type: "POST",
		url: "AjaxResponse/shop/EditShippingAddress.asp",
		data: "id=" + id,
		success: function(data){
			alert(data);
		} 
	});
}

function DeleteShippingAddress(id) {
	
	$.ajax({
		type: "POST",
		url: "AjaxResponse/shop/DeleteShippingAddress.asp",
		data: "id=" + id,
		success: function(data){
			$("DIV.changeshippingaddress").html(data);
			LoadCustomerAddressEvents();
		} 
	});
}


function LoadShippingAddress(id, editAddress) {
	
	$.ajax({
		type: "POST",
		url: "AjaxResponse/shop/LoadShippingAddress.asp",
		data: "id=" + id,
		success: function(data){
			$("DIV.shippingdata").html(data);
			
			if (editAddress) {
				AddCustomerAddress(id);
			}
			
			LoadCustomerAddressEvents();
		} 
	});
}

/****************************************************************
/ Nombre: 		AddCustomerAddress
/ Implentacion: Jordi Darijo
/ Revision: 	24/08/2011
/ Descripcion: 	Muestra la capa de añadir dirección de cliente
'***************************************************************/
function AddCustomerAddress(id) {
	$(".shoppingcartlayer2 .changeshippingaddress").hide();
	$(".shoppingcartlayer2 .shippingdatalayer .promotionalcode").hide();
	$(".shoppingcartlayer2 .modificar").hide();
	$(".shoppingcartlayer2 .confirm").hide();
	$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #name").hide();
	$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #name").prev().hide();
	$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #phone").hide();
	$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #phone").prev().hide();
	$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #comentarios").hide();
	$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #comentarios").prev().hide();
	$(".shoppingcartlayer2 .saveaddress").show();
	$(".shoppingcartlayer2 .cancelsaveaddress").show();
	
	$(".shoppingcartlayer2 .cancelsaveaddress").unbind("click");
	$(".shoppingcartlayer2 .cancelsaveaddress").click(function () {
		$(".shoppingcartlayer2 .changeshippingaddress").show();
		$(".shoppingcartlayer2 .shippingdatalayer .promotionalcode").show();
		$(".shoppingcartlayer2 .modificar").show();
		$(".shoppingcartlayer2 .confirm").show();
		$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #name").show();
		$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #name").prev().show();
		$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #phone").show();
		$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #phone").prev().show();
		$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #comentarios").show();
		$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #comentarios").prev().show();
		$(".shoppingcartlayer2 .saveaddress").hide();
		$(".shoppingcartlayer2 .cancelsaveaddress").hide();
	});
	
	$(".shoppingcartlayer2 .saveaddress").unbind("click");
	$(".shoppingcartlayer2 .saveaddress").click(function () {
		$("IMG.loading").remove();
		$("SPAN.error").remove();
		
		var url 	= "AjaxResponse/shop/AddCustomerAddress_ajax.asp";
		var params 	= "";
		
		var address = "";
		if ($("#address") != null && $("#address").val() != undefined && $("#address").val() != "undefined" && $("#address").val() != "") {
			address = encodeURIComponent($("#address").val());
		}
		var cp = "";
		if ($("#code") != null && $("#code").val() != undefined && $("#code").val() != "undefined" && $("#code").val() != "") {
			cp = encodeURIComponent($("#code").val());
		}
		var city = "";
		if ($("#city") != null && $("#city").val() != undefined && $("#city").val() != "undefined" && $("#city").val() != "") {
			city = encodeURIComponent($("#city").val());
		}
		var province = "";
		if ($("#province") != null && $("#province").val() != undefined && $("#province").val() != "undefined" && $("#province").val() != "") {
			province = encodeURIComponent($("#province").val());
		}
		var provinceId = 0;
		if ($("#provinceId") != null && $("#provinceId").val() != undefined && $("#provinceId").val() != "undefined" && $("#provinceId").val() != "" && parseInt($("#provinceId").val()) != NaN) {
			provinceId = parseInt($("#provinceId").val());
		}
		var country = 53;
		if ($("#country") != null && $("#country").val() != undefined && $("#country").val() != "undefined" && $("#country").val() != "" && parseInt($("#country").val()) != NaN) {
			country = parseInt($("#country").val());
		}
		
		params += "id=" + id;
		params += "&address=" + address;
		params += "&cp=" + cp;
		params += "&city=" + city;
		params += "&province=" + province;
		params += "&provinceId=" + provinceId;
		params += "&country=" + country;
		
		$(".shoppingcartlayer2 .cancelsaveaddress").after(_loading);
		$.ajax({
			type: "POST",
			url: url,
			data: params,
			success: function(data) {
				var result = data.split("|");
				$("IMG.loading").remove();
				$("SPAN.error").remove();
				if (result[0] == "0") {
					$(".shoppingcartlayer2 .changeshippingaddress").show();
					$(".shoppingcartlayer2 .shippingdatalayer .promotionalcode").show();
					$(".shoppingcartlayer2 .modificar").show();
					$(".shoppingcartlayer2 .confirm").show();
					$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #name").show();
					$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #name").prev().show();
					$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #phone").show();
					$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #phone").prev().show();
					$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #comentarios").show();
					$(".shoppingcartlayer2 .shippingdatalayer .shippingdata #comentarios").prev().show();
					$(".shoppingcartlayer2 .saveaddress").hide();
					$(".shoppingcartlayer2 .cancelsaveaddress").hide();
					
					if (id == 0) {
						libackground = "";
						if (($(".shoppingcartlayer2 UL.customeraddress LI").size() + 1) % 2 != 0) {
							libackground = "style=\"background-color:#DDD; border:0px;\"";
						}
						licontent = "<li id=\"customeraddress_" + result[1] + "\" " + libackground + ">";
							licontent += '<a href="javascript:void(null)" class="edit" title="Editar" style="margin-left:0px;"><img src="images/cart-edit.png" alt="Editar"></a>';
							licontent += '<a href="javascript:void(null)" class="delete" title="Borrar"><img src="images/cart-delete.png" alt="Borrar"></a>';
							licontent += '<a href="javascript:void(null)" class="load" title="Cargar">' + $("#address").val() + '</a>';
						licontent += "</li>";
						$(".shoppingcartlayer2 UL.customeraddress").append(licontent);
						LoadCustomerAddressEvents();
					}
					else {
						$("#customeraddress_" + id).find("A.load").html($("#address").val());
					}
				}
				else {
					$(".shoppingcartlayer2 .cancelsaveaddress").after("<span class=\"error\">" + result[1] + "</span>");
				}
			}
		});
	});
}

/****************************************************************
/ Nombre: 		AddCustomerAddress
/ Implentacion: Jordi Darijo
/ Revision: 	24/08/2011
/ Descripcion: 	Carga los eventos de las direcciones de los clientes
'***************************************************************/
function LoadCustomerAddressEvents() {
	$(".changeshippingaddress .add").unbind("click");
	$(".changeshippingaddress .add").click(function () {
		AddCustomerAddress(0);
	});
	
	$(".changeshippingaddress .edit").unbind("click");
	$(".changeshippingaddress .edit").click(function () {
		var aux = $(this).parent().attr("id").split("_");
		id = aux[1];
		LoadShippingAddress(id, true);
	});
	
	$(".changeshippingaddress .delete").unbind("click");
	$(".changeshippingaddress .delete").click(function () {
		var aux = $(this).parent().attr("id").split("_");
		id = aux[1];
		DeleteShippingAddress(id);
	});
	
	$(".changeshippingaddress .load").unbind("click");
	$(".changeshippingaddress .load").click(function () {
		var aux = $(this).parent().attr("id").split("_");
		id = aux[1];
		LoadShippingAddress(id, false);
	});
}

/****************************************************************
/ Nombre: 		ConfirmOrder
/ Implentacion: Fran Soriano
/ Revision: 	24/08/2011
/ Descripcion: 	Carga los eventos de las direcciones de los clientes
'***************************************************************/
function InsertOrder() {
	var params = "";
	
	params += "orderHtml=" + encodeURIComponent($(".shoppingcartlayer3").html());
	params += "&address=" + encodeURIComponent($("#address").val());	
	params += "&city=" + encodeURIComponent($("#city").val());
	params += "&province=" + encodeURIComponent($("DIV.shippingdata EM.province").html());
	//params += "&provinceId=" + encodeURIComponent($("#provinceId").val());
	params += "&country=" + encodeURIComponent($("#country").val());
	params += "&postalCode=" + encodeURIComponent($("#code").val());
	params += "&comments=" + encodeURIComponent($("DIV.shippingdata EM.comments").html());
	params += "&price=" + encodeURIComponent($("#totalproducts").val());
	params += "&portes=" + encodeURIComponent($("#costes").val());
	params += "&totalprice=" + encodeURIComponent($("#totaliva").val());
	params += "&deliveryname=" + encodeURIComponent($("#name").val());
	params += "&deliveryphone=" + encodeURIComponent($("#phone").val());
	
	$.ajax({
		type: "POST",
		url: "AjaxResponse/shop/ConfirmOrder_ajax.asp",
		data: params,
		success: function(data) {
			if ($("#payorder").attr("checked")) {
				$("#tpvrasan").html(data);
				$("#tpvrasan #payordertpv").submit();
			}
			else {
				var destination = "index.asp?pagina=mycart";
				var load 		= "../templates/alert.html";
				
				//e.preventDefault();
				$('body').append('<div id="overlay" />');
				$('#overlay').css("height", $('body').outerHeight() + "px");
				$('#overlay').fadeIn(300, function() {
					$('body').append('<div id="alertModalOuter"><div id="alertModal"></div></div>');
					var outer = $('#alertModalOuter');
					var modal = $('#alertModal');
					var defWidth = outer.outerWidth();
					var defHeight = outer.outerHeight();
					
					var alertBoxContent = $('#alert');
					var alertWidth 		= alertBoxContent.outerWidth();
					var alertHeight 	= alertBoxContent.outerHeight();
					var widthCombine 	= -((defWidth + alertWidth) / 2);
					var heightCombine 	= -((defHeight + alertHeight) / 2);

					$("#alertModal").html(alertBoxContent)
					
					modal.animate({width: alertWidth, height: alertHeight}, 200);
					outer.animate({marginLeft: widthCombine, marginTop: heightCombine}, 200, function() {
						alertBoxContent.fadeIn(200, function() {
							$('#yes').click(function(e) {
								e.preventDefault();
								window.location.href = destination;
							});
							$('#no').click(function(e) {
								e.preventDefault();
								$('#overlay, #alertModalOuter').fadeOut(400, function() {
									$(this).remove();
								});
							});
						});
					});
				});
				//document.location = "index.asp?pagina=mycart";
			}
		} 
	});
}

/****************************************************************
/ Nombre: 		ChangeImage
/ Implentacion: Fran Soriano
/ Revision: 	24/08/2011
/ Descripcion: 	Cambia la imagen principal del producto.
'***************************************************************/
function ChangeImage(obj, color) {
	var pathnew 			= obj.attr("name");
	var pathold 			= $("IMG.imagengrande").attr("name");
	var ajustaimagengrande 	= "appFunctions/FitImage.php?w=253&h=339&p=";
	var ajustaimagenpeque 	= "appFunctions/FitImage.php?w=64&h=60&p=";
	
	$("IMG.imagengrande").attr("name", pathnew);
	$("IMG.imagengrande").attr("src", pathnew);
	$("IMG.imagengrande").parent().attr("href", pathnew);
	
	$("DIV.miniaturas A").attr("rel", "fancybox");
	obj.attr("rel", "");
	//obj.attr("name", pathold);
	//obj.find("IMG").attr("src", pathold);
	//obj.attr("href", pathold);
	
	$(".productselector #color").val(color);
	$(".productselector #color").trigger("liszt:updated");
	
	return false;
}


/****************************************************************
/ Nombre: 		ChangeYearNews
/ Implentacion: Víctor Arroyo
/ Revision: 	13/09/2011
/ Descripcion: 	Cambia las noticias de la seccion de empresa
'***************************************************************/
function ChangeYearNews(sub,year,obj) {
	$.ajax({
		type: "POST",
		url: "AjaxResponse/empresa_ajax.asp",
		data: "subpagina=" + sub + "&year=" + year,
		success: function(data){
			var result = data.split("|");
			$("DIV.carruselFotoAmpliada").html(result[0]);
			$("DIV.contenidoNoticia").html(result[1]);
			$("DIV.year").html(result[2])
			if(result[3] > 1) {
				$("DIV.flechaNoticia A").show();
			}
			else {
				$("DIV.flechaNoticia A").hide();
			}
			$('.textoNoticia').jScrollPane();
			$("DIV.fichaYear.yearSelected A").append("<div class=\"layerNoSelected\"></div>")
			$("DIV.fichaYear.yearSelected").removeClass("yearSelected");
			$(obj).parent().addClass("yearSelected");
			$("DIV.layerNoSelected",obj).remove();
			$(".contenidoNoticia").carouFredSel({
				items : 1,
				auto : false,
				prev : ".flechaNoticiaPrevious",
				next : ".flechaNoticiaNext"
			});
			$(".carruselFotoAmpliada").carouFredSel({
				items : 1,
				auto : false,
				prev : ".flechaNoticiaPrevious",
				next : ".flechaNoticiaNext"
			});
		}
	});
}
