(function( $ ) {
	'use strict';
	var last_call_time = 0 
	var last_query_length = 0
	var suggestions = null;
	var sugg_li = null;
	var selected_li = null;
	var addresses = [];

	function clear_suggest_list() {
	  suggestions.html('')
	}

	function search(params) {
	    var d = new Date()
	    var elapsed_since_last_call = d.getTime() - last_call_time
	    if (elapsed_since_last_call > 1000) {
	      clear_suggest_list()
	      addresses = []
	      last_call_time = d.getTime()
	      const geo_url = new URL('https://api-adresse.data.gouv.fr/search');
	      Object.keys(params).forEach(
	        key => geo_url.searchParams.append(key, params[key])
	      )
	      fetch(geo_url)
	        .then(response => {
	          if (response.status >= 200 && response.status < 300) {
	            return response
	          } else {
	            const error = new Error(response.statusText)
	            error.response = response
	            throw error
	          }
	        })
	        .then(response => response.json())
	        .then(data => display_received_points(data))
	        .catch(error => console.log('request failed', error))
	    } 
    
	}

	function display_received_points(data) {
	  // console.log('Display_received_ points recu ', data)
	  if (typeof(data.features) != "undefined" && data.features.length > 0) {
	    var features = data.features
	    var list = $('<ul/>')
	    $.each(features, function(i,e) {
	      var li = $('<li/>')
	               .attr('data-index',i)
	               .text(e.properties.label)

	      list.append(li)
	    })
	    
	    suggestions.append(list)
	    sugg_li = list.find('li');
	    selected_li = null;
	    addresses = data.features;
	  }
	}

	function confirm_chosen_address(){
	   if (selected_li) {
	     var selected_addr = addresses[selected_li.data('index')];
	     // Address elements are known
	     // Just display coordinates as an example
	     $('#wosmpl_address_auto').val(selected_addr.properties.label)
	     clear_suggest_list();
	     var lat = selected_addr.geometry.coordinates[1];
	     var lng = selected_addr.geometry.coordinates[0];
	     $('input[name="wosmpl_latlon"]').val(lat + ',' + lng);
	     $('input[name="wosmpl_post_addr"]').val(selected_addr.properties.label);
	     suggestions.html(msg);
	   } else {
	     // TODO
	   }
	   
	}
	function select_li_suggest() {
		var clicked = $(this);
		selected_li = clicked;
		confirm_chosen_address();
	}
	function li_up(){
	  if(selected_li) {
	    selected_li.removeClass('selected');
	    next = selected_li.prev();
	    if(next.length > 0) {
	      selected_li = next.addClass('selected');
	    } else {
	      selected_li = sugg_li.last().addClass('selected');
	    }
	  } else {
	    selected_li = sugg_li.last().addClass('selected');
	  }
	}

	function li_down(){
	  //move down in suggestions li list
	  if(selected_li) {
	    selected_li.removeClass('selected');
	    next = selected_li.next();
	    if(next.length > 0) {
	      selected_li = next.addClass('selected');
	    } else {
	      selected_li = sugg_li.eq(0).addClass('selected');
	    }
	  } else {
	    selected_li = sugg_li.eq(0).addClass('selected');
	  }
	}

	function search_address_auto(e) {
	  e = e || window.event;
	  if (e.keyCode == '13') {
	    // enter
	    e.preventDefault();
	    confirm_chosen_address();
	  }
	  else if (e.keyCode == '38') {
	    // up arrow
	    li_up();
	  }
	  else if (e.keyCode == '40') {
	    // down arrow
	    li_down();
	  }
	  else {
	    var query = $(this).val()
	    var worth = false
	    if (new RegExp('[0-9]+[ ,]+[a-z]+ [a-z]+','i').exec(query)) {
	      // ca ressemble a une debut d'adresse genre 1 rue g')
	      worth = true
	    } else if (new RegExp('^[a-z]+','i').exec(query)) {
	      worth = true
	    }

	    if (worth == true) search({q:query, limit:6})
	  } 
	  
	  
	}

	$( window ).load(function() {
		var gdb = $('#wosmpl_geodata_box');

		if (gdb.length > 0) {
			//alert('On va assister la loc');
			suggestions = $('#wosmpl_address_suggestions');
			$('#wosmpl_address_auto').keyup(search_address_auto);
			suggestions.on('click','li',select_li_suggest);
			let imageUpload = document.getElementById('wosml_img_selector');
			imageUpload.onchange = wosmpl_show_file;
			$('.wosmpl_upload_image_button').click(wosmpl_upload_file);
		}
		
		
		
	});
	 
})( jQuery );
