//<![CDATA[

//Ajax object
var query = false;

try 
{
      query = new XMLHttpRequest();
} 
catch (trymicrosoft) 
{
	try 
	{
		query = new ActiveXObject("Msxml2.XMLHTTP");
	} 
	catch (othermicrosoft) 
	{
		try 
		{
			query = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch (failed) 
		{
			query = false;
		} 
	}
}

function ajaxGet(url,div,object_id)
{
	document.getElementById(div).innerHTML = '<label style="text-transform:lowercase;">Cargando...</label>';
	
	query.open("POST", url, true);
	query.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	
	id=document.getElementById(object_id).options[document.getElementById(object_id).selectedIndex].value;	

	form_string="id="+id;

	query.onreadystatechange = function () {
		if (query.readyState == 4) 
		{
			document.getElementById(div).innerHTML = query.responseText;
		}
	}
	
	query.send(form_string);
}

function checkAccessData(url)
{
	alerta=document.getElementById('access_data_msg');
	alerta.innerHTML="Comprobando...";
	alerta.style.display="block";
	
	query.open("POST", url, true);
	query.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	
	username=document.getElementById('username').value;
	password=document.getElementById('password').value;

	form_string="username="+username+"&password="+password;

	query.onreadystatechange = function () {
		if (query.readyState == 4) 
		{
			if(query.responseText=="ok")
			{
				//Recargamos la página 
				document.location=document.location;
			}
			else
			{
				alerta.innerHTML="Datos de acceso incorrectos";
			}
		}
	}
	
	query.send(form_string);
	return false;
}

function suscribeNewsletter(url)
{
	alerta=document.getElementById('newsletter_data_msg');
	alerta.innerHTML="Enviando...";
	alerta.style.display="block";
	
	query.open("POST", url, true);
	query.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	
	email=document.getElementById('email').value;

	form_string="email="+email;

	query.onreadystatechange = function () {
		if (query.readyState == 4) 
		{
			if(query.responseText=="ok")
			{
				alerta.innerHTML="¡Suscripción realizada!";
			}
			else
			{
				if(query.responseText=="ko")
				{	
					alerta.innerHTML="E-mail incorrecto";
				}
				else
				{
					alerta.innerHTML="E-mail ya registrado";
				}	
			}
		}
	}
	
	query.send(form_string);
	return false;
}

function comprobar_login(url)
{
	login=document.getElementById('login').value;
	document.getElementById('check_login_msg').innerHTML="Comprobando nombre de usuario...";

	cadena = new String(login);
	
	if(cadena.length<3 || cadena.length>100)
	{
		document.getElementById('check_login_msg').innerHTML="Mínimo 3 carácteres";
		document.getElementById('login').style.border="1px #ff0000 solid";
		document.getElementById('login').style.color="#ff0000";
	}
	else
	{	
		query.open("POST", url, true);
		query.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		
		form_string="login="+login;

		query.onreadystatechange = function () {
			if (query.readyState == 4) 
			{
				if(query.responseText=="ok")
				{
					//El login esta dispobible
					document.getElementById('check_login_msg').innerHTML="Nombre de usuario válido";
					document.getElementById('login').style.border="1px #00bb00 solid";
					document.getElementById('login').style.color="#00bb00";
				}
				else
				{
					document.getElementById('check_login_msg').innerHTML="Nombre de usuario no disponible";
					document.getElementById('login').style.border="1px #ff0000 solid";
					document.getElementById('login').style.color="#ff0000";
				}
			}
		}
		
		query.send(form_string);
	}
}

function aplicar_pronto_pago(aplicar)
{
	if(aplicar==1)
	{
		document.getElementById('descuento_pronto_pago').style.display='';
		document.getElementById('total_acumulado_value').innerHTML=document.getElementById('total_acumulado_h').value;
		document.getElementById('total_value').innerHTML=document.getElementById('total_h').value;
		document.getElementById('iva_value').innerHTML=document.getElementById('iva_h').value;
		document.getElementById('descuento2').innerHTML='-'+document.getElementById('descuento_web_h').value+' €';
	}
	else
	{
		document.getElementById('descuento_pronto_pago').style.display='none';
		document.getElementById('total_acumulado_value').innerHTML=document.getElementById('total_acumulado_sin_pronto_pago_h').value;
		document.getElementById('total_value').innerHTML=document.getElementById('total_sin_pronto_pago_h').value;
		document.getElementById('iva_value').innerHTML=document.getElementById('iva_sin_pronto_pago_h').value;
		document.getElementById('descuento2').innerHTML='-'+document.getElementById('descuento_web_sin_pronto_pago_h').value + ' €';
	}	
}

function actualizar_pedido_pre(lineas, url, url_envio, url_eliminar,tipo_cliente)
{
	//Actualizamos el pedido
	var Formulario = document.getElementById('cesta');
        var longitudFormulario = Formulario.elements.length;
        var cadenaFormulario = "";
        var sepCampos;
        sepCampos = "";
        for (var i=0; i <= Formulario.elements.length-1;i++) 
	{
        	cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+encodeURI(Formulario.elements[i].value);
         	sepCampos="&";
	}		
		
	query.open("POST", url, true);
	query.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		
	query.onreadystatechange = function () {
		if (query.readyState == 4) 
		{
			//Recuperamos el precio de envio
			query.open("POST", url_envio, true);
			query.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
				
			query.onreadystatechange = function () {
				if (query.readyState == 4) 
				{
					//Recuperamos el precio de envio
					gastos_envio=query.responseText;
					gastos_envio_formateado=Math.round(gastos_envio*100)/100;
					gastos_envio_formateado=gastos_envio_formateado.toFixed(2);
					gastos_envio_formateado=gastos_envio_formateado.split(".").join(",");
					document.getElementById('gastos_envio').value=gastos_envio;
					document.getElementById('gastos_envio_span').innerHTML=gastos_envio_formateado+" €";

					//Actualizamos la parte visible del pedido
					actualizar_pedido(lineas, url, url_eliminar,tipo_cliente)
				}
			}
				
			query.send('');
		}
	}
		
	query.send(cadenaFormulario);
}

function actualizar_pedido(lineas, url, url_eliminar,tipo_cliente)
{
	total_acumulado=0;
	items=0;
	
	if(url_eliminar=="")
	{
		document.getElementById('chivato_pedido').innerHTML='Actualizando el pedido...';
	}

	for(x=0;x<lineas;x++)
	{
		//Unidades: debe se un entero
		unidades_string=document.getElementById('unidades'+x).value;
		u = new String(unidades_string);
		
		aux=u.split(",");
		u=aux.join(".");
		
		unidades=parseInt(u);
		if (isNaN(unidades))
		{
			unidades=0;
		}
		
		if(unidades_string!="") document.getElementById('unidades'+x).value=unidades;
		//Fin tratamiento unidades
			

		precio_unidad=document.getElementById('precio_unidad'+x).value;
	
		//Total línea	
		total_linea=unidades*precio_unidad;
		total_linea_formateado=Math.round(total_linea*100)/100;
		
		aux=total_linea_formateado.toFixed(2);
		auxs= new String(aux);
		auxv=aux.split('.');
		
		document.getElementById('subtotal'+x+'_value').innerHTML=auxv.join(',');
		//Fin total línea
		
		items=items+unidades;
		total_acumulado=total_acumulado+total_linea;
	}
	
	gastos_envio=document.getElementById('gastos_envio').value;
	
	total_acumulado_formateado_sin_iva=Math.round(total_acumulado*100)/100;
	total_acumulado_formateado_sin_iva_con_descuento=Math.round(total_acumulado*100)/100;

	//Total acumulado
	//Cliente profesional 2% descuento por web
	descuento2=Math.round(total_acumulado*0.02*100)/100;
	if(tipo_cliente>=0) 
	{
		total_acumulado_formateado_sin_iva=Math.round(total_acumulado*100)/100;
		
		if(tipo_cliente>1) 
		{
			total_acumulado=total_acumulado-descuento2;
		}
		total_acumulado_formateado_sin_iva_con_descuento=Math.round(total_acumulado*100)/100;
		total_acumulado=total_acumulado*1.18;
	}

	total_acumulado_formateado=Math.round(total_acumulado*100)/100;
	
	aux=total_acumulado_formateado.toFixed(2);
	auxs= new String(aux);
	auxv=aux.split('.');

	aux_sin_iva=total_acumulado_formateado_sin_iva.toFixed(2);
	auxs_sin_iva= new String(aux_sin_iva);
	auxv_sin_iva=aux_sin_iva.split('.');

	aux_sin_iva_con_descuento=total_acumulado_formateado_sin_iva_con_descuento.toFixed(2);
	auxs_sin_iva_con_descuento= new String(aux_sin_iva_con_descuento);
	auxv_sin_iva_con_descuento=aux_sin_iva_con_descuento.split('.');


	document.getElementById('total_acumulado_value').innerHTML=auxv_sin_iva_con_descuento.join(",");
	document.getElementById('resumen_usuario_precio').innerHTML=auxv_sin_iva.join(",");
	//Fin total acumulado

	//Total
	if(tipo_cliente>=0)
	{
		//Profesional: añadimos el IVA al total
		total=parseFloat(total_acumulado)+parseFloat(gastos_envio);
		//También tenemos que actualizar el IVA
		iva=parseFloat(total_acumulado_formateado_sin_iva_con_descuento)*0.18;
		iva_formateado=Math.round(iva*100)/100;
		aux=iva_formateado.toFixed(2);
		auxs= new String(aux);
		auxv=aux.split('.');
		document.getElementById('iva_value').innerHTML=auxv.join(",");
		
		//También tenemos que actualizar el descuento 2%
		descuento2=parseFloat(descuento2);
		descuento2_formateado=Math.round(descuento2*100)/100;
		aux=descuento2_formateado.toFixed(2);
		auxs= new String(aux);
		auxv=aux.split('.');

		if(tipo_cliente>1) { 
			document.getElementById('descuento2_value').innerHTML=auxv.join(",");
		}
	}
	else
	{
		total=parseFloat(total_acumulado)+parseFloat(gastos_envio);
	}
	
	total_formateado=Math.round(total*100)/100;
	aux=total_formateado.toFixed(2);
	auxs= new String(aux);
	auxv=aux.split('.');
	document.getElementById('total_value').innerHTML=auxv.join(",");
	//Fin total

	document.getElementById('resumen_usuario_items').innerHTML=items+' items';	

	//Ya hemos actualizado la vista, usamos ajax ahora para modificar realmente el pedido
	var Formulario = document.getElementById('cesta');
        var longitudFormulario = Formulario.elements.length;
        var cadenaFormulario = "";
        var sepCampos;
        sepCampos = "";
        for (var i=0; i <= Formulario.elements.length-1;i++) 
	{
        	cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+encodeURI(Formulario.elements[i].value);
         	sepCampos="&";
	}		
		
	query.open("POST", url, true);
	query.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		
	query.onreadystatechange = function () {
		if (query.readyState == 4) 
		{
			document.getElementById('chivato_pedido').innerHTML='&nbsp;';
		
			if(url_eliminar!='')
			{
				document.location=url_eliminar;
			}
		}
	}
		
	query.send(cadenaFormulario);
}

function eliminar(lineas, linea, url, url_envio, url_eliminar)
{
	document.getElementById('chivato_pedido').innerHTML='Eliminando artículo...';
	document.getElementById('unidades'+linea).value=0; //Poniendo a 0 las unidades eliminamos la línea
	actualizar_pedido_pre(lineas,url,url_envio,url_eliminar);
}

function validatePromo(url)
{
	alerta=document.getElementById('promo_msg');
	alerta.innerHTML="Validando...";
	alerta.style.display="block";
	
	query.open("POST", url, true);
	query.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
	
	codigo=document.getElementById('promocion').value;

	form_string="&codigo="+codigo;

	query.onreadystatechange = function () {
		if (query.readyState == 4) 
		{
			if(query.responseText=="ok")
			{
				//Recargamos la página 
				document.location=document.location;
			}
			else
			{
				alerta.innerHTML="Código no válido";
			}
		}
	}
	
	query.send(form_string);
	return false;
}
//]]>
