// JavaScript Document


var myBuilder = new ILegendBuilder();


function generateLegend()
{
	//myService.getService();	
	myBuilder.service = myMap.service;
	multiBuild();
}


function multiBuild()
{
	//var items = document.getElementById("legendItems");
	for (i in RESPONSE.LAYER)
	{
		var id =RESPONSE.LAYER[i].id;
		var name =RESPONSE.LAYER[i].name;
		var url = myBuilder.build(id);
		
		//items.innerHTML += '<img src="'+url+'" > <font size=2>ID=<b>'+id+'</b> NAME=<b>'+name+'</b></font><br />';
	}
}



function ILegendBuilder()
{
	this.service;;
	this.axl;
	this.builderAXL = builderAXL;
	this.build = build;
	this.url;
	this.legendURL;
	this.renderCount = 0;
}


//*************************************************************
//send, recieve and parse XML and create Objects
//*************************************************************
function build(id)
{
	
		this.service = myMap.service;
		this.url = this.service.url 
		this.builderAXL(id)

		var xml = new JKL.ParseXML(this.url,this.axl);
		var data = xml.parse();
		RESPONSE.IMAGE = data.ARCXML.RESPONSE.IMAGE;
		this.legendURL = RESPONSE.IMAGE.LEGEND.url
		
		
		document.getElementById("renderLegend_"+id).innerHTML = '<img src="'+this.legendURL+'">';
		return this.legendURL;
}






function builderAXL(id)
{
	this.axl  ='<?xml version="1.0" encoding="UTF-8"?>\n';
	this.axl +='<ARCXML version="1.1">\n';
	this.axl +='<REQUEST>\n';
	this.axl +='<GET_IMAGE>\n';
	this.axl +='<PROPERTIES> \n';
	
	//INSERT the LAYER DEFINITIONS
	this.axl += '<LAYERLIST>\n';
	for (var num in RESPONSE.LAYER) 
	{
		this.axl +='<LAYERDEF id="'+RESPONSE.LAYER[num].id+'" visible="'+RESPONSE.LAYER[num].visible+'">\n';
	
		for (var ii  in myMap.renderers)
		{
			
			if (myMap.renderers[ii].layerId == 	RESPONSE.LAYER[num].id)
			{	this.renderCount++;
				if (myMap.renderers[ii].visible)
				{	this.renderCount = myMap.renderers[ii].ranges.length -1;
					this.axl +=myMap.renderers[ii].axl;
				}
			}
		
		}
		
		this.axl +='</LAYERDEF>';
	}
	this.axl += '</LAYERLIST>\n'
	
	var height = 30
	
	this.axl +='<LEGEND tialiasing="true" reverseorder="false" swatchwidth="15" swatchheight="15" autoextend="true" columns="1" width="200" height="'+height+'" backgroundcolor="255,255,255" >\n';
	this.axl +='<LAYERS>\n';
	
	var xml = '';
	for (i in RESPONSE.LAYER)
	{
		layerId =RESPONSE.LAYER[i].id;
		if (layerId != id) 
		{
			xml +='<LAYER id="'+layerId+'"/>\n'
		}
	}
	this.axl +=xml;
	
	this.axl +='</LAYERS>\n';
	this.axl +='</LEGEND>\n';
	this.axl +='<DRAW map="false"/>\n';
	this.axl +='</PROPERTIES>\n';
	this.axl +='</GET_IMAGE>\n';
	this.axl +='</REQUEST>\n';
	this.axl +='</ARCXML>\n';
	
}
	
	

