/*
@@@BUILDINFO@@@ "illustrator-13.0.jsx" 2.0 221 14-Jul-2006 
*/

/*
@@@START_XML@@@
<?xml version="1.0" encoding="UTF-8"?>
<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="en_US">
     <dc:title>Adobe Illustrator CS3</dc:title>
     <dc:description>This script enables other applications to communicate with Adobe Illustrator CS3.</dc:description>
</ScriptInfo>
@@@END_XML@@@
*/

/*********************************************************************/
/*                                                                   */
/* Copyright (C) 2004 Adobe Systems, Inc. All rights reserved.       */
/*                                                                   */
/* Module Name: illustrator13.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 illustrator13 != "undefined")
{
	if (illustrator13.revision == undefined || 
	    illustrator13.revision < 2)	// in-sync: revision # of current startup script
		delete illustrator13;
	else
		// bail out right here...
		throw "Object illustrator13() has been defined! New definition is ignored.";	
}

illustrator13 = new Object;
illustrator13.revision = 2;			// in-sync: revision # of current startup script
illustrator13.appName = "illustrator";
illustrator13.targetName = "illustrator-13.0";

illustrator13.ColorModeRGB = 0;
illustrator13.ColorModeCMYK = 1; 

illustrator13.LibraryTypeArtwork= 0;
illustrator13.LibraryTypeSwatches= 1;
illustrator13.LibraryTypeBrushes= 2;
illustrator13.LibraryTypeGraphicStyles= 3;
illustrator13.LibraryTypeSymbols= 4;



/**
  Do the file open.
  @param  files File or Array of File to be opened.
  @return true if all the files are successfully opened.
*/
illustrator13.open = function ( files )
{
    if( BridgeTalk.appName == illustrator13.appName )
    {	
		BridgeTalk.bringToFront(illustrator13.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 = illustrator13.fileArrayToString ( files );

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


/**
  Do the file open with Options
  @param  files File or Array of File to be opened.
  @return true if all the files are successfully opened.
*/


illustrator13.openWithOptions = function ( files, colorspace, library )
{
    if( BridgeTalk.appName == illustrator13.appName )
    {	

		BridgeTalk.bringToFront(illustrator13.targetName);

		var fileArray = new Array;
		if (files instanceof File)
			fileArray.push(files);
		else 
			fileArray = files.concat(fileArray);
		
		var reply = true;
			
		var aiColorSpace = DocumentColorSpace.CMYK; // Initialize with default value
	
		if( colorspace == illustrator13.ColorModeRGB )
			aiColorSpace = DocumentColorSpace.RGB;
		else if( colorspace == illustrator13.ColorModeCMYK )
			aiColorSpace = DocumentColorSpace.CMYK;
			
		var openOpts = new OpenOptions;
		openOpts.openAs = LibraryType.SWATCHES;	
		
		if( library == illustrator13.LibraryTypeArtwork )
			openOpts.openAs = LibraryType.IllustratorArtwork;
		
		else if( library == illustrator13.LibraryTypeSwatches )
			openOpts.openAs = LibraryType.SWATCHES;
		
		else if( library == illustrator13.LibraryTypeBrushes )
			openOpts.openAs = LibraryType.BRUSHES;
		
		else if( library == illustrator13.LibraryTypeGraphicStyles )
			openOpts.openAs = LibraryType.GRAPHICSTYLES;
		
		else if( library == illustrator13.LibraryTypeSymbols )
			openOpts.openAs = LibraryType.SYMBOLS;
			
 		for( var i = 0; i < fileArray.length; i++ )
		{
			try
			{
				app.open( fileArray[i], aiColorSpace, openOpts );
			}
			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 = illustrator13.fileArrayToString ( files );

        var btMessage = new BridgeTalk;
        btMessage.target = illustrator13.targetName;
        btMessage.body = "illustrator13.openWithOptions (" + filesString + "," + colorspace + "," + library + ");";
        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.
*/
illustrator13.openAsNew = function ()
{
    if( BridgeTalk.appName == illustrator13.appName )
    {			
       	BridgeTalk.bringToFront(illustrator13.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 = illustrator13.targetName;
        btMessage.body = "illustrator13.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.
*/
illustrator13.place = function ( files )
{
    if( BridgeTalk.appName == illustrator13.appName )
    {			
		BridgeTalk.bringToFront(illustrator13.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 = illustrator13.fileArrayToString ( files );

        var btMessage = new BridgeTalk;
        btMessage.target = illustrator13.targetName;
        btMessage.body = "illustrator13.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.
*/
illustrator13.print = function ( files )
{
    if( BridgeTalk.appName == illustrator13.appName )
    {			
		BridgeTalk.bringToFront(illustrator13.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 = illustrator13.fileArrayToString ( files );

        var btMessage = new BridgeTalk;
        btMessage.target = illustrator13.targetName;
        btMessage.body = "illustrator13.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.
*/
illustrator13.reveal = function ( file )
{
    if( BridgeTalk.appName == illustrator13.appName )
    {			
		BridgeTalk.bringToFront(illustrator13.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 = illustrator13.targetName;
        btMessage.body = "illustrator13.reveal (" + fileString + ");";
        btMessage.onResult = function(bto) {BridgeTalk.bringToFront(bto.sender);}
        btMessage.send();
	}
}

/**
  Shutdown Illustrator.
  @param  none.
  @return none.
*/
illustrator13.quit = function ()
{
    if( BridgeTalk.appName == illustrator13.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 = illustrator13.targetName;
        btMessage.body = "illustrator13.quit();";
        btMessage.send();
	}
}

/**
  Execute arbitrary Illustrator JavaScript.
  @param  jsscript The script for the Illustrator to run.
  @return result from evaluating the script.
*/
illustrator13.executeScript = function ( jsscript ) 
{
    if( BridgeTalk.appName == illustrator13.appName )
    {			
		BridgeTalk.bringToFront(illustrator13.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 = illustrator13.targetName;
        btMessage.body = "illustrator13.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.
*/
illustrator13.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 if single item is selected.
*/
illustrator13.singleSelectionEnabled = function (menuElement)
{
    menuElement.enabled = false;
    if (app.document != undefined)
    {
		if (app.document.selectionLength == 1)
			menuElement.enabled = true;
	}
}

/**
  This routine sets the argument menu node to be enabled if something is selected.
*/
illustrator13.selectionEnabled = function (menuElement)
{
    menuElement.enabled = false;
    if (app.document != undefined)
    {
		if (app.document.selectionLength > 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.
*/
illustrator13.thumbnailArrayToFileArray = function (thumbnails)
{
	var filesArray = new Array ();
	for (var index = 0; index < thumbnails.length; index++ )
	{
		// Filter out folders
		if (!thumbnails[index].container)
		{
			if(thumbnails[index].spec != undefined) 
			{
				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.
*/
illustrator13.getBridgeFileList = function ()
{	
	var files = new Array;
	if (app.document.thumbnail != undefined)
	{
		var thumbnails = new Array;
		thumbnails = app.document.getSelection("*");
		for (var index = 0; index < thumbnails.length; index++ )
		{
			// Filter out folders
			if (!thumbnails[index].container)
			{
				if(thumbnails[index].spec != undefined) 
				{
					files.push (thumbnails[index].spec);
				}
			}
		}
	}
	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.
*/
illustrator13.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.
*/
illustrator13.getBridgeFilePathList = function ()
{	
	var files = new Array;
	
	if (app.document.thumbnail != undefined)
	{
		files = illustrator13.thumbnailArrayToFilePathArray (app.document.getSelection("*"));
	}
		
	return files;
}
	
/**
  Worker routine to place files from Bridge.
*/
illustrator13.placeLinkFromBridge = function ()
{
	var files = new Array;
	if (app.document.thumbnail != undefined)
	{
		var thumbnails = app.document.getSelection("*");
		files = illustrator13.thumbnailArrayToFileArray (thumbnails);

		if (files.length == 0)
		{
			alert(localize("$$$/Bridge/Menu/Scripting/Illustrator/NoFilesToPlace=There are no files to place into Illustrator."));
		}
		else
		{
			// preflighting
			app.acquirePhysicalFiles(thumbnails);
			
			// call Illustrator place command
			illustrator13.place (files);
		}
	}
}

/**
  Returns true iff the current target app is the highest version installed on the user machine.
*/
illustrator13.CheckHighestInstalledTarget = function()
{
	var thisVersionExists = false;
	var higherVersionExists = false;

	if (BridgeTalk.getTargets(null).join().indexOf(illustrator13.appName) >= 0)
	{
	    var appTargetVersion = illustrator13.targetName.substring(illustrator13.targetName.indexOf('-')+1);
	    
		var appSpecifiers = BridgeTalk.getTargets(0);
		for( var i = 0; i < appSpecifiers.length; i++ )
		{
			var appSpecifier = appSpecifiers[i];
			if( appSpecifier.indexOf(illustrator13.appName) == 0 )
			{
				// get the version #
				var appVersion = appSpecifier.substring(appSpecifier.indexOf('-')+1)
				
				if (appVersion == appTargetVersion)
				{
					thisVersionExists = true;
				}
				else if (appVersion > appTargetVersion)
				{
					higherVersionExists = true;
				}
			}
		}
	}

	if (!higherVersionExists && thisVersionExists	)
		return true;
	else
		return false;
}

/**
  Create the default version-less illustrator BridgeTalk namespace
*/
illustrator13.isHighestInstalledTarget = illustrator13.CheckHighestInstalledTarget();

if (illustrator13.isHighestInstalledTarget)
{
	illustrator = illustrator13;
}

/**
  This routine inserts the "Place/Link to Illustrator" menu item into the Bridge object menu
  and inserts the "Open As AI Library" in right-click context menu for .ai files.
*/
if (BridgeTalk.appName == "bridge" && illustrator13.isHighestInstalledTarget)
{
	var placeLinkCmd = MenuElement.create("command", localize("$$$/Bridge/Menu/Scripting/Illustrator/PlaceLink=In Illustrator"), "at the end of submenu/Place", "PlaceLinkInIllustrator");
	placeLinkCmd.onDisplay = function()
	{
		illustrator13.selectionEnabled(this);
	}
	placeLinkCmd.onSelect = illustrator13.placeLinkFromBridge;
	
	// create illustrator context menu
	var contextMenu = MenuElement.create( "menu", localize("$$$/AI13/MainContextMenu=Open As AI Library"), "-at the end of Thumbnail", "AIContextMenu" );
	contextMenu.onDisplay = function(m) 
	{  
		m.enabled = true;
		try
		{
			m.enabled = app.document.selectionLength > 200 || app.document.getSelection("ai").length > 0;
		} catch(error)
	 	{ 
	 		Window.alert(error); 
	 	}
	}  		
  	
  	// create sub-menu-items
	var	subMenuBrush = MenuElement.create( "command", localize("$$$/AI13/BrushLibrary=AI Brush Library"), "at the end of AIContextMenu", "AIContextMenu/BrushLibrary");
	var	subMenuGraphic = MenuElement.create( "command", localize("$$$/AI13/GraphicLibrary=AI Graphic Library"), "at the end of AIContextMenu", "AIContextMenu/GraphicLibrary");
	var	subMenuSwatch = MenuElement.create( "command", localize("$$$/AI13/SwatchLibrary=AI Swatch Library"), "at the end of AIContextMenu", "AIContextMenu/SwatchLibrary");
	var	subMenuSymbol = MenuElement.create( "command", localize("$$$/AI13/SymbolLibrary=AI Symbol Library"), "at the end of AIContextMenu", "AIContextMenu/SymbolLibrary");


	subMenuBrush.onSelect = function() 
	{
		var thumbnails = app.document.selections;
		app.acquirePhysicalFiles(thumbnails);
		var files = illustrator13.thumbnailArrayToFileArray(thumbnails);
		illustrator13.openWithOptions(files, illustrator13.ColorModeRGB, illustrator13.LibraryTypeBrushes);		
	}
	
	subMenuGraphic.onSelect = function() 
	{
		var thumbnails = app.document.selections;
		app.acquirePhysicalFiles(thumbnails);
		var files = illustrator13.thumbnailArrayToFileArray(thumbnails);
		illustrator13.openWithOptions(files, illustrator13.ColorModeRGB, illustrator13.LibraryTypeGraphicStyles);
	}
	
	subMenuSwatch.onSelect = function() 
	{
		var thumbnails = app.document.selections;
		app.acquirePhysicalFiles(thumbnails);
		var files = illustrator13.thumbnailArrayToFileArray(thumbnails);
		illustrator13.openWithOptions(files, illustrator13.ColorModeRGB, illustrator13.LibraryTypeSwatches);
	}
	
	subMenuSymbol.onSelect = function() 
	{
		var thumbnails = app.document.selections;
		app.acquirePhysicalFiles(thumbnails);
		var files = illustrator13.thumbnailArrayToFileArray(thumbnails);
		illustrator13.openWithOptions(files, illustrator13.ColorModeRGB, illustrator13.LibraryTypeSymbols);
	}	
	
}

illustrator13.matchesFileExtensions = function ( aThumbnail, extensionsToMatch )
{
	if(aThumbnail.spec == undefined)
	{
		return false;
	}
	
	var period = ".";
	var index = aThumbnail.spec.name.toString().lastIndexOf(period);
	
	if (index > -1)
	{
		ext = aThumbnail.spec.name.substring(index+1).toLowerCase();
		if (extensionsToMatch.length > 0)
		{
			for (var extIndex = 0; extIndex < extensionsToMatch.length; extIndex++ )
			{
				if (ext == extensionsToMatch[extIndex])
					return true;
			}
		}
	}
	return false;
}

illustrator13.matchesMacFileType = function ( fileType, fileTypesToMatch )
{	
	if (fileTypesToMatch.length > 0 && fileType != "????" && fileType != "    " && fileType != null)
	{
		for (var i = 0; i < fileTypesToMatch.length; i++ )
		{
			if (fileType == fileTypesToMatch[i])
				return true;
		}
	}
	return false;
}


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