/*
 * L.Control.Fit
 */

L.Control.Fit = L.Control.extend({
	options: {
		position: 'topleft'
	},

	onAdd: function (map) {
		var fitName = 'leaflet-control-fit',
		    barName = 'leaflet-bar',
		    partName = barName + '-part',
		    container = L.DomUtil.create('div', fitName + ' ' + barName);

		this._map = map;

		this._fitMetroButton = this._createButton('<i class="icon-resize-small"></i>', 'Afficher la métropole',
				fitName + '-metro ' +
				partName + ' ' +
	                        partName + '-top',
				container, this._fitMetro,  this);
		this._fitWorldButton = this._createButton('<i class="icon-globe"></i>', 'Afficher le monde entier',
				fitName + '-world ' + 
				partName + ' ' +
	                        partName + '-bottom',
				container, this._fitWorld, this);

		map.on('zoomend', this._updateDisabled, this);

		return container;
	},

	onRemove: function (map) {
		map.off('zoomend', this._updateDisabled, this);
	},

	_fitMetro: function (e) {
                var metro = [ [41.1, -5.53], [51.5, 9.91] ];
		this._map.fitBounds(metro);
	},

	_fitWorld: function (e) {
		this._map.fitWorld();
	},

	_createButton: function (html, title, className, container, fn, context) {
		var link = L.DomUtil.create('a', className, container);
		link.innerHTML = html;
		link.href = '#';
		link.title = title;

		var stop = L.DomEvent.stopPropagation;

		L.DomEvent
		    .on(link, 'click', stop)
		    .on(link, 'mousedown', stop)
		    .on(link, 'dblclick', stop)
		    .on(link, 'click', L.DomEvent.preventDefault)
		    .on(link, 'click', fn, context);

		return link;
	},

	_updateDisabled: function () {
		var map = this._map,
			className = 'leaflet-control-fit-disabled';

		L.DomUtil.removeClass(this._fitMetroButton, className);
		L.DomUtil.removeClass(this._fitWorldButton, className);
	}
});

L.Map.mergeOptions({
	fitControl: true
});

L.Map.addInitHook(function () {
	if (this.options.fitControl) {
		this.fitControl = new L.Control.Fit();
		this.addControl(this.fitControl);
	}
});

L.control.fit = function (options) {
	return new L.Control.Fit(options);
};

