// Обновляем альбомы по загрузке и по ресайзу окна
$(function (){
  albumsUpdate();
  $(window).resize(albumsUpdate);
})

// Убирает не влезающие картинки в альбомах, чтобы они были в одну строчку
function albumsUpdate(){
  $("#gallery .album").each(albumUpdate);
}

// Убирает не влезающие картинки в одном альбоме
function albumUpdate(){
  var $this = $(this);
  var count = Math.floor((this.offsetWidth + 17) / (122+17)) ;

  $this.find(".item:lt(" + count + ")").show();
  $this.find(".item:gt(" + (count-1) + ")").hide();
}

// Храним уже кликнутые картинки, чтобы два раза не добавлять счётчик
var imageHits = {};

// Добавляет просмотр картинке
function imageAddHit(id){
  if (imageHits[id]) return; 

  (new Image()).src = "/counter.fcgi?obj=gallery.image;id="+id;

  var hitsEl = $("#image-hits-"+id);
  if (hitsEl) hitsEl.text( 1*hitsEl.text() + 1 );

  imageHits[id] = true;
}

// Удаление картинки владельцем
function deleteImage(id){
  if (confirm("Вы уверены что хотите удалить изображение?")) {
    var img = $("#image" + id);
    var dom = img.get(0);

    if (img.css("position") == "static") img.css("position", "relative");

    dom._mask = $('<div class="j-el-mask"></div>');
    dom._mask.appendTo(img);
    img.addClass('j-masked');

    $.ajax({
      url: "/fotki/my/image.delete.ajax.cgi?id="+id,
      success: deleteImageCallback,
      error: function (XMLHttpRequest, textStatus, errorThrown){
        alert(textStatus + ' ' + XMLHttpRequest.status);
        $("#gallery .j-el-mask").remove();
      }
    });
  }
}

Gallery = {};

// Сообщения об ошибках
Gallery.errorMessages = {
    error: 'Произошла неизвестная ошибка',
    internal: 'Произошла внутренняя ошибка',
    db: 'Ошибка при работе с БД',

    auth_required: 'Необходима авторизация',
    album_owner_mismatch: 'Вы не владелец альбома',

    require_id: 'Требуется id изображения',
    image_not_found: 'Изображение не найдено',

    stop_word: 'Нельзя создать тег с таким именем'
};

function deleteImageCallback(data){
  var result;

  try {result = eval("(" + data + ")");} 
  catch (e) {
    alert(data);
    result = {success: false, errors: []};
  }

  if (result.success) $("#image" + result.id).remove();
  else {
    var msg = $.map(result.errors, function (item) {
      return Gallery.errorMessages[item] || item;
    }).join("\n")

    if (msg) alert(msg);

    $("#gallery .j-el-mask").remove();
  }
}

Gallery.errorFunc =  function (XMLHttpRequest, textStatus, errorThrown){
  alert(textStatus + ' ' + XMLHttpRequest.status);
  if (this.cleanup) this.cleanup();
}

Gallery.processJson = function (data, errorMessages)
{
  var result;

  try {result = eval("(" + data + ")");} 
  catch (e) {
    alert(data);
    result = {success: false};
  }

  if (!result.success)
  {
    var msg;

    if (result.error)
    {
      msg = errorMessages[result.error] || result.error;
      if (result.text) msg += "\n" + result.text;
    }
    else if (result.errors)
    {
      msg = $.map(result.errors, function (item) { return errorMessages[item] || item; }).join("\n")
    }

    alert(msg);
  }

  return result;
}

Gallery.url = {};
Gallery.url.favoriteAdd = '/fotki/favorite-add/';
Gallery.url.favoriteRemove = '/fotki/favorite-remove/';
Gallery.url.tagAdd = '/fotki/tag-add/';
Gallery.url.tagRemove = '/fotki/tag-remove/';

Gallery.favoriteAdd = function (id)
{
    $('#img_table_p a').hide();
    $('#img_table_p').append('<b style="color:#9b9b9b">Добавляется..</b>');

    $.ajax({
      url: this.url.favoriteAdd,
      data: {id: id},
      success: this.favoriteAddSuccess,
      error: this.errorFunc,
      cleanup: this.favoriteAddCleanup,
      scope: this
    });
}

Gallery.favoriteAddCleanup = function (data)
{
    $('#img_table_p b').remove();
    $('#img_table_p a').show();
}

Gallery.favoriteAddSuccess = function (data)
{
    var result = this.scope.processJson(data, this.scope.errorMessages);

    if (result.success)
    {
        $('#img_table_p a').remove();
        $('#img_table_p b').remove();
        $('#img_table_p').append('<a href="/fotki/favorites/">В избранном</a>')
    }
    else
    {
        this.cleanup();
    }
}

Gallery.favoriteRemove = function (id)
{
    var thumb = $('#thumb'+id);
    thumb.find('.remove').hide();
    thumb.append('<span class="removing" style="color:#9b9b9b">Удаляется..</span>')

    $.ajax({
      url: this.url.favoriteRemove,
      data: {id: id},
      success: this.favoriteRemoveSuccess,
      error: this.errorFunc,
      cleanup: this.favoriteRemoveCleanup,
      scope: this,
      thumb: thumb
    });
}

Gallery.favoriteRemoveCleanup = function (data)
{
    this.thumb.find('.removing').remove();
    this.thumb.find('.remove').show();
}

Gallery.favoriteRemoveSuccess = function (data)
{
    var result = this.scope.processJson(data, this.scope.errorMessages);

    if (result.success)
    {
/*        this.thumb.find('.remove').remove();
        this.thumb.find('.removing').remove();*/
        this.thumb.remove();
    }
    else
    {
        this.cleanup();
    }
}

Gallery.tagAdd = function (id, tag)
{
    $('#image-tag-add a').css({opacity: 0.5});

    var cfg = {id: id, tag: tag};

    $.ajax({
      url: this.url.tagAdd,
      data: cfg,
      cfg: cfg,
      success: this.tagAddSuccess,
      error: this.errorFunc,
      cleanup: this.tagAddCleanup,
      scope: this
    });
}

Gallery.tagAddCleanup = function (data)
{
    $('#image-tag-add a').css({opacity: 1});
    $('#image-tag-add input').focus();
}

Gallery.tagAddSuccess = function (data)
{
    var result = this.scope.processJson(data, this.scope.errorMessages);

    if (result.success)
    {
        $('#image-tags-cell .none').remove();
        if ($('#tag'+result.id).length == 0)
        {
            var newTag = this.cfg.tag.toLowerCase();

            // Формируем html
            var html = '<span class="tag new-tag" id="tag'+result.id+'">';
            html +=  '<a class="tag-link" href="/fotki/tag/'+result.id+'/">' + newTag + '</a>';
            html += '<a class="remove"><img src="http://redom.ru/img/admin/delete.gif" alt="Удалить"/></a></span>';

            // Ищем место для вставки
            var tags = $('#image-tags-cell .tag-link');
            for (var i = 0; i < tags.length; i++)
            {
                if (tags[i].innerHTML > newTag) break;
            }
            // Вставляем
            var tag = $('#image-tags-cell .tag:eq('+i+')');
            if (tag.length) tag.before(html); else $('#image-tags-cell').append(html);

            // активируем кнопку удаления
            var image_id = this.cfg.id;
            $('#tag'+result.id+' .remove').click(function (){
                Gallery.tagRemove(image_id, result.id);
            });
        }
        $('#image-tag-add input').val('');
    }

    this.cleanup();
}

Gallery.tagRemove = function (id, tag_id)
{
    $('#tag'+tag_id+' img').css({opacity: 0.5});

    var cfg = {id: id, tag_id: tag_id};

    $.ajax({
      url: this.url.tagRemove,
      data: cfg,
      cfg: cfg,
      success: this.tagRemoveSuccess,
      error: this.errorFunc,
      cleanup: this.tagRemoveCleanup,
      scope: this
    });
}

Gallery.tagRemoveCleanup = function (data)
{
    $('#tag'+this.cfg.tag_id+' img').css({opacity: 1});
}

Gallery.tagRemoveSuccess = function (data)
{
    var result = this.scope.processJson(data, this.scope.errorMessages);

    if (result.success)
    {
        $('#tag'+this.cfg.tag_id).remove();
    }

    this.cleanup();
}

