var weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
	closedDates = [],
	closedDatesJS = [],
	pHolidays = [],
	pHolidaysJS = [],
	accommodationSleeps = 0,
	totalGuests = 0;

function oc(a) {
	var o = {},
		i;

	for (i = 0; i < a.length; i++) {
		o[a[i]] = '';
	}
	
	return o;
}

function compareAccommodationSleepsWithGuests() {
	var accommodationType = $('#accommodation_type option:selected'),
		accommodationName = accommodationType.data('name'),
		numUnitsRequired;

	accommodationSleeps = parseInt(accommodationType.data('sleeps'), 10);

	if (totalGuests <= accommodationSleeps) {
		$('#user-message').hide();
	} else if (totalGuests > accommodationSleeps) {
		numUnitsRequired = Math.ceil(totalGuests / accommodationSleeps);
		
		// If accommodationSleeps = 17 then its the bunk barn. Only 1 exists so set message accordingly
		if (accommodationSleeps >= 12) {
			$('#user-message').text('Sorry, the maximum number of guests for the Bunk Barn is 12!').show();
		} else {
			$('#user-message').text('You will need ' + numUnitsRequired + ' ' + accommodationName + 's for this many people').show();
		}
	}
}

function get_durations(selectedDate) {	
	var options;
	
	// Get all duration options based on selected arrival date
	$.ajax({
		url: '/index.php',
		dataType: 'json',
		data: {'ACT': '29', 'ajax': true, 'method': 'get_durations', 'start_date': selectedDate},
		type: 'post',
		success: function (data) {
			var options = "<option value=''>Please select how long you wish to stay</option>";

			$.each(data.durations, function (key, val) {
				var nights = val[0],
					start = val[1],
					end = val[2];

				if (nights === 1) {
					options += "<option value=" + nights + ">" + nights + " nights (" + start + " - " + end + ")</option>";
				} else {
					options += "<option value=" + nights + ">" + nights + " nights (" + start + " - " + end + ")</option>";
				}
			});

			$('select#duration').html(options).parent().show();
		}
	});	
}

function calendar_tooltip() {
	$('#ui-datepicker-div').on('mouseover', 'td.public_holiday', function (event) {			
		if (event.pageX) {
			$('#tooltip_hint').css({
				top: event.pageY + 15,
				left: event.pageX - 30
			}).html("Public Holiday").show();
		} else {
			$('#tooltip_hint').hide();
		}

		return false;
	});

	$('#ui-datepicker-div').on('mouseout', 'table.ui-datepicker-calendar', function (event) {
		$('#tooltip_hint').hide();
	});
}

$(function () {
	// General Calendar
	if ($('.quick-booking').length > 0) {
		$('#quick-book').submit(function () {
			// Some basic form validation
			if ($('#datepicker').val() === '') {
				alert('Please select an arrival date');
				return false;
			}
			
			if ($('#duration').val() === '') {
				alert('Please select how long you would like to stay');
				return false;
			}
		});
	
		// Get all closed/unavailable dates	
		$.ajax({
			url: '/index.php',
			dataType: 'json',
			type: 'post',
			data: {'ACT': '29', 'ajax': true, 'method': 'get_unavailable_dates'},
			success: function (data) {
				if (data.response === true) {
					$.each(data.dates, function (key, val) {
						var date = val.split("-"),
							dateArray = [date[0], date[1], date[2]],
							dateArrayJSDate = date[0] + "/" + date[1] + "/" + date[2];

						closedDates.push(dateArray);
						closedDatesJS.push(dateArrayJSDate);
					});
				}
			}
		});

		// Get Public Holiday dates
		$.ajax({
			url: '/index.php',
			dataType: 'json',
			data: {'ACT': '29', 'ajax': true, 'method': 'get_public_holidays'},
			type: 'post',
			success: function (data) {
				$.each(data, function (key, val) {
					var pHoliday = val['start_date'].split("-"),
						pHolidayArray = [pHoliday[0], pHoliday[1], pHoliday[2]],
						pHolidayJSDate = pHoliday[0] + "/" + pHoliday[1] + "/" + pHoliday[2];

					pHolidays.push(pHolidayArray);
					pHolidaysJS.push(pHolidayJSDate);
				});
					
				$("#datepicker").datepicker({
					firstDay: 1,
					//minDate: 0,
					minDate: "04/01/2012",
					maxDate: "12/31/2012",
					
					showOn: "button",
					buttonImage: "/images/calendar-white-icon.png",
					buttonImageOnly: true,
					beforeShow: function (input, inst) {
						inst.dpDiv.css({marginTop: -(input.offsetHeight + 115) + 'px', marginLeft: (input.offsetWidth - 250) + 'px'});
					},
					beforeShowDay: function (date) {
						var day = date.getDay(),
							month = date.getMonth(),
							year = date.getFullYear(),
							thisDate = date.getDate(),
							i;
							
						// Process closed dates
						for (i = 0; i < closedDates.length; i++) {
							if (month == closedDates[i][1] - 1 && thisDate == closedDates[i][0] && year == closedDates[i][2]) {
								return [false, 'unavailable'];
							}
						}
						
						// Process Public holidays
						for (i = 0; i < pHolidays.length; i++) {
							var holDate = pHolidays[i][0],
								holMonth = pHolidays[i][1] - 1,
								holYear = pHolidays[i][2],
								nextDay = parseInt(pHolidays[i][0], 10) + 1,
								nextDate = new Date(holYear, holMonth, nextDay);
											
							if (month == holMonth && thisDate == holDate && year == holYear) {
								if (weekdays[day - 1] == 'Friday') {
									return [true, 'book-in-date available'];
								} else if (weekdays[day - 1] == 'Monday') {
									return [false, 'available public_holiday'];
								} else {
									return false;
								}
							} else if (month == nextDate.getMonth() && thisDate == nextDate.getDate() && year == nextDate.getFullYear()) {
								if (weekdays[day - 1] === 'Tuesday') {
									return [true, 'book-in-date available'];
								}
							}
						}
						
						if (weekdays[day - 1] === 'Monday' || weekdays[day - 1] === 'Friday') {
							return [true, 'book-in-date available'];
						} else {
							return [false, 'available'];
						}
					},
					onSelect: function (dateText, inst) {
						var selectedDate = inst.selectedDay + "-" + (inst.selectedMonth + 1) + "-" + inst.selectedYear,
							selectedMonthYear = "",
							d = new Date(dateText);
							
						// Change dropdown month_year and day to match selected from calendar
						if ((inst.selectedMonth + 1) < 10) {
							selectedMonthYear = "0" + (inst.selectedMonth + 1) + "/" + inst.selectedYear;
						} else {
							selectedMonthYear = (inst.selectedMonth + 1) + "/" + inst.selectedYear;
						}
									
						$('#month_year').val(selectedMonthYear).change();
						$('#day').val(inst.selectedDay).change();
		
						get_durations(selectedDate);	
					}
				});	
				
				calendar_tooltip();
			}
		});	
		
		// Get accommodation types
		$.ajax({
			url: '/index.php',
			data: {'ACT': '29', 'ajax': true, 'method': 'get_accommodation_types'},
			type: 'post',
			success: function (data) {
				$('#accommodation_type').append(data);
			}
		});	
		
		// Month & Year select change
		$('#month_year').change(function (e) {
			var monthYear = $(this).val(),
				daysInMonth,
				today = new Date(),
				loopDateTime,
				loopDate,
				firstDay,
				daysText = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'],
				days = [],
				numDays,
				options = "<option value='--'>--</option>",
				i;
			
			// Get number of days in this month
			monthYear = monthYear.split("/");
			daysInMonth = new Date(monthYear[1], monthYear[0], 0).getDate();		

			for (i = 1; i <= daysInMonth; i++) {
				loopDateTime = new Date(monthYear[1], monthYear[0] - 1, i);
				loopDate = loopDateTime.getDate();
			
				// Is this date a public holiday?
				for (var x = 0; x < pHolidays.length; x++) {
					var holDate = pHolidays[x][0],
						holMonth = pHolidays[x][1] - 1,
						holYear = pHolidays[x][2],
						nextDay = parseInt(pHolidays[x][0], 10) + 1,
						nextDate = new Date(holYear, holMonth, nextDay);
									
					if ((monthYear[0] - 1) == holMonth && loopDate == holDate && monthYear[1] == holYear) {
						if (daysText[loopDateTime.getDay()] == 'Fri') {
							days.push([i, loopDateTime.getDay()]);
						}
					} else if ((monthYear[0] - 1) == nextDate.getMonth() && loopDate == nextDate.getDate() && monthYear[1] == nextDate.getFullYear()) {
						if (daysText[loopDateTime.getDay()] === 'Tue') {
							days.push([i, loopDateTime.getDay()]);
						}
					}
				}
			
				// If not a public holiday then if it's a Monday or Friday add then to days array
				if (daysText[loopDateTime.getDay()] == 'Mon' || daysText[loopDateTime.getDay()] == 'Fri') {
					days.push([i, loopDateTime.getDay()]);
				}
			}

			// Add each Date to select field
			numDays = days.length;
					
			for (i = 0; i < numDays; i++) {
				// Only add to options if today or in the future
				var thisDate = new Date(monthYear[1], monthYear[0] - 1, days[i][0]);
				
				if (thisDate >= today) {
					// Check if this isn't a public holiday or a site closed day
					var dateString,
						dayString = thisDate.getDate(),
						monthString = thisDate.getMonth() + 1,
						closed = oc(closedDatesJS),
						holidays = oc(pHolidaysJS);
					
					// Add leading 0's if under 10 for day and month
					if (monthString < 10) {
						monthString = "0" + monthString;
					}
					
					if (dayString < 10) {
						dayString = "0" + dayString;
					}
					
					dateString = dayString + "/" + monthString + "/" + thisDate.getFullYear();
					
					if ((dateString in closed) === false) {
						if ((dateString in holidays) === false) {
							options += "<option value='" + days[i][0] + "'>" + daysText[days[i][1]] + " " + days[i][0] + "</option>";
						}	
					}
				}
			}
			
			$('#day').html(options);
			
			// Set Month/Year on Calendar 
			var calendarDate = $('#datepicker').datepicker('getDate'),
				calendarMonth;

			if (calendarDate != null) {
				calendarMonth = calendarDate.getMonth() + 1;
					
				if (calendarMonth < 10) {
					calendarMonth = "0" + calendarMonth;
				}
				
				if (calendarMonth !== monthYear[0]) {
					$('#datepicker').datepicker('setDate', monthYear[0] + "/01/" + monthYear[1]);
				}
			} else {
				$('#datepicker').datepicker('setDate', monthYear[0] + "/01/" + monthYear[1]);
			}
						
			//$('#day').change();
		}).change();
		
		// Day select Change
		$('#day').change(function () {
			// Set Month/Year/Day on Calendar 
			// Get selected Month/Year
			var monthYear = $('#month_year').val().split("/"),
				day = $(this).val(),
				selectedDate = monthYear[0] + "/" + day + "/" + monthYear[1];
			
			$('#datepicker').datepicker('setDate', selectedDate);
			
			get_durations(selectedDate);
		});
		
		// Accommodation Type select
		$('#accommodation_type').change(compareAccommodationSleepsWithGuests);
		
		// Get total guests on adult or under 17 select
		$('#adults, #children').change(function () {
			// Number of adults
			var adults = $('#adults').val(),
				children = $('#children').val();
				
			totalGuests = parseInt(children, 10) + parseInt(adults, 10);
			
			compareAccommodationSleepsWithGuests();
		});
	}
	
	// Newsletter lightbox
	$('#newsletter').fancybox({
		fitToView	: false,
		autoSize	: true,
		closeClick	: false,
		closeBtn	: true,
		openEffect	: 'none',
		closeEffect	: 'none',
		title		: true
	});

	// Map
	if ($('div.map').length > 0) {
		var latlng = new google.maps.LatLng(54.215, -1.67),
			myOptions = {
				zoom: 12,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				mapTypeControl: true,
			    mapTypeControlOptions: {
			        style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
			        position: google.maps.ControlPosition.TOP_RIGHT
			    },
			    zoomControl: true,
			    zoomControlOptions: {
			        style: google.maps.ZoomControlStyle.SMALL,
			        position: google.maps.ControlPosition.RIGHT_TOP
			    },
			    streetViewControl: false
			},
			map = new google.maps.Map($('.map').get(0) , myOptions),
			marker = new google.maps.Marker({
				position: new google.maps.LatLng(54.2034, -1.72557),
				map: map,
				title:"Bivouac Swinton"
			});
	}
	
	if ($('.feature-slider').length > 0) {
		var featureContainer = $('.feature-box'),
			featureContainerWidth = featureContainer.width(),
			dotNav = $('.feature-dot-nav');
	
		$('.feature-slider').cycle({
			speed	: 1000,
			timeout	: 8000,
			next	: '.feature-slide-right',
			prev	: '.feature-slide-left',
			pager	: '.feature-dot-nav'
		});
		
		// Align dot navigation centrally
		dotNav.css({
			'left': (featureContainerWidth - dotNav.width()) / 2
		});
	}
	
	// Sub Section Sliders
	if ($('ul.sub-section-slider').length > 0) {
		// Sub Section Image Sliders
		$('ul.sub-section-slider').each(function () {
			var entryID = $(this).data('id'),
				ImageContainer = $('#sub-section-image-box-' + entryID),
				ImageContainerWidth = ImageContainer.width(),
				dotNav = $('#sub-section-images-dot-nav-' + entryID);
		
			$('#sub-section-slider-' + entryID).cycle({
				speed	: 1000,
				timeout	: 0,
				next	: '#sub-section-images-slide-right-' + entryID,
				prev	: '#sub-section-images-slide-left-' + entryID,
				pager	: '#sub-section-images-dot-nav-' + entryID
			});
			
			// Align dot navigation centrally
			dotNav.css({
				'left': (ImageContainerWidth - dotNav.width()) / 2
			});
		});
	}
	
	if ($('ul.page-sub-section-content li').length > 0) {
		$('ul.page-sub-section-content').height($('ul.page-sub-section-content > li:eq(0)').height() + "px");
	
		var subSectionNav = $('ul.page-sub-section-nav');
		
		// Sub Section Primary Slider
		$('ul.page-sub-section-content').cycle({
			speed: 500,
			timeout: 0
		});
		
		// Make first slider nav link active
		subSectionNav.find('li').eq(0).children('a').addClass('active');
		
		// When sub section nav link clicked, show appropriate content/slide
		subSectionNav.find('a').on('click', function () {
			var li = $(this).parent(),
				slide = subSectionNav.find('li').index(li),	
				slideHeight = $('ul.page-sub-section-content > li:eq(' + slide + ')').height();
			
			subSectionNav.find('a.active').removeClass('active');
			$(this).addClass('active');
			
			$('ul.page-sub-section-content').cycle(slide).animate({'height': slideHeight + "px"}, 1000);
			
			return false;
		});
	}
	
	// Image Lightbox for blog
	if ($('a.lightbox-image').length > 0) {
		$('a.lightbox-image').fancybox();
	}
	
	//CONTACT FORM VALIDATION BEGIN
	if ($('#contact-form').length > 0) {
		$('#contact-form').validate({
			rules: {
				contact_name: {
					required: true,
					minlength: 2
				},
				contact_subject: {
					required: true
				},
				contact_question: {
					required: true,
					minlength: 5
				},
				contact_captcha: {
					required: true
				}
			},
			messages: {
			    contact_name: {
					required: "Please specify your name",
					minlength: "Please enter 2 or more characters"
			    },
			    contact_email: {
					required: "We need your email address to send you a reply.",
					email: "We need your full email address please."
				},
				contact_subject: {
					required: "Please enter a subject"
				},
				contact_question: {
					required: "Please enter your question or query",
					minlength: "Please enter 5 or more characters"
				},
				contact_captcha: {
					required: "Please enter the number"
				}
			},
			submitHandler: function() {
				$('#contact-form').ajaxSubmit({
					url: 'http://www.thebivouac.co.uk/scripts/formtoemail.php',
					resetForm: true,
					success: function (data) {
	                    $('#form-validation').html("<h2 class='contact_result'>" + data + "</h2>");
	                }
				});
			}
		}); 
	}
	
	if ($('ul.faqs').length > 0) {
		$('ul.faqs').find('h3').on('click', function () {
			// Close any open questions before opening the clicked question
			// check if this one is already open. If so just close it
			if ($(this).next('div.answer').hasClass('open')) {
				$('ul.faqs').find('div.open').slideUp(500).removeClass('open');
			} else {
				$('ul.faqs').find('div.open').slideUp(500).removeClass('open');
				$(this).next('div.answer').addClass('open').slideDown(500);
			}
			
			return false;
		});
	}
});

/* ============= Other Scripts ================== */

window._gaq = [['_setAccount','UA-310331-21'],['_trackPageview'],['_trackPageLoadTime']];

Modernizr.load({
  load: ('https:' == location.protocol ? '//ssl' : '//www') + '.google-analytics.com/ga.js'
});

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

try {
var pageTracker = _gat._getTracker("UA-310331-21");
pageTracker._trackPageview();
} catch(err) {}
