jQuery(document).ready(function( $ ) {
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));
    }
  });
}


let form_confirm_user = $('#form-confirm-migrated-user');

if( form_confirm_user.length ){

  /*Form Validation*/
  form_confirm_user.validate({
    rules:{
      "password": {
        required: true,
        minlength : 6
      },
      "repeat_password": {
        required: true,
        equalTo : "[name='password']"
      },
      "country": {
        required: true
      },

    },
    errorClass: 'error-field',
    errorElement: 'p',
    errorPlacement: function( label, element ) {
      label.insertAfter( element );
    },
    ignore: ":hidden",
    submitHandler: function(form) {
      let confirm_user_data = getFormData(form);
      handleConfirmUser(form, confirm_user_data);
    }
  });

}

function handleConfirmUser(form, confirm_user_data){
  let data = handle_confirm_migrated_user_controller_object;

  data['user_data'] = confirm_user_data;

  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: handle_confirm_migrated_user_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('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(request.responseText);
    }
  });
}


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));
    }
  });
}

$('.open-menu').on('click', function(){
    $('.hero--navigation--menu').addClass('fadeInLeft');
    $(".close-menu").css("display", "block");
  });

  $('.close-menu').on('click', function(){
    $('.hero--navigation--menu').removeClass('fadeInLeft');
  });

// CAROUSELS

$('.slick-articles').slick({
  slidesToShow: 3,
  slidesToScroll: 3,
  autoplay: true,
  speed: 600,
  autoplaySpeed: 2000,
  prevArrow: '<button class="slick-prev" aria-label="Previous" type="button" style=""><i class="fas fa-long-arrow-alt-left"></i></button>',
  nextArrow: '<button class="slick-next" aria-label="Previous" type="button" style=""><i class="fas fa-long-arrow-alt-right"></i></button>',
  responsive: [
    {
      breakpoint: 768,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1
      }
    }
  ]
});

$('.slick-numbers').slick({
  slidesToShow: 3,
  slidesToScroll: 3,
  autoplay: true,
  speed: 600,
  autoplaySpeed: 2000,
  prevArrow: '<button class="slick-prev" aria-label="Previous" type="button" style=""><i class="fas fa-long-arrow-alt-left"></i></button>',
  nextArrow: '<button class="slick-next" aria-label="Previous" type="button" style=""><i class="fas fa-long-arrow-alt-right"></i></button>',
  responsive: [
    {
      breakpoint: 768,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 1,
      }
    }
  ]
});

$('.slick-advertiser').slick({
  slidesToShow: 3,
  slidesToScroll: 3,
  autoplay: true,
  speed: 600,
  autoplaySpeed: 2000,
  prevArrow: '<button class="slick-prev" aria-label="Previous" type="button" style=""><i class="fas fa-long-arrow-alt-left"></i></button>',
  nextArrow: '<button class="slick-next" aria-label="Previous" type="button" style=""><i class="fas fa-long-arrow-alt-right"></i></button>',
  responsive: [
    {
      breakpoint: 768,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 1,
      }
    }
  ]
});

//open modal anunciante
$("#btn-adv").click(function(){
  $("#anunciante").modal();
});


let form_restore_password = $('#form-restore-password');

if( form_restore_password.length ){

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



};

function handleRestorePassword(form, email){
  let data = restore_password_controller_object;
  data['email'] = email;

  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: restore_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('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));
    }
  });
}


$.extend($.validator.messages, {
  required: "Campo requerido.",
  email: "Formato de email inválido.",
  customDate: "Ingrese la fecha en formato dd/mm/yyyy.",
  equalTo: "Las contraseñas no coinciden.",
  remote: "Email ya registrado en el sitio.",
  minlength: "Cantidad mínima de caracteres: 6"
});

$('[name="company_area"]').on('change', function(){
  let current = $(this).val();
  if(current == 'otros'){
    $('.other-area-container').show();
  }else{
    $('.other-area-container').hide();
  }
});

let form_subscription = $('#form-subscription');

if( form_subscription.length ){

  /*Form Validation*/
  form_subscription.validate({
    rules:{
      "first_name": {
        required: true
      },
      "last_name": {
        required: true
      },
      "profession": {
        required: true
      },
      "company": {
        required: true
      },  
      "email": {
        required: true,
        email: true
      }

    },
    errorClass: 'error-field',
    errorElement: 'p',
    errorPlacement: function( label, element ) {
      label.insertAfter( element );
    },
    ignore: ":hidden",
    submitHandler: function(form) {
      let suscription_data = getFormData(form);
      handleSuscription(form, suscription_data);
    }
  });

}

function handleSuscription(form, suscription_data){
  let data = handle_subscription_controller_object;

  data['user_data'] = suscription_data;

  $.ajax({
    type: 'POST',
    dataType: 'json',
    url: handle_subscription_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('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(request.responseText);
    }
  });
}


function getFormData(form){
  let fields = $(form).find('.data-field');
  let data = {};
  fields.each( function(){
    let name = $(this).attr('name');
    let value = $(this).val();
    let valid = true;

    if( $(this).is(':checkbox') ){
      if( $(this).hasClass('true-false') ){
        if( $(this).is(':checked') ){
          value = true;
        }else{
          value = false;
        }
      }
    }

    if( $(this).is(':radio') ){
      valid = false;
      if( $(this).is(':checked') ){
        valid = true;
        value = $(this).val();
        if($(this).hasClass('is-boolean')){
          value = (value === "1");
        }
      }
    }
    if(valid){
      data[name] = value;
    }
  });

  return data;
}
});