
//-------------------------------------------------------------------------------------------------------------
// function to read a SLD file (XML) and extract the title, each rule and build a Legend for screen display
function buildLegend (Url, legHolder, leg, legTitle, legTable, legBox, legText, tdCell, opVal, dvbdy1, dvhdr1)

// Input variables for this function:
//	- Url = full sld Url of the SLD file
//  - legHolder = ID in application of the holder Div all other Divs are inside this
//	- leg = ID in application for whole of legend and sits inside legHolder
//	- legTitle = ID in application for legend Title 
//	- legTable = ID in application for legend Table
//	- legBox = Class definition for coloured box of legend item
//	- legText = Class definition for text of legend item
//	- tdCell = Class definition for Table cell holding coloured box of legend item
//  - opVal =  opacity override used to dynamically fade the legend in sync with map (if = null it is ignored)
//
// Please note that all the positioning and style controls are underatken in the application
//------------------------------------------------------------------------------------------------------------
{
	var legend=document.getElementById(leg);
	//alert ('removing existing legend table')
	checkRemoveObject(legTable);
	checkRemoveObject(legTitle);

	// get the SLD file into the DOM
	if (!getSldInfo(Url)){alert ("Returning False"); return false;}
	//alert ("SLD Data = "+layerName+" : "+titleData+" : "+nameData);

	// Create the Legend Title Text node 
	var ltit = document.createElement("div")
	ltit.id=legTitle;
	ltit.setAttribute('id',legTitle);
	ltit.title=nameData;
	var textNode = document.createTextNode(nameData);
	ltit.appendChild(textNode);
	ltit.setAttribute("title", "cssbody=[dvbdy1] cssheader=[dvhdr1] body=["+titleData+"]");
	ltit.title="cssbody=[dvbdy1] cssheader=[dvhdr1] body=["+titleData+"]";
	legend.appendChild(ltit);
	
	// Create the Table Object 
	var table = document.createElement("table");
	table.setAttribute("id", legTable);
	table.id=legTable;
	var tbody=document.createElement("tBody");	
	
	
	// Set up the FOR loop for all the Rules in the XML SLD file
	var sldRules = ajaxRequest.responseXML.getElementsByTagName("Rule");
	num= sldRules.length;


	//alert("opacity Value ="+opVal)

	// now set the height of the legend background
	//var ht = parseInt((num * 25) + 35)
	//if (ht <120){ht='120px'}
	//else {ht = ht+"px";}
	// should interrogate height set in styles for table rows
	//document.getElementById(legHolder).style.height=ht;
	document.getElementById(legHolder).style.overflowX='hidden';
	document.getElementById(legHolder).style.overflowY='auto'; 
	//alert (ht)
	
	// Loop through all the rules in the SLD file and build legend rows for each
	for (var i = 0; i < num ; i++)
	{	
		var fillColr = null
		var fillOpac = null
		var fillPat = null
		var fillPatForm = null;
		var strokeOpac = null;
		var strokeDash = null;
		var strokeColr = null;
		var strokeWidth = null;
		
		// get the rule Title for Mouseover feature
		var title='';
		if(sldRules[i].getElementsByTagName("Title")[0])
		{
			title= sldRules[i].getElementsByTagName("Title")[0].firstChild.nodeValue;
		}
		if(sldRules[i].getElementsByTagName("Abstract")[0])
		{
			title= sldRules[i].getElementsByTagName("Abstract")[0].firstChild.nodeValue;
		}

		
		// Look for a polygon symboliser tag
		if (sldRules[i].getElementsByTagName("PolygonSymbolizer"))
		{	
			var polygonSymboliser = sldRules[i].getElementsByTagName("PolygonSymbolizer");
			var numPsym = polygonSymboliser.length;

			//alert('there are '+numPsym+' PolygonSymbolizers') 
			// precess each polygon symboliser tag
			for (var ii=0 ; ii<numPsym ; ii++ )
			{
				var sldFill = polygonSymboliser[ii].getElementsByTagName("Fill");
				if (sldFill.length > 0) // check to see if we have any Fills first
				{
					// CSSParameters are only used for color filling
					var sldFillCss = sldFill[0].getElementsByTagName("CssParameter");
					
					// if we have a regulat solid fill process here
					if (sldFillCss.length > 0 )
					{
						var fillColr = ""; 
						//var fillOpacity = opacityValue;
						// process each Fill CssParemeter attribute	
						for (var j=0; j<sldFillCss.length ; j++)
						{
							var fillAtt = sldFillCss[j].getAttribute("name");
							if (fillAtt == "fill") 
							{
								fillColr = sldFill[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
								if (fillColr == ''){fillColr='transparent'}
							}
							if (fillAtt == "fill-opacity")
							{			
								fillOpac = sldFill[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
								if (fillOpac == '' || fillOpac == null || fillOpac == 'undefined')
								fillOpac = 0;
								if (opVal != null) {fillOpac = parseFloat(fillOpac)*parseFloat(opVal);} // this adopts the input opacity when interactively adjusting layer 
							}
						}
					}
					else if(sldFill[0].getElementsByTagName("GraphicFill")) // looking for Graphic Fills
					{
						// we now have a graphic fill tag so get the data for inclusion in legend fill
						var graphicFill = sldFill[0].getElementsByTagName("GraphicFill");
						var graphic = graphicFill[0].getElementsByTagName("Graphic");
						var externalGraphic = graphic[0].getElementsByTagName("ExternalGraphic");
						var onlineResource = externalGraphic[0].getElementsByTagName("OnlineResource")
						var fillPat = onlineResource[0].getAttribute("xlink:href"); 
						//alert ("source = "+fillPat);
						var fillPatForm = externalGraphic[0].getElementsByTagName("Format")[0].firstChild.nodeValue;
						//alert ("format = "+fillPatForm)
					}
				}
				//alert("fill = "+fillColr)
				// find out how many Stroke Rule nodes
				if(polygonSymboliser[ii].getElementsByTagName("Stroke"))
				var sldStroke = polygonSymboliser[ii].getElementsByTagName("Stroke");
				if (sldStroke.length > 0)
				{
					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 (var 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;
								}
								if (strokeAtt == "stroke-opacity")
								{
									strokeOpac = sldStroke[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
								}
								if (strokeAtt == "stroke-dasharray")
								{
									strokeDash = sldStroke[0].getElementsByTagName("CssParameter")[j].firstChild.nodeValue;
								}
							}
						}
					}
				}
			}
		}
		/*
		alert("fillColr = "+fillColr)
		alert("fillOpac = "+fillOpac)
		alert("fillPat = "+fillPat)
		alert("fillPatForm = "+fillPatForm)
		alert("strokeColr = "+strokeColr)
		alert("strokeWidth = "+strokeWidth)
		alert("strokeOpac = "+strokeOpac)
		alert("strokeDash = "+strokeDash)
		*/

		// Ok now we have all the parameters from the SLD start to build the Legend
		if(sldRules[i].getElementsByTagName("Name")[0])
		{		var name = sldRules[i].getElementsByTagName("Name")[0].firstChild.nodeValue;	}
		else
		{	var name = '';		}

		// set up the Table Body node and the TR node
		var tdIdbox="tdBox"+i;
		var tdIdtext="tdText"+i;
		var trId="tr"+i;
		
		// Set up the legend box TD node with appropriate color		
		var trNode = document.createElement("tr");
		if(title != '')
		{	
			var boxover ='"header=['+name+'] cssbody=[dvbdy1] cssheader=[dvhdr1] body=['+title+']"';
			trNode.setAttribute("title", boxover);
			trNode.title=boxover;
		}
		
		// first cell is the polygon symbology box
		var tdNode1 = document.createElement("td");
		tdNode1.className = tdCell;
		
			var divNode = document.createElement("div");
			divNode.className = legendBox;
			divNode.id = tdIdbox;
			divNode.setAttribute("id", tdIdbox);
					
			// set up borders if required
			if (strokeWidth == null)
			{	divNode.style.borderStyle="none";	}
			else
			{	divNode.style.border = strokeWidth+"px solid "+strokeColr;	}
				
			// fill in color if required
			if (fillColr != 'transparent' && fillColr != null  )
			{	
				divNode.style.backgroundColor = fillColr;
				var op=Number(fillOpac);
				var fillNumber = Math.abs(op*100);
				setOpacity(divNode, fillNumber);
			}

			// now check for fill patterns
			if (fillPat != null)
			{
				var divNode2 = document.createElement("div");
				divNode2.className = legendBox;
				divNode2.style.backgroundImage= "url("+fillPat+")";
				divNode2.style.backgroundRepeat='repeat';
				var fillNumber = Math.abs(op*100);
				setOpacity(divNode, fillNumber);
				divNode.appendChild(divNode2);
			}
						
			// 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=legText;
			if (name != '')
			{
				var textNode = document.createTextNode(name);
				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);
	legend.appendChild(table);
	
	//alert('legend created')
	return true;
}
function getSldInfo(sldfileUrl)				
//--------------------------------------------- getSldInfo -----------------------------------------------
// sldfileUrl can be either a URL of an SLD e.g. http://demos.numaps.com.au/inc/sld/mb/landuse.xml  
// or, sldfileUrl can be a URL with a DrapeID appended e.g. http://demos.numaps.com.au/inc/sld/mb/DID:624
// note you camn also simply have DID:624 as the DrapeID.
//--------------------------------------------------------------------------------------------------------
{
	//alert('inside getSldInfo = '+sldfileUrl)
	if(sldfileUrl !='')
	{
		sldAbstract = '';
		layerName = '';
		titleData = '';
		nameData = '';
		opValue = '';
		themeData = '';
		
		// get the SLD file into the DOM 
		var query = '';
		var parts = sldfileUrl.split('DID:');
		if(parts.length > 1) 
		{
			// get the SLD into DOM from DrapeId
			//alert('by DrapeId')
			ajaxRequest = getSldByDrapeId(parts[1]);
			if (ajaxRequest.status != 200) {return false;}
		}
		else
		{
			// get the SLD into the DOM	from the file
			var query = '';
			var parts = sldfileUrl.split("?bruid");
			if(parts.length <= 1){ query = "?bruid="+new Date().getTime();}
			//alert(sldfileUrl+query)
			ajaxRequest = loadXml(sldfileUrl, query, false);
			if (ajaxRequest.status != 200) {return false;}
		}
	}
	else
	{	return false;	}
	//alert('status = '+ajaxRequest.status)
	
	// now get NamedLayer header elements from DOM
	var sldNamedLayer = ajaxRequest.responseXML.getElementsByTagName("NamedLayer");
	layerName = sldNamedLayer[0].getElementsByTagName("Name")[0].firstChild.nodeValue;
	
	// get UserStyle header elements
	var sldTitle = ajaxRequest.responseXML.getElementsByTagName("UserStyle");
	
	if(sldTitle[0].getElementsByTagName("Theme")[0])
	{	themeData = sldTitle[0].getElementsByTagName("Theme")[0].firstChild.nodeValue;}

	if(sldTitle[0].getElementsByTagName("Title")[0])
	{	titleData = sldTitle[0].getElementsByTagName("Title")[0].firstChild.nodeValue;}
	
	if(sldTitle[0].getElementsByTagName("Name")[0])
	{	nameData = sldTitle[0].getElementsByTagName("Name")[0].firstChild.nodeValue;}
	
	if(sldTitle[0].getElementsByTagName("Abstract")[0])
	{	sldAbstract = sldTitle[0].getElementsByTagName("Abstract")[0].firstChild.nodeValue;}
		
	var sldCss = ajaxRequest.responseXML.getElementsByTagName("CssParameter");
	//alert(sldCss.length)
	if(sldCss.length >0)
	{
		for (var i=0 ; i<sldCss.length ; i++)
		{
			if (sldCss[i].getAttribute("name")) 
			{ 
					
				//alert(sldCss[i].getAttribute("name") + " = "+ sldCss[i].firstChild.nodeValue);
				if(sldCss[i].getAttribute("name") == "fill-opacity")
				{	
					opValue = sldCss[i].firstChild.nodeValue;
					//alert('DONE & opValue = '+opValue)
					break ;
				}
			}
		}
	}
	

	//alert(layerName+" - "+titleData+" - "+nameData+" - "+themeData+" - "+opValue+"\n"+sldAbstract)
	return true;
}
/*
//------------------------------------------------------------------------------
function getSldInfo(Url)
{
	// get the SLD file into the DOM
	//alert(Url)
	var query="?bruid="+new Date().getTime();
	ajaxRequest = loadXml(Url, query);
	if (ajaxRequest.status != 200) {return false;}

	// get NamedLayer header elements
	var sldNamedLayer = ajaxRequest.responseXML.getElementsByTagName("NamedLayer");
	var sldLayerName = sldNamedLayer[0].getElementsByTagName("Name")[0].firstChild.nodeValue;
	
	// get UserStyle header elements
	var sldTitle = ajaxRequest.responseXML.getElementsByTagName("UserStyle");
	sldTitleData = sldTitle[0].getElementsByTagName("Title")[0].firstChild.nodeValue;
	var sldName = sldTitle[0].getElementsByTagName("Name")[0].firstChild.nodeValue;
	
	// set the global variables
	layerName = sldLayerName;
	//if(titleData == ""){titleData = sldTitleData;}
	titleData = sldTitleData;
	nameData = sldName;
	//alert ("SLD Data = "+layerName+" : "+sldTitleData+" : "+nameData);

	return true;
}
*/
// ---------------- Set opacity for different Browsers -------------------//
function setOpacity(obj, opacity) 
{
// obj = object that is to have aopacity set for
// opacity =  integer between 0 & 100
	opacity = (opacity == 100)?99.999:opacity;

  // IE/Win
	obj.style.filter="alpha(opacity="+ opacity + ")";

  // Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;

  // Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;

  // Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}
// ------------------ function to check if object exists and if so remove it --------------------
function checkRemoveObject(oId)
{
	if (document.getElementById(oId))
	{	
		var obj = document.getElementById(oId);
		obj.parentNode.removeChild(obj);
		obj.value=null;
		//alert('object '+oId+' removed')
	}
}
function getLayerOpacity(sldUrl)
{
	var opValue=1;
	var query="?bruid="+new Date().getTime();
	ajaxRequest=loadXml(sldUrl, query, false)
	{	var sldRules = ajaxRequest.responseXML.getElementsByTagName("Rule");
		if (sldRules[0].getElementsByTagName("Fill"))
		{
			var sldFill = sldRules[0].getElementsByTagName("Fill");
			if (sldFill[0].getElementsByTagName("CssParameter"))
			{
				var sldFillCss = sldFill[0].getElementsByTagName("CssParameter");
				if (sldFillCss[0].getAttribute("name") == "fill-opacity")
				{opValue =sldFill[0].getElementsByTagName("CssParameter")[0].firstChild.nodeValue;}
				if (sldFillCss[1].getAttribute("name") == "fill-opacity")
				{opValue = sldFill[0].getElementsByTagName("CssParameter")[1].firstChild.nodeValue;}
			}
		}
	}
	//alert("SLD Layer Opacity value =" +opValue);
	return opValue;
}
/*
function getAttributeSchema(serviceBase, layerName)
{
	// do a DescribeFeatureType request to get attribute schema
	
	//This works...	//http://203.217.18.65:81/cubewerx/cubeserv/cubeserv.cgi?request=DescribeFeatureType&typename=socio_economic&service=wfs&version=1.0.0&datastore=ABS
	// buld up the GetFeature request here
	var srcParts = layerName.split(':');
	var dfParams = '';
	dfParams = "REQUEST::DescribeFeatureType";
	dfParams += "|SERVICE::WFS";
    dfParams += "|DATASTORE::"+srcParts[1];
	dfParams += "|TYPENAME::"+srcParts[0];
	dfParams += "|VERSION::1.0.0";

	// Ajax to get data from the remote server via a GetFeatureInfo WMS request
	var request = applicationBase+"inc/getgfi02.php?";
	var p1= "url="+serviceBase;
	var p2= "&params="+dfParams;
	var dateStamp = new Date().getTime();
	var fln = "attsData"+dateStamp+".xml";
	var file = "&file=data/"+fln;
	//alert(request)
	//alert(p1)
	//alert(p2)
	//alert(file)
	//document.write(request+p1+p2+file)
	// makeXml(request, p1+p2, async)
	ajaxRequest = ajaxGet02(request, p1, p2, file)
	
	//alert('deleting file = data/'+fln)
	deleteit('data/'+fln);
	//alert('check in data/ that file attsData... is gone')
	//alert ('XML file created = inc/data/'+fln)
	return ajaxRequest;
}
*/
function getAttributeSchema(serviceBase, layerName)
{
	// do a DescribeFeatureType request to get attribute schema
	// initialise the request
	ajaxRequest = null;
	var gfiParams = '';
	gfiParams = startReq(serviceBase, gfiParams);

	// buld up the GetFeature request here
	var srcParts = layerName.split(':');
	gfiParams = "REQUEST=DescribeFeatureType";
	gfiParams += "&SERVICE=WFS";
    gfiParams += "&DATASTORE="+srcParts[1];
	gfiParams += "&TYPENAME="+srcParts[0];
	gfiParams += "&VERSION=1.0.0";

	// substitute special chars in string
	//gfiParams = gfiParams.replace(/=/g, "::");
	//gfiParams = gfiParams.replace(/&/g, "|");

	// execute the getFeatureInfo request on server via proxy
	ajaxRequest = proxyRequest(serviceBase, gfiParams, '') ;
	//alert(ajaxRequest.status)
	return ajaxRequest;
}

