var working = false;
var lighteditor = false;

$(document).ready(function() {

  $('.firefrontedit').click(function(){
    var editarea = $(this).data("area");
    var pageid = $(this).data("pageid");
    lighteditor = $(this).data("lighteditor");
    frontendedit(editarea, pageid);
  });

  $('.firefrontsave').click(function(){
    var savearea = $(this).data("area");
    var pageid = $(this).data("pageid");
    fronteditsave(savearea, pageid);
  });

  $('.firefrontclose').click(function(){
    var closearea = $(this).data("area");
    var pageid = $(this).data("pageid");
    frontendclose(closearea, pageid);
  });

});

function frontendedit(area, pageid) {

  // Now we will need to save the  code
  if(working) return false;

  working = true;
  
    // Call the server and due the necessary
  var request = $.ajax({
      async: true,
      url: ls.main_url+'include/load_content.php',
      type: "POST",
      data: { fieldid: area},
      dataType: "json",
      cache: false
  });

    request.done(function(data) {

      working = false;

      if (data.status) {

        // console.log(lighteditor);

        if (lighteditor) {
          $('.'+area).summernote({toolbar: [['style', ['bold', 'italic', 'underline', 'codeview']]], focus: true, dialogsInBody: true}, 'code', data.content);
        } else {
          $('.'+area).summernote('code', data.content, {focus: true, dialogsInBody: true});
        }

        $('.firefrontsave.'+pageid+'').show();
      $('.firefrontclose.'+pageid).show();
      $('.firefrontedit.'+pageid).hide();

      }

  });
}

function frontendclose(area, pageid) {

  // Remove the editor
  $('.'+area).summernote('destroy');

  location.reload();

}

function fronteditsave(area, pageid) {

  // Get the content to save.
  var markup = $('.'+area).summernote('code');

  // Now we will need to save the  code
  if(working) return false;

  working = true;

    // Call the server and due the necessary
  var request = $.ajax({
      async: true,
      url: ls.main_url+'include/save_content.php',
      type: "POST",
      data: { fieldid: area, content : markup},
      dataType: "json",
      cache: false
  });

    request.done(function(data) {

      working = false;

      if (data.status) {

        // Remove the editor
        $('.'+area).summernote('destroy');

      // Show the correct button
      $('.firefrontsave.'+pageid+'').hide();
      $('.firefrontclose.'+pageid).hide();
      $('.firefrontedit.'+pageid).show();

      location.reload();
      return true;
    }

  });
}
