/*********************************************************************/
/*                                                                   */
/* Copyright (C) 2004 Adobe Systems, Inc. All rights reserved.       */
/*                                                                   */
/* Module Name: fireworks.jsx                                    */
/*                                                                   */
/* Description: Fireworks Cross-DOM implementation for the Bridge. */
/*                                                                   */
/*                                                                   */
/* NOTICE:  All information contained herein or attendant            */
/* hereto is, and remains, the property of Adobe Systems, Inc.       */
/* Many of the intellectual and technical concepts contained         */
/* herein are proprietary to Adobe Systems, Inc. and may be          */
/* covered by U.S. and Foreign Patents or Patents Pending or         */
/* are protected as trade secrets.  Any dissemination of this        */
/* information or reproduction of this material are strictly         */
/* forbidden unless prior written permission is obtained from        */
/* Adobe Systems, Inc.                                               */
/*                                                                   */
/*********************************************************************/

/**
   Set debugging level: 0-2 (0:disable, 1:break on error, 2:break at beginning)
*/
$.level = 2;

/**
  Guard against loading of multiple revisions of the same startup script. The latest revision
  will take precedence.
*/

try
{ // overall try-catch

fireworks = new Object;
fireworks.revision = "CS3";			// in-sync: revision # of current startup script
fireworks.appName = "Adobe%20Fireworks";
fireworks.targetName = "Fireworks";
fireworks.highestInstalledTargetName = BridgeTalk.getSpecifier(fireworks.targetName);

fireworks.installPathURIprefix = '"file:///c|/Program%20Files/Adobe/';

//*******************************************************************************************************************************
//CROSS DOM API
fireworks.open = function ( files )
{
    if( BridgeTalk.appName == fireworks.targetName )
    {	
 		BridgeTalk.bringToFront(fireworks.targetName);

		var filesString = fireworks.fileArrayToString ( files );
		
		var reply = true;
		for( var i = 0; i < filesString.length; i++ )
		{
			try
			{
				app.openDocument( filesString[i] );
			}
			catch (err)
			{
				reply = false;
				rs = ("Error on open(): " + (err.number & 0xFFFF) + ", " + err.description + ", " + fileArray[i].toString() );
				alert(rs);
			}
		}
		return reply;
	}
	else
	{
		// create a BridgeTalk message for fireworks to invoke open
		var filesString = fireworks.fileArrayToString ( files );

        var btMessage = new BridgeTalk;
        btMessage.target = fireworks.targetName;
       	btMessage.body = "fw.openDocument (" + filesString + ");";
        btMessage.onResult = function(bto) {BridgeTalk.bringToFront(bto.sender);}
        btMessage.send();
    }
}

/**
  Create a new un-titled document. 
  @param  creationOptions not supported by FW
  @return true if new artwork is successfully created.
*/
fireworks.openAsNew = function ()
{
    if( BridgeTalk.appName == fireworks.targetName )
    {			
       	BridgeTalk.bringToFront(fireworks.targetName);		

		var doc = null;
		
		try
		{
				doc = app.openDocument( NULL, true);
		}
		catch (err)
		{
		}
        if (doc != null)
            return true;
        else
            return false;
	}
	else
	{
		// create a BridgeTalk message for Fireworks to invoke openAsNew
        var btMessage = new BridgeTalk;
        btMessage.target = fireworks.targetName;
        btMessage.body = "fireworks.openAsNew;";
        btMessage.onResult = function(bto) {BridgeTalk.bringToFront(bto.sender);}
        btMessage.send();
	}
}

/**
  Do the file print.  -- UNSUPPORTED 
  @param  files File or Array of File to be printed.
  @return true if all the files are successfully printed.
*/
fireworks.print = function ( files )
{
   // DO NOTHING
}

/**
  Shutdown fireworks.
  @param  none.
  @return none.
*/
fireworks.quit = function ()
{
    if( BridgeTalk.appName == fireworks.targetName )
    {			
		try
		{
			fw.quit();
		}
		catch (err)
		{
			//rs = ("Error on quit(): " + (err.number & 0xFFFF) + ", " + err.description);
			//alert(rs);
		}
	}
	else
	{
		// create a BridgeTalk message for Fireworks to invoke quit
        var btMessage = new BridgeTalk;
        btMessage.target = fireworks.targetName;
        btMessage.body = "fireworks.quit();";
        btMessage.send();
	}
}

/**
  Execute arbitrary fireworks JavaScript.
  @param  jsscript The script for the Fireworks to run.
  @return result from evaluating the script.
*/
fireworks.executeScript = function ( jsscript ) 
{
    if( BridgeTalk.appName == fireworks.targetName )
    {			
		BridgeTalk.bringToFront(fireworks.targetName);

		try
		{
			return fw.eval(jsscript);
		}
		catch (err)
		{
			rs = ("Error on executeScript(): " + (err.number & 0xFFFF) + ", " + err.description);
			alert(rs);
		}
	}
	else
	{
		// create a BridgeTalk message for Fireworks to invoke executeScript
        var btMessage = new BridgeTalk;
        btMessage.target = fireworks.targetName;
        btMessage.body = "fireworks.executeScript(" + jsscript + ");";
        btMessage.onResult = function(bto) {BridgeTalk.bringToFront(bto.sender);}
        btMessage.send();
	}
}
//*******************************************************************************************************************************
//FIREWORKS SPECIFIC COMMANDS
/**
  Convert selected images to gray scale.
  @param  none.
  @return none.
*/

fireworks.convertToGrayScale = function ()
{
	if (BridgeTalk.appName == "bridge")
	{
		var files = fireworks.getBridgeFileList ();
		if (files.length > 0)
		{
		var filesString = fireworks.fileArrayToString ( files );
		
        var btMessage = new BridgeTalk;
        btMessage.target = fireworks.targetName;
        btMessage.onResult = function(bto) {BridgeTalk.bringToFront(bto.sender);}
	/*	btMessage.launchTarget( btMessage.target, 
                          "mmoptimize", 
                          1 );
        btMessage.body = 'alert("hidden mode")';
        btMessage.send();
		*/
		//btMessage.body = '';
        if(files.length > 0)
        {
        	for( var i = 0; i < filesString.length; i++ )
        	{
        		btMessage.body = 'fw.openDocument (' + filesString[i] + ');';
        		btMessage.body += 'fw.runScript('+fireworks.installPathURIprefix+fireworks.appName+'%20'+fireworks.revision+'/Configuration/Commands/Creative/Convert%20to%20Grayscale.jsf")';
        		var ret = btMessage.send();
        	}
        }
        else
        {
        	btMessage.body += 'fw.openDocument (' + filesString + ');';
      		btMessage.body += 'fw.runScript('+fireworks.installPathURIprefix+fireworks.appName+'%20'+fireworks.revision+'/Configuration/Commands/Creative/Convert%20to%20Grayscale.jsf")';
      		btMessage.send();
      	}
      	BridgeTalk.bringToFront(fireworks.targetName);
        }
     }
}

fireworks.convertToSepia = function ()
{
	if (BridgeTalk.appName == "bridge")
	{
		var files = fireworks.getBridgeFileList ();
		//Window.alert(files);
		if (files.length > 0)
		{
		var filesString = fireworks.fileArrayToString ( files );
		
        var btMessage = new BridgeTalk;
        btMessage.target = fireworks.targetName;
        btMessage.onResult = function(bto) {BridgeTalk.bringToFront(bto.sender);}
		
        if(files.length > 0)
        {
        	for( var i = 0; i < filesString.length; i++ )
        	{
        		btMessage.body = 'fw.openDocument (' + filesString[i] + ');';
        		btMessage.body += 'fw.runScript('+fireworks.installPathURIprefix+fireworks.appName+'%20'+fireworks.revision+'/Configuration/Commands/Creative/Convert%20to%20Sepia%20Tone.jsf")';
        		btMessage.send()
        	}
        }
        else
        {
        	btMessage.body = 'fw.openDocument (' + filesString + ');';
      		btMessage.body += 'fw.runScript('+fireworks.installPathURIprefix+fireworks.appName+'%20'+fireworks.revision+'/Configuration/Commands/Creative/Convert%20to%20Sepia%20Tone.jsf")';
      		btMessage.send()
      	}
      	BridgeTalk.bringToFront(fireworks.targetName);
        }
     }
}

fireworks.commandBatchInvert = function ()
{
	if (BridgeTalk.appName == "bridge")
	{
		var files = fireworks.getBridgeFileList ();
		if (files.length > 0) 
		{
		var filesString = fireworks.fileArrayToString ( files );
		
        var btMessage = new BridgeTalk;
        btMessage.target = fireworks.targetName;
        btMessage.onResult = function(bto) {BridgeTalk.bringToFront(bto.sender);}
		
        if(files.length > 0)
        {
        	for( var i = 0; i < filesString.length; i++ )
        	{
        		btMessage.body = 'fw.openDocument (' + filesString[i] + ');';
        		btMessage.body += 'fw.runScript('+fireworks.installPathURIprefix+fireworks.appName+'%20'+fireworks.revision+'/Configuration/Commands/Batch%20Commands/Select%20All.jsf");fw.runScript('+fireworks.installPathURIprefix+fireworks.appName+'%20'+fireworks.revision+'/Configuration/Commands/Batch%20Commands/Invert%20Selection%20Color.jsf");';
        		btMessage.send()
        	}
        }
        else
        {
        	btMessage.body = 'fw.openDocument (' + filesString + ');';
      		btMessage.body += 'fw.runScript('+fireworks.installPathURIprefix+fireworks.appName+'%20'+fireworks.revision+'/Configuration/Commands/Batch%20Commands/Select%20All.jsf");fw.runScript('+fireworks.installPathURIprefix+fireworks.appName+'%20'+fireworks.revision+'/Configuration/Commands/Batch%20Commands/Invert%20Selection%20Color.jsf");';
        	btMessage.send()
      	}
      	BridgeTalk.bringToFront(fireworks.targetName);
        }
     }
}

fireworks.commandBatchProcess = function ()
{
	if (BridgeTalk.appName == "bridge")
	{
		var fl = new Array;
		fl = fireworks.getBridgeFileList ();
		if (fl.length > 0) 
		{
		//var filesString = fireworks.fileArrayToString ( files );
		var btMessage = new BridgeTalk;
		//btMessage.launchTarget( fireworks.targetName,"mmhidden");
        
        btMessage.target = fireworks.targetName;
        btMessage.onResult = function(bto) {BridgeTalk.bringToFront(bto.sender);}
        //Window.alert(fl.toSource().split(','));
        btMessage.body = 'fw.doBatchProcess('+fl.toSource().split(',')+');';
        btMessage.send();
        BridgeTalk.bringToFront(fireworks.targetName);
        }
     }
}

fireworks.fileArrayToString = function ( files )
{
	var fileArray = new Array;
	if (files instanceof File)
		fileArray.push(files);
	else 
		fileArray = files.concat(fileArray);
    
    var filesString = fileArray.toSource();
    //remove quotes, starting and ending brackets
	var str = filesString.split('[');
	str = str[1].split(']');
	str = str[0].split(',');
   	return str;
}


fireworks.thumbnailArrayToFileArray = function (thumbnails)
{
	var filesArray = new Array ();
	
	for (var index = 0; index < thumbnails.length; index++ )
	{
		// Filter out folders
		if (!thumbnails[index].container)
		{
			var fname = thumbnails[index].spec.getRelativeURI("/");
			//var fname = thumbnails[index].spec.absoluteURI;
			var c = fname.substr(0,2);
			fname = "file://"+fname.replace(c,c+"|");
			filesArray.push (fname);
		}
		else
		{
			//Window.alert (localize ("$$$/PSBI/Automate/FoldersNotAllowed=Folders cannot be used for this command.")
			Window.alert ("Folders cannot be used for this command.");
			}
	}
		
	return filesArray;
}


fireworks.getBridgeFileList = function ()
{	
	var files = new Array;
	if (app.document.thumbnail != undefined)
	{
		if (app.document.selections.length > 0)
		{
			files = fireworks.thumbnailArrayToFileArray (app.document.selections);
			
		}
		else if (app.document.thumbnail.children.length > 0)
		{
			files = fireworks.thumbnailArrayToFileArray (app.document.thumbnail.children);
		}
	}
		
	return files;
}
/**
  This routine inserts the "Convert to gray scale, Convert To Sepia to Fireworks" menu item into the Bridge tools menu.
*/

if (BridgeTalk.appName == "bridge")
{
	var exportMenu = MenuElement.find ("fw");
	if (exportMenu == null)
	{
		newMenu = new MenuElement( "menu", "Fireworks", "at the end of Tools","fw");
		alertCommand = new MenuElement( "command", "Convert To Grayscale", "at the end of fw");
   		alertCommand.onSelect = fireworks.convertToGrayScale;   
   		alertCommand1 = new MenuElement( "command", "Convert To Sepia", "at the end of fw");
   		alertCommand1.onSelect = fireworks.convertToSepia;   
   		alertCommand2 = new MenuElement( "command", "Invert Selection Color", "at the end of fw");
   		alertCommand2.onSelect = fireworks.commandBatchInvert;
   		alertCommand3 = new MenuElement( "command", "Batch Process...", "at the end of fw");
   		alertCommand3.onSelect = fireworks.commandBatchProcess;
	}
	   
}

} // overall try-catch
catch(ex)
{
}
