/*******************************************************************
 $CRT 29 Sep 2006 : hb

 $DAT >>Vegas_MtPv_Transition.js<< 03 Oct 2006  11:36:28 - (c) proDAD
*******************************************************************/

import System.Windows.Forms;
import Microsoft.Win32;
import Sony.Vegas;


StopPlayback();


var TC  : Timecode   = Vegas.Cursor;
var Evt : TrackEvent = FindSelectedEvent();

if(Evt != null)
{
  var Start : Timecode = Evt.Start;
  var End   : Timecode = Evt.End;


  if(Evt.FadeIn.Transition != null)
  {
    SaveDuration(Evt.FadeIn.Length);
    End = Start + Evt.FadeIn.Length;
  }


  if(TC <= Start)
  {
    TC = Start;
    TC.FrameCount += 1;
  }
  else
  {
    TC.FrameCount += 2;
    if(TC >= End)
    {
      TC = Start;
      TC.FrameCount += 1;
    }
  }

  Vegas.Cursor = TC;

  SavePrjInfo();
}




/*----------------------------------
----------------------------------*/
function FindSelectedEvent() : TrackEvent
{
  var trackEnum = new Enumerator(Vegas.Project.Tracks);
  while(!trackEnum.atEnd())
  {
    var track : Track = Track(trackEnum.item());
    if(track.Selected)
    {
      var eventEnum = new Enumerator(track.Events);
      while(!eventEnum.atEnd())
      {
        var evnt : TrackEvent = TrackEvent(eventEnum.item());
        if(evnt.Selected)
        {
          return evnt;
        }
        eventEnum.moveNext();
      }
    }
    trackEnum.moveNext();
  }
  return null;
}


/*----------------------------------
----------------------------------*/
function GetRegTopKey()
{
  var rk = Registry.CurrentUser;
  rk = rk.CreateSubKey("Software");
  rk = rk.CreateSubKey("proDAD");
  rk = rk.CreateSubKey("tmp");
  rk = rk.CreateSubKey("Vegas");
  return rk;
}


/*----------------------------------
----------------------------------*/
function SaveDuration(tc : Timecode)
{
  var rk = GetRegTopKey();
  rk.SetValue
  (
    "duration",
    tc.ToMilliseconds()
  );
}


/*----------------------------------
----------------------------------*/
function SavePrjInfo()
{
  var rk = GetRegTopKey();

  rk.SetValue
  (
    "width",
    Vegas.Project.Video.Width.ToString()
  );

  rk.SetValue
  (
    "height",
    Vegas.Project.Video.Height.ToString()
  );

  rk.SetValue
  (
    "aspect",
    Math.round(10000*Vegas.Project.Video.PixelAspectRatio).ToString()
  );

  rk.SetValue
  (
    "fps",
    Math.round(10000*Vegas.Project.Video.FrameRate).ToString()
  );
}


/*----------------------------------
 Don't work ?!
----------------------------------*/
function StopPlayback()
{
  var WshShell = new ActiveXObject("WScript.Shell");
  WshShell.SendKeys("{ESC}");
}
