Event.observe(window, 'load', function() {
 if($('register_form'))
   $('register_form').observe('submit', validateRegForm);

 if($('auth_password1'))
   $('auth_password1').observe('keyup', checkAllowedPasswordCharacters);
});

// {{{ validateRegForm(ev)
function validateRegForm(ev) {

  var errors=[];

  // {{{ Username:
  var el = $('auth_user_name');
  if(!el || !el.value) {
    if(!$('current_username')) {
      errors.push('Please enter an account name');
    }
  } else {
    // Be nice and strip leading/trailing whitespace now:
    el.value = el.value.replace(/^\s+/, '').replace(/\s+$/, '');

    var val = $F(el);
    if(!val.match(/^[a-zA-Z0-9_]{4,20}$/)) {
      errors.push('Your account name must contain only letters, numbers and '
                + 'underscores\nand be 4-20 characters long.');
      if(val.match(/\s/)) {
        errors.push('Your account name contains white spaces.');
      }
    }

    // Check if checked if username exists. This is set if AJAX component on
    else if($('auth_user_name_inuse')) {
      errors.push('The selected account name is already take.');
    }
  } // }}}

  // {{{ Password
  el = $('auth_password1');
  if(el) {
    if(!el.value) {
      if(!$('current_username')) {
        errors.push('Please enter a password.');
      }
    } else {
      var p2 = $('auth_password2');
      if(!p2 || !p2.value) {
        // This is covered by checkreqfields.js
        // errors.push('Please enter your password again for confirmation.');
      } else if(p2.value != el.value) {
        errors.push('Your password confirmation does not match '
                  + 'your original password.');
      } else if(!CheckPasswordSecurity()) {
        errors.push('Please enter a secure password.');
      }
    }
  } // }}}

  // {{{ Only validate if not registering as a guest:
  if(!$('auth_register_as_guest') ||
      $('auth_register_as_guest').checked != 'checked') {

    var checkList = [];

    if(typeof(reqFields) != 'undefined') {
      reqFields.each(function(rec) { checkList.push(rec); });
    }

    checkList.each(function(kv) {
      if(!$(kv[0]) || !$F(kv[0] || $F(kv[0]).match(/^\s+$/))) {
        // See if we can find a localized copy of the label ...
        var label = $('register_form').select('label[for=' + kv[0] +']');
        if(label && label[0]) { label = label[0].textContext; }
        errors.push('You must enter your ' + (label || kv[1]) +'.');
      }
    });

    if($('auth_email')) {
      var val = $F('auth_email');

      if($('auth_email_select')) {
        val += '@' + $F('auth_email_select');
      }

      if(!val) {
        // Already used error above
      } else if(!val.match(/^[0-9a-zA-Z_.-]+@[a-zA-Z0-9-.]+\.[a-z]{2,}$/)) {
        errors.push('You must enter a valid e-mail address.');
      } else {
        if($('auth_email2') && $val != $F('auth_email2')) {
          errors.push('Your e-mail confirmation does not match your '
                    + 'original e-mail address.');
        } else if(typeof(validateEmail) != 'undefined' &&
                  typeof(auth_email_type) != 'undefined' &&
                  !validateEmail()) {
          errors.push('Your e-mail address is not valid or accepted.');
        }
      }
    }
  } // }}}

  // {{{ Verify correct size of Captcha
  el = $('captchabox');
  if(el) {
    if(!el.value) {
      errors.push('Please enter the CAPTCHA code to proceed');
    }

    else if(el.size && el.value.length !== el.size) {
      errors.push('Please enter the CAPTCHA code that is displayed.\n'
            + 'If you cannot read the image click on the "Reload Code" link.');
    }
  } // }}}

  // {{{ URL - must be valid if anything entered.
  var el = $('auth_url');
  if(el && !validateURL(el)) {
    errors.push('Please enter a valid URL of the form http://xyz.com/');
  } // }}}


  if(errors.length) {
    ev.stop();
    alert(errors.join("\n"));
  }

} // }}}


// {{{ checkAllowedPasswordCharacters(ev)
function checkAllowedPasswordCharacters(ev) {
  var err = $('auth_password1err');
  if(!err) return;

  var val = $F('auth_password1');

  if(val.length == 0)
    return;

  var errtxt = '';

  // Only warn if not already doing so:
  if(!$('pstests')) {
    if(val.length < 4) {
      errtxt = 'Password Must be 4+ characters';
    } else if(val.length > 20) {
      errtxt = 'Password Must be less than 20 characters';
    }
  }

  var badMatch = new RegExp(/[^\[\]a-zA-Z0-9<>!@#$%^&*()\/{};':",.?_=+-]/);
  if(val.match(badMatch)) {
    errtxt = 'Password contains invalid characters.';
  }

  if(errtxt) {
    err.childElements().each(function(el) { Element.remove(el); });
    err.appendChild(new Element('br'));
    err.appendChild(new Element('span', {className: 'error'}).update(errtxt));
    err.show();
  } else {
    err.update('');
    err.hide();
  }
} // }}}

// {{{ validateURL(ev_or_el)
function validateURL(ev_or_el) {
  var el = ev_or_el.element ? Event.element(ev_or_el) : ev_or_el;

  if(!el || !el.value)
    return 1;

  var v = new String($F(el)).toLowerCase().replace(/^\s+/, '').replace(/\s+$/, '');
  if(el.value !== v)
    el.value = v;

  if(!v.match(/^https?:\/\//)) {
    v = 'http://' + v;
    el.value = v;
  }

  var ret = v.match(/^https?:\/\/[a-z0-9-]+\.(?:[a-z0-9-]+\.)*[a-z]{2,}(?:[\/?].*)?$/);
  return ret;
} // }}}
