(function($){
  $.fn.geolocalise = function(options)
  {
    var o = $.extend({
      geocoder  : new google.maps.Geocoder()
    },options);
	
    function laodGeo()
    {
      $(this).autocomplete({
        source: function(request, response) {
          o.geocoder.geocode( {'address': request.term}, function(results, status) {
            response($.map(results, function(item) {
              return {
                label     :  item.formatted_address,
                value     :  item.formatted_address ,
                latitude  :  item.geometry.location.lat() ,
                longitude :  item.geometry.location.lng() ,
                other     : [$("#geo_lng").val(item.geometry.location.lng()), $("#geo_lat").val(item.geometry.location.lat()), $("#geo_address").val(item.formatted_address) ]
              }
            }));
          })
        }
      });
    }
    $(this).click(function(){
      laodGeo();
    });
	
    $(this).autocomplete({
      source: function(request, response) {
        o.geocoder.geocode( {'address': request.term}, function(results, status) {
          response($.map(results, function(item) {
            return {
              label     :  item.formatted_address,
              value     :  item.formatted_address ,
              latitude  :  item.geometry.location.lat() ,
              longitude :  item.geometry.location.lng() ,
			        other     : [$("#geo_lng").val(item.geometry.location.lng()), $("#geo_lat").val(item.geometry.location.lat()), $("#geo_address").val(item.formatted_address) ]
            }
          }));
        })
      }
    });

    $(this).keypress(function(event){
      if ( event.which == 13 ) //Entrée
      {
        if (confirmAddress()){
          $("#get_localisation").submit();
        }
      }
    });

    $("#bt_cherche").bind('click', function(){
      if (confirmAddress()){
        $("#get_localisation").submit();
      }
    });

    /* Vérifi que l'adresse est bien saisi */
    function confirmAddress()
    {
      if ( $("#geo_address").val() !="" && $("#geo_lat").val()!="" && $("#geo_lng").val()!="" ){
        return true;
      }

     return false;
    }

  }
})(jQuery)
