"use strict";

// Class Definition
var KTLogin = function() {
    var _login;

    var _showForm = function(form) {
        var cls = 'login-' + form + '-on';
        var form = 'kt_login_' + form + '_form';

        //_login.removeClass('login-forgot-on');
        _login.removeClass('login-signin-on');
        _login.removeClass('login-signup-on');

        _login.addClass(cls);

        KTUtil.animateClass(KTUtil.getById(form), 'animate__animated animate__backInUp');
    }

    var _handleSignInForm = function() {
        var validation;

        // Init form validation rules. For more info check the FormValidation plugin's official documentation:https://formvalidation.io/
        validation = FormValidation.formValidation(
			KTUtil.getById('kt_login_signin_form'),
			{
				fields: {
					username: {
						validators: {
							notEmpty: {
								message: 'Usuario es requerido'
							}
						}
					},
					password: {
						validators: {
							notEmpty: {
                                message: 'Contrase&ntilde;a es requerida'
							}
						}
					}
				},
				plugins: {
                    trigger: new FormValidation.plugins.Trigger(),
                    submitButton: new FormValidation.plugins.SubmitButton(),
                    //defaultSubmit: new FormValidation.plugins.DefaultSubmit(), // Uncomment this line to enable normal button submit after form validation
					bootstrap: new FormValidation.plugins.Bootstrap()
				}
			}
		);

        $('#kt_login_signin_submit').on('click', function (e) {
            e.preventDefault();
            validation.validate().then(function(status) {
		        if (status == 'Valid') {
                    //swal.fire({
                    //	text: "Todo bien, el formulario se subio correctamente",
                    //	icon: "success",
                    //	buttonsStyling: false,
                    //	confirmButtonText: "Ok, entendido!",
                    //    customClass: {
                    //    	confirmButton: "btn font-weight-bold btn-light-primary"
                    //    }
                    //}).then(function() {
                    //    KTUtil.scrollTop();
                    //    //window.location.replace("https://expocongreso.azurewebsites.net/MiPerfil");
                    //    window.location.replace("https://localhost:44354/MiPerfil");
                    //});
                    var data = {
                        "username": $("#loginusername").val(),
                        "password": $("#loginpassword").val()
                    };
                    $.ajax({
                        url: "/Login/ValidateUser",
                        type: "POST",
                        data: JSON.stringify(data),
                        dataType: "json",
                        contentType: "application/json",
                        success: function (response) {
                            if (response.Success) {
                                //$.get('@Url.Action("Index", "AdminUser")', function (data) {
                                //    $('.container').html(data);
                                //});                                
                                window.location.href = '/ClientePerfil';
                            }
                            else {
                                swal.fire({
                                    text: "El usuario y/o contraseņa incorrecta",
                                    icon: "error",
                                    buttonsStyling: false,
                                    confirmButtonText: "Ok, entendido!",
                                    customClass: {
                                        confirmButton: "btn font-weight-bold btn-light-primary"
                                    }
                                }).then(function () {
                                    KTUtil.scrollTop();
                                    window.location.href = '/Login';
                                });
                            }
                                
                        },
                        error: function () {
                            console.log('Login Fail!!!');
                        }
                    });
				} else {
					swal.fire({
		                text: "Lo sentimos, parece que se detecto unos errores, por favor intenta otra vez,",
		                icon: "error",
		                buttonsStyling: false,
		                confirmButtonText: "Ok, entendido!",
                        customClass: {
    						confirmButton: "btn font-weight-bold btn-light-primary"
    					}
		            }).then(function() {
						KTUtil.scrollTop();
					});
				}
		    });
        });
        $('#kt_login_signin_submit_demo').on('click', function (e) {
            
            var data = {
                "username": 'demo',
                "password": 'demo'
            };
            $.ajax({
                url: "/Login/ValidateUser",
                type: "POST",
                data: JSON.stringify(data),
                dataType: "json",
                contentType: "application/json",
                success: function (response) {
                    if (response.Success) {
                        //$.get('@Url.Action("Index", "AdminUser")', function (data) {
                        //    $('.container').html(data);
                        //});                                
                        window.location.href = '/ClientePerfil';
                    }
                    else {
                        swal.fire({
                            text: "El usuario y/o contraseņa incorrecta",
                            icon: "error",
                            buttonsStyling: false,
                            confirmButtonText: "Ok, entendido!",
                            customClass: {
                                confirmButton: "btn font-weight-bold btn-light-primary"
                            }
                        }).then(function () {
                            KTUtil.scrollTop();
                            window.location.href = '/Login';
                        });
                    }

                },
                error: function () {
                    console.log('Login Fail!!!');
                }
            });
        });

        // Handle forgot button
        //$('#kt_login_forgot').on('click', function (e) {
        //    e.preventDefault();
        //    _showForm('forgot');
        //});

        // Handle signup
        $('#kt_login_signup').on('click', function (e) {
            e.preventDefault();
            _showForm('signup');
        });
    }

    var _handleSignUpForm = function(e) {
        var validation;
        var form = KTUtil.getById('kt_login_signup_form');

        // Init form validation rules. For more info check the FormValidation plugin's official documentation:https://formvalidation.io/
  //      validation = FormValidation.formValidation(
		//	form,
		//	{
		//		fields: {
		//			fullname: {
		//				validators: {
		//					notEmpty: {
		//						message: 'Usuario es requerido'
		//					}
		//				}
		//			},
		//			email: {
  //                      validators: {
		//					notEmpty: {
		//						message: 'Correo es requerido'
		//					},
  //                          emailAddress: {
		//						message: 'El campo no es un correo valido'
		//					}
		//				}
		//			},
  //                  password: {
  //                      validators: {
  //                          notEmpty: {
  //                              message: 'The Contraseņa es requerida'
  //                          }
  //                      }
  //                  },
  //                  cpassword: {
  //                      validators: {
  //                          notEmpty: {
  //                              message: 'The password confirmation is required'
  //                          },
  //                          identical: {
  //                              compare: function() {
  //                                  return form.querySelector('[name="password"]').value;
  //                              },
  //                              message: 'The password and its confirm are not the same'
  //                          }
  //                      }
  //                  },
  //                  agree: {
  //                      validators: {
  //                          notEmpty: {
  //                              message: 'You must accept the terms and conditions'
  //                          }
  //                      }
  //                  },
		//		},
		//		plugins: {
		//			trigger: new FormValidation.plugins.Trigger(),
		//			bootstrap: new FormValidation.plugins.Bootstrap()
		//		}
		//	}
		//);
        function delay(time) {
            return new Promise(resolve => setTimeout(resolve, time));
        }

        
        $('#kt_login_signup_submit').on('click', function (e) {
            //e.preventDefault();

            //validation.validate().then(function(status) {
		    //    if (status == 'Valid') {
                    swal.fire({
                        text: "Gracias por registrarse, en unos minutos le estaremos enviando sus credenciales via correo. Favor revisar su bandeja spam.",
		                icon: "success",
		                buttonsStyling: false,
		                confirmButtonText: "Ok, entendido!",
                        customClass: {
    						confirmButton: "btn font-weight-bold btn-light-primary"
    					}
                    }).then(function () {
                        _showForm('signin');
                        //delay(1000).then(() => console.log('ran after 1 second1 passed'));
                        //KTUtil.scrollTop();
                        //window.location.replace("https://expocongreso.azurewebsites.net/MiPerfil");
                        //window.location.replace("http://expocongresso.com/Login");
                    });
            //delay(4000).then(() => window.location.replace("http://expocongresso.com/Login"));
				//} else {
				//	swal.fire({
		  //              text: "Lo sentimos, parece que se detectaron errores, por favor intente otra vez.  ",
		  //              icon: "error",
		  //              buttonsStyling: false,
		  //              confirmButtonText: "Ok, entendido!",
    //                    customClass: {
    //						confirmButton: "btn font-weight-bold btn-light-primary"
    //					}
		  //          }).then(function() {
				//		KTUtil.scrollTop();
				//	});
				//}
		  //  });
        });

        // Handle cancel button
        $('#kt_login_signup_cancel').on('click', function (e) {
            e.preventDefault();

            _showForm('signin');
        });
    }

  //  var _handleForgotForm = function(e) {
  //      var validation;

  //      // Init form validation rules. For more info check the FormValidation plugin's official documentation:https://formvalidation.io/
  //      validation = FormValidation.formValidation(
		//	KTUtil.getById('kt_login_forgot_form'),
		//	{
		//		fields: {
		//			email: {
		//				validators: {
		//					notEmpty: {
		//						message: 'Correo es requerido'
		//					},
  //                          emailAddress: {
		//						message: 'El campo no es un correo valido'
		//					}
		//				}
		//			}
		//		},
		//		plugins: {
		//			trigger: new FormValidation.plugins.Trigger(),
		//			bootstrap: new FormValidation.plugins.Bootstrap()
		//		}
		//	}
		//);

  //      // Handle submit button
  //      $('#kt_login_forgot_submit').on('click', function (e) {
  //          e.preventDefault();

  //          validation.validate().then(function(status) {
		//        if (status == 'Valid') {
  //                  // Submit form
  //                  KTUtil.scrollTop();
		//		} else {
		//			swal.fire({
		//                text: "Lo sentimos, parece que se detectaron errores, por favor intente otra vez.  ",
		//                icon: "error",
		//                buttonsStyling: false,
		//                confirmButtonText: "Ok, entendido!",
  //                      customClass: {
  //  						confirmButton: "btn font-weight-bold btn-light-primary"
  //  					}
		//            }).then(function() {
		//				KTUtil.scrollTop();
		//			});
		//		}
		//    });
  //      });

  //      // Handle cancel button
  //      $('#kt_login_forgot_cancel').on('click', function (e) {
  //          e.preventDefault();

  //          _showForm('signin');
  //      });
  //  }

    // Public Functions
    return {
        // public functions
        init: function() {
            _login = $('#kt_login');

            _handleSignInForm();
            _handleSignUpForm();
            //_handleForgotForm();
        }
    };
}();

// Class Initialization
jQuery(document).ready(function() {
    KTLogin.init();
});
