/* by Matt Amos (stolen from his sandbox site) */

EditLinkControl = function() {};

EditLinkControl.prototype = {
	initialize: function(map) {
		this._map = map;
	
		var container = document.createElement('div');
		container.className = 'wml-permalink';
		
		//var backgroundLayer = document.createElement('div');
		//backgroundLayer.className = 'wml-text-background';
		
		this._link = document.createElement('a');
		this._link.innerHTML = 'Edit in OSM';
		this._link.className = 'wml-text-background';
		this._link.style['padding'] = '6px';

		this._spacer = document.createElement('span');
		this._spacer.innerHTML = '&nbsp;';
		
		this._link2 = document.createElement('a');
		this._link2.innerHTML = 'View in OSM';
		this._link2.className =  'wml-text-background';
		this._link2.style['padding'] = '6px';
		
		if (this._map.isLoaded()) {
			this._update();
		} else {
			CM.Event.addListener(this._map, 'load', this._update, this);
		}
		CM.Event.addListener(this._map, 'moveend', this._update, this);
		
		//container.appendChild(backgroundLayer);
		container.appendChild(this._link);
		container.appendChild(this._spacer);
		container.appendChild(this._link2);
				
		return container;
	},
	
	getDefaultPosition: function() {
		return new CM.ControlPosition(CM.BOTTOM_RIGHT, new CM.Size(0, 46));
	},
	
	remove: function(map) {
		CM.Event.removeListener(map, 'load', this._update, this);
		CM.Event.removeListener(map, 'moveend', this._update, this);
	},
	
	_update: function() {
		this._link.href = this._getPermalink();
		this._link2.href = this._getPermalink2();
	},
	
	_getPermalink: function() {
		function format(n) {
			var mod = Math.pow(10, 6);
			return Math.round(n*mod)/mod;
		}
		
		var center = this._map.getCenter(),
			lat = format(center.lat()),
			lng = format(center.lng()),
		        zoom = this._map.getZoom();

		var url = "http://osm.org/edit";
		url += '?lat=' + lat;
		url += '&lon=' + lng;
		url += '&zoom=' + zoom;
		return url;		
	},

	_getPermalink2: function() {
		function format(n) {
			var mod = Math.pow(10, 6);
			return Math.round(n*mod)/mod;
		}
		
		var center = this._map.getCenter(),
			lat = format(center.lat()),
			lng = format(center.lng()),
		        zoom = this._map.getZoom();

		var url = "http://osm.org/";
		url += '?lat=' + lat;
		url += '&lon=' + lng;
		url += '&zoom=' + zoom;
		return url;		
	},
};