//# -*- tab-width: 4 -*-

$(document).ready(function() {

  $("#tracklist li").each(function(){
    var num = '<span class="number"></span>';
    $(this).prepend(num);
  });

  setTrackNumber();

  $("#tracklist").sortable({ 
    handle: '.handle', 
    update: function(event, ui) {
      $.post(
        '/playlist_items/sort', 
        '_method=put&'+$(this).sortable('serialize'),
        function(data){
          $("#body").effect("highlight");
          setTrackNumber();
        }
      );
    }
  });
    
  $('.deletePlaylistItem').click(function(){
    var item = $(this).parent().parent();
    if(confirm("Are you sure you want to remove this track from the playlist?")){
      $.ajax({
              url: this.href.replace('/delete', ''),
              type: 'post',
              dataType: 'script',
              data: { '_method': 'delete' },
              success: function() {
                $(item).fadeOut().remove();
                setTrackNumber();
              }
          });
    }
    return false;
  });
  
  $('#removeCheckedTracks').click(function(){
    var items = new Array;
    $('#tracklist li .title input:checked').each(function(){
        items.push(this.value);
    });
    $(this).blur();    
    if(items.length < 1){
      alert('You must select some tracks first.');
      return false;
    }
    if(confirm("Are you sure you want to remove selected tracks from the playlist?")){
      $.ajax({
              url: "/playlist_items/destroy_multiple",
              type: 'post',
              dataType: 'script',
              data: {'items' : [items]},
              success: function() {
                $(items).each(function()
                {
                  $('#tracklist li#item_'+this).fadeOut().remove();
                });
                setTrackNumber();
              }
          });
    }
    return false;
  });
  
	$('.themedlist .hidden').hide();  
	
  $('.themedlist a.more').click(function(e){
    if($(this).html() == "Show more"){
      $(this).html('Show less');			
      $(this).parent().children('ul').children('li.hidden').removeClass('hidden').addClass('extra');	
    } else {
      $(this).html('Show more');
      $(this).parent().children('ul').children('li.extra').addClass('hidden').removeClass('extra');	
    }
    return false;
  });


  $('.playPlaylist').click(function(){
    var id = $(this).attr('rel');
    PlayerPopup(id);
    return false;
  });

  $('.deletePlaylist').click(function(){
    if(confirm($(this).attr('title'))){
      $.ajax({
              url: this.href.replace('/delete', ''),
              type: 'post',
              dataType: 'script',
              data: { '_method': 'delete' },
              success: function() {
                self.location = "/playlists";
              }
          });
    }
    return false;
  });


  $('.listing li span.notes a.togglemore').click(function(e){
    $(this).parents('span.notes').hide().siblings('.fullnotes').show();
    return false;
  });

  $('.listing li span.fullnotes a.toggleless').click(function(e){
    $(this).parents('span.fullnotes').hide().siblings('.notes').show();
    return false;
  });
  
  $('#copyCheckedTracks').click(function(){
    var items = new Array;
    $('#tracklist li .title input:checked').each(function(){
        items.push(this.value);
    });
    if(items.length < 1){
      alert('You must select some tracks to copy first');
      $(this).blur();   
      return false;
    }
    $("#items_to_copy").val(items);
    var formContents = $("#copy_items_form").serialize();
    $.ajax({
      type: 'POST',
      url: $('#copy_items_form').attr('action'), 
      data: formContents,
      success: function(data){
        showPlaylistModal(data);
        return false;
      }
    });
    return false;
  });	
  
  $('.playlist li').hover(function(){
    $(this).addClass('hovering');
  }, function(){
    $(this).removeClass('hovering');    
  });	
  
  $('p.notes').each(function(){
    if($(this).html().length < 1){
      var notes = $('#playlistheader p.notes');
      var text = $(notes).html();
      $(this).hide();
      var form = '<div id="editingNotes"><textarea id="notesContent">'+text+'</textarea><input type="button" value="Save notes" id="saveNotes"/><a href="#" id="cancelNotes">cancel</a></div>';
      $(notes).before(form).hide();      
      $('#editPlaylistNotes').hide();
    }
  });
  
  $('#editPlaylistNotes').click(function(){
    var notes = $('#playlistheader p.notes');
    var text = $(notes).html();
    $(this).hide();
    var form = '<div id="editingNotes"><textarea id="notesContent">'+text+'</textarea><input type="button" value="Save notes" id="saveNotes"/><a href="#" id="cancelNotes">cancel</a></div>';
    $(notes).before(form).hide();
    return false;
  });
  
  $('#cancelNotes').live('click', function(){
    $('#playlistheader p.notes').show();
    $('#editPlaylistNotes').show();
    $('#editingNotes').remove();
    return false;
  });

  $('#saveNotes').live('click', function(){
    var pl_id = $('#playlistheader p.notes').attr('rel');
    var newNote = $('#notesContent').val();
    $('#editingNotes').before('<div id="notesProgress"><img src="/images/spinner.gif"/> Saving...</div>').remove();
    $.ajax({
      type: 'PUT', 
      url: '/playlists/'+pl_id, 
      data: 'playlist[notes]='+newNote,
      success: function(data){
        $("#playlistheader p.notes").html(newNote).show().effect("highlight");
        $("#editPlaylistNotes").show();
        $('#notesProgress').remove();
      }
    });
    return false;
  });
  
  $('#renamePlaylist').click(function(){
    var pl_id = $('#playlistheader p.notes').attr('rel');
    var oldTitle = $.trim($('#playlistTitle span.title').html());
    var form = '<div id="renameForm"><input type="text" id="playlistRenameTitle" value="'+oldTitle+'" /><input type="button" value="Save title" id="saveRename"/><a href="#" id="cancelRename">cancel</a></div>';
    $('#playlistTitle .title').before(form).hide();
    return false;
  });
  
  $('#cancelRename').live('click', function(){
    $('#playlistTitle .title').show();
    $('#renameForm').remove();
    return false;
  });
  
  $('#saveRename').live('click', function(){
        var pl_id = $('#playlistheader p.notes').attr('rel');    
        var title = $('#playlistRenameTitle').val();
        if(title.length > 3){
          $.ajax({
            type: 'PUT',
            url: '/playlists/'+pl_id+'.js',
            data : 'playlist[title_en]='+title,
            success: function(data){
              $('#renameForm').remove();
              $('#playlistTitle .title').html(title).effect("highlight");
            }
          });
        } else {
          alert('The title has to be atleast 3 characters long');
        }
      return false;
    });
  
  $('#playlistPublicStatus').click(function(){
    var pl_id = $('#playlistheader p.notes').attr('rel');
    var isPublic = $(this).is(':checked') ? 1 : 0;
    $.ajax({
      type: 'PUT',
      url: '/playlists/'+pl_id+'.js',
      data : 'playlist[is_public]='+isPublic,
      success: function(data){
        $("#playlistheader .meta").effect("highlight");
      }
    });
  });
});

function setTrackNumber(){
  var number = 1;
  $('#tracklist li .number').each(function(){
    $(this).html(number);
    number++;
  });
}
