$(function(){
  var loggedIn = $('.user-handle').length > 0;
  var tags = Object.create(null);

  function toggleClick(){
    if (!loggedIn) {
      login();
      return false;
    }

    var $this = $(this);
    var normalized = $this.data('slug');
    var upvote = !$this.hasClass('tagged');
    $this.text($this.text() * 1 + (upvote? 1 : -1));
    $this.toggleClass('tagged');
    if (upvote)
      $.ajax({
        method: 'POST',
        url: '@{PackageTagR pn}',
        data: {slug:normalized}
      });
    else
      $.ajax({
        method: 'POST',
        url: '@{PackageUntagR pn}',
        data: {slug:normalized}
      });
  }


  $('.tags').find('.tag').each(function(){
    tags[$(this).find('.tag-name').text()] = true;
  });
  $('.expanding').each(function(){
    var $this = $(this);
    if ($this.height() > 300) {
      $this.addClass('collapsed');
      $this.find('.bottom-gradient').click(function(){
        $this.removeClass('collapsed');
      });
    }
  });
  $('#like').click(function(){
    var $this = $(this);

    if (loggedIn) {
      var action = 'like';
      if ($this.hasClass('fa-thumbs-up')) {
        action = 'unlike';
      }

      $this.toggleClass('fa-thumbs-up');
      $this.toggleClass('fa-thumbs-o-up');

      $likes = $('#likes');
      nLikes = parseInt($likes.text(), 10);

      if (action == 'like') {
        $this.attr('title','You liked this!');
        nLikes += 1;
        $.post("@{PackageLikeR pn}");
      } else {
        $this.attr('title','You disliked this.');
        nLikes -= 1;
        $.post("@{PackageUnlikeR pn}");
      }

      $likes.text(nLikes);
      $('#like-or-likes').text(nLikes == 1 ? ' like ' : ' likes ');

    } else {
      login();
    }
  });
  $('.tag-toggle').click(toggleClick);
  $('#add-tag').click(function(){
    if (!loggedIn) login();
    $('#add-tag-form').toggleClass('hidden');
    $('#new-tag').focus();
  });
  $('#new-tag').change(function(){
    $('#add-form-btn').val('Confirm');
    $('#tag-msg').hide();
  });
  $('#new-tag').keypress(function(){
    $('#add-form-btn').val('Confirm');
  });
  $('#add-tag-form').submit(function(){
    try {
      var candidate = $('#new-tag').val();
      var normalized = candidate
        .replace(/[^a-zA-Z0-9-.]/g,'-')
        .replace(/-+/g,'-')
        .replace(/^-/,'')
        .replace(/-$/,'')
        .toLowerCase();
      if (candidate !== normalized) {
        $('#new-tag').val(normalized);
        $('#add-form-btn').val('Done');
      } else {
        $.ajax({
          method: 'POST',
          url: '@{PackageTagR pn}',
          data: {slug:normalized},
          success: function(){

            $('.no-tags').remove();

            $('#new-tag').val('');
            $('#add-form-btn').val('Confirm');

            if (!tags[normalized]) {
              var tag = $('<span><a></a></span>');
              tag.find('a').text(normalized + ' ').attr('href','/tag/' + normalized);
              $('.tags').prepend(', ');
              var count = $('<a>1</a>')
                .addClass('tag-count')
                .addClass('tag-toggle')
                .addClass('tagged')
                .data('slug',normalized)
                .attr('title','Add/remove vote for: ' + normalized)
                .click(toggleClick);
              $('.tags').prepend(count);
              $('.tags').prepend(tag);
            }

            tags[normalized] = true;
          },
          error: function(err){
            $('#tag-msg').text("Couldn't add that tag").show();
          }
        });
      }
    } finally {
      return false;
    }
  });
});

// Workaround for missing functionality in IE 8 and earlier.
if( Object.create === undefined ) {
  Object.create = function( o ) {
    function F(){}
    F.prototype = o;
    return new F();
  };
}

function login(){
  window.location.href = '@{AuthR LoginR}';
}
