/**
 *  Register click events for login
 *
 */
var CALLBACK_FUNCTION="";
function ajax_login_init(callback_function) {
  CALLBACK_FUNCTION = callback_function;

  // Unbind events from form submit
  $("form#iasg_signin").unbind('submit');

  $("form#iasg_signin").submit(function(){
    form_data = $("#iasg_signin").serialize();
    jQuery.ajax({
      type:     "POST",
      url:      SITE_URL+"ajax/login/iasg_login",
      data:     form_data,
      success:  function(json){
                  self.parent.tb_remove();
                  if (json.success && json.payload.logged_in) {
                    $("form#iasg_signin :input").val("");
                    if (json.payload.reload_page)
                      window.location.reload();
                    else
                      if (typeof CALLBACK_FUNCTION == 'function')
                        CALLBACK_FUNCTION();
                  }
                  else {
                    $("form#iasg_signin")[0].reset();
                    $("form#iasg_signin #signin_errors").css({'color':'red'});
                    $("form#iasg_signin #signin_errors").html('Login information is incorrect.');
                    setTimeout(
                      'self.parent.tb_show("Login to IASG", "#TB_inline?inlineId=signin_wrapper&height=250")',
                      250
                    );
                  }
                },
      dataType: "json"
    });
  });

}

/**
 *  Checks if a user is logged in, if they are not a modal will popup asking for
 *  the user to login
 *
 *  Returns true if logged in
 */
function check_login(callback_function){
  // Reintialize login form with callback function
  ajax_login_init(callback_function);

  $.getJSON(
    SITE_URL + 'ajax/login/is_loggedin',
    function(json){
      if (json.success) {
        if (json.payload.logged_in)
          if (typeof callback_function == 'function')
            callback_function();
          else
            return true;
        else
          return login_with_ajax(callback_function);
      }
      else
        return false;
    }
  );
}

/**
 *  Displays the login form with a modal box
 *
 */
function login_with_ajax(callback_function) {
  $('form#iasg_signin input#reload_page').val('false');
  self.parent.tb_show('Login to IASG', "#TB_inline?inlineId=signin_wrapper&amp;height=250");
}

/**
 *    Check a text input value against a bad value
 *
 */
function checkInput(element, bad_value) {
  valid = true;
  if (element.val() == bad_value) {
    element.addClass("error");
    valid = false;
  }
  else
    element.removeClass("error");
  return valid;
}

// HACK: use a global because I can't seem to save and return the JSON response
// back the proper way -- George
var VALID_EMAIL;

/**
 *    AJAX call to server to check if the email has already been registered
 *
 */
function is_registered_email (email_address) {
    VALID_EMAIL = null;
    $.ajax({
        async : false,
        url: SITE_URL + 'ajax/is_email_registered',
        data: { email: email_address },
        dataType: "json",
        success: function(response){
            VALID_EMAIL = !response.payload.registered;
        }
    });
}

/**
 *    Checks an phone element to see if it is valid
 *
 */
function checkPhone(phone_element, error_element) {
    error_element.hide("fast");
    if (phone_element.val() == "") {
        phone_element.addClass("error");
        return false;
    }

  // Simple validation which check for the number of phone # digits
    var strPhone = phone_element.val().replace(/\D/g, '');
    var phoneCount = strPhone.length;
    if (phoneCount == 7
        || phoneCount == 8
        || phoneCount == 10
        || phoneCount == 11
        || phoneCount == 12
    ) {
    phone_element.removeClass("error");
        return true;
    }

  phone_element.addClass("error");
    error_element.html("Invalid phone number format.");
    error_element.show("slow");
    return false;
}

/**
 *    Checks an email element to see if it is valid
 *
 */
function checkEmail(email_element, error_element) {
    error_element.hide("fast");
    if (email_element.val() == "") {
        email_element.addClass("error");
        return false;
    }

    emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    email_str = email_element.val();
    if(!email_str.match(emailRegEx)) {
      email_element.addClass("error");
        error_element.html("Invalid email address.");
        error_element.show("slow");
        return false;
    }

  email_element.removeClass("error");
    is_registered_email(email_element.val());
    if (!VALID_EMAIL) {
        email_element.addClass("error");
        error_element.html("Email is already registered.");
        error_element.show("slow");
    }

    return VALID_EMAIL;
}

/**
 *    Validates step 1 of the registration process
 *
 */
function step_1_is_valid() {
  first_name_valid = checkInput($("input#first_name"), "First Name")
  last_name_valid = checkInput($("input#last_name"), "Last Name");
  email_valid = checkEmail($("input#email"), $("#email_registered_error"));
  password_valid = checkInput($("input#password"), "");
    phone_valid = checkPhone($("input#phone"), $("#phone_registered_error"));

  return  first_name_valid && last_name_valid && email_valid && password_valid && phone_valid;
}

/**
 *    Serializes form data for step 1
 *
 */
function step_1_serialize(){
  return  'first_name=' + $("input#first_name").val() +
          '&last_name=' + $("input#last_name").val() +
          '&email=' + $("input#email").val() +
          '&zip_code=' + $("input#zip_code").val() +
          '&password=' + $("input#password").val() +
          '&accredited=' + $("input#accredited").attr("checked") +
          '&remember_me=' + $("input#remember_me").attr("checked") +
          '&phone=' + $("input#phone").val();
}

/**
 *    Submits form data for step 1
 *
 */
function step_1_submit() {
  $("span#step_1_close_tb_x").replaceWith('');
  $("td#step_1_already_member").replaceWith('');
  $("td#step_1_actions_td").html('Registering...<br/><img src="' + IMAGE_URL +'loadingAnimation.gif">')
  // Simple check to make sure the google tracking function exists
  if (pageTracker && pageTracker._trackPageview) {
    pageTracker._trackPageview('/registration/submit');
  }
  $.post(
    SITE_URL + '/ajax/user_register_step_1',
    step_1_serialize(),
    function(json) {
      // Replace fields in our success message with name / email
            $("span#user_first_name").replaceWith(json.payload.first_name);
            $("span#user_email").replaceWith(json.payload.email);

            // Close previous, and display step 2
            self.parent.tb_remove();
            setTimeout(
        'self.parent.tb_show(null, "#TB_inline?inlineId=step_2&width=510&height=686&modal=true", null);',
        250
      );
    },
    "json"
  );
}

/**
 *    Serializes form data for step 2 and 3
 *
 */
function step_2_and_3_serialize() {

  return  '&portfolio_size=' + $("select#portfolio_size").val() +
          '&invest_style=' + $("input.invest_style:checked").val() +
          '&invest_stocks=' + $("input#invest_stocks").attr("checked") +
          '&invest_commodities=' + $("input#invest_commodities").attr("checked") +
          '&invest_forex=' + $("input#invest_forex").attr("checked") +
          '&invest_etf_and_mf=' + $("input#invest_etf_and_mf").attr("checked") +
          '&invest_managed_futures_forex=' + $("input#invest_managed_futures_forex").attr("checked") +
          '&invest_hedge_funds=' + $("input#invest_hedge_funds").attr("checked") +
          '&invested_in_managed_futures=' + $("input#invested_in_managed_futures:checked").val() +
          '&considering_investing_in_managed_futures=' + $("input#considering_investing_in_managed_futures:checked").val() +
          '&licensed_professional=' + $("select#licensed_professional").val() +
          '&phone=' + $("input#phone").val();
}

/**
 *    Serializes form data for step 2 and 3
 *
 */
function step_2_and_3_submit(){

  data = step_2_and_3_serialize();
  // Submit if data is not default data
  if (data != '&portfolio_size=&invest_style=dont_know&invest_stocks=false&invest_commodities=false&invest_forex=false&invest_etf_and_mf=false&invest_managed_futures_forex=false&invest_hedge_funds=false&phone=')
  {
    // Simple check to make sure the google tracking function exists
    if (pageTracker && pageTracker._trackPageview) {
      pageTracker._trackPageview('/registration/financial');
    }
    $.post(
      SITE_URL + '/ajax/user_register_step_2_and_3',
      step_1_serialize() + data,
      function(json) {},
      "json"
    );
  }

  $("form#registration_form")[0].reset();

  // Close previous, and display success modal
    self.parent.tb_remove();
  // Simple check to make sure the google tracking function exists
  if (pageTracker && pageTracker._trackPageview) {
    pageTracker._trackPageview('/registration/thankyou');
  }
    setTimeout(
    'self.parent.tb_show(null, "#TB_inline?inlineId=step_finished&width=515&height=375&modal=true", null);',
    250
  );

}

/**
 *    Create events for elements on page load
 *
 */
function ajax_registration_init() {

  $(".step_1_close").click(function(){
    $("form#registration_form")[0].reset();
    self.parent.tb_remove();
  });

    // Remove field identifiers on focus
  $("#first_name").focus(function(){
    if ($(this).val() == "First Name") {
      $(this).val("");
      $(this).removeClass("grey-text");
    }
  });
  $("#last_name").focus(function(){
    if ($(this).val() == "Last Name") {
      $(this).val("");
      $(this).removeClass("grey-text");
    }
  });

    // Add field indentifiers on blur if the field is blank
  $("#first_name").blur(function() {
    if ($(this).val() == "") {
      $(this).val("First Name");
      $(this).addClass("grey-text");
    }
  });
  $("#last_name").blur(function() {
    if ($(this).val() == "") {
      $(this).val("Last Name");
      $(this).addClass("grey-text");
    }
  });

    // Close login TB and open registration form
  $("#register_from_login").click(function(){
    self.parent.tb_remove();
    setTimeout(
      'self.parent.tb_show(null, "#TB_inline?inlineId=step_1&amp;width=500&amp;height=380&amp;modal=true", null)',
      250
    );
  });

    // Close registration TB and open login form
    $("#login_from_registration_link").click(function(){
    self.parent.tb_remove();
    setTimeout(
      'self.parent.tb_show("Login to IASG", "#TB_inline?inlineId=signin_wrapper&amp;height=250", null)',
      250
    );
  });

  $("a#step_1_continue").click(function(){
    if (step_1_is_valid())
      step_1_submit();
  });

  $("a.step_2_and_3_submit").click(function(){
    self.parent.tb_remove();
    // Simple check to make sure the google tracking function exists
    if (pageTracker && pageTracker._trackPageview) {
      pageTracker._trackPageview('/registration/thankyou');
    }
    setTimeout(
      'self.parent.tb_show(null, "#TB_inline?inlineId=step_finished&width=515&height=375&modal=true", null)',
      250
    );
  });

  $("#step_2_continue").click(function() {
    step_2_and_3_submit();
  });

}

