
let forms_login = $('.form-login');

forms_login.each(function(){

  let form_login = $(this);

  /*Form Validation*/
  form_login.validate({
    rules:{
      "email": {
        required: true
      },
      "password": {
        required: true
      },
    },
    errorClass: 'error-field',
    errorElement: 'p',
    errorPlacement: function( label, element ) {
      label.insertAfter( element );
    },
    ignore: ":hidden",
    submitHandler: function(form) {
      let login_data = {};
      login_data["email"] = $(form).find('[name="email"]').val();
      login_data["password"] = $(form).find('[name="password"]').val();
      handleLogin(form, login_data);
    }
  });



});

function handleLogin(form, login_data){
  let data = login_controller_object;
  data['email'] = login_data['email'];
  data['password'] = login_data['password'];

  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: login_controller_object.url,
    data: data,
    beforeSend: function(){
      $(form).find('.form-message').hide();
      $(form).find('.sending-message').fadeIn();
    },
    success: function(data){
      $(form).find('.form-message').hide();
      if( data.hasOwnProperty('success') ){
          $(form).find('.success-message').fadeIn();
        if( data.hasOwnProperty('refresh') ){
          location.reload();
        }
        if( data.hasOwnProperty('redirect') ){
          window.location.href = data.redirect;
        }
      }
      if( data.hasOwnProperty('error') ){
        $(form).find('.error-message').find('p').html(data.message);
        $(form).find('.error-message').fadeIn();
      }
    },
    error: function (request, status, error) {
      console.log(status);
      console.log(error);
      console.log(JSON.parse(request.responseText));
    }
  });
}
