<!-- Includes JQuery AJAX Code - INCLUDE BELOW JQuery Library -->
<div class="modal fade" id="modalLoginForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
  aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Sign in</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <i class="fas fa-envelope prefix grey-text"></i>
          <input type="email" id="user" class="form-control validate">
          <label data-error="wrong" data-success="right" for="user">Your email</label>
        </div>
        <div class="md-form mb-4">
          <i class="fas fa-lock prefix grey-text"></i>
          <input type="password" id="pass" class="form-control validate">
          <label data-error="wrong" data-success="right" for="pass">Your password</label>
        </div>
		<div id='loginError' class='text-danger' style='font-style:italic; font-size:.7em'></div>
      </div>
      <div class="modal-footer d-flex justify-content-center">
        <button class="btn btn-primary" id='login'>Login</button>
      </div>
    </div>
  </div>
</div>
<script>
	var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
	var passPattern  = /^[\x20-\x7E]{1,}$/; 

	$(document).ready(function(){
		$("#login").click(function(){

			var email = $("#user").val().trim();
			var pass  = $("#pass").val().trim();

			// Client-side validation
			if(!emailPattern.test(email)){
				$("#loginError").text("Please enter a valid email address.");
				return;
			}
			if(!passPattern.test(pass) || pass.length === 0){
				$("#loginError").text("Please enter your password.");
				return;
			}

			// Clear any previous error
			$("#loginError").text("");

			$.ajax({
				type:"POST",
				url:"scripts/loginScript.php",
				data:{
					user: email,
					pass: pass
				},
				success:function(response){
					if(response != 0){
						// Close modal
						$("#modalLoginForm").modal("hide");

						// Redirect users based on level
						if(response == "Admin")          window.location.href = "index.php";
						else if(response == "Organizer") window.location.href = "organizer.php";
						else                             window.location.href = "participant.php";
					}
					else {
						$("#loginError").text("Login Error. Your email or password is not correct.");
					}
				},
				error:function(){
					$("#loginError").text("Connection Error. Please contact your system administrator.");
				}
			});//end ajax
		});//end login click
	});//end ready
</script>

