dojo.require("dojo.cookie");

var handlers = [];
var objDialog = null;

function closeDialog(e) {
	if( e )
		dojo.stopEvent(e);
	
	if(objDialog)
		objDialog.hide();
	
	if(!dojo.isIE)
		objDialog.destroy();
	
	dojo.disconnect(handlers[0]);
	dojo.disconnect(handlers[1]);
	
	handlers = [];
	objDialog = null;
}

function catchAClick(e) {
	var target = e.target;
	// On remonte l'arborescence DOM jusqu'a ce qu'on croise une ancre
	while( target != null && target.nodeName.toLowerCase() != 'a' ) {
		target = target.parentNode;
	}
	if( target == null || target.nodeName.toLowerCase() != 'a' )
		return;
	
	// On a cliquer sur un lien de popup
	if( dojo.hasClass(target, "popup") && target.href ) {
		dojo.stopEvent(e);
		dojo.require("dijit.Dialog");
		
		openDialog(target.href);
	}
}

// Ouvre une popup avec l'url donné en paramètre
function openDialog(href) {
	if( objDialog )
		closeDialog();
	// Creation de la popup
	objDialog = new dijit.Dialog({
		content: "<iframe src='"+href+"' style=\"width: 800px; height: 480px\" onload=\"iframeLoaded();\" />",
		"class": "tundra",
		"title": "Médiathèque"
	});
	
	var iframe = objDialog.containerNode.firstChild;
	
	// Attente du chargement de l'iframe ( hack IE )
	window.iframeLoaded = function(){
		// Document dans l'iframe
		var iDocument = iframe.contentWindow.document;
		
		var object = iDocument.getElementById("media");
		if( object ) {
			var max = -1;
			var list = dojo.query("> *", object);
			dojo.forEach(list, function(item){
				var box = dojo.contentBox(item);
				max = Math.max(max, box.w);
			});

			max += 20;
			dojo.style(iframe, "width", max+'px');
			objDialog.layout();
		}
	};
	
	objDialog.show();
	
	// Lorsqu'on clique n'importe ou avec la souris on ferme la popup
	handlers[0] = dojo.connect(dojo.body(), "mousedown", closeDialog);
	// Surcharge du clic sur la croix de la popup
	handlers[0] = dojo.connect(objDialog, "onCancel", closeDialog);
}

dojo.addOnLoad(function() {
	dojo.connect(dojo.body(), "click", null, catchAClick);
	// Recherche des popup auto-ouvrants
	var auto = dojo.query("a.popup.autoopen");
	// Ouverture du 1er popup uniquement
	if( auto.length ) {
		var href = auto[0].href;
		var shorthref = href.substring(href.lastIndexOf('/')+1, href.length);
		shorthref = shorthref.replace(/[^0-9a-zA-Z_-]/g, '_');
		console.log(shorthref);
		
		// La popup avec ce lien a t elle déjà été ouverte
		var open = dojo.cookie("notfirst_"+shorthref);
		
		if( open == undefined && dojo.cookie.isSupported() )
			openDialog(href);
		
		dojo.cookie("notfirst_"+shorthref, true, {expires: 360});
	}
})

