// unit object
function Unit(unit_type, number) 
{
	this.unit_type = unit_type;
	this.number = number;
	this.comments = "";
}

// magic path object
function Magic_path(path, level)
{
	this.path = path;
	this.level = level;
}

// commander object (include units, items, magic path, etc ...)
function Commander(unit_type)
{
	this.unit_type = unit_type;

	this.comments = "";
	
	this.comname = "";
	this.clearmagic = false;
	this.magic_paths = new Array();
	this.xp = null;
	this.randomequip = null;
	
	// there should be only one set of bodyguards, but in case I misunderstood the command, 
	// better be prepared with an array anyway
	this.bodyguards = new Array();
	this.units = new Array();
	this.items = new Array();
}

// selection of province/neighbour(s)
// -- if no province is selected : select the province
// -- if the province was already selected : unselect it
// -- if the province was not selected, but another province was, 
// -- make the province a neighbour of the selected one.
// -- if the province was already a neighbour of the selected province, remove
// -- the neighbour connexion
function select_province(province_id)
{
	// get current selected province (if any)
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// -- if no province is selected : select the province
	if (selected_province_id == "" && province_id != null && province_id != "")
	{
		// now change class of the selected province, and mark it as selected
		document.getElementById('selected_province_id').value = province_id;
		document.getElementById("province_" + province_id + "_position").className= 'province_selected';
		
		// show the neighbours
		var neightbours = get_province_neighbours(province_id);
		for (var i = 0; i < neightbours.length; i++)
		{
			document.getElementById("province_" + neightbours[i] + "_position").className= 'neighbour';
		}
		
		// show the province info panel
		var scrOfX = 0, scrOfY = 0;
		var x; var y;
		if( typeof( window.pageYOffset ) == 'number' ) 
		{
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		}
		else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ))
		{
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		}else	if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ))
		{
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		// get mouse position, in pixels relative top top-left of screen
		/*
		if (document.all)  // IE
		{
			x = window.event.clientX + scrOfX;
			y = window.event.clientY + scrOfY;
		}
		else 
		{
			x = e.clientX + scrOfX;
			y = e.clientY + scrOfY;
		}
		*/
		document.getElementById("province_infos").style.display = "block";
		document.getElementById("province_infos").style.left = scrOfX;
		document.getElementById("province_infos").style.top = scrOfY;
	}
	else if (province_id == null || province_id == "" || selected_province_id == province_id)
	{
		// -- if the province was already selected (or no province id has been provided : unselect it
		document.getElementById('selected_province_id').value = ""; // province no longer selected
		
		if (selected_province_id != null && selected_province_id != "")
		{
			// unselect the neighbours of the province
			var previous_neightbours = get_province_neighbours(selected_province_id);
			for (var i = 0; i < previous_neightbours.length; i++)
			{
				document.getElementById("province_" + previous_neightbours[i] + "_position").className= 'province';
			}
		
			// mark the province as unselected
			document.getElementById("province_" + selected_province_id + "_position").className= 'province';
			
			// hide the province info panel
			document.getElementById("province_infos").style.display = "none";
		}
	}
	else
	{	
		// -- the province was not selected, but another province was, 
		
		if (document.getElementById("province_" + province_id + "_position").className == "neighbour")
		{
			// -- the province was already a neighbour of the selected province
			// -- => remove the neighbour connexion
			remove_neighbour(province_id, selected_province_id);
			document.getElementById("province_" + province_id + "_position").className = "province";
		}
		else
		{
			// -- make the province a neighbour of the selected one.
			add_neighbour(province_id, selected_province_id);
			document.getElementById("province_" + province_id + "_position").className = "neighbour";
		}
	}
	
	// update selected province values.
	update_province_values();
}

// update province description and values depending on the selected province
// *** OBSOLETE ***
function update_province_values_old()
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// reset terrain types selection
	var terrain_types_list = get_all_terrain_types();
	for (var i = 0; i < terrain_types_list.length; i++)
	{
		document.getElementById("tt_" + terrain_types_list[i]).checked = false;
	}
	
	// reset commanders list
	current_commander = new Commander();
	document.getElementById("province_commanders").innerHTML = "";
	
	// reset features
	document.getElementById("province_features").innerHTML = "";
	
	if (document.getElementById("province_" + selected_province_id) != null) // province exists
	{
		// get the XML code of the province
		var province_xml = document.getElementById("province_" + selected_province_id).value;
		var dom_province = parse_xml_string(province_xml);
	
		// --------------------------------------------------
		// Province general infos
		// --------------------------------------------------
		
		// province custom name
		var landname = dom_province.documentElement.getAttribute("landname");
		if (landname != null && landname != "")
		{
			document.getElementById("landname").value = landname;
		}
		else
		{
			document.getElementById("landname").value = "- random name -";
		}
		
		// province custom population type
		var poptype = dom_province.documentElement.getAttribute("poptype");
		if (poptype != null && poptype != "")
		{
			document.getElementById("poptype").value = poptype;
		}
		else
		{
			document.getElementById("poptype").value = " - ";
		}
	
		// kill poptype units ?
		var killpop = dom_province.documentElement.getAttribute("killpop");
		if (killpop != null && killpop != "")
		{
			document.getElementById("killpop").checked = true;
		}
		else
		{
			document.getElementById("killpop").checked = false;
		}
	
		// --------------------------------------------------
		// Terrain Types
		// --------------------------------------------------

		// update province terrain types
		var terrain_types = get_terrain_types(selected_province_id);
		for (var i = 0; i < terrain_types.length; i++)
		{
			var type = terrain_types[i];
			document.getElementById("tt_" + type).checked = true;
		}	
		
		// --------------------------------------------------
		// Features
		// --------------------------------------------------
		
		// kill previous features ?
		var killfeatures = dom_province.documentElement.getAttribute("killfeatures");
		if (killfeatures != null && killfeatures != "")
		{
			document.getElementById("killfeatures").checked = true;
		}
		else
		{
			document.getElementById("killfeatures").checked = false;
		}
		
		// get DOM features list
		var dom_features = dom_province.getElementsByTagName("features");
		if (dom_features.length == 0)
		{
			// create a new feature block
			var feature_block = document.createElement('DIV');
			feature_block.className = "desert_button padding_h";

			// add the DIV to the html features list
			document.getElementById("province_features").appendChild(feature_block);
			
			var txt = document.createTextNode("-none-");
			feature_block.appendChild(txt);
		}
		else
		{
			for (var i = 0; i < dom_features.length; i++)
			{
				var feature = dom_features[i];	// current feature
				
				// create a new feature block
				var feature_block = document.createElement('DIV');
				feature_block.className = "desert_button padding_h";
				// set the feature block id
				feature_block.id = "feature_" + i;
				// add the DIV to the html features list
				document.getElementById("province_features").appendChild(feature_block);
				
				var feature_name = feature.getAttribute("name");
				var feature_known = feature.getAttribute("known");
				if (feature_known != null && feature_known == "1")
				{
					var txt = document.createTextNode(feature_name + " (known)");
					feature_block.appendChild(txt);
				}
				else
				{
					var txt = document.createTextNode(feature_name);
					feature_block.appendChild(txt);
				}
			}
		}
		
		// --------------------------------------------------
		// Commanders and Units
		// --------------------------------------------------

		// get DOM commander list
		var dom_commanders = dom_province.getElementsByTagName("commanders");
		
		// extract the list of commanders from the DOM into the commanders array (gloabl , so no "var" to localise the Array)
		if (dom_commanders.length == 0)
		{
			// create a new feature block
			var commander_block = document.createElement('DIV');
			commander_block.className = "desert_button padding_h";
			
			var txt = document.createTextNode("-none-");
			commander_block.appendChild(txt);
			
			// add the DIV to the html features list
			document.getElementById("province_commanders").appendChild(commander_block);
		}
		else
		{
			for (var i = 0; i < dom_commanders.length; i++)
			{
				// convert the dom node into a commander object
				var commander = commander_dom_to_object(dom_commanders[i])
				// create a new commander DIV
				var commander_block = document.createElement('DIV');
				commander_block.className = "text_background";
				// add the DIV to the html commander list
				document.getElementById("province_commanders").appendChild(commander_block);			
				// set the ID of the div
				commander_block.id = "commander_" + i;
				// commander name (if any)
				var comname = document.createElement('DIV');
				comname.className = "desert_button padding_h";
				commander_block.appendChild(comname);
				if (commander["comname"] != null && commander["comname"] != "")
				{
					var txt = document.createTextNode(commander["comname"]);
					comname.appendChild(txt);
				}
				else
				{
					var txt = document.createTextNode("Commander " + i);
					comname.appendChild(txt);
				}
				// commander unit type
				var unit_type = document.createElement('DIV');
				unit_type.className = "padding_h";
				commander_block.appendChild(unit_type);
				var unit_type_txt = document.createTextNode("Unit : " + commander["unit_type"]);
				unit_type.appendChild(unit_type_txt);
				// commander XP
				var xp = document.createElement('DIV');
				xp.className = "padding_h";
				commander_block.appendChild(xp);
				var xp_value = commander["xp"];
				if (xp_value == null)
				{
					xp_value = 0;
				}			
				var xp_txt = document.createTextNode("Xp: " + xp_value);
				xp.appendChild(xp_txt);
				// commander magic
				var magic = document.createElement('DIV');
				magic.className = "padding_h";
				commander_block.appendChild(magic);
				
				var magic_title = document.createElement('DIV');
				magic.appendChild(magic_title);
				if (commander["clearmagic"])
				{
					var txt = document.createTextNode("Magic (remove previous)");
					magic_title.appendChild(txt);
				}
				else
				{
					var txt = document.createTextNode("Magic (added to base)");
					magic_title.appendChild(txt);
				}
				
				var magic_paths = document.createElement('UL');
				magic.appendChild(magic_paths);
				if (commander["magic_paths"].length == 0)
				{
					var magic_infos = document.createElement('LI');
					
					var magic_string = "no custom magic";
					var magic_txt = document.createTextNode(magic_string);
					magic_infos.appendChild(magic_txt);
					magic_paths.appendChild(magic_infos);
				}
				else
				{
					for (var j = 0; j < commander["magic_paths"].length; j++)
					{
						var magic_infos = document.createElement('LI');
					
						var magic_string = commander["magic_paths"][j]["path"];
						magic_string +=	" " + commander["magic_paths"][j]["level"]
						
						var magic_txt = document.createTextNode(magic_string);
						magic_infos.appendChild(magic_txt);
						magic_paths.appendChild(magic_infos);
					}
				}
				
				// commander items
				var items = document.createElement('DIV');
				items.className = "padding_h";
				commander_block.appendChild(items);
				var items_string = "Items : ";
				if (commander["items"].length == 0)
				{
					items_string += "none";
				}
				else
				{
					items_string += commander["items"].join(",");
				}
				var items_txt = document.createTextNode(items_string);
				items.appendChild(items_txt);
				
				// commander units & bodyguards
				var commander_units_block = document.createElement('DIV');
				commander_units_block.className = "padding_h";
				commander_block.appendChild(commander_units_block);
				// -- commander bodyguards
				var bodyguards = document.createElement('UL');
				commander_units_block.appendChild(bodyguards);
				if (commander["bodyguards"].length == 0)
				{
					var bodyguards_infos = document.createElement('LI');
					
					var bodyguards_string = "no bodyguards";
					var bodyguard_txt = document.createTextNode(bodyguards_string);
					bodyguards_infos.appendChild(bodyguard_txt);
					bodyguards.appendChild(bodyguards_infos);
				}
				else
				{
					for (var j = 0; j < commander["bodyguards"].length; j++)
					{
						var bodyguards_infos = document.createElement('LI');
					
						var bodyguards_string = "Bodyguard(s) : ";
						bodyguards_string +=	commander["bodyguards"][j]["unit_type"]
						bodyguards_string +=	"(x" + commander["bodyguards"][j]["number"] +  ")";
						
						var bodyguard_txt = document.createTextNode(bodyguards_string);
						bodyguards_infos.appendChild(bodyguard_txt);
						bodyguards.appendChild(bodyguards_infos);
					}
				}
				// -- commander units
				var units = document.createElement('UL');
				commander_units_block.appendChild(units);
				if (commander["units"].length == 0)
				{
					var units_infos = document.createElement('LI');
					
					var units_string = "no units";
					var units_txt = document.createTextNode(units_string);
					units_infos.appendChild(units_txt);
					units.appendChild(units_infos);
				}
				else
				{
					for (var j = 0; j < commander["units"].length; j++)
					{
						var units_infos = document.createElement('LI');
					
						var units_string = "";
						units_string +=	commander["units"][j]["unit_type"]
						units_string +=	" (x" + commander["units"][j]["number"] +  ")";
						
						var units_txt = document.createTextNode(units_string);
						units_infos.appendChild(units_txt);
						units.appendChild(units_infos);
					}
				}
			}
		}
	}
}

// convert a commander from a dom nod object into a Commander object
function commander_dom_to_object(dom_commander)
{
	// create new commander object
	var commander = new Commander(dom_commander.getAttribute("unit_id"));
	
	// get any additionnal commander settings
	
	// -- commander name
	var comname = dom_commander.getAttribute("name");
	if (comname != null)
	{
		commander["comname"] = comname;
	}
	// -- random equipment ?
	var randomequip = dom_commander.getAttribute("randomequip");
	if (randomequip != null && randomequip != "")
	{
		commander["randomequip"] = randomequip;
	}
	// custom magic on this commander
	// -- reset existing magic paths ?
	var clearmagic = dom_commander.getAttribute("clearmagic");
	if (clearmagic != null && clearmagic == 1)
	{
		commander["clearmagic"] = true;
	}
	// -- fire magic
	var mag_fire = dom_commander.getAttribute("mag_fire");
	if (mag_fire != null)
	{
		commander["magic_paths"].push( new Magic_path("fire",  mag_fire) );
	}
	// -- air magic
	var mag_air = dom_commander.getAttribute("mag_air");
	if (mag_air != null)
	{
		commander["magic_paths"].push( new Magic_path("air",  mag_air) );
	}
	// -- earth magic
	var mag_earth = dom_commander.getAttribute("mag_earth");
	if (mag_earth != null)
	{
		commander["magic_paths"].push( new Magic_path("earth",  mag_earth) );
	}
	// -- water magic
	var mag_water = dom_commander.getAttribute("mag_water");
	if (mag_water != null)
	{
		commander["magic_paths"].push( new Magic_path("water",  mag_water) );
	}
	// -- astral magic
	var mag_astral = dom_commander.getAttribute("mag_astral");
	if (mag_astral != null)
	{
		commander["magic_paths"].push( new Magic_path("astral",  mag_astral) );
	}
	// -- death magic
	var mag_death = dom_commander.getAttribute("mag_death");
	if (mag_death != null)
	{
		commander["magic_paths"].push( new Magic_path("death",  mag_death) );
	}
	// -- nature magic
	var mag_nature = dom_commander.getAttribute("mag_nature");
	if (mag_nature != null)
	{
		commander["magic_paths"].push( new Magic_path("nature",  mag_nature) );
	}
	// -- blood magic
	var mag_blood = dom_commander.getAttribute("mag_blood");
	if (mag_blood != null)
	{
		commander["magic_paths"].push( new Magic_path("blood",  mag_blood) );
	}
	// -- holy (priest) magic
	var mag_priest = dom_commander.getAttribute("mag_priest");
	if (mag_priest != null)
	{
		commander["magic_paths"].push( new Magic_path("priest",  mag_priest) );
	}
	// Custom XP level
	var xp = dom_commander.getAttribute("xp");
	if (xp != null)
	{
		commander["xp"] = xp;
	}
	// commander bodyguards
	var dom_bodyguards = dom_commander.getElementsByTagName("bodyguards");
	for (var i = 0; i < dom_bodyguards.length; i++)
	{
		var bodyguards_unit_type = dom_bodyguards[i].getAttribute("unit_id");
		var bodyguards_number = dom_bodyguards[i].getAttribute("number");
		var bodyguards = new Unit(bodyguards_unit_type, bodyguards_number);
		commander["bodyguards"].push(bodyguards);
	}
	// commander units
	var dom_units = dom_commander.getElementsByTagName("units");
	for (var i = 0; i < dom_units.length; i++)
	{
		var unit_type = dom_units[i].getAttribute("unit_id");
		var number = dom_units[i].getAttribute("number");
		var unit = new Unit(unit_type, number);
		commander["units"].push(unit);
	}
	// commander items
	var dom_items = dom_commander.getElementsByTagName("items");
	for (var i = 0; i < dom_items.length; i++)
	{
		var item_name = dom_items[i].childNodes[0].nodeValue;
		commander["items"].push(item_name);
	}
	
	// return commander object
	return commander;
}

// get the list of terrain_types of the province
function get_terrain_types(province_id)
{
	var terrain_types = new Array();
	
	if (document.getElementById("province_" + province_id) != null) // province exists
	{
		// get the XML code of the province
		var province_xml = document.getElementById("province_" + province_id).value;
		// convert to DOM object
		var dom_terrain_types = parse_xml_string(province_xml).getElementsByTagName("terrain_types");
		// extract the list of terrain types from the DOM into the terrain_types array
		for (var i = 0; i < dom_terrain_types.length; i++)
		{
			terrain_types.push(dom_terrain_types[i].childNodes[0].nodeValue);
		}
	}
	
	return terrain_types;
}

// update the list of terrain types of a province, depending on what terrain types are checked
function update_terrain_types()
{
	var province_id = document.getElementById("selected_province_id").value;
	
	if (document.getElementById("province_" + province_id) == null)
	{
		// province does not exist ?
		return null;
	}
	
	var terrain_types = get_terrain_types(province_id);
	
	// get the XML code of the province
	var province_xml = document.getElementById("province_" + province_id).value;
	// convert to DOM object
	var dom_province = parse_xml_string(province_xml);

	// remove previous defined types
	var dom_terrain_types = dom_province.getElementsByTagName("terrain_types");
	for (var i = dom_terrain_types.length -1; i >= 0; i--)
	{
		parent_node = dom_terrain_types[i].parentNode;
		var deleted_node = parent_node.removeChild(dom_terrain_types[i]);
	}

	// Add the checked types
	var possible_terrain_types = get_all_terrain_types(); // list of all existing terrain types
	for (var i = 0; i < possible_terrain_types.length; i++) // for each possible terrain type, see if it has been checked
	{
		var current_type = possible_terrain_types[i];
		
		if (document.getElementById("tt_" + current_type) && document.getElementById("tt_" + current_type).checked) // checked
		{
			// create new "terrain_types" element
			var new_terrain_type = dom_province.createElement("terrain_types");
			// create the corresponding text value 
			var new_terrain_type_value =dom_province.createTextNode(current_type);
			// assign the value to the element
			new_terrain_type.appendChild(new_terrain_type_value);
			// add the terrain type to the province
			dom_province.documentElement.appendChild(new_terrain_type);
		}
	}
	
	// update the province xml
	var xml = xml_output(dom_province);
	document.getElementById("province_" + province_id).value = xml;
	
	// update_province_values();
}

// return the list of all existing terrain types
function get_all_terrain_types()
{
	var all_terrain_types = new Array(
																	"small",
																	"large",
																	"sea",
																	"somewater",
																	"mountain",
																	"swamp",
																	"waste",
																	"forest",
																	"farm",
																	"nostart",
																	"manysites",
																	"deep",
																	"cave",
																	"firesite",
																	"airsite",
																	"watersite",
																	"earthsite",
																	"astralsite",
																	"deathsite",
																	"naturesite",
																	"bloodsite",
																	"priestsite",
																	"edgemount"
																);
																
	return all_terrain_types;
}

// get the list of neighbours of the province
function get_province_neighbours(province_id)
{
	var province_neighbours = new Array();
	
	// get the XML code of the neighbours list
	var neighbours_xml = document.getElementById("neighbours").value;
	// convert to DOM object
	var neighbours = parse_xml_string(neighbours_xml).getElementsByTagName("anon");
	for (var i = 0; i < neighbours.length; i++)
	{
		if (neighbours[i].getAttribute('province_1') == province_id)
		{
			province_neighbours.push(neighbours[i].getAttribute('province_2'));
		}
		else if 	(neighbours[i].getAttribute('province_2') == province_id)
		{
			province_neighbours.push(neighbours[i].getAttribute('province_1'));
		}
	}
	
	return province_neighbours;
}

// remove a neighbour
function remove_neighbour(province_1, province_2)
{
	// get the XML code of the neighbours list
	var neighbours_xml = document.getElementById("neighbours").value;
	// convert to DOM object
	var neighbours_dom = parse_xml_string(neighbours_xml);
	var neighbours = neighbours_dom.getElementsByTagName("anon");
	
	for (var i = 0; i < neighbours.length; i++)
	{
		if (neighbours[i].getAttribute('province_1') == province_1 && neighbours[i].getAttribute('province_2') == province_2
				|| neighbours[i].getAttribute('province_2') == province_1 && neighbours[i].getAttribute('province_1') == province_2)
		{
			// neighbours connection found, delete it
			neighbours_dom.documentElement.removeChild(neighbours[i]);
			
			// TOPRORG : update the "neighbour_total attributes for both provinces
			
			// exit the loop
			break;
		}
	}
	
	// update the XML list of neighbours
	var xml = xml_output(neighbours_dom);
	document.getElementById("neighbours").value = xml;
}

// add a neighbour connection
function add_neighbour(province_1, province_2)
{
	// get the XML code of the neighbours list
	var neighbours_xml = document.getElementById("neighbours").value;
	// convert to DOM object
	var neighbours_dom = parse_xml_string(neighbours_xml);
	
	var new_neighbour = neighbours_dom.createElement('anon');
	new_neighbour.setAttribute("province_1", province_1);
	new_neighbour.setAttribute("province_2", province_2);
	// add the element
	neighbours_dom.documentElement.appendChild(new_neighbour);
	
	// TOPRORG : update the "neighbour_total attributes for both provinces
	
	// update the XML list of neighbours
	var xml = xml_output(neighbours_dom);
	document.getElementById("neighbours").value = xml;
}

// parse a XML string into a dom object
// -- should works will all recent browsers
function parse_xml_string(xml_string)
{
	// code for IE
	if (window.ActiveXObject)
	{
		var doc=new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(xml_string);
	}
	// code for Mozilla, Firefox, Opera, etc.
	else if (typeof DOMParser != 'undefined') 
	 {
		var parser=new DOMParser();
		var doc=parser.parseFromString(xml_string,"text/xml");
	}
	else
	{
		alert("Error : your browser seems to lack the required XML support. (maybe it's time to upgrade ?)");
	}

	// return root element
	return doc;
}

// serialize a DOM node (produce the XML code from a dom node/document
// -- the succession of "if/else if" if made to handle all browsers.
function xml_output (node) 
{
	if (typeof XMLSerializer != 'undefined') 
	{	return new XMLSerializer().serializeToString(node);	}
	else if (typeof node.xml != 'undefined')
	{	return node.xml;	}
	else if (typeof printNode != 'undefined') 
	{	return printNode(node);	}
	else 
	{
	    // seems like this browser doesn't handle XML serialization
	    alert("Error : your browser seems to lack the required XML support. (maybe it's time to upgrade ?)");
	}
}


/*
Dragging an element
*/

// start draging an element
function drag_start(e, elem_id)
{
	// element
	$element = document.getElementById(elem_id);

	// save initial  component position
	$prev_x = $element.style.left;
	$prev_y = $element.style.top;

	// while mouse button is down, continue to drag, else end
	if (document.all)  // IE
	{
		document.onmousemove=drag;
		document.onmouseup=drag_end;
	}
	else // other browsers
	{
		window.onmousemove=drag;
		window.onmouseup=drag_end;
	}
}


// stop moving the element
function drag_end(e)
{
	// drag mode is off
	if (document.all)
	{
		//R?initialisation du onmousemove
		document.onmousemove=null;
	}
	else
	{
		//R?initialisation du onmousemove
		window.onmousemove=null;
	}
}


// move and drag a div or other element
function drag(e)
{
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) 
	{
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	}
	else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ))
	{
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	}else	if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ))
	{
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	// get new position, in pixels relative top top-left of screen
	if (document.all)  // IE
	{
		$new_x = window.event.clientX + scrOfX;
		$new_y = window.event.clientY + scrOfY;
	}
	else 
	{
		$new_x = e.clientX + scrOfX;
		$new_y = e.clientY + scrOfY;
	}
	
	// add a small offset so the element is notdragged exactly from its top left point
	$new_x = $new_x - Math.round($element.offsetWidth / 2);
	$new_y = $new_y - 15;
	
	// ... but don't go so far that the element is so outside the screen that it cannot be dragged back in
	if ($new_x < -50)
	{
		$new_x  = 0;
	}
	if ($new_y < 0)
	{
		$new_y  = 0;
	}
	
	// change element position
	$element.style.left = $new_x;
	$element.style.top  = $new_y;
	
	
}

/* dragging : end */

// hide/show an element
function toggle(obj) 
{
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) 
	{
		el.style.display = 'none';
	}
	else 
	{
		el.style.display = '';
	}
}

// hide an element
function mask(elem)
{
	var elem = document.getElementById(elem);
	
	if (elem != null)
	{
		elem.style.display = "none";
	}
}

// show an element
function show(elem)
{
	var elem = document.getElementById(elem);
	
	if (elem != null)
	{
		elem.style.display = "block";
	}
}

/* Menu */

// update the select list of map files selection depending on the map currently selected
function update_map_files_list()
{
	// get name of map image selected
	var selected_map = document.getElementById('map_name').value ;
	
	// reinitialize the map files list
	document.getElementById("map_file").options.length = 0;
	
	// list of the options
	var map_files_list = new Array();
	
	// add the default choice (no map file)
	var no_map = new Option("- no map file - (new map from scratch)", "");
	map_files_list.push(no_map);

	// now add all existing map files for this map image
	for (var i=0;i<maps.length;i++) 
	{
		if (maps[i]["map_name"] == selected_map)
		{
			var map_files = maps[i]["map_files"];
			for (var j=0;j<map_files.length;j++) 
			{
				var map_file = new Option(map_files[j], map_files[j]);
				map_files_list.push(map_file);
			}
		}
	}
	
	// now update the SELECT list
	for (var i=0;i<map_files_list.length;i++) 
	{
		document.getElementById("map_file").options[i] = map_files_list[i];
	}
	
	// if there is at least one specific map file, select the first one
	if (map_files_list.length > 1)
	{
		document.getElementById("map_file").selectedIndex = "1";
	}
}

// use Ajax to make a POST request (with arguments)
function update_province_values()
{
	var http_request = false;
	
	var url = "province_panel.cgi";
	
	// get current selected province (if any)
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	var parameters = "";
	if (document.getElementById("province_" + selected_province_id) != null)
	{
		// get province XML (and do the appropriate encoding)
		parameters = "province_xml=" + encodeURI( document.getElementById("province_" + selected_province_id).value );
	}
	
	http_request = false;
	if (window.XMLHttpRequest)  // Mozilla, Safari,...
	{
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) 
		{
			// set type accordingly to anticipated content type
			//http_request.overrideMimeType('text/xml');
			http_request.overrideMimeType('text/html');
		}
	} 
	else if (window.ActiveXObject)  // IE
	{
		try 
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) 
			{
				alert("Your browser doesn't support Ajax. Maybe it's time for an upgrade ?");
				return false;
			}
		}
	}
	if (!http_request) 
	{
		alert('Cannot create XMLHTTP instance');
		return false;
	}

	// what to do at each step of the request :
	http_request.onreadystatechange = function()
	{	
		switch (http_request.readyState)
		{
			case 0: 
				document.getElementById('province_infos_contents').innerHTML = "<I>Initializing ...</I>";
				break;
			case 1: 
				document.getElementById('province_infos_contents').innerHTML = "<I>sending request ...</I>";
				break;
			case 2: 
				document.getElementById('province_infos_contents').innerHTML = "<I>Processing request ...</I>";
				break;
			case 3: 
				document.getElementById('province_infos_contents').innerHTML = "<I>Receiving response ...</I>";
				break;
			case 4: 	// request completed, checking response
			
				if (http_request.status == 200) 
				{
					var response = http_request.responseText;
					document.getElementById('province_infos_contents').innerHTML = response; 
				}
				else
				{
					document.getElementById('province_infos_contents').innerHTML = "<I STYLE='color: red;'>Response Error ! (" + http_request.status  + ")</I>";
				}
				break;
			default : 
				document.getElementById('province_infos_contents').innerHTML = "<I STYLE='color: red;'>Request Error ! (" + http_request.readyState +")</I>";
				break;
		}
   };
   
	// method 'post' will be used for the query
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
	
	// reset terrain types selection
	var terrain_types_list = get_all_terrain_types();
	for (var i = 0; i < terrain_types_list.length; i++)
	{
		document.getElementById("tt_" + terrain_types_list[i]).checked = false;
	}
	
	if (document.getElementById("province_" + selected_province_id) != null) // province exists
	{
		// get the XML code of the province (to get some infos not already set by the xslt)
		var province_xml = document.getElementById("province_" + selected_province_id).value;
		var dom_province = parse_xml_string(province_xml);
		
		// province custom name
		var landname = dom_province.documentElement.getAttribute("landname");
		if (landname != null && landname != "")
		{
			document.getElementById("landname").value = landname;
		}
		else
		{
			document.getElementById("landname").value = "- random name -";
		}
		
		// --------------------------------------------------
		// Terrain Types
		// --------------------------------------------------

		// update province terrain types
		var terrain_types = get_terrain_types(selected_province_id);
		for (var i = 0; i < terrain_types.length; i++)
		{
			var type = terrain_types[i];
			document.getElementById("tt_" + type).checked = true;
		}	
	}
}

// get the dom object of a province from its ID
function get_dom_province(province_id)
{
	var dom_province;
	
	// check that the province exists
	if (document.getElementById("province_" + province_id) != null)
	{
		var province_xml = document.getElementById("province_" + province_id).value;
		dom_province = parse_xml_string(province_xml);
	}
	
	return dom_province;
}

// update selected province name
function update_province_name()
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get the new name (empty for random name)
	var landname = document.getElementById('edit_landname').value;
		
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
		
	// update the "landname" attribute
	dom_province.documentElement.setAttribute("landname", landname);
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
	
	// refresh the province panel
	update_province_values();
}

// update selected province poptype
function update_province_poptype()
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get the new poptype (empty for random poptype)
	var selected_poptype = document.getElementById('edit_poptype').selectedIndex;
	var poptype = document.getElementById('edit_poptype').options[selected_poptype].value;
	var poptype_comments = document.getElementById('edit_poptype').options[selected_poptype].text;
		
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
		
	// update the "poptype" attribute
	dom_province.documentElement.setAttribute("poptype", poptype);
	dom_province.documentElement.setAttribute("poptype_comments", poptype_comments);
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
	
	// refresh the province panel
	update_province_values();
}

// update selected province "killpop" attribute
function update_province_killpop()
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
		
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
		
	// update the "killpop" attribute, depending if the checkbox is checked or not
	if (document.getElementById('killpop').checked)
	{
		dom_province.documentElement.setAttribute("killpop", "1");
	}
	else if (dom_province.documentElement.getAttribute("killpop") != null)
	{
		dom_province.documentElement.removeAttribute("killpop");
	}
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
}

// update selected province "nostart" attribute
function update_province_nostart()
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
		
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
		
	// update the "killpop" attribute, depending if the checkbox is checked or not
	if (document.getElementById('nostart').checked)
	{
		dom_province.documentElement.setAttribute("nostart", "1");
	}
	else if (dom_province.documentElement.getAttribute("nostart") != null)
	{
		dom_province.documentElement.removeAttribute("nostart");
	}
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
}

// set/unset province as starting point
function update_province_start()
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
		
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
		
	// update the "start" attribute, depending if the checkbox is checked or not
	if (document.getElementById('start').checked)
	{
		dom_province.documentElement.setAttribute("start", "1");
	}
	else if (dom_province.documentElement.getAttribute("start") != null)
	{
		dom_province.documentElement.removeAttribute("start");
	}
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
}

// update selected province "killfeatures" attribute
function update_province_killfeatures()
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
		
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
		
	// update the "killpop" attribute, depending if the checkbox is checked or not
	if (document.getElementById('killfeatures').checked)
	{
		dom_province.documentElement.setAttribute("killfeatures", "1");
	}
	else
	{
		dom_province.documentElement.setAttribute("killfeatures", "");
	}
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;

	// refresh the province panel
	// -- not needed for this version, as the checkbox is part of the base panel
	//update_province_values();
}

// remove a commander from the selected province
function remove_commander(commander_index)
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
	
	// get DOM commanders list
	var dom_commanders = dom_province.getElementsByTagName("commanders");
	
	// remove the commander
	var commander = dom_commanders[commander_index - 1];
	if (commander != null)
	{
		if (confirm("Delete Commander ?"))
		{
			var parent_node = commander.parentNode;
			var deleted_node = parent_node.removeChild(commander);
		}
	}
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
	
	// refresh the province panel
	update_province_values();
}

// remove a feature from the selected province
function remove_feature(feature_index)
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
	
	// get DOM features list
	var dom_features = dom_province.getElementsByTagName("features");
	
	// remove the feature
	var feature = dom_features[feature_index - 1];
	if (feature != null)
	{
		if (confirm("Delete Feature ?"))
		{
			var parent_node = feature.parentNode;
			var deleted_node = parent_node.removeChild(feature);
		}
		else
		{
			return;
		}
	}
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
	
	// refresh the province panel
	update_province_values();
}



// remove an unit squad  from a commander on the selected province
function remove_selected_unit()
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get units info
	var commander_index = document.getElementById('edit_commander_index').value;
	var units_index = document.getElementById('edit_units_index').value;

	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
	
	// get DOM commanders list
	var dom_commanders = dom_province.getElementsByTagName("commanders");
	
	// get the commander
	var commander = dom_commanders[commander_index - 1];
	if (commander != null)
	{
		if (units_index == -1)	// "-1" is for bodyguards
		{
			var dom_bodyguards = dom_province.getElementsByTagName("bodyguards");
			if (dom_bodyguards[0] != null)
			{
				// remove bodyguards
				var deleted_node = commander.removeChild(dom_bodyguards[0]);
			}
		}
		else	// other index is for units
		{
			var dom_units = dom_province.getElementsByTagName("units");
			var units = dom_units[units_index - 1];
			if (units != null)
			{
				// remove units squad
				var deleted_node = commander.removeChild(units);
			}
		}
	}
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
	
	// refresh the province panel
	update_province_values();
}

// add a feature to the current provice
function add_feature()
{
	var selected_province_id = document.getElementById("selected_province_id").value;
	
	if (document.getElementById("province_" + selected_province_id) == null)
	{
		// province does not exist ?
		alert('Error : no province selected');
		return null;
	}
	
	// get the XML code of the province
	var province_xml = document.getElementById("province_" + selected_province_id).value;
	// convert to DOM object
	var dom_province = parse_xml_string(province_xml);

	// get selected feature name
	var selected_feature_index  = document.getElementById("new_feature").selectedIndex;
	if (selected_feature_index == null || selected_feature_index == -1)
	{
		alert ("No Feature Selected");
		return false;
	}
	var feature = document.getElementById("new_feature").options[selected_feature_index].value;
	if (feature == null || feature == "")
	{
		alert ("No Feature Selected !");
		return false;
	}
	
	// create new "terrain_types" element
	var new_feature = dom_province.createElement("features");
	// set the feature attributes
	new_feature.setAttribute("name", feature);
	if (document.getElementById("new_feature_known").checked)
	{
		new_feature.setAttribute("known", "1");
	}

	if (isInteger(feature))	// we used the feature ID instead of the name
	{
		// search the features list for this ID
		for (var i=0; i < features_list.length; i++)
		{
			if (features_list[i]["id"] == feature)
			{
				// add the name and comments of the feature in the "comments" attribute
				// -- add the feature name with double-quotes (this will help to identify those features)
				var comments = features_list[i]["name"];
				// -- if the feature has comments add them after the name
				if (features_list[i]["comments"] != null && features_list[i]["comments"] != "")
				{
					comments += " (" + features_list[i]["comments"] + ")";
				}
				new_feature.setAttribute("comments", comments);
			}
		}
	}
	// add the feature to the province
	dom_province.documentElement.appendChild(new_feature);
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
	
	// refresh the province panel
	update_province_values();
}


function activate_panel(panel_id)
{
	// hide others panel
	var panels = 	document.getElementById("panels").childNodes;
	for (var i = 0; i < panels.length; i++)
	{
		var current_panel = panels[i];
		if (current_panel.id != panel_id)
		{
			mask(current_panel.id);
		}
	}
	
	// show the chosen panel (if exists)
	show(panel_id);
	
	// if panel exists, move it
	var panel = document.getElementById(panel_id);
	if (panel != null)
	{	
		// some last things to do, depending of the specific panel activated
		switch (panel_id)
		{
			case "panel_poptype": 
					// preselect the appropriate poptype (if any)
					var current_poptype = document.getElementById("poptype").value;
					if (poptype != null && poptype != "" && poptype != "-")
					{
						document.getElementById("edit_poptype").value = current_poptype;
					}
				break;
				
			case "panel_add_feature": 
					// initialize features list select box
					for (var i = 0; i < features_list.length; i++)
					{
						var feature = features_list[i];
						var text = feature["name"];
						if (feature["comments"] != null && feature["comments"] != "")
						{
							text += " (" + feature["comments"] + ")";
						}
						var value = feature["id"];
						
						var feature = new Option(text, value);
						document.getElementById("new_feature").options[i+1] = feature;
					}
				break;
			
			case "panel_landname": 
				// initialize province name
				var province_name = document.getElementById("landname").value;
				if (province_name != null && province_name != "- random name -")
				{
					document.getElementById("edit_landname").value = province_name;
				}
				break;
				
			default:
					// default : nohing more to do
				break;
		}
	}
}

// initialization of the panel allowing to edit a commander's name
function activate_panel_comname(commander_index)
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
	
	// get DOM commanders list
	var dom_commanders = dom_province.getElementsByTagName("commanders");
	
	// get the commander
	var commander = dom_commanders[commander_index - 1];
	if (commander != null)
	{
		document.getElementById('edit_commander_index').value = commander_index;
		
		var comname = commander.getAttribute("name");
		if (comname != null)
		{
			document.getElementById('edit_comname').value = comname;
		}
	}

	// activate the panel
	activate_panel("panel_comname");
}

// update selected commander name
function update_comname()
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get the new name (empty for random name)
	var comname = document.getElementById('edit_comname').value;
	
	// get commander index
	var commander_index = document.getElementById('edit_commander_index').value;
	
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
		
	// get DOM commanders list
	var dom_commanders = dom_province.getElementsByTagName("commanders");
		
	// get the commander
	var commander = dom_commanders[commander_index - 1];
	if (commander != null)
	{
		// update the name
		commander.setAttribute("name", comname);
	}
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
	
	// refresh the province panel
	update_province_values();
}

function isInteger(x) 
{
	// regular expression that validates a value is an Integer 
	var RegExp = /^[0-9]+$/;
	// compare the argument to the RegEx 
	// the 'match' function returns 0 if the value didn't match 
	if (x.match(RegExp))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function isNumeric(x) 
{
	// regular expression that validates a value is numeric 
	var RegExp = /^(-)?([0-9]*)(\.?)([0-9]+)$/;
	// compare the argument to the RegEx 
	// the 'match' function returns 0 if the value didn't match 
	if (x.match(RegExp))
	{
		return true;
	}
	else
	{
		return false;
	}
}

// initialization of the panel allowing to edit a commander's unit type
function activate_panel_commander_unit(commander_index)
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
	
	// get DOM commanders list
	var dom_commanders = dom_province.getElementsByTagName("commanders");
	
	// note that commander_index == "0"  means a new commander
	var commander;
	var commander_unit = -1;
	if (commander_index != 0)
	{
		// get the commander
		commander = dom_commanders[commander_index - 1];
		commander_unit = commander.getAttribute("unit_id");
	}
	
	if (commander_index == 0 || commander != null)
	{
		document.getElementById('edit_commander_index').value = commander_index;
	
		// initialize units list select box
		var selected_unit_index;
		for (var i = 0; i < units_list.length; i++)
		{
			var unit = units_list[i];
			var text = unit["name"];
			if (unit["comments"] != null && unit["comments"] != "")
			{
				text += " (" + unit["comments"] + ")";
			}
			var value = unit["id"];
			
			var feature = new Option(text, value);
			document.getElementById("edit_commander_unit").options[i+1] = feature;
			
			if (commander_unit == value)
			{
				selected_unit_index = i+1;
			}
		}
		if (selected_unit_index != null)
		{
			// preselect the current value
			document.getElementById("edit_commander_unit").selectedIndex = selected_unit_index;
		}
	}
	
	
	// activate the panel
	activate_panel("panel_commander_unit");
}


// add or update a commander's unit type
function edit_comunit()
{
	var selected_province_id = document.getElementById("selected_province_id").value;
	
	if (document.getElementById("province_" + selected_province_id) == null)
	{
		// province does not exist ?
		alert('Error : no province selected');
		return null;
	}
	
	// get the XML code of the province
	var province_xml = document.getElementById("province_" + selected_province_id).value;
	// convert to DOM object
	var dom_province = parse_xml_string(province_xml);

	// get selected commander unit
	// -- first check if a custom commander unit is set
	var commander_unit = document.getElementById("edit_commander_unit_custom").value;
	if (commander_unit == null || commander_unit == "")	// no custom commander
	{
		// get the unit type from the select list
		var selected_unit_index  = document.getElementById("edit_commander_unit").selectedIndex;
		if (selected_unit_index == null || selected_unit_index == -1)
		{
			alert ("No Unit Selected");
			return false;
		}
		commander_unit = document.getElementById("edit_commander_unit").options[selected_unit_index].value;
		if (commander_unit == null || commander_unit == "")
		{
			alert ("No Unit Type Selected !");
			return false;
		}
	}
	
	var comments = "";
	if (isInteger(commander_unit))	// we used the unit  ID instead of the name
	{
		// search the units list for this ID
		for (var i=0; i < units_list.length; i++)
		{
			if (units_list[i]["id"] == commander_unit)
			{
				// add the name and comments of the feature in the "comments" attribute
				// -- add the unit name with double-quotes
				comments = units_list[i]["name"];
				// -- if the feature has comments add them after the name
				if (units_list[i]["comments"] != null && units_list[i]["comments"] != "")
				{
					comments += " (" + units_list[i]["comments"] + ")";
				}
			}
		}
		
	}
	
	// get commander index
	var commander_index = document.getElementById("edit_commander_index").value;
	
	if (commander_index == 0) // "0" is for a new commander
	{
		// create new "Commanders" element
		var new_commander = dom_province.createElement("commanders");
		// set the commander attributes
		new_commander.setAttribute("unit_id", commander_unit);	
		new_commander.setAttribute("comments", comments);
		
		// add the commander to the province
		dom_province.documentElement.appendChild(new_commander);
	}
	else	// update existing commander
	{
		// get DOM commanders list
		var dom_commanders = dom_province.getElementsByTagName("commanders");
		
		// note that commander_index == "0"  means a new commander
		var commander;
		
		// get the commander
		commander = dom_commanders[commander_index - 1];
		
		if (commander != null)
		{
			// update the unit type
			commander.setAttribute("unit_id", commander_unit);
			commander.setAttribute("comments", comments);
		}
	}
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
	
	// refresh the province panel
	update_province_values();
}

// initialization of the panel allowing to edit units and bodyguards
function activate_panel_edit_unit(commander_index, unit_index)
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
	
	// get DOM commanders list
	var dom_commanders = dom_province.getElementsByTagName("commanders");
	
	// note that unit_index == "0"  means a new unit
	var commander = dom_commanders[commander_index - 1];;
	
	var unit_type;
	var unit_number;
	
	if (unit_index == -1) // -1 is for bodyguards
	{
		// get DOM units list
		var dom_bodyguards = commander.getElementsByTagName("bodyguards");
		
		var bodyguards = dom_bodyguards[0];
		
		if (bodyguards != null)	// bodyguards already set
		{
			// get the current bodyguards as unit
			unit = bodyguards;
			unit_type = unit.getAttribute("unit_id");
			unit_number = unit.getAttribute("number");
			
			// show the "remove unit button"
			mask("remove_selected_unit_button");
			show("remove_bodyguards_button");
		}
		else
		{
			mask("remove_selected_unit_button");
			mask("remove_bodyguards_button");
		}
	}
	else if (unit_index > 0)
	{
		// get DOM units list
		var dom_units = commander.getElementsByTagName("units");
		
		// get the unit
		unit = dom_units[unit_index - 1];
		unit_type = unit.getAttribute("unit_id");
		unit_number = unit.getAttribute("number");
		
		// show the "remove unit button"
		show("remove_selected_unit_button");
		mask("remove_bodyguards_button");
	}
	else
	{
		// hide the "remove unit button"
		mask("remove_selected_unit_button");
		mask("remove_bodyguards_button");
	}
	
	if (unit_index == 0 || unit_index == -1 || unit != null)
	{
		document.getElementById('edit_commander_index').value = commander_index;
		document.getElementById('edit_units_index').value = unit_index;
		
		// initialize units list select box
		var selected_unit_index;
		for (var i = 0; i < units_list.length; i++)
		{
			var unit = units_list[i];
			var text = unit["name"];
			if (unit["comments"] != null && unit["comments"] != "")
			{
				text += " (" + unit["comments"] + ")";
			}
			var value = unit["id"];
			
			var feature = new Option(text, value);
			document.getElementById("edit_unit").options[i+1] = feature;
			
			if (unit_type == value)
			{
				selected_unit_index = i+1;
			}
		}
		if (selected_unit_index != null)
		{
			// preselect the current value
			document.getElementById("edit_unit").selectedIndex = selected_unit_index;
		}
		
		if (unit_number != null)
		{
			// preselect the current number of units
			document.getElementById("edit_unit_number").value = unit_number;
		}
	}
	
	// activate the panel
	activate_panel("panel_edit_unit");
}

// add or update a commander's unit type
function edit_selected_unit()
{
	var selected_province_id = document.getElementById("selected_province_id").value;
	
	if (document.getElementById("province_" + selected_province_id) == null)
	{
		// province does not exist ?
		alert('Error : no province selected');
		return null;
	}
	
	// get the XML code of the province
	var province_xml = document.getElementById("province_" + selected_province_id).value;
	// convert to DOM object
	var dom_province = parse_xml_string(province_xml);

	// get selected commander unit
	// -- first check if a custom commander unit is set
	var unit_type = document.getElementById("edit_unit_custom").value;
	if (unit_type == null || unit_type == "")	// no custom unit
	{
		// get the unit type from the select list
		var selected_unit_index  = document.getElementById("edit_unit").selectedIndex;
		if (selected_unit_index == null || selected_unit_index == -1)
		{
			alert ("No Unit Selected");
			return false;
		}
		unit_type = document.getElementById("edit_unit").options[selected_unit_index].value;
		if (unit_type == null || unit_type == "")
		{
			alert ("No Unit Type Selected !");
			return false;
		}
	}
	
	var number = document.getElementById("edit_unit_number").value;
	if (number == null || number == 0 || ! isInteger(number))
	{
		alert("Invalid number of units");
		return false;
	}
	
	var comments = "";
	if (isInteger(unit_type))	// we used the unit  ID instead of the name
	{
		// search the units list for this ID
		for (var i=0; i < units_list.length; i++)
		{
			if (units_list[i]["id"] == unit_type)
			{
				// add the name and comments of the feature in the "comments" attribute
				// -- add the unit name with double-quotes
				comments = units_list[i]["name"];
				// -- if the feature has comments add them after the name
				if (units_list[i]["comments"] != null && units_list[i]["comments"] != "")
				{
					comments += " (" + units_list[i]["comments"] + ")";
				}
			}
		}
	}
	
	// get commander index
	var commander_index = document.getElementById("edit_commander_index").value;
	
	// get unit index (0 for new unit)
	var unit_index = document.getElementById("edit_units_index").value;
	
	if (unit_index == -1 && number > 5)
	{
		alert("Bodyguards number must be between 1 and 5");
		return false;
	}
	
	// get DOM commanders list
	var dom_commanders = dom_province.getElementsByTagName("commanders");
	
	// note that unit_index == "0"  means a new unit
	var commander = dom_commanders[commander_index - 1];;
	
	if (unit_index == -1) // "-1" is for bodyguards
	{
		// get DOM previously defined bodyguards (if any)
		var dom_units = commander.getElementsByTagName("bodyguards");
		
		var bodyguards;
		
		if (dom_units[0] != null) // bodyguards already set
		{
			bodyguards = dom_units[0];
		}
		else
		{
			// create new "Bodyguards" element
			var bodyguards = dom_province.createElement("bodyguards");
			commander.appendChild(bodyguards);
		}
		
		// set bodyguards settings
		bodyguards.setAttribute("unit_id", unit_type);	
		bodyguards.setAttribute("number", number);	
		bodyguards.setAttribute("comments", comments);
	}
	else if (unit_index == 0) // "0" is for a new unit
	{
		// create new "Units" element
		var new_unit = dom_province.createElement("units");
		// set the commander attributes
		new_unit.setAttribute("unit_id", unit_type);	
		new_unit.setAttribute("number", number);	
		new_unit.setAttribute("comments", comments);
		
		// add the units to the commander
		commander.appendChild(new_unit);
	}
	else	// update existing unit
	{
		// get DOM units list
		var dom_units = commander.getElementsByTagName("units");
		
		// note that unit_index == "0"  means a new unit
		var unit = dom_units[unit_index - 1];;
		
		if (unit != null)
		{
			// update the unit type
			unit.setAttribute("unit_id", unit_type);
			unit.setAttribute("number", number);
			unit.setAttribute("comments", comments);
		}
	}
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
	
	// refresh the province panel
	update_province_values();
}



// remove an unit squad  from a commander on the selected province
function remove_item(commander_index, item_index)
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
	
	// get DOM commanders list
	var dom_commanders = dom_province.getElementsByTagName("commanders");
	
	// get the commander
	var commander = dom_commanders[commander_index - 1];
	if (commander != null)
	{
		var dom_items = dom_province.getElementsByTagName("items");
		var item = dom_items[item_index - 1];
		if (item != null && confirm("Remove Item ?"))	// item exists, and user confirm
		{
			// remove item
			var deleted_node = commander.removeChild(item);
			
			// update province XML
			var province_xml = xml_output(dom_province);
			document.getElementById("province_" + selected_province_id).value = province_xml;
			
			// refresh the province panel
			update_province_values();
		}
	}
}

// activate panel to add items to a commander
function activate_panel_add_item(commander_index)
{
	alert("not available yet");	// TOPROG
}

// activate panel to edit commander custom magic
function activate_panel_edit_commagic(commander_index)
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
	
	// get DOM commanders list
	var dom_commanders = dom_province.getElementsByTagName("commanders");
	
	// get the commander
	var commander = dom_commanders[commander_index - 1];
	if (commander != null)
	{
		document.getElementById('edit_commander_index').value = commander_index;
		
		// clearmagic
		var clearmagic = commander.getAttribute("clearmagic");
		if (clearmagic != null && clearmagic == "1")
		{
			document.getElementById('edit_clearmagic').checked = true;
		}
		
		// get already defined custom magic path(s)
		var magic_paths = new Array("fire", "air", "earth", "water", "astral", "death", "nature", "blood", "priest");
		
		for (var i=0; i < magic_paths.length; i++)
		{
			var path = magic_paths[i];
			var path_level = commander.getAttribute("mag_" + path);
			if (path_level != null && isInteger(path_level) )
			{
				document.getElementById('edit_mag_' + path).value = path_level;
			}
			else
			{
				// no level in this path
				document.getElementById('edit_mag_' + path).selectedIndex = 0;
			}
		}
	}

	// activate the panel
	activate_panel("panel_edit_commagic");
}

// update a commander custom magic levels
function edit_commagic()
{
	// get the selected province id
	var selected_province_id = document.getElementById('selected_province_id').value;
	
	// get commander index
	var commander_index = document.getElementById('edit_commander_index').value;
	
	// get the province DOM
	var dom_province = get_dom_province(selected_province_id);
		
	// get DOM commanders list
	var dom_commanders = dom_province.getElementsByTagName("commanders");
		
	// get the commander
	var commander = dom_commanders[commander_index - 1];
	if (commander != null)
	{
		// clearmagic
		if (document.getElementById('edit_clearmagic').checked)
		{
			commander.setAttribute("clearmagic", "1");
		}
		else
		{
			if (commander.getAttribute("clearmagic") != null)
			{
				commander.removeAttribute("clearmagic");
			}
		}
		// get already defined custom magic path(s)
		var magic_paths = new Array("fire", "air", "earth", "water", "astral", "death", "nature", "blood", "priest");
		
		for (var i=0; i < magic_paths.length; i++)
		{
			var path = magic_paths[i];
			var selected_level = document.getElementById("edit_mag_" + path).selectedIndex;
			
			if (selected_level != null && selected_level != -1 )
			{
				var path_level = document.getElementById("edit_mag_" + path).options[selected_level].value;
				if (path_level != null && isInteger(path_level) && path_level > 0)
				{
					commander.setAttribute("mag_" + path, path_level);
				}
				else	if (commander.getAttribute("mag_" + path) != null)
				{
					commander.removeAttribute("mag_" + path);
				}
			}
			else	if (commander.getAttribute("mag_" + path) != null)
			{
				commander.removeAttribute("mag_" + path);
			}
		}
	}
	
	// update province XML
	var province_xml = xml_output(dom_province);
	document.getElementById("province_" + selected_province_id).value = province_xml;
	
	// refresh the province panel
	update_province_values();
}
