/** Calls the ajax_getcalendar module that returns the current month calendar for the selected room*/

var curMonthHTML = '';
var dateFrameStartHTML = '';

function loadroomcalendars(idHotel,idRoom,month,year){

    

	var url = "module=ajax_getcalendar&idRoom="+idRoom+"&idHotel="+idHotel+"&month="+month+"&year="+year;

	divCurMonth = Page.FindControl("home_currentmonthcalendar");

	divNextMonth = Page.FindControl("home_nextmonthcalendar");



	_idHotel = idHotel;

	_idRoom = idRoom;

	_month = month;

	_year = year;

//prompt ('',url);



    var objReservation = Page.FindControl("idReservation");

	if (objReservation.value){

		url += "&idReservation=" + objReservation.value;

	}



    //prompt('',url);



	xmlhttpPost(

		"index.php",

		url,

		"processCurrentRoomCalendar"

	);



}





function processCurrentRoomCalendar(res){

	divCurMonth.innerHTML = res;

	var idHotel = _idHotel;

	var idRoom = _idRoom;

	var month = _month;

	var year = _year;


	if (month == 12){ month = 1; year++;}else{month++;}

	var url = "module=ajax_getcalendar&idRoom="+idRoom+"&idHotel="+idHotel+"&month="+month+"&year="+year;

	var objReservation = Page.FindControl("idReservation");

	if (objReservation.value){

		url += "&idReservation=" + objReservation.value;

	}



//	window.prompt("first calendar with room",url);



	xmlhttpPost(

		"index.php",

		url,

		"processNextRoomCalendar"

	);



}



function processNextRoomCalendar(res){

	divNextMonth.innerHTML = res;

	selectPreviousDates(false);

}



/** Calls the ajax_getcalendar module that returns the current month calendar*/

function loadcalendars(idHotel,month,year){



	var url = "module=ajax_getcalendar&idHotel="+idHotel+"&month="+month+"&year="+year;

	divCurMonth = Page.FindControl("home_currentmonthcalendar");

	divNextMonth = Page.FindControl("home_nextmonthcalendar");



	_idHotel = idHotel;

	_month = month;

	_year = year;



	Page.FindControl("roomsbox").innerHTML = roomsboxEmpty;

	if (room)

		room.idRoom = 0;


	dateFrameStartHTML = "" + months[month-1] + " " + year;
	//Page.FindControl("spDateFrameStart").innerHTML = "" + months[month-1] + " " + year;





	var objReservation = Page.FindControl("idReservation");

	if (objReservation.value){

		url += "&idReservation=" + objReservation.value;

	}

	//window.prompt("first calendar",url);


	
	divCurMonth.style.width = '241px';
	divCurMonth.style.height = '125px';
	divCurMonth.innerHTML = '<img src="project/images/frontend/content/ajax-loader.gif" style="margin-top:46px;" />';

	divNextMonth.style.width = '241px';
	divNextMonth.style.height = '125px';
	divNextMonth.innerHTML = '<img src="project/images/frontend/content/ajax-loader.gif" style="margin-top:46px;" />';
	
	xmlhttpPost(

		"index.php",

		url,

		"processCurrentCalendar"

	);



}



/** Receives the current calendar and updates the page with its content*/

function processCurrentCalendar(res){


	divCurMonth.style.width = 'auto';
	divCurMonth.style.height = 'auto';
	curMonthHTML = res
	//divCurMonth.innerHTML = res;



	var idHotel = _idHotel;

	var month = _month;

	var year = _year;



	if (month == 12){ month = 1; year++;}else{month++;}


	Page.FindControl("spDateFrameStart").innerHTML = dateFrameStartHTML;
	Page.FindControl("spDateFrameEnd").innerHTML = "" + months[month-1] + " " + year;



	var url = "module=ajax_getcalendar&idHotel="+idHotel+"&month="+month+"&year="+year;

	//prompt("",url);

	var objReservation = Page.FindControl("idReservation");

	if (objReservation.value){

		url += "&idReservation=" + objReservation.value;

	}

	//window.prompt("second calendar",url);



	xmlhttpPost(

		"index.php",

		url,

		"processNextCalendar"

	);







}



/** updates the next month calendar */

function processNextCalendar(res){

	divNextMonth.style.width = 'auto';
	divNextMonth.style.height = 'auto';
	divCurMonth.innerHTML = curMonthHTML;
	divNextMonth.innerHTML = res;

	//alert(usePreviousDates+' '+curMin+' '+curMax);

	if (usePreviousDates && curMin && curMax){

		usePreviousDates = false;

		selectPreviousDates(true);

	}

}



function selectPreviousDates(reload){

	var day = curMin.getDate();

	var month = (curMin.getMonth()+1);

	var year = curMin.getFullYear();



	var day_max = curMax.getDate();

	var month_max = (curMax.getMonth()+1);

	var year_max = curMax.getFullYear();



	if (reload){

		objTDMin = Page.FindControl("td_" + year + "_" + month + "_" + day );

		selectdate(null,null,objTDMin,  year, month, day,true);



		objTDMax = Page.FindControl("td_" + year_max + "_" + month_max + "_" + day_max )

		selectdate(null,null,objTDMax, year_max, month_max, day_max,true);

	}else{

		objTDMin = Page.FindControl("td_" + year + "_" + month + "_" + day );

		selectdate(null,null,objTDMin,  year, month, day,false);



		objTDMax = Page.FindControl("td_" + year_max + "_" + month_max + "_" + day_max )

		selectdate(null,null,objTDMax, year_max, month_max, day_max,false);

	}



}





function selectdate(r,c,objTD,y,m,d,reload,cutoff){



	objDate = new Date(y,(m-1),d);

    var idHotel = Page.FindControl('idHotel').value;

    if(isBoolean(objTD)){

        var objId = "td_"+y+"_"+m+"_"+d;

        objTD = Page.FindControl(objId);

    }



	if (objTD && objTD.style.background.indexOf("unavailable") != -1)  return;

    

/*    diaanterior=parseInt(d,10)

    diaanterior-=1;

    //alert(diaanterior);

    var objId = "cutoffid_"+y+"_"+m+"_"+diaanterior;

    var objIdAnterior ="td_"+y+"_"+m+"_"+diaanterior;

    objTDanterior = document.getElementById(objId);

    objTD4 = document.getElementById(objIdAnterior);

    if (objTDanterior.value > 0)

    {

	    objTD.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_unavailable.gif')"; 

	    objTD4.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_unavailable.gif')"; 

	    return;

    }

    

	if (cutoff > 0)

    {

		//alert("hola");

		Modal.Window("index.php?module=modal_message&title=reservation.validation.availablerange.title&message=La Fecha Seleccionada no puede ser reservada ");

		curMax = null;

		curMin = null;

		Page.FindControl("roomsbox").innerHTML = roomsboxEmpty;

	    d=parseInt(d,10);

	    

	    for(aux1 = d, aux2 = d + Math.floor(cutoff / 24); aux1 < aux2; aux1++)

	    {

	    	var objId = "td_"+y+"_"+m+"_"+aux1;

	    	objTD2 = Page.FindControl(objId);

	    	objTD2.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_unavailable.gif')";

	    }

	    

        /*d+=1

        var objId = "td_"+y+"_"+m+"_"+d;

        objTD2 = Page.FindControl(objId);*/

        //objTD.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_unavailable.gif')";

        //objTD2.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_unavailable.gif')";

        //alert(objTD2.style.background);

        //resetCalendarSelection();

        //return; 

    //}   

    

    //clear the calendars

	clearGrid(objDate.getMonth(),objDate.getFullYear());

	clearGrid(objDate.getMonth()+1,objDate.getFullYear());



	//if setting the new maximum value...

    

	if (objDate >= curMax){

		curMax = objDate;

		curSelected = new Array();

		curSelected[0] = curMin;

		curSelected[1] = curMax;

    }else if (objDate <= curMin){

		curMin = objDate;

		curSelected = new Array();

		curSelected[0] = curMin;

		curSelected[1] = curMax;

    }else if (objDate > curMin && objDate < curMax){

		middiff = parseInt(((curMax - curMin) / 60 / 60 / 24 / 1000) / 2);

		mid = new Date(curMin.getTime() + middiff * 60 * 60 * 24 * 1000);



		if (objDate.getTime() > mid.getTime()){

			curMax = objDate;

    	}else{

			curMin = objDate;

    	}

	}

	

    

    if(curMin) {

         

         

         dayselect=curMin.getDate();
         
         monthselect=m;
         //alert("Selectday: "+dayselect)
         prevday=dayselect -1;
         //alert("Prevday: "+prevday)
         //alert("Month: "+monthselect) 
         if (prevday == 0 ) {
         
            ltdom=new Date(y,m-1,0);
            
            lastday=ltdom.getDate();
                        
            prevmonth= m-1;           
            
            var objId = "td_"+y+"_"+prevmonth+"_"+lastday;
            
            objTD2 = Page.FindControl(objId);
            
            if (objTD2.style.background.indexOf('unavailable')!= -1){
         
            objTD2.style.background="url('project/output/hotels/"+idHotel+"/calendar/color_unavailable.gif')"; 
       
            Modal.Window("index.php?module=modal_message&title=reservation.validation.availablerange.title&message=La Fecha Seleccionada no puede ser reservada "); 
            
            resetCalendarSelection();

            return;
            
                }
            
         }else{
         
            //alert(prevday);
                           
            var objId = "td_"+y+"_"+m+"_"+prevday;
            
            objTD2 = Page.FindControl(objId);
            
            if (objTD2.style.background.indexOf('unavailable')!= -1){
         
            objTD2.style.background="url('project/output/hotels/"+idHotel+"/calendar/color_unavailable.gif')"; 
       
            Modal.Window("index.php?module=modal_message&title=reservation.validation.availablerange.title&message=La Fecha Seleccionada no puede ser reservada "); 
            
            resetCalendarSelection();

            return;
         
         
         
            }
         
         
         
         }
         
  
    }

    

    

    

/*    if(curMin && curMax)

	{

		var ok = true;

		var auxDate = {};

		auxDate['y'] = curMin.getFullYear();

		auxDate['m'] = curMin.getMonth()+1;

		auxDate['d'] = curMin.getDate();

		while(ok && auxDate['y'] <= curMax.getFullYear() && auxDate['m'] <= curMax.getMonth()+1 && auxDate['d'] <= curMax.getDate())

		{

			auxDOMObj = document.getElementById('cutoffDays_'+auxDate['y']+auxDate['m']+auxDate['d']);

			if(auxDOMObj && auxDOMObj.value > 0)

			{

				var objId = "td_"+auxDate['y']+"_"+auxDate['m']+"_"+auxDate['d'];

				ok = false;

				break;

			}

			auxDate['d']++;

			if(auxDate['d'] > 31)

			{

				auxDate['d'] = 1;

				auxDate['m']++;

			}

			if(auxDate['m'] > 12)

			{

				auxDate['m'] = 1;

				auxDate['y']++;

			}		

		}

		if(!ok)

		{

			Modal.Window("index.php?module=modal_message&title=reservation.validation.availablerange.title&message=La Fecha Seleccionada no puede ser reservada ");

			curMax = null;

			curMin = null;

			Page.FindControl("roomsbox").innerHTML = roomsboxEmpty;

		    d=parseInt(d,10);

	        d+=1

	        objTD2 = Page.FindControl(objId);

	        //objTD.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_unavailable.gif')";

	        objTD2.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_unavailable.gif')";

	        for(auxDays = Math.floor(auxDOMObj.value/24); auxDays > 0; auxDays--)

	        	Page.FindControl("td_"+auxDate['y']+"_"+auxDate['m']+"_"+(auxDate['d'] + auxDays - 1)).style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_unavailable.gif')";        

	        return;

		}

	} */

	

	//mark the selected item

	//if (objTD){



	

    

    if(isObject(objTD)){

    	if(Page.FindControl('noStyles').value.match(','+idHotel+',') == ','+idHotel+',')

			idHotel = Page.FindControl('defStyle').value;

		if (objTD.style.background.indexOf("checkout_only") != -1){

			//objTD.style.background = "url('project/images/frontend/content/color_check.gif')";

			objTD.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_check.gif')";

		}else{

			//objTD.style.background = "url('project/images/frontend/content/color_selected.gif')";

			objTD.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_selected.gif')";

		}

	}



	//add a new item into the curSelected Array

	var ind = curSelected.length;

	curSelected[ind] = objDate;



	//set the range (max and min)

	setDateRange(objDate.getMonth(),objDate.getFullYear());



	//validate the range

	if (!verifyRange(objDate.getMonth(),objDate.getFullYear())) return;



	//if the range is valid, mark all the items between the first and the last.

	datediff = (curMax - curMin) / 60 / 60 / 24 / 1000;



	for( i = 0 ; i < datediff ; i++ ){

		curDate = new Date(curMin.getTime() + i * 60 * 60 * 24 * 1000 );

		paintCell(curDate);

	}



	if (curMin){

        paintCell(curMin);

    }



	if (curMax){

        paintCell(curMax);

    }



	reloadReservationData(reload);



	//If only one day has been selected, should also select the next day.

	if ( curMin.getTime() == curMax.getTime()){



		nextDay = new Date(curMin.getTime() + (1*60*60*24*1000));



		objTDId = "td_"+(nextDay.getFullYear())+"_"+(nextDay.getMonth()+1)+"_"+(nextDay.getDate())



		objTD = Page.FindControl(objTDId);

		if (objTD){

			selectdate(null,null,objTD, nextDay.getFullYear(), (nextDay.getMonth()+1), (nextDay.getDate())  ,true,cutoff);

		}

	}





}



function clearGrid(month,year){



	if (month == 12){ month = 1; year++;}



	var idHotel = Page.FindControl('idHotel').value;



	for ( i = 0 ; i <= 31 ; i++ ) {

		curId = "td_" + year + "_" + (month+1) + "_" + i;



		objTD = Page.FindControl(curId);

        

		//alert(Page.FindControl('noStyles').value);

        if(isObject(objTD)){

			if(Page.FindControl('noStyles').value.match(','+idHotel+',') == ','+idHotel+',')

				idHotel = Page.FindControl('defStyle').value;

            if (objTD && (objTD.style.background.indexOf("selected") != -1)){

			    objTD.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_available.gif')";

		    }



		    if (objTD && (objTD.style.background.indexOf("color_check") != -1)){

			    objTD.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_checkout_only.gif')";

		    }

        }



	}



}



function setDateRange(){



	for(i=0;i<curSelected.length;i++){



		if (!curMax && !curMin){

			curMax = curSelected[i];

			curMin = curSelected[i];

		}



	}



	if (!curMin) curMin = curMax;



}



function paintCell(curDate){

	curId = "td_" + curDate.getFullYear() + "_" + (curDate.getMonth()+1) + "_" + curDate.getDate();

    curTD = Page.FindControl(curId);

    var idHotel = Page.FindControl('idHotel').value;

    if(Page.FindControl('noStyles').value.match(','+idHotel+',') == ','+idHotel+',')

		idHotel = Page.FindControl('defStyle').value;

	if(isObject(curTD)){

        if (curTD.style.background.indexOf("color_check.gif") != -1 || curTD.style.background.indexOf("checkout_only") != -1){

		    curTD.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_check.gif')";

		    return;

	    }



	    curTD.style.background = "url('project/output/hotels/"+idHotel+"/calendar/color_selected.gif')";

    }

}



function verifyRange(month,year){



	if (! (curMax && curMin)) return true;



	datediff = (curMax - curMin) / 60 / 60 / 24 / 1000;



	for( i = 0 ; i < datediff ; i++ ){

		curDate = new Date(curMin.getTime() + i * 60 * 60 * 24 * 1000 );

		curId = "td_" + curDate.getFullYear() + "_" + (curDate.getMonth()+1) + "_" + curDate.getDate();



		curTD = Page.FindControl(curId);



		if ( curTD.style.background.indexOf('unavailable') != -1 ){

			Modal.Window("index.php?module=modal_message&title=reservation.validation.availablerange.title&message=reservation.validation.availablerange.text&idHotel="+_idHotel);

			curMax = null;

			curMin = null;

			curSelected = new Array();

			clearGrid(month,year);

			clearGrid((month-1),year);

			clearGrid((month+1),year);

			Page.FindControl("roomsbox").innerHTML = roomsboxEmpty;



			resetCalendarSelection();



			return false;

		}



        if ( curTD.style.background.indexOf('checkout_only') != -1 ){

			Modal.Window("index.php?module=modal_message&title=reservation.validation.availablerange.title&message=reservation.validation.availablerange.text&idHotel="+_idHotel);

			curMax = null;

			curMin = null;

			curSelected = new Array();

			clearGrid(month,year);

			clearGrid((month-1),year);

			clearGrid((month+1),year);

			Page.FindControl("roomsbox").innerHTML = roomsboxEmpty;



			resetCalendarSelection();



			return false;

		}



	}

	return (true);

}



function changeCalendarMonth(type){

	var m = _month;

	var y = _year;



	var today = new Date();



	var idHotel = Page.FindControl('idHotel').value;

	if(Page.FindControl('noStyles').value.match(','+idHotel+',') == ','+idHotel+',')

		idHotel = Page.FindControl('defStyle').value;



	if (type == -1){



		if (m == (today.getMonth()+1)) return;



		if (m == 1) {m = 12; y-- }

		else m--;



		//if (m == (today.getMonth()+1)) Page.FindControl("imgCalendarArrowBack").src = "project/output/hotels/"+idHotel+"/calendar/arrowtransparent.gif";



	}else{



		if (m == 12) {m = 1; y++ }

		else m++;



		//Page.FindControl("imgCalendarArrowBack").src = "project/output/hotels/"+idHotel+"/calendar/arrowback.gif";



	}



	curMax = null;

	curMin = null;

	curSelected = new Array();



	loadcalendars(_idHotel,m,y);

	resetCalendarSelection();

}



function resetCalendarSelection(){

	var m = _month;

	var y = _year;



	curMax = null;

	curMin = null;

	curSelected = new Array();

	clearGrid(m,y);

	clearGrid((m-1),y);

	clearGrid((m+1),y);



	room = null;

	loadcalendars(_idHotel,m,y);



	resetselectors();



	reloadReservationData(true);

}



function resetselectors(){

	Page.FindControl("qtyAdults").value = 1;

	Page.FindControl("qtyChildren").value = 0;

	Page.FindControl("qtyRooms").value = 1;

	Page.FindControl("roomsbox").innerHTML = roomsboxEmpty;

	/*

	if (hotel.images && hotel.images[0]){

		Page.FindControl("imgRoom").src = hotel.images[0].filePath;

		Page.FindControl("imagedescriptionbox").innerHTML = hotel.images[0].description;

	}

	*/

    changeHotel(Page.FindControl("idHotel").value);

	updateQuantities();



}

function getHotels(idHotel) {
	region = Page.FindControl("idRegion").value;
	
	if (typeof(idHotel) == "undefined") {
		var selectedHotel = document.getElementById('selectedHotel');	
		if (selectedHotel != null) {
			idHotel = selectedHotel.value;
		}
	}
	
	xmlhttpPost(
		"index.php",
		"module=ajax_gethotels&idRegion=" + region + "&idHotel=" + idHotel,
		"loadHotels"
	);
}

function loadHotels(res) {
	eval("hotels = " + res);
	
	var combo = Page.FindControl('idHotelBook');
	while(combo.options.length > 0) {
		combo.options[0] = null;	
	}
	
	for(i=0; i<hotels.length; i++) {
		combo.options[combo.length] = new Option(hotels[i].name, hotels[i].idHotel);
		
		if (hotels[i].selected) {
			combo.selectedIndex = i;
		}
	}
	Page.FindControl("roomsbox").innerHTML = roomsboxEmpty;
	changeHotel(combo.value);
	changeHotelStyle();	
}

/* Calendar Functions */
var startDate;
var endDate;


function disableDates(date, year, month, day) {
	var today = new Date();
	today.setDate(today.getDate()+1);
	today.setHours(0,0,0,0);
	if (date < today) {
		return true;
	}
}

function updateCheckIn(cal) {
	var checkOut = Page.FindControl('checkOut');
	cal.date.setHours(0,0,0,0);
	curMin = new Date(cal.date.valueOf());
	cal.date.setDate(cal.date.getDate() + 2);
	curMax = new Date(cal.date.valueOf());
	
	var days = cal.date.getDate();
	var month = cal.date.getMonth() + 1;

	if (days.toString().length == 1) {
		days = "0" + days;
	}

	if (month.toString().length == 1) {
		month = "0" + month;
	}

	
	checkOut.value = days+"/"+month+"/"+cal.date.getFullYear();
	
	if (_idRoom != 0) {
		_idRoom = 0;
		var combo = Page.FindControl('idHotelBook');
		changeHotel(combo.value);
	}
}

function updateCheckOut(cal) {
	cal.date.setHours(0,0,0,0);

	curMax = new Date(cal.date.valueOf());
	
	if (_idRoom != 0) {
		_idRoom = 0;
		var combo = Page.FindControl('idHotelBook');
		changeHotel(combo.value);
	}
}

function validateRange() {
	_idHotel = Page.FindControl('idHotelBook').value;

	if (curMin == null || curMax == null) {
		alert('Seleccione fecha de llegada y de partida');
		return false;
	}
	
	start = curMin.getFullYear() + "-" + (curMin.getMonth() + 1) + "-" + curMin.getDate();
	end = curMax.getFullYear() + "-" + (curMax.getMonth() + 1) + "-" + curMax.getDate();

	xmlhttpPost(
		"index.php",
		"module=ajax_validate&idHotel=" + _idHotel + "&idRoom=" + _idRoom + "&start=" + start + "&end=" + end,
		"showValid"
	);	
}

function showValid(res) {
	if (res == 0) {
		Modal.Window("index.php?module=modal_message&title=reservation.validation.availablerange.title&message=reservation.validation.availablerange.text&idHotel="+_idHotel);
	} else {
		Page.FindControl("roomsbox").innerHTML = "";
		reloadReservationData(true);
	}
}

function createDates() {

	first = Page.FindControl('checkIn').value.split("/");	
	curMin = new Date(first[2],first[1]-1,first[0]);
	
	second = Page.FindControl('checkOut').value.split("/");	
	curMax = new Date(second[2],second[1]-1,second[0]);	
}

