﻿/**strength_check
  Check the strength of the password and that the two fields match
  this function should be delay very briefly to allow
  the input box to actually change its a value before
  running the check
*/

function strength_check() {
  //a small delay to allow the input box to actually change
  var check = document.getElementById("passwordConfirm");
  var pass = document.getElementById("password");
  var strength_bar = document.getElementById("strength_bar");
  var strength_text = document.getElementById("strength_text");

  try {
    strength_bar.style.width = getStrength(pass.value, strength_text) + "%";
  } catch (e) {
    strength_bar.style.width = "0%"
    strength_text.innerHTML = "Weak";
  }
}
//check the strength of a given passowrd. This same function
//should be implemented on the server side as a static method
//within the password class
function getStrength(word,text) {

  var length = word.length;
  var numbers = word.count("[0-9]"); //numbers
  var upperCase = word.count("[A-Z]"); //upper case characters
  var lowerCase = word.count("[a-z]");  //lower case characters
  var weird = word.count("[^A-Za-z0-9]"); //non-alphanumeric

  if (length > 10) length = 10;
  if (numbers > 2) numbers = 2;
  if (upperCase > 2) upperCase = 2;
  if (lowerCase > 2) lowerCase = 2;
  if (weird > 1) weird = 1;

  var total = (numbers / 2) * 0.2;
      total+= (upperCase / 2) * 0.2; 
      total+= (lowerCase / 2) * 0.1;
      total+= (length / 10) * 0.4;
      total+= (weird / 1) * 0.1;
      
  if(length == 0) {
    text.innerHTML = "Password not set"
  } else if(total < 0.5) {
    text.innerHTML = "Weak";
  } else if(total < 0.7) {
    text.innerHTML = "Medium";
  } else {
    text.innerHTML = "Strong";
  }

  return total*100; //not set
}

/**
  Register an account
*/
function Register(f, redirect) {
  //check all required fields are filled
  if ($form.basicValidation(f) != null) {
    document.getElementById("register_errors").innerHTML = errors["incomplete"];
    return false;
  }

  request(f.action, f, function() {
    var error = null;
    var message = arguments[0];
    if (message == "success") {
      $('registerForm').innerHTML = '';
      $('registered').style.display = '';
    } else {
      $("register_errors").innerHTML = errors[message];
    }
  });
  
  return false;
}

/** Account login */
function Login(f, redirect) {

  if ($form.basicValidation(f) != null) {
    return false;
  }
  f["submit"].disabled = true;
  /*
  document.getElementById("Profile").Rewind();
  document.getElementById("Profile").Play();
  */
  //let the Profile spinner go for a half second before loading...
  setTimeout(function() {
    request(f.action, f, function() {
      if (arguments[2] == false) {
        $("login_error").innerHTML =
          "Error contacting the server";
      }
      var error = null;
      var status = arguments[0];
      f["submit"].disabled = false;

      if (status == "success") {
        location = redirect;
      } else {
        $("login_error").innerHTML = errors[status];
      }
    })
  }, 500 //half second time out
  );

  return false;
}

/*
  Post action for 
*/
function passwordChange(f) {
  if (basicValidation(f) != null) {
    return false;
  }

  if (f["password"].value != f["match"].value) {
    $("change_error").innerHTML = "Passwords do not match";
    markField(f["password"], true);
    markField(f["match"], true);
    return false;
  }
  
  request(f.action, f, function() {
    if (arguments[2] == false) {
      $("change_error").innerHTML = "Error contacting the server";
    }
    
    if (arguments[0] == "success") {
      $("change_error").innerHTML =
        "<font color='#0a0'>Password changed successfully</font>";
    } else {
      $("change_error").innerHTML = decodeError(arguments[0]);
    }
  });

  return false; 
}

//Security question displayed in the password reset
//field after an email is provided
var hasSecurityQuestion = false;
//number of times the user tried to answer the 
//security question
var securityAttempts = 0;

function resetPassword(f) {
  //check the user entered an email
  if (f['username'].value == "") {
    markField(f.getElementById('answer'), true);
    document.getElementById("reset_error").innerHTML =
      "Please enter your email.";
    return false;
  }
  //check the user answer the question if it's showing
  if (hasSecurityQuestion == true) {
    if (f['answer'].value == "") {
      markField(f['answer'], true);
      document.getElementById("reset_error").innerHTML =
        "No security answer provided";
      return false;
    } else {
      markField(f['answer'], false);
    }
  }
  //remove the error after validation passes.
  document.getElementById("reset_error").innerHTML = "";

  //show the grind
  document.getElementById("passResetLoad").style.display = "block";

  //The user has not provided a security answer yet  
  if (hasSecurityQuestion == false) {
    request(f.action, f, function() {
      //hide the grind
      document.getElementById("passResetLoad").style.display = "none";
      if (arguments[2] == false || arguments[0] == null) {
        document.getElementById("reset_error").innerHTML =
          "Error contacting the server.";
        return;
      }

      securityAttempts = 0;
      var status = arguments[0].split(":");
      if (status[0] == "success") {
        document.getElementById("reset_question").style.display = "block";
        document.getElementById("security_question").innerHTML = status[1];
        document.getElementById("reset_explination").innerHTML =
          "To reset your password please answer the security " +
          "question. Your new password will be mailed to you at the " +
          "address provided.";

        hasSecurityQuestion = true;
      } else if (status[0] == "bad email") {
        document.getElementById("reset_error").innerHTML =
          "No account linked to email.";
      }
    });
    //the security answer was present, attempt to reset the password.
  } else {
    request(f.action, f, function() {
      //hide the grind
      document.getElementById("passResetLoad").style.display = "none";
      //the reset was a success
      if (arguments[2] == false || arguments[0] == null) {
        document.getElementById("reset_error").innerHTML =
          "Error contacting the server.";
        return;

      } else if (arguments[0] == "success") {
        document.getElementById("reset_explination").innerHTML =
          "Your password has been reset. You should recieve an email " +
          "containing your new password."

        document.getElementById("reset_question").style.display = "none";
        document.getElementById("reset_question").style.display = "none";
        document.getElementById("security_question").innerHTML = "";

        hasSecurityQuestion = false;

        //the user probably changed the email in the first field 
      } else if (arguments[0] == "bad email") {
        document.getElementById("reset_error").innerHTML =
          "No account linked to email.";
        //the user provided the wrong answer
        //taunt them if they can't get it right
      } else if (arguments[0] == "badlogin") {
        securityAttempts++;
        if (securityAttempts == 1) {
          document.getElementById("reset_error").innerHTML =
            "Try again?";
        } else if (securityAttempts == 2) {
          document.getElementById("reset_error").innerHTML =
            "Wrong answer";
        } else if (securityAttempts == 3) {
          document.getElementById("reset_error").innerHTML =
            "Are you sure this is your account?";
        } else if (securityAttempts == 4) {
          passwordResetScreen(false);
        }
      }
    });
  }
  return false;
}


function termsScreen(show) {
  if (show) {
    document.getElementById("termsOfService").style.display = "block";
  } else {
    document.getElementById("termsOfService").style.display = "";
  }
}

function privacyScreen(show) {
  if (show) {
    document.getElementById("privacyPolicy").style.display = "block";
  } else {
    document.getElementById("privacyPolicy").style.display = "";
  }
}