jQuery.fn.extend({
  scrollTo : function(speed, easing) {
    return this.each(function() {
      var targetOffset = $(this).offset().top;
      $('html,body').animate({scrollTop: targetOffset}, speed, easing);
    });
  }
});

jQuery.fn.highlight=function(b){function a(e,j){var l=0;if(e.nodeType==3){var k=e.data.toUpperCase().indexOf(j);if(k>=0){var h=document.createElement("span");h.className="highlight";var f=e.splitText(k);var c=f.splitText(j.length);var d=f.cloneNode(true);h.appendChild(d);f.parentNode.replaceChild(h,f);l=1}}else{if(e.nodeType==1&&e.childNodes&&!/(script|style)/i.test(e.tagName)){for(var g=0;g<e.childNodes.length;++g){g+=a(e.childNodes[g],j)}}}return l}return this.each(function(){a(this,b.toUpperCase())})};jQuery.fn.removeHighlight=function(){return this.find("span.highlight").each(function(){this.parentNode.firstChild.nodeName;with(this.parentNode){replaceChild(this.firstChild,this);normalize()}}).end()};

function LiveFilter(container){
  this.container = $(container);
  this.complete_list = this.container.children('div');
  this.current_list = this.complete_list;
  this.items = this.container.find('li');
  this.cloned_items = this.items.clone(true);
  this.input = $('<input type="text">');
  this.container.find('h2').after(this.input);
  this.filters = {};
  var _this = this;
  this.input.keyup(function(ev){
    var filter = _this.input.val().toLowerCase();
    if(filter == '' || ev.keyCode == 27){
      _this.input.val('');
      if(_this.current_list != _this.complete_list){
        _this.current_list.replaceWith(_this.complete_list);
        _this.current_list = _this.complete_list;
      }
    } else {
      if(typeof _this.filters[filter] == 'undefined'){
        var complete_set = _this.cloned_items.clone(true);
        var list = complete_set.filter(function(){
          return $(this).text().toLowerCase().indexOf(filter) > -1;
        })
        _this.filters[filter] = list;
      }else{
        var list = _this.filters[filter];
      }
      list.removeHighlight().highlight(filter);
      var ol = $('<ol class="filtered"></ol>');
      ol.append(list);
      _this.current_list.replaceWith(ol);
      _this.current_list = ol;
    }
  })
}

$(function(){
  $('.triple div.collection').each(function(){
    new LiveFilter(this);
  })
  
  
  $('div.artists ol').hide();
  $('div#info p:first').after('<p><a href="#" id="expand-all">Expand all</a><a href="#" style="display:none" id="collapse-all">Collapse all</a></p>');
  $('div.artists h2').each(function(){
    $(this).wrapInner('<a href="#'+$(this).text()+'" id="'+$(this).text()+'"></a>');
    $(this).find('a').prepend('<em>+ </em>');
  });
  var last_open = $.cookie('last_open');
  if(last_open !== null){
    if (last_open == 'all'){
      $('div.artists ol').show();
      $('div.artists h2 a em').text('- ');
      $('a#expand-all').hide();
      $('a#collapse-all').show();
    } else {
      $('h2:contains('+last_open+')').next().show().end().find('em').text('- ');
    }
  }
  $('div.artists h2 a').click(function(ev){
    ev.preventDefault();
    var $this = $(this);
    var $list = $this.parent().next('ol');
    if($list.is(':visible')){
      $('div.artists ol').each(function(){
        var $that = $(this);
        $.cookie('last_open',null);
        $('a#expand-all').show();
        $('a#collapse-all').hide();
        if($that.is(':visible')){
          $that.slideUp(500,function(){
            $(this).prev().find('em').text('+ ');
          })
        }
      });
    } else {
      $('div.artists ol').slideUp();
      $list.slideDown(500,function(){
        $this.scrollTo(500);
        $('div.artists h2 em').text('+ ');
        $this.find('em').text('- ');
        $.cookie('last_open',$this.text().split(' ')[1], { expires: 365 });
      });
    }
  })
  var seenIt = $.cookie('seen_it');
  if(seenIt === null){
    $('div.artists').prepend('<div id="instructions"><p>Click the heading to expand</p></div>');
    $.cookie('seen_it','true', { expires:365 })
    setTimeout(function(){
      $('div#instructions').fadeOut('slow',function(){
        $(this).remove();
      })
    },10000);
  }
  $('form').submit(function(ev){
    var $this = $(this);
    if($this.find('input[type=file]').val() == ''){
      ev.preventDefault();
      var errors = $('.errors');
      if(errors.length > 0){
        if(errors.text().indexOf('Please enter an XML file')==-1){
          errors.append('<li style="display:none;">Please enter an XML file</li>');
          $('.errors li').fadeIn();
        }
      }else{
        $this.before('<ul class="errors" style="display:none;"><li>Please enter an XML file</li></ul>');
        $('.errors').fadeIn();
      }
    }
  });
  $('a#expand-all').click(function(ev){
    ev.preventDefault();
    $(this).hide();
    $('a#collapse-all').show();
    $('div.artists ol').slideDown(500,function(){
      $('div.artists h2 a em').text('- ');
      $.cookie('last_open','all', { expires: 365 });
    })
  });
  $('a#collapse-all').click(function(ev){
    ev.preventDefault();
    $('div.artists ol').each(function(){
      var $that = $(this);
      $.cookie('last_open',null);
      $('a#expand-all').show();
      $('a#collapse-all').hide();
      if($that.is(':visible')){
        $that.slideUp(500,function(){
          $(this).prev().find('em').text('+ ');
        })
      }
    });
  });
  
  var update_permalink = function(){
    var text = $('#library_link').val()
    if(text != ''){ $('p#permalink').addClass('active').find('span').text(text); }
    else { $('p#permalink').removeClass('active').find('span').text('example'); }
  }
  $('#library_link').keyup(function(){ update_permalink(); }).blur(function(){ update_permalink() });
  if($('#library_link').text()!='example'){ update_permalink(); }
  
  var deleteLink = $('<a href="#">Delete your library</a>');
  var deleteForm = $('#delete-library');
  deleteForm.hide().prepend('<p>Are you sure you want to delete your library?</p>').before(deleteLink).find('input[type="submit"]').val('Yes, delete my library');
  deleteLink.click(function(ev){
    if(deleteForm.is(':visible')){ deleteForm.slideUp(500); }
    else{ deleteForm.slideDown(500); }
    ev.preventDefault();
  });
  
  var deleteAccoutLink = $('<a href="#">Delete your account</a>');
  var deleteAccoutForm = $('#delete-user');
  if(deleteAccoutForm.parent().find('ul.errors').length == 0){
    deleteAccoutForm.hide();
  }
  deleteAccoutForm.prepend('<p>Are you sure you want to delete your account?</p>').before(deleteAccoutLink).find('input[type="submit"]').val('Yes, delete my account');
  deleteAccoutLink.click(function(ev){
    if(deleteAccoutForm.is(':visible')){ deleteAccoutForm.slideUp(500); }
    else{ deleteAccoutForm.slideDown(500); }
    ev.preventDefault();
  });
  
  var uploadForm = $('div.account form#upload-library, ul.errors');
  var uploadLink = $('<a href="#">Upload your library</a>');
  if(uploadForm.parent().find('ul.errors').length == 0){
    uploadForm.hide();
  }
  uploadForm.parent().find('h3').replaceWith(uploadLink);
  uploadLink.click(function(ev){
    if(uploadForm.is(':visible')){ uploadForm.slideUp(500); }
    else{ uploadForm.slideDown(500); }
    ev.preventDefault();
  });
  
  var claimForm = $('div.account form#claim-library, ul.errors');
  var claimLink = $('<a href="#">Claim your library</a>');
  if(claimForm.parent().find('ul.errors').length == 0){
    claimForm.hide();
  }
  claimForm.parent().find('h3').replaceWith(claimLink);
  claimLink.click(function(ev){
    if(claimForm.is(':visible')){ claimForm.slideUp(500); }
    else{ claimForm.slideDown(500); }
    ev.preventDefault();
  });
  
  var secretForm = $('div.account form#update-library, ul.errors');
  var secretLink = $('<a href="#">Edit your library</a>');
  if(secretForm.parent().find('ul.errors').length == 0){
    secretForm.hide();
  }
  secretForm.parent().find('h3').replaceWith(secretLink);
  secretLink.click(function(ev){
    if(secretForm.is(':visible')){ secretForm.slideUp(500); }
    else{ secretForm.slideDown(500); }
    ev.preventDefault();
  });
  
})
