// Javascript for soundManager

fader = new Fader('artWork', 'fader');
st = new SoundThingFromId('audiolist');

// Fader Settings
// Ticks are the time intervals between fade adjustments
// Clicks are the amount of fade adjustment (.01 = 1% opacity)
fader.setTick(30);
fader.setClick(0.01);

soundManager.url = 'soundmanager/';
soundManager.onload = sminit;

// Here is the object that keeps track of sounds. It takes the ID of the
// audio list.
function SoundThingFromId(lid) {
    this.urls = new Array();    // array of urls for sounds.
    this.imgs = new Array();    // array of artwork images.
    this.anchors = new Array(); // array of the anchor elements.
    this.listels = new Array(); // array of list elements.

    this.playing = -1;          // -1 = nothing playing. player stopped.

    // Here's the construction
    ul = document.getElementById(lid);
    if (!ul) {
	alert(lid + " is not a valid element id.");
	die();
    }

    for (this.i=0;this.i<ul.childNodes.length;this.i++) {
	if (ul.childNodes[this.i].nodeName == "LI") {	
	    li = ul.childNodes[this.i];
	    // Find the first child which is an A
	    for (this.j=0;this.j<li.childNodes.length;this.j++) {
		a = li.childNodes[this.j];
		if (a.nodeName == "A") {
		    this.urls[a.getAttribute('nr')] = a.getAttribute('href');
		    this.imgs[a.getAttribute('nr')] = a.getAttribute('art');
		    this.anchors[a.getAttribute('nr')] = a;
		    this.listels[a.getAttribute('nr')] = li;
		}
	    }
	}
    }

    // Now we change the anchors to switch artwork on click.
    for (this.i=0;this.i<this.anchors.length;this.i++) {
	if (this.anchors[this.i]) {
	    this.anchors[this.i].onclick = function() { handle_click(this); return false; };
	    this.anchors[this.i].className = "sm2_link";
	}
    }

}

function play_sound(sidx)
{
    if (sidx == -1) {
	if (st.playing != -1)
	    st.anchors[st.playing].className = "sm2_link";
	soundManager.stop(st.playing);
	st.playing = -1;
	return;
    }

    if (sidx == st.playing) {
	soundManager.togglePause(st.playing);
	if (soundManager.getSoundById(st.playing).paused)
	    st.anchors[st.playing].className = "sm2_link sm2_paused";
	else
	    st.anchors[st.playing].className = "sm2_link sm2_playing";

	return;
    }

    soundManager.stop(st.playing);
    fader.setFade(st.imgs[sidx]);
    soundManager.play(sidx, { onfinish: function() { handle_finish(); }});

    st.anchors[sidx].className = "sm2_link sm2_playing";
    if (st.anchors[st.playing])
	st.anchors[st.playing].className = "sm2_link";

    st.playing = sidx;
}

function handle_click(t) {
    this.idx = t.getAttribute('nr');
    play_sound(this.idx);
}

function handle_finish()
{
    this.x = parseInt(st.playing)+1;
    if (st.anchors[x]) {
	play_sound(this.x);
    } else {
	play_sound(-1);
    }
}

function sminit()
{
    for (count=0;count<st.urls.length;count++) {
	if (st.urls[count]) {
	    soundManager.createSound(count, st.urls[count]);
	}
    }
}
