var Blog = function() {

}
/**
 * Всплывающее окно с предложением регистрации
 */
Blog.popup = function(at) {

  if (Blog.popup.at) $(Blog.popup.at).toggleClass('translucent-more');
  if ($('.auth-popup').size() == 0) {
    var text = 'Для этого вам нужно <a href="/registration/">зарегистрироваться</a> или <a href="/enter/">войти</a> в систему';
    var html = '<div class="auth-popup">' +
        '<div class="l"></div>' +
        '<div class="c">' +
        '<a class="x" onclick="return Blog.popup.close(this)"><span>Закрыть</span></a>' +
        text +
        '</div>' +
        '<div class="r"></div>' +
        '</div>';

    $('#leftColumn').append(html)
  }

  Blog.centrize($('.auth-popup'), at);
  $(at).toggleClass('translucent-more');
  $('.auth-popup').show();
  Blog.popup.at = at;
  return false;
}
/**
 * Закрывашка всплывающего окна
 */
Blog.popup.close = function(elem)
{
  $(elem).parents('.auth-popup').hide();
  $(Blog.popup.at).toggleClass('translucent-more');
  return false;
}

/**
 * Центрует элемент в окне (но не ставит ему position:absolute)
 */
Blog.centrize = function(elem, under)
{
  if (under) return Blog.centrize.under(elem, under);

  var p = {h:Blog.dimentions.pageHeight(), w:Blog.dimentions.pageWidth()};
  var e = {h:$(elem).height(), w:$(elem).width()};

  var n = {
    t: (p.h - e.h) / 2,
    w: (p.w - e.w) / 2
  }
  if (n.t < 0) n.t = 0;
  if (n.l < 0) n.l = 0;
  if (n.l + e.w > p.w) n.l = p.w - e.w;

  n = Blog.centrize.compensation(elem, n);

  $(elem).css({
    left: (n.l) + 'px',
    top:  (n.t + Blog.dimentions.scrollHeight()) + 'px'
  });

}
/**
 * Центрует элемент над блоком under
 */
Blog.centrize.under = function(elem, under)
{

  var p = Blog.dimentions.cumulativeOffset($(under).get(0));
  var p = {h:$(under).height(), w:$(under).width(), l:p[0], t:p[1]};
  var e = {h:$(elem).height(), w:$(elem).width()};

  var n = {
    l: p.l + (p.w - e.w) / 2,
    t: p.t + (p.h - e.h) / 2
  }

  if (n.t < 0) n.t = 0;
  if (n.l < 0) n.l = 0;

  n = Blog.centrize.compensation(elem, n);

  $(elem).css({
    left: (n.l) + 'px',
    top:  (n.t) + 'px'
  });
}
/**
 * Корректирует централизацию, т.к. .box имеет position:relative
 */
Blog.centrize.compensation = function(elem, d)
{
  var r = Blog.dimentions.cumulativeOffset($(elem).parents('.box').get(0));

  d.l = d.l - r[0];
  d.t = d.t - r[1];
  return d;
}

/**
 * Размеры
 */
Blog.dimentions = {
  pageWidth : function() {
    return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
  },
  pageHeight : function() {
    return window.innerHeight != null? window.innerHeight: document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight:document.body != null? document.body.clientHeight:null;
  },
  scrollHeight : function() {
    var h = window.pageYOffset ||
            document.body.scrollTop ||
            document.documentElement.scrollTop;
    return h ? h : 0;
  },
  scrollWidth : function() {
     var w = window.pageXOffset ||
             document.body.scrollLeft ||
             document.documentElement.scrollLeft;

     return w ? w : 0;
  },
  cumulativeOffset : function(element)
  {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  }
}



Blog.widget = {
  /**
   * Прежнего активного делаем ссылкой
   */
  beforeload : function(a, functionName)
  {
    var selected = $(a).parents('div.selector').find('li.select');
    selected.toggleClass('select');
    var href = selected.attr('class');
    selected.html('<a onclick="return Blog.widget.' + functionName + '(this)" href="/' + functionName + '/' + href + '">' + selected.text() + '</a>');
  },
  /**
   * Делаем активным кликнутого
   */
  afterload : function(a)
  {
    var selected = $(a).parent();
    selected.toggleClass('select');
    selected.text($(a).text());
  },
  /**
   * Включаем правильный rmore
   */
  setmore : function(a)
  {
    $(a).parents('div.infobox').find('a.rmore').hide();
    $(a).parents('div.infobox').find('a.' + $(a).parent().attr('class')).show();
  },
  /**
   * Загрузка виджета "Лидеры рейтинга"
   */
  shortlist : function (a)
  {

    $.getJSON($(a).attr('href'), function(json){
      Blog.widget.beforeload(a, 'shortlist');

      // Вставляем данные
      var auth = $(a).parents('div.infobox').find('.auth');
      auth.empty();

      for (var i = 0, l = json.users.length; i < l; i++) {
        var u = json.users[i];
        var html = '<li class="' + (u.gender == 'M' ? 'userm' : 'userw') +
          '"><a href="' + u.url + '">' + u.name + '</a><span>' + u.rating + '</span></li>'
        auth.append(html);
      }

      Blog.widget.setmore(a);
      Blog.widget.afterload(a);

    });
    return false;
  },
  /**
   * Загрузка виджета "Популярные темы"
   */
  popular : function (a)
  {
    $.getJSON($(a).attr('href'), function(json){

      Blog.widget.beforeload(a, 'popular');

      // Вставляем данные
      var popT = $(a).parents('div.infobox').find('.popT');
      popT.empty();

      for (var i = 0, l = json.topics.length; i < l; i++) {
        var t = json.topics[i];
        var html = '<li class="popT' + t.type + '"><a href="' + t.url + '">' + t.subject + '</a><span>' + t.rating + '</span></li>'
        popT.append(html);
      }

      Blog.widget.setmore(a);
      Blog.widget.afterload(a);

    });
    return false;
  }
}

/**
 * Добавление/удаление избранного
 */
Blog.favorite = function (a, current_user)
{
  if (!current_user) {
    return Blog.popup($(a).parents('.subNav'));
  }
  $.getJSON($(a).attr('href'), function(json){
    if (json && json.favorite) {
      if (json.favorite.status) {
        // Топик в фаворитах
        $(a).attr('title', 'убрать из избранного');
        $(a).html('из избранного');
        $(a).parent().attr('class', 'favorite');
      } else {
        // Топик не в фаворитах
        $(a).attr('title', 'добавить в избранное');
        $(a).html('в избранное');
        $(a).parent().attr('class', 'infavorite');
      }
    }
  });
  return false;
}

/**
 * Голосование
 */
Blog.vote = function (a, current_user)
{
  if (!current_user) {
    if ($(a).parents('.comment').size()) {
      // Это в комментарии
      return Blog.popup($(a).parents('.comment'));
    } else {
      // Это в топике
      return Blog.popup($(a).parents('.btHeader'));
    }
  }

  $.getJSON($(a).attr('href'), function(json){
    if (json && json.status) {

      var s = $(a).siblings('span');
      var b = $(a).siblings('a');
      var ia = $(a).find('img');
      var ib = $(b).find('img');

      var sr = json.rating > 0 ? '+' + json.rating :
               (json.rating < 0 ? '&minus;' + (- json.rating) : '0');
      var sc = json.rating > 0 ? 'cool' : 'poor';

      // обновление рейтинга
      s.html(sr);
      s.removeClass('cool');
      s.removeClass('poor');
      s.addClass(sc);

      // отключение стрелок
      $(a).removeAttr('onclick');
      $(a).removeAttr('href');
      $(b).removeAttr('onclick');
      $(b).removeAttr('href');

      // новые стрелки

      if (json.vote > 0) {
        ia.attr('src', '/siteimg/arr-' + json.target + '-up-hot.gif');
        ib.attr('src', '/siteimg/arr-' + json.target + '-down-cold.gif');
      } else {
        ia.attr('src', '/siteimg/arr-' + json.target + '-down-hot.gif');
        ib.attr('src', '/siteimg/arr-' + json.target + '-up-cold.gif');
      }
    }
  });
  return false;
}

/**
 * Список всех форм для комментирования
 */
var CommentFormsList = {};

/**
 * Форма для комментирования
 */
var CommentForm = function(target, url, parentComment, subscribe, current_user)
{

  if (!current_user) {
    return Blog.popup($(target));
  }

  // Смотрим в кеше форм, прячем все формы. Если в кеше есть наша, то отображаем ее
  if (parentComment) {
    for (i in CommentFormsList) {
      if (i == parentComment) {
        CommentFormsList[i].showMe();
      } else {
        CommentFormsList[i].hideMe();
      }
    }
    if (CommentFormsList[parentComment]) {
      CommentFormsList[parentComment].showMe();
      return;
    } else {
      CommentFormsList[parentComment] = this;
    }
  }

  this.target = target;
  this.url = url;
  this.parc = parentComment;
  this.subscribe = subscribe;
  this.init();
}

/**
 * Отрисовка формы и определение событий
 */
CommentForm.prototype.init = function()
{
  var html = '<form action="' + this.url + '/' + this.parc + '/comment" ' +
      'method="post" style="display: none;" class="' + (this.parc ? 'child' : 'root') + '">' +
      '<p class="txt err" style="display:none">Добавление комментария не удалось</p>' +
      '<input type="hidden" name="parent" value="' + this.parc + '" />' +
      '<textarea name="comment"></textarea>' +
      '<div class="check">' +
      '<input type="checkbox" id="subscribe-' + this.parc + '" name="subscribe" ' +
      'class="ci" ' + (this.subscribe ? 'checked ' : ' ') + '/>' +
      '<label for="subscribe-' + this.parc + '" class="cl">Получать ответы на комментарий по электронной почте</label>' +
      '</div>' +
      '<div><input type="image" class="btn" src="/siteimg/btn/write.gif" value="Отправить" />' +
      (this.parc ? '<input type="image" class="btn cancel" src="/siteimg/btn/cancel.gif" value="Отмена" />' : '') +
      '</div>' +
      '</form>';
  $(this.target).append(html);
  this.form = $(this.target).find('form');

  this.editor = new SimpleEditor($(this.form).find('textarea'));

  var CF = this;

  // Отмена
  if (this.parc) {
    $(this.form).find('input.cancel').click(function(){
      CF.hideMe();
      return false;
    })
  }

  $(this.form).submit(function(){
    return CF.submit();
  });

  this.showMe();
}

/**
 * Оотображение формы
 */
CommentForm.prototype.showMe = function()
{
  if (this.visible) return;

  if (this.parc) {
    $(this.form).show('fast');
  } else {
    $(this.form).show();
  }
  this.visible = true;
}

/**
 * Сокрытие формы
 */
CommentForm.prototype.hideMe = function(scrollTo)
{
  if (!this.visible) return;

  // Если после закрытия формы нужен переход к элементу, то форму закрываем моментально
  $(this.form).find('.err').hide(scrollTo ? '' : 'slow');

  if (this.parc) {
    $(this.form).hide(scrollTo ? '' : 'fast');
    this.visible = false;
  }

  if (scrollTo) this.scrollTo(scrollTo);

  this.editor.reset();
}

/**
 * Отправка формы
 */
CommentForm.prototype.submit = function()
{
  if (this.submitting) return false;

  var text = this.editor.getText();
  if (!text || text == '<br>') return false;

  this.submitting = true;

  var CF = this;
  $(this.form).ajaxSubmit({
    dataType: 'json',
    success: function(json) {

      if (json && json["comment"]) {
        CF.pasteComment(json["comment"]);
      } else {
        CF.showError();
      }
      CF.submitting = false;
    }
  });
  return false;
}
CommentForm.prototype.showError = function()
{
  $(this.form).find('.err').show('slow');
}
CommentForm.prototype.pasteComment = function(r)
{

  if ($('#commens').css('display') == 'none') {
    var first = true;
  } else {
    var first = false;
  }

  var arrows = r.u_status == 'W' ? true : false;

  var html = '<div id="comment-' + r.c_id + '" class="comment own ' + (first ? 'first_com' : (r.c_id_parent ? 'answer ' : '')) + ('level' + r.c_indent) + '">' +
    '<ul>' +
      '<li><a class="' + r.u_gender + '" title="Профиль" href="/' + r.u_login + '/about" name="comment-' + r.c_id + '">' + r.u_name + '</a> <b>|</b></li>' +
      '<li><span class="dateC">' + r.c_created + '</span> <b>|</b></li>' +
      '<li>' +
        (arrows ? '<img height="11" width="8" src="/siteimg/arr-c-down-cold.png" alt="&darr;" title="Плохой комментарий"/>' : '') +
        ' <span class="poor" title="Рейтинг комментария">0</span> ' +
        (arrows ? '<img height="11" width="8" src="/siteimg/arr-c-up-cold.png" alt="&uarr;" title="Хороший комментарий"/>' : '') + '<b>|</b>' +
      '</li>' +
      '<li><a href="/' + r.u_blog + '/' + r.t_id + '/' + r.c_id + '/comment"' +
      'onclick="new CommentForm(\'#comment-' + r.c_id + '\', \'/' + r.u_blog + '/' + r.t_id + '\', ' + r.c_id + ', true, ' + r.u_id + '); return false">Ответить</a></li>' +
    '</ul><br clear="all"/>' +
    '<div class="txtcom">' + r.c_body + '</div>' +
  '</div>';
  var CF = this;
  if (r.c_id_parent) {
    // Надо найти последний комментарий на этом уровне и встать после него
    // А если соседей нет, то встать сразу после родителя

    // Пройдем по всем комментариям.
    // Между родителем и следующим камментом того же уровня
    // найдем последний комментарий такого же, как и вставляемый и встанем после него
    var parent = false;     // Родитель, тот на кого отвечали
    var found = false;      // Ссылка на найденый камент, вставить надо перед ним
    var ownIndent = r.c_indent;    // Уровень вставляемого
    if (ownIndent == 'N') ownIndent = 10;
    var parIndent = ownIndent - 1; // Уровень родителя
    var quit = false;   // Поиск успешно завершен

    $('.comment').each(function() {
      if (!parent) {
        /*
         * Поиск родителя
         */
        if ($(this).attr('id') == ('comment-' + r.c_id_parent)) {
          parent = $(this);
//          console.info('Levels %i %i', ownIndent, parIndent);
//          console.info('Parent %o', parent.get(0));
        }
      } else {
        /*
         * Родитель найден, а цель нет;
         * идем дальше, пока не наткнемся на коммент этого же уровня
         */
        if (!quit) {
          // бежим по комментариям пока не добежим до следующей ветки
          var ind = $(this).attr('class').match(/\d/i);
          if (CF.hasClassName($(this), 'levelN')) ind = 10;
          if (ind <= parIndent) quit = true;
          if (!quit) found = $(this);
        }
      }
    });

    // и если на своем уровне ничего нет, то встанем под родителя
    if (!found) found = parent;
//    console.info('Found %o', found.get(0));

    $(found).after(html);
//    console.info('Inserted %o', $('#comment-' + r.c_id).get(0));

  } else {
    $('#comments').append(html);
  }

  $('#count-counter').html('(' + r.t_comments + ')');
  $('#comments').show('fast');
  CF.hideMe('#comment-' + r.c_id);
}
CommentForm.prototype.hasClassName = function(elem, className)
{
  var classes = $(elem).attr('class').split(' ');
  for (var i = 0, l = classes.length; i < l; i++) {
    if (classes[i] == className) return true;
  }
  return false;
}
CommentForm.prototype.scrollTo = function(element)
{
  if (element) {
    element = $(element);
    var pos = this.cumulativeOffset(element.get(0));
    window.scrollTo(pos[0], pos[1]);
  }
}
CommentForm.prototype.cumulativeOffset = function(element)
{
  var valueT = 0, valueL = 0;
  if (element) do {
    valueT += element.offsetTop  || 0;
    valueL += element.offsetLeft || 0;
    element = element.offsetParent;
  } while (element);
  return [valueL, valueT];
}

/**
 * Если надо, переводит два разряда года в четыре разряда для указанного контрола
 * @param {Object} input
 */
function year24(input)
{
  var y = $(input).val();

  y = y * 1;

  if (y < 100) {
    // берем текущий год + 5 лет
    var cy = (new Date().getFullYear() + 5).toString();
    var cy12 = cy.slice(0, 2);
    var cy34 = cy.slice(2);

    if (y < cy34) {
      $(input).val(cy12.toString().concat(y < 10 ? '0' + y : y));
    } else {
      $(input).val((cy12 - 1).toString().concat(y < 10 ? '0' + y : y));
    }
  }
}
/**
 * Проверяет возможна ли такая дата
 *
 * @param {Integer} d день
 * @param {Integer} m месяц
 * @param {Integer} y год (четыре разряда)
 * @param {Integer} h часы
 * @param {Integer} i минуты
 * @return {Boolean}
 */
function date_valid(d, m, y, h, i)
{

  d = d * 1;
  m = m * 1;
  y = y * 1;
  h = h * 1;
  i = i * 1;

  if (h > 24 || h < 0) return false;

  if (i > 60 || i < 0) return false;

  if (!d || !m || !y) return false;

  if (d < 1 || d > 31) return false;

  if (m == 4 || m == 6 || m == 9 || m == 11) {
    if (d > 30) return false;
  }

  if (m == 2) {

    if (d > 29) return false;

    // Кратность
    var rep4   = (y % 4)   ? false : true;
    var rep100 = (y % 100) ? false : true;
    var rep400 = (y % 400) ? false : true;

    // Не високосный
    // http://ru.wikipedia.org/wiki/Високосный_год
    if (!rep4 || (rep4 && rep100 && !rep400)) {
      if (d > 28) return false;
    }

  }

  return true;
}
