/*	Bend Bulletin Ad load script.
		Written by Luke Dupin 2008

		Props to John Resig for providing the html to dom parser.
		http://ejohn.org

		The following code overwrites document.write with loadWrapper func.	This
		function writes a div out to store the document.write's position in the 
		html document.	Then it stores the information that would have been written
		into a buffer that matches the positioning div IE the names are the same.
		
		Once the entire body is loaded, attachWrapper must be called by body:
		<body onLoad="attachWrapper();">
			//Overwrite document.write with our positioning and accumulating function
		document.write = loadWrapper;

		This function changes document.write to go into a recursive script loading
		mode.	Since all the divs are already in place, we needn't write any more.
		Now, anything that is passed to document.write is accumlated.	An
		interval is started, and when it times out, all the information from the
		external script we loaded is written to our current div.	At this point
		we load the next external script, move to our next positioning div, and 
		repeat.

		The affect produced by this is a snappy page that loads quickly.	Ad's
		and other heavy javascript are loaded after the bulk of the content exist.
		
		The script is a drop in functionality replacement and should work in all
		cases.	Enjoy!
*/

//Requirement, Body must be of the following form
//		<script language="javascript>document.write = loadWrapper;</script>
//		<body onLoad="attachWrapper();">

	//My variable holders
var ad_wrap_idx = 0;
var ad_wrap_data = new Array();

		//Used to load scripts recursively
var recursive_load = new Array();
var recursive_div = new Array();
var recursive_idx = 0;

		//Used to call the next add
var ad_timer_id = null;
var ad_timer_wait = 1000;	//Two seconds
var ad_timer_buf = '';

	//Used for debuging counting
var debug_count = 1;

	//Catch document.writes, accumulate the html, write out a position div
function loadWrapper()
{
	if ( loadWrapper.arguments.length > 0 )
	{
		var html = loadWrapper.arguments[0];
		//document.getElementById("debug").innerHTML += debug_count++ + html;

			//Write out a div to keep track of my location and store this html
		document.writeln('<div id="ad_wrapper_'+ ad_wrap_idx +'"></div>');
		ad_wrap_data[ad_wrap_idx++] = html;
	}
}


	//This is used to load up the next script
	//This is the function called when our interval times out
function loadNextScript()
{
		//Reset the timer always
	if ( ad_timer_id != null )
	{
		clearInterval( ad_timer_id );
		ad_timer_id = null;

			//If we have a valid rec_idx and ad_timer_buf != '' inline that... stuff
		if ( recursive_idx >= 0 && recursive_idx < recursive_load.length &&
				ad_timer_buf != '' )
		{
			document.getElementById(recursive_div[recursive_idx]).innerHTML = ad_timer_buf;
		}
	}

		//Reset the ad_timer buffer
	ad_timer_buf = '';

		//Increase my recursive count and load the next guy
	if ( ++recursive_idx < recursive_load.length )
	{
			//Add a timer to move to the next script
		ad_timer_id = setInterval( loadNextScript, ad_timer_wait );

			//Load up the next script
		var scrpt = document.createElement('script');
		scrpt.src = recursive_load[recursive_idx];
		document.getElementById(recursive_div[recursive_idx]).appendChild(scrpt);
	}
}

	
	//This function over write document.write after the page has loaded.
	//This use's existing position divs layed down by loadWrapper and recursively
	//loads remote scripts
function realtimeWrapper()
{
		//Called by a document, write
	if ( realtimeWrapper.arguments.length > 0 && 
				recursive_idx < recursive_load.length)
	{
			//Store the html the user wants to insert
		var html = realtimeWrapper.arguments[0];
		//document.getElementById("debug").innerHTML += debug_count++ + html;

			//Map out this javascript and add it into my current child
		var scripts = parseScript( html );

			//If the new dom tree has no scripts, then move onto the next script
		if ( scripts.length <= 0 )
		{
				//Insert the user's html
			ad_timer_buf += html;
		}
			//We must have more scripts to work with!
		else
		{
				//Push all the new scripts onto our stack
			for ( var r = 0; r < scripts.length; r++ )
			{
				recursive_load.push( scripts[r] );
				recursive_div.push(recursive_div[recursive_idx]);
			}
		}

			//Reset and set the timer yet again
		if ( ad_timer_id != null )
			clearInterval( ad_timer_id );

			//Add a timer to move to the next script
		ad_timer_id = setInterval( loadNextScript, ad_timer_wait );
	}
}

	//This is called once by body onLoad once the main page is loaded
	//This function will write out any static content it can
	//Any remote scripts we find are put into the recursive remote script loading
	//logic.
	//Notice that document.write changes when this function is ran!
function attachWrapper() 
{
		//Now we want to go into a real time mode
	document.write = realtimeWrapper;

		//Load up my objects
	for ( var i = 0; i < ad_wrap_idx; i++ )
	{
			//Create a dom tree from this html
		var scripts = parseScript( ad_wrap_data[i] );

			//If the we have a script in here, store the dom tree to a global array
		if ( scripts.length > 0 )
		{
			for ( var r = 0; r < scripts.length; r++ )
			{
				recursive_load.push( scripts[r] );
				recursive_div.push( 'ad_wrapper_'+ i);
			}
		}

			//otherwise just insert the new dom tree and move on
		else
		{
			document.getElementById('ad_wrapper_'+ i).innerHTML = ad_wrap_data[i];
		}
	}

		//Now I am going to start my recursive loading of scripts
	if ( recursive_load.length > 0 )
	{
			//I do this because it will be incremented in the following func call
		recursive_idx = -1;
		loadNextScript();
	}
}

//Everything below is John Resig's javascript parser script
//This is used to parse out <script tags, Thanks again John!

	//Hack to make this code work in IE... because IE rocks!
function valid(objToTest) 
{
	if (objToTest == "null" || objToTest == "undefined")
		return false;

	return true;
}


// An inhouse parser that will pull out script calls to remote resources 
function parseScript( str )
{
	var scripts = new Array();
	var hits;
	var src;
	var r = 0;

		//Look for a script tag
	if ( hits = str.match(/<script[^>]*javascript[^>]*>/ig) )
		for ( var i = 0; i < hits.length; i++ )
		{
				//Pull out the src def for this script
			if ( src = hits[i].match(/src="(.*?[^\\])"/i) )
				scripts[r++] = src[1];
		}

	return scripts; 
}
