
/**************************************************************/
/*                                                            */
/*     Initialization of the type of navigator                */
/*                                                            */
/**************************************************************/
    var ieNavigator = false;
    var isIE6 = (navigator.appVersion.indexOf('MSIE 6.0')>=0); 
     
    if(navigator.userAgent.indexOf("MSIE") != -1) 
    {
        ieNavigator = true;
    } 
    var ffNavigator = false;
    if(navigator.userAgent.indexOf("Firefox") != -1) 
    {
        ffNavigator = true; 
    }


/**************************************************************/
/*                                                            */
/*     Initialization of the separator for the autocomplete   */
/*                                                            */
/**************************************************************/
var HiddenSeparatorAutocomplete = String.fromCharCode(167);// Correspond to the '§'

/**********************************************************************/
/*                                                                    */
/*     Initialization of the separator for the FillInTheGapQuestion   */
/*                                                                    */
/**********************************************************************/
var proposalsSeparatorQuestion = String.fromCharCode(167);// Correspond to the '§'
var argumentsSeparatorQuestion = String.fromCharCode(164);// Correspond to the '¤'

/**************************************************************/
/*                                                            */
/*     Page events and Ajax Request                           */
/*                                                            */
/**************************************************************/
    function OnBodyLoad()
    {
        resizeContent();
        MakeGridViewsDynamics();   
        CopyAlwaysVisibleElement();
        MessageBoxClear();
        //var viewState = document.getElementById('__VIEWSTATE');
        //window.status = 'ViewState:'+viewState.value.length;
    }
    
    function OnBodyUnload() {

    }
   
    
    function OnBeforeUnload(evt)
    {
        //trick to prevent document.activeElement throw unknown js exception
        if (typeof document.activeElement != 'unknown')
        {
            if (document.activeElement != document.body)
            {
                MessageBoxWaiting();
            }
        }

        var e = (window.event) ? window.event : evt;
        if (e) 
        {
//            var clientX = !ieNavigator ? e.pageX : e.clientX;
//            var clientY = !ieNavigator ? e.pageY : e.clientY;

//            if (clientY < 0 && clientX > 500) {
//                __doPostBack('userLeaveApplication', 'DoCloseWindow');
//            }
            
            if (!ieNavigator && (
            //Handling FF window closing
            e.explicitOriginalTarget.toString() == "[object HTMLHtmlElement]"  //App
            //|| e.explicitOriginalTarget.toString() == "[object HTMLDivElement]" //player
            )) {
                //window.open(base_url + 'LeaveApp.aspx', '_self');
                __doPostBack('userLeaveApplication', 'DoCloseWindow');
            }
            //if window is closing redirect to page who set userconnexion to finished
            else {
                //Handling IE window closing
                if (e.clientY < 0 && e.clientX > 500) {
                    //window.open(base_url + 'LeaveApp.aspx', '_self');
                    __doPostBack('userLeaveApplication', 'DoCloseWindow');
                }
            }
        }
    }
    
    function OnBodyResize()
    {
        resizeContent();
    }
    
    function AjaxRequestStart(sender, args)
    {
        MessageBoxWaiting();
    }

    function AjaxRequestEnd()
    {
        OnBodyLoad();
        MessageBoxClear();
        
    }


/**************************************************************/
/*                                                            */
/*     MessageBox                                             */
/*                                                            */
/**************************************************************/

function MessageBoxWaiting()
{
    
    var messageBoxContent = document.getElementById('MessageBoxContent');
    
    if ( messageBoxContent ) {
        document.body.className+= ' Wait';
        var html = '<div class="Wait">&nbsp;</div>';
        messageBoxContent.innerHTML = html;
    }
}

function MessageBoxClear()
{
    var messageBoxContent = document.getElementById('MessageBoxContent');
    if ( messageBoxContent && messageBoxContent.innerHTML.indexOf('Wait')!=-1)
    {
        messageBoxContent.innerHTML = '';
    }
    while (document.body.className.indexOf(' Wait') != -1) {
        document.body.className = document.body.className.replace(' Wait', '');
    };
}

/************************************
* Function Hide message box DIV
*************************************/
function hideMessageBox(idMessageBox, idCloseMessageBox, idDetailsMessageBox)  
{
    var divMessageBox = document.getElementById(idMessageBox);
    if (divMessageBox)
    {
        divMessageBox.style.display = "none";
	}
	var divCloseMessageBox = document.getElementById(idCloseMessageBox);
    if (divCloseMessageBox)
    {
        divCloseMessageBox.style.display = "none";
	}
	var divDetailsMessageBox = document.getElementById(idDetailsMessageBox);
    if (divDetailsMessageBox)
    {
        divDetailsMessageBox.style.display = "none";
	}
}

/****************************************************************
* Function Update height message box DIV
* switch LENGTH text
*****************************************************************/
function heightMessageBox(idMessageBox, idDetailsMessageBox) 
{
    if (isIE6) return;
     
    // Height current browser
    var maxHeight = (ieNavigator)? document.body.offsetHeight : window.innerHeight;
    var minHeight = "62";
    
    // Update height MessageBox
    var divMessageBox = document.getElementById(idMessageBox);
    if (divMessageBox)
    {
        if (divMessageBox.style.maxHeight.search(maxHeight) > -1){
            divMessageBox.style.maxHeight = minHeight+"px";
        }else{
            divMessageBox.style.maxHeight = maxHeight+"px";
        }    
	}
	
	// Update CSS class details div
	var divDetailsMessageBox = document.getElementById(idDetailsMessageBox);
    if (divDetailsMessageBox)
    {  
        var replace = "";
        if (divDetailsMessageBox.className.search("Down") > -1)
        {
            replace = divDetailsMessageBox.className.replace("Down", "Up");
            divDetailsMessageBox.className = replace;
        }else{
            replace = divDetailsMessageBox.className.replace("Up", "Down");
            divDetailsMessageBox.className = replace;
        }  
	}
}

/****************************************************************
* Function Add message box DIV to page
*****************************************************************/	
function MessageBoxAdd(text, level)
{
    var messageBoxContent = document.getElementById('MessageBoxContent');
    var idDivMessageBox = 'Messages';
    var idCloseMessageBox = 'CloseMessages';
    var idDetailsMessageBox = 'DetailsMessages';
    
    var lenghtText = text.length;
    var maxCharactersTitle = text.indexOf('</span>',0);
    var maxCharactersLi = text.indexOf('</li>',maxCharactersTitle);
    
    // Number LI balises
    // > 2 then show details
    var regExp = /<\/li>/gi;
    var numberLi = false;
    if (text.match(regExp))
        numberLi = (text.match(regExp).length) > 2;
        
    // Length first/second LI balise
    var maxCharactersLiLength = -1;
    var maxCharactersLiLength2 = -1;
    if (maxCharactersLi > 0)
    {
        var maxCharactersLi2 = text.indexOf('</li>',maxCharactersLi + "</li>".length);
        maxCharactersLiLength = (maxCharactersLi - maxCharactersTitle);
        maxCharactersLiLength2 = (maxCharactersLi2 - maxCharactersLi);
    }
    
    var isBigText = (lenghtText > 255) || (maxCharactersTitle > 255) || (numberLi)
        || ((maxCharactersLiLength > 0) && (maxCharactersLiLength > 160))
        || ((maxCharactersLiLength2 > 0) && (maxCharactersLiLength2 > 105));
       
    var html = '<div id="' + idCloseMessageBox + '" class="Close" onclick="hideMessageBox(\''+ idDivMessageBox +'\',\''+ idCloseMessageBox +'\',\''+ idDetailsMessageBox +'\');" ></div>';
    
    html += '<div id="' + idDivMessageBox + '" class="' + level + '" ';
    if (isBigText && !isIE6)
        html += 'onclick="heightMessageBox(\''+ idDivMessageBox +'\', \''+ idDetailsMessageBox +'\');" ';
    
    html += '>';
    html += text;      
    html += '</div>';
    
    if (isBigText && !isIE6)
    {
        html += '<div id="' + idDetailsMessageBox + '" onclick="heightMessageBox(\''+ idDivMessageBox +'\', \''+ idDetailsMessageBox +'\');"  class="Details Down" ></div>';
    }
    messageBoxContent.innerHTML = html;       
}
    
    

/**************************************************************/
/*                                                            */
/*     Goto LMS, enter the LMS 4.2 web site                   */
/*                                                            */
/**************************************************************/
    function GotoLms()
    {
        SubmitForm('FormGotoLms');
    }

    function SubmitForm(id)
    {
        var myDiv = document.getElementById('myDynamicForm');
        if (!myDiv)
        {
            if (ieNavigator) 
            {
                myDiv = document.createElement("<div id='myDynamicForm'></div>");
            }
            else
            {
                myDiv = document.createElement("div");
                myDiv.id = 'myDynamicForm';
            }
            document.body.appendChild(myDiv);
        }
        myDiv.innerHTML = document.getElementById(id).value;
        document.forms[id].submit();
    }

/**************************************************************/
/*                                                            */
/*     Utilities for AutoComplete for the mail                */
/*                                                            */
/**************************************************************/

function returnValue() {
    //get the EntitieArea with selected items
    var area = EntitiesArea.getInstanceFromId("lblRecipients");
    
    //get the id of the objectselector
    var objselector = getParamInUrl("ObjectSelectorId");

    //Get a reference to the parent page (Default.aspx) 
    var oWnd = getRadWindow(); 

    //get a reference to the second RadWindow 
    var dialog1 = oWnd.get_windowManager().getWindowByName("Mail"); 
    var contentWin = null;

    // Get a reference to the first RadWindow's content
    if (dialog1) {
        contentWin = dialog1.get_contentFrame().contentWindow;
    } else {
        contentWin = oWnd.get_contentFrame().contentWindow.parent; 
    }

    //Call the predefined function in SendMail
    if (contentWin) {
        recipients = contentWin.getRecipients(objselector); 
    }
    
    //Call the predefined function in SendMail
    if (contentWin)
    {
        area.Refresh();
        contentWin.populateRecipients(area.Items, objselector);         
    }

    //Close the second RadWindow
    oWnd.close();
    return contentWin;
}
function returnPostBackValue() {
    var ret = returnValue();
    if (ret) {
        ret.__doPostBack('', '');
        ret.MessageBoxWaiting();
    }
}

/**
 * Process a postback call from a radwindo script
 */
function doPostBackFromRadWindow(name, target, value) {
    //Get a reference to the parent page (Default.aspx) 
    var oWnd = getRadWindow(); 
    var contentWin = null;
    var dialog1 = null;
    //get a reference to the second RadWindow     
    if (name) dialog1 = oWnd.get_windowManager().getWindowByName(name); 

    // Get a reference to the first RadWindow's content
    if (dialog1) {
        contentWin = dialog1.get_contentFrame().contentWindow;
    } else {
        contentWin = oWnd.get_contentFrame().contentWindow.parent; 
    }
    oWnd.close();
    contentWin.__doPostBack(target, value);
}

//Populate control with items selected for the mail autocomplete
function populateRecipients(items, objselectorId) {
    var inputHidden = document.getElementById(objselectorId + "_selectedIds");
    var autocomplete = $find(objselectorId + "_ComboBox");
    
    if (items.length > 0) {
        if (autocomplete.get_text() == autocomplete.get_emptyMessage())
            autocomplete.set_text("");
    }
    
    var i = 0;
    for (i=0; i<=items.length-1; i=i+1) {
        var itemValue = items[i].getInput().value;
        //test if input hidden has already the item
        if (itemValue != "")
        {
            if (inputHidden.value != "")
                inputHidden.value += ";";
                
            if (autocomplete.get_text() != "")
                autocomplete.set_text(autocomplete.get_text() + ";");
                
            inputHidden.value += itemValue;
            autocomplete.set_text(autocomplete.get_text() + items[i].Name);
        }
    }
}

function getRecipients(objselectorId) {
    var inputHidden = document.getElementById(objselectorId + "_selectedIds");
    return inputHidden.value;            
}


/**************************************************************/
/*                                                            */
/*     Utilities for AutoComplete                             */
/*                                                            */
/**************************************************************/

 //Populate control with items selected
function populateAutocompleteForAdd(listitems, objselectorId) {
        
    var inputHidden = document.getElementById(objselectorId + "_selectedIds");
    var autocomplete = $find(objselectorId + "_ComboBox");    
    
    var items = listitems.split(";");
    if (items.length > 0) {
        if (autocomplete.get_text() == autocomplete.get_emptyMessage())
            autocomplete.set_text("");
    }
    var allowMultiple = autocomplete.get_attributes().getAttribute("AllowMultiple")
  
    if (!Boolean.parse(allowMultiple))
    {
        inputHidden.value = "";
        autocomplete.set_text("");
    }
    
    var i = 0;
    for (i=0; i<=items.length-1; i=i+1) {
        var itemValue = items[i];
        //test if input hidden has already the item
        if (itemValue != "")
        {
            if (inputHidden.value != "")
                inputHidden.value += ";";
                
            if (autocomplete && autocomplete.get_text() != "")
                autocomplete.set_text(autocomplete.get_text() + ";");
                
            inputHidden.value += itemValue;
            var name = items[i].split(HiddenSeparatorAutocomplete);
            autocomplete.set_text(autocomplete.get_text() + name[2]);
        }
    }
}

//RadComboBox events
function OnClientItemsRequesting(sender, eventArgs) {
    var filter = GetFilter(sender, eventArgs)
    if (filter == null)
        return;
    var context = eventArgs.get_context();  
    context["FilterString"] = filter;
    
    context["NumberOfItems"] = eventArgs.get_context()["NumberOfItems"];
    context["ItemsPerRequest"] = sender.get_attributes().getAttribute("ItemsPerRequest");
    context["ClassName"] = sender.get_attributes().getAttribute("ClassName");
    context["Privilege"] = sender.get_attributes().getAttribute("Privilege");
    context["AllowMultiple"] = sender.get_attributes().getAttribute("AllowMultiple");
    var text = context["Text"];
    var separator = sender.get_attributes().getAttribute("AutoCompleteSeparator");
    if (!text.match(separator))
    {
        context["NumberOfSelected"] = 0;
    }
    else
    {
        var items = text.split();
        var numberOfItems = items.length;
        context["NumberOfSelected"] = numberOfItems;
    }
}

function GetFilter(sender, eventArgs) {
    var minChar = sender.get_attributes().getAttribute("MinCharFilter");
  
    var filter = sender.get_text();
    var separator = sender.get_attributes().getAttribute("AutoCompleteSeparator");
    
    var temp = filter.split(separator);
    if (separator != "" && temp.length > 1) {
        filter = temp[temp.length - 1];
    }
    
    if(filter.length < minChar) {
        eventArgs.set_cancel(true);
        return null;
    }
    return filter;
}

function OnClientSelectedIndexChanged(sender, eventArgs) {
    var item = eventArgs.get_item();
    var ctrl = $get(sender.get_id().replace("_ComboBox", "_selectedIds")); 
    if(item != null) {        
        if (!ctrl.value.match(item.get_value()) )    
            ctrl.value += ";" + item.get_value() + ";";        
    } 
}

function OnClientLoad(sender) {
    var cmb = sender;
    
    var ctrl = $get(sender.get_id().replace("_ComboBox", "_selectedIds"));
    if (ctrl != null) {
        if (!cmb._ajaxRequest)
        {
            var text = ctrl.getAttribute("text");
            if(text != null && text != "") {
                cmb.set_text(text);
            }
        }
    }
}

function HandleOpen(sender, eventArgs)
{
   var filter = GetFilter(sender, eventArgs)
   if (filter == null)
      return;        
}

function rightTrim(sString)
{
    while (sString.substring(sString.length-1, sString.length) == ' ')
    {
        sString = sString.substring(0,sString.length-1);
    }
    return sString;
}
/**
 * Class EntitiesArea (constructor)
 */
function EntitiesArea(clientId, AutoPostBack, OnAddItem, OnRemoveItem) {
    /**
     * @var array Static instances garbage
     */
    if (!EntitiesArea.instance) EntitiesArea.instance = new Object();
    /**
     * @var string HTML ID 
     */
    this.clientId = clientId;
    /**
     * @var boolean AUTO-POST-BACK
     */
    this.AutoPostBack = AutoPostBack;    
    /**
     * @var mixed Event : On Add Item 
     * Note : could be a string or an annonymous function 
     */
    this.OnAddItem = OnAddItem;
    /**
     * @var array List of items
     */
    this.Items = new Array();
    /**
     * @var mixed Event : On Remove Item
     * Note : could be a string or an annonymous function 
     */    
    this.OnRemoveItem = OnRemoveItem;
    /**
     * Get the HTML element
     */
    this.getElement = function() {
        return document.getElementById(this.clientId);
    }
    /**
     * Refresh the list of elements
     */
    this.Refresh = function() {
        this.Items = new Array();
        var elem = this.getElement();
        for(var i = 0; i < elem.childNodes.length; i++) {
            this.Items.push(new EntityLabel(elem.childNodes[i]));
        }     
    }
    /**
     * Constuctor
     */        
    this.Refresh();
    EntitiesArea.instance[this.clientId] = this;        
    /** END CONSTRUCTOR **/        
    /**
     * Add a new entity reference
     * @access public
     */
    this.AddItem = function(type, id, name) {
        this.Refresh();
        if (this.HasItem(type, id)) {
            this.GetItem(type, id).setName(name);
            return true;
        }
        var postId = this.clientId.toString().split("_").join("$");
        var uniqueId = this.clientId + "_" + type + "_" + id;
        
        var trimName = rightTrim(name);
        var value = type + HiddenSeparatorAutocomplete + id + HiddenSeparatorAutocomplete + name;
        var html = "<a id=\"" + uniqueId + "\" class=\"token\" href=\"#\" onClick=\"EntitiesArea.RemoveEntity(this);\" tabindex=\"-1\">";
        html += "<span><span><span><span class=\"" + type + "\">";
        html += "<input type=\"hidden\" name=\"" + postId + "$" + type + ":" + id + "\" value=\"" + value + "\" />";
        html += rightTrim(name);
        html += "<span class=\"x\"> </span>";
        html += "</span></span></span></span>";
        html += "</a>";
        this.getElement().innerHTML += html;
        var found = new EntityLabel(document.getElementById(uniqueId));
        if (this.OnAddItem) {
            var args = {
                item: found,
                cancel: false
            };
            if (typeof this.OnAddItem==='function') {
                this.OnAddItem(this, args);       
            } else {
                eval(this.OnAddItem + "(this, args)");
            }
            if (args.cancel) {
                found.Remove();
                return false;
            }
        }
        this.Items.push(found);        
        if (this.AutoPostBack) {
            __doPostBack(this.clientId, 'AddItem');
        }        
    }
    /**
     * Check for an existing item
     */   
    this.HasItem = function(type, id) {        
        return (this.GetItem(type, id) != null);
    }
    /**
     * Check for an existing item
     */   
    this.GetItem = function(type, id) {
        for(var i = 0; i < this.Items.length; i++) {
            if (
                this.Items[i].getTypeName() == type
                && this.Items[i].getId() == id
            ) {
                return this.Items[i];
            } 
        }        
        return null;
    }    
    /**
     * Remove an entity
     * @access public
     */ 
    this.RemoveItem = function(type, id) {
        this.Refresh();
        var newArray = new Array();
        var found = null;
        for(var i = 0; i < this.Items.length; i++) {
            if (
                this.Items[i].getTypeName() == type
                && this.Items[i].getId() == id
            ) {            
                found = this.Items[i];
            } else newArray.push(this.Items[i]);
        }
        if (!found) return false;
        // CHECK CLIENT SIDE EVENT
        if (this.OnRemoveItem) {
            var args = {
                item: found,
                cancel: false
            };
            if (typeof this.OnRemoveItem==='function') {
                this.OnRemoveItem(this, args);       
            } else {
                eval(this.OnRemoveItem + "(this, args)");
            }
            if (args.cancel) {
                return false;
            }
        }
        // EXECUTE DELETION
        found.Remove();
        this.Items = newArray;
        // EXECUTE POSTBACK
        if (this.AutoPostBack) {
            __doPostBack(this.clientId, 'RemoveItem');
        }                
    }
    
    /**
     * Remove an element from his link
     * @access static
     */
    EntitiesArea.RemoveEntity = function(aElement) {
        var instance = this.getInstanceFromEntity(aElement);
        if (instance) {
            var entity = new EntityLabel(aElement);
            instance.RemoveItem(entity.getTypeName(), entity.getId());
        }
    }    
    /**
     * Get an instance from an entity node
     * @access static
     */
    EntitiesArea.getInstanceFromEntity = function(aElement) {        
        return this.instance[aElement.parentNode.id];
    }    
    /**
     * Get an instance from div node
     * @access static
     */
    EntitiesArea.getInstanceFromElement = function(divElement) {        
        return this.instance[divElement.id];
    }     
    /**
     * Get an instance from object id
     * @access static
     */
    EntitiesArea.getInstanceFromId = function(id) {        
        for(var name in this.instance) {
            var str = name.toString()
            if (str.substr(str.length - id.length, id.length) == id) {
                return this.instance[name];
            }
        }
        return null;
    }     
    /**
     * Get an instance from client id
     * @access static
     */
    EntitiesArea.getInstance = function(id) {        
        return this.instance[id];
    }        
} 

/** 
 * Entity Label Class
 */
function EntityLabel(object) {
    /**
     * @var DOMNode NODE REFERENCE
     * @access public
     */
    this.elementId = object.id;
    /**
     * @var string 
     * @access private
     */
    this.TypeName = null;
    /**
     * @var string 
     * @access private
     */
    this.Id = null;
    /**
     * @var string 
     * @access private
     */
    this.Name = null;
    /**
     * Get the label element
     */
    this.getElement = function() {
        return document.getElementById(this.elementId);
    }     
    /**
     * Get the hidden field input
     */
    this.getInput = function() {
        return this.getElement().childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0];
    }          
    /**
     * Constructor
     */
    var parts = this.getInput().value.split(HiddenSeparatorAutocomplete);    
    this.TypeName = parts[0];
    this.Id = parts[1];
    this.Name = parts[2]
    /** END CONSTRUCTOR **/   
    /**
     * Refresh input value
     */
    this.RefreshInput = function() {
        this.getInput().value = this.TypeName + HiddenSeparatorAutocomplete + this.Id + HiddenSeparatorAutocomplete + this.Name;
    }      
    /**
     * Getting the type name
     */
    this.getTypeName = function() {
        return this.TypeName;
    }
    /**
     * Setting the type name
     */
    this.setTypeName = function(type) {
        this.TypeName = type;
        this.RefreshInput();
    }    
    /**
     * Getting the id
     */
    this.getId = function() {
        return this.Id;
    }
    /**
     * Setting the id
     */
    this.setId = function(id) {
        this.Id = id;
        this.RefreshInput();
    }    
    /**
     * Getting the name
     */
    this.getName = function() {
        return this.Name;
    }
    /**
     * Setting the name
     */
    this.setName = function(name) {
        this.Name = name;
        var nameNode = this.getElement().childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[1];
        if (nameNode.nodeValue) {
            nameNode.nodeValue = name;
        } 
        else 
            nameNode.textContent = name;
        this.RefreshInput();
    }    
    /**
     * Remove item
     */
    this.Remove = function() {
        if (this.getElement() != null) {
            return this.getElement().parentNode.removeChild(this.getElement());    
        } else return false;
    }
}

    
/**************************************************************/
/*  getElementsByClass                                        */
/*  get an Html element from it's css class                   */
/**************************************************************/
function getElementsByClass(searchClass,node,tag) {
    var classElements = new Array();
    if ( node == null )
        node = document;
    if ( tag == null )
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    var i;
    var j = 0;
    for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i];
            j++;
        }
        
    }
    return classElements;
}


/**************************************************************/
/*                                                            */
/*     Methods for WebParts                                   */
/*                                                            */
/**************************************************************/

    /**
     * Gestionnaire d'événements UNOBSTRUSIVE
     */
    function addEvent(obj, evType, fn){ 
     if (obj.addEventListener){ 
       obj.addEventListener(evType, fn, false); 
       return true; 
     } else if (obj.attachEvent){ 
       var r = obj.attachEvent("on"+evType, fn); 
       return r; 
     } else { 
       return false; 
     } 
    }
     
    // Fonction de stockage des scripts à charger 
    function addOnLoad(Obj) { 
        addEvent(window, 'load', Obj);
    } 
    function addOnResize(Obj) { 
        addEvent(window, 'resize', Obj);
    } 

     /**
     * Initialize dock area
     */
    function SetHandleDock(dock, e) {
        dock.set_handle(document.getElementById("Handle_" + dock.get_id()));
    }
    function DisableDock(dock, e) {
        dock.set_handle(null);
    }
    /**
     * Save a drag to current page
     */
    function SetLibraryDock(dock, e) {
        if (dock.get_dockZoneID().substr(dock.get_dockZoneID().length - 17) != 'WebPartZoneDelete') {
            dock.set_enableDrag(false);
            var c = document.getElementById(dock.get_id() + "_C");
            c.innerHTML = '<div class="WPItemSaving rdDraggable"><div class="icon"></div></div>';
            var args = dock.get_id() + ";" + dock.get_title() + ";" + dock.get_dockZoneID() + ";" + dock.get_index();
            __doPostBack("WebPartSave", args);
        }
    }
    /**
     * Close current window
     */
    function closeEditMode() {
        var obj = document.getElementById("ctl00_GlobalToolsContent_WebPartsTools1_ViewButton");
        if (obj)  {
            obj.click();
        } else {
            __doPostBack('', '');
        }
    }
    
    /**
     * Call Select Node for disabled TreeViews
     */
    function DisableEvent(sender, args) {
        args.set_cancel(true);
    }
    /**
     * Call delete
     */
    function callDeleteDock(dock, e) {
        if (e.command.get_name() == "Close") {
            if (dock.get_closed()) {
                dock.get_element().style.display = "block";
                if (confirm('Souhaitez-vous supprimer cette rubrique ?')) {
                    dock.set_enableDrag(false);
                    var c = document.getElementById(dock.get_id() + "_C");
                    c.innerHTML = '<div class="WPItemSaving rdDraggable"><div class="icon"></div></div>';
                } else {
                    e.set_cancel(true); // IGNORE CALLBACK
                    dock.set_closed(false); // DO NOT CLOSE
                }
            } else {
                e.set_cancel(true); // IGNORE CALLBACK
            }
        }
    }

    /**
     * Resize app
     */
    if (navigator.userAgent.indexOf("MSIE") != -1) {
        addOnLoad(fixWpLibHeight);
        addOnResize(fixWpLibHeight);

        addOnLoad(fixWpContentHeight);
        addOnResize(fixWpContentHeight);

        //Avoid Webpart Clipping on IE6
        function fixWpContentHeight() {
            try {
                var wpContent = $telerik.$('.WpContent');
                if (wpContent) {
                    //remove top + bottom positionning
                    wpContent.height($telerik.$(document).height() - 120);
                }    
            }
            catch (ex) {
                //alert('error');
            }
        }
        
        
        function fixWpLibHeight() {
            try {
                if (RefIdWpLib) {
                    var zone = document.getElementById(RefIdWpLib);
                    if (zone) {
                        var ul = zone.parentNode.parentNode.parentNode;
                        if (ul) {
                            // FIX FOR IE6
                            if (navigator.userAgent.indexOf("MSIE 6") != -1) {
                                var divMain = getParentByClass(ul, 'WebParts EditMode');
                                divMain.style.width = (windowWidth() - 40 - 140) + "px";
                                divMain.style.height = (windowHeight() - 106 - 10) + "px";
                                var lib = getParentByClass(ul, 'WpLibrary');
                                
                                // TRY PARENT
                                try {
                                    var child = getParentByClass(lib, 'WpLibrary');
                                    if (child != null) lib = child;
                                }
                                catch (ex) { }
                                lib.style.position = 'absolute';
                 
                                lib.style.left = (windowWidth() - 20 - 140) + 'px';
                                if (ul.clientHeight) {
                                    if (ul.clientHeight < windowHeight() - 106 - 10) {
                                        zone.style.height = (ul.clientHeight - 3) + "px";
                                    } else {
                                        zone.style.height = (windowHeight() - 106 - 46) + "px";
                                    }
                                }
                            } else {
                                // FIX ZONE FOR IE 7              
                                if (ul.clientHeight) zone.style.height = (ul.clientHeight - 2) + "px";
                            }
                        }
                    }
                }

            } catch (ex) {
                // ignore RefIdWpLib undefined
            }
        }
    } 

    function windowWidth() {
        return document.documentElement.clientWidth;
    }
    function windowHeight() {
        return document.documentElement.clientHeight;
    }

    function getParentByClass(child, css) {
        if (child == null) return null;
        if (child.parentNode.className.indexOf(css) != -1) {
            return child.parentNode;
        } else {
            return getParentByClass(child.parentNode, css);
        }
    }

/**************************************************************/
/*                                                            */
/*     GridView                                               */
/*                                                            */
/**************************************************************/

    var ctrlPress = 0;              // Use to indicate if the Control key is pressed
    var shiftPress = 0;             // Use to indicate if the Shift key is pressed
    var checkClic = 0;              // Use to indicate if the checkBox of a line has been clicked
    var lastGridView = null;        // The last GridView
    //var menuContext = null;         // The menuContext
    
    var currentId = "";     // current row id maintained during a selection phase
    var currentIndex = -1;  // current tableau ligne index maintained during a selection phase
    var lastId = "";  // the last id to be selected which begins a selection phase
    
    var notifyTimer = null;
    var selectInProgress = false;
    
    // ---------------------------------------------------------------------------------------------
    // Name : MakeGridViewsDynamics
    // Initialize all GridViews of the page
    // Result : return true when finished        
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function MakeGridViewsDynamics() {
        var gridViews = getElementsByClass('GridView', document.getElementById('DivContent'), 'table');
        var i;
        for (i=0; i< gridViews.length;i++) {
            InitGridView(gridViews[i]);
        }
        return true;
    }

    function Datas() {
        this.SelectLigne = 0;            // Use to indicate if at least one line is selected
        this.Temp;                       // Current line selected
        this.CheckAll = 0;               // Use to indicate if every lines are selected
        this.MenuContext;                // Define the contextual menu element
        this.TableauLignes = null;       // Table that contains all the lines of the table (TD)
        this.FirstLine = 0;              // Set the index of the firstline TD of the table
        this.AllowSelection = false;
        this.AllowMultiple = false;
        
        this.LastSelectedId = "";
        this.LastSelectedIndex = -1;
        
        this.AllowClickLineSelector = false;
    }

    /**
     * Get a line from his index
     */
    function getLineFromId(gridview, id) {
        for(var i = 0; i < gridview.Datas.TableauLignes.length; i ++) {
            if (
                gridview.Datas.TableauLignes[i].getAttribute("dataitemid") != null
                && gridview.Datas.TableauLignes[i].getAttribute("dataitemid") != ""
                && gridview.Datas.TableauLignes[i].getAttribute("dataitemid") == id) {
                return gridview.Datas.TableauLignes[i];
            }
        }
        return null;
    }    

    // ---------------------------------------------------------------------------------------------
    // Name : SearchFirstLineRow
    // Search line with classname 'ROW' or 'ROWSEL' and have column TD (not TH)
    // Param gridView : the gridView component
    // Result : return first line classname 'ROW' or 'ROWSEL' and have column TD (not TH)        
    // Author : Ronan Salmon                                     
    // ---------------------------------------------------------------------------------------------
    function SearchFirstLineRow(gridView)
    {
        var lineRow = null;
        var testLine = null;
        var firstCellNode = null;
        
        var allLines = gridView.Datas.TableauLignes;
        for (iLigneGrid = 0; iLigneGrid < allLines.length; iLigneGrid++)
        {
            // Search line with column 'TD' (not 'TH')
            testLine = gridView.Datas.TableauLignes[iLigneGrid];
            if ( testLine.className == 'Row' || testLine.className == 'RowSel' ) {
                firstCellNode = testLine.firstChild;
                
                // ignore whitespace seen as text nodes by non IE browsers ..
                while ( firstCellNode.nodeType == 3 ) {
                    firstCellNode = firstCellNode.nextSibling;
                }
                
                if ( firstCellNode.tagName == 'TD' ) {
                    lineRow = testLine;   
                    break;         
                }
                
            }
        }
        return lineRow;
    }
    

    function stop() { 
        return false; 
    }
    
    // ---------------------------------------------------------------------------------------------
    // Name : InitGridView
    // Initialize the GridView of the page : add multiple selection, contextual menu, add 
    // buttons in the toolBox    
    // Param gridView : the gridView component
    // Result : return true when finished           
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function InitGridView(gridView) {
    
        if ((lastGridView != null) && (lastGridView != gridView))
            hideContextualMenu();
            
        lastGridView = gridView;
        if (!gridView.Datas) {
            gridView.Datas = new Datas();
        }
        
        // SQ : can not disable onselectstart on the whole document : otherwise we can not select a text in a textbox when a GridView is on same screen.
        //document.body.onselectstart = stop;
        // SQ : I can not see any difference with or without the line below
        //gridView.onselectstart = stop;
        document.onkeydown = ctrlKeyDown;
        document.onkeyup = ctrlKeyUp;
         
        InitTableauLigne(gridView);

        if (gridView.Datas.TableauLignes[0].className.search("Pager") != -1) {
            gridView.Datas.FirstLine = 2;
        }
        else {
            gridView.Datas.FirstLine = 1;
        }
        
        // if gridview is empty, quit
        if (gridView.Datas.TableauLignes.length<=gridView.Datas.FirstLine) 
            return;
        var node = gridView.Datas.TableauLignes[gridView.Datas.FirstLine-1].getElementsByTagName('TH');

        if (node.length == 0) return;
        
        // Set selection behaviour if selection is allowed
        
        var selectedIdsInput = document.getElementById(gridView.id+'_SelectedIds');

        if (selectedIdsInput) {
            gridView.Datas.AllowSelection = true;
            if ( gridView.getAttribute( "allowMultipleSelector" ) == 'true' ) {
                gridView.Datas.AllowMultiple = true;
            }
            
            if ( gridView.getAttribute( "allowClickLineSelector" ) == 'true' ) {
                gridView.Datas.AllowClickLineSelector = true;
            }
        }
 
        if (gridView.Datas.AllowSelection == true)  {
            gridView.Datas.LastSelectedId = document.getElementById( gridView.id+'_LastSelectedId' ).value;
            // Selection is allowed : create context menu     
            initContextualMenuCreate(gridView);
            // Set the functions for the mouse events
            gridView.onmousedown = createContextualMenuClick;
            initSelectedRows(gridView, selectedIdsInput);
        }
        
        // Initialize buttons in the toolBox
        // Get the first line of the gridView IF is a 'ROW' class
        // else IF is a 'GROUPING' class, get line appropriated
        var ligneTrs1 = SearchFirstLineRow(gridView);
            
        if (ligneTrs1 != null) {   // Create a list to store column numeros of the action's buttons
            var lignesTD = ligneTrs1.getElementsByTagName('TD');
            var lignesBouton = new Array();
            var withButton = false;
            var colonnesDeBoutons = new Array();
            for ( var i = 0; i < lignesTD.length; i++)
            {
                if (lignesTD[i].className == 'Button')
                {
                    // Store column numeros of the button in the list
                    colonnesDeBoutons.push(i);                               
                    lignesBouton.push(lignesTD[i]);
                    withButton = true;
                }
            }
            if (withButton == true)
            {
                var idButton = null;
                var titleBouton = null;
                var index = 0;
                
                // Check if toolBox buttons have already been added
                var toolBox = GetToolBox(gridView);
                if (!toolBox) return true;
                if (toolBox.GridViewInitialized) return true;
                toolBox.GridViewInitialized = true;               
                while (index < lignesBouton.length)
                {
                    // Test the type of button action
                    var ligneA = lignesBouton[index].getElementsByTagName('A');
                    if (ligneA.length != 0)
                    {
                        titleBouton = ligneA[0].getElementsByTagName('IMG')[0].title; 
                        var classButton = ligneA[0].getElementsByTagName('IMG')[0].getAttribute('ClassButton');
                        // Take image name with nameProp property : delete suffixe '.gif'
                        if (classButton == null)
                        {
                            var name = ligneA[0].getElementsByTagName('IMG')[0].src;
                            if (!name)
                                name = ligneA[0].getElementsByTagName('IMG')[0].getAttribute('src');
                            if (name)
                            {
                                var urlP = name.split('/');
                                name = urlP[urlP.length - 1];
                                classButton = name.split('.')[0];
                            }
                        }
                        initToolBoxCreateButton("a", titleBouton, classButton, index, gridView, colonnesDeBoutons[index]);                    
                    }                
                    
                    var ligneInputs = lignesBouton[index].getElementsByTagName('INPUT'); 
                    var input = null;
                    for (var indexInput = 0; indexInput < ligneInputs.length; indexInput++)
                    {
                        input = ligneInputs[indexInput];
                        if ( input.type != 'hidden')
                        {   
                            titleBouton = input.title;
                            var allowMultiple = input.getAttribute('AllowMultiple');
                            var classButton = input.getAttribute('ClassButton');
                            if ('true' == allowMultiple)
                            {         
                                initToolBoxCreateButton("inputMultiple", titleBouton, classButton, index + '_' + indexInput, gridView, colonnesDeBoutons[index]);
                            }       
                            else
                            {
                                initToolBoxCreateButton("inputSimple", titleBouton, classButton, index + '_' + indexInput, gridView, colonnesDeBoutons[index]);
                            }
                        }
                    }
                    index++;    
                }            
            }
            
            modifyEmptyCells( gridView );
        }
        return true;
    }
    
    // -------------------------------------------------------------------------------------
    // This function goes through the data field cells inserting a &nbsp; inside all empty
    // field data cells.  This is needed so that browsers (mainly IE) show rows that have empty cells
    // ------------------------------------------------------------------------------------
    function modifyEmptyCells( gridView ) {
        var trs = gridView.getElementsByTagName("TR");    
        var iLigneGrid;
        for ( iLigneGrid = 0; iLigneGrid < trs.length; iLigneGrid++) {
            var cells = trs[iLigneGrid].getElementsByTagName("TD");
            for ( var idx = 0; idx < cells.length; idx++ ) {
                
                if ( cells[idx].className.match( "FieldData" ) ) {
                    
                    var childNodes = cells[idx].childNodes;
                    var node = null;
                    
                    // if empty add &nbsp;
                    if ( childNodes.length == 0 ) {
                        node = cells[idx];
                        if (node.innerText == "" || node.textContent == "" ) {
                            var newNode = document.createElement("span");
                            newNode.innerHTML = "&nbsp;";
                            node.appendChild(newNode );
                        }
                    }
                    else if ( childNodes.length == 1 ) {
                        node = childNodes[0];
                        // otherwise add &nbsp; only if a empty span is found
                        if ( node.childNodes.length == 0 && node.nodeName == "SPAN" ) {
                            var newNode = document.createElement( "span");
                            newNode.innerHTML = "&nbsp;";
                            var parent = node.parentNode;
                            parent.appendChild( newNode );
                        }
                    }
                }
            }
        }
    }

    // ---------------------------------------------------------------------------------------------
    // Name : initToolBoxCreateButton
    // Function that permit to create and add buttons in the toolBox
    // Param typeAction : string that define the type of action bind to the button
    // Param titleButton : string that define the value of the button
    // Param classButton : string that define the value of the class button
    // Param numId : number, that precise the index of the button, added to its id
    // Param gridView : the gridView component
    // Param numeroDeColonne : the index of the column coreesponding at the action to do
    // Result : return true when finished
    // Author : Philippe
    // ---------------------------------------------------------------------------------------------
    var buttonTableAction = {};
    function initToolBoxCreateButton(typeAction, titleButton, classButton, numId, gridView, numeroDeColonne) {
        var buttonToAdd;
        var disabled = false;
        // Create Toolbox item button (custom button is an <a><span /></a> from
        buttonToAdd = document.createElement('a');
        buttonToAdd.id = gridView.id + '_ButtonAction' + numId;
        buttonToAdd.className = 'CustomButtonCommon ' + classButton;
        
        if (typeAction == "a") {
            buttonToAdd.setAttribute("AllowMultiple", "false");
            buttonToAdd.setAttribute("onClick", "ViewButton_Click('" + gridView.id + "'," + numeroDeColonne + ");");
        }
        if (typeAction == "inputMultiple") {
            buttonToAdd.setAttribute("AllowMultiple", "true");
            buttonToAdd.setAttribute("onClick", "MultipleButton_Click('" + gridView.id + "'," + numeroDeColonne + ");");
        }
        if (typeAction == "inputSimple") {
            buttonToAdd.setAttribute("AllowMultiple", "false");
            buttonToAdd.setAttribute("onClick", "SimpleButton_Click('" + gridView.id + "'," + numeroDeColonne + ");");
        }

        if (gridView.Datas.SelectLigne == 0) {
            //buttonToAdd.disabled = 'true';
            // a does not support disabled propertie
            if (buttonToAdd.className.indexOf(' disabled') == -1) {
                buttonToAdd.className += " disabled";
                buttonToAdd.setAttribute("disabled", "disabled");
                disabled = true;
            }
            buttonToAdd.setAttribute("onClick", "if (this.getAttribute('disabled')) return false;" + buttonToAdd.attributes["onClick"].value);
        }
        else {
            buttonToAdd.className = buttonToAdd.className.replace(' disabled', '');
            buttonToAdd.removeAttribute("disabled");
        }
        buttonTableAction[buttonToAdd.id] = buttonToAdd.getAttribute("onClick");
        
        //IE does not allow complex element creation
        if (ieNavigator) 
        {
            //DEBUG #4830 - check button is enabled
            var inputSimple = "";
            //alert("typeAction = " + typeAction + " select lines = " + gridView.Datas.SelectLigne);
            if (typeAction == "inputSimple" || typeAction == "a") {
                if (gridView.Datas && gridView.Datas.SelectLigne > 1) {
                    inputSimple = "disabled=\"" + disabled + "\"";
                    buttonToAdd.disabled = disabled;
                    buttonToAdd.className += " disabled";
                }                 
            }
            var buttonText = "<span class=\"" + classButton + "\" >&nbsp;</span><input class=\"ContainerLeftPart\" value=\""
                        + titleButton.toString() + "\"" + inputSimple + " type=\"button\" />"; // disabled=\"" + disabled + "\"  
            buttonToAdd.innerHTML = buttonText;
            
            if (!buttonToAdd.onclick)
                buttonToAdd.onclick = new Function("event", "if (this.getAttribute('disabled')) return false;" + buttonToAdd.attributes["onClick"].value);
        }
        else {
            //create child control for a
            buttonContentSpan = document.createElement('span');
            buttonContentSpan.className = classButton;
            buttonContentSpan.innerHTML = "&nbsp;"
            buttonLogoInput = document.createElement('input');
            buttonLogoInput.setAttribute("value",titleButton);
            buttonLogoInput.className = "ContainerLeftPart";
            
            buttonLogoInput.type = 'button';
            //DEBUG #4830 - check button is enabled
            if (typeAction == "inputSimple" || typeAction == "a") {
                if (gridView.Datas && gridView.Datas.SelectLigne > 1) {
                    buttonLogoInput.disabled = disabled;
                    buttonContentSpan.className += " disabled";
                    buttonToAdd.className += " disabled";
                }
            }
            //buttonLogoInput.disabled = disabled;
            buttonToAdd.appendChild(buttonContentSpan);
            buttonToAdd.appendChild(buttonLogoInput);            
        }

        // Get the toolBox element of the document (DIV)
        var toolBox = GetToolBox(gridView);

        // Add the button action to the toolBox
        if (toolBox) {
            toolBox.appendChild(buttonToAdd);
        }

        return true;
    }

    function GetToolBox(gridView) {
        var toolBoxID = gridView.getAttribute('toolBoxID');
        if (toolBoxID) {
            return document.getElementById(toolBoxID);
        }
        return null;
    }

    function InitTableauLigne(gridView) {
        if (!gridView) return;
        var trs = gridView.getElementsByTagName("TR");    
        gridView.Datas.TableauLignes = new Array();
        var iLigneGrid;
        for (iLigneGrid = 0; iLigneGrid < trs.length; iLigneGrid++) {
            if (trs[iLigneGrid].parentNode.parentNode.className.search('GridView') != -1)
            {
                gridView.Datas.TableauLignes.push(trs[iLigneGrid]);
            }
        }
    }

    function initSelectedRows(gridView, selectedIdsInput) {
        
        if (!gridView) return;
        var selection = ','+selectedIdsInput.value+',';
        
        var lines = gridView.Datas.TableauLignes;
        var currentLine = null;
        for (i = 0; i < lines.length; i++) {
            currentLine = lines[i];
            var id = GetLigneId( currentLine );
            if (id)  {
                if (selection.search(','+id+',') != -1)  {
                    selectLine( currentLine );
                    gridView.Datas.LastSelectedIndex = GetLigneIndex( currentLine );
                }
            }
        }
        
        testCheckAll(gridView);
    }

    // Utility method to call when an button is to push
    // If the button has a confirm message, it will be displayed.
    // The submit is done via ajax panel.
    function PushButton(id, name) {   
        var func = document.getElementById(id).onclick;
        if (func) {
            var result = func();
            if (result==false) {
                return ;
            }
            else {
            
                if (name)
                    __doPostBack(name, '');
                else
                    __doPostBack(id, '');
            }
        } 
        else {
            if (name)
                __doPostBack(name, '');
            else
                __doPostBack(id, '');
        }
    }

    // ---------------------------------------------------------------------------------------------
    // Name : ViewButton_Click
    // Function that permit redirection to the page of the selected line after a mouse click
    // Param column : numero of the column that contains the button action
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function ViewButton_Click(gridViewId, column) {        
        var gridView = document.getElementById(gridViewId);
        if (!gridView) return;

        if (!gridView.Datas) return;
        
        if (!gridView.Datas.TableauLignes) return;
        
        var lines = gridView.Datas.TableauLignes;
        var ligneSel = null;
        for (iLigneGrid = 0; iLigneGrid < lines.length; iLigneGrid++) {
            if ( isLineSelected( lines[iLigneGrid] ) ) {
               
                if (ligneSel != null) return;
                ligneSel = lines[iLigneGrid];            
            }
        }
        
        if (ligneSel != null) {   
            // Create the link for the redirection
            var listeTd = ligneSel.getElementsByTagName('TD');
            url = listeTd[column].getElementsByTagName('A')[0].href;
            window.location.href = url;
        }
        return true;
    }

    // ---------------------------------------------------------------------------------------------
    // Name : MultipleButton_Click
    // Function to execute the button action when several lines were selected
    // Param column : numero of the column that contains the button action
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function MultipleButton_Click(gridViewId, column) {
        var gridView = document.getElementById(gridViewId);
        if (!gridView) return;
        
        //TOM InitGridView(gridView);
        
        var ligneTrs1 = SearchFirstLineRow(gridView);
        var tdCourant = ligneTrs1.getElementsByTagName('TD')[column];
     
        var listeInput = tdCourant.getElementsByTagName('INPUT');
        if (listeInput.length > 0) {
            PushButton(listeInput[0].id, listeInput[0].name);
        }
        return true;
    }

    // ---------------------------------------------------------------------------------------------
    // Name : SimpleButton_Click
    // Function to execute the button action when one line only was selected
    // Param column : numero of the column that contains the button action
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function SimpleButton_Click(gridViewId, column) {
        var gridView = document.getElementById(gridViewId);
        if (!gridView) return;
        
        
        //TOM InitGridView(gridView);
        
        var lines = gridView.Datas.TableauLignes;
        var ligneSel = null;
        for (iLigneGrid = 0; iLigneGrid < lines.length; iLigneGrid++) {
            
            if (isLineSelected( lines[iLigneGrid] ) == true ) {
                if (ligneSel != null) return;
                ligneSel = lines[iLigneGrid];            
            }
        }
        
        if (ligneSel != null) {
            var tdCourant = ligneSel.getElementsByTagName('TD')[column];
            var listeInput = tdCourant.getElementsByTagName('INPUT');
            if (listeInput.length > 0)
            {
                PushButton(listeInput[0].id, listeInput[0].name);
            }
        }
        return true;
    }

    // ---------------------------------------------------------------------------------------------
    // Name : changeToolBoxState
    // Function that permit to change the state of the buttons in the toolBox
    // Param nbLigneSelect : number of lines selected
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function changeToolBoxState(gridView) {         
        var simpleSelect = AreMultiplelignesChecked(gridView.Datas);
        // On AlwaysVisible if exists
        var divAlwaysVisible = document.getElementById('AlwaysVisible');
        if (divAlwaysVisible)
            changeToolBoxStateOnDiv(gridView.Datas.SelectLigne, divAlwaysVisible, simpleSelect);
        // On ToolBox if exists
        var toolBox = GetToolBox(gridView);
        if (toolBox)
            changeToolBoxStateOnDiv(gridView.Datas.SelectLigne, toolBox, simpleSelect);
        return true;
    }

    // DEBUG #4830 
    // Test for checkbox All
    function AreMultiplelignesChecked(datas) {
        
        //if (!datas || !datas.TableauLignes) return true;
            
        return datas.SelectLigne == 1 && (
            datas.CheckAll == 0 ||
            (datas.CheckAll == 1 && datas.TableauLignes.length == 2)
            );
    }

    function changeToolBoxStateOnDiv(nbLigneSelect, div, checkAll) {
        //changes for a span Elements
        var listeInput = div.getElementsByTagName('a');

        for (iListe = 0; iListe < listeInput.length; iListe++) {
        
            var allowMultiple = listeInput[iListe].getAttribute('AllowMultiple');
            if (allowMultiple == null) continue;      

            var onclickvalue = buttonTableAction[listeInput[iListe].id];
            if (!onclickvalue) {
                //IE onclick value
                onclickvalue = listeInput[iListe].attributes["onClick"].value;
            }
            var className = listeInput[iListe].className;
            if (!className) className = listeInput[iListe].attributes["class"].value;

            var elt = listeInput[iListe];
            var eltinput = elt.getElementsByTagName('input');
            if ('true' == allowMultiple) {
                
                if (nbLigneSelect == 0) {
                    if (elt.className.indexOf(' disabled') == -1) {
                        elt.className = className + ' disabled';
                        elt.setAttribute("disabled", "disabled");

                    }
                    eltinput[0].disabled = true;
                    //if (onclickvalue) functionToCall = "return false;" + onclickvalue;
                }
                else {
                    elt.className = className.replace(' disabled', '');
                    elt.removeAttribute("disabled");
                    eltinput[0].disabled = false;
                }
            }
            else {
                
                if (nbLigneSelect == 1 && checkAll) {
                   elt.className = className.replace(' disabled', '');
                   elt.removeAttribute("disabled");
                   eltinput[0].disabled = false;
                }
                else {
                    if (elt.className.indexOf(' disabled') == -1) {
                        elt.className = className + ' disabled';
                        elt.setAttribute("disabled", "disabled");
                    }
                    eltinput[0].disabled = true;
                    //if (onclickvalue) functionToCall = 'return false;' + onclickvalue;
                }
            }
            if (ieNavigator)
                elt.onclick = new Function("event", onclickvalue);
            else
                elt.setAttribute("onClick", onclickvalue);
        }
    }   

    // ---------------------------------------------------------------------------------------------
    // Name : stopClicDroit
    // Disable the contextual menu when there is a right click on the GridView
    // Result : return false
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function stopClicDroit() {
        return(false);
    }

    /****************************************************************/
    /*               Functions for the Table                        */
    /****************************************************************/
    // ---------------------------------------------------------------------------------------------
    // Name : colorMove
    // Set the style of the selected line when the mouse is over (expected when selected)
    // Param e : event representing the mouse movement
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function colorMove(e){
        var ligne = getLigne(e);
        if (ligne == null) return;
        
        if (ligne.className.search('RowSel') == -1) {
            ligne.className = 'RowOver';    
        }
        return true;
    }

    // ---------------------------------------------------------------------------------------------
    // Name : uncolorMove
    // Set the style of the unselected line when the mouse is out (expected when selected)
    // Param e : event representing the mouse movement
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function uncolorMove(e) {
    
        var ligne = getLigne(e);
        if (ligne == null) return;
        if (ligne.className.search('RowOver') != -1) {
            ligne.className = 'Row';
        }
        return true;
    }

    // ---------------------------------------------------------------------------------------------
    // Name : getLigne
    // Get the ligne from the mouse click event on the gridView
    // Param e : event representing the mouse movement
    // Result : return the line or null if no line was found
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function getLigne(e)
    {
        var ligne = (document.all) ? event.srcElement: e.target;
        if (!ligne) return null;

        if (ligne != null)
        {
            while ((ligne.tagName != 'TR') || (ligne.className.search('Row') == -1))
            {
                ligne = ligne.parentNode;
                if (ligne == null)
                {
                    break;
                }
            }
        }
        if ((ligne != null) && (ligne.parentNode.parentNode.className.indexOf('GridView') != -1))
            return ligne;
        else
            return null;
    }
    
    // --------------------------------------------------------------------
    // Select all lines between one selected row and another
    // --------------------------------------------------------------------
    function doShiftSelect( gridView, ligne ) {

        if ( gridView.Datas.SelectLigne == 0 ) {
        
            var allLines = gridView.Datas.TableauLignes;
                                
            for ( idx = 1; idx <= ligne.rowIndex; idx++ ) {  
                selectLine( allLines[idx] );
            }
            
            gridView.Datas.LastSelectedId = GetLigneId( ligne );
            gridView.Datas.LastSelectedIndex = GetLigneIndex( ligne );
        }
        else {
        
            // a line is already selected - select all those between the two
            
            if ( ! gridView.Datas.LastSelectedId ) {
                //alert( "last selected id error" );
            }
            else {
                // current ligne index
                var allLines = gridView.Datas.TableauLignes;
                var lastOneFound = false;

                var idx = parseInt( gridView.Datas.LastSelectedIndex ) + gridView.Datas.FirstLine;
               
                lastOneFound = allLines[ idx ];
                
                if (lastOneFound ) {
                
                    // select all lines between current line index and index of last selelcted
                    var from;
                    var to;
                    
                    if ( idx < ligne.rowIndex ) {
                        from = idx;
                        to   = ligne.rowIndex;
                    }
                    else {
                        from = ligne.rowIndex;
                        to   = idx;
                    }

                    for ( idx = from; idx <= to; idx++ ) {
                        selectLine( allLines[idx] );
                        
                    }
                    
                    gridView.Datas.LastSelectedId = GetLigneId( ligne );
                    gridView.Datas.LastSelectedIndex = GetLigneIndex ( ligne );
               }
            }
        }

    }
    
    //-----------------------------------------------------------
    // Update variables so that the last selected row is known
    // ----------------------------------------------------------
    function saveSelectedLine( gridView, id, index ) {
	    currentIndex = -1;
	    gridView.Datas.LastSelectedId = id;
        gridView.Datas.LastSelectedIndex = index;
    }
    
    // -----------------------------------------------------------
    // Post backs the current selection
    // -----------------------------------------------------------
    function notifyServerOfSelect( gridView ) {
        
        if ( ! gridView )
            gridView = lastGridView; 
        selectInProgress = false;

        if ( ! gridView.getAttribute( "notifySelectionChanged" ) ) {   
            document.getElementById( gridView.id+'_LastSelectedId' ).value = gridView.Datas.LastSelectedId;
            __doPostBack( gridView.getAttribute( "UniqueId" ), 'RowClicked' );
        }
    }
    
    
    // ---------------------------------------------------------------------------------------------
    // Name : selectLineClick
    // Realize selection and unselection of the lines, according to differents cases, when the
    // user click on the GridView
    // Param e : event representing the mouse click
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function selectLineClick(e)
    {
        // clear an existing timeout (required for firefow which raises onclick then onclick again before ondblclick !)
        clearTimeout( notifyTimer );
        notifyTimer  = null;
        
        var ligne = getLigne(e);
        var gridView = ligne.parentNode.parentNode;
        if (!gridView) return;

        if ( (ligne != null) && (gridView.className.search("GridView") != -1) )
        {
            selectInProgress = true;
            if ( gridView.Datas.AllowMultiple && e.shiftKey === true) {
                doShiftSelect( gridView, ligne );
                shiftPress = 0;
                testCheckAll(gridView);
            } 
            else if ( gridView.Datas.AllowMultiple && e.ctrlKey === true ) {
            
                // select or deselct the selected line
                if ( isLineSelected( ligne ) == true ) {
                    deselectLine( ligne );
                }
                else {
                    selectLine( ligne );
                    saveSelectedLine( gridView, GetLigneId( ligne ), GetLigneIndex( ligne ) );
                }

                testCheckAll(gridView);
                
            }
            else { // normal select either by line or by check box
                
                if (gridView.Datas.SelectLigne == 0) {	
                    // No lines are currently selected so we can select the chosen line
                    gridView.Datas.SelectLigne = 1;

	                if ( isLineSelected( ligne ) == false ) {

                        selectLine( ligne );
                        
                        lastId =  GetLigneId( ligne );
                        saveSelectedLine( gridView, GetLigneId( ligne ), GetLigneIndex( ligne ) );
	                }
	                else {
	                    deselectLine( ligne );
	                }
                }
                else {
                   // At least one line is already selected if lineSelect deselct all & select line
                    if ( checkClic != 1 ) {
                    
                        // simple line select
                        // deslect all and select chosen line
                        var allLines = gridView.Datas.TableauLignes;
                                
                        for ( idx = 1; idx < allLines.length; idx++ ) {  
                           deselectLine( allLines[idx] );
                        }
                        
                        selectLine( ligne );
                        lastId =  GetLigneId( ligne );
                        saveSelectedLine( gridView, GetLigneId( ligne ), GetLigneIndex( ligne ) );
                    }
                    else {
                        // line clicked via checkbox
                        if ( isLineSelected( ligne ) == true ) {
                            deselectLine( ligne );
                        } 
                        else {
                            selectLine( ligne );
                            lastId =  GetLigneId( ligne );
                            saveSelectedLine( gridView, GetLigneId( ligne ), GetLigneIndex( ligne ) );
                        }
                    }
                }

                checkClic = 0;
                testCheckAll(gridView);
                
                // delay the server notification to give the double click event the chance to fire
                // and cancel the single select event.  Note in the case of Firefox we will receive
                // a second onclick before a ondblclick!
                notifyTimer = setTimeout( function(){ notifyServerOfSelect(gridView); }, 275 );
            }
        }
        return false;
    }
    
    function selectLineByCheckBox(e) {    
        checkLineState(e);
        selectLineClick(e);
    }
    
    // ---------------------------------------------------------
    // Returns true if line is currently selected else false
    // ---------------------------------------------------------
    function isLineSelected( line ) {
        
        //if ( line.className.search( 'RowSel' ) != -1 ) {  // TOM search is not necessary - check for equality

        if ( line.className == 'RowSel' ) {
            return true;
        } else {
            return false;
        }
    }
    
    //-------------------------------------------------
    // Update the line to selected
    //-------------------------------------------------
    function selectLine( line ) {
        if (line.className != 'RowSel') {            
            line.className = 'RowSel';   
            var gridView = line.parentNode.parentNode;    
            var evt = gridView.getAttribute("onclientcheck");
            if (evt != null && evt != "") {
                eval(evt + "(gridView, line)");
            }   
        }
    }
    
    //-------------------------------------------------
    // Update the line to be not selected
    //-------------------------------------------------
    function deselectLine ( line ) {
        if (line.className != 'Row') {
            line.className = 'Row';
            var gridView = line.parentNode.parentNode;    
            var evt = gridView.getAttribute("onclientuncheck");
            if (evt != null && evt != "") {
                eval(evt + "(gridView, line)");
            }   
        }
    }
    
    // ---------------------------------------------------------------------------------------------
    // Name : deselectAllLines
    // Function that deselect all the lines of the GridView
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function deselectAllLines(gridView)
    {
        if ((!gridView) || (!gridView.Datas) || (!gridView.Datas.TableauLignes))
            return;
        
        var lines = gridView.Datas.TableauLignes;
        for( idx = 1; idx < lines.length; idx++ ) {
            deselectLine( lines[idx] );
        } 
    }


    // ---------------------------------------------------------------------------------------------
    // Name : testCheckAll
    // Check if all the lines are selected or not and set the state of the general checkBox
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function testCheckAll(gridView) {
        var indLigne = gridView.Datas.FirstLine;
        var totalLigne = 0;
	    nbSelect = 0;
    	
	    // Reset the hidden field that contains the ids of the selected lines
        resetSelectedIds(gridView);

        if (gridView.Datas.TableauLignes != null)
        {
            while (gridView.Datas.TableauLignes[indLigne] != null)
            {
                if ( (gridView.Datas.TableauLignes[indLigne].parentNode.parentNode.className.search("GridView") != -1)
                        && (gridView.Datas.TableauLignes[indLigne].className.search("Header") == -1) )
                {
                    if (gridView.Datas.TableauLignes[indLigne].className.search("RowSel") != -1)
                    {
                        // Update the contents of the hidden field of ids
                        updateSelectedIds(indLigne, gridView);     
                                  
                        nbSelect++;
                    }
                    totalLigne++;
                }
                indLigne++;      
            }
            if (nbSelect == totalLigne && totalLigne > 1)
            {   // All the lines are selected : set general checkBox state to checked
            
                if (gridView.Datas.TableauLignes.length > 0)
                {
                    gridView.Datas.CheckAll = 1;
                    var checkBoxAll = getCheckBoxAll(gridView.Datas.TableauLignes[0].parentNode.parentNode);
                                       
                    if (checkBoxAll)
                    {
                        checkBoxAll.checked = true;
                        var copy = document.getElementById(checkBoxAll.id+'Copy');
                        
                        if (copy )
                        {
                            copy.checked = true;
                        }

                    }
                }
            }
            else
            {   // Not all the lines are selected : set general checkBox state to not checked
                if (gridView.Datas.TableauLignes.length > 0)
                {
                    gridView.Datas.CheckAll = 0;
                    var checkBoxAll = getCheckBoxAll(gridView.Datas.TableauLignes[0].parentNode.parentNode);
                    if (checkBoxAll)
                    {
                        checkBoxAll.checked = false;
                        var copy = document.getElementById(checkBoxAll.id + 'Copy');
                                                
                        if (copy)
                        {
                            copy.checked = false;
                        }
                    }
                }
            }

            // Set state of the buttons in the toolBox
            gridView.Datas.SelectLigne = nbSelect;
            changeToolBoxState(gridView);
            return true;
        }
    }

    function getCheckBoxAll(gridView) {
        return document.getElementById('CheckBoxAll' + gridView.id);
    }

    /****************************************************************/
    /*       Function to manage the ids of the Selected lines       */
    /****************************************************************/
    // ---------------------------------------------------------------------------------------------
    // Name : updateSelectedIds
    // Function that save the ids of the selected lines of the gridView to a hidden field
    // Param firstLine : the index of the first line (TD) of the GridView, expected the Header
    // Param gridView.Datas.TableauLignes : global table of all the lines of the gridView
    // Author : Philippe                                     
     // ---------------------------------------------------------------------------------------------
    function updateSelectedIds(firstLine, gridView){
        var id = GetLigneId(gridView.Datas.TableauLignes[firstLine]);
        var input;
        if (id) 
        {
            input = document.getElementById(gridView.id+'_SelectedIds');
            if (input)
            {
                if (!input.value)
                    input.value = id;
                else if (input.value.length == 0)
                    input.value = id;
                else
                    input.value = input.value+','+id;
            }
        }
            
        var index = GetLigneIndex(gridView.Datas.TableauLignes[firstLine]);
        if (index) 
        {
            input = document.getElementById(gridView.id+'_SelectedIndexes');
            if (input)
            {
                if (!input.value)
                    input.value = index;
                else if (input.value.length == 0)
                    input.value = index;
                else
                    input.value = input.value+','+index;
            }
        }
    }

    // Get the id associated to a ligne (TR dom element)
    function GetLigneId(ligne) {
        var listeInputLigne = ligne.getElementsByTagName('INPUT');
        for (iListeInput = 0; iListeInput < listeInputLigne.length; iListeInput++) {
            if (listeInputLigne[iListeInput].name.search("IdForMultipleSelection") != -1) {   
                // Get the hidden field element
                return listeInputLigne[iListeInput].value;
            }
        }
        return null;
    }

    // Get the index associated to a ligne (TR dom element)
    function GetLigneIndex(ligne) {
        var listeInputLigne = ligne.getElementsByTagName('INPUT');
        for (iListeInput = 0; iListeInput < listeInputLigne.length; iListeInput++) {
            if (listeInputLigne[iListeInput].name.search("IndexForMultipleSelection") != -1) {   
                // Get the hidden field element
                return listeInputLigne[iListeInput].value;
            }
        }
        return null;
    }
    
    function getIndexForId( gridView, id ) {
        if ( ! gridView ) {
            gridView = lastGridView;
        }
        var allLines = gridView.Datas.TableauLignes;

        for( idx = 0; idx < allLines.length; idx++ ) {
            var listInputLigne = allLines[idx].getElementsByTagName( 'INPUT' );
            for( idx2 = 0; idx2 < listInputLigne.length; idx2++ ) {
                var input = listInputLigne[idx2];
                if (input.name.search("IdForMultipleSelection") != -1) {  
                    if ( input.value === id ) {
                    
                        return idx;
                    }
                }
            }
        }

        return  null;
    }

    // ---------------------------------------------------------------------------------------------
    // Name : resetSelectedIds
    // Function that reset to null the value of the hidden field for the ids of the selected lines
    // Param gridView : the gridView
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function resetSelectedIds(gridView) {
        if (!gridView) return;
        var input = document.getElementById(gridView.id+'_SelectedIds');
        if (input)
            input.value = '';
        input = document.getElementById(gridView.id+'_SelectedIndexes');
        if (input)
            input.value = '';
    }

    /****************************************************************/
    /*               Functions of the keyboard event                */
    /****************************************************************/
    // ---------------------------------------------------------------------------------------------
    // Name : ctrlKeyDown
    // Function that manage the event cause by a key down
    // Param e : event representing the key
    // Result : return true
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function ctrlKeyDown(e) {
        if (!e)
            e = event;
        switch(e.keyCode) {
            case 17: ctrlPress = 1; break;
            case 16: shiftPress = 1; break;
        }
        return true;
    }

    // ---------------------------------------------------------------------------------------------
    // Name : ctrlKeyUp
    // Function that manage the event cause by a key up, testing the value of the key
    // Param e : event representing the key
    // Result : return true
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function ctrlKeyUp(e) {
        if (!e)
            e = event;
            
        switch(e.keyCode) {
            case 17:
                ctrlPress = 0; 
                if ( lastGridView.Datas.AllowMultiple && selectInProgress == true ) { 
                    notifyServerOfSelect( lastGridView );
                }
                break;    
            case 16:
                shiftPress = 0; 
                if ( lastGridView.Datas.AllowMultiple && selectInProgress == true ) { 
                    notifyServerOfSelect( lastGridView ); 
                }
                break;
            case 40:// Key Down pressed
                    // Select the line below the current line
                    // check keyboard events are allowed
                    
                    var gridView = lastGridView;
                    
                    if ( gridView == null || ! gridView.Datas.LastSelectedIndex ) {
                        return;
                    }

                    if ( gridView.Datas.SelectLigne > 0 ) {
                        // select line below
                        // current index = current line position
                        if ( currentIndex === -1 ) {
                            // starting at last selected
                            currentIndex = parseInt(gridView.Datas.LastSelectedIndex ) + gridView.Datas.FirstLine;  
                        }
                        
                        var nextIndex = currentIndex + 1;

                        if ( nextIndex < gridView.Datas.TableauLignes.length) {
                            // can descend
                            
                            var nl = gridView.Datas.TableauLignes[nextIndex];
                            var cl = gridView.Datas.TableauLignes[currentIndex];
                            
                            if ( isLineSelected( nl ) === false ) {
                                
                                if (  lastGridView.Datas.AllowMultiple === false || e.shiftKey === false ) {
                                    deselectAllLines( gridView );
                                }
                                selectLine( nl );
                                currentId = GetLigneId(nl );
                                currentIndex = nextIndex;
                            }
                            else {
                                deselectLine( cl );
                                currentId = GetLigneId(nl );
                                currentIndex = nextIndex;
                            }
                            
                            testCheckAll(gridView);
                            
                            if ( selectInProgress === false ) {
                                notifyServerOfSelect( gridView );
                            }
                        }
                    }

                    break;
            case 38:// Key Up pressed
                    // Select the line above the current line
                    // check keyboard events are allowed  
                    var gridView = lastGridView;
                    
                    if ( gridView == null || ! gridView.Datas.LastSelectedIndex ) {
                        return;
                    }
                    
                    if ( gridView.Datas.SelectLigne > 0 ) {
                        // select line above
                        // current index = current line position
                        if ( currentIndex === -1 ) {
                            // starting at last selected
                            currentIndex = parseInt(gridView.Datas.LastSelectedIndex ) + gridView.Datas.FirstLine;  
                        }
                        
                        var nextIndex = currentIndex - 1;

                        if ( nextIndex >= gridView.Datas.FirstLine) {
                            // can descend
                            
                            var nl = gridView.Datas.TableauLignes[nextIndex];
                            var cl = gridView.Datas.TableauLignes[currentIndex];
                            
                            if ( isLineSelected( nl ) === false ) {
                                if (  lastGridView.Datas.AllowMultiple === false || e.shiftKey === false ) {
                                    deselectAllLines( gridView );
                                }
                                selectLine( nl );
                                currentId = GetLigneId(nl );
                                currentIndex = nextIndex;
                            }
                            else {
                                deselectLine( cl );
                                currentId = GetLigneId(nl );
                                currentIndex = nextIndex;
                            }
                            
                            testCheckAll(gridView);
                            
                            if ( selectInProgress === false ) {
                                notifyServerOfSelect( gridView );
                            }
                        }
                    }
                    break;
// With this code, the return pressed on confirmation window for a delete redirect to the element instead
//             case 13: // Key Enter pressed
//                      // Execute the first action button         
//                    // check keyboard events are allowed  
//                    var gridView = lastGridView;
//                    if (gridView == null) return;
//                    //InitGridView(gridView);
//                    if ((gridView.Datas.LastSelectedIndex <0) && (gridView.allowKeyboard!=null))
//                        return true;
//                        
//                    if (gridView.Datas.LastSelectedIndex >= 0 )
//                    {
//                        //var ligne = gridView.Datas.TableauLignesgridView.Datas.LastSelectedId;
//                        var lineIdx = parseInt( gridView.Datas.LastSelectedIndex ) + gridView.Datas.FirstLine;
//                        var ligne = gridView.Datas.TableauLignes[ lineIdx ];
//                        var lignesTD = ligne.getElementsByTagName('TD');
//                        var ligneBouton = null;
//                        for (i = 0; i < lignesTD.length; i++)
//                        {
//                            if (lignesTD[i].className == 'Button')
//                            {
//                                ligneBouton = lignesTD[i];
//                                break;
//                            }
//                        }
//                        
//                        if (ligneBouton != null)
//                        {
//                            ligneA = ligneBouton.getElementsByTagName('A');
//                            if (ligneA.length != 0)
//                            {
//                                document.location.href = ligneA[0].href;
//                                return false;
//                            }
//                            
//                            ligneInput = ligneBouton.getElementsByTagName('Input');
//                            if (ligneInput.length != 0)
//                            {
//                                __doPostBack(ligneInput[0].name, '');
//                            }
//                        }                
//                    }
//                    break;
        }
        return true;
    }

    /****************************************************************/
    /*               Functions of the mouse event                   */
    /****************************************************************/
    // ---------------------------------------------------------------------------------------------
    // Name : doubleClick
    // Function that manage the mouse double-click, calling the first action button of the line
    // Param e : event representing the mouse click
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function doubleClick(e)
    {
        if ( notifyTimer ) {
            clearTimeout( notifyTimer );
            notifyTimer = null;
            selectInProgress = false;
        }
        
        var ligne = getLigne(e);    
        var gridView = ligne.parentNode.parentNode;
        if (!gridView) return;
        
        lignesTd = ligne.getElementsByTagName('TD');
        // If the line is empty
        if (lignesTd.length == 0) return;
        var indexTd;
        for (indexTd = 0; indexTd < lignesTd.length; indexTd++)
        {
            if (lignesTd[indexTd].className.search('Button') != -1)
            {     
                // Test the type of the buttons   
                ligneA = lignesTd[indexTd].getElementsByTagName('A');
                if (ligneA.length != 0)
                {
                    ViewButton_Click(gridView.id, indexTd);
                    indexTd = lignesTd.length;
                }
                else
                {
                    ligneInput = lignesTd[indexTd].getElementsByTagName('INPUT');                
                    for (indexInput = 0; indexInput < ligneInput.length; indexInput++)
                    {
                        if (ligneInput[indexInput].type != 'hidden')
                        {
                            var allowMultiple = ligneInput[indexInput].getAttribute('AllowMultiple');
                            if ('true' == allowMultiple)
                            {
                                MultipleButton_Click(gridView.id, indexTd);
                                indexTd = lignesTd.length;
                                break;
                            }
                            else
                            {
                                SimpleButton_Click(gridView.id, indexTd);
                                indexTd = lignesTd.length;
                                break;
                            }
                        }
                    }
                }                 
            } 
        }
        return true; 
    }

    // ---------------------------------------------------------------------------------------------
    // Name : checkAllClick
    // Click on the general checkBox that allow to select or deselect all the lines of the gridView
    // Param checkBox : general checkBox using to select or deselect all lines
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function checkAllClick(checkBox) 
    {
        if (checkBox == null)
            return false;

        var gridViewId = checkBox.id.replace('CheckBoxAll', '').replace('Copy','');
        var gridView = document.getElementById(gridViewId);
        if (!gridView) return;
        //TOM InitGridView(gridView);
        if (checkBox.id.indexOf('Copy')!=-1)
        {
            var originalCheckBox = document.getElementById(checkBox.id.replace('Copy',''));
            originalCheckBox.checked = checkBox.checked;
        }
        // Reset the hidden field that contains the ids of the selected lines
        resetSelectedIds(gridView);
        
        if (checkBox.checked === false)
        {   
            var allLines = gridView.Datas.TableauLignes;
            var line = null;
            for ( idx = 1; idx < allLines.length; idx++ ) {
                line = allLines[idx];
                
                if ( isLineSelected( line ) == true && line.className.search("Grouping") == -1 ) {
                    deselectLine( line );
                    
                }
                
            }    
            
            //checkBox.checked = true;  
            gridView.Datas.SelectLigne = 0; //i;
            gridView.Datas.CheckAll = 0; //1;
        }
        else
        {  
            var allLines = gridView.Datas.TableauLignes;
            for ( idx = 1; idx < allLines.length; idx++ ){
                selectLine( allLines[idx] );
                updateSelectedIds( idx, gridView );
            }

            //checkBox.checked = true;
        
            gridView.Datas.SelectLigne = 1; //0;
            gridView.Datas.CheckAll = 1;
        }
        changeToolBoxState(gridView);
        
        notifyServerOfSelect( gridView );
        
        return true;
    }


//    // ---------------------------------------------------------------------------------------------
//    // Name : stopSelect
//    // Function that disable the selection of the text with shift or control keys
//    // Result : return true if selection able, false if not
//    // Author : Philippe                                     
//    // ---------------------------------------------------------------------------------------------
//    function stopSelect()
//    {
//        if ( (shiftPress == 1) || (ctrlPress == 1) )
//        {
//            return false;
//        }
//        else 
//        {
//            return true;
//        }
//    }

    // ---------------------------------------------------------------------------------------------
    // Name : checkLineState
    // Function that change the checkBox state of the line to checked or not
    // Param e : event representing the mouse click on the gridView
    // Result : return true
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function checkLineState(e) {

        checkClic = 1;
        
        // TOM row state set in selectLine event which follows
        
        return true;
    }


    /****************************************************************/
    /*                     Contextual menu                          */
    /****************************************************************/

    // ---------------------------------------------------------------------------------------------
    // Name : initContextualMenuCreate
    // Function that add the contextual menu in the gridView
    // Param gridView : the gridView component
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function initContextualMenuCreate(gridView)
    {
        if (!gridView) return;
        var menuContextuel = document.getElementById("menuContext");
        if (menuContextuel == null)
        {
            var newBaliseDiv = document.createElement('DIV');
            newBaliseDiv.innerHTML += "<div>";
            newBaliseDiv.id = "menuContext";
            newBaliseDiv.className = "skinMenu";
            newBaliseDiv.style.display = 'none';
            newBaliseDiv.onmouseover = contextualMenuOver;
            newBaliseDiv.onmouseout = contextualMenuOut;
            newBaliseDiv.onclick = contextualMenuClick;
            //gridView.appendChild(newBaliseDiv);
            document.body.appendChild(newBaliseDiv);    
            menuContextuel = document.getElementById("menuContext");
        }
        // Set the new functions associated to the right mouse button
        var table = document.getElementById(gridView.id);
        table.oncontextmenu = stopClicDroit;
        menuContextuel.oncontextmenu = stopClicDroit;
        window.document.onclick = hideContextualMenu;
        window.document.onmousedown = hideDefaultContextualMenu;   
    }

    // ---------------------------------------------------------------------------------------------
    // Name : createContextualMenuClick
    // Function that manage the right click of the mouse and call the contextual menu
    // Param e : event representing the mouse click
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function createContextualMenuClick(e)
    {
        if (!e)
            e = event;
            
        var ligne = getLigne(e);
        if (ligne == null) return;
        var gridView = ligne.parentNode.parentNode;
        if (!gridView) return;
        
        //TOM InitGridView(gridView);
        
        listeTdLignes = ligne.getElementsByTagName('TD');
        // Test if there are button action
        var haveAction = false;
        for (x = 0; x < listeTdLignes.length; x++)
        {
            if (listeTdLignes[x].className == 'Button')
            {
                haveAction = true;
                break;
            }
        }

        if (haveAction == true)
        {        
            // Right click for the contextual menu
            if (e.button == 2)
            {
                gridView.Datas.MenuContext = document.getElementById("menuContext");
                if (gridView.Datas.MenuContext == null)
                {
                    return;
                }
                gridView.Datas.MenuContext.style.display = '';     
                
                var parentElt;
                parentElt = ligne;
                
                if ( (parentElt.tagName == 'TR') && (parentElt.getElementsByTagName('TH').length == 0) )
                {            
                    var ind = 0;
                    var nbl = 0;
                    while (ind < gridView.Datas.TableauLignes.length)
                    {
                        if (gridView.Datas.TableauLignes[ind].className == 'RowSel')
                        {
                            nbl++;
                        }
                        ind++;
                    }
                    if ( (nbl < 2) || (parentElt.className == 'RowOver') )
                    {   // If the current line is not selected, deselect all other selected lines 
                        deselectAllLines(gridView);
                    }
                    //parentElt.className = 'RowSel';
                    //TOMgridView.Datas.LastLineSelected = parentElt;
                    selectLine( parentElt );
                    saveSelectedLine( gridView, GetLigneId( parentElt ), GetLigneIndex( parentElt ) );
                    
                    if (initContextualMenu(parentElt) == 0)
                    {
                        // Display the contextual menu
                        showContextualMenu(e);
                        
                        // Adapt the contents of the contextual menu with one or several lines selected
                        if (nbl > 1)
                        {  // There are more than one line selected
                            var listeDivMenu = gridView.Datas.MenuContext.getElementsByTagName("DIV");
                            for (var i = 0; i < listeDivMenu.length; i++)
                            {
                                // If the action is not able for multiple selection, the corresponding element is disabled
                                var allowMultiple = listeDivMenu[i].getAttribute('AllowMultiple');
                                if ('true' != allowMultiple)
                                    listeDivMenu[i].className = "menuItemsDisabled";
                            }
                        }
                    }
                }
                testCheckAll(gridView);    
            }
        }
    }

    // ---------------------------------------------------------------------------------------------
    // Name : initContextualMenu
    // Function that initialize dynamicaly the contents of the contextual menu
    // Param ligneEnCours : line of the table on which the user has clicked
    // Result : return 0 if contextual menu was displayed, else 1
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function initContextualMenu(ligneEnCours)
    {
        // Reset the contextual menu if it has already been called
        reInitContextualMenu();
        
        var lignesTD = ligneEnCours.getElementsByTagName('TD');
        var lignesBouton = new Array();
        var withButton = false;
        for (i = 0; i < lignesTD.length; i++)
        {
            if (lignesTD[i].className == 'Button')
            {
                lignesBouton.push(lignesTD[i]);
                withButton = true;
            }
        }
        // If there are no button action
        if (withButton == false)
        {
            return 1;
        }
        // Create and add all button action of the line 
        var index = 0;
        var listDivIndex = 0;
        while (index < lignesBouton.length)
        {
            ligneA = lignesBouton[index].getElementsByTagName('A');
            if (ligneA.length != 0)
            {
                titre = ligneA[0].getElementsByTagName('IMG')[0].title;
                url = ligneA[0].getAttribute('href');
                menuContextObj = document.getElementById('menuContext');
                listeDiv = menuContextObj.getElementsByTagName('DIV');           
                var newBaliseDiv = document.createElement('DIV');
                newBaliseDiv.className = "menuItems";
                newBaliseDiv.setAttribute("url", url);
                newBaliseDiv.innerHTML += titre;
                menuContextObj.insertBefore(newBaliseDiv, listeDiv[listDivIndex]);
                listDivIndex++;
            }
            
            ligneInput = lignesBouton[index].getElementsByTagName('INPUT');
            if (ligneInput.length != 0)
            {
                titre = ligneInput[0].title;            
                menuContextObj = document.getElementById('menuContext');
                listeDiv = menuContextObj.getElementsByTagName('DIV'); 
                var newBaliseDiv = document.createElement('DIV');
                newBaliseDiv.className = "menuItems";
                newBaliseDiv.innerHTML += titre;
                
                var allowMultiple = ligneInput[0].getAttribute('AllowMultiple');
                if ('true' == allowMultiple)
                    newBaliseDiv.setAttribute("AllowMultiple", "true");
                newBaliseDiv.setAttribute("url", "javascript:PushButton('" + ligneInput[0].id + "', '"+ligneInput[0].name+"')");
                menuContextObj.insertBefore(newBaliseDiv, listeDiv[listDivIndex]);
                listDivIndex++;
            }
            
            
            index++;    
        }    
        
        return 0;
    }


    // ---------------------------------------------------------------------------------------------
    // Name : reInitContextualMenu
    // Function that reset the contextual menu by delete the first lines of this menu, that 
    // corresponding to the action button of the gridView
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function reInitContextualMenu()
    {
        // Set the number of div elements to delete in the beginning of the menu
        menuContextObj = document.getElementById("menuContext");
        var numero = 0;
        while (numero < menuContextObj.childNodes.length)
        {
            if (menuContextObj.childNodes[numero].tagName == 'HR')
            {
                break;
            }
            else
            {
                numero++;
            }
        }
        // Suppression of the nodes to reset the contextual menu
        for (z = 0; z < numero - 1; z++)
        {
            var noeud = menuContextObj.firstChild;
            menuContextObj.removeChild(noeud);
        }
    }

    // ---------------------------------------------------------------------------------------------
    // Name : showContextualMenu
    // Function that display the contextual menu
    // Param e : event representing the position of the mouse when right clicking
    // Result : return true
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function showContextualMenu(e)
    {
        var ligne = getLigne(e);
        if (!ligne) return;
        var gridView = ligne.parentNode.parentNode;
        if (!gridView) return;
        
        //TOMInitGridView(gridView);
        
        // Define position of the contextual menu, near the mouse click
        var bordDroit = (ieNavigator)? document.body.clientWidth-event.clientX : window.innerWidth-e.clientX;
        var bordBas = (ieNavigator)? document.body.clientHeight-event.clientY : window.innerHeight-e.clientY;
        var bordHaut = (ieNavigator)? event.clientY : e.clientY;

        if (bordDroit < gridView.Datas.MenuContext.offsetWidth)
        {
            gridView.Datas.MenuContext.style.left = (ieNavigator)? document.body.scrollLeft+event.clientX-gridView.Datas.MenuContext.offsetWidth : window.pageXOffset+e.clientX-gridView.Datas.MenuContext.offsetWidth;
            if (ffNavigator)
            {
                gridView.Datas.MenuContext.style.left = window.pageXOffset+e.clientX-gridView.Datas.MenuContext.offsetWidth + "px";
            }
        }
        else
        {
            gridView.Datas.MenuContext.style.left = (ieNavigator)? document.body.scrollLeft+event.clientX : window.pageXOffset+e.clientX;
            if (ffNavigator)
            {
                gridView.Datas.MenuContext.style.left = window.pageXOffset+e.clientX + "px";
            }
        }
        if (bordBas < gridView.Datas.MenuContext.offsetHeight)
        {
            if (bordHaut < gridView.Datas.MenuContext.offsetHeight) 
            {
                gridView.Datas.MenuContext.style.top = (ieNavigator)? document.body.scrollTop+event.clientY : window.pageYOffset+e.clientY;
                if (ffNavigator)
                {
                    gridView.Datas.MenuContext.style.top = window.pageYOffset+e.clientY + "px";
                }            
            }
            else
            {
                gridView.Datas.MenuContext.style.top = (ieNavigator)? document.body.scrollTop+event.clientY-gridView.Datas.MenuContext.offsetHeight : window.pageYOffset+e.clientY-gridView.Datas.MenuContext.offsetHeight;
                if (ffNavigator)
                {
                    gridView.Datas.MenuContext.style.top = window.pageYOffset+e.clientY-gridView.Datas.MenuContext.offsetHeight + "px";
                }
            }
        }
        else
        {
            gridView.Datas.MenuContext.style.top = (ieNavigator)? document.body.scrollTop+event.clientY : window.pageYOffset+e.clientY;
            if (ffNavigator)
            {
                gridView.Datas.MenuContext.style.top = window.pageYOffset+e.clientY + "px";
            }
        }
        gridView.Datas.MenuContext.style.visibility = "visible";
    }

    // ---------------------------------------------------------------------------------------------
    // Name : hideDefaultContextualMenu
    // Function that able or disable display of the contextual menu
    // Param e : event representing the mouse right click
    // Result : return true when finished
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function hideDefaultContextualMenu(e)
    {
        var ligne = getLigne(e);
        if (!ligne) return;
        var gridView = ligne.parentNode.parentNode;
        if (!gridView) return;
        //TOM InitGridView(gridView);
        
        
        if (!e && window.event)
            e = window.event;
        if ( !e || e.button == 2)
        {
            if (gridView.Datas.MenuContext != null)
            {
                var ligneCourante;

                if (ieNavigator)
                {
                    ligneCourante = e.srcElement;
                }
                else
                {
                    ligneCourante = e.target;
                }            
                
                while (ligneCourante.parentNode != null)
                {
                    if ( (ligneCourante.parentNode.tagName == 'TR') 
                            && (ligneCourante.parentNode.className.search("AlwaysVisible") == -1) )
                    {
                        gridView.Datas.MenuContext.style.visibility = "visible";
                        break;
                    }
                    ligneCourante = ligneCourante.parentNode;
                }
                if (ligneCourante.parentNode == null)
                {
                    if (e.button != 2)
                        gridView.Datas.MenuContext.style.visibility = "hidden";
                }
            }
        }
    }


    // ---------------------------------------------------------------------------------------------
    // Name : hideContextualMenu
    // Function that hide the contextual menu
    // Param e : event representing the position of the mouse when right clicking
    // Result : return true
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function hideContextualMenu(e)
    {
        if (!lastGridView) return;
        if (!lastGridView.Datas) return;
        if (lastGridView.Datas.MenuContext != null)
        {
            if (!e && window.event)
                e = window.event;
            if ( !e || e.button != 2)
            {
                lastGridView.Datas.MenuContext.style.visibility = "hidden";
            }
        }
    }

    // ---------------------------------------------------------------------------------------------
    // Name : contextualMenuOver
    // Function that manage the behaviour of the contextual menu when the mouse is over
    // Param e : event representing the position of the mouse when right clicking
    // Result : return true
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function contextualMenuOver(e)
    {
        var firingObj = (ieNavigator)? event.srcElement : e.target;
        if (firingObj.className == "menuItems")
        {
            firingObj.style.backgroundColor = "highlight";
            firingObj.style.color = "white";
        }
    }

    // ---------------------------------------------------------------------------------------------
    // Name : contextualMenuOut
    // Function that manage the behaviour of the contextual menu when the mouse is out
    // Param e : event representing the position of the mouse when right clicking
    // Result : return true
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function contextualMenuOut(e)
    {
        var firingObj = (ieNavigator)? event.srcElement : e.target;
        if (firingObj.className == "menuItems")
        {
            firingObj.style.backgroundColor = "";
            firingObj.style.color = "black";
            window.status = '';
        }
    }

    // ---------------------------------------------------------------------------------------------
    // Name : contextualMenuOut
    // Function that manage the behaviour of the contextual menu when the user click on an item
    // Param e : event representing the position of the mouse when right clicking
    // Result : return true
    // Author : Philippe                                     
    // ---------------------------------------------------------------------------------------------
    function contextualMenuClick(e)
    {
        var firingObj = (ieNavigator)? event.srcElement : e.target;
        var evenement;
        if (ieNavigator) 
            evenement = event;
        else
            evenement = e;
        if ( (evenement.button == 2) || (evenement.button == 0) )
        {
            if (firingObj.className == "menuItems")
            {
                if (firingObj.getAttribute("target"))
                {
                    window.open(firingObj.getAttribute("url"), firingObj.getAttribute("target"));
                }
                else
                {
                    window.location = firingObj.getAttribute("url");
                }
            }
        }
    }

    // ---------------------------------------------------------------------------------------------
    // Name : displayGroupRows
    // Function that manage the behaviour of the gridview for grouping
    // Cells visible in table
    // Param e : Table Id, GroupId
    // Author : Ronan Salmon                                     
    // ---------------------------------------------------------------------------------------------
    function displayGroupRows(tableId, groupId, show, imagecnt)
    {
        tbl = document.getElementById(tableId);
        var len = tbl.rows.length;
        for(i=0 ; i< len; i++)
        {
            if (tbl.rows[i].groupid == 'grouprow'+groupId)
                tbl.rows[i].style.display = (show)?'':'none';
        }
        if (imagecnt.id.indexOf('btnShow')>=0)
        {
            imagecnt.style.display = 'none';
            document.getElementById(imagecnt.id.replace('btnShow', 'btnHide')).style.display = '';
        }
        else
        {
            imagecnt.style.display = 'none';
            document.getElementById(imagecnt.id.replace('btnHide', 'btnShow')).style.display = '';
        }
    }


/**************************************************************/
/*                                                            */
/*     MasterPage                                             */
/*                                                            */
/**************************************************************/

    /*
    ** Aborts the current UpdatePanel request currently in progress pn the master page
    **
    */
    function AbortRequest()
    {
        var requestManager = Sys.WebForms.PageRequestManager.getInstance();
        
        if ( requestManager.get_isInAsyncPostBack() )
        {
            requestManager.abortPostBack();
        }
    }

    
    /* IE6 Resize */
    function resizeContent()
    {
        if( !isIE6 ) return;

        var scrollableObject = document.getElementById('DivContent');
        resizeControlWithWindow(scrollableObject);
        
        var alwaysVisibleDiv = document.getElementById('AlwaysVisible');
        if (alwaysVisibleDiv)
        {
            var wie = scrollableObject.currentStyle.width.replace(/px/,'');
            if (wie != "auto") {
                alwaysVisibleDiv.style.width = (wie - 17) + 'px';
            }
        }
    }

    function resizeControlWithWindow(contentDiv)
    {
        if (!contentDiv)
            return;
            
        var bodyHeight = 0;
        var bodyWidth = 0;
        
        var marginTop = contentDiv.currentStyle.top.replace(/px/,'');
        var marginBottom = contentDiv.currentStyle.bottom.replace(/px/,'');
        var marginRight = contentDiv.currentStyle.right.replace(/px/,'');
        var marginLeft = contentDiv.currentStyle.left.replace(/px/,'');

        bodyHeight = document.body.clientHeight;
        bodyWidth = document.body.clientWidth;
        
        /* Set body size corresponding to the body size */
        if( bodyWidth < 600 ) bodyWidth = 600;
        if( bodyWidth < 450 ) bodyWidth = 450;

        /* Set scrollable object size */
        if (marginTop != "auto" && marginBottom != "auto") {
            var hIE = bodyHeight - marginTop - marginBottom - 4;
            contentDiv.style.height = hIE + 'px';
        }
        if (marginLeft != "auto" && marginRight != "auto") {
            var wIE = bodyWidth - marginLeft - marginRight - 4;
            contentDiv.style.width = wIE + 'px';
        }
    }

    function CopyAlwaysVisibleElement()
    {
        var alwaysVisibleDiv = document.getElementById('AlwaysVisible');
        var height = 0;
        // To desactivate alwaysVisible Top div
        //alwaysVisibleDiv = null;
        
        var clonedElements = new Array();
        if (alwaysVisibleDiv)
        {
            var components = getElementsByClass('AlwaysVisible', document.getElementById('DivContent'));
            var i;
            alwaysVisibleDiv.innerHTML='<div></div>';//'<iframe src="about:blank" scrolling="no"></iframe>';
            for (i=0; i< components.length;i++)
            {
                height=height+components[i].offsetHeight;
                if (components[i].nodeName == 'TR')
                {
                    var originalGrid = components[i].parentNode;
                    if (originalGrid)
                        originalGrid = originalGrid.parentNode;
                    if (originalGrid)
                    {
                        var alreadyIn = false;
                        var j;
                        for (j=0; j < clonedElements.length;j++)
                            if (clonedElements[j] == originalGrid)
                                alreadyIn = true;
                        if (!alreadyIn)
                        {
                            clonedElements[clonedElements.length] = originalGrid;
                            var newGrid = originalGrid.cloneNode(true);
                            reattributeIdsAndNames(newGrid);
                            alwaysVisibleDiv.appendChild(newGrid);
                        }
                    }
                }
                else
                {
                    //if component does not have copy in its name
                    if (components[i].id || components[i].name )
                    {
                        if ( ( components[i].id && components[i].id.indexOf('Copy') != -1) ||
                            ( components[i].name && components[i].name.indexOf('Copy') != -1 ) )
                        {
                            //if ((components[i].id) && (components[i].id.indexOf('Copy') != -1))
                            //    continue;
                            var newElement = components[i].cloneNode(true);
                            // When ids are reattributed, the buttons don't work on toolbox

                            reattributeIdsAndNames(components[i]);

                            alwaysVisibleDiv.appendChild(newElement);
                        }
                        else
                        {
                            // exists already ?
                            var newElement = components[i].cloneNode(true);
                            alwaysVisibleDiv.appendChild(newElement);
                        }
                    }
                    else
                    {
                        var newElement = components[i].cloneNode(true);
                            // When ids are reattributed, the buttons don't work on toolbox

                            reattributeIdsAndNames(components[i]);

                            alwaysVisibleDiv.appendChild(newElement);
                    }
                    
                    /*
                    // Implementation to move node to the always visible div (instead of cloning)
                    if (components[i].parentNode != null)
                    {
                        var div = document.createElement('<div style="height:'+components[i].offsetHeight+'px" id="Position'+i+'" >&nbsp;</div>');
                        components[i].parentNode.insertBefore(div, components[i]);
                        components[i].setAttribute('originalPosition', 'Position'+i);
                        components[i].removeNode(true);
                        
                        alwaysVisibleDiv.appendChild(components[i]);
                    }
                    */
                }
            }
            if (height > 0)
            {
                // If we found at least one element
                alwaysVisibleDiv.style.height = height+'px';
                alwaysVisibleDiv.className = 'Visible';
            }
        }    
    }

    function reattributeIdsAndNames(control)
    {
        if ((control.id) && (control.id.indexOf('Copy') == -1)) 
            control.id = control.id+'Copy';
        if ((control.name) && (control.name.indexOf('Copy') == -1))
            control.name = control.name+'Copy';
        if (control.childNodes)
        {
            var i;
            for (i=0; i <control.childNodes.length;i++)
                reattributeIdsAndNames(control.childNodes[i]);
        }
    }

    function ChangeTarget(button) 
    {
        var old = document.forms[0].target;
        document.forms[0].target = "_blank";
        document.getElementById("MethodToCall").value = button;
        document.forms[0].submit();
        document.getElementById("MethodToCall").value = null;
        document.forms[0].target = old;
        MessageBoxClear();
    }
    

    /***************************************************************/
    /***************************************************************/
    /* Resize splitter for ColumnsMasterPage + ThreePaneMasterPage */
    /***************************************************************/
    /***************************************************************/
    function ResizeSplitter(_splitter, _paneLeft, _paneRight, _contentPlaceToolBox)
    {
        if (_splitter)
        {
            var contentDiv = document.getElementById('DivContent');
            var newHeight = contentDiv.offsetHeight;
            var newWidth = contentDiv.offsetWidth;
            var paneLeft = _splitter.getPaneById(_paneLeft);
            var paneRight = _splitter.getPaneById(_paneRight);
            var heightCPH = 0;
            if (_contentPlaceToolBox)
            {
                var contentPlaceToolBox = document.getElementById(_contentPlaceToolBox);
                if (contentPlaceToolBox)
                {
                    // Old code : is not correct for IE6
                    //var heightCPH = contentPlaceToolBox.offsetHeight;
                    
                    // Display contentPlaceToolBox.childNodes for all browsers
                    
                    for (var i = 0; i < contentPlaceToolBox.childNodes.length; i++) 
                    {
                        if (contentPlaceToolBox.childNodes[i].style) {
                            if (contentPlaceToolBox.childNodes[i].childNodes.length > 0) 
                            {
                                contentPlaceToolBox.childNodes[i].style.display = "";
                                heightCPH += contentPlaceToolBox.childNodes[i].offsetHeight;
                            } 
                            else 
                            {
                                contentPlaceToolBox.childNodes[i].style.display = "none";
                            }                    
                        }
                    }
                }
            }
            newHeight = newHeight - heightCPH - 1;
            paneLeft.set_height(newHeight);
            paneRight.set_height(newHeight);
            newWidth = newWidth - paneLeft.get_width() - 6;
            paneRight.set_width(newWidth);
        }
            
    }


    /************************************************************************************/
    // Telerik Control RadWindow : Use in HTMLUtils for RadConfirm 
    // the following code use radconfirm to mimic the blocking of the execution thread.
    // The approach has the following limitations:
    // 1. It works inly for elements that have *click* method, e.g. links and buttons
    // 2. It cannot be used in if(!confirm) checks
    /**************************************************************************************/
    window.blockConfirm = function(text, mozEvent, oWidth, oHeight, callerObj, oTitle, closeWindow) 
    { 
        var ev = mozEvent ? mozEvent : window.event; //Moz support requires passing the event argument manually 
        //Cancel the event 
        ev.cancelBubble = true; 
        ev.returnValue = false;
        if (ev.stopPropagation) 
            ev.stopPropagation();
        if (ev.preventDefault) 
            ev.preventDefault(); 
           
        //Determine who is the caller 
        var callerObj = ev.srcElement ? ev.srcElement : ev.target; 

        //Call the original radconfirm and pass it all necessary parameters 
        if (callerObj) 
        { 
            //Show the confirm, then when it is closing, if returned value was true, automatically call the caller's click method again. 
            var callBackFn = function (arg) 
            { 
                if (arg) 
                { 
                    callerObj["onclick"] = ""; 
                    if (callerObj.click)
                    { 
                        callerObj.click(); //Works fine every time in IE, but does not work for links in Moz 
                        // Close current window
                        if (closeWindow)
                            window.close();
                    }
                    else if (callerObj.tagName == "A") //We assume it is a link button! 
                    { 
                        try 
                        { 
                            eval(callerObj.href) 
                        } 
                        catch(e){} 
                    } 
                } 
            } 

            radconfirm(text, callBackFn, oWidth, oHeight, callerObj, oTitle); 
        } 
        return false; 
    } 


    /*
    ** Code for Ajax tooltip
    **
    ** Usage : Client script should call AjaxTooltip.SetContent( s ); to initialise the tooltip with the required
    **         html snippet then call AjaxTooltip.ShowAt( mousePos.X, mousePos.Y ); to display it at a specific
    **         screen position
    */
    var AjaxTooltip = function()
    {
        var timerHide = null;
        var timerShow = null;
        var tooltip   = null;
        var isVisible = false;
        var isHolding = false;
        var nextContent = "";
        
        return {
            /*
            ** Initilaise object using provided ID of undelying HTML element
            */
            Init : function( id ) {
            
                tooltip = $get( id );
                
                if ( ! tooltip ) {
                    alert( "Error: Tooltip with id " + id + " not found " );
                }
                
                tooltip.onselectstart  = function() { 
                    return false; 
                };
                
                tooltip.onmouseover = function() { 
                    HoldTooltipVisible();
                };
                
                tooltip.onmouseout = function() {
                    DropTooltip();
                };
            },
            
            SetAndShow : function ( e, content ) {
                var mousePos = GetPosition(e);
                AjaxTooltip.SetContent( content );
                AjaxTooltip.ShowAt( mousePos.X, mousePos.Y );
            },
            
            /*
            ** Show the tooltip at the given screen position
            */
            ShowAt : function( posX, posY ) { 
            
                SetPosition( posX, posY );

                AjaxTooltip.Show();
            },

            /*
            ** Set the content of the tooltip - we hold it in a variable until we are ready to actually display the text
            */
            SetContent : function ( s ) {
            
                nextContent = s;
            },
            
            /*
            ** Force the tooltip to display for a period of time ( showTime is optional - defaults to 2.8 seconds)
            */
            Show : function ( showTime) {
            
                // Cancel timers - strating a new show/hide cycle
                clearTimeout( timerShow );
                clearTimeout( timerHide );
                
                if ( isVisible === true ) {
                    AjaxTooltip.Hide(0);
                }

                timerShow = setTimeout( function() { ShowFor( showTime ); }, 1000 );
            },
            
            /*
            ** Force the tooltip to hide after a certain delay ( a short delay is used by default)
            */
            Hide : function( delay ) {
            
                // Cancel timers - strating a new show/hide cycle
                clearTimeout( timerShow );
                clearTimeout( timerHide );
                
                if ( isVisible === true ) {
                           
                    if ( delay === 0 ) {
                        HideTooltip();
                    }
                    else  {
                        if ( ! delay ) {
                            delay = 1000;
                        }
                
                        timerHide = setTimeout( HideTooltip, delay );
                    }
                }
            }
        };
        
        /*
        ** Shows the tooltip and sets up a timer to automatically hide it after a certain time
        */
        function ShowFor( displayLength ) {
            
            ShowTooltip();
            
            // Hide after provieded time
            if ( ! displayLength ) {
                displayLength = 2800;
            }
            
            timerHide = setTimeout( HideTooltip, displayLength );
            
        }
        
        /*
        ** Maintain the visibility of the tooltip event though a demand to hide it has been placed
        */
        function HoldTooltipVisible() {
            
            clearTimeout( timerHide );
            isHolding = true;
        }
        
        /*
        ** Exists tooltip 'hold' mode
        */
        function DropTooltip() {
            isHolding = false;
            AjaxTooltip.Hide();
                
        }
        
        /*
        ** Actually hide the tooltip
        */
        function HideTooltip() {
        
            if ( isHolding === false ) {
            
                isVisible = false;
                tooltip.style.visibility = "hidden";
            }
        }
        
        /*
        ** Actually show the tooltip
        */
        function ShowTooltip() {
        
            isVisible = true;
            CopyContentToView();
            tooltip.style.visibility = "visible";
            
        }
        
        /*
        ** Actually write the content to the DOM
        */
        function CopyContentToView() {
        
            if ( tooltip.childNodes.length != 1 ) {  
                    // firefox has extra nodes
                    tooltip.childNodes[1].innerHTML = nextContent;
                }
                else {
                    tooltip.childNodes[0].innerHTML = nextContent;
                }
        }
        
        function GetPosition( e ) {
            var pos = new Object();
            pos.X = 0;
            pos.Y = 0;
            
            var evt = e;
            
	        if (!e) {
	            evt = window.event;
	        }
    	    
	        if (evt.pageX || evt.pageY) {	
    	    
		        pos.X = evt.pageX;
		        pos.Y = evt.pageY;
	        }
	        else if (evt.clientX || evt.clientY) {	
    	    
		        pos.X = evt.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		        pos.Y = evt.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	        }
	        
    	    
	        return pos;
        }
        
        /*
        ** Position the tooltip relative to the mouse position provided by the client
        */
        function SetPosition( posX, posY ) {
            
            // uses a  VERY NAIVE method of reclaculatng xPOs so that its not too near the right side
                
            var halfWidth = document.body.offsetWidth / 2;
                
            if ( posX < halfWidth ) {
               tooltip.style.left = posX + "px";
            }
            else {
                tooltip.style.left = ((posX - halfWidth) / 2 ) + halfWidth + "px";
            }
                
            tooltip.style.top  = posY + "px";
        }
            
    }();  // END OF NAMSPACE OBJECT SCOPE


/********************************************************
* Method to get extension of string
*********************************************************/    
function GetFileExtension(value) 
{ 
    if( value.length == 0 ) 
        return ""; 
    var dot = value.lastIndexOf("."); 
    if( dot == -1 ) 
        return ""; 
    var extension = value.substr(dot,value.length); 
    return extension.toLowerCase(); 
} 
 
 
/**************************************************************/
/*                                                            */
/*     TreeDropDownList                                       */
/*                                                            */
/**************************************************************/

    /********************************************************
    * Method to click a node
    *********************************************************/
    function NodeClicking(sender, args, comboBox)
    {
        var node = args.get_node()

        var itemId = node.get_value();
        
        // Display an empty string for the empty node and not the text displayed in the tree view
        if ( itemId == sender.get_attributes().getAttribute("_EmptyNodeId" ) )
            comboBox.set_text("");
        else
            comboBox.set_text(node.get_text());

        comboBox.trackChanges();
        /* Probleme with this code : double click in RadcombobBox, treeview not known in radcombobox
        due to set_text() method */
        /*comboBox.get_items().getItem(0).set_text(node.get_text());*/
        comboBox.get_items().getItem(0).set_value(node.get_value());
        comboBox.commitChanges();

        comboBox.hideDropDown();
    }

    function StopPropagation(e)
    {
        if(!e)
        {
            e = window.event;
        }
        e.cancelBubble = true;
    }

    /********************************************************
    * Method to open TreeView in RadComboBox
    *********************************************************/
    function OnClientDropDownOpenedHandler(sender, eventArgs)
    {
        var tree = sender.get_items().getItem(0).findControl("RadTreeView1");
        var selectedNode = tree.get_selectedNode();
        if (selectedNode)
        {
            selectedNode.scrollIntoView();
        }
    }



 
/**************************************************************/
/*                                                            */
/*                      RadEditor                             */
/*                                                            */
/**************************************************************/
/**************************************************************/
/*    Initialization of RadWindow for Editor Full Screen      */
/* Open a RadWindow navigate URl                              */
/* /WebSite/WebControls/Editors/EditorFullScreen.aspx         */
/**************************************************************/
var editorContent = null;
var editorCurrent = null; // Current editor for full screen

var editorWindow = null;
var editorDivCurrent = null;
var editorInputCurrent = null;
var editorTextAreaCurrent = null;

// Fill the content of the editor with the html saved in Full screen window
function SetEditorContent(content){ 
    if (editorCurrent)
        editorCurrent.set_html(content);
    else if (editorDivCurrent)
    {
        editorDivCurrent.innerHTML = content;
        editorInputCurrent.value = content;
    }
    else if (editorTextAreaCurrent)
    {
        editorTextAreaCurrent.value = content;
    }
}

function GetEditorContent()
{
    return editorContent;
}

// Function to render RadEditor
// Div encapsule RadEditor display : block
function RenderVisibleEditor(divEditorId, editorId, divTextId)
{
    var divEditor = document.getElementById(divEditorId);
    var divText = document.getElementById(divTextId);
    
    divText.style.display = "block"; 
    var editor = $find(editorId); //get a reference to RadEditor's client object
    editor.set_visible(true);
    editor.set_html(divEditor.innerHTML);
    
    divEditor.style.display = "none"; 
}

function ShowPopupEditor(divEditorId, inputEditorId, textAreaId, url)
{
    if (textAreaId)
    {
        editorTextAreaCurrent = document.getElementById(textAreaId);
        editorContent = editorTextAreaCurrent.value;
        editorDivCurrent = null;
        editorInputCurrent = null;
    }
    else
    {
        editorDivCurrent = document.getElementById(divEditorId);
        editorInputCurrent = document.getElementById(inputEditorId);
        editorContent = editorDivCurrent.innerHTML
        editorTextAreaCurrent = null;
    }
    if (editorWindow)
    {
        if (editorWindow.get_navigateUrl() != url)
        {
            editorWindow.setUrl (url);
        }
        editorWindow.show();
        var contentWindow = editorWindow.get_contentFrame().contentWindow;
        if (contentWindow && contentWindow.setContent)
        {
            contentWindow.setContent(editorContent);
        }
    }
    else
    {
        editorWindow = openRadWindow(url,null);
    }
}


/**************************************************************
***************************************************************
*** Show Div in javascript switch RadioButton Item selected ***
***************************************************************
**************************************************************/
function ShowControlRadioButtonSelected(idControl, idDiv) 
{
    // Radio Button
    var radioButtons = document.getElementById(idControl);
    var criteria = document.getElementById(idDiv);
    criteria.style.display = radioButtons.checked ? "block" : "none";
}  

        
function CheckEditorDisableArea(editor, args)
{
    //var doc = editor.get_document();
    //var body = doc.body;
    //body.setAttribute("editable", "false");
    editor.attachEventHandler ("onclick", EnableDisableEditing);
    editor.attachEventHandler ("onkeydown", EnableDisableEditing);
    editor.attachEventHandler ("onkeyup", EnableDisableEditing);


        function EnableDisableEditing(e)
        {
            var editable = true;   
            var element = editor.getSelection().getParentElement();   
            try 
            {
                while(element != null)    
                {   
                    if (element.getAttribute("editable") == "true")   
                    {   
                        editable = true;   
                        break;   
                    }   
                    if (element.getAttribute("editable") == "false")   
                    {   
                        editable = false;   
                        break;   
                    }   
                    element = element.parentNode;   
                }   
            } catch (dontCare)
            {
                // If we do not know the element is not editable, let's consider it is editable
            }
                 
            if (editable == false)   
            {   
                editor.set_editable(false);   
                   
                if (!document.all)   
                {   
                    e.preventDefault();   
                    e.preventBubble();   
                    e.stopPropagation();   
                }   
                else  
                {   
                    e.returnValue = false;   
                    e.cancelBubble = true;   
                }   
                return false;          
            }   
            else  
            {   
                editor.set_editable(true);   
            }               
        }

}


/**************************************************************/
/*                                                            */
/*                      RadWindow                             */
/*                                                            */
/**************************************************************/

// ----------------------------------------------------------
// Open a simple rad window with a name
// ----------------------------------------------------------
function openRadWindow(path, name, width, height, reload) 
{
    // Get width and height calculated with browser
    if (width == null)
        width = getWidthForRadWindow();        
    if (height == null)
        height = getHeightForRadWindow();    
    
    var oWindow = window.radopen(path, name);
    oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Maximize + Telerik.Web.UI.WindowBehaviors.Resize);
    oWindow.set_modal(true);
    oWindow.set_visibleStatusbar(false);    
    oWindow.setSize(width, height);
    oWindow.center();
    
    // Forced to reload RadWindow because in RadWindowManager 
    // ReloadOnShow = false for the performance ...
    if (reload)
        oWindow._reloadOnShow = reload;
    return oWindow;
}

// ----------------------------------------------------------
// Open radwindows with AutoComplete Control
// ----------------------------------------------------------
function openRadWindowAutoComplete(path, name, width, height) 
{
    var oWindow;
    var oBrowserWnd = getRadWindow();
    if (!oBrowserWnd) {
        oWindow = window.radopen(path, name);
    } else {
        oWindow = oBrowserWnd.BrowserWindow.radopen(path, null);
        var maxHeight = oBrowserWnd.get_height();
        if (maxHeight < height)
            height = maxHeight;
    }
    
    // Get width and height calculated with browser
    if (width == null)
        width = getWidthForRadWindow();        
    if (height == null)
        height = getHeightForRadWindow();    
    
    oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Maximize + Telerik.Web.UI.WindowBehaviors.Resize);
    oWindow.set_modal(true);
    //DEBUG 4247 - Hide status bar in radwindows
    oWindow.set_visibleStatusbar(false);       
    oWindow.set_visibleStatusbar(false);    
    oWindow.setSize(width, height);
    oWindow.center();
    
    //DEBUG 4361 - Make the window appears before all windows
    window.setTimeout(function() 
    {         
        oWindow.setActive(true);
    },0); 
    return oWindow;
}

// ----------------------------------------------------------
// Open a rad window Simple Behavior (move and close)
// ----------------------------------------------------------
function openNewRadWindowSimpleBehavior(path, width, height) 
{
    var oWindow;
    var oBrowserWnd = getRadWindow();
    if (!oBrowserWnd) {
        oWindow = window.radopen(path, null);
    } else {
        oWindow = oBrowserWnd.BrowserWindow.radopen(path, null);
        height = oBrowserWnd.get_height();
    }    
    
    // Get width and height calculated with browser
    if (width == null)
        width = getWidthForRadWindow();        
    if (height == null)
        height = getHeightForRadWindow();    
    
    oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close);
    oWindow.set_modal(true);
    //DEBUG 4247 - Hide status bar in radwindows
    oWindow.set_visibleStatusbar(false);    
    oWindow.setSize(width, height);
    oWindow.center();
    return oWindow;
}

// ----------------------------------------------------------
// Open a simple rad window for Enumeration Field
// Display Help enumeration
// ----------------------------------------------------------
function openRadWindowEnumeration(path, name) 
{
    var oWindow = window.radopen(path, name);
  
    // Get width and height calculated with browser
    var width = getWidthForRadWindow();        
    var height = getHeightForRadWindow();    
    if (width > 450)
        width = 450;
    if (height > 400)
        height = 400;
    
    oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Resize);
    oWindow.set_modal(false);
    //DEBUG 4247 - Hide status bar in radwindows
    oWindow.set_visibleStatusbar(false);    
    oWindow.setSize(width, height);
    oWindow.center();

    return oWindow;
}

// ----------------------------------------------------------
// Open a simple rad window for Documentation
// ----------------------------------------------------------
function openRadWindowDocumentation(path) 
{
    var oWindow;
    var width;
    var height;
    
    var oBrowserWnd = getRadWindow();
    if (!oBrowserWnd) {
        oWindow = window.radopen(path, null);
    } else {
        oWindow = oBrowserWnd.BrowserWindow.radopen(path, null);
        height = oBrowserWnd.get_height();
    }    
    
    // Get width and height calculated with browser
    width = getWidthForRadWindow();        
    height = getHeightForRadWindow();    
    
    oWindow.set_behaviors(Telerik.Web.UI.WindowBehaviors.Move + Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Resize + Telerik.Web.UI.WindowBehaviors.Maximize);
    oWindow.set_modal(false);
    //DEBUG 4247 - Hide status bar in radwindows
    oWindow.set_visibleStatusbar(false);    
    oWindow.setSize(width, height);
    oWindow.center();

    return oWindow;
}
function OnClientClose() {
    __doPostBack('', '');
}
// ----------------------------------------------------------
// Method to get TOTAL Height of browser
// ----------------------------------------------------------
function getTotalHeight() 
{
    // firefox is ok
    var height = document.documentElement.scrollHeight;

    // now IE 7 + Opera with "min window"
    if(height > document.documentElement.clientHeight) 
    {
        height  = document.documentElement.clientHeight;
    }
    
    // Safari
    if(height > document.body.scrollHeight) 
    {
        height = document.body.scrollHeight;
    }
    
    return height;
}
function getHeightForRadWindow() 
{
    // Get height calculated with browser
    var height = getTotalHeight() - 100;
    
    // Last solution if height = null
    if (height == null) 
        height = 530;  

    return height;
}

// ----------------------------------------------------------
// Method to get TOTAL Width of browser
// ----------------------------------------------------------
function getTotalWidth() 
{
    // firefox is ok
    var width = document.documentElement.scrollWidth;

    // now IE 7 + Opera with "min window"
    if(width > document.documentElement.clientWidth) 
    {
        width = document.documentElement.clientWidth;
    }
    
    // last for safari
    if(width > document.body.scrollWidth) 
    {
        width = document.body.scrollWidth;
    }
    
    return width;
}
function getWidthForRadWindow() 
{
    // Get width calculated with browser
    var width = getTotalWidth() - 300; 
    
    // Last solution if width = null
    if (width == null) 
        width = 650;  

    return width;
}

// ----------------------------------------------------------
// Locate the current RadWindow
// ----------------------------------------------------------
function getRadWindow()
{      
    var oWindow = null;      
    if (window.frameElement && window.frameElement.radWindow) {
        oWindow = window.frameElement.radWindow;//IE (and Moz as well)      
    }   
    else if (window.radWindow) {
        oWindow = window.radWindow; //Will work in Moz in all cases, including clasic dialog   
    }
    return oWindow;                
}

// --------------------------------------------------------------
// Close the current RadWindow
// --------------------------------------------------------------
function closeForm() 
{
   getRadWindow().Close();
   return true; 
}

// --------------------------------------------------------------
// Close the current RadWindow and refresh the parent page
// --------------------------------------------------------------
function closeFormAndRefresh() 
{
   getRadWindow().Close();
   getRadWindow().BrowserWindow.__doPostBack('', 'closeFormAndRefresh');
   return true;  
}

function closeFormAndRefreshRadWindow() {
    getRadWindow().Close();
    //Getting rad window manager
    var oManager = getRadWindow().get_windowManager();
    //Call GetActiveWindow to get the active window
    var oActive = oManager.getActiveWindow();
    oActive.reload();
    return true;  
}

// --------------------------------------------------------------
// Rating Control
// Rating : Click in button to put value 0
// --------------------------------------------------------------
function SetRatingValue(ratingId)
{
    var rating = $find(ratingId); //get a reference to Rating's client object
    if (rating != null)
        rating.set_value(0);
}


// --------------------------------------------------------------
// Upload Control
// --------------------------------------------------------------
function RemoveDocument(inputId, fileName, fileUrl, lineId) {
    var input = document.getElementById(inputId);
    
    if(input.value != "")
        input.value += ",";

    input.value += fileName + "#" + fileUrl;
        
    var tr = document.getElementById(lineId);
    if (tr == null) 
        tr = $telerik.$("#" + lineId);
    if (tr != null) 
        tr.style.display = "none";
}

// --------------------------------------------------------------
// Get value of a parameter in url
// --------------------------------------------------------------
function getParamInUrl(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}



/**************************************************************/
/**************************************************************/
/*              TabStripBar Control                           */
/**************************************************************/
/**************************************************************/ 

/****  Event Tab Selected in TabStrip control  ****/
function OnClientTabStripBarSelected(sender, eventArgs)
{
    var tab = eventArgs.get_tab();
    var attributes = sender.get_attributes();
    var cookie_name = attributes.getAttribute("cookie");

    write_cookie(cookie_name, tab.get_index());
}


/**************************************************************/
/**************************************************************/
/*              Manage Cookie                           */
/**************************************************************/
/**************************************************************/ 

/****  Function to write a cookie in javascript  ****/
function write_cookie(nom, valeur, expires) 
{
    document.cookie=nom+"="+escape(valeur)+
    ((expires==null) ? "" : ("; expires="+expires.toGMTString()));
}

function read_cookie_value(valeur) {
    var cookie = document.cookie;
    if (cookie) {
        cookie_datas = cookie.split(';');
        if (cookie_datas) {
            for (var i = 0; i < cookie_datas.length; i++) {
                if (cookie_datas[i].indexOf(cookie_name) != -1) {
                    var temp = cookie_datas[i].split('=');
                    if (temp && temp.length == 2 && temp[0] == valeur){
                        //get value
                        return temp[1];
                    }
                }
            }
        }
    }
}

/**************************************************************/
/**************************************************************/
/*              UploadField Control                          */
/**************************************************************/
/**************************************************************/
function OnUploadField(text, idControlText, isZip, idControlZip, guid, idControlGuid)
{
    // Get TextBox in control UploadField       
    var textboxFileName = document.getElementById(idControlText);
    if (textboxFileName)
    {
        textboxFileName.value = text;
        
        // ReadOnly in javascript 
        // because if server (ReadOnly = true), can not to get a value in textbox (is null) ! 
        textboxFileName.readOnly = true;
    }
    
    // File is in package ZIP
    var isZipControl = document.getElementById(idControlZip);
    if (isZipControl)
    {
        isZipControl.value = isZip;
    }
    
    // Guid
    var guidControl = document.getElementById(idControlGuid);
    if (guidControl)
    {
        guidControl.value = guid;
    }
}

// -------------------------------------------------------------------------------------
// Name : Script to finish load    
// IMPORTANT : Add notifyScriptLoaded at 2 files .js 
// Check that files .js has finished to load                                  
// Author : Ronan Salmon          
// See : http://msdn.microsoft.com/fr-fr/library/bb310952.aspx                           
// -------------------------------------------------------------------------------------
if (typeof(Sys) !== 'undefined')
    Sys.Application.notifyScriptLoaded();

// -------------------------------------------------------------------------------------
// Name : addLoadEvent
// Description : manage onload event handler by calling functions in the order they are declared
//  Ex: addLoadEvent(OnBodyLoad); addLoadEvent(OnResizeBody);
// -------------------------------------------------------------------------------------
function addLoadWindowEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func.call();
        }
    }
}

//function addUnloadWindowEvent(func) {
//    var oldonunload = window.onunload;
//    if (typeof window.onunload != 'function') {
//        window.onunload = func;
//    } else {
//        window.onunload = function() {
//            if (oldonunload) {
//                oldonunload();
//            }
//            func();
//        }
//    }
//}

// -------------------------------------------------------------------------------------
// Name : addLoadEvent
// Description : manage onload event handler by calling functions in the order they are declared
//  Ex: addLoadEvent(OnBodyLoad); addLoadEvent(OnResizeBody);
// -------------------------------------------------------------------------------------
function addUnloadWindowEvent(func, scope, revert) {
    if (!scope) scope = window;
    var oldonunload = scope.onunload;
    if (typeof scope.onunload != 'function') {
        scope.onunload = func;
    } else {
        scope.onunload = function() {
            if (revert) func();
            if (oldonunload) {
                oldonunload();
            }
            if (!revert) func();
        }
    }
}

function addBeforeUnloadWindowEvent(func, scope, revert) {
    if (!scope) scope = window;
    var oldonunload = scope.onbeforeunload;
    if (typeof scope.onbeforeunload != 'function') {
        scope.onbeforeunload = func;
    } else {
        scope.onbeforeunload = function() {
            if (revert) func();
            if (oldonunload) {
                oldonunload();
            }
            if (!revert) func();
        }
    }
}

/*******************************************
****    Custom Button PostBack
********************************************/
function onClickCustomButton(elt) {
    if (elt) {
        var disabled = elt.getAttribute('disabled');
        if (ieNavigator && !disabled ) __doPostBack(elt.name, '');
        else 
         if (!ieNavigator && (!disabled || (disabled && disabled != 'disabled'))) __doPostBack(elt.name, '');
    }
}
/*******************************************
****    Open Player popup fullscreen for IE
********************************************/
function openPlayer(url) {

    var height = screen.availHeight;
    var width = screen.availWidth;
    window.resizeTo(width, height);
    window.moveTo(0, 0);

    return window.open(url, "", "status=yes, resizable=yes, toolbar=no, location=yes, fullscreen=no");
}

/******************************************
****  FillInTheGapQuestion Toolbar
*******************************************/

// Find a select or input control in element according to its name
function findElement(element, name)
{
    var i = 0;
    if (element == null)
        return null;
    if (element.attributes != null && element.attributes.getNamedItem("name")!= null && element.attributes.getNamedItem("name").value == name )
        return element;
    
    for (i=0; i<element.childNodes.length; i++)
    { 
        var s = null;
        s = findElement(element.childNodes[i], name);
        if (s!= null)
            return s;                
    }
        
    return null;
}

// find Input or select control
function FindInputOrSelect(selectedHTML, commandName)
{
    var tag = "";
    if (commandName == "InsertCustomSelect" || commandName == "OpenCustomSelectDialog")
    {
        tag = "<select";
    }
    else if (commandName == "InsertCustomText" || commandName == "OpenCustomInputDialog")
    {
        tag = "<input";
    }
    if (selectedHTML.toLowerCase().match(tag))
    {
        // find good id
        var goodId = null;
        var re = new RegExp("name=\"(\\S*)\""); // Firefox
        re.lastIndex = 0;
        var m = re.exec(selectedHTML);
        if (m == null)
        {
            re = new RegExp("name=(\\S*) "); // IE
            re.lastIndex = 0;
            m = re.exec(selectedHTML);                
        }
        if (m != null && m.length >= 2)
        {
            goodId = m[1];
        }        
    }
    elem = findElement(elem, goodId);
    return elem; 
}

// Evenemens
function OnClientCommandExecutingGap(editor, args)
{      
    var commandName = args.get_commandName(); //returns the executed command
   
    var selectedHTML = editor.getSelection().getHtml(); 
       
    elem = editor.getSelectedElement(); 

    elem = FindInputOrSelect(selectedHTML, commandName);

    if (elem == null)
        elem = editor.getSelectedElement(); //returns the selected element.
       
    var hole ="";
        
    if (commandName == "InsertCustomSelect" || commandName == "OpenCustomSelectDialog")
    {
        if (elem.tagName == "SELECT") // get hole value
        {    
            editor.selectElement(elem);
            argument = elem;
            hole = elem.attributes.getNamedItem("hole").value;
        }
        
        var addSelectAndElement = function(sender, args)
        {
            if (elem.tagName == "SELECT")
            // We have already created the combo, we need just to add elements
            // so delete old combo
            {
                var span = elem.parentNode; 
                if (span.tagName != "SPAN")
                {
                    span.removeChild(elem);
                }
                else
                { 
                    var selectParentNode = span.parentNode;
                    selectParentNode.removeChild(span);
                }
            }
            // create new one
            createSelect(editor, args);            
        }
       
        ShowExternalDialog(editor, hole, elem, addSelectAndElement, "select");
        args.set_cancel(true); //cancel the InsertCustomSelect command
    }
    
    if (commandName == "InsertCustomText" || commandName == "OpenCustomInputDialog")
    {
        if (elem.tagName == "INPUT") // get hole value
        {    
            editor.selectElement(elem);
            argument = elem;
            hole = elem.attributes.getNamedItem("hole").value;
        }
        
        var addInputText = function(sender, args)
        {
            if (elem.tagName == "INPUT")
            // We have already created the input, we need just to add elements
            // so delete old input
            {
                var span = elem.parentNode; 
                if (span.tagName != "SPAN")
                {
                    span.removeChild(elem);
                }
                else
                { 
                    var selectParentNode = span.parentNode;
                    selectParentNode.removeChild(span);
                }
            }
            // create new one
            createInput(editor, args);            
        }

        ShowExternalDialog(editor, hole, elem, addInputText, "input");
        args.set_cancel(true); //cancel the InsertCustomText command
    }  
}

// Create select element
function createSelect(editor, args)
{
    var argumentsSeparator = proposalsSeparatorQuestion;// Correspond to the '§'
    var separator = argumentsSeparatorQuestion;// Correspond to the '¤'
    
    var values = args.split(separator);
    var name = values[0];
    var hole = values[1];
    
    var elements = "";
    if (values.length >2)
    {
        elements = values[2].split(argumentsSeparator);
    }
    
    var toPaste = "";
    toPaste = '<span><select hole="'+ hole +'" name="' + name +'" >';        
    toPaste +='<option></option>';
    for (i = 0; i<elements.length; i++)
    {
        if (elements[i] != null)
            toPaste += "<option>" + elements[i] + "</option>";
    }
    toPaste += '</select></span>';
    
    editor.pasteHtml(toPaste);
}
    
function createInput(editor, args)
{
    var separator = argumentsSeparatorQuestion;// Correspond to the '¤'
    
    var values = args.split(separator);
    var name = values[0];
    var hole = values[1];
       
    var toPaste = "";
    toPaste = '<span><input hole="'+ hole +'" name="' + name +'" style="width:80px" type="text"></input></span>';  
    editor.pasteHtml(toPaste);
}

// Double clic event (select only in IE)
function OnClientLoadGap(editor, args)
{
    editor.attachEventHandler ("ondblclick", function (e)
    {
        var argument = editor.getSelection().getParentElement(); //get the currently selected element
        
        if (argument.tagName == "INPUT" || argument.tagName == "SELECT")
        {
            var hole = argument.attributes.getNamedItem("hole").value;
            var addSelectAndElement = function(sender, args)
            {
                if (argument.tagName == "SELECT")
                // We have already created the combo, we need just to add elements
                // so delete old select
                {                    
                    var span = argument.parentNode; 
                    if (span.tagName != "SPAN")
                    {
                        span.removeChild(argument);
                    }
                    else
                    { 
                        var selectParentNode = span.parentNode;
                        selectParentNode.removeChild(span);
                    }
                }
                createSelect(editor, args);
            }
            var addInputAndElement = function(sender, args)
            {
                if (argument.tagName == "INPUT")
                // We have already created the input
                // so delete old input
                {
                    var span = argument.parentNode; 
                    if (span.tagName != "SPAN")
                    {
                        span.removeChild(argument);
                    }
                    else
                    { 
                        var selectParentNode = span.parentNode;
                        selectParentNode.removeChild(span);
                    }
                }
                createInput(editor, args);
            }
            if (argument.tagName == "SELECT")
            {                   
                ShowExternalDialog(editor, hole, argument, addSelectAndElement, "select");         
                return false;
            }
            if (argument.tagName == "INPUT")
            {
                ShowExternalDialog(editor, hole, argument, addInputAndElement, "input");     
                return false;
            }
        }
    });
}

/******************************************************
***  Quiz Timer
*******************************************************/

/***********************
* Handle Timer
************************/
var timeElaspse;

function chrono() {
    var elt = document.getElementById(start_input);
    if (elt && elt.value == "true") {
        if (time == initialTime) {
            //Add 1000 to make algorithm working : if browser is too fast, new Date().getTime() - timeElapse == 0
            // and time calculation will fail
            timeElaspse = new Date().getTime() + 1000;
        }
        time = initialTime - ( new Date().getTime() - timeElaspse )/10;
        //time--;
        if (time >= 0) {
            chronoLabel = document.getElementById(lblTime);
            //h:m:s:cs
            chronoLabel.innerHTML = displayTime(time);
            compte = setTimeout('chrono()', 10); //Function is launched again every 0.01s
        }
        else {
            //Prevent Sco manager Terminate()
            $removeHandler(window, "unload", SyfScoManager.TerminateSco);
            $removeHandler(window, "beforeunload", SyfScoManager.TerminateSco);
            timeElaspse = null;
            __doPostBack('timeElapsed', time);
        }
    }
    else {
        //Not Started and Stoped message
        compte = setTimeout('chrono()', 10); //Function is launched again every 0.01s
    }
}

//Troncate time
function calcage(secs, num1, num2) {
    s = ((Math.floor(secs / num1)) % num2).toString();
    if (LeadingZero && s.length < 2)
        s = "0" + s;

    return s;
}

function displayTime(timeLeft) {
    var result = "";
    //show hours only if there is some hours
    //Days other are not showned
    if (calcage(timeLeft, 8640000, 360000) > 0)
        result += calcage(timeLeft, 8640000, 360000) + "d: ";
    result += calcage(timeLeft, 360000, 24) + "h: ";
    result += calcage(time, 6000, 60) + "m: ";
    result += calcage(time, 100, 60) + "s";
    //show 0.01 if needed
    if (displayCts && displayCts == "True")
        result += ": " + calcage(time, 1, 100);

    return result;
}
/***********************
* Handle user changed page
************************/
function userLeaveQuizRequest() {
    //Prevent Sco manager Terminate()
    //$removeHandler(window, "unload", SyfScoManager.TerminateSco);
    //$removeHandler(window, "beforeunload", SyfScoManager.TerminateSco);
    //Time spent in secs.
    timeSpent = (initialTime - time) / 100;
    __doPostBack('userLeaveQuizRequest', timeSpent);
}

//Fonction translate for multilangBox
function translate(sourceTextBox, sourceLanguage, targetTextBox, targetLanguage) 
{		     
    var sourceBox = $find(sourceTextBox);     
    var targetBox = $find(targetTextBox);   
    google.language.translate(sourceBox.get_value(), sourceLanguage, targetLanguage, function(result) {				
	        if (result.translation) {					
				targetBox.set_value(result.translation);
	        } });    
}


/*****************************************************************************************
** Functions used by the DropDownTree control used by cube builders in the Analysis module
******************************************************************************************/
var SyfadisDropDownTree = function() {

    return {
        /*
        ** Handle node start of node selection : cancel postbacks if a group node is selected
        */
        NodeClicking : function(sender, args) {
            var node = args.get_node();
            
            if ( node.get_nodes().get_count() > 0 ) {

                node.toggle();
                
                args.set_cancel(true);
            }
        },
        
        /*
        ** Put the text and value from the selected node in to the outer Combo box
        */
        NodeClicked : function ( sender, args, combo, nullValue ) {
            var node = args.get_node();
          
            var val = node.get_value();
            if ( val === nullValue ) {
                combo.set_text("");
            }
            else {
                combo.set_text(node.get_text());
            }
            
            combo.trackChanges();
            combo.get_items().getItem(0).set_value(node.get_value());
            combo.commitChanges();

            combo.hideDropDown();
            
            // Call comboBox.attachDropDown if:
            // 1) The RadComboBox is inside an AJAX panel.
            // 2) The RadTreeView has a server-side event handler for the NodeClick event, i.e. it initiates a postback when clicking on a Node.
            // Otherwise the AJAX postback becomes a normal postback regardless of the outer AJAX panel.

            combo.attachDropDown();
       }
    }
}();

/*************************************************************************
** Functions used during configuration of individual web parts
**************************************************************************/
var SyfadisWebPartConfig = function() {

    return {
        /*
        ** Open a window for editing -full url is passed in DockCommand.name property
        */
        Open : function ( sender, eventArgs ) {
            var command = eventArgs.Command;
            var arguments = command.get_name();
    
            openRadWindow( arguments, "SyfadisWebPartConfig", null, null, true );
   
        },

        /*
        ** Cancel the configuration without saving changes
        */
        Cancel : function () {
            closeFormAndRefresh();
        },

        /*
        ** Postback to server indicating configuration should be saved
        */
        Save : function( idDock ) {
            getRadWindow().Close();
            getRadWindow().BrowserWindow.__doPostBack( idDock, 'SyfadisWebPartConfig.Save' );
            return true;
        }
     }

}();

   
