
function gup( name,url )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( url );
  if( results == null )
    return "";
  else
    return results[1];
}

$.expr[':'].textEquals = function(a, i, m) {
	return $(a).text().match("^" + m[3] + "$");
};


$(document).ready(function(){
	
	$("a[rel='slides']").colorbox({slideshow:true, slideshowSpeed: 7000, maxHeight: "90%", opacity: 0.6, onLoad: function() {$('#cboxClose').show();}});
	
	$("#errors").hide();
	
	$("#enter.click").livequery("click", function(){
		$.fn.colorbox({inline:true, width: '500px', overlayClose: false, href: "#contact-details",
		
			onLoad: function() {
				 $('#cboxClose').hide();
			}, 
			onOpen: function(){
				$("#dates-form").html($('.update').html());
			}
		});
	});
	
	$("img.reflect").reflect({height: 0.1, opacity: 0.3});
	
	var date=new Date();
	var dateTo=new Date();
	$(".calendar").load("calendar.php", {y: date.getFullYear(), m:date.getMonth()+1});
	$(".calendar").ajaxStart(function(){
		$(this).show();
	});
	
	bind = false;

	$(".calendar-header a,.calendar-today a").livequery("click", function(){
		
			var href = $(this).attr("href");
			var m = gup("m",href);
			var y = gup("y",href);
			
			$(".calendar").load("calendar.php", {y: y, m: m});
			
			return false;
	});

	$(".colDay1 .day,.colDay2 .day,.colDay3 .day,.colDay4 .day,.colDay5 .day,.colDay6 .day, .colDay7 .day,").livequery("click", function(){
		
		$(".leave").html("");
		if(!$(this).hasClass("eventDay"))
		{
			if($(this).hasClass("selected")){
				$(this).removeClass("selected");
				$("#stay").hide();
			}
			else
			{
				$(".day").removeClass("selected");
				$(this).addClass("selected");
				$("#stay").show();
			}
			if($(".arrival-date").length == 0)
			{
				$(".instructions .alpha li:nth-child(1)").addClass("strike");
				$(".update ol").append("<li class='green arrival-date'>Arrival: <span class='arrival'></span></li>");
			}
			
			date = new Date($("#year-input").val(), $("#month-input").val()-1, $(this).html(), 0, 0, 0, 0);
			dateTo = new Date($("#year-input").val(), $("#month-input").val()-1, $(this).html(), 0, 0, 0, 0);
			
			$(".arrival").html(date.toDateString());
			
		}
		
		if($(".leave").html() == "")
		{
			if($("select[name='duration']").val() == "other")
			{
				$("#other").show();	
				$("#other").trigger("keyup");	
			}
			else
			{
				$("select[name='duration']").trigger("change");	
			}
		}
		
	});

	$("select[name='duration']").livequery("change", function(){
		
		dateTo.setFullYear($("#year-input").val(), $("#month-input").val()-1, $(".selected").html());
		if($(".leave-date").length == 0)
		{
			$(".update ol").append("<li class='green leave-date'>Departure: <span class='leave'></span></li>");
			$(".instructions .alpha li:nth-child(2)").addClass("strike");
			$("#enter").addClass("click");
		}
		var days = $(this).val();
		
		if(days == "other"){
			$("#other").show();
			$("#other").keyup(function(){
				var originalDate = date;
				//alert(originalDate);
				var other = parseFloat($("#other").val())-1;
				if(!isNaN(other))
				{
					dateTo.setTime(date.getTime());
					dateTo.setDate(dateTo.getDate()+other);
					$(".leave").html(dateTo.toDateString());
					$.ajax({
					  type: 'POST',
					  url: 'check.php',
					  data: {to:dateTo.toDateString(),from:date.toDateString()},
					  success: function(data){
						  if(data=="TRUE"){ 
							 
							$("#enter").removeClass("click");
							$(".leave-date").removeClass("green").addClass("red").attr("title", 'This date is not available, check the calendar');  
							$('.leave-date').tipsy({trigger: 'manual', gravity: "n"});
							$('.leave-date').tipsy("show");
						  }
						  else
						  {
							$(".leave-date").removeClass("red").addClass("green");  
							$('.leave-date').tipsy('hide');
							$("#enter").addClass("click");  
						  }
					  },
					  dataType: 'HTML'
					});
				}
				else
				{
					$(".leave").html("Please enter a valid number of days");
				}
			});	
		}
		else
		{
			$("#other").hide();	
			//work out the end date
			for(var i = 1; i<days; i++)
			{
				var currentDay = dateTo.getDate();
				dateTo.setDate(dateTo.getDate()+1);
			}
			$(".leave").html(dateTo.toDateString());
		}
		
		$.ajax({
		  type: 'POST',
		  url: 'check.php',
		  data: {to:dateTo.toDateString(),from:date.toDateString()},
		  success: function(data){
			  if(data=="TRUE"){ 
				$("#enter").removeClass("click");
				$(".leave-date").removeClass("green").addClass("red").attr("title", 'This date is not available, check the calendar');  
				$('.leave-date').tipsy({trigger: 'manual', gravity: "n"});
				$('.leave-date').tipsy("show");
		  	  }
			  else
			  {
				$(".leave-date").removeClass("red").addClass("green");  
				$('.leave-date').tipsy('hide');
				$("#enter").addClass("click");  
			  }
		  },
		  dataType: 'HTML'
		});

	});
	
	$(".calendar").ajaxComplete(function(){
		$("#stay, .next").hide();

		if($(".leave-date").length > 0){
			$(".next").show();
		}
		if($(".arrival-date").length > 0){
			if((date.getMonth()+1) == $("#month-input").val())
			{
				$("#stay").show();	
				$(".colDay1 .day:textEquals('"+date.getDate()+"'),.colDay2 .day:textEquals('"+date.getDate()+"'),.colDay3 .day:textEquals('"+date.getDate()+"'),.colDay4 .day:textEquals('"+date.getDate()+"'),.colDay5 .day:textEquals('"+date.getDate()+"'),.colDay6 .day:textEquals('"+date.getDate()+"'),.colDay7 .day:textEquals('"+date.getDate()+"'),").addClass("selected");	
			}
		}
		
		$(this).show();
	});
	
	//submit form stuff
	$("#submit").click(function(){
		if($("#name").val()	&& $("#address").val()){
			if($("#email").val() || $("#tel").val()){
				var serial = $("#contact-details").serialize()+"&from="+escape(date.toDateString())+"&to="+escape(dateTo.toDateString());
				$.post("submit.php", serial, function(data) {
				  if(data == "SUCCESS"){
					  alert("Thankyou for the enquiry, I'll be in touch soon!");
					  $(".instructions .alpha li:nth-child(3), .instructions .alpha li:nth-child(4)").addClass("strike");
					  $(".calendar").load("calendar.php", {y: date.getFullYear(), m:date.getMonth()+1}, function(){
						$("#stay, .update").remove();  
					    $(".calendar-header").attr("title", "Your dates can now be seen here");
					    $(".calendar-header").tipsy({trigger: 'manual', gravity: "s"});
					    $(".calendar-header").tipsy("show");
						$("#enter").removeClass("click");
					  });
				  }
				  else
				  {
					   alert("Please get in touch by phone, we're having trouble with the contact form");
				  }
				  
				  $.fn.colorbox.close();
				});

				return false;
			}
			else
			{
				$("#errors").html("Make sure you've entered an email address or telephone number, or both").slideDown("fast");
				return false;
			}
		}
		else
		{
			$("#errors").html("Please ensure you've entered both your name and address").slideDown("fast");
			return false;
		}
	});
	
	$("body").click(function(){
		$(".calendar-header").tipsy("hide");	
	});
	
});
