"use strict";
/*jslint white: true, devel: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true, indent: 2 */
/*global FormError, FormValidator, ErrorsFormatter*/
var EK = EK || {};

EK.Auth = {
  popupOptions: {
    close : true,
    escClose : true,
    overlayCss : {
      backgroundColor : 'black'
    },
    closeClass : 'sglg_close',
    onClose: function () {
      $.modal.close();
      $('.popup-auth').hide();
      window.location.replace('#');
    },
    position: ['15px']
  },
  init: function () {
    this.bind();
  },
  popup: function (hash) {
    if ($('.popup-auth').length) {
      var isBack = $('#terms_dialog').is(':visible');

      $('#terms_dialog, #popup-auth-signup, #popup-auth-login').hide();
      $('#guest_dialog, #popup-auth-' + hash).show();

      if ($('#simplemodal-container').length && isBack) {
        EK.Auth.resizePopup("#guest_dialog");
      } else {
        $('.popup-auth').show().modal(EK.Auth.popupOptions);
      }

      EK.Auth.loadErrors();

      $('#popup-auth-signup a, #popup-auth-login a').removeClass('active');
      $('#guest_dialog .sglg_tabs li a').removeClass('active').filter('[href=#' + hash + ']').addClass('active');
    }
  },
  loadErrors: function () {
    var $error = $('#error-message-container');

    if ($error.length && $error.html()) {
      var type = $error.getParam('type'),
          error = new FormError($error.html());
      if (type === 'login') {
        FormValidator.showErrors(error, "#popup-auth-login .form-errors");
        $('#popup-auth-login .slgl_errors_hold').show();
      } else {
        FormValidator.showErrors(error, "#popup-auth-signup .form-errors");
        $('#popup-auth-signup .slgl_errors_hold').show();
      }
    }
  },
  showTerms: function () {
    if ($('.popup-auth').length) {
      $('#guest_dialog').hide();
      $('#terms_dialog').show();

      if ($('#simplemodal-container').length) {
        EK.Auth.resizePopup("#terms_dialog");
      } else {
        $('.popup-auth').show().modal(EK.Auth.popupOptions);
      }
    }
  },
  resizePopup: function (container) {
    //@todo: find better solution!
    var recized = false;
    $(window).bind('resize.simplemodal', function () {
      var dimension = {
        width: $(container).width(),
        height: $(container).height()
      };
      $('#simplemodal-container').css(dimension);
      if (!recized) {
        recized = true;
        $(window).trigger('resize.simplemodal');
      }
    });
    $(window).trigger('resize.simplemodal');
  },
  referrer: null,
  bind: function () {
    $('.guest_link').live('click', function () {
      window.location.replace('#login');
      EK.Auth.referrer = $(this).attr('rel');
      return false;
    });
    $('.signup_link').live('click', function () {
      window.location.replace('#signup');
      Auth.referrer = $(this).attr('rel');
      return false;
    });

    $('.popup-submit').live('click', function () {
      var $form = $(this).parents('form');
      EK.Auth.addReferer($form);
      $form.trigger('submit');
    });

    $('input[name=email], input[name=password]', $('#popup-auth-login')).live('keypress', function (e) {
      if (e.keyCode === 13) {
        EK.Auth.addReferer($(this).parents('form'));
        $('#popup-login-form').trigger('submit');
        return false;
      }
    });

    $('#verify').bind('click', function () {
      $('#verification').trigger('submit');
    });

    $('#popup-login-form').bind('submit', EK.Auth.loginBefore);
    $('#popup-auth-signup').bind('submit', EK.Auth.signupBefore);
    $('#verification').bindSubmit({success: EK.Auth.verificationCallback, dataType: 'json', beforeSubmit: EK.Auth.verificationBefore});    
  },
  addReferer: function ($form) {
    if (EK.Auth.referrer) {
      var action = $form.attr('action').replace(/\?.*$/, '') + '?referrer=' + EK.Auth.referrer;
      $form.attr('action', action);
    }
  },
  loginBefore: function () {
    /**
     * @todo: replace with better validation
     */
    try {
      EK.Auth.loginCheckFields();
      $('#popup-auth-login .slgl_errors_hold').hide();
      return true;
    } catch (e) {
      FormValidator.showErrors(e, "#popup-auth-login .form-errors");
      $('#popup-auth-login .slgl_errors_hold').show();
      return false;
    }
  },
  loginCallback: function (xhr) {
    if (EK.Auth.loginIfSuccess(xhr)) {
      if (xhr.url) {
        window.location.replace(xhr.url);
      } else {
        window.location.replace(window.location.pathname);
      }
    } else {
      var e = new FormError(xhr.error_msg);
      FormValidator.showErrors(e, "#popup-auth-login .form-errors");
      $('#popup-auth-login .slgl_errors_hold').show();
    }
  },
  loginIfSuccess: function (xhr) {
    return xhr.success;
  },
  loginCheckFields: function () {
    var fields = {
      'email'      : 'Username',
      'password'   : 'Password'
    };
    FormValidator.checkFields(fields, '#popup-login-form');
  },
  verificationCallback: function (xhr) {
    if (xhr.success) {
      window.location.replace(xhr.redirect || '/');
    } else {
      var e = new FormError(xhr.error_msg);
      FormValidator.showErrors(e, '#verification-error');
    }
  },
  verificationBefore: function () {
    var val = $.trim($('input[name=verification_code]').val());
    if (!val) {
      var e = new FormError('Please enter verification code.');
      FormValidator.showErrors(e, '#verification-error');
      return false;
    }
    $('#verification-error').hide();
    return true;
  },
  signupBefore: function () {
    try {
      EK.Auth.signupCheckFields();
      EK.Auth.signupCheckEmail();
      EK.Auth.signupCheckTermsAndConditions();
      EK.Auth.signupCheckPassword();
      $('#popup-auth-signup .slgl_errors_hold').hide();
      return true;
    } catch (e) {
      FormValidator.showErrors(e, "#popup-auth-signup .form-errors");
      $('#popup-auth-signup .slgl_errors_hold').show();
      return false;
    }
  },
  signupCallback: function (xhr) {
    if (EK.Auth.loginIfSuccess(xhr)) {
      if (xhr.url) {
        window.location.replace(xhr.url);
      } else {
        window.location.replace(window.location.pathname);
      }
    } else {
      var e = new FormError(xhr.error_msg);
      FormValidator.showErrors(e, "#popup-auth-signup .form-errors");
      $('#popup-auth-signup .slgl_errors_hold').show();
    }
  },
  signupCheckFields: function () {
    var fields = {
      'signup[first_name]' : 'First Name',
      'signup[last_name]'  : 'Last Name',
      'signup[email]'      : 'Email Address',
      'signup[password]'   : 'Password'
    };
    FormValidator.checkFields(fields);
  },
  signupCheckEmail: function () {
    var email = $.trim($('input[name=signup[email]]').val());

    FormValidator.checkEmail(email);

    var result = $.ajax({
      type: 'POST',
      url: '/auth/api/email_exist',
      data: {email: email},
      async: false
    }).responseText;

    if (result === 'true') {
      throw new FormError('This Email exists in the system.');
    }
  },
  signupCheckTermsAndConditions: function () {
    if (! $('input[name=signup[term_and_conditions]]').attr('checked')) {
      throw new FormError('Please confirm that you have reviewed the terms and conditions.');
    }
  },
  signupCheckPassword: function () {
    var password = $.trim($('input[name=signup[password]]').val()),
        confirmPassword = $.trim($('input[name=signup[confirm_password]]').val());
    if (password !== confirmPassword) {
      throw new FormError('The passwords do not match, please try again!');
    }
  }
};

$(function () {
  EK.Auth.init();
});
