/* ********************* SOUND PLAYER *************** */

var TEXTSOUND_fOldUnLoad = document.body.onunload;
document.body.onunload = TEXTSOUND_OnUnload;


var TEXTSound_sTargetName = "" // Text to mark on

// SOUND VARIABLES
var TEXTSOUND_sLastEl = "";
var TEXTSOUND_bSoundPlay = false;
var TEXTSOUND_sTool = "";
var TEXTSOUND_bOpenHeadlines = false;
var TEXTSOUND_oFirstNormalVoice;
var TEXTSOUND_bLoad = "true";
var TEXTSOUND_sState;

//For telling the control if just to emphasis
var bJustEmphasisGlobal = false;
var nManualEmpesizeValueGlobal = -1;

// to manage time-based emphasizing in a fix rate of words-per-minute
var TEXTSOUND_nWordInterval;
var TEXTSOUND_nWordsInCurrentSeg;
var TEXTSOUND_nCurrentWordInCurrentSeg;
var TEXTSOUND_arSegIDs;
var TEXTSOUND_nCurrentSegIndex;
// this feature must be triggered by one interval handle and not by consequent timeouts, to eliminate processing time.
// for this the interval is fix along the text and matched to one word. a word-counter triggers the MarkerHitNew.

//An array of handles for the setInterval
var oIntervalHandlesARR = new Array();

//For listening to the key press event
document.body.onkeypress = ActivateNextAudioSegManually;

//This function will receive a new parameter (bJustEmphasis)
//For telling the control to disconnect itselft from being depend on the soundloader.swf.
//This way we can make the control just to emphasis and not play.
//When the bJustEmphasis is sent as true also the nManualEmpesizeValue is sent
function TEXTSOUND_MngSound(sTextID, sState, sID, bJustEmphasis, nManualEmpesizeValue)
{
  //Check if just to emphasis 
  if (bJustEmphasis != undefined && bJustEmphasis != null)
  {
    bJustEmphasisGlobal = bJustEmphasis;
    nManualEmpesizeValueGlobal = nManualEmpesizeValue;
  }
  else
  {
    bJustEmphasisGlobal = "false";
  }

  TEXTSOUND_sTool = "sound";
  TEXTSound_sTargetName = sTextID;
  TEXTSOUND_sState = sState;

  if (sState == 'play')
  {
    //Stop the topbar
    var oTopBar = document.getElementById("topbar");

    //Choose is the left sound maker in the ofek kesem project.
    var oChoose = document.getElementById("choose");
    if (oTopBar != null)
    {
      oTopBar.setVariable("bar.helpEnabled", "false");
    }

    if (oChoose != null)
    {
      oChoose.setVariable("stopSounds", "true");
      oChoose.setVariable("sNeedSound", "false");
    }
  }

  if (!TEXTSOUND_bSoundPlay)
  {
    if (sState == 'play' || sState == 'record')
    {
      //       var oCursor_img = document.getElementById("Cursor_TextCursor_img");           
      //       var oCursor = document.getElementById("Cursor_TextCursor");                                
      ////       oCursor_img.src = "http://" + location.host + "/images/time.gif" ;                                                                       
      //       BASETEXT_SetCursor(oCursor, eval(TEXTSound_sTargetName));            
      //    
      // ex: TEXTSound_sTargetName = "TEXT_Unit001"   
      //      var sCursorSrc = "CetSound_" + TEXTSound_sTargetName.split("_")[1]+ "_" + "Cursor";             
      //      var bNoCursor = false;
      //      try
      //      {
      //        oCursor_img.src = eval(sCursorSrc);                                                                       
      //        if (oCursor_img.src == "")
      //          bNoCursor = true;
      //      }
      //      catch (e)
      //      {
      //        bNoCursor = true;
      //        BASETEXT_HideCursor();   
      //      }

      if (TEXTSOUND_sLastEl != "")
      {
        if (bJustEmphasisGlobal == false || bJustEmphasisGlobal == "false")
        {
          TEXTSOUND_MarkerHit(TEXTSOUND_sLastEl);
        }
        else
        {
          TEXTSOUND_MarkerHitMute(TEXTSOUND_sLastEl);
          TEXTSOUND_StartEmphasizingTimer();
        }
      }
      else
      {
        var sMarkerID = TEXTSOUND_nGetFirstSoundMarker();

        if (bJustEmphasisGlobal == false || bJustEmphasisGlobal == "false")
        {
          TEXTSOUND_MarkerHit(sMarkerID);
        }
        else
        {
          TEXTSOUND_InitMuteEmphasizing(nManualEmpesizeValueGlobal);
          TEXTSOUND_MarkerHitMute(sMarkerID);
        }
      }
    }
    else if (sState == 'stop') // while pausing
    {
      TEXTSOUND_StopSound();
    }
  }
  else
  {
    if (sState == 'play' || sState == 'record')
    {
      var sMarkerID = TEXTSOUND_nGetFirstSoundMarker();

      if (bJustEmphasisGlobal == false || bJustEmphasisGlobal == "false")
      {
        TEXTSOUND_MarkerHit(sMarkerID);
      }
      else
      {
        TEXTSOUND_InitMuteEmphasizing(nManualEmpesizeValueGlobal);
        TEXTSOUND_MarkerHitMute(sMarkerID);
      }
      return;
    }
    else if (sState == 'pause')
    {
      var sSwfID = TEXTSOUND_GetSwfId();
      document.getElementById(sSwfID).setVariable("bStop", "true")
      TEXTSOUND_StopTimer();
    }
    else
    {
      TEXTSOUND_StopSound();
    }
  }
  TEXTSOUND_bSoundPlay = !TEXTSOUND_bSoundPlay;
}
//---------------------------------------------------     

function TEXTSOUND_mngLoad(bLoad)
//      ~~~~~~~~~~~~~~~~~~~
{
  if (bLoad == "false")
  {
    TEXTSOUND_bLoad = "false";
    var oCursor = document.getElementById("Cursor_TextCursor");

    oCursor.src = "images/load.gif";
    BASETEXT_SetCursor(oCursor, eval(TEXTSound_sTargetName))
  }
  else
  {
    TEXTSOUND_bLoad = "true";
    if (TEXTSOUND_bSoundPlay)
    {
      TEXTSOUND_SetCursor();
    }
  }
}
//---------------------------------------------------     

function TEXTSOUND_SetCursor()
//      ~~~~~~~~~~~~~~~~~~~~
{
  if (TEXTSound_sTargetName != "")
  {
    var oCursor_img = document.getElementById("Cursor_TextCursor_img");
    var oCursor = document.getElementById("Cursor_TextCursor");

    // ex: TEXTSound_sTargetName = "TEXT_Unit001"   
    var sCursorSrc = "CetSound_" + TEXTSound_sTargetName.split("_")[1] + "_" + "Cursor";
    var bNoCursor = false;
    try
    {
      oCursor_img.src = eval(sCursorSrc);
      if (oCursor_img.src == "")
        bNoCursor = true;
    }
    catch (e)
    {
      bNoCursor = true;
    }
    if (!bNoCursor)
      BASETEXT_SetCursor(oCursor, eval(TEXTSound_sTargetName));
    else
      BASETEXT_HideCursor();
  }
}

function TEXTSOUND_nGetFirstSoundMarker()
{
  var sMark = eval(TEXTSound_sTargetName.split("_")[1] + "_oFirstAudioseg");
  return sMark;
}

//In cases where the mode is emphezing only we need to redirect and call the TEXTSOUND_MarkerHitMute function
function TEXTSOUND_MarkerHit(sID)
{

  if (TEXTSOUND_sState == 'pause')
  {
    TEXTSOUND_bSoundPlay = true;
    TEXTSOUND_sState = 'play';
  }

  if (TEXTSOUND_sState == 'stop')
  {
    return;
  }

  if (TEXTSOUND_bLoad != "true")
  {
    return;
  }

  if (bJustEmphasisGlobal != null && bJustEmphasisGlobal != undefined && bJustEmphasisGlobal != "false" && bJustEmphasisGlobal != false)
  {
    TEXTSOUND_StopTimer();
    TEXTSOUND_MarkerHitMute(sID);
    return;
  }

  if (TEXTSOUND_sTool == "sound")
  {
    if (sID != "")
    {
      //Get the span itslef from the given id
      var oEl = document.getElementById(sID)
      if (oEl != null)
      {
        TEXTSOUND_ChangeSoundMarkColor(TEXTSOUND_sLastEl, "")

        var sHighLightProp = eval("CetSound_" + TEXTSound_sTargetName.split("_")[1] + "_" + "Style")
        var arrProps = sHighLightProp.split(";")
        if ((oEl.sType.toLowerCase() == 'headline') && (oEl.bOpen == "false"))
        {
          //Marker of close headline --> go to the next audioseg          
          var oEl = TEXTSOUND_GetNextAudioseg(sID);
          if (oEl != null || oEl != "stop")
          {
            sID = oEl.id
          }
          else
          {
            TEXTSOUND_bSoundPlay = false;
            TEXTSOUND_StopSound();
            return;
          }
        }

        for (var i = 0; i < arrProps.length; i++)
        {
          if (arrProps[i].indexOf(":") == -1)
            continue;
          var aProp = arrProps[i].split(":");
          oEl.style.setAttribute(aProp[0], aProp[1]);
        }

        TEXTSOUND_sLastEl = sID;

        // ex; TEXTSound_sTargetName: "TEXT_Unit001"              
        var sSwfID = TEXTSOUND_GetSwfId();
        BASETEXT_ScrollText(TEXTSound_sTargetName, oEl)
        var sID = sID.split("_")[1];
        document.getElementById(sSwfID).SetVariable("nFrameToPlay", sID);
        document.getElementById("BtnTextMenu_" + TEXTSound_sTargetName.split("_")[1]).PressPlayButton()

      }
      else
      {
        TEXTSOUND_bSoundPlay = false;
        TEXTSOUND_StopSound();
      }
    }
    else
    {
      TEXTSOUND_ChangeSoundMarkColor(TEXTSOUND_sLastEl, "");
    }
  }
}

function TEXTSOUND_GetNextAudioseg(sID)
//       ~~~~~~~~~~~~~~~~~~~~~~~~~~
{
  var oText = eval(TEXTSound_sTargetName);

  var arroSpan = oText.all.tags("SPAN");
  var arroAudioseg = new Array();

  for (var i = 0; i < arroSpan.length; i++)
  {
    if (arroSpan[i].sType == 'headline' || arroSpan[i].sType == 'Audioseg')
    {
      arroAudioseg.push(arroSpan[i]);
    }
  }
  for (var i = 0; i < arroAudioseg.length; i++)
  {
    if (arroAudioseg[i].id == sID)
    {
      for (var j = i + 1; j < arroAudioseg.length; j++)
      {
        if (j >= arroAudioseg.length)
          return "stop";
        if (arroAudioseg[j].sType != 'headline')
        {
          return arroAudioseg[j];
        }
        else
        {
          if (arroAudioseg[j].bOpen == "true")
          {
            return arroAudioseg[j];
          }
        }
      }
    }
  }
  return null;

}
//--------------------------------------------------- 

//Change the color of the text to the original before the change of the marker
function TEXTSOUND_ChangeSoundMarkColor(sEl, sColor)
{
  if (sEl != "")
  {
    var oEl = document.getElementById(sEl)
    if (oEl != null)
    {
      oEl.style.backgroundColor = sColor;
      oEl.style.color = "";
    }
  }
}
//---------------------------------------------------     

function TEXTSOUND_StopSound()
//       ~~~~~~~~~~~~~~~~~~~
{
  TEXTSOUND_ChangeSoundMarkColor(TEXTSOUND_sLastEl, "");
  var sSwfID = TEXTSOUND_GetSwfId();
  document.getElementById(sSwfID).setVariable("bStop", "true")
  TEXTSOUND_sLastEl = "";
  TEXTSOUND_sTool = "";
  BASETEXT_HideCursor();
  TEXTSOUND_StopTimer();
  document.getElementById("BtnTextMenu_" + TEXTSound_sTargetName.split("_")[1]).PressStopButton()
  // callback
  if (typeof (TEXTSOUND_OnSoundEnded) == "function")
  {
    TEXTSOUND_OnSoundEnded();
  }

  //For the kesem projects stop the top tool bar
  //Note:This is a damn studpid code!!!! the code will work only if in the aspx files
  //the users called the toolbar 'topbar'
  var oTopBar = document.getElementById("topbar");
  if (oTopBar != null)
  {
    oTopBar.setVariable("bar.helpEnabled", "true");
  }
}
//---------------------------------------------------      

function TEXTSOUND_GetSwfId()
//       ~~~~~~~~~~~~~~~~~
{
  // ex; TEXTSound_sTargetName: "TEXT_Unit001"    
  var aSoundFile = TEXTSound_sTargetName.split("_")

  return aSoundFile[1];
}
//---------------------------------------------------      


function TEXTSOUND_MngHeadlines(sTextID)
//       ~~~~~~~~~~~~~~~~~~~~~~
{
  TEXTSOUND_bOpenHeadlines = !TEXTSOUND_bOpenHeadlines;
  if (TEXTSOUND_bOpenHeadlines)
    var sStyle = ""
  else
    var sStyle = "none"

  TEXTSound_sTargetName = sTextID;
  var oText = eval(TEXTSound_sTargetName);
  var arroAudioseg = oText.all.tags("SPAN");
  var arrHeadlines = new Array();

  for (var i = 0; i < arroAudioseg.length; i++)
  {
    if (arroAudioseg[i].sType == 'headline')
    {
      if (i == 0) //first element
      {
        if (TEXTSOUND_bOpenHeadlines)
        {
          TEXTSOUND_oFirstNormalVoice = eval(TEXTSound_sTargetName.split("_")[1] + "_oFirstAudioseg")
          eval(TEXTSound_sTargetName.split("_")[1] + "_oFirstAudioseg" + '=arroAudioseg[i].id');
        }
        else
        {
          eval(TEXTSound_sTargetName.split("_")[1] + "_oFirstAudioseg" + '=TEXTSOUND_oFirstNormalVoice');
        }
      }
      arrHeadlines.push(arroAudioseg[i]);
    }
  }

  for (var i = 0; i < arrHeadlines.length; i++)
  {
    if (TEXTSOUND_bOpenHeadlines)
      arrHeadlines[i].bOpen = "true";
    else
      arrHeadlines[i].bOpen = "false";
    arrHeadlines[i].style.display = sStyle;
  }
}

function TEXTSOUND_OnUnload()
{

}

function TEXTSOUND_MarkerHitMute(sID)
{
  if (TEXTSOUND_sState != 'pause')
  {
    TEXTSOUND_ChangeSoundMarkColor(TEXTSOUND_sLastEl, "");
  }

  //Debug
  //alert("first time:" + sID);   
  if (TEXTSOUND_sState == 'pause')
  {
    TEXTSOUND_StopTimer();
    //   TEXTSOUND_sLastEl = sID;      
    //   TEXTSOUND_bSoundPlay = false;
    //   TEXTSOUND_sState  = 'play';
    return;
  }

  if (TEXTSOUND_sState == 'stop')
  {
    return;
  }

  if (TEXTSOUND_bLoad != "true")
    return;

  if (TEXTSOUND_sTool == "sound")
  {
    if (sID != "")
    {
      //Get the span itslef from the given id
      var oEl = document.getElementById(sID);

      if (oEl != null)
      {
        //Return the previous one to the original text color        
        TEXTSOUND_ChangeSoundMarkColor(TEXTSOUND_sLastEl, "");

        var sHighLightProp = eval("CetSound_" + TEXTSound_sTargetName.split("_")[1] + "_" + "Style")
        var arrProps = sHighLightProp.split(";");

        if (TEXTSOUND_nCurrentSegIndex >= TEXTSOUND_arSegIDs.length)
        {
          TEXTSOUND_bSoundPlay = false;
          TEXTSOUND_StopSound();
          //dtEndClear = new Date();
          //alert(nClearingWord + " words in " + (dtEndClear.getTime()-dtStartClear.getTime()) + " ms")
          //alert(sDebug);
          return;
        }
        if (nManualEmpesizeValueGlobal >= 0)
        {
          //This is the place where we emphezise the text  
          for (var i = 0; i < arrProps.length; i++)
          {
            if (arrProps[i].indexOf(":") == -1)
              continue;
            var aProp = arrProps[i].split(":");
            oEl.style.setAttribute(aProp[0], aProp[1]);
          }
          if (nManualEmpesizeValueGlobal > 0)
          {
            TEXTSOUND_nWordsInCurrentSeg = GetTextLength(oEl);
            TEXTSOUND_nCurrentWordInCurrentSeg = 0;
          }
        }

        BASETEXT_ScrollText(TEXTSound_sTargetName, oEl)

        TEXTSOUND_sLastEl = sID;
      }
      else
      {
        TEXTSOUND_bSoundPlay = false;
        TEXTSOUND_StopSound();
        //dtEndClear = new Date();
        //alert(nClearingWord + " words in " + (dtEndClear.getTime()-dtStartClear.getTime()) + " ms")
        //alert(sDebug);
      }
    }
    else
    {
      TEXTSOUND_ChangeSoundMarkColor(TEXTSOUND_sLastEl, "");
    }
  }
}


///Gets the lenth of the words from the span object represting the audio seg
function GetTextLength(oTextObj)
{
  var sText = oTextObj.innerText;
  //trim:
  while (sText.charAt(0) == " ")
    sText = sText.substr(1);
  while (sText.charAt(sText.length - 1) == " ")
    sText = sText.substr(0, sText.length - 1);

  var nTextObjTextLength = sText.split(" ").length;
  return nTextObjTextLength;
}

///This function will clear all the handles that was called using the oIntervalHandle 
function TEXTSOUND_StopTimer()
{
  for (var i = 0; i < oIntervalHandlesARR.length; i++)
  {
    COMMON_ClearInterval(oIntervalHandlesARR[i]);
  }
  oIntervalHandlesARR = new Array();
}

function ActivateNextAudioSegManually()
{
  if (TEXTSOUND_sState != "play")
  {
    return;
  }
  if (nManualEmpesizeValueGlobal == 0)
  {
    if (event.keyCode == 32)
    {
      TEXTSOUND_NextMuteAudioSeg();
    }
  }
}

function TEXTSOUND_NextMuteAudioSeg()
{
  // when the marker is not hit by sound, but by timer or on keypress (bJustEmphasis)
  TEXTSOUND_nCurrentSegIndex++;
  TEXTSOUND_MarkerHitMute(TEXTSound_sTargetName.split("_")[1] + "_" + TEXTSOUND_arSegIDs[TEXTSOUND_nCurrentSegIndex]);
}

function TEXTSOUND_OnWordInterval()
{
  window.status = TEXTSOUND_nCurrentSegIndex;
  //dtNew = new Date();
  //sDebug += (dtNew.getTime() - dtOld.getTime()) + "\n";
  //dtOld = dtNew;
  //nClearingWord++;
  TEXTSOUND_nCurrentWordInCurrentSeg++;
  if (TEXTSOUND_nCurrentWordInCurrentSeg == TEXTSOUND_nWordsInCurrentSeg)
  {
    TEXTSOUND_NextMuteAudioSeg();
  }
}

var bIsEmphesizing = false;
function TEXTSOUND_InitMuteEmphasizing(nEmphasizingValue)
{
  // load list of AudioSeg IDs
  TEXTSOUND_LoadAudioSegIDs();
  TEXTSOUND_StartEmphasizingTimer();
  TEXTSOUND_nCurrentSegIndex = 0;
  bIsEmphesizing = true;

  //sDebug = "";
  //nClearingWord = 0;
  //dtStartClear = new Date();
  //dtOld = new Date();
}

//this function is taking place when a user clicks on the texts
// and the narration/emphesizing should jump to the clicked area
function TEXTSOUND_StartEmphasizingFromClickedSeg(SegID)
{
  if (!bIsEmphesizing)
  {
    //segment marking function for narration
    TEXTSOUND_MarkerHit(SegID);
  }
  else
  {
    try
    {
      //we resolve and change the index number of the clicked segment 
      SegID.match(/.*?_.{1}0*(.*)/);
      TEXTSOUND_nCurrentSegIndex = parseInt(RegExp.$1);
    }
    catch (err)
    {
      //if cannot resolve segment index number from segID there is enigmatic error that we choose to ignore 
      //so the onclick event will not effect the marked text
      return;
    }
    //segment marking function for narration
    TEXTSOUND_MarkerHitMute(SegID);
  }
}
function TEXTSOUND_StartEmphasizingTimer()
{
  //==========================================================================
  // nManualEmpesizeValueGlobal values:
  // If -1 return
  // If 0 wait for key press
  // If 10,20,30,40,50 - the number of words per minute
  //==========================================================================        
  if (nManualEmpesizeValueGlobal > 0)
  {
    TEXTSOUND_nWordInterval = 60 * 1000 / nManualEmpesizeValueGlobal;
    var oIntervalHandle = COMMON_SetInterval(TEXTSOUND_OnWordInterval, TEXTSOUND_nWordInterval);
    oIntervalHandlesARR.push(oIntervalHandle);
  }
}

function TEXTSOUND_LoadAudioSegIDs()
{
  if (typeof (TEXTSOUND_MarkersFilePath) == typeof (undefined))
  {
    alert("ERROR - TestSound.js: TEXTSOUND_MarkersFilePath is not set on page for mute emphasizing!");
    return;
  }
  var oXml = new ActiveXObject("Msxml2.DOMDocument");
  oXml.async = false;
  oXml.load(TEXTSOUND_MarkersFilePath);
  TEXTSOUND_arSegIDs = new Array();
  var oMarkerNameNodes = oXml.selectNodes("/Root/Markers/Marker/@sID");
  // TEXTSOUND_arSegIDs[0] keeps place for the "_oFirstAudioSeg"
  for (var i = 0; i < oMarkerNameNodes.length; i++)
  {
    TEXTSOUND_arSegIDs[i] = oMarkerNameNodes[i].text;
  }
  //alert(TEXTSOUND_arSegIDs.join("\n"));
}
