var fromComplete = false;
$(function() {
  $("input.complete").attr('autocomplete', 'off');
	var focused = false;
  var cityPatern = "";
	$("input.complete").live('focus', function() {
		focused = true;
	});
	$("input.complete").live('blur', function() {
		focused = false;
	});
	$("input.complete").live('keyup', function(event) {
    fromComplete = false;
    //Déplacement dans la liste d'autocomplete avec les fleches'
    code = event.keyCode;
    var KEY = {
        UP: 38,
        DOWN: 40,
        RETURN: 13,
        ESC: 27
    };
    var activeLine = $(".complete-list li.active");

    switch(code) {
        case KEY.DOWN:
          if (activeLine.text() == "") {
            $("ul.complete-list li:first").addClass('active');
          } else {
            if ($("ul.complete-list li.active").next('li').text() != "") {
              $("ul.complete-list li.active").next('li').addClass('active');
              $("ul.complete-list li.active:first").removeClass('active');
            }
          }
        break;
        case KEY.UP :
          if (activeLine.text() == "") {
            $("ul.complete-list li:first").addClass('active');
          } else {
            $("ul.complete-list li.active").prev('li').addClass('active');
            $("ul.complete-list li.active:last").removeClass('active');
          }
        break;
        case KEY.RETURN :
          event.preventDefault();
          if (activeLine.text() != "") {
            selectItem(activeLine.children('a'));
            activeLine = $(".complete-list li.active");
            return false;
          } else {
            $("#searchMode").val('search');
            $(this).parents('form').submit();
          }
        break;
        case KEY.ESC :
          $('ul.complete-list').hide();
        break;
      }

    //Système d'autocomplétion
	if ($(this).val().length > 2 && !fromComplete) {
      if (utf8_encode($(this).val()) != cityPatern) {
        cityPatern = utf8_encode($(this).val());
        $.getJSON(
         rootPath+"admin/ajax_city_name.php",
          {
            patern : utf8_encode($(this).val()),
            langId : $("#lang_id").val(),
            department : $("#department_id").val(),
            region : $("#region_id").val(),
            country : $("#country_id").val()
          },
          function(data) {
            if (data != undefined && data != null) {
              $('ul.complete-list').html('');
              if (data.length > 0) {
                $('ul.complete-list').show();
                for (var offset = 0; offset < data.length; offset++) {
                  var city = data[offset];
                  $('ul.complete-list').append("<li><a href='javascript:void(0);' id='"+city.city_id+"' title=\""+city.name+"\">"+city.name+" - "+city.region+" ("+city.country+")</a></li>");
                }
              }
            }
          }
        );
      }
    }
  });
  $('ul.complete-list a').live('click', function() {
     selectItem($(this));
  });

   $("body").live('click', function() {
    if ($(this) != $('ul.complete-list a') && !focused) {
      $('ul.complete-list').hide();
    }
  });
});

function selectItem(item)
{
  $("input.complete").val(item.attr('title'));
  $("input#city_id").val(item.attr('id'));
  $('ul.complete-list').hide();
  fromComplete = true;
}

function utf8_encode(string) {
    var utftext = "",
        start, end, stringl = 0;

    start = end = 0;stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
         if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.slice(start, end);}
            utftext += enc;
            start = end = n + 1;
        }
    }
    if (end > start) {
        utftext += string.slice(start, stringl);
    }
     return utftext;
}
