/**
 * Administrator functionality
 */
$(function(){
 
  // Initialize Ajax file upload if the ajaxUpload element is present
  if($('#ajaxUpload').length){
    new qq.FileUploader({
      element: $('#ajaxUpload')[0],
      action: basePath() + 'ajax/?upload',
      allowedExtensions: ['jpeg', 'jpg', 'png', 'gif'],
      onComplete: function(id, fileName, responseJSON){
        // Queue a removal of the last successful upload message to prevent clutter
        $('.qq-upload-list li:last').delay(5000).slideUp(500);
 
        // If a successful upload, we need to reload the images container
        if(responseJSON.success){
          loadUploadedImages();
        }else{
          alert(responseJSON.error);
        }
      }
    });
  }
 
  loadUploadedImages();
 
  // Enable jWYSIWYG
  jWysiwyg($('textarea:visible'));
 
  // Add a warning to menu links on click while editing
  if($('#actions').is(':visible')){
    $('#menu a').click(function(){
      return confirm('You are currently editing this page. Are you sure you want to navigate away?');
    });
  }
 
  var sections = 0;
 
  // Add a new section
  $('#add').click(function(e){
    e.preventDefault();
 
    // New ID
    sections++;
 
    // Clone the placeholder section and update the attributes
    var clone = $('#clone').clone();
    clone.removeAttr("id");
    clone.find('input:first-child').val('');
    clone.find('label, input[type=text], textarea').each(function(){
      var attr = $(this).is('label') ? "for" : "id";
      $(this).attr(attr, $(this).attr(attr) + sections);
    });
 
    // Add to bottom of fieldset list
    $('#actions').before(clone);
 
    // Re-initialize
    jWysiwyg($('#content_' + sections));
 
    // Rebind section events
    bindSectionEvents();
 
  });
 
  // Save changes
  $('#save').click(function(e){
    e.preventDefault();
    $('form').submit();
  });
 
  // Bind section events
  bindSectionEvents();
});
 
/**
 * Bind section traversal method
 * We put these bindings into their own method because when cloning, events
 * do not exist on the newly cloned element
 */
function bindSectionEvents(){
 
  // Must unbind all events, otherwise we'll double up on events
  // for every time we bind these
  $('.sorting .remove, .sorting .up, .sorting .down, .sorting .image').unbind('click');
 
  // Associate image to section
  $('.sorting .image').click(function(e){
    e.preventDefault();
 
    var images = $('#imagesContainer');
    var parent = $(this).closest('fieldset');
    var offset = parent.offset();
    offset.top += parent.height() / 2 - images.height() / 2;
    offset.left += parent.width() / 2 - images.width() / 2;
 
    // Store a reference ID so we know where we're assocating the image
    $('#imageId').val(parent.find('input[name=title\\[\\]]').attr('id'));
 
    // Fade out the image selector if it's visible right now, then
    // complete future actions in the callback
    $('#imagesContainer').stop(true, true).fadeOut(250, function(){
      // Move the image selector to the current mouse position, then fade in
      $(this).css({
      'top': offset.top + 'px',
      'left': offset.left + 'px',
      }).fadeIn(250);
    });
  });
 
  // Removing section
  $('.sorting .remove').click(function(e){
    e.preventDefault();
 
    // Find self
    var removing = $(this).closest('fieldset');
    var id = removing.find('input:hidden').val();
    if(id){
      $('#clone').before('<input type="hidden" name="delete[]" value="' + id + '" />');
    }
    removing.remove();
  });
 
  // Moving section upward
  $('.sorting .up').click(function(e){
    e.preventDefault();
 
    // Find self and next fieldset
    var moving = $(this).closest('fieldset');
    var moveto = moving.prev('fieldset:visible');
 
    // Make sure an element was found
    if(!moveto.length)
      return;
 
    // Load textarea template into container
    var movingTextarea = moving.find('textarea');
    var container = moving.find('div.editContent');
    var params = $.param({
      id:       movingTextarea.attr('id'),
      name:     "content[]",
      label:    "Content",
      content:  movingTextarea.val()
    });
    container.load(basePath() + 'ajax/?' + params);
 
    // Shift elements
    moveto.before(moving);
  });
 
  // Moving section downward
  $('.sorting .down').click(function(e){
    e.preventDefault();
 
    // Find self and next fieldset 
    var moving = $(this).closest('fieldset');
    var moveto = moving.next('fieldset:visible');
 
    // Make sure an element was found
    if(!moveto.length)
      return;
 
    // Load textarea template into container
    var movingTextarea = moving.find('textarea');
    var container = moving.find('div.editContent');
    var params = $.param({
      id:       movingTextarea.attr('id'),
      name:     "content[]",
      label:    "Content",
      content:  movingTextarea.val()
    });
    container.load(basePath() + 'ajax/?' + params);
 
    // Shift elements
    moveto.after(moving);
  });
}
 
/**
 * Load and attach event handlers for the uploaded images container
 */
function loadUploadedImages(){
  // Load images
  $('#imagesContainer').load(basePath() + 'ajax/?images', function(){
    $('#imagesContainer img').each(function(){
      $(this).attr('src', basePath() + $(this).attr('alt'));
    });
 
    // First, unbind click events to prevent possible issues
    $('#imagesContainer a, #imagesContainer img').unbind('click');
 
    // Select an image
    $('#imagesContainer img').click(function(e){
      e.preventDefault();
 
      // Traverse to find the imageId reference, then the parent (fieldset), then the
      // img[] input to set the source to
      var fieldset = $('#' + $('#imageId').val()).closest('fieldset');
      fieldset.find('input[name=img\\[\\]]').val($(this).attr('title'));
      var img = fieldset.find('img');
      img.attr('src', $(this).attr('src')).removeClass('unassoc');
      $('#imageId').val('');
 
      // Simulate a cancel click to close image select
      $('#imagesContainer a.cancel').click();
    });
 
    // Delete image
    $('#imagesContainer a.delete').click(function(e){
      e.preventDefault();
 
      var parent = $('#' + this.name);
      var image = parent.find('img').attr('title');
      $.post(basePath() + 'ajax/?images&delete', {"image": image }, function(data){
        if(data.status == "success"){
          parent.remove();
        }else{
          alert("Couldn't delete " + image + "! An unknown error occurred.");
        }
      }, 'json');
    });
 
    // Cancel image select
    $('#imagesContainer a.cancel').click(function(e){
      e.preventDefault();
 
      $('#imagesContainer').stop(true, true).fadeOut(250);
    });
  });
}
 
/**
 * Initialize jWYSIWYG on an element
 */
function jWysiwyg(el){
  el.wysiwyg({
    autoGrow:         true,
    initialContent:   "<p></p>",
    controls: {
      /* Font */
      bold:           { visible: true },
      italic:         { visible: true },
      underline:      { visible: true },
      /* Indentation */
      indent:         { visible: true },
      outdent:        { visible: true },
      /* Lists */
      /*
      insertOrderedList:    { visible: true },
      insertUnorderedList:  { visible: true },
      */
      /* Options */
      html:           { visible: true },
      removeFormat:   { visible: true }
    },
    rmUnusedControls: { visible: true },
  });
}