// Copyright 2006 Adobe, Inc. All rights reserved.
//**************  GLOBAL CONSTANTS  *************************

var _DETECT_SIZE_LOOP = 30; //times

// js object for FLV loader
var FLVLoader = dwscripts.findDOMObject("MM_FLVLoader");

var rtnStr='';
var progress = null;
var codecID = -1;

var width;
var height;
var videoDim = null;
var videoDimParams = null;

var bFlashInit = false;
var videoUrl = '';

//***********************************************************

function isDOMRequired() { 
  // return true.  This will insert the object into the design view.
  return true;
}

function isAsset() {
  return true;
}

function detectSize()
{ 
    // this is for safety, of having the window open forever
    // since this is a hidden window we will automatically close it in 20 seconds
    // as it should not be visible beyond this time
    setTimeout("window.close()", 20000);

    // initialize all vars
    if(!bFlashInit)
         bFlashInit = true; 

    rtnStr='';
    progress = null;		
	codecID = -1;		
    
    // the default dimensions
    width = 320;
	height = 240;
	videoDim = null;
	videoDimParams = null;			
	
	var dom = dw.getDocumentDOM();
    if(dom)
        dom.setFlashVideoDetectingSize(true);       
    
	detectVideoInfoForProgressive();    
}
        
 
function genFlvHtml()		
{			
    var dom = dw.getDocumentDOM();
    if(dom)
        dom.setFlashVideoDetectingSize(false);
        
	var videoPlayerFileSourceFolder = dwscripts.filePathToLocalURL(dw.getConfigurationPath()
				+ dwscripts.FILE_SEP + "Templates" + dwscripts.FILE_SEP + "Video_Player");
	var videoControlsFileSourceFolder = dwscripts.filePathToLocalURL(dw.getConfigurationPath()
				+ dwscripts.FILE_SEP + "Templates" + dwscripts.FILE_SEP + "Video_Controls");
	         
	var swfPath = videoPlayerFileSourceFolder + "/" + "FLVPlayer_Progressive.swf";        
	var skinName = videoControlsFileSourceFolder + "/" + "Clear_Skin_1";		
	      
	//    set reqVerStr for Flash detection 
	var reqVerStr = "";
	if (codecID == 4 || codecID == 5)
		reqVerStr = "8,0,0,0";
	else
	    reqVerStr = "7,0,0,0";

	var docPath = dw.getDocumentPath("document");
	var siteRoot = "";
	var isSiteRelative = false;

	if (docPath)
	    siteRoot = dw.getSiteRootForURL(docPath);

	if (siteRoot != "") {
        isSiteRelative = dw.isUrlSiteRelative(docPath); 
    }

	var expInstallPath = "Scripts" + dwscripts.FILE_SEP;
	var absoluteExpInstallPath;

	if (siteRoot == "") {
	    absoluteExpInstallPath = docBase + dwscripts.FILE_SEP + expInstallPath;
	}
	else {
	    absoluteExpInstallPath = siteRoot + expInstallPath;
	}

	if (isSiteRelative)
	    expInstallPath = dw.absoluteURLToSiteRelative(docPath, siteRoot, absoluteExpInstallPath, true);
	else
	    expInstallPath = dw.absoluteURLToDocRelative(docPath, siteRoot, absoluteExpInstallPath, true);

	expInstallPath += "expressInstall.swf";
	
	// streamName  
	var sourceURL = videoUrl;
	if(/\.flv$/i.test(sourceURL))
		streamName = trimString(sourceURL.replace(/\.flv$/i,""));
	else
	    streamName = trimString(sourceURL);
	
	// other parameters
	var isAutoPlay = "true";
	var isAutoRewind = "false";        
	
	// get the default flv html to be inserted
	var str = getHTMLCode();
	       
	// fill in the html with the detected values
	str = str.replace(/\$PLAYERVERSION\$/, reqVerStr);
	str = str.replace(/\$EXPRESSINSTALL\$/g, expInstallPath);
	str = str.replace(/\$SWFPATH\$/g, swfPath);    
	str = str.replace(/\$SKIN_NAME\$/g, skinName);
	str = str.replace(/\$AUTO_PLAY\$/g, isAutoPlay);
	str = str.replace(/\$AUTO_REWIND\$/g, isAutoRewind);
	str = str.replace(/\$STREAM_NAME\$/g, streamName);
	str = str.replace(/\$WIDTH\$/g,width);
	str = str.replace(/\$HEIGHT\$/g, height);
	str = str.replace(/\$PLAYERVERSION\$/, reqVerStr);
	rtnStr = str;
	        
	if (rtnStr && dw.getPreferenceString("Accessibility", "Accessibility Media Options", "") == 'TRUE')
	{
	  rtnStr = addAccessibility(rtnStr);
	}

    var isBlogSite = false;
    if(dom)
    {
        if(CCWorkspaceManager.getManager(dom))
        { // todo - make a single extension list and use it
            if(CCWorkspaceManager.getManager(dom).isBlogSite())                          
                isBlogSite = true;            
        }
    } 
   
   window.close();  
}

function addAccessibility(rtnStr) {
   var cmdFile = dreamweaver.getConfigurationPath() + "/Commands/Object Options.htm";
   var cmdDOM = dreamweaver.getDocumentDOM(cmdFile);
 
   cmdDOM.parentWindow.setFormItem(rtnStr);
   dreamweaver.popupCommand("Object Options.htm");
   return (cmdDOM.parentWindow.returnAccessibilityStr(rtnStr));	
}


// FLV specific code:

//-------------------------------------------------------------------
// FUNCTION:
//   getHTMLCode
//
// DESCRIPTION:
//   returns HTML code correponding to the video type selected.
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   return - HTML code correponding to the video type selected.
//
//--------------------------------------------------------------------

function getHTMLCode()
{
  var str;
  var uniqueIndex;
  var uniqueFlashPlayerID;
    
  uniqueIndex = generateUniqueIndex();
  if(uniqueIndex == 0)
    uniqueFlashPlayerID = "FLVPlayer";
  else
      uniqueFlashPlayerID = "FLVPlayer" + uniqueIndex;

  var isBlogSite = false;
  var dom = dw.getDocumentDOM();
  if (dom) {
      if (CCWorkspaceManager.getManager(dom)) { // todo - make a single extension list and use it
          if (CCWorkspaceManager.getManager(dom).isBlogSite())
              isBlogSite = true;
      }
  }

  //Return old flash code for blogs and new code for websites
  if (isBlogSite == true) 
  {
      str = "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=$PLAYERVERSION$\" width=\"$WIDTH$\" height=\"$HEIGHT$\" id=\"" + uniqueFlashPlayerID + "\">" + "\n"
          + "<param name=\"movie\" value=\"$SWFPATH$\" />" + "\n"
          + "<param name=\"salign\" value=\"lt\" />" + "\n"
          + "<param name=\"quality\" value=\"high\" />" + "\n"
          + "<param name=\"scale\" value=\"noscale\" />" + "\n"
	      + "<param name=\"FlashVars\" value=\"&amp;MM_ComponentVersion=1&amp;skinName=$SKIN_NAME$&amp;streamName=$STREAM_NAME$&amp;autoPlay=$AUTO_PLAY$&amp;autoRewind=$AUTO_REWIND$\" />" + "\n"
          + "<embed src=\"$SWFPATH$\" FlashVars=\"&amp;MM_ComponentVersion=1&amp;skinName=$SKIN_NAME$&amp;streamName=$STREAM_NAME$&amp;autoPlay=$AUTO_PLAY$&amp;autoRewind=$AUTO_REWIND$\" quality=\"high\" scale=\"noscale\" width=\"$WIDTH$\" height=\"$HEIGHT$\" name=\"" + uniqueFlashPlayerID + "\" salign=\"LT\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash\" />" + "\n"
          + "</object>";
  }
  else 
  {
      var useEntities = isDoubleByteOrUtf8Encoding() == false;
      var innerObjComment = dw.loadString("flash/comment for inner object tag");
      var expressInstallComment = dw.loadString("flash/comment for express install");
      var altContentComment = dw.loadString("flash/comment for alternative content");
      var getNewPlayerMsg = dw.loadString("flash/get new player message");
      var altValueForImg = dw.loadString("flash/alt attribute value for get player image");
      var paramTags = '<param name="quality" value="high">\n' +
                    '<param name="wmode" value="opaque">\n' +
                    '<param name="scale" value="noscale">\n' +
                    '<param name="salign" value="lt">\n';
      var progressParamTags = paramTags + '<param name="FlashVars" value="&amp;MM_ComponentVersion=1&amp;skinName=$SKIN_NAME$&amp;streamName=$STREAM_NAME$&amp;autoPlay=$AUTO_PLAY$&amp;autoRewind=$AUTO_REWIND$" />\n';
      var streamingParamTags = paramTags + '<param name="FlashVars" value="&amp;MM_ComponentVersion=1&amp;serverName=$SERVER_NAME$&amp;skinName=$SKIN_NAME$&amp;appName=$APP_NAME$&amp;streamName=$STREAM_NAME$&amp;isLive=$IS_LIVE$&amp;bufferTime=$BUFFER_TIME$&amp;autoPlay=$AUTO_PLAY$&amp;autoRewind=$AUTO_REWIND$" />\n';
      var swfVersionParam = '<param name="swfversion" value="$PLAYERVERSION$">\n';
      var expressInstallParam = '<param name="expressinstall" value="$EXPRESSINSTALL$">\n';
      var altContent = '<!-- ' + altContentComment + ' -->\n' +
                    '<div>\n<h4>' + getNewPlayerMsg + '</h4>\n' +
                    '<p><a href="http://www.adobe.com/go/getflashplayer">' +
                    '<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="' +
                    altValueForImg + '" /></a></p>\n</div>';

      if (useEntities) {
          getNewPlayerMsg = dwscripts.entityNameEncode(getNewPlayerMsg);
          altValueForImg = dwscripts.entityNameEncode(altValueForImg);
      }

      str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="$WIDTH$" height="$HEIGHT$" id="' + uniqueFlashPlayerID + '">\n'
          + '<param name="movie" value="$SWFPATH$" />\n'
          + progressParamTags + swfVersionParam + '<!-- ' + expressInstallComment + ' -->\n' + expressInstallParam
          + '<!-- ' + innerObjComment + ' -->\n'
          + '<!--[if !IE]>-->\n'
          + '<object type="application/x-shockwave-flash" data="$SWFPATH$" width="$WIDTH$" height="$HEIGHT$">\n'
          + '<!--<![endif]-->\n'
          + progressParamTags + swfVersionParam + expressInstallParam
          + altContent
          + '<!--[if !IE]>-->\n</object>\n<!--<![endif]-->\n'
          + '</object>';


      var assetList = new Array();
      var assetInfo = new AssetInfo("Shared/Flash/" + FlashObjectLibraryFile, "Scripts/" + FlashObjectLibraryFile, "javascript", false);
      assetList.push(assetInfo);

      assetInfo = new AssetInfo("Shared/Flash/expressInstall.swf", "Scripts/expressInstall.swf", "", false);
      assetList.push(assetInfo);

      var dom = dw.getDocumentDOM();
      dom.copyAssets(assetList);

      var scriptStr = FlashObjectFuncName + '("' + uniqueFlashPlayerID + '");';
      dom.addJavaScript(scriptStr, false);
  }

  return str;
}

//-------------------------------------------------------------------
// FUNCTION:
//   generateUniqueIndex
//
// DESCRIPTION:
//   returns unique index for Flash Object.
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   return - unique index for Flash Object.
//
//--------------------------------------------------------------------

function generateUniqueIndex()
{
  var FLV_PLAYER_ID = "FLVPlayer";
  var uniqueId = FLV_PLAYER_ID;
  var ctr=0;
  var dom = dw.getDocumentDOM();
  var nodeArr;
  if(dom)
  {
    nodeArr = dom.getElementsByTagName("object");    
    while(isIdExists(uniqueId, nodeArr))
    {
      uniqueId = FLV_PLAYER_ID + ++ctr;
    }
  }
  return ctr;
}

//-------------------------------------------------------------------
// FUNCTION:
//   isIdExists
//
// DESCRIPTION:
//   returns true if initFLVPlayerID already exists on the page.
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   return - true if initFLVPlayerID already exists on the page.
//
//--------------------------------------------------------------------

function isIdExists(initFLVPlayerID, nodeArr)
{
  var flvPlayerID;
  for(var i=0; i<nodeArr.length; i++)
  {
    if(nodeArr[i].getAttribute("id"))
      flvPlayerID = nodeArr[i].getAttribute("id");
    else
      continue;
      
    if(flvPlayerID && flvPlayerID == initFLVPlayerID)         
      return true;    
  }
  return false;
}


//--------------------------------------------------------------------
// FUNCTION:
//   detectVideoInfoForProgressive()
//
// DESCRIPTION:
//   detect the size for .flv (file , http) and initialize the width and height
//
//
// ARGUMENTS:
//   the url (file or http)
//
// RETURNS:
//   nothing.
//             
//--------------------------------------------------------------------
function detectVideoInfoForProgressive()
{    
	videoDim = null;
	var videoURL = dw.doURLDecoding(videoUrl);

	if ((videoURL != null) && (videoURL.length > 0))
	{
		codecID = -1;
		videoURL = trimString(videoURL);
		if (isFileURL(videoURL))
		{
			//form a file:///url if not http
			videoURL = getFullURL(videoURL);
			
			// if the flv file does not exist, don't try to detect codec ID. 
			if (!DWfile.exists(videoURL))
			{
				alert(dw.loadString("Movie/file not found"));
				window.close();
			}
		}
		
		//load the video URL to get the auto detect the video dimension
		loadVideo(videoURL);
		
		//start the detect poll
		//we need the below flag to track when the auto detect from
		//swfloader extension is completed.
		//we loop 30 times x 500ms (1/2 second)15 seconds
		MM._LOOPCOUNTER = 0;
		var funCallBack = "isDetectCodecIDDone()";		
		setTimeout(funCallBack,500);				
	}
}

//--------------------------------------------------------------------
// FUNCTION:
//   isDetectCodecIDDone()
//
// DESCRIPTION:
//   checks if detect size is done
//
//
// ARGUMENTS:
//   none
//
// RETURNS:
//   nothing.
//             
//--------------------------------------------------------------------
function isDetectCodecIDDone()
{
	//check if we are not yet done detecting	
	videoDimParams = getVideoProps();
	if ((videoDimParams != null) && (videoDimParams.length > 0))
	{
		if (videoDimParams[2] != null && (videoDimParams[0] != 0) && (videoDimParams[1] != 0))
		{
			width = videoDimParams[0];
			height = videoDimParams[1];
			codecID = videoDimParams[2];						
			if(progress != null)
       		    progress.close();
       		    
			genFlvHtml();			
		}
		else
		{		
			if (MM._LOOPCOUNTER == _DETECT_SIZE_LOOP - 1)
			{				
				codecID = -1;
				genFlvHtml();				    
				if(progress != null)
        		    progress.close();
			}
			else
			{		
			    var cancelled = false;
			    if( progress==null )
			    {
			        var title = dw.loadString("Movie/progress dialog title");
			        var desc = dw.loadString("Movie/progress dialog desc");
			        progress = dw.openProgressDialog(title, desc, 0, true);
			        cancelled = progress.update(Math.round(MM._LOOPCOUNTER*3.3), 100);
			    }
			    else
			        cancelled = progress.update(Math.round(MM._LOOPCOUNTER*3.3), 100);
			        
			    if(cancelled == true)
			    {
			        genFlvHtml();				        
			        if(progress)
			            progress.close();
			    }
			    else
			    {    
			        //increament the loop counter and set a time out recursively				   
				    MM._LOOPCOUNTER++;			
				    var funCallBack = "isDetectCodecIDDone()";				   
				    setTimeout(funCallBack,500);			    	
				}
			}
		}
	}		
}

function setVideoUrl(url)
{
    videoUrl = url;    
}

function GetGenHtml()
{
    return rtnStr;
}

function mmHideDialog()
{
}

//+-------------------------------------------------------------------+
// jvillegas: helper functions to call the Flash Player dll 

// loadVideo must be called to initialize the FLV file before 
// calling getVideoProps()
function loadVideo(videoURL)
{
  	if(bFlashInit)
	{ // call this function in the stub movie
		
		if((videoURL != null) && (videoURL.length > 0))
		{
			FLVLoader.fileToLoad = videoURL;
			FLVLoader.wantFLVDimensions = "true";
			FLVLoader.reload();		
		}
	}
}

// getVideoProps() sniffs the FLV file for the width/height info
// this should be called on a separate event from loadVideo to give the player
// some cycles to actualy load the FLV buffer
function getVideoProps()
{
	videoDim = new Array();
	if (bFlashInit)
	{ 		
		if (FLVLoader.isReady == "true" && FLVLoader.xnError == "false")
		{
		    videoDim[0] = FLVLoader.flvWidth;
		    videoDim[1] = FLVLoader.flvHeight;
		    videoDim[2] = FLVLoader.videocodecid;		    		    
		}
		else
		{	
		    videoDim[0] = videoDim[1] = videoDim[2] = 0; 
		}
	}		
	return videoDim;
}

// other helper functions

//-------------------------------------------------------------------
// FUNCTION:
//   isFileURL
//
// DESCRIPTION:
//   checks if it fileURL
//
// ARGUMENTS:
//   aFileURL
//
// RETURNS:
//   nothing.
//
//--------------------------------------------------------------------
function isFileURL(aURL)
{
	var bIsFileURL = true;
	if ((aURL != null) && (aURL.length))
	{
		if ((aURL.indexOf("http://") == 0) || (aURL.indexOf("rtmp://") == 0))
		{
			bIsFileURL = false;
		}
	}
	return bIsFileURL;
}


//--------------------------------------------------------------------
// FUNCTION:
//   getFullURL()
//
// DESCRIPTION:
//   get the full url specified the url , w.r.t to either doc relative 
//   or site relative.
//
// ARGUMENTS:
//   the url (rtmp)
//
// RETURNS:
//   nothing.
//             
//--------------------------------------------------------------------
function getFullURL(aURL)
{
	var absoluteURL = aURL;
	if ((aURL != null) && (aURL.length))
	{
		//get docPath URL
		var docPath = dw.getDocumentPath("document");
		var siteRoot = dw.getSiteRoot();
		//get absolute URL from relative URL
		absoluteURL = dw.relativeToAbsoluteURL(docPath,siteRoot,aURL);
		if (absoluteURL.indexOf("file:////") == 0)
		{
			absoluteURL = absoluteURL.substring(8,absoluteURL.length);
		}
	}
	return absoluteURL;
}

//-------------------------------------------------------------------
// FUNCTION:
//   trimString
//
// DESCRIPTION:
//   trims the string.
//
// ARGUMENTS:
//   str - the string
//
// RETURNS:
//   return - trimmed string.
//
//--------------------------------------------------------------------

function trimString(str)
{
  var regExpBeginSpaces = /^\s*/
  var regExpEndSpaces = /\s*$/;
  str = str.replace(regExpBeginSpaces,"");
  str = str.replace(regExpEndSpaces,"");
  return str;
}

