var time_search;

function search(value) {
  var regex = /\S/i;

  if(value.length < 2) {
    rc.abort();
    clearTimeout(time_search);
    document.getElementById('proposals').style.display = 'none';
  }
  else if(regex.test(value)) {
    rc.abort();
    clearTimeout(time_search);
    time_search = setTimeout('autocomplete(\''+value+'\');', 100);
  }
}

function autocomplete(value) {
  if(value.length > 2) {
    if(document.getElementById('list-type').value == 'postcode')
      rc.open('post', racine+'/js/autocomplete_pc.php', true);
    else if(document.getElementById('list-type').value == 'city')
      rc.open('post', racine+'/js/autocomplete.php', true);

    rc.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    rc.onreadystatechange = autocompleteControl;
    rc.send('value='+value);
  }
}

function autocompleteControl() {
  if(rc.readyState == 4 && rc.status == 200) {
    var response = rc.responseText.split('*');

    // If the response's good
    if(response[0] == '1') {
      if(response[1] != 'null') {
        document.getElementById('proposals').style.display = 'block';
        document.getElementById('proposals').innerHTML = response[1];
      }
      else {
        document.getElementById('proposals').style.display = 'block';
        document.getElementById('proposals').innerHTML = 'No propositions...';
      }
    }
  }
}

function clickControl(e) {
  if(out) {
    document.getElementById('proposals').style.display = 'none';
    out = false;
  }
  else
    out = true;
}

function give(value, elem) {
  document.getElementById(elem).value = value;
  document.getElementById('proposals').style.display = 'none';
  out = true;
}

function detectEnter(event) {
  if((document.all && event.keyCode == 13) || (event.which == 13))
    submitSearch();
}

function submitSearch() {
  var regex = /\S/i;

  if(document.getElementById('shop').value == 'Name of the shop you\'re searching for...' || !regex.test(document.getElementById('shop').value))
    var shop_value = '';
  else
    var shop_value = document.getElementById('shop').value;

  if(document.getElementById('location').value == 'Address, city, postcode or county...' || !regex.test(document.getElementById('location').value))
    var location_value = '';
  else
    var location_value = document.getElementById('location').value;

  if(shop_value != '' || location_value != '') {
    var regex = /[a-zA-Z0-9]{3,}/;
	var one_word_is_good = false;
	
	if(regex.test(shop_value) || regex.test(location_value)) {
      document.getElementById('search-shop-value').value = shop_value;
      document.getElementById('search-value').value = location_value;
      document.getElementById('search-type').value = document.getElementById('list-type').value;
      document.getElementById('search').submit();
	}
	else
	  alert('You must search a word of at least 3 characters.');
  }
  else
    alert('Please fill the two fields.');
}
