$(document).ready(function() {

  $('.hidden').hide();
  $('.media').media(
    {
    	width:     470,
    	height:    20,
    	attrs :    { 'id': 'player' + $(this).attr('id') },
    	params:    { 'id': 'player' + $(this).attr('id') },
        flashvars: { 'type': 'mp3' }
    }
  );

  // Initialize history plugin.
  // The callback is called at once by present location.hash.
  $.historyInit(pageload);

  // set onlick event for buttons
  $("a[@rel='history']").click(function() {
    var hash = this.href;
    hash = hash.replace(/^.*#/, '');
    // moves to a new page.
    // pageload is called at once.
    $.historyLoad(hash);
    toggleBrowseTracksCross();
    return false;
  });

  // Enable full index link
  $('a.index-toggle').click(function() {
    $('#index').slideToggle('normal', toggleBrowseTracksCross);
    return false;
  });

  $('#index a').click(function() {
    $('#index').toggle();
  });

  // TODO : Switch to next track automatically
//  $('player').addModelListener('state', 'playerStateHandler');

});

function toggleBrowseTracksCross()
{
  if ($('a.index-toggle span.arrow').is(':visible'))
  {
    $('a.index-toggle span.arrow').hide();
  }
  else
  {
    $('a.index-toggle span.arrow').show();
  }
}

function pageload(hash) {
  // hash doesn't contain the first # character.
  if (hash && hash != 'index') {
		$('div#posts div').hide();
		var e_id = hash;
		var e = document.getElementById(e_id);
		$(e).show();
		$('div.media').show();
		$('div.media div').show();
		document.title = 'Musique Approximative : ' + $(e).attr('x-ma-title');
  }
}

function playerStateHandler(state, newstate, oldstate)
{
  console.log(state);
  console.log(newstate);
  console.log(oldstate);
}
