// Copyright 2000, 2001, 2002, 2003 Macromedia, Inc. All rights reserved.

//******************* GLOBALS **********************

var helpDoc = MM.HELP_behPlaySound;

var MM_sndFiles = new Array();
var MM_sndNames = new Array();

//******************* BEHAVIOR FUNCTION **********************

//Plays a soundfile, or stops one from playing.
//Accepts the following arguments:
//  sndAction - currently, 'stop' or 'play'
//  sndObj    - Javascript object reference for sound EMBED (ex: document.mySound)
//
//Tests if the object exists, then initiates the action on the object.
//The play() method is called for Netscape; for IE, either play() or run() is called depending
//on the plugin: the new Windows Media Player uses the new Netshow 2 API and
//consequently requires play().  The old plugin uses the DirectShow API and
//requires the run() method after ensuring that the FileName property is
//assigned. If all else fails, plays sound as link (may popup a play window).

function MM_controlSound(x, _sndObj, sndFile) { //v3.0
  var i, method = "", sndObj = eval(_sndObj);
  if (sndObj != null) {
    if (navigator.appName == 'Netscape') method = "play";
    else {
      if (window.MM_WMP == null) {
        window.MM_WMP = false;
        for(i in sndObj) if (i == "ActiveMovie") {
          window.MM_WMP = true; break;
      } }
      if (window.MM_WMP) method = "play";
      else if (sndObj.FileName) method = "run";
  } }
  if (method) eval(_sndObj+"."+method+"()");
  else window.location = sndFile;
}

MM.VERSION_MM_controlSound = 3.0; //define latest version number for behavior inspector

//******************* API **********************


//Can be used with any tag and any event

function canAcceptBehavior(){
  return true;
}



//Returns a Javascript function to be inserted in HTML head with script tags.

function behaviorFunction(){
  return "MM_controlSound";
}



//Returns fn call to insert in HTML tag <TAG... onEvent='thisFn(arg)'>

function applyBehavior() {
  var i, sndFile="", sndName="";

  sndFile = document.theForm.sndFileObj.value; // get filename from text input

 //If snd EMBED already exists, we want to return the old sndName
  for (i=0; i<MM_sndFiles.length; i++) { //scan existing embeds
    if (MM_sndFiles[i] == sndFile) { //if already existing
      sndName = MM_sndNames[i]; break;//get prior uniquename
  } }

  if (!sndName) { //sound didn't exist, create it
    sndName = "CS"+((new Date()).getTime()); //create unique name
    createSoundObject(sndName,sndFile);
  }

  //return function call or error message
  if (sndFile) {
    updateBehaviorFns("MM_controlSound");
    return "MM_controlSound('play','document."+sndName+"','"+dw.doURLEncoding(sndFile)+"')"
  }
  else return MSG_NoSndFile;
}


//Passed the function call above, takes prior arguments and reloads the UI.

function inspectBehavior(fnCallStr) {
  var sndFile, argArray = new Array;

  //get previous args
  argArray = extractArgs(fnCallStr);
  if (argArray.length >3) {
    sndFile = argArray[3];
    document.sndFileObj.value = unescape(sndFile); //show name
} }



//Returns a dummy function call to inform Dreamweaver the type of certain behavior
//call arguments. This information is used by DW to fixup behavior args when the
//document is moved or changed.
//
//It is passed an actual function call string generated by applyBehavior(), which
//may have a variable list of arguments, and this should return a matching mask.
//
//The return values are:
//  other...: argument is ignored
//  dep     : argument is a dependent file path, should be included in uploads
//  IE4.0ref: arg is an object ref that may be changed by Convert Tables to Layers

function identifyBehaviorArguments(fnCallStr) {
  var argArray;

  argArray = extractArgs(fnCallStr);
  if (argArray.length == 4) {
    return "other,NS4.0ref,dep";
  } else {
    return "";
  }
}



//Given the original function call, this parses out the args and maybe
//removes associated sound embed calls. Only if:
//1) there's an embed with the same name
//2) when scanning the entire doc, name only found once

function deleteBehavior(fnCallStr) {
  var argArray,sndName,doc,tagArray,i,embedName;

  argArray = extractArgs(fnCallStr);
  if (argArray.length > 3) {
    sndName = dreamweaver.getTokens(argArray[2],".")[1]; //remove "document.", use unique name
    //Find all EMBED calls that we created (name starts with "CS"),
    doc = dreamweaver.getDocumentDOM("document"); //get all
    tagArray = doc.getElementsByTagName("EMBED");
    for (i=0; i<tagArray.length; i++) {  //with each EMBED tag
      embedName = tagArray[i].name;
      if (embedName == sndName) { //if same embed
        if (numOccurences(sndName)<2){ // and embed ref'd no where else
           tagArray[i].outerHTML = ""; //delete the embed
           break;
  } } } }
}



//***************** LOCAL FUNCTIONS  ******************


//Finds any previous sound EMBEDs and adds them to the Stop Sound menu.

function initializeUI() {
  var i,j,tagArray,embedName,embedSrc;

  //Find all EMBED calls that we created (name starts with "CS"), add to the global list.
  tagArray = dreamweaver.getDocumentDOM("document").getElementsByTagName("EMBED");
  for (i=0; i<tagArray.length; i++) {  //with each EMBED tag
    embedName = tagArray[i].name;
    embedSrc = unescape(tagArray[i].src);
    if (embedName && embedSrc) {
       for (j=0; j<MM_sndFiles.length && MM_sndFiles[j] !=embedSrc; j++); //search
       if (j == MM_sndFiles.length) { //if matc not found
           MM_sndNames.push(embedName);  //save sound name for later
           MM_sndFiles.push(embedSrc); //append to the array
  } } }
  document.theForm.sndFileObj.focus(); //set focus on textbox
  document.theForm.sndFileObj.select(); //set insertion point into textbox
}

//Creates a sound embed object, given a name and file. This object is appended to the
//end of the user's document (the end of the BODY tag).

function createSoundObject(sndName,sndFile) {
  var objStr;
  objStr = "<EMBED NAME=\'"+sndName+"\' SRC=\'"+dw.doURLEncoding(sndFile)+"\' LOOP=false \n"+
           "AUTOSTART=false MASTERSOUND HIDDEN=true WIDTH=0 HEIGHT=0></EMBED>\n";
  bodyObj = dreamweaver.getDocumentDOM("document").body; //get body
  bodyObj.innerHTML = bodyObj.innerHTML + objStr; //append new embed
}


//Called by Attain to silently update behavior calls
//Returns new call if ok, otherwise returns empty string

function reapplyBehavior(oldBehaviorCall) {
  var newBehaviorCall = "";
  var behName = "MM_controlSound";

  document.SILENT_MODE = true;
  initializeUI();
  inspectBehavior(oldBehaviorCall);
  newBehaviorCall = applyBehavior();
  if (newBehaviorCall.indexOf(behName) == -1) newBehaviorCall=""; //if not fn call, return ""
  document.SILENT_MODE = false;

  return newBehaviorCall;
}

//**************** GENERIC FUNCTIONS ****************

function numOccurences(theStr) {
  var src, doc, retVal = 0;
  var pat = new RegExp(theStr, "g");

  doc = dreamweaver.getDocumentDOM("document"); //get all
  src = doc.body.outerHTML;
  retVal = src.match(pat).length;

  return retVal;
}
