var mapHoverOverlay = null;
var mapSelectionOverlay = null;
var countryElements;
var countryData;
var useQuicksand = true;
var mapHoverOverlays = {
	'NA': $(document.createElement('img')).attr('src', '/images/map/continent_NA.png'),
	'SA': $(document.createElement('img')).attr('src', '/images/map/continent_SA.png'),
	'EU': $(document.createElement('img')).attr('src', '/images/map/continent_EU.png'),
	'AS': $(document.createElement('img')).attr('src', '/images/map/continent_AS.png'),
	'OC': $(document.createElement('img')).attr('src', '/images/map/continent_OC.png'),
	'AN': $(document.createElement('img')).attr('src', '/images/map/continent_AN.png'),
	'AF': $(document.createElement('img')).attr('src', '/images/map/continent_AF.png')
};


for ( var continent in mapHoverOverlays ) {
	mapHoverOverlays[continent].css({
		'position': 'absolute',
		'left': '0px',
		'top': '0px'
	});
	mapHoverOverlays[continent].fadeTo(0, 0);
}

function mapHover(continent) {
	if ( mapHoverOverlay ) {
		mapHoverOverlay.remove();
		mapHoverOverlay = null;
	}
	if ( mapHoverOverlays[continent] ) {
		mapHoverOverlay = mapHoverOverlays[continent];
		$('#map_image').after(mapHoverOverlay);
		mapHoverOverlay.fadeTo(1, 0.5);
	}
}

function mapClick(continent) {
	showCountries(continent);
	if ( mapSelectionOverlay ) {
		mapSelectionOverlay.remove();
		mapSelectionOverlay = null;
	}
	if ( continent != 'none' ) {
		mapSelectionOverlay = mapHoverOverlays[continent].clone();
		$('#map_image').after(mapSelectionOverlay);
	}
}

function showCountries(continent) {
	if ( !countryData ) {
		return;
	}
	if ( continent == 'none' ) {
		var filtered = countryData.find('a');
		$('#clear_selection_link').hide();
	} else {
		var filtered = countryData.find('a[data-continent='+continent+']');
		$('#clear_selection_link').show();
	}
	if ( !useQuicksand ) {
		filterCountries(filtered);
	} else {
		countryElements.quicksand(filtered, { duration: 800 });
	}
}

function filterCountries(filtered) {
	countryElements.empty();
	countryElements.append(filtered.clone());
}

$(function() {
	countryElements = $('div.country_cloud');
	countryData = countryElements.clone();
});
