//  **************************************************************
/** (c) 2004 GeoWise Limited.
  *
  * Functions for SVG mapping.
  *
  * author Jonathan Clare.
  * 	
  * version 1.0, 9th January, 2004.
  */
//  **************************************************************

// Global variables
var svgMap;
var svgChart;
var svgTable;
var svgLegend;

// Map variables.
var map;
var mapFullExtent;
var mapViewBoxWidth;	
var mapViewBoxHeight;
var mapViewBoxX;	
var mapViewBoxY;
var mapX = 20;
var mapY = 20; 
var mapWidth = 350;
var mapHeight = 350;
var showMapping;

// Rank chart dimensions.
var legendX = 0;
var legendY = 10;
var legendWidth = 10;
var legendHeight = 100;
var colourTable;
var legendIndex1 = 0;

// Table dimensions.
var tableNameColWidth = 240;	// Width of name column.
var tableDataColWidth = 50;	// Width of data column.
var tableCellHeight = 11.15;	// Height of rows.
var tableX = 2;		// Coords of top left corner of table.
var tableY = 2;
var tableMoveTextX = 5;	// Indentation of text into table cells.
var tableMoveTextY = 10;
var sortTable = "name";
var nRows = 0;

// Bar Chart dimensions.
var chartX = 0;	// Coords of top left corner of chart.
var chartY = 10;
var chartHeight = 100;	
var chartWidth = 300;

// Selected data array stats.
var dataArray;
var minValue;
var maxValue;
var range;
var sortedData = new Array(AREAID.length);
var sortedId = new Array(AREAID.length);
var sortedName = new Array(AREAID.length);

// Styles.
var currentStyle;
var highlightStyle = "fill:#FF9751;";
var toolHighlightStyle = "fill:#00FFFF";

// Replaces adobe menu with custom menu.
function stopMenu(evt)
{ 
	evt.preventDefault();
}

// Called by the body onload event.
// Gets the embedded svg documents.
function init() 
{
	// Get the svg docs.
	svgMap = document.embeds["svgmap"].getSVGDocument(); 
	svgChart = document.embeds["svgchart"].getSVGDocument(); 
	svgTable = document.embeds["svgtable"].getSVGDocument(); 
	svgLegend = document.embeds["svglegend"].getSVGDocument(); 
	
	buildMap(svgMap, mapX, mapY, mapWidth, mapHeight);
	
	populateThemeList("theme", TID, TNAME);
	var theme = document.forms['mapSettings'].elements['theme'].value;
	populateIndicatorList("indicator", eval(theme));
	populateColourSchemeList('legend1s', colourSchemeNames);
	
	loadData();
	var licensePlus = document.getElementById('copyrightAndLicense');
	if (licensePlus) {
		licensePlus.innerHTML = licenseText + '&nbsp;' + copyrightText;
	}
	var userHeading = document.getElementById('userHeading');
	if (userHeading && userHeadingText) {
		userHeading.innerHTML = userHeadingText;
	}
	var tableHeading = document.getElementById('tableHeading');
	if (tableHeading && tableNameText) 
		tableHeading.innerHTML = 'Name: ' + tableNameText;
	if (tableHeading && tablePopulationText)
		tableHeading.innerHTML += '<br />Population: ' + tablePopulationText;	
	if (tableHeading && tableLevelText)
		tableHeading.innerHTML += '<br />Level: ' + tableLevelText;	
	tableHeading = document.getElementById('footnote');
	if (tableHeading && tableFootnoteText) {
		tableHeading.innerHTML = 'Footnote: ' + tableFootnoteText;
	}
}

// Loads a new set of data.
function loadData()
{
	var indicator = document.forms['mapSettings'].elements['indicator'].value;
	dataArray = eval(indicator);
	
	sortArray(dataArray)
	minValue = getMinValue(dataArray);
	maxValue = getMaxValue(dataArray);
	range = maxValue - minValue;

	buildApp();
}

// Groups functions required for building the app.
function buildApp()
{	   	
	buildColourTable(legendIndex1);
	
	if(sortTable == "name")
		buildTable(svgTable, AREAID, AREANAME, dataArray);
	else
		buildTable(svgTable, sortedId, sortedName, sortedData);
	
	buildLegend(svgLegend);
	buildBarChart(svgChart);
	colourAreas();
}

function refreshColours(ci) {
	legendIndex1 = ci;
	buildApp();
}

function buildColourTable(table)
{
	var cScheme = colourSchemes[table];
	if (cScheme != null) {
		var lowerIndex = minValue;
		var upperIndex = maxValue;
		var btm = cScheme[0].split(',');
		var top = cScheme[cScheme.length - 1].split(',');
		var colourRule1 = new Array(lowerIndex,parseInt(btm[0]),parseInt(btm[1]),parseInt(btm[2]),upperIndex,parseInt(top[0]),parseInt(top[1]),parseInt(top[2]));
		colourTable = new Array(colourRule1);
	}
	else {
		var classWidth = range / 4;
		var lowerIndex = minValue;
		var upperIndex = lowerIndex + classWidth;
		var colourRule1 = new Array(lowerIndex,51,51,101,upperIndex,139,145,255);
		var lowerIndex = upperIndex;
		var upperIndex = lowerIndex + classWidth;
		var colourRule2 = new Array(lowerIndex,139,145,255,upperIndex,225,225,225);
		var lowerIndex = upperIndex;
		var upperIndex = lowerIndex + classWidth;
		var colourRule3 = new Array(lowerIndex,225,225,225,upperIndex,220,172,172);
		var lowerIndex = upperIndex;
		var upperIndex = maxValue;
		var colourRule4 = new Array(lowerIndex,220,172,172,upperIndex,172,49,46);
		colourTable = new Array(colourRule1,colourRule2,colourRule3,colourRule4);
	}
}

// Colours shapes according to the band they reside in.
function colourAreas()
{
	for (i=0; i<dataArray.length; i++)
	{
		var value = dataArray[i];
	
		var fillColour = getColour(value, colourTable)
		if(svgMap.getElementById(AREAID[i]) != null)svgMap.getElementById(AREAID[i]).setAttribute("style", fillColour);
		if(svgTable.getElementById(AREAID[i]) != null)svgTable.getElementById(AREAID[i]).setAttribute("style", fillColour);
		if(svgChart.getElementById(AREAID[i]) != null)svgChart.getElementById(AREAID[i]).setAttribute("style", fillColour);
	}
	if(svgLegend != null) colourLegend();
}

// Returns a colour.
function getColour(index, colourTable)
{
	var colour;
	var lowerIndex;
	var upperIndex ;
	
	for (j=0; j<colourTable.length; j++) 
	{ 
		var colourRule = colourTable[j];

		lowerIndex = colourRule[0];
		var r1 = colourRule[1];
		var g1 = colourRule[2];
		var b1 = colourRule[3];
		
		upperIndex = colourRule[4];
		var r2 = colourRule[5];
		var g2 = colourRule[6];
		var b2 = colourRule[7];
		
		if ((index >=  lowerIndex) && (index <= upperIndex))
		{
			// Get the difference between the upper and lower indexes.
			var range =  upperIndex - lowerIndex;

			// Get the difference between the index and lower index.
			var diff =  index - lowerIndex;

			// Get the percentage of the range
			var percRange = diff / range;

			// Get the difference between the upper and lower color values
			var diffRed = r2 - r1;
			var diffGreen = g2 - g1;
			var diffBlue = b2 - b1;

			// Get the colour values.
			var  r = r1 + Math.round(percRange * diffRed);
			var  g = g1 + Math.round(percRange * diffGreen);
			var  b = b1 + Math.round(percRange * diffBlue);

			// Create the colour.
			colour = "fill:rgb("+r+","+g+","+b+");";

			// Break out of loop when colour is found.
			break;
		}
      	}
	return colour;
}

// Mouse-event functions for map.
function over(evt,code)
{
	currentStyle = evt.getTarget().getAttribute("style");
	var code = evt.target.getAttribute("id");
	overMap(code);
	overTable(code);
	overChart(code);
	overLegend(code) 
}

function out(evt)
{
	var code = evt.target.getAttribute("id");
	outMap(code);
	outTable(code)
	outChart(code);
	outLegend(code) 
}

function select(evt)
{

}

// Called on mouseover events.
function overMap(code) 
{
	if(svgMap.getElementById(code) != null)svgMap.getElementById(code).setAttribute("style",highlightStyle);
}

function overTable(code) 
{
	if(svgTable.getElementById(code) != null)svgTable.getElementById(code).setAttribute("stroke-width", "2");

}

function overChart(code) 
{
	if(svgChart.getElementById(code) != null)svgChart.getElementById(code).setAttribute("style",highlightStyle);
}

function overLegend(code) 
{
	var value;

	if(svgLegend != null)
	{
		for (i=0; i<AREAID.length; i++) 
		{ 
			if(AREAID[i] == code)
			{
				value = dataArray[i];
				break;
			}
		}

		var legendPosition = legendY  + parseInt(legendHeight - (legendHeight * ((value - minValue) / range)));
		legendHighlight = svgLegend.createElement("rect");
		legendHighlight.setAttribute("x", legendX);
		legendHighlight.setAttribute("y", legendPosition - 1);
		legendHighlight.setAttribute("width", legendWidth + 4);
		legendHighlight.setAttribute("height", 2);
		legendHighlight.setAttribute("class", "legendHighlight");
		legendHighlight.setAttribute("id", "legendHighlight");
		svgLegend.getDocumentElement().appendChild(legendHighlight);
		
		var textData = svgLegend.createTextNode(value);
		legendHighlightText = svgLegend.createElement("text");
		legendHighlightText.setAttribute("x", legendX + legendWidth + 5);
		legendHighlightText.setAttribute("y", legendPosition + 3);
		legendHighlightText.setAttribute("class", "legendHighlightText");
		legendHighlightText.setAttribute("id", "legendHighlightText");
		legendHighlightText.appendChild(textData);
		svgLegend.getDocumentElement().appendChild(legendHighlightText);
	}
}

// Called on mouseout events
function outMap(code) 
{
	if(svgMap.getElementById(code) != null)svgMap.getElementById(code).setAttribute("style",currentStyle);
}

function outTable(code) 
{
	if(svgTable.getElementById(code) != null)svgTable.getElementById(code).setAttribute("stroke-width", "0");
} 

function outChart(code) 
{
	if(svgChart.getElementById(code) != null)svgChart.getElementById(code).setAttribute("style",currentStyle);
} 

function outLegend(code) 
{
	if(svgLegend.getElementById('legendHighlight') != null)
	{
		targetGroup = svgLegend.getElementById('legendHighlight');
		targetGroup.getParentNode().removeChild(targetGroup);
		targetGroup = svgLegend.getElementById('legendHighlightText');
		targetGroup.getParentNode().removeChild(targetGroup);
	}	
} 


// Sorts the data by value.
function sortArray(arrayObj)
{
	for(i = 0; i < dataArray.length; i++)
	{	 
		sortedData[i] = dataArray[i];
		sortedId[i] = AREAID[i];
		sortedName[i] = AREANAME[i];
	}
	
	for(x = 0; x < sortedData.length; x++) 
	{
		for(y = 0; y < (sortedData.length-1); y++) 
		{
			if(sortedData[y] > sortedData[y+1]) 
			{
				holder = sortedData[y+1];
				sortedData[y+1] = sortedData[y];
				sortedData[y] = holder;
				
				temp = sortedId[y+1];
				sortedId[y+1] = sortedId[y];
				sortedId[y] = temp;
				
				temp = sortedName[y+1];
				sortedName[y+1] = sortedName[y];
				sortedName[y] = temp;	
			}
		}
	}
}

// Builds the legend.
function buildLegend(svgDoc)
{
	if (svgDoc.getElementById('legend') != null)
	{
		targetGroup = svgDoc.getElementById('legend');
		targetGroup.getParentNode().removeChild(targetGroup);
	}

	// Element used to hold the legend.
	var legend = svgDoc.createElement("g");
	legend.setAttribute("id", "legend");
	svgDoc.documentElement.appendChild(legend);
	
	var rect = svgDoc.createElement("rect");
	rect.setAttribute("x", legendX);
	rect.setAttribute("y", legendY);
	rect.setAttribute("width", legendWidth);
	rect.setAttribute("height", legendHeight);
	rect.setAttribute("class", "legendRect");
	legend.appendChild(rect);
	
	// Display the min and max values.
	var chartText = svgDoc.createElement("g");
	chartText.setAttribute("id", "chartText");
	svgDoc.documentElement.appendChild(chartText);
		
	var minRound = Math.round(minValue*100)/100;
	var textData = svgDoc.createTextNode(minRound);
	text = svgDoc.createElement("text");
	text.setAttribute("x", legendX + legendWidth + 5);
	text.setAttribute("y", legendY + legendHeight + 3);
	text.setAttribute("class", "legendText")
	text.appendChild(textData);
	legend.appendChild(text);

	var maxRound = Math.round(maxValue*100)/100;
	var textData = svgDoc.createTextNode(maxRound);
	text = svgDoc.createElement("text");
	text.setAttribute("x", legendX + legendWidth + 5);
	text.setAttribute("y", legendY + 3);
	text.setAttribute("class", "legendText")
	text.appendChild(textData);
	legend.appendChild(text);
}

// Colours the legend.
function colourLegend()
{
	if (svgLegend.getElementById('legendGradient') != null)
	{
		var legendGradient = svgLegend.getElementById("legendGradient")
		while( (ch = legendGradient.firstChild) != null ) {
			legendGradient.removeChild(ch)
		}
		
		var legendGradient = svgLegend.getElementById("legendGradient")

		for (j=0; j<colourTable.length; j++) 
		{ 
			var colourRule = colourTable[j];
			var stop = svgLegend.createElement("stop");

			offset = parseInt(((colourRule[0]-minValue) / range) * 100);
			stop.setAttribute("offset", offset + "%")

			var r = colourRule[1];
			var g = colourRule[2];
			var b = colourRule[3];
			var style = "stop-color:rgb("+r+","+g+","+b+");stop-opacity:1";
			stop.setAttribute("style",style)

			legendGradient.appendChild(stop)

			if(j == (colourTable.length - 1))
			{
				var stop = svgLegend.createElement("stop");
				stop.setAttribute("offset","100%")

				var colourRule = colourTable[j];
				var r = colourRule[5];
				var g = colourRule[6];
				var b = colourRule[7];
				var style = "stop-color:rgb("+r+","+g+","+b+");stop-opacity:1";
				stop.setAttribute("style",style)
				legendGradient.appendChild(stop)
			}
		}
	}
}

// Builds the table.
function buildTable(svgDoc, idArray, nameArray, dataArray)
{
	if (svgDoc.getElementById('table') != null)
	{
		targetGroup = svgDoc.getElementById("table");
		targetGroup.getParentNode().removeChild(targetGroup);
   	}
   	
	// Add a group element to hold the table.
	var table = svgDoc.createElement("g");
	table.setAttribute("id", "table");
	svgDoc.getDocumentElement().appendChild(table);

	var cellWidth = tableNameColWidth + tableDataColWidth;
	var cellY = tableY;
	var noCells = 1;
	
	cellY = cellY + tableCellHeight;
	nRows = 0;
	for (i=0; i<dataArray.length; i++) 
	{ 
		var code = idArray[i];

		// Create the cell.
		cellX = tableX;
		var cell = svgDoc.createElement("rect");
		cell.setAttribute("x", cellX);
		cell.setAttribute("y", cellY);
		cell.setAttribute("width", cellWidth);
		cell.setAttribute("height", tableCellHeight);
		cell.setAttribute("class", "table");
		cell.setAttribute("stroke-width", "0");
		cell.setAttribute("id", code);

		var zone = svgMap.getElementById(code);
		var over = zone.getAttribute("onmouseover");
		var out = zone.getAttribute("onmouseout");
		var select = zone.getAttribute("onclick");
		cell.setAttribute("onmouseover",over);
		cell.setAttribute("onmouseout",out);
		cell.setAttribute("onclick",select);

		// Add the name column.
		textX = cellX + tableMoveTextX;
		textY = cellY + tableMoveTextY;
		var textData = svgDoc.createTextNode(nameArray[i]);
		var text = svgDoc.createElement("text");
		text.setAttribute("x", textX);
		text.setAttribute("y", textY);
		text.setAttribute("class", "tableText")
		text.appendChild(textData);
		table.appendChild(text);

		// Add the data column.
		cellX = cellX + tableNameColWidth;
		textX = cellWidth;

		// Get the value and test for decimal places.
		var value = Math.round(dataArray[i]*100)/100;
		value = value + '';
		hasDecimal = value.indexOf('.');
		if (hasDecimal == -1){
			value = value + '.0';
		}
		while (value.indexOf('.') >= (value.length - 2)) {
			value += '0';
		}

		textData = svgDoc.createTextNode(value);
		text = svgDoc.createElement("text");
		text.setAttribute("x", textX);
		text.setAttribute("y", textY);
		text.setAttribute("class", "tableValue")
		text.appendChild(textData);
		table.appendChild(text);

		// Add the cell last so it can respond to mouse events.
		table.appendChild(cell);

		// Move to next row.
		cellY = cellY + tableCellHeight;

		noCells = noCells + 1;
		nRows++;
	} 	
	
	// Background.
	var r = svgDoc.createElement("rect");
	r.setAttribute("x", tableX);
	r.setAttribute("y", tableY);
	r.setAttribute("rx", 2);
	r.setAttribute("ry", 2);
	r.setAttribute("width", cellWidth);
	r.setAttribute("height", tableCellHeight*noCells);
	r.setAttribute("class", "tableRect");
	r.setAttribute("id", "chartRect");
	table.appendChild(r);
	
	var nameArrow = svgDoc.getElementById("nameArrow");
	var transX = tableX + 2;
	var transY = tableY + 2;
	nameArrow.setAttribute("transform", "translate(" + transX + "," + transY + ")");
	
	var valueArrow = svgDoc.getElementById("valueArrow");
	var transX = tableX + cellWidth - 13;
	var transY = tableY + 2;
	valueArrow.setAttribute("transform", "translate(" + transX + "," + transY + ")");
	createScrollButtons(svgDoc);
}

// Builds the bar chart.
function buildBarChart(svgDoc)
{
	if (svgDoc.getElementById('barChart') != null)
	{
		targetGroup = svgDoc.getElementById("barChart");
		targetGroup.getParentNode().removeChild(targetGroup);
   	}

	// Values for scaling chart chartBars.
	var multiplier = chartHeight / range;
		
	var chartBarWidth = chartWidth / sortedData.length;
	var chartBarHeight;
	var chartBarX = 0;
	var chartBarY = 0;
	var transY = chartHeight + chartY

	// Group element used to invert the chart.
	var chart = svgDoc.createElement("g");
	chart.setAttribute("id", "barChart");
	chart.setAttribute("transform", "translate("+chartX+","+transY+") scale(1,-1)");
	svgDoc.documentElement.appendChild(chart);
	
	// Create the chart bars.
	for (i=0; i<sortedData.length; i++) 
	{ 
		chartBarHeight = multiplier * (sortedData[i] - minValue);
		var code = sortedId[i];
		
		var chartBar = svgDoc.createElement("rect");
		chartBar.setAttribute("x", chartBarX);
		chartBar.setAttribute("y", chartBarY);
		chartBar.setAttribute("width", chartBarWidth);
		chartBar.setAttribute("height", chartBarHeight);
		chartBar.setAttribute("class", "chartBar");	
		chartBar.setAttribute("id", code);
		
		var zone = svgMap.getElementById(code);
		var over = zone.getAttribute("onmouseover");
		var out = zone.getAttribute("onmouseout");
		var select = zone.getAttribute("onclick");
		chartBar.setAttribute("onmouseover",over);
		chartBar.setAttribute("onmouseout",out);
		chartBar.setAttribute("onclick",select);
		
		chart.appendChild(chartBar);
		chartBarX = chartBarX + chartBarWidth;
	} 
}

// Builds the map.
function buildMap(svgDoc, x, y, width, height) 
{ 
	// Set map pixel dimensions.
	map = svgDoc.getElementById("map");
	map.setAttribute("x", x);
	map.setAttribute("y", y);
	map.setAttribute("width", width);
	map.setAttribute("height", height);
	
	var copyright = svgDoc.getElementById('copyrightText');
	copyright.setAttribute('x', (x + 10) + 'px');
	copyright.setAttribute('y', (y + height - 10) + 'px');
	copyright.setAttribute('font-family', 'Verdana,Arial,sans-serif');
	copyright.setAttribute('font-size', '10px');

	// Set the map to full extents..
	mapFullExtent = map.getAttribute("viewBox");
	var values = mapFullExtent.split(" ");
	mapViewBoxX = parseFloat(values[0]);
	mapViewBoxY = parseFloat(values[1]);
	mapViewBoxWidth = parseFloat(values[2]);
	mapViewBoxHeight = parseFloat(values[3]);

	// Used for clipping the map.
	var mapClip = svgDoc.getElementById("mapClip"); 
	mapClip.setAttribute("x", x);
	mapClip.setAttribute("y", y);
	mapClip.setAttribute("width", width);
	mapClip.setAttribute("height", height)
	mapClip.setAttribute("rx", 12);
	mapClip.setAttribute("ry", 12);

	// Map border.
	var mapBorder = svgDoc.getElementById("mapBorder"); 
	mapBorder.setAttribute("x", x - 16);
	mapBorder.setAttribute("y", y - 16);
	mapBorder.setAttribute("rx", 30);
	mapBorder.setAttribute("ry", 30);
	mapBorder.setAttribute("width", width + 32);
	mapBorder.setAttribute("height", height + 32);
	
	// Map background.
	var mapBackground = svgDoc.getElementById("mapBackground"); 
	mapBackground.setAttribute("x", x - 16);
	mapBackground.setAttribute("y", y - 16);
	mapBackground.setAttribute("rx", 30);
	mapBackground.setAttribute("ry", 30);
	mapBackground.setAttribute("width", width + 32);
	mapBackground.setAttribute("height", height + 32);
	
	// Map Tools
	var toolBarRect = svgDoc.getElementById("toolBarRect")
	toolBarRect.setAttribute("width", 30);
	toolBarRect.setAttribute("height", 90);
	
	var toolBar = svgDoc.getElementById("toolBar")
	transX = x + width - 22;
	transY = y + 30;
	toolBar.setAttribute("transform", "translate(" + transX + "," + transY + ")");
	
	// Display the tool bar.
	showTools();
	
	// Map arrows.
	svgDoc.getElementById("arrows").setAttribute("visibility", "visible");
	var southEastArrow = svgDoc.getElementById("southEast")
	var northEastArrow = svgDoc.getElementById("northEast")
	var southWestArrow = svgDoc.getElementById("southWest")
	var northWestArrow = svgDoc.getElementById("northWest")
	var northArrow = svgDoc.getElementById("north")
	var westArrow = svgDoc.getElementById("west")
	var eastArrow = svgDoc.getElementById("east")
	var southArrow = svgDoc.getElementById("south")
	var majorArrowAdjustment = 8; 
	var minorArrowAdjustment = 0;

	transX = x + width + minorArrowAdjustment;
	transY = y + height + minorArrowAdjustment;
	southEastArrow.setAttribute("transform", "translate(" + transX + "," + transY + ") rotate(315,0,0)");

	transX = x + width + minorArrowAdjustment;
	transY = y - minorArrowAdjustment;
	northEastArrow.setAttribute("transform", "translate(" + transX + "," + transY + ") rotate(225,0,0)");

	transX = x - minorArrowAdjustment;
	transY = y + height + minorArrowAdjustment;
	southWestArrow.setAttribute("transform", "translate(" + transX + "," + transY + ") rotate(45,0,0)");

	transX = x -  minorArrowAdjustment;
	transY = y - minorArrowAdjustment;
	northWestArrow.setAttribute("transform", "translate(" + transX + "," + transY + ") rotate(135,0,0)");

	transX = x + (width/2);
	transY = y - majorArrowAdjustment;
	northArrow.setAttribute("transform", "translate(" + transX + "," + transY + ") rotate(180,0,0)");

	transX = x - majorArrowAdjustment;
	transY = y + (height/2);
	westArrow.setAttribute("transform", "translate(" + transX + "," + transY + ") rotate(90,0,0)");

	transX = x + width + majorArrowAdjustment;
	transY = y + (height/2);
	eastArrow.setAttribute("transform", "translate(" + transX + "," + transY + ") rotate(270,0,0)");

	transX = x + (width/2);
	transY = y + height + majorArrowAdjustment;
	southArrow.setAttribute("transform", "translate(" + transX + "," + transY + ")");
	
	var hint = svgMap.getElementById("hint");
	transX = x;
	transY = y + height + 30;
	hint.setAttribute("transform", "translate(" + transX + "," + transY + ")");
}

// Increase the rendering quality of the map.
function increaseMapQuality()
{
	var mapGroup = svgMap.getElementById("mapGroup")
	mapGroup.setAttribute("shape-rendering", "auto");
	
	if(showMapping == false)
	{
		//var backgroundMapping = svgMap.getElementById("backgroundMapping")
		//backgroundMapping.setAttribute("visibility", "visible");
		
		var zones = svgMap.getElementById("zones")
		zones.setAttribute("fill-opacity", "0.7");
	}
}

// Decresase the rendering quality of the map.
function decreaseMapQuality()
{
	var mapGroup = svgMap.getElementById("mapGroup")
	mapGroup.setAttribute("shape-rendering", "optimizeSpeed");
	
	//var backgroundMapping = svgMap.getElementById("backgroundMapping")
	//backgroundMapping.setAttribute("visibility", "hidden");
	
	var zones = svgMap.getElementById("zones")
	zones.setAttribute("fill-opacity", "1");
}

// Sets the viewbox.
function setViewBox(viewBox)
{	
	values = mapFullExtent.split(" ");
	fullExtentViewBoxWidth = parseFloat(values[2]);
	var oldViewBox =  mapViewBoxX + " " + mapViewBoxY + " " + mapViewBoxWidth + " " + mapViewBoxHeight;
	var oldStrokeWidth = mapViewBoxWidth / fullExtentViewBoxWidth;
	
	// Set viewBos variables.
	var values = viewBox.split(" ");
	mapViewBoxX = parseFloat(values[0]);
	mapViewBoxY = parseFloat(values[1]);
	mapViewBoxWidth = parseFloat(values[2]);
	mapViewBoxHeight = parseFloat(values[3]);
	
	// Map animation.
	var animation = svgMap.getElementById("setViewBox");
	var values = oldViewBox +";"+ viewBox;
	animation.setAttribute("values", values);
	animation.beginElement();
	
	// Set the new viewbox.
	var newViewBox = mapViewBoxX + " " + mapViewBoxY + " " + mapViewBoxWidth + " " + mapViewBoxHeight;
	map.setAttribute("viewBox", newViewBox);
	
	// Handle stroke thickness of the zones.
	var newStrokeWidth = mapViewBoxWidth / fullExtentViewBoxWidth;
	var animation = svgMap.getElementById("setStrokeWidth");
	animation.setAttribute("from", oldStrokeWidth*0.8);
	animation.setAttribute("to", newStrokeWidth*0.8);
}

// Scales the map.
function scale(scaleX, scaleY)
{
	var coords = getMapCoords(scaleX, scaleY);
	var realX = coords[0];
	var realY = coords[1];

	var x2 = mapWidth - scaleX;
	var y2 = mapHeight - scaleY;
	var coords = getMapCoords(x2, y2);
	var realX2 = coords[0];
	var realY2 = coords[1];
	
	var realWidth = realX2 - realX;
	var realHeight = realY2 - realY;
	
	var viewBox = realX + " " + realY + " " + realWidth + " " + realHeight;
	setViewBox(viewBox);
}

// Translates the map.
function translate(transX, transY)
{ 
	var x = mapViewBoxX - transX;
	var y = mapViewBoxY - transY;
	var viewBox = x + " " + y + " " + mapViewBoxWidth + " " + mapViewBoxHeight;
	setViewBox(viewBox);
} 

// Moves the map in the given direction.
function pan(dir)
{
	var transX = mapViewBoxWidth * 0.25;
	var transY = mapViewBoxHeight * 0.25;
	var negTransX = transX * -1;
	var negTransY = transY * -1;

	if (dir == 'north') translate(0,transY);
	else if (dir == 'south') translate(0,negTransY);
	else if (dir == 'east') translate(negTransX,0);
	else if (dir == 'west') translate(transX,0);
	else if (dir == 'northWest') translate(transX,transY);
	else if (dir == 'northEast') translate(negTransX,transY);
	else if (dir == 'southWest') translate(transX,negTransY);
	else if (dir == 'southEast') translate(negTransX,negTransY);
}

// Zooms in.
var zooming;
function zoomIn()
{
	var scaleX = mapWidth * 0.25;
	var scaleY = mapHeight * 0.25;		
	scale(scaleX, scaleY);
}

// Zooms out.
function zoomOut()
{
	var scaleX = (mapWidth * 0.25) * -1;
	var scaleY = (mapHeight * 0.25) * -1;
	scale(scaleX, scaleY);
}

// Zooms to full extent.
function zoomToFullExtent()
{
	setViewBox(mapFullExtent);
}

// Zooms to a bbox.
function zoomToBBox(id)
{	
	if(id == "No filter")
	{
		zoomToFullExtent();
	}
	else
	{
		var poly = map.getElementById(id);
		var bbox = poly.getBBox();
		var viewBox = bbox.x + " " + bbox.y + " " + bbox.width + " " + bbox.height;
		setViewBox(viewBox);
	}
}

// Zooms to a rect.
function zoomToRect(rect)
{	
	var x = rect.getAttribute("x");
	var y = rect.getAttribute("y");
	var width = rect.getAttribute("width");
	var height = rect.getAttribute("height");
	
	var viewBox = x + " " + y + " " + width + " " + height;
	setViewBox(viewBox);
}

// Functions for zoom to user defined rectangle.
var zoomRect;
var acetate;
var doZoom = false;
var zoomX1;
var zoomY1;

function zoomDown(evt)
{
	if(mapViewBoxWidth > 0.1)
	{
		var x = evt.clientX - mapX;
		var y = evt.clientY - mapY;
		var coords = getMapCoords(x, y);
		zoomX1 = coords[0];
		zoomY1 = coords[1];

		if(zoomRect != null && zoomRect.getParentNode() != null)
			zoomRect.getParentNode().removeChild(zoomRect);
			
		zoomRect = svgMap.createElement("rect");
		zoomRect.setAttribute("x", zoomX1);
		zoomRect.setAttribute("y", zoomY1);
		zoomRect.setAttribute("width", 0);
		zoomRect.setAttribute("height", 0);
		zoomRect.setAttribute("id", "zoomRect");
		zoomRect.setAttribute("class", "zoomRect");
		zoomRect.setAttribute("onmousemove", "zoomMove(evt);");
		zoomRect.setAttribute("onmouseup", "zoomUp();");
		
		animateZoomRect = svgMap.createElement("animate");
		animateZoomRect.setAttribute("attributeName", "fill-opacity");
		animateZoomRect.setAttribute("attributeType", "XML");
		animateZoomRect.setAttribute("dur", "1");
		animateZoomRect.setAttribute("from", "0.4");
		animateZoomRect.setAttribute("to", "0");
		animateZoomRect.setAttribute("fill", "freeze");
		animateZoomRect.setAttribute("begin", "indefinate");
		zoomRect.appendChild(animateZoomRect);
		map.appendChild(zoomRect);
		
		addAcetate();
		
		doZoom = true;
	}
}

function zoomMove(evt)
{
	if(doZoom)
	{
		var x = evt.clientX - mapX;
		var y = evt.clientY - mapY;
		var coords = getMapCoords(x, y);
		var zoomX2 = coords[0];
		var zoomY2 = coords[1];
		
		var rectX;
		var rectY;
		var rectWidth;
		var rectHeight;

		if(zoomX1 < zoomX2)
		{
			rectX = zoomX1;
			rectWidth = zoomX2 - zoomX1;
		}
		else
		{
			rectX = zoomX2;
			rectWidth = zoomX1 - zoomX2;
		}
		if(zoomY1 < zoomY2)
		{
			rectY = zoomY1;
			rectHeight = zoomY2 - zoomY1;
		}
		else
		{
			rectY = zoomY2;
			rectHeight = zoomY1 - zoomY2;
		}

		zoomRect.setAttribute("x", rectX);
		zoomRect.setAttribute("y", rectY);
		zoomRect.setAttribute("width", rectWidth);
		zoomRect.setAttribute("height", rectHeight);
	}
}

function zoomUp()
{
	var width = zoomRect.getAttribute("width");
	var height =  zoomRect.getAttribute("height");
	if(width > 0.05  && height > 0.05)
	{
		zoomToRect(zoomRect);
		animateZoomRect.beginElement();
		setTimeout("removeAcetate();",1000);
	}
	else
	{
		removeAcetate();
	}
		
	doZoom = false;
}

function addAcetate()
{
	if(svgMap.getElementById("acetate") == null)
	{
		acetate = svgMap.createElement("rect");
		acetate.setAttribute("x", mapX);
		acetate.setAttribute("y", mapY);
		acetate.setAttribute("width", mapWidth);
		acetate.setAttribute("height", mapHeight);
		acetate.setAttribute("onmousemove", "zoomMove(evt);");
		acetate.setAttribute("onmouseup", "zoomUp();");
		acetate.setAttribute("onmousedown", "zoomDown(evt);");
		acetate.setAttribute("id", "acetate");
		acetate.setAttribute("class", "acetate");
		svgMap.getDocumentElement().appendChild(acetate);
	}
}

function removeAcetate()
{	
	if(svgMap.getElementById("acetate")  != null)
		acetate.getParentNode().removeChild(acetate);
	if(svgMap.getElementById("zoomRect")  != null)
		zoomRect.getParentNode().removeChild(zoomRect);
}

// Returns pixel coords as map coords.
function getMapCoords(x, y)
{
	var scaleY = mapViewBoxHeight / mapHeight;
	var scaleX = mapViewBoxWidth / mapWidth;
	var newX;
	var newY;
	
	if(scaleY > scaleX)
	{
		var adjustedWidth = scaleY * mapWidth
		var adjustedX = mapViewBoxX - ((adjustedWidth - mapViewBoxWidth) / 2)
		newX = adjustedX + (adjustedWidth * (x / mapWidth));
		newY = mapViewBoxY + (mapViewBoxHeight * (y / mapHeight));
	}
	else if(scaleX > scaleY)
	{
		var adjustedHeight = scaleX * mapHeight;
		var adjustedY = mapViewBoxY - ((adjustedHeight - mapViewBoxHeight) / 2)
		newX = mapViewBoxX + (mapViewBoxWidth * (x / mapWidth));
		newY = adjustedY + (adjustedHeight * (y / mapHeight));	
	}
	else
	{
		newX = mapViewBoxX + (mapViewBoxWidth * (x / mapWidth))
		newY = mapViewBoxY + (mapViewBoxHeight * (y / mapHeight));
	}
	
	var coords = new Array(newX, newY);
	return coords;
}

// Called by tool mouseover.
function overTool(svgDoc, id, hint)
{ 
	svgDoc.getElementById(id).setAttribute('style', toolHighlightStyle);
	setHint(hint);
}

// Called by tool mouseout.
function outTool(svgDoc, id, hint)
{ 
	svgDoc.getElementById(id).setAttribute('style', "");
	setHint(hint);
}

// Sets the Hint.
function setHint(textString)
{
	var hint = svgMap.getElementById("hint");
	var myText = svgMap.createTextNode(textString);
	hint.removeChild(hint.getChildNodes().item(0));
	hint.appendChild(myText);
}

// Clears the Hint.
function clearHint()
{
	setHint("")
}

// Populates a list.
function populateThemeList(listName, arrayValue, arrayText) 
{
   	var listObj = document.forms['mapSettings'].elements[listName]; 
	
	// Clear out the previous list.
	clearOptions(listObj);

	for (i=0; i<arrayValue.length; i++) 
	{ 
		addToOptionList(listObj, arrayValue[i], arrayText[i]);
	}	
}

// Populates a list.
function populateIndicatorList(listName, arrayValue) 
{
   	var listObj = document.forms['mapSettings'].elements[listName]; 
	
	// Clear out the previous list.
	clearOptions(listObj);

	for (i=0; i<arrayValue.length; i++) 
	{ 
		
		for (j=0; j<IID.length; j++) 
		{ 
			var indicatorID = IID[j];
			var indicatorName = INAME[j];
			
			if(indicatorID == arrayValue[i])
			{
				addToOptionList(listObj, indicatorID, indicatorName);
			}
		}
	}	
}

function populateColourSchemeList(listName, arrayText) 
{
   	var listObj = document.forms['mapSettings'].elements[listName]; 
	
	// Clear out the previous list.
	clearOptions(listObj);

	for (i=0; i<arrayText.length; i++) 
	{ 
		addToOptionList(listObj, i, arrayText[i]);
	}	
}

// Clears an option list.
function clearOptions(OptionList) 
{
	// Always clear an option list from the last entry to the first
	for (x = OptionList.length; x >= 0; x = x - 1)
	{
		OptionList[x] = null;
	}
}

// Populates an option list.
function addToOptionList(OptionList, OptionValue, OptionText) 
{
	// Add option to the bottom of the list
	OptionList[OptionList.length] = new Option(OptionText, OptionValue);
}

// Returns the minimum value in the data array.
function getMinValue(arrayObj)
{
	var value = 9999999999;
	for (i=0; i<arrayObj.length; i++) 
	{ 
		if (arrayObj[i] < value)
		{
			value = arrayObj[i];
		}
	}
	
	var value = Math.round(value*100)/100;
	return value;
}

// Returns the maximum value in the data array.
function getMaxValue(arrayObj)
{
	var value = -9999999999;
	for (i=0; i<arrayObj.length; i++) 
	{ 
		if (arrayObj[i] > value)
		{
			value = arrayObj[i];
		}
	}
	
	var value = Math.round(value*100)/100;
	return value;
}

// Displays the tool bar.
function showTools()
{
	var tools = svgMap.getElementById("tools");
	var showTools = svgMap.getElementById("showTools")
	var flipArrow = svgMap.getElementById("flipArrow");
	var moveArrow = svgMap.getElementById("moveArrow");

	flipArrow.setAttribute("from", flipArrow.getAttribute("to"));
	flipArrow.setAttribute("to", "-1 1");
	moveArrow.setAttribute("from", moveArrow.getAttribute("to"));
	moveArrow.setAttribute("to", "6 0");				

	flipArrow.beginElement();
	moveArrow.beginElement();
	showTools.beginElement()

	var toolBarButton = svgMap.getElementById("toolBarButton");
	toolBarButton.setAttribute("onclick","hideTools()");

	var moveToolBar = svgMap.getElementById("moveToolBar");
	moveToolBar.setAttribute("from", moveToolBar.getAttribute("to"));
	moveToolBar.setAttribute("to", "5 0");
	moveToolBar.beginElement();
}

// Hides the tool bar.
function hideTools()
{

	var tools = svgMap.getElementById("tools");
	var hideTools = svgMap.getElementById("hideTools")
	var flipArrow = svgMap.getElementById("flipArrow");
	var moveArrow = svgMap.getElementById("moveArrow");

	flipArrow.setAttribute("from", flipArrow.getAttribute("to"));
	flipArrow.setAttribute("to", "1 1");
	moveArrow.setAttribute("from", moveArrow.getAttribute("to"));
	moveArrow.setAttribute("to", "0 0");

	flipArrow.beginElement();
	moveArrow.beginElement();
	hideTools.beginElement()

	var toolBarButton = svgMap.getElementById("toolBarButton");
	toolBarButton.setAttribute("onclick","showTools()");
	
	var moveToolBar = svgMap.getElementById("moveToolBar");	
	moveToolBar.setAttribute("from", "5 0");
	moveToolBar.setAttribute("to", "30 0");
	moveToolBar.beginElement();
}


function popupNotes() {
	if (!notes) {
		alert('No notes available');
	}
	else {
		var w = window.open();
		w.document.open();
		w.document.writeln('<html><head><title>Notes</title>');
		w.document.writeln('<link href="./style.css" rel="styleSheet" type="text/css" />');
		w.document.writeln('<link href="./user.css" rel="styleSheet" type="text/css" />');
		w.document.writeln('</head>');
		w.document.writeln('<body>');
		w.document.write('<div class="banner">		<div id="userHeading">');
		w.document.write(userHeadingText);
		w.document.writeln('</div></div>');
		w.document.writeln('<div class="page"><table width="100%" cellspacing="0" cellpadding="5" border="1">');
		w.document.writeln('<tr><th>Note</th><th>About</th><th>Value</th></tr>');
		for (var i = 0; i < noteEntries.length; i += 3) {
			w.document.write('<tr><td>');
			w.document.write(noteEntries[i]);
			w.document.write('</td><td>');
			w.document.write(noteEntries[i + 1]);
			w.document.write('</td><td>');
			if ((noteEntries[i + 2].substring(0, 7) == 'http://') || (noteEntries[i + 2].substring(0, 4) == 'www.')){
				w.document.write('<a href="');
				if (noteEntries[i + 2].substring(0, 4) == 'www.')
					w.document.write('http://');
				w.document.write(noteEntries[i + 2]);
				w.document.write('">');
				w.document.write(noteEntries[i + 2]);
				w.document.write('</a>');
			}
			else {
				w.document.write(noteEntries[i + 2]);
			}
			w.document.writeln('</td></tr>');
		}
		w.document.writeln('</table></div></body></html>');
		w.document.close()
		w.focus();
	}
}

var cellsOffsetX = 0;
var cellsOffsetY = 0;
var repeat = false;
var accelerator = 1.1;
function createScrollButtons(svgDoc) {
	if ((nRows * tableCellHeight) > 500) {
		var upBtn = svgDoc.createElement('g');
		upBtn.setAttribute('onclick', 'scroll(\'s\');');
		var a = svgTable.createElement('a');
		var arrow = svgTable.createElement('path');
		arrow.setAttribute('d', 'M-1,-9S0,-10 1,-9L4,-2S5,-1 4,0L-4,0S-5,-1 -4,-2z');
		arrow.setAttribute('class', 'tableArrow');
		a.appendChild(arrow);
		upBtn.appendChild(a);
		upBtn.setAttribute('transform', 'translate(296 10)');
		svgDoc.documentElement.appendChild(upBtn);
		var downBtn = svgDoc.createElement('g');
		downBtn.setAttribute('onclick', 'scroll(\'n\');');
		a = svgTable.createElement('a');
		arrow = svgTable.createElement('path');
		arrow.setAttribute('d', 'M-1,-9S0,-10 1,-9L4,-2S5,-1 4,0L-4,0S-5,-1 -4,-2z');
		arrow.setAttribute('class', 'tableArrow');
		arrow.setAttribute('transform', 'scale(1 -1)');
		a.appendChild(arrow);
		downBtn.appendChild(a);
		downBtn.setAttribute('transform', 'translate(296 480)');
		svgDoc.documentElement.appendChild(downBtn);
	}
}
function scroll(dir) 
{
	if ((dir == 'n') || (dir == 's')) {
		if (dir == 'n') {
			if ((nRows * tableCellHeight) > 500) {
				cellsOffsetY -= 10;
			}
			if (cellsOffsetY < ((-1 * (nRows * tableCellHeight)) + tableCellHeight)) {
				cellsOffsetY = (-1 * (nRows * tableCellHeight)) + tableCellHeight;
			}
		}
		else {
			cellsOffsetY += 10;
			if (cellsOffsetY > 0) {
				cellsOffsetY = 0;
			}
		}
		//var g = svgTable.getElementById('rows');
		//g.setAttribute('transform', 'translate(0,' + cellsOffsetY + ')');					
		//g = svgTable.getElementById('cells');
		//g.setAttribute('transform', 'translate(' + cellsOffsetX + ',' + cellsOffsetY + ')');
		var g = svgTable.getElementById('table');
		g.setAttribute('transform', 'translate(0,' + cellsOffsetY + ')');					
	}
	else if ((dir == 'e') || (dir == 'w')) {
		if (dir == 'e') {
			cellsOffsetX -= 10;
			/*if (cellsOffsetX < ((-1 * (nRows * 25)) + 25)) {
				cellsOffsetX = (-1 * (nRows * 25)) + 25;
			}*/
		}
		else {
			cellsOffsetX += 10;
			if (cellsOffsetX > 0) {
				cellsOffsetX = 0;
			}
		}
		var g = svgTable.getElementById('headers');
		g.setAttribute('transform', 'translate(' + cellsOffsetX + ',0)');
		g = svgTable.getElementById('cells');
		g.setAttribute('transform', 'translate(' + cellsOffsetX + ',' + cellsOffsetY + ')');
	}
	if (repeat) {
		setTimeout('scroll(\'' + dir + '\',true)', Math.round(200.0 / accelerator));
		accelerator = accelerator * accelerator;
	}
}