var siteInit = function () {
  $('#content img')
    .not('img.no')
    .wrap('<div class="featuredImg"></div>');

  $('div.featuredImg')
    .filter(function (index) {
        return $(this).width() < 400;
      })
    .addClass('featuredImgNarrow')

  if (window.soundManager) {
    soundManager.debugMode = false;
    soundManager.url = '/javascripts/soundmanager2.swf';
    soundManager.createMovie();
    $('a[href$=.mp3]')
      .addClass('audioClip')
      .bind('mouseover.audioClip',audioLoad)
      .bind('click.audioClip',audioPlay);
  }
  
  $('div.LTitem').each(tweakLibraryThingItem);
}

$(siteInit);


var getAudioId = function (el) {
  return 'audioClip_'+ el.href.substring(el.href.lastIndexOf('/') +1,el.href.lastIndexOf('.'));
}

var audioLoad = function (event) {
  soundManager.createSound({
    id: getAudioId(this),
    url: this.href,
    autoPlay: false
  });
}

var audioPlay = function (event) {
  if (soundManager.getSoundById(getAudioId(this))) {
    soundManager.play(getAudioId(this));
  } else {
    soundManager.createSound({
      id: getAudioId(this),
      url: this.href,
      autoPlay: false
    });
    soundManager.play(getAudioId(this));
  }
  
  if (null !== (multiClip = this.href.match(/\b\-(\d+)\.mp3/))){
    $(this).attr('count') || ($(this).attr('count', parseInt(multiClip[1])));
    nextClip = parseInt(multiClip[1]) -1;
    if (nextClip <= 0) {
      nextClip = parseInt($(this).attr('count'));
    }
    this.href = this.href.replace(multiClip[0], '-'+ nextClip +'.mp3');
  }

  event.preventDefault();
  event.stopPropagation();
  return false;
}




var tweakLibraryThingItem = function () {
  var Linkies = this.getElementsByTagName('a');
  if (Linkies.length == 2) {
    var Text = $(Linkies[1]).html();
    $(Linkies[1]).html('');
    $(Linkies[0]).append(Text);
    Linkies[0].href = Linkies[0].href.replace(/ref=.*?uqbar/, 'ref=uqbar');
  }
}