﻿/*
@@@BUILDINFO@@@ aftereffects-8.0.jsx 8.0
*/

/*
@@@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 After Effects CS3</dc:title>
     <dc:description>This script enables other applications to communicate with Adobe After Effects CS3.</dc:description>
</ScriptInfo>
<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="fr_FR">
     <dc:title>Adobe After Effects CS3</dc:title>
     <dc:description>Ce script permet à d'autres applications de communiquer avec Adobe After Effects CS3.</dc:description>
</ScriptInfo>
<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="de_DE">
     <dc:title>Adobe After Effects CS3</dc:title>
     <dc:description>Mithilfe dieses Skripts können andere Anwendungen mit Adobe After Effects CS3 kommunizieren.</dc:description>
</ScriptInfo>
<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="it_IT">
     <dc:title>Adobe After Effects CS3</dc:title>
     <dc:description>Questo script consente ad altre applicazioni di comunicare con Adobe After Effects CS3</dc:description>
</ScriptInfo>
<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="es_ES">
     <dc:title>Adobe After Effects CS3</dc:title>
     <dc:description>Este script posibilita que otras aplicaciones se comuniquen con Adobe After Effects CS3</dc:description>
</ScriptInfo>
<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="ja_JP">
     <dc:title>Adobe After Effects CS3</dc:title>
     <dc:description>このスクリプトは、他のアプリケーションと Adobe After Effects CS3 との通信を有効にします。</dc:description>
</ScriptInfo>
@@@END_XML@@@
*/

//$.level = 1; debugger;

aftereffects8 = {};

aftereffects8.AfterEffectsTargetName = "aftereffects-8.0"
aftereffects8.AfterEffectsAppName = "aftereffects"
aftereffects8.AfterEffectsVersion = "8.0"
aftereffects8.BridgeTargetName = "bridge"

/**
**	Open Event
**
**	The event is:
**		type - document
**		location - document
**		object - document
**
**	To get the selection use object.selections.
**
*/
aftereffects8.eventHandler = function(event)
{
	var retval = {};
	retval.handled = false;

	if ( event.type == "open" &&
		event.location == "document" &&
		event.object.constructor.name == "Document" &&
		app.document.owner == aftereffects8.AfterEffectsTargetName)
	{
		var sels = event.object.groupedSelections;
		var files = [];
		
		for (var i = 0; i < sels.length; i++)
		{
			var sub_sels = sels[i];
			var sub_files = [];
			for (var j= 0; j < sub_sels.length; j++) {
				sub_files[j] = sub_sels[j].spec;
			}
			files[i] = sub_files;
		}

		aftereffects8.open(files);
		retval.handled = true;
	}

	return retval;
}

if(BridgeTalk.appName == aftereffects8.BridgeTargetName)
{
	app.eventHandlers.push( { handler:aftereffects8.eventHandler } );
}

/**
**	fileArrayToString
**
**	This routine create a string for the array of array of files where
** sub-array of 1 element is an individual file and a sub-array of 
** multiple elements is a sequence that we can transmit
**	over BridgeTalk as text, like this:
**
**	Array (Array(File ('path1')), Array(File ('path1'), File ('path3')))
*/
aftereffects8.fileArrayToString = function (files)
{
    var filesString = new String ("Array (");
    
	for (var index = 0; index < files.length; index++)
    {
		if (index > 0) {
			filesString += ", ";
		} 
			
		filesString += "Array (";
		
		var sub_files = files[index];
		
		for (var sub_index = 0; sub_index < sub_files.length; sub_index++) {
			if (sub_index > 0)
			{
				filesString += ", ";
			}
	
			filesString += "File ('" + sub_files[sub_index].absoluteURI.toString() + "')";
		}
		// close the Array
		filesString += ")";
    }
    
    // close the Array
    filesString += ")";
    
    return filesString;
}

//
// aftereffects8 Cross DOM
//
aftereffects8.executeScript = function(script)
{
	var btMessage = new BridgeTalk;
	btMessage.target = aftereffects8.AfterEffectsTargetName;
	btMessage.body = script;
	btMessage.send();
}


aftereffects8.getExtension = function(filename)
{
	var	dot_index = filename.lastIndexOf('.');
	
	return filename.substring(dot_index);
}

aftereffects8.applyPreset = function(filepath)
{
	if (app.project.activeItem instanceof CompItem) {
 		if(app.project.activeItem.selectedLayers.length) {
 			for (aLayer in app.project.activeItem.selectedLayers) {
 				app.project.activeItem.selectedLayers[aLayer].applyPreset(File(filepath));
 			}
 		} else {
 			app.project.activeItem.applyPreset(File(filepath));
 		}
 	}
}

aftereffects8.open = function(target)
{	
	if (BridgeTalk.appName == aftereffects8.AfterEffectsAppName && BridgeTalk.appVersion == aftereffects8.AfterEffectsVersion)
	{	
		var	first_file_array = target[0];
		var	ext = aftereffects8.getExtension(first_file_array[0].name);
		var	is_project = (ext == ".aep");
		var	is_template_proj = (ext == ".aet");
		
		BridgeTalk.bringToFront( aftereffects8.AfterEffectsAppName );
		
		app.activate();
		
		if (target.length == 1 && first_file_array.length == 1 && (is_project || is_template_proj)) {
			try {
				if (is_project) {
					app.open(File(first_file_array[0].fsName));
				} else {
					app.openTemplate(File(first_file_array[0].fsName));
				}
			} catch(e) {
				alert(e);
			}
		} else { 
			for (var index = 0; index < target.length; index++)
			{
				try {
					var file_subarray = target[index];
					var len = file_subarray.length;
					
					if (len == 1) {
						if (aftereffects8.getExtension(file_subarray[0].name) == ".ffx") {
							aftereffects8.applyPreset(file_subarray[0].fsName);
						} else {
							var imp_options = new ImportOptions(new File(file_subarray[0].fsName));
							app.project.importFile(imp_options);
						}
					} else {	// sequence
						var file_name1 = file_subarray[0].fsName;
						var file_name2 = file_subarray[len -1].fsName;
						var imp_options = new ImportOptions(new File(file_name1));
						var seq_range_start = imp_options.isFileNameNumbered(file_name1);
						var seq_range_end = imp_options.isFileNameNumbered(file_name2);
						
						if (seq_range_start.isNumbered && seq_range_end.isNumbered) {
								imp_options.rangeStart = seq_range_start.num;
								imp_options.rangeEnd = seq_range_end.num;
						}
						imp_options.sequence = true;
						app.project.importFile(imp_options);
					}
				} catch(e) {
					alert(e);
				}
			}
		}
		
	} else {
		var filesString = aftereffects8.fileArrayToString (target);
		aftereffects8.executeScript("aftereffects8.open(" + filesString + ");");
	}
}



//-----------------------------------------------------------------
// The code below inserts the Place in After Effects menu item into the 
// place menu and sets up the onSelect and onDisplay routines for
// it.
//-----------------------------------------------------------------
if (BridgeTalk.appName == aftereffects8.BridgeTargetName) {
	// Use temp function to keep vars out of global namespace.
	aftereffects8.tempFunction = function () {
		
		placePlaceCommandName = {
			en: "In After Effects",
			fr: "Dans After Effects",
			de: "In After Effects",
			it: "In After Effects",
			es: "En After Effects",
			ja: "After Effects 内"
		};
		
		var placeMenuItem = MenuElement.create ("command",
												localize (placePlaceCommandName),
												'at the end of submenu/Place',
												'PlaceInAE');
												
		shouldPlaceInAEMenuItemBeEnabled = function () {
			var enableMenuItem = (BridgeTalk.isRunning (aftereffects8.AfterEffectsAppName) &&
				(app.document.selectionLength >= 1));
				
			if (enableMenuItem) {
				for (var i = 0; i < app.document.selectionLength; i++) {
					if (app.document.selections[i].container) {
						enableMenuItem = false;
						break;
					}
				}
			}
			
			return enableMenuItem;
		}
		
		placeSelectedFiles = function () {
			try {
				var sels = app.document.groupedSelections;
				var files = [];
				
				for (var i = 0; i < sels.length; i++) {
					var sub_sels = sels[i];
					var sub_files = [];
					for (var j = 0; j < sub_sels.length; j++) {
						sub_files[j] = sub_sels[j].spec;
					}
					files[i] = sub_files;
				}
				aftereffects8.open(files);
			}
			catch (error) {
				alert (error);
			}
		}
		
		placeMenuItem.onDisplay = function () {
			this.enabled = shouldPlaceInAEMenuItemBeEnabled();
		}
			
		placeMenuItem.onSelect = function () {
			placeSelectedFiles();
		}
		
		
		
		placeThumbCommandName = {
			en: "Place In After Effects",
			fr: "Importer dans After Effects",
			de: "In After Effects platzieren",
			it: "Inserisci in After Effects",
			es: "Colocar en After Effects",
			ja: "After Effects 内に配置"
		};
		
		var contextPlaceMenuItem = MenuElement.create ("command",
												localize (placeThumbCommandName),
												'at the end of Thumbnail',
												'ContextPlaceInAE');
		
		contextPlaceMenuItem.onDisplay = function () {
			this.enabled = shouldPlaceInAEMenuItemBeEnabled();
		}
		
		contextPlaceMenuItem.onSelect = function () {
			placeSelectedFiles();
		}
	}
	
	aftereffects8.tempFunction ();
	delete aftereffects8.tempFunction;
}	




aftereffects8.quit = function()
{
	if (BridgeTalk.appName == aftereffects8.AfterEffectsAppName && 
			BridgeTalk.appVersion == aftereffects8.AfterEffectsVersion) {
		app.quit();
	} else {
		aftereffects8.executeScript("app.quit();");
	}
}

// if this is the highest installed version of aftereffects, then
aftereffects = aftereffects8;
//alert( "Loaded successfully.");
