var map;                                                                                                                                                                  
var lon="";                                                                                                                                                               
var lat="";                                                                                                                                                               
var zoom="";                                                                                                                                                              
var markers;

OpenLayers.Util.onImageLoadErrorColor="transparent";

function gotoLatLon(lat, lon) {
  var pos = new OpenLayers.LonLat(lon, lat);
  pos.transform(map.displayProjection,map.projection);
  map.setCenter(pos, 18);

  var m = markers.markers;
  for (var i = 0; i < m.length; i++) {
    markers.removeMarker(m[i]);
  }

  markers.addMarker(new OpenLayers.Marker(pos));
}


function myFormat(lonLat) {
        var digits = parseInt(this.numdigits);
        var newHtml =                         
                "Lon: " +                     
                lonLat.lon.toFixed(digits) +  
                " Lat: " +                    
                lonLat.lat.toFixed(digits) +                                                                                                                                        
                " Zoom: " +                                                                                                                                                         
                this.map.getZoom();                                                                                                                                                 
        return newHtml;                                                                                                                                                             
};                                                                                                                                                                                  

function onFeatureUnselect(feature) {
	map.removePopup(feature.popup);
	feature.popup.destroy();
	feature.popup = null;
}

function onPopupClose(evt) {
	selectControl.unselect(selectedFeature);
}

function onFeatureSelect(feature) {
	selectedFeature = feature;

	osm_id  = feature.fid;

        popup = new OpenLayers.Popup.FramedCloud("chicken", 
                                     feature.geometry.getBounds().getCenterLonLat(),
                                     new OpenLayers.Size(400,200),
                                     "<div style='font-size:.8em; width: 350px;'><h3>"+feature.attributes.name+"</h3><form method='post'><input type='hidden' name='id' value'"+osm_id+"' /><input type='text' name='email' value='uw e-mail adres' onfocus='if(this.value==\'uw e-mail adres\') {this.value=\'\';}'><input type='submit' value='Sla op' /></form></div>",
                                     null, true, onPopupClose);
        
	
	feature.popup = popup;
        map.addPopup(popup);
	popup.autoSize = true; 
}

function init(name,lon,lat,zoom){
        var center = center = new OpenLayers.LonLat(lon,lat);
        map = new OpenLayers.Map(               
                name,                           
                {                               
                        maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508),
                        numZoomLevels: 18,                                                      
                        maxResolution: 156543,                                                  
                        units: 'm',                                                             
                        controls:[                                                              
                                new OpenLayers.Control.MouseDefaults(),                         
                                new OpenLayers.Control.Attribution({displayClass: "olAttribution"}),
				new OpenLayers.Control.ScaleLine({bottomOutUnits: ""}),
//				new OpenLayers.Control.PanZoomBar()
                        ],                                                                         
                        displayProjection: new OpenLayers.Projection("EPSG:4326"),                 
                        projection: new OpenLayers.Projection("EPSG:900913")                       

                });

        var layerMapnik = new OpenLayers.Layer.TMS(
                "Mapnik",
                ["http://tile.openstreetmap.nl/tiles/"],
                {
                        type:'png',
                        getURL:get_osm_url,
                        attribution: '<p style="font-size: x-small">Map data &copy; 2009 <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a><br /><a href="http://openstreetmap.org">OpenStreetMap.org</a> contributors</p>',
			transitionEffect: 'resize'
                }
        );

//            var stations = new OpenLayers.Layer.Vector("Stations", {
//                projection: new OpenLayers.Projection("EPSG:4326"),
//                strategies: [
//                        new OpenLayers.Strategy.BBOX(),
//                        new OpenLayers.Strategy.Cluster()
//                ],
//                protocol: new OpenLayers.Protocol.HTTP({
//                        url: "/stations.kml",
//                        format: new OpenLayers.Format.KML({
//                                extractStyles: true, 
//                                extractAttributes: true
//                        }),
//                })
//            });

	var stations = new OpenLayers.Layer.GML("KML", "/kml/points.kml", 
               {
	        projection: new OpenLayers.Projection("EPSG:4326"),
                format: OpenLayers.Format.KML, 
                formatOptions: {
                  extractStyles: true, 
                  extractAttributes: true
                }
               });

        map.addLayers([layerMapnik, stations]);
	selectControl = new OpenLayers.Control.SelectFeature(map.layers[1], {onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
	map.addControl(selectControl);
	selectControl.activate();

        map.setCenter(center.transform(map.displayProjection, map.projection), zoom);
//        map.addControl(new OpenLayers.Control.Permalink());

//        markers=new OpenLayers.Layer.Markers("Markers");
//        map.addLayer(markers);

	map.events.register('click', map, handleMapClick);
//	map.events.register('zoomend', map, handleZoom);
}

function get_osm_url (bounds) {
        var res = this.map.getResolution();
        var x = Math.round ((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
        var y = Math.round ((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
        var z = this.map.getZoom();
        var path = z + "/" + x + "/" + y + "." + this.type;
        var url = this.url;

        if (url instanceof Array) {
                url = this.selectUrl(path, url);
        }

        return url + path;
}

function handleMapClick(e) {
  	markers.clearMarkers();
	var lonlat = map.getLonLatFromViewPortPx(e.xy);
	markers.addMarker(new OpenLayers.Marker(lonlat));

	var newlonlat = lonlat.clone();
	newlonlat = newlonlat.transform(map.projection, map.displayProjection);

	selectedFeature = marker;

	osm_id  = "new";

        popup = new OpenLayers.Popup.FramedCloud("chicken", 
                                     feature.geometry.getBounds().getCenterLonLat(),
                                     new OpenLayers.Size(400,200),
                                     "<div style='font-size:.8em; width: 350px;'><h3>"+feature.attributes.name+" ("+feature.fid+")</h3><form method='post'><input type='hidden' name='id' value'"+osm_id+"' /><input type='text' name='postcode' value='de postcode' onfocus='if(this.value==\'de postcode\') {this.value=\'\';}' /><input type='text' name='huisnummers' value='huisnummers' onfocus='if(this.value==\'huisnummers\') {this.value=\'\';}'/><input type='text' name='email' value='uw e-mail adres' onfocus='if(this.value==\'uw e-mail adres\') {this.value=\'\';}'><input type='submit' value='Sla op' /></form></div>",
                                     null, true, onPopupClose);
        
	
	feature.popup = popup;
        map.addPopup(popup);
	popup.autoSize = true; 


//	document.getElementById('but_rmmarker').disabled = false;
//	document.getElementById('but_center').disabled = false;

}

function handleZoom(e) {
	document.getElementById('mapzoom').value = map.getZoom();
}


