$(function() {
  $('.slider').slider({
    min: 1,
    max: 4,
    value: $('#mongbat_maxev').val(),
    slide: function(e, ui) {
      $('#mongbat_maxev').val(ui.value).trigger('change');
    }
  });
  
  $(document).bind('evader.configuration_loaded', function() {
    $('#netconfig_iface').dropdown({
      stack: false,
      onOptionSelect: function() {
        $('#netconfig_iface').trigger('change');
      }
    });

    if($('.presets').length > 0) {
      Evader.networkPresets = JSON.parse($('.network_presets_json').html());
      Evader.targetPresets = JSON.parse($('.target_presets_json').html());

      $('.presets.network select').dropdown({
        stack: false,
        onOptionSelect: function(li) {
          var name = li.text(),
              preset = _.first(_.select(Evader.networkPresets, function(preset) {
                return preset.name === name;
              }));
          
          if(preset) {
            if(preset.iface) {
              $('#netconfig_iface').val(preset.iface);
              $('.interface .cd-dropdown').children('span').text(preset.iface);
            }
            $('#netconfig_src_ip').val(preset.src_ip);
            $('#netconfig_gateway').val(preset.gw);
            $('#netconfig_dst_ip').val(preset.dst_ip);
            $('#netconfig_src_mask').val(preset.src_mask);
            targetPresetSelected($('.target.presets .cd-dropdown').children('span').text());
          }
        }
      });

      var targetPresetSelected = function(name) {
        var preset = _.first(_.select(Evader.targetPresets, function(preset) {
              return preset.name === name;
            }));
        
        if(preset) {
          var ip = $('#netconfig_dst_ip').val(),
              address = new v4.Address(ip);

          if(address.isValid()) {
            ip = ip.split('.');
            ip[ip.length - 1] = preset.ip_end;
            ip = ip.join('.');
          } else {
            ip = ip.split(':');
            ip[ip.length - 1] = preset.ipv6_end;
            ip = ip.join(':');
          }

          $('#netconfig_dst_ip').val(ip);
        }        
      };

      $('.presets.target select').dropdown({
        stack: false,
        onOptionSelect: function(li) {
          targetPresetSelected(li.text());
        }
      });
      
      $('#netconfig_src_mask').val('');
    }
  });  
});