// AJAX function to open up the XML file
function loadXMLDoc(url) 
{
	isIE = false;
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) 
	{
        //alert("loadXMLDoc url no1 = " +url);
		req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
		//req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
        req.open("GET", url, false);
		//alert ("get completed")
        req.send(null);
		//alert("null set")
    // branch for IE/Windows ActiveX version
    } 
	else if (window.ActiveXObject) 
	{
		//alert("loadXMLDoc url no2 = " +url);
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) 
		{
            req.onreadystatechange = processReqChange;
			//req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
            req.open("GET", url, false);
            req.send();
        }
    }
}
// AJAX function to validate the XML file opens correctly
function processReqChange() 
{
//alert("readystate= " +req.readyState+ " status= " +req.status);
    // only if req shows "loaded"
    if (req.readyState == 4) 
	{
        // only if "OK"
        if (req.status == 200) 
		{
			// This is where you can place all the code to process the XML file
			return;
		} 
		else 
		{
            alert("There was a problem retrieving the XML data:\n" + req.statusText);
        }
	}
}


//-------------------------------------------------------------------------------------------------------------
// function to read a SLD file (XML) and extract the title, each rule and build a Legend for screen display
function buildLegend (sldUrl, legend, legendTitle, legendTable, legendBox, legendText, tdCell, firstTime)

// Input variables for this function:
//	- sldUrl = full sld Url of the SLD file
//	- legend = ID in application for whole of legend 
//	- legendTitle = ID in application for legend Title 
//	- legendTable = ID in application for legend Table
//	- legendBox = Class definition for coloured box of legend item
//	- legendText = Class definition for text of legend item
//	- tdCell = Class definition for Table cell holding coloured box of legend item
//	- firstTime = boolean flag to indicate elements already exist and need to be removed
//
// Please note that all the positioning and style controls are underatken in the application
//------------------------------------------------------------------------------------------------------------
{
	// Open the XML file for the SLD and get data
	loadXMLDoc(sldUrl);
	var sldTitle = req.responseXML.getElementsByTagName("UserStyle");
	var title = sldTitle[0].getElementsByTagName("Title")[0].firstChild.nodeValue;
		
	// Update the Legend Title with selected object
	var ltit = document.getElementById(legendTitle);
	if (firstTime)
	{
		// if first time create the Legend Title Text node 
		var textNode = document.createTextNode(" ");
		ltit.appendChild(textNode);
		ltit.firstChild.nodeValue=title;
	}
	else
	{
		// update the existing LegendTitle Text node
		ltit.firstChild.nodeValue=title;
	}
				
	// Get the Table Object 
	var table=document.getElementById(legendTable);
		
	// If this is not the first time kill off existing table body cell
	if (!firstTime)
	{
		var tbody=document.getElementById("tBody");
		tbody.parentNode.removeChild(tbody);
		tbody.value=null;	// must null it out to completely kill it out of memory
	}

	// Ok now we can start afresh with a new Table Legend Body
	var tbody=document.createElement("tBody");
	tbody.setAttribute("id", "tBody");
		
	// Set up the FOR loop for all the Rules in the XML SLD file
	var sldRules = req.responseXML.getElementsByTagName("Rule");
	var num= sldRules.length;
	if (num>0)
	{	
		var strokeColr = ""; 
		var strokeWidth = "";
		var fillColr = ""; 
		var fillOpacity = "";
		// There are some rules in the SLD to control the symbology
		// Loop through all the rules in the SLD file and build legend rows for each
		for (i = 0; i < num ; i++)
		{	
		// Check for a polygon symboliser tag
		var sldPolygon = sldRules[i].getElementsByTagName("PolygonSymbolizer");
		if (sldPolygon.length>0)
		{
			// find out how many fill Rules there are 
			var sldFill = sldRules[i].getElementsByTagName("Fill");
			if (sldFill.length > 0)
			{
				// find out how many CssParameter tags there are
				var sldFillCss = sldFill[0].getElementsByTagName("CssParameter");
				
				//alert ("sldFillCss = "+sldFillCss.length)
				if (sldFillCss.length > 0 )
				{
					// process each Fill CssParemeter attribute	
					for (j=0; j<sldFillCss.length ; j++)
					{
						var fillAtt = sldFillCss[j].getAttribute("name");
						if (fillAtt == "fill") 
						{
							fillColr = sldFill[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;		
						}
						if (fillAtt == "fill-opacity")
						{
							fillOpacity = sldFill[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
						}
					}
				}
			}
			// find out how many Stroke Rule nodes
			var sldStroke = sldRules[i].getElementsByTagName("Stroke");
			if (sldStroke.length > 0)
			{
				var sldStrokeCss = sldStroke[0].getElementsByTagName("CssParameter");
				
				//alert ("sldStrokeCss = "+sldStrokeCss.length)
				if(sldStrokeCss.length > 0)
				{
					// process each Stroke CssParemeter attribute				
					for (j=0; j<sldStrokeCss.length ; j++)
					{
						var strokeAtt = sldStrokeCss[j].getAttribute("name");
						if (strokeAtt == "stroke") 
						{
							strokeColr = sldStroke[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;		
						}
						if (strokeAtt == "stroke-width")
						{
							strokeWidth = sldStroke[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
						}
					}
				}
			}
		}
			//alert ("fillColr = "+fillColr+ " fillOpacity = "+fillOpacity);
			//alert ("strokeWidth = "+strokeWidth+ " strokeColr = "+strokeColr);
			
			// Ok now we have all the parameters from the SLD start to build the Legend
			var name = sldRules[i].getElementsByTagName("Name")[0].firstChild.nodeValue;			
				
			// set up the Table Body node and the TR node
			var tdIdbox="tdBox"+i;
			var tdIdtext="tdText"+i;
				
			// Set up the legend box TD node with appropriate color		
			var trNode = document.createElement("tr");
			var tdNode1 = document.createElement("td");
			tdNode1.className=tdCell;
			var divNode = document.createElement("div");
			divNode.className=legendBox;
			divNode.setAttribute("id", tdIdbox);	
			divNode.style.backgroundColor=fillColr;
			if (isIE)
			{
				// This is for IE's opacity control
				var op=Number(fillOpacity);
				var fillNumber = Math.abs(op*100);
				divNode.style.filter="alpha(opacity="+fillNumber+")";
			}
			else
			{
				divNode.style.opacity=fillOpacity;
			}
			// set up borders
			if (strokeWidth == "")
			{
				divNode.style.borderStyle="none";
			}
			else
			{	
				divNode.style.border=strokeWidth+"px solid "+strokeColr;
			}				
			// append TD node with legend symbol box to TR node 
			tdNode1.appendChild(divNode);
			trNode.appendChild(tdNode1);
			
			// Now generate the Text node in the second column of the table row
			var tdNode2 = document.createElement("td"); 
			tdNode2.className=legendText;
			var textNode = document.createTextNode(name);
			tdNode2.setAttribute("id", tdIdtext);	
			tdNode2.appendChild(textNode);
					
			// append TD node with legend text to TR node 
			trNode.appendChild(tdNode2);
			tbody.appendChild(trNode);	
		}
		// append the tbody note to the Table element
		table.appendChild(tbody);
	}
	else
	{	alert ("Sorry can't generate a legend");	}
}
//-------------------------------------------------------------------------------------
