/**
 * Initialisation
 */
$(document).ready
(
    function () 
    {
		dp.addMenuInteractor();
		if($("#console").length) {
			$("#console").bind(
				"click",
				function (e) {
					if($("#console").css("height") == "300px")
						$("#console").css("height","20px");
					else
						$("#console").css("height","300px");
				}
			);
			$("#console").bind(
				"dblclick",
				function (e) {
					$("#console").html('');
				}
			);
		}
		if($("#myUrlLoader").length) {
			$("#myUrlLoader").bind(
				"keydown",
				"return",
				function() {
					if($('#myUrlLoader').val().substring(0,7) == "http://" 
							|| $('#myUrlLoader').val().substring(0,1) == "/") {
						dp.openUrl($('#myUrlLoader').val());
					} else {
						dp.search($('#myUrlLoader').val());
					}
					$('#myUrlLoader').val('');
				}
			);
		}
		if($("#refreshMenu").length) {
			$("#refreshMenu").click(
				function() {
					dp.refreshMenu();
				}
			);
		}
    }
);

/**
 * Fonction D&P
 */
var dp={
	addMenuInteractor:function() {
        $("#MENU .window").each(
            function (i) {                
				$(this).bind(
					"click",
					function(){
						eval("dp.newWindow($(this).attr(\"id\"), $(this).attr(\"title\"),"+$(this).attr("rel")+", true);");
					}
				);
            }
        );
        $("#MENU .url").each(
            function (i) {
				$(this).bind(
					"click",
					function(){
						eval("dp.newWindow($(this).attr(\"id\"), $(this).attr(\"title\"),{URL:\""+$(this).attr("rel")+"\"}, true);");
					}
				);
            }
        );
	},
	refreshMenu:function() {
		$("#MENU > ul").html('<img src="/images/loadingv.gif"/> Chargement...');
		$("#MENU > ul").load("/DPWindows.php?refreshMenu=true", function() {dp.addMenuInteractor()});
		$("#todoListe").html('<img src="/images/loadingv.gif"/> Chargement...');
		$("#todoListe").load("/DPWindows.php?DAO=Todo&action=liste");
	},
    saveNotesMJ:function(myForm) {
        if($("textarea[name=notesMJ]", myForm).val() == "") {
            $("input[name=action]", myForm).val("DeleteNotesMJ");
        }
        myForm.ajaxSubmit({dataType:'script'});
    },
    // Nombre de fenêtre lancé avec openUrl
    nbExec:0,
    // Fonction ouvrant une adresse web dans une frame
    openUrl:function(myUrl) {
        this.nbExec++;
        this.newWindow(
            "Execute"+this.nbExec, (arguments[1] ? arguments[1]:"Navigateur "+this.nbExec), 
            {URL:myUrl}, 
            true
        );
    },
	// Fonction ouvrant les évènements d'un personnage
	ouvrirEvenements:function(id, pseudo) {
		this.newWindow(
			"Evenements"+id, 
			"Évènements - "+pseudo, 
			{URL:"/evenement.php?id_perso_a_voir="+id+"&accesMJ=1",size:"rightSide"}, 
			true
		);    		
	},
	// Fonction ouvrant la carte admin sur la vue d'un personnage
	ouvrirVueCarte:function(id, pseudo) {
		this.newWindow(
			"VueCarte"+id, 
			"Carte - "+pseudo, 
			{URL:"/admin/Carte.php?repartition=2&vueText="+id+"&PersoNo=on&MonstreNo=on&QGNo=on&LieuNo=on&ObjetNo=on&TresorNo=on&special=on&specialSuppr=on&specialDepl=on",size:"rightSide"}, 
			true
		);    
	},
	// Fonction ouvrant la carte admin centré sur une coordonnée
	ouvrirPosCarte:function(x,y,z) {
		this.newWindow(
			"VueCarte"+x+"_"+y+"_"+z,
			"Carte - "+x+" / "+y+" / "+z,
			{URL:"/admin/Carte.php?repartition=2&cameraX="+x+"&cameraY="+y+"&cameraZ="+z+"&cameraPortee=12&vueCamera=Cam%E9ra&PersoNo=on&MonstreNo=on&QGNo=on&LieuNo=on&ObjetNo=on&TresorNo=on&special=on&specialSuppr=on&specialDepl=on",size:"rightSide"}, 
			true
		);
	},
    // Fonction ouvrant la fenêtre d'édition de message avec le destinataire id
    ecrireMessage:function(id)
    {
        this.newWindow(
            "EcrireMessage"+id, 
            (arguments[1] ? arguments[1]:"Ecrire un message"), 
            {URL:"/messagerie/ecrire_message.php?id_receveur="+id,size:"rightSide"}, 
            true
        );
    },
    // Fonction ouvrant la fenêtre d'édition de message avec le destinataire id
    ecrireMessageFrom:function(from, to)
    {
        this.newWindow(
            "EcrireMessage"+from+"_"+to,
            (arguments[2] ? arguments[2]:"Ecrire un message"), 
            {URL:"/messagerie/ecrire_message.php?persoID="+from+"&id_receveur="+to,size:"rightSide"}, 
            true
        );
    },    
    // Fonction ouvrant le profil d'un aventurier.
    profilAdmin:function(id)
    {
        this.newWindow(
            "ProfilAdmin"+id, 
            (arguments[1] ? arguments[1]:"Administration du Profil"), 
            {URL:"/voir_aventurier.php?onglet=1&id_perso_a_voir="+id,size:"fullSize"}, 
            true
        );
    },
	// Fonction ouvrant la fiche d'un type d'objet
    typeObjet:function(id)
    {
        this.newWindow(
            "TypeObjet"+id, 
            (arguments[1] ? arguments[1]:"Type d'objet"), 
            {URL:"/type_objet.php?id_type_objet="+id,size:"fullSize"}, 
            true
        );
    },
    consulterMessagerie:function(id)
    {
        this.newWindow(
            "ConsulterMessagerie"+id,
            (arguments[1] ? arguments[1]:"Messagerie"),
            {URL:'/messagerie/consulter_messagerie?persoID='+id,size:"rightSide"},
            true
        );
    },
    loadDAO:function(DAO)
    {
        if(!$('head link[href=/css/'+DAO+'.css.php]').length)
            $("head").append('<link rel="stylesheet" type="text/css" href="/css/'+DAO+'.css.php"/>');
        if(typeof DAO != "undefined" && eval("typeof "+DAO+"Loaded") == "undefined") {
            eval(DAO+"Loaded = true;");
            $.getScript("/javascript/"+DAO+".js");
        }
    },
    // Fonction ouvrant une fenêtre la chargeant avec le retour de la requête
    // ajax spécifié dans myAction sur le framework
    newWindow:function(id, titre, myAction) 
    {
        // Création du div et chargement s'il n'existe pas
		if($('#window_'+id).length) {
			$('#window_'+id).remove();
		}
		var fenetre =
			'<div class="jqmAlert"     id="window_'+id+'">'+
			'<div class="jqmAlertWindow" id="window_'+id+'">' +
			'<div class="jqmAlertTitle clearfix jqDrag" rel="window_'+id+'">' +
			'<h1>'+titre+'</h1>'+
			'<a href="#" class="jqmClose"><em>Fermer</em></a>' +
			'<a href="#" class="jqmMinimize"><em>Réduire</em></a>' +
			'<a href="#" class="jqmRefresh"><em>Rafraichir</em></a>' +
			'</div>' +
			'<div class="jqmAlertContent">' +
			'</div>' +
			'<img src="/optim/www/images/resize.png" alt="resize" class="jqResize jqHandle"/>' +
			'</div>' +
			'</div>';

		$('body').prepend(fenetre);
		
		$('#window_'+id)
			.jqDrag('.jqDrag')
			.jqm({
				ajax: "/DPWindows.php",
				ajaxText: '<p><img src="/images/loadingv.gif" width="15px" alt="loading"/> Chargement...</p>',
				ajaxParam: myAction,
				trigger: '#'+id,
				overlay: 0,
				topTop: true,
				target: '.jqmAlertContent',
				onShow: function(h) {
					/* callback executed when a trigger click. Show notice */
					h.w.css('opacity',1).show();
					dp.focusOn(h.w.attr("id").replace(new RegExp("(window_)", "g"),""));
				},
				onHide: function(h) {
					/* callback executed on window hide. Hide notice, overlay. */
					h.w.hide();
					if(h.o) h.o.hide();
				}
			});
		
		$('#window_'+id+' .jqmAlert .jqmMinimize').click(
			function() {
				var myId = $(this).parent().attr("rel").replace(new RegExp("(window_)", "g"),"");
				if(!$("#barreTaches #Bouton_"+myId).length) {
					$('#barreTaches').append(
						"<div id='Bouton_"+myId+"' class='boutonTache' title='"+$("h1", $(this).parent()).html()+"'>" + 
							$("h1", $(this).parent()).html()+
						"</div>");
					$("#Bouton_"+myId).click(
						function() {
							var myId = $(this).attr("id").replace(new RegExp("(Bouton_)", "g"),"");
							$("#window_"+myId+".jqmAlert").show();
							$("#window_"+myId+".jqmAlertWindow").show();
							dp.focusOn(myId);
							$(this).remove();
						}
					);
					$("#window_"+myId+".jqmAlert").hide();
					$("#window_"+myId+".jqmAlertWindow").hide();
				}
				return false;
			}
		);


		$('#window_'+id+' .jqmAlertWindow').jqResize('.jqResize');

		$("#window_"+id+" .jqmAlertWindow .jqmAlertTitle").bind(
			"click",
			function(evt) {
				dp.focusOn($(this).attr("rel").replace(new RegExp("(window_)", "g"),""));
				return false;
			}
		);
		$("#window_"+id+" .jqmAlertWindow .jqmAlertTitle").bind(
			"dblclick",
			function(evt) {
				dp.toggleMax($(this).attr("rel"));
				return true;
			}
		);
		// Chargement des fichiers spécifiques à la DAO
		if(typeof myAction.DAO != "undefined" && myAction.DAO != "") {
			this.loadDAO(myAction.DAO);
		}
        if(arguments[3]) {
            $('#window_'+id).jqmShow();
            dp.focusOn(id);
        }
        switch(myAction.size) {
            case "leftSide":
                dp.leftSide(id);
                break;
            case "rightSide": 
                dp.rightSide(id);
                break;
            case "fullSize":
                dp.fullWindow(id);
                break;
            case "mediumSize":
                dp.mediumWindow(id);
            break;
            default:
                dp.defaultSize(id);
                break;
        }
    },
    focusOn:function(id) {
        $(".jqmAlert").css("z-index", 2);
        $("#window_"+id+".jqmAlert").css("z-index", 1000);

    },
    toggleMax:function(id) {
        if($('#'+id+" .jqmAlertWindow").width() > parseInt($(window).width()*0.90)) {
           this.posAndSize(
                id,
                $('#'+id).data("top"),
                $('#'+id).data("left"),
                $('#'+id).data("height"),
                $('#'+id).data("width")
           );
        } else {
           $('#'+id).data("top", parseInt($("#"+id).css("top")));
           $('#'+id).data("left", parseInt($("#"+id).css("left")));
           $('#'+id).data("height", $("#"+id+" .jqmAlertWindow").height());
           $('#'+id).data("width", $("#"+id+" .jqmAlertWindow").width());
           var realId = id.replace(new RegExp("(window_)", "g"),"");
           this.fullWindow(realId);
           this.focusOn(realId);
        }
    },
    posAndSize:function(id, top, left, height, width) {
        $('#'+id+" .jqmAlertWindow").width(parseInt(width));
        $('#'+id+" .jqmAlertWindow").height(parseInt(height));
        $('#'+id)
            .css("top", parseInt(top)+"px")
            .css("left", parseInt(left)+"px");
    },
    leftSide:function(id) {
        dp.posAndSize('window_'+id, 25,0, $(window).height()-70, 400);
    },
    rightSide:function(id) {
        dp.posAndSize('window_'+id, 25,410, $(window).height()-55, $(window).width()-415);
    },
    fullWindow:function(id) {
        dp.posAndSize('window_'+id, 25, 0,$(window).height()-55, $(window).width() - 10);
    },
    mediumWindow:function(id) {
        dp.posAndSize('window_'+id, 25, 270, Math.min(600, $(window).height()-55), 700);
    },
    defaultSize:function(id) {
        dp.posAndSize('window_'+id, ($(window).height()-500)/1.8+25,($(window).width()-550)/1.8, 500, 550);
    }
};
