jQuery(document).ready(function()
{
	if ($.browser.msie && /6.0/.test(navigator.userAgent))
    {
		jQuery("div.available ol li").hover(function() {
			jQuery(this).addClass('hover');
		}, function() {
			jQuery(this).removeClass('hover');
		});
	}

	/*
	jQuery('#sigplus_crys img, #sigplus_crys a').click(function()
	{
		//http://africanpride.d.cytrus.biz:35/images/gallery/crys/crys23.jpg

		while ($('#SLB-Image').length < 1)
		{

		}

		//setInterval("handleDuckHunt()", 2000);
	});
	*/

	// For homepage slideshow
	if($('#fadingImages').length > 0)
	{
		setInterval("slideSwitch()", 9000);
	}

	// On hotel pages for top gallery
	if ($("#imageScroll").length > 0) {

		jQuery("#imageScroll").jCarouselLite({
			auto: 5000,
			speed: 1000,
			btnNext: "#galleryNext",
			btnPrev: "#galleryPrev",
			afterEnd: function(data)
			{
				$('img#largeImg').attr('src', data[0].children[0]['href']);
			}
		});

		jQuery("#imageScroll ul li a").click(function(){

			var largePath = jQuery(this).attr("href");
			var largeAlt = jQuery(this).attr("title");

			jQuery("#largeImg").attr({
				src: largePath,
				alt: largeAlt
			});

			jQuery("h2 em").html(" (" + largeAlt + ")");

			return false;
		});
	}
	
	//For booking forms with single calendar requirement
	if (jQuery("#booking_date").length > 0) {
		
		jQuery("#booking_date").datepicker({
			minDate: 0,
			dateFormat: 'yy-mm-dd',
			buttonImage: '/modules/mod_ap_bookingwidget/datepicker.png',
			buttonImageOnly: true,
			showOn: 'both',
			buttonText: 'Pick date'
		});
	}

	// Calendars on booking forms
	if (jQuery("#checkin, #checkout").length > 0)
	{
		jQuery("#checkin, #checkout").datepicker({
			minDate: 0,
			dateFormat: 'yy-mm-dd',
			onSelect: function() {
				var msPday = 1000 * 60 * 60 * 24;

				var checkinDate = $("#checkin").datepicker('getDate');
				var checkoutDate = $("#checkout").datepicker('getDate');

				if(this.id == "checkin" &&  checkinDate.getTime() > checkoutDate.getTime()) {
					checkoutDate.setTime(checkinDate.getTime() + (msPday * 3));

					$("#checkout").datepicker('setDate', checkoutDate);
				} else {
					var regex = new RegExp('^[0-9]+-[0-9]+-[0-9]+$');

					if(!regex.test($("#checkin").val()) || !regex.test($("#checkout").val())) {
						$("#nights").val("n/a");

						return;
					}
				}

				var diff = Math.floor((checkoutDate.getTime() - checkinDate.getTime()) / msPday);

				if(diff <= 0) {
					diff = "n/a";
				}

				$("#nights").val(diff);
			}
		});
	}

	// Calendars on conference booking forms
	if (jQuery("#booking_arrival, #booking_departure").length > 0) {
		jQuery("#booking_arrival, #booking_departure").datepicker({
			buttonImage: '/modules/mod_ap_bookingwidget/datepicker.png',
			buttonImageOnly: true,
			showOn: 'both',
			buttonText: 'Pick date',
			defaultDate: 0,
			minDate: +1,
			maxDate: '+5y',
			dateFormat: 'yy-mm-dd',
			onSelect: function(dateText) {
				var checkinDate = $("#booking_arrival").datepicker('getDate');
				var checkoutDate = $("#booking_departure").datepicker('getDate');

				if(this.id == "booking_arrival") {
					if (checkinDate.getTime() >= checkoutDate.getTime()) {
						checkoutDate.setTime(checkinDate.getTime());

						$("#booking_departure").datepicker('setDate', checkoutDate);
					}
					$("#booking_departure").datepicker('option', 'minDate', checkinDate);
				} else {
					var regex = new RegExp('^[0-9]+-[0-9]+-[0-9]+$');
				}
			}
		});
	}

	if (jQuery('#booking_eventrequirement').length > 0) {
		toggle_optional = function (element) {
			if ('Venue and Accommodation' == jQuery(element).val()) {
				jQuery('.optional').show('fast');
			} else {
				jQuery('.optional').hide('fast');
			}
		};

		toggle_optional($('#booking_eventrequirement'));
		jQuery('#booking_eventrequirement').change(function () {
			toggle_optional(this);
		});
	}


	if($('#roomTimer').length > 0) {
		var time = $('#roomTimer').text();

		time = time.split(":");

		var seconds = parseInt(time[1], 10) + (parseInt(time[0], 10) * 60);

		document.countDownTo = new Date().getTime() + (seconds * 1000);

		updateRoomTimer();
	}
	
	if ($('#prokardPopup').length > 0) {
		$('#prokardPopup').fancybox({overlayColor: '#000'});
	}

    // Google analytics click tracking
    analyticsTracking();
	
	contactUsForm();
	
	specialsLandingPage();
});

function contactUsForm()
{
	if ($('#frmContactUs').length > 0)
	{
		$('#frmContactUs').submit(function()
		{
			if ($('#contactSubject').val() == '')
			{
				alert('Please select a subject for your message');
				
				return false;
			}
		});
	}
}

function handleDuckHunt()
{
	//jQuery()
}

function log(message)
{
	if(typeof console != "undefined")
	{
		console.log(message);
	}
}

function updateRoomTimer() {
	if(document.countDownTo) {
		var nowSeconds = new Date().getTime();
		var remaining = Math.floor((document.countDownTo - nowSeconds) / 1000);

		var text = '00:00';
		if(remaining > 0) {
			var seconds = Math.floor(remaining % 60);
			var minutes = Math.floor(remaining / 60);

			text = (minutes < 10 ? '0' + minutes : minutes) + ":" + ((seconds < 10) ? '0' + seconds : seconds);

			$('#roomTimer').text(text);

			setTimeout(updateRoomTimer, 250);
		} else {
			$('#roomTimer').text(text);

			alert('Your session has expired, and we can no longer guarantee that your room is still available. Please restart your booking, and try again.');

			document.location.href = '/';
		}
	}
}

function slideSwitch()
{
	var active = jQuery('#fadingImages div.active');

	if ( active.length == 0 ) {
		active = jQuery('#fadingImages div:last');
	}

	var next =  active.next().length ? active.next() : jQuery('#fadingImages div:first');

	next.show();

	active.fadeOut('slow', function()
	{
    	active.addClass('last-active');
    	active.removeClass('active last-active');
    	next.addClass('active');
    });

	/*
	active.addClass('last-active');

	// Removed opacity for now cause of IE crappiness
	next.css({
		//		opacity: 0.0
		}).
	addClass('active').
	animate({
		//		opacity: 1.0
		}, 1000, function() {
			active.removeClass('active last-active');
		});
	*/
}

function select_hotel(hotelcode, firstRoomCode, firstRateCode, firstRateSlug) {
	$('#hotels li.selected').removeClass('selected');
	$('#hotel_' + hotelcode).addClass('selected');

	$("#rooms ol").hide();
	$('#rooms_' + hotelcode).show();

	$('#hotelinfo div').hide();
	$('#hotelinfo_' + hotelcode).show();

	select_room(hotelcode, firstRoomCode, firstRateCode, firstRateSlug);
}

function select_room(hotelcode, roomcode, firstRateCode, firstRateSlug) {
	$("#rooms_" + hotelcode + " li.selected").removeClass('selected');
	$('#room_' + hotelcode + '_' + roomcode).addClass('selected');

	$('#rates ol').hide();
	$('#rates_' + hotelcode + '_' + roomcode).show();

	select_rate(hotelcode, roomcode, firstRateCode, firstRateSlug);
}

function select_rate(hotelcode, roomcode, ratecode, slug) {
	$('#rates_' + hotelcode + '_' + roomcode + ' li.selected').removeClass('selected');

	$('#rate_' + hotelcode + '_' + roomcode + '_' + ratecode).addClass('selected');

	$('#booking-slug').val(slug);
}

function specialsLandingPage(){
	if ($('.landingPage').length > 0){
		$('.specialId').each(function(){
			
			var specialId = $(this).val();

			if ($('#prokard_' + specialId).length > 0){
				$('#prokard_' + specialId).focus(function(){
					if ($('#prokard_' + specialId).val() == 'Prokard Number'){
						$('#prokard_' + specialId).val('');
					}
				});
				
				$('#prokard_' + specialId).blur(function(){
					if ($('#prokard_' + specialId).val() == ''){
						$('#prokard_' + specialId).val('Prokard Number');
					}
				});
			}

			if (jQuery("#checkin_" + specialId + ", #checkout_" + specialId).length > 0)
			{
				jQuery("#checkin_" + specialId + ", #checkout_" + specialId).datepicker({
					minDate: 0,
					dateFormat: 'yy-mm-dd',
					onSelect: function() {
						var msPday = 1000 * 60 * 60 * 24;

						var checkinDate = $("#checkin_" + specialId).datepicker('getDate');
						var checkoutDate = $("#checkout_" + specialId).datepicker('getDate');

						if(this.id == "checkin_" + specialId &&  checkinDate.getTime() > checkoutDate.getTime()) {
							checkoutDate.setTime(checkinDate.getTime() + (msPday * 3));

							$("#checkout_" + specialId).datepicker('setDate', checkoutDate);
						} else {
							var regex = new RegExp('^[0-9]+-[0-9]+-[0-9]+$');

							if(!regex.test($("#checkin_" + specialId).val()) || !regex.test($("#checkout_" + specialId).val())) {
								$("#nights_" + specialId).val("n/a");

								return;
							}
						}

						var diff = Math.floor((checkoutDate.getTime() - checkinDate.getTime()) / msPday);

						if(diff <= 0) {
							diff = "n/a";
						}

						$("#nights_" + specialId).val(diff);
					}
				});
			}
		});
	}
}

function validateLandingPageBooking(specialId) {
	var regex = new RegExp('^[0-9]+-[0-9]+-[0-9]+$');
	if(!regex.test($("#checkin_" + specialId).val()) || !regex.test($("#checkout_" + specialId).val())) {
		alert('Please select a start and end date');

		$("#checkin_" + specialId).focus();

		return false;
	}

	var today = new Date();
	var checkinDate = $("#checkin_" + specialId).datepicker('getDate');
	var checkoutDate = $("#checkout_" + specialId).datepicker('getDate');

	if(checkoutDate.getTime() <= checkinDate.getTime()) {
		alert('Your check out date needs to be after your check in date');

		$("#checkout_" + specialId).focus();

		return false;
	}

	if ($('#chkProkardMember_' + specialId).is(':checked'))
	{
		if ($('#inptProkard_' + specialId).val() == '')
		{
			$('#prokardPopup_' + specialId).trigger('click');

			return false;
		}
	}

	$('#availability-search-btn_' + specialId).hide();
	$('#availability-search-loading_' + specialId).show();

	$('#bookingWidget_' + specialId).hide();
	$('#availability_' + specialId).hide();

	$('#preloader_' + specialId).show();

	return true;
}

(function($){
	$.fn.extend({
		validateMiniBooking: function() {
			var regex = new RegExp('^[0-9]+-[0-9]+-[0-9]+$');
			if(!regex.test($("#checkin").val()) || !regex.test($("#checkout").val())) {
				alert('Please select a start and end date');

				$("#checkin").focus();

				return false;
			}

			var today = new Date();
			var checkinDate = $("#checkin").datepicker('getDate');
			var checkoutDate = $("#checkout").datepicker('getDate');

//			if(checkinDate.getTime() < today.getTime()) {
				//alert('Please enter a date after today');

//				$("#checkin").focus();

  //			  return false;
	//		}

			if(checkoutDate.getTime() <= checkinDate.getTime()) {
				alert('Your check out date needs to be after your check in date');

				$("#checkout").focus();

				return false;
			}
			
			if ($('#chkProkardMember').is(':checked'))
			{
				if ($('#inptProkard').val() == '')
				{
					$('#prokardPopup').trigger('click');

					return false;
				}
			}

			$('#availability-search-btn').hide();
			$('#availability-search-loading').show();

			$('#bookingWidget').hide();
			$('#availability').hide();

			$('#preloader').show();

			return true;
		},
		validateBooking: function() {
			var messages = new Array();
			var fields = new Array();

			function checkEmpty(id) {
				return $(document.getElementById(id)).val().replace(/^\s*/, '').replace(/\s*$/, '') == '';
			}

			function checkEmail(id) {
				return $(document.getElementById(id)).val().match(/^[^@]+@[^.]+[.].*$/);
			}

			if(checkEmpty('guest.name')) {
				messages.push('Name');
				fields.push('guest.name');
			}

			if(checkEmpty('guest.surname')) {
				messages.push('Surname');
				fields.push('guest.surname');
			}

			if(checkEmpty('guest.idnumber')) {
				messages.push('ID/Passport Number');
				fields.push('guest.idnumber');
			}

			if(checkEmpty('guest.telephone')) {
				messages.push('Telephone/Mobile');
				fields.push('guest.telephone');
			}

			if(checkEmpty('guest.email') || !checkEmail('guest.email')) {
				messages.push('Email');
				fields.push('guest.email');
			}

			if(checkEmpty('guest.address.line1')) {
				messages.push('Address Line 1');
				fields.push('guest.address.line1');
			}

			if(checkEmpty('guest.address.city')) {
				messages.push('City');
				fields.push('guest.address.city');
			}

			if(checkEmpty('guest.address.postalcode')) {
				messages.push('Postal Code');
				fields.push('guest.address.postalcode');
			}

			if(checkEmpty('guest.card.name')) {
				messages.push('Name on Card');
				fields.push('guest.card.name');
			}

			if(checkEmpty('guest.card.type')) {
				messages.push('Credit Card Type');
				fields.push('guest.card.type');
			}

			if(checkEmpty('guest.card.number')) {
				messages.push('Card Number');
				fields.push('guest.card.number');
			}

			if(checkEmpty('guest.card.cvv')) {
				messages.push('CVC');
				fields.push('guest.card.cvv');
			}
			
//			if (!$('#chkAgree').is(':checked'))
//			{
//				messages.push('Agree to the terms and conditions');
//				fields.push('chkAgree');
//			}

			if(messages.length == 0) {
				return true;
			}

			var message = '';
			for(i in messages) {
				message += " * " + messages[i] + "\n";
			}

			alert("Please check the following values:\n" + message);

			$('label', this).css({
				color: 'inherit'
			});
			for(i in fields) {
				$("label[for='"+fields[i]+"']", this).css({
					color: '#984251'
				});
			}

			return false;
		}
	});
})(jQuery);

function analyticsTracking()
{
    // Home page - Search button on booking widget
    if ($('li.lower #availability-search-btn').length > 0)
    {
        $('li.lower #availability-search-btn').click(function()
        {
            pageTracker._trackEvent('Booking','Check_Availability_Button','Home_Page');
        });
    }

    // Results page - Book button and search button
    if ($('#reserve-form #btnBookNow').length > 0)
    {
        $('#reserve-form #btnBookNow').click(function()
        {
            pageTracker._trackEvent('Booking','Book_Now_Button','Search_Results');
        });

		$('li.lower #availability-search-btn').click(function()
        {
            pageTracker._trackEvent('Booking','Check_Availability_Button','Search_Results');
        });
    }

    // Personal details - book button
    if ($('#booking-form').length > 0)
    {
        $('#booking-form').submit(function()
        {
			var hotelCode = $('#hotelCode').val();

            pageTracker._trackEvent('Booking','Check_Availability_Button','Hotel_Booking_Widget_'+hotelCode);
        });
    }

    // Carousel click through URL
    if ($('div#fadingImages').length > 0)
    {
        $('div#fadingImages a').click(function()
        {
            pageTracker._trackEvent('Home','Carousel_Image_Click',$(this).find('img').attr('alt'));
        });
    }

    // Hotel page – Search button on booking widget
    if ($('div.hotelBook').length > 0)
    {
        $('div.hotelBook #availability-search-btn').click(function()
        {
			var hotelCode = $('#hotelCode').val();

            pageTracker._trackEvent('Booking','Search_Button','Hotel_Booking_Widget_'+hotelCode);
        });
    }
}
