#pragma strict

  /*
	Sound Manager Scripty by Tom Vogt <tom@lemuria.org>
 
	attach to a gameobject that has two children (Source1 and Source2) which have audio source components
	the audio clips used as soundtracks should have "3D sound" DISABLED
	call "Interrupt()" to fade in event-driven music (see MusicTrigger.js for an example)
  */
 
var MaxVolume = 1.0;
var CrossfadeDuration = 1.0;

var Source1 : GameObject;
var Source2 : GameObject;
var Source3 : GameObject;

private var Interrupted = false;
 
function Start() {
	StopAllMusic();
	Source1.audio.Stop();

	Source1.audio.volume = MaxVolume;
	Source2.audio.volume = 0;
	Source3.audio.volume = 0;
 
	Source1.audio.Play();
	//yield WaitForSeconds(SoundTracks[0].length - FadeLength);
}

function StopAllMusic() {
	Source1.audio.Pause();
	Source2.audio.Stop();
	Source3.audio.Stop();
}

function StopAlertMusic() {
	Source2.audio.Stop();
	Source3.audio.Stop();
}

function Alert() {
	if(Interrupted) return;
	Interrupted = true;

	StopAlertMusic();

	Source2.audio.Play();

	FadeUpDown(Source2.audio, Source1.audio, CrossfadeDuration);
}

function AlertStopped() {
	Interrupted = false;

	Source1.audio.Pause();
	Source3.audio.Play();

	FadeUpDown(Source3.audio, Source2.audio, CrossfadeDuration);

	yield WaitForSeconds(Source3.audio.clip.length - CrossfadeDuration);

	Source2.audio.Stop();
	Source1.audio.Play();

	FadeUpDown(Source1.audio, Source3.audio, CrossfadeDuration);
}

function FadeUpDown(up:AudioSource, down:AudioSource, duration:float) {
	var MyVolume = 0.0;
	while (MyVolume<MaxVolume) {
		MyVolume += Time.deltaTime / duration;
		up.volume = MyVolume;
		down.volume = MaxVolume-MyVolume;
		yield WaitForFixedUpdate();
	}
	up.volume = MaxVolume;
	down.volume = 0.0;

	down.Pause();
}