/**
 * Flash Navigation
 * By Weston Ruter
 * Copyright 2010. Shepherd Interactive, LLC.  All Rights Reserved.
 * $Id: flash-navigation.js 662 2010-03-23 19:48:39Z weston $
 */

(function($, undefined){
	
//var updateLocationStatePending = 0;

var flashNav = window.FlashNavigation = {
	debug:false,
	//parentNodeID:'flash-navigation-container',
	//htmlNavigationID:'navigation',
	replaceElemIdStr:'flashNav',
	object:null,
	swf:null,
	xml:null,
	enabled: true,
	initialized:false,
	object:null,
	stateKey:'flashNav',
	uriFilter:null,
	
	init:function(){
		try {
			if(!window.AjaxLoading)
				throw Error("FlashNavigation dependent on AjaxLoading");
			
			//Default Flash enabled?
			if(!/flashNav=/.test(document.cookie))
				document.cookie = flashNav.stateKey+"=" + (flashNav.enabled && window.swfobject && swfobject.hasFlashPlayerVersion('8.0.0') ? 1 : 0) + "; path=/";
			
			if(flashNav.initialized)
				return;
			flashNav.initialized = true;
			
			if(flashNav.isEnabled())
				flashNav.enable();
			else
				flashNav.disable();
			
		}
		catch(e){
			flashNav.disable();
			throw e;
		}
	},
	
	isEnabled:function(){
		if(!flashNav.enabled || document.cookie.indexOf(flashNav.stateKey+'=0') != -1)
			return false;
		return Boolean(window.swfobject && swfobject.hasFlashPlayerVersion('8.0.0'));
	},
	
	updateLocationState:function(uri, keepTrying){
		if(!flashNav.isEnabled())
			return;
		
		//Only allow the keep trying to happen once at a time
		//if(updateLocationStatePending > 0 && keepTrying){
		//	alert(uri + ' -- ' + updateLocationStatePending)
		//	return;
		//}
		//updateLocationStatePending++;
		
		if(flashNav.uriFilter)
			uri = flashNav.uriFilter(uri);
		
		var checkCount = 0;
		(function(){
			if(!(flashNav.object && flashNav.object.updateLocationState)){
				checkCount++;
				if(keepTrying){
					if(checkCount > 1000){ //would be ten seconds
						if(flashNav.debug){
							console.error('flashNav.object.updateLocationState never available');
						}
						//updateLocationStatePending--;
					}
					else {
						setTimeout(arguments.callee, 10);
					}
				}
			}
			else {
				//updateLocationStatePending--;
				flashNav.object.updateLocationState(uri);
				if(flashNav.debug && checkCount > 0){
					console.warn("It took " + (checkCount*10) + "ms for the swf.updateLocationState function to become available.");
				}
			}
		})();
	},
	
	enable:function(){
		if(flashNav.object)
			return true;
		
		if(/Firefox\/[12]\./.test(navigator.userAgent) || !window.swfobject || !swfobject.hasFlashPlayerVersion('8.0.0')/* || /Firefox\/[12]\./.test(navigator.userAgent)*/){
			flashNav.disable();
			return false;
		}
		document.cookie = flashNav.stateKey+"=1; path=/";
		flashNav.enabled = true;
		
		//var div = document.createElement('div');
		//div.id = flashNav.swfNavigationID;
		//$(document.documentElement).addClass('is-flash-navigation');
		//$('#' + flashNav.parentNodeID).append(div);
		
		flashNav.placeholder = document.getElementById(flashNav.replaceElemIdStr);
		
		var uri = AjaxLoading.getURI();
		if(flashNav.uriFilter)
			uri = flashNav.uriFilter(uri);
		
		swfobject.embedSWF(
			flashNav.swf,
			flashNav.replaceElemIdStr,
			"100%",
			350,
			'8.0.0',
			null,
			{
				siteNavigationXML:flashNav.xml + '?' + flashNavXMLModifiedTime,
				initialURI:uri
			},
			{wmode:'transparent'},
			{},
			function(e){
				if(!e.success){
					flashNav.disable();
				}
				else {
					try {
						flashNav.object = e.ref;
						var uri = AjaxLoading.getURI();
						
						//TODO: Remove this once the SWF supports initialURI
						if(uri != '/')
							flashNav.updateLocationState(uri, true);
						
						//var uri = '/' + window.location.hash.substr(1);
						//uri = uri.replace(/\/\d\d\d\d.*/, '/'); //don't pass post URIs to the Flash
						
						//AIMEE TODO: the updateLocationState function must return false if the XML hasn't been loaded yet!
						//TODO: Must be resizable horizontally (and allow for full screen resize)
						//if(!(flashNav && flashNav.updateLocationState && flashNav.updateLocationState(uri))){ //
							//window.setTimeout(arguments.callee, 10);
						//}
						//DELETE THIS ELSE WHEN updateLocationState UPDATED TO RETURN TRUE/FALSE
						//ALSO TODO: Stop trying to get style.css
						//Add SWFs to XML
						//else {
						//	console.info(uri)
						//	console.info(flashNav.updateLocationState(uri))
						//}
					
						flashNav.enabled = true;
						if(flashNav.onenable)
							setTimeout(flashNav.onenable, 0);
					}
					catch(e){
						if(flashNav.debug)
							throw e;
						else
							flashNav.disable();
					}
				}
			}
		);
		
		//When navigating back and forward in history, make sure Flash state restored
		if(window.addEventListener){
			try {
				window.addEventListener('pageshow', onpageshow, false);
			}
			catch(e){}
		}
		return true;
	},
	disable:function(){
		document.cookie = flashNav.stateKey+"=0; path=/";
		flashNav.enabled = false;
		flashNav.object = false;
		if(flashNav.placeholder)
			$('#' + flashNav.replaceElemIdStr).replaceWith(flashNav.placeholder);
		//$('#' + flashNav.htmlNavigationID).show();
		//$('#' + flashNav.swfNavigationID).remove();
		//$(document.documentElement).removeClass('is-flash-navigation');
		
		if(flashNav.ondisable)
			setTimeout(flashNav.ondisable, 0);
		
		//When navigating back and forward in history, make sure Flash state restored
		if(window.removeEventListener){
			try {
				window.removeEventListener('pageshow', onpageshow, false);
			}
			catch(e){}
		}
		return true;
	}
};

//var windowLoaded = false;
//$(window).load(function(){
//	alert('windowLoaded')
//	windowLoaded = true;
//});

/**
 * Related to bug 1494: Flash.updateLocationState ExternalInterface call blocks UI  <http://bugs.shepherd-interactive.com/view.php?id=1494>
 * When navigating back and forward in history, the Flash's state will get
 * reset to the initial falshvars provided.
 */
function onpageshow(){
	var uri = AjaxLoading.getURI();
	flashNav.updateLocationState(uri, true);
}


})(jQuery /*, undefined*/);
