var lon = 5;
var lat = 40;
var zoom = 5;
var map;
var mode, position;
var permalink, vectors; //, WindowLocation
var selectCtrl;
var files = [];
var selectedCountry;
var email = 'enter email address';
var html;
var countries_host;
var custom_host;
var version;
var typFile = "";
var bCLearing = false;

function init(){
	version = countries.version;
	
	if (available) {
		map = new OpenLayers.Map ("map", {
		    controls:[
		        new OpenLayers.Control.Navigation(),
		        new OpenLayers.Control.PanZoomBar(),
		        new OpenLayers.Control.Attribution()
			],
			//maxExtent: new OpenLayers.Bounds(-180, -80, 180, 80),
		    units: 'degrees',
		    projection: new OpenLayers.Projection("EPSG:900913"),
		    displayProjection: new OpenLayers.Projection("EPSG:4326")
		} );
	
		var options = {numZoomLevels: 10};	// This works
		//var options = {numZoomLevels: null, minZoomLevel: 8, maxZoomLevel: 10 };
		var layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik", options);

		// create a styleMap with a custom default symbolizer
		var styleMap = new OpenLayers.StyleMap({
		    fillOpacity: 1,
		    pointRadius: 10
		});

		// create a lookup table with different symbolizers for 0, 1 and 2
		var defaultStyles = {
		    '#Blue': {
					strokeWidth: '1.5',
					fillColor: '#0000FF',
					strokeColor: '#0000FF',
					fillOpacity: '0.1'
				},
		    '#Red': {
		    		strokeWidth: '1.5',
					strokeColor: '#FF0000',
					fillColor: '#FF0000',
					fillOpacity: '0.1'
				}
		};
		
		var selectStyles = {
		    '#Blue': {
					strokeWidth: '1.5',
					fillColor: '#0000FF',
					strokeColor: '#0000FF',
					fillOpacity: '0.4'
				},
		    '#Red': {
		    		strokeWidth: '1.5',
					strokeColor: '#FF0000',
					fillColor: '#FF0000',
					fillOpacity: '0.4'
				}
		};
		
		// add rules from the above lookup table, with the keyes mapped to
		// the "type" property of the features, for the "default" intent
		styleMap.addUniqueValueRules("default", "styleUrl", defaultStyles);

		styleMap.addUniqueValueRules("select", "styleUrl", selectStyles);
	
		var protocol = new OpenLayers.Protocol.HTTP({
			url: "transport.php?url=http://planetosm.oxilion.nl/~lambertus/garmin/routable/"+version+"/world.kml",
			format: new OpenLayers.Format.KML({
		                extractAttributes: true
		        	})
		});

		vectors = new OpenLayers.Layer.Vector("KML", {
			projection: map.displayProjection,
		    strategies: [new OpenLayers.Strategy.Fixed()],
		    protocol: protocol,
		    styleMap: styleMap,
		    eventListeners: {
		    	featuresadded: LoadKML
		    }
		});

		map.addLayers([layerMapnik, vectors]);
		
		selectCtrl = new OpenLayers.Control.SelectFeature(vectors, {
				onSelect: onFeatureSelect, 
				onUnselect: onFeatureUnselect,
				clickout: false, 
				toggle: true,
				multiple: true, 
				hover: false,
				box: false	// must be false to be able to select single tiles}
			});

		map.addControl(selectCtrl);
		countries_host = "planetosm.oxilion.nl/~lambertus/garmin/routable/" + version + "/";
		custom_host = "osm.pleiades.uni-wuppertal.de/garmin/routable/" + version + "/";
	
		// Start building the pull-down menus
		html = "<table><tr>\n";
		for (var i = 0; i < countries.continents.length; i++) {
			cont = countries.continents[i];
			html += "<td><SELECT style='width:150px;' TITLE='"+cont.name+"' NAME='"+cont.name+"' onChange='onCountrySelect(this);'>\n";
		   	html += "<OPTION VALUE='' SELECTED='selected' STYLE='font-style:italic' >"+cont.name+"\n";
		   	for (var j = 0; j < cont.countries.length; j++) {
		   		var k;
		   		country = cont.countries[j];
		   		html += "<OPTION NAME='"+country.name+"' VALUE='";
		   		if (country.hasOwnProperty("tiles")) {
			   		for (k = 0; k < country.tiles.length; k++) {
			   			tile = country.tiles[k];
			   			html += tile.nr+";";
			   		}
				}
				html += "'>"+country.name+"\n";
		   		if (country.hasOwnProperty("states")) {
		   			for (var l = 0; l < country.states.length; l++) {
			   			state = country.states[l];
			   			html += "<OPTION NAME='"+state.name+"' VALUE='";
			   			for (k = 0; k < state.tiles.length; k++) {
				   			tile = state.tiles[k];
				   			html += tile.nr+";";
				   		}
				   		html += "'>&mdash;&nbsp;"+state.name+"\n";
			   		}		   		
			   	}
		   	}
		   	html += "</SELECT></td>\n";
		}
		html += "</tr></table>\n";
		var feature_info = OpenLayers.Util.getElement('controls-form');
		feature_info.innerHTML = html;
		
		clearAll();
		map.setCenter(new OpenLayers.LonLat(0, 0), 2);
	}
}

function LoadKML(data) {
	var feature_info = OpenLayers.Util.getElement('feature_info');
	feature_info.innerHTML = "";
}

function enableSelection(e) {
	if (e.value == "select") {
		if (e.checked === true) {
			selectCtrl.activate();
		} else {
			selectCtrl.deactivate();
		}
	}
}
	
function onFeatureSelect(feature) {
	if (feature.attributes.styleUrl == '#Red') {
		// This tile does not exist -> deselect
		selectCtrl.unselect(feature);
		return;
	}
	updateList();
	showEmail();
}

function onFeatureUnselect(feature) {
	updateList();
	showEmail();
}

function sortFeatures(a,b)
{
	//console.log(a.attributes.name - b.attributes.name);
	return a.attributes.name - b.attributes.name;
}

var menus;
var arrCountries = Array();

function updateList() {
	var i;
	// load the list of countries only once
	if (typeof(menus) == 'undefined') {
	
		menus = OpenLayers.Util.getElement('controls-form');
		for (i = 0;i < menus.length; i++) {
			var menu = menus[i];
			var menuName = menus[i].name;
			//for (var j in menu.options) {

			for (var j =0; j < menu.options.length; j++) {
				var optionName = menu.options[j].text;
				var optionValue = menu.options[j].value;
				if (!(optionName == undefined) && !(optionValue == undefined)) {
					if (optionName.length > 0 && optionValue.length > 0) {
						//console.log(optionName+" "+optionValue);
						var tileString = "";
						var tiles = optionValue.substr(0, optionValue.length-1).split(';').sort();
						for (k in tiles) {
							tileString += tiles[k]+";";
						}
						arrCountries.push(new Array(optionName, tileString));
					}
				}
			}
		}
	}
	
	if (!bClearing) {
		var tilelist ="";
		var feature_info = OpenLayers.Util.getElement('feature_info');
		if (feature_info !== null) {
			var html = "";
			var files = vectors.selectedFeatures;

			if (files.length > 0) {
				files.sort(sortFeatures);
		
				for (i in files) {
					var name = files[i].attributes.name;
				
					tilelist += files[i].attributes.name+';';
				
					var description = files[i].attributes.description;
					html += "<li><a href='" + 'http:///' + countries_host + name + ".img'>" + description + "</a><input type='hidden' name='tile" + i + "' value='" + name + ".img'/></li>";
				}
				html += "</ul>";
			
				// Check if the current tile selection matches a country
			
				//alert("updateList");
				selectedCountry = "";
				if (tilelist.length>0) {
					for (i in arrCountries) {
						country = arrCountries[i];
						if (country[1].length == tilelist.length) {
							if (country[1] == tilelist) {
								selectedCountry = country[0];
								selectionDone();				// Enable this line if we only want to check for existing country maps 
								break;
							}
						}
					}
					selectionDone();	// Disable this line if we only want to check for existing country maps
				}
			
				html = "Selected tiles:<br><i>"+selectedCountry+"</i><ul>"+html;
				html+= "<input type='hidden' name='country' value='" + selectedCountry + "'/>";
			} else {
				html = "";
			}
			feature_info.innerHTML = html;
		}
	}
}

function selectionDone() {
	var i ;
	
	var files = vectors.selectedFeatures;
	if (files !== null) {
		if (files.length > 0) {
			OpenLayers.Util.getElement('email_form').innerHTML = "Checking existing maps... <img src='ajax-loader.gif'>";
		
			//Calculate MD5 sum
			var md5string = version+";"+typFile;
			var items = [];
			for (i in files) {
				items.push(files[i].attributes.name);
			}
			items.sort();
			for (i in items) {
				md5string += ";"+items[i]+".img";
			}
			//alert(md5string);
			md5sum = MD5(md5string);
		
			//See if the dir exists
			new OpenLayers.Ajax.Request('exists.php',
			            {method:'post',
			                asynchronous: true,
			                contentType:'application/x-www-form-urlencoded',
			                onComplete: onSuccess,
			                postBody: "md5sum=" + escape(md5sum) + "&version=" + version + "&country=" + selectedCountry}
				);
		}
	}
}

function onSuccess(e) {
	if (e.responseText.length > 0) {
		showDownloadNow(e.responseText);
	} else {
		showEmail();
	}
}

function onFailure(e) {
	showEmail();
}

function showDownloadNow(url) {
	var email_form = OpenLayers.Util.getElement('email_form');
	html = "<a href='"+url+"'>Download map now!</a>";
	email_form.innerHTML = html;
}

var form;
function showEmail() {
	form = OpenLayers.Util.getElement('combine');
	if (selectedCountry.length > 0) {
		//alert("country");
		form.action = "http://planetosm.oxilion.nl/~lambertus/garmin/routable/request-combine.php";
	} else {
		//alert("custom");
		form.action = "http://osm.pleiades.uni-wuppertal.de/garmin/routable/request-combine.php";
	}
	var email_form = OpenLayers.Util.getElement('email_form');
	html = "Email address:\n";
	html += "<input type='hidden' name='version' value='"+version+"'>\n";
	html += "<input type='hidden' name='typ' value='"+typFile+"' />\n";
	html += "<input type='text' name='email' value='"+email+"' />\n";
	html += "<input type='submit' value='Build my map' />\n";
	email_form.innerHTML = html;
}

function saveEmail() {
	if (document.forms['combine'].email != undefined) {
		email = document.forms['combine'].email.value;
		//alert(email);
	}
	
//combine =  document.forms['combine'];
	//email =combine.childNodes['email'].defaultValue;
	//alert(email);
	//OpenLayers.Util.getElement('email').innerHTML = "";
}

var selected;	//temporary
function onCountrySelect(selection) {
	// Clear the current selection
	clearSelection();

selected = selection;	//temporary

	var i;
	if (selection.value.length > 0) {
		var new_files = [];
		arr_files = selection.value.split(";");
		
		if (arr_files.length > 1) {
			
			for (i = 0; i < arr_files.length-1; i++) {
				var vector = getFeatureByName(arr_files[i]);
				if (vector != 'undefined') {
					if (vector !== null) {
						if (vector.attributes.styleUrl != '#Red') {
							selectCtrl.select(vector);
						}
					}
				}
			}
		
			// Zoom to the selected tiles
			var fts = vectors.selectedFeatures;
			var bounds = fts[0].geometry.getBounds().clone();
			for(i = 1; i < fts.length; i++) {
				bounds.extend(fts[i].geometry.getBounds());
			}
			map.zoomToExtent(bounds,false);
		}
		//selectedCountry = selection[selection.selectedIndex].attributes['name'].value;
	}
	//alert("onCountrySelect");
	//selectionDone();	// This causes a second call to exists.php and should not be necessary. Test.
}


function onTypSelect(selection) {
	typFile = selection.value;
	
	selectionDone();
}

function clearAll() {
	bClearing = true;
	for (i = 0; i < document.forms.length; i++) {
    	for (j = 0; j < document.forms[i].elements.length; j++) {
    		//alert(document.forms[i].elements[j].type);
    		if (document.forms[i].elements[j].type == "select-one") {
    			document.forms[i].elements[j].selectedIndex=0;
			}
		}
	}
	
	clearSelection();
}

function clearSelection() {
	
	saveEmail();
	selectCtrl.unselectAll();
	bClearing = false;
	updateList();
	OpenLayers.Util.getElement('email_form').innerHTML = "";
/*
	while (vectors.selectedFeatures.length > 0) {
		onFeatureUnselect(vectors.selectedFeatures[0]);
	}
	//alert(selectedCountry);
*/
	
}

function getFeatureByName(name) {
	for (var i = 0; i < vectors.features.length; i++) {
		if (vectors.features[i].attributes.name == name) {
			return vectors.features[i];
		}
	}
	return null;
}

