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 host;

function init(){
	map = new OpenLayers.Map ("map", {
        controls:[
            new OpenLayers.Control.Navigation(),
            new OpenLayers.Control.PanZoomBar(),
            new OpenLayers.Control.Attribution()
		],
        maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
        maxResolution: 156543.0399,
        numZoomLevels: 20,
        units: 'm',
        projection: new OpenLayers.Projection("EPSG:900913"),
        displayProjection: new OpenLayers.Projection("EPSG:4326")
    } );
	
	var layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");

	// 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.5'
			}
    };
    
    var selectStyles = {
        '#Blue': {
	    		strokeWidth: '1.5',
				fillColor: '#0000FF',
				strokeColor: '#0000FF',
				fillOpacity: '0.4'
			},
        '#Red': {
        		strokeWidth: '1.5',
				strokeColor: '#FF0000',
				fillColor: '#FF0000',
				fillOpacity: '0.5'
			}
    };
    
    // 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: "world.php",
		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);

    map.setCenter(new OpenLayers.LonLat(0, 0), 2);
    
    host = "planetosm.oxilion.nl/~lambertus/garmin/routable/" + version + "/";
    
    clearAll();
	//document.forms.controls.selectControl.checked=0;
}

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 updateList() {
	selectedCountry = "";
	var feature_info = OpenLayers.Util.getElement('feature_info');
	if (feature_info !== null) {
		var html;
		var files = vectors.selectedFeatures;

		if (files.length > 0) {
			html = "Selected tiles:<ul>";
			for (var i in files) {
				var name = files[i].attributes.name;
				
				var description = files[i].attributes.description;
				html += "<li><a href='" + 'http:///' + host + name + ".img'>" + description + "</a><input type='hidden' name='tile" + i + "' value='" + name + ".img'/></li>";
			}
			html += "</ul>";
		} else {
			html = "";
		}
		feature_info.innerHTML = html;
	} else {
		//window.open('http:///' + host + name);
	}
}

function selectionDone() {
	var i ;
	
	var files = vectors.selectedFeatures;
	OpenLayers.Util.getElement('email_form').innerHTML = "Checking existing maps... <img src='ajax-loader.gif'>";
	if (files !== null) {
		//Calculate MD5 sum
		var md5string = version;
		var items = [];
		for (i in files) {
			items.push(files[i].attributes.name);
		}
		items.sort();
		for (i in items) {
			md5string += ";"+items[i]+".img";
		}
		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}
			);	
	}
}

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;
}

function showEmail() {
	var email_form = OpenLayers.Util.getElement('email_form');
	html = "Email address:\n";
	html += "<input type='hidden' name='version' value='"+version+"'>\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;

	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 !== null) {
				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;
	selectionDone();
}

function clearAll() {
	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();
	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];
		}
	}
}
