//Ce fichier contient les divers scripts utilises dans le CMS

/*
 * Fonction permettant de demander une confirmation avant de charger une page.
 *
 * @author JPoulin
 * @param string message: La question a confirmer
 * @param string urlCible: La page a charger en cas de confirmation.
 */
function confirmation(message,urlCible) {
    if (confirm(message)) {
        document.location.href = urlCible;
    }
}

/*
 * Fonction permettant d'ouvrir une popup.
 *
 * @author JPoulin
 * @param string url: Page a ouvrir dans la popup
 * @param string cible: Nom de la popup
 * @param integer largeur: Largeur de la popup
 * @param integer hauteur: Hauteur de la popup
 * @param integer left: Distance du bord gauche de la page
 * @param integer top: Distance du haut de la page
 * @param boolean resizable: Redimenssionnable ou pas.
 * @param boolean scrollbars: Barres de defilement verticales ou pas.
 * @param boolean menubar: Barre de menu ou pas.
 */
function openWindow(url,cible,largeur,hauteur,left,top,resizable,scrollbars,menubar) {
    if (typeof(menubar) == 'undefined') {
        menubar = 0;
    }
    params  = "";
    params += "toolbar=0,";
    params += "location=0,";
    params += "directories=0,";
    params += "status=0,";
    params += "menubar="+menubar+",";
    params += "scrollbars="+scrollbars+",";
    params += "copyhistory=0,";
    params += "resizable="+resizable+",";
    params += "left="+left+",";
    params += "top="+top+",";
    params += "width="+largeur+",";
    params += "height="+hauteur;
    var w = window.open(url,cible,params);
    return w;
}

/*
 * Fonction permettant d'ouvrir une popup en plein ecran
 *
 * @author EAnken
 * @param string url: Page a ouvrir dans la popup
 * @param string cible: Nom de la popup
 */
function launchFullScreenWindow(url, cible) {
    //var str = "left=0,screenX=0,top=0,screenY=0,fullscreen";
    var str = "left=0,screenX=0,top=0,screenY=0,scrollbars=1,status=0,fullscreen";
	
    if (window.screen) {
        var ah = screen.availHeight - 30;
        var aw = screen.availWidth - 10;
        str += ",height=" + ah;
        str += ",innerHeight=" + ah;
        str += ",width=" + aw;
        str += ",innerWidth=" + aw;
    } else {
        str += ",resizable"; // so the user can resize the window manually
    }
	
    window.open(url, cible, str);

}

/*
 * Fonction permettant de recuperer un argument passe dans une URL
 *
 * @author EAnken
 * @param string nameArg: Nom de l'argument dont la valeur doit etre retournee
 * @return string: Retourne la valeur de l'argument demande, ou une string vide si elle n'a pas ete trouvee
 */
function getArgument(nameArg) {
    // Extraction de la string des arguments de l'URL
    var argstr = location.search.substring(1, location.search.length);
    // Copie de tous les arguments dans un tableau
    var tabArg = argstr.split("&");
    // Boucle sur tous les arguments
    for (i=0; i<tabArg.length; i++) {
        // Decoupe de l'argument en cours et test s'il est egal a celui demande
        var detailsArg = tabArg[i].split("=");
        if (detailsArg[0]==nameArg) {
            // Si oui, renvoi de la valeur de l'argument
            return detailsArg[1];
        }
    }
    return "";
}

/**
 * Changement de visibilite d'un calque
 *
 * @author JPoulin
 * @param integer identifiant L'ID du calque.
 */
function switchVisible(identifiant) {
    if (document.getElementById(identifiant).style.display == 'none') {
        display(identifiant);
    } else {
        cache(identifiant);
    }
}


/**
 * Affichage d'un calque
 *
 * @author JPoulin
 * @param integer identifiant L'ID du calque
 */
function display(identifiant) {
    Element.show(identifiant);
}

/**
 * Masquage d'un calque
 *
 * @author JPoulin
 * @param integer identifiant L'ID du calque
 */
function cache(identifiant) {
    Element.hide(identifiant);
}

/**
 * Determine, dans une liste de boutons radio du meme nom, lequel
 * est checke.
 *
 * @author JPoulin
 * @param string radio Le nom du/des boutons radios
 * @return mixed La valeur du bouton radio checke.
 */
function getRadioCheckedValue(radio) {
    for (var i=0; i<radio.length;i++) {
        if (radio[i].checked) {
            return radio[i].value;
        }
    }
}

/**
 * Fonction pour afficher un calque a une certaine distance du curseur de la souris
 *
 * @author JPoulin
 * @param mixed div Le calque a afficher
 * @param integer x Distance horizontale
 * @param integer y Distance verticale.
 * @return void()
 */
function displayFromMouse(div, x, y, event) {
    div = $(div);
	
    /**
	 * On affiche la DIV
	*/
    display(div);
	
    /**
	 * Ici on determine la position du curseur, en se basant egalement sur
	 * la position de la scrollbar.
	 */
    if (document.all) {
        if (document.documentElement && document.documentElement.scrollTop) {
            xSrc = window.event.clientX + document.documentElement.scrollLeft;
            ySrc = window.event.clientY + document.documentElement.scrollTop;
        } else if (document.body) {
            xSrc = window.event.clientX + document.body.scrollLeft;
            ySrc = window.event.clientY + document.body.scrollTop;
        }
    } else {
        xSrc = event.pageX + x;
        ySrc = event.pageY + y;
    }
	
    /**
	 * Le calque apparaîtra a l'emplacement oe se trouve le curseur.
	 */
    div.style.position = 'absolute';
    div.style.top = ySrc + y;
    div.style.left = xSrc + x;
}

/**
 * Fonction pour afficher un calque a une certaine distance d'un autre
 *
 * @author JPoulin
 * @param string div Le calque a afficher
 * @param string other Le calque reference
 * @param integer x Distance horizontale
 * @param integer y Distance verticale.
 * @return void()
 */
function displayFromLayer(div, other, x, y) {
    /**
	 * On affiche la DIV
	*/
    display(div);
	
    /**
	 * Ici on determine la position du calque de reference.
	 */
    ySrc = findPosY(other);
    xSrc = findPosX(other);
	
    document.getElementById(div).style.position = 'absolute';
    document.getElementById(div).style.top = ySrc + y;
    document.getElementById(div).style.left = xSrc + x;
}

/**
 * Fonction pour trouver la coordonnee horizontale d'un element de la page
 *
 * @author Site Quirksmode.org
 * @author JPoulin (modification pour prendre un ID en entree)
 * @param string id L'identifiant de l'objet
 * @return integer La position
 */
function findPosX(id) {
    var obj = document.getElementById(id);
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

/**
 * Fonction pour trouver la coordonnee verticale d'un element de la page
 *
 * @author Site Quirksmode.org
 * @author JPoulin (modification pour prendre un ID en entree)
 * @param string id L'identifiant de l'objet
 * @return integer La position
 */
function findPosY(id) {
    var obj = document.getElementById(id);
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }
    return curtop;
}

function getWindowDimensions() {
    if (parseInt(navigator.appVersion)>3) {
        if (navigator.appName=="Netscape") {
            winW = window.innerWidth;
            winH = window.innerHeight;
        }
        if (navigator.appName.indexOf("Microsoft")!=-1) {
            winW = document.body.offsetWidth;
            winH = document.body.offsetHeight;
        }
    }
	
    var dimensions = {
        width:winW,
        height:winH
    };
	
    return dimensions;
}

/**
 * Methode pour afficher un div au milieu de la page
 */
function displayInMiddleWindow(div) {
    if (typeof(div) == 'string') {
        div = $(div);
    }
	
    divDimensions = Element.getDimensions(div);
    winDimensions = getWindowDimensions();
	
    scrollPosition = document.body.scrollTop;
	
    var posY = scrollPosition + (winDimensions.height/2) - (divDimensions.height/2);
    var posX = (winDimensions.width/2) - (divDimensions.width/2);
	
    div.style.top = posY;
    div.style.left = posX;
}

/**
 * Methode pour cacher l'objet de loading s'il existe.
 */
hideLoadObj = function() {
    if (typeof(loadObj) == 'object') {
        loadObj.hide();
    }
}

/**
 * Methode pour afficher un div au milieu de l'ecran de l'utilisateur
 *
 */
function showDiv(div) {
    hideLoadObj();
    Element.show(div);
    displayInMiddleWindow(div);
}

/**
 * Fonction qui va effectuer une requete Ajax avec retour.
 *
 * @param string recept L'element de retour
 * @param string scriptname Le fichier a appeler
 * @param string params Les parametres a passer a la requete
 * @param function funcOnComplete La fonction a lancer sur le onComplete de l'Ajax.Updater.
 * @param bool loading Affichage du loading ou pas
 * @param function funcInsertion La fonction a lancer sur le insertion de l'Ajax.Updater.
 */
runAjaxUpdater = function(recept, scriptname, params, funcOnComplete, loading, funcInsertion) {
    if (loading) {
        if (typeof(loadObj) == 'undefined') {
            loadObj = new Loading(PATH_IMG_LOADING);
        }
        loadObj.montre();
    }
	
    new Ajax.Updater(
        recept,
        scriptname,
        {
            method: 'post',
            asynchronous: true,
            parameters: params,
            evalScripts: true,
            insertion: funcInsertion,
            onComplete: function() {
                if (typeof(funcOnComplete) == 'function') {
                    funcOnComplete();
                }
                if (loading) {
                    hideLoadObj();
                }
            }
        }
        );
}

/**
 * Fonction qui va effectuer une requete Ajax avec retour et confirmation prealable.
 *
 * @param string message Le message de confirmation
 * @param string recept L'element de retour
 * @param string scriptname Le fichier a appeler
 * @param string params Les parametres a passer a la requete
 * @param function funcOnComplete La fonction a lancer sur le onComplete de l'Ajax.Updater.
 * @param bool loading Affichage du loading ou pas
 * @param function funcInsertion La fonction a lancer sur le insertion de l'Ajax.Updater.
 */
runAjaxConfirmUpdater = function(message, recept, scriptname, params, funcOnComplete, loading, funcInsertion) {
    if (!confirm(message)) {
        return false;
    }
    runAjaxUpdater(recept, scriptname, params, funcOnComplete, loading, funcInsertion);
}


// This code is in the public domain. Feel free to link back to http://jan.moesen.nu/
function sprintf() {
    if (!arguments || arguments.length < 1 || !RegExp) {
        return;
    }
    var str = arguments[0];
    var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
    var a = b = [], numSubstitutions = 0, numMatches = 0;
    while (a = re.exec(str)) {
        var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
        var pPrecision = a[5], pType = a[6], rightPart = a[7];
		
        //alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);

        numMatches++;
        if (pType == '%') {
            subst = '%';
        } else {
            numSubstitutions++;
            if (numSubstitutions >= arguments.length) {
                alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
            }
            var param = arguments[numSubstitutions];
            var pad = '';
            if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
            else if (pPad) pad = pPad;
            var justifyRight = true;
            if (pJustify && pJustify === "-") justifyRight = false;
            var minLength = -1;
            if (pMinLength) minLength = parseInt(pMinLength);
            var precision = -1;
            if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
            var subst = param;
            if (pType == 'b') subst = parseInt(param).toString(2);
            else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
            else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
            else if (pType == 'u') subst = Math.abs(param);
            else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
            else if (pType == 'o') subst = parseInt(param).toString(8);
            else if (pType == 's') subst = param;
            else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
            else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
        }
        str = leftpart + subst + rightPart;
    }
    return str;
}

/**
 * Fonction in_array transcrite de PHP pour Javascript
 *
 * @param string value la valeur dont on veut verifier si elle est dans le tableau
 * @return boolean true si oui
 */
Array.prototype.in_array = function(value) {
    for (var i in this) {
        if (this[i] == value) return true;
    }
    return false;
}


var Imhotep = {
    Person: {
        Templates: {}
    },
    menu: {},
    is_object: function( mixed_var ){
        // http://kevin.vanzonneveld.net
        // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +   improved by: Legaev Andrey
        // +   improved by: Michael White (http://crestidg.com)
        // *     example 1: is_object('23');
        // *     returns 1: false
        // *     example 2: is_object({foo: 'bar'});
        // *     returns 2: true
        // *     example 3: is_object(null);
        // *     returns 3: false
	 
        if(mixed_var instanceof Array) {
            return false;
        } else {
            return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
        }
    },
    /**
     * Make a copy of an object
     *
     * @author Oran Looney
     * @link http://oranlooney.com/functional-javascript/
     * @param Object obj
     * @return Object the copy
     */
    copy: function(obj) {
        if (typeof obj !== 'object' ) {
            return obj;  // non-object have value sematics, so obj is already a copy.
        } else {
            var value = obj.valueOf();
            if (obj != value) {
                // the object is a standard object wrapper for a native type, say String.
                // we can make a copy by instantiating a new object around the value.
                return new obj.constructor(value);
            } else {
                // ok, we have a normal object. We have to
                // copy the whole thing, property-by-property.
                var c = {};
                for ( var property in obj ) c[property] = obj[property];
                return c;
            }
        }

    },
    debug: {
        /**
		 * Affiche un object de telle sorte qu'on y voit plus clair
		 *
		 * @param Object obj l'objet a parcourir
		 * @param string html l'id d'un div html dans lequel on y mettra l'objet
		 * @param boolean add true pour ajouter la string plutot que de remplacer
		 * @return void
		 */
        displayObject: function (obj, html, add, inline) {
            var str = '';
            if (typeof obj == 'object') {
                for (var i in obj) {
                    str += i + ' : ' + obj[i] + (inline ? ', ' : '<br/><br/>');
                }
            } else {
                str = obj;
            }
            if (!html) html = 'debug';
            if (add) {
                document.getElementById(html).innerHTML += str;
            } else {
                document.getElementById(html).innerHTML = str;
            }
        },
		
        addObject: function (obj, inline, html) {
            this.displayObject(obj, html, true, inline);
        }
    },

    /**
     * Initialise les menus javascript
     *
     * @return void
     */
    initJsMenus: function() {
        var id = null, funcload = null, funclick = null;
        var jsmenus = $$('.imhotep-js-menu-click');
        for (var i = 0; i < jsmenus.length; i++) {
            id = jsmenus[i].id.split('_')[1];
            funcload = 'Imhotep.menu.menu' + id + 'OnLoad';
            if (typeof eval(funcload) == 'function') {
                eval(funcload + '(jsmenus[i])');
            }
            funclick = 'Imhotep.menu.menu' + id + 'OnClick';
            if (typeof eval(funclick) == 'function') {
                Event.observe(jsmenus[i], 'click', eval(funclick), false);
            }
        }
    },

    isPrototypeLoaded: function() {
        return Event && Event.observe;
    }
};

// load des menus js
if (Imhotep.isPrototypeLoaded()) {
    Event.observe(window, 'load', Imhotep.initJsMenus, false);
}