Blog.Topic = {
  /**
   * Тип темы
   */
  type : function()
  {
    return $('#type').val();
  },
  /**
   * Включает/выключает тему
   */
  activate : function (a)
  {
    $.getJSON($(a).attr('href'), function(json){
      if (json && json.active) {
        if (json.active.status) {
          // Топик активен
          $(a).attr('title', 'выключить тему');
          $(a).html('выключить');
          $(a).parent().attr('class', 'active');
        } else {
          // Топик не активен
          $(a).attr('title', 'включить тему');
          $(a).html('включить');
          $(a).parent().attr('class', 'inactive');
        }
      }
    });
    return false;
  },
  /**
   * Удаляет тему
   */
  remove : function (a, reload)
  {
    if (confirm('Вы уверены?')) {
      $.getJSON($(a).attr('href'), function(json){
        if (json && json.removed) {
          if (json.removed.status) {
            // Топик удален
            if (reload) {
              location.reload();
            } else {
              $(a).parents('.topicBox').hide('fast');
            }
          }
        }
      });
    }
    return false;
  },
  /**
   * Удаляет комментарий
   */
  commentRemove : function(a)
  {
    if (confirm('Вы уверены?')) {
      $.getJSON($(a).attr('href'), function(json){
        if (json && json.removed) {
          if (json.removed.status) {
            // каммент удален
            $(a).parents('.comment').find('.txtcom').html('<em class="spam">Этот комментарий был удален автором темы</em>');
            $(a).parents('ul').remove();
          }
        }
      });
    }
    return false;
  },
  /**
   * Показывает или прячет время публикации топика
   */
  delay : function(checkbox)
  {
    if ($(checkbox).attr('checked')) {
      $('#t_publish').show('fast');
    } else {
      $('#t_publish').hide('fast');
    }

  },
  progressBar : function(elem, on)
  {
    if (on) {
      if (Blog.Topic.type() == 'TXT') {
        var img = "loader.gif";
      } else {
        var img = "g-loader.gif";
      }
      $(elem).after('<img src="/siteimg/' + img + '" class="load-indicator" />');
      Blog.centrize($(elem).siblings('.load-indicator'), $(elem));
      $(elem).addClass('translucent-max');
    } else {
      $(elem).siblings('.load-indicator').remove();
      $(elem).removeClass('translucent-max');
    }
  },
  /**
   * Клонируем форму для отправки одного файла
   */
  cloneForm : function(fileinput)
  {
    var f = $('#topic-edit');
    var html = '<form id="topic-edit-clone" style="display:none" action="' + f.attr('action') + '" enctype="' + f.attr('enctype') + '" method="post">' +
        '<input type="hidden" name="form" value="sent" />' +
        '<input type="hidden" name="fileupload" value="1" />' +
        '<input type="hidden" name="t_id" value="' + $('#t_id').val() + '" />' +
        '<input type="hidden" name="type" value="' + $('#type').val() + '" />' +
        '</form>';
    f.after(html);
    fileinput.after('<div class="fileinput">&nbsp;</div>');
    fileinput.appendTo($('#topic-edit-clone'));
    return $('#topic-edit-clone');
  },
  /**
   * Убираем клонированную форму
   */
  cloneFormKill : function(fileinput)
  {
    fileinput.insertAfter($('.fileinput'));
    $('.fileinput').remove();
    $('#topic-edit-clone').remove();
  },


  /**
   * Предпросмотр топика
   *
   */
  preview : function()
  {
    Blog.Topic.Editor.getText();
    $('#preview').val(1);
    if (!$('#subject').val()) {
      alert ('Необходимо заполнить поле "Заголовок"');
      return false;
    } else {
      return true;
    }
  },
  /**
   * Публикация топика
   *
   */
  submit : function()
  {
    Blog.Topic.Editor.getText();
    if (!$('#subject').val()) {
      alert ('Необходимо заполнить поле "Заголовок"');
      return false;
    } else {
      return true;
    }
  }
}


/**
 * Текстовый топик
 */
Blog.Topic.TXT = {
  updateFileList : function(j)
  {

    for(var i = 0, l = j.length; i < l; i++) {
      var f = j[i];

      var li = $('.file-' + f.index);
      li.find('.err').remove();

      if (f.uploaded) {
        Blog.Topic.TXT.uploadedFile(li, f);
      } else {
        if (f.message) {
          li.prepend('<div class="err">' + f.message + '</div>');
        }
      }
    }
  },
  uploadedFile : function(li, f)
  {
    var url = $('#topic-edit').attr('action');
    var html = '' +
      '<span class="clear-file"><a onclick="return Blog.Topic.Image.remove(' + f.index + ', ' + f.f_id + ')" href="' + url + '">удалить фото</a></span> ' +
      '<span class="paste-file"><a onclick="return Blog.Topic.Editor.tagImg(\'' + f.src + '\')" href="' + url + '">вставить фото в текст</a></span> ' +
      '<span class="exist-file">Закачан файл: <a onclick="return Blog.Topic.Image.preview(\'' + f.src + '\')" href="' + url + '">' + f.name + '</a> (' + f.size + ')</span> ';
    $(li).html(html);
    Blog.Topic.Image.cache(f.src);
  },
  inputFile : function(li, index)
  {
    var html = '<input type="file" name="file[' + index + ']" size="75" /> ' +
        '<input onclick="return Blog.Topic.TXT.upload(this)" type="image" class="btn" src="/siteimg/btn/upload.gif" title="Отправить файл" value="Загрузить" alt="Загрузить" />';
    $(li).html(html);
  },
  /**
   * Отправка формы с файлами аяксом
   */
  upload : function(btn)
  {

    var file = $(btn).siblings('input[type="file"]');
    var clone = Blog.Topic.cloneForm(file);
    Blog.Topic.progressBar($('.fileinput'), true);

    clone.ajaxSubmit({
      success: function(json) {
        eval('json = ' + json);
        // Убиваем клонированную форму
        Blog.Topic.cloneFormKill(file);
        file.remove();
        if (json) {
          // Обновляем t_id на случай, если это новый топик
          $('#t_id').val(json.t_id);
          Blog.Topic.progressBar($('.fileinput'), false);
          // Обновляем список файлов

          $('#topic-edit').attr('action', json.url);
          Blog.Topic.TXT.updateFileList(json.files);
        }
      }
    });
    return false;
  }
}
/**
 * Фото топик
 */
Blog.Topic.IMG = {
  updateFileList : function(j)
  {
    var url = $('#topic-edit').attr('action');
    var f = j[0];
    if (f.uploaded) {
      var html = '' +
        '<div class="file-' + f.f_id + ' thumbnail added" ' +
        'title="' + f.name + ' (' + f.size + ')" ' +
        'style="background-image: url(' + f.thumb + ');">' +
          '<div class="actions">' +
            '<a onclick="return Blog.Topic.IMG.editForm(' + f.f_id + ')" ' +
            'href="' + url + '" class="setup-file"><span>свойства</span></a>' +
            '<a onclick="return Blog.Topic.Image.remove(' + f.f_id + ', ' + f.f_id + ')" ' +
            'href="' + url + '" class="clear-file"><span>удалить</span></a>' +
          '</div>' +
        '</div>';
      $('.files').append(html);
      Blog.Topic.IMG.cache[f.f_id] = f;
      Blog.Topic.IMG.cache[f.f_id].id = f.f_id;
      new DND($('.file-' + f.f_id));
    } else {
      if (f.message) {
        $('#file-0').before('<p class="err">' + f.message + '</p>');
      }
    }
  },
  removed : function(id)
  {
    $('.files .file-' + id).remove();
    Blog.Topic.IMG.cache[id] = false;
  },
  /**
   * Загрузка информации о фотографии в кеш
   */
  getImageData : function(id, callback)
  {
    var img = $('.file-' + id);
    Blog.Topic.IMG.progressBar(img, true);
    var href = $('#topic-edit').attr('action');
    $.getJSON(href, {f_data : id}, function(json){
      if (json.file) {
        Blog.Topic.IMG.cache[id] = json.file;
        Blog.Topic.IMG.progressBar(img, false);
        if (callback) callback();
      }
    });
  },
  progressBar : function(elem, on)
  {
    if (on) {
      $(elem).after('<img src="/siteimg/loader1.gif" class="load-indicator" />');
      Blog.centrize($(elem).siblings('.load-indicator'), $(elem));
      $(elem).addClass('translucent-max');
    } else {
      $(elem).siblings('.load-indicator').remove();
      $(elem).removeClass('translucent-max');
    }
  },
  hideForm : function()
  {
    $('.file').hide('fast');
    $('.thumbnail').removeClass('selected');
    return false;
  },
  /**
   * Массив с данными фотографий
   */
  cache : [],
  /**
   * Показывает форму добавления/редактирования фотографии
   */
  editForm : function(id)
  {
    id = id || 0;
    var p = id ? Blog.Topic.IMG.cache[id] : [];
    if (id && !p) {
      // Данных о фотографии в кеше нет, их надо загрузить
      Blog.Topic.IMG.getImageData(id, function(){Blog.Topic.IMG.editForm(id)});
      return false;
    }
    $('.thumbnail').removeClass('selected');
    $('.thumbnail').removeClass('added');
    $('.file-' + id).addClass('selected');
    var html = '' +
      '<div class="file check' +
      (id ? ' edit-' + id : '') +
      '" style="display:none;">' +
      '<div class="top"></div>' +
        '<div class="dt"><label for="file-' + id + '" class="cl">Фотография:</label></div>' +
        '<div class="dd">' +
          (id ?
          'Загружена фотография: ' +
          '<a href="' + $('#topic-edit').attr('action') + '" ' +
          'onclick="return Blog.Topic.Image.preview(\'' + p.src + '\')">' +
          p.name + '</a> (' + p.size + ')' :
          '<input type="file" name="file[0]" id="file-0" size="60" />') +
        '</div>' +
        '<div class="dt"><label for="description" class="cl">Комментарий:</label></div>' +
        '<div class="dd"><textarea name="description[' + id + ']" id="description">' +
          (id ? p.description : '') +
        '</textarea></div>' +
        '<div class="dd">' +
          '<input onclick="' +
          (id ? 'return Blog.Topic.IMG.update(' + id + ')' : 'return Blog.Topic.IMG.upload(this)') +
          '" type="image" class="btn" src="/siteimg/btn/g-save.gif" title="' +
          (id ? 'Сохранить фотографию' : 'Добавить фотографию') +
          '" value="Сохранить" alt="Сохранить" /> ' +
          '<input onclick="return Blog.Topic.IMG.hideForm()" type="image" class="btn" src="/siteimg/btn/g-cancel.gif" title="Отмена" value="Отмена" alt="Отмена" />' +
          (id ? '<img class="cache" src="' + p.src + '" />' : '') +
        '</div>' +
      '<div class="bottom"></div>' +
      '</div>';
    if ('.file') {
      $('.file').remove();
      $('.add-file').before(html);
      $('.file').show();
    } else {
      $('.add-file').before(html);
      $('.file').show('fast');
    }
    return false;
  },
  /**
   * Отправка формы аяксом
   */
  update : function(id)
  {
    $('.err').remove();
    var on = $('.file .dd');
    Blog.Topic.progressBar(on, true);
    $.getJSON($('#topic-edit').attr('action'),
     {f_update:id, f_desc:$('#description').val()},
     function(json){
       Blog.Topic.progressBar(on, false);
       if (json.file) {
         Blog.Topic.IMG.cache[id].description = json.file.description;
         $('.file').hide('slow');
         $('.file-' + id).addClass('added');
       }
     });
     return false;
  },
  /**
   * Пересортировка файлов
   * @param {Object} dragged что таскали
   * @param {Object} replaced куда вставили
   * @param {Object} ordering 1 после, -1 до
   */
  order : function(dragged, replaced, ordering)
  {
    if (dragged && replaced) {
      var dragged_id = dragged.attr('class').match(/-(\d)*/)[0] * -1;
      var replaced_id = replaced.attr('class').match(/-(\d)*/)[0] * -1;

      $.getJSON($('#topic-edit').attr('action'),
        {f_dragged : dragged_id, f_replace : replaced_id, f_ord : ordering}
      );
    }
  },
  /**
   * Отправка формы с файлами аяксом
   */
  upload : function(btn)
  {
    $('.err').remove();
    var file = $(btn).parents('.file').find('input[type="file"]');
    var clone = Blog.Topic.cloneForm(file);
    Blog.Topic.progressBar($('.fileinput'), true);

    clone.append('<textarea name="description[0]">' +
          $('#description').val() +
        '</textarea>')

    clone.ajaxSubmit({
      success: function(json) {
        eval('json = ' + json);
        // Убиваем клонированную форму
        Blog.Topic.cloneFormKill(file);
        if (json) {
          // Обновляем t_id на случай, если это новый топик
          $('#t_id').val(json.t_id);
          Blog.Topic.progressBar($('.fileinput'), false);
          // Обновляем список файлов
          Blog.Topic.IMG.editForm(0);
          $('#topic-edit').attr('action', json.url);
          Blog.Topic.IMG.updateFileList(json.files);
        }
      }
    });
    return false;
  }
}
/**
 * Видео топик
 */
Blog.Topic.VID = {
  updateFileList : function(j)
  {
    var url = $('#topic-edit').attr('action');
    var f = j[0];
    if (f.uploaded) {
      $('#href').val();
      if (f.message) {
        $('#file').before('<p class="inf">' + f.message + '</p>');
      } else {
        var html = '<div>Загружен: ' + f.name + ' (' + f.size + ')</div>';
        var dd = $('#file').parent();
        dd.html('<input type="file" size="60" id="file" name="file[0]"/>' + html);
        $('#f_id').val(f.f_id);
      }
    } else {
      if (f.message) {
        $('#file').before('<p class="err">' + f.message + '</p>');
      }
    }
  },
  /**
   * Показывает форму добавления/редактирования видео
   */
  editForm : function(a)
  {

    $('.err').remove();
    $('.inf').remove();
    var li = $(a).parent('li');
    var mode = li.attr('class');
    if (mode == 'file' || mode == 'link') {} else return false;

    var il = li.siblings('.select'); // Соседний il, который сейчас выбран
    var ilText = il.text(); // Запоминем, какой в нем текст
    il.removeClass('select'); // Он теперь не выбран
    il.html($(a).clone()); // Вставляем в него ссылку
    il.find('a').text(ilText); // А в ссылку текст, который был прежде
    li.text($(a).text()); // Убираем ссылку на текущем элементе
    li.addClass('select'); // И делаем его активным

    $('#mode').val(mode);

    if (mode == 'file') {
      $('.file div.file').show('fast');
      $('.file div.link').hide('fast');
    } else {
      $('.file div.file').hide('fast');
      $('.file div.link').show('fast');
    }
    return false;
  },
  /**
   * Отправка формы с файлами аяксом
   */
  upload : function(btn)
  {
    $('.err').remove();
    var file = $('#file');

    var clone = Blog.Topic.cloneForm(file);
    Blog.Topic.progressBar($('.fileinput'), true);

    clone.append('<textarea name="description[0]">' +
          $('#description').val() +
        '</textarea>');
    clone.append('<input type="hidden" name="f_id" value="' + $('#f_id').val() + '" />');

    clone.ajaxSubmit({
      success: function(json) {
        try {
          eval('json = ' + json);
          // Убиваем клонированную форму
          Blog.Topic.cloneFormKill(file);
          if (json) {
            // Обновляем t_id на случай, если это новый топик
            $('#t_id').val(json.t_id);
            Blog.Topic.progressBar($('.fileinput'), false);
            // Обновляем список файлов
            if (json.url) $('#topic-edit').attr('action', json.url);
            Blog.Topic.VID.updateFileList(json.files);
          }
        } catch(e) {
          Blog.Topic.progressBar($('.fileinput'), false);
          Blog.Topic.cloneFormKill(file);
        }
      }
    });
    return false;
  },
  /**
   * Отправка формы без файла
   */
  uplink : function(btn)
  {
    $('.err').remove();
    var on = $('#href');
    Blog.Topic.progressBar(on, true);
    $.getJSON($('#topic-edit').attr('action'),
     {
        f_uplink:$('#f_id').val(),
        f_desc:$('#description1').val(),
        f_href:$('#href').val()
     },
     function(json){
       Blog.Topic.progressBar(on, false);
     });
     return false;
  }
}

/**
 * Работа с изображениями в редакторе
 */
Blog.Topic.Image = {
  /**
   * Предпросмотр
   */
  preview : function(src)
  {
    var html = '<img class="preview" src="' + src + '" onclick="$(this).remove()" title="Закрыть" />';
    $('#leftColumn').append(html);

    switch(Blog.Topic.type()) {
      case 'TXT':
        var on = $('.files');
        break;
      case 'IMG' :
        var on = $('.file');
        break;
    }

    Blog.centrize($('img.preview'), on);

    return false;
  },
  /**
   * Удаление изображения
   */
  remove : function(index, id)
  {
    var li = $('.file-' + index);

    if (Blog.Topic.type() == 'IMG') {
      Blog.Topic.IMG.progressBar($('.file-' + id), true);
    }

    $.getJSON(li.find('a').attr('href'), { f_remove : id , t_id : $('#t_id').val() },
    function(json){
      if (json["delete"]) {
        switch (Blog.Topic.type()) {
          case 'TXT':
            Blog.Topic.TXT.inputFile(li, index);
            break;
          case 'IMG':
            Blog.Topic.IMG.progressBar($('.file-' + id), false);
            $('.edit-' + id).hide('fast');
            Blog.Topic.IMG.removed(id);
            break;
        }
      }
    });

    return false;
  },
  /**
   * Кеширование фотографии
   */
  cache : function(src)
  {
    $('form#topic-edit').append('<img style="display:none" src="' + src + '" />');
  }
}

var dragging = false;
var dragMembers = {};
var DND = function(elem)
{
  this.elem = $(elem);
  this.init();
}
DND.prototype.init = function()
{
  var DND = this;
  $(this.elem).mousedown(function(e){
    if (e.button == 0) {
      dragging = DND.elem;
      dragging.addClass('dragged');
    }
  });
  $(this.elem).mouseup(function(e){
    if (dragging) {
      dragging.removeClass('dragged');
      dragging = false;
      Blog.Topic.IMG.order(dragMembers.dragging, dragMembers.replaced, dragMembers.position);
    }
  });
  $(this.elem).mouseover(function(e){
    if (dragging) {
      var client = e.clientX;
      var drclient = Blog.dimentions.cumulativeOffset(DND.elem.get(0))[0] + 45;
      if (client <= drclient) {
        $(dragging).insertAfter(DND.elem);
        dragMembers.position = 1;
      } else {
        $(dragging).insertBefore(DND.elem);
        dragMembers.position = -1;
      }
      dragMembers.dragging = dragging;
      if (DND.elem != dragging) dragMembers.replaced = DND.elem;

    }
  });
}

$(function(){
  var t = $('#topic-edit textarea').get(0);
  if (t) Blog.Topic.Editor = new SimpleEditor(t);
  $('#topic-edit .thumbnail').each(function(){
    new DND($(this));
  });
})