var player = false;
var badBrowser = false;

/** HARDCODED - NAVIGATION
 * This is an array of objects containing video hash and corresponding page title and url.
 * The title is required for the History.js / Ajaxify statepushing (but I would rather load dynamically -- dont have time)
 * The category is used for knowing which menu items to mark as selected
 * (this can be fixed later with the script above -- see commented out lines) 
 */
var navigation_map = [];

$.ajax({
	
	type: 'GET',
	url: '/js/navigation_map.json',
	dataType: 'json',
	async: false,
	success: function(data) {
		navigation_map = data;
	}
});

/** GET NAV FROM VIDEO HASH
 * Looks at all nav items until a video hash matches and returns that nav item
 * @param video_hash String of video_hash from player to compare
 * @returns Object Nav object containing category, video_hash, title, and url.
 */
function get_nav_from_video_hash(video_hash)
{
	for (var i in navigation_map) {	if (navigation_map[i].video_hash == video_hash) return navigation_map[i]; }
	return null;
}

/** GET NAV FROM URL
 * Looks at all nav items until a url matches and returns that nav item
 * @param url String of url we want to find
 * @returns Object Nav object containing category, video_hash, title, and url.
 */
function get_nav_from_url(url)
{ 
	url = url.replace(/^\//, "");
	url = url.replace(/\/$/, "");
	
	for (var i in navigation_map) { if (navigation_map[i].url == url) return navigation_map[i]; }
	return null;
}

/** IN PLAYER CLICK
 * This function is called within the player and can be customized to your liking
 * @param video_hash String of video_hash which is being loaded
 */
function in_player_click(video_hash)
{
	var nav = get_nav_from_video_hash(video_hash);
	if (nav)
	{
		if (nav.url.indexOf("about-us/blog") != -1)
		{
			window.location = "/"+nav.url;
		}
		else
		{
			url = "/"+nav.url;
			title = nav.title;
			History.pushState(null,title,url);
		}
		
	}
}

function in_player_colorbox(url)
{
	player.pause();
	$.colorbox({
		href:url,
		iframe:true,
		innerWidth:640,
		innerHeight:400,
		scrolling: false,
		slideshow: false
	});
}


/** CHANGE VIDEO
 * 
 * @param video_hash
 * @returns
 */
function change_video(video_hash)
{
	if (video_hash != null && video_hash != "")
	{
		if (player = $('#hustream-player').data('hsPlayer'))
		{
			player.navigate('video:'+video_hash);
			return true;	
		}
	}
	return false;
}

/** CHANGE SELECTED TO
 * 
 * @param nav
 * @returns
 */
function change_selected_to(nav)
{
	if (nav != null)
	{
		category = nav.category || "";
		url = nav.url || "";
		
		// remove all selected
		$("a").each(function() {
			if ($(this).parent().hasClass('selected')) $(this).parent().removeClass('selected');
		});
		
		// selected category topmenu
		$("#nav a[href='"+rootUrl+category+"']").each(function() {
			if (!$(this).parent().hasClass('selected')) $(this).parent().addClass('selected');
		});
		
		// selected footer links
		$("#footer-links a[href='"+rootUrl+url+"']").each(function() {
			if (!$(this).parent().hasClass('selected')) $(this).parent().addClass('selected');
		});
	}
}



/** DOCUMENT READY SCRIPT
 * 
 */

$(document).ready(function() {
	
	if ($("html").is(".ie6, .ie7"))
		alert('This website may not be displayed on this version of Internet Explorer.');
	
	if (navigator.userAgent.match(/Android|iPhone|iPod|webOS/i))
		alert('This website may not be displayed correctly on mobile devices');
	
	// check the browser
	if ($('html').hasClass('ie8')) badBrowser = "IE8";
	if ($('html').hasClass('ie7')) badBrowser = "IE7";
	if ($('html').hasClass('ie6')) badBrowser = "IE6";
	
	// initialize the player
	$('.hustream-player').each(function(){
		var app_path = $("input[type='hidden'].app-path", $(this)).attr('value');
		var startpoint = $("input[type='hidden'].startpoint", $(this)).attr('value');
		
		$(this).hsPlayer({ "app-path" : app_path, "startpoint" : startpoint, "splashOverride" : "anything" });
		player = $(this).data('hsPlayer');
//		console.log(player)
	});

	// Check to see if History.js is enabled for our Browser
	History = window.History;
	if ( !History.enabled ) {
		return false;
	}
	
	$ = window.jQuery;
	doc = window.document;

	// Wait for Document
	$(function(){
		
		/* Application Specific Variables */
		contentSelector = '#content';
		$content = $(contentSelector).filter(':first');
		contentNode = $content.get(0);
		
		ctaSelector = '#cta-button';
		$ctaContent = $(ctaSelector).filter(':first');
		ctaNode = $ctaContent.get(0);
		
		/* Application Generic Variables */
		$body = $(doc.body);
		rootUrl = History.getRootUrl();
		relativeUrl = doc.URL.replace(rootUrl,'');
		scrollOptions = {
			duration: 2000,
			easing:'easeInOutCubic'
		};

		// Ensure Content
		if ( $content.length === 0 ) {
			$content = $body;
		}
		
		if ( $ctaContent.length === 0) {
			$ctaContent = $body;
		}

		// Internal Helper
		$.expr[':'].internal = function(obj, index, meta, stack){
			// Prepare
			var
			$this = $(obj),
			url = $this.attr('href')||'',
			isInternalLink;

			// Check link
			isInternalLink = url.substring(0,rootUrl.length) === rootUrl || !/:\/\//.test(url);
			
			// Ignore or Keep
			return isInternalLink;
		};

		// Ajaxify Helper
		$.fn.ajaxify = function(){
			// Prepare
			var $this = $(this);
			
			$this.find('a:internal:not(.no-ajaxy)').each(function() {
				
				// check for pre-bound events
				var clickEvents = $(this).data("events");
				var href = $(this).attr('href');
				
				if (!clickEvents && href)
				{
					// is it an #anchor link?
					if (href.indexOf('#') != -1)
					{
						
						$(this).unbind("click").click(function(event){
							event.preventDefault();
							anchor = $(this).attr('href').replace(new RegExp(".*#"), "");
							$("a[name='"+anchor+"']").ScrollTo(scrollOptions);
						});
					}
					else if (href.indexOf('mailto:') != -1)
					{
						// do nothing for mail links
					}
					else
					{
						$(this).unbind("click").click(function(event){

							// Prepare
							var
							$this = $(this),
							url = $this.attr('href'),
							title = $this.attr('title')||null;

							// Continue as normal for cmd clicks etc
							if ( event.which == 2 || event.metaKey ) { return true; }
							
							// Ajaxify this link
							History.pushState(null,title,url);
							
							// change the video separate from the statepushing
							// attempt to get nav (not done in the if statement because of IE8 errors)
							relativeUrl = url.replace(rootUrl,'');
							var nav = get_nav_from_url(relativeUrl);
							if (nav)
							{
								if (player.initialized == true)
								{
									change_video(nav.video_hash);
								}
								else
								{
									var leavingVideo = player.settings.videoRef;
									var newVideo = nav.video_hash;
									
									player.settings.splashScreen = player.settings.splashScreen.replace(leavingVideo, newVideo);
									player.settings.videoFile = player.settings.videoFile.replace(leavingVideo, newVideo);
									player.settings.videoRef = player.settings.videoRef.replace(leavingVideo, newVideo);
									player.settings.startpoint = player.settings.startpoint.replace(leavingVideo, newVideo);
									
									var splash = $(".hustream-player img.splash");
									if (splash)
									{
										$(splash).fadeOut(500, function() {
											$(this).attr('src', player.settings.splashScreen);
											$(this).fadeIn(500);
										});
									}
								}
								
								change_selected_to(nav);
							}
							
							// dont act like a normal anchor
							event.preventDefault();
							return false;
						});
					}
				}
				
			});
			
			// Chain
			return $this;
		};

		// Ajaxify our Internal Links
		$body.ajaxify();

		// Hook into State Changes
		$(window).bind('statechange',function(){
			
			load_ajax_content();
	
		}); // end onStateChange
		
	}); // end onDomLoad
	
});

function load_ajax_content()
{
	// Check to see if History.js is enabled for our Browser
	History = window.History;
	if ( !History.enabled ) {
		return false;
	}

	// Prepare our Variables
	$ = window.jQuery;
	var doc = window.document;
	
	// Prepare Variables
	State = History.getState();
	url = State.url;
	relativeUrl = url.replace(rootUrl,'');
	
	// Set Loading
	$body.addClass('loading');

	// Start Fade Out
	// Animating to opacity to 0 still keeps the element's height intact
	// Which prevents that annoying pop bang issue when loading in new content
	if (badBrowser == false)
	{
		$content.animate({opacity:0},100);
	}
	else
	{
		$content.hide();
	}
	
	// HTML Helper
	var documentHtml = function(html){
		
		// Prepare
		var result = String(html)
		.replace(/<\!DOCTYPE[^>]*>/i, '')
		.replace(/<(html|head|body|title|meta|script)/gi,'<div class="document-$1"')
		.replace(/<\/(html|head|body|title|meta|script)/gi,'</div')
		;
		
		// Return
		return result;
	};
	
	fetchUrl = rootUrl+"/"+relativeUrl;

	// Ajax Request the Traditional Page
	$.ajax({
		url: fetchUrl,
		success: function(data, textStatus, jqXHR){
			
			// Prepare
			var $domContent = $(documentHtml(data));
			
			// Get the content we want
			var ctaBtnHtml = $domContent.find('#cta-button').html();
			var contentHtml = $domContent.find('#content').html();
			var $domScripts = $domContent.find('.document-script').detach();
			
			if ( !contentHtml ) {
				doc.location.href = url;
				return false;
			}
			
			// Update the content
			$content.stop(true,true);
			$ctaContent.stop(true,true);
			
			if (badBrowser == false)
			{
				$content.html(contentHtml).ajaxify().show().animate({opacity:1},500).hide().show();
				$ctaContent.html(ctaBtnHtml).ajaxify().show();
			}
			else
			{
				$content.html(contentHtml).show().ajaxify();
				$ctaContent.html(ctaBtnHtml).ajaxify().show();
			}

			// Update the title
			document.title = $domContent.find('.document-title:first').text();
			try {
				document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ');
			}
			catch ( Exception ) { }
			
			// Add the scripts
			$domScripts.each(function(){
				var $script = $(this);
				
				if ($script.attr('src') != null)
				{
					var script = $script.attr('src');
//					alert('script src='+script);
					$.getScript(script);
				}
				else
				{
//					alert('non src script');
					scriptText = $script.html(), scriptNode = doc.createElement('script');
					scriptNode.appendChild(doc.createTextNode(scriptText));
					contentNode.appendChild(scriptNode);
				}

			});

			// Complete the change
//			if ( $body.ScrollTo||false ) { $body.ScrollTo(scrollOptions); } /* http://balupton.com/projects/jquery-scrollto */
			$body.removeClass('loading');

			// Inform Google Analytics of the change
			if ( typeof window.pageTracker !== 'undefined' ) {
//				console.log('window.pageTracker._trackPageview('+relativeUrl+')');
				window.pageTracker._trackPageview(relativeUrl);
			}
		},
		error: function(jqXHR, textStatus, errorThrown){
			doc.location.href = url;
			return false;
		},
		complete: function(jqXHR, textStatus){
		}
	}); // end ajax
}


