// JavaScript Document

var issueList = ["02","03","04","05","06","07","09","11","12","13","14","15","16","17","19","21","22","23","24","25","27","28","29","30"];
var lookUpArray = ["af","al","ag","an","ao","ac","ar","am","as","au","aj","bf","ba","bg","bb","bo","be","bh","bn","bt","bl","bk","bc","br","bx","bu","uv","by","cb","cm","ca","cv","ct","cd","ci","ch","co","cn","cg","cf","cw","cs","iv","hr","cu","cy","ez","da","dj","do","dr","ec","eg","es","ek","er","en","et","fj","fi","fr","gb","ga","gg","gm","gh","gr","gj","gt","gv","pu","gy","ha","ho","hk","hu","ic","in","id","ir","iz","ei","is","it","jm","ja","jo","kz","ke","kr","ku","kg","kn","la","lg","le","lt","li","ly","lh","lu","mk","ma","mi","my","mv","ml","mt","rm","mr","mp","mx","fm","md","mn","mg","mj","mo","mz","bm","wa","nr","np","nl","nz","nu","ng","ni","ne","no","mu","pk","ps","pm","pp","pa","pe","rp","pl","po","qa","ro","rs","rw","sc","st","vc","ws","sm","tp","sa","sg","rb","se","sl","sn","lo","si","bp","so","sf","sp","ce","su","ns","wz","sw","sz","sy","ti","tz","th","tt","to","tn","td","ts","tu","tx","tv","ug","up","ae","uk","us","uy","uz","nh","ve","vm","ym","za","zi"]
var lookUpArrayOC = objectConverter(lookUpArray);

//clear the checked boxes and the country list input when the page loads
document.observe("dom:loaded", function() {
	var elements = Form.getElements('countryList');
	elements.each( function(item) {	
	  item.checked = false;
	});
	$('countryInput').clear();
});

function updateCountryList (input) {
	if(input.checked) {
	  $('countryInput').value += input.value + ",";
	}
	else {
		$('countryInput').value = $('countryInput').value.sub(input.value + ",", "");
	}
}

function toggleCountryList() {
	$('countryList').toggle();
	$('footer').hide();
}

function getCountryData (form) {
	var url = "xml/countrydata.xml";
	var countriesStripped = form.countries.value.replace(" ","");
	var countryList = countriesStripped.split(",");
	var areasRequests = []
	$('countryDataDisplay').replace("<div id='countryDataDisplay'><p id='loading-message'>Loading data...</p></div>");
	if(countryList[0] != "" && lookUpCountryCodes(countryList)) {
	  $('footer').hide();
	  for(a=0; a < issueList.length; a++) {
		var mapURL = "fmASMap/maps/map_" + issueList[a] + ".xml";
		new Ajax.Request (mapURL, {  
		  method: 'get',
		  onSuccess: function (request) {
		    var xmlObj = request.responseXML;
			var titles = xmlObj.getElementsByTagName("title");
			var title = titles[0].firstChild.nodeValue;
			var issID = xmlObj.firstChild.getAttribute("id");
			var worldAreasURL = "fmASMap/maps/" + issID + "/world_areas.xml";
			new Ajax.Request (worldAreasURL, {  
			  method: 'get',  
			  onSuccess: function (request) {
				var output = "<br /><h3>" + title + "</h3>";
				for(i=0; i < countryList.length; i++) {
				  var countryData = getElementsByAttribute("id", countryList[i], request.responseXML);
				  var info = countryData[0].getAttribute("info");
				  if(info == "" || info == "undefined") {
					info = "No Data";
				  }
				  output += "<strong>" +countryData[0].getAttribute("label") + ":</strong> " + info + "<br />";
				}
				$('loading-message').hide();
				$('countryDataDisplay').insert(output);
			  },
			  onFailure: function(){ alert('Error: could not load an xml file')},  
			  onException: function(){ alert('There was an error processing part of your request. Not all countries you requested may have data available in every category.')}
			});
		  },
		  onFailure: function(){ alert('Error: could not load an xml file')},  
		  onException: function(){ alert('There was an error processing map xml')}//part of your request. Not all countries you requested may have data available in every category.')} 
		});
	  }
	}  
}

//return elements with a specific attribute, or only if that attribute matches a certain value or tagName
function getElementsByAttribute(the_attribute, the_value, the_node){
	var node_tags = the_node.getElementsByTagName('*');
	var results = [];
	for(var i=0;i<node_tags.length;i++){
		if(node_tags[i].getAttribute(the_attribute)){	
			if(node_tags[i].getAttribute(the_attribute) == the_value){
				results.push(node_tags[i]);
			}
		}
	}
	return results;
}

function lookUpCountryCodes (codeArray) {
	var validCodes = true;
	for(var i = 0; i < codeArray.length; i++) {
		//remove the code if it is empty
		if(codeArray[i] == "") {
			codeArray.splice(i, i);
		}
		else {
			if(lookUpCountry(codeArray[i]) == false) {
				alert("Could not find a country with the country code: " + codeArray[i]);
				validCodes = false;
			}
		}
	}
	if(validCodes) {
		return true;
	}
	else {
		return false;
	}
}

function lookUpCountry (countryCode) {
	if(countryCode in lookUpArrayOC) {
		return true;
	}
	else {
		return false;
	}
}

//convert an array into an array of objects (useful for finding a string in the array)
function objectConverter(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}