
//var carpetaPrincipal = "FTP/ITR/calendar_ajax_ava";
var carpetaPrincipal = ".com";

// Hasta el 8 de enero del anio actual muestra Pre-Reserve de Marzo en adelante, despues del 8 de enero consulta la Base de Datos
var dayLimit = 8;      // 8 
var monthLimit = 1;	   // Enero	 			   

var totalEspacios = 0;      // Variable depende de XML

var Meses = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
var Dias = new Array ('Sunday','Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var Dias_Mes = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var unaVez = true;
var success;

main();

function main()
{	
	urlLink = "&funcion=get_month_DB_ajax"; 
	urlLink = getURL() + carpetaPrincipal +'/paquetes/php/funciones_servidor.php?' + urlLink;	
	Ajax3 (urlLink, startCalendar);
}

function startCalendar()
{
  	eval(request3.responseText);
	if (success)
	{
		mes_numerico = parseInt(m_disp)-1;
		Lista_Meses_Anios(mes_numerico, a_disp);
		document.getElementById("mesDisponible").innerHTML = "<span style='color:#CC3333;font-weight:bold'>"+document.getElementById('Mes')[mes_numerico].text+" "+a_disp+"</span>";	  
	}
	else
	{
		selecMes = new Date().getMonth();
		selecAnio = new Date().getFullYear();
		Lista_Meses_Anios(selecMes, selecAnio);		
	}			
	procesar();
}	

function fechaAnumero (dia, mes, anio)
{   
    if(dia < 10) fecDia="0"+dia;
	else	fecDia=""+dia;            
    if(mes < 10) fecMes="0"+mes;	
	else	fecMes=""+mes;            
    fecha = anio+fecMes+fecDia;
    valor = parseInt(fecha); 
    return valor;
}

function Lista_Meses_Anios(m_disp, a_disp)
{
	var i, longitud = 0;
	for (i=0; i<Meses.length; i++)  	
  		window.document.formulario1.Mes[i] = new Option(Meses[i], i,"","");
	window.document.formulario1.Mes.options[1].disabled = true;	
	
	year = new Date().getFullYear();	
	for (i=year; i<year+4; i++)
  	{  		
  		window.document.formulario1.Anio[longitud] = new Option(i, i,"","");
		longitud++;
  	}		

	if (m_disp == 1) //para febrero se selecciona marzo
		m_disp++; 
	window.document.formulario1.Mes.selectedIndex = m_disp;	//Se selecciona el mes actual	
	window.document.formulario1.Anio.selectedIndex = a_disp - year;

}

function Bisiesto(year) 
{
	if ((year % 4 == 0) && (( year % 100 != 0) || (year % 400 ==0)))
		  return true;
	else
  		  return false;
}

function getDays(month, year)
{
	if (Bisiesto(year)) 
  		Dias_Mes[1]=29;			 // solo para Febrero
	else
  		Dias_Mes[1]=28;
	return Dias_Mes[month];
}

function muestra()
{
	ahora = new Date();  	
	da = ahora.getDate();
	mo = ahora.getMonth()+1;
	ye = ahora.getFullYear();
	if (mo <= monthLimit)
	{
		if (mo == monthLimit && da > dayLimit)
			yearLimite = ye+1;		
		else		
			yearLimite = ye;
	}
	else
		yearLimite = ye+1;		
	numLimite = fechaAnumero(dayLimit,monthLimit,yearLimite);
	numSelecFecha = fechaAnumero(1,parseInt(document.getElementById("Mes").value)+1,document.getElementById("Anio").value);
		
	respo = request.responseText;
	x = respo.indexOf("var fieldList");
	if (x != -1)
		respo = respo.substring(x, respo.length);
  	eval(respo);
	
	if (numSelecFecha > numLimite)	
		crearCalendarioHtml(null,true);
	else
		crearCalendarioHtml(fieldList,false);		 
	mostrarInfoProcesar(dayCopied);	 
	if (unaVez && !success)
	{
		procesarMesDisponible();
		unaVez = false;
	}	
}

function crearCalendarioHtml(fieldList,prereserve)
{
	  var Contenido ="<table class='copyright' border=1 cellpadding=1 cellspacing=0><tr>";
	  var fecha;
	  var dias_mes;
	  var j=1;
	  fecha=new Date(parseInt(window.document.formulario1.Anio.value),parseInt(window.document.formulario1.Mes.value),1);
	  dias_mes=getDays(fecha.getMonth(), fecha.getFullYear());
	 	   
	  for (i=0;i<7;i++)
		 Contenido=Contenido + "<th>" + Dias[i] + "</th>";
	  Contenido=Contenido+ "</tr><tr>";
	  for (i=0; i<fecha.getDay();i++)
		 Contenido=Contenido+ "<td></td>";
	  for (i=fecha.getDay();i<7;j++,i++)
	  {
		 if(!prereserve) 
		 {			 
	 	 	 capacidad =  totalEspacios + parseInt(fieldList[j-1]);
			 Contenido=Contenido+ tableAsLink(capacidad,j-1);
		 }
		 else
			 Contenido=Contenido+ prereserveAsLink(j-1);
	  }
	
	  while (j<=dias_mes)
	  {
		 Contenido=Contenido+"</tr><tr>"
		 for (i=0; i<7 & j<=dias_mes; j++,i++)
		 {
			 if(!prereserve) 
		 	 {
				 capacidad =  totalEspacios + parseInt(fieldList[j-1]);
			 	 Contenido=Contenido+ tableAsLink(capacidad,j-1);
			 }
	   	     else
				 Contenido=Contenido+ prereserveAsLink(j-1);
		 }
	  }
	  Contenido=Contenido+"</tr></table>";
	  window.document.getElementById('calendario').innerHTML=Contenido;
}

function prereserveAsLink(day)
{
	cadena = "<td align='center' width=90 height=60 "; 
	day = day+1;
	mesNro = parseInt(document.getElementById("Mes").value) + 1;	
	cadena = cadena+" style=\"cursor:pointer;\" onmouseover= \"this.style.backgroundColor = '#CEF9C1'\" onmouseout=\"this.style.backgroundColor = '#FFFFFF'\" onclick=\"submitFormulario(document.getElementById('Anio').value,"+mesNro+","+day+")\"><span style='font-weight: bold;'>"+day+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>";
	capacidadStr = "<br><img src='images/check.jpg' alt='Pre-reserve'><br><br><span style='font-weight: bold;'>Pre-reserve<span/>";				
	cadena = cadena+capacidadStr+"</td>";	
	return cadena;	
}

function submitFormulario(anio, mes, dia)
{	
	mesStr = "";
	dayStr = "";
	if (mes < 10) 	mesStr = "0"+mes;
	else		mesStr = mes;
	if (dia < 10) 	dayStr = "0"+dia;			
	else		dayStr = dia;
	document.getElementById("fecha").value = anio+"-"+mesStr+"-"+dayStr;
	document.formulario1.submit();
}

function tableAsLink(dispo, day)
{
	cadena = "<td align='center' width=90 height=60 "; 
	day = day+1;
	mesNro = parseInt(document.getElementById("Mes").value) + 1;	
	anioNro = parseInt(document.getElementById("Anio").value);	
	D_fecha = new Date(1970,1,1,0,0,0,0);   //initialization
	D_fecha.setFullYear(anioNro, mesNro-1, day);	
	D_ahora = new Date();
	D_ahora.setDate(D_ahora.getDate()+2);          // INC no vende permisos en los tres dias siguientes de hoy
	
	if (D_fecha < D_ahora)
	{
		cadena = cadena+"><span style='font-weight: bold;'>"+day+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>";
		capacidadStr = "<br><br><br><br><br>";		
	}
	else
	{
		if (dispo != 0)	
		{
			cadena = cadena+" style=\"cursor:pointer;\" onmouseover= \"this.style.backgroundColor = '#CEF9C1'\" onmouseout=\"this.style.backgroundColor = '#FFFFFF'\" onclick=\"submitFormulario(document.getElementById('Anio').value,"+mesNro+","+day+")\"><span style='font-weight: bold;'>"+day+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>";
			capacidadStr = "<br><img src='images/check.jpg' alt='Book now'><br><span style='font-size: 12px'>"+dispo+"</span> permits<br><span style='font-weight: bold;'>Book now<span/>";		
		}
		else
		{
			cadena = cadena+" onmouseover= \"this.style.backgroundColor = '#EED5B7'\" onmouseout=\"this.style.backgroundColor = '#FFFFFF'\" ><span style='font-weight: bold;'>"+day+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>";
			capacidadStr = "<br><img src='images/bad.jpg' alt='sold out!'><br><br><span style='color: #CC3333;'>Sold Out!<span/>";		
		}
	}
	cadena = cadena+capacidadStr+"</td>";	
	return cadena;	
}

function procesar()
{
	bloquear();
	mesStr = "";
	mesNro = parseInt(document.getElementById("Mes").value) + 1;
	if (mesNro < 10) 	
		mesStr = "0"+mesNro;
	else	
		mesStr = mesNro;
	urlLink = "&Mes="+mesStr+"&Anio="+document.getElementById("Anio").value+"&funcion=result_array_ajax"; 
	urlLink = getURL() + carpetaPrincipal +'/paquetes/php/funciones_servidor.php?' + urlLink;
	
	Ajax (urlLink,muestra);
}

function getURL()
{
 	 urlMain = window.location.href;
 	 pos = urlMain.indexOf(carpetaPrincipal);    
  	 return urlMain.substr(0,pos); 
}

function innerTexto(idElement, stringInner)
{
	if(document.all)
		document.getElementById(idElement).innerText = stringInner;
	else	
		document.getElementById(idElement).textContent = stringInner;			
}

function bloquear()
{
	document.getElementById("Mes").disabled = true;
	document.getElementById("Anio").disabled = true;
	document.getElementById("calendario").innerHTML = 
	"<table class='copyright'><tr><td align='center'  style='font-size:12px; font-weight:bold'>Loading...<br>www.IncaTrailReservations.com<br>is gathering information</td></tr></table>"
	innerTexto('fechaHoraActual','');
	innerTexto('tituloMes','');
}

function restaurar()
{
	document.getElementById("Mes").disabled = false;
	document.getElementById("Anio").disabled = false;
}

function mostrarInfoProcesar(dayCopied)
{   
	restaurar(); 
	var dayCopiedArr = dayCopied.split("-");
	ye = dayCopiedArr[0];
    mo = parseInt(dayCopiedArr[1]);
    da = dayCopiedArr[2];
    timeString = '07 : 00 : 00';
	m = document.getElementById("Mes");	
	document.getElementById("fechaHoraActual").innerHTML = 'Information updated &rarr;&nbsp;&nbsp;&nbsp;&nbsp;'+m[mo-1].text+" "+da+", "+ye+" at "+timeString;	
	document.getElementById('tituloMes').innerHTML = splitVerticalText(m[m.selectedIndex].text+"  "+document.getElementById("Anio").value);
} 

function procesarMesDisponible()
{   
	urlLink = "&funcion=month_permits_ajax";
    urlLink = getURL() + carpetaPrincipal +'/paquetes/php/funciones_servidor.php?' + urlLink; 
    Ajax2 (urlLink,getMesDisponible);
}

function getMesDisponible()
{
	respo = request2.responseText;
	x = respo.indexOf("var mesDispo");
	if (x != -1)
		respo = respo.substring(x, respo.length);
  	eval(respo);
	document.getElementById("mesDisponible").innerHTML = "<span style='color:#CC3333;font-weight:bold'>"+mesDispo+"</span>";	  
}

function splitVerticalText(string)
{
	cadenaVertical = "";
	for( x = 0; x < string.length; x++)	
		cadenaVertical = cadenaVertical+string.charAt(x).toUpperCase()+"<br>"; 
	return cadenaVertical;
}

var request;     

function Ajax(url, funcion)
{
    if (window.XMLHttpRequest)    // Mozilla, IE7, Safari, etc
        request = new XMLHttpRequest();    
    
    if (window.ActiveXObject)     // IE5, IE6
        request = new ActiveXObject ("Microsoft.XMLHTTP");
    
    request.onreadystatechange = 
              function ()
              {
                  if(request.readyState == 4) // Conexion OK
                  {
                       if(request.status == 200)   // Hay respuesta del servidor      
                       {
                            funcion.call();
                       }
                   }
              };
    request.open("POST",url,true);          
    request.send(null);
    return this;
}

var request2;   

function Ajax2(url, funcion)
{
    if (window.XMLHttpRequest)    // Mozilla, IE7, Safari, etc
        request2 = new XMLHttpRequest();    
    
    if (window.ActiveXObject)     // IE5, IE6
        request2 = new ActiveXObject ("Microsoft.XMLHTTP");
    
    request2.onreadystatechange = 
              function ()
              {
                  if(request2.readyState == 4) // Conexion OK
                  {
                       if(request2.status == 200)   // Hay respuesta del servidor      
                       {
                            funcion.call();
                       }
                   }
              };
    request2.open("POST",url,true);          
    request2.send(null);
    return this;
}

var request3;   

function Ajax3(url, funcion)
{
    if (window.XMLHttpRequest)    // Mozilla, IE7, Safari, etc
        request3 = new XMLHttpRequest();    
    
    if (window.ActiveXObject)     // IE5, IE6
        request3 = new ActiveXObject ("Microsoft.XMLHTTP");
    
    request3.onreadystatechange = 
              function ()
              {
                  if(request3.readyState == 4) // Conexion OK
                  {
                       if(request3.status == 200)   // Hay respuesta del servidor      
                       {
                            funcion.call();
                       }
                   }
              };
    request3.open("POST",url,true);          
    request3.send(null);
    return this;
}

