//Funcion para envio de formulario, donde form es el atributo name del mismo

function guardar(action, formulario){



	resultado=megavalidacion(formulario);

//	alert('Acabe validacion = '+resultado);

//	resultado=true;

	if (resultado!=false)

	{

		if (formulario=="cuentaform"){

				envia_solicitud(action);

		}

		else if(formulario=="cobform")

		{

		envia_cobertura(action);

		}

		else if(formulario=="promform")

		{

		envia_prom(action);

		}

		else if(formulario=="contacto")

		{

		envia_correo(action);

		}

		else if(formulario=="duda")

		{

		envia_duda(action);

		}

		else if(formulario=="wizardform")

		{

		envia_wiz(action);

		}

		else

		{

			if(document.forms[formulario].TelefonoFijo.value == '' && document.forms[formulario].TelefonoMovil.value == '')

				alert('Debes completar uno de los campos de telefono');

			else

				envia_datos(action);

		}		

		 //setTimeout("cambio_pag('"+dondevoy+"')", 2600);

	}

	else

	{

		alert('Hay datos incorrectos y/o campos obligatorios sin rellenar');

	}

		

	resultado="";

}

function BorrarArchivo(ref, line)

{

  respuesta = document.getElementById('messageform');

  envia('ajax/deletefile.php', 'file='+ref);

  document.getElementById('documents').deleteRow(line);

  respuesta = document.getElementById('uploadform');

  envia('zonausuario/showform.php', '');  

}

function GetAyuda()

{

document.getElementById('operadora').style.display='block';

respuesta = document.getElementById('operadora');

envia('ayuda_contacto.php','status=show');

}

function ShowMessage()

{

respuesta = document.getElementById('operadora');

document.getElementById('operadora').style.display='none';

envia('ayuda_contacto.php','status=hide');

}

function comsubv(lineform)

{

	if(megavalidacion(lineform))

	{

		respuesta = document.getElementById('response');

		envia('ajax/subvencion.php',

		'nombre='+document.subvform.nombre.value+

		'&linea='+document.subvform.linea.value+

		'&email='+document.subvform.email.value+

		'&telefono='+document.subvform.telefono.value);

	}

	else

	{

		alert('Hay datos incorrectos y/o campos obligatorios sin rellenar');

		return false;

	}

}

function comlinea(lineform, adsl)

{

	if(megavalidacion(lineform))

	{
		var nom = document.getElementById('nombre'+adsl).value;
		var lin = document.getElementById('linea'+adsl).value;
		var email = document.getElementById('email'+adsl).value;
		var tel = document.getElementById('telefono'+adsl).value;
		respuesta = document.getElementById('compra');

		envia('ajax/pedidoadsl.php',

		'articulo='+adsl+

		'&nombre='+nom+

		'&linea='+lin+

		'&email='+email+

		'&telefono='+tel);

		return true;

	}

	else

	{

		alert('Hay datos incorrectos y/o campos obligatorios sin rellenar');

		return false;

	}

}

function lineaadsl(adsl)

{

respuesta = document.getElementById('compra');

envia('servicios/agregarform.php','articulo='+adsl);

}

function guardar_t_p_medida(formulario)

{

	resultado=megavalidacion(formulario);



	if (resultado!=false)

	{

		procesar_tpmform();

	}

	else

	{

		alert('Hay datos incorrectos y/o campos obligatorios sin rellenar');

	}

	resutado="";

}

function guardar_empresa(formulario)

{

	resultado=megavalidacion(formulario);



	if (resultado!=false)

	{

		procesar_gran_empresa();

	}

	else

	{

		alert('Hay datos incorrectos y/o campos obligatorios sin rellenar');

	}

	resutado="";

}

function guardar_facturacion(action,formulario)

{

	if(document.forms[formulario].facturacion.checked == true)

		rellenar(0);

		

resultado=megavalidacion(formulario);

//	resultado=true;

	if (resultado!=false){

		if(document.getElementById('TelefonoFijo').value != '' || document.getElementById('TelefonoMovil').value != '') 

			facturacion(action);

		else

		{

			document.getElementById('TelefonoFijo').className='error';	

			document.getElementById('TelefonoMovil').className='error';

		}

			

	}

	else

	{

		alert('Hay datos incorrectos y/o campos obligatorios sin rellenar');

	}

	resutado="";

}



function guardar_facturacion2(action,formulario)

{

	if(document.forms[formulario].facturacion.checked == true)

		rellenar(0);

		

resultado=megavalidacion(formulario);

//	resultado=true;

	if (resultado!=false){

		if(document.getElementById('TelefonoFijo').value != '' || document.getElementById('TelefonoMovil').value != '') 

			facturacion2(action);

		else

		{

			document.getElementById('TelefonoFijo').className='error';	

			document.getElementById('TelefonoMovil').className='error';

		}

			

	}



	else

	{

		alert('Hay datos incorrectos y/o campos obligatorios sin rellenar');

	}

	

	resutado="";

}





var scroll_top = function(){



	if(window.pageYOffset){

		return window.pageYOffset;

	 }

	 else {

		return  Math.max(document.body.scrollTop,document.documentElement.scrollTop);

	 }



}

function compEmail(formulario)

{

	if(formulario.email.value!=formulario.confirmacion.value)

	{

	alert("Los campos de e-mail no coinciden");

	formulario.email.focus();

	formulario.email.select();

	return false;

	}

	else

	{

		return true;

	}

}

function comprobarEmail(formulario)

{

	if(formulario.email.value!=formulario.confirmacion.value)

	{

	alert("Los campos de e-mail no coinciden");

	formulario.email.focus();

	formulario.email.select();

	return false;

	}

	else

	{

		if(formulario.clave.value!=formulario.claveconfirm.value)

		{

		alert("Los campos de clave no coinciden");

		formulario.clave.focus();

		formulario.clave.select();

		return false;

		}

		else{

		return true; 

		}

	}

}

function blanco(){

  this.className="ok";

}



function cambiaImagen(indice, movil){



	document.images["top"].src = arrayImages[indice-1].src;



	var myDiv1=document.getElementById("modseleccionado");



	myDiv1.innerHTML=movil;

}



function rellenar(valor){

	if(valor==0)

	{
	var nomyape_envio = $("#form_nuevo_usuario input[name=nomyape_envio]").val();
	var tipo_via_envio = $("#form_nuevo_usuario select[name=tipo_via_envio]").val();
	var nomvia_envio = $("#form_nuevo_usuario input[name=nomvia_envio]").val();
	var numvia_envio = $("#form_nuevo_usuario input[name=numvia_envio]").val();
	var escalera_envio = $("#form_nuevo_usuario input[name=escalera_envio]").val();
	var cp_envio = $("#form_nuevo_usuario input[name=cp_envio]").val();
	var localidad_envio = $("#form_nuevo_usuario input[name=localidad_envio]").val();
	var provincia_envio = $("#form_nuevo_usuario input[name=provincia_envio]").val();
	
	document.getElementById("nomyape_envio").value=document.getElementById("nomyape").value;

	document.getElementById("tipo_via_envio").selectedIndex=document.getElementById("tipo_via").selectedIndex;	

	document.getElementById("nomvia_envio").value=document.getElementById("nomvia").value;

	document.getElementById("numvia_envio").value=document.getElementById("numvia").value;

	document.getElementById("escalera_envio").value=document.getElementById("escalera").value;

	document.getElementById("cp_envio").value=document.getElementById("cp").value;

	document.getElementById("provincia_envio").value=document.getElementById("provincia").value;

	document.getElementById("localidad_envio").value=document.getElementById("localidad").value;

	document.getElementById("div-datos-envio").style.display = 'none';

	}

	else

	{
	document.getElementById("div-datos-envio").style.display = 'block';

	}

}


//Borra el contenido de formularios que ya tenian contenido inicialmente ("edicion")



function borrar(formulario)

{

campos = document.forms[formulario].elements;



	for (i=0; i<document.forms[formulario].elements.length; i++) 

	{

		objeto = document.forms[formulario].elements[i] ;

		

		if(objeto.value != undefined)

		{	

			if(objeto.tagName == 'select')

				objeto.selectedIndex = 0;

			else if(objeto.type == 'checkbox')

					objeto.checked = "false";

					else

						objeto.value='';

			

		}

	}

}





function buscarrapido(){

document.forms['busqterminales'].submit();

}



		





//Funciones para el comparador de terminales

function comparadorterminales(objeto,refrescar)

{



	if(objeto.tagName == 'INPUT') //agregamos/eliminamos desde el resultado de busqueda

	{	

		if(objeto.checked == true)

			accion = 'agregar';

		else

			accion = 'eliminar';

		

		movil = objeto.value;

		

		respuesta = document.getElementById('semaforo');

		envia('movil/comparador-de-terminales.php','movil='+movil+'&accion='+accion+'&input='+objeto.id+'&refrescar='+refrescar);

	}

	

	if(objeto.tagName == 'A') //eliminamos desde el propio comparador o aÃ±adimos desde ficha

	{	

		if(refrescar == 'si')

		{

			window.scrollTo(0,0);

			respuesta = document.getElementById('contenido');
			
			if(objeto.id.indexOf('mov')!=-1)
			var term = objeto.id.replace("mov","" )
			else 
			var term = objeto.id;

			envia('movil/comparador-de-terminales.php','movil='+objeto.id+'&accion=eliminar&refrescar='+refrescar);		

		}

		

		else

		{
			if(objeto.id.indexOf('mov')!=-1)
			var term = objeto.id.replace("mov","" )
			else 
			var term = objeto.id;
			
			respuesta = document.getElementById('semaforo');

			envia('movil/comparador-de-terminales.php','movil='+term+'&accion=agregar&refrescar='+refrescar);		



		}

	}

	

}



//Refresca el resumen de tu compra ("cesta")

function refrescarresumen()

{		
		$('#cuerpoResumenCompra').load('resumencompra.php');
		//respuesta = document.getElementById('micompra');
		//envia('resumencompra.php','');

}



function valorar(mivaloracion,id)

{

respuesta = document.getElementById('valoracion');

envia('movil/valoracion.php','valoracion='+mivaloracion+'&id='+id);

}

function searchadsl()

{

	var email = document.getElementById('mailadsl').value;



	if( email != '')

    {			

		if(megavalidacion('adslform'))

		{

			showSol(document.getElementById('mailadsl').value)

			
			/*
			respuesta = document.getElementById('adslrespuesta');

			envia('ajax/newsletter.php','linea='+document.getElementById('mailadsl').value);

			return true;
			*/
			

		}

		

		else

			alert('El numero introducido no es valido');

	}

	

	else

		alert('Debes introducir un numero de telefono valido');

}

function showSol(campo)

{

document.getElementById('hiddenline').value=campo	

document.getElementById('line').value=campo

document.getElementById('Asistente').style.display='block'
document.getElementById('Asisback').style.display='block';
return true

}

function AddDatos(que)

{

	respuesta = document.getElementById('adslrespuesta');	

/*

	contact_val=getCheckedValue(document.adslfrm.envio);	

	if(contact_val=='0')

	{	

		envia('ajax/mailadsl.php',

		'coment='+que+

		'&linea='+document.getElementById('hiddenline').value);

		document.getElementById('Asistente').style.display='none'

	}

	else

	{

*/

	if(megavalidacion('adslform'))

		{

		envia('ajax/mailadsl.php',

		'coment='+que+

		'&linea='+document.adslfrm.hiddenline.value+

		'&nombre='+document.adslfrm.nombre.value+

		'&telefono='+document.adslfrm.telefono.value);
		document.getElementById('Asisback').style.display='none';
		document.getElementById('Asistente').style.display='none';

		}		

	//}

}




function boletin()

{

	var email = document.getElementById('mailboletin').value;

	

	if( email != '' && email != 'introduce tu e-mail')

    {			

		if(megavalidacion('boletinform'))

		{

			respuesta = document.getElementById('semaforo');

			envia('boletin.php','mailboletin='+document.getElementById('mailboletin').value);

		}

		

		else

			alert('El e-mail introducido no es valido');

	}

	

	else

		alert('Debes introducir un e-mail valido');

}





//Funcion de busqueda en noticias y reviews

function buscar(criterio,quebusco)

{



	if(criterio == 'palabras')

	{

		if(document.getElementById('palabras').value == '')

			document.getElementById('palabras').value = ' ';

		

		document.getElementById('archivo').selectedIndex = 0;

	}

	else

		document.getElementById('palabras').value = '';

	

	

	if(quebusco == 'noticias')		

		document.forms['noticiasfrm'].submit();	

	else

		document.forms['reviewsfrm'].submit();	

}



//Funcion que muestra vista ampliada foto noticias/reviews

function popup(accion)

{

	if(accion == true)

		document.getElementById("popup").style.display="block";

	

	else

		document.getElementById("popup").style.display="none";

		

}



//Funcion que muestra vista ampliada foto noticias/reviews

function popuppubli(accion)

{

	if(accion == true)

		document.getElementById("popuppublicidad").style.display="block";

	

	else

		document.getElementById("popuppublicidad").style.display="none";

		

}







//Funcion que selecciona automaticamente tipo documento segun tipo cliente

function tipodecliente(tipo)

{

selector = document.getElementById('tipodocumento');

opciones = document.getElementById('tipodocumento').options;



	if(tipo == 'empresa')

	{

		for(opcion in opciones)

		{

			if(opciones[opcion].value == 'C')

				selector.selectedIndex = opcion;

		}

	}		

	

	else

	{

		for(opcion in opciones)

		{

			if(opciones[opcion].value == 'N')

				selector.selectedIndex = opcion;

		}

	}

}



//Funcion para recomendar terminales

function recomendar()

{



	if(megavalidacion('recomendarfrm'))

	{	

		document.getElementById('recomendar').style.display='none';

		urlcod = document.location.href;

		urlcod = urlcod.replace(/&/g,"%");

		respuesta = document.getElementById('semaforo');

		envia('movil/recomendar.php',

		'nombre='+document.getElementById('recomendarfrm').txtnombre.value+

		'&mensaje='+document.getElementById('mensaje').value+

		'&email='+document.getElementById('email').value+

  		'&url='+urlcod);

  		

  		document.forms['recomendarfrm'].reset();

	}

}



function error404()

{

 document.getElementById('contenido').innerHTML = '<div id="error" style="margin: 80px auto;text-align:center;"><img src="images/error404.jpg" /></div>';

}



//Funcion para recordar password cuenta usuario

function recordar()

{

	if(megavalidacion('cuentaform'))

	{

	respuesta = document.getElementById('motor');

	envia('inicio/recordar.php','email='+document.getElementById("email").value);

	}

}



//Funciones para contenedor de carga en procesos AJAX

function aparecer()

{	

	//if(document.getElementById("procesandomsg") == 'undefined' || document.getElementById("procesandomsg").style.display != "block")

	//{

	if(document.getElementById("procesandomsg"))

		document.getElementById("procesandomsg").style.display = "block";

	//document.getElementById("procesando").style.display = "block";

	//fader.fadeIn();

	//}

}



function desvanecer()

{

	document.getElementById("procesandomsg").style.display = "none";

	//fader.fadeOut();

}





//Mostrar tarifas empresa con ancla en ventan nueva

function verTarifas(ancla,segmento)

{

	if(segmento=='empresas')
	ventanaSecundaria('http://192.168.1.252/compratuorange/empresas/tarifas-particular.php'+ancla,700);
	//ventanaSecundaria('http://www.latiendaconexion.com/empresas/tarifas-empresas.php'+ancla,700);

	

	if(segmento=='particular')
	ventanaSecundaria('http://192.168.1.252/compratuorange/movil/tarifas-particular.php'+ancla,700);
	//ventanaSecundaria('http://www.latiendaconexion.com/movil/tarifas-particular.php'+ancla,700);



}





//Funcion para nueva ventana personalizada sin barra estado, navegacion, no redimensionable

function ventanaSecundaria(URL,ancho)

{		

   window.open(URL,null,"width="+ancho+",scrollbars=YES,resizable=NO,status=NO,toolbar=NO");

}





//Funciones que devuelven dimensiones y scroll del area de contenido del navegador

function f_clientWidth() {

	return f_filterResults (

		window.innerWidth ? window.innerWidth : 0,

		document.documentElement ? document.documentElement.clientWidth : 0,

		document.body ? document.body.clientWidth : 0

	);

}

function f_clientHeight() {

	return f_filterResults (

		window.innerHeight ? window.innerHeight : 0,

		document.documentElement ? document.documentElement.clientHeight : 0,

		document.body ? document.body.clientHeight : 0

	);

}

function f_scrollTop() {

	return f_filterResults (

		window.pageYOffset ? window.pageYOffset : 0,

		document.documentElement ? document.documentElement.scrollTop : 0,

		document.body ? document.body.scrollTop : 0

	);

}

function f_scrollLeft() {

    return f_filterResults (

        window.pageXOffset ? window.pageXOffset : 0,

        document.documentElement ? document.documentElement.scrollLeft : 0,

        document.body ? document.body.scrollLeft : 0

    );

}



function f_filterResults(n_win, n_docel, n_body) {

	var n_result = n_win ? n_win : 0;

	if (n_docel && (!n_result || (n_result > n_docel)))

		n_result = n_docel;

	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;

}



//Funcion guarda contacto de promocion

function guardar_contacto(segmento)

{

	resultado=megavalidacion('dudaformulario');



	if (resultado!=false)

	{
		if(document.getElementById('politica').checked)
		{
		respuesta = document.getElementById('semaforo');

		envia('guardar_contacto.php','nombre='+document.dudaformulario.nombre.value+'&email='+document.dudaformulario.email.value+'&telefono='+document.dudaformulario.telefono.value+'&producto='+document.dudaformulario.producto.value+'&segmento='+segmento);
		}
		else
			jAlert("Para poder continuar necesitas aceptar la política de protección de datos.","Existen campos sin rellenar");
		
	}

	else

	{

		alert('Hay datos incorrectos y/o campos obligatorios sin rellenar');

	}

	resultado="";



}



//Funcion guarda contacto de promocion con codigo promocional

function guardar_contacto2()

{

	var segmento;



	url = window.location.search;

	

	if(url.search('movil')>-1)

		segmento = 'residencial';

	

	else if(url.search('empresas')>-1)

			segmento = 'empresas';

	

		 else

			segmento = 'libres';



	resultado=megavalidacion('dudaformulario');



	if (resultado!=false)

	{
		if(document.getElementById('politica').checked)
		{
		respuesta = document.getElementById('semaforo');

		envia('guardar_contacto.php','nombre='+document.dudaformulario.nombre.value+'&email='+document.dudaformulario.email.value+'&telefono='+document.dudaformulario.telefono.value+'&producto='+document.dudaformulario.producto.value+'&segmento='+segmento+'&codigopromocional='+document.dudaformulario.codigopromocional.value);
		}
		else
			jAlert("Para poder continuar necesitas aceptar la política de protección de datos.","Existen campos sin rellenar");
		
	}

	else

	{

		alert('Hay datos incorrectos y/o campos obligatorios sin rellenar');

	}

	resultado="";



}

function ejec_procesoCompra(evento,direccion)
{
	direccion = direccion.replace(/&/gi,'-_-');
	
	respuesta = document.getElementById('procesoCompra');
	
	envia('procesoCompra.php','evento='+evento+
			'&url='+direccion);
}

function paginador(url,capa,pagina)
{
	respuesta=document.getElementById(capa);
	envia(url,'pagina='+pagina);
}

function contratar_adsl(adsl,segmento)
{
	/* efecto degradado al aparecer el popup*/
	var alto = $(document).height();
	var ancho = $(window).width();
	
	
	$("#ppup").load("inicio/popup.php",{"adsl":adsl,"segmento":segmento},function(){
		$("#popup").css({"width":ancho,"height":alto});
		$('#popup').fadeTo("slow",0.6);    
		$("#todopopup").fadeTo("slow",1);
		
	});
	

}
function add_comparador(movil,select)
{
	if(movil=='%')
		movil = 0;
	$(".cuerpo-buscador-comparador").load("ajax/carga-select-comparador.php",{"mvl":movil,"select":select});
}

function cambia_tipocliente(cliente)
{
	if(cliente=='p')
	{
		$("#capa-razonsocial").html("Nombre y apellidos* ");
		$("#capa-razonsocial-envio").html("Nombre y apellidos* ");
	}
	else
	{
		$("#capa-razonsocial").html("Raz&oacute;n Social* ");
		$("#capa-razonsocial-envio").html("Raz&oacute;n Social* ");
	}
}
function  muestra_datos_envio(radio)
{
	if(radio=='diferente')
	{
		$("#procesandomsg").css("display","block");
		$("#div-datos-envio").load("ajax/carga-datos-form-nuevousuario.php",function(){
			$("#div-datos-envio").css("display","block");
			$("#procesandomsg").css("display","none");
		});
		//$("#div-datos-envio").css("display","block");
	}
	else
	{
		$("#procesandomsg").css("display","block");
		$("#div-datos-envio").html("");
		$("#procesandomsg").css("display","none");
	}
}

function guardaDatos()
{
	
		
		
		var arrayDatos = new Array();
		
		arrayDatos[0] = nomyape_envio;
		arrayDatos[1] = tipo_via_envio;
		arrayDatos[2] = nomvia_envio;
		arrayDatos[3] = numvia_envio;
		arrayDatos[4] = escalera_envio;
		arrayDatos[5] = cp_envio;
		arrayDatos[6] = localidad_envio;
		arrayDatos[7] = provincia_envio;
	
		return arrayDatos;
		//alert(arrayDatos);
}

function  muestra_datos_envio_resumencompra(radio)
{
	/*var nomyape_envio = $("#form_nuevo_usuario_resumencompra input[name=nomyape_envio]").val();
	var tipo_via_envio = $("#form_nuevo_usuario_resumencompra select[name=tipo_via_envio]").val();
	var nomvia_envio = $("#form_nuevo_usuario_resumencompra input[name=nomvia_envio]").val();
	var numvia_envio = $("#form_nuevo_usuario_resumencompra input[name=numvia_envio]").val();
	var escalera_envio = $("#form_nuevo_usuario_resumencompra input[name=escalera_envio]").val();
	var cp_envio = $("#form_nuevo_usuario_resumencompra input[name=cp_envio]").val();
	var localidad_envio = $("#form_nuevo_usuario_resumencompra input[name=localidad_envio]").val();
	var provincia_envio = $("#form_nuevo_usuario_resumencompra input[name=provincia_envio]").val();
	
	if(radio=='diferente')
	{
		$("#div-datos-envio").html("");
	}
	else
	{
		
		$("#procesandomsg").css("display","block");
		$("#div-datos-envio").load("ajax/carga-datos-form-nuevousuario-resumencompra.php",{
			'nomyape_envio':nomyape_envio,
			'tipo_via_envio':tipo_via_envio,
			'nomvia_envio':nomvia_envio,
			'numvia_envio':numvia_envio,
			'escalera_envio':escalera_envio,
			'cp_envio':cp_envio,
			'localidad_envio':localidad_envio,
			'provincia_envio':provincia_envio,
			'estado':'oculto'
		},function(){
			$("#div-datos-envio").css("display","none");
			$("#procesandomsg").css("display","none");
		});
	}*/
	if(radio=='diferente')
	{
		$("#procesandomsg").css("display","block");
		$("#div-datos-envio").load("ajax/carga-datos-form-nuevousuario-resumencompra.php",function(){
			$("#div-datos-envio").css("display","block");
			$("#procesandomsg").css("display","none");
		});
		//$("#div-datos-envio").css("display","block");
	}
	else
	{
		$("#procesandomsg").css("display","block");
		$("#div-datos-envio").html("");
		$("#procesandomsg").css("display","none");
	}

}

function cerrar_ie6(){
	$('#ie6').css('display','none');
	$.post('ie6.php');
}
$(document).ready(function(){
	DD_belatedPNG.fix('.transparente','.cabetar');
	$('.rollgris').mouseover(function(){
		var s=$(this).attr('src').split('-gris');
		$(this).attr('src',s[0]+s[1]);
	});
	$('.rollgris').mouseleave(function(){
		var s=$(this).attr('src').split('-icon');
		$(this).attr('src',s[0]+'-icon-gris'+s[1]);
	});
	
	$('.rollgrisMinis').mouseover(function(){
		var s=$(this).attr('src').split('-gris');
		$(this).attr('src',s[0]+s[1]);
	});
	$('.rollgrisMinis').mouseleave(function(){
		var s=$(this).attr('src').split('-mini');
		$(this).attr('src',s[0]+'-mini-gris'+s[1]);
	});
});
