// function collection for managing country stuff
var countryTools = {
	// replace standard text form field with country with 
	// more usable select-box  
	doCountrySelect : function () {
		if(!isoCountries) return null;

		var repl = document.getElementById("country"); // this will be replaced
		var dflt = repl.value == "" ? "DE" : repl.value.toUpperCase(); // default country
		
		// only for inputs
		if(repl.nodeName != "INPUT") return null;
		
		var select = document.createElement("SELECT");
		select.name = "country";
		select.mandatory = repl.mandatory;
		
		for(var i = 0; i<isoCountries.length; i++) {
			var cur = isoCountries[i];

			// create option
			var opt = document.createElement("OPTION");
			opt.value = cur.alpha2;
			opt.innerHTML = cur.country;
			// check if this is default
			if(cur.alpha2 == dflt) {
				opt.selected = true;
			}
			
			// add option to select
			select.appendChild(opt);
		}
		// replace old input with select
		repl.parentNode.replaceChild(select, repl);
		return select;
	},
	
	// return country-name for abbrev
	getCountryForAlpha2 : function (alpha2) {
		if(!isoCountries) return null;
		
		for(var i = 0; i<isoCountries.length; i++) {
			var cur = isoCountries[i];
			if(cur.alpha2 == alpha2) return cur.country;
		}
		return null;
	},
	
	// replace alpha2-code with country-name where id="code2country"
	code2country : function () {
		var elems = null;
		if(document.getElementsByClassName) // hooray
			elems = document.getElementsByClassName("code2country");
		else { // OMFG
			// iam using this on <span> right now only
			// if this will be used on different tags in the future this will have to be corrected
			elems = Array();
			var tmp = document.getElementsByTagName("SPAN");
			for(var i=0; i<tmp.length; i++) {
				var t = tmp[i];
				if(t.className == "code2country") {
					elems.push(t);
				}
				//console.debug(t);
			}
		}
		
		if(elems) {
			for(var i = 0; i<elems.length; i++) {
				var trg = elems[i];
				var cou = countryTools.getCountryForAlpha2(trg.innerHTML.trim().toUpperCase());
				trg.innerHTML = cou;				
			}
		}
	}
};


