$(function () {	
	var windowFocus = true;
	function windowActive() { windowFocus = true; }
	function windowInactive() { windowFocus = false; }
	window.onfocus = windowActive;
	window.onblur = windowInactive;
	
	if ($('.dynamic_form').length > 0)
	{
		function fix_length (form_width, arr)
		{
			var shortest = form_width;
			
			$.each(arr, function () {
				var width = $(this).prev().width();
				
				if ((form_width - width - 50) < shortest)
					shortest = form_width - width - 50;
			});
			
			$.each(arr, function () {
				$(this).width(shortest);
			});
		}
		
		$('.dynamic_form').each(function () {
			var e = $(this);
			
			var shortest = e.width();
			var newrun = 1;
			var arr = [];
			
			$('label', e).each(function () {
				if ( $(this).next().is('input[type="text"]') || $(this).next().is('select') )
					arr.push($(this).next());
				
				else
				{
					if (arr.length > 0)
					{
						fix_length(e.width(), arr);
						arr = [];
					}
				}
			});
		});
	}
	
	if ($('.photo_gallery .gallery_box').length > 0)
	{
		var tallest = 0;
		
		$('.photo_gallery .gallery_box').each(function () {
			if ($(this).height() > tallest)
				tallest = $(this).height();
		});
		
		$('.photo_gallery .gallery_box').height(tallest);
	}
	
	$('#menu > ul > li > ul > li > ul > li:last-child').addClass('last-child');
	
	$('#menu > ul > li > ul li.open > ul').css('display', 'block');
	
	if ($('#menu > ul > li.open').length == 1)
	{
		var e = $('#menu > ul > li.open');
		
		if (e.hasClass('wedding'))
			$('#menu > ul > li:first').after(e);
		
		if ($('ul > li.open:not(:first-child), ul > li.current:not(:first-child)', e).length > 0)
			$('#menu > ul > li.open > ul').css('display', 'block');
		else
			$('#menu > ul > li.open > ul').slideDown(500);
		// $('#menu > ul > li.open > ul').css('display', 'block');
		// $('#menu > ul > li.open > a').click();
	}
	
	$('#menu ul li a').click(function () {
		var e = $(this).parent();
		
		// This is a top nav item, go to the first sub li
		if ($('ul', e).length > 0)
		{
			var url = $('ul li:first-child a', e).attr("href");
			
			document.location.href = url;
			return true;
		}
		
		if ($('ul', e).length > 0)
		{
			// The sub ul is visible
			if ( $('ul', e).is(':visible') )
			{
				e.removeClass('open');
				$('ul', e).slideUp(500);
			}
			else
			{
				e.siblings().find('ul').slideUp(500);
				e.find('ul').slideUp(500);
				$('ul:eq(0)', e).slideDown(500);
				e.addClass('open');
				e.siblings().removeClass('open');
			}
			
			return false;
		}
	});
	
	$('.faqs_container .question').click(function () {
		if ($(this).next().is(':visible'))
			$(this).next().slideUp();
		else
			$(this).next().slideDown();
	});
	
	// var start_time = 200;
	
	// $('.faqs_container .question').each(function () {
		// window.setTimeout(function () {
			// $('.faqs_container .answer:hidden').eq(0).slideDown();
		// }, start_time);
		
		// start_time += 200;
	// });
	
	$('.submitForm').click(function () {
		$(this).closest('form').submit();
	});
	
	var brdColor = $('#content > h1:first').css('borderBottomColor');
	
	$('#content h1, #content h2').css('borderBottomColor', brdColor);
	
	var date = new Date();
	year = parseInt( date.getFullYear() ) + 1;
	month = parseInt( date.getMonth() );
	day = parseInt( date.getDate() );
	
	$('#book_now .date').datepicker({
		'minDate': new Date(),
		'maxDate': new Date(year, month, day),
		'dateFormat': 'dd/mm/yy'
	});
	$('#book_now .datepickerBtn, #book_now .date').click(function () {
		$('#book_now .date').datepicker('show');
	});
	$('#book_now form').submit(function () {
		var date = $('#book_now .date').val();
		date = date.split('/');
		$('#book_now input[name="ad"]').val(date[0]);
		$('#book_now input[name="am"]').val(date[1] +':'+ date[2]);
	});
	
	$('#book_now .adults, #book_now .children').change(function () {
		var peoples = parseInt( $('#book_now .adults').val() ) + parseInt( $('#book_now .children').val() );
		
		fix_selects(peoples);
	});
	
	function fix_selects (peoples) {
		var minRooms = Math.ceil(peoples / 4);
		
		$('#book_now .rooms option').each(function () {
			if ($(this).attr('value') < minRooms)
				$(this).attr('disabled', 'disabled');
			else
				$(this).removeAttr('disabled');
		});
		
		if ($('#book_now .rooms').val() < minRooms)
		{
			if ($('#book_now .rooms option[value="'+ minRooms +'"]').length == 0)
				$('#book_now .rooms option:last-child').attr('selected', 'selected');
			else
				$('#book_now .rooms option[value="'+ minRooms +'"]').attr('selected', 'selected');
		}
	}
	
	$('#book_now .adults').change();
	
	// Check if the slider controls are visible i.e. we have a top slideshow
	if ( $('#header .slider_controls').is(':visible') )
	{
		var slideInterval;
		var slides = $('#header .backgrounds div');
		var slides_num = slides.length;
		var current_slide = 1;
		var buttons = $('#header .slider_controls .buttons div');
		
		function nextSlide ()
		{
			if (slides_num < 2)
				return;
			
			if (current_slide == slides_num)
				current_slide = 1;
			else
				current_slide++;
			
			if (windowFocus)
			{
				slides.not( slides.eq(current_slide - 1) ).fadeOut();
				slides.eq(current_slide - 1).fadeIn('slow');
			}
			
			buttons.removeClass('sel');
			buttons.eq(current_slide - 1).addClass('sel');
		}
		
		function showSlide (i)
		{
			current_slide = i;
			
			slides.not( slides.eq(current_slide - 1) ).fadeOut();
			slides.eq(current_slide - 1).fadeIn('slow');
			
			buttons.removeClass('sel');
			buttons.eq(current_slide - 1).addClass('sel');
		}
		
		slideInterval = window.setInterval(nextSlide, 5000);
		
		$('#header .slider_controls .pause_btn').click(function () {
			clearInterval(slideInterval);
			slideInterval = null;
		});
		
		$('#header .slider_controls .play_btn').click(function () {
			if (slideInterval == null)
				slideInterval = window.setInterval(nextSlide, 5000);
		});
		
		buttons.click(function () {
			var num = $(this).index();
			
			if (slides.eq(num).length == 1)
			{
				showSlide(num + 1);
				
				clearInterval(slideInterval);
				slideInterval = null;
				
				window.setTimeout(function () {
					$('#header .slider_controls .play_btn').click();
				}, 5000);
			}
		});
	}
	
	$('form.style').submit(function () {
		var e = $(this);
		var error;
		
		$('form.style p > .required, form.style p > span > .required').each(function () {
			var el = $(this);
			
			if (el.attr('type') == 'checkbox' || el.attr('type') == 'radio')
			{
				var text = rtrim(rtrim(el.parent().parent().children('label').text(), ' *'), ':');
				var name = el.attr('name');
				
				if ($('input[name="'+ name +'"]:checked').length == 0)
				{
					alert(lang_txt.please_fill_in + ' ' + text);
					el.focus();
					error = true;
					return false;
				}
			}
			else
			{
				var val = $.trim( el.val() );
				
				if (val == '')
				{
					var text = rtrim(rtrim(el.parent().children('label').text(), ' *'), ':');
					
					alert(lang_txt.please_fill_in + ' ' + text);
					el.focus();
					error = true;
					return false;
				}
				
				if ( el.hasClass('email') && !isValidEmailAddress( el.val() ) )
				{
					var text = rtrim(rtrim(el.parent().children('label').text(), ' *'), ':');
					
					alert(lang_txt.email_invalid);
					el.focus();
					error = true;
					return false;
				}
			}
		});
		
		if (error)
			return false;
	});
	
	if ($('.nivoSlider').length == 0)
		loadWebcam();
	
	
	if (!isMobileUser())
	{
		$('.flashplayer').each(function (index) {
			var movie_info = {
				id: 'mov_'+ index,
				width: $(this).attr('width'),
				height: $(this).attr('height'),
				poster: site_url + $(this).attr('poster'),
				src: $(this).attr('src')
			};
			
			$(this).replaceWith('<div id="'+ movie_info.id +'"></div>');
			
			var flashvars = {
				file: movie_info.src,
				image: movie_info.poster,
				autostart: 'false'
			};
			var params = {
				allowfullscreen:'true',
				allowscriptaccess:'always'
			};
			var attributes = {
				id: 'flash_' + movie_info.id,
				name: 'flash_' + movie_info.id
			};
			
			// Overwrite the width and height
			movie_info.width = 480;
			movie_info.height = 360;
			
			swfobject.embedSWF(site_url + '/resources/jwplayer/player.swf', movie_info.id, movie_info.width, movie_info.height, '9.0.115', 'false', flashvars, params, attributes);
		});
	}
	
	
	$('.cancel_booking_link').fancybox({
		'centerOnScroll': true,
		'hideOnContentClick': false,
		'type': 'iframe',
		'padding': 0,
		'scrolling': 'yes',
		'width': 700,
		'height': 580
	});
});

$(window).load(function() {
	$('.nivoSlider').nivoSlider({
		effect: 'fade',
        pauseTime: 4000,
		afterLoad: function () {
			loadWebcam();
		}
	});
});

function loadWebcam () {
	if ($('#webcam_link').length == 1)
	{
		$('#webcam_link').append('<h3 style="margin-bottom: 5px; padding: 0; font-size: 15px; font-weight: bold; color: #333; text-align: center;">' + lang_txt.webcam + '</h3><img src="http://80.33.86.101:1256/axis-cgi/jpg/image.cgi?resolution=160x120&amp;'+ mktime() +'" />');
		
		$('#webcam_link').fancybox({
			'centerOnScroll': true,
			'hideOnContentClick': true,
			'type': 'iframe',
			'padding': 0,
			'scrolling': 'no',
			'width': 640,
			'height': 480
		});
		
		$('#webcam_link img').error(function () {
			$(this).parent().append('<span style="padding: 0; color: #333;">Oops webcam is not working.<br />Please check again later.</span>');
			$(this).remove();
		});
	}
}

function rtrim (str, charlist) {
    charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\\$1');
    var re = new RegExp('[' + charlist + ']+$', 'g');    return (str + '').replace(re, '');
}

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function mktime () {
    var d = new Date(),
        r = arguments,
        i = 0,
        e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear'];

    for (i = 0; i < e.length; i++) {
        if (typeof r[i] === 'undefined') {
            r[i] = d['get' + e[i]]();
            r[i] += (i === 3); // +1 to fix JS months.
        } else {
            r[i] = parseInt(r[i], 10);
            if (isNaN(r[i])) {
                return false;
            }
        }
    }

    r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0);

    d.setFullYear(r[5], r[3] - 1, r[4]);

    d.setHours(r[0], r[1], r[2]);

    return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0);
}

function isMobileUser ()
{
	if (navigator.userAgent.match(/Android/i) ||
		navigator.userAgent.match(/webOS/i) ||
		navigator.userAgent.match(/iPhone/i) ||
		navigator.userAgent.match(/iPod/i) ||
		navigator.userAgent.match(/iPad/i)
	) {
		return true;
	}
	
	return false;
}
