/*
 * Copyright IPVision, Inc 2003 - .   All rights reserved.
 */


function UILegendGroupManager(entityMap, windowId)
{
	if(arguments.length == 1 && arguments[0] == UI_PROTO)
		return;

	this.uiLegendGroupManagerInit(entityMap, windowId);
}

// Inherit member functions and default member values from base class
UILegendGroupManager.prototype = UiPrototype(UIElement);

// Initialize default member values
UILegendGroupManager.prototype.classId = "uiLegendGroupManager";

UILegendGroupManager.prototype.uiLegendGroupManagerInit = function(entityMap, windowId)
{
	this.uiElementInit();
	this.entityMap = entityMap ? entityMap : {};
	this.windowId = windowId;
	this.legendGroup = entityMap.LegendGroup ? entityMap.LegendGroup : [];
	this.selectedLegendIndex = (this.legendGroup && this.legendGroup.length ? 0 : -1);
	this.selectedUiLegendGroup = null;
}
//--------------------------------------------------------------------------

UILegendGroupManager.prototype.build2 = function()
{
	this.addHTML('<div id="' + this.domElemId + '">');
	this.buildInner();
	this.addHTML('</div>');
}

UILegendGroupManager.prototype.build = function()
{
//	DebugText("UILegendGroupManager.prototype.buildInner ")

	this.addHTML('<table width="100%">');
	this.addHTML('<tr><td style="padding: 8px">');

	this.addHTML('<tr><td>');
	this.addHTML('<font class="title">Select Legend:&nbsp;');
	this.addHTML('<div id="' + (this.domElemId + ".selectDiv") + '">' + this.buildSelectorHtml() + '</div>');
	this.addHTML('<tr><td style="padding-top: 10px; padding-bottom: 10px;">');
	this.addButton("Edit Legend ...", "", "editLegend()", this);
	this.addHTML('&nbsp;&nbsp;')
	this.addButton("Add Legend ...", "", "addLegend()", this);
	this.addHTML('&nbsp;&nbsp;')
	this.addButton("Delete Legend", "", "deleteLegend()", this);
	this.addHTML('&nbsp;&nbsp;')
	this.addButton("Set as Default", "", "defaultToSelectedLegend()", this);
	this.addHTML('&nbsp;&nbsp;')
	this.addButton("Update Map", "", "doAction('mapUpdateLegend')", window);
	this.addHTML('<hr style="margin-top: 10px; margin-bottom: 5px;"/>')

	this.addHTML('<tr><td id="' + this.domElemId + '">');
	if(this.selectedLegendIndex > -1) {
		this.selectedUiLegendGroup = new UILegendGroup(this.legendGroup, this.selectedLegendIndex, this.windowId);
		this.addHTML(this.selectedUiLegendGroup.getHTML());
	}
	this.addHTML('</table>');
}

UILegendGroupManager.prototype.buildSelectorHtml = function()
{
	var html = new Array(this.legendGroup.length)
	for(var n = 0; n < this.legendGroup.length; n++)
		html[n] = '<option value="' + n + '" ' + (n == this.selectedLegendIndex ? "selected" : "")
					+ '>&nbsp;' + ToXmlText(this.legendGroup[n].title) + '</option>';

	return '<select name="' + (this.domElemId + ".select") + '" style="width: 24em;" '
	            + 'onChange="GetUiElem(' + this.id + ').selectLegend(this.selectedIndex);">'
				+ html.join("") + '</select>';
}


UILegendGroupManager.prototype.updateSelector = function()
{
	// IE defect - can't replace the <option>s of a <select>.  Must replace entire <select>.
	GetDomElem(this.domElemId + ".selectDiv").innerHTML = this.buildSelectorHtml();
}

//--------------------------------------------------------------------------
UILegendGroupManager.prototype.selectLegend = function(selectedLegendIndex)
{
	ForgetUiElem(this.selectedUiLegendGroup);
	this.selectedLegendIndex = selectedLegendIndex;

	if(selectedLegendIndex >= 0) {
		this.selectedUiLegendGroup = new UILegendGroup(this.legendGroup, this.selectedLegendIndex, this.windowId);
		GetDomElem(this.domElemId).innerHTML = this.selectedUiLegendGroup.getHTML();
	}
	else {
		this.selectedUiLegendGroup = null;
		GetDomElem(this.domElemId).innerHTML = "";
	}
}


UILegendGroupManager.prototype.addLegend = function()
{
	index = this.appendLegendData("New Legend", []);
	this.selectLegend(index)
	this.updateSelector();
	this.editLegend();
}

UILegendGroupManager.prototype.appendLegendData = function(title, items)
{
	if(this.legendGroup == null)
		this.entitiyMap.LegendGroup = this.legendGroup = [];

	var index = this.legendGroup.length;
	this.legendGroup[index] = {mType: "LegendGroup", title: title, xOffset: 0, yOffset: 0, LegendItem: items};
	return index;
}

UILegendGroupManager.prototype.deleteLegend = function()
{
	var index = this.selectedLegendIndex;
	if(index >= 0) {
		this.legendGroup.splice(index,1);
		this.selectLegend(index < this.legendGroup.length ? index : index-1);
		this.updateSelector();
	}
}

UILegendGroupManager.prototype.editLegend = function()
{
	if(this.selectedUiLegendGroup)
		this.selectedUiLegendGroup.editLegend();
}

UILegendGroupManager.prototype.defaultToSelectedLegend = function()
{
	if(this.selectedLegendIndex == -1)
		return;
	for(var n = 0; n < this.legendGroup.length; n++)
		this.legendGroup[n].isDisabled = (this.selectedLegendIndex == n) ? "false" : "true";
}

//--------------------------------------------------------------------------

UILegendGroupManager.prototype.addSelectedItemsToLegend = function(renderCd, entitySet, selectedLegendIndex)
{
	if(!this.legendGroup || this.legendGroup.length == 0)
		selectedLegendIndex = this.appendLegendData("New Legend", []);

	if(typeof selectedLegendIndex != "number") {
		selectedLegendIndex = 0;
		if(this.legendGroup.length > 1) {
			text = "Which MapAnalysis Group you want to append.\n\n";
			for(var n=0;  n < this.legendGroup.length;  n++)
				text += (n + ".  " + this.legendGroup[n].title + "\n");
			text += "\nType in the number at the next prompt."
			alert(text)
			selectedLegendIndex = prompt("Type in number of MapAnalysis Group to append.", selectedLegendIndex);

		}
		selectedLegendIndex = Math.max(0, Math.min(selectedLegendIndex,this.legendGroup.length-1));
	}

	ForgetUiElem(this.selectedUiLegendGroup);
	this.selectedLegendIndex = selectedLegendIndex;
	this.selectedUiLegendGroup = new UILegendGroup(this.legendGroup, this.selectedLegendIndex, this.windowId);
	this.selectedUiLegendGroup.addLegendItem(renderCd, entitySet);
	var domElem = GetDomElem(this.domElemId);
	if(domElem)
		domElem.innerHTML = this.selectedUiLegendGroup.getHTML();
}

//--------------------------------------------------------------------------

UILegendGroupManager.prototype.getAccentedEntities = function(uiMap)
{
	var uidHash = uiMap.getEntityUidHash();
	var uidUsed = new Array(uidHash.length);
	var uidsAccented = [];

	for(var n = 0; n < this.legendGroup.length; n++) {
		var legend = this.legendGroup[n];
		if(legend.isDisabled == "true")
			continue;

		var items = legend.LegendItem;
		for(var m = 0; m < items.length; m++) {
			var item = legend.LegendItem[m];
			if(item.isDisabled == "true" || !this.isRenderAccent(item.renderCd))
				continue;

			var uidsTemp = PipeSetToArray(item.entitySet);
			for(var k=0;  k < uidsTemp.length;  k++) {
				var index = uidHash[uidsTemp[k]];
				if(index != undefined && !uidUsed[index]) {
					uidsAccented.push(uidsTemp[k]);
					uidUsed[index] = true;
				}
			}
		}
	}
	return uidsAccented;
}

//--------------------------------------------------------------------------

UILegendGroupManager.prototype.isRenderAccent = function(renderCd)
{
	var hash = UILegendGroupManager.prototype.renderAccentHash;

	if(!hash) {
		hash = new Array();
		for(var n = 0; n < GC.ACCENT_RENDER_CD.length; n++)
			hash[GC.ACCENT_RENDER_CD[n]] = true;
		UILegendGroupManager.prototype.renderAccentHash = hash;
	}
	return hash[renderCd];
}

//===========================================================================

function UILegendGroup(legendGroup, iLegend, windowId)
{
	if(arguments.length == 1 && arguments[0] == UI_PROTO)
		return;

	this.uiLegendGroupInit(legendGroup, iLegend, windowId);
}

// Inherit member functions and default member values from base class
UILegendGroup.prototype = UiPrototype(UIElement);

// Initialize default member values
UILegendGroup.prototype.classId = "uiLegendGroup";
UILegendGroup.prototype.renderOptions = GC.ALL_RENDER_CD;

// Initialize the instance specific member variables
UILegendGroup.prototype.uiLegendGroupInit = function(legendGroup, iLegend, windowId)
{
	this.uiElementInit();
	this.legendGroup = legendGroup;     // Array of legend groups
	this.iLegend = iLegend;             // Index of the legend that this UI object will handle
	this.windowId = windowId;
	this.uiTable = null;
}

//--------------------------------------------------------------------------

UILegendGroup.prototype.build = function()
{
//	DebugText("UILegendGroup.prototype.build iLegend = " + this.iLegend)

	lg = this.legendGroup[this.iLegend];
	this.addHTML('<table id="' + this.domElemId + '"><tr width="100%"><td>');
	this.addHTML('<font class="title">' + lg.title);
	this.addHTML(',&nbsp;&nbsp;xOffset: ' + lg.xOffset + ',&nbsp;&nbsp;yOffset: ' + lg.yOffset );
	this.addHTML(', &nbsp&nbsp;Default render: ' + (lg.defaultRenderCd ? lg.defaultRenderCd : 'none'));

	this.makeUiTable();
	this.addHTML('<tr><td>' + this.uiTable.getHTML());

	this.addHTML('<tr><td class="bgLightShade">');
	this.addButton("Edit Row...", "margin: 6;", "editLegend('editSelected')", this);
	this.addButton("Add Row...", "margin: 6; margin-right: ", "addLegendItem('halo')", this);
	this.addButton("Delete Rows...", "margin: 6; margin-right: ", "deleteRows()", this);

	var selectId = this.domElemId + '.select';
	this.addHTML('<span  style="vertical-align: 20%; margin-left: 1in;"><font class="title">Rendering:&nbsp;</span>');
	this.addSelect(selectId, this.renderOptions, lg.renderCd, "width: 7em; vertical-align: 5%;", '');
	this.addButton("Change Selected", "margin: 6;  float: top;", 'changeRenderCd()', this);
	this.addHTML('</table>')
}

//--------------------------------------------------------------------------

UILegendGroup.prototype.makeUiTable = function()
{
	var display = {showTitle: false, number: false, sort: false, select: true, columns: []};
	var table = this.legendGroupToTable();
	ForgetUiElem(this.uiTable)

	this.uiTable = new UIBasicTable(table, display);
}

//--------------------------------------------------------------------------

UILegendGroup.prototype.legendGroupToTable = function()
{
	var table = {title: this.legendGroup[this.iLegend].title};
	table.ColumnDefs = [    {label: "Label", type: "string"},
							{label: "Rendering", type: "string", subType: "renderCd"},
							{label: "Color", type: "string", subType: "color"},
							{label: "IDs", name: "", type: "entitySet", subType: "multi"},
							{label: "Count", type: "string" },
							{label: "In Map", type: "string"},
							{label: "Disabled", type: "string"}];

	var items = this.legendGroup[this.iLegend].LegendItem;

	table.Rows = new Array(items.length);
	for(var k = 0; k < items.length; k++)
		table.Rows[k] = [items[k].label, items[k].renderCd, items[k].color, items[k].entitySet,
				items[k].entityCount, items[k].entityInMapCount, items[k].isDisabled];

	return table;
}
//--------------------------------------------------------------------------

var legendInfo;

UILegendGroup.prototype.addLegendItem = function(renderCd, entitySet)
{
	var legendGroup = CloneObject(this.legendGroup[this.iLegend]);
	var items = legendGroup.LegendItem;
	var item = {mType: "LegendItem", label: "", color: "", renderCd: renderCd, entitySet: entitySet};

	for(var property in items[0]) {
		if(typeof item[property] == undefined)
			item[property] = "";
	}
	items.push(item)

	var legendInfo = { uiLegendGroup: this, legendGroup: legendGroup, iItem: items.length-1};
	this.editLegendDialog(legendInfo);
}

UILegendGroup.prototype.editLegend = function(mode)
{
	var legendInfo = { uiLegendGroup: this, legendGroup: CloneObject(this.legendGroup[this.iLegend]), iItem: 0};
	if(mode == "editSelected") {
		var rowNumber = this.getSelectedRowNumbers();
		legendInfo.iItem = (rowNumber == null) ? 0 : rowNumber[0];
	}
	this.editLegendDialog(legendInfo);
}

UILegendGroup.prototype.editLegendDialog = function(legendInfo)
{
	legendInfo.ts = new Date().getMilliseconds()
	window.legendInfo = legendInfo;     // Dialog will access opener.legendInfo
	var editLegendDialog = window.open("/Dialog/EditLegend.act", this.windowId, "scrollbars,  resizable, width=600, height=620");
	if(editLegendDialog)
		editLegendDialog.focus();
}

UILegendGroup.prototype.editLegendDone = function(cmd)
{
	var items = this.legendGroup[this.iLegend].LegendItem;
	var itemsNew = legendInfo.legendGroup.LegendItem;

	for(var n = 0; n < items.length; n++) {
		if(items[n].entitySet != itemsNew[n].entitySet)
			itemsNew[n].entityCount = itemsNew[n].entityCountInMap = "";
	}

	this.legendGroup[this.iLegend] = legendInfo.legendGroup;

	this.resetHTML();
	domElem = GetDomElem(this.domElemId);
	if(domElem)
		domElem.parentNode.innerHTML = this.getHTML()

	if(cmd == "updateMap")
		setTimeout("doAction('mapUpdateLegend')", 100);
}

//--------------------------------------------------------------------------

UILegendGroup.prototype.deleteRows = function()
{
	var rowNumber = this.getSelectedRowNumbers(true);
	if(rowNumber == null || !confirm("Will delete row" + (rowNumber.length > 1 ? "s " : " " ) + rowNumber.join(", ")))
		return;

	var legend = this.legendGroup[this.iLegend];
	var items = legend.LegendItem;
	legend.LegendItem = [];

	for(var n = 0, m = 0; n < items.length; n++) {
		if(n == rowNumber[m])
			m++;
		else
			legend.LegendItem.push(items[n]);
	}

	this.makeUiTable();
	this.resetHTML();
	domElem = GetDomElem(this.domElemId).parentNode
	domElem.innerHTML = this.getHTML()
}

//--------------------------------------------------------------------------

UILegendGroup.prototype.changeRenderCd = function()
{
	var rowNumber = this.getSelectedRowNumbers(true);
	if(rowNumber == null)
		return;

	var items = this.legendGroup[this.iLegend].LegendItem;
	var renderCd = GetDomElem(this.domElemId + '.select').value;

	for(var k = 0; k < rowNumber.length; k++)
		items[rowNumber[k]].renderCd = renderCd;

	this.makeUiTable();
	this.resetHTML();
	domElem = GetDomElem(this.domElemId).parentNode
	domElem.innerHTML = this.getHTML()
}

//--------------------------------------------------------------------------

UILegendGroup.prototype.getSelectedRowNumbers = function(multiple)
{
	var rowNumber = this.uiTable.getSelectedRowNumbers();
	if(rowNumber.length == 0) {
		alert("No rows are selected");
		return null;
	}

	if(rowNumber.length > 1 && !multiple)
		alert("Only one row may be selected");

	return rowNumber;
}

//--------------------------------------------------------------------------

UILegendGroup.prototype.doAction = function(cmd, arg)
{
	doAction(cmd, arg)
}

//--------------------------------------------------------------------------

UILegendGroup.prototype.addSelect = function(selectId, options, selectedValue, style, onChange)
{
	if(onChange)
		onChange = 'onChange="uiLegendGroupSelectHandler(this,event,' + this.id + ',' + JsString(onChange) + ')"';

	this.addHTML('<select id="' + selectId + '" style="' + (style ? style : '') + '" ' + onChange + '>');

	for(var k = 0; k < options.length; k++)
	{
		var optionAttrib = 'value="' + options[k] + '" ';
		if(selectedValue && options[k] == selectedValue)
			optionAttrib += 'selected '
		this.addHTML('<option ' + optionAttrib + '>' + options[k] + '</option>');
	}

	this.addHTML('</select>');
}

function uiLegendGroupSelectHandler(selectDomElem, event, targetId, action)
{
	UiCancelEvent(event);
	action = action.replace('$1', '"' + selectDomElem.value + '"');
	eval('GetUiElem(' + targetId + ').' + action);
}


UILegendGroupManager.prototype.getHTML2 = function()
{
	DebugText("Get HTML for UILegendGroupManager");
	this.getHTML2 = UIElement.prototype.getHTML;
	return this.getHTML2();
}


UILegendGroup.prototype.getHTML2 = function()
{
	DebugText("Get HTML for UILegendGroup " + this.iLegend);
	this.getHTML2 = UIElement.prototype.getHTML;
	return this.getHTML2();
}

//===========================================================================

function UIMapSettings(entityMap)
{
	if(arguments.length == 1 && arguments[0] == UI_PROTO)
		return;

	// Assume no subclasses, so skip the uiMapSettingsInit() approach
	this.uiWidgetInit();
	this.entityMap = entityMap;
	this.mapSettings = entityMap.MapSettings;
	this.statCount = this.entityMap.EntityGroup ? this.entityMap.EntityGroup.length : 0;
}

// Inherit member functions and default member values from base class
UIMapSettings.prototype = UiPrototype(UIWidget);

// Initialize default member values
UIMapSettings.prototype.classId = "uiMapSettings";

//--------------------------------------------------------------------------

UIMapSettings.prototype.build = function()
{
	var ms = this.mapSettings;
	this.addHTML('<div style="padding-left: 10px"><font class="uiTableHead">Change Map Settings</font><br/>');
	this.addHTML('<table cols=4 class="uiFrame">');
	this.addHTML('<tr width="100%"><td><font style="vertical-align: top" class="title">Map Title:&nbsp;</td><td width="100%" colspan=3>')
	this.addHTML('<textarea id="mapTitle" rows="3" style="width: 100%">' + ms.title + '</textarea></td></tr>');

	this.buildInput("Title Font Size", "titleFontSize", 3, ms.titleFontSize);
	this.buildInput("Sub Title Font Size", "subTitleFontSize", 3, ms.subTitleFontSize);
	this.buildTag('Selected Items Color');
	this.buildColorSelector('<td>', "selectedItemsColor", "lightBlue", '</td></tr>');
	this.buildTag('Border Color');
	this.buildColorSelector('<td>', "borderColor", ms.borderColor, '</td></tr>');
	this.buildInput('Border Width', "borderWidthPct" , 3, ms.borderWidthPct, "%");
	this.buildInput('Cluster Legend X Offset', "layerLegendXOffset", 3, ms.layerLegendXOffset);
	this.buildInput('Cluster Legend Font Scale',"layerLegendFontScale", 3 ,ms.layerLegendFontScale);

	this.addHTML('</table><br/>');
	this.addHTML('<table width="100%"><tr><td colspan="4" align="left"><font class="title">Show the following statistics:<hr/>');

	for(var n=0; n < this.statCount; n++) {
		var ss = ms.StatSettings[n];
		var isShown = ss.isShown == "true" ? "checked" : ""
		var isKeyed = ss.isKeyed == "true" ? "checked" : "";
		var description = entityMap.EntityGroup[n].description;

		this.addHTML('<tr>');
		this.addHTML('<td style="vertical-align: top">&nbsp;&nbsp;&nbsp;<input id="isShown' + n + '" type="checkbox"' + isShown + '>' + description + '</input></td>');
		this.addHTML('<td>X Offset:&nbsp;<input id="xOffset' + n + '" size="3" value="' + ss.xOffset + '"></input></td>');
		this.addHTML('<td>Y Offset:&nbsp;<input id="yOffset' + n + '" size="3" value="' + ss.yOffset + '"></input></td>');

		if(description.indexOf("All") == 0 || description == "Attributes")
			this.addHTML('<td></td>');
		else
			this.addHTML('<td><input id="isKeyed' + n + '" type="checkbox" onclick="GetUiElem(' + this.id + ').doRadioButtons(' + n + ')"' + isKeyed + '>Color Keyed</input></td>');

		this.addHTML('</tr>');
	}

	this.addHTML('</table><hr/>')
	this.addHTML('<table><tr><td colspan=2 align="center">');
	this.addHTML('<input type="button" onclick="GetUiElem(' + this.id + ').updateMapSettings(' + n + ')" value="Update Settings"></input>');
	this.addHTML('</table></div>');
}

UIMapSettings.prototype.buildInput = function(label, domElemId, size, value, text)
{
	this.buildTag(label);
	this.addHTML('<td><input id="' + domElemId + '" size="' + size + '" value="' + value + '">' + (text ? text : "") + '</td></tr>');

}
UIMapSettings.prototype.buildTag = function(label)
{
	this.addHTML('<tr><td nowrap><font class="title">' + label + ':&nbsp;&nbsp;&nbsp;</td>')
}
//--------------------------------------------------------------------------

UIMapSettings.prototype.buildColorSelector = function(pre, domElemId, defaultColor, post)
{
	this.addHTML(pre + '<select id="' + domElemId + '" style="width: 120;">');

	var colors = gRes.palette.colors;
	for(var n in colors) {
		var color = colors[n].name;
		this.addHTML('<option style="background: #' + colors[n].rgbHex + '" value="' + color + '"');
		if(color == defaultColor)
			this.addHTML(' selected ');
		this.addHTML('>' + color + '</option>');
	}
	this.addHTML('</select>' + post);
}

//--------------------------------------------------------------------------

UIMapSettings.prototype.updateMapSettings = function()
{
	var mapUpdate = {mName: "MapUpdate"};
	mapUpdate.title = document.getElementById('mapTitle').value;
	mapUpdate.titleFontSize = GetFloat("titleFontSize",0);
	mapUpdate.subTitleFontSize = GetFloat("subTitleFontSize", 0);
	mapUpdate.borderColor = document.getElementById('borderColor').value;
	mapUpdate.borderWidthPct = GetFloat("borderWidthPct", 0);
	mapUpdate.LayerLegend = { xOffset: GetFloat("layerLegendXOffset", 30), fontScale: GetFloat("layerLegendFontScale", 1.4) };

    mapUpdate.statIsShown = new Array(this.statCount);
    mapUpdate.statXOffset = new Array(this.statCount);
    mapUpdate.statYOffset = new Array(this.statCount);
	for(var n = 0; n < this.statCount; n++)
	{
		var isShown = document.getElementById('isShown' + n);
		var isKeyed = document.getElementById('isKeyed' + n);
		mapUpdate.statIsShown[n] = isShown.checked ? GC.TRUE : GC.FALSE;
		if((isKeyed != null) && isKeyed.checked)
			mapUpdate.keyStat = n;
        mapUpdate.statXOffset[n] = document.getElementById('xOffset' + n).value;
        mapUpdate.statYOffset[n] = document.getElementById('yOffset' + n).value;
    }

	doAction("updateMapSettings", mapUpdate);
}

function GetFloat(domElemId, defaultValue)
{
	var value = parseFloat(GetDomElem(domElemId).value);
	if(isNaN(value)) {
		alert("Warning:  '" + value + "' is not a number, using " + defaultValue);
		value = defaultValue;
	}
	return String(value)
}

//--------------------------------------------------------------------------

UIMapSettings.prototype.doRadioButtons = function(n)
{
	var isKeyed = document.getElementById('isKeyed' + n);
	if(!isKeyed.checked)
		return;

	var isShown = document.getElementById('isShown' + n);
	if(!isShown.checked) {
		isKeyed.checked = false;
		return;
	}

	for(var k = 0; k < this.statCount; k++) {
		if(k == n)
			continue;
		var isKeyed = document.getElementById('isKeyed' + k);
		if(isKeyed)
			isKeyed.checked = false;
	}
}