//******funcion para verificar la estructura de los emails
function esEmail(email){
    invalidChars = " ~\'^\`\"*+=\\|][(){}$&!#%/:,;";
    // Si es nulo
    if (email == "")
        return false;
    // Chequea caracteres inválidos
    for (i=0; i<invalidChars.length; i++){
        badChar = invalidChars.charAt(i);
        if (email.indexOf(badChar,0) > -1)
            return false;
    }
    lengthOfEmail = email.length;
    if ((email.charAt(lengthOfEmail - 1) == ".") || (email.charAt(lengthOfEmail - 2) == "."))
        return false;
    Pos = email.indexOf("@",1);
    if (email.charAt(Pos + 1) == ".")
        return false;
    while ((Pos < lengthOfEmail) && ( Pos != -1)){
        Pos = email.indexOf(".",Pos);
        if (email.charAt(Pos + 1) == ".")
            return false;
        if (Pos != -1)
            Pos++;
        };
    // Debe haber una arroba
    atPos = email.indexOf("@",1);
    if (atPos == -1)
        return false;
    // Solo una arroba
    if (email.indexOf("@",atPos+1) != -1)
        return false;
    // Por lo menos un punto despues de la arroba
    periodPos = email.indexOf(".",atPos);
    if (periodPos == -1)
        return false;
    if (periodPos+3 > email.length)
        return false;
    return true;
}
//********funcion que elimina los espacios en blanco del principio y el final de una cadena
function trim(cadena){
    for(i=0; i<cadena.length; ){
        if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
        else
            break;
    }

    for(i=cadena.length-1; i>=0; i=cadena.length-1){
        if(cadena.charAt(i)==" ")
            cadena=cadena.substring(0,i);
        else
            break;
    }
    return cadena;
}
//******verifica que una casilla tenga solo números
function esnumero(num,formu,nom){//recive el valor de la casilla, el nombre del formulario y el nombre del cuadro de texto
var checkOK = "0123456789";
var checkStr = num;
var allNum = "";
for (i = 0; i < checkStr.length; i++){
	ch = checkStr.charAt(i);
	for (j = 0; j < checkOK.length; j++)
		if (ch == checkOK.charAt(j))
			break;
		if (j == checkOK.length){
			window.alert("Esta Casilla Solamente Acepta Números");
			allNum=checkStr.substring(0,i);
			eval("document."+formu+"."+nom+".value=allNum")
			break;
		}
	}
}

/*para llamar a la funcion

onKeyUp="esnumero(this.value,this.form.name,this.name)"

se debera de colocar dentro del tag <input> y es necesario que exista un form

ejemplo:

<input type="text" name="cp_emp" size="10" maxlength="8"  
onKeyUp="esnumero(this.value,this.form.name,this.name)">*/

//Acepta número decimales OOOJJOOO: todavía no funciona adecuadamente
function EsNumero(valor) {
  Decimal = false
  inputStr = valor.toString() //convierte el valor a cadena
  for (var i = 0; i < inputStr.length; i++) {
    var Car = inputStr.charAt(i) //retorna el caracter del índice especificado
    if (i == 0 && Car == "-") {
	    continue //detiene la iteración y la vuelve a iniciar
		}
		if (Car == "." && !Decimal) {
	  	Decimal = true
	  	continue
		}
		if (Car < "0" || Car > "9") {
	  	return false
		}
  }
  return true
} 
//******verifica si es numero (viene de la funcion checar)
function esnumero2(num){
	var checkOK = "0123456789";
	var checkStr = num;
	var allValid = true;
	var allNum = "";
	for (i = 0; i < checkStr.length; i++){
		ch = checkStr.charAt(i);
		for (j = 0; j < checkOK.length; j++)
			if (ch == checkOK.charAt(j))
				break;
		if (j == checkOK.length){
			allValid = false;
			break;
		}
		allNum += ch;
	}
	return allValid;
}
//**********funcion para checar los campos obligatorios y abrir la ventana correspondiente
//*****pasando sus respectivos valores.
function checar(){
	resp=document.armatuviaje.responsable.value;
	inst=document.armatuviaje.institucion.value;
	em=document.armatuviaje.email.value;
	cp=document.armatuviaje.cod_postal.value;
	ciud=document.armatuviaje.ciudad.value;
	prov=document.armatuviaje.provincia.value;
	//ca=document.armatuviaje.codarea.value;
	tel=document.armatuviaje.telefono.value;
	pres=document.armatuviaje.presupuesto.value;
	desViaje=document.armatuviaje.destinoviaje.value;
	pas=document.armatuviaje.pasajeros.value;
	pasmen=document.armatuviaje.menores.value;
	pais=document.armatuviaje.pais.value;
	mens=document.armatuviaje.comentarios.value;
	alo=document.armatuviaje.alojamiento.value;
	hote=document.armatuviaje.hoteles.value;
	diasal=document.armatuviaje.diasalida.value;
	messal=document.armatuviaje.salida.value;
	diare=document.armatuviaje.diaregreso.value;
	mesre=document.armatuviaje.regreso.value;
	tviaje=document.armatuviaje.viaje.value;
	if(resp.length<3){
		window.alert("Por Favor, Escriba Su Nombre");
		document.armatuviaje.responsable.select();
		return;
	}
	if(inst.length<3){
		window.alert("Por Favor, Escriba Sus Apellidos");
		document.armatuviaje.institucion.select();
		return;
	}
	if(!esEmail(em)){
		window.alert("Por Favor, Escriba un E-Mail Válido");
		document.armatuviaje.email.select();
		return;
	}
	nume=esnumero2(cp);
	if(!nume){
		window.alert("Por Favor, Escriba el Código Postal (Solamente Números)");
		document.armatuviaje.cod_postal.select();
		return;
	}
	if(ciud.length<3){
		window.alert("Por Favor, Escriba el Nombre de la Ciudad");
		document.armatuviaje.ciudad.select();
		return;
	}
	if(prov.length<3){
		window.alert("Por Favor, Escriba el Nombre de la Provincia");
		document.armatuviaje.provincia.select();
		return;
	}
	/*   if(ca.lenth<3){
		window.alert("Por Favor, Escriba el Código de Área");
		document.armatuviaje.codarea.select();
		return;
	}*/
	if(tel.length<12){
		window.alert("Por Favor, Escriba o verifique el Número Telefónico");
		document.armatuviaje.telefono.select();
		return;
	}
	pre=esnumero2(pres);
	if((!pre) || (pres<300)){
		window.alert("Por Favor, Escriba el Presupuesto (Solamente Números) y >= $300 USD");
		document.armatuviaje.presupuesto.select();
		return;
	}
	if(desViaje.length<3){
		window.alert("Por Favor, Escriba el Destino Elegido");
		document.armatuviaje.destinoviaje.select();
		return;
	}
	numper=esnumero2(pas);
	if(!numper){
		window.alert("Por Favor, Escriba el Total de Pasajeros Adultos (Solamente Números)");
		document.armatuviaje.cod_postal.select();
		return;
	}
	var cont=0;
	var actividades="";
	for( var i=0;i<=7;i++){
		if(document.armatuviaje.act[i].checked)
		cont++;
	}
	if(cont!=0){
		for( var i=0;i<=7;i++){
			if(document.armatuviaje.act[i].checked){
				if(cont!=1){
					actividades=actividades+document.armatuviaje.act[i].value+", ";
					--cont;
				}else
					actividades=actividades+document.armatuviaje.act[i].value+".";
			}
		}
	}else{
		actividades="Sin Actividades";
	}
	if (pasmen!=""){
		numpermen=esnumero2(pasmen);
		if(!numpermen){
			window.alert("Por Favor, Escriba el Total de Pasajeros Menores de Edad (Solamente Números)");
			document.armatuviaje.menores.select();
			return;
		}
	}
	if(document.armatuviaje.incluirpasaje[0].checked){
		incpas="SI";
		for(i=0;i<=1;i++){
			if(document.armatuviaje.vias[i].checked)
				var	via=document.armatuviaje.vias[i].value;
			var horario=document.armatuviaje.horarios.value;
			var tipopas=document.armatuviaje.tipo_viaje.value;
		}
	}else{
		incpas="NO";
	}
	if (document.armatuviaje.rentautomovil[0].checked){
		lr=document.armatuviaje.lugar_recogida.value;
		le=document.armatuviaje.lugarde_laentrega.value;
		if(lr.length<3){
			window.alert("Por Favor, Escriba el Nombre del Lugar Recogida (Completo)");
			document.armatuviaje.lugar_recogida.select();
			return;
		}
		if(le.length<3){
			window.alert("Por Favor, Escriba el Nombre del Lugar Entrega (Completo)");
			document.armatuviaje.lugarde_laentrega.select();
			return;
		}
		rentarauto="SI";
		mesrenta=document.armatuviaje.mesde_larenta.value;
		diarenta=document.armatuviaje.diade_larenta.value;
		horarenta=document.armatuviaje.horariode_larenta.value;
		mesentrega=document.armatuviaje.mesde_laentrega.value;
		diaentrega=document.armatuviaje.diade_laentrega.value;
		horaentrega=document.armatuviaje.horariode_laentrega.value;
	}else{
		rentarauto="NO";
	}
	if(mens==""){
		mens="Sin Mensaje";
	}
	if (incpas=="No" && rentarauto=="NO"){
		mostrardatos=window.open('verificar.php?nomb='+resp+'&ape='+inst+'&email='+em+'&prov='+prov+'&ciud='+ciud+'&pais='+pais+/*'&ctel='+ca+*/'&tel='+tel+'&cp='+cp+'&pre='+pres+'&dest='+desViaje+'&alojamiento='+alo+'&hotel='+hote+'&ds='+diasal+'&ms='+messal+'&dr='+diare+'&mr='+mesre+'&pasajes='+pas+'&ninios='+pasmen+'&tviaje='+tviaje+'&act='+actividades+'&mens='+mens,'','width=680, height=680, menubar=no, status=no, toolbar=no, scrollbars=yes,left=0, top=0,screenX=0,screenY=0')
	}else{
		if(rentarauto=="SI"){
			mostrardatos=window.open('verificar.php?nomb='+resp+'&ape='+inst+'&email='+em+'&prov='+prov+'&ciud='+ciud+'&pais='+pais+/*'&ctel='+ca+*/'&tel='+tel+'&cp='+cp+'&pre='+pres+'&dest='+desViaje+'&alojamiento='+alo+'&hotel='+hote+'&ds='+diasal+'&ms='+messal+'&dr='+diare+'&mr='+mesre+'&pasajes='+pas+'&ninios='+pasmen+'&tviaje='+tviaje+'&act='+actividades+'&mens='+mens+'&tipopas='+tipopas+'&vias='+via+'&horario='+horario+'&lr='+lr+'&dr='+diarenta+'&mr='+mesrenta+'&hr='+horarenta+'&le='+le+'&de='+diaentrega+'&me='+mesentrega+'&he='+horaentrega+'&incpas='+incpas+'&rentarauto='+rentarauto,'','width=680, height=680, menubar=no, status=no, toolbar=no, scrollbars=yes,left=0, top=0,screenX=0,screenY=0')
		}else{
			mostrardatos=window.open('verificar.php?nomb='+resp+'&ape='+inst+'&email='+em+'&prov='+prov+'&ciud='+ciud+'&pais='+pais+/*'&ctel='+ca+*/'&tel='+tel+'&cp='+cp+'&pre='+pres+'&dest='+desViaje+'&alojamiento='+alo+'&hotel='+hote+'&ds='+diasal+'&ms='+messal+'&dr='+diare+'&mr='+mesre+'&pasajes='+pas+'&ninios='+pasmen+'&tviaje='+tviaje+'&act='+actividades+'&mens='+mens+'&tipopas='+tipopas+'&vias='+via+'&horario='+horario+'&incpas='+incpas+'&rentarauto='+rentarauto,'','width=680, height=680, menubar=no, status=no, toolbar=no, scrollbars=yes,left=0, top=0,screenX=0,screenY=0')
		}
	//document.armatuviaje.submit();
	}
}
//*****funcion para saber si la ventana donde se muestran los datos esta abierta
//****si lo esta la cierra
function checarventana(){
	if(window.mostrardatos){
		window.mostrardatos.close();
	}
	checar();
}
//******FUNCION PARA BLOQUEAR EL PASAJE
function bloquea_pasaje(){
	document.armatuviaje.tipo_viaje.disabled=true;
	for(var i=0;i<=1;i++) //recorrer los radios para bloquearlos
		document.armatuviaje.vias[i].disabled=true;
	document.armatuviaje.horarios.disabled=true;
}
//******FUNCION PARA DESBLOQUEAR EL PASAJE
function desbloquea_pasaje(){
	document.armatuviaje.tipo_viaje.disabled=false;
	for(var i=0;i<=1;i++) //recorrer los radios para desbloquearlos
		document.armatuviaje.vias[i].disabled=false;
	document.armatuviaje.horarios.disabled=false;
}
//******FUNCION PARA BLOQUEAR LA RENTA DE AUTOMOVIL
function bloquea_renta(){
	document.armatuviaje.lugar_recogida.disabled=true;
	document.armatuviaje.mesde_larenta.disabled=true;
	document.armatuviaje.diade_larenta.disabled=true;
	document.armatuviaje.horariode_larenta.disabled=true;
	document.armatuviaje.lugarde_laentrega.disabled=true;
	document.armatuviaje.mesde_laentrega.disabled=true;
	document.armatuviaje.diade_laentrega.disabled=true;
	document.armatuviaje.horariode_laentrega.disabled=true;
}
//******FUNCION PARA DESBLOQUEAR LA RENTA DE AUTOMOVIL
function desbloquea_renta(){
	document.armatuviaje.lugar_recogida.disabled=false;
	document.armatuviaje.mesde_larenta.disabled=false;
	document.armatuviaje.diade_larenta.disabled=false;
	document.armatuviaje.horariode_larenta.disabled=false;
	document.armatuviaje.lugarde_laentrega.disabled=false;
	document.armatuviaje.mesde_laentrega.disabled=false;
	document.armatuviaje.diade_laentrega.disabled=false;
	document.armatuviaje.horariode_laentrega.disabled=false;
}
function capitalizar(cadena){
	nuevaCadena="";
	if (cadena.length >=1){
		for (var i=0; i<=cadena.length; i++){
			char1 = cadena.charAt(i);
			if (i==0){
				nuevaCadena=char1.toUpperCase();
			}else{
				j=i-1;
				char2=cadena.charAt(j);
				if(char2==" " || char2=="(" || char2=="." || char2=="-"){
					nuevaCadena+=char1.toUpperCase();
				}else{
					nuevaCadena+=char1.toLowerCase();
				}
			}
		}
		return nuevaCadena;
	}else{
		return nuevaCadena;
	}
}
function verificar(){
	with (document.Recomendar){
		var nom=tunombre.value;
		if(nom.length<2){
			window.alert("Por Favor:\n'El campo Nombre no puede estar en Blanco'");
			tunombre.focus();
			return false;
		}
		var correo=tuemail.value;
		if(!esEmail(correo)){
			window.alert("Por Favor:\n'Verifique su E-Mail'");
			tuemail.focus();
			return false;
		}
		var anom=nombreamigo.value;
		if(anom.length<2){
			window.alert("Por Favor:\n'El campo Nombre no puede estar en Blanco'");
			nombreamigo.focus();
			return false;
		}
		var acorreo=emailamigo.value;
		if(!esEmail(acorreo)){
			window.alert("Por Favor:\n'Verifique del E-Mail de su Amigo'");
			emailamigo.focus();
			return false;
		}
		window.open('','nueva','width=600, height=450');
		document.forms['Recomendar'].submit();
	}
}

function verificar2(){
	with (document.Suscribir){
		var nom=nombre.value;
		if(nom.length<2){
			window.alert("Por Favor:\n'Escriba su nombre correctamente'");
			nombre.focus();
			return false;
		}
		var ape=apellido.value;
		if(ape.length<2){
			window.alert("Por Favor:\n'verifique si su apellido es correcto'");
			apellido.focus();
			return false;
		}
		var acorreo=email.value;
		if(!esEmail(acorreo)){
			window.alert("Por Favor:\n'Verifique el E-Mail'");
			email.focus();
			return false;
		}
			/*var dir=direccion.value;
			if(dir.length<2)
			{
				window.alert("Por Favor:\n'El campo Residencia no puede estar en Blanco'");
				direccion.focus();
				return false;
			}*/
		window.open('','nueva','width=600, height=450, menubar=no, status=no, toolbar=no, scrollbars=yes,left=0, top=0,screenX=0,screenY=0');
		document.forms['Suscribir'].submit();
	}
}
/* Funcion para verificar formulario*/
function verifica(form){
	with (eval('document.'+form)){
		var nom=nombre.value;
		if(nom.length<2){
			window.alert("Por Favor:\n'Escriba su nombre correctamente'");
			nombre.focus();
			return false;
		}
		var ape=apellido.value;
		if(ape.length<2){
			window.alert("Por Favor:\n'verifique si su apellidoasaasaaaaaaaa es correcto'");
			apellido.focus();
			return false;
		}
		var acorreo=email.value;
		if(!esEmail(acorreo)){
			window.alert("Por Favor:\n'Verifique el E-Mail'");
			email.focus();
			return false;
		}
		window.open('','nueva','width=600, height=450, menubar=no, status=no, toolbar=no, scrollbars=yes,left=0, top=0,screenX=0,screenY=0');
		eval("document."+form+".submit()");
		return true;
	}
}
function ventana(url,ancho, alto){
	var H = (screen.height/2)-(alto/2);
	var L = (screen.width/2)-(ancho/2);
	window.open(url,'nueva','width='+ancho+',height='+alto+',scrollbars=no,top='+H+',left='+L);
}
