jQuery(document).ajaxError(function(e, xhr, settings, exception) {
	alert(xhr.responseText );
});
	
jQuery(document).ready(function (){
	jQuery(":input[name^='query']").keyup(function (){
		//var resultados =  jQuery('#muestra_search_ajax').html();
		if(jQuery(":input[name^='query']").val().length==1){
			if(jQuery("#busquedasinprevio").val()!="1"){
				jQuery('#muestra_search_ajax').html("<table width='400' style='background-color:#FFFFFF; border: 1px solid #999999; z-index:1; text-align:center;'><tr><td style='padding:8px;'><img src='/img/general/cargando.gif' align='absmiddle' /></td></tr></table>")
			}
		} else if(jQuery(":input[name^='query']").val().length<1) {
			jQuery('#muestra_search_ajax').css("display", "none");
		}
		var valor = jQuery(":input[name^='query']").val();
		jQuery.get("/includes/ajax/busqueda_inteligente.asp?id="+valor, {biplantilla: jQuery("#buscaquedaplantilla").val(), bihplantilla: jQuery("#buscaquedahayplantilla").val(), idfam: jQuery("#busquedafiltrofamilia").val(), idsubfam: jQuery("#busquedafiltrosubfamilia").val(), limite: jQuery("#busquedalimiteresultados").val(), comprables: jQuery("#busquedacomprables").val()}, function(data){ 
			if(data!="KO" && jQuery(":input[name^='query']").val().length>0){
				jQuery('#muestra_search_ajax').html(data);
				if(jQuery('#muestra_search_ajax').css("display")=="none"){
					jQuery("#muestra_search_ajax").fadeIn(500);
				}
			}
		});
	});
});


var peticions = false; 
var  testPasados = false; 
try { 
  peticions = new XMLHttpRequest(); 
  } catch (trymicrosoft) { 
  try { 
  peticions = new ActiveXObject("Msxml2.XMLHTTP"); 
  } catch (othermicrosoft) { 
  try { 
  peticions = new ActiveXObject("Microsoft.XMLHTTP"); 
  } catch (failed) { 
  peticions = false; 
  } 
  } 
} 
if (!peticions) 
alert("¡ERROR AL INICIALIZAR AJAX!"); 

function replace(texto,s1,s2){
	return texto.split(s1).join(s2);
}

function ejecutacarac(urlactual){
	valores = "";
	valoresc = "";
	// Recorremos los combos
	jQuery("select[name=combocarac] option:selected").each(function (index) {
		if(jQuery(this).val()!="0"){
			valores = valores+"&carac"+jQuery(this).val()+"=1";
			if(valoresc==""){
				valoresc = jQuery(this).val();
			} else {
				valoresc = valoresc+","+jQuery(this).val();
			}
		}
	});
	
	// Recorremos los checkbox
	jQuery("input:checkbox[name=checkcarac]:checked").each(function (index) {
		valores = valores+"&carac"+jQuery(this).val()+"=1";
		if(valoresc==""){
			valoresc = jQuery(this).val();
		} else {
			valoresc = valoresc+","+jQuery(this).val();
		}
	});
	if(valores!=""){
		if(Right(urlactual,1)=="/" || Right(urlactual,1)=="&"){
			urlactual = urlactual.substring(0,urlactual.length-1);
		}
		window.location=urlactual+"&carac="+valoresc+valores;
	} else {
		window.location=urlactual;
	}
}

//Típica Right para js
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);
	}
}

//Típica Left para js
function Left(str, n){
	if (n <= 0)
		return "";
	else if (n > String(str).length)
		return str;
	else
		return String(str).substring(0,n);
}

function validarnumerosjq(campo){
	if (IsNumeric(jQuery("#"+campo).val())==false) {
		jQuery("#"+campo).val("1");
	}
}

function calculadora_cofidis(pvp, partner, producto, cuotas){
  	pvp = pvp.replace(".","");
	pvp = pvp.replace(" ","");
	pvpn = pvp.replace(",",".");
	window.open("https://www.cofidisonline.cofidis.es/FinanciacionEstandar/calcular?importe="+pvpn+"&partner="+partner+"&producto="+producto+"&num_cuotas="+cuotas,null,"toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=368,height=550,left = 0,top = 0");
}

// Comprueba que un valor sea numérico.
function IsNumeric(sText)
{
	var ValidChars = "0123456789";
	var IsNumber=true;
	var Char;
	
	for (bucleiIsNumeric = 0; bucleiIsNumeric < sText.length && IsNumber == true; bucleiIsNumeric++) 
	  { 
	  Char = sText.charAt(bucleiIsNumeric); 
	  if (ValidChars.indexOf(Char) == -1) 
		 {
		 IsNumber = false;
		 }
	  }
	return IsNumber;
}

function abrirventana(ruta, ancho, alto, barras){
	var posicion_x; 
	var posicion_y; 
	posicion_x=(screen.width/2)-(ancho/2); 
	posicion_y=(screen.height/2)-(alto/2);
	var parametros = "width="+ancho+",height="+alto+",scrollbars="+barras+",status=no,location=no,toolbar=0,left="+posicion_x+"top="+posicion_y;
	window.open(ruta,'ventana',parametros,'');
}

function cargayoutube(id, divdatos){
	var fragment_url = '/includes/ajax/apic.asp?clase=youtube&id='+id; 
	//abrimos la url 
	peticions.open("GET", fragment_url); 
	peticions.onreadystatechange = function() { 
		if (peticions.readyState == 4) { 
		//escribimos la respuesta 
		//alert(unescape(peticions.responseText)); 
			if(unescape(peticions.responseText)!=""){
				document.getElementById(divdatos).value = unescape(peticions.responseText); 
			} else {
				document.getElementById(divdatos).value = "";
			}
		} 
	} 
   peticions.send(null);
}

function insertarcarro(errormsg){
	if(jQuery("#cunidades").length>0 && jQuery("#cunidades").val()!="" && IsNumeric(jQuery("#cunidades").val())){
		jQuery("#chunidades").val(jQuery("#cunidades").val());
	}
	
	var pasamos = true;
	
	// Comprobamos que no exista ningún combo de atributos sin seleccionar
	jQuery(":input[name^='#Atrib#']").each(function(){
		var comboactivo = jQuery(this);
		if(comboactivo.val()!="" && comboactivo.val()!=undefined){
			var datos = comboactivo.val().split("[SEPA]");
			if(datos[0]=="0" && datos[5]=="No"){ // Si es igual que cero, buscamos si tiene opción ninguno, sino, no se deja pasar
				// Antes verificamos que no estén todos desactivados
				var cuenta = 0;
				comboactivo.find('option').each(function() {
					var datos1 = jQuery(this).val().split("[SEPA]");  
					if(datos1[0]!="0"){
						if(jQuery(this).prop("disabled")==false){
							cuenta++;
						}
					}
				});
				if(cuenta>0){pasamos = false;}
			}
		}
	});
	if(pasamos==true){
		return true;
	} else {
		alert(errormsg);
		return false;
	}
}


// Recalculamos los atributos
function recalcularatributos_front(){
	var total = 0;
	var totaliva = 0;
	var precioart = 0;
	var iva = 0;
	var simbolo = "";
	var temporal = "";
	jQuery(":input[name^='#Atrib#']").each(function(){
		var comboactivo = jQuery(this);
		if(comboactivo.val()!="" && comboactivo.val()!=undefined){
			var datos = comboactivo.val().split("[SEPA]");
			if(datos[1]!="escoge"){
				total += parseFloat(datos[1]);
			}
			if(datos[1]!="escoge" && datos[1]!="0"){
				jQuery(".textostockf").html(datos[7]);
				jQuery(".textounidadesf").html(datos[8]);
				jQuery(".imagenstockf").removeAttr("src");
				switch(datos[6]){
					case "1": {jQuery(".imagenstockf").attr("src","img/stock-ok.gif"); break;}
					case "2": {jQuery(".imagenstockf").attr("src","img/stock-query.gif"); break;}
					case "3": {jQuery(".imagenstockf").attr("src","img/stock-ko.gif"); break;}
					case "4": {jQuery(".imagenstockf").attr("src","img/stock-ok4.gif"); break;}
					case "5": {jQuery(".imagenstockf").attr("src","img/stock-ok5.gif"); break;}
				}
				
			}
			iva = parseFloat(datos[2]);
			precioart = parseFloat(datos[3]);
			simbolo = datos[4];
		}
	});
	total += parseFloat(precioart);
	total=roundNumber(total,3);
	totaliva=((total*(100+iva))/100);
	totaliva=roundNumber(totaliva,2);
	total=total+'';
	totaliva=totaliva+'';
	jQuery(".lzr_preciofichasart").html(replace(total,".",",")+" "+simbolo);
	jQuery(".lzr_preciofichasart_iva").html(replace(totaliva,".",",")+" "+simbolo);
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

// Comprobamos los atributos encadenados
function compruebaplus(valor, seccion){
	if(valor!="{0};0"){
		// Comenzamos el cálculo de atributos encadenados
		var fragment_url = '/includes/ajax/apic.asp?clase=atributosplus&id='+valor; 
		//abrimos la url 
		peticions.open("GET", fragment_url); 
		peticions.onreadystatechange = function() { 
			if (peticions.readyState == 4) { 
			//escribimos la respuesta 
			//alert(unescape(peticions.responseText)); 
				if(unescape(peticions.responseText)!=""){
					document.getElementById(seccion).innerHTML = unescape(peticions.responseText); 
				} else {
					document.getElementById(seccion).innerHTML = "";
				}
			} 
		} 
	   peticions.send(null);
	} else {
		document.getElementById(seccion).innerHTML = "";
	}
}

// Esta función comprueba que se hayan seleccionado todos los atributos
function compruebatipos(errormsg){
	seleccionados = 0;
	formcomprar1 = document.getElementById("formcomprarid");
	for(i=0;i<formcomprar1.elements.length;i++) {
		var elemento = formcomprar1.elements[i];
		if(elemento.type == "radio") {
			if(elemento.checked) {
				if(elemento.value == "{0};0") {
					seleccionados += 1;
				}
			}
		}
		if(elemento.type == "select-one") {
			if(elemento.value == "{0};0") {
				seleccionados += 1;
			}
		}
	}
	
	if(seleccionados > 0) {
		alert(errormsg);
		return false;
	} else {
		return true;
	}
}

function copiarcampos()
{
	document.formregistro.flogin_contacto.value=document.formregistro.flogin_nombre.value + ' ' + document.formregistro.flogin_apellidos.value;
	document.formregistro.flogin_direccionenvio.value=document.formregistro.flogin_direccion.value;
	document.formregistro.flogin_poblacionenvio.value=document.formregistro.flogin_poblacion.value;
	document.formregistro.flogin_provinciaenvio.value=document.formregistro.flogin_provincia.value;
	document.formregistro.flogin_cpenvio.value=document.formregistro.flogin_cp.value;
	document.formregistro.flogin_telefonoenvio.value=document.formregistro.flogin_telefono.value;
	document.formregistro.flogin_paisenvio.value=document.formregistro.flogin_pais.value;
}

function validanuevadireccion(mensaje){
	if (document.formregistro.nombredireccion.value == '' || document.formregistro.flogin_contacto.value == '' || document.formregistro.flogin_direccionenvio.value == '' || document.formregistro.flogin_poblacionenvio.value == '' || document.formregistro.flogin_provinciaenvio.value == '' || document.formregistro.flogin_cpenvio.value == '' || document.formregistro.flogin_telefonoenvio.value == '' || document.formregistro.flogin_pais.value == '(0)') {
		alert(mensaje);
		return false;
	}
}

function Calculadora_Cofidis(pvp, partner, producto, cuotas){
  	pvp = pvp.replace('.','');
	pvp = pvp.replace(' ?','');
	pvpn = pvp.replace(',','.');
window.open('https://www.cofidisonline.cofidis.es/FinanciacionEstandar/calcular?importe='+pvpn+'&partner='+partner+'&producto='+producto+'&num_cuotas='+cuotas+'',null,'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=368,height=550,left = 0,top = 0');
};

function ValidaCamposR(valores, msgerror){
	//Realiamos el bucle
	var validador = true;
	valores = valores.split("|");
	for(var i=0;i<valores.length;i++){
		if(document.getElementById(valores[i]).value==""){
			validador = false;
		}
	}
	if(validador==true){
		return true;
	} else {
		alert(msgerror);
		return false;
	}
}

function comprobarnickforo(idinput, divtemporal){
	var tempdiv = jQuery("#"+divtemporal).html();
	jQuery("#"+divtemporal).html("<img src='/img/general/loading.gif' align='absmiddle'>");
	jQuery.get("/index.asp?mod=f_foro&op=cnick&nick="+jQuery("#"+idinput).val(), {}, function(data){ 
		if(data=="KO" || jQuery("#"+idinput).val()==""){
			jQuery("#"+idinput).css('background-color','#900');
			jQuery("#"+idinput).css('color','#FFF');
		} else {
			jQuery("#"+idinput).css('background-color','#060');
			jQuery("#"+idinput).css('color','#FFF');
		}
		jQuery("#"+divtemporal).html(tempdiv);
	});
}

function veravatarforo(valor){
	if(valor=="0"){
		jQuery("#foro_select_avatar_div").html("");
	} else {
		jQuery.get("/index.asp?mod=f_foro&op=avatar&folder="+valor, {}, function(data){ 
			jQuery("#foro_select_avatar_div").html(data);
		});
	}
}

function cambiarmsgforo(idforo, idmsg){
	if(idforo!="0"){
		jQuery.post("/index.asp?mod=f_foro&op=cambiarmsgforo", {idforo: idforo, idmsg: idmsg}, function(data){ 
			location.reload(true);
		});
	}
}





