$(document).ready(function(){

  var playItem = 0,
      track;
  
  function generatePlaylist(){
    var playList = new Array();
    $('a.audio').each(function(i){
      var track = new Object();
      track.name = $(this).text();
      track.mp3 = $(this).attr('href');
      playList.push(track);
  
      /*
      var html = ' \
    	<div id="jquery_jplayer'+i+'" class="jquery_jplayer"></div> \
    	<div class="jp-single-player"> \
    		<div class="jp-interface"> \
    			<ul class="jp-controls"> \
    				<li><a href="#" id="jplayer_play'+i+'" class="jp-play" tabindex="1">play</a></li> \
    				<li><a href="#" id="jplayer_pause'+i+'" class="jp-pause" tabindex="1">pause</a></li> \
    				<li><a href="#" id="jplayer_stop'+i+'" class="jp-stop" tabindex="1">stop</a></li> \
    				<li><a href="#" id="jplayer_volume_min'+i+'" class="jp-volume-min" tabindex="1">min volume</a></li> \
    				<li><a href="#" id="jplayer_volume_max'+i+'" class="jp-volume-max" tabindex="1">max volume</a></li> \
    			</ul> \
    			<div class="jp-progress"> \
    				<div id="jplayer_load_bar'+i+'" class="jp-load-bar"> \
    					<div id="jplayer_play_bar'+i+'" class="jp-play-bar"></div> \
    				</div> \
    			</div> \
    			<div id="jplayer_volume_bar'+i+'" class="jp-volume-bar"> \
    				<div id="jplayer_volume_bar_value'+i+'" class="jp-volume-bar-value"></div> \
    			</div> \
    			<div id="jplayer_play_time'+i+'" class="jp-play-time"></div> \
    			<div id="jplayer_total_time'+i+'" class="jp-total-time"></div> \
    		</div> \
    		<div id="jplayer_playlist'+i+'" class="jp-playlist"> \
    			<ul> \
    				<li>'+title+'</li> \
    			</ul> \
    		</div> \
    	</div> \
      ';
    
      var orig = $(this).parent().html();
      $(this).parent().html(html);
      */
      $(this).parent().remove();
    });
    return playList;
  }
  //swfPath: "http://flyingbathtub.co.uk/images/3.swf",
  
  function getFlashVersion(){ 
    // ie 
    try { 
      try { 
        // avoid fp6 minor version lookup issues 
        // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/ 
        var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); 
        try { axo.AllowScriptAccess = 'always'; } 
        catch(e) { return '6,0,0'; } 
      } catch(e) {} 
      return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; 
    // other browsers 
    } catch(e) { 
      try { 
        if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){ 
          return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]; 
        } 
      } catch(e) {} 
    } 
    return '0,0,0'; 
  }
  
  var version = getFlashVersion().split(',').shift();
  
  if ($('a.audio').length && version > 8) {

  
  var $list = $('a.audio:first-child').parents('ul');
  playList = generatePlaylist();
  var html = ' \
  <li> \
	<div id="jquery_jplayer" class="jquery_jplayer"></div> \
	<div class="jp-single-player"> \
		<div class="jp-interface"> \
			<ul class="jp-controls"> \
				<li><a href="#" id="jplayer_play" class="jp-play" tabindex="1">play</a></li> \
				<li><a href="#" id="jplayer_pause" class="jp-pause" tabindex="1">pause</a></li> \
				<li><a href="#" id="jplayer_stop" class="jp-stop" tabindex="1">stop</a></li> \
				<li><a href="#" id="jplayer_volume_min" class="jp-volume-min" tabindex="1">min volume</a></li> \
				<li><a href="#" id="jplayer_volume_max" class="jp-volume-max" tabindex="1">max volume</a></li> \
			</ul> \
			<div class="jp-progress"> \
			  <div id="jplayer_progress_mask"></div> \
				<div id="jplayer_load_bar" class="jp-load-bar"> \
					<div id="jplayer_play_bar" class="jp-play-bar"></div> \
				</div> \
			</div> \
			<div id="jplayer_volume_bar" class="jp-volume-bar"> \
			  <div id="jplayer_volume_mask"></div> \
				<div id="jplayer_volume_bar_value" class="jp-volume-bar-value"></div> \
			</div> \
			<div id="jplayer_play_time" class="jp-play-time"></div> \
			<div id="jplayer_total_time" class="jp-total-time"></div> \
		</div> \
		<div id="jplayer_playlist" class="jp-playlist"> \
			<ul> \
				<li></li> \
			</ul> \
		</div> \
	</div> \
  </li>';

  $list.prepend(html);
  
  }
  
	// Local copy of jQuery selectors, for performance.
	var jpPlayTime = $("#jplayer_play_time");
	var jpTotalTime = $("#jplayer_total_time");

	$("#jquery_jplayer").jPlayer({
		ready: function() {
			displayPlayList();
			playListInit(false); // Parameter is a boolean for autoplay.
		},
		nativeSupport: true,
		oggSupport: false,
		swfPath: "http://flyingbathtub.co.uk/images/"
	})
	.jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
		jpPlayTime.text($.jPlayer.convertTime(playedTime));
		jpTotalTime.text($.jPlayer.convertTime(totalTime));

	})
	.jPlayer("onSoundComplete", function() {
		playListNext();
	});

	$("#jplayer_previous").click( function() {
		playListPrev();
		$(this).blur();
		return false;
	});

	$("#jplayer_next").click( function() {
		playListNext();
		$(this).blur();
		return false;
	});

	function displayPlayList() {
		$("#jplayer_playlist ul").empty();
		for (i=0; i < playList.length; i++) {
			var listItem = (i == playList.length-1) ? "<li class='jplayer_playlist_item_last'>" : "<li>";
			listItem += "<a href='#' id='jplayer_playlist_item_"+i+"' tabindex='1'>"+ playList[i].name +"</a></li>";
			$("#jplayer_playlist ul").append(listItem);
			$("#jplayer_playlist_item_"+i).data( "index", i ).click( function() {
				var index = $(this).data("index");
				if (playItem != index) {
					playListChange( index );
				} else {
          if ($('#jplayer_play:visible').length == 0) {
            $("#jquery_jplayer").jPlayer("pause");
          } else {
            $("#jquery_jplayer").jPlayer("play");
          }
				}
				$(this).blur();
				return false;
			});
		}
	}

	function playListInit(autoplay) {
		if(autoplay) {
			playListChange( playItem );
		} else {
			playListConfig( playItem );
		}
	}

	function playListConfig( index ) {
		$("#jplayer_playlist_item_"+playItem).removeClass("jplayer_playlist_current").parent().removeClass("jplayer_playlist_current");
		$("#jplayer_playlist_item_"+index).addClass("jplayer_playlist_current").parent().addClass("jplayer_playlist_current");
		playItem = index;
		$("#jquery_jplayer").jPlayer("setFile", playList[playItem].mp3, playList[playItem].ogg);
	}

	function playListChange( index ) {
		playListConfig( index );
		$("#jquery_jplayer").jPlayer("play");
	}

	function playListNext() {
		var index = (playItem+1 < playList.length) ? playItem+1 : 0;
		playListChange( index );
	}

	function playListPrev() {
		var index = (playItem-1 >= 0) ? playItem-1 : playList.length-1;
		playListChange( index );
	}


  $('.jplayer_playlist_current a').live('click', function(){
    alert('hi');
    if ($('#jplayer_play:visible').length == 0) {
      $("#jquery_jplayer").jPlayer("pause");
    } else {
      $("#jquery_jplayer").jPlayer("play");
    }
    return false;
  });

/*  
  $('.jquery_jplayer').each(function(i){
    var url = $(this).parents('li').find('a.audio').attr('href');
    
    $(this).jPlayer({
      ready: function(){
        this.element.jPlayer("setFile", url);
      },
      customCssIds: true,
      swfPath: "http://flyingbathtub.co.uk/images/",
      nativeSupport: true,
      oggSupport: false
    })
    .jPlayer("cssId", "play", "jplayer_play"+i)
    .jPlayer("cssId", "pause", "jplayer_pause"+i)
    .jPlayer("cssId", "stop", "jplayer_stop"+i)
    .jPlayer("cssId", "loadBar", "jplayer_load_bar"+i)
    .jPlayer("cssId", "playBar", "jplayer_play_bar"+i)
    .jPlayer("cssId", "volumeMin", "jplayer_volume_min"+i)
    .jPlayer("cssId", "volumeMax", "jplayer_volume_max"+i)
    .jPlayer("cssId", "volumeBar", "jplayer_volume_bar"+i);
    
    $(this).data("instance", i);
    
  });
  
  

  $('.jp-play,.jp-load-bar,.jp-play-bar').click(function(){ 
    var instance = $(this).parents('li').find('.jquery_jplayer').data("instance");
    $('.jquery_jplayer').each(function(i){
      if (i != instance) { $(this).jPlayer("pause") };
    });
  });

  
/*
	$("#jquery_jplayer").jPlayer({
		ready: function () {
			this.element.jPlayer("setFile", "http://www.miaowmusic.com/mp3/Miaow-08-Stirring-of-a-fool.mp3", "http://www.miaowmusic.com/ogg/Miaow-08-Stirring-of-a-fool.ogg").jPlayer("play");
			demoInstanceInfo(this.element, $("#demo_info")); // This displays information about jPlayer's configuration in the demo page
		},
		oggSupport: true
	})
	.jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
		jpPlayTime.text($.jPlayer.convertTime(playedTime));
		jpTotalTime.text($.jPlayer.convertTime(totalTime));

		demoStatusInfo(this.element, jpStatus); // This displays information about jPlayer's status in the demo page
	})
	.jPlayer("onSoundComplete", function() {
		$("#jquery_jplayer2").jPlayer("playHead", 0); // Crossover the players here
	});

	$("#jquery_jplayer2").jPlayer({
		ready: function () {
			this.element.jPlayer("setFile", "http://www.miaowmusic.com/mp3/Miaow-02-Hidden.mp3");
			demoInstanceInfo(this.element, $("#demo_info2")); // This displays information about jPlayer's configuration in the demo page
		},
		nativeSupport: false,
		customCssIds: true
	})
	.jPlayer("cssId", "play", "jplayer_play2")
	.jPlayer("cssId", "pause", "jplayer_pause2")
	.jPlayer("cssId", "stop", "jplayer_stop2")
	.jPlayer("cssId", "loadBar", "jplayer_load_bar2")
	.jPlayer("cssId", "playBar", "jplayer_play_bar2")
	.jPlayer("cssId", "volumeMin", "jplayer_volume_min2")
	.jPlayer("cssId", "volumeMax", "jplayer_volume_max2")
	.jPlayer("cssId", "volumeBar", "jplayer_volume_bar2")
	.jPlayer("cssId", "volumeBarValue", "jplayer_volume_bar_value2")
	.jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
		jpPlayTime2.text($.jPlayer.convertTime(playedTime));
		jpTotalTime2.text($.jPlayer.convertTime(totalTime));

		demoStatusInfo(this.element, jpStatus2); // This displays information about jPlayer's status in the demo page
	})
	.jPlayer("onSoundComplete", function() {
		$("#jquery_jplayer").jPlayer("playHead", 0); // Crossover the players here
	});

	// Add extra .click() event handlers to avoid both jPlayers playing together.

/*
	$("#jplayer_play").click( pausePlayer2 );
	$("#jplayer_load_bar").click( pausePlayer2 );
	$("#jplayer_play_bar").click( pausePlayer2 );

	$("#jplayer_play2").click( pausePlayer1 );
	$("#jplayer_load_bar2").click( pausePlayer1 );
	$("#jplayer_play_bar2").click( pausePlayer1 );

	function pausePlayer1(e) {
		$("#jquery_jplayer").jPlayer("pause");
	}
	function pausePlayer2(e) {
		$("#jquery_jplayer2").jPlayer("pause");
	}
*/
  
  
  
  
});
