var loader;

function initDistribution() {
	// enable radio buttons
	$(".radioView").click(changeMapType);
	
	// store ajax loader
	loader = $("img#loader");
	$("img#absolute").load(function(){loader.css("visibility", "hidden")});
	getAvailableMaps();
}

function changeMapType(event) {
	var radio = $(event.target);
	
	if (radio.val() == "absolute") {
		$("img#relative").hide();
		$("img#absolute").show();
	} else {
		$("img#absolute").hide();
		$("img#relative").show();
	}
}

function getAvailableMaps(name) {
	var url = $("form#countries").attr("action");
	
	$.getJSON(url, showAvailableMaps);	
}

function showAvailableMaps(json) {
	var maps = json.maps.map;

	var mapsHtml = '<ul class="countries">';
	
	if (maps == null) {
		$("#disMap_availableMapsContainer").html('<p class="no-result">No maps found</p>');
		return false;
	}
	
	// only 1 country?
	if (maps.countryName != null) {
		$("img#absolute").attr("src", $(this).val());
		$("img#relative").attr("src", $(this).attr("rel"));
		$("#name-distribution-countries").hide();
		console.info("1 country");
	} else {
		console.info("several countries");
		$.each(maps, function() {
			var checked = this.locale == locale ? ' checked="checked"' : '';
			mapsHtml += '<li>';
			mapsHtml += '<input type="radio" name="country" class="radio" rel="' + this.relativeImageUrl  + '" value="' + this.absoluteImageUrl  + '"' + checked + '/><span class="flag flag-' + this.locale + '">' + this.countryName + '</span>';
			mapsHtml += '</li>';
		});
		
		// insert html into admin page
		$("form#countries").html(mapsHtml);
		
		$("form#countries input[name='country']").click(function() {
			// add loader to clicked option
			$(this).parent().append(loader);
			loader.css("visibility", "visible")
			
			// load new country
			$("img#absolute").attr("src", $(this).val());
			$("img#relative").attr("src", $(this).attr("rel"));
		});
	}
	
}



$(document).ready(function(){
	initDistribution();	  
});

