$(function(){
	
	var currentPage = window.location.pathname;
	var urlSections = new Array();
	urlSections = currentPage.split('/');
	
	function setUpCassette(){
		$('.spool').hide();
		$('.first').hover(
			function(){
				$(this).find('.spool').show();
			},
			function(){
				$(this).find('.spool').hide();
			}
		);
	}

	var players = new Array();
	var i = 0;

	function removePlayers(){
		i = 0;
		$('.playerette').each(function(){
			players[i] = $(this).html();
			$(this).html('');
			i++;
		});
	}

	function addPlayers(){
		$('.first .playerette').html('').remove();
		
		$('.playerette').show();

		i = setStartIndex()
		$('.playerette').each(function(){
			$(this).html(players[i]);
			i++
		});
	}

	function updatePlayers(){
		i = setStartIndex();
		for(i in players){
			var contents = players[i];
			contents = contents.replace(/\"best\"/g, '"best" wmode="transparent"');
			contents = contents.replace(/E4E4E4/g, '1AACB9');
			players[i] = contents;
		}
	}

	function updateFeaturedPlayer(){
		$('.first .playerette').html('').remove();
		
		var playCount = $('.first .meta .plays').html();
		$('.first .meta .plays').remove();
		playCount = playCount.substr(0,playCount.indexOf(' '));
		
		var cassetteWrap = '<div class="cassette"><div class="player">[player]</div><div class="mask"></div><div class="spool"></div><div class="plays">[plays]</div></div>';
		
		var contents = players[0];
		contents = contents.replace(/\"best\"/g, '"best" wmode="transparent"');
		contents = contents.replace(/E4E4E4/g, 'FFFFFF');
		
		cassetteWrap = cassetteWrap.replace('[player]',contents);
		cassetteWrap = cassetteWrap.replace('[plays]',playCount);
		
		$('.first').prepend(cassetteWrap);
		
		if(!urlSections[1] || (urlSections[1] == 'page' && urlSections[2] == '1')){
			$('.first').append('<div class="latest"></div>')
		}
		setUpCassette();
	}
	
	function setStartIndex(){
		if(urlSections[1] == 'page' && urlSections[2] != '1'){
			return 0;
		} else {
			return 1;
		}
	}

	window.onload = function(){
		removePlayers();
		if(urlSections[1] != 'page' || (urlSections[1] == 'page' && urlSections[2] == '1')){
			$('.audio:first').addClass('first');
			$('.audio:first .notes-button').appendTo('.audio:first .meta');
			if( $('.audio').length < 2 ){
				$('#pagination').addClass('single');
			}
			if( $('.audio:first').height() > 40 ){
				$('.audio:first .tags').addClass('long');
			}
			updateFeaturedPlayer();
		}
		updatePlayers();
		addPlayers();
		handleNotes();
	}
	
});