(function() {
  Evader.validator = function() {
    this.errors = 0;

    this.validatePresence = function(val, $field) {
      if(val === '') {
        $field.addClass('error');
        this.errors += 1;
        return false;
      } else {
        return true;
      }
    };

    this.validateIsIP = function(val, $field) {
      if(val !== '') {
        var address = new v4.Address(val);

        if(address.isValid()) {
          return true;
        } else {
          address = new v6.Address(val);
          if(address.isValid()) {
            return true;
          } else {
            $field.addClass('error');
            this.errors += 1;
            return false;            
          }
        }
      }
    };

    this.validateIPRange = function(val, $field) {      
      if(val !== '') {
        if(val.match(/-/)) {
          var ips = val.split('-');
          return this.validateIsIP($.trim(ips[0]), $field) && this.validateIsIP($.trim(ips[1]), $field);
        } else {
          return this.validateIsIP(val, $field);
        }
      }    
    };
    
    this.hasErrors = function() {
      return this.errors !== 0;
    };
  };


  Evader.validate = function($form) {
    var $source = $('#netconfig_src_ip'),
        $gateway = $('#netconfig_gateway'),
        $gateway_needed = $('#gateway_needed_yes'),
        $target = $('#netconfig_dst_ip'),
        validator = new Evader.validator();

    validator.validatePresence($source.val(), $source);
    validator.validatePresence($target.val(), $target);
    
    validator.validateIPRange($source.val(), $source);
    validator.validateIsIP($target.val(), $target);
    
    if($gateway_needed.is(':checked')) {
      validator.validatePresence($gateway.val(), $gateway);
      validator.validateIsIP($gateway.val(), $gateway);
    }

    return !validator.hasErrors();
  };
})();
