function intToIP(int) {
  var part1 = int & 255;
  var part2 = ((int >> 8) & 255);
  var part3 = ((int >> 16) & 255);
  var part4 = ((int >> 24) & 255);

  return part4 + "." + part3 + "." + part2 + "." + part1;
}

function handleUserLatencyForm(){
  var $userLatenciesForm   = $('form#user_latencies_form');
  var $latenciesMyUser     = $userLatenciesForm.find('#latencies_my_user');
  var $latenciesMyUserId   = $userLatenciesForm.find('#latencies_my_user_id');
  var $latenciesMyPublicIp = $userLatenciesForm.find('#latencies_my_public_ip');

  $latenciesMyUser.on('focus', function(){
    $latenciesMyUserId.val('')
  });

  $latenciesMyUser.bind('railsAutocomplete.select', function(event, data){
    $latenciesMyUserId.val('');
    $latenciesMyPublicIp.val('');
    if(data.item.last_jam_addr){
      var ipAddr = intToIP(data.item.last_jam_addr);
      $latenciesMyPublicIp.val(ipAddr);
    }
    $latenciesMyUserId.val(data.item.id);
  });

  $userLatenciesForm.find('#latencies_user_1').bind('railsAutocomplete.select', function(event, data){
    $userLatenciesForm.find('#latencies_user_1_id').val(data.item.id);
  });

  $userLatenciesForm.find('#latencies_user_2').bind('railsAutocomplete.select', function(event, data){
    $userLatenciesForm.find('#latencies_user_2_id').val(data.item.id);
  });

  $userLatenciesForm.find('#latencies_user_3').bind('railsAutocomplete.select', function(event, data){
    $userLatenciesForm.find('#latencies_user_3_id').val(data.item.id);
  });

  $userLatenciesForm.find('#latencies_user_4').bind('railsAutocomplete.select', function(event, data){
    $userLatenciesForm.find('#latencies_user_4_id').val(data.item.id);
  });

  $userLatenciesForm.find('#latencies_user_5').bind('railsAutocomplete.select', function(event, data){
    $userLatenciesForm.find('#latencies_user_5_id').val(data.item.id);
  });
}

function handleLatencyRecommendationForm(){
  var $latencyRecommendationForm = $('form#latency_recommendation_form');
  var $latenciesMyUser     = $latencyRecommendationForm.find('#latency_recommendation_my_user');
  var $latenciesMyUserId   = $latencyRecommendationForm.find('#latency_recommendation_my_user_id');
  var $latenciesMyPublicIp = $latencyRecommendationForm.find('#latency_recommendation_my_public_ip');

  $latenciesMyUser.on('focus', function(){
    $latenciesMyUserId.val('')
  });

  $latenciesMyUser.bind('railsAutocomplete.select', function(event, data){
    $latenciesMyUserId.val('');
    $latenciesMyPublicIp.val('');
    if(data.item.last_jam_addr){
      var ipAddr = intToIP(data.item.last_jam_addr);
      $latenciesMyPublicIp.val(ipAddr);
    }
    $latenciesMyUserId.val(data.item.id);
  });

  
}

$(document).ready(function() {
  handleUserLatencyForm();
  handleLatencyRecommendationForm();
});