///////////////////////////////////////////////////////////////////////////
// @Sitio: Marketing Destino			 								 //
// @Version: 1.1														 //
// @Autor: Juan J. Lopez Lira							    			 //
// @Fecha: 30 Diciembre 2009											 //
// @Descripción: Archivo de Funciones JS	 						 	 //
///////////////////////////////////////////////////////////////////////////


// Abrir Nueva Ventana
function OpenWindow(Url,Ventana,ancho,alto) {
  window.open(Url,Ventana,'status=yes,scrollbars=yes,resizable=yes,width='+ancho+',height='+alto);
}

// Ajusta Ventana al Centro del Monitor
function FixWindow(){
	x =(screen.width - 640) / 2;
	y =(150) / 2;
	moveTo(x,y);
}

//Imprime Paginas 
function Print(){
	window.print();
}
	
//Cierra la Pagina Pop Up y Refresca la Pagina Opener
function RefreshWindow(){
	window.opener.location.href = window.opener.location.href;
		
		if (window.opener.progressWindow);
		{
		window.opener.progressWindow.close();
		}
		window.close();
	 
}

//Funcion para Envio de formularios
function Send(form){
	if(form == 'DoReserve'){
		ValidaReserva();
		}else{
		document.getElementById(form).submit();
	}	
}
	
function ClearForm(){
	document.getElementById('name').value='';
	document.getElementById('last').value='';
	document.getElementById('message').value='';
	document.getElementById('e_mail').value='';
	document.getElementById('phone').value='';
	}


//Funcion para mostrar mas informacion
function Show(id){
	if(document.getElementById(id).style.display =='none'){
		document.getElementById(id).style.display ='block'
		} else {
		document.getElementById(id).style.display ='none'
			}
	}
	
//Funcion para Borrar contenido de campos
function ClearField(id){
   var field = document.getElementById(id);
      var stringNew = field.value;
      field.value = "";
}

//Funcion para asignar valor default a campos
function SetField(id,ogval){
   var field = document.getElementById(id);
   if(field.value == ""){
      field.value = ogval;
   }
}

///////////////////////////////////
// Funciones AJAX				 //
///////////////////////////////////

// Genera el Objeto de Conexion para Ajax
function newajax(){
	var xmlhttp=false;
	try{
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e){
		try{
			// Creacion del objet AJAX para IE
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(E){
				if (!xmlhttp && typeof XMLHttpRequest!='undefined') xmlhttp=new XMLHttpRequest();
				}
				}
				return xmlhttp; 
}

//Funcion de Precarga Ajax
function precarga(){
	loader = '<div class="loader"></div>';
	return loader;
}

function seletopt(){
	sel = '<select name="tmp"><option>-></option></select>';
	return sel;
}

function DoDelImg(img,sct,tbl,ids,idv){	
	//alert(noticia);
	ajax = newajax();
	
	ajax.open("POST", "/include/ajaxlib.php", true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajax.onreadystatechange=function() {
        if (ajax.readyState==1) {
            document.getElementById('bkimgkontainer').innerHTML = precarga();
        }
        if (ajax.readyState==4) {
            document.getElementById('bkimgkontainer').innerHTML = ajax.responseText;
        }
    }
	ajax.send("cmd=dodelimg"+"&img="+img+"&sct="+sct+"&tbl="+tbl+"&ids="+ids+"&idv="+idv)
}

function getzonas(){	
	ajax = newajax();
	
	dest = document.getElementById("iddestino").value;
	
	ajax.open("POST", "/include/ajaxlib.php", true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajax.onreadystatechange=function() {
        if (ajax.readyState==1) {
            document.getElementById('zonas').innerHTML = precarga();
        }
        if (ajax.readyState==4) {
            document.getElementById('zonas').innerHTML = ajax.responseText;
        }
    }
	ajax.send("cmd=getzonas"+"&iddestino="+dest)
}


function getaccomodations(){
	ajax = newajax();
	idhotel = document.getElementById("idhotel").value;
	habitaciones = document.getElementById("no_habitaciones").value;
	htllng = document.getElementById("htllng").value;
	
	ajax.open("POST", "/include/ajaxlib.php", true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajax.onreadystatechange=function() {
        if (ajax.readyState==1) {
            document.getElementById('roomsaccomodation').innerHTML = precarga();
        }
        if (ajax.readyState==4) {
            document.getElementById('roomsaccomodation').innerHTML = ajax.responseText;
        }
    }
	ajax.send("cmd=getroomaccomodations"+"&idhotel="+idhotel+"&habitaciones="+habitaciones+"&l="+htllng)
	
	}


function gethotellist(){
	
	if(document.getElementById('listhoteles').style.display =='none'){
		document.getElementById('listhoteles').style.display ='block'
		}

	ajax = newajax();
	
	var hotel = document.getElementById('hotel').value;
	var dstfld = document.getElementById('dstfld').value;
	
	ajax.open("POST", "/include/ajaxlib.php", true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajax.onreadystatechange=function() {
        if (ajax.readyState==1) {
            document.getElementById('listhoteles').innerHTML = precarga();
        }
        if (ajax.readyState==4) {
            document.getElementById('listhoteles').innerHTML = ajax.responseText;
        }
    }
	ajax.send("cmd=gethotel"+"&k="+hotel+"&f="+dstfld);
}

function getestados(){
	
	ajax = newajax();
	
	var idpais = document.getElementById('idpais').value;
	
	ajax.open("POST", "/include/ajaxlib.php", true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajax.onreadystatechange=function() {
        if (ajax.readyState==1) {
            document.getElementById('estados').innerHTML = precarga();
        }
        if (ajax.readyState==4) {
            document.getElementById('estados').innerHTML = ajax.responseText;
        }
    }
	ajax.send("cmd=getestados"+"&idpais="+idpais);
}


function addservicios(idservicio,idhotel){
	ajax = newajax();
	
	var nota_es = document.getElementById('nota_es'+idservicio).value;
	var nota_en = document.getElementById('nota_en'+idservicio).value;
	var costo = document.getElementById('costo'+idservicio).value;
	var idhotelservicio = document.getElementById('idhotelservicio'+idservicio).value;
	
	//alert(idhotelservicio);
	
	ajax.open("POST", "/include/ajaxlib.php", true);
	ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajax.onreadystatechange=function() {
        if (ajax.readyState==1) {
            document.getElementById('idserviciocontainer'+idservicio).innerHTML = precarga();
        }
        if (ajax.readyState==4) {
            document.getElementById('idserviciocontainer'+idservicio).innerHTML = ajax.responseText;
        }
    }
	ajax.send("cmd=addservicios"+"&idservicio="+idservicio+"&idhotel="+idhotel+"&nota_es="+nota_es+"&nota_en="+nota_en+"&costo="+costo+"&idhotelservicio="+idhotelservicio);
}


function removeservicios(idservicio){
	var idhotelservicio = document.getElementById('idhotelservicio'+idservicio).value;
	
	if(idhotelservicio == ''){
		alert('No se ha agregado este servicio, error al eliminar');
	}else{
		ajax = newajax();
		ajax.open("POST", "/include/ajaxlib.php", true);
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		ajax.onreadystatechange=function() {
        if (ajax.readyState==1) {
            document.getElementById('idserviciocontainer'+idservicio).innerHTML = precarga();
        }
        if (ajax.readyState==4) {
            document.getElementById('idserviciocontainer'+idservicio).innerHTML = ajax.responseText;
        }
    }
	ajax.send("cmd=delservicios"+"&idhotelservicio="+idhotelservicio);		
		}
	}
	
function deleteitem(c,r,l,f,t){
		ajax = newajax();
		ajax.open("POST", "/include/ajaxlib.php", true);
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		ajax.onreadystatechange=function() {
        if (ajax.readyState==1) {
            document.getElementById('rlc').innerHTML = precarga();
        }
        if (ajax.readyState==4) {
            document.getElementById('rlc').innerHTML = ajax.responseText;
        }
    }
	ajax.send("cmd=deleteitem"+"&c="+c+"&r="+r+"&l="+l+"&f="+f);		
}

function getschedule(idioma){
	
		fecha =  document.getElementById('entrada').value;
		opcion =  document.getElementById('idtourprecio').value;

		ajax = newajax();
		ajax.open("POST", "/include/ajaxlib.php", true);
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		ajax.onreadystatechange=function() {
        if (ajax.readyState==1) {
            document.getElementById('schedule').innerHTML = precarga();
        }
        if (ajax.readyState==4) {
            document.getElementById('schedule').innerHTML = ajax.responseText;
        }
    }
	ajax.send("cmd=getschedule"+"&fecha="+fecha+"&idtourprecio="+opcion+"&lang="+idioma);		
}

function getedades(hab){
		menores =  document.getElementById('htl_no_menores['+hab+']').value;
		htllng = document.getElementById("htllng").value;
		limite = document.getElementById("limite").value;

		ajax = newajax();
		ajax.open("POST", "/include/ajaxlib.php", true);
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		ajax.onreadystatechange=function() {
        if (ajax.readyState==1) {
            document.getElementById('edad'+hab).innerHTML = precarga();
        }
        if (ajax.readyState==4) {
            document.getElementById('edad'+hab).innerHTML = ajax.responseText;
        }
    }
	ajax.send("cmd=getedades"+"&menores="+menores+"&limite="+limite+"&l="+htllng);		
}


function add(id,field,lang){	
	adultos = document.getElementById(id+'_adultos').value;
	menores = document.getElementById(id+'_menores').value;
	
	maxpax = parseInt(adultos)+parseInt(menores);

	var mensaje=["","Para reservar mas de 7 pasajeros contacte a nuestro concierge en linea","For more then 7 passengers, contact our online concierge"];
	
	if(maxpax > 6){
		alert(mensaje[lang]);
		}else{
	val = document.getElementById(id+'_'+field).value
	document.getElementById(id+'_'+field).value = parseInt(val)+parseInt('1');
		}
	
}

function remove(id,field){
	val = document.getElementById(id+'_'+field).value
	if(val > 0){
		document.getElementById(id+'_'+field).value = parseInt(val)-parseInt('1');
	}else{
		document.getElementById(id+'_'+field).value = 0
		}
	}

function dst(hotel,dst){
	document.getElementById('dst').value =dst;
	document.getElementById('hotel').value=hotel;
	$("#htllist").fadeOut("slow");
	//document.getElementById('listhoteles').style.display ='none';
	}

function fixToolTipColor(){
			$('.ui-tooltip-pointer-down-inner').each(function(){
				var bWidth = $('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
				var bColor = $(this).parents('.ui-slider-tooltip').css('backgroundColor')
				$(this).css('border-top', bWidth+' solid '+bColor);
			});	
		}
		
$(function() {
		$("#cartflag").click(function(event){
		$("#showcart").slideDown("normal");
 	});
	});

$(function() {
		$("#close a").click(function(event){
		$("#showcart").slideUp("normal");
 	});
	});

function goReserve(id){
	$('#resBox'+id).slideDown("slow");
	}

//Valida Tarjetas
function validarTarjeta(campo,lang) {
  var expReg = /\W/gi;
  var numero = campo.replace(expReg, "");
  var mensaje=["","El número de la tarjeta de crédito no es válido","Invalid credit card number"];

  if (isNaN(numero)) {
	alert(mensaje[lang]);
	document.getElementById('ccn').focus(); return false
	return false;
  }
  
  if ((numero.length!=16) && (numero.length!=18)) {
	 alert(mensaje[lang]);
	 document.getElementById('ccn').focus(); return false
	 return false;
  }
  var suma = 0;
  for (i = numero.length; i > 0; i--) {
	
	if (i % 2 == 1) {
	  var doble = "" + (parseInt(numero.substring(i - 1, i)) * 2);
	  //Si el doble tiene más dos cifras (o sea es mayor que 9)
	  if (doble.length == 2) {
		 doble = parseInt(doble.substring(0,1)) + parseInt(doble.substring(1,2));
	  }
	  suma += parseInt(doble);
	}
	//Si la posición es par
	else {
	  suma += parseInt(numero.substring(i - 1, i));
	}
  }
  //Si la suma total no es divisible por 10 entonces el número no es válido
  if (suma % 10 != 0) {
	alert(mensaje[lang]);
	document.getElementById('ccn').focus(); return false
	return false;
  }
}

//Valida Correo
function validarEmail(valor,lang){
	var e_correonovalido=["","La dirección de email " + valor + " es incorrecta.","The e-mail " + valor + "is not valid."];
	
	if (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/.test(valor)){
//return false;
} else {
alert(e_correonovalido[lang]);
return false;
}
}

function ValidaReserva(){
	var lang = document.getElementById('lang').value;
	var nombre = document.getElementById('nombre').value;
	var apellido = document.getElementById('apellido').value;
	var correo = document.getElementById('correo').value;
	var correoconf = document.getElementById('correoconf').value;
	var telefono = document.getElementById('telefono').value;
	var tarjetahabiente = document.getElementById('ccu').value;
	var tarjeta = document.getElementById('ccn').value;
	var cvv = document.getElementById('cvv').value;
	var pais = document.getElementById('idpais').value;
	var estado = document.getElementById('idestado').value;
	var ciudad = document.getElementById('ciudad').value;
	var cp = document.getElementById('cp').value;
	var direccion = document.getElementById('direccion').value;
	var aerolinea = document.getElementById('idaerolinea').value;
	var llegada_fecha = document.getElementById('llegada_fecha').value;
	var llegada_vuelo = document.getElementById('llegada_vuelo').value;
	var salida_fecha = document.getElementById('salida_fecha').value;
	var salida_vuelo = document.getElementById('salida_vuelo').value;
	var acepto = document.getElementById('acepto').value;
	var facturasi = document.getElementById('showfactura').value;
	var facturano = document.getElementById('hidefactura').value;

	//Mensajes de Error 
	var e_comparaemail=["","El correo electronico no coincide, favor de verificar","E-mail address does not match, please try again"];
	var e_nombre=["","Nombre es un campo requerido","Name is a required field"];
	var e_apellido=["","Apellido es un campo requerido","Last name is a required field"];
	var e_correo=["","Correo es un campo requerido","E-mail is a required field"];
	var e_confcorreo=["","La confirmacion de su correo es importante para validar su autenticidad","You must confirm your email address"];
	var e_telefono=["","Telefono es un campo requerido","Phone number is a required field"];
	var e_tarjetahabiente=["","Nombre del Tarjetahabiente es un campo requerido","Card holder name is a required field"];
	var e_numtarjeta=["","Numero de tarjeta es un campo requerido","Credit card number is a required field"];
	var e_cvv=["","El codigo de seguridad es un campo requerido","Security code is a required field"];
	var e_pais=["","Pais es un campo requerido","Country is a required field"];
	var e_estado=["","Estado es un campo requerido","State is a required field"];
	var e_ciudad=["","Ciudad es un campo requerido","City is a required field"];
	var e_cp=["","Codigo Postal es un campo requerido","Zip Code is a required field"];
	var e_direccion=["","Direccion es un campo requerido","Address is a required field"];
	var e_aerolinea=["","Aerolinea es un campo requerido","Airline is a required field"];
	var e_llegadafecha=["","Fecha de llegada es un campo requerido","Arrival is a required field"];
	var e_llegadavuelo=["","Vuelo de lLlegada es un campo requerido","Arrival flight number is a required field"];
	var e_salidafecha=["","Fecha de salida es un campo requerido","Departure is a required field"];
	var e_salidavuelo=["","Vuelo de salida es un campo requerido","Departure flight number is a required field"];
	var e_empresa=["","Razon Social es un campo requerido","Company Name is a required field"];
	var e_rfc=["","R.F.C. es un campo requerido","Company I.D. is a required field"];
	
	var e_acepto=["","Es necesario que lea y acepte las politicas de cancelacion y pagos","You must read and acept our payment and cancelation policies"];

	//Validacion de Campos Vacios
	if(nombre == ""){ alert(e_nombre[lang]); document.getElementById('nombre').focus(); return false; }
	if(apellido == ""){ alert(e_apellido[lang]); document.getElementById('apellido').focus(); return false;}
	if(correo == ""){ alert(e_correo[lang]); document.getElementById('correo').focus(); return false; }
	//if(correo != ""){ validarEmail(correo,lang); }
	if(correoconf == ""){ alert(e_confcorreo[lang]); document.getElementById('correoconf').focus(); return false; }
	if(correo != correoconf){ alert(e_comparaemail[lang]); document.getElementById('correoconf').focus(); return false; }
	if(telefono == ""){ alert(e_telefono[lang]); document.getElementById('telefono').focus(); return false; }
	if(tarjetahabiente == ""){ alert(e_tarjetahabiente[lang]); document.getElementById('ccu').focus(); return false; }
	if(tarjeta == ""){ alert(e_numtarjeta[lang]); document.getElementById('ccn').focus(); return false; }
	//if(tarjeta != ""){ validarTarjeta(tarjeta,lang); }
	if(cvv == ""){ alert(e_cvv[lang]); document.getElementById('cvv').focus(); return false; }	
	if(pais == ""){ alert(e_pais[lang]); document.getElementById('idpais').focus(); return false; }
	if(estado == ""){ alert(e_estado[lang]); document.getElementById('idestado').focus(); return false; }
	if(ciudad == ""){ alert(e_ciudad[lang]); document.getElementById('ciudad').focus(); return false }
	if(cp == ""){ alert(e_cp[lang]); document.getElementById('cp').focus(); return false }
	if(acepto == "" || acepto == 0 || acepto == null){ alert(e_acepto[lang]); document.getElementById('acepto').focus(); return false }
	if(direccion == ""){ alert(e_direccion[lang]); document.getElementById('direccion').focus(); return false }
	if(aerolinea == ""){ alert(e_aerolinea[lang]); document.getElementById('idaerolinea').focus(); return false }
	if(llegada_fecha == ""){ alert(e_llegadafecha[lang]); document.getElementById('llegada_fecha').focus(); return false }
	if(llegada_vuelo == ""){ alert(e_llegadavuelo[lang]); document.getElementById('llegada_vuelo').focus(); return false }
	if(salida_fecha == ""){ alert(e_salidafecha[lang]); document.getElementById('salida_fecha').focus(); return false }
	if(salida_vuelo == ""){ alert(e_salidavuelo[lang]); document.getElementById('salida_vuelo').focus(); return false }

	//Si no existen errores envia la reservacion
	document.getElementById('DoReserve').submit();
}

$(function() {
		$("#showfactura").click(function(event){
		$("#facturas").slideDown("normal");
 	});
	});

$(function() {
		$("#hidefactura").click(function(event){
		$("#facturas").slideUp("normal");
 	});
	});


function copyToClipboard(field){
    var content = eval("document."+field)
    content.focus()
    content.select()
    range = content.createTextRange()
    range.execCommand("Copy")
    window.status="Link copiado exitosamente"
    setTimeout("window.status=''",1800)
}

