/**
 * 24-7 Prayer map builder 
 * 
 * author:	honza AT kotrs DOT cz 
 * version:	0.0.2
 * 
 * 0.0.2:	minor; added hyperlinks to city DIVs
 * 0.0.1:	first version, bare-bones, only previous flash version
 * 			replacement; should be easy to enhance though
**/

function MapBuilder(data, settings) {
	
	// PROPERTIES //
		
	this.map = settings.map;
	this.cities = data;
	
	// CONSTANTS //
	
	var LAT = 0;
	var LON = 1;
		
	var TOP_LEFT_LL = [51.057797, 12.091141]; 		// .. top left corner of the map in GPS	
	var BOTTOM_RIGHT_LL = [48.55116, 18.859406];	// .. bottom right corner of the map in GPS
	var TOP_LEFT_MAP = [0, 0];						// .. top left corner of the map in pixels
	var BOTTOM_RIGHT_MAP = [526, 882];				// .. bottom right corner of the map in pixels
	
	// .. ratios for ease of pixel coordinates computing
	var LL2MAP_RATIOS = [((BOTTOM_RIGHT_MAP[LAT]-TOP_LEFT_MAP[LAT])/(TOP_LEFT_LL[LAT]-BOTTOM_RIGHT_LL[LAT])),
	                     ((BOTTOM_RIGHT_MAP[LON]-TOP_LEFT_MAP[LON])/(BOTTOM_RIGHT_LL[LON]-TOP_LEFT_LL[LON]))];
	
	//$("#log").append("LL2MAP_RATIOS[LAT]:"+LL2MAP_RATIOS[LAT]+", LL2MAP_RATIOS[LON]:"+LL2MAP_RATIOS[LON]+"<br />");
	
	// TEMPLATES //
	
	var CITY = "<a href='%cityLink%'><div class='city state-%cityState%' id='city_%cityID%' style='top:%top%px;left:%left%px'>%cityName%</div></a>";
	var LEGEND = "<div class='legend'><div class='state-2'>Právě se modlí</div>"
								   + "<div class='state-1'>Spuštěna rezervace</div></div>";
	
	// METHODS //	
	
	this.buildMap = function() {
		
		// .. flush in case it's not the rist time call
		this.clearMap();
		
		// .. incrementally add all cities		
		if(this.cities != null || this.cities != undefined) {			
			for(var city in this.cities) {
				var newCity = this.createCity(this.cities[city]);
				$(this.map).append(newCity);	
			}						
		}
		
		// .. add city state legend
		$(this.map).append(this.createLegend());		
			
	};
	
	this.translateLL2Map = function(coordinates) {
		var mapCoordinates = [];		

		mapCoordinates[LAT] = LL2MAP_RATIOS[LAT]*(TOP_LEFT_LL[LAT]-coordinates[LAT]);		
		mapCoordinates[LON] = LL2MAP_RATIOS[LON]*(coordinates[LON]-TOP_LEFT_LL[LON]);				
		
		return mapCoordinates;
	};	
	
	this.clearMap = function() {
		$(this.map).empty();
	};
	
	this.createCity = function(city) {
		
		if(city.lat != undefined && city.lon != undefined) {		
			var coords = this.translateLL2Map([city.lat,city.lon]);
			var newCity = CITY.replace(/%cityID%/g, city.id)
							  .replace(/%cityName%/g, city.name)
							  .replace(/%cityState%/g, city.state)
							  .replace(/%cityLink%/g, city.url)
							  .replace(/%top%/g, coords[LAT])
							  .replace(/%left%/g, coords[LON]);
			return newCity;		
		}
		
		return "";
	};
	
	this.createLegend = function() {
		return LEGEND;
	};
	
}
