/**
	responseHTML
	(c) 2007 xul.fr		
	Licence Mozilla 1.1
*/	


/**
	Searches for body, extracts and return the content
*/

function getBody(content)
{
	var x = content.indexOf("<!-- BEGIN RESULTS -->");
	if(x == -1) return "";
	
	x = content.indexOf(">", x);
	if(x == -1) return "";
	
	var y = content.lastIndexOf("<!-- END RESULTS -->");
	if(y == -1) return "";
	
	var z = content.slice(x + 1, y);
	return z;
}


/**
 * Loads a HTML page
 * Put the content of the body tag into the current page.
 * Arguments:
 * url of the other HTML page to load
 * id of the tag that has to hold the content
 */

function loadHTML(url, fun, storage, param)
{
	var xhr = createXHR();
	xhr.onreadystatechange=function() { 
		if(xhr.readyState == 4)
		{
			//if(xhr.status == 200)
			{
				storage.innerHTML = getBody(xhr.responseText);
				fun(storage, param);
			}
		} 
	}; 

	xhr.open("GET", url , true);
    xhr.setRequestHeader("Cache-Control", "no-cache");
    xhr.setRequestHeader("Pragma", "no-cache");
	
	xhr.send(null); 

} 

	/**
	 * Callback
	 * Assign directly a tag
	 */
	function processHTML(temp, target)
	{
		target.innerHTML = temp.innerHTML;
	}

	function loadWholePage(url)
	{
		var y = document.getElementById("storage");
		var x = document.getElementById("displayed");
		loadHTML(url, processHTML, x, y);
	}	

	function loadWholePageEx(url, divBase)
	{
		var y = document.getElementById(divBase + "-storage");
		var x = document.getElementById(divBase + "-displayed");
		loadHTML(url, processHTML, x, y);
	}	


	/**
		Create responseHTML
		for acces by DOM's methods
	*/	
	
	function processByDOM(responseHTML, target)
	{
		target.innerHTML = "Extracted by id:<br />";

		var message = responseHTML.getElementsByTagName("div").namedItem("two").innerHTML;
		target.innerHTML += message;

		target.innerHTML += "<br />Extracted by name:<br />";
		
		message = responseHTML.getElementsByTagName("form").namedItem("ajax");
		target.innerHTML += message.dyn.value;
	}
	
	function accessByDOM(url)
	{
		//var responseHTML = document.createElement("body");	// Bad for opera
		var responseHTML = document.getElementById("storage");
		var y = document.getElementById("displayed");
		loadHTML(url, processByDOM, responseHTML, y);
	}	
