/*
 * Search the DOM for any anchor tags with xhref attributes, and asynchronously
 * fetch the given document and replace the anchor tag with it
 */

var queue = new Array();
var xlinkCache = new Array();
xhr = null;

//if ( window.addLoadEvent )
//	addLoadEvent( processXLinks );

function processXLinks()
{
	// Build a list of all div tags with xhref attributes
	var divs = document.getElementsByTagName( 'div' );
	var i;
	for ( i = 0; i < divs.length; i++ )
	{
		var d = divs[i];
		if ( d.attributes.length > 0 && d.attributes['xhref'] )
		{
			queue.push( d );
			d.innerHTML = '<i>Loading page...</i>';
		}
	}
	
	doNextDiv();
}

function doNextDiv()
{
	if ( queue.length > 0 )
	{
		var url = queue[queue.length - 1].attributes['xhref'].nodeValue;
		if ( !xlinkCache[url] )
		{
			xhr = newXHR();
			xhr.onreadystatechange = stateChange;
			xhr.open( 'GET', url, true );
			xhr.send( null );
		}
		else
		{
			var div = queue.pop();
			div.innerHTML = xlinkCache[url];
			doNextDiv();
		}
	}
	else
	{
		removeLeadingSpaces();
		annotateText();
		highlightSearch();
	}
}

function stateChange()
{
	if ( xhr.readyState == 4 )
	{
		if ( xhr.status == 200 )
		{
			var div = queue.pop();
//			var html = parseChapter( xhr.responseXML );
			var html = xhr.responseText;
			div.innerHTML = html;

			var url = div.attributes['xhref'].nodeValue;
			xlinkCache[url] = html; 
		}
		doNextDiv();
	}
}

function parseChapter( xml )
{
    // Some browsers dice up long text nodes, so we must put them back together
    var body = '';
    var bodyNodes = xml.getElementsByTagName( 'body' )[0].childNodes;
    for( i = 0; i < bodyNodes.length; i++ )
    {
        body += unescape( bodyNodes[i].nodeValue );
    }
	
	return body;
}

//function setBiblePreference()
//{
//	var doclinks = document.links;
//	var scripRef;
//	for ( var i = 0; i < doclinks.length; i++ )
//	{
//		if ( doclinks[i].className == 'scripRef' )
//		{
//			scripRef = doclinks[i];
////			console.log( 'old: ' + scripRef.href );
//			scripRef.href = scripRef.href.replace( /^(.*?)\/(\w+)\.(.*)$/, '$1/niv.$3' );
////			console.log( 'new: ' + scripRef.href );
//		}
//	}
//}
//
