//
// The page processing functionality within the Hedgehog architecture ensures
// that the content for each active element (using the attribute 
// class="active") within the page is requested, asynchronously.
//

// PagePopulator
// First find all elements with the class "active"
// Then for each element, send XMLhttp request with the id and the name of the current screen and next screen*
// *this used to be the next URL, but we are moving away from URLs and towards 'screen names'.
// Insert reply into element (when it arrives, asynchronously).

function PagePopulator(screen)
{
    // Find all nodes with the class attribute set to "active"
    var activeNodes = getElementsByAttribute("class", "active");
    
    // then, for each active node
    //   populate it
    for (i=0; i<activeNodes.length; i++)
    {
        //debug
        //alert( "about to call PopulateElement with [" + activeNodes[i].id + "," + newScreen + "]" );
        // On page load hard code parameters string to empty
        PopulateElement(activeNodes[i].id,screen,"");
    }
}

function PopulateElement(ElementID,screen,parameters)
{
    // debug
    //alert("PopulateElement(" + ElementID + ")");
    
	var URLarray = document.URL.split('/');
	var URL = URLarray[URLarray.length-1];
	
	var XMLHttpRequestObject = false;
	
	// Cater for Microsoft/non-Microsoft differences
	if (window.XMLHttpRequest)
	{
		XMLHttpRequestObject = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
	}

	if (XMLHttpRequestObject)
	{
		var obj = document.getElementById(ElementID);
		var Generator;
		var dataToSend;

		// At this point in time, all active elements generate the same kind of request, APART FROM the text elements,
		// which simply requests a text file (which, we happen to know, contains tagged data)
		
		// frig: until we can have multiple instances of the same active element, we need to have differently-named
		// active elements that are functionally equivalent
		if (ElementID == "text1" || ElementID == "text2" || ElementID == "text3")
		{
		    // frig: text2 element is the flexible general area; text1 & 3 are static, so always request the same file
		    if (ElementID == "text2")
		    {
		        Generator = "./content/" + screen + ".txt";
		    }
		    else
		    {
		        Generator = "./content/" + ElementID + ".txt";
		    }
		    dataToSend = null;

    		//debug
    		//alert("set up XMLHttpRequest with [" + Generator + "] and [" + dataToSend + "]" );
    		
            // for some reason, this request for a file seems to prefer a GET to a POST
            XMLHttpRequestObject.open("GET", Generator);            
		}    
        else // not a text active element - call the script
		{
		    // tell the server which active element we are, and which screen we are requesting. 
		    // This will allow the server to (a) do the appropriate processing for our active element, 
		    // and (b) generate the correct links for the nav bars based on where we are in the website
		    Generator = "architecture/UpdateElements.php";
		    dataToSend = "id=" + escape(ElementID) + "&screen=" + escape(screen) + parameters;

    		//debug
    		//alert("set up XMLHttpRequest with [" + Generator + "] and [" + dataToSend + "]" );

            // was XMLHttpRequestObject.open("GET", Generator); but to avoid caching problems, use POST instead (Head Rush Ajax; 301)
    		XMLHttpRequestObject.open("POST", Generator, true);
		}

        // Associate an anonymous function with the callback
		XMLHttpRequestObject.onreadystatechange = function()
		{
			if (XMLHttpRequestObject.readyState == 4 &&
				XMLHttpRequestObject.status == 200)
			{
			    // debug
			    // alert( "callback for " + ElementID + ". Response headers are: " + XMLHttpRequestObject.getAllResponseHeaders() );
			    
			    if (XMLHttpRequestObject.getResponseHeader("Content-Type") == "text/xml")
			    {
			        // Debug: display XML as text so we can see what we have just received
    				var text = XMLHttpRequestObject.responseText;
                     //alert( "Received XML: " + text );

		            // Extract the response (as XML)
    			    var xmlDoc = XMLHttpRequestObject.responseXML;

			        // From the response, extract the function which is about to be called
			        var functionNameNodes = xmlDoc.getElementsByTagName("code");
			        // ...and now extract the data which to be passed to the function
			        var dataNodes = xmlDoc.getElementsByTagName("data");
    			    
			        // These lines of code just clarify exactly what is being passed
			        var functionName = functionNameNodes[0].firstChild.nodeValue;
                    var functionParameter = dataNodes[0];
                    var evaluationString = functionName + "(obj,functionParameter);";
                    
                    // call the line of JavaScript that has just been constructed
				    eval( evaluationString );
				}
				else if ((XMLHttpRequestObject.getResponseHeader("Content-Type") == "text/plain")
				      || (XMLHttpRequestObject.getResponseHeader("Content-Type") == "text/html"))
				{
	                //debug
	                alert( "Received plaintext for " + ElementID + ". \n\nShouldn't really have done that but I'll process it using innerHTML to keep you happy!" );

    				var text = XMLHttpRequestObject.responseText;
                     alert( "Received text: " + text );

	                // If response is not XML, for the time being assume it is HTML and
	                // just insert it into the element
    				var text = XMLHttpRequestObject.responseText;
	                clearText( obj );
	                obj.innerHTML = text;
				}
				// else { //shouldn't reach here! }
			}
		}

        // Tell the server the data is encoded as it would be in a request URL, as if it came from a GET request (Head Rush Ajax; 308)
        XMLHttpRequestObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		// Because this is now a POST request, the parameters are added when we send the request
    	XMLHttpRequestObject.send( dataToSend );
	}
 
}