var user = {id: null, username: null, first_name: null, last_name: null};
var item = {};
function makePrettyDates() {
  var dates = $('.comment-time');
  for ( var i = 0; i < dates.length; i++ )
    if ( dates[i].title ) {
      var date = prettyDate(dates[i].title);
      if ( date )
        dates[i].innerHTML = date;
    } 
}
$(document).ready(function(){
  $('.saved-fade-out').fadeOut(3000);

  makePrettyDates();
  setInterval(makePrettyDates,5000);

  $('.dropdown-toggle').mouseover(function(e) {
    $(this).next('.dropdown-menu').show();
  });

  $('.dropdown-toggle').mouseout(function(e) {
    $(this).next('.dropdown-menu').hide();
  });

  $('.dropdown-menu').mouseover(function(e) {
    $(this).show();
  });

  $('.dropdown-menu').mouseout(function(e) {
    $(this).hide();
  });

  $('#logout').click(function(){
    FB.logout(function(){
      window.location = '/signout';
    });  
  });

  $('.tip').twipsy({'live':true});
  $('.tip-right').twipsy({'live':true,'placement': 'right'});

  // Open modal for original song
  $('.play-original').click(function(){
    ytplayer.pauseVideo();
    $('#ytapimodalplayer').height(390).width(640);
    
    // Get YouTube
    $.post('/music/get-song',{ss:$(this).attr('data-ss')}, function(resp) {
        resp = eval(resp);
        var yid = resp.url.match(/v\/(.{11})/)[1];
        if(yid === '') {
        } else {
          var params = { allowScriptAccess: "always" };
          var atts = { id: "ytmodalplayer", wmode:"transparent" };
          swfobject.embedSWF(resp.url + '&wmode=transparent&version=3&rel=0&autoplay=1',
                             "ytapimodalplayer", "640", "390", "8", null, null, params, atts);
        }
    });
  });

  // When modal player is hidden, resume original video
  $('#originalmodal').bind('hidden',function(){
    if (ytplayer.getPlayerState() === 2)
      ytplayer.playVideo();
  });


  $('#submit-cover').click(function(e){
    e.preventDefault();
    $('#submit-cover-form').submit();
  });

  $('#submit-cover-form').submit(function(e){
    e.preventDefault();
    $('#submit-cover').hide();
    $('.modal-footer .saving').show();
    $.post('/items/submit',$('#submit-cover-form').serialize(), function(resp) {
      $('.modal-container').hide();
      $('#submit-cover').show();
      $('.modal-footer .saving').hide();
      $('#submitmodal').modal('hide');
    });
  });

  $('#instruments').click(function(){
    if ($(this).is(':checked'))
      $('.instruments_list').show();
    else
      $('.instruments_list').hide();
  });

  $('.submiturl').submit(function(e){
    e.preventDefault();
    if (user.id) {
      var match = $('#yturlinput').val().match(/youtube.com\/[^?]*\?[^?]*v=(.{11})(&|$)|\/(.{11})$/);

      if ($('#yturlinput').val().length < 1 || (!match)) {
        $('span.error', $(this)).show();
        return;
      }

      $('#yturl').val($('#yturlinput').val());

      $('#submitmodal').modal({show:true,keyboard:true,backdrop:true});
    } else {
      //$('.not-logged-in').show();
    }
  });

  /**
   * Comment/Reply Stuff
   */
  $('.vote').live('click', function() {
    if (user.id) {
      $.post('/items/vote',{vote: $(this).attr('data-value'),item_id: $(this).attr('data-item-id'),comment:$('.newcomment').val()}, function(resp) {
        if (resp) {
          if (resp.bio == null) {
            resp.bio = '';
          }
          if ($('.' + resp['id']).length > 0) {
            if (resp['comment']) {
              $('.' + resp['id']).find('.comment-text').text(resp.comment);
              $('.' + resp['id']).children('.comment-wrapper').attr('style','background:#FFFFCC;');
            } else {
              $('.' + resp['id']).remove();
            }
          } else {
            if (resp['comment'])
              $('.master-comments').append('<li class="comment ' + resp['id'] + '"><div class="comment-wrapper" style="background:#FFFFCC;"><div class="user-pic-small"><img src="' + resp.img + '" /></div><div class="comment-content"><div class="comment-title"><a href="' + resp.url + '">' + resp.name + '</a>, <span class="inline-bio tip" data-original-title="' + resp.bio + '">' + resp.bio.substr(0,30) + '</span> - <span class="comment-time" title="' + resp.timestamp['sec'] + '"></span></div><span class="comment-text">' + resp.comment + '</span></div><div class="comment-controls"><ul class="unstyled"><li><a class="comment-reply" href="#">Reply</a></li></ul></div></div><div class="level2 newcomment-reply"><form class="comment-reply" data-comment-id="' + resp['id'] + '" data-user-id="' + user.id + '"><input type="hidden" value="' + resp['id'] + '" name="vote_id"/><textarea class="xlarge" name="comment"></textarea>&nbsp;<button type="submit" class="btn primary">Reply</button></form></div><ul class="unstyled comment-replies level2"></ul></li>');
          }
          makePrettyDates();
          
          // Scroll to comment change
          $('.comment-success').show();
          $('html, body').animate({
            scrollTop: $('.' + resp['id']).offset().top
          }, 1000);
        }
      });
      return false;
    } else {
      //$('.not-logged-in').show();
    }
  });

  $('a.comment-reply').live('click', function(e){
    e.preventDefault();

    var reply_form = $(this).closest('.comment').find('.newcomment-reply');

    // Show comment reply form
    reply_form.toggle();
    
    // Scrolls the page to the newly shown reply form
    $('html, body').animate({
      scrollTop: reply_form.offset().top
    }, 1000);

    // Set focus to the reply form
    reply_form.find('textarea').focus();
  });

  $('form.comment-reply').live('submit', function(e){
    // Submit comment reply to /comments/reply with Vote id
    var that = this;
    $(this).children('button').disabled = true;
    $.post('/items/vote/reply',$(this).serialize(), function(resp) {
      if (resp) {
        var comment_id = $(that).attr('data-comment-id');
        var user_id = $(that).attr('data-user-id');
        if (resp.bio == null) {
          resp.bio = '';
        }
        $(that).parent().siblings('ul').append('<li class="comment"><div style="background:#FFFFCC;" class="comment-wrapper" data-comment-id="' + comment_id + '" data-post-id="' + user_id + '" data-user-id="' + user_id + '"><div class="user-pic-small"><img src="' + resp.img + '" /></div><div class="comment-content"><div class="comment-title"><a href="' + resp.url + '">' + resp.name + '</a>, <span class="inline-bio tip" data-original-title="' + resp.bio + '">' + resp.bio.substr(0,30) + '</span> - <span class="comment-time" title="' + resp.timestamp['sec'] + '"></span></div><span class="content">' + resp.comment + '</span></div><div class="comment-controls delete-reply" style="display:none;"><a class="comment-delete" href="#">Delete</a></div></div></li>');
        $(that).children('button').disabled = false;
        makePrettyDates();
        $('.comment-success').show();
      }
    });
    e.preventDefault();
    $(this).closest('.comment').find('.newcomment-reply').toggle();
  });

  /**
   *
   */
  $('a.preview').live('click',function(e){
    e.preventDefault();
    var itemid = $(this).attr('data-itemid');
    if ($('#preview' + itemid).length > 0) {
      $('#preview' + itemid).closest('.inline-player').toggle();
      return;
    }

    var source = $(this).attr('data-source');
    $(this).closest(".item-row").next().find(".inline-player").prepend('<div class="previewplayer"><div id="preview' + itemid + '"><embed id="preview' + itemid +'" src="http://www.youtube.com/v/' + source + '?wmode=transparent&version=3&rel=0&autoplay=0&enablejsapi=1&playerapiid=preview' + itemid +'" type="application/x-shockwave-flash" allowscriptaccess="always" width="425" height="356"></embed></div></div>');
    $('#preview' + itemid).closest('.inline-player').show();
    var params = { allowScriptAccess: "always", autoplay: 1, wmode: 'transparent' };
    var atts = { id: "preview" + itemid };
    swfobject.embedSWF("http://www.youtube.com/e/" + source + "?enablejsapi=1&autoplay=1&playerapiid=preview" + itemid,
                       "preview" + itemid, "464", "283", "8", null, null, params, atts);
  });
  $('.inline-player .close').click(function(){
    $(this).closest('.inline-player').hide();
  });

  /**
   * Cover battle
   */
  $('.arena-vote').live('click',function(e){
    e.preventDefault();
    $('#vote-modal').show();
    var i = $(this).attr('data-item-id');
    var that = this;
    // Save vote, then load next video
    if (user.id) {
      $.post('/contests/vote',{contest_id: $(this).attr('data-contest-id'), left: $(this).attr('data-left'), right: $(this).attr('data-right'), winner: $(this).attr('data-winner'), vh: $(this).attr('data-vh')}, function(resp) {
        if ($(that).attr('data-contest-slug'))
          window.location = '/battle/' + $(that).attr('data-contest-slug');
        else
          window.location.reload();
      });
    }
  });

  $('.battle-comment-form').submit(function(e){
    e.preventDefault();
    var that = this;
    
    $.post('/items/vote',{vote: 0,item_id: $(this).attr('data-item-id'),comment:$(this).find('input').val()}, function(resp) {
      if (resp) {
        if (resp['comment']) {
          $(that).children('.comment-form').children().hide();
          $(that).find('.comment').show().text(resp['comment']);
        }
      }
    });
  });

  /**
   * Limit character count to 300
   */
  $('.newcomment').textLimit('300',function(length,limit,reached) {
    $(this).siblings('.help-block').children('span.#charsLeft').text((limit - length) + ' characters left.');
    if (reached) {
      $(this).siblings('.help-block').children('span.#charsLeft').text('0 Limit reached.');
    }
  });

  /*
  $(document).click(function() {
    $('.popover').parent('li').popover('hide');
  });

  $('.recent-vote').live('click',function(e) {
    e.preventDefault();
    $('.popover').parent('li').popover('hide');
    $(this).popover({html:true,trigger:'manual',placement:'left'});
    $(this).popover('show');
  });
  */

  $('.comment-wrapper').live({
    mouseover: function () {
      if ($(this).attr('data-post-id') == $(this).attr('data-user-id')) {
        $(this).children('.delete-reply').show();
      }
    },
    mouseout: function () {
      $(this).children('.delete-reply').hide();
    }
  });

  $('.comment-delete').live({
    click: function (e) {
      e.preventDefault();
      var comment_wrapper = $(this).closest('.comment-wrapper');
      var comment_id = comment_wrapper.attr('data-comment-id');
      var user_id = comment_wrapper.attr('data-user-id');
      var comment = comment_wrapper.children('div.comment-content').children('span.content').text();
      $(this).closest('li').remove();
      $.post('/items/delete-reply',{comment_id:comment_id, user_id:user_id, comment:comment });
    }
  });
});

var player1_played = false;
var player2_played = false;
var playerListeners = {};
var ytplayer;
var ytarenaplayer1
var ytarenaplayer2;

function onYouTubePlayerReady(playerId) {
  $('.arena-vote').attr('disabled', 'disabled');

  var tmp = playerId;
  ytplayer = document.getElementById("ytpageplayer");

  if (playerId == 'ytarenaplayer1') {
    ytarenaplayer1 = document.getElementById(playerId);
  } else if (playerId == 'ytarenaplayer2') {
    ytarenaplayer2 = document.getElementById(playerId);
  }

  playerListeners[playerId] = function (status) {
    var playerId = tmp;
    $(document).ready(function() {
      if (playerId == 'ytarenaplayer1' && status === 1 && ytarenaplayer2.getPlayerState() === 1) {
        ytarenaplayer2.pauseVideo();
      } else if (playerId == 'ytarenaplayer2' && status === 1 && ytarenaplayer1.getPlayerState() === 1) {
        ytarenaplayer1.pauseVideo();
      }
      if (playerId == 'ytarenaplayer1' && ytarenaplayer1.getPlayerState() !== -1) {
        player1_played = true;
      } else if (playerId == 'ytarenaplayer2' && ytarenaplayer2.getPlayerState() !== -1) {
        player2_played = true;
      }
      if (player1_played && player2_played) {
        $('.arena-vote').removeAttr('disabled');
      }
    });
  };

  if (playerId == 'ytarenaplayer1') {
    ytarenaplayer1.addEventListener('onStateChange', 'playerListeners.' + playerId);
  } else if (playerId == 'ytarenaplayer2') {
    ytarenaplayer2.addEventListener('onStateChange', 'playerListeners.' + playerId);
  }

  if (ytplayer)
    ytplayer.addEventListener('onStateChange', 'playerListeners.' + playerId);
}

