var mapEntries;
var mapActiveElement = 0;
var mapMouseOver = false;

$(document).ready(function(){	
	
	// Read CSV file and create the map objects
	jQuery.get('http://www.schoema.de/fileadmin/user_upload/csv/map_en.csv', function(data) { 
		createMap(data);		
	});
		
	// Set Mouse Events
	$('#map').mouseenter(function() {
		mapMouseOver = true;
	});
	
	$('#map').mouseleave(function() {
		mapMouseOver = false;
	});			

	$('#mapDescription').mouseenter(function() {
		mapMouseOver = true;
	});
	
	$('#mapDescription').mouseleave(function() {
		mapMouseOver = false;
	});
		
	
	// Set Timer
	window.setInterval(mapTimerEvent, 3000);	
});


// Set the active map element
function setActiveMapElement(elementId) {
		if(elementId < 0 || elementId >= mapEntries.length) {
			elementId = 0;
		}

		// Disable current active element 
		$('#mapElement-'+mapActiveElement).removeClass('mapElement-active');		
		$('#mapElement-'+mapActiveElement).addClass('mapElement-passive');
		$('#mapDescriptionElement-'+mapActiveElement).hide();
		
		// Set new active element
		mapActiveElement = elementId;
		$('#mapElement-'+mapActiveElement).removeClass('mapElement-passive');	
		$('#mapElement-'+mapActiveElement).addClass('mapElement-active');
		$('#mapDescriptionElement-'+mapActiveElement).show();
}

// Timer Event
function mapTimerEvent() {
	if(!mapMouseOver) {
		setActiveMapElement(mapActiveElement+1);
	}
}

// Reads CSV and creates map
function createMap (data) {
	mapEntries = jQuery.csv(';')(data); 
	
	var newId = 0;
	
	$.each(mapEntries, function(index, line) { 
	
		var headline = line[0];
		var text = line[1];
		var x = line[2];
		var y = line[3];
		var newMapElement = '<a id="mapElement-'+newId+'" class="mapElement-passive" href="http://www.schoema.de/index.php?id=94" style="top:'+y+'px; left: '+x+'px;"> </a>';
		var newMapDescriptionElement = '<p id="mapDescriptionElement-'+newId+'" class="mapDescriptionElement" style="display: none;"><strong>'+headline+'</strong>: '+text+'<br><a href="http://www.schoema.de/index.php?id=94">&#8250; read more</a></p>';

		$('#map').append(newMapElement);
		$('#mapDescription').append(newMapDescriptionElement);
		newId++;
	});

	// Set Mouse Events
	$('.mapElement-passive').mouseenter(function(event) {
		setActiveMapElement(this.id.substr(11, 7));
	});
	
	setActiveMapElement(0);	
}
