
function insertObjetFofo(id_objet) {
    var prix = prompt("Entrer le prix auquel vous souhaitez vendre cet objet\n(laisser blanc pour ne pas afficher de prix)", "");
    if(typeof prix == "string") {
        var comment = prompt("Entrer le commentaire que vous voulez associé à cet objet", "");
        if(typeof comment == "string") {
            prompt("Copier/coller ce code dans votre message", "[objet id="+id_objet+" prix="+prix+"]"+comment+"[/objet]");
        }
    }
}


var animations = new Array();
var running = false;
function launchAnimation(init, command, objectif, commandObjectif) {
    animations.push(new Array(init, command, objectif, commandObjectif));
    if(!running) {
        setTimeout("runAnimation()", 10);
        running = true;
    }
}
function runAnimation() {
    var copieAnimations = animations;
    for(i=0;i<animations.length;i++) {
        eval(animations[i][0]);
        eval("var condition = ("+animations[i][2]+");");
        if(!condition) {
            eval(animations[i][1]);
        } else {
            eval(animations[i][3]);
            copieAnimations.splice(i, 1);
        }
    }
    animations = copieAnimations;
    if(animations.length) setTimeout("runAnimation()", 10);
    else running = false;
}

function fadeIn(id) {
    var pas = 3;
    var maxi = 100;
    if(arguments[1] !== undefined) maxi = arguments[1];
    if(arguments[2] !== undefined) pas = arguments[2];
    var init = "var obj = new getObj('"+id+"');var op = getOpacity(obj);";
    var command = "setOpacity(obj, op+"+pas+");";
    var objectif = "op >= "+maxi;
    var commandObjectif = "setOpacity(obj, "+maxi+");";
    if(arguments[3] !== undefined) commandObjectif += arguments[3];
    launchAnimation(init,command,objectif,commandObjectif);
}
function fadeOut(id) {
    var pas = 3;
    var mini = 0;
    if(arguments[1] !== undefined) mini = arguments[1];
    if(arguments[2] !== undefined) pas = arguments[2];
    var init = "var obj = new getObj('"+id+"');var op = getOpacity(obj);";
    var command = "setOpacity(obj, op-"+pas+");";
    var objectif = "op <= "+mini;
    var commandObjectif = "setOpacity(obj, "+mini+");";
    if(arguments[3] !== undefined) commandObjectif += arguments[3];
    launchAnimation(init,command,objectif,commandObjectif);
}

function getObj(name) {
    if(document.getElementById) {
  	    this.obj = document.getElementById(name);
  	    if(this.obj)
	        this.style = document.getElementById(name).style;
    } else if(document.all) {
	    this.obj = document.all[name];
	    if(this.obj)
	        this.style = document.all[name].style;
    } else if(document.layers) {
   	    this.obj = document.layers[name];
   	    this.style = document.layers[name];
    }
}

function setOpacity(obj, opacity) {
    if(obj && obj.style) {
        opacity = (opacity>=100) ? 100 : opacity;
        switch( true ){
            case obj.style.opacity != null:// Standards compliant browsers: Firefox, Opera
                obj.style.opacity = opacity/100;
            break;
            case obj.style.filter != null:// Internet Exploder
                obj.style.filter = "alpha(opacity:"+opacity+")";
            break;
            case obj.style.KHTMLOpacity != null:// Safari and Konqueror
                obj.style.KHTMLOpacity = opacity/100;
            break;
            case obj.style.MozOpacity != null:// Older Mozilla browsers
                obj.style.MozOpacity = opacity/100;
            break;
            default:// return an empty function for browsers that do not support changing opacity.
                if( opacity>=100 )
                    obj.style.visibility = 'visible';
                else if( opacity <= 0 )
                    obj.style.visibility = 'hidden';
        }
    }
}

function getOpacity(obj) {
    if(obj && obj.style) {
        switch( true ){
            case obj.style.opacity != null:// Standards compliant browsers: Firefox, Opera
                return obj.style.opacity*100;
            break;
            case obj.style.filter != null:// Internet Exploder
                return obj.style.filter.slice(14,-1);
            break;
            case obj.style.KHTMLOpacity != null:// Safari and Konqueror
                return obj.style.KHTMLOpacity*100;
            break;
            case obj.style.MozOpacity != null:// Older Mozilla browsers
                return obj.style.MozOpacity*100;
            break;
            default:// return an empty function for browsers that do not support changing opacity.
                if(obj.style.visibility == 'visible')
                    return 100;
                else if(obj.style.visibility == 'hidden')
                    return 0;
        }
    }
    return 0;
}

function changeObjectDisplay(id) {
    var objet = new getObj(id);
    if(objet && objet.style) {
        if(objet.style.display == 'none') {
            objet.style.display = 'block';
        } else {
            objet.style.display = 'none';
        }
    }
    delete objet;
}

function changeRowDisplay(id) {
    var objet = new getObj(id);
    if(objet && objet.style) {
        if(objet.style.display == 'none') {
            objet.style.display = 'table-row';
        } else {
            objet.style.display = 'none';
        }
    }
    delete objet;
}

function changeCellDisplay(id) {
    var objet = new getObj(id);
    if(objet && objet.style) {
        if(objet.style.display == 'none') {
            objet.style.display = 'table-cell';
        } else {
            objet.style.display = 'none';
        }
    }
    delete objet;
}

function changeTableDisplay(id) {
    var objet = new getObj(id);
    if(objet && objet.style) {
        if(objet.style.display == 'none') {
            objet.style.display = 'table';
        } else {
            objet.style.display = 'none';
        }
    }
    delete objet;    
}
function changeTBodyDisplay(id) {
    var objet = new getObj(id);
    if(objet && objet.style) {
        if(objet.style.display == 'none') {
            objet.style.display = 'table-row-group';
        } else {
            objet.style.display = 'none';
        }
    }
    delete objet;    
}
function setTBodyDisplay(id,display) {
    var objet = new getObj(id);
    if(objet && objet.style) {
        if(display) {
            objet.style.display = 'table-row-group';
        } else {
            objet.style.display = 'none';
        }
    }
    delete objet;
}
function changeInlineDisplay(id) {
    var objet = new getObj(id);
    if(objet && objet.style) {
        if(objet.style.display == 'none') {
            objet.style.display = 'inline';
        } else {
          objet.style.display = 'none';
        }
    }
    delete objet;
}

function setObjectDisplay(id,display) {
    var objet = new getObj(id);
    if(objet && objet.style) {
        if(display) {
            objet.style.display = 'block';
        } else {
            objet.style.display = 'none';
        }
    }
    delete objet;
}
function setInlineDisplay(id,display) {
    var objet = new getObj(id);
    if(objet && objet.style) {
        if(display) {
            objet.style.display = 'inline';
        } else {
            objet.style.display = 'none';
        }
    }
    delete objet;
}

function isDisplayed(id) {
    var objet = new getObj(id);
    var returnValue = false;
    if(objet && objet.style) {
        returnValue = (objet.style.display != 'none');
        delete objet;
    }
    return returnValue; 
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// Fonction permettant de choisir plusieurs objets quand ils sont "stackés" chez les marchands.
function chooseNumberOfObjects(idsObjets, idAction, verbe, nombreMaxi) {
	if(nombreMaxi == 1) {
		selectObj(idsObjets, idAction);
		return false;
	}
	var tabObjets = idsObjets.split(",");
	var nb = prompt("Choisissez le nombre d'objets que vous souhaitez "+verbe+" (max : "+nombreMaxi+") :", "1");
	if(nb == null || nb == undefined) {
		return false;
	}
	nb = parseInt(nb);
	if(nb == NaN) {
		alert("Saisissez un nombre");
		return false;
	}
	if(nb < 0) {
		alert("Choisissez un nombre positif !");
		return false;
	}
	if(nb > nombreMaxi) {
		alert("Choisissez un nombre inférieur au maximum d'objet disponible ("+nombreMaxi+")");
		return false;
	}
	var idToSend = new Array();
	for(i = 0; i < nb; i++) {
		idToSend[i] = tabObjets[i];
	}
	selectObj(idToSend.join(","), idAction);
}

// Fonction transverse à plusieurs pages pour la sélection d'action
function selectAction(idAction) {
    if(top.frames["mainframe"] &&
       top.frames["mainframe"].frames["action"]) {
        unhideActionFrame();
        var listeId = new Array();
        var listeValue = new Array();
        for(i=1;i < arguments.length;i++) {
            if(i%2 == 1) {
                listeId.push(arguments[i]);
            } else {
                listeValue.push(arguments[i]);
            }
        }

        // On test le premier input pour voir si l'action est déjà chargée
        var loadingToDo = false;
        if(top.frames["mainframe"].frames["action"].document.forms["selectActionForm"]) 
            loadingToDo = true;
        
        if(loadingToDo) {
            top.frames["mainframe"].frames["action"].document.forms["selectActionForm"].elements["action"].value = idAction;
        }
		
        for(i=0;i < listeId.length;i++) {
            if(loadingToDo) {
                if(top.frames["mainframe"].frames["action"].document.forms["selectActionForm"].elements[listeId[i]])
                    top.frames["mainframe"].frames["action"].document.forms["selectActionForm"].elements[listeId[i]].value = listeValue[i];
            } else {
                var selectDOM = top.frames["mainframe"].frames["action"].document.getElementById(listeId[i]);
                if(selectDOM) {
                    if(selectDOM.options) {
						var tabIds = listeValue[i].split(",");
                        for(j=0; j < selectDOM.options.length; j++) {
                            if(tabIds.contains(selectDOM.options[j].value)) {
                                selectDOM.options[j].selected = !selectDOM.options[j].selected;
                            }
                        }
                    } else {
                        selectDOM.value = listeValue[i];
                    }
                }
            }
        }
        if(loadingToDo)
            top.frames["mainframe"].frames["action"].document.forms["selectActionForm"].submit();
    } else {
        alert("Cette fonctionnalité ne marche pas dans un onglet à part.\nOuvrez cette page dans l'onglet où se trouve la barre d'action.")
    }
}

// Ajout de la méthode contains aux Array
Array.prototype.contains = function (element) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == element) {
			return true;
		}
	}
	return false;
}

// Fonction transverse à plusieurs pages pour la sélection d'objet.
function selectObj(myId, idAction) {
    selectAction(idAction, "selectObj", myId, "idObjet", myId);
}

function retirerDesPO(compte) {
    var montant = prompt("Entrez le montant du retrait sur le compte n°"+compte+" :", 0);
    if(montant) 
        selectAction(57, "montant", montant, "id_compte", compte);
}
function openHasard() {
    document.open("/outils/Hasard.php", "hasard", "top=40,left=40,width=276,height=190,menubar=no,directories=no,status=no,location=no,scrollbars=no,resizable=no");
}
function openChat() {
    document.open("/irc.php", "Causette", "top=50,left=150,width=830,height=510,scrollbars=no,resizable=yes,toolbar=no,location=no,directories=no,status=no,menubar=no");
}
function openUploadImage(typeUpload) {
    document.open("/outils/uploadImage.php?upload="+typeUpload, "Upload d'avatar", "top=50,left=150,width=450,height=100,scrollbars=no,resizable=no,toolbar=no,location=no,directories=no,status=no,menubar=no");
}


function scrollGauche(idObj, idContainer, pas) {
    var obj = new getObj(idObj);
    var container = new getObj(idContainer);
    if(obj.obj.offsetLeft + pas <= 0)
        obj.style.left = obj.obj.offsetLeft + pas;
     else
        obj.style.left = 0;
    delete obj;
    delete container;
}
function scrollDroite(idObj, idContainer, pas) {
    var obj = new getObj(idObj);
    var container = new getObj(idContainer);
    if(obj.obj.offsetLeft + obj.obj.offsetWidth - pas > container.obj.offsetWidth)
        obj.style.left = obj.obj.offsetLeft - pas;
    else
        obj.style.left = container.obj.offsetWidth - obj.obj.offsetWidth;
    delete obj;
    delete container;
}

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

function consoleDebug(message) {
    if(message != "") {
        var jQueryObj;
        var closeObj;
        var emptyObj;
        var create = false;
        if(top.frames["mainframe"] && 
           top.frames["mainframe"].frames["main"]) {
            if($("#consoleDebug", top.frames["mainframe"].frames["main"].document).length == 0) {
                $("body", top.frames["mainframe"].frames["main"].document).append("<div id='consoleDebug'></div><img id='toggleConsoleDebug' src='/images/Apercu.gif' width='15px' height='15px'/><img id='empyConsoleDebug' src='/images/Bt_supprimer.gif' width='15px' height='15px'/>");
                create = true;
            }
            jQueryObj = $("#consoleDebug", top.frames["mainframe"].frames["main"].document);
            closeObj = $("#toggleConsoleDebug", top.frames["mainframe"].frames["main"].document);
            emptyObj = $("#empyConsoleDebug", top.frames["mainframe"].frames["main"].document);
        } else {
            if($("#consoleDebug").length == 0) {
                $("body").append("<div id='consoleDebug'></div><img id='toggleConsoleDebug' src='/images/Apercu.gif' width='15px' height='15px'/>");
                create = true;
            }
            jQueryObj = $("#consoleDebug");
            closeObj = $("#toggleConsoleDebug");
            emptyObj = $("#emptyConsoleDebug");
        }
        closeObj.css(
        {
            position:           "fixed",
            bottom:             "0px",
            right:              "0px",
            zIndex:             100001
        });
        emptyObj.css(
        {
            position:           "fixed",
            bottom:             "0px",
            right:              "20px",
            zIndex:             100001
        });        
        jQueryObj.css(
        {
            position:           "fixed",
            bottom:             "0px",
            width:              "100%",
            display:            "none",
            overflow:           "auto",
            backgroundColor:    "#FFFFFF",
            color:              "#000000",
            padding:            "10px",
            zIndex:             100000
        });
        jQueryObj.fadeTo(0, 0.9);
        if(!create) {
            jQueryObj.append("<br/>");
        }
        closeObj.bind("click", function () { jQueryObj.slideToggle(); });
        emptyObj.bind("click", function () { 
            closeObj.remove(); 
            jQueryObj.remove();
            emptyObj.remove();
        });
        jQueryObj.append(message);
        jQueryObj.slideDown();
    }
}


if(typeof $ != "undefined") {

    if(typeof $.frameReady != "undefined") {
        // Fonction cachant et découvrant la barre d'action.
        function hideActionFrame() {
            $.frameReady(
                function() {
                    $("#boutonHide").hide();
                    $("#boutonUnhide").fadeIn();
                },
                "top.menu"
            );
            $.frameReady(
                function() {
                    if($("#main").css("height") != "100%") {
                        $("#main").animate({
                            height:"100%"
                        }, 500);
                        $("#action").animate({
                            height:"0px"
                        }, 500, "linear", function() {$("#main").resize()});
                    }
                },
                "top.mainframe"
            );
        }
        function unhideActionFrame() {
            $.frameReady(
                function() {
                    $("#boutonUnhide").hide();
                    $("#boutonHide").fadeIn();
                },
                "top.menu"
            );
            $.frameReady(
                function() {
                    if($("#main").css("height") == "100%") {
                        $("#main").animate({
                            height:$(window).height()-125
                        }, 500);
                        $("#action").animate({
                            height:"125px"
                        }, 500, "linear", function() {$("#main").resize()});
                    }
                }, 
                "top.mainframe"
            );
        }
    }
/*******************************************************************************
* Gestion de l'aide
* 
******************************************************************************/
    function prepareAideForm() {
        $("#FormAide").ajaxForm({
            url:"/APIHelp.php",
            type:"POST",
            target:$("#AideText"),
            success:function() {
                alert("Aide sauvée...");
                addAideInteractor();
                prepareAideForm();
            }
        });
    }
    function addAideInteractor() {
        if($(".OpenAide").length) {
            // On récupère le script pour l'insertion dans les formulaires
            if(typeof isInsertion == "undefined") {
                $.getScript("/javascript/insererFormulaire.js");
            }
            // Et on inclut aussi le script pour valider forumaire de modification
            // des aides. (Indispensable)
            if(typeof $.fn.ajaxSubmit == "undefined") {
                $.getScript("/optim/www/js/jquery.form.js");
            }
        }
        $(".OpenAide").each(
            function (i) {
                $(this).bind(
                    "click",
                    function (evt) {
                        // Si le conteneur n'est pas présent, on l'ajoute au document.
                        if(!$("#AideContent").length) {
                            var MonTitre = "Aide"
                            if(document.title != "") {
                                MonTitre = document.title+" : Aide";
                            }
                            // Si l'aide n'est pas présente dans la page, on l'ajoute
                            $("body").prepend('<div id="AideContent"><div><div id="CloseAide"> </div><div id="AideTitle" class="jqDrag">'+MonTitre+'</div><div id="AideBG"/></div><div id="AideText"></div></div>');
                            $("#AideContent").css("left", parseInt(($(window).width() - $("#AideContent").width())/2)+"px");
                            $("#AideContent").css("top", parseInt(($(window).height() - $("#AideContent").height())/2)+"px");
                            $("#AideContent").jqDrag(".jqDrag");
                        }
                        $("#AideContent").fadeIn();
                        // On le rempli en Ajax
                        var myURL = "/APIHelp.php?page="+escape(document.URL);
                        if($(this).attr("rel") != "undefined" && $(this).attr("rel") != "") {
                            myURL = "/APIHelp.php?ce_aide="+$(this).attr("rel");
                        }
                        // On désactive les interacteurs pour empêcher le lancement en boucle des requêtes.
                        $(".OpenAide").each(
                            function (i) {
                                $(this).unbind("click");
                            }
                        );
                        $.ajax(
                            {
                                url: myURL,
                                async: false,
                                dataType:"html",
                                beforeSend:function(xhr) {
                                    $("#AideText").html("<img src='/images/loadingv.gif'/> Chargement...");
                                },
                                success:function(data, status) {
                                    $("#AideText").html(data);
                                    prepareAideForm();
                                    
                                    $("#CloseAide").bind(
                                        "click",
                                        function() {
                                            $("#AideContent").remove();
                                        }
                                    );
                                    addAideInteractor();
                                }
                            }
                        );
                    }
               );
            }
        );
    }
    // Initialisation.
    $(document).ready(
        function () {
            addAideInteractor();
        }
    );
}