﻿// CreateTrimmed Adjustment Layer.jsx
// ©June 2008  Lloyd Alvarez  http://aescripts.com
//
//   Creates an Adjustment Layer which is trimmed to the length of the selected layers.
// 
//   v1.1 - If no layers are selected a comp length adj layer is added  (by ken komuro)
//   v1 - Initial release


var proj = app.project;
	var undoStr = "Create Trimmed Adjustment Layer";

	if (proj){
		var myComp = app.project.activeItem;
		if (myComp != null && (myComp instanceof CompItem)){
			app.beginUndoGroup(undoStr);
			
			var myLayers = myComp.selectedLayers;
			if (myLayers.length != 0) {
			var saveIn = myComp.duration;
			var saveOut = 0;
			var saveIndex = myComp.numLayers
			var newInpoint=myComp.duration, newOutpoint=0, myIndex=myComp.numLayers;
			for (i=0; i <= myLayers.length-1; i++){
				
				currentLayer = myLayers[i];
				saveIn = (currentLayer.stretch < 0) ? currentLayer.outPoint : currentLayer.inPoint;
				saveOut = (currentLayer.stretch < 0) ? currentLayer.inPoint : currentLayer.outPoint;
				saveIndex = currentLayer.index;
			
				if (saveIn < newInpoint) {newInpoint = saveIn}
				if (saveOut > newOutpoint) {newOutpoint = saveOut}
				if (saveIndex < myIndex) {myIndex = saveIndex}
			}
		
				var newAdjLayer = myComp.layers.addSolid([255,255,255], "Adjustment Layer", myComp.width, myComp.height, myComp.pixelAspect, myComp.duration);
				newAdjLayer.adjustmentLayer  = true; 
				if (parseFloat(app.version) > 10) newAdjLayer.label= 5; 
				newAdjLayer.moveBefore(myComp.layer(myIndex+1));
				newAdjLayer.inPoint = newInpoint;
				newAdjLayer.outPoint = newOutpoint;
			app.endUndoGroup();
			} else {
				var newAdjLayer = myComp.layers.addSolid([255,255,255], "Adjustment Layer", myComp.width, myComp.height, myComp.pixelAspect, myComp.duration);
				newAdjLayer.adjustmentLayer  = true; 
				newAdjLayer.label= 5; 
				newAdjLayer.moveBefore(myComp.layer(myIndex+1));
				//alert("Please select at least one layer");
				}
		} else {
			alert("Please select an active comp to use this script");
		}
	}
	else
	{
		alert("Please open a project first to use this script.");
	}
