<!---FUNCIONES PASO2--->

function per_emp(valor){
	var defecto=document.getElementById('titular').value;
	if(valor=='persona' || defecto=='persona')
	{
		document.getElementById('tit').innerHTML='Nombre';
		document.getElementById('doc').innerHTML='NIF / Pasaporte';
		document.getElementById('tit_contact').innerHTML='Contacto';
		document.getElementById('contact').innerHTML="<input type=text name='contacto' id='contacto' size=60>";
	}
	if(valor=='empresa' || defecto=='empresa')
	{
		document.getElementById('tit').innerHTML='Empresa';
		document.getElementById('doc').innerHTML='CIF';
		document.getElementById('tit_contact').innerHTML='';
		document.getElementById('contact').innerHTML='';
	}
}

function validar_paso2(){
	var cp=document.getElementById('cp').value;
	var longcp=cp.length;
	var telefono=document.getElementById('telefono').value;
	var movil=document.getElementById('movil').value;
	var navegador= navigator.appName;
	if(navegador=="Microsoft Internet Explorer")
	{
		var email=form2.email.value;
		var acepto=form2.acepto.value;
	}
	else
	{
		var email=document.getElementById('email').value;
		var acepto=document.getElementById('acepto').value;
	}

	if(document.getElementById('nombre_empresa').value=='')
	{
		alert('Debe introducir un nombre');
		document.getElementById('nombre_empresa').focus();
		return false;
	}
	if(document.getElementById('cif_nif').value=='')
	{
		alert('Debe introducir un cif o nif');
		document.getElementById('cif_nif').focus();
		return false;
	}
	if(document.getElementById('provincia').value=='')
	{
		alert('Debe introducir una provincia');
		document.getElementById('provincia').focus();
		return false;
	}
	if(document.getElementById('poblacion').value=='')
	{
		alert('Debe introducir una población');
		document.getElementById('poblacion').focus();
		return false;
	}
	if(document.getElementById('direccion').value=='')
	{
		alert('Debe introducir una direccion');
		document.getElementById('direccion').focus();
		return false;
	}
	if(isNaN(cp) || cp=='')
	{
		alert('Debe introducir un código postal	');
		document.getElementById('cp').focus();
		return false;
	}
	var tit=document.getElementById('titular').value;
	if(tit=='persona')
	{
		if(document.getElementById('contacto').value=='')
		{
			alert('Debe especificar un contacto');
			document.getElementById('contacto').focus();
			return false;
		}
		document.getElementById('nombre_contacto').value=document.getElementById('contacto').value;
	}
	if(document.getElementById('llamada_telefonica').checked==true)
	{
		if(telefono=='' && movil=='')
		{
			alert('Debe introducir al menos un número de teléfono');
			document.getElementById('telefono').focus();
			return false;
		}
	}
	if(document.getElementById('sms').checked==true)
	{
		if(movil=='')
		{
			alert('Debe introducir su número de móvil');
			document.getElementById('movil').focus();
			return false;
		}
	}

    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)==false){

		alert("La dirección de email es incorrecta.");
		document.getElementById('email').focus();
		return (false);
	}
	if(document.getElementById('acepto').checked==false)
	{
		alert('Debe aceptar las condiciones');
		return false;
	}
	if(document.getElementById('fuera').checked==true)
		document.getElementById('destino_envio').value="fuera";
}

function mostrar_datos_envio(opcion)
{
	if(opcion=='n')
	{
		document.getElementById('nom').style.display="none";
		document.getElementById('prov').style.display="none";
		document.getElementById('pob').style.display="none";
		document.getElementById('dir').style.display="none";
		document.getElementById('cod_pos').style.display="none";
		document.getElementById('nombre_envio').value="";
		document.getElementById('provincia_envio').value="";
		document.getElementById('poblacion_envio').value="";
		document.getElementById('direccion_envio').value="";
		document.getElementById('cp_envio').value="";
	}
	if(opcion=='s')
	{
		document.getElementById('nom').style.display="";
		document.getElementById('prov').style.display="";
		document.getElementById('pob').style.display="";
		document.getElementById('dir').style.display="";
		document.getElementById('cod_pos').style.display="";
	}
}

function mensaje(destino)
{
	if(destino=='fuera')
	{
		alert("Para pedidos a Canarias, Ceuta o Melilla por favor, llame al 902 113 981 y consúltenos");
		document.getElementById('destino_envio').value="fuera";
	}
	if(destino=='peninsula')
	{
		document.getElementById('destino_envio').value="";
	}
}

//-------------------------------------------------------------------------
//					NUEVAS FUNCIONES ( O MODIFICADAS)
//-------------------------------------------------------------------------


//Actualizamos los totales el total con y sin iva
// Si Reembolso!='' entonces sumamos el reembolso
function actualiza_total()
{

	document.getElementById('sumado_contrato_ges').value='no';
	document.getElementById('contrato_ges').value='n';
	document.getElementById('sumado_contrato_conta').value='no';
	document.getElementById('contrato_conta').value='n';

	var total_sin_iva=0; // El total = suma productos + envio + (contrarreembolso si tiene)
	var num_productos=document.getElementById('numero_productos').value;
	for(i=1;i<=num_productos;i++)
	{
		// Valores guardados de precios de los distintos productos
			var precio_ges=document.getElementById('id_precio_ges_'+i).value;

		// Comprobamos si el elemento es la eleccion de contrato (input radio)
		//if(!document.getElementById('ges_'+i)) Esto no lo admite el kkexplorer
		if(i==7 || i==9 || i==11)
		{

			// Si el elemento se encuentra con el valor S, entonces lo sumamos al total

			if(document.getElementById('ges_'+i+'_s').checked)
			{	total_sin_iva=total_sin_iva+(precio_ges*1);
				// Esto es para el paso de parametros (por la version antigua)
				if(i==7)
				{
					document.getElementById('sumado_contrato_ges').value='si';
					document.getElementById('contrato_ges').value='on';
				}
				if(i==9)
				{
					document.getElementById('sumado_contrato_conta').value='si';
					document.getElementById('contrato_conta').value='on';
				}
				if(i==11)
				{
					document.getElementById('sumado_contrato_mobile').value='si';
					document.getElementById('contrato_mobile').value='on';
				}
			}
		}
		else
		{
			//Comprobamos que el dato que se recoge esté o vacio o sea un numero (cantidad de cada producto)
				var num_ges =document.getElementById('ges_'+i).value;

					if(!isNaN(num_ges) && num_ges!='')
						total_sin_iva=total_sin_iva+(precio_ges*num_ges); // Suma de productos
		}

	}
	// Sumamos el reembolso (si lo tiene)
	if(document.getElementById('reembolso').checked)
	{
		var gasto_reembolso=document.getElementById('gasto_reembolso').value;
		total_sin_iva = total_sin_iva+round(gasto_reembolso);

		// Guardamos los gastos para pasarlos al siguiente form
		document.getElementById('precio_reembolso').value=document.getElementById('gasto_reembolso').value;
	}
	else
		document.getElementById('precio_reembolso').value='';

	// Sumamos los gastos de envio
	var envio= document.getElementById('gastos_envio').value;

	
	total_sin_iva=total_sin_iva+round(envio);
	total_sin_iva=round(total_sin_iva);
	var iva = round(total_sin_iva * 0.18);
	var total_mas_iva= 	round(total_sin_iva * 1.18);

	
if (document.getElementById('pais').value == '66')

makeRequest('includes/calcula_total.php?total_sin_iva='+total_sin_iva+'&cupon='+document.getElementById('cupon').value,'capa_resultado_total');

else 

makeRequest('includes/calcula_total_noiva.php?total_sin_iva='+total_sin_iva+'&cupon='+document.getElementById('cupon').value,'capa_resultado_total');

}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

function round(number,X)
{
	// rounds number to X decimal places, defaults to 2
	X = (!X ? 2 : X);
	return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

// deja 2 decimales y los alarga (si no tiene) con los ceros
function decimal_con_ceros(numero)
{
	numero=String(numero);
	var partes_numero=numero.split('.');
		var npartes_numero=partes_numero.length;
		if(npartes_numero==1)
			numero=numero +'.00';
		if(npartes_numero==2)
		{
			decimal_numero=partes_numero[1];
			if(decimal_numero.length==1)
				numero=numero + '0';
		}
return numero;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

function funcion_gasto_envio(pais,gasto_espana,gasto_fuera)
{
	if(pais==66) // España
	{
		document.getElementById('gastos_envio').value=gasto_espana;
	//	document.getElementById('envio1').value=gasto_espana;
	}
	else
	{
		document.getElementById('gastos_envio').value=gasto_fuera;
	//	document.getElementById('envio1').value=gasto_fuera;
	}

//Cambiamos informacion visual en la pagina para el cliente
var precio=document.getElementById('gastos_envio').value;
document.getElementById('capa_envio').innerHTML= precio + ' &euro;';
document.getElementById('precio_envio').innerHTML=decimal_con_ceros(precio);


actualiza_total();
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

function funcion_gasto_reembolso(precio)
{

	precio=decimal_con_ceros(precio);

	if(document.getElementById('reembolso').checked)
	{
		document.getElementById('pvp_reembolso').innerHTML= precio;
	}
	else
		document.getElementById('pvp_reembolso').innerHTML='';

actualiza_total();
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

// Cuando es internacional se retira la opcion de reembolso
function pago_internacional(pais){
	var elemento1=document.getElementById('reembolso');
	var elemento2=document.getElementById('transferencia');
	if(pais==66) //Si es españa se habilita
	{
		elemento1.disabled=false;
		elemento2.disabled=false;
	}
	else		// Se deshabilita
	{
		document.getElementById('tarjeta').checked=true;
		document.getElementById('pvp_reembolso').innerHTML='';
		elemento1.disabled=true;
		elemento2.disabled=true;
	}
actualiza_total();
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------


function makeRequest(url,div)
{
	document.getElementById('control').value = div;

	var n_url = url;
	//document.getElementById(div).innerHTML = '';
	//ventanaCargando();
	document.getElementById(div).style.opacity = 0.4;
	document.getElementById(div).style.filter = "alpha(opacity=40)";

	http_request = false;

        if (window.XMLHttpRequest)
		{ // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType)
			{
                http_request.overrideMimeType('text/xml');
            }
        }
		else if (window.ActiveXObject)
		{ // IE
            try
			{
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e)
			{
                try
				{
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }

        if (!http_request)
		{
            alert('Falla :( No es posible crear una instancia XMLHTTP');
            return false;
        }
        http_request.onreadystatechange = alertContents;
        http_request.open('GET', n_url, true);
        http_request.send(null);
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

function alertContents()
{
	div = document.getElementById('control').value;

	if (http_request.readyState == 4)
	{
   		if (http_request.status == 200)
		{
			document.getElementById(div).style.opacity = "1";
			document.getElementById(div).style.filter = "alpha(opacity=100)";
			document.getElementById(div).innerHTML=http_request.responseText;
    	}
		else
		{
        	alert('Hubo problemas con la petición.');
    	}
	}
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

function ver_foto(imageType,imageName,imageWidth,imageHeight,alt,posLeft,posTop) {  // v4.01
	newWindow = window.open("","newWindow","width="+imageWidth+",height="+imageHeight+",scrollbars=no,left="+posLeft+",top="+posTop);
	newWindow.document.open();
	newWindow.document.write('<html><title>'+alt+'</title><body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginheight="0" marginwidth="0" onBlur="self.close()">');
	if (imageType == "swf"){
	newWindow.document.write('<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0\" width=\"'+imageWidth+'\" height=\"'+imageHeight+'\">');
	newWindow.document.write('<param name=movie value=\"'+imageName+'\"><param name=quality value=high>');
	newWindow.document.write('<embed src=\"'+imageName+'\" quality=high pluginspage=\"http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash\" type=\"application/x-shockwave-flash\" width=\"'+imageWidth+'\" height=\"'+imageHeight+'\">');
	newWindow.document.write('</embed></object>');	}else{
	newWindow.document.write('<img src=\"'+imageName+'\" width='+imageWidth+' height='+imageHeight+' alt=\"'+alt+'\">'); 	}
	newWindow.document.write('</body></html>');
	newWindow.document.close();
	newWindow.focus();
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------

function openWindow(url, name, width, height)
{
     w = width
     h = height
     x = Math.round((screen.availWidth-w)/2); //center the top edge
     y = Math.round((screen.availHeight-h)/2); //center the left edge
     popupWin = window.open(url, name, "width="+w+",height="+h+",scrollbars=no,history=no,toolbar=no,resizable=1,statusbar=yes,top="+y+",left="+x+",screeenY="+y+",screenX="+x);
     popupWin.creator=self
	 popupWin.window.focus();
}

function validar1(){

	if(document.getElementById('aux_total_sin_iva')!=null)
	{
		document.getElementById('total_sin_iva').value=document.getElementById('aux_total_sin_iva').value;
		document.getElementById('total_siva').value=document.getElementById('aux_total_sin_iva').value;
	}

	if(document.getElementById('aux_cupon_descuento')!=null)
			document.getElementById('cupon_descuento').value=document.getElementById('aux_cupon_descuento').value;

	if(document.getElementById('aux_total_con_iva')!=null)
			document.getElementById('total').value=round(document.getElementById('aux_total_con_iva').value);


	var ges=document.getElementById('ges_1').value;
	var ges3=document.getElementById('ges_2').value;
	var ges4=document.getElementById('ges_3').value;
	var ges5=document.getElementById('ges_4').value;
	var ges6=document.getElementById('ges_5').value;
	var ges7=document.getElementById('ges_6').value;
	var ges10=document.getElementById('ges_10').value;
	var conta=document.getElementById('ges_8').value;

	if(ges<0 || ges3<0 || ges4<0 || ges5<0 || ges6<0 || ges7<0 || conta<0 || ges10<0)
	{
		alert('No puede introducir cantidades negativas');
		document.getElementById('ges_1').focus();
		return false;
	}

    if ((isNaN(ges) || ges=='' || ges<=0) && (isNaN(ges3) || ges3=='' || ges3<=0) &&
	(isNaN(ges4) || ges4=='' || ges4<=0) && (isNaN(ges5) || ges5=='' || ges5<=0) &&
	(isNaN(ges6) || ges6=='' || ges6<=0) && (isNaN(ges7) || ges7=='' || ges7<=0) &&
	(isNaN(conta) || conta=='' || conta<=0) && (isNaN(ges10) || ges10=='' || ges10<=0))
	{
		alert('Debe introducir un número');
		document.getElementById('ges_1').focus();
		return false;
    }


}
