function choosePlural(amount, form1, form2, form3) {
  var variant = (amount%10==1 && amount%100!=11 ? 1 : amount%10>=2 && amount%10<=4 && (amount%100<10 || amount%100>=20) ? 2 : 3);
  return arguments[variant];
}

function distanceOfTimeInWordsFromNow(fromTime, includeSeconds) {
  return distanceOfTimeInWords(fromTime, new Date(), includeSeconds);
}

function distanceOfTimeInWords(fromTime, toTime, includeSeconds) {
  var fromSeconds = fromTime.getTime();
  var toSeconds = toTime.getTime();
  var distanceInSeconds = Math.round(Math.abs(fromSeconds - toSeconds) / 1000);
  var distanceInMinutes = Math.round(distanceInSeconds / 60);
  if (distanceInMinutes <= 1) {
    if (!includeSeconds)
      return (distanceInMinutes == 0) ? 'менее минуты' : '1 минуту';
    if (distanceInSeconds < 15)
      return 'около 15 секунд';
    if (distanceInSeconds < 40)
      return 'около 30 секунд';
    if (distanceInSeconds < 60)
      return 'менее минуты';
    return '1 минуту';
  }
  if (distanceInMinutes < 45)
    return distanceInMinutes + ' ' + choosePlural(distanceInMinutes, "минута", "минуты", "минут");
  if (distanceInMinutes < 90)
    return "около 1 часа";
  if (distanceInMinutes < 1440) {
    var hoursCount = (Math.round(distanceInMinutes / 60));
    return "около " + hoursCount + ' ' + choosePlural(hoursCount, "час", "часа", "часов");
  }

  if (distanceInMinutes < 2880)
    return "1 день";
  if (distanceInMinutes < 43200) {
    var daysCount = (Math.round(distanceInMinutes / 1440));
    return '' + daysCount + ' ' + choosePlural(daysCount, "день", "дня", "дней");
  }
  if (distanceInMinutes < 86400)
    return "около 1 месяца";
  if (distanceInMinutes < 525600) {
    var monthsCount = (Math.round(distanceInMinutes / 43200));
    return '' + monthsCount  + ' ' + choosePlural(monthsCount, 'месяц', 'месяца', 'месяцев');
  }
  if (distanceInMinutes < 1051200) {
    return "около 1 года";
  }

  var yearsCount = (Math.round(distanceInMinutes / 525600));
  return "более " + yearsCount + ' ' + choosePlural(yearsCount, "год", "года", "лет");
}

// Спасибо, Тёма!
function hsv2rgb (h, s, v)
{
  h /= 360;
  s /= 100;
  v /= 100;

  var m2 = v <= 0.5 ? v * (s + 1) : v + s - v * s;
  var m1 = v * 2 - m2;
    var r = norm2hex (hue2rgb (m1, m2, h + 1/3));
    var g = norm2hex (hue2rgb (m1, m2, h));
    var b = norm2hex (hue2rgb (m1, m2, h - 1/3));
    return r + '' + g + '' + b;
}

function hue2rgb (m1, m2, h)
{
  if (h < 0) h = h + 1;
  if (h > 1) h = h - 1;
  if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
  if (h * 2 < 1) return m2;
  if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;
  return m1;
}

function norm2hex (value)
{
  return dec2hex (Math.floor (255 * value));
}

function dec2hex (dec)
{
  var hexChars = "0123456789ABCDEF";
  var a = dec % 16;
  var b = (dec - a) / 16;
  hex = '' + hexChars.charAt (b) + hexChars.charAt (a);
  return hex;
}

function doHeaderAnim() {
  var h = Math.floor(360 * Math.random());
  var s = 30 + Math.floor(70 * Math.random());
  var v = 30 + Math.floor(50 * Math.random());

  $("#header h1 a").animate({
    color: '#' + hsv2rgb(h, s, v)
  }, 100 );
}

var currentCommentReplyFormId = null;

function toggleCommentReplyForm(id) {
  if (currentCommentReplyFormId != id) {
    $('#comment-' + id).append($("#comment-reply-form"));
    $('#comment-reply-form input[name=reply_to]').attr('value', id);
    currentCommentReplyFormId = id;
    forceShow = true;
  }

  if (!forceShow && $("#comment-reply-form").is(':visible')) {
    $("#comment-reply-form").hide();
  } else {
    $("#comment-reply-form").show();
    $("#comment-reply-form").find("textarea").focus();
    $("#comment-form").hide();
  }
}

function toggleCommentForm() {
  if ($("#comment-form").is(':visible')) {
    $("#comment-form").hide();
  } else {
    $("#comment-form").show();
    $("#comment-form").find("textarea").focus();
    $("#comment-reply-form").hide();
  }
}

function insertCommentAtEnd(html) {
  if ($("#comments .pagination:last").length > 0) {
    $("#comments .pagination:last").before(html);
  } else {
    $("#comments").append(html);
  }
}

function insertComment(parentId, commentDepth, html) {
  if (parentId == null) {
    insertCommentAtEnd(html);
  } else {
    var parentComment = $('#comment-' + parentId).get(0);
    var parentCommentDepth = commentDepth - 1;

    lastComment = parentComment;
    do {
      lastComment = $(lastComment).nextAll(".comment").get(0);
      if (lastComment) {
        var matches = /depth(\d+)/.exec(lastComment.className);
        currentDepth = parseInt(matches[1]);
      }
    } while(lastComment && currentDepth >= commentDepth)

    if (lastComment) {
      $(lastComment).before(html);
    } else {
      insertCommentAtEnd(html);
    }
  }

  $(".meta .follow").addClass('active');
}

function showComment(cid) {
  $('#comment-' + cid)
    .removeClass('hidden')
    .find('ul.links li')
      .show().end()
    .find('ul.links .show_comment')
      .hide().end();
}

var activeRequests = 0;

// Neonification!
/*$(document).ready(function() {
  $("#header h1 a").hover(function() {
    headerAnimInterval = setTimeout('headerAnimInterval = setInterval("doHeaderAnim();", 100)', 1000);
  }, function() {
    if (headerAnimInterval) {
      clearInterval(headerAnimInterval);
      headerAnimInterval = null;

      $("#header h1 a").animate({
        color: '#fff'
      }, 50 );
    }
  });
});*/

var privateMessageClickHandler = function(e) {
  pm_id = this.parentNode.id.match(/\d+$/)[0];
  window.location = '/private_messages/' + pm_id;
  return false;
}

var lastCheckedPM = null;
var lastCheckedPMState = null;
var privateMessageCheckBoxClickHandler = function(e) {
  var rowIndex = this.parentNode.parentNode.rowIndex;

  if (e.shiftKey && lastCheckedPM != null) {
    var table = this.parentNode.parentNode.parentNode;
    var from = rowIndex > lastCheckedPM ? lastCheckedPM : rowIndex - 1;
    var to   = rowIndex > lastCheckedPM ? rowIndex : lastCheckedPM;

    var rows = $(table).find("tr:gt(" + from + "):lt(" + (to - from) + ")");
    if (lastCheckedPMState) {
      rows.addClass('selected').find('input').attr('checked', true);
    } else {
      rows.removeClass('selected').find('input').attr('checked', false);
    }

  } else {
    lastCheckedPM = rowIndex;
    lastCheckedPMState = this.checked;
    $(this.parentNode.parentNode).toggleClass('selected', this.checked);
  }
}

//////////// VOTEBOX /////////////////

function votebox_vote(value, votebox_id, voteable_type, voteable_id) {
  votebox = $("#" + votebox_id);

  $.ajax({
    url:      '/votes/',
    dataType: 'html',
    type:     'post',
    data:     { 'voteable_type':        voteable_type,
                'voteable_id':          voteable_id,
                'value':                value,
                'authenticity_token':   window._token },

    success: function(data, textStatus) {
      votebox.replaceWith(data);
    }
  });
}

function initCachedVotebox(id, created_at, author_id, allowedToVoteForComments) {
  var votebox = $("#votebox_comment_" + id + ".cacheable");

  if (votebox.length > 0) {
    var vote = null;
    if (window['votebox_states'] != undefined) {
      vote = votebox_states ? votebox_states["comment_" + id] : null;
    }

    if (!allowedToVoteForComments || vote || (author_id == currentUserId) || (Date.now() - created_at) / 1000 > 30 * 24 * 3600) {
      votebox.removeClass("enabled")
      .addClass("disabled")
      .find("a.plus").replaceWith("<span class='button plus'></span>").end()
      .find("a.minus").replaceWith("<span class='button minus'></span>").end();
    }

    if (vote) {
      votebox
      .addClass("voted")
      .addClass(vote.voted > 0 ? "voted_for" : "voted_against");
    }
  }
}

var initializedComments = [];

  function initComments(allowedToDeleteComments, newCommentsAfter, allowedToVoteForComments) {
  var firstNewCommentId = null;
  var comments = $("#comments .comment.alive");

  comments.live('mouseover', function() {
    if (initializedComments.indexOf(this.id) < 0) {
      var id = this.id.match(/(\d+)$/)[1];
      var created_at = new Date(parseInt($(this).find("span.created_at").text()) * 1000);
      var author_id  = parseInt($(this).find("span.author_id").text());

      initCachedVotebox(id, created_at, author_id, allowedToVoteForComments);

      if (!allowedToDeleteComments) {
        $(this).find("li.delete").hide();
      }

      initializedComments.push(this.id);
    }
  });

  if (newCommentsAfter != null) {
    comments.filter(function() {
      var created_at = parseInt($(this).find("span.created_at").text());
      var ret = created_at > newCommentsAfter;

      if (ret) {
        if (firstNewCommentId == null) {
          firstNewCommentId = parseInt(this.id.match(/(\d+)$/)[1]);
        }
      }

      return ret;
    }).addClass('new');


    if (firstNewCommentId && window.location.hash == "#new-comments") {
      window.location.hash = "#comment-" + firstNewCommentId;
    }
  }
}


$(document).ready(function() {
  //$("#wrapper .tabs_group > .tabs li.active, #wrapper #subtabs li.active, #wrapper #primary_tabs").corner({ tl: { radius: 4 }, tr: { radius: 4 }, br: { radius: 0 }, bl: { radius: 0 } });
  //$(".rounded").corner({ tl: { radius: 4 }, tr: { radius: 4 }, br: { radius: 4 }, bl: { radius: 4 } });
  // $("#sidebar .block.community-info").corner({ radius: 3 })
  $("#content .flash").fadeIn("slow");
  $(".markItUp").css("width", String($("#content").innerWidth() - 200) + "px");

  $("#comment-form textarea, #comment-reply-form textarea").keydown(function(e) {
    if (e.ctrlKey && e.keyCode == 13) {
      this.form['commit'].click();
    }
  });

  $("form.disable_submits").submit(function() {
    $(this)
    .find(".submission input[type=submit], .submission input[type=button]")
    .disable();
  });

  $("#loading_indicator").ajaxStart(function() {
    activeRequests = activeRequests + 1;

    if (activeRequests > 0) {
      $('#loading_indicator').fadeIn('slow');
    }
  });

  $("#loading_indicator").ajaxStop(function() {
    activeRequests = activeRequests - 1;

    if (activeRequests == 0) {
      $('#loading_indicator').fadeOut('slow');
    }
  });


  if (document.body.id == "private_messages-index") {
    $('table.private_messages td.body, table.private_messages td.date').click(privateMessageClickHandler);
    $('table.private_messages td.checkbox input').click(privateMessageCheckBoxClickHandler);
  }

  $("#twitter_chat ol.tweets li.hoverable").hover(function() {
    $(this).removeClass("collapsed");
    $(this).addClass("full");
  }, function() {
    $(this).addClass("collapsed");
    $(this).removeClass("full");
  });
});
