var validated = false;

$(document).ready(function() {
  $("#dialog-login").dialog({
    autoOpen: false,
    modal: true,
    width: 400,
    buttons: {
      "Login": verifyLogin
    }
  });
  $("#dialog-edit").dialog({
    autoOpen: false,
    modal: true,
    width: 400,
    buttons: {
      "Delete": function() {
        if ( !$("#edit-props-delete").prop("checked") ) {
          toastr.error("You must check the delete confirmation box");
          return;
        }
        deleteCard();
      },
      "Cancel": function() { 
        $(this).dialog("close");
        $("#edit-props-id").val("0");
        $("#edit-props-filename").val("");
        $("#edit-props-enabled").prop("checked", false);
      },
      "Save": saveCardProperties
    }
  });
  showGallery();
});

function showGallery() {
  $.ajax({
    url: 'ajax/getimages.php',
    dataType: 'json',
    success: function(data, stat, jqo) {
      validated = data.validated;
      $("#gallery").html("");
      if ( validated ) {
        var html = "";
        html += "<div class='item'>";
        html += "<div class='upload-text'>Upload</div>";
        html += "<div class='upload-text'>Files</div>";
        html += "<div class='upload-text'>Here</div>";
        html += "<form action='#' id='upload-form' method='POST' enctype='multipart/form-data'>";
        html += "<input type='file' name='images[]' id='fileselect' multiple='multiple' class='upload-form' />";
        html += "</form>";
        html += "<button id='upload-images'>Upload</button>";
        html += "</div>";
        $("#gallery").append(html);
        $("#upload-images").on("click", uploadImages);
      }
      data.images.forEach(function(image) {
        var html = "";
        html += "<div class='item " + image.size + ((image.enabled) ? "" : " disabled") + "'>";
        html += "<div class='mtgimage'>";
        html += "<a href=\"images/" + image.filename + "\"><img class='card-image' data-imgid='" + image.id + "' src=\"thumb.php?id=" + image.id + "\" /></a>";
        html += "</div>";
        html += "<div><span data-id='" + image.id + "' class='mtgimagetitle" + ((image.enabled) ? "" : " notenabled") + "'>" + image.title + "</span></div>";
        html += "</div>";
        $("#gallery").append(html);
      });
      $('.imagegallery a').simpleLightbox();
      $(".mtgimagetitle").on("click", function() { openEditDialog($(this).data("id")); });
      if ( !validated ) openLoginDialog();
    }
  });
}

function uploadImages() {
  var form = $("#upload-form")[0];
  var data = new FormData(form);
  data.append("goodform", "true");
  $.ajax({
    type: "POST",
    enctype: "multipart/form-data",
    url: "ajax/uploadimages.php",
    data: data,
    processData: false,
    contentType: false,
    cache: false,
    timeout: 600000,
    success: function(data, stat, jqo) {
      if ( !data.error ) {
        form.reset();
        toastr.success(data.uploadcount + " images uploaded");
        showGallery();
      } else {
        toastr.error(data.message);
      }
    }
  });
}

function toggleState(imageId) {
  $.ajax({
    url: 'ajax/togglestate.php',
    dataType: 'json',
    data: {id: imageId},
    success: function(data, stat, jqo) {
      if ( data.image.enabled ) {
        $('[data-id="' + imageId + '"]').removeClass("notenabled");
      } else {
        $('[data-id="' + imageId + '"]').addClass("notenabled");
      }
    }
  });
}

function refreshDB() {
  $.ajax({
    url: 'ajax/populate.php',
    dataType: 'json',
    success: function(data, stat, jqo) {
      if ( !data.error ) {
        toastr.success("Databse list of images was updated");
        showGallery();
      } else {
        toastr.error("Error updating database!");
      }
    }
  });
}

function verifyLogin() {
  $.ajax({
    url: 'ajax/login.php',
    dataType: 'json',
    data: {
      username: $("#login-username").val(),
      password: $("#login-password").val()
    },
    type: 'POST',
    success: function(data, stat, jqo) {
      validated = data.validated;
      if ( !validated ) {
        toastr.error("Invalid Login");
      } else {
        toastr.success("Login Successful");
        $("#login-username").val("");
        $("#login-password").val("");
        $("#dialog-login").dialog("close");
        showGallery();
      }
    }
  });
}

function openLoginDialog() {
  $("#dialog-login").dialog("open");
}

function openEditDialog(imageId) {
  if ( !validated ) {
    openLoginDialog();
    return;
  }
  $.ajax({
    url: 'ajax/getimage.php',
    dataType: 'json',
    data: {
      id: imageId
    },
    success: function(data, stat, jqo) {
      if ( data.error ) {
        toastr.error(data.message);
        return;
      }
      $("#edit-image").attr("src", "thumb.php?id="+imageId);
      $("#edit-props-id").val(imageId);
      $("#edit-props-filename").val(data.image.title);
      $("#edit-props-enabled").prop("checked", data.image.enabled);
      $("#edit-props-dimensions").html(data.image.dimensions);
      $("#edit-props-size").html(data.image.size);
      $("#dialog-edit").dialog("open");
    }
  });
}

function clearEditDialog() {
  $("#dialog-edit").dialog("close");
  $("#edit-image").attr("src", "img/error.png");
  $("#edit-props-id").val("0");
  $("#edit-props-filename").val("");
  $("#edit-props-enabled").prop("checked", false);
  $("#edit-props-dimensions").html("");
  $("#edit-props-size").html("");
  $("#edit-props-delete").prop("checked", false);
}

function deleteCard() {
  if ( !validated ) return;
  $.ajax({
    url: 'ajax/deletecard.php',
    dataType: 'json',
    data: {
      id: $("#edit-props-id").val()
    },
    success: function(data, stat, jqo) {
      if ( !data.error ) {
        toastr.success("Card Deleted: " + data.filename);
        clearEditDialog();
        showGallery();
      } else {
        toastr.error(data.message);
      }
    }
  });
}

function saveCardProperties() {
  if ( !validated ) return;
  $.ajax({
    url: 'ajax/savecard.php',
    dataType: 'json',
    data: {
      id: $("#edit-props-id").val(),
      filename: $("#edit-props-filename").val(),
      enabled: ($("#edit-props-enabled").prop("checked")) ? 1 : 0
    },
    success: function(data, stat, jqo) {
      if ( !data.error ) {
        clearEditDialog();
        showGallery();
      } else {
        toastr.error(data.message);
      }
    }
  });
}

// vim:ts=2 sw=2 et:
