﻿/* TO-DO : flatten deletes stuff outside of the selected comp too. :S*/
function pad(n,i){ //pad n with ceroes up to i places.
    if (String(n).length>=i){
        return String(n)
    }else{
        dif = i- (String(n)).length;
        padding = "";
        for (p=0;p<dif;p++){
            padding = padding+"0"
            }
        return padding+String(n)
    }
}
function getSelectedProjectItems(){
    var items = [];
    var p = app.project;
    for ( var i = 1 ; i <= p.numItems ; i ++ ){
        var item = p.item(i);
    
    

    if ( (item.selected) && ((item.typeName == "Composition")||(item.typeName == "Folder")) ){
            //alert(item.typeName);
            items.push(item);
        }
    }
    return items;
}
function prSlCmps(){
    //save a reference of the original file's path.
    ogFile = app.project.file;
    //alert(ogFile);
    //request a folder to dump these.
    
    dumpFolder = Folder.selectDialog("Choose a folder to DUMP all these ");
    //alert(dumpFolder.absoluteURI);
    sl = getSelectedProjectItems();
    ln = sl.length;
    ids = [];
    for (var i =0; i < ln ; i++ ){
        ids.push(sl[i].id);
    }
    for (var i =0; i < ln ; i++ ){
        //alert(sl);
        itemID = ids[i];
        workComp = app.project.itemByID(itemID);
        //workComp.comment = "COLLECTED";
        projFile = new File( dumpFolder.absoluteURI+"\\"+workComp.name+".aep" );
        //alert( projFile );
        //save a new file per selected comp, named as the comp itself. in the previously given folder and save a reference of its filepath
        app.project.save(projFile);
        //open each of the given file paths, reduce them and save them.
        app.open(projFile);
        workComp = app.project.itemByID(itemID);
        //alert(workComp);
        //workComp.comment = "COLLECTED";
        app.project.reduceProject([workComp]);
        app.project.save(projFile);
        app.executeCommand(app.findMenuCommandId("Collect Files..."));
        app.open(ogFile);
    }
    for (var i =0; i < ln ; i++ ){
        itemID = ids[i];
        workComp = app.project.itemByID(itemID);
        workComp.comment = "collected";
        app.project.save();
    }
}
function incVer( amt ){
    app.beginUndoGroup("Invcrementing Versions");
    sl = getSelectedProjectItems();
    for ( var i = 0; i < sl.length ; i ++){
        var item = sl[i];
        var ogName = item.name;
        var ver = ogName.match("[vV|rR][0-9]{1,999}")[0];
        var verDenom = ver.substring(0,1);
        var verN = parseInt(ver.substring(1,ver.length));
        var newName = ogName.substring(0,ogName.search(ver));
        item.comment = ""; //remove the "collected" comment
        item.name = newName+verDenom+pad((verN+amt),ver.length-1);
        
    }
    app.endUndoGroup();
}
function changeLabel( n ){
    sl = getSelectedProjectItems();
    for ( var i = 0; i < sl.length ; i ++){
        var item = sl[i];
        if ( n == 8 ){
            item.comment = ""; //remove the "collected" comment
        }
        item.label = n;
    }
     
}
function purgeEmptyFolders(){
	//app.beginUndoGroup("Purge Empty Folders")
	var emptyFolders = [];
	
	var p = app.project;
	for ( var i = p.numItems ; i >= 1 ; i -- ){
		item = p.item(i);
		if ( item.typeName == "Folder" ){
			if ( item.numItems <= 0 ){
				item.remove();
			}
		}
	}
	
	//app.endUndoGroup()
}
function getAllItems( folderItem ){
	
	var items = [];
	var folders = [];
	
	for ( var i = 1 ; i <= folderItem.numItems ; i ++ ){
	var item = folderItem.item(i);
	
	if ( (item.typeName != "Folder") ){
			//if ( (isInArray( items ,item )) == false ){
				items.push( item );
			//}
		}else{
				var new_items = getAllItems(item);
				for ( var j = 0 ; j < new_items.length ; j ++ ){
					new_item = new_items[j];
					//if ( (isInArray ( new_item )) == false ){
						items.push ( new_item );
					//}
				}
			}
		}
	return items
}
function flatten( items, root ){
	app.beginUndoGroup("Flatten Selected Folder Contents")
	for ( var i = 0; i < items.length ; i ++){
		item = items[i];
		item.parentFolder = root;
	}
	app.endUndoGroup()
	purgeEmptyFolders();
}

/* Exposed Functions */

function plus1() {
    incVer(1);
}
function minus1() {
    incVer(-1);
}
function minus1() {
    incVer(-1);
}
function tagWip() {
    changeLabel( 8 );
}
function collect() {
    prSlCmps();
    tagDone();
    //alert("It's alive, it's ALIVE!!!!2");
}
function tagDone() {
    changeLabel( 9 );
}
function yFlattenSelectedFolderContents(){
	flatten( getAllItems( getSelectedProjectItems()[0] ) , getSelectedProjectItems()[0] );
}
function ySetProject(){
    app.beginUndoGroup('ySetProject');
    var preStruct = [
	    "01_MAIN",
	    "02_pComps",
	    "03_Images",
	    "04_Movies",
	    "05_Audio",
	    "06_Tools",
	    "07_Ref",
	    "08_Projects"
	    ];
    var newStruct = [];
    var projectItems = [];
    for(i=1;i<=app.project.items.length;i++)
    {
        if(app.project.items[i].parentFolder.name=='Root'){
	    projectItems.push(app.project.items[i].name);
        }
    }

    //to start a new organized project since the beginning
    if (projectItems.length == 0){
    	newStruct = preStruct;
    }else{  
        for(a=0;a<preStruct.length;a++){
        	if ((projectItems.getOne(preStruct[a]))==-1){
	            newStruct.push(preStruct[a]);
		    } 
	    }
    }
    for(i = 1;i<=newStruct.length;i++)
    {
    app.project.items.addFolder(newStruct[i-1]);
        if ( app.project.items[i].name == preStruct[0] ) //Put in MAIN.
       {
           //alert("yes");
               //app.project.items[i].items.addComp("JOBCODE_TYPE_[Scene_name]_vA_r000",1920,1080,1,30,23.976);
        }  
    
    }

    saveNow = confirm("Project Succesfully Set, Save Project?",true,"ySetProject");

    if(saveNow==true){
        app.project.save()
    }else{
    
    }
}
function renderMarkers(){
    p = app.project;
    rq = p.renderQueue;
    rqi = rq.items;
    comp = p.activeItem;
    
    var myRenderNull = comp.layer("Render");
    if ( myRenderNull == null ){
        myRenderNull = app.project.activeItem.layers.addNull();
        myRenderNull.name = "Render";
        myRenderNull.inPoint = -1;
        myRenderNull.outPoint = -1;
        alert('Created "Render Stills" layer.\nAdd markers to this layer and run again to render stills.');
    }	
    
    markers= myRenderNull.property("Marker");
    
    for ( var j = 1 ; j <= markers.numKeys ; j ++ ){
        i = rqi.add( comp );
        var destPath = i.outputModule(1).file.path;
        //i.outputModule(1).applyTemplate("PNG+");
        var markerName = markers.keyValue(j).comment;
        i.timeSpanStart = markers.keyTime(j);
        i.timeSpanDuration = comp.frameDuration;
        
        var destName = comp.name.replace(" ","_");
        
        var destFrame =  markers.keyTime(j) / comp.frameDuration;
        if ( markerName == "" ){
            i.outputModule(1).file = new File( destPath + "/" + destName + "_Still_f" + "[####]" )
        }else{
            i.outputModule(1).file = new File( destPath + "/" + destName + "_Still" + "_f[####]_" + markerName )
        }
        //alert( i.outputModule(1).file );
        //i.outputModule(1).includeSourceXMP = true;
    rq.render();	
    }
    //alert(i.timeSpanStart);
    //alert(i.timeSpanDuration);
    
}