/* 
	calendario.js
	Dpto.: Creatividad Velázquez
	Autor: Alberto Aranda Domínguez
	Versión: 2.0
	Navegadores: IE 5+ / Netscape 6
	Fecha: 19/02/2003
*/


/**************************************** GLOBALES E INICIO *******************************************/
var limite_inferior;
var limite_superior;
var xmlLiter;

function inicio(){	var idioma = "ESP";
	idioma = extraeParam("idioma");	if (document.getElementById("naveg").value == "Firefox") {//El navegador es Firefox		xmlLiter = document.implementation.createDocument("","",null);	} else {//El navegador es cualquier otro diferente a Firefox		xmlLiter=new ActiveXObject("Microsoft.XMLDOM");	}                   xmlLiter.async = false;        xmlLiter.load("../../../VECI/mapaweb/XML/literalesCalendario.xml");	var campo_destino=extraeParam("destino");		//var campoDestino=eval("window.opener.document.frmDatos."+ campo_destino);	  var campoDestino=eval("window.opener.document.getElementById('"+campo_destino+"')");
	//Rellenamos los meses
	var htmlLit = "";
	var nombre = "";
	var objSelect=obtenerElemento("cboMes","");		var htmlLit1 = "";
	for (var i=1; i<=12; i++){
		nombre = "MES";
		if (i<10) {
			nombre += "0"+i;
		} else {
			nombre +=i;
		}
		objOption = document.createElement("OPTION");						if (document.getElementById("naveg").value == "Firefox") {//El navegador es Firefox			//SelectSingleNode( xmlLiter, "//LITERALES/BLOQUE[@COD='"+idioma+"']/TEXTO[@COD='"+nombre+"']/@DES");			objOption.text= SelectSingleNode(xmlLiter, "//LITERALES/BLOQUE[@COD='"+idioma+"']/TEXTO[@COD='"+nombre+"']/@DES").value; 									} else {//El navegador es cualquier otro diferente a Firefox			objOption.text=xmlLiter.selectSingleNode("//LITERALES/BLOQUE[@COD='"+idioma+"']/TEXTO[@COD='"+nombre+"']/@DES").text;		}				if (document.getElementById("naveg").value == "Firefox") {//El navegador es Firefox			objSelect.appendChild(objOption);		} else {//El navegador es cualquier otro diferente a Firefox			objSelect.add(objOption);		}
	}
	
	htmlLit = "";
	for (var i=1; i<=7; i++){
		//htmlLit = xmlLiter.selectSingleNode("//LITERALES/BLOQUE[@COD='"+idioma+"']/TEXTO[@COD='"+("DIA"+i)+"']/@DES").text;		if (document.getElementById("naveg").value == "Firefox") {//El navegador es Firefox			htmlLit = xmlLiter.selectSingleNode("//LITERALES/BLOQUE[@COD='"+idioma+"']/TEXTO[@COD='"+("DIA"+i)+"']/@DES").value;		} else {//El navegador es cualquier otro diferente a Firefox			htmlLit = xmlLiter.selectSingleNode("//LITERALES/BLOQUE[@COD='"+idioma+"']/TEXTO[@COD='"+("DIA"+i)+"']/@DES").text;		}
    	//Rellenamos días de la semana 		if (document.getElementById("naveg").value == "Firefox") {//El navegador es Firefox			celda = document.getElementById("trSemana").insertCell(i-1);		} else {//El navegador es cualquier otro diferente a Firefox			celda = document.all("trSemana").insertCell(i-1);		}		
		if (document.getElementById("naveg").value == "Firefox") {//El navegador es Firefox			celda.textContent = htmlLit;		} else {//El navegador es cualquier otro diferente a Firefox			celda.innerText = htmlLit;		}				
		celda.className = "txtSemana";				celda.style.backgroundColor=fondo_cabeceras_semana;		
	}
//en mapavuelos no esta
//	document.getElementById("idCancelar").innerText = xmlLiter.selectSingleNode("//LITERALES/BLOQUE[@COD='"+idioma+"']/TEXTO[@COD='CAN']/@DES").text;	if (document.getElementById("naveg").value == "Firefox") {//El navegador es Firefox						document.getElementById("idCancelar").value= SelectSingleNode(xmlLiter, "//LITERALES/BLOQUE[@COD='"+idioma+"']/TEXTO[@COD='CAN']/@DES").value; 					} else {//El navegador es cualquier otro diferente a Firefox			document.getElementById("idCancelar").innerText = xmlLiter.selectSingleNode("//LITERALES/BLOQUE[@COD='"+idioma+"']/TEXTO[@COD='CAN']/@DES").text;		}
		
	limite_inferior=extraeParam("limite_inferior");

	//var campoDiasRes=eval("window.opener.document.getElementById('idDiasRes')";
	//alert("Días en calendario: "+campoDiasRes.value);
	if (limite_inferior == null || limite_inferior == "") { 
		if (campoDestino.name == "calEntrada")	{
		    //Venimos de fecha entrada por lo que el limite inferior es dia actual + 3		
			var campoDiasRes=eval("window.opener.document.frmDatos.idDiasRes");
			//limite_inferior = sumaDiasFecha(fechaHoy, parseInt(campoDiasRes.value, 10));				
			limite_inferior = sumaDiasFecha(fechaHoy, parseInt(campoDiasRes.value, 10));	
		} else {
			//Venimos de fecha de salida por lo que el limite inferior es actual + 2;//en mapavuelos esta a 1
			limite_inferior = sumaDiasFecha(fechaHoy, 2);	
		}
	} 
	limite_superior=extraeParam("limite_superior");	
	//fechaInicio= fechaHoy;
	//formatearLimites(fechaInicio.getDate(),fechaInicio.getMonth(),fechaInicio.getFullYear())	
	
	formatearLimites(limite_inferior.substring(0, 2), parseInt(limite_inferior.substring(3,5), 10) - 1,limite_inferior.substring(6,10));
	calendario(limite_inferior.getMonth()+1,limite_inferior.getFullYear())  //Montamos el calendario
	//calendario(parseInt(limite_inferior.substring(3,5), 10) - 1,limite_inferior.substring(6,10))  //Montamos el calendario
	llenarComboAno(limite_inferior.getFullYear());
	//llenarComboAno(limite_inferior.substring(6,10))
	sincronizarCombos(limite_inferior.getMonth(),limite_inferior.getFullYear()) //Sincronizamos los combos
	//sincronizarCombos(parseInt(limite_inferior.substring(4,6),10) - 1,limite_inferior.substring(0,4)) //Sincronizamos los combos
	cambiaCal();
}


function calendario(mes,ano){  // F O R M A T E O   D E   F E C H A S
	//Esta función extrae el día de la semana correspondiente al
	//dia uno del mes/año pasado por parámetro, formatea los tres elementos y llama a 
	//la función que pinta el calendario.
		
	if(ano<=1999 && ano>=1000) ano=ano-1900 //Dos dígitos para años inferiores a 1999
	if(ano>=100 && ano<1900) ano=ano+1900 //Y cuatro para superiores...
	mes-- //Meses internos van de 0 a 11
	
	var fecha=new Date(ano, mes) //Establecemos fecha
		
	var inicio=fecha.getDay() //Nos traemos el día de la semana donde empieza el mes.
	
	//Pasamos los domingos a último día de la semana, y no al primero.
	if(inicio==0) {
		inicio=6 
	}
	else {
		inicio--
	}
	
	dias_total=determinarDias(mes,ano) //Determinamos los días que hay en dicho mes.
	escribeTabla(inicio,dias_total,mes,ano)  //Escribimos en la tabla los días
}


function escribeTabla(inicio, dias_total, mes, ano){  // E S C R I B I M O S   E N   L A   T A B L A
	/*
	Parametros
	inicio: 	posicion 1er. dia
	mes: 		entero con el mes a representar
	dias:		días total del mes
	*/
	
	var hoy=comprobarHoy(mes,ano) //Día de hoy si se halla en el mes.
	var ano_aux;
	var item=null;
		
	if(ano<1900) ano_aux=1900+ano
	else ano_aux=ano
		
	//limpiarTabla()
	
	var cuenta_dias=1 //contador de dias a escribir
	var contador=0 //cuenta los días de la semana (0 a 6)
	escribir_dia=false
	 
	for(i=0;i<42;i++){	//Recorremos las celdas de la tabla
		item=obtenerElemento("td",i)	
		item.style.width=22;
		item.style.height=17;
		item.className="textoDias";		
		
		if(i>=inicio) escribir_dia=true   //Posición de la primera celda a excribir
		if(cuenta_dias>dias_total) escribir_dia=false; //Si nos pasamos de días, terminar
		if(escribir_dia){
			if(contador>5) {
				item.style.backgroundColor=fondo_festivo;
			}
			else {
				item.style.backgroundColor=fondo_laborable;
			}		
			if(hoy==cuenta_dias) {
			    item.title="Hoy";
			    item.style.backgroundColor=fondo_hoy;
			}
			
			if(comprobarLimites(cuenta_dias,mes,ano)){	
				item.innerHTML="<a href='javascript:seleccionarFecha("+cuenta_dias+","+mes+","+ano+")' class='"+item.className+"'>"+cuenta_dias+"</a>&nbsp;"					
				//item.style.backgroundColor="#000000"								
			}else{
				item.innerHTML=cuenta_dias+"&nbsp;"
				if(contador>5) item.style.backgroundColor=fondo_deshab_festivo;
				else  		   item.style.backgroundColor=fondo_deshabilitado;								item.style.color = color_texto_deshabilitado;
			}
			cuenta_dias++
		} else {
			if (document.getElementById("naveg").value == "Firefox") {//El navegador es Firefox				item.textContent="";			} else {//El navegador es cualquier otro diferente a Firefox				item.innerText="";			}
			item.style.backgroundColor=fondo_deshabilitado;						item.style.color = color_texto_deshabilitado;
			//item.innerHTML="<img src='"+img_fondo+"' border=0 width=22 height=17>";
		}
		contador++
		if(contador>6) contador=0
	}
	escribir_dia=false	
}

function comprobarLimites(dia,mes,ano){
	var fecha_entrada=new Date(ano,mes,dia);
	var fecha_ent=fecha_entrada/(1000*60*60*24);

	if(limite_superior!=null && limite_inferior!=null){
		var lim_sup=limite_superior/(1000*60*60*24);
		var lim_inf=limite_inferior/(1000*60*60*24);
		if(fecha_ent>=lim_inf && fecha_ent<=lim_sup) return true;
		else return false;
	}else{
		 if(limite_superior!=null){
			var lim_sup=limite_superior/(1000*60*60*24);
			if(fecha_ent<=lim_sup) return true;
			else return false;	
		}else{
			if(limite_inferior!=null){
				var lim_inf=limite_inferior/(1000*60*60*24);
				if(fecha_ent>=lim_inf) return true;
				else return false;
			}
		}
	}
}

/**************************************** FUNCION DE SALIDA *******************************************/
function seleccionarFecha(s_dia,s_mes,s_ano){ 
	//Devuelve la fecha seleccionada a window.opener y cierra esta ventana.

	var campo_destino=extraeParam("destino");

	s_mes+=1;
	if(s_mes<10) {
		 s_mes="0"+s_mes;
	}
	
	if(s_dia<10) { 
		s_dia="0"+s_dia;
	}

	var fresult = s_dia + "/" + s_mes + "/"+ s_ano;
	//en mapavuelos
//	var campoDestino=eval("window.opener.document.frmDatos."+ campo_destino);	var campoDestino=eval("window.opener.document.getElementById('"+ campo_destino+"')");	   	//Si el día es menor estricto que 10 y el mes es menor estricto que octubre, entonces las variables s_dia y s_mes son string.   	//Si estamos en el caso contrario, dichas variables son enteros. (*)   	//Por tanto, como la funcion sumaDiasFecha recibe un parámetro de fecha tipo string, debemos transformar a string la concatenación   	//del año, mes y día antes de sumarle 1 día a la fecha seleccionada por si nos encontramos en la situación (*).   	var sfechaSeleccionada = s_ano + "" + s_mes + "" + s_dia;
	if (campoDestino.name=="calEntrada") {			
		//SELECCION DE FECHA ENTRADA//
//		var campoSalida=eval("window.opener.document.frmDatos.calSalida");			//en mapavuelosvar campoSalida=eval("window.opener.document.getElementById('calSalida')");   		   		//campoSalida.value = sumaDiasFecha(sfechaSeleccionada,1);		//en mapavuelos		campoSalida.value = fresult;		
		campoDestino.value=fresult;		
	} else {
		//SELECCION DE FECHA SALIDA
		//var campoEntrada=eval("window.opener.document.frmDatos.calEntrada");		//en mapavuelos		var campoEntrada=eval("window.opener.document.getElementById('calEntrada')");				
		if (campoEntrada.value == null || campoEntrada.value == "") {				
			//campoEntrada.value = sumaDiasFecha(sfechaSeleccionada, -1);			//en mapavuelos			campoEntrada.value =fresult;
			campoDestino.value=fresult;			
		} else {
			//DEPENDE DEL TIPO DE FOLLETO
			//ProductoFolleto=="EM" || ProductoFolleto=="PE" --> 7 días
			//Resto de productos = 21 días
			var numDiasDif = 21;			//en mapavuelos			//var numDiasDif = 300;
			if (devuelveNumNoches(campoEntrada.value, fresult) <= numDiasDif) {			
				campoDestino.value = fresult;	
			} else {				var idioma = extraeParam("idioma");								if (document.getElementById("naveg").value == "Firefox") {//El navegador es Firefox					alert(xmlLiter.selectSingleNode("//LITERALES/BLOQUE[@COD='"+idioma+"']/TEXTO[@COD='NOSEL']/@DES").value);				} else {//El navegador es cualquier otro diferente a Firefox					alert(xmlLiter.selectSingleNode("//LITERALES/BLOQUE[@COD='"+idioma+"']/TEXTO[@COD='NOSEL']/@DES").text);				}				
			}
		}
	}
	self.close();
}



/*************************************** FUNCIONES AUXILIARES *****************************************/

function cambiaCal(){
	var comboMes=obtenerElemento("cboMes","");
	var comboAno=obtenerElemento("cboAno","");
	calendario(parseInt(comboMes.selectedIndex+1,10), parseInt(comboAno.options[comboAno.selectedIndex].text,10));
}


function sincronizarCombos(mes,ano){
	//Colocamos los combos en el mes y el año en curso (solo al cargar)
	var comboMes=obtenerElemento("cboMes","");
	var comboAno=obtenerElemento("cboAno","");
	
	comboMes.selectedIndex=mes;
	for(c=0;c<comboAno.options.length;c++){
		if(comboAno.options[c].text==ano){
			comboAno.selectedIndex=c;
			break;
		}
	}
	sincronizar=false;
}


function llenarComboAno(ano){
	var ano_inicio=extraeParam("ano_inicio");
	if (ano_inicio == null && ano_inicio == "") {
		var campoDiasRes=eval("window.opener.document.frmDatos.idDiasRes");
		limite_inferior = sumaDiasFecha(fechaHoy, parseInt(campoDiasRes.value, 10));
		ano_inicio = sumaDiasFecha(limite_inferior, parseInt(campoDiasRes.value, 10)).substring(0,4);
	}
	var ano_fin=extraeParam("ano_fin");
	ano=parseInt(ano,10);
	if(ano_inicio!=null) ano=parseInt(ano_inicio,10);		if(ano_fin==null) ano_fin=ano+10;
	else ano_fin=parseInt(ano_fin,10);
	
	var objSelect=obtenerElemento("cboAno","");
	
	var objOption = null;
	
	if(document.all){	//Explorer
		for(i=ano;i<ano_fin;i++){
			objOption = document.createElement("OPTION");
			objOption.text=i;
			objSelect.add(objOption);
		}
	}else{				//Netscape
		for(i=ano;i<ano_fin;i++){
			objSelect.options[objSelect.options.length]=new Option(i,i);
		}
	}
}


function obtenerElemento(raiz,ord){
	var aux_el;
	if(document.all) {
		aux_el=document.all(raiz+ord); //IE
	}
	else aux_el=document.getElementById(raiz+ord);  //NS
	return aux_el;
}


function limpiarTabla(){
	for(i=0;i<42;i++){
		var item=obtenerElemento("td",i);
		if (document.getElementById("naveg").value == "Firefox") {//El navegador es Firefox			item.textContent="";		} else {//El navegador es cualquier otro diferente a Firefox			item.innerText="";		}
		item.className="";
		item.style.width=22;
		item.style.height=17;
		item.innerHTML="<img src='"+img_fondo+"' border=0 width=22 height=17>";
    }
}


function formatearLimites(dia,mes,ano){
	var aux_lim;
	if(limite_superior!=null){
		if(limite_superior.indexOf("/")>0){ //Es una fecha
			aux_lim=new Date(parseInt(limite_superior.substring(6,10),10),
			                 (parseInt(limite_superior.substring(3,5),10))-1,
		                      parseInt(limite_superior.substr(0,2),10));
			
		}else{	//Es un número a sumar a una fecha
			aux_lim=new Date(parseInt(ano,10),
			                 parseInt(mes,10),
			                 parseInt(dia,10)+parseInt(limite_superior), 10);	//sumamos los días
		}		

		limite_superior=aux_lim;
	}
	

	if(limite_inferior!=null){
		if(limite_inferior.indexOf("/")>0){ //Es una fecha
			aux_lim=new Date(parseInt(limite_inferior.substring(6,10),10),
			                 (parseInt(limite_inferior.substring(3,5),10))-1,
		                      parseInt(limite_inferior.substr(0,2),10));
			
		}else{		//Es un número a sumar a una fecha
			aux_lim=new Date(parseInt(ano,10),
			                 parseInt(mes,10),
			                 parseInt(dia,10)+parseInt(limite_inferior, 10));	//sumamos los días

		}	

		limite_inferior=aux_lim;
	} 
	
}


function determinarDias(mes,ano){
	/*Recibe el mes y el año y devuelve el nº de días de ese mes.
	Funcion necesaria dado que javascript no provee una función nativa que determine los días del mes.
	
	Recorremos los días del mes desde el 28 (menor día posible en un mes) al 32 (mayor posible+1)
	cuando cambia de mes, paramos de contar, porque javascript, si se exceden los días de un mes, pasa al mes siguiente.
	*/
	for(i=28;i<=32;i++){
		fechaDet=new Date(ano, mes,i)
		if(fechaDet.getMonth()!=mes){
			resultado=i-1
			return resultado
			break;
		}
	}
}


function cambiar_mes(cual){	
	mes=this[nombre_tabla+"_friso"].mes+1
	ano=this[nombre_tabla+"_friso"].ano
	
	if(cual=="-1"){
		if(mes==1){ mes=12; ano-=1; }
		else mes-=1
	}
	
	if(cual=="1"){
		if(mes==12){ mes=1; ano+=1; }
		else mes+=1
	}
	calendario(mes,ano)
}


function cambiar_ano(cual){	
	mes=this[nombre_tabla+"_friso"].mes+1
	ano=this[nombre_tabla+"_friso"].ano
	
	trace(">"+mes+"/"+ano)
	if(cual=="-1")	ano-=1;
	if(cual=="1")	ano+=1;
	
	calendario(mes,ano)
}


function comprobarHoy(mes,ano){
	/*
	Recibe el mes y el año y devuelve el día en el que estamos en caso de que 
	corresponda al mes en curso. En caso contrario devuelve -1
	*/
	fechaDet=fechaHoy;
	var diaDet = parseInt(fechaDet.substring(6,8), 10);
	var mesDet = parseInt(fechaDet.substring(4,6), 10) - 1;
	var anioDet = parseInt(fechaDet.substring(0,4),10); 
	if(mesDet==mes && anioDet==ano) {
		return diaDet;
	}
	else { 
		return -1;
	}
}

//Coge la fecha del día siguiente al día actual
function sumaDiasFecha(fecha, valor) {
	   var dia = parseInt(fecha.substring(6,8), 10);
	   var mes = parseInt(fecha.substring(4,6), 10);
	   var anio = parseInt(fecha.substring(0,4),10);
	   var date = new Date(anio, mes, dia);
	   var milisegundos=valor*24*60*60*1000;
	   var tiempo=date.getTime();
	   date.setTime(tiempo+milisegundos);

		dia=date.getDate();		
		var strDia = dia + "";
		if (dia < 10) {
			strDia = "0" + dia;
		}				var strMes = mes + "";		
		if (mes < 10) {
			strMes = "0" + mes;
		}
	    return strDia+"/"+strMes+"/"+anio;
}

function extraeParam(parametro){	//Exclusiva para el calendario. No usar la habitual
	var param=window.location.search;
	if(param.indexOf(parametro)!=-1){
		param=param.substr(param.indexOf(parametro)+(parametro.length+1),param.length-1);
		
		if(param.indexOf("%26")!=-1){
			param=param.substr(0,param.indexOf("%26"));
		}else{
			if(param.indexOf("&")!=-1){
				param=param.substr(0,param.indexOf("&"));
			}	
		}
		return param;
	}else{
		return null
	}
}

	
	function devuelveNumNoches(sFecha1, sFecha2) {				
		var lNumNoches = 0;
		if (sFecha1 != null && sFecha1 !="" && sFecha2 != "" && sFecha2 != null) {
			var dFecha1 = new Date (sFecha1.substring(6,10), sFecha1.substring(3,5), sFecha1.substring(0,2));
			var dFecha2 = new Date (sFecha2.substring(6,10), sFecha2.substring(3,5), sFecha2.substring(0,2));
			lNumNoches = (dFecha2.getTime()-dFecha1.getTime())/(24*60*60*1000);
		 }
		 return lNumNoches;
	}

	function convertirFechaABBDD(sFecha) {
		return sFecha.substring(6,10)+sFecha.substring(3,5)+sFecha.substring(0,2);
	}		function SelectSingleNode(xmlDoc, rutaElemento){	if(window.ActiveXObject){    		return xmlDoc.selectSingleNode(rutaElemento);	}else{		var xpe = new XPathEvaluator();		var nsResolver = xpe.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);		var results = xpe.evaluate(rutaElemento,xmlDoc,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE, null);    		return results.singleNodeValue; 	}}	
