var minBrowserWidth = 960;
var minBrowserHeight = 768;
var backgroundImage;
var rotateBackground = true;
var backgroundTimer;
var animateWidth;
var animateHeight;
var currentBackground = 1;
var isOpen = true;
var cache = [];
var isInitialized = false;
var videoHTML = '';
var isiPad = navigator.userAgent.match(/iPad/i) != null;
var isiPod = navigator.userAgent.match(/iPod/i) != null;
var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1;
var player;

function resizeBackground() {
	browserWidth = $(document).width();
	browserHeight = $(document).height();
	var ratio = (backgroundImage.attr('height') / backgroundImage.attr('width')).toFixed(2);
	if (browserWidth < minBrowserWidth) {
		browserWidth = minBrowserWidth;
	}

	if (browserHeight < minBrowserHeight) {
		browserHeight = minBrowserHeight;
	}
	
	if ((browserHeight / browserWidth) > ratio) {
		backgroundImage.width(browserHeight / ratio);
	    backgroundImage.height(browserHeight);
	}
	else {
		backgroundImage.width(browserWidth);
	    backgroundImage.height(browserWidth * ratio);
	}
	
	backgroundImage.css('top', ((browserHeight - backgroundImage.height()) / 2));
	backgroundImage.css('left', ((browserWidth - backgroundImage.width()) / 2));
	
	backgroundImage.bind("contextmenu",function(){
		return false;
	});
	backgroundImage.bind("mousedown",function(){
		return false;
	});
}

function changeBackground(that) {
	$('#caption').fadeOut(300);
	$('#rendering').fadeOut(300);
	that.css('margin-top', '0px');
	if ($('#map-wrapper').length) {
		$('#map-wrapper').fadeOut(600);
		$('#gradient-bottom').fadeIn(300);
		$('#gradient').removeClass('mapped');
	}
	if (that.attr('class') != 'video') {
		$('#video').fadeOut(300);
	}
	else {
		$('#video').fadeIn(300);
	}
	backgroundImage.fadeOut(300, function(){
		var cacheImage = document.createElement('img');
		cacheImage.src = backgroundImage.attr('src');
		cache.push(cacheImage);
		
		if (that.attr('class') != 'google-map') {
			backgroundImage.load(function () {
				$(this).fadeIn(300);
				$('#caption p').html(that.attr('title'));
				$('#caption').fadeIn(300);
				if (that.attr('src') == '/graphics/residences/westbeach/thumbnails/01.jpg') {
					$('#rendering').fadeIn(300);
				}
				if (that.attr('src') == '/graphics/ritz-carlton-reserve/ambassadors/jeanmichelcousteau/thumbnails/02.jpg') {
					$('#video').height(0);
				}else{
					$('#video').height("100%");
				}
				if (rotateBackground == true) {
					clearTimeout(backgroundTimer);
					backgroundTimer = setTimeout('backgroundSlideshow()', 7500);
				}
			}).attr('src', that.attr('src').replace('thumbnails/', ''));
		}
		else {
			backgroundImage.attr('src', '');
			if (isInitialized == false) {
				isInitialized = true;
				initialize();
			}
			$('#gradient-bottom').fadeOut(300);
			$('#gradient').addClass('mapped');
			$('#map-wrapper').fadeIn(300);
			if (rotateBackground == true) {
				clearTimeout(backgroundTimer);
				backgroundTimer = setTimeout('backgroundSlideshow()', 7500);
			}
		}
	});
	console.log(currentBackground);
}

function backgroundSlideshow() {
	currentBackground = currentBackground + 1;
	if ($('#thumbnail_' + currentBackground).length == false) {
		currentBackground = 1;
	}
	highlightThumbnail();
	changeBackground($('#thumbnail_' + currentBackground));
}

function highlightThumbnail() {
	var currentThumbnail = 1;
	while ($('#thumbnail_' + currentThumbnail).length == true) {
		if (currentThumbnail == currentBackground) {
			$('#thumbnail_' + currentThumbnail).css('margin-top', '0px');
		}
		else {
			$('#thumbnail_' + currentThumbnail).css('margin-top', '-50px');
		}
		currentThumbnail++;
	}
}

function onPlayerStateChange(evt) {
	if (evt.data == YT.PlayerState.ENDED) {
		$('#video_container').remove();
		if (isOpen == false) {
				$('#open-hide').trigger('click');
			}
		$('#gradient').css('height', '428');
		$('#header h1 a').fadeIn(300);
		$('#footer').fadeIn(300);
		$('#pattern').fadeIn(300);
		$('#video').fadeIn(300);
	}
}

$(window).load(function () {
	$(window).bind("unload", function() {
		// Force reload on back button
	});
	
	if (!((isiPad) || (isiPod) || (isiPhone) || (isAndroid))) {
		var tag = document.createElement('script');
		tag.src = "http://www.youtube.com/player_api";
		var firstScriptTag = document.getElementsByTagName('script')[0];
		firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
	}
	
	backgroundImage = $('#background img');
	backgroundImage.fadeIn(300);

	$(window).resize(function(){
		resizeBackground();
	});
	resizeBackground();

	$('#gallery').css('top', $('#copy').outerHeight());
	$('#gallery').fadeIn(200);

	$('#open-hide').hover(function(event) {
		if (isOpen == true) {
			$(this).css('background-position', '-37px -11px');
		}
		else {
			$(this).css('background-position', '0 -11px');
		}
	}, function(event) {
		if (isOpen == true) {
			$(this).css('background-position', '-37px 0');
		}
		else {
			$(this).css('background-position', '0 0');
		}
	});

	$('#map').hover(function(event) {
		$(this).css('background-position', '0 -12px');
	}, function(event) {
		$(this).css('background-position', '0 0');
	});

	$('#map').click(function(event) {
		$.colorbox({ width:800, height:600,scrolling: false, transition: "fade", opacity: 0, href: '/map/', title: 'Dorado Beach', close: '<div id="map-close"></div>' });
	});

	$('#video').click(function(event) {
		if ((isiPad) || (isiPod) || (isiPhone) || (isAndroid)) {
			location.href = 'http://www.youtube.com/watch?v=' + $('#video').attr('class');
		}
		else {
			rotateBackground = false;
			clearTimeout(backgroundTimer);
			$(this).after($(this).clone().attr('id', 'video_container'));
			$('#video').fadeOut(0);
			$('#video_container').css('z-index', '1');
			$('#video_container').css('display', 'block');
			player = new YT.Player('video_container', {
				height: '100%',
				width: '100%',
				videoId: $('#video').attr('class'),
				playerVars: {
					'autoplay': 1,
					'disablekb': 1,
					'enablejsapi': 1,
					'modestbranding': 1,
					'rel': 0,
					'showinfo': 0,
					'showsearch': 0,
					'theme': 'light'
				},
				events: {
					'onStateChange': onPlayerStateChange
				}
			});
			
			if (isOpen == true) {
				$('#open-hide').trigger('click');
			}
			$('#footer').fadeOut(300);
			$('#pattern').fadeOut(300);
			$('#header h1 a').fadeOut(300);
			$('#gradient').css('height', '195');
		}
	});

	$('#open-hide').click(function(event) {
		$('#copy').stop(false, true);
		$('#copy').children().stop(false, true);
		animateHeight = $(this).siblings('#copy').height();
		if (isOpen == true) {
			animateWidth = $(this).siblings('#copy').width();
			var newWidth = 58 - ($(this).siblings('#copy').outerWidth() - animateWidth);
			isOpen = false;
			$('#open-hide').css('background-position', '0 -11px');
			$('#copy').css('height', animateHeight + 'px');
			$('#copy').children().fadeOut(0);
			$('#gallery').fadeOut(0);
			$('#copy').animate({
				width: newWidth + 'px'
			}, 400);
		}
		else {
			isOpen = true;
			$('#open-hide').css('background-position', '-37px -11px');
			$('#copy').animate({
				width: animateWidth + 'px'
			}, 400, function() {
				$(this).children().fadeIn(200);
				$('#gallery').fadeIn(200);
				$('#copy').css('height', 'auto');
			});
		}
	});
	
	$('#gallery img').hover(function(event) {
		$(this).css('margin-top', '0px');
	}, function(event) {
		highlightThumbnail();
	});
	
	$('#gallery img').click(function(event) {
		event.preventDefault();
		if (backgroundImage.attr('src') != $(this).attr('src').replace('thumbnails/', '')) {
			rotateBackground = false;
			clearTimeout(backgroundTimer);
			currentBackground = $(this).attr('id').replace('thumbnail_', '');
			highlightThumbnail();
			changeBackground($(this));
		}
	});
	$('a').click(function(event) {
		if (($(this).attr('target') != "_blank") && ($(this).attr('class') != "email_address")) {
			event.preventDefault();
			backgroundImage.fadeOut(300, function() {
				location.href = $(event.target).attr('href');
			});
		}
	});
	
	var ineligibleStates = ['CT', 'HI', 'ID', 'IL', 'NY', 'NJ', 'OR'];
	var PVineligibleStates = ['AZ', 'CA', 'ID', 'IA', 'KY', 'MS', 'NE', 'NV', 'NH', 'OH', 'OR', 'RI', 'WI'];
	var DBEineligibleStates = ['AZ', 'CA', 'CT', 'ID', 'IA', 'KY', 'MN', 'NE', 'NV', 'NH', 'NY', 'OH', 'OR', 'RI'];
	var RITZineligibleStates = ['AZ', 'CA', 'CT', 'ID', 'IA', 'KY', 'NE', 'NV', 'NH', 'OH', 'OR', 'RI', 'WI'];
	
	$('#states').change(function() {
		if ($('#which_residence').val() == '') {
			alert('Please select the residence that interests you prior to selecting your state.');
			$(this).val('');
		}
		else {
			if ($('#which_residence').val() == 'West Beach, A Ritz-Carlton Reserve Residence') {
				ineligibleStates = RITZineligibleStates;
			}
			else if ($('#which_residence').val() == 'Plantation Resort Residences') {
				ineligibleStates = PVineligibleStates;
			}
			else if ($('#which_residence').val() == 'Dorado Beach East Estate Homes') {
				ineligibleStates = DBEineligibleStates;
			}
			for (var key in ineligibleStates) {
				if ($(this).val() === ineligibleStates[key]) {
					alert('At this time, due to state regulations, we are unable to provide you with additional information regarding residential opportunities.');
					$(this).val('');
				}
			}
		}
	});

	$('#which_residence').change(function() {
		$('#states').val('');
	});
	
	if ($('#thumbnail_2').length) {
		backgroundTimer = setTimeout('backgroundSlideshow()', 7500);
	}
	
	$('#scrollable').tinyscrollbar();
	
	highlightThumbnail();
	
	if ($('#map-wrapper').length) {
		if (isInitialized == false) {
			isInitialized = true;
			initialize();
		}	
	}
});

