if(window.console === undefined){
	// dummy function to mask firebug
	window.console={};
	window.console.debug=function(){};
}

var map;
var mapLabels;
var mapLanguage;
var polys = [];
var markers = [];
var editingNow = false;

function lineLength(x1, y1, x2, y2){
	var dx=x1-x2;
	var dy=y1-y2;
	return Math.sqrt(dx*dx + dy*dy);
}

function updateImage() {
	var baseUrl = "http://maps.bmsite.net/static?";

	var params = [];

	if (!document.getElementById("mapFitCHECKBOX").checked) {
		var ig=map.toIngame(map.getCenter());
		params.push("center=" + ig.x.toFixed(0) + "," + ig.y.toFixed(0));
		params.push("zoom=" + map.getZoom());
	}
	if (document.getElementById("mapShowFlagsRADIO").checked){
		params.push("flags=1");
	}else if (document.getElementById("mapHideFlagsRADIO").checked){
		params.push("flags=0");
	}
	var lang = document.getElementById("mapLangSELECT").value;
	if(lang!=''){
		// &lang is reserved, so we use 'language'
		params.push("language="+lang);
	}


	var coords;
	for (var i = 0; i < markers.length; i++) {
		var markerParams=[];
		var markerIcon = markers[i]._iconName || markers[i].getIcon()._name;
		var markerColor = markers[i].getIcon()._color;
		var markerTooltip = markers[i].tooltip;
		if(markerIcon!='') markerParams.push('icon:'+markerIcon);
		if(markerColor!='') markerParams.push('color:0x'+markerColor.replace('#', ''));
		if(markerTooltip!='') markerParams.push('label:'+escape(markerTooltip));
		// FIXME: label color, label overlay color, label size

		coords=false;
		// as addresses
		if (document.getElementById("markerTypeCHECKBOX").checked) {
			var address=markers[i].getTitle();
			if(address !== undefined && address != ''){
				coords=markers[i].getTitle().replace(" ", "+", "g");
			}
		}
		if(coords===false){
			var ig=map.toIngame(markers[i].getLatLng());
			var coords=ig.x.toFixed(0) + "," + ig.y.toFixed(0);
		}
		markerParams.push(coords);
		params.push('markers='+markerParams.join('|'));
	}

	for (var i = 0; i < polys.length; i++) {
		var poly = polys[i];
		var polyParams = [];
		var polyLength = 0;
		var lastVertex;
		var mixedContinents = false;
		for (var j = 0; j < poly.getVertexCount(); j++) {
			var ig=map.toIngame(poly.getVertex(j));
			polyParams.push(ig.x.toFixed(0) + "," + ig.y.toFixed(0));
			if(j>0){
				// test for last element because first might be town
				if(lastVertex.regions[lastVertex.regions.length-1] != ig.regions[ig.regions.length-1]){
					mixedContinents = true;
				}else{
					polyLength+=lineLength(lastVertex.x, lastVertex.y, ig.x, ig.y);
				}
			}
			lastVertex = ig;
		}
		if(poly.color!==undefined && poly.color!='') {
			var opacity = Math.floor(poly.opacity*255);
			var alpha = opacity<16 ? '0'+opacity.toString(16) : opacity.toString(16);
			polyParams.push('color:0x'+poly.color.replace('#', '')+alpha);
		}
		if(poly.weight!==undefined && poly.weight!='') polyParams.push('weight:'+poly.weight);
		if(poly.tooltip!==undefined && poly.tooltip!='') polyParams.push('label:'+escape(poly.tooltip));

		if(poly.do_fill){
			var opacity = poly.fillopacity*255;
			var alpha = opacity<16 ? '0'+opacity.toString(16) : opacity.toString(16);
			if(poly.fillcolor!==undefined && poly.fillcolor!='') polyParams.push('fillcolor:0x'+poly.fillcolor.replace('#', '')+alpha);
		}
		params.push("path=" + polyParams.join("|"));
		$('#polyLength'+i).html('(length '+polyLength.toFixed(1)+'m'+(mixedContinents ? ', mixed' : '')+')');
	}
	if (map.isIgMap()) {
		params.push("maptype=satellite");
	}else{
		params.push("maptype=atys");
	}

	params.push("size=" + document.getElementById("mapWidthTEXT").value + "x" + document.getElementById("mapHeightTEXT").value);
	//var img = document.createElement("img");
	//img.src = baseUrl + params.join("&");
	//document.getElementById("staticMapIMG").innerHTML = "-disabled-";
	//document.getElementById("staticMapIMG").appendChild(img);
	
	document.getElementById("staticMapURL").value = baseUrl + params.join("&");
	document.getElementById('staticLINK').href=baseUrl+params.join('&');
}


function createPolyAt(latlng) {
	var poly = new GPolyline([latlng]);
	map.addOverlay(poly);
	poly.enableDrawing();
	poly.color = '#0000ff';
	poly.opacity = 0.8;
	poly.weight = 3;
	poly.tooltip = ''; // my param
	
	editingNow = true;
	GEvent.addListener(poly, "mouseover", function() {
		poly.enableEditing();
	});
	GEvent.addListener(poly, "mouseout", function() {
		poly.disableEditing();
	});
	GEvent.addListener(poly, "lineupdated", function() {
		updateImage();
	});
	GEvent.addListener(poly, "endline", function() {
		editingNow = false;
	});
	polys.push(poly);
	updateList();
}

function createMarkerAt(latlng, icon, address) {
	address=address || '';
	var marker = new GMarker(latlng, {icon:RyzomIcons[icon].copy(), draggable:true, title: address});
	marker.tooltip=address || icon;
	marker.icon=icon;

	GEvent.addListener(marker, 'dragend', function() {
		updateImage();
	});
	map.addOverlay(marker);
	markers.push(marker);
	// redraw markers/polys list
	updateList();
}

function clearMarkers() {
	for (var i = 0; i < markers.length; i++) {
	map.removeOverlay(markers[i]);
	}
	markers = [];
	updateImage();
	updateList();
}

function clearPolys() {
	for (var i = 0; i < polys.length; i++) {
		map.removeOverlay(polys[i]);
	}
	polys = [];
	updateImage();
	updateList();
}

function updateList(){
	$('#list').html('');
	for(var i=0;i<markers.length;i++){
  		var $li = $('<li><span onclick="toggle_edit('+i+', \'marker\', this);" style="cursor:pointer;">(edit)</span> Marker #'+i+': '+markers[i].tooltip+'</li>');
		create_editMarker(i, $li);
		$('#list').append($li);
	}
	for(var i=0;i<polys.length;i++){
		var $li=$('<li><span onclick="toggle_edit('+i+', \'poly\', this);" style="cursor:pointer;">(edit)</span> Poly #'+i+': polyline/polygon<span id="polyLength'+i+'"></span></li>');
		create_editPoly(i, $li);
		$('#list').append($li);
	}
}

function toggle_edit(i, id, span){
	id=id+'_'+i;
	if(span.editing){
		span.editing=false;
		$(span).html('(edit)');
		$('#'+id).hide();
	}else{
		span.editing=true;
		$(span).html('(close)');
		$('#'+id).show();
	}
}
/**
 * Show icon selection popup
 */
function selectMarkerIcon(i, img){
	var h=[];
	var $ul = $('<ul style="list-style-type: none; margin: 0; padding: 0; overflow: auto;width: 150px; height: 100px; background-color: white; border: 1px solid black; position: absolute; z-index: 100;"/>');
	for(var icon in RyzomIcons){
		if(RyzomIcons[icon] instanceof GIcon && RyzomIcons[icon]._name !== undefined){
			$('<li style="width:32px; height:32px; display: inline; margin: 0; padding: 0;" icon="'+icon+'"><img src="'+RyzomIcons[icon].image+'" alt=""/></li>')
				.click(function(e){
					var icon=$(this).attr('icon');
					img.src=RyzomIcons[icon].image;
					marker_param(i, 'icon', icon);
					$ul.remove();
				})
				.appendTo($ul);
		}
	}
	$(img).after($ul);
//	var $cont = $('ul');
//	$cont.append(h.join());
//	$cont.css({display: 'absolute'});
//	$(img).prepend($cont);
//	$cont.show();
//	$(img).parentNode().append($cont);
}

function create_editMarker(i, div){
	var marker=markers[i];
	var $html=$(''+
		'<table class="alert small" id="marker_'+i+'">'+
			'<tr>'+
				'<td><div style="width:32px; height: 32px; float: left;"><img src="'+marker.getIcon().image+'" onclick="selectMarkerIcon('+i+', this);"/></div></td>'+
				'<td colspan="3">Name (optional)</td>'+
			'</tr>'+
			'<tr>'+
				'<td colspan="4"><input type="text" value="'+marker.tooltip+'" onchange="marker_param('+i+',\'tooltip\', this.value);" /></td>'+
			'</tr>'+
		'</table>').hide();
	$(div).append($html);
}

function create_editPoly(i, div){
	var poly=polys[i];
	// poly color, fill color, weight, name, name size/color/outline
	var $html=$(''+
		'<table class="alert small" id="poly_'+i+'">'+
			'<tr>'+
				'<td colspan="4">Name (optional)</td>'+
			'</tr>'+
			'<tr>'+
				'<td colspan="4"><input type="text" value="'+poly.name+'" onchange="poly_param('+i+',\'tooltip\', this.value);" /></td>'+
			'</tr>'+
			'<tr>'+
				'<td colspan="2" style="font-weight: bold;">Line style</td>'+
				'<td colspan="2" style="font-weight: bold;">Fill <input type="checkbox" onchange="poly_param('+i+', \'do_fill\', this.checked);"/></td>'+
			'</tr>'+
			'<tr>'+
				'<td>Line color</td>'+
				'<td><input type="text" size="6" class="color" value="'+poly.color+'" onchange="poly_param('+i+', \'color\', \'#\'+this.value, true);" /></td>'+
				'<td>Fill color</td>'+
				'<td><input type="text" size="6" class="color" value="'+poly.color+'" onchange="poly_param('+i+', \'color\', \'#\'+this.value, true);" /></td>'+
			'</tr>'+
			'<tr>'+
				'<td>Line opacity (%)</td>'+
				'<td><input type="text" size="6" value="'+Math.floor(poly.opacity*100)+'" onchange="poly_param('+i+', \'opacity\', this.value, true);" /></td>'+
				'<td>Fill opacity (%)</td>'+
				'<td><input type="text" size="6" value="80" onchange="poly_param('+i+', \'fillopacity\', this.value, true);" /></td>'+
			'</tr>'+
			'<tr>'+
				'<td>Line width (pixels)</td>'+
				'<td><input type="text" size="3" value="'+poly.weight+'" onchange="poly_param('+i+', \'weight\', this.value, true);" /></td>'+
				'<td colspan="2"></td>'+
			'</tr>'+
		'</table>').hide();
	$html.find('.color').each(function(){
			var color=new jscolor.color(this);
	});
	$(div).append($html);
}

function marker_param(i, param, val, refresh){
	if(param=='icon'){
		var icon=RyzomIcons[val];
		var m=new GMarker(markers[i].getLatLng(), { icon:icon.copy(), draggable: true, title: markers[i].getTitle()});
		m.tooltip=markers[i].tooltip;
		m.icon=val;
		m._iconName=icon._name;
		map.removeOverlay(markers[i]);
		markers[i]=m;
		map.addOverlay(m);
	}else{
		markers[i][param]=val;
	}
	if(refresh){
		markers[i].redraw(true);
	}
	updateImage();
}

function poly_param(i, param, val, refresh){
	// strokeColor, strokeWeight, strokeOpacity
	// fillColor, fillOpacity
	//
	// polyline:
	// opacity 0.0 to 1.0
	//
	//FIXME: if setting do_fill, we must convert polyline to polygon and vice versa
	
	switch(param){
		case 'do_fill':
			// FIXME: convert to GPolyliine / GPolygon
			break;
		case 'fillopacity': // fall thru
		case 'opacity'  : polys[i][param]=val/100; break;
		case 'weight'   : polys[i]['strokeWeight']=val; break;
		case 'fillcolor': polys[i]['strokeColor']=val; break;
		default:
			polys[i][param]=val;
	}
	if(refresh){
	   polys[i].redraw(true);
	}
	updateImage();
}

function showAddress() {
	var address = document.getElementById("addressTEXT").value;
	$.getJSON('/geo', {q: address}, function(data){
		if(!data){
			alert(address + ' not found');
		}else{
			map.igCenter(data.x, data.y);
			createMarkerAt(map.fromIngame(data.x, data.y), 'MARKER', '');
			updateImage();
		}
	});
}

/**
 * Init UI
 */
function load() {
	if (GBrowserIsCompatible()) {
		map = new RyzomMap('map', 5, 1, 11);

		// map labels
		mapLabels=new RyzomMapLabelOverlay('en', true);
		map.addOverlay(mapLabels);
		mapLanguage = new RyzomMapLabelControl(mapLabels);
		mapLanguage.doLabelChange = function(obj, lang, target){
		if(target){
			$(':hidden', target.parentNode).show();
				$(target).hide();
			}
		};
		map.addControl(mapLanguage);

		map.addControl(new RyzomNavLabelControl());
		//map.addMapType(G_PHYSICAL_MAP);
		//map.addControl(new GSmallMapControl());
		//map.addControl(new GMapTypeControl());
		GEvent.addListener(map, "moveend", function(marker, point) {
			updateImage();
		});
		GEvent.addListener(map, "maptypechanged", function(marker, point) {
			updateImage();
		});
		GEvent.addListener(map, "click", function(overlay, latlng) {
			if (latlng && !editingNow) {
				createPolyAt(latlng);
			}
			updateImage();
		});

		function append_icon(icon){
			$('<li><img src="'+RyzomIcons[icon].image+'" alt="'+i+'"/></li>').appendTo('#icons').click(function(e){
				createMarkerAt(map.getCenter(), icon, '');
			}).hover(function(){ $(this).addClass('hover');}, function(){ $(this).removeClass('hover');});
		}

		var icons = [];
		for(var i in RyzomIcons){
			if(RyzomIcons[i] instanceof GIcon && RyzomIcons[i]._name !== undefined){
				append_icon(i);
			}
		}

		// refresh static image
		updateImage();

//		// import URL if possible
		import_from(window.location.href);
	}
}
