jQuery(document).ready(function () {
  jQuery.ajaxSetup({cache: false});
  Registration.init.call();
});

Registration = {};

Registration.init = function () {

  jQuery('#registration-overlay-trigger').overlay({
    // 50px from top of viewport
    top: 50,
    left: 'center',
    fixed: false,
    closeOnClick: false,
    mask: {
      color: '#000',
      opacity: 0.4,
      position: 'fixed'
    },
    onBeforeLoad: Registration.loadStep1
    // only for dev
    // onBeforeLoad: Registration.loadStep2Register
    // onBeforeLoad: Registration.loadStep2Activate

  });
    // only for dev
    // jQuery('#registration-overlay-trigger').click();

  var url_params = window.location.search.substring(1);
  if (url_params.indexOf('open_registration_overlay') === 0) {
    jQuery('#registration-overlay-trigger').click();
  }

};

Registration.loadStep1 = function () {
  jQuery('html').scrollTop(150);
  // Load main screen
  jQuery.ajax({
    url: MTSettings.basepath + 'ajax/registration/registration.cfc?method=step1',
    data: {
      'lang_id': MTSettings.langId
    },
    success: function (response) {
      jQuery('#registration-overlay .dynamic').replaceWith(response);
      jQuery('#registration-overlay .next').click(Registration.goToStep2);
    }
  });
};

Registration.validateStep1 = function () {
  var valid = true;
  if (jQuery('#registration-parent-permission-yes:checked').length == 0) {
    jQuery('#registration-parent-permission .mt-form-field').addClass('error');
    valid = false;
  } else {
    jQuery('#registration-parent-permission .mt-form-field').removeClass('error');
  }
  if (jQuery('#registration-overlay input:radio[name=registration-received-mail]:checked').length == 0) {
    jQuery('#registration-received-mail .mt-form-field').addClass('error');
    valid = false;
  } else {
    jQuery('#registration-received-mail .mt-form-field').removeClass('error');
  }
  if (valid == true) {
    jQuery('#registration-overlay button').removeClass('disabled');
  } else {
    jQuery('#registration-overlay button').addClass('disabled');
  }
};

Registration.goToStep2 = function () {
  Registration.validateStep1();
  // validation sets disabled class on button
  if (jQuery('#registration-overlay button').hasClass('disabled')) {
  // revalidate on change
    jQuery('#registration-overlay input').change(Registration.validateStep1);
  }
  else {
    if (jQuery('#registration-received-mail-yes:checked').length == 0) {
      Registration.loadStep2Register();
    } else {
      Registration.loadStep2Activate()
    }
  }
};

Registration.loadStep2Register = function () {
  jQuery.ajax({
    url: MTSettings.basepath + 'ajax/registration/registration.cfc?method=step2_register',
    data: {
      'lang_id': MTSettings.langId
    },
    success: function (response) {
      jQuery('#registration-overlay .dynamic').replaceWith(response);
      jQuery('html').scrollTop(150);
      Registration.enableStep2Validation();
      // BUTTONS NEXT / PREVIOUS
      jQuery('#registration-overlay .previous').click(Registration.loadStep1);
      jQuery('#registration-overlay .next').click(Registration.goToStep3);
    }
  });
};

Registration.loadStep2Activate = function () {
  jQuery.ajax({
    url: MTSettings.basepath + 'ajax/registration/registration.cfc?method=step2_activate',
    data: {
      'lang_id': MTSettings.langId
    },
    success: function (response) {
      jQuery('#registration-overlay .dynamic').replaceWith(response);
      jQuery('html').scrollTop(150);
      jQuery('#registration-overlay .previous').click(Registration.loadStep1);
      jQuery('#registration-overlay .next').click(Registration.searchActivationCode);
    }
  });
};

Registration.searchActivationCode = function () {
  // for validation issues
  var hasError = true;
  // Load main screen
  jQuery.ajax({
    // nice url for analytics
    url: MTSettings.basepath + 'ajax/registration/registration.cfc?method=step2_activate_search&lang_id=' + MTSettings.langId,
    type: 'POST',
    data: {
      'cardnr': jQuery('#registration-overlay input:text[name=cardnr_search]').val(),
      'lastname': jQuery('#registration-overlay input:text[name=lastname_search]').val()
    },
    success: function (response) {
      jQuery("#regError").html('');
      jQuery("#registrationField").removeClass('error');
      jQuery('#registration-overlay input:text[name=cardnr_search]').attr('disabled', 'disabled');
      jQuery('#registration-overlay input:text[name=lastname_search]').attr('disabled', 'disabled');
      jQuery('#registration-overlay .search-result-placeholder').replaceWith(response);
      Registration.enableStep2Validation();
      // BUTTONS NEXT / PREVIOUS
      jQuery('#registration-overlay .next').unbind('click', Registration.searchActivationCode);

      var registered = jQuery('#registration-overlay .dynamic').find('#alreadyregistered');

      if (registered.length == 0) {
          jQuery('#registration-overlay .previous').click(Registration.goToStep1);
          jQuery('#registration-overlay .next').click(Registration.goToStep3);
      } else {
          jQuery('#registration-overlay .previous').parents('.row').remove();
      }
    },
    error:  function() {
      jQuery("#registrationField").addClass('error');
      jQuery("#regError").html(errorHint1);
    }
  });
};

Registration.enableStep2Validation = function () {
  // ADD VALIDATION FIELDS ONBLUR
  jQuery('#registration-overlay input.validate:password').blur(Registration.validateStep2);
  jQuery('#registration-overlay input.validate:text'    ).blur(Registration.validateStep2);
  jQuery('#registration-overlay select.validate'        ).blur(Registration.validateStep2);
  jQuery('#registration-overlay input:radio'   ).click(Registration.validateStep2);
  // Multiple input validation (zip + city text field)
  jQuery('#registration-overlay input.validate:text'    ).focus(function() {
    jQuery(this).parents(".mt-form-field").removeClass('error');
    jQuery(this).next(".errorHint").hide();
  });
  // Multiple input validation (birthday select fields)
  jQuery('#registration-overlay select.validate'        ).focus(function() {
    jQuery(this).parents(".mt-form-field").removeClass('error');
  });
};

Registration.validateStep2 = function () {
    var parent = jQuery(this).parents(".mt-form-field");
    var childsToValidate = parent.find('.validate')
    parent.data('validation_ok', true);
    childsToValidate.each(function () {
      Registration.validateInput(this, parent);
    });

    if (parent.data('validation_ok')) {
      parent.removeClass('error');
    }  else {
      parent.addClass('error');
    }

};

Registration.validateInput = function (element, parent) {
    var value = jQuery(element).val();
    var attrName = jQuery(element).attr('name');
    // EMPTY VALIDATION
    if (value == '') {
        jQuery('#registration-overlay').data('validation_ok', false);
      parent.data('validation_ok', false);
    }
    // EMAIL VALIDATION
    if (attrName == 'email') {
      if(!isValidEmailAddress(jQuery(element).val())) {
        jQuery('#registration-overlay').data('validation_ok', false);
        parent.data('validation_ok', false);
        parent.find('.errorHint').show();
      } else {
        parent.data('validation_ok', true);
        parent.find('.errorHint').hide();
      }
    }
    // PASSWORD REGEX VALIDATION
    if (attrName == 'password') {
      if(!isValidPassword(jQuery(element).val())) {
        jQuery('#registration-overlay').data('validation_ok', false);
        parent.data('validation_ok', false);
        parent.find('.errorHint').show();
      } else {
        parent.data('validation_ok', true);
        parent.find('.errorHint').hide();
      }
    }
    // PASSWORD CONFIRMATION VALIDATION
    if (attrName == 'confirmpassword') {
      var pass1 = jQuery('#registration-password').val();
      var pass2 = jQuery(element).val();
      if(pass1 !== pass2) {
        jQuery('#registration-overlay').data('validation_ok', false);
        parent.data('validation_ok', false);
        parent.find('.errorHint').show();
      } else {
        parent.data('validation_ok', true);
        parent.find('.errorHint').hide();
      }
    }
    // NICKNAME VALIDATION
    if (attrName == 'nickname') {
      isValidNickName(jQuery(element).val())
    }
    // RADIOGROUP VALIDATION
    if (attrName == 'gender') {
      if (jQuery('#registration-overlay input:radio[name=gender]:checked').length == 0) {
        jQuery('#registration-overlay').data('validation_ok', false);
        parent.data('validation_ok', false);
      } else {
        parent.data('validation_ok', true);
      }
    }
  };

Registration.goToStep3 = function () {

  jQuery('#registration-overlay').data('validation_ok', true);

  jQuery('#registration-overlay .validate').each(function() {
    Registration.validateStep2.call(this);
  });

  if (jQuery('#registration-overlay').data('validation_ok') && jQuery('#registration-overlay input:text[name=nickname]').data('validation_ok')) {
    var lang_id = jQuery('#registration-overlay input:radio[name=lang_id]:checked').val();
    // Hide Buttons and add waiting image
    jQuery('#registration-overlay .buttons').html('<img src="/images/overlay-loader.gif" />')
    //Load 3thd screen
    var dataString = jQuery("#formStep2").serialize();
    jQuery.ajax({
      url: MTSettings.basepath + 'ajax/registration/registration.cfc?method=step3&lang_ID=' + lang_id,
      type: 'POST',
      dataType: 'JSON',
      data: dataString,
      success: function (response) {
        jQuery('#registration-overlay .dynamic').replaceWith(response);
        jQuery('html').scrollTop(150);
        // toggle Newsletter
        jQuery('#is_newsletter').click(Registration.toggleNewsletter);
        // BUTTONS PREVIOUS
        jQuery('#registration-overlay .previous').click(Registration.loadStep1);
      }
    });
  }
};

/* toggle Newsletter subscription ON / OFF */
Registration.toggleNewsletter = function () {
  if (jQuery('#is_newsletter:checked').length == 0) {
    var is_newsletter_val = true;
  } else {
    var is_newsletter_val = false;
  }
  jQuery.ajax({
    url: MyAccount.saveUrl,
    type: 'post',
    dataType: 'json',
    data: {
      'name': 'is_newsletter',
      'value': is_newsletter_val,
      'lang_id': MTSettings.langId
    }
  });
};

function isValidEmailAddress(emailAddress) {
  // var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);

  var pattern = new RegExp(/^(.+\@([a-zA-Z0-9]{2,6})+[.])+[a-zA-Z0-9]{2,6}/i);

  return pattern.test(emailAddress);
}

function isValidPassword(Password) {
  var pattern = new RegExp(/([a-zA-Z0-9]{6,10})/i);
  return pattern.test(Password);
}

function isValidNickName(Nickname) {

  var parent = jQuery('#registration-overlay input:text[name=nickname]');

  if(Nickname == '') {
    parent.data('validation_ok', false);
    } else {
    jQuery.ajax({
      url: MTSettings.basepath + 'ajax/registration/registration.cfc?method=nickname_validation',
      data: {
        'nickname': Nickname
      },
      success: function() {
      parent.data('validation_ok', true);
      parent.parents(".mt-form-field").removeClass('error');
      parent.next(".errorHint").hide();
      },
      error: function() {
      parent.data('validation_ok', false);
      parent.parents(".mt-form-field").addClass('error');
      parent.next(".errorHint").show();
      }
    });
  };
};
