﻿//Permet d'afficher un sousMenu sans recharger la page
var clickListener=null;
var cheminSite = "../../";
var mouseXPosition = 0;
var mouseYPosition = 0;
var dateFin = new Date();
var dateDebut = new Date(dateFin.getFullYear() - 5, dateFin.getMonth(), dateFin.getDate());
var selectedCell = null;

var heuresJournee = new Array();
for (var i = 1; i <= 24; i++) { heuresJournee.push({ 'Text': i, 'Value': i }); }

function OverlaySize(element){
     if(element!=null){
	    if (window.innerHeight && window.scrollMaxY || window.innerWidth && window.scrollMaxX) {
		    yScroll = 2000;
		    xScroll = window.innerWidth + window.scrollMaxX;
	    } else if (document.body.scrollHeight > document.body.offsetHeight || document.body.scrollWidth > document.body.offsetWidth){ // all but Explorer Mac
		    yScroll = document.body.scrollHeight;
		    xScroll = document.body.scrollWidth;
	    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		    yScroll = document.body.offsetHeight;
		    xScroll = document.body.offsetWidth;
  	    }
  	    element.setStyle({height:yScroll + "px",width:xScroll + "px"});
  	  }
}

    function charger(uri, destination) {
        load(destination);
        if (uri == "") return;
        if (destination == "#" || destination == "") return;
        if (destination == null || destination == undefined) { new Ajax.Request(uri); } else {new Ajax.Updater(destination, uri, { method: 'get', evalScripts: true }); }
    }
        
    function chargerAvecAction(uri, destination, actionSiOk, actionSiPasOk)
        {
            if (uri == "")return;
            if (destination == "#" || destination == "") return;
            new Ajax.Request(uri, {
                method: 'get',
                evalScripts: true,
                onComplete: function(transport) {if (transport.status == 200) {if (actionSiOk != null) window[actionSiOk]();} else { if (actionSiPasOk != null) window[actionSiPasOk](); }},
                onFailure: function() {if (actionSiPasOk != null) { window[actionSiPasOk](); }else { $(destination).innerHTML = 'Erreur de chargement'; }}
            });
        }

        function formatDate(maDate) { return maDate.getFullYear() + "-" + maDate.getMonth() + "-" + maDate.getDate();}

        function getAnnee(maDate) {
            if (maDate == null || maDate == undefined) { maDate = new Date() };
            var annee = maDate.getYear(); (Prototype.Browser.Gecko || Prototype.Browser.Chrome || Prototype.Browser.Safari) ? annee = annee + 1900 : void (0);
            return annee;
        }
         
//------------------------------------------
//   Gestion des formulaires
//------------------------------------------
 
  function envoyerFormulaire(uri, formName, destination)
  {
       monUrl = Form.serialize($(formName));
       charger(uri+"/"+monUrl,destination);  
  }
  
   function postFormulaire(uri, data, destination){
       new Ajax.Updater(destination, uri, {
           method: 'POST',
           parameters: data,
           evalScripts: true,
           onComplete: function(transport) {
               if (transport.status == 200) {
                   $(destination).innerHTML = transport.responseText;
               }
           }
       });
  }

  function postRequestForm(uri,data,action){
    return new Ajax.Request(uri,{
            method : 'POST',
            parameters : data,
            onComplete: function(transport) {
                        if (200 == transport.status)
                            if(action!=null)window[action](transport.responseText);                            
                        },
            onFailure: function(){ alert("erreur de chargement: " + uri + " - " + data); }
        });
  }
  
  function postFormulaireBottom(uri, data, destination){
        new Ajax.Updater(destination,uri,{   
                    method: 'POST',
                    parameters : data, 
                    evalScripts : true,
                    insertion: Insertion.Bottom
                });
  }
  
  function load(element) {
       try { element = $(element); element.innerHTML = "<img src='" + cheminSite + "App_Themes/shared/Images/ajax-loader.gif' alt='chargement du contenu'>"; } catch (e) { };
  }

  function saveMousePosition(e) {
    
  } 
  
//------------------------------------------
//   Autres fonctions
//------------------------------------------
        
//permet de positionner la fenetre d'info des indices sur la position de la souris
  function setPosition(element, monEvent, parentElement) {
      try {
          if (parentElement != undefined && parentElement != null) { 
                    element.clonePosition(parentElement, { 'setWidth': false, 'setHeight': false }); 
                    if (Number(element.getStyle("left").replace("px", "")) + Number(element.getStyle("width").replace("px", "")) > document.viewport.getWidth())
                         { 
                           var newposition = Number(element.getStyle("left").replace("px", "")) - (((Number(element.getStyle("left").replace("px", "")) + Number(element.getStyle("width").replace("px", "")) - document.viewport.getWidth()) + 20)); 
                           element.setStyle({ "left": newposition + "px" }); 
                         } else { 
                            element.setStyle({ "left": (Number(element.getStyle("left").replace("px", ""))+ 10) + "px" }); 
                         };
          }
          else { $(element).style.top = (Event.pointerY(monEvent) + 10) + 'px'; $(element).style.left = (Event.pointerX(monEvent) + 10) + 'px'; }
      } catch (e) { centerWindow(element); }
}

function beginSavingMousePosition(monEvent) { document.observe("mousemove", saveMousePosition);}
function endSavingMousePosition(monEvent) { document.stopObserving("mousemove", saveMousePosition);}
function saveMousePosition(monEvent) {try { mouseXPosition = Event.pointerX(monEvent); mouseYPosition = Event.pointerY(monEvent); } catch (e) { alert(e.message); }}

function centerWindow(element) {     
  if($(element) != null) {          
      if(typeof window.innerHeight != 'undefined') {               
          $(element).style.top = Math.round(document.viewport.getScrollOffsets().top + ((window.innerHeight - $(element).getHeight()))/2)+'px';       
          $(element).style.left =  Math.round(document.viewport.getScrollOffsets().left + ((window.innerWidth - $(element).getWidth()))/2)+'px';
      } else {               
          $(element).style.top = Math.round(document.body.scrollTop + (($$('body')[0].clientHeight - $(element).getHeight()))/2)+'px';
          $(element).style.left = Math.round(document.body.scrollLeft + (($$('body')[0].clientWidth - 350))/2)+'px';
      } 
   }
}

function getRadioValue(form, name) {
    tests = form.getElements(); var value = 0;
    for (i = 0; i < tests.length; i++) {
        if (tests[i].name=name && tests[i].checked)
            value = tests[i].value;
    }
    return value;
}

function daysDiff(date1, date2) { return Math.round((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24)); }

function validerDate(date) {
    try {
        madate = date.value.replace("/", "-");
        madate = madate.replace("/", "-");
        var dateparts = madate.split("-");
        if (dateparts.length == 3) {
            if (dateparts[0] < 10 && dateparts[0].charAt(0) != "0") { dateparts[0] = "0" + dateparts[0]; }
            if (dateparts[1] < 10 && dateparts[1].charAt(0) != "0") { dateparts[1] = "0" + dateparts[1]; }
            date.value = dateparts[0] + "-" + dateparts[1] + "-" + dateparts[2];
        }
    } catch (e) { }
}

function loadProtoFlow(id) { return new ProtoFlow($(id), { startIndex: 2, captions: false, useReflection: true, enableOnClickScroll: true }); }

/* //////////////////////////////////////////////////
// OBJETS JAVASCRIPT
//////////////////////////////////////////////////// */

var iATMOElement = Class.create({
    initialize: function(unElement) { this._element = unElement; try { if (this._element != null && (this._element.id == null || this._element.id == "")) { this._element.identify(); } } catch (e) { }; this._scriptExecutes = false; },
    getElement: function() { return this._element; },
    id: function() { return this._element.id; },
    insert: function(object, options) { this._element.insert(object, options); },
    info: function(content) { try { this.clearAllInfoMessage(); if (content != null) { new tip(null, this._element, { 'closePosition': 'left', 'width': '300px', 'defaultText': content }); } } catch (e) { } },
    getAjaxDestination: function() { return this._element; },
    loadComplete: function(data) { this._scriptExecutes = false; this.setContent(data.responseText); },
    loadFailed: function() { },
    vider: function() { while (this._element.childElements().length > 0) { this._element.childElements()[0].remove(); }; this._element.innerHTML = ""; },
    supprimer: function(e) { this.vider(); this._element.remove(); },
    hide: function() { this._element.hide(); },
    show: function() { this._element.show(); },
    visible: function() { return this._element.visible(); },
    setContent: function(content, evalScripts) {
        this.getAjaxDestination().update(content);
        (evalScripts == null) ? evalScripts = true : void (0);
        if (evalScripts && Object.isString(content)) { this.evalScripts(content); }
    },
    evalScripts: function(content) {
        try {
            if(!this._scriptExecutes){
                var scripts;
                (Object.isElement(content)) ? scripts = content.innerHTML.extractScripts() : scripts = content.extractScripts();
                for (var j = 0; j < scripts.length; j++) {
                    var result = eval(scripts[j]);
                    if (Object.isFunction(result)) {
                        var resultat = result();
                        if (resultat != null && resultat.isJSON()) { this.parseData(resultat.evalJSON()); }
                    }
                }
                this._scriptExecutes = true;
            }
        }
        catch (e) { }
    },
    makeDraggable: function() { try { new Draggable(this._element); } catch (e) { } },
    addElement: function(element, destination, position) {
        try {
            if (destination == null) {
                this._element.insert(element._element);
            } else {
                var whereToInsert = $(this._element.getElementsByClassName(destination)[0]);
                var maxPosition = whereToInsert.childElements().size() - 1;
                if (position == 0) { whereToInsert.insert({ top: element._element }); }
                else if (maxPosition > position) { whereToInsert.childElements()[position].insert({ before: element._element }); }
                else { whereToInsert.insert(element._element); position = whereToInsert.childElements().size() - 1; }
                element.setPosition(position);
                //whereToInsert.insert(new Element("BR"));
            }
        } catch (e) { return false; }
        return true;
    },
    clearAllInfoMessage: function() { }
});


//function tip(url, destination, id, closePosition, closing, width, defaultText, actionOnClosing, defaultBackgroundColor, parentElement, add)
var tip = Class.create(iATMOElement, {
    initialize: function($super, url, parentElement, parametres) {
        $super(new Element("DIV")); this._element.setStyle({ 'position': 'absolute' }); this._element.identify(); this._element.style.zIndex = 99999; this._element.addClassName("tip");
        //parametres = JSON : closePosition, closing, width, defaultText, actionOnClosing, defaultBackgroundColor, parentElement, add
        try {
            (parametres == null || parametres == undefined) ? parametres = {} : void (0);
            (Object.isString(parametres)) ? parametres = parametres.evalJSON() : void (0);
            (parametres.closePosition == null || parametres.closePosition == undefined) ? parametres.closePosition = 'right' : void (0);
            (parametres.defaultText == null || parametres.defaultText == undefined) ? parametres.defaultText = '' : void (0);
            (parametres.closing == null || parametres.closing == undefined) ? parametres.closing = true : void (0);
            (parametres.width == null || parametres.width == undefined) ? parametres.width = '400px' : void (0);
            (parametres.add == null || parametres.add == undefined) ? parametres.add = false : void (0);
            if (parametres.actionOnClosing != null) { this._onClosing = parametres.actionOnClosing; }
            this._closeButton = null; this._conteneur = null;
            var tableau = new Element("TABLE", { "width": "100%" }); tableau.addClassName("defaultBox"); var tableauBody = new Element("TBODY"); tableau.insert(tableauBody);
            if (parametres.closing) {
                var lignehaut = new Element("TR"); var celluleHaut = new Element("TD", { "align": parametres.closePosition });
                this._closeButton = new Element("A", { "href": "javascript:void(0)" }); this._closeButton.observe("click", this.supprimer.bindAsEventListener(this)); this._closeButton.addClassName("boutonFermer"); this._closeButton.update("<img src='" + cheminSite + "App_themes/shared/Images/icons/close-icon-16x16_orange.gif' />Fermer");
                celluleHaut.insert(this._closeButton); lignehaut.insert(celluleHaut); tableauBody.insert(lignehaut);
            }
            var ligneBas = new Element("TR"); this._conteneur = new Element("TD"); this._conteneur.appendChild(document.createTextNode(parametres.defaultText)); this._conteneur.identify(); this._conteneur.setStyle({ "width": "100%" });
            ligneBas.insert(this._conteneur); tableauBody.insert(ligneBas);
            this._element.insert(tableau); this.makeDraggable(); this._element.setStyle({ 'width': parametres.width });
            document.iGlobal.insert(this._element);
            if (parentElement != null || parametres.event != null) { try { setPosition(this._element, parametres.event, parentElement); } catch (e) { } }
            if (url != null || url != undefined) {
                if (Object.isString(url)) {
                    new iLoadingElement(this, url, null, false, this._conteneur);
                } else {
                    this._conteneur.insert(url._element);
                    if (url.addedToDesk()) { try { url.update(); } catch (e) { } }
                }
            }
        } catch (e) { alert(e.message); }
    },
    getAjaxDestination: function($super) { return this._conteneur; },
    setContent: function($super, content, evalScripts) { $super(content); content.evalScripts(); }
});

var iAutocompleter = Class.create(iATMOElement, {
    initialize: function($super, parentElement, adresse) {
        $super(new Element("div", { id: parentElement.id() + 'Autocompleter' })); this._defaultUrl = adresse;
        this._autocompleter = new Element("div", { id: parentElement.id() + 'AutocompleterChoices' }); this._autocompleter.setStyle({ 'backgroundColor': '#EDEDED', 'position': 'absolute', 'border': '1', 'z-index': '99999', 'width': '300px' });
        this._loading = new Element("div", { id: parentElement.id() + 'Loading' }); this._loading.setStyle({ 'z-index': '20000', 'position': 'absolute', 'width': '300px' });
        this._loading.insert(new Element("img", { "src": cheminSite + "app_themes/shared/images/ajax-loader.gif" })); this._loading.appendChild(document.createTextNode("Recherche en cours...")); this._loading.hide();
        this._element.insert(this._loading); parentElement.insert(this._element); parentElement.insert(this._autocompleter);
        this._monCompleter = new Ajax.Autocompleter(parentElement.getInputZone().id, this._autocompleter.id, adresse, { minChars: 2, tokens: ',', indicator: this._loading.id });
    },
    click: function(newUrl) {
        this._monCompleter.url = newUrl;
        this._monCompleter.activate();
        this._monCompleter.url = this._defaultUrl;
    }
});

  var iLoadingElement = Class.create(Ajax.Request, {
      success: function(response) { try { this._element.show(); } catch (e) { }; try { this._loading.remove(); } catch (e) { }; this._element.loadComplete(this.transport); },
      fail: function() { try { this._loading.remove(); } catch (e) { }; this._element.loadFailed(); },
      initialize: function($super, element, url, method, hideOnLoad, insertLocation, parametres) {
          this._element = element; (method == null || method == undefined) ? method = 'GET' : void (0);
          var id = ''; if (element != null) { try { id = element.id() } catch (e) { id = element.id; } }
          this._loading = new Element("div", { id: id + 'loading' });
          try {
              (insertLocation == null || insertLocation == undefined) ? insertLocation = element._element.up() : void (0);
              this._loading.setStyle({ 'z-index': '20000', 'width': element._element.style.width });
              this._loading.insert(new Element("img", { "src": cheminSite + "app_themes/shared/images/ajax-loader.gif" })); this._loading.appendChild(document.createTextNode("Chargement en cours..."));
              insertLocation.insert(this._loading); (hideOnLoad || hideOnLoad == null) ? element._element.hide() : void (0);
          } catch (e) { }
          $super(url, {
              method: method,
              parameters: parametres,
              onSuccess: function(response) { this.success.bindAsEventListener(this); },
              onFailure: function() { this.fail.bindAsEventListener(this); }
          });
      }
  });

  var iFormulaire = Class.create(iATMOElement, {
      initialize: function($super, monElement, urlMethod, validationRules, object) { $super(monElement); this._urlMethod = urlMethod; this._validationRules = validationRules; this._object = object; },
      getUrl: function() { if (Object.isFunction(this._urlMethod)) { return this._urlMethod() } else { return this._urlMethod; } },
      valid: function(event) {
          var valid = true; //if (this._validationRules != null) { valid = yav.performCheck(this._element, this._validationRules, 'inline') };
          if (valid) { try { this._object.update(this.getUrl(), 'url'); } catch (e) { } }
      },
      getAjaxDestination: function() { return new Element('DIV', { 'id': this._element.id + 'load' }); },
      loadComplete: function($super, transport) { try { this._object.update(transport.responseText); } catch (e) { } },
      loadFailed: function() { }
  });

  var iElementFormulaire = Class.create(iATMOElement, {
      initialize: function($super, monElement, onSelect) { $super(monElement); if (onSelect != null) { this._onSelect = onSelect; this._element.observe('change', this.onElementSelect.bindAsEventListener(this)); } },
      onElementSelect: function(e) { if (this._onSelect != null) { this._onSelect(); } },
      value: function() { if (this._element.value == "" || this._element.value == null) { return "all" } else { return this._element.value; } },
      disable: function() { this._element.disable(); },
      enable: function() { this._element.enable(); }
  });

  var iListElement = Class.create(iElementFormulaire, {
      initialize: function($super, monElement, contentUrl, elements, onSelect, addDefaultValue, defaultValue) { $super(monElement, onSelect); (addDefaultValue == null || addDefaultValue == undefined) ? this._addDefaultValue = true : this._addDefaultValue = addDefaultValue; if (contentUrl != null) { this.charger(contentUrl); } else if (elements != null) { this.addElements(elements.evalJSON()); }; this._defaultValue = defaultValue; },
      charger: function(url, method) { (method == null) ? method = 'get' : void (0); new iLoadingElement(this, url, method); },
      loadComplete: function($super, transport) { try { this.addElements(transport.responseText.evalJSON()); } catch (e) { } },
      text: function() { return this._element.options[this._element.selectedIndex].text; },
      loadFailed: function() { },
      allValues: function() { var mesValeurs = "["; for (var i = 0; i < this._element.options.length; i++) { if (this._element.options[i].value != "all") { var maValeur = "{\"Text\":\"" + this._element.options[i].text + "\",\"Value\":\"" + this._element.options[i].value + "\"}"; if (mesValeurs != "[") { mesValeurs += "," }; mesValeurs += maValeur; } } mesValeurs += "]"; return mesValeurs; },
      addElements: function(elements) {
          while (this._element.length > 0) { this._element.remove(0); };
          if (elements.length > 0 && this._addDefaultValue) { this._element.options[this._element.options.length] = new Option("Tous", "all") };
          for (var i = 0; i < elements.length; i++) { var nouvelleOption = new Option(elements[i].Text, elements[i].Value); if (this._defaultValue != null && this._defaultValue == elements[i].Value) { nouvelleOption.selected = true }; this._element.options[this._element.options.length] = nouvelleOption; }
      }
  });

  var iLiListElement = Class.create(iListElement, {
      initialize: function($super, monElement, contentUrl, elements, onSelect, addDefaultValue) { $super(monElement, contentUrl, elements, onSelect, addDefaultValue); },
      addElements: function($super, elements) { while (this._element.length > 0) { this._element.remove(0); }; if (elements.length > 0) { for (var i = 0; i < elements.length; i++) { var unItem = new Element("li"); unItem.insert(elements[i].Text); unItem.valeur = elements[i].Value; unItem.observe("mouseover", function() { this.style.cursor = 'hand'; }); unItem.observe("mouseout", function() { this.style.cursor = 'default'; }); unItem.observe("click", this.onElementSelect.bindAsEventListener(this)); this._element.insert(unItem); } } },
      value: function() { },
      onElementSelect: function($super, e) {
          if (this._onSelect != null) {
              this._onSelect(Event.element(e));
          }
      }
  });

  var iCalendarElement = Class.create(iElementFormulaire, {
      initialize: function($super, monElement, defaultValue, updateElement) {
          $super(new Element("DIV", { 'id': 'container' + monElement.id })); this._element.addClassName('calendrier'); this._element.setStyle({ 'text-align': 'right' }); monElement.up().insert(this._element); this.hide(); new Draggable(this._element);
          this._lien = monElement; this._lien.observe("click", this.afficher.bindAsEventListener(this));
          this._date = defaultValue; this._getDateListe = cheminSite + "BoiteAOutils/listerDate/{mois}/{annee}";
          this._moisPrecedent = new Element("A", { 'id': 'moisPrec' + this._element.id, 'href': 'javascript:void(0)' }); this._moisPrecedent.innerHTML = "&lt;"; this._moisPrecedent.observe("click", this.explorerMoisPrecedent.bindAsEventListener(this));
          this._moisSuivant = new Element("A", { 'id': 'moisSuiv' + this._element.id, 'href': 'javascript:void(0)' }); this._moisSuivant.innerHTML = "&gt;"; this._moisSuivant.observe("click", this.explorerMoisSuivant.bindAsEventListener(this));
          this._anneePrecedente = new Element("A", { 'id': 'anPrec' + this._element.id, 'href': 'javascript:void(0)' }); this._anneePrecedente.innerHTML = "<b>&lt;&lt;</b>"; this._anneePrecedente.observe("click", this.explorerAnPrecedent.bindAsEventListener(this));
          this._anneeSuivante = new Element("A", { 'id': 'anSuiv' + this._element.id, 'href': 'javascript:void(0)' }); this._anneeSuivante.innerHTML = "<b>&gt;&gt;</b>"; this._anneeSuivante.observe("click", this.explorerAnSuivant.bindAsEventListener(this));
          this._moisCourant = new Element("SPAN"); this._tablePrincipale = null; this._currentExploringDate = defaultValue;
          this._fermer = new Element("A", { "href": "javascript:void(0)" }); this._fermer.addClassName('boutonFermer'); this._fermer.update("<img src='" + cheminSite + "App_themes/shared/Images/icons/close-icon-16x16_orange.gif' />"); this._fermer.observe("click", this.fermer.bindAsEventListener(this));
          this._updateElement = updateElement; this._aujourdhui = this.creerJour(('{"id":"' + this.annee(new Date()) + '/' + this.mois(new Date()) + '/' + this.jour(new Date()) + '","titre":"Aujourd&#39;hui"}').evalJSON());
          try { this._updateElement.value = this.value() } catch (e) { }
          this._loading = false;
      },
      value: function($super) { return (this.jour() + "-" + this.mois() + "-" + this.annee()); },
      dateChanged: function(e) { },
      afficher: function(e) { if (!this._loading) { this._loading = true; this.show(); setPosition(this._element, e); this.creerCalendrier(this.mois(), this.annee()); } },
      creerCalendrier: function(mois, annee) { new iLoadingElement(this, this._getDateListe.replace("{mois}", mois).replace("{annee}", annee), null, false, this._element); },
      loadComplete: function($super, transport) { this.afficherValeurs(transport.responseText.evalJSON()); },
      getAjaxDestination: function() { return new Element("DIV", { 'id': this._element.id + 'loader' }); },
      afficherValeurs: function(data) {
          this._currentExploringDate = new Date(data.id); if (this._tablePrincipale != null) { this._tablePrincipale.remove(); }
          this._tablePrincipale = new Element("TABLE"); this._tablePrincipaleBody = new Element("TBODY"); this._tablePrincipale.addClassName('calendrier');
          this._tablePrincipale.insert(this._tablePrincipaleBody);
          this.genererEntete(this._tablePrincipaleBody);
          this._moisCourant.innerHTML = data.titre;
          var ligne = new Element("TR"); 
          ligne.insert(new Element("TD", { 'align': 'center', 'width': '14%' }));
          for (var i = 0; i < data.dates.length; i++) {
              if (i != 0 && i % 7 == 0) {
                  this._tablePrincipaleBody.insert(ligne);
                  ligne = new Element("TR");
                  ligne.insert(new Element("TD", { 'align': 'center', 'width': '14%' }));
              };
              var unElement = new Element("TD");
              unElement.insert(this.creerJour(data.dates[i]));
              ligne.insert(unElement);
              if (i != 0 && (i + 1) % 7 == 0) {
                  ligne.insert(new Element("TD", { 'align': 'center', 'colspan': 2 }));
              } 
           }
          var pied = new Element("TR"); var piedTD = new Element("TD", { 'colspan': 10, 'align': 'center' }); piedTD.insert(this._aujourdhui); pied.insert(piedTD); this._tablePrincipaleBody.insert(ligne); this._tablePrincipaleBody.insert(pied); this._element.insert(this._tablePrincipale); this._loading = false;
      },
      genererEntete: function(place) {

          var ligne = new Element("TR");
          var enTeteTD_moisprec = new Element("TD", { 'align': 'center', 'width': '14%' }); enTeteTD_moisprec.insert(this._anneePrecedente); ligne.insert(enTeteTD_moisprec);
          var enTeteTD_date = new Element("TD", { 'align': 'center', 'colspan': 7 }); enTeteTD_date.insert(this._moisPrecedent); enTeteTD_date.insert("&nbsp;"); enTeteTD_date.insert(this._moisCourant); enTeteTD_date.insert("&nbsp;"); enTeteTD_date.insert(this._moisSuivant); ligne.insert(enTeteTD_date);
          var enTeteTD_ansuiv = new Element("TD", { 'align': 'center', 'width': '14%' }); enTeteTD_ansuiv.insert(this._anneeSuivante); ligne.insert(enTeteTD_ansuiv);
          var enTeteTD_fermer = new Element("TD", { 'align': 'center', 'width': '14%' }); enTeteTD_fermer.insert(this._fermer); ligne.insert(enTeteTD_fermer);
          place.insert(ligne);

      },
      creerJour: function(data) { var unJour = new Element("a", { 'id': data.id + this._element.id, 'href': 'javascript:void(0)' }); unJour.value = data.id; unJour.innerHTML = data.titre; unJour.observe("click", this.selectionneJour.bindAsEventListener(this)); return unJour; },
      selectionneJour: function(e) { this._date = new Date(Event.element(e).value); this.fermer(); if (this._updateElement != null) { try { if (Object.isFunction(this._updateElement)) { this._updateElement(); } else { this._updateElement.setValue(this.value()); } } catch (e) { }; } },
      annee: function(value) { if (value == null) { value = this._date; }; var annee = value.getFullYear(); /* (Prototype.Browser.Gecko || Prototype.Browser.Chrome || Prototype.Browser.Safari) ? annee = annee + 1900 : void (0); */return annee; },
      mois: function(value) { if (value == null) { value = this._date; }; return value.getMonth() + 1; },
      jour: function(value) { if (value == null) { value = this._date; }; return value.getDate(); },
      explorerMoisPrecedent: function() { var annee = this.annee(this._currentExploringDate); var mois = this.mois(this._currentExploringDate) - 1; if (mois <= 0) { mois = 12; annee = annee - 1 }; this.creerCalendrier(mois, annee); },
      explorerMoisSuivant: function() { var annee = this.annee(this._currentExploringDate); var mois = this.mois(this._currentExploringDate) + 1; if (mois == 13) { mois = 1; annee = annee + 1 }; this.creerCalendrier(mois, annee); },
      explorerAnPrecedent: function() { this.creerCalendrier(this.mois(this._currentExploringDate), this.annee(this._currentExploringDate) - 1); },
      explorerAnSuivant: function() { this.creerCalendrier(this.mois(this._currentExploringDate), this.annee(this._currentExploringDate) + 1); },
      fermer: function(e) { this.hide(); }
  });

  var iCart = Class.create(iATMOElement, {
      initialize: function($super, element, noDataMessage) { $super(element); this._nombreElements = 0; (noDataMessage == null) ? this._noDataMessage = "Sélectionnez des mesures pour créer votre graph" : this._noDataMessage = noDataMessage; this.info(this._noDataMessage); },
      info: function(text) { if (this._element != null) { this._element.insert(text); } },
      ajouterValeur: function(data, type) {
          if (type == null) { if (data.isJSON()) { type = 'json'; } else { type = 'url'; } };
          switch (type) {
              case 'url': new iLoadingElement(this, data); break;
              case 'json':
                  data = data.evalJSON();
                  if (this._nombreElements == 0) { this._element.innerHTML = ""; }
                  for (var i = 0; i < data.length; i++) {
                      if (!this.dejaPresente(data[i].Value)) {
                          try {
                              var maligne = new Element("SPAN", { 'id': this.id() + data[i].Value });
                              maligne.insert(new Element("input", { 'type': 'hidden', 'value': data[i].Value }));
                              maligne.insert(new Element("input", { 'type': 'checkbox' }));
                              maligne.appendChild(document.createTextNode(data[i].Text.unescapeHTML()));
                              this._element.insert(maligne);
                              this._element.insert("<br>");
                              this._nombreElements++;
                          } catch (e) { } 
                      } 
                  }; break;
          }
      },
      dejaPresente: function(valeur) { for (var i = 0; i < this._element.childElements().length; i++) { if (this._element.childElements()[i].outerHTML.toLowerCase() != "<br>") { if (valeur == this._element.childElements()[i].childElements()[0].value) { return true; } } }; return false; },
      loadComplete: function(transport) { this.ajouterValeur(transport.responseText); },
      loadFailed: function() { },
      retirerValeur: function(elementASupprimer) {
          (elementASupprimer != null && elementASupprimer.isJSON()) ? elementASupprimer = elementASupprimer.evalJSON() : elementASupprimer = null;
          var i = 0;
          while (i < this._element.childElements().length) {
              if (this._element.childElements()[i].innerHTML != "") {
                  if (this._element.childElements()[i].childElements()[1].checked || (elementASupprimer != null && this._element.childElements()[i].childElements()[0].value == elementASupprimer.Value)) {
                      this._element.childElements()[i].remove();
                      this._nombreElements--;
                  }
                  else { i++; }
              } else {
                  this._element.childElements()[i].remove(); i++;
              }
          }
          if (this._nombreElements == 0) { this.info(this._noDataMessage); }
      },
      value: function() { var values = ""; for (var i = 0; i < this._element.childElements().length; i++) { if (this._element.childElements()[i].outerHTML.toLowerCase() != "<br>") { values += this._element.childElements()[i].childElements()[0].value + ';' } } return values },
      vider: function($super) { $super(); this._nombreElements = 0; this.info(this._noDataMessage); }
  });

  var Graph = Class.create(iATMOElement, {
      initialize: function($super, monElement, dataUrl, width, height, options, extraSettingsUrl, urlSecours) {
          $super(monElement); this._dataUrl = dataUrl; (width == null) ? this._width = monElement.getWidth() : this._width = width; this._height = height; this._folder = null; this._graphLib = null; this._options = options; this._extraSettingsUrl = extraSettingsUrl; this._urlSecours = urlSecours;
          this._loadingDiv = new Element('DIV', { id: 'loading' + monElement.id }); this._loadingDiv.setStyle({ 'width': '100%', 'background': '#EFEFEF' }); this._loadingDiv.appendChild(new Element('img', { 'src': cheminSite + "app_themes/shared/images/ajax-loader.gif" })); this._loadingDiv.appendChild(document.createTextNode("Création du graphique en cours"));
          this._containerDiv = new Element('DIV', { id: 'dataContainer' + this._element.id });
          this._element.insert(this._loadingDiv); this._element.insert(this._containerDiv);
      },
      loadGraph: function(data) {
          try {
              this.loadStart();
              var dataloaded = false;
              if (this._monGraph == null && (data != undefined && data != null) || this._dataUrl != null) {
                  this._containerDiv.insert("<br><br><b>Nous n'avons pas pu détecter le plugin flash nécessaire à l'affichage des graphiques. Merci de le télécharger et de l'installer depuis <a href='http://www.adobe.com/support/flashplayer/downloads.html' target='_blank'>http://www.adobe.com/support/flashplayer/downloads.html</a>.");
                  if (this._urlSecours != null && this._urlSecours != undefined) {
                      this._containerDiv.insert(" Sinon, exportez les données sous forme de tableau en <a href='" + this._urlSecours + "' target='_blank'>cliquant ici</a>");
                  }
                  this._containerDiv.insert("</b><br><br>");
                  (this._settingFile == null || this._settingFile == undefined) ? this._settingFile = this._graphLib + "_settings.xml" : void (0);
                  var unGraph = new SWFObject(cheminSite + '_librairies/' + this._folder + '/' + this._graphLib + '.swf', 'graph0' + this.id(), this._width, this._height, '8', '#FFFFFF');
                  unGraph.addVariable("loading_settings", "Chargement des paramètres");
                  unGraph.addParam("wmode", "opaque");
                  unGraph.addVariable("path", cheminSite + "_librairies/" + this._folder + "/");
                  unGraph.addVariable("chart_id", 'graph0' + this.id());
                  if (this._extraSettingsUrl != null && this._extraSettingsUrl != "" && this._extraSettingsUrl != "undefined" && this._extraSettingsUrl != "null") { this._extraSettingsUrl = "," + this._extraSettingsUrl } else { this._extraSettingsUrl = "" };
                  unGraph.addVariable("settings_file", cheminSite + "_librairies/" + this._folder + "/" + this._settingFile + this._extraSettingsUrl);
                  if (this._options != '') { unGraph.addVariable("additional_chart_settings", this._options); }
                  var dataUrlLoaded = false; if (this._dataUrl != null && this._dataUrl.length > 4) { dataUrlLoaded = true; if (this._dataUrl.substr(0, 4) == "http") { unGraph.addVariable("data_file", encodeURIComponent(this._dataUrl)); dataloaded = true; } }
                  if (!dataUrlLoaded) { unGraph.addVariable("chart_data", encodeURIComponent(data)); this._loadWhenInited = data; }
                  unGraph.write(this._containerDiv.id); this._monGraph = $('graph0' + this._element.id); this._monGraph.graph = this;
              } else { if (this._monGraph != null && data != null) { this._monGraph.setData(data); } }
              this.loadEnd();
          } catch (e) { this.loadEnd(true); }
      },
      chartInited: function() { if (this._loadWhenInited != null) { this.update(this._loadWhenInited, "data"); this._loadWhenInited = null; } },
      loadEnd: function(withError) { (withError == null || withError == undefined) ? withError = false : void (0); this._loadingDiv.hide(); if (withError) { this.show(); this.info("Erreur lors du chargement du graph"); } else { this._loadingDiv.hide(); } },
      loadStart: function() { this.show(); this._loadingDiv.show(); },
      update: function(data, type, append) {
          if (data != null || data != undefined) {
              if (type == null) { (data.startsWith("http://")) ? type = "url" : type = "data"; };
              switch (type) {
                  case "url": new iLoadingElement(this, data); break;
                  case "data": this.loadStart(); (append == null || append == undefined) ? append = false : void (0);
                      try {
                          if (this._monGraph == null || this._monGraph == undefined) { this.loadGraph(data); }
                          else { if (append) { this._monGraph.appendData(data); } else { this._loadWhenInited = data; this._monGraph.setData(data, true); }; this._monGraph.rebuild(); };
                          return true;
                      } catch (e) { this.loadEnd(); }
                      break;
              };
          } else { this.info("Erreur lors du chargement des données") }; return false;
      },
      getAjaxDestination: function($super) { return new Element('DIV', { 'id': this._element.id + 'load', 'style': 'display:none' }); },
      loadComplete: function($super, data) { try { this.update(data.responseText); } catch (e) { } },
      loadFailed: function($super) { },
      graphProcessComplete: function() { this.loadEnd(); },
      setContent: function($super, content, evalScripts) { }
  });

  function amChartInited(chart_id) { $(chart_id).graph.chartInited(); }
  function amProcessCompleted(chart_id) { $(chart_id).graph.graphProcessComplete(); }

  var lineGraph = Class.create(Graph, { initialize: function($super, idGraph, dataUrl, width, height, options, data, extraSettingsUrl, urlSecours) { $super($(idGraph), dataUrl, width, height, options, extraSettingsUrl, urlSecours); this._folder = "amline_1.6.4.1"; this._graphLib = "amline"; this.loadGraph(data); } });
  var columnGraph = Class.create(Graph, { initialize: function($super, idGraph, dataUrl, width, height, options, data, extraSettingsUrl, urlSecours) { $super($(idGraph), dataUrl, width, height, options, extraSettingsUrl, urlSecours); this._folder = "amcolumn"; this._graphLib = "amcolumn"; this.loadGraph(data); } });
  var stackedGraph = Class.create(Graph, { initialize: function($super, idGraph, dataUrl, width, height, options, data, extraSettingsUrl, urlSecours) { $super($(idGraph), dataUrl, width, height, options, extraSettingsUrl, urlSecours); this._folder = "amcolumn"; this._graphLib = "amcolumn"; this._settingFile = "amStackedColumnSettings.xml"; this.loadGraph(data); } });
  var pieGraph = Class.create(Graph, { initialize: function($super, idGraph, dataUrl, width, height, options, data, extraSettingsUrl, urlSecours) { $super($(idGraph), dataUrl, width, height, options, extraSettingsUrl, urlSecours); this._folder = "ampie"; this._graphLib = "ampie"; this.loadGraph(data); } });

  var iTableau = Class.create(iATMOElement, {
      initialize: function($super, element, dataUrl, width, height) { $super(element); this._table = new Element("iframe", { 'id': this.id() + "iframe", 'width': width, 'height': height }); this._element.insert(this._table); this.hide(); },
      update: function(data, type) { if (type == 'url') { this._table.src = data; } }
  });

  var iGlobal = Class.create({
      initialize: function(page) {
          this._page = page; this._page.setParent(this); this._titrePage = document.title; this._menus = new Array(); this._waitingAction = new Array();
          this._allowDeskToAddModules = false; if (this.getQuickReference() != null && this.getQuickReference() != "*") { this.loadQuickReference(); } else { this._allowDeskToAddModules = true; }
          window.document.iGlobal = this; this._objectWaitingReady = new Array(); this._pageReady = false;
          window.document.observe("historyChange", function(e) { alert("op"); });
      },
      getDesk: function() { return this._page; },
      addMenu: function(menu) { this._menus.push(menu); this._menus[this._menus.length - 1].setParent(this); },
      switchMode: function(url) { this._page.emptyMainPanel(); this._page.loadNewContent(cheminSite + url); },
      deskReady: function() { while (this._waitingAction.length > 0) { eval(this._waitingAction.pop()); }; },
      addQuickReference: function(url) { window.location.href = window.location.href.split('#')[0] + '#' + url; },
      getQuickReference: function() { if (window.location.href.split('#').length > 1 && window.location.href.split('#')[1] != "") { return window.location.href.split('#')[1] }; return "*"; },
      addContentReference: function(url) { this.addQuickReference(this.getQuickReference()); window.location.href = window.location.href + "#" + url; },
      getContentReference: function() { if (window.location.href.split('#').length > 2 && window.location.href.split('#')[2] != "") { return window.location.href.split('#')[2] }; return null; },
      loadQuickReference: function() {
          var url = window.location.href.split('#')[1];
          if (url != undefined && url != null) { if (url.startsWith("menu")) { /*this._menus[item.level()].load(item); */ } else { this._waitingAction.push("this._page.update('" + cheminSite + url + "',['iRessourceModule'])"); this.switchMode("page/modules/" + url.split("/")[0]); } };
          //if (window.location.href.split('#').length == 3) { /*on met à jour tous les iPersonnalizableModule > dont le contenu peut être mis à jour grâce à des données dans l'url */ this._page.update(cheminSite + window.location.href.split('#')[2], ['iPersonnalizableModule','iExternalModule']); }
      },
      menuSelect: function(item) { if (item.level() == 3) { action = "this._page.dispatch(\"{'motscles':'" + item.id() + "'}\",['iRessourceListe'])"; if (this._page.isReady()) { eval(action); } else { this._waitingAction.push(action) } } else { this._menus[item.level()].load(item); } },
      allowDeskToAddModules: function() { return this._allowDeskToAddModules; },
      titre: function(monTitre) { document.title = this._titrePage; if (monTitre != undefined && monTitre != null && monTitre != "") { document.title += "-" + monTitre } },
      pageReady: function(e) { this._pageReady = true; this._page.pageReady(); for (var i = 0; i < this._objectWaitingReady.length; i++) { if (this._objectWaitingReady[i].pageReady != null) { this._objectWaitingReady[i].pageReady(); } } },
      tellMeWhenReady: function(object) { if (this._pageReady) { object.pageReady(); } else { this._objectWaitingReady.push(object); } },
      insert: function(element, options) { this._page.insert(element, options); }
  });

  var iMenuItem = Class.create(iATMOElement, {
      initialize: function($super, element, item, style, onClic) { $super(element); this._style = style; this._item = item; if (this._element != null) { this._element.insert(this.getLink()); }; this._onClic = onClic; },
      clic: function(e) { this._parent.newItemClicked(this); if (this._onClic != null) { this._onClic() }; },
      id: function($super) { return this._item.Value; },
      level: function() { return this._parent.level(); },
      setParent: function(parent) { this._parent = parent; },
      getLink: function() { var monLien = new Element("a", { "href": "javascript:void(0)" }); monLien.className = this._style; var texteLien = this._item.Text.unescapeHTML().replace("&apos;", "'"); if (this._style == "MenuNiveau2") { monLien.insert("&nbsp;<img src='" + cheminSite + "app_themes/shared/Images/point.png'/>&nbsp;"); }; monLien.insert(texteLien); monLien.observe("click", this.clic.bindAsEventListener(this)); return monLien; }
  });

    var iMenu = Class.create(iATMOElement, {
        initialize: function($super, element, level, loadFirst, urlWhenClicked, childStyle, actionWhenClicked) { $super(element); this._elements = new Array(); this._level = level; this._loadFirst = loadFirst; this._urlWhenClicked = urlWhenClicked; this._childStyle = childStyle; this._actionWhenClicked = actionWhenClicked; },
        addItem: function(item) { this._elements.push(item); item.setParent(this); if (item._element == null) { this._element.insert(item.getLink()); } },
        load: function(item) { new iLoadingElement(this, item._parent._urlWhenClicked.replace("{id}", item.id())); },
        newItemClicked: function(item) { this._parent.menuSelect(item); },
        loadComplete: function($super, data) { this.vider(); if (data != null && data.responseText != null) { var mesItems = data.responseText.evalJSON(); for (var i = 0; i < mesItems.length; i++) { this.addItem(new iMenuItem(null, mesItems[i], this._childStyle, this._actionWhenClicked)); }; if (this._loadFirst) { this._parent.menuSelect(this._elements[0]); }; }; },
        getAjaxDestination: function() { return new Element('DIV', { 'id': this._element.id + 'load' }); },
        setParent: function(parent) { this._parent = parent; },
        level: function() { return this._level; },
        vider: function($super) { $super(); this._elements.clear(); }
    });

    var iMetas = Class.create({
        initialize: function(data) { this.parse(data); if (this.motscles == null || this.motscles == undefined) { this.motscles = "all"; } },
        parse: function(data) {
            if (Object.isString(data)) { data = data.evalJSON(); }
            if (data.zones != undefined && data.zones != null) { this.zones = data.zones; } else { this.zones = "all"; }
            if (data.motscles != undefined && data.motscles != null && data.motscles != "") { this.motscles = data.motscles; }
            if (data.domaine != undefined && data.domaine != null) { this.domaine = data.domaine; }
            if (data.dateDebut != undefined && data.dateDebut != null) { this.dateDebut = data.dateDebut; }
            if (data.dateFin != undefined && data.dateFin != null) { this.dateFin = data.dateFin; }
            if (data.ordre != undefined && data.ordre != null) { this.ordre = data.ordre; }
            if (data.polluants != undefined && data.polluants != null) { this.polluants = data.polluants; }
            if (data.themes != undefined && data.themes != null) { this.themes = data.themes; } else { this.themes = ""; }
            if (data.contentUrl != undefined && data.contentUrl != null) { this.contentUrl = data.contentUrl; }
			if (data.id != undefined && data.id != null) { this.id = data.id; }
        },
        updateUrl: function(url) { return url.replace("{sitePath}", cheminSite).replace("{zones}", this.zones).replace("{tags}", this.tags()).replace("{motscles}", this.motscles).replace("{ordre}", this.ordre).replace("{dateDebut}", this.dateDebut).replace("{dateFin}", this.dateFin).replace("{polluants}", this.polluants).replace("{domaine}", this.domaine).replace("{id}", this.id); },
        json: function() { return Object.toJSON(this); },
        tags: function() {
            var tags = "";
            if (this.domaine != null && this.domaine != undefined && this.domaine != "all") { tags += this.domaine; }
            if (this.themes != null && this.themes != undefined && this.themes != "all") { tags += ";" + this.themes; }
            if (this.motscles != null && this.motscles != undefined && this.motscles != "all") { tags += ";" + this.motscles; } return tags;
        }
    });

    var iDesk = Class.create(iATMOElement, {
        initialize: function($super, element, id, defaultZone, defaultDomain) {
            $super(element); this._waitingActions = new Array(); this._id = id; this._elements = new Array();
            this._metas = new iMetas("{'zones':'" + defaultZone + "','domaine':'" + defaultDomain + "','themes':'all','motscles':'all','dateDebut':'" + formatDate(dateDebut) + "','dateFin':'" + formatDate(dateFin) + "'}");
            this._isReady = false; this._currentContent = null; this._ressourceSelectionnee = null;
            this.liveInserter = new iLiveModuleInserter(this);
        },
        initMeta: function(data) { try { if (data == null || data == undefined) { data = this.getContentReference(); }; this._metas.parse(data); } catch (e) { } },
        addElement: function($super, element, destination, position, addIntoPage) {
            var reussite = true;
            if (this.isReady()) {
                try {
                    this._elements.push(element); element.setParent(this); if (addIntoPage == null || addIntoPage == undefined) { addIntoPage = true; }; if (position == null || position == undefined) { position = 0 };
                    if (addIntoPage) { reussite = $super(element, destination, position, addIntoPage); };
                    if (reussite) { element.addedToDesk(destination); element.adapteToi(this._metas); }
                } catch (e) { reussite = false }
            } else { this._waitingActions.push(function() { this.addElement(element, destination, position, addIntoPage); } .bindAsEventListener(this)); }
            return reussite;
        },
        addElements: function(data) { try { for (var i = 0; i < data.length; i++) { try { var e = eval("new " + data[i].JSModule + "('" + data[i].uniqueId + "', '" + Object.toJSON(data[i].viewData) + "', '" + data[i].titre + "',null,'" + data[i].controller + "')"); this.addElement(e, data[i].viewData.destination, data[i].position); } catch (e) { } }; return true; } catch (e) { return false } },
        ressourceSelected: function(data, loadRessource, addQuickReference, forceReloading) {
            try {
                (forceReloading == null || forceReloading == undefined) ? forceReloading = false : void (0);
                if ((this._ressourceSelectionnee != null && data.url != this._ressourceSelectionnee.url) || this._ressourceSelectionnee == null || forceReloading) {
                    this.emptyMainPanel(); this._ressourceSelectionnee = data; try { if (data.isJSON()) { data = data.evalJSON() }; } catch (e) { }
                    (loadRessource == null || loadRessource == undefined) ? loadRessource = true : void (0);
                    (addQuickReference == null || addQuickReference == undefined) ? addQuickReference = true : void (0);
                    var modulesToDispatch = ['iModule', 'iMetadonneesExplorer', 'iPermalinkModule', 'iRessourceLiees'];
                    if (loadRessource) { modulesToDispatch.push('iRessourceModule'); };
                    this._parent.titre(data.titre); this.dispatch(data, modulesToDispatch);
                    if (addQuickReference) { this._parent.addQuickReference(data.url); }
                    var i = 0; while (i < this._elements.length) { if (this._elements[i].typeName == "iPersonnalizableModule") { var module = this._elements[i].pop(); module.supprimer(); } else { i++ } };
                    return true;
                }
            } catch (e) { }
            return false;
        },
        setRessourceContent: function(container) {
            var evalScripts = false; for (i = 0; i < this._elements.length; i++) { if (this._elements[i].typeName == "iRessourceModule") { this._elements[i].setContent(container); evalScripts = true; } };
        },
        preloadRessource: function(data, container) { if (this._parent.getQuickReference() == "*") { this.ressourceSelected(data, false, false); this.setRessourceContent(container); } },
        dispatch: function(metas, targetModuleTypes) {
            this.initMeta(metas); this.addContentReference(this._metas.json());
            for (i = 0; i < this._elements.length; i++) { if (targetModuleTypes == null || targetModuleTypes.indexOf(this._elements[i].typeName) > -1) { if (["iPermalinkModule", "iPersonnalizableModule", "iRessourceLiees", "iRessourceModule"].indexOf(this._elements[i].typeName) > -1) { this._elements[i].adapteToi(metas); } else { this._elements[i].adapteToi(this._metas); } } }
        },
        emptyMainPanel: function() { var newelements = new Array(); var i = 0; while (i < this._elements.length) { var element = this._elements[i]; if (element._currentLocation == "MainPanel") { element.close(); } else { newelements.push(element); i++; } }; this._elements = newelements; },
        update: function(url, targetModuleTypes) { for (i = 0; i < this._elements.length; i++) { if (targetModuleTypes == null || targetModuleTypes.indexOf(this._elements[i].typeName) > -1) { this._elements[i].update(url, 'url'); } } },
        removeAllModules: function() { this._elements = new Array(); this.vider(); },
        remove: function(module) {
            module.supprimer();
            this._elements = this._elements.without(module);
            try { /*envoyer la suppression du module à la page*/
                /* ByVal idPage As Integer, ByVal idModule As String, ByVal colonne As String, ByVal ordre As String */
                new Ajax.Request(cheminSite + module._controller + '/deleteModule/' + this._id + '/' + module._objectId + '/' + module._currentLocation + '/' + module._position);
            } catch (e) { }
        },
        loadNewContent: function(url) { if (url != this._currentContent) { this.removeAllModules(); this._isReady = false; var loader = new iLoadingElement(this, url); this._currentContent = url; } },
        loadComplete: function(data) { this.createDesk(data.responseText.evalJSON().template.evalJSON(), data.responseText.evalJSON().modules) },
        createDesk: function(layout, elements) { this._isReady = this.createLayout(layout); if (this._isReady) { this._isReady = this.addElements(elements) || elements == null; }; if (this.isReady) { this.executeWaitingActions(); this._parent.deskReady(); } },
        executeWhenReady: function(object) { this._waitingActions.push(object); },
        executeWaitingActions: function() { while (this._waitingActions.length > 0) { try { var action = this._waitingActions.pop(); if (Object.isString(action)) { eval(this._waitingAction.pop()); } else { action(); } } catch (e) { } } },
        createLayout: function(template) { try { for (var i = 0; i < template.zones.length; i++) { var monDiv = new Element("DIV", { 'id': this.id() + template.zones[i] }); monDiv.addClassName(template.zones[i]); this._element.insert(monDiv); } } catch (e) { return false; }; return true; },
        loadFailed: function() { },
        getAjaxDestination: function() { return new Element('DIV', { 'id': this._element.id + 'load' }); },
        setParent: function(parent) { this._parent = parent; this.initMeta(); },
        isReady: function() { return this._isReady && this.allModulesAreReady(); },
        allModulesAreReady: function() { var ready = true; for (var i = 0; i < this._elements.length; i++) { ready = ready && this._elements[i].isReady(); }; return ready; },
        addContentReference: function(url) { this._parent.addContentReference(url); },
        getContentReference: function() { return this._parent.getContentReference(); },
        pageReady: function() { for (var i = 0; i < this._elements.length; i++) { this._elements[i].pageReady(); }; }
    });

    var iLiveModuleInserter = Class.create({
        initialize: function(desk) { this._desk = desk; this._ligne = null; this._colonne = null; },
        setPosition: function(ligne, colonne) { this._ligne = ligne; this._colonne = colonne; },
        add: function(sourceUrl, form) { if (this._ligne != null && this._colonne != null) { new iLoadingElement(this, sourceUrl.replace('{sitePath}', cheminSite).replace('{colonne}', this._colonne).replace('{ligne}', this._ligne), "POST", false, null, form.serialize()); } },
        loadComplete: function(data) { if (this._desk.addElements(new Array(data.responseText.evalJSON()), this._colonne, this._ligne, true)) { this._ligne = null; this._colonne = null; }; }
    });

    var iModuleMenu = Class.create(iATMOElement, {
        initialize: function($super, parentModule, options) {
            $super(new Element("DIV", { 'id': 'iModuleMenu' + parentModule.id() })); this._element.addClassName("menuModule");
            this._closeButton = new Element("A", { 'id': 'iMMClose' + this.id(), 'href': 'javascript:void(0)' }); this._closeButton.insert(new Element("IMG", { 'src': cheminSite + 'App_themes/shared/Images/icons/close-icon-16x16_orange.gif' })); this._closeButton.observe("click", this.close.bindAsEventListener(this));
            this._contentUrl = new Element("A", { 'id': 'iMMContent' + this.id(), 'href': 'javascript:void(0)' }); this._contentUrl.insert(new Element("IMG", { 'src': cheminSite + 'App_themes/shared/Images/icons/integrer-icon-16x16_orange.gif' })); this._contentUrl.observe("click", this.shared.bindAsEventListener(this));
            this._rssUrl = new Element("A", { 'id': 'iMMRss' + this.id(), 'href': 'javascript:void(0)' }); this._rssUrl.insert(new Element("IMG", { 'src': cheminSite + 'App_themes/shared/Images/icons/feed-icon-16x16_orange.gif' })); this._rssUrl.observe("click", this.rss.bindAsEventListener(this));
            this._kmlUrl = new Element("A", { 'id': 'iMMKml' + this.id(), 'href': 'javascript:void(0)' }); this._kmlUrl.insert(new Element("IMG", { 'src': cheminSite + 'App_themes/shared/Images/icons/feed-gearth-16x16_orange.gif' })); this._kmlUrl.observe("click", this.kml.bindAsEventListener(this));
            this._parent = parentModule;
            this.insert(this._closeButton);
            this.insert(this._contentUrl);
            this.insert(this._rssUrl);
            this.insert(this._kmlUrl);
            this._parent.insert(this._element);
            try {
                if (options.close == null || options.close == 'undefined' || !options.close || options.close == 'false') { this._closeButton.hide(); };
                if (options.share == null || options.close == 'undefined' || !options.share || options.share == 'false') { this._contentUrl.hide(); };
                if (options.rss == null || options.rss == 'undefined' || !options.rss || options.rss == 'false') { this._rssUrl.hide(); };
                if (options.kml == null || options.kml == 'undefined' || !options.kml || options.kml == 'false') { this._kmlUrl.hide(); };
            } catch (e) { }
            if (!this._closeButton.visible() && !this._contentUrl.visible() && !this._rssUrl.visible() && !this._kmlUrl.visible()) { this.hide(); }
        },
        close: function(e) { this._parent.close();  },
        shared: function(e) { return this._parent._contentUrl; },
        rss: function(e) { alert("rss"); },
        kml: function(e) { alert("kml"); }
    });

    var iBaseModule = Class.create(iATMOElement, {
        initialize: function($super, id, controller, element) { $super(element); this._id = id; this._controller = controller; },
        update: function(data, type) { /* must inherit */ },
        adapteToi: function(metas) { if (this._contentUrl != null) { try { this.update(metas.updateUrl(this._contentUrl), "url"); } catch (e) { } } },
        isReady: function() { return true; },
        setParent: function(parent) { this._parent = parent; },
        parseData: function(data) { },
        close: function() { this._parent.remove(this); },
        addedToDesk: function(location) { this._currentLocation = location; },
        pageReady: function() { },
        setPosition: function(position) { this._position = position; }
    });

    var iModule = Class.create(iBaseModule, {
        initialize: function($super, id, data, titre, conteneur, controller) {
            try {
                $super(id, controller, new Element("DIV")); this.typeName = "iModule";
                try { data = data.evalJSON(); } catch (e) { }
                if (conteneur == null) { this.createConteneur(); } else { this._conteneur = new iATMOElement(conteneur); }; this._conteneur._element.setStyle({ 'width': '100%' }); this._conteneur._element.className = "moduleContent";
                if (titre != null && titre != undefined) { this._titre = new Element("DIV"); this._titre.addClassName("titreModule"); this._titre.addClassName("titreModule" + controller); this._titre.insert(titre); this._element.insert(this._titre); }
                this._menu = new iModuleMenu(this, ('{\"close\":\"' + data.closeButton + '\",\"share\":false,\"rss\":' + (data.rssUrl != null) + ',\"kml\":' + (data.kmlUrl != null) + '}').evalJSON());
                this._element.insert(this._conteneur._element);
                this._pied = new Element("DIV"); this._pied.setStyle({ 'width': '100%', 'text-align': 'center' }); this._element.insert(this._pied);
                if (data != null) { this.parseData(data); }
                this._isReady = true;
            } catch (e) { this._isReady = false; }
        },
        hide: function($super) { $super(); if (this._conteneur != null) { this._conteneur.hide(); } },
		show: function($super) { $super(); if (this._conteneur != null) { this._conteneur.show(); } },
        parseData: function($super, data) {
            try {
				if (Object.isString(data)) { data = data.evalJSON() }
                $super(data);
                if (data.contentUrl != null && data.contentUrl != undefined) { this._contentUrl = data.contentUrl.replace("{sitePath}", cheminSite); };
                if (data.titreCssClasse != null && data.titreCssClasse != undefined) { this._titre.className = data.titreCssClasse };
                if (data.cssClasse != null && data.cssClasse != undefined) { this._element.className = data.cssClasse; } else { this._element.className = 'module'; };
                if (data.titre != null && data.titre != undefined) { this._titre.innerHTML = ""; this._titre.appendChild(document.createTextNode(data.titre)); };
                if (data.lien != null && data.lien != undefined) {
                    this._lien = new Element("A", { 'id': 'lien' + this.id(), 'href': data.lien.contentUrl }); this._lien.addClassName("ressource"); this._lien.appendChild(document.createTextNode(data.lien.libelle)); this._pied.insert(this._lien);
                    this._titre_lien = new Element("A", { 'id': 'lien' + this.id(), 'href': data.lien.contentUrl }); this._titre_lien.addClassName(this._titre.classNames());
                    this._titre_lien.update(this._titre.innerHTML); this._titre.innerHTML = ""; this._titre.insert(this._titre_lien);
                }
                if (data.objectId != null && data.objectId != undefined) { this._objectId = data.objectId; }
                if (data.rssUrl != null && data.rssUrl != undefined) { this._rssUrl = data.rssUrl; }
                if (data.kmlUrl != null && data.kmlUrl != undefined) { this._kmlUrl = data.kmlUrl; }
				if (data.message != null && data.message != null && data.message != "") { this.info(data.message); }
            } catch (e) { };
        },
        update: function($super, data, type, force) { switch (type) { case 'url': if (data == null) { data = this._contentUrl; }; if (this._currentContentUrl != data || force) { this._currentContentUrl = data; this._conteneur.vider(); new iLoadingElement(this, data.replace("{sitePath}", cheminSite), null, false, this.getAjaxDestination()); } break; default: this._conteneur._element.innerHTML = data; break; } },
        getAjaxDestination: function($super) { return this._conteneur._element; },
        createConteneur: function() { this._conteneur = new iATMOElement(new Element("DIV", { 'id': 'content' + this._id })); },
        pageReady: function($super) { $super(); }
    });

    var iStaticModule = Class.create(iModule, {
        initialize: function($super, id, data, titre, conteneur, controller) { $super(id, data, titre, conteneur, controller); this.typeName = "iStaticModule"; },
        adapteToi: function($super, metas){},
        parseData: function($super, data){
            try {
                if (data.sourceUrl != null && data.sourceUrl != undefined) { this._contentUrl = data.sourceUrl; this.update(data.sourceUrl, 'url'); };
                if (data.contentUrl != null && data.contentUrl != undefined) { this._contentUrl = data.contentUrl; this.update(data.contentUrl, 'url'); };
                if (data.titreCssClasse != null && data.titreCssClasse != undefined) { this._titre.className = data.titreCssClasse };
                if (data.cssClasse != null && data.cssClasse != undefined) { this._element.className = data.cssClasse; } else { this._element.className = 'module'; };
            } catch (e) { };
        },
        setContent: function($super, content, evalScripts) {$super(content); (evalScripts == null) ? evalScripts = true : void (0);  if (evalScripts) { this.evalScripts(content); } }
    });

    var iPermalinkModule = Class.create(iModule, {
        initialize: function($super, id, data, titre, conteneur, controller) { $super(id, data, titre, conteneur, controller); this.typeName = "iPermalinkModule"; this._monLien = null; },
        adapteToi: function($super, metas) { if (metas.permalink != null && metas.permalink != undefined) { this.vider(); this._monLien = new Element("a", { "href": metas.permalink }); this._monLien.addClassName("ressource"); this._monLien.appendChild(document.createTextNode("[ Lien permanent vers cet article ]")); this._element.insert(this._monLien); } }
    });

    var iPersonnalizableModule = Class.create(iModule, {
        initialize: function($super, id, data, titre, conteneur, controller) { $super(id, data, titre, conteneur, controller); },
        update: function($super, data, type) {
            try {
                if (data != this._currentContentUrl) {
                    this._currentContentUrl = data;
                    this._object.update(data, type);
                } else {
                    if (data == null && this._currentContentUrl == null && this._contentUrl != null) {
                        this._currentContentUrl = this._contentUrl;
                        this._object.update(this._contentUrl, type);
                    }
                } 
            } catch (e) { } 
        },
        adapteToi: function($super, metas) { if (metas.contentUrl != null && metas.contentUrl != this._contentUrl) { this._contentUrl = metas.contentUrl; }; $super(metas); },
        parseData: function($super, data) {
            try {
                $super(data);
                if (data.height != null && data.height != undefined) { this._height = data.height; }
                if (data.width != null && data.width != undefined) { this._width = data.width; }
            } catch (e) { };
        },
        pageReady: function($super) { $super(); }
    });

    var iExternalModule = Class.create(iBaseModule, {
        initialize: function($super, id, data, titre, conteneur, controller, object) { $super(id, controller, conteneur); this.typeName = "iExternalModule"; this._object = object; if (data.contentUrl != null && data.contentUrl != undefined) { this._contentUrl = data.contentUrl.replace('{sitePath}', cheminSite); } },
        update: function($super, data, type) {
            if (data != this._currentContentUrl) {
                this._currentContentUrl = data;
                if (type == "url") { try { this._parent.addContentReference("{'contentUrl':'" + data + "'}"); } catch (e) { } }
                try { this._object.update(data, type); } catch (e) { }
            }
        },
        setParent: function($super, parent) { $super(parent); },
        addedToDesk: function($super) { /*écrase le contenu par défaut par du contenu sauvé dans l'url */try { this._contentUrl = this._parent.getContentReference().evalJSON().contentUrl; } catch (e) { }; }
    });

    var iMap = Class.create(iPersonnalizableModule, {
        initialize: function($super, id, data, titre, conteneur, controller) {
            $super(id, data, titre, conteneur, controller);
            this.typeName = "iPersonnalizableModule";
            this._mapZone = new Element("DIV", { 'id': 'mapZone' + this._id }); this._mapZone.setStyle({ 'width': this._width, 'height': this._height });
            this._conteneur._element.insert(this._mapZone);
            var defaultAction = null; try { data = data.evalJSON()} catch (e) { }
            this._object = new baseLayer(titre, data.contentType, this._contentUrl, null, data.clicSensible, [this._width, this._height], this._bounds, false);
        },
        parseData: function($super, data) { try { $super(data); if (data.bounds != null && data.bounds != undefined) { if (Object.isString(data.bounds)) { data.bounds = data.bounds.evalJSON(); }; this._bounds = data.bounds; }; if (data.actionUrl != null && data.actionUrl != undefined) { this._actionUrl = data.actionUrl.replace("{sitePath}", cheminSite); } } catch (e) { } },
        addedToDesk: function($super, location) { $super(location); this._maCarte = new iMapModule(this._conteneur._element, null, null, this._mapZone, new baseLayer("Google(TM)", "google"), null, null, false, null, null, false); this._maCarte.tellMeWhenClicked(this); this._maCarte.addLayer(this._object, false, false); },
        adapteToi: function($super, metas) { $super(metas); try { this._maCarte.geolocaliser(zones); } catch (e) { }; this._polluant = metas.polluants; },
        actionWhenClicked: function(coords) { if (this._actionUrl != null) { new tip(this._actionUrl.replace("{x}", coords.lon).replace("{y}", coords.lat).replace("{polluants}", this._polluant), this._mapZone); } },
        pageReady: function($super) { if (this._maCarte.pageReady != null) { this._maCarte.pageReady(); }; }
    });

    var iGraph = Class.create(iPersonnalizableModule, {
        initialize: function($super, id, data, titre, conteneur, controller) { $super(id, data, titre, conteneur, controller); this.typeName = "iPersonnalizableModule"; },
        parseData: function($super, data) { $super(data); try { this._typeGraph = data.typeGraph; } catch (e) { }; try { this._extraSettingsUrl = data.extraSettingsUrl; } catch (e) { this._extraSettingsUrl = "" }; try { this._extraSettings = data.extraSettings; } catch (e) { this._extraSettings = "" }; try { this._urlSecours = data.urlSecours.replace("{sitePath}",cheminSite); } catch (e) { this._urlSecours = "" } },
        addedToDesk: function($super, location) { try { $super(location); if (this._typeGraph != null) { this._object = eval("new " + this._typeGraph + "('" + this._conteneur.id() + "',null," + this._width + "," + this._height + ",'" + this._extraSettings + "',null,'" + this._extraSettingsUrl + "','" + this._urlSecours + "')") }; return true; } catch (e) { return false; } },
        loadComplete: function($super, data) { }
    });
	
	var iAdminDesk = Class.create(iDesk, {

    initialize: function($super, element, id, defaultZone, defaultDomain, selector, browser, editor) {
        $super(element, id, defaultZone, defaultDomain); this._editor = editor; this._browser = browser; this._selector = selector; if (this._editor != null) { this._elements.push(this._editor); } if (this._browser != null) { this._elements.push(this._browser); } if (this._selector != null) { this._elements.push(this._selector); }
        /*if (this._browser != null && this._editor != null) { this._switcher = new Element("A", { 'href': 'javascript:void(0)' }); this._switcher.insert("<-- Retour à la liste"); this._switcher.identify(); this._switcher.observe("click", this.switchElements.bindAsEventListener(this)); this._switcher.hide(); this._element.insert(this._switcher); }*/
    },
    ressourceSelected: function($super, data, loadRessource, addQuickReference) {
        if (this._editor.loaded()) {
            if (this._editor != null) { this._editor.linkRessource(data); }
        } else {
            $super(data, loadRessource, addQuickReference, true);
            if (this._browser != null) { this._brower.hide(); }
            if (this._selector != null) { this._selector.hide(); }
        }
    },
    load: function(contenu, type, destination, data) {
        switch (destination) {
            case "browser": this._brower.update(contenu, type); this.switchElements("browser"); break;
            case "selector": this._selector.update(contenu, type); this.switchElements("browser"); break;
            case "switcher": this._switcher.update(contenu, type); this.switchElements("browser"); break;
            case "editor": this._editor.update(contenu, type, data); this.switchElements("editor"); break;
        }
    }
});

    var iRessourceListeConteneur = Class.create(iATMOElement, {
        initialize: function($super, unElement, parent) { $super(unElement); this._parent = parent; },
        loadComplete: function($super, data) {
            try {
                this.vider();
                var mesItems = data.responseText.evalJSON();
                var premiereLigne = new Element("TR"); deuxiemeLigne = new Element("TR");
                for (var i = 0; i < mesItems.length; i++) {
                    var image = new Element("IMG", { 'src': cheminSite + "App_themes/shared/Images/FlecheBas.png" }); var celluleImage = new Element("TD", { 'align': 'center' }); celluleImage.insert(image); premiereLigne.insert(celluleImage);
                    var celluleTexte = new Element("TD", { 'align': 'center', 'width': Math.round(100 / mesItems.length) + '%' });
                    var lien = new Element("A", { 'id': mesItems[i].url, 'href': 'javascript:void(0)' }); lien.appendChild(document.createTextNode(mesItems[i].titre));
                    lien.data = mesItems[i]; lien.observe("click", this.select.bindAsEventListener(this));
                    if (i == 0) { this._parent.itemSelected(mesItems[i]); }
                    celluleTexte.insert(lien);
                    deuxiemeLigne.insert(celluleTexte);
                }
                var monTableau = new Element("TABLE", { 'width': '100%' }); var monTableauBody = new Element("TBODY");
                monTableau.insert(monTableauBody); monTableauBody.insert(premiereLigne); monTableauBody.insert(deuxiemeLigne);
                this._element.insert(monTableau);
            } catch (e) { }
        },
        select: function(e) { try { this._parent.itemSelected(Event.element(e).data); } catch (e) { } }
    });

    var iRessourceListe = Class.create(iModule, {
        initialize: function($super, id, data, titre, classe, size, conteneur, controller) { $super(id, data, titre, classe, size, conteneur, controller); this.typeName = "iRessourceListe"; },
        itemSelected: function(item) { this._parent.ressourceSelected(item); },
        createConteneur: function($super) { this._conteneur = new iRessourceListeConteneur(new Element("DIV", { 'id': 'content' + this._id }), this); },
        loadComplete: function($super, data) { this._conteneur.loadComplete(data); }
    });

    var iMetadonneesExplorer = Class.create(iModule, {
        initialize: function($super, id, data, titre, classe, size) { $super(id, data, titre, classe, size); this.typeName = "iMetadonneesExplorer"; this.creerZones(); },
        creerZones: function() { this._motcles = new Element("DIV"); this._conteneur._element.insert(this._motcles); this._themes = new Element("DIV"); this._conteneur._element.insert(this._themes); },
        adapteToi: function($super, metas) {
            this.createLinks(metas.themes, metas.updateUrl("ressources/chercher/{id}/article;media/{zones}/all/now"), this._themes, "Thèmes: ");
            this.createLinks(metas.motscles, metas.updateUrl("ressources/chercher/{id}/article;media/{zones}/all/now"), this._motcles, "Mots clés: ");
        },
        createLinks: function(data, url, where, label) {
            if (data != undefined && data != null) {
                where.update(""); where.insert(label); var addedElements = 0; if (data != null && data != undefined && Object.isString(data)) { data = data.split(";"); }
                for (var j = 0; j < data.length; j++) {
                    if (data[j] != "all" && data[j] != "") {
                        var libelle; if (!Object.isString(data[j])) { url = data[j].contentUrl; libelle = data[j].libelle; } else { libelle = data[j]; }
                        var unLien = new Element("A", { 'href': 'javascript:void(0)' }); unLien.addClassName("ressource");
                        unLien.data = url.replace("{id}", data[j]);
                        unLien.insert(libelle.replace(new RegExp("(_)", "g"), " "));
                        unLien.observe("click", this.select.bindAsEventListener(this));
                        where.insert(unLien); addedElements += 1;
                        this.thisElementHasBeenAdded(unLien, where);
                    }
                }
                if (addedElements == 0) { where.update(""); }
            }
        },
        select: function(e) { try { new tip(cheminSite + Event.element(e).data, this._element, { 'width': '300px' }); } catch (e) { } },
        thisElementHasBeenAdded: function(element, where) { where.insert("&nbsp;"); }
    });

var iRessourceLiees = Class.create(iMetadonneesExplorer, {
    initialize: function($super, id, data, titre, conteneur, controller, editable) {
        $super(id, data, titre, conteneur, controller); this.typeName = "iRessourceLiees"; this._monLien = null;
        //gestion du editionLink + gestionnaire suppression ressource/{action}/...
    },
    adapteToi: function($super, metas) { this._idRessource =  metas.id;  this.createLinks(metas.liens, null, this._ressourcesLiees, "<b>Documents associés</b>: "); },
    creerZones: function($super) { this._ressourcesLiees = new Element("DIV"); this._conteneur._element.insert(this._ressourcesLiees); },
    thisElementHasBeenAdded: function($super, element, where) { where.insert("<br>"); }
});

var iRessourceModule = Class.create(iModule, {
    initialize: function($super, id, data, titre, conteneur, controller) { $super(id, data, titre, conteneur, controller); this.typeName = "iRessourceModule"; this._data = data; },
    setContent: function($super, content, evalScripts) {
        this._conteneur.vider();
        this._conteneur._element.insert(content);
        try { content.show(); } catch (e) { }
        (evalScripts == null) ? evalScripts = true : void (0);
        if (evalScripts) { this.evalScripts(content); }
    },
    adapteToi: function($super, metas) {
        if (metas.url != null) {
            this.update(cheminSite + metas.url, 'url');
        } else if (this._contentUrl != null) {
            if ((this._contentUrl.include("{id}") && metas.id != null) || !this._contentUrl.include("{id}")) { this.update(metas.updateUrl(this._contentUrl), "url"); }
        };
    }
});

var iRessourceEditor = Class.create(iRessourceModule, {
    initialize: function($super, id, data, titre, conteneur, controller, links) { $super(id, data, titre, conteneur, controller); this._loaded = false; this.createRessourceLinker(); this.addLinkButtons(links); },
    setContent: function($super, content, evalScripts) { if (!this._loaded) { $super(content, evalScripts); this._loaded = true; this.show(); }; },
    unload: function() { this._loaded = false; this.hide(); },
    loaded: function() { return this._loaded; },
    createRessourceLinker: function() { if (this._ressourcesLiees == null) { this._ressourcesLiees = new iRessourceLiees(null, this._data, ""); this._ressourcesLiees.hide(); this.addElement(this._ressourcesLiees); } this._ressourcesLiees.adapteToi(this._data); },
    addLinkButtons: function(links) {
        this._linkButtons = new Element("DIV"); this._element.insert(this._linkButtons);
        if (links != null) {
            try {
                for (var i = 0; i < links.length; i++) {
                    links[i] = links[i].evalJSON();
                    this._linkButton = new Element("A", { 'href': 'javascript:void(0)' });
                    this._linkButton.insert(links[i].text);
                    this._linkButton.url = links[i].url;
                    if (i > 0) { this._linkButtons.insert("&nbsp;-&nbsp;"); }; this._linkButtons.insert(this._linkButton);
                    this._linkButton.observe("click", function(e) { new tip(Event.element(e).url, this); } .bindAsEventListener(this));
                }
            } catch (e) { }
        };
        this._linkButtons.hide();
    },
    addedToDesk: function($super, location) { this._parent.addElement(this._ressourcesLiees, null, null, false); },
    linkRessource: function(ressource) { new iLoadingElement(this, cheminSite + "ressources/lier/" + this._ressourcesLiees._idRessource + "/" + ressource.evalJSON().id); },
    ressourceSelected: function(e) { },
    hide: function($super) { $super(); this._ressourcesLiees.hide(); try { this._linkButtons.hide(); } catch (e) { } },
    show: function($super) { $super(); this._ressourcesLiees.show(); try { this._linkButtons.show(); } catch (e) { } },
    update: function($super, url, type, data) {
        this.unload();
        var method = "GET";
        if (data != null) { method = "POST"; }
        new iLoadingElement(this, url, method, false, this.getAjaxDestination(), data);
    },
    loadComplete: function($super, data) {
        try {
            if (Object.isString(data.responseText) && data.responseText.isJSON()) {
                data = data.responseText.evalJSON();
                if (data.message != null && data.message != undefined) { this.info(data.message); }
            } else { $super(data); }
            this._loaded = true;
        } catch (e) { }
    }
});
	
    var iGeolocator = Class.create({
        initialize: function(object) { this._object = object; },
        search: function(lieu) { new iLoadingElement(this, cheminSite + "zone/getCoordinates/" + lieu, null, false); },
        getAjaxDestination: function() { var monElement = new Element("DIV"); monElement.identify(); return monElement; },
        loadComplete: function(transport) { this._object.locate(transport.responseText.evalJSON().coordonnees, transport.responseText.evalJSON().typeLieu, transport.responseText.evalJSON().systeme, false); },
        loadFailed: function() { }
    });

    var iMetaBrowser = Class.create(iATMOElement, {
        initialize: function($super, element, object, options, subtypesBrowser, defaultValue, allowMultipleValues) {
            $super(element); this._object = object;
            if (options != null) { this._options = options; } else { this._options = { 'okButton': true }; };
            if (subtypesBrowser != null) { this._subtypesBrowser = subtypesBrowser; }
            if (defaultValue == null || defaultValue == undefined) { defaultValue = "" }; this._defaultValue = defaultValue;
        },
        createSearchZone: function(url) {
            try {
                this._inputZone = new Element("input", { 'id': this._element.id + 'input', 'name': this._type, 'type': 'text', 'value': this._defaultValue });
                this._inputZone.setStyle({ 'width': '80%' });
                this._element.insert(this._inputZone);
                if (this._options.okButton == true) {
                    this._searchButton = new Element("a", { href: 'javascript:void(0)' }); this._searchButton.identify();
                    this._searchButton.appendChild(document.createTextNode("OK"));
                    this._searchButton.observe("click", this.search.bindAsEventListener(this));
                    this._element.insert(this._searchButton);
                }
                this.addText();

                this._monAutocompleter = new iAutocompleter(this, url);
            } catch (e) { this._element.up().hide(); }
        },
        search: function(e) { },
        createSubtypeBrowser: function() {
            var conteneur = new Element("SPAN");
            if (this._subtypesBrowser != null && this._subtypesBrowser != undefined) {
                for (var i = 0; i < this._subtypesBrowser.length; i++) {
                    var valeur = this._subtypesBrowser[i].evalJSON();
                    var unLien = new Element("A", { 'href': 'javascript:void(0)' }); unLien.identify(); unLien.insert(valeur.text); unLien.url = valeur.url;
                    unLien.observe("click", function(e) { this._monAutocompleter.click(Event.element(e).url); } .bindAsEventListener(this));
                    if (i > 0) { conteneur.insert("&nbsp;-&nbsp;"); } conteneur.insert(unLien);
                }
            }
            this._element.insert(conteneur);
        },
        value: function() { return this._inputZone.serialize().split("=")[1]; },
        addText: function() { },
        getInputZone: function() { return this._inputZone }
    });

var iArborescenceBrowser = Class.create(iMetaBrowser, {
    initialize: function($super, element, object, options, typeArborescence, subtypesBrowser, defaultValue, allowMultipleValues) {
        $super(element, object, options, subtypesBrowser, defaultValue);
        (typeArborescence != null) ? this._type = typeArborescence : this._typeArborescence = 'arborescence'; //par défaut toutes les zones
        this.createSearchZone(cheminSite + this._type + '/liste/all/autocompleter');
        this.createSubtypeBrowser();
    }
});

var iZoneBrowser = Class.create(iMetaBrowser, {
    initialize: function($super, element, object, directLocations, options, typeZone, subtypesBrowser, defaultValue, allowMultipleValues) {
        $super(element, object, options, subtypesBrowser, defaultValue);
        (typeZone != null) ? this._type = typeZone : this._type = 'zone'; //par défaut toutes les zones
        this.createSearchZone(cheminSite + this._type + '/liste/all/autocompleter');
        this.createSubtypeBrowser();
        if (directLocations != null && directLocations.length > 0) { this.createDirectLocationLinks(directLocations); };
    },
    createDirectLocationLinks: function(locations) {
        var directLinks = new Element("Div"); directLinks.innerHTML += "Accés direct à:<br/>";
        for (var i = 0; i < locations.length; i++) { var monLien = new Element("a", { "href": "javascript:void(0)" }); monLien.identify(); monLien.appendChild(document.createTextNode(locations[i])); monLien.addClassName("ressource"); monLien.observe("click", function(e) { this._inputZone.value = Event.element(e).innerHTML; this.search(); } .bindAsEventListener(this)); directLinks.appendChild(document.createTextNode(" ")); directLinks.insert(monLien); }
        this._element.insert(directLinks);
    },
    search: function($super, e) { if (this._object != null) { this._object.geolocaliser(this.value()); } },
    ajouterNouveauLieu: function(lieu) { },
    addText: function($super) { this._element.insert("<br/><i>(Nom ou code postal)</i>"); }

});