function color_nuevo(nuevo){
	source=event.srcElement
	if (source.tagName=="TR"||source.tagName=="TABLE")
	return
	while(source.tagName!="TD")
	source=source.parentElement
	//alert(source.parentElement);
	if (nuevo == 1) {nuevo = "#2e88ce";}
	
	
	
	if (source.style.backgroundColor!=nuevo&&source.id!="ignore")
	{source.style.backgroundColor=nuevo;}
}

function color_antiguo(viejo){
//if (event.fromElement.contains(event.toElement)||source.contains(event.toElement)||source.id=="ignore")
//return
	if (source)
	{
		if (event.toElement!=source)
		{
			if (viejo == 1) {viejo = "#999A9C";}
			if (viejo == 2) {viejo = "#d0e4f4";}
			source.style.backgroundColor=viejo
		}
	}
}

function cambia_color_texto(indice,color)
{
	if (color == 1) {color = "#d0e4f4";}
	if (color == 2) {color = "#2e88ce";}
	eval("link"+indice+".style.color='"+color+"'");
}


var qDiaEsHoyC;			/*indica el dia q estamos actualmente*/
var qMesEsHoyC;
var dia_pulsado;		/*indica el dia en q ese ha pulsado*/
var mes_today;			/*indica el mes q estamos actualmente*/
var anio_today;			/*indica el año en el q nos encontramos*/
var anioSel;
var opSel;				/*indica el numero de calendario seleccionado*/
var qTipo;				/*indica el campo a rellenar*/

//pinta la fila que contiene los dias de las semanas
var wCeldas = parseInt((196/7),10);
var tDias = "<table width=100% border=0 cellpadding=0 cellspacing=0 class=calendar>";
tDias += "<tr bgcolor=#82b8e3><td width=10></td>"
	for (var ind=0;ind<tDay.length;ind++)
	{	tDias += "<td class=txtDay align=center width="+wCeldas+" height=20>" + tDay[ind] + "</td>"; }
tDias += "<td width=10></td></tr></table>";
//tDias +="<table width=100% border=0 cellpadding=0 cellspacing=0><tr><td height=10><spacer type=block height=10/></td></tr></table>";

function posInicio(mes,anio_today)
{	/* calcular la posicion q debe de comenzar el mes*/
	var posIni = new Date(anio_today,mes,1);
	//var iFor = parseInt(posIni.getDay(),10) + 1;
	var iFor = parseInt(posIni.getDay(),10);
	return iFor;
}



function pintarMes(mes)
{	
	aux_mes = mes.toString()
	if(aux_mes.length < 2){aux_mes="0"+aux_mes}

	aux_monthLimite = monthLimite.toString()
	if(aux_monthLimite.length < 2){aux_monthLimite="0"+aux_monthLimite}
					
	var dateCald = anio_today +""+ aux_mes
	var dateCaldLimit = yearLimite +""+ aux_monthLimite
	
	dateCald = parseInt(dateCald,10)
	dateCaldLimit = parseInt(dateCaldLimit,10)		
	//pinta la cabecera que contiene el mes y el año del calendario
	var avance = "<table width=100% cellspacing=0 cellpadding=0 border=0 class=calendar>";
	/* puedo avanzar unicamente en el mes seleccionado*/
	avance += "<tr bgcolor=#2e88ce>";
	avance += "<td width=20%>&nbsp;</td>";
	if (mes > month)
		avance += "<td><a href='javascript:redibujar("+(mes-1)+")'><img src=img/arrow_back.gif border=0></a></td>";
	else
	{	if (anio_today > yYear)
		{	avance += "<td><a href='javascript:redibujar("+(mes-1)+")'><img src=img/arrow_back.gif border=0></a></td>"; }
	}
	avance += "<td width=60% height=24 align=center class=cabecera_calendario>"+tMeses[mes] +", "+ deE +" "+ anio_today +"</td>";
	if (dateCald < dateCaldLimit){
		avance += "<td><a href='javascript:redibujar("+(mes+1)+")'><img src=img/arrow_fwd.gif border=0></a></td>";
	}
	avance += "<td width=18% align=right><a href='javascript:closeCalendar()'><img src=img/close.gif alt='Cerrar/Close' title='Cerrar' border=0></a></td>";
	avance += "<td width=2%>&nbsp;</td>";
	avance += "</tr>";
	avance += "</table>";
	return avance;
}

/*pintar la tabla de dias*/
//Pinta el pie del calendario
function tOK()
{	var objCalendar = "<table width=100% cellspacing=0 cellpadding=0 border=0 bgcolor=#E9F3FB>";
		objCalendar += "<tr bgcolor=#2e88ce><td colspan=2 height=5><spacer type=block height=10></td></tr>";
		objCalendar += "<tr bgcolor=#2e88ce><td align=right height=5></td><td width=10><spacer type=block width=10></td></tr>";
	objCalendar += "</table>";
	return objCalendar;
}

function dibujar(qDiaEsHoy,qMesEsHoy,diaSel,mes,aYear,opCion,qType)
{	
	
	qDiaEsHoyC = qDiaEsHoy;
	qMesEsHoyC = qMesEsHoy;

	dia_pulsado = diaSel; mes_today = mes; anioSel = aYear; anio_today = anioSel;
	opSel = opCion; qTipo = qType;
	redibujar(mes);
}

var nVeces;
var source;
function redibujar(mes)
{	tMonth[1] = 28;
	if (mes > 11) { anio_today++; mes = 0; }
	if (mes < 0) { anio_today--; mes = 11; }
	
	var iFor = posInicio(mes,anio_today);
	pMes = pintarMes(mes);
	if (isBisiesto(anio_today)) tMonth[1]+=1;

	var nfilas = parseInt((tMonth[mes]/7),10); /*numero d filas a dibujar*/
	var rfilas = parseInt((tMonth[mes]%7),10); /*numero restante d filas a pintar*/
	if (rfilas > 0) { nfilas +=rfilas; }
	nfilas++;

	/*numero de veces q se tiene q repetir*/
	nVeces = (nfilas*7);
	var cCalendar = "<table border=0 width=100% cellpadding=0 cellspacing=0 class=calendar bgcolor=#d0e4f4>";
	cCalendar += "<tr bgcolor=#d0e4f4><td width=10><spacer type=block width=10></td>";
	var cDias = 1;

	if (iFor == 0){ iFor= 7;}
	for (var ind=1;ind<=nVeces;ind++)
	{	CssClass = "days";
		cCalendar += "<td  id='cell"+ind+"' align=center width="+wCeldas
		if ( (ind >= iFor) && (cDias <= tMonth[mes]) )
		{	/*pinto el dia en cuestion*/
			if ( (parseInt(cDias,10)==parseInt(dia_pulsado,10)) && (mes==mes_today) && (anio_today==anioSel))
			{	cCalendar+=" onMouseover='color_nuevo(1);cambia_color_texto("+ind+",1);' onMouseout=\"color_antiguo(1);\" bgcolor=#999A9C class=daysSel height=20 "; CssClass = "daysSel"; }
			else
			{	
				
				if ( (mes==monthLimite) && (anio_today==yearLimite) )
				{	if (cDias > dayLimite)
					{}
					else
					{	cCalendar+=" onMouseover='color_nuevo(1);cambia_color_texto("+ind+",1);' onMouseout='color_antiguo(2);cambia_color_texto("+ind+",2);' height=20 "; }
				}
				else
				{	if ((mes > monthLimite) && (anio_today >= yearLimite))
					{}
					else
					{	if ( (parseInt(cDias,10)<parseInt(qDiaEsHoyC,10)) && (mes==qMesEsHoyC) && (anio_today==yYear))
						{ }
						else
						{	cCalendar+=" onMouseover='color_nuevo(1);cambia_color_texto("+ind+",1);' onMouseout='color_antiguo(2);cambia_color_texto("+ind+",2);' height=20 "; }
					}
				}
			
			 }
			if ( (mes==monthLimite) && (anio_today==yearLimite) )
			{	if (cDias > dayLimite)
				{	cCalendar += "><span class=nodaysSel>O<s>"+ cDias +"</s></span>"; }
				else
				{	cCalendar += " onclick='javascript:recogerDays("+ cDias +","+ mes +","+ anio_today +","+ind+");indicarFecha()' style='cursor:hand'><a href='javascript:recogerDays("+ cDias +","+ mes +","+ anio_today +","+ind+");indicarFecha()' class="+CssClass+" id='link"+ind+"'>"+cDias+"</a>"; }
			}
			else
			{	if ((mes > monthLimite) && (anio_today >= yearLimite))
				{	cCalendar += "><span class=nodaysSel id='link"+ind+"'><s>"+ cDias +"</s></span>"; }
				else
				{	if ( (parseInt(cDias,10)<parseInt(qDiaEsHoyC,10)) && (mes==qMesEsHoyC) && (anio_today==yYear))
					{	cCalendar += "><span class=nodaysSel id='link"+ind+"'><s>"+ cDias +"</s></span>"; }
					else {	
						if ( (parseInt(cDias,10)==parseInt(qDiaEsHoyC,10)) && (mes==qMesEsHoyC) && (anio_today==yYear)){
							if (hora_actual >= 0)
							{cCalendar += "><a class="+CssClass+" id='link"+ind+"'>"+cDias+"</a>";}
							else
							{cCalendar += "><a class="+CssClass+" id='link"+ind+"' href='javascript:recogerDays("+ cDias +","+ mes +","+ anio_today +","+ind+");indicarFecha()'>"+cDias+"</a>";}
						}else{
							cCalendar += "onclick='javascript:recogerDays("+ cDias +","+ mes +","+ anio_today +","+ind+");indicarFecha()' style='cursor:hand'><a href='javascript:recogerDays("+ cDias +","+ mes +","+ anio_today +","+ind+");indicarFecha()' class="+CssClass+" id='link"+ind+"'>"+cDias+"</a>"; 
						}
					}
				}
			}
			cDias++;
		}
		else
		{	cCalendar +=" onMouseout=color_antiguo('#d0e4f4');><spacer type=block width=1 height=1>"; }
		cCalendar +="</td>";

		if ((ind%7) == 0)
		{	/*cierro el tr*/
			cCalendar +="<td width=10><spacer type=block width=10></td></tr><tr bgcolor=#d0e4f4><td width=10><spacer type=block width=10></td>";
		}
	}
	cCalendar += "</tr>";
	cCalendar += "</table>";
//	cCalendar += "<table width=100% border=0 cellpadding=0 cellspacing=0><tr bgcolor=#ffffff><td height=11><spacer type=block height=11></td></tr></table>";
	var oCalendar = tOK();
	var qMuestro = pMes;

	var lLayer = "lCalendar";
	var qMuestro = pMes+tDias+cCalendar+oCalendar;
	document.getElementById("lCalendar").innerHTML = qMuestro;
}

var aux_dia;		/*indica el dia q hemos seleccionado*/
var aux_mes;		/*indica el mes seleccionado*/
var aux_anio;		/*indica el ano seleccionado*/
var vDays; var vMonths; var vtxtDays; var vYears;

function recogerDays(dia,mes,anio,ind){
	var opSel_aux = opSel + 1;
	switch (qTipo){
		case 'S':
					limpiaEstilos();
					vDays = "BEGIN_DAY_0"+opSel_aux;
					vtxtDays = "TXT_BEGIN_DAY_0"+opSel_aux;
					vMonths = "BEGIN_MONTH_0"+opSel_aux;
					vYears = "BEGIN_YEAR_0"+opSel_aux;
					document.getElementById("cell"+ind).style.backgroundColor = "#858485"; 
					document.getElementById("link"+ind).className = "daysSel"
					break;

		case 'R':
					limpiaEstilos();
					vDays = "END_DAY_0"+opSel_aux;
					vtxtDays = "TXT_END_DAY_0"+opSel_aux;
					vMonths = "END_MONTH_0"+opSel_aux;
					vYears = "END_YEAR_0"+opSel_aux;
					document.getElementById("cell"+ind).style.backgroundColor = "#858485"; 
					document.getElementById("link"+ind).className = "daysSel"
					break;
	}
	aux_dia = dia; aux_mes = mes; aux_anio = anio;
}

function limpiaEstilos(){	
	for (var ind=0;ind<nVeces;ind++){		
		if(document.getElementById("link"+ind)!=null){
			document.getElementById("cell"+ind).style.backgroundColor = "#ffffff"; 
			document.getElementById("link"+ind).className = "days"
		}
	}
}


function indicarFecha(){	
	var lLayer = "lCalendar";
	/*comprobar q la fecha esta entre los rangos*/
	if (aux_anio<2000){	aux_anio += 1900; }
	var fechaSel = new Date(aux_anio,aux_mes,aux_dia);

	if ( (fechaSel <= fLimite) )
	{	jkk = parseInt(fechaSel.getDay(),10)-1;
		if (jkk == (-1)){ jkk = 6; }

		var auxiliar_dia = aux_dia - 1;
		/*para indicar el texto corto o largo*/
		if (booking){
			document.getElementById(vtxtDays).value = tDay_ext[jkk];
		}
		else{
			document.getElementById(vtxtDays).value = tDayLong[jkk];
		}
			
		aux_mes=aux_mes+1;
		if((""+aux_mes).length <2)aux_mes="0"+aux_mes;
		var indiceCombo = ""+aux_anio+aux_mes;
		var posicion=0;
		var tama = document.getElementById(vMonths).length;
		for (var i=0; i < tama; i++){			
			if(document.getElementById(vMonths).options[i].value==indiceCombo){
				posicion=i;
				break;
			}
		}
		document.getElementById(vDays).options.selectedIndex = auxiliar_dia;
		document.getElementById(vMonths).options.selectedIndex = posicion; 
		document.getElementById(vYears).value = aux_anio;

		/*este if determina si se tiene que cambiar varios combos de SALIDA*/
		if (swChangeDate){
			var opSel_aux = opSel + 1;
			aux_begin_day = auxiliar_dia;
			aux_begin_month = aux_mes;
			aux_yYear = aux_anio;
			cambioLasFechas(aux_mes,opSel_aux)
			//llamar a una funcion de la pagina de abajo
		}

		/*comprobar si el objeto de regreso seleccionado existe */
		if (qTipo == 'S'){	
			var opSel_aux = opSel + 1;
			var objDay = "END_DAY_0"+(opSel_aux);
			
			if (document.getElementById(objDay) != null){
				//document.getElementById(objDay).options.selectedIndex = document.getElementById(vDays).options.selectedIndex;
				var objtxt = "TXT_END_DAY_0"+opSel_aux;
				document.getElementById(objtxt).value = document.getElementById(vtxtDays).value;
				var objMonth = "END_MONTH_0"+(opSel_aux);
				var objYear = "END_YEAR_0"+(opSel_aux);
				//si el año de regreso es menor mostramos la advertencia y lo establecemos al mismo que de salida
				if(document.getElementById(objYear).value < document.getElementById(vYears).value){
					document.getElementById(objDay).options.selectedIndex = document.getElementById(vDays).options.selectedIndex;
					document.getElementById(objMonth).options.selectedIndex = document.getElementById(vMonths).options.selectedIndex;
					document.getElementById(objYear).value = document.getElementById(vYears).value;
				}
				//en caso de que el año sea mayor o igual comprobamos los meses y los dias
				else
				{
					//en caso de que el año sea el mismo
					if(document.getElementById(objYear).value == document.getElementById(vYears).value){
						
						//comprobamos si el mes de regreso es menor que el de salida, en ese caso procedemos a establecer el mes de regreso
						//para que sea el mismo que el de salida y mostramos la advertencia
						if(document.getElementById(objMonth).options.selectedIndex < document.getElementById(vMonths).options.selectedIndex){
							document.getElementById(objDay).options.selectedIndex = document.getElementById(vDays).options.selectedIndex;
							document.getElementById(objMonth).options.selectedIndex = document.getElementById(vMonths).options.selectedIndex;							
						}
						//en caso de que el mes de regreso sea mayor o igual que el de salida comprobamos el dia seleccionado
						else
						{							
							//si el mes de regreso es igual al de salida comprobamos el dia seleccionado y le mostramos la advertencia
							if(document.getElementById(objMonth).options.selectedIndex == document.getElementById(vMonths).options.selectedIndex){
								
								if(document.getElementById(objDay).options.selectedIndex < document.getElementById(vDays).options.selectedIndex){
									document.getElementById(objDay).options.selectedIndex = document.getElementById(vDays).options.selectedIndex;									
								}
							}
						}
					}
				}
			}			

	    }
		pintaTextoDiaSemana();		
		
		/* Para la página v3.RECCL2*/
        if((document.getElementById("dcon_02")!=null) && (document.getElementById("dcon_03")!=null))
        {
            var fecha = (auxiliar_dia + 1) + "/" + (aux_mes) + "/" + aux_anio;


			if (qTipo == 'S')
            {
                document.getElementById("dcon_02").value = fecha;
            }else
            {  			
                document.getElementById("dcon_03").value = fecha;
            }
        }

	}
	document.getElementById(lLayer).style.visibility = "hidden";
	cargar_fechas_finales();
	actualizar_dia();
}

//////////////////////////////////MECANICA DEL CALENDARIO////////////////////////////////////////
function diferencia_dias(tipo)
{
	formulario1 = document.getElementById("bookingForm");
	formulario2 = document.getElementById("formulario");
	
	var fecha_tmp_inicio_or = formulario1.fecha_entrada.value;
	var fecha_tmp_salida_or = formulario1.fecha_salida.value;
	
	var fecha_tmp_inicio, fecha_tmp_salida;
	
	fecha_tmp_inicio = String(fecha_tmp_inicio_or);
	fecha_tmp_inicio = fecha_tmp_inicio.split("/");		
	fecha_tmp_inicio = new Date(fecha_tmp_inicio[2],fecha_tmp_inicio[1]-1,fecha_tmp_inicio[0]);

	fecha_tmp_salida = String(fecha_tmp_salida_or);
	fecha_tmp_salida = fecha_tmp_salida.split("/");		
	fecha_tmp_salida = new Date(fecha_tmp_salida[2],fecha_tmp_salida[1]-1,fecha_tmp_salida[0]);

	/*dias_entre_fechas = Math.ceil((fecha_tmp_inicio-fecha_tmp_salida)/86400000);
	if (tipo == "abs")	{dias_entre_fechas = Math.abs(dias_entre_fechas);}	*/
	
	/* modificacion jar */
	horas_entre_fechas = Math.ceil((fecha_tmp_inicio-fecha_tmp_salida)/3600000);
	
	
	if (horas_entre_fechas%24==23){
		horas_entre_fechas++;
	}
	if (horas_entre_fechas%24==-23){
		horas_entre_fechas--;
	}
	dias_entre_fechas = Math.floor(horas_entre_fechas/24)
	if (tipo == "abs")	{dias_entre_fechas = Math.abs(dias_entre_fechas);}	
	/* fin modificacion jar */
	return dias_entre_fechas;
}

function cargar_fechas_finales(){
		
		dia_ini = document.getElementById("BEGIN_DAY_01").value;
		mes_ini = document.getElementById("BEGIN_MONTH_01").value;
		mes_ini = mes_ini.substr(4,2);
		anio_ini = document.getElementById("BEGIN_YEAR_01").value;
		
		dia_fin = document.getElementById("END_DAY_01").value;
		mes_fin = document.getElementById("END_MONTH_01").value;
		mes_fin = mes_fin.substr(4,2)
		anio_fin = document.getElementById("END_YEAR_01").value;
						
		fecha_inicial = dia_ini + "/" + mes_ini + "/" + anio_ini;
		fecha_final = dia_fin + "/" + mes_fin + "/" + anio_fin;
		
		formulario1 = document.getElementById("bookingForm");
		
		formulario1.fecha_entrada.value = fecha_inicial;
		formulario1.fecha_salida.value = fecha_final;
		actualizar_diferencia_dias();
		
}

function actualizar_diferencia_dias()
{
	dias_entre_fechas = diferencia_dias('');
		
		if (dias_entre_fechas > 0){
			var begin_day = document.getElementById("BEGIN_DAY_01");
			var end_day = document.getElementById("END_DAY_01");
			begin_day.options.selectedIndex = end_day.options.selectedIndex;
			
			var begin_month = document.getElementById("BEGIN_MONTH_01");
			var end_month = document.getElementById("END_MONTH_01");
			begin_month.options.selectedIndex = end_month.options.selectedIndex;
			
			var begin_year = document.getElementById("BEGIN_YEAR_01");
			var end_year = document.getElementById("END_YEAR_01");
			document.getElementById("BEGIN_YEAR_01").value =document.getElementById("END_YEAR_01").value;
			
			recargar_fechas_finales()
		}
}

function recargar_fechas_finales(){
		dia_ini = document.getElementById("BEGIN_DAY_01").value;
		mes_ini = document.getElementById("BEGIN_MONTH_01").value;
		mes_ini = mes_ini.substr(4,2);
		anio_ini = document.getElementById("BEGIN_YEAR_01").value;
		
		dia_fin = document.getElementById("END_DAY_01").value;
		mes_fin = document.getElementById("END_MONTH_01").value;
		mes_fin = mes_fin.substr(4,2)
		anio_fin = document.getElementById("END_YEAR_01").value;
						
		fecha_inicial = dia_ini + "/" + mes_ini + "/" + anio_ini;
		fecha_final = dia_fin + "/" + mes_fin + "/" + anio_fin;
		
		formulario1 = document.getElementById("bookingForm");
		
		formulario1.fecha_entrada.value = fecha_inicial;
		formulario1.fecha_salida.value = fecha_final;

}

