function multisort(element)
{
  var $category_selector = $(element).parents('.cell').find('select.category-select');
  var category_value = null;
  if ($category_selector.length) {
    category_value = $category_selector.val();
    $category_selector.off('change').on('change', function() {
      multisort(element);
    });
  }
  var $ordering_selector = $(element).parents('.cell').find('select.ordering-select');
  if ($ordering_selector.length) {
    $ordering_selector.off('change').on('change', function() {
      var val = $(this).val();
      if (val == 'manual') {
        $(element).prev().show();
        $(element).show();
      } else {
        $(element).prev().hide();
        $(element).hide();
      }
    }).trigger('change');
  }

  $(element).find('ul').remove();
  $(element).find('select').hide();

  var $ul = $('<ul class="multisort"></ul>');

  $(element).find('option').each(function(i, x) {
    if (category_value && $(x).val().indexOf(category_value + ':') != 0) {
      return;
    }
    $('<li data-value="' + $(x).val() + '"><span class="handle">⣿</span>' + $(x).text() + '</li>').appendTo($ul);
  });
  $ul.appendTo(element);
  $ul.sortable({
    handle: '.handle',
    update: function(event, ui) {
      var options = Array();
      var select = $(element).find('select');
      $ul.find('li').each(function(i, x) {
        options.push($(element).find("option[value='" + $(x).data('value') + "']").attr('selected', 'selected').detach());
      });
      while (options.length) {
        select.prepend(options.pop());
      }
    }
  });
}

function init_pages_list()
{
  if ($('#pages-list').length == 0)
    return;
  var list_offset = $('#pages-list').offset().left;
  $('#pages-list').sortable({
     handle: '.handle',
     stop: function(event, ui) {
       var moved_page_id = ui.item.data('page-id');
       /* 25 is the per-level margin-left applied to pages, it needs to be kept
        * in sync with the css file */
       var item_offset = ui.offset.left - list_offset + parseInt($(ui.item).data('level'))*25;
       var new_level = Math.abs(Math.round(item_offset / 25));
       if (new_level <= 0) {
         new_level = 0;
       } else {
         var previous_page = $('#pages-list div[data-page-id=' + moved_page_id + ']').prev();
         var previous_page_level = parseInt($(previous_page).data('level'));
         if (new_level > previous_page_level+1) {
           new_level = previous_page_level+1;
         }
       }

       var new_parent = null;
       if (new_level != 0) {
          new_parent = $($(ui.item).prevAll('[data-level='+(new_level-1)+']')[0]).data('page-id');
       }
       /* remove classes and add new values */
       $(ui.item).removeClass('level-0').removeClass('level-1').removeClass('level-2');
       $(ui.item).addClass('level-' + new_level);
       $(ui.item).data('level', new_level).attr('data-level', new_level);

       var new_order = $('#pages-list div').map(function() { return $(this).data('page-id'); }).get().join();

       $.ajax({
           url: $('#pages-list').data('page-order-url'),
           data: {'new-order': new_order,
                  'moved-page-id': moved_page_id,
                  'moved-page-new-parent': new_parent
           },
           success: function(data, status) {
             $('#pages-list').replaceWith($(data).find('#pages-list'));
             init_pages_list();
           }
       });
     }
  });
}

$(function() {
  $('div.cell-list h3').on('click', function() {
    $(this).parent().toggleClass('toggled').toggleClass('untoggled');
  });
  $('div.cell-list a.close-button').on('click', function() {
    $(this).parents('.toggled').toggleClass('toggled').toggleClass('untoggled');
    return false;
  });
  init_pages_list();

  function init_cells_lists() {
    $('.cell-list').each(function() {
      if ($(this).find('div.cell').length == 0) {
        $(this).addClass('empty-cell-list');
      } else {
        $(this).removeClass('empty-cell-list');
      }
    });
  }
  init_cells_lists();

  $('.cell-list').sortable({
     handle: '.handle',
     connectWith: '.cell-list',
     helper: 'clone',
     placeholder: 'empty-cell',
     tolerance: 'pointer',
     start: function(event, ui) {
             if (ui.helper.parent().find('div.cell').length <= 2) {
                     /* cell + placeholder */
                     ui.helper.parent().addClass('empty-cell-list');
             }
             $('body').addClass('dragging-cell');
             ui.helper.removeClass('toggled').addClass('untoggled').css('height',
                             ui.helper.find('h3').outerHeight());
     },
     stop: function(event, ui) {
             $('body').removeClass('dragging-cell');
             init_cells_lists();
     },
     update: function(event, ui) {
       var new_order = Object();
       $('.cell').each(function(i, x) {
           var cell_suffix = $(x).data('cell-reference');
           new_order['pos_' + cell_suffix] = i;
           new_placeholder = $(x).closest('.placeholder').data('placeholder-key');
           new_order['ph_' + cell_suffix] = new_placeholder;
       });
       $.ajax({
           url: $('#placeholders').data('cell-order-url'),
           data: new_order
       });
     }
  });
  $('#sidebar button').on('click', function() {
    window.location = $(this).data('add-url');
    return false;
  });

  $('div.cell button.save').on('click', function(event) {
     var $button = $(this);
     var $form = $(this).closest('form');
     var button_label = $button.text();
     for (instance in CKEDITOR.instances) {
        CKEDITOR.instances[instance].updateElement();
     }
     $.ajax({
         url: $form.attr('action'),
         data: $form.serialize(),
         type: 'POST',
         beforeSend: function() { $button.attr('disabled', 'disabled'); },
         success: function(data) {
            $button.attr('disabled', null);
            if (data.indexOf('ckeditortype') == -1) {
              /* update form with new content, unless it has a ckeditor, as
               * this causes an unpleasant flickering */
              $button.parents('form').find('div.cell-form').html(data);
            }
            if (data.indexOf('class="errorlist"') == -1) {
              $.getJSON($form.data('label-url'),
                function(data) {
                    $form.parents('div.cell').find('.additional-label i').text(data['label']);
                }
              );
            }
         }
     });
     return false;
  });

  $('div.cell').each(function(i, x) {
    $(this).attr('id', 'div-cell-'+i);
    var h = $(this).find('h3 + div').height() + 10;
    h += $(this).find('.multisort').length * 250;
    h += $(this).find('.django-ckeditor-widget').length * 200;
    var style = '<style>div#div-cell-'+i+'.toggled h3 + div { max-height: '+h+'px; }</style>';
    $(style).appendTo('head');
    $(this).addClass('untoggled');
  });
  $('#assets-thumbs a').on('click', function() {
    $('#asset-img').empty().append($('<img src="' + $(this).attr('href') + '"/>'));
    $('#asset-cmds').show();
    return false;
  });
  $('#asset-delete').on('click', function() {
    var img_src = $('#asset-img img').attr('src');
    var thumb_item = $('#assets-thumbs a[href="' + img_src + '"]').parent();
    var img_orig = $(thumb_item).data('orig');
    $(thumb_item).hide();
    $('#asset-img').empty();
    $('#asset-cmds').hide();
    $.ajax({
      url: $(this).data('asset-delete-url'),
      data: {'img_orig': img_orig}
    });
  });
  $('.manager-add-new-cell a').on('click', function() {
    $(this).next().toggle();
    return false;
  });
  $('.manager-add-new-cell button').on('click', function() {
    window.location = $(this).parent('div').find('option:selected').data('add-url');
    return false;
  });
});
