
let form_change_password = $('#form-change-password');

if( form_change_password.length ){

  /*Form Validation*/
  form_change_password.validate({
    rules:{
      "password": {
        required: true,
        minlength : 6
      },
      "repeat_password": {
        required: true,
        equalTo : "[name='password']"
      },
    },
    errorClass: 'error-field',
    errorElement: 'p',
    errorPlacement: function( label, element ) {
      label.insertAfter( element );
    },
    ignore: ":hidden",
    submitHandler: function(form) {
      let change_password_data = {};
      change_password_data["password"] = $(form).find('[name="password"]').val();
      change_password_data["repeat_password"] = $(form).find('[name="repeat_password"]').val();
      handleChangePassword(form, change_password_data);
    }
  });



};

function handleChangePassword(form, change_password_data){
  let data = change_password_controller_object;
  data['password'] = change_password_data['password'];
  data['repeat_password'] = change_password_data['repeat_password'];

  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: change_password_controller_object.url,
    data: data,
    beforeSend: function(){
      $(form).find('.form-message').hide();
      $(form).find('.sending-message').fadeIn();
    },
    success: function(data){
      console.log(data);
      $(form).find('.form-message').hide();
      if( data.hasOwnProperty('success') ){
        $(form).find('.success-message').fadeIn();
        if( data.hasOwnProperty('refresh') ){
          location.reload();
        }
      }
      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));
    }
  });
}
