/*
	Copyright Joop Ringelberg 2011.
	This code loads javascript and css stylesheets files dynamically.
	Maintain this file in /db/talkTalk/views/talkingHead/
	
	A file will not be loaded if another url that ends on the same filename has been loaded before.
*/


/*
	loadStylesheets( [ "style1.css", "style2.css, "/somedir/style3.css" ] );
*/

var loadedFiles, loadStyleSheets, loadScripts;

(function($)
{
		if ( loadedFiles == undefined )
		{
			loadedFiles = {};
		};
		
		loadStylesheets = function( urls, baseUrl )
		{
			var styleSheetExists = 
				function( url )
				{
					//return $( "link[ href $= '" + url + "']" ).length > 0;
					return loadedFiles[ url ] == true;
				};
						
			var loadCss = 
				function( index, url )
				{
					if ( url )
					{
						if ( document.createStyleSheet )
						{
							if ( ! styleSheetExists( url ) ) { document.createStyleSheet( baseUrl + url ) };
						}
						else
						{
							if ( ! styleSheetExists( url ) )
							{
								$( "head" ).append( $( "<link rel='stylesheet' href='" + baseUrl + url + "' type='text/css' media='screen'></link>") );
							};
						};
					loadedFiles[ url ] = true;
					}
				}
			$.each( urls, loadCss );
		};
		
		/*
			loadScripts( [ "source1.js", "source2.js, "/somedir/source3.js" ] );
			Scripts are loaded in order, consequtively and only when all previous scripts have been evaluated.
		*/
		loadScripts = function( urls, callback, baseUrl )
		{
			var scriptExists = 
				function( url )
				{
					//return $( "script[ src $= '" + url + "']" ).length > 0;
					return loadedFiles[ url ] == true;
				};
			var loadRecursively =
				function ( n )
				{
					if ( n > maxIndex ) { callback(); return }
					if ( ! scriptExists( urls[ n ] ) ) 
					{
						/*$( "head" ).append( '<script type="text/javascript" src="' + baseUrl + urls[ n ] + '">&#160;</script>' );
						loadedFiles[ urls[ n ] ] = true; 
						loadRecursively( n + 1 )*/
						if ( urls[n] )
						{
							// Protected by this test, as IE8 reports an array with 3 elements to have length 4 (probably counting its
							// member length, too?!).
							$.getScript( baseUrl + urls[ n ], function() { loadedFiles[ urls[ n ] ] = true; loadRecursively( n + 1 ) } );
						}
						else
						{
							callback();
							return;
						};
					}
					else
					{
						loadRecursively( n + 1 )
					}
				};
			var maxIndex = urls.length - 1;
			loadRecursively( 0 );
		};
})(jQuery);

