$(document).ready(function(){
  $("form#loginForm").submit(function() { // loginForm is submitted
    var username = $('#username').attr('value'); // get username
    var password = $('#password').attr('value'); // get password

    if (username && password) { // values are not empty
      $.ajax({
        type: "GET",
        url: scripts+"/login.pl", // URL of the Perl script
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        // send username and password as parameters to the Perl script
        data: "username=" + username + "&password=" + password,
        // script call was *not* successful
        error: function(XMLHttpRequest, textStatus, errorThrown) { 
          $('div#loginResult').text("responseText: " + XMLHttpRequest.responseText 
            + ", textStatus: " + textStatus 
            + ", errorThrown: " + errorThrown);
          $('div#loginResult').addClass("alert-danger");
        }, // error 
        // script call was successful 
        // data contains the JSON values returned by the Perl script 
        success: function(data){
          if (data.error) { // script returned error
            $('div#loginResult').text("error: " + data.error);
            $('div#loginResult').addClass("alert-danger");
          } // if
          else { // login was successful
            $('form#loginForm').hide();
            // $('div#loginResult').text("success: " + data.success);
            $('div#loginResult').text(data.success);
              // + ", data.userid: " + data.userid);
            $('div#loginResult').removeClass("alert-danger");
            $('div#loginResult').addClass("alert-success");
            //refresh();
            window.location.reload();
          } //else
        } // success
      }); // ajax
    } // if
    else {
      $('div#loginResult').text("Enter username and password");
      $('div#loginResult').addClass("alert-danger");
    } // else
    $('div#loginResult').fadeIn();
    return false;
  });
});
