/*********************************************************************/
/*                                                                   */
/* Copyright (C) 2004 Adobe Systems, Inc. All rights reserved.       */
/*                                                                   */
/* Module Name: illustrator12.jsx                                    */
/*                                                                   */
/* Description: Illustrator 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 = 0;

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

try
{ // overall try-catch

if (typeof illustrator12 != "undefined")
{
	if (illustrator12.revision == undefined || 
	    illustrator12.revision < 9)	// in-sync: revision # of current startup script
		delete illustrator12;
	else
		// bail out right here...
		throw "Object illustrator12() has been defined! New definition is ignored.";	
}

illustrator12 = new Object;
illustrator12.revision = 9;			// in-sync: revision # of current startup script
illustrator12.appName = "illustrator";
illustrator12.targetName = "illustrator-12.0";
illustrator12.highestInstalledTargetName = BridgeTalk.getSpecifier(illustrator12.appName);

/**
  Do the file open.
  @param  files File or Array of File to be opened.
  @return true if all the files are successfully opened.
*/
illustrator12.open = function ( files )
{
    if( BridgeTalk.appName == illustrator12.appName )
    {	
		BridgeTalk.bringToFront(illustrator12.targetName);

		var fileArray = new Array;
		if (files instanceof File)
			fileArray.push(files);
		else 
			fileArray = files.concat(fileArray);
		
		var reply = true;
		for( var i = 0; i < fileArray.length; i++ )
		{
			try
			{
				app.open( fileArray[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 Illustrator to invoke open
		var filesString = illustrator12.fileArrayToString ( files );

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

/**
  Create a new un-titled document. 
  @param  creationOptions Optional Illustrator specific creation settings [<color space> [<width> <height>]].
  @return true if new artwork is successfully created.
*/
illustrator12.openAsNew = function ()
{
    if( BridgeTalk.appName == illustrator12.appName )
    {			
       	BridgeTalk.bringToFront(illustrator12.targetName);		

		var doc = null;
		
		try
		{
			// handle valid creation options
			if (arguments.length > 0)
			{
				var colorSpace = null;
				var width = 0;
				var height = 0;
				
				// [<color space>]: DocumentColorSpace
				for (var i = 0; i < arguments.length; i++)
				{
					if (typeof(arguments[i]) == "object" && 
					    (arguments[i] == DocumentColorSpace.RGB || arguments[i] == DocumentColorSpace.CMYK))
					{
						colorSpace = arguments[i];
						break;
					}
				}
	           
				// [<width> <height>] : two numbers
				for (var i = 0; i < arguments.length - 1; i++)
				{
					if (typeof(arguments[i]) == "number" && typeof(arguments[i+1]) == "number")
					{
						width = arguments[i];
						height = arguments[i+1];
						break;
					}
				}
				
				if (colorSpace != null && width > 0 && height > 0)
					doc = app.documents.add(colorSpace, width, height);				
				else if (colorSpace != null)
					doc = app.documents.add(colorSpace);
				else
					doc = app.documents.add();					
			}
			else
			{
				doc = app.documents.add();
			}
		}
		catch (err)
		{
			doc = null;
			//rs = ("Error on reveal(): " + (err.number & 0xFFFF) + ", " + err.description );
			//alert(rs);
		}
        if (doc != null)
            return true;
        else
            return false;
	}
	else
	{
		// create a BridgeTalk message for Illustrator to invoke openAsNew
        var btMessage = new BridgeTalk;
        btMessage.target = illustrator12.targetName;
        btMessage.body = "illustrator12.openAsNew (";
        if (arguments.length > 0)
        {
            for (var i = 0; i < arguments.length; i++)
            {
                btMessage.body += arguments[i].toSource();
            }
        }
        btMessage.body += ");";
        btMessage.onResult = function(bto) {BridgeTalk.bringToFront(bto.sender);}
        btMessage.send();
	}
}

/**
 Place linking files.
 @param  files File or Array of File to be place-linked.
 @return true if all the files are successfully place-linked.
*/
illustrator12.place = function ( files )
{
    if( BridgeTalk.appName == illustrator12.appName )
    {			
		BridgeTalk.bringToFront(illustrator12.targetName);
		
		var fileArray = new Array;
		if (files instanceof File)
			fileArray.push(files);
		else 
			fileArray = files.concat(fileArray);
				
		var reply = false;
		if (app.documents.length == 0)
		{
			app.documents.add();
		}

		reply = true;
		for( var i = 0; i < fileArray.length; i++ )
		{
			try
			{
				var placedArt = app.activeDocument.placedItems.add();
				placedArt.file = fileArray[i];
			}
			catch (err)
			{
				// rollback the earlier actions
				if (placedArt != null && placedArt != undefined)
					placedArt.remove();
					
				reply = false;
				//rs = ("Error on place(): " + (err.number & 0xFFFF) + ", " + err.description + ", " + fileArray[i].toString() );
				//alert(rs);
			}
		}
		return reply;
	}
	else
	{
		// create a BridgeTalk message for Illustrator to invoke place
		var filesString = illustrator12.fileArrayToString ( files );

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

/**
  Do the file print.
  @param  files File or Array of File to be printed.
  @return true if all the files are successfully printed.
*/
illustrator12.print = function ( files )
{
    if( BridgeTalk.appName == illustrator12.appName )
    {			
		BridgeTalk.bringToFront(illustrator12.targetName);
			
		var fileArray = new Array;
		if (files instanceof File)
			fileArray.push(files);
		else 
			fileArray = files.concat(fileArray);
			
		var reply = true;
		for( var i = 0; i < fileArray.length; i++ )
		{
			try
			{
				var doc = app.open( fileArray[i] );
				doc.print();
			}
			catch (err)
			{
				reply = false;
				//rs = ("Error on print(): " + (err.number & 0xFFFF) + ", " + err.description + ", " + fileArray[i].toString() );
				//alert(rs);
			}
		}
		return reply;
	}
	else
	{
		// create a BridgeTalk message for Illustrator to invoke print
		var filesString = illustrator12.fileArrayToString ( files );

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

/**
  Give the target application focus and bring the specified document to the 
  foreground if it is already open.
  @param  file File to be activated.
  @return true if the file was open and is successfully brought to the foreground.
*/
illustrator12.reveal = function ( file )
{
    if( BridgeTalk.appName == illustrator12.appName )
    {			
		BridgeTalk.bringToFront(illustrator12.targetName);
		
		var reply = false;
		try
		{
			for(var index = 0; index < app.documents.length; index ++)
			{
				var doc = app.documents[index];
				if (doc.fullName.toString() == file.toString())
				{
					doc.activate();
					reply = true;
					break;
				}
			}
		}
		catch (err)
		{
			//rs = ("Error on reveal(): " + (err.number & 0xFFFF) + ", " + err.description + ", " + file.toString() );
			//alert(rs);
		}
		return reply;
	}
	else
	{
		// create a BridgeTalk message for Illustrator to invoke reveal
		var fileString = "File ('" + file.path.toString() + "')";;

        var btMessage = new BridgeTalk;
        btMessage.target = illustrator12.targetName;
        btMessage.body = "illustrator12.reveal (" + fileString + ");";
        btMessage.onResult = function(bto) {BridgeTalk.bringToFront(bto.sender);}
        btMessage.send();
	}
}

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

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

		try
		{
			return eval(jsscript);
		}
		catch (err)
		{
			//rs = ("Error on executeScript(): " + (err.number & 0xFFFF) + ", " + err.description);
			//alert(rs);
		}
	}
	else
	{
		// create a BridgeTalk message for Illustrator to invoke executeScript
        var btMessage = new BridgeTalk;
        btMessage.target = illustrator12.targetName;
        btMessage.body = "illustrator12.executeScript(" + jsscript + ");";
        btMessage.onResult = function(bto) {BridgeTalk.bringToFront(bto.sender);}
        btMessage.send();
	}
}

/**
  This routine create a string for the files array that we can transmit
  over BridgeTalk as text, like this:
     Array (File ('path1'), File ('path2'), File ('path3'))
     
  @param  files File or Array of Files.
  @return String.
*/
illustrator12.fileArrayToString = function ( files )
{
	var fileArray = new Array;
	if (files instanceof File)
		fileArray.push(files);
	else 
		fileArray = files.concat(fileArray);
    
    	return fileArray.toSource();
}

/**
  This routine sets the argument menu node to be enabled.
*/
illustrator12.alwaysEnabled = function (menuElement)
{
    menuElement.enabled = true;
}

/**
  This routine sets the argument menu node to be enabled if single item is selected.
*/
illustrator12.singleSelectionEnabled = function (menuElement)
{
    menuElement.enabled = false;
    if (app.document != undefined)
    {
		if (app.document.selections.length == 1)
			menuElement.enabled = true;
	}
}

/**
  This routine sets the argument menu node to be enabled if something is selected.
*/
illustrator12.selectionEnabled = function (menuElement)
{
    menuElement.enabled = false;
    if (app.document != undefined)
    {
		if (app.document.selections.length > 0)
			menuElement.enabled = true;
	}
}
	
/**
  This routine takes an array of thumbnails and returns an array of the
  files represented by those thumbnail objects.

  @param   thumbnails Array of thumbnails.
  @return  Array of Files.
*/
illustrator12.thumbnailArrayToFileArray = function (thumbnails)
{
	var filesArray = new Array ();
	
	for (var index = 0; index < thumbnails.length; index++ )
	{
		// Filter out folders
		if (!thumbnails[index].container)
		{
			filesArray.push (thumbnails[index].spec);
		}
	}
		
	return filesArray;
}

/**
  This routine returns the selected files, or if no files are selected,
  all the files.

  @return  Array of Files.
*/
illustrator12.getBridgeFileList = function ()
{	
	var files = new Array;
	
	if (app.document.thumbnail != undefined)
	{
		if (app.document.selections.length > 0)
		{
			files = illustrator12.thumbnailArrayToFileArray (app.document.selections);
		}
		else if (app.document.thumbnail.children.length > 0)
		{
			files = illustrator12.thumbnailArrayToFileArray (app.document.thumbnail.children);
		}
	}
		
	return files;
}

/**
  This routine takes an array of thumbnails and returns an array of file paths
  represented by those thumbnail objects.

  @param   thumbnails Array of thumbnails.
  @return  Array of Strings.
*/
illustrator12.thumbnailArrayToFilePathArray = function (thumbnails)
{
	var filesArray = new Array ();
	
	for (var index = 0; index < thumbnails.length; index++ )
	{
		// Filter out folders
		if (!thumbnails[index].container)
		{
			filesArray.push (thumbnails[index].path);
		}
	}
		
	return filesArray;
}

/**
  This routine returns an array of file paths for the selected files, or if no files are selected,
  all the files.

  @return  Array of Strings.
*/
illustrator12.getBridgeFilePathList = function ()
{	
	var files = new Array;
	
	if (app.document.thumbnail != undefined)
	{
		if (app.document.selections.length > 0)
		{
			files = illustrator12.thumbnailArrayToFilePathArray (app.document.selections);
		}
		else if (app.document.thumbnail.children.length > 0)
		{
			files = illustrator12.thumbnailArrayToFilePathArray (app.document.thumbnail.children);
		}
	}
		
	return files;
}
	
/**
  Worker routine to place files from Bridge.
*/
illustrator12.placeLinkFromBridge = function ()
{
	var files = illustrator12.getBridgeFileList ();

	if (files.length == 0)
	{
		alert(localize("$$$/Bridge/Menu/Scripting/Illustrator/NoFilesToPlace=There are no files to place into Illustrator."));
	}
	else
	{
		// make sure local replicas are available for Version Cue files 
		var filePathArrays = illustrator12.getBridgeFilePathList ();
		
		// preflighting
		app.preflightFiles( filePathArrays );
		
		// call Illustrator place command
		illustrator12.place (files);
	}
}

/**
  Create the default version-less illustrator BridgeTalk namespace
*/
if (illustrator12.highestInstalledTargetName != null &&
    illustrator12.highestInstalledTargetName.indexOf(illustrator12.targetName) == 0)
{
	illustrator = illustrator12;
}

/**
  This routine inserts the "Place/Link to Illustrator" menu item into the Bridge object menu.
*/
if (BridgeTalk.appName == "bridge")
{
	var placeLinkMenu = MenuElement.find ("PlaceLinkInIllustrator");
	if (placeLinkMenu == null)
	{
		var placeLinkCmd = new MenuElement("command", localize("$$$/Bridge/Menu/Scripting/Illustrator/PlaceLink=In Illustrator"), "at the end of submenu/Place", "PlaceLinkInIllustrator");

		placeLinkCmd.onDisplay = function()
		{
			illustrator12.selectionEnabled(this);
		}
		placeLinkCmd.onSelect = illustrator12.placeLinkFromBridge;
	}
}

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