function update_email() {
  var email = $('#email_value').html()   // If it starts with <span, it's blank
  if(email.match(/^<span/i)) email = "";

  $.post("/account/update_email_dialog", {nothing:"nothing"}, function(hash){
    dialog(hash.dialog, {ignore_bg_click:true, params:{email:email}});
  }, 'json');
  return false;
}

function update_password_form() {
  dialog('accounts/update_password.html', {ignore_bg_click:true, close_function:function(){window.location.reload(); return false;}});
  return false;
}

function check_availability() {
  var username = $('#username').val();

  if(! username) return dialog_from_hash({message:"Enter a username in the <b>username</b> field before clicking the 'check availability' link."});

  $.post('/account/check_availability', {user: username}, check_availability_callback, 'json');
  return false;
}
function check_availability_callback(hash) {
  $('#check_availability, #available, #not_available').hide();
  hash.result ? $('#available').show() : $('#not_available').show();
}

function sign_up_form(choose_username) {
  params = {};
  if(choose_username) params['do'] = 'choose_username';
  dialog('sign_up.html', {ignore_bg_click:true, params:params})

  //   analytics_event("Sign Up", "Clicked")

  return false;
}

function sign_up() {
  if(sign_up_errors)   // Error if there's a complaint on the page
    return dialog_from_hash({"message":"You must fix the errors before submitting (the <span style='color:#cc3333'>red text</span>)."});

  var fields = $('#sign_up').serializeHash();

  var activation_code = $("#activation_code");
  if(activation_code.length && $.trim(activation_code.val()) != "")
    fields['activation_code'] = activation_code.val();

  append_captcha_fields(fields);

  gl.sign_up_continue = sign_up;

  $.post("/account/sign_up", fields, sign_up_callback, 'json');
  return false;
}

function sign_up_callback(hash) {

  if(hash.result == 'request_activation_code') {

    close_dialog();
    dialog('accounts/activation_code_box.html');
    return true;
  }

  if(hash.result == "email_already_used") {   // specific error
    dialog_from_hash(hash);
    return true;
  }

  if(handle_captcha_response(hash, sign_up)) return;

  if(hash.result == 'success') {
    //     analytics_event("Sign Up", "Success", {label:$('#username').val()})

    if($('#recaptcha_response_field').length) close_dialog();   // Close captcha dialog if open

  }else{
    dialog_from_hash(hash);
  }
}

function validate_sign_up_username() {
  var username = $("#username").val();
  var complaint = $("#username_complaint");

  if(username != "" && ! username.match(/^[a-z0-9]+$/)) {
    $('#check').hide()
    complaint.text("lower-case letters or numbers only");
  }else if(username != "" && username.length < 5) {
    $('#check').hide()
    complaint.text("not long enough");
  }else{
    $('#check').show()
    complaint.text("");
  }
}

function validate_sign_up() {
  sign_up_errors = false;
  var username = $('#username').val();

  var password = $('#password').val();
  var verify_password = $('#verify_password').val();
  var password_complaint = $('#password_complaint');
  var verify_password_complaint = $('#verify_password_complaint');
  var email = $('#email').val();
  var email_complaint = $('#email_complaint');

  sign_up_errors = sign_up_errors ||
    validate_password_and_verify(password, password_complaint, verify_password, verify_password_complaint);

  if(! email_valid(email) && email != ""){
    email_complaint.text("incomplete");
    sign_up_errors = true;
  }else
    email_complaint.text("");
}

function validate_password_and_verify(password, password_complaint, verify_password, verify_password_complaint) {
  var bad_passwords = "qwertyuiop asdfghjkl; 123123123 1234567890 password1234 passphrase1234 anonymous1234 abcdefghij abc123456 letmein1234 liverpool charlie monkey arsenal thomas"

  errors = false;
  if(password == "")
    password_complaint.text("");
  else if(password.length < 6) {
    password_complaint.text("not long enough");
    errors = true;
  }else if(bad_passwords.indexOf(password) >= 0 || password.match(/(.)\1\1\1/) || password.match(/(..)\1\1/)) {
    password_complaint.text("not strong enough");
    errors = true;
  }else{
    password_complaint.text("");
  }

  if(password != verify_password && verify_password != ''){
    verify_password_complaint.text("doesn't match");
    errors = true;
  }else
    verify_password_complaint.text("");

  return errors;
}

function email_valid(email) {
  return email.match(/^[.\w_+-]+@[.\w-]+\.[\w-][\w-]+$/);
}

function resend_verify_email() {
  $.post("/account/resend_verify_email", {nothing:"nothing"}, resend_verify_email_callback, 'json');
  return false;
}

function resend_verify_email_callback(hash) {
  if(hash.result == 'success') {
    close_dialog();
    dialog("An email was sent to <b>"+hash.email+"</b> to confirm.  Look for this email shortly and click the link you'll find in it, to confirm the address.", {elephant:true});
  } else {
    dialog((hash.message || "An error occurred"));
  }
}

function email_opt_in_dialog() {
  $.post("/account/email_opt_in_dialog", {nothing:"nothing"}, function(hash){dialog(hash.dialog)}, 'json');
  return false;
}

function email_opt_in_subscribe() {
  $.post("/account/email_opt_in_subscribe", {nothing:"nothing"}, email_opt_in_subscribe_callback, 'json');
  return false;
}

function email_opt_in_unsubscribe() {
  $.post("/account/email_opt_in_unsubscribe", {nothing:"nothing"}, email_opt_in_subscribe_callback, 'json');
  return false;
}

function email_opt_in_resubscribe() {
  $.post("/account/email_opt_in_resubscribe", {nothing:"nothing"}, email_opt_in_subscribe_callback, 'json');
  return false;
}

function email_opt_in_subscribe_callback(hash) {
  close_dialog();
  close_dialog();
  dialog(hash.dialog, {elephant:true});
}


function captcha_continue() {
  if($('#recaptcha_response_field').val() == "")
    return dialog_from_hash({message:"You can't leave these fields blank:<div class='top2 bold'>Type the two words</div>"}, {leave_captcha_open:true});

  gl.captcha_on_submit();   // Call original method, to continue on
  return false;
}

function captcha(on_submit) {
  gl.captcha_on_submit = on_submit;// || gl.on_submit;
  load_then_call('Recaptcha', 'http://api.recaptcha.net/js/recaptcha_ajax.js', 'captcha_display()');
  return true;
}

function captcha_display() {

  if($('#recaptcha_response_field').length)  close_dialog();   // Close captcha dialog if open
  dialog("captcha.html", {ignore_bg_click:true});

  return false;
}

function append_captcha_fields(params) {
  var recaptcha_response_field = $("#recaptcha_response_field");
  if(! recaptcha_response_field.length) return;

  params['recaptcha_response_field'] = recaptcha_response_field.val();
  params['recaptcha_challenge_field'] = $("#recaptcha_challenge_field").val();
}

function handle_captcha_response(hash, after_code) {
  if(! hash.result.match(/^captcha/)) return false;   // Do nothing if not captcha response

  // If recaptcha not open yet, just open it
  if(! $('#recaptcha_response_field').length) return captcha(after_code);

  if(hash.message) dialog(hash.message, {elephant:true, continue_button:true});

  else{
    dialog("<div class='center top2'>The words you entered didn't match.</div><div class='center top4'><button onclick=\"close_dialog(); Recaptcha.reload(); return false;\" style='width:160px' id='try_again'>Try Again</button></div>", {leave_captcha_open:true});
    $("#try_again").focus();
    return true;
  }

  Recaptcha.reload();
  return true;
}

function sign_in() {
  var fields = $('#sign_in').serializeHash();

  append_captcha_fields(fields);

  $.post("/account/sign_in", fields, sign_in_callback, 'json');
  return false;
}

function sign_in_callback(hash) {
  if(handle_captcha_response(hash, sign_in)) return;

  if(hash.result == 'error') {
    if($('#recaptcha_response_field').length)  close_dialog();   // Close captcha dialog if open
    return dialog_from_hash(hash);
  }
}

function choose_username_and_password() {
  gl.assign_username_continue = function(){
    window.location.reload();
    loading_elephant();
  };
  assign_username('choose_username');
  return false;
}

function upgrade_from_account() {
  $.post('/account/upgrade_from_account', {}, function(){
    window.location = "/account/upgrade";
  });
  loading_elephant();
  return false;
}

