
/**
* Quelques définitions liées à autocompletion
*/
var inputHEIGHT=20;
var divMere_completion = 'content'; //id de la div devant contenir le div de completion
var all_completion_handlers={}; //garde les handlers des controls


function lookup_completion_handler (id){
    return all_completion_handlers[id];
};


function completion_resize (e){
	for(id in all_completion_handlers) {
		all_completion_handlers[id].positionCompletion();
	}
};

//redmisensionnement de la fenetre implique repositionnement des autocomplete
window.onresize = completion_resize;

/* Fin définition des parametres autocompletion*/

//Définitions des controls



(function($){


 //Conrtol de base avec des fonctions de base
 var Control= {
   init: function(options, elem){
     /*Fixer quelques données par defaut communes aux controles*/
	 this.alert_obligatoire = 'Ce champ est obligatoire';
     this.alert_email = 'Le format est incorrect';
     this.alert_telephone = 'Le format est incorrect';
     this.alert_date = 'Le format est incorrect';
     this.alert_numeric = 'Le format doit être numérique';
     this.alert_number = 'Le format doit être un nombre';

     this.css_obligatoire = 'obligatoire';
     this.css_label_obligatoire = "<font color='#B42727'> * </font>";

     this.elem  = elem; /*objet DOM*/
     this.$elem = $(elem); /*objet Jquery*/
     this.options = options;


     /**/
     this.display_obligatoire= function(){
        if (this.options.obligatoire && this.options.obligatoire == 'true') {
         	//m
         	this.$elem.addClass(this.css_obligatoire);

    		 var label_obligatoire = this.css_label_obligatoire;

         	this.$elem.parents('[class$=_inner_container]').siblings().each(function(){
    	      if ($(this).html().trim() != '') {
    	        /*
				var reg = new RegExp(/<font[^>]*>[^<]*<\/font>/);
    	        if (!$(this).html().match(reg)) $(this).append(label_obligatoire);
				
				*/
				var span_obligatoire = "<span id='obligatoire'>"+ label_obligatoire + "</sapn>";
				var ctrl_obligatoire = $(this).find('span#obligatoire');
				if (ctrl_obligatoire.length > 0) {
					$(this).find('span#obligatoire').html(label_obligatoire);
				} else {
					$(this).append(span_obligatoire);
				}
				
    	      }
    	     });
        }

        if (this.options.obligatoire && this.options.obligatoire == 'false') {
             //m
         	this.$elem.removeClass(this.css_obligatoire);

    		 var label_obligatoire = this.css_label_obligatoire;

         	this.$elem.parents('[class$=_inner_container]').siblings().each(function(){
    	      if ($(this).html().trim() != '') {
    	        //$(this).append(label_obligatoire);
    	        /*var reg = new RegExp(/<font[^>]*>[^<]*<\/font>/);
    	        $(this).html($(this).html().trim().replace(reg, ''));*/
				var ctrl_obligatoire = $(this).find('span#obligatoire');
				if (ctrl_obligatoire.length > 0) {
					ctrl_obligatoire.html('');
				}
    	      }
    	     });

    	     this.flush_error();
        }
     }

     this.setObligatoire=function(bool){
        if (bool && (bool == true)) {
            this.options.obligatoire='true';
        } else this.options.obligatoire='false';

        this.display_obligatoire();
     }

     this.display_obligatoire();

     /*
	   !!!Important : Ajouter le control au formulaire
      */
      //alert('tagname=.' + this.elem.tagName);
      if (this.elem.tagName.toUpperCase() != 'FORM') {
      	    var crtl_form =this.getFormulaire(1);
      	    //&& PageMng.findForm(ctrl_form.attr('id'))
            if (crtl_form) {
                crtl_form.addControl(this.$elem.attr('id'),this);
      	    } else{
      	    //on l'ajoute à la page
      	     //alert('ajout de ' + this.$elem.attr('id') + ' a la page');
      	      PageMng.addControl(this.$elem.attr('id'),this);
      	    }

      }

   },
   getDomElt:function(){
     return this.elem;
   },
   getJqueryElt:function(){
    return this.$elem;
   },
   //retrouver le bloc devant contenir les alertes d'erreur
   get_ctrl_error : function(){
    //return  $(elt).parent().siblings().css('display','');
    return  this.$elem.siblings('[class=requiredError]').css('display','');
  },
  flush_error:function(){
    this.get_ctrl_error().html('').css('display','none');
  },
  validate:function(){
	  this.flush_error();
      var erreur = false;
	  if (this.options.obligatoire && this.options.obligatoire == 'true') {
		  var erreur= (this.getValue().trim() == '' ? true : false);
		  if (erreur) {
			this.get_ctrl_error().html(this.alert_obligatoire);
      	    this.elem.focus();
		  }
      }
      //validation suivant une expression reguliere
      if ((!erreur) && this.options.expression && (this.getValue() != '')) {
		var erreur = !isRegulierValid(this.getValue(),this.options.expression);
     	if (erreur) {
			this.get_ctrl_error().html(this.options.erreur);
      	    this.elem.focus();
      	    //erreur = true;
		}
      }

      //par defaut retourne est valide
      return !erreur;
  },
  getId:function(){
   return this.$elem.attr('id');
  },
  getValue:function(){
   return this.$elem.val().trim();
  },
  /*retrouve l'objet Formulaire stoqué dans PageMng*/
  getFormulaire:function(noalert){
	var form = this.$elem.parents('form:first');
    if (form.length == 0) {
       if (!noalert) {
    	alert('Le control doit inclus dans un form');
        }
    	return null;
    }
    return PageMng.getForm(form.attr('id'));
  }
 }



 var Text = $.extend(true,{},Control,{

    init:function(options,elem){
       /*Enregistrment des fonctions parents*/
	   this._superInit= Control.init;
	   this._superValidate = Control.validate;

	   this._superInit(options,elem);
       /*this.$elem.click(function(){
         alert('click on me');
       });*/

       /**/

       /*
	   !!!Important : Ajouter le control au formulaire
       */
       //this.getFormulaire().addControl(this.getId(),this);
    },
	validate:function(){
      return this._superValidate();
    }
 });




 /*Control Date*/
 var InputDate = $.extend(true,{},Text,{

   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Text.init;
     this._superValidate=Text.validate;

	 this._superInit(options,elem);

     var datepick= this.$elem.datepicker({changeMonth: true,
		 	changeYear: true,
		 	buttonImage: '/squelettes/images/calendar.gif',
		 	beforeShow: function() {}//pas suffisant pour changer zindex
     });//date Picker
     //$.datepicker.dpDiv.css("z-index",200);
     /*
	  !!!Important : Ajouter le control au formulaire
     */
     //this.getFormulaire().addControl(this.getId(),this);
   },
   validate:function(){
     var no_erreur=true;
	 var no_erreur = this._superValidate();

     if (no_erreur && (this.getValue() != '')) {
		no_erreur = isDate(this.getValue());
     	if (!no_erreur) {
			this.get_ctrl_error().html(this.alert_date);
      	    this.elem.focus();
		}
     }
     //validation valeur minimale
      if ((no_erreur) && this.options.min_value && (this.options.min_value != '') && (this.getValue() != '')) {
          var date_min = this.options.min_value.split('/');
          var min = new Date();
          min.setDate(date_min[0]);
          min.setMonth(date_min[1]-1);
          min.setFullYear(date_min[2]);

          var ladate = new Date();
          var date_encours = this.getValue().split('/');
          ladate.setDate(date_encours[0]);
          ladate.setMonth(date_encours[1]-1);
          ladate.setFullYear(date_encours[2]);

          if (ladate.getTime() <= min.getTime()) {
            no_erreur = false;
            this.get_ctrl_error().html(this.options.min_value_message);
      	    this.elem.focus();
          }
      }
      //validation valeur maximale
      if ((no_erreur) && this.options.max_value && (this.options.max_value!='') && (this.getValue() != '')) {
          var date_max = this.options.max_value.split('/');
          var max = new Date();
          max.setDate(date_max[0]);
          max.setMonth(date_max[1]-1);
          max.setFullYear(date_max[2]);

          var ladate = new Date();
          var date_encours = this.getValue().split('/');
          ladate.setDate(date_encours[0]);
          ladate.setMonth(date_encours[1]-1);
          ladate.setFullYear(date_encours[2]);

          if (ladate.getTime() >= max.getTime()) {
            no_erreur = false;
            this.get_ctrl_error().html(this.options.max_value_message);
      	    this.elem.focus();
          }
      }
      //validation valeur maximale
      if ((no_erreur) && this.options.min_control && (this.getValue() != '') && (this.getFormulaire().getControl(this.options.min_control).getValue() != '')) {
          var date_ctrl = this.getFormulaire().getControl(this.options.min_control).getValue().split('/');
          var min = new Date();
          min.setDate(date_ctrl[0]);
          min.setMonth(date_ctrl[1]-1);
          min.setFullYear(date_ctrl[2]);

          var ladate = new Date();
          var date_encours = this.getValue().split('/');
          ladate.setDate(date_encours[0]);
          ladate.setMonth(date_encours[1]-1);
          ladate.setFullYear(date_encours[2]);

          if (ladate.getTime() <= min.getTime()) {
            no_erreur = false;
            this.get_ctrl_error().html(this.options.min_control_message);
      	    this.elem.focus();
          }
      }
     return no_erreur;
   }
 });

 /*Control Téléphone*/
 var InputTelephone = $.extend(true,{},Text,{

   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Text.init;
     this._superValidate=Text.validate;

	 this._superInit(options,elem);

     /*
	  !!!Important : Ajouter le control au formulaire
     */
     //this.getFormulaire().addControl(this.getId(),this);
   },
   validate:function(){
     var no_erreur=true;
	 var no_erreur = this._superValidate();

     if (no_erreur && (this.getValue() != '')) {
		var no_erreur = verifierTelephone(this.getValue());
     	if (!no_erreur) {
			this.get_ctrl_error().html(this.alert_telephone);
      	    this.elem.focus();
      	    //erreur = true;
		}
     }
     return no_erreur;
   }
 });

 /*Control Email*/
 var InputEmail = $.extend(true,{},Text,{

   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Text.init;
     this._superValidate=Text.validate;

	 this._superInit(options,elem);

     /*
	  !!!Important : Ajouter le control au formulaire
     */
     //this.getFormulaire().addControl(this.getId(),this);
   },
   validate:function(){
     var no_erreur=true;
	 var no_erreur = this._superValidate();
//alert('test obligatoire sur ' + this.getId() + '=' + no_erreur);
     if (no_erreur && (this.getValue() != '')) {
		//alert('test format email sur ' + this.getId());
        var no_erreur = verifierEmail(this.getValue());
     	if (!no_erreur) {
			this.get_ctrl_error().html(this.alert_email);
      	    this.elem.focus();
      	    //erreur = true;
		}
     }
     //alert('resultat erreur ' + this.getId() + '=' + !erreur);
     return no_erreur;
   }
 });

  /*Control Numeric*/
 var InputNumber = $.extend(true,{},Text,{

   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Text.init;
     this._superValidate=Text.validate;

	 this._superInit(options,elem);

     /*
	  !!!Important : Ajouter le control au formulaire
     */
     //this.getFormulaire().addControl(this.getId(),this);
   },
   validate:function(){
     var no_erreur=true;
	 var no_erreur = this._superValidate();

     if (no_erreur && (this.getValue() != '')) {
		var no_erreur = isNumber(this.getValue().replace('.','x').replace(',','.'));
		//on ne veut pas de .
     	if (!no_erreur) {
			this.get_ctrl_error().html(this.alert_number);
      	    this.elem.focus();
		}
     }
     return no_erreur;
   }
 });

 var InputNumberValidation = $.extend(true,{},InputNumber,{
  init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=InputNumber.init;
     this._superValidate=InputNumber.validate;

	 this._superInit(options,elem);
   },
   validate:function(){
     var no_erreur=true;
	 var no_erreur = this._superValidate();
	 if ((no_erreur) && this.options.min_value && (this.options.min_value != '') && (this.getValue() != '')) {
	   if (this.getValue() < parseFloat(this.options.min_value)) {
	       no_erreur = false;
	       this.get_ctrl_error().html(this.options.min_value_message);
      	   this.elem.focus();
	   }
	 }
	 return no_erreur;
   }
 });

 /*Control Numeric*/
 var InputNumeric = $.extend(true,{},Text,{

   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Text.init;
     this._superValidate=Text.validate;

	 this._superInit(options,elem);

     /*
	  !!!Important : Ajouter le control au formulaire
     */
     //this.getFormulaire().addControl(this.getId(),this);
   },
   validate:function(){
     var no_erreur=true;
	 var no_erreur = this._superValidate();

     if (no_erreur && (this.getValue() != '')) {
		var no_erreur = isNumeric(this.getValue());
     	if (!no_erreur) {
			this.get_ctrl_error().html(this.alert_numeric);
      	    this.elem.focus();
		}
     }
     return no_erreur;
   }
 });

 /*Control Expression reguliere*/
 var InputExpRegulier = $.extend(true,{},Text,{
   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Text.init;
     this._superValidate=Text.validate;

	 this._superInit(options,elem);

    /*
	  !!!Important : Ajouter le control au formulaire*/
     //this.getFormulaire().addControl(this.getId(),this);

   },
   validate:function(){
     var no_erreur=true;
	 var no_erreur = this._superValidate();

     if (no_erreur && (this.getValue() != '')) {
		var no_erreur = isRegulierValid(this.getValue(),this.options.expression);
     	if (!no_erreur) {
			this.get_ctrl_error().html(this.options.erreur);
      	    this.elem.focus();
      	    //erreur = true;
		}
     }
     return no_erreur;
   }
 });

 /*Control Login dont la on verifie l'existence dans la base*/
 var InputLogin = $.extend(true,{},Text,{
   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Text.init;
     this._superValidate=Text.validate;

	 this._superInit(options,elem);


	 //on doit verifier que si on a une nouvelle valeur
     this.old_value = this.getValue();


    /*
	  !!!Important : Ajouter le control au formulaire*/
     //this.getFormulaire().addControl(this.getId(),this);

   },
   validate:function(){
     var no_erreur=true;
	 var no_erreur = this._superValidate();

     if (no_erreur && (this.getValue() != '')) {
        var canal = this.options.canal; //formualaire de validation
        var form = $("#" + canal); //PageMng.getForm(canal);
        var attribut = this.options.attribut;
        var that=this;
        //form.getJQueryElt().find("#login").attr(this.getValue());

        options = {'success':function(data){
          //form = $("#" + canal);
          $("#" + canal).parents('div:first').html(data);
          //alert(form.find("#resultat").val());

          if ($("#" + canal).find("#resultat").val() == '1') {
              no_erreur = false;
              that.get_ctrl_error().html(that.options.message);
          } else no_erreur = true;
          return no_erreur;
         },async:false
        };

        form.unbind('submit');
        if (this.getValue() != this.old_value) {
            form.find("#attribut").val(attribut);
            form.find("#valeur").val(this.getValue());
            form.ajaxForm(options);
            form.submit();
        }
     }
     return no_erreur;
   }
 });

 /*Control Login dont la on verifie l'existence dans la base*/
 var InputPassword = $.extend(true,{},Text,{
   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Text.init;
     this._superValidate=Text.validate;

	 this._superInit(options,elem);


	 //on doit verifier que si on a une nouvelle valeur
	 this.modification=false;
     if (this.getValue() != '') {
         //on est en modifcation
         this.modification=true;
         //effacer la valeur
         this.$elem.val('');
     }


    /*
	  !!!Important : Ajouter le control au formulaire*/
     //this.getFormulaire().addControl(this.getId(),this);

   },
   validate:function(){

     var no_erreur=true;
     if ((this.modification==false) || (this.modification==true && this.getValue() != '')) {
        var no_erreur = this._superValidate();
        if (no_erreur && (this.getValue() != '')) {
          if (this.getValue().length<8) {
              this.get_ctrl_error().html("le mot de passe  doit dépasser 8 caracteres");
              no_erreur =false;
          }
          //le mot de passe doit comporter des chiffres
          var reg= new RegExp(/[\d+]/) ;
          if (!this.getValue().match(reg)) {
              this.get_ctrl_error().html("le mot de passe  doit comporter des chiffres");
              no_erreur =false;
          }

        }
     }

     return no_erreur;
   }
 });

  /*Control de confirmation d'un autre controle*/
 var InputConfirmation = $.extend(true,{},Text,{
   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Text.init;
     this._superValidate=Text.validate;

	 this._superInit(options,elem);





    /*
	  !!!Important : Ajouter le control au formulaire*/
     //this.getFormulaire().addControl(this.getId(),this);

   },
   validate:function(){


     var no_erreur=true;

     //var no_erreur = this._superValidate();

          if (this.getValue() != this.getFormulaire().getControl(this.options.confirm_ctrl).getJqueryElt().val()) {
              this.get_ctrl_error().html(this.options.message);
              no_erreur =  false;
          }

     return no_erreur;
   }
 });

  /*Control Fenetre carto*/
 var DivFenetreCarto = $.extend(true,{},Control,{
   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Control.init;

	 this._superInit(options,elem);

	 this.form=PageMng.getForm("cartoform");

	 this.mapID=this.options.mapID;

	 this.adresses = this.options.adresses;
	 
	 
	 /*this.markerManager = new MarkerManager(map2);  
	 
	 */

	 //this.$elem.dialog({modal: true, overlay: { opacity: 0.5, background: "black" }}) ;
	 //this.$elem.dialog({autoOpen: false}) ;
	 var that = this;

	 /*if (this.$elem.is(':visible')) {
	     $("#info_carto_communaute").clone().attr('id','info_carto_communaute_cloned').appendTo(map1.getPane(G_MAP_FLOAT_SHADOW_PANE));
	 }*/



	 this.$elem.find("#fermer_carto").click(function(){
	   that.close();
	 });

	 $("#form_info_carto_communaute").find("#operid").val('');

	 //initialisation du mode
	 this.mode = $("#cartoform").find("#mode").val();


	 if ((CTXT_CARTO.is_ondemand == false) || (CTXT_CARTO.is_open == true)) {
	     //la carte est sur demande mais pas encore lancé
	      this.loadGoogleMap();
	 }

   },
   //TODO: position close to caller
   open:function(caller){
     this.$elem.show();
     $("#cw_gedmask").show();
     if ((CTXT_CARTO.is_ondemand == true) && (CTXT_CARTO.is_open == false)) {
	     //la carte est sur demande mais pas encore lancé
	      this.adresses=[];
	      this.loadGoogleMap();
	 }
     //soumettre
     /*if (pan_info) {
	     $("#info_carto_communaute").clone().attr('id','info_carto_communaute_cloned').appendTo(map1.getPane(G_MAP_FLOAT_SHADOW_PANE));
	 }*/
   },
   close:function(){
    this.$elem.hide();
    $("#cw_gedmask").hide();
    //$("#oper_session").val(2);
   },
   clear_markers :function(){
		/*map2.clearMarkers();
		this.clusters = [];
		return; 
		*/
		/*this.markerManager.clearMarkers();
		this.all_markers= [];
		this.markerManager.refresh(); 
		return;
		*/
		
		//for(var i=0; i<this.clusters.length; i++){ 
		var cluster_mng = CTXT_CARTO.cluster_mng;
		if (CTXT_CARTO.cluster_mng) {
			//alert('remove Nbr de markers: ' + CTXT_CARTO.cluster_mng.getTotalMarkers());
			CTXT_CARTO.cluster_mng.clearMarkers();
			//cluster_mng.setMap(null);
			
		}
		CTXT_CARTO.markers = [];
		//}
		//map2.clearOverlays();
		
   },
   setExtent : function(){
		
        var map_comm = eval('map' + this.options.mapID);
		
		this.adresses=[];
		
		//zoomer sur l'extent
          if ((CTXT_CARTO.xmin!=null) &&(CTXT_CARTO.xmax!=null) && (CTXT_CARTO.ymin!=null) && (CTXT_CARTO.ymax!=null)){
            var extent = new GLatLngBounds(new GLatLng(CTXT_CARTO.xmin, CTXT_CARTO.ymin), new GLatLng(CTXT_CARTO.xmax, CTXT_CARTO.ymax));
            map_comm.zoom = map_comm.getBoundsZoomLevel(extent);
            if (map_comm.zoom > 20) map_comm.zoom = 15;
           //if (map_comm.zoom > 20) map_comm.zoom =7;
            map_comm.setCenter(extent.getCenter(),map_comm.zoom);
          }

        /* retinitialiser l'extent*/
        CTXT_CARTO.xmin= null;
        CTXT_CARTO.xmax= null;
        CTXT_CARTO.ymin= null;
        CTXT_CARTO.ymax= null;
        $("#attente").hide();
		
		//poser le cluster
		var style= CTXT_CARTO.markers_style_utilisateur;
		if (this.getMode() == 2 ) style= CTXT_CARTO.markers_style_action;
		if (this.getMode() == 3 ) style= CTXT_CARTO.markers_style_display;
		if (this.getMode() == 4 ) style= CTXT_CARTO.markers_style_suivi;
		
		
		style = CTXT_CARTO.markers_style_default;
		
	
		//CTXT_CARTO.cluster_mng = new MarkerClusterer(map_comm, CTXT_CARTO.markers, {maxZoom: 10});
		CTXT_CARTO.cluster_mng = new MarkerClusterer(map_comm, CTXT_CARTO.markers, {maxZoom: 10, styles: style});
		//markerClusterer = new MarkerClusterer(map, markers, {maxZoom: zoom, gridSize: size, styles: styles[style]});
		//alert('len=' + this.clusters.length);
   },

   showLoading : function(){
    //$("#map"+this.options.mapID).find("#attente" + this.options.mapID).show();
    //$("#attente" + this.options.mapID).show();
    //$("#map_loader_msg").show();  
   },
   hideLoading : function(){
    //$("#attente" + this.options.mapID).hide(); 
    
   },
   loadGoogleMap :function() {
    if (CTXT_CARTO.is_open == false) {
        //alert('chargement de la carte');
        eval('load' + this.options.mapID + '()');
       $("#map"+this.options.mapID).append('<div id="attente"'+ this.options.mapID + ' style="position: absolute; z-index: 1000; top: 0; left: 0; background-color: #FFFFFF; filter:alpha(opacity=70); -moz-opacity: 0.7; opacity: 0.7;width: 100%; height: 100%"><span style="display: block; width: 100%; height: 100%; background: transparent url(plugins/gis/img_pack/attente.gif) center center no-repeat;"></span></div>');
        //alert(this.options.mapID);
        var map_comm = eval('map' + this.options.mapID);
        $("#info_carto_communaute").clone().attr('id','info_carto_communaute_cloned').appendTo(map_comm.getPane(G_MAP_FLOAT_SHADOW_PANE));

        CTXT_CARTO.is_open = true;

        this.showLoading();
    }

    this.loadGoogleMarker(this.adresses);
   },

   loadGoogleMarker: function(adresses_participants){
     
    var map_comm = eval('map' + this.options.mapID);
	var markers_lot= [];
    if (adresses_participants.length > 0){
          //alert('chargement des marker '+adresses_participants.length);
          //alert('deb: xmin=' + CTXT_CARTO.xmin + ' xmax=' + CTXT_CARTO.xmax);
          var xmin=CTXT_CARTO.xmin;
          var xmax=CTXT_CARTO.xmax;
          var ymin=CTXT_CARTO.ymin;
          var ymax=CTXT_CARTO.ymax;
          for(var index=0; index<adresses_participants.length;index++){
            adresse = adresses_participants[index];

        	var Glatitude = parseFloat(adresse['lat']);
        	var Glongitude = parseFloat(adresse['lng']);


        	//initialiser pour la premmier fois
            xmin = (xmin==null?Glatitude:xmin);
        	xmax = (xmax==null?Glatitude:xmax);
        	ymin = (ymin==null?Glongitude:ymin);
        	ymax = (ymax==null?Glongitude:ymax);

        	xmin = (xmin > Glatitude ? Glatitude : xmin);
        	xmax = (xmax < Glatitude ? Glatitude : xmax);
        	ymin = (ymin > Glongitude ? Glongitude : ymin);
        	ymax = (ymax < Glongitude ? Glongitude : ymax);
        	operateur = adresse['operid'];

        	if ((Glatitude!='') && (Glongitude!='')){
            	var point = new GLatLng(Glatitude, Glongitude);
            	//var picto= "squelettes/images/marker/marker_m2_vert_essai.png";
            	var picto= "";
                if (adresse['picto'] && (adresse['picto'] != '')){
                    picto=adresse['picto'];
                }

                var myIcon = new GIcon(G_DEFAULT_ICON,picto);
                //pour afficher les shadow, commenter
                myIcon.shadow="";
                var marker = new GMarker(point,{icon:myIcon});

                //map_comm.addOverlay(marker);
				//maj du 21/09/2011 user clluster
				
				
                this.personnaliser(marker,point,operateur);
				//markers_lot.push(marker);
				CTXT_CARTO.markers.push(marker);
        	}

        	CTXT_CARTO.xmin= xmin;
        	CTXT_CARTO.xmax = xmax;
        	CTXT_CARTO.ymin = ymin;
        	CTXT_CARTO.ymax = ymax;

        	//alert('fin: xmin=' + CTXT_CARTO.xmin + ' xmax=' + CTXT_CARTO.xmax);

        	/*if (index==0) {
        	    alert('xmin=' + this.xmin + ' xmax=' + this.xmax + ' ymin=' + this.ymin + ' ymax=' + this.ymax);
        	}*/

          }
		  
		  
		  
		  /*this.markerManager.addMarkers(this.all_markers); 
		  this.markerManager.refresh(); 
		  */
		  
        }
        this.hideLoading();
        
   },



   personnaliser : function(marker,point,operateur){

		 GEvent.addListener(marker,"click", function() { //click mouseover
			PageMng.getControl('fenetre_carto').showInfo(operateur,marker);
         });
         /*GEvent.addListener(marker,"mouseout", function() {
            PageMng.getControl('fenetre_carto').hideInfo();
         });*/
     },


   setDemand:function(){
      //on emande de lancer la carte
     $("#cartoform").find("#demand").val(1);
   },
   showInfoOLD:function(operateur,point){
     //Survol sur un picto
     var div_info = $("#info_carto_communaute");
     div_info.html('').show();
     var containerID = map2.getContainer().getAttribute('id');
		  var taille= taille_ecran();
          var retrait= (taille['width'] - 860) /2; //860 correspond a la  largeur de la page globale du site
          var position_left = getOffsetPosition(containerID,'Left');

          position_left -= retrait;
		  var mapleft = position_left; //getOffsetPosition("map2", "Left");
		  var maptop = getOffsetPosition(containerID, "Top");
		  //this.getWindowInfo().innerHTML= html;
		  //div_info.css('top',maptop + point.y + 'px');
		  //div_info.css('left',mapleft + point.x + 'px');
		  div_info.css('top',maptop + 'px');
		  div_info.css('left',mapleft + 'px');

		  //alert(containerID + '  -' +  maptop + ' ' + mapleft);

		  $("#form_info_carto_communaute").find("#operid").val(operateur);
		  /*$("#form_info_carto_communaute").find("#posTOP").val(maptop);
		  $("#form_info_carto_communaute").find("#posLEFT").val(mapleft);*/
		  //var mode = this.getMode();
          PageMng.getForm("form_info_carto_communaute").getJqueryElt().find("#mode").val(this.mode).submit();
   },
   showInfo:function(operateur,marker){
     //Survol sur un picto 
     //map2.panTo(marker.getPoint());
     var div_info =$("#info_carto_communaute_cloned");
     var form_info = $("#form_info_carto_communaute");

     var markerOffset = map2.fromLatLngToDivPixel(marker.getPoint());

     this.current_point = marker.getPoint(); //garder le point en cours;
//alert(markerOffset.y + ' - ' + markerOffset.x);
     div_info.css({ top:markerOffset.y, left:markerOffset.x });
     var val_en_cours = form_info.find("#operid").val();
     if (val_en_cours != operateur) {
         //on retourne sur le serveur
          div_info.html("<img src='squelettes/images/loading.gif' style='width:30px;height:30px'>");
          //L'utilisateur doit attendre un certain temps sur le marker
          div_info.show();

          form_info.find("#operid").val(operateur);
          form_info.find("#mode").val(this.mode);
          PageMng.getForm("form_info_carto_communaute").submit();
     } else map2.openInfoWindowHtml(this.current_point,this.current_data);
   },
   getMode:function(){
    return $("#cartoform").find("#mode").val();
   },
   setMode:function(mode){
     $("#cartoform").find("#mode").val(mode);
     this.mode=mode;
   },
   hideInfo:function(){
     $("#info_carto_communaute_cloned").hide();
   },
   dataAvailable:function(data){
     /*var div_info = $("#info_carto_communaute_cloned");
     div_info.html(data);*/
     this.current_data= data;

     $("#info_carto_communaute_cloned").hide();
     map2.openInfoWindowHtml(this.current_point,this.current_data);

	 },
	flush:function(){
		/* decommenter pour ne pas garder la selection
		$("#cartoform").find("input[type=checkbox]").attr('checked', true);
		$("#cartoform").find("select option:selected").attr('selected', false);
		*/
		var form = $("#cartoform");
		form.find("input[id^=action_]").attr('checked', true);
		form.find("input[id^=class_]").attr('checked', true);
		form.find("input[id^=coll_]").attr('checked', true);
		//map2.clearOverlays();
		this.clear_markers();
		this.showLoading();
	},
   setUtilisateur:function(){

    this.flush();
    this.setMode(1);
    $("#cartoform").submit();
    //lancer_recherche_picto();
   },
   setDisplay:function(){
    this.flush();
    this.setMode(3);
    $("#cartoform").submit();
    //lancer_recherche_picto();
   },
   setSuivi:function(){
    this.flush();
    this.setMode(4);
    $("#cartoform").submit();
    //lancer_recherche_picto();
   },
   setAction:function(actions){
     //this.elem.reset();//enlever les anciennes valeurs
		
     this.flush();
     this.form.getJqueryElt().find("input[id^=action]").each(function(){
       var id= $(this).attr('id').replace('action_','');
       if (actions.inArray(id)) {
          //$(this).attr('checked', true);
          $("#cartoform").find("#" + $(this).attr('id')).attr('checked', true);
       }
     });
	 
	


     this.setMode(2);
     $("#cartoform").submit();
     //lancer_recherche_picto();

   }
 });

 /*Control Fenetre carto*/
 var LanceurCarto = $.extend(true,{},Control,{
   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Control.init;

	 this._superInit(options,elem);

	 this.$elem.click(function(){
	   //rechercher carto et le lancer
	   PageMng.getControl('fenetre_carto').show();
     })

   }
 });

 /*Control Date*/
 var InputTextEnrichi = $.extend(true,{},Text,{

   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Text.init;
     this._superValidate=Text.validate;

	 this._superInit(options,elem);

	 this.extra_buttons = ((this.options.extra_buttons != 'undefinded') ? "|," + this.options.extra_buttons + "," : "");
	 //this.extra_buttons = "link,image";

     this.$elem.tinymce({
    // Location of TinyMCE script
			script_url : './plugins/iad-form/javascript/tinymce/jscripts/tiny_mce/tiny_mce.js',

    // General options
			theme : "advanced",
			//plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",
			plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr," +
                        "advimage,advlink,emotions,iespell,inlinepopups,insertdatetime," +
                        "preview,media,searchreplace,print,contextmenu,paste," +
                        "directionality,fullscreen,noneditable,visualchars,nonbreaking," +
                        "xhtmlxtras,template",

			// Theme options
			//theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons1 :"undo,redo,removeformat," +
                     "|,bold,italic,underline,strikethrough," +
                     "|,numlist,bullist," + this.extra_buttons,
            theme_advanced_buttons2 : '',
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_resizing : true,
			//theme_advanced_statusbar_location : "bottom", 


			// Example content CSS (should be your site CSS)
			content_css : "css/content.css",

			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
			external_link_list_url : "lists/link_list.js",
			external_image_list_url : "lists/image_list.js",
			media_external_list_url : "lists/media_list.js"
       });
     /*
	  !!!Important : Ajouter le control au formulaire
     */
     //this.getFormulaire().addControl(this.getId(),this);
   },
   validate:function(){
     return this._superValidate();
   }
 });

 /*Control GroupRadio*/
 var GroupRadio = $.extend(true,{},Control,{

   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Control.init;
	 this._superValidate=Control.validate;

	 this._superInit(options,elem);

	 this._currentvalue = "";


	 var that=this;

     this.$elem.find("input:radio").each(function(){
      $(this).click(function(){
        if (that._currentvalue == $(this).attr('value')) {
          //il etait sélectionné, faire cancel
          $(this).attr('checked',false);
          that._currentvalue = "";
		  that.setValue('');
        } else {
          that.setValue($(this).attr('value'));
        }
 	  });
	  //si il est choisi, alimenter le div qui garde sa valeur
	  if ($(this).is(":checked")) {
	  	 that.setValue($(this).attr('value'));
	  }
     });

	 /*
	  !!!Important : Ajouter le control au formulaire
     */
     //this.getFormulaire().addControl(this.getId(),this);
   },
   updateValue:function(value){
     var that = this;
     this.$elem.find("input:radio").each(function(){
       if ($(this).attr('value') == value) {
           $(this).attr('checked',true);
           that.setValue(value);
       } else {
          $(this).attr('checked',false);
       }
     })
   },
   setValue:function(value){
     this._currentvalue= value;
   },
   getValue:function(){
	 return this._currentvalue;
   },
   validate:function(){
	 return this._superValidate();
   }
 });

  /*Control GroupRadio*/
 var ChoixMultiple = $.extend(true,{},Control,{

   init:function(options,elem){
     /*Enregistrment des fonctions parents*/
	 this._superInit=Control.init;
	 this._superValidate=Control.validate;

	 this._superInit(options,elem);

	 this._currentvalue = "";

	 var that=this;

     this.checked = [];
   //champ hidden qui contient les valeurs choisis
    this.id_hidden = this.getId() + "_choixmultiple";
    //this.champs_valeurs = $(this).find("#" + id_hidden);


   this.$elem.find("input:checked").each(function(){
      that.add($(this).attr('value'));
   });


   //
   this.$elem.find("input[type=checkbox]").each(function(){
     	$(this).click(function(){
     	   if ($(this).is(":checked")) {
     	   	 that.add($(this).attr('value'));
     	   } else that.remove($(this).attr('value'));

     	   //la valeur du control change
     	   that.update();
     	});
   });

   //la valeur du control change
   this.update();


   /*
	  !!!Important : Ajouter le control au formulaire
    */
    //this.getFormulaire().addControl(this.getId(),this);
   },
   add:function(elt){
     this.checked.push(elt);
   },
   remove:function(elt){
     var arr = []
     for (var i=0; i<this.checked.length; i++){
       if (this.checked[i] != elt) {
       	arr.push(this.checked[i]);
       }
     }
     this.checked=arr;
   },
   //mettre dans le controle caché les valeurs selectionnés
   update:function(){
     var choisis = this.checked.join(",");
     //var id_hidden = champs_valeurs;
     //alert(id_hidden);
	 this.$elem.find("#" + this.id_hidden).attr("value", choisis);
   },
   //mettre dans le controle caché les valeurs selectionnés
   updateValue:function(values){
     var choisis = "";
     this.$elem.find("input[type=checkbox]").each(function(){
        if (values.inArray($(this).attr('value'))) {
            $(this).attr('checked',true);
            choisis += (choisis != "" ? "," : "") + $(this).attr('value');
        } else  $(this).attr('checked',false);
     });

     this.$elem.find("#" + this.id_hidden).attr("value", choisis);

     //this.update();
   },
   getValue:function(){
	 return this.$elem.find("#" + this.id_hidden).attr("value");
   },
   validate:function(){
	 return this._superValidate();
   }
 });
 
 var Autocomplete = $.extend(true,{},Text,{
	init:function(options,elem){
		/*Enregistrment des fonctions parents*/
		this._superInit=Text.init;
		this._superValidate=Text.validate;

		this._superInit(options,elem);
		
		/*init propre a autocomplete*/
		this.letterStart = (options.letterStart ? options.letterStart :2);
		this.help = (options.help ? options.help :"");

		this._controlID = this.getId();

		/*Eviter que le navigateur ne garde les anciennes saisies*/
		document.getElementById(this.getId()).setAttribute('autocomplete','off');
		
		this.dataControls = (options.dataControls ? options.dataControls : []);
		this.current_dataControls_values = {};

		//les controls dont depend la completion

		//variables internes de la completion
		this._completionValues=new Array();
		this._completion_flag= 0; //requete en cours
		this._queryBd=true;//doit on retourner chercher à la base
		this._completionEnv='';
		this._completionEnvBase ='';

		var div_search = document.createElement('div');
		div_search.id= this.getId() + '_completion';
		div_search.className='search_completion' ;//
		var divMere = document.getElementById(divMere_completion);
		divMere.appendChild(div_search);
		this.completion =div_search; //div devant contenir le resultat de la completion

		//ajouter un div sur action ajax bloquant: par ex lancer la recherche
		div_hid_compl = document.createElement('div');
		div_hid_compl.id= this.getId() + 'hid_completion';
		div_hid_compl.className='search_querying' ;//'div_bassin';
		div_hid_compl.style.visibility="hidden";
		divMere.appendChild(div_hid_compl);
		this.lock_completion =div_hid_compl;
		
		
		/*personnaliser les evenements*/
		var that = this;
		$("#" + this._controlID).keyup(function(evt){
			that.completionChange(evt);
		}).blur(function(e){
			/*var val_en_cours = e.value;
			if (val_en_cours == "") {
				e.value = that.help;
			}*/
			//that.hideCompletion();
		}).focus(function(e){
			/*var val_en_cours = e.value;
			if (val_en_cours == that.help) {
				e.value = "";
			}*/

			if (that.is_controls_datas_changed()) {
				that._completionValues=new Array(); //forcer la recerche depuis la base
				that.hideCompletion();
				//handler._elt.value='';
			}
		});
		
		//initialiser le handler
		this.setCompletionEnv(this.options.source);

		this.set_datacontrols_values();
		//garder les datacontrols;

		all_completion_handlers[this._controlID] = this;
			
   },
   get_data_value:function (index){
		if (this._completionValues.length == 0) {
			return "";
		}
		//return this._completionValues[index];
		return this._completionValues[index]['value'];
    },
	/*donne le texte associé à l'index index
    interfacer pour traiter des données personnalisées
    */
    get_data_text:function (index){
		if (this._completionValues.length == 0) {
			return "";
		}
		//return this._completionValues[index];
		return this._completionValues[index]['text'];
    },
	fire_newvalue : function(opt){
		//on donne la possibilté de recuperer la valeur en cours
		//alert("fire_newvalue, opt.value="+opt.value+", opt.text="+opt.text);
		
		/*mettre la valeur dans le champ caché*/
		var ctrl = this._controlID.replace('_ctrl_autocompletion','');
		$("#"+ctrl).val(opt.value);
    },
	/*refedinition  de cette methode, o
	on prend la valeur sur le control caché*/
	getValue:function(){
		var ctrl = this._controlID.replace('_ctrl_autocompletion','');
		return  $("#"+ctrl).val();
		
	},
	sqlQuery : function(letter){
		var completionAjax = this._completionEnv;
		//var url=completionAjax + (completionAjax.indexOf('?')>0?'&':'?')+'bg='+letter;
		var url=completionAjax + '&bg='+letter;

		//ajouter les datacontrols
		for(var i=0; i<this.dataControls.length; i++){
		   url += '&' + this.dataControls[i] + '=' + $('#' + this.dataControls[i]).val();
		}
		
		var that = this;

		/*var form Handler = this.getFormHandler();
		this.getAjaxRequesHandler().handleRequest(url, [], null);
		*/
		
		
		$.ajax({url:url,
			success : function(data){that.setValue(data)}
		});
		
		//Ajax.get(encodeURI(url), that.updateCompletion);
		//updateCompletion(url,'');
	},
	dataview:function(left){
		//afficher les elements qui correspondent 
		//alert('dataview sur ' + left);
		var completionValues=this._completionValues;
		var id= this._controlID;
		
		var result="";

		var leftLen=left.length;
		if (completionValues.length>0) {
			//alert(completionValues.length);
		}
		

		if (leftLen) { //nv 
			//alert('left=' + left +' car=' + left.toLowerCase()); 
			for(var i=0;i<completionValues.length;i++){
				if (this.get_data_text(i).substring(0,leftLen).toLowerCase()==left.toLowerCase()) {
					//var match=completionValues[i];
					result+='<option value="' + this.get_data_value(i) + '" title="' + this.get_data_text(i) + '">' + this.get_data_text(i) + '</option>';
				}
			}
		}


		var completionItem=this.completion;
		var list_id = id + '_completion_result';

		if (result=="") {
			this.hideCompletion();
		} else {
			//result= "<select id='"+id+"_completion_result' multiple  style='height:100px;width:100%' onblur='lookup_completion_handler(\""+id+"\").hideCompletion();' ondblclick='javascript:lookup_completion_handler(\""+id+"\").checkSelected(this.options.selectedIndex)' onkeyup='lookup_completion_handler(\""+id+"\").choiceCompletion(event, this.options.selectedIndex);'>" + result + "</select>";
			result="<select id='"+list_id+"' multiple  style='height:100px;width:100%' >" + result + "</select>";
			this.positionCompletion();
			this.visibleCompletion();
		}

		completionItem.innerHTML=result;

		if (result!="") {
			//ajouter le handler lié au select
			/*var extra_events = {};
			extra_events[list_id] = {handlerClass:'AutocompletionList', target:this, events:["click","blur","keyup"]};
			pc.addActiveControls(extra_events);
			*/
			
			var that= this;
			$("#"+list_id).unbind().click(function(){
				that.checkSelected(document.getElementById($(this).attr('id')).options.selectedIndex);
			}).blur(function(){
				that.hideCompletion();
			}).keyup(function(evt){
				that.choiceCompletion(evt, document.getElementById($(this).attr('id')).options.selectedIndex);
			});
		}
	},
	/*garder les valeurs des datacontrols
        Si un change, reinitialiser la comlpétion
     */
    set_datacontrols_values : function(){
        for(var i=0; i<this.dataControls.length; i++){
			this.current_dataControls_values[this.dataControls[i]] = $("#" + this.dataControls[i]).val();
		}
	},


	/*teste si les données de controls changent*/
	is_controls_datas_changed : function(){
		var is_changed= false;
		for(var i=0; i<this.dataControls.length; i++){
			if (this.current_dataControls_values[this.dataControls[i]] != $("#" + this.dataControls[i]).val()) {
				is_changed = true;
			}
		}
		if (is_changed) {
			//garder les nouvealles valeurs
			this.set_datacontrols_values();
		}
		return is_changed;
	},


    getTarget : function(e) {
		//return e.target.parentNode();
		var targ;
		if (!e) var e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3) // defeat Safari bug
			targ = targ.parentNode;

		return targ;
	},
	
	/*completion_change*/
	completionChange : function(e){

		var id= e.target.id;

		//var curVal=new String(document.getElementById(id).value.trim());
		var curVal=$('#'+id).val();
		var completionValues = this.completionValues;

		var charCode=(e.charCode)?e.charCode:e.keyCode;
		if (document.getElementById(id+'_completion_result')) {
				var compl_rslt=document.getElementById(id+'_completion_result');
				if ((charCode==40) && (compl_rslt.options.length>0)) {
					compl_rslt.options[0].selected=true;
					compl_rslt.focus();
					return ;
				//fleche bas: selectioner le premeier dans la liste
				}
		}


		if (charCode==13) {
			this.hideCompletion(id);
			return false;
			//submitSearch();
			//touche Entree
		}

		if (charCode==27) {
			this.hideCompletion();
			this.completion.innerHTML="";
			return;
			//touche Echap
		}
		
		/*this._completion_flag=1; //querying result
		this._completionValues=new Array();
		if (curVal.length >= this.letterStart) {
			this.sqlQuery(curVal.toLowerCase(),id);
		}
		return;
		*/
					

		if (this._queryBd) { //nv
			if (curVal=='') {
				this._completionValues=new Array();
				this._completion_flag=0;
			}
			if ((curVal!='')){
				if (((this._completionValues.length>0) && (curVal.toLowerCase().substring(0,this.letterStart)!=this.get_data_text(0).toLowerCase().substring(0,this.letterStart))) ||
				 ((this._completionValues.length == 0) && (this._completion_flag==0))){
					//les valeurs du tableau necoincident pas avec le texte tapé.
					//mettre a jour le tableau
					
					this._completionValues=new Array();
					if (curVal.length >= this.letterStart) {
						this._completion_flag=1; //querying result
						this.sqlQuery(curVal.toLowerCase().substring(0,this.letterStart),id);
						return ;
					}
				}
			}
		}

		this.dataview(curVal);
	},
	positionCompletion:function (){
		var id= this._controlID;
		var completionItem=this.completion;
		$(completionItem).css('top',this.$elem.position().top + inputHEIGHT).css('left',this.$elem.position().left );
		
		/*var ofTop=this.getOffsetPosition('Top')+inputHEIGHT;
		var ofLeft=this.getOffsetPosition('Left');
		completionItem.style.top=ofTop+'px';
		completionItem.style.left=ofLeft+'px';
		*/

		//IE perdait l'inscription de cette action, quand on positionne les div (je ne suis pas tres sur);
		//window.onresize=function(){completion_resize();};
	},


    hideCompletion:function(){
		this._completionOff = true;
		//alert("IAD_PageController.AutocompletionFormHandler.hideCompletion");
		if (this.completion) {
			this.completion.style.visibility='hidden';
		}
		var id= this._controlID;
		if (document.getElementById(id+'_completion_result')) {
			document.getElementById(id+'_completion_result').innerHTML=""; //nv
		}
	}, 

	visibleCompletion:function(){
		this._completionOff = false;
		var id = this._controlID; //id du control

		//var curVal=new String(document.getElementById(id).value.trim());
		var curVal=new String(document.getElementById(id).value);
		if (this.completion && curVal!='') {
			this.completion.style.visibility='visible';
		}
	},
	updateCompletion:function(resp){
		if (resp != '') {
			 eval('var response = ' + resp);
			 var id=response.id;
			//rechercher le handler
			var handler=this.setValue(response.values);
		}
	},
	/*definit l'url ajax*/
	setCompletionEnv:function(url){
	  this._completionEnvBase= url; //garde l'url de base
	  // completer avec les parametre exterieurs pour avoir le contexte complet
	  this._completionEnv=url;
	},

    checkSelected:function(index){
		var id= this._controlID;
		var el=this.elem;
		/*var index=getIndex(id);
		if (index) {
			var nextEl = el.form.elements[index+1];
			if (nextEl.focus) {nextEl.focus();}
		}*/


		var checkedIndex=index;//document.getElementById(id+'_completion_result').options.selectedIndex;
		el.value=document.getElementById(id+'_completion_result').options[checkedIndex].text;
		this.fire_newvalue(document.getElementById(id+'_completion_result').options[checkedIndex]);
		this.hideCompletion();
		el.focus();
	},

	choiceCompletion:function(e,index){
		var charCode=(e.charCode)?e.charCode:e.keyCode;

		if((charCode==13) && index>=0){
			this.checkSelected(index);
			return true;
		}
		if (charCode==27) {
			this.hideCompletion();
			this.elem.focus();
			return ;
			//touche Echap
		}
		return false;

	},

	completeCompletionEnv : function(param){
		this._completionEnv= this._completionEnvBase + (this._completionEnvBase.indexOf('?')>0?'&':'?');
		this._completionEnv += param;
	},
	
	setValue : function(params, evt)
	{
	   //alert('receiving values from server ');
	   this._completionValues=eval(params);
	   this._completion_flag=0;
	   var curVal=new String(document.getElementById(this.getId()).value.trim());
	   //var curVal=new String(this.getValue());
	   //alert("data received");
	   this.dataview(curVal);
	},
	getOffsetPosition : function(inTYPE){
		var inID =this.getId();
		var iVal = 0;
		var oObj = document.getElementById(inID);
		//alert('oObj.id = ' + oObj.id);
		var sType = 'oObj.offset' + inTYPE;
		while (oObj && oObj.tagName != 'BODY') {
		iVal += eval(sType);
		oObj = oObj.offsetParent;
		}
		return iVal;
	}

	/*validate : function(evt)
	{
		if (!(Object.isUndefined(this.options.help))) {
			if (this.getValue() == this.options.help) {
			   this.$elem.val("");
			}
		}

		return true;
	}*/


 });

 var GoogleAdress = $.extend(true,{},Control,{
    init:function(options,elem){
        this.WAIT=1;
        this.NOVALIDE=2;
        this.VALIDE=3;
        this.NOTSET = 0;

        this.ZONE_MIN= {lat:47.801445,lng:0.832205};
        this.ZONE_MAX= {lat:45.090247,lng:12.239839};

        this.control_is_ok=0;


        this._superInit= Control.init;

        this._superInit(options,elem);

        this.setFlag(this.NOTSET);
    },
    setFlag:function(flag){
        this.flag=flag;
    },
    getFlag:function(){
        return this.flag;
    },
    getUserNumRue:function(){
        return $("#" + this.options.numero).val().trim();
    },
    getUserRue:function(){
        return $("#" + this.options.rue).val().trim();
    },
    getUserCodeP:function(){
        return $("#" + this.options.codepostal).val();
    },
    getUserCommune:function(){
		//var commune = $("#" + this.options.codepostal + " option:selected").text().trim();
		var commune = $("#" + this.options.codepostal + '_ctrl_autocompletion').val().trim();
    //    var commm_arr =commune.split('('); ancienne ligne
    //    var localite = commm_arr[0];   ancienne ligne
    /*
    //debut lignes ajouter pour prendre en compe la modification du libelle
        var reg = new RegExp(/\([^\)]+\)/);
        var commm_arr =commune.split(',');
        var localite = commm_arr[0].replace(reg,'');
      //  alert(localite);
     // fin lignes ajouter pour prendre en compe la modification du libelle
  */

	  var commm_arr =commune.split('(');
	  var localite=commm_arr[0].trim();
  //alert(localite);
        var pays="000";
        if (commm_arr.length > 1) {

//pays=commm_arr[2];// ligne ajouter pour prendre en compe la modification du libelle

      //  pays=commm_arr[1].replace(")",""); ancienne ligne

			if (commm_arr.length==2) {
				var commm_arr2 =commm_arr[1].split(',');
				pays=commm_arr2[1].replace(")","");
				pays=pays.trim();
			} else if (commm_arr.length==3){
				 var commm_arr2=commm_arr[2];
				 var commm_arr2split=commm_arr2.split(',');
				 pays=commm_arr2split[1].replace(")","");
				 pays=pays.trim();
				  //alert(pays);
			}


			if (pays.toLowerCase() != 'fr') {
				pays='Suisse'
			} else pays = 'France';
		
			
        }
		this.setUserPays(pays);

        return localite;
    },
    getUserPays:function(){
        return this.user_pays;
    },
    setUserPays:function(pays){
        this.user_pays = pays;
    },
    localiser:function(){
        var lat = $("#" + this.options.lat_ctrl).val();
        var lng = $("#" + this.options.lng_ctrl).val();
        if ((lat == '') || (lng == '')) {
            return;
        }
        var point = new GLatLng(lat, lng);
        var marker = new GMarker(point);
        map1.addOverlay(marker);
        map1.setCenter(point,15);
    },
    is_coord_set:function(){
        var lng = $("#" + this.options.lng_ctrl).val();
        var lat = $("#" + this.options.lat_ctrl).val();
        if ((lng != '') && (lat != '')) {
            return true
        } else return false;
    },
    reg_equivalent:function(mot){
        var reg_esp = new RegExp(/[-_\s]+/g);
        var reg_e = new RegExp(/[éêe]/g);
        var reg_a = new RegExp(/[àâa]/g);
        var reg_rte_esp = new RegExp(/Rte[\s]{1}/);
        var reg_rte_pt = new RegExp(/Rte[\.]{1}/);
        var reg_av_esp = new RegExp(/Av[\s]{1}/);
        var reg_av_pt = new RegExp(/Av[\.]{1}/);

      var new_mot= mot.replace(reg_esp,' ');
      new_mot= new_mot.replace(reg_e,'e');
      new_mot= new_mot.replace(reg_a,'a');
      new_mot= new_mot.replace(reg_rte_esp,'Route ');
      new_mot= new_mot.replace(reg_rte_pt,'Route');
      new_mot= new_mot.replace(reg_av_esp,'Avenue ');
      new_mot= new_mot.replace(reg_av_pt,'Avenue');



      return new_mot;
    },
    isAdresseValid:function(placemark){
        
        var adresse =placemark.address;
		//alert('adr_google= ' + adresse);

        /*Controle alternatif */
        var reg_google = new RegExp(/[,]/);
        var googleadr = adresse.split(reg_google);
        if (googleadr.length >=2) {
            var pays = googleadr[googleadr.length - 1];
            var comm_arr  = googleadr[googleadr.length - 2].trim().split(' ');
            var google_cpostal = comm_arr[0].trim();
            if (parseInt(google_cpostal) + '' == google_cpostal) {
                //on a un code postal
                var commune = googleadr[googleadr.length - 2].replace(google_cpostal,'').trim();
            } else commune = google_cpostal;

//alert(pays);
//alert(commune);
//alert(this.getUserPays().trim().toLowerCase());
//alert('commune google = ' + commune.trim().toLowerCase());
//alert('commune saisie= '+this.getUserCommune().trim().toLowerCase());
            //comparer avec les valeurs saisies

 // if((pays.trim().toLowerCase()==this.getUserPays().trim().toLowerCase()))

if((pays.trim().toLowerCase()==this.getUserPays().trim().toLowerCase())) 
	//&& (commune.trim().toLowerCase() == this.getUserCommune().trim().toLowerCase())
        {
                return  true;
        }
        }

        return false;

        /*Fin control alternatif*/


        googleadr=adresse.split(",");
        /*Partie 2 servere*/
        if (googleadr.length < 3) {
            return false;
        }

        var numero="";
        var rue="";
        var codepostal = "";
        var commune = "";
        var pays = "";

        googleadr[0] = googleadr[0].trim();
        googleadr[1] = googleadr[1].trim();
        googleadr[2] = googleadr[2].trim();

        var rue_arr = googleadr[0].split(" ");
        if (rue_arr.length > 1) {
            if (this.getUserPays() == 'France') {
                //le numero se trouve en premier
                numero = rue_arr[0].trim();
            } else numero = rue_arr[rue_arr.length - 1].trim();

            rue = googleadr[0].replace(numero,"").trim();
        }

        var commune_arr = googleadr[1].split(" ");
        codepostal = commune_arr[0];
        commune = googleadr[1].replace(codepostal,"").trim();

        pays = googleadr[2];

        //on doit avoir le meme nom de rue et le meme nom de commune
        //var reg = new RegExp(/(_|-|\s)/);

        var google_rue_smpl =  this.reg_equivalent(rue).toLowerCase();
        var user_rue_smpl =  this.reg_equivalent(this.getUserRue()).toLowerCase();

        var google_comm_smpl = this.reg_equivalent(commune).toLowerCase();
        var user_comm_smpl =  this.reg_equivalent(this.getUserCommune()).toLowerCase();

        /*alert(numero.trim() +' ' + google_rue_smpl.trim() + ' ' + google_comm_smpl.trim() + ' ' + pays.trim() + '<br>' +
        this.getUserNumRue() + ' ' + user_rue_smpl.trim() + ' ' + user_comm_smpl.trim() + ' ' + this.getUserPays().trim());
        */




/*
        if ((google_rue_smpl == user_rue_smpl.trim()) && (google_comm_smpl.trim()==user_comm_smpl.trim())
         && (numero.trim()==this.getUserNumRue().trim()) && (pays.trim()==this.getUserPays().trim())) */ {
            //verification par Lat/Lng
            var google_lat = placemark.Point.coordinates[1];
            var google_lng = placemark.Point.coordinates[0];

            /*alert(google_lat + ' ('+ this.ZONE_MIN.lat + ':' + this.ZONE_MAX.lat +')');
            alert(google_lng + ' ('+ this.ZONE_MIN.lng + ':' + this.ZONE_MAX.lng +')');
            */
            if ((google_lat>this.ZONE_MIN.lat) || (google_lat<this.ZONE_MAX.lat)
             || (google_lng<this.ZONE_MIN.lng) || (google_lng>this.ZONE_MAX.lng)) {
                return false;

            }

            return true;
        }


        return false;
    },
    flushAdress:function(){
      this.control_is_ok = 0;
    },
    setAdressOk: function(){
      this.control_is_ok = 1;
    },
    /*La validation se fait par Google de maniere asynchron,
    personnaliser le traitement une fois service google repond
    */
    handlePostValid:function(){
        return;
    },
    validate:function(simple){
        //on verifie
        var numero= this.options.numero;
        var rue= this.options.rue;
        var codepostal= this.options.codepostal;
        /*Enregistrer les coord dans ces controls*/
        var lat_ctrl= this.options.lat_ctrl;
        var lng_ctrl= this.options.lng_ctrl;

        if (!numero) {
            alert('Erreur un numero de rue manque');
            return false;
        };
        if (!rue) {
            alert('Erreur rue manque');
            return false;
        };
        if (!codepostal) {
            alert('Erreur commune codepostal');
            return false;
        };
        if (!lat_ctrl) {
            alert('Erreur le ctrl lat_ctrl manque');
            return false;
        };
        if (!lng_ctrl) {
            alert('Erreur le ctrl lng_ctrl manque');
            return false;
        };


        var adresse = this.getUserNumRue() + ' ' + this.getUserRue() +
       ', ' + this.getUserCodeP() + ' ' + this.getUserCommune() + ', ' + this.getUserPays();

       //alert('adresse recherche:' + adresse);


       this.flush_error();
       var geocoder = new GClientGeocoder();
       if (this.control_is_ok == 1) {
           //alert('deuxieme validation on arrete');
           this.control_is_ok=0;
           return true;
           //le serveru a repondu OK sur l'adresse
       } else {
            //alert('control non valide on continue');
            $("#" + lat_ctrl).val('');
            $("#" + lng_ctrl).val('');
       }

       //this.setFlag(this.WAIT);

       var that= this;

       geocoder.getLocations(adresse, function(reponse){
           if (!reponse || reponse.Status.code != 200) {
               /*$("#adr_x").val(0);
               $("#adr_y").val(0);
               */
               //clearTimeout(that.timer);
               //that.setFlag(that.NOVALIDE);
               map1.clearOverlays();
               that.get_ctrl_error().html("L'adresse n'est pas valide");
               return false;
            } else {
                 //traitement de la réponse: recuperer les elements existants
                 //clearTimeout(that.timer);
                 var nombreReponse = reponse.Placemark.length;
                 if (nombreReponse>=1){
                   //that.setFlag(that.VALIDE);
                   //effacer le dernier point
                   /*for(var i=0;i<nombreReponse; i++){
                    alert('adr google trouve:' + reponse.Placemark[i].address);
                   }*/
                   if (!that.isAdresseValid(reponse.Placemark[0])) {
                       that.get_ctrl_error().html("L'adresse n'est pas valide");
                       return false;
                   };


                   map1.clearOverlays();
    			   var place = reponse.Placemark[0];
                   var Glatitude = place.Point.coordinates[1];
                   var Glongitude = place.Point.coordinates[0];
                   $("#" + lng_ctrl).val(Glongitude);
                   $("#" + lat_ctrl).val(Glatitude);

                   that.localiser();


                   if (!simple || (simple == 'undefined')) {
                       //revalidation du form
                       that.control_is_ok = 1;
                       that.handlePostValid();
                   }


                   return true;
                 }
            }
    	});

    	//setInterval("if(that.getFlag() != that.WAIT){alert('ok');}clearInterval();",1000);
    	//setTimeout(function(){if(that.getFlag() != that.WAIT){alert('ok');}},1000);
        //return true;
        if (this.is_coord_set()) {
            //alert('coord ok');
            return true;
        } else {
            /*if (this.getFlag() == this.NOVALIDE) {
                this.get_ctrl_error().html("l'adresse n'est pas correcte");
            } else {
                //lancer une autre validation du formulaire
                if (!this.timer || (this.timer==0)) {
                    this.get_ctrl_error().html("Validation de l'adresse en cours...");
                    this.timer = setTimeout(function(){if (that.getFormulaire().validate('etape1')) {
                            alert('validation ok');
                            aller_etape(2);
                            clearTimeout(that.timer);
                            }
                        },
                    1000);
                }

            }*/
            return false;
        }

    } //fin validate


 });

 var Graphe = $.extend(true,{},Control,{
   init:function(options,elem){
     this._superInit= Control.init;
     this._superInit(options,elem);





    // google.setOnLoadCallback(this.draw(options.data));

   },
   yValueFormatter:function(y){
    return new String(format(y)) + ' ' + this.unite;
   },
   xValueFormatter:function(x){
     var dt = new Date();
     dt.setTime(x);
     return Dygraph.zeropad(dt.getDate())+'/' + Dygraph.zeropad(dt.getMonth()+1) + '/' + dt.getFullYear();
   },
   yAxisLabelFormatter:function(y){
    return format(y);
   },
   draw:function(){
     //$("#graphe_indicateur").html('');
     //document.getElementById('graphe_indicateur').innerHTML='';
     //var valeurs = this.options.data;
     //var colors = {data:'#FF0000',reference:'#0000FF'};
     //var series_colors= ['#FF0000','#0000FF'];
     //var series_label = [];
     var options=this.options;

     var data = new google.visualization.DataTable();
     var data_ref = new google.visualization.DataTable();
     var data_all = new google.visualization.DataTable();


        //data.addColumn('number', 'Expenses');

        //alert(typeof options.data.length);
        var titre = "";
        var reference = null;
        if (options.data && (typeof options.data.length == 'undefined')) {
            data.addColumn('date', 'Jours');
            data_ref.addColumn('date', 'Jours');


            for(compteur in options.data){
              var valeurs = [];
              var valeurs_ref = [];
              titre += options.data[compteur].titre ;
              //Mettre le titre :
              //$("#graphe_titre").html(titre);
              if ((options.data[compteur].valeur_ref != "null") && (options.data[compteur].valeur_ref != "")
              && (options.data[compteur].valeur_ref != null) && (options.data[compteur].valeur_ref != 'undefined')) {
                  reference=parseFloat(options.data[compteur].valeur_ref);
              }

              representation = parseInt(options.data[compteur].representation);
              unite = options.data[compteur].unite;
              this.unite=unite;
              this.representation = representation;

              //if (options.data[compteur] && (typeof options.data[compteur].length == 'undefined')) {
                  data.addColumn('number', compteur);
                  /*data.addColumn('string', 'title1');
                  data.addColumn('string', 'text1');*/

                  data_ref.addColumn('number', 'Référence');


                  //data_ref.addColumn('number', 'Référence ' + (representation==2 ? 'cumulée': 'journalière'));
                  /*data_ref.addColumn('string', 'title2');
                  data_ref.addColumn('string', 'text2');*/


                  var donnees = options.data[compteur].data;
                  //garde la date precedente
                  var date_prec = null;
                  for(var i=0; i<donnees.length; i++){
                    //if (donnees[i].valeur) {
                        var tabl = [];
                        var tabl_ref = [];
                        var jour = donnees[i].jour.split('/');
                        var jj= jour[0];
                        var mm= jour[1];
                        var aa = jour[2];
                        var date_2_saisie = new Date(aa,mm,jj);

                        //ajout de ligne
                        /*if ((representation != 2) && (date_prec!=null)) {
                            //on est en journaliere, representation segment
                            var tabl_prec = [];
                            tabl_prec.push(date_prec);
                            tabl_prec.push(parseFloat(donnees[i].valeur));
                            valeurs.push(tabl_prec);
                        }*/
                        tabl.push(date_2_saisie);
                        tabl.push(parseFloat(donnees[i].valeur));
                        valeurs.push(tabl);

                        if (reference != null) {
                            tabl_ref.push(date_2_saisie);
                            if (representation == 2) {
                                val_ref = reference * diffdate(donnees[0].jour,donnees[i].jour,'d');
                            } else val_ref = reference;

                            //ajout de ligne
                            /*if ((representation != 2) && (date_prec!=null)) {
                                //on est en journaliere, representation segment
                                var tabl_ref_prec = [];
                                tabl_ref_prec.push(date_prec);
                                tabl_ref_prec.push(val_ref);
                                valeurs_ref.push(tabl_ref_prec);
                            }*/
                            tabl_ref.push(val_ref);
                            valeurs_ref.push(tabl_ref);
                        }

                        //garde la date precedente
                        date_prec = new Date();
                        date_prec.setTime(date_2_saisie.getTime());

                    //}

                  }
                  data.addRows(valeurs);
                  data_ref.addRows(valeurs_ref);



              //}
            }

            var escalier = false;
            if (representation != 2) {
                escalier = true;
            }



           if (reference != null) {
                data_all = google.visualization.data.join(data, data_ref, 'left', [[0,0]], [1], [1]);
                //alert('premierdatref=' + data_ref.getValue(0,0))
            } else data_all= data;


            //format de datatable en csv
            var csv = "";
            //ajout des colonnes
            for(var columnIndex=0; columnIndex<data_all.getNumberOfColumns();columnIndex++){
                csv += data_all.getColumnLabel(columnIndex);
                if (columnIndex < data_all.getNumberOfColumns() -1) csv+=",";
            }
            csv+= "\n";

            for(var i=0; i<data_all.getNumberOfRows();i++){
                for(j=0;j<data_all.getNumberOfColumns();j++){
                    var val;
                    if ((j>0) && escalier && (i < (data_all.getNumberOfRows() - 1))) {
                         val = data_all.getValue(i+1,j);
                    } else val = data_all.getValue(i,j);
                    if (j==0) {
                     val= val.getFullYear() + "-" + val.getMonth() + "-" + val.getDate();
                     }
                    csv += val;
                    if (j<data_all.getNumberOfColumns() -1) csv+=",";
                }
                csv += "\n";
            }

           /*var csv ='Date,Compteur Test Sthiam\n'+
           '2010-11-09,0\n'+
           '2011-01-02,385.753424657535\n'+
          '2011-01-25,547.068493150686\n'+
           '2011-02-03,589.1506849315081\n'+
           '2011-02-10,638.246575342467\n';*/

           /*var csv= "Date,Temperature\n" +
    "2008-05-07,75\n" +
    "2008-05-08,70\n" +
    "2008-05-09,80\n";*/



            //alert(csv);

            Date.ext.locales.fr = {
                a: ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
                A: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
                b: ['jan.', 'fév.', 'mar.', 'avr.', 'mai', 'jun.', 'jul.', 'aou.', 'sep.', 'oct.', 'nov.', 'dec.'],
                B: ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
                c: '%a %d %b %Y %T %Z',
                p: ['AM', 'PM'],
                P: ['am', 'pm'],
                x: '%d/%m/%y',
                X: '%T'
            };

            Date.locale = 'fr';

             g = new Dygraph(document.getElementById("graphe_view"),csv,{
             drawPoints:true,
             pointSize : 2,
             //colors : series_colors,
             //labelsDivWidth:600,
             labelsDiv:'graphe_survol',
             labelsSeparateLines: true,
             strokeWidth : 2,
             axisLabelFontSize : 10,
             xValueFormatter:this.xValueFormatter,
             yValueFormatter:this.yValueFormatter,
             yAxisLabelFormatter:this.yAxisLabelFormatter,
             stepPlot:(escalier ? true:false) //fonction en escalier
             }
            );



            g.generateLegendHTML_ = function(x, sel_points) {
              // If no points are selected, we display a default legend. Traditionally,
              // this has been blank. But a better default would be a conventional legend,
              // which provides essential information for a non-interactive chart.
              if (typeof(x) === 'undefined') {
                if (this.attr_('legend') != 'always') return '';

                var sepLines = this.attr_('labelsSeparateLines');
                var labels = this.attr_('labels');
                var html = '';
                for (var i = 1; i < labels.length; i++) {
                  var c = new RGBColor(this.plotter_.colors[labels[i]]);
                  if (i > 1) html += (sepLines ? '<br/>' : ' ');
                  html += "<b><font color='" + c.toHex() + "'>&mdash;" + labels[i] +
                    "</font></b>";
                }
                return html;
              }

              var displayDigits = this.numXDigits_ + this.numExtraDigits_;
              var html = "<div id='survol_ss_date'> " + this.attr_('xValueFormatter')(x, displayDigits) + "</div>";
              //var html = this.attr_('xValueFormatter')(x, displayDigits);
              html += "<div id='survol_ss_valeur'>";
              var fmtFunc = this.attr_('yValueFormatter');
              var showZeros = this.attr_("labelsShowZeroValues");
              var sepLines = this.attr_("labelsSeparateLines");
              for (var i = 0; i < this.selPoints_.length; i++) {
                var pt = this.selPoints_[i];
                if (pt.yval == 0 && !showZeros) continue;
                if (!Dygraph.isOK(pt.canvasy)) continue;
                if (sepLines && (i>0)) html += "<br/>";

                var c = new RGBColor(this.plotter_.colors[pt.name]);
                var yval = fmtFunc(pt.yval, displayDigits);

                // TODO(danvk): use a template string here and make it an attribute.
                html += "&nbsp;<b><font color='" + c.toHex() + "'>"
                  + pt.name + "</font></b> : "
                  + yval;

              }
              html += "</div>";
              return html;
            };


            //construction de la legende
            html= "";
            var labels = g.attr_('labels');
            for (var i = 1; i < labels.length; i++) {
                  var c = new RGBColor(g.plotter_.colors[labels[i]]);
                  if (i > 1) html += "<div class='legende_sep'>&nbsp</div>";
                  html += "<div class='legende_color' style='background-color:"+c.toHex()+"'></div> " +
                        "<div class='legende_titre'><b>"+labels[i]+"</b></div>" ;
            }
            if (html!="") {
                $("#graphe_legende").html(html);
            }




        } else if (options.data.length ==0) {
              $("#graphe_view").html('Aucun graphique n’existe pour ce compteur');
        }

        /*data.addRows([
          ['2004', 1000, 400],
          ['2005', 1170, 460],
          ['2006', 660, 1120],
          ['2007', 1030, 540]
        ]);*/


   }
 });

 /* gestion de formulaire */
 var Formulaire= $.extend(true,{},Control,{

    init:function(options,elem){
      /*Enregistrment des fonctions parents*/
	  this._superInit= Control.init;

	  this._superInit(options,elem);

      //garde tous les plugins;
	  this.all_plugins = [];
	  this.all_controls = [];

	  var that = this;


	  this.$elem.submit(function(event){
	   //event.stopPropagation();
	   return that.validate();
	   //return false;
	   //return that.valider();
      });

      //ajouter le controle à Page
	  PageMng.addForm(this.getId(), this);
      if (options && options['control_handler']) {
        //alert(options['control_handler'].length);
        var controls = options['control_handler'];
        //if (controls != "")  {
        if (options['control_handler'] != "") {
            this.addHandler(options['control_handler']);
        }

      }
      /*if (options) {
		  this.addHandler(options);
      }*/


   },
   /* ajoute des handler sur les controls*/
   addHandler:function(options){
     //recherche des plugins et association
      if (options) {
      	//de la forme plugins ={control_id:{plugin:le_nom_du_plugin,options:ses_options}, ...,... }
		for(control_id in options){
		   //alert(this.getId() + ' - ' + control_id);
		   var plug_et_options = options[control_id];
			 //ajouter a la liste des plugins
		   //all_plugins = all_plugins.push(control_id);
		   this.all_plugins.push(control_id);
		   var plug_name= plug_et_options.plugin;
		   var ses_options = plug_et_options.options;

		   if (ses_options && ses_options.length != 0) {
		   	 ses_options_str = json2str(ses_options);
		   } else ses_options_str="{}";

//alert("id=" + $("#" + control_id).attr('id') + " et plugname=" + plug_name);
          	eval("$('#"+ this.getId() +"').find('#" + control_id + "')." + plug_name + "(" + ses_options_str + ")");
		  //enregistrer les controls
		   //this.all_controls.push({id:control_id,jq:jq_control});

      	}
      }
   },
   submit:function(){
	 this.$elem.submit();
   },
   validate:function(bloc){
      //alert('validation de form');
	  var no_erreur = true;
      for(var i=0; i<this.all_controls.length; i++){
		 var ctrl = this.all_controls[i]['elt'];
		 //var ctrl$elem = ctrl.$elem;
		 if (bloc) {

              //on filtre sur le bloc, verifier qu'il est dans le bloc

              var tableau_des_parents = ctrl.$elem.parents();
              est_dans_le_bloc = false;
              $.each(tableau_des_parents,function(j,piece){
                   //alert('elt='+ elt + ':' +piece.getAttribute("id"));
                   var id_piece= piece.getAttribute("id");
                   if (id_piece && (id_piece==bloc)) {
                      est_dans_le_bloc = true;
                      return false; //arreter l'iteration
                    }
                });
          }

		  if ((!bloc) || (bloc && est_dans_le_bloc)) {
             no_erreur = ctrl.validate() && no_erreur;
		  }

      }
      return no_erreur;
   },
   /*Ajouter un control à l'objet Formulaire*/
   addControl:function(control_id,control_obj){
	 var i = this.findControl(control_id);
     if (i == null) {
    	this.all_controls.push({id:control_id,elt:control_obj});
     } else this.all_controls[i]['elt'] = control_obj;
   },
   /**/
   getControl:function(control_id){
     var i= this.findControl(control_id);
     if (i!=null) {
     	return this.all_controls[i]['elt'];
     }  else {alert("Le control " + control_id + " n'a pas été trouvé"); return null};
   },
   findControl:function(control_id){
     for(var i=0; i<this.all_controls.length; i++){
       if (this.all_controls[i]['id'] == control_id) {
       	  return i;
       	  break;
       }
     }
     return null;
   },
   alert_save_success : function(titre,sous_titre){
    PageMng.alert_success_msg(titre,sous_titre);
   }

 });

 /* gestion de formulaire */
 var IADAjaxForm= $.extend(true,{},Formulaire,{

    init:function(options,elem){
      /*Enregistrment des fonctions parents*/
	  this._superInit= Formulaire.init;
	  this._superInit(options,elem);

	  this.$elem.unbind('submit');

	  var that=this;


      this.div_container = this.getJqueryElt().parents('div[class*=ajax]:first');
      this.div_loading= this.div_container;
      if (options['options'] && options['options']['loading']) {
        this.div_loading  =options['options']['loading'];
      }
      //alert(this.div_loading.attr('id'));

      this.updatecontent  = true;
      if (options['options'] && options['options']['updatecontent'] && options['options']['updatecontent']=='false') {
        this.updatecontent  = false;
      }

	  /*Le premier div parent qui contient une classe ajax*/

	  var perso_options = {success:function(data){
			var div_container="";

            that.stopLoading();

            if (that.updatecontent) {
				//alert(that.div_container.attr('id'));
				//alert(data);
				that.div_container.html(data);
				//that.div_container.get(0).innerHTML =data;
            }
			
			//alert(that.div_container.html());

            if (that.options['options'] && that.options['options']['success']) {
			    var client_success = that.options['options']['success'];
                if(typeof client_success =='function'){
                  client_success(data);
			    } else div_container=$("#"+options['options']['success']);
			} else div_container = that.div_container;
    },beforeSubmit:function(){
	      //that.div_container.addClass('loading');
	      //that.getJqueryElt().fadeIn(600);
	      that.startLoading();//div_container.addClass('loading').animeajax();
	    }
	   };


	   this.$elem.ajaxForm(perso_options);

   },
   stopLoading:function(){
    //this.removeClass('loading-visible');
   }, 
   startLoading:function(){
    //alert(this.div_loading.attr('id'));
    //this.div_loading.addClass('loading-visible');//.animeajax();
	
	/*
	 a voir de plus pres le css loading-visible sur div.css
	 pose pb sur la carto, le
	*/
   },
   updateSuccessHandle:function(f){
    this.options['options']['success'] = f;
   }
 });

 //bouton Submit
 $.fn.submitBtn= function(){
    this.click(function() {
        //rechercher le formulaire contenant
		var form = $(this).parents('form:first').submit();
		//PageMng.getForm(this.id).valider();
     });
     return this;
  }

  $.fn.submitSelect= function(){
    this.change(function() {
        //rechercher le formulaire contenant
		var form = $(this).parents('form:first').submit();
		//PageMng.getForm(this.id).valider();
     });
     return this;
  }


  //bouton Redirection
  $.fn.redirectionBtn = function(url){
     this.url = url;
     var that = this;

	 this.click(function(){
	    window.location.href=that.url;
	 });

	 return this;
  }
  
  //charger un module
  $.fn.loadModule = function(module){
    this.module = module;

    var that = this;

     
	PageMng.setWindowClose(this.module);
	 
    $("#fermer_mod_" + module).click(function(){
        that.fermer_wnd();
    });
	
	this.fermer_wnd = function(){
		$("#" + this.module).hide();
		if (PageMng.is_comptabible_mask())
		{
			$("#cw_gedmask").hide();
		}
	}
	

	this.each(function(){
		$(this).click(function(e){
			//positionner le div au  bon endroit
			
			/*if (!(e.pageX || e.pageY)) {
				return;
			}*/

			if (PageMng.is_comptabible_mask())
			{
				$("#cw_gedmask").show();
			}
			$("#" + that.module).show();
			
			
			/*centrer sur l'ecran*/
			var doc_width = $(document).width();
			var elt_width = (doc_width - $("#" + that.module).width())/2;
			
			//alert('docWidth=' + doc_width + ' eltWidth=' + $("#" + that.module).width());
			  
			//that.positionOnObj({X:e.pageX - $("#content").offset().left, Y:e.pageY - $("#content").offset().top});

			//var wnd_height = $(window).height();
			//alert('scrollTop:' + $(document).scrollTop() + ' windHeight:' + $(window).height() + ' contentOffetTop:'+$("#content").offset().top);
			//var top = getOffsetPositionElt(e.target,'Top'); //$(document).scrollTop() + ($(window).height()/2) - $("#content").offset().top;
			//alert('top:' + top + '--topContent=' + getOffsetPosition('content','Top'));
			
			/*meme niveau que l'element clique*/
			that.positionOnObj({X:elt_width, Y:$(e.target).offset().top});
			/*en debut de la partie visible*/
			//that.positionOnObj({X:elt_width, Y:$(document).scrollTop()});
			
		});
	});
  
	this.positionMe = function(elt){
        //alert('top=' + $(elt).offset().top + ' left='+ $(elt).offset().left); 
		var doc_width = $(document).width();
		var elt_width = (doc_width - $("#" + this.module).width())/2;
		//alert(doc_width + ' - ' + $("#" + this.module).width());
		//$("#" + this.module).css('top',$(elt).offset().top + 20).css('left',elt_width).show();
		this.positionOnObj({X:$(elt).offset().left,Y:$(elt).offset().top});
	}; 
	  
	this.positionOnObj = function(obj) 
	{
		//alert(obj.Y + '-' + obj.X); 
		var lemodule=$("#" + this.module);
		var my_elem_offset = lemodule.offset();
		if (obj.Y) {
			//lemodule.css('top',obj.Y);
			
			my_elem_offset.top = obj.Y + 15;
			
			//lemodule.offset({'top':obj.Y});
		}
		
		if (obj.X) {
			//lemodule.css('left',obj.X);
			my_elem_offset.left= obj.X;
		}
		
		lemodule.offset(my_elem_offset);
		//lemodule.show();
		
	}
	 
	 return this;
  }

  /*Gere les validation formulaire par Ajax*/
  $.fn.ajaxFormHdl = function(options,whereloading)
  {

   var client_succes=null;
   var client_before = null
   var perso_options = options;

   this.whereloading = 'whereloading';
   //var perso_options = options;
   //var that = this;


   if (options['beforeSubmit']=='undefined' || options['beforeSubmit']==null) {
   	  perso_options.beforeSubmit = function(){
   	       //PageMng.showLoading(that.whereloading);
      }
   }

   if (options['success'] != 'undefined' && options['success']!=null) {
   	  client_succes= options['success'];
   	  perso_options['success'] = function(data){
   	    //alert('arret du chargement');
   	    //on peut persoonnalisé le loading ici
   	    //
   	    //PageMng.hideLoading(that.whereloading);

   	    //si un nom de div est donné alors y metre le contenu
   	    //sinon c'est une fonction l'appeler
   	    if(typeof client_succes =='function'){
		   client_succes(data);
		} else {
		   $("#" + client_succes).html(data);
		}
   	  }
   } else  perso_options['success']= function(){$("#loading").hide();};

   return $(this).ajaxForm(perso_options);
  }


  /*$.fn.choixmultiple = function(){
   //recuperer les valeurs selectionnes pas defaut
   var that = this;
   this.checked = [];
   //champ hidden qui contient les valeurs choisis
    var id_hidden = $(this).attr("id") + "_choixmultiple";
    //this.champs_valeurs = $(this).find("#" + id_hidden);

   this.add = function(elt) {
     this.checked.push(elt);
   }

   this.remove = function(elt) {
     var arr = []
     for (var i=0; i<this.checked.length; i++){
       if (this.checked[i] != elt) {
       	arr.push(this.checked[i]);
       }
     }
     this.checked=arr;
   }

   $(this).find("input:checked").each(function(){
      that.add($(this).attr('value'));
   });


   //
   $(this).find("input[type=checkbox]").each(function(){
     	$(this).click(function(){
     	   if ($(this).is(":checked")) {
     	   	 that.add($(this).attr('value'));
     	   } else that.remove($(this).attr('value'));

     	   //la valeur du control change
     	   that.update();
     	});
   });

   //mettre dans le controle caché les valeurs selectionnés
   this.update = function(){
     var choisis = this.checked.join(",");
     //var id_hidden = champs_valeurs;
     //alert(id_hidden);
	 $(this).find("#" + id_hidden).attr("value", choisis);

	 //ajouter dans l'attribut value du div
	 //au cas ou le controle serait obligatoire
	 $(this).attr("value", choisis);
   }

   this.val = function(){
     return $(this).find("#" + id_hidden).attr("value");
   }

    //la valeur du control change
    this.update();

  }

  //plugin groupradio 

  $.fn.groupradio = function(){
    var that= this;
    $(this).find("input:radio").each(function(){
      $(this).click(function(){
        that.attr('value',$(this).attr('value'));
	  });
	  //si il est choisi, alimenter le div qui garde sa valeur
	  if ($(this).is(":checked")) {
	  	 that.attr('value',$(this).attr('value'));
	  }
   });
  }*/


 //générateur de plugin
  $.plugin = function(name, object) {
	    $.fn[name] = function(options) {
	        var args = Array.prototype.slice.call(arguments, 1);
	        return this.each(function() {
	            var instance = $.data(this, name);
	            if (instance) {
					instance[options].apply(instance, args);
	            } else {
	                instance = $.data(this, name, Object.create(object).init(options, this));
	            }
	        });
	    };
	};


// With the Speaker object, we could essentially do this:
	$.plugin('Control', Control);
	$.plugin('Text', Text);
	$.plugin('InputDate', InputDate);
	$.plugin('InputTextEnrichi', InputTextEnrichi);
	$.plugin('InputNumeric', InputNumeric);
	$.plugin('InputNumber', InputNumber);
	$.plugin('InputNumberValidation',InputNumberValidation);
	$.plugin('InputTelephone', InputTelephone);
	$.plugin('InputEmail', InputEmail);
	$.plugin('InputLogin',InputLogin);
	$.plugin('GroupRadio', GroupRadio);
	$.plugin('ChoixMultiple', ChoixMultiple);
	$.plugin('InputExpRegulier', InputExpRegulier);
	$.plugin('InputConfirmation',InputConfirmation);
	$.plugin('DivFenetreCarto',DivFenetreCarto);
	$.plugin('InputPassword',InputPassword);
	$.plugin('Graphe',Graphe);
	$.plugin('Autocomplete',Autocomplete);
	$.plugin('GoogleAdress',GoogleAdress);
	$.plugin('Formulaire', Formulaire);
	$.plugin('IADAjaxForm', IADAjaxForm);


})(jQuery);



