var month_names = new Array ( );
month_names[month_names.length] = "January";
month_names[month_names.length] = "February";
month_names[month_names.length] = "March";
month_names[month_names.length] = "April";
month_names[month_names.length] = "May";
month_names[month_names.length] = "June";
month_names[month_names.length] = "July";
month_names[month_names.length] = "August";
month_names[month_names.length] = "September";
month_names[month_names.length] = "October";
month_names[month_names.length] = "November";
month_names[month_names.length] = "December";

var day_names = new Array ( );
day_names[day_names.length] = "Sunday";
day_names[day_names.length] = "Monday";
day_names[day_names.length] = "Tuesday";
day_names[day_names.length] = "Wednesday";
day_names[day_names.length] = "Thursday";
day_names[day_names.length] = "Friday";
day_names[day_names.length] = "Saturday";

$(document).ready(function() {
	
	$(function() {
		// Highlight calendar TD
		$('table.avail2 td.toHightlight').live("mouseover",function() {
	         $(this).addClass('mouseOverRow');
	      }).live("mouseout",function() {
	         $(this).removeClass('mouseOverRow');
	      })   
		// Highlist Period tr      
	      $('table#periods tr').live("mouseover",function() {
	    	  	 var id = $(this).attr('title');
	    	  	$(this).addClass('mouseOverRow');
	    	  	$('table.avail2 td.'+id).addClass('mouseOverRow');
		      }).live("mouseout",function() {
		    	  	 var id = $(this).attr('title');
		    	  	$(this).removeClass('mouseOverRow');
			    	 $('table.avail2 td.'+id).removeClass('mouseOverRow');
		  })       	      
	}); // Function


});

var i = 0;
var startDate = null;
var endDate = null;
var snumberMonths;
var endJustSet = false;
var minStay = null;

function changeCheckINOUTcolor() {
	// Try change checkin checkout BG color
	$("table.avail2 td.checkin").each(function() { // Go throught all the tds 
		td = $(this);
		var tmp = td.prev().css('background-color');
		var prevClass = tmp;
		var prevTitle = td.prev().attr('title');
		
		td.css('background-color',prevClass);
		if (prevTitle != '') {
			td.attr('title','<strong>Half Booked Day</strong><br /><br />'+prevTitle);	
		} else {
			td.removeAttr('title');	
		}

	});
	
	// Checkout
	$("table.avail2 td.checkout").each(function() { // Go throught all the tds 
		td = $(this);
		var tmp = td.next().css('background-color');
		var prevClass = tmp;
		var nextTitle = td.next().attr('title');
		
		td.css('background-color',prevClass);
		if (nextTitle != '') {
			td.attr('title','<strong>Half Booked Day</strong><br /><br />'+nextTitle);	
		} else {
			td.removeAttr('title');	
		}

	});
}


function lauchCalendar(sid,divc,numberMonths) {
	// Close booking and init stuff
	close_confirm();
	startDate = null;
	endDate = null;
	
	var snumberMonths = numberMonths;
	$('.pcalendar').empty().html('<img style="margin-left:45%;margin-top:20px;" src="/images/ajax-loader.gif" />');
	var divIframe = $('.pcalendar');
	
	if (divc != '') {
		divIframe = $('#'+divc+' .pcalendar');
	}
	
	$.getJSON("/lineCalendar.php", { sid: sid, months: numberMonths },
			  function(data){
			  	// Set some var
			  	minStay = data.minStay; 
			  	
			  	// Insert html
				divIframe.html(data.html);
				
				// CheckIn CheckOut color
				changeCheckINOUTcolor();
				
				// Show
			    divIframe.show();
				
			    // Qtip booking
				 $('td.booked').each(function() {
				 	currentQtip = $(this);
					 $(this).qtip({ 
					 		style: { background: '#ffffff', color: '#666666', padding: '7px 13px', border: { width: 3, color: '#C00'}, width: { max: 210, min: 0 }, 'font-size': '12px' , tip: true }, 
			    			 show: { solo: true},
			    			 position: { corner: { target: 'bottomMiddle',tooltip: 'topLeft' } }
					});
				});
				
			    // Qtip period
				 $('td.period0, td.checkin, td.checkout').each(function() {
				 	currentQtip = $(this);
					 $(this).qtip({ 
  	    					 content: { title: currentQtip.attr('period_name') },
					 	     style: { background: '#ffffff', color: '#666666', padding: '7px 13px', border: { width: 3, color: '#66B266'}, width: { max: 210, min: 0 }, 'font-size': '12px' , tip: true }, 
			    			 show: { solo: true}
					});
				});
			    
			    // Hide link if we show 12 months
			    if (numberMonths > 7) {
			    	$('#seeMore').hide();
			    }
			  });
}

function close_confirm() {
	clean_form();
	$('.infoDays .qtip').remove(); // Remove damn qtip
}

function refreshCalendar() {
	// Close Booking Table
	close_confirm();
	$('table.avail2 td').removeClass('selected');
}

function reloadCalendar() {
	// Close Booking Table
	$("#confirm-tabs").hide();
	close_confirm();
	lauchCalendar(currentSid,'',7);
}

function clean_form() {
	$("#booking_total").attr('value','');
	$(".sid").attr('value','');
	$(".periodH").attr('value','');
}

function selectDate (date,sid) {
	var id = null;
	var sid = currentSid;
	
	if (date == startDate) {
		startDate = null;
		endDate = null;
		refreshCalendar();
		alert('Invalid selection. Please select check in and check out dates.');
		return false;
	}
	
	if (startDate == null && endDate == null) {
		if (endJustSet) { // Redefine period
			refreshCalendar();
			startDate = date;
			id = '#'+date;
			$(id).removeClass('mouseOverRow');
			$(id).addClass('selected');	
			endJustSet = false;
		} else {
			startDate = date;
			var ffStartDate = new Date( startDate*1000);
			var fStartDate = ffStartDate.getDate()+' '+month_names[ffStartDate.getMonth()]+' '+ffStartDate.getFullYear();
	
			id = '#'+date;
			$(id).removeClass('mouseOverRow');
			$(id).addClass('selected');
			//$.jGrowl("You Pick "+fStartDate+" as start day");
		}
	} 
	else if (startDate != null && endDate == null) {
		endDate = date;
		var ffStartDate = new Date(startDate*1000)
		var ffEndDate = new Date(endDate*1000);
		
		// EndDate must be before startDate...
		if (ffStartDate > ffEndDate) { 
			startDate = null;
			endDate = null;
			refreshCalendar();
			// Show booking Div into Facebox
		  	var contentDiv = $("#wrongEndDate").html();
		  	jQuery.facebox(function($) { 
		  		jQuery.facebox(contentDiv)
	  		});
	  		return false;	
		}
		
		// Minimum stay
		var nbDaysSelected = (endDate - startDate) / (60*60*24);
		if (minStay > nbDaysSelected) {
			// Reset
			startDate = null;
			endDate = null;
			refreshCalendar();
			// Show booking Div into Facebox
		  	var contentDiv = $("#minStay").html();
		  	jQuery.facebox(function($) { 
		  		jQuery.facebox(contentDiv)
	  		});
	  		return false;			
		}
		
		var fEndDate = ffEndDate.getDate()+' '+month_names[ffEndDate.getMonth()]+' '+ffEndDate.getFullYear();
		
		id = '#'+date;
		$(id).removeClass('mouseOverRow');
		$(id).addClass('selected');
		endJustSet = true;
		//$.jGrowl("You Pick "+fEndDate+" as end day");
	}

	if (startDate != null && endDate != null && endJustSet) {
		//endJustSet = false;
		var idStart = '#'+startDate;
		var idEnd = '#'+endDate;
		
		var objDateStart = new Date(startDate*1000);
		var objDateEnd = new Date(endDate*1000);
		
		var error = null;
		
		$("#avaitab tr > td").each(function() {
			var curDate = new Date($(this).attr('id')*1000);
			
			if ((objDateStart < curDate) && (curDate < objDateEnd)) { // td included in our period

				if ($(this).attr('class').match(/undefined/gi) || $(this).attr('class').match(/booked/gi)) {
					error = true;
					return false;
				} else {
					$(this).addClass('selected');
				}
				
				if (curDate == objDateEnd) {
					return false;
				}
				
				
			} // end td inc
				
		});
		
		if (error) {
			alert("Please select consecutive days");
			refreshCalendar();
			return false;
		}
		
		/////////////
		// if No error, fill table
		var fStartDate = ffStartDate.getDate()+' '+month_names[ffStartDate.getMonth()]+' '+ffStartDate.getFullYear();
		var fEndDate = ffEndDate.getDate()+' '+month_names[ffEndDate.getMonth()]+' '+ffEndDate.getFullYear();
		// If all the days are available
		var periodHidden = startDate+' - '+endDate;
		var period = fStartDate+' - '+fEndDate;
		// Enquiry format
		var enqStartDate =  ffStartDate.getFullYear()+'-'+ffStartDate.getMonth()+'-'+ffStartDate.getDate();
		var enqEndDate = ffEndDate.getFullYear()+'-'+ffEndDate.getMonth()+'-'+ffEndDate.getDate();

		// Set span total & hidden field
		$("#bookingDiv .PeriodspanBooking").html(period);
		$("#bookingDiv .periodH").val(Base64.encode(periodHidden));
		$("#bookingDiv .sid").val(Base64.encode(sid));
		$("#bookingDiv .enqStartDate").val(enqStartDate);
		$("#bookingDiv .enqEndDate").val(enqEndDate);
		
		
		// Get total
		$.post("/getTotal.php", { period: periodHidden, sid:sid  },
		  function(data){
			$(".booking_total").html(data.currency+''+data.total);

			// Remove qTip just to be sure first
				$('.infoDays .qtip').remove();
			// Add qtip on info button
			$('.infoDays').qtip({ 
				content: data.days,
	  			show: { 
						when: { event: 'mouseover'}, 
						solo: true
					},
	  			hide: 'mouseout',
	  			position: { adjust: { screen: true } },
	  			style: { background: '#ffffff', color: '#666666', padding: '7px 13px', border: { width: 2, color: '#f07e4f'}, width: { max: 210, min: 0 }, 'font-size': '12px' , tip: true }
			});	 			
			
		  },'json'); // End post
		
		  // Show booking Div into Facebox
		  var contentDiv = $("#bookingDiv").html();
		  jQuery.facebox(function($) { 
		  	jQuery.facebox(contentDiv)
	  		})
		//$("#bookingDiv").facebox();
		  
		// Set to null for the next booking  
		startDate = null;
		endDate = null;
		
		
		

	}
}


