// ######################################################################################
// ##### Librarie de fonctions personnelles javascript
// ##### © 2007 Eddy Minet
// ######################################################################################
EdLib = {};


    // ######################################################################################
    // ##### Fonctions Diverses
    // ######################################################################################
EdLib._onError = function(p_exception) {};
    // ########### _getAgentNames
EdLib._getAgentNames = function () {
	    var reg = new RegExp('([^/ ]+)/[0-9\.]+', "g");
	    var tab_result = [];
	    var ag = null;
	    do {
		    ag = reg.exec(navigator.userAgent);
		    if (ag != null)
			    tab_result.push(ag[1]);
	    } while (ag != null);
	    return tab_result;
    };
    // ############################################################################
    // ##### Fonctions DOM
    // ############################################################################
    // ########### addEventHandler
EdLib.addEventHandler = function (p_obj, p_event_name, p_CallBack) {
	    if (p_obj._events == null)
	        p_obj._events = new Array();
	    var new_event_item = new EdLib._EventItem(p_obj, p_event_name, p_CallBack);
	    p_obj._events.push(new_event_item);
	    try {
	        if (document.attachEvent)
		        p_obj.attachEvent("on" + p_event_name, p_CallBack);
	        if (document.addEventListener)
		        p_obj.addEventListener(p_event_name, p_CallBack, false);
		} catch (e) { EdLib._onError(e); return null; }
		return new_event_item;    		
    };
    // ########### clearEventHandlers
EdLib.clearEventHandlers = function (p_obj, p_event_name) {
        if (typeof(p_obj._events) != "undefined" && p_obj._events != null) {
            var new_array = [];
            for (var i=0; i<p_obj._events.length; i++) {
                if (p_event_name != null && p_obj._events[i].name != p_event_name)
                    new_array.push(p_obj._events[i]);
                else
                    p_obj._events[i].detach();
            }
                
            p_obj._events = new_array;
        }
    };
    // ########### createHTMLElement
EdLib.createHTMLElement = function (p_tagname, p_properties, p_handlers, p_parent) {
        try {
            var el = document.createElement(p_tagname);
        } catch (e) { EdLib._onError(e); return; }
        if (p_properties != null)
            try {
                for (var prop in p_properties)
                    try {
                        el[prop] = p_properties[prop];
                    }
                    catch (e) {}
            } catch (e) { EdLib._onError(e); }
        if (p_handlers != null)
            try {
                for (var hand in p_handlers)
                    EdLib.addEventHandler(el, hand, p_handlers[hand]);
            } catch (e) { EdLib._onError(e); }
        if (p_parent != null)
            try {
                p_parent.appendChild(el);       
            } catch (e) { EdLib._onError(e); }
        return el;            
    };
    // ########### _getTag
EdLib._getTag = function(p_obj, p_tag_name) {
        if (p_obj == null)
            return null;
        if (typeof(p_obj.getElementsByTagName) != "undefined") {
            var els = p_obj.getElementsByTagName(p_tag_name);
            return (els == null || els.length == 0) ? null : els[0];
        }
        return null;
    };
    // ########### _getTags
EdLib._getTags = function(p_obj, p_tag_name) {
        if (p_obj == null)
            return [];
        if (typeof(p_obj.getElementsByTagName) != "undefined")
            return p_obj.getElementsByTagName(p_tag_name);
        return [];
    };
    // ########### setObjectOpacity
EdLib.setObjectOpacity = function (obj, opacity) {
        obj.style.opacity = opacity / 100;
        obj.style.MozOpacity = opacity / 100;
        obj.style.KhtmlOpacity = opacity / 100;
        obj.style.filter = "alpha(opacity=" + (opacity) + ")";
    };
    // ########### addCssClass
EdLib.addCssClass = function (p_el, classname) {
	var obj = typeof(p_el) == "string" ? $get(p_el) : p_el;
    var class_tab = obj.className.split(' ');
    if (!class_tab.contains(classname))
        class_tab.push(classname);
    obj.className = class_tab.join(' ');
};
    // ########### removeCssClass
EdLib.removeCssClass = function (p_el, classname) {
	var obj = typeof(p_el) == "string" ? $get(p_el) : p_el;
    var class_tab = obj.className.split(' ');
    for (var i=0; i<class_tab.length;)
        if (class_tab[i] == classname)
            class_tab.splice(i, 1);
        else
            i++;
    obj.className = class_tab.join(' ');
};
    // ########### addCssLink
EdLib.addCssLink = function (p_href) {
    return $create("link", { rel: "stylesheet", type: "text/css", href: p_href}, null, $getTag(document, "head"));
};
    // ########### addJScriptLink
EdLib.addJScriptLink = function (p_src) {
    return $create("script", { type: "text/javascript", src: p_src}, null, $getTag(document, "head"));
};
    // ########### getKeyCode
EdLib.getKeyCode = function (p_event) { 
    if (window.event) 
        return window.event.keyCode;    
    else if (p_event)  
        return p_event.which;    
    
    return -1;
};
    // ########### restrictKey
EdLib.restrictKey = function (p_string, p_event) {
    var code = EdLib.getKeyCode(p_event);
    var car = String.fromCharCode(code);
    return p_string.indexOf(car) > -1 // valeurs dans la chaine
        || code == 0 // suppr
        || code == 8 // del
        || code == 99; // copier
        //|| code == 118; // coller
};
    // ########### restrictNumeric
EdLib.restrictKeyNumeric = function (p_event) { 
    var restrictedchar = "0123456789";    
    
    return EdLib.restrictKey(restrictedchar, p_event);
};
    // ########### cancelEvent
EdLib.cancelEvent = function (p_event, p_window) {
    p_window = p_window == null ? window : p_window;
    
    if (p_window.event)
        p_window.event.cancelBubble = true;
    else { 
        if (p_event.cancelBubble)
            p_event.cancelBubble = true;
        if (p_event.preventDefault)
            p_event.preventDefault();
        if (p_event.returnValue)
            p_event.returnValue = false;
    }
    return false;
};
    // ########### setEnterKeyBehavior
EdLib.setEnterKeyBehavior = function (p_el, p_method, p_args) { 
    p_el = typeof(p_el) == "string" ? $get(p_el) : p_el;
    $addHandler(p_el, "keypress", 
        function (p_event) {
            if (EdLib.getKeyCode(p_event) == 13) {
                p_method(p_args);
                return EdLib.cancelEvent(p_event);
            }
        }
    );
};
    // ########### getSelection
EdLib.getSelection = function (p_document) { 
    p_document = p_document == null ? document : p_document;
    var range;
    var parentnode;
    var sel;
    var text;
    if (navigator.isIE) {
        sel = p_document.selection;
        range = sel.createRange();
        parentnode = range.parentElement();
        text = range.text;
    }
    else {
        sel = p_document.defaultView.getSelection();
        range = sel.getRangeAt(0);
        parentnode = sel.anchorNode.parentNode;
        text = sel.toString();
    }
    return { "text" : text, "selection" : sel, "range" : range, "parentNode" : parentnode };
};
    // ############ createImgRollOver
EdLib.createImgRollOver = function (p_img, p_rollback_img_url) { 
    p_img = typeof(p_img) == "string" ? $get(p_img) : p_img;
    var img_base_url = p_img.src;
    // preload
    var img_preload = $create("img", {"src" : p_rollback_img_url}, {"load" : function() { img_preload = null; } });
    // evenements
    var this_img = p_img;
    $addHandler(p_img, "mouseover", function() { this_img.src = p_rollback_img_url; });
    $addHandler(p_img, "mouseout", function() { this_img.src = img_base_url; });
};    
		// ########### Ellipsis
EdLib.Ellipsis = function (p_el, p_maxwidth, p_setVisible) {
	p_el = typeof(p_el) == "string" ? $get(p_el) : p_el;
	p_maxwidth = p_maxwidth != null ? p_maxwidth : p_el.offsetWidth;
	p_setVisible = p_setVisible != null ? p_setVisible : false;
	// mesurer dans un conteneur neutre
	var test_el = p_el.cloneNode(true);
	test_el.style.position = "absolute";
	test_el.style.visible = false;
	test_el.style.width = "auto";
	p_el.parentNode.appendChild(test_el);
	if (test_el.offsetWidth > p_maxwidth) {
		// augmenter avec ... jusqu'au maximum
		var actual_good_html = "...";
		var max_length = p_el.innerHTML.length;
		for (var i=1; i<max_length; i++) { 
			test_el.innerHTML = p_el.innerHTML.substring(0, i).trim() + "...";
			if (test_el.offsetWidth > p_maxwidth) {
				p_el.innerHTML = actual_good_html;
				break;
			}
			actual_good_html = test_el.innerHTML;
		}
	}
	if (p_setVisible)
		p_el.style.visibility = 'visible';
	p_el.parentNode.removeChild(test_el);
	test_el = null;
};
    // ######################################################################################
    // ##### Fonctions XMLHttpRequest
    // ######################################################################################
EdLib._createXHR = function() {
        if(window.XMLHttpRequest)
            try {
                return new XMLHttpRequest();
            } catch (e) { EdLib._onError(e); return null; }
        else if(window.ActiveXObject)
            try {
                return new ActiveXObject("MSXML2.XMLHTTP.3.0");
            } catch (e) { EdLib._onError(e); return null; }
        else { // XMLHttpRequest non supporté par le navigateur
            var e= new Error();
            e.name = "XMLHttpRequest non support\351";
            e.message = "Le navigateur ne supporte pas XMLHttpRequest";
            EdLib._onError(e);
            return null;
        }
    };
        // ########### HttpRequestMethod
EdLib.HttpRequestMethod = {GET: "GET", POST: "POST", SOAP: "SOAP"};
        // ########### makeHTTPRequest
EdLib.makeHTTPRequest = function(p_Method, p_Url, p_Callback, p_Datas, p_SoapAction, p_username, p_password) {
        var xhr = EdLib._createXHR();
        if (p_Callback != null)
            xhr.onreadystatechange = function() { if (xhr.readyState == 4) p_Callback(xhr); };
        if (p_Method != EdLib.HttpRequestMethod.SOAP) {
            var datas = "";
            for (var key in p_Datas)
                datas += "&" + key + "=" + encodeURIComponent(p_Datas[key]);
            datas = datas.substr(1);
        }
        else datas = p_Datas;
        if (p_Method == EdLib.HttpRequestMethod.GET && p_Datas != null) {
            if (!p_Url.contains("?")) p_Url += "?"; else p_Url += "&";
            p_Url += datas;
            datas = null;
        }
        
        // identifiant unique
        p_Url += p_Url.indexOf('?') != -1 ? '&' : '?';
        p_Url += "edlibuid=" + Math.round(Math.random() * 100000000).toString();
        
        try {
            xhr.open(p_Method == "GET" ? "GET" : "POST", p_Url , (p_Callback != null), p_username, p_password);
        } catch (e) { EdLib._onError(e); return null; }
        
        try {
            if (p_Method == "POST")
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
            if (p_Method == "SOAP")
                xhr.setRequestHeader("Content-type", p_SoapAction != null ? "text/xml" : "application/soap+xml");
            if (p_SoapAction != null)
                xhr.setRequestHeader("SOAPAction", p_SoapAction);
        } catch (e) { EdLib._onError(e); return null; }
        
        try {
            xhr.send(datas);
        } catch (e) { EdLib._onError(e); return null; }
        
        return xhr;
    };

// ######################################################################################
// ##### Objet _EventItem
// ######################################################################################
EdLib._EventItem = function (p_parent, p_e_name, p_e_callback) {
        this.parent = p_parent;
        this.name = p_e_name;
        this.callback = p_e_callback;
        this.detach = function() {
            if (document.detachEvent)
                this.parent.detachEvent("on" + this.name, this.callback);
            if (document.removeEventListener)
                this.parent.removeEventListener(this.name, this.callback, false);
        };
};
        // ########### Type
EdLib._EventItem.prototype.Type = "EdLib._EventItem";
// ######################################################################################
// ##### Objet _DynamicField
// ######################################################################################
EdLib._DynamicField = function (p_el, p_placeHolderText) {
	this.control = typeof(p_el) == "string" ? $get(p_el) : p_el;
	this.placeHolderText = p_placeHolderText;
	if (this.control.value.trim() == "") {
			$addCssClass(this.control, "dynamicfield_placeholder");
			this.control.value = this.placeHolderText;
	}
	this.focus = function() {
		if (this.control.value == this.placeHolderText)
			this.control.value = "";
		$removeCssClass(this.control, "dynamicfield_placeholder");
		$addCssClass(this.control, "dynamicfield_editing");
	};
	this.blur = function() {
		if (this.control.value.trim() == "") {
			this.control.value = this.placeHolderText;
			$addCssClass(this.control, "dynamicfield_placeholder");
		}
		$removeCssClass(this_object.control, "dynamicfield_editing");
	};
	var this_object = this;
	this._BlurEvent = $addHandler(this.control, "blur", function() { this_object.blur(); } );
	this._FocusEvent = $addHandler(this.control, "focus", function() { this_object.focus(); } );
	this.clear = function() {
		$removeCssClass(this.control, "dynamicfield_placeholder");
		$removeCssClass(this.control, "dynamicfield_editing");
		this.control.value = "";
		this._BlurEvent.detach();
		this._FocusEvent.detach();
	}
	this.reset = function() {
		this.control.value = "";
		this.blur();
	}
};
        // ########### Type
EdLib._DynamicField.prototype.Type = "EdLib._DynamicField";
// ######################################################################################
// ##### Ajout de membres à des objets existants
// ######################################################################################
// ########### Array contains 
Array.prototype.contains = function(p_value_to_search, p_ignoreCase) {
    for (var i=0; i<this.length; i++) {
	    var value_to_compare = this[i];
	    if (typeof(this[i]) == "string") {
		    value_to_compare = p_ignoreCase ? value_to_compare.toLowerCase() : value_to_compare;
		    p_value_to_search = p_ignoreCase ? p_value_to_search.toLowerCase() : p_value_to_search;
	    }
	    if (value_to_compare == p_value_to_search)
		    return true;
    }
    return false;
};
// ########### Array indexOf 
if (Array.prototype.indexOf == null) {
    Array.prototype.indexOf = function(p_obj){
        for (i=0; i<this.length; i++)
            if (this[i] == p_obj)
                return i;
        return -1;
    };
}
// ########### String trim
String.prototype.trim = function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
};
// ########### String trimStart
String.prototype.trimStart = function() {
    return this.replace(/^\s+/, '');
};
// ########### String trimEnd
String.prototype.trimEnd = function() {
    return this.replace(/\s+$/, '');
};
// ########### String contains
String.prototype.contains = function(p_search, p_ignoreCase) {
    var string1 = p_ignoreCase ? this.toLowerCase() : this;
    var string2 = p_ignoreCase ? p_search.toLowerCase() : p_search;
    return string1.indexOf(string2) != -1;
};
// ########### String endWith
String.prototype.endsWith = function(p_text, p_ignoreCase) {
    var string1 = p_ignoreCase ? this.toLowerCase() : this;
    var string2 = p_ignoreCase ? p_text.toLowerCase() : p_text;
    return string1.substring( string1.length - string2.length) == string2;
};
String.prototype.isEmail = function () {
	return this.trim().match(/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/);
}
// ########### String parseForUrlUse
String.prototype.parseForUrlUse = function() {
        var search = "_\" &'(ç)=+~#{[|`\\^@]}^$*!:;,¨£%µ§/.?<>€éèëêãàâäôöõòûüùïîì";
        var replace = "---------------------------------------eeeeaaaaoooouuuiii";

        var result = "";

        for (var i=0; i<this.length; i++) {

            var index = search.indexOf(this.charAt(i));
            if (index != -1)
                result += replace[index];
            else
                result += this.charAt(i);
        }
        
        result = result.replace(/^-+/, '').replace(/-+$/, '');

        return result;
};
// ########### Navigator isIE
navigator.isIE = new RegExp('MSIE [0-9\.]+[a-z]?[;\)]').exec(navigator.userAgent) != null;
// ########### Navigator isFirefox
navigator.isFirefox = EdLib._getAgentNames().contains("firefox", true);
// ########### Navigator isFirebird
navigator.isFirebird = EdLib._getAgentNames().contains("firebird", true);
// ########### Navigator isOpera
navigator.isOpera = new RegExp('Opera [0-9\.]+').exec(navigator.userAgent) != null || EdLib._getAgentNames().contains("opera", true);
// ########### Navigator isNetscape
navigator.isNetscape = EdLib._getAgentNames().contains("netscape", true);
// ########### Navigator isKonqueror
navigator.isKonqueror = EdLib._getAgentNames().contains("KHTML") || EdLib._getAgentNames().contains("konqueror", true);
// ########### Navigator isSafari
navigator.isSafari = EdLib._getAgentNames().contains("safari", true);

// ######################################################################################
// ##### Raccourcis et fonctions utiles
// ######################################################################################
function $get(p_elname) { return document.getElementById(p_elname); };
function $addHandler(p_obj, p_event_name, p_CallBack) { return EdLib.addEventHandler(p_obj, p_event_name, p_CallBack); };
function $clearHandlers(p_obj, p_event_name) { return EdLib.clearEventHandlers(p_obj, p_event_name); };
function $create(p_tagname, p_attributes, p_handlers, p_parent) { return EdLib.createHTMLElement(p_tagname, p_attributes,p_handlers, p_parent); };
function $getTag(p_obj, p_tag_name) { return EdLib._getTag(p_obj, p_tag_name); };
function $getTags(p_obj, p_tag_name) { return EdLib._getTags(p_obj, p_tag_name); };
function $show(p_el, p_) { var el = typeof(p_el) == "string" ? $get(p_el) : p_el; el.style.visibility = ''; };
function $hide(p_el, p_) { var el = typeof(p_el) == "string" ? $get(p_el) : p_el; el.style.visibility = 'hidden'; };
function $display(p_el, p_) { var el = typeof(p_el) == "string" ? $get(p_el) : p_el; el.style.display = ''; };
function $undisplay(p_el, p_) { var el = typeof(p_el) == "string" ? $get(p_el) : p_el; el.style.display = 'none'; };
function $addOption(p_el, p_optionText, p_optionValue) {
    var objSelect = typeof(p_el) == "string" ? $get(p_el) : p_el;
    if (objSelect == null)
        return;
    p_optionValue = p_optionValue != null ? p_optionValue : p_optionText;
    p_index = objSelect.options.length;
    var newOption = $create("option", { text: p_optionText, value: p_optionValue});
    objSelect.options[p_index] = newOption;
    return newOption;
};
function $insertOption(p_el, p_optionText, p_optionValue, p_index) {
    var objSelect = typeof(p_el) == "string" ? $get(p_el) : p_el;
    if (objSelect == null)
        return;
    p_optionValue = p_optionValue != null ? p_optionValue : p_optionText;
    var newOption = $create("option", { text: p_optionText, value: p_optionValue});
    var before = navigator.isIE ? p_index : objSelect.options[p_index];
    objSelect.add(newOption, before);
    return newOption;
};
function $moveOption(p_el, p_optionIndex, p_optionNewIndex) {
    var objSelect = typeof(p_el) == "string" ? $get(p_el) : p_el;
    if (objSelect == null)
        return;
    // effacer l'ancienne option
    var optionText = p_el.options[p_optionIndex].text;
    var optionValue = p_el.options[p_optionIndex].value;
    var optionSelected = p_el.options[p_optionIndex].selected;
    p_el.options[p_optionIndex] = null;
    // insérer la nouvelle
    var newOption = $insertOption(objSelect, optionText, optionValue, p_optionNewIndex);
    newOption.selected = optionSelected;
};
function $enterKey(p_el, p_method, p_args) { EdLib.setEnterKeyBehavior(p_el, p_method, p_args); };
var $LoadScripts = new Array();
function $raiseLoadScripts() { for (var i=0; i<$LoadScripts.length; i++) $LoadScripts[i](); };
function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp('(^|\s)' + className + '(\s|$)');
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}
function $addCssClass(p_el, p_className) { EdLib.addCssClass(p_el, p_className); }
function $removeCssClass(p_el, p_className) { EdLib.removeCssClass(p_el, p_className); }




