// Triggerable Client Scripted
// Flash Sound Effects System
// (C) 2007 by Christer Kaitila

// if ((window.game) && (game.logger)) game.logger('Loading sound engine...');

function detectIEplugin(ClassID) { result = false; document.write('<SCR'+'IPT LANGUAGE=VBScript>\n on error resume next \n result = IsObject(CreateObject("' + ClassID + '"))</SCR'+'IPT>\n'); return result; }
function detectNSplugin(ClassID) { return (navigator.mimeTypes[ClassID].enabledPlugin != null); }
function flash_is_installed()
{
	var agt = navigator.userAgent.toLowerCase();
	var ie  = (agt.indexOf("msie") != -1);
	var ns  = (navigator.appName.indexOf("Netscape") != -1);
	var win = ((agt.indexOf("win")!=-1) || (agt.indexOf("32bit")!=-1));
	var mac = (agt.indexOf("mac")!=-1);
	if (ie && win)  { return detectIEplugin("ShockwaveFlash.ShockwaveFlash.1"); }
	if (ns || !win) { return detectNSplugin("application/x-shockwave-flash"); }
}

//IE6 fix: cached flash doesn't load... add random? breaks.
var theflashfile = 'sound-config.swf';//?random='+Math.random();
var isIE = navigator.appName.toLowerCase().indexOf('internet explorer')+1;
var isMac = navigator.appVersion.toLowerCase().indexOf('mac')+1;

function SoundManager(container) {
  // DHTML-controlled sound via Flash
  var self = this;
  this.movies = []; // movie references
  this.container = container;
  this.unsupported = 0; // assumed to be supported
  this.defaultName = 'default'; // default movie

  this.FlashObject = function(url)
  {
    var me = this;
    this.o = null;
    this.loaded = false;
    this.isLoaded = function()
    {
      if (me.loaded) return true;
      if (!me.o) return false;
      me.loaded = ((typeof(me.o.readyState)!='undefined' && me.o.readyState == 4) || (typeof(me.o.PercentLoaded)!='undefined' && me.o.PercentLoaded() == 100));
      return me.loaded;
    };

    //$CK
	//if (game.logger) game.logger('Creating sound container element...');
	//document.write("<div name='soundcontainer' class='soundcontainer' id='soundcontainer' style='position:absolute; top:-999px; left:-999px; width:1px; height:1px; border:0; padding:0; margin:0;'></div>");

    this.mC = document.getElementById('soundcontainer');
    if (this.mC)
    {
	    var html = ['<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"><param name="movie" value="'+url+'"><param name="quality" value="high"></object>','<embed src="'+url+'" width="1" height="1" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>'];
	    if (navigator.appName.toLowerCase().indexOf('microsoft')+1) {
	      this.mC.innerHTML = html[0];
	      this.o = this.mC.getElementsByTagName('object')[0];
	    } else {
	      this.mC.innerHTML = html[1];
	      this.o = this.mC.getElementsByTagName('embed')[0];
	    }
    }
else
	{
		//alert('ERROR: sound could not find the soundcontainer');
		if (game.logger) game.logger('ERROR: sound engine was unable to find sound container element.');
	}

    /*
    // $CK removed for less DOM
    this.mC = document.createElement('div');
    this.mC.className = 'movieContainer';
    with (this.mC.style) {
      // "hide" flash movie
      position = 'absolute';
      left = '-256px';
      width = '64px';
      height = '64px';
    }
    var html = ['<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"><param name="movie" value="'+url+'"><param name="quality" value="high"></object>','<embed src="'+url+'" width="1" height="1" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed>'];
    if (navigator.appName.toLowerCase().indexOf('microsoft')+1) {
      this.mC.innerHTML = html[0];
      this.o = this.mC.getElementsByTagName('object')[0];
    } else {
      this.mC.innerHTML = html[1];
      this.o = this.mC.getElementsByTagName('embed')[0];
    }
    document.getElementsByTagName('div')[0].appendChild(this.mC);
    */

  };

  this.addMovie = function(movieName,url) {
    self.movies[movieName] = new self.FlashObject(url);
  };

  this.checkMovie = function(movieName) {
    movieName = movieName||self.defaultName;
    if (!self.movies[movieName])
    {
      self.errorHandler('checkMovie','Exception: Could not find movie',arguments);
      return false;
    } else
    {
      return (self.movies[movieName].isLoaded())?self.movies[movieName]:false;
    }
  };

  this.errorHandler = function(methodName,message,oArguments,e)
  {
    writeDebug('<div class="error">soundManager.'+methodName+'('+self.getArgs(oArguments)+'): '+message+(e?' ('+e.name+' - '+(e.message||e.description||'no description'):'')+'.'+(e?')':'')+'</div>');
  };

  this.play = function(soundID,loopCount,noDebug,movieName)
  {
    if (self.unsupported) return false;
    movie = self.checkMovie(movieName);
    if (!movie) return false;
    if (typeof(movie.o.TCallLabel)!='undefined')
    {
      try
      {
        self.setVariable(soundID,'loopCount',loopCount||1,movie);
        movie.o.TCallLabel('/'+soundID,'start');
        if (!noDebug) writeDebug('soundManager.play('+self.getArgs(arguments)+')');
        // $CK return success
        return true;
      } catch(e) {
        self.errorHandler('play','Failed: Flash unsupported / undefined sound ID (check XML)',arguments,e);
      }
    }
    return false; // default
  };

  this.stop = function(soundID,movieName)
  {
    if (self.unsupported) return false;
    movie = self.checkMovie(movieName);
    if (!movie) return false;
    try
    {
      movie.o.TCallLabel('/'+soundID,'stop');
      writeDebug('soundManager.stop('+self.getArgs(arguments)+')');
    } catch(e)
    {
      // Something blew up. Not supported?
      self.errorHandler('stop','Failed: Flash unsupported / undefined sound ID (check XML)',arguments,e);
      return false;
    }
    return true; // default
  };

  this.getArgs = function(params)
  {
    var x = params?params.length:0;
    if (!x) return '';
    var result = '';
    for (var i=0; i<x; i++)
    {
      result += (i&&i<x?', ':'')+(params[i].toString().toLowerCase().indexOf('object')+1?typeof(params[i]):params[i]);
    }
    return result;
  };

  this.setVariable = function(soundID,property,value,oMovie)
  {
    // set Flash variables within a specific movie clip
    if (!oMovie) return false;
    try
    {
      	// $CK Firefox RARELY (but occasionally) fires this error: =(
      	// "Error: Error calling method on NPObject!"
      if (oMovie.o.SetVariable) // $CK sanity
      	oMovie.o.SetVariable('/'+soundID+':'+property,value);
      // writeDebug('soundManager.setVariable('+self.getArgs(arguments)+')');
    } catch(e)
    {
      // d'oh
      self.errorHandler('setVariable','Failed',arguments,e);
      return false;
    }
    return true; // default
  };

  this.setVariableExec = function(soundID,fromMethodName,oMovie)
  {
    try
    {
      oMovie.o.TCallLabel('/'+soundID,'setVariable');
    } catch(e)
    {
      self.errorHandler(fromMethodName||'undefined','Failed',arguments,e);
    }
  };

  this.callMethodExec = function(soundID,fromMethodName,oMovie)
  {
    try
    {
      oMovie.o.TCallLabel('/'+soundID,'callMethod');
    } catch(e)
    {
      // Something blew up. Not supported?
      self.errorHandler(fromMethodName||'undefined','Failed',arguments,e);
    }
  };

  this.callMethod = function(soundID,methodName,methodParam,movieName)
  {
    movie = self.checkMovie(movieName||self.defaultName);
    if (!movie) return false;
    self.setVariable(soundID,'jsProperty',methodName,movie);
    self.setVariable(soundID,'jsPropertyValue',methodParam,movie);
    self.callMethodExec(soundID,methodName,movie);
    return true;
  };

  this.setPan = function(soundID,pan,movieName)
  {
    self.callMethod(soundID,'setPan',pan,movieName);
  };

  this.setVolume = function(soundID,volume,movieName)
  {
    self.callMethod(soundID,'setVolume',volume,movieName);
  };

  // constructor - create flash objects

  if (isIE && isMac)
  {
    this.unsupported = 1;
  }

  if (!this.unsupported)
  {
    this.addMovie(this.defaultName,theflashfile);
  }
  //else alert('You need the flash plugin for sound...'); // hmm

}

function SoundManagerNull()
{
  // Null object for unsupported case
  this.movies = []; // movie references
  this.container = null;
  this.unsupported = 1;
  this.FlashObject = function(url) {};
  this.addMovie = function(name,url) {};
  this.play = function(movieName,soundID) { return false; };
  this.defaultName = 'default';
}

function writeDebug(msg)
{
  var o = document.getElementById('debugContainer');
  if (!o) return false;
  var d = document.createElement('div');
  d.innerHTML = msg;
  o.appendChild(d);
  return true; // default
}

window.soundManager = null;

function init_sound_effects()
{
	if (flash_is_installed())
	{
		if (game.logger) game.logger('You have scriptable flash.  Creating soundManager...');
		window.soundManager = new SoundManager();
	}
	else
	{
		if (game.logger) game.logger('ERROR: You do not have scriptable flash.  No sound effects.');
	}
}

init_sound_effects(); // now due to document write
//alert('Loaded soundmanager!'); // hmm

