var availPropDatesSelected = [,,];

$(function(){

	$.ajaxSetup({ "error": ajaxError });

/*
		$('#pleaseWaitMessage').dialog({
			modal: true,
			closeOnEscape: false,
			resizable: false,
			height: 75,
			width: 200,
			open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); }
			});

		hidePleaseWait();
*/

		$('#guestReviewPrompt').dialog({
			modal: true,
			closeOnEscape: false,
			height: 300,
			width: 400
			});

		hideGuestReviewPrompt();
		
		getAvailUpdateDate($('#currentAvailPropID').val());
		
		// checkGuestReviews(9748, 3);
	}
);

function ajaxError(XMLHttpRequest, textStatus, errorThrown) {
	$("#divAjaxErrorMessage").show("fast");
	$("#divAjaxErrorMessage").html('Sorry, we have experienced an error while saving your data. <br/>If the problem persists please contact the Holiday France Direct team.');
}

function hideAjaxError()
{
	$("#divAjaxErrorMessage").hide();
}

function availNavYear(moveYear)
{
	if(moveYear == 'prev')
		overViewYear--
	else
		overViewYear++

	$("#currentYearDisplay").html(overViewYear);

	var availLoadUrl = strBaseHref + "ownersarea/AvailCalendar_Overview.cfm?targetYear="+overViewYear;
	$("#displayAvailability").load(availLoadUrl);
}

function savePropAvail(propID, availAction)
{
	$('#availaction').val(availAction);
	var formS = $('#frmPropAvail').serialize();

	$.post(strBaseHref + 'ownersarea/AvailCalendar_Save.cfm', formS, savePropAvailCallBack);
}

function savePropAvailCallBack(data, textStatus)
{
	$('#availPropSaveStatus' + data).html('Save status = ' + textStatus);
}

function selectPropAvailDate(selDate, d, m, y)
{
	var isDaily = $('#propAvailDateIsDaily_' + selDate).val();

	if(isDaily == 1)
	{
		if($('#propAvailDateTD_' + selDate).hasClass("availPropSelected"))
		{
			$('#propAvailDateTD_' + selDate).removeClass("availPropSelected");
		}
		else
		{
			$('#propAvailDateTD_' + selDate).addClass("availPropSelected");
		}
	}
	else
	{
		var periodStart = $('#propAvailDatePeriodStart_' + selDate).val();
		var periodStartDate = new Date(periodStart.split('-')[2], periodStart.split('-')[1] - 1, periodStart.split('-')[0])

		var periodEnd = $('#propAvailDatePeriodEnd_' + selDate).val();
		var periodEndDate = new Date(periodEnd.split('-')[2], periodEnd.split('-')[1] - 1, periodEnd.split('-')[0]);

		while(periodStartDate <= periodEndDate)
		{
			var periodStartYYYY = periodStartDate.getFullYear().toString();

			var periodStartMM = (periodStartDate.getMonth() + 1).toString();
			if(periodStartMM.length < 2)
				periodStartMM = '0' + periodStartMM;

			var periodStartDD = periodStartDate.getDate().toString();
			if(periodStartDD.length < 2)
				periodStartDD = '0' + periodStartDD;

			var periodStartYYYYMMDD = periodStartYYYY + periodStartMM + periodStartDD;

			// alert(periodStartYYYYMMDD);


			if($('#propAvailDateTD_' + periodStartYYYYMMDD).hasClass("availPropSelected"))
			{
				$('#propAvailDateTD_' + periodStartYYYYMMDD).removeClass("availPropSelected");
			}
			else
			{
				$('#propAvailDateTD_' + periodStartYYYYMMDD).addClass("availPropSelected");
			}

			periodStartDate = DateAdd('d', 1, periodStartDate);
		}
	}
}

function availPropNavYear(movement, showWait, propID)
{
	clearSelectedPropAvail();

	var selYear = $('#SelYear').val();

	if(movement == 'prev')
		selYear--;
	else if(movement == 'next')
		selYear++;

	$('#SelYear').val(selYear);

	var startYear = $('#StartYear').val();
	var endYear = $('#EndYear').val();

	var showPrev = false;
	var showNext = false;

	if(selYear > startYear)
	{
		showPrev = true;
		$('#yearNavPrev').css("display", "block");
		$('#yearNavPrev').css("visibility", "visible");
	}
	else
	{
		$('#yearNavPrev').css("display", "none");
		$('#yearNavPrev').css("visibility", "hidden");
	}

	if(selYear < endYear)
	{
		showNext = true;
		$('#yearNavNext').css("display", "block");
		$('#yearNavNext').css("visibility", "visible");
	}
	else
	{
		$('#yearNavNext').css("display", "none");
		$('#yearNavNext').css("visibility", "hidden");
	}

	if(showPrev && showNext)
	{
		$('#yearNavDivider').css("display", "block");
		$('#yearNavDivider').css("visibility", "visible");
	}
	else
	{
		$('#yearNavDivider').css("display", "none");
		$('#yearNavDivider').css("visibility", "hidden");
	}
	
	var prevYear = selYear;
	prevYear--;
	var nextYear = selYear;
	nextYear++;

	var prevYearText = '&lt;&lt; ' + prevYear;
	var nextYearText = nextYear + ' &gt;&gt;';	
	
	$('#yearNavPrev').html(prevYearText);
	$('#currentYearDisplay').html(selYear);
	$('#yearNavNext').html(nextYearText);
	
	if(showWait)
		showPleaseWait();
	
	$('#PropAvailContainer').load(strBaseHref + 'ownersarea/AvailCalendarEditCal.cfm?propID=' + propID + '&curAvailYear='+selYear, function() { availPropNavYearComplete() });
}

function clearStatusMessage()
{
	$('#propAvailSaveStatus').delay(2000).fadeOut('slow');
}

function showLoadStatusMessage()
{
	$('#propAvailLoadStatus').fadeIn();
}

function clearLoadStatusMessage()
{
	$('#propAvailLoadStatus').delay(500).fadeOut('slow');
}

function availPropNavYearComplete()
{
	hidePleaseWait();
	clearLoadStatusMessage();
	attachAvailCalendarHandlers();
}

function attachAvailCalendarHandlers()
{
	$('#availUpToDateButton,#loadPropertyButton,.availPropButtonAvailable,.availPropButtonProvisional,.availPropButtonBookedHFD,.availPropButtonBookedOther,.availPropButtonBlocked,.convertweekstodaysButton,.convertdaystoweeksButton').hover(
		function()
		{
			var hoverText = '';
			
			if($(this).attr('id') === 'availUpToDateButton')
			{
				hoverText = 'Mark your calendar is up-to-date without making any changes.';
			}
			else if($(this).attr('id') === 'loadPropertyButton')
			{
				hoverText = 'Load up the calendar for your next property.';
			}
			else if($(this).attr('class') === 'availPropButtonAvailable')
			{
				hoverText = 'Click on date/s and then this button to mark dates as available.';
			}
			else if($(this).attr('class') === 'availPropButtonProvisional')
			{
				hoverText = 'Click on date/s and then this button to mark dates as provisionally booked.';
			}
			else if($(this).attr('class') === 'availPropButtonBookedHFD')
			{
				hoverText = 'Click on date/s and then this button to mark dates as booked via this website.';
			}
			else if($(this).attr('class') === 'availPropButtonBookedOther')
			{
				hoverText = 'Click on date/s and then this button to mark dates as booked via another website/other.';
			}
			else if($(this).attr('class') === 'availPropButtonBlocked')
			{
				hoverText = 'Date/s blocked for your own use.';
			}
			else if($(this).attr('class') === 'convertweekstodaysButton')
			{
				hoverText = 'Click on week and then this button to change dates to daily availability.';
			}
			else if($(this).attr('class') === 'convertdaystoweeksButton')
			{
				hoverText = 'Click on any day of the selected week to change dates to weekly availability.';
			}
			
			if(hoverText != '')
			{
				$('#availHoverContainer').html(hoverText);
				$('#availHoverContainer').css('left', $(this).offset().left + 'px');
				$('#availHoverContainer').css('top', ($(this).offset().top + $(this).height()) + 'px');
				$('#availHoverContainer').css('width', $(this).css('width'));
				$('#availHoverContainer').show();
			}
		}
		,
		function()
		{
			$('#availHoverContainer').hide();
		}
	);

	$('.availPropDay,.availPropDailyDay').hover(
		function()
		{
			var elemID = $(this).attr('id');
			var hoverText = elemID.substr(elemID.length - 2, 2) + '/' + elemID.substr(elemID.length - 4, 2) + '/' + elemID.substr(elemID.length - 8, 4);
			
			hoverText += '<br/>';

			if($(this).hasClass('availPropAvailableIsDaily')
				|| $(this).hasClass('availPropProvisionalIsDaily')
				|| $(this).hasClass('availPropBookedHFDIsDaily')
				|| $(this).hasClass('availPropBlockedIsDaily')
				|| $(this).hasClass('availPropBookedOtherIsDaily'))
			{
				hoverText += 'Daily availability'
			}
			else
			{
				hoverText += 'Weekly availability'
			}
			
			hoverText += '<br/>';
			
			if($(this).hasClass('availPropAvailable')
				|| $(this).hasClass('availPropAvailableIsDaily'))
			{
				hoverText += 'Available';
			}
			else if($(this).hasClass('availPropProvisional')
				|| $(this).hasClass('availPropProvisionalIsDaily'))
			{
				hoverText += 'Provisional';
			}
			else if($(this).hasClass('availPropBookedHFD')
				|| $(this).hasClass('availPropBookedHFDIsDaily'))
			{
				hoverText += 'Booked HFD';
			}
			else if($(this).hasClass('availPropBlocked')
				|| $(this).hasClass('availPropBlockedIsDaily'))
			{
				hoverText += 'Blocked';
			}
			else if($(this).hasClass('availPropBookedOther')
				|| $(this).hasClass('availPropBookedOtherIsDaily'))
			{
				hoverText += 'Booked Other';
			}
			
			$('#availHoverContainer').html(hoverText);
						
						
			$('#availHoverContainer').css('left', ($(this).offset().left - $('#availHoverContainer').width() - (0.5 * $(this).width())) + 'px');
			$('#availHoverContainer').css('top', ($(this).offset().top + $(this).height()) + 'px');
			$('#availHoverContainer').css('width', '90px');
			$('#availHoverContainer').show();
		}
		,
		function()
		{
			$('#availHoverContainer').hide();
		})
}

function hidePleaseWait()
{
//	$('#pleaseWaitMessage').dialog('close');

	$('#alertboxavail-closelink').css('display', 'block');
	
	if($('#alertboxavail-wrapper').css('display') == 'block')
	{
		$('#sitemask').css('display', 'none');
		$('#alertboxavail-wrapper').css('display', 'none');
	}
}

function showPleaseWait()
{
//	$('#pleaseWaitMessage').dialog('open');
	
	$('#sitemask').css('display', 'block');
	$('#alertboxavail-wrapper').css('display', 'block');
	$('#alertboxavail-heading').html('Please wait, loading');
	
	$('#alertboxavail-closelink').css('display', 'none');

	var pleaseWaitContent = '<img src="images/ajax-loader-round.gif" border="0" alt="Please Wait" style="margin:30px 30px 30px 30px;" />';

	$('#alertboxavail-optionsinnerwrapper').html(pleaseWaitContent);	
	$('#alertboxavail-options').html('');
}

function hideGuestReviewPrompt()
{
	$('#guestReviewPrompt').dialog('close');
}

function clearSelectedPropAvail()
{
	$(".availPropSelected").removeClass("availPropSelected");
}

function convertAvailability(propID, type)
{
	var dateList = $(".availPropSelected");
	var dateParam = "";

	if(dateList.size() > 0)
	{
		showPleaseWait();

		$.each(dateList, function(key, value) {
			if(dateParam.length > 0)
			{
				dateParam += "_";
			}

			dateParam += value.id.split("_")[1];
		});

		var url = strBaseHref + 'ownersarea/AvailCalendar_Convert.cfm?propID='+propID+'&type='+type+'&dates='+dateParam;
		
		hideAjaxError();
		$('#propAvailSaveStatus').html('');
		$('#propAvailSaveStatus').fadeIn();
		$('#propAvailSaveStatus').load(url, function() { clearStatusMessage(); availPropNavYear('',true,propID) });
	}
	else
	{
		alert("Please select at least one date to convert");
	}
}

function updateAvailability(propID, type)
{
	var dateList = $(".availPropSelected");
	var dateParam = "";

	if(dateList.size() > 0)
	{
		$.each(dateList, function(key, value) {
			if(dateParam.length > 0)
			{
				dateParam += "_";
			}

			dateParam += value.id.split("_")[1];
		});

		var url = strBaseHref + 'ownersarea/AvailCalendar_Save.cfm?propID='+propID+'&type='+type+'&dates='+dateParam;
		
		// alert(url);

		hideAjaxError();
		$('#propAvailSaveStatus').html('');
		$('#propAvailSaveStatus').fadeIn();
		$('#propAvailSaveStatus').load(url, function() { showLoadStatusMessage(); clearStatusMessage(); availPropNavYear('',false,propID); checkGuestReviews(propID,type); getAvailUpdateDate(propID); });
	}
	else
	{
		alert("Please select at least one date to update");
	}
}

function checkGuestReviews(propID, type)
{
	/* if(type == 3)
	{ */ 
		var rUrl = strBaseHref + 'ownersarea/reviewinvitesrequired.cfm?propID=' + propID;

		$.ajax({
			url: rUrl,
			success: function(data) {
					if(data != 'NONE')
					{
						$('#sitemask').css('display', 'block');
						$('#guestreviewbox-listwrapper').html(data);						
						$('#guestreviewbox-wrapper').fadeIn();

						$('.GRMergeLink').bind('click', function() {
							$selLI = $(this).parent().parent('li');
							$selIDs = $selLI.children('.GRIDs').val();
							$selStartDate = $selLI.children('h3').children('.GRStart').html();
							$selEndDate = $selLI.children('h3').children('.GREnd').html();
							
							newEndDate = '';
							if($selEndDate != '')
								newEndDate = $selEndDate;
							else
								newEndDate = ' - ' + $selStartDate;
							
							$prevLI = $selLI.prev();
							$prevLI.children('h3').children('.GREnd').html(newEndDate);
							$prevIDs = $prevLI.children('.GRIDs').val();
							$prevLI.children('.GRIDs').val($prevIDs + ',' + $selIDs);
							
							$selLI.remove();
						});
					}
				}
		});
	// }
}

function mergeGRWithAbove(l)
{

}

function saveGRInvites()
{
	var msg = '';
	
	var populatedNames = $('input.GRName[value!=""]');
	var populatedEmails = $('input.GREmail[value!=""]');
	
	if(populatedNames.length > 0 || populatedEmails.length > 0)
	{
		for(var i = 0; i < populatedNames.length; i++)
		{
			if($('#txtGREmail' + populatedNames[i].name.replace('txtGRName', '')).val() == '')
			{
				msg += '\r\n- If you do not wish to complete an invite at this time leave both the name and email blank, otherwise both name and email must be provided.';		
				i = populatedNames.length;
			} 
		}	

		if(msg == '')
		{
			for(var i = 0; i < populatedEmails.length; i++)
			{
				if($('#txtGRName' + populatedEmails[i].name.replace('txtGREmail', '')).val() == '')
				{
					msg += '\r\n- If you do not wish to complete an invite at this time leave both the name and email blank, otherwise both name and email must be provided.';		
					i = populatedEmails.length;
				} 
			}	
		}		
	}
	
	if($('input.GRName[value==""]').length == 0 && $('input.GREmail[value==""]').length == 0)
	{
		msg += '\r\n- Complete at least one review invitation.';
	}
	else
	{
	
		var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
		
		for(var i = 0; i < populatedEmails.length; i++)
		{
			if(!emailReg.test(populatedEmails[i].value))
			{
				msg += '\r\n- All populated email addresses must be valid.';
				i = populatedEmails.length;
			}
		}
		
	}
	
	
	if(msg == '')
	{
		$.post(strBaseHref + 'ownersarea/reviewinvitessave.cfm',$('#frmGRInvites').serialize(), function(data) { $('#propAvailSaveStatus').html(data); $('#propAvailSaveStatus').fadeIn(); $('#propAvailSaveStatus').delay(3000).fadeOut('slow'); });

		cancelGRInvites();
	}
	else
	{
		alert('Please complete the following:' + msg);
	}
}

function cancelGRInvites()
{
	$('#guestreviewbox-wrapper').fadeOut();
	$('#sitemask').css('display', 'none');
}

function closeGuestReviewPrompt()
{
	$('#guestreviewbox-wrapper').fadeOut();
	$('#sitemask').css('display', 'none');
}

function showGuestReviewPrompt()
{
	$('#guestReviewPrompt').dialog('open');
}

function showPropertyChoice()
{
	$('#sitemask').css('display', 'block');
	$('#propertybox-wrapper').css('display', 'block');
}

function closePropertyChoice()
{
	$('#sitemask').css('display', 'none');
	$('#propertybox-wrapper').css('display', 'none');
}

function closeAlertAvailBox()
{
	$('#sitemask').css('display', 'none');
	$('#alertboxavail-wrapper').css('display', 'none');
}

function markAvailUpToDate(propID)
{
	var url = strBaseHref + 'ownersarea/AvailCalendar_SetUpdateDate.cfm?propID=' + propID;
	$('#availPropUpdateDate').load(url, function() { $('#propAvailUpToDateStatus').fadeIn(400, function() { $('#propAvailUpToDateStatus').delay(1000).fadeOut('slow'); } ) });
}

function getAvailUpdateDate(propID)
{
	var url = strBaseHref + 'ownersarea/AvailCalendar_GetUpdateDate.cfm?propID=' + propID;
	$('#availPropUpdateDate').load(url, function() { });	
}

