Zee = window.Zee || {};

/**
 * Modal
 *
 * Manage modal headaches
 *
 * @author Julien Cabanès <jc@aaz.fr>
 * @version 0.1
 * @class Zee.Modal
 */
Zee.Modal = {
	PageController: new Zee.PageController({
		get: {
			'#/modal/::modalPath': function(request, modalPath){
				request.keepLooping = true;
				//console.log('modalPath', modalPath);
				Zee.Modal.open(modalPath);
			}
		}
	}),
	open: function(href) {
		Zee.Modal.close();
		window.setTimeout(function() {
			//console.log(href);
			$.get(href, function(data) {
				$('html, body').animate({scrollTop: 0}, 800);
				// Dangereux
				if (data.json==1) {
					Zee.Modal.create(data.title,data.content);
				}
				else {
					$('body').append(data);
				}
				rebase_anchors();
				$('#overlay').show();
			});
		}, 250);
	},
	close: function(callback) {
		if($('#modal').length > 0) {
			$('#modal, #overlay').animate({opacity: 0}, 300, function() {
				$('#overlay').hide().css({opacity: 0.5});
				$('#modal').remove();
				callback && typeof callback == 'function' && callback();
			});
		}
	},
	create: function(title, content) {
		$('#overlay').show();
		$('body').append([
			'<div id="modal">',
				'<a class="close" href="#" title="Fermer">Fermer</a>',
				'<h1>'+title+'</h1>',
				'<div class="richtext">'+content+'</div>',
			'</div>'].join(''));
			$('html, body').animate({scrollTop: 0}, 800);
	},
	onOpen: function(e) {
		e.preventDefault();
		Zee.Modal.open($(this).attr('href'));
	},
	onClose: function(e) {
		e.preventDefault();
		Zee.Modal.close();
	}
};

Zee.Modal.PageController.run();

$('#modal a.close,#modal a.cancel').live('click', function(e) {
	e.preventDefault();
	Zee.Modal.close();
	Zee.Modal.PageController.setHash(Zee.Modal.PageController.lastHash || '/');
});
