$(function() {
 
	$.get("/includes/xml/home-live.xml", function (data) {
		
		data = $(data);
		
		var $nav = $('#nav');
		var $navul = $nav.children('ul');
		var $hover = $('#nav-play-bg');
		var $cover = $('.cover-image');
		var $player = $('#videoplayer');
		var $watchVideo = $('#watch-video-link');

		var lnk = data.find('tiles').children('tile'),
			nav = data.find('navs').children('nav');
			
		$nav.hover(function(){},
		function(){
			$hover.find('#watch-video-link').unbind();
			$hover.find('#page-link').unbind().find('#page-button').unbind();
			$navul.find('.nav_hover').removeClass('selected');
			$hover.hide();
		});

		
		// create the nav
		$.each( nav, function ( i, v ) {
			
			var $v = $(v).text();


			$('<a/>')
			.attr({
				'class' : 'nav_hover'
			})
			.text($v)
			.hover(function(){
			
				$hover.find('#watch-video-link').unbind();
				$hover.find('#page-link').unbind().find('#page-button').unbind();
				$navul.find('.nav_hover').removeClass('selected');
				
				$(this).addClass('selected');

                $hover.css({ top : 45, left : $(this).position().left - 4, right : 'auto' });

				// Choose which video to play based on the screen width
				var video_url_key = (window.screen.width >= 1024) ? 'ipad_video_url' : 'iphone_video_url',
					video_url = lnk.eq(i).find(video_url_key).text();

				// If there is no video for this device type, check if we can get different (ill-fitting) video
				if (!video_url) {
					video_url_key = (video_url_key == "iphone_video_url") ? 'ipad_video_url' : 'iphone_video_url',
					video_url = lnk.eq(i).find(video_url_key).text();
				}

				// If there is no video for this tab, hide the watch video link
				if (!video_url) {
					$watchVideo.hide();
				} else {
					$watchVideo.show();
				}
			    
				// Play the video when the watch video link is clicked
				$hover.find('#watch-video-link').bind('click', function(e){
					e.preventDefault();
					$cover.fadeOut();

					$player.attr("src", video_url);

					$player[0].load();
					$player[0].play();
				});

				$hover.find('#page-link').attr({ href : lnk.eq(i).find('nav_url').text() }).find('#page-button').html('Go to ' + $(v).text() + " Page");
				$cover.attr({src:lnk.eq(i).find('image_url').text()});

				$hover.show();
				
			}, function (){}).appendTo($('<li/>').appendTo('#nav-links'));
			
		});
		
	});		
	
});

