

var carpetaPrincipal = "inca_trail";



// 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 yearNewFormat = 2010;     // Anio que disponibilidad es obtenida de diferente forma (negativos. Ej. -200 es 200 espacios vendidos) 

var totalEspacios = 500;      // Total espacios por dia

var newFormatFlag = false; 



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;



Lista_Meses_Anios();

procesar();



function nuevoFormato()

{	

	mon = parseInt(document.getElementById("Mes").value)+1;

	yea = document.getElementById("Anio").value;



	if (fechaAnumero(1,2,yearNewFormat) < fechaAnumero(1,mon,yea))

		newFormatFlag = true; 

	else	

		newFormatFlag = false; 

}	



function formatearDispo(espacios)

{

	if (newFormatFlag)

		return parseInt(totalEspacios) + parseInt(espacios);

	else

		return espacios;

}



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() //Funcion que aņade las diferentes opciones a la lista de meses

{

	var i, longitud;

	for (i=0; i<Meses.length; i++)

  	{

  		longitud = window.document.formulario1.Mes.length;

  		window.document.formulario1.Mes[longitud] = new Option(Meses[i], i,"","");

  	}	

	selecMes = new Date().getMonth();

	if (selecMes == 1) //para febrero se selecciona marzo

		selecMes++; 

	window.document.formulario1.Mes.selectedIndex=selecMes;	//Se selecciona el mes actual

	

	year = new Date().getFullYear();	

	for (i=year; i<year+4; i++)

  	{

  		longitud = window.document.formulario1.Anio.length;

  		window.document.formulario1.Anio[longitud] = new Option(i, i,"","");

  	}	

	window.document.formulario1.Anio.selectedIndex = 0;

	window.document.formulario1.Mes.options[1].disabled = true;

}



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);

	if (numSelecFecha > numLimite)

	{

		crearCalendarioHtml(null,true);

		mostrarInfoProcesar();	 

		if (unaVez)

		{

			procesarMesDisponible();

			unaVez = false;

		}

	}

	else

	{

		  try 

		  {

			  eval(request.responseText);

			  if (correctoPhp)

			  {	  

				  crearCalendarioHtml(fieldList,false);

				  mostrarInfoProcesar();	 

				  if (unaVez)

				  {

						procesarMesDisponible();

						unaVez = false;

				  }

			  }

		  }

		  catch (err)

		  {	  

				window.document.getElementById('calendario').innerHTML="<table class='copyright'><tr><td height=\"59\" align='center'style='font-size:12px; color: #CC3333;'>Please Contact us:<br> USA & Canada 1800.930.4319<br> UK 0800.242.5434</td></tr><tr><td align='center' style='font-size:14px;'><br>Review updated permit availability information in the following .PDF electronic documents.<br>Make sure permits are available for the date you want to start the trek<br>and proceed to booking:<br><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=1&amp;anio=2010&amp;anioAut=2009&amp;formato=PDF' target='_blank'><u class='normal'>January 2010</u></a><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=3&anio=2010&anioAut=2010&formato=PDF' target='_blank'><u class='normal'>March 2010</u></a><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=4&anio=2010&anioAut=2010&formato=PDF' target='_blank'><u class='normal'>April 2010</u></a><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=5&anio=2010&anioAut=2010&formato=PDF' target='_blank'><u class='normal'>May 2010</u></a><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=6&anio=2010&anioAut=2010&formato=PDF' target='_blank'><u class='normal'>June 2010</u></a><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=7&anio=2010&anioAut=2010&formato=PDF' target='_blank'><u class='normal'>July 2010</u></a><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=8&anio=2010&anioAut=2010&formato=PDF' target='_blank'><u class='normal'>August 2010</u></a><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=9&anio=2010&anioAut=2010&formato=PDF' target='_blank'><u class='normal'>September 2010</u></a><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=10&anio=2010&anioAut=2010&formato=PDF' target='_blank'><u class='normal'>October 2010</u></a><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=11&anio=2010&anioAut=2010&formato=PDF' target='_blank'><u class='normal'>November 2010</u></a><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=12&anio=2010&anioAut=2010&formato=PDF' target='_blank'><u class='normal'>December 2010</u></a><br><a href='http://nahui.inc-cusco.gob.pe/Kratos/site/reportes/DisponibilidadPorMes.cfm?mes=1&anio=2011&anioAut=2011&formato=PDF' target='_blank'><u class='normal'>January 2011</u></a><br><br><a href='http://www.incatrailreservations.com/forms/inca-trail-booking.php'><u style='font-size:16px;'>Click here to Book the Inca Trail Now</u></a></td></tr></table>";

		  }

	}

}



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());

	  nuevoFormato();

	 	   

	  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 =  formatearDispo(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 =  formatearDispo(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;

	if (dispo != 0)	

	{

		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='Book now'><br><span style='font-size: 12px'>"+dispo+"</span> spaces<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();

	mesNro = parseInt(document.getElementById("Mes").value)+1;

	urlLink = "&Mes="+mesNro+"&Anio="+document.getElementById("Anio").value; 

    urlLink = getURL() + carpetaPrincipal +'/php/result_array_ajax.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()

{   

	restaurar();

	ahora = new Date();  

	hour   = ahora.getHours();

    minute = ahora.getMinutes();

    second = ahora.getSeconds();

	if (hour   < 10)  hour   = "0" + hour;   

    if (minute < 10)  minute = "0" + minute; 

    if (second < 10)  second = "0" + second; 

    timeString = hour + ' : ' + minute + ' : ' + second;

	m = document.getElementById("Mes");		

	document.getElementById("fechaHoraActual").innerHTML = 'Information updated &rarr;&nbsp;&nbsp;&nbsp;&nbsp;'+m[ahora.getMonth()].text+" "+ahora.getDate()+", "+ahora.getFullYear()+" at "+timeString;

	document.getElementById('tituloMes').innerHTML = splitVerticalText(m[m.selectedIndex].text+"  "+document.getElementById("Anio").value);

} 



function procesarMesDisponible()

{   

    urlLink = getURL() + carpetaPrincipal +'/php/month_permits_ajax.php'; 

    Ajax2 (urlLink,getMesDisponible);

}



function getMesDisponible()

{

  	eval(request2.responseText);

	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;

}





