var audio;
var btn;
var select;
var playType = '';
var source = '';

function setup() {
	try {
		var audioTest = new Audio();

		//タイプの設定
		var playTypeArray = [
			{type: 'audio/mp3', ext: '.mp3'},
			{type: 'audio/ogg; codecs="vorbis"', ext: '.ogg'}
		];
		for(var p in playTypeArray) {
			var type = audioTest.canPlayType(playTypeArray[p].type);
			if(type == "probably" || type == "maybe") {
				playType = playTypeArray[p].ext;
				break;
			}
		}
		
		//selectの設定
		select = document.getElementById('select');
		select.addEventListener('change', changeHandler, false);
		
		//再生ボタンの設定
		audio = document.getElementById('audio');
		audio.addEventListener('play', playHandler, false);
		audio.addEventListener('pause', pauseHandler, false);
		audio.addEventListener('ended', endHandler, false);
		
		btn = document.getElementById('btn');
		btn.addEventListener('click', clickHandler, false);
	} catch(err) {
		alert('このWebブラウザではご利用になれません。');
	}
}

//select
function changeHandler(e) {
	var str = e.target.value;
	if(str != '') {
		source = e.target.value + playType;
	} else {
		source = '';
	}
}

//audioイベント
function playHandler(e) {
	setPauseImg();
}

function pauseHandler(e) {
	setPlayImg();
}

function endHandler(e) {
	setPlayImg();
	audio.pause();
}

//ボタン
function clickHandler(e) {
	if(audio.paused) {
		if(source != '') {
			audio.src = source;
			audio.play();
		} else {
			alert('曲を選んでください');
		}
	} else {
		audio.pause();
	}
}

function setPlayImg() {
	btn.src = "images/play.png";
}

function setPauseImg() {
	btn.src = "images/pause.png";
}