$(document).ready(function(){
	/*
	 * BEGIN SETUP
	 */
	// prep the nutrition popup by moving it off screen
	//$("#fitmeetings-section .nutLightbox").css("left", "-500%");
	//$("#fitmeetings-section .participatingLightbox").css("left", "-500%");
	
	//Check for hash value in URL
	nutritionHash = false;
	
	window.onload = function() {
		if(location.hash.length >= 2){
			var pos = $(window).scrollTop(); // get scroll position
			var section = unescape(location.hash.substring(1));
			console.log(section);
			showSection(section);
			setTimeout("self.scrollTo(0,0);", 50);
			$(window).scrollTop(pos); // set scroll position back
		}
	}
	
    // A place to store information without polluting the global name space.
    window.fitness = {
		assetPath: 'Media/'
	};
    
	// Prelaod essential images.
	preloadImages(
		'about-background.jpg',
		'training-background.jpg',
		'participating-background.jpg',
		'tips-background.jpg',
		'button-bookNow.gif',
		'tips-nav-leftArrow.png',
		'tips-nav-leftArrow.gif',
		'tips-nav-rightArrow.png',
		'tips-nav-rightArrow.gif',
		'training-download-background.gif',
		'centers-listing-background.gif',
		'tips-tip-background.gif',
		'meetings-background.jpg',
		'meetings-inner-background.gif'
	);
	
	// Set #home-section as the active section.
    //$('#subnav-home').addClass('active');
	$('#home-section').show();
	setupSection('home');
	
	/* END SETUP ****************************************************/
	
	
	
	/*
	 * BEGIN FLASH
	 */
	
	// Homepage slideshow
	window.fitness.flashvars = {};
	window.fitness.flashvars.home = {
		xmlPath: window.fitness.assetPath + 'SheratonFitness.xml'
	};
	
	window.fitness.params = {};
	window.fitness.params.home = {
		wmode: 'transparent'
	};
	
	swfobject.embedSWF(
		window.fitness.assetPath + 'sheratonFitnessFlash.swf',
		'flash',
		'832',
		'380',
		'9.0.124',
		window.fitness.assetPath + 'expressInstall.swf',
		window.fitness.flashvars.home,
		window.fitness.params.home
	);
	// END slideshow
	
	// Overview video
	window.fitness.flashvars.video = {};
	window.fitness.params.video = {
		scale: "noscale",
		wmode: "transparent",
		allowscriptaccess: "always"
	};
	
	swfobject.embedSWF(
		window.fitness.assetPath + 'videoPlayer.swf',
		'video',
		'533',
		'307',
		'9.0.124',
		window.fitness.assetPath + 'expressInstall.swf',
		window.fitness.flashvars.video,
		window.fitness.params.video
	);
	// END video
	
	/* END FLASH ****************************************************/
    
	
	
	
	/*
	 * BEGIN AJAX
	 */
    
	// Get the data for the Life Tips section.
    $.get('Media/tips.html', {}, function(data, textStatus){
        if (textStatus == 'success') {
            fitness.tipData = $(data).filter('div');
			
			// Now that we've loaded the tips, we can put a random one in the bottom box $('#lifeTips p')
			var maxChars = 100;
			var $tips = $('.tip', fitness.tipData);
			var randomIndex = Math.floor((Math.random() * $tips.length));
			var $context = $tips.filter(':eq(' + randomIndex + ')');
			var tipText = $.trim($('p', $context).text());
			
			if (tipText.length > maxChars) {
				var tipTextArray = tipText.split(' ');
				
				// Clear out the tipText var so we can build it back up using the array.
				tipText = '';
				for (var i = 0; i < tipTextArray.length; i++) {
					if (tipText.length + tipTextArray[i].length + 1 < maxChars) {
						tipText += tipTextArray[i] + ' ';
					} else {
						break;
					}
				}
				tipText = $.trim(tipText) + '...';
			}
			// THIS IS TURNED OFF BECAUSE WE DON'T WANT TO DYNAMICALLY REPLACE THE COPY IN THE BOTTOM BOX...
			 //$('#lifeTips p').empty().text(tipText);
				
        } else {
			
            if (confirm('There was an error loading some required data.\n\nWould you like to reload the page to try again?\n\nNOTE: The page will not function properly until the data has been loaded.')) {
                window.location = window.location;
            }
        }
    }, 'html'); 
	
	// Get the data for the Fitness Centers section
    $.get('Media/hotels.html', {}, function(data, textStatus){
        if (textStatus == 'success') {
			fitness.hotelData = $(data).filter('div');
			
        } else {
            if (confirm('There was an error loading some required data.\n\nWould you like to reload the page to try again?\n\nNOTE: The page will not function properly until the data has been loaded.')) {
                window.location = window.location;
            }
        }
    }, 'html');
	
	/* END AJAX ****************************************************/
	
	
	
	/*
	 * BEGIN EVENT HANDLING
	 */
    
    // Subnav click handling to change sections.
    $('#subnav li a').click(function(){
        var showArray = $(this).parent().attr('id').split('-');
		var pos = $(window).scrollTop(); // get scroll position
        window.location.hash = showArray[1];
		$(window).scrollTop(pos); // set scroll position back
		showSection(showArray[1]);
		jsOnCollapsed();
		//$('#fitmeetings-section').hide();
    });
    
    $('#nutritionLearnMoreLink').click(function(){
    	var pos = $(window).scrollTop(); // get scroll position
		showSection('home');
		//window.location.hash = 'nutrition';
		$(window).scrollTop(pos); // set scroll position back
		showNutrition();
    });
	
	$('#aboutLearnMoreLink').click(function(){
		var pos = $(window).scrollTop(); // get scroll position
		showSection('about');
		 window.location.hash = 'about';
		 $(window).scrollTop(pos); // set scroll position back
	});
	
	$('#workoutsLearnMoreLink').click(function(){
		var pos = $(window).scrollTop(); // get scroll position
		showSection('training');
		 window.location.hash = 'training';
		 $(window).scrollTop(pos); // set scroll position back
	});
	
	$('#tipsLearnMoreLink').click(function(){
		var pos = $(window).scrollTop(); // get scroll position
		showSection('tips');
		 window.location.hash = 'tips';
		 $(window).scrollTop(pos); // set scroll position back
	});
	
	$('#sheratonFITmeetingsLink').click(function(){
		resetMeetings();
        var meetingId = $(this).parent().attr('id');
		var pos = $(window).scrollTop(); // get scroll position
        window.location.hash = meetingId;
		$(window).scrollTop(pos); // set scroll position back
		showSection(meetingId);
		$('#subnav-fitmeetings').addClass('active');
    });
	
	$('#openWorkoutsLink').click(function(){
		var pos = $(window).scrollTop(); // get scroll position
		$(window).scrollTop(pos); // set scroll position back
		showSection('training');
		window.location.hash = 'training';
		$('#fitmeetings-section').hide();
		
		$('#subnav-training').addClass('active');
	});
	
	$('#fitnessCenters').click(function(){
		var pos = $(window).scrollTop(); // get scroll position
		$(window).scrollTop(pos); // set scroll position back
		showSection('centers');
		window.location.hash = 'centers';
		$('#fitmeetings-section').hide();
		
		$('#subnav-centers').addClass('active');
	});
	
    
	$('#openParticipating').click(function(){
		var pos = $(window).scrollTop(); // get scroll position
		$(window).scrollTop(pos); // set scroll position back
		showSection('fitmeetingshotels');
		window.location.hash = 'fitmeetingshotels';
		// $('#fitmeetings-section').hide();
		$('#subnav-fitmeetings').addClass('active');
	});
	
    // Nav hover handler. Done in JS instead of CSS for IE compatability.
    $('#nav li a img').hover(
		function(event){
	        $(this).css({
	            top: '-12px'
	        });
	    }, function(event){
	        $(this).css({
	            top: ''
        });
    });
    
    // Subnav hover handler. Done in JS instead of CSS for IE compatability.
    $('#subnav li a img').hover(
		function(){
			if (!$(this).parent().parent().hasClass('active')) {
				$(this).stop().animate({ top: '-74' }, 100);
			}
	    },
		function(){
			if (!$(this).parent().parent().hasClass('active')) {
				$(this).stop().animate({ top: '0' }, 100);
			}
    	}
	);
    
    // Tips nav handler. Done in JS instead of CSS for IE compatablility.
    $('#tipNav li a img').hover(function(){
        $(this).css({
            top: '-12px'
        });
    }, function(){
        $(this).css({
            top: ''
        });
    });
	
	// Other Starwood Brands menu
	$('#otherLink').click(function(){
		$('#otherBrands').css({
			top: (-1 * $('#otherBrands').height() * 0.75) + 'px', //Math.floor(offset.top - ($('#otherBrands').height() * 0.75)) + 'px',
			left: 0 //offset.left + 'px'
		}).fadeIn();
	});
	
	$('#otherBrands').hover(
		function(){
			$(this).fadeIn();
		},
		function(){
			$(this).fadeOut();
		}
	);
	
	$('#brandPopupLink').click(function(event){
		window.open(
			'http://www.starwoodhotels.com/sheraton/common/components/content/global_footer_brand_popup.html',
			'POPUP',
			'width=560, height=710, status=0, toolbar=0, location=0, menubar=0, directories=0, resizeable=0, scrollbars=0'
		);
	});
	
	$('#watchVideoLink').click(function(){
		$('#videoOverlay').fadeTo('fast', 0.5, function(){
			$('#videoWrapper').css({
				left: '10px',
				top: '35px'
			});
			expandVideo();
			playVideo();
		});
	});
	
	$('#videoOverlay').click(function(){
		collapseVideo();
	});
	
	// OPEN & CLOSE the "sample menu" popup
	$('#openMenuLink').click(function(){
		$(".nutLightbox").css("left", "0px");
	});
	
	$('.nutLightbox a').click(function(){
		$("#fitmeetings-section .nutLightbox").css("left", "-500%");
	});
	
	// OPEN & CLOSE the "participating hotels" popup
	$('#openParticipating').click(function(){
		$("#fitmeetings-section .participatingLightbox").css("left", "0px");
	});
	
	$('.participatingLightbox a').click(function(){
		$("#fitmeetings-section .participatingLightbox").css("left", "-500%");
	});
	/* END EVENT HANDLING ****************************************************/
    
}); // END $(document).ready();


$(window).load(function(){
	theSWF = document.getElementById('video');
	mainFlash = document.getElementById('flash');
}); // END $(window).load()


/*
 * BEGIN FUNCTIONS
 */

// External interface functions for flash.
function collapseVideo() {
	theSWF.asCollapse();
}

function expandVideo() {
	theSWF.asExpand();
}

function playVideo() {
	var theVideo = 'overview.flv';
	theSWF.asPlay(theVideo);
}

function showNutrition(){
	mainFlash.asNutrition();
}

function jsOnCollapsed() {
	$('#videoWrapper').css({
		left: '',
		top: ''
	});
	
	$('#videoOverlay').fadeTo('fast', 'hide');
}
// END external interface

function resetMeetings() {
	$('#fitmeetings-section #intro').show(1, function () {
		$('.ctaMindset').removeClass('ctaMindsetCurrent');
		$('.ctaNutrition').removeClass('ctaNutritionCurrent');
		$('.ctaMovement').removeClass('ctaMovementCurrent');
		$('.ctaRecovery').removeClass('ctaRecoveryCurrent');
		$("#fitmeetings-section .nutLightbox").css("left", "-500%");
		$("#fitmeetings-section .participatingLightbox").css("left", "-500%");
		$('#fitmeetings-section #mindset').hide();
		$('#fitmeetings-section #nutrition').hide();
		$('#fitmeetings-section #movement').hide();
		$('#fitmeetings-section #recovery').hide();
    });
}

function ifMeetings(){
	$('#subnav-fitmeetings').addClass('active');
}
function show_fitmeetingshotels(){
	$('#subnav-fitmeetings').addClass('active');
	$('#fitmeetings-section').show(1, function(){
		$("#fitmeetings-section .participatingLightbox").css("left", "0px");
	});
	
	$('#fitmeetings-section #intro').show(1, function () {
		$('.ctaMindset').removeClass('ctaMindsetCurrent');
		$('.ctaNutrition').removeClass('ctaNutritionCurrent');
		$('.ctaMovement').removeClass('ctaMovementCurrent');
		$('.ctaRecovery').removeClass('ctaRecoveryCurrent');
		$("#fitmeetings-section .nutLightbox").css("left", "-500%");
		$("#fitmeetings-section .participatingLightbox").css("left", "-500%");
		$('#fitmeetings-section #mindset').hide();
		$('#fitmeetings-section #nutrition').hide();
		$('#fitmeetings-section #movement').hide();
		$('#fitmeetings-section #recovery').hide();
    });
}
/*
 * showSection(section)
 * 		@section = id of the section to show, no #
 * 
 * Hides the currently visible section, shows the requested section, and updates the menu state
 */
function showSection(section) {
	//var hideArray = $('#subnav li.active').attr('id').split('-');
	//var activeSectionId = $('#content div[style="display: block;"]').attr('id');
	// If the video player is open, close it
	if ($('#videoOverlay').is(':visible')) {
		collapseVideo();
		$('#videoOverlay').fadeTo('0', 'hide');
	}
	
	//$('#home-section').hide();
	$('#about-section').hide();
	$('#training-section').hide();
	$('#centers-section').hide();
	$('#tips-section').hide();
	$('#fitmeetings-section').hide();
	
	
	
	// Hide the currently active section.    
	//$('#' + activeSectionId).hide();
	//$('#' + hideArray[1]).hide();
	
	$('#subnav li.active')
		.find('img')
		.animate({ top: '0' }, 100, function(){
			$(this).css({ top: '' });
		}).end().removeClass('active');
	
	// Show the requested section.
	$('#' + section + '-section').show();
	$('#subnav-' + section).addClass('active');
		
	// Call the post show section helper.
	setupSection(section);
} // END showSection

/*
 * setupSection(section)
 * 		@section = id of the section to be setup
 * 
 * Performs any pre-display setup needed for the specified section.
 */
function setupSection(section) {
	switch(section) {
		case 'tips':
			tips.init();
			break;
			
		case 'centers':
			hotels.init();
			break;
		case 'fitmeetings':
			ifMeetings();
			resetMeetings();
			break;
		case 'fitmeetingshotels':
			show_fitmeetingshotels();
		case 'home':
			
			break;
			
		case 'about':
		case 'training':
		
		default:
			// No setup needed.
			break;
	}
	
} // END setupSection()

/*
 * preloadImages()
 * 
 * Preloads images specified as arguments at call time
 */
function preloadImages() {
	window.fitness.imageCache = [];
	
	// Iterate over the arguments array creating an image element for each item and pushing it
	// onto the imageCache array.
	for (var i = 0; i < arguments.length; i++) {
		var cacheImage = new Image();
		cacheImage.src = window.fitness.assetPath + arguments[i];
		window.fitness.imageCache.push(cacheImage);
	}
	
} // END preloadImages()

/* END FUNCTIONS ****************************************************/
 
