/***********************************************************************/
/*                                                                     */
/*      FlyingButtons :: Create a PDF portfolio with popup images      */
/*                       from an InDesign document using thumbnails    */
/*                                                                     */
/*      [Ver: 1.05b]     [Author: Marc Autret]    [Modif: 03/26/10]    */
/*      [Lang: EN]       [Req: InDesign CS4]      [Creat: 03/23/10]    */
/*      [Type: FREE]                                                   */
/*                                                                     */
/*      Installation:                                                  */
/*                                                                     */
/*      1) Place the current file into Scripts/Scripts Panel/          */
/*                                                                     */
/*      2) Run InDesign, open/create a document                        */
/*                                                                     */
/*      3) Create some thumbnails containing images (links),           */
/*         then create an empty frame (destination)                    */
/*                                                                     */
/*      4) Select the thumbnails and the destination frame             */
/*                                                                     */
/*      5) Exec the script from Window>Automatisation>Scripts          */
/*         + double-click on the script file name                      */
/*                                                                     */
/*      Bugs & Feedback : marc{at}indiscripts{dot}com                  */
/*                        www.indiscripts.com                          */
/*                                                                     */
/***********************************************************************/

var flyingButtons = function()
{
if( app.documents.length <= 0 )
	{
	alert( "Please open a document." );
	return;
	}
if( app.activeDocument.modified == true )
	{
	alert( "Please save your document." );
	return;
	}
if( app.selection.length < 2 )
	{
	alert( "Please select an empty frame for output and at least one thumbnail frame." );
	return;
	}

var bTmbName = function(bCount,pgName)
	{
	return 'bTmb_'+pgName+'_'+bCount;
	};

var bScreenName = function(bCount,pgName)
	{
	return 'bScr_'+pgName+'_'+bCount;
	};
	
var convertToButton = (function()
	{
	var maCreateButton = app.menuActions.item('$ID/$$$/Dialog/CmdName/CreateButton');
	return function(/*PageItem*/obj, /*str*/bName, /*str*/bDesc)
		{
		var tStyle, ret;

		app.selection = [obj];
		maCreateButton.invoke();
		ret = app.selection[0];
		
		ret.name = bName||ret.name;
		ret.description = bDesc||ret.description;
		
		return ret;
		};
	})();

var stylizeState = function(tState,tStyle,tStyleImg)
	{
	if( tStyle.isValid )
		{
		tState.pageItems[0].applyObjectStyle(tStyle);
		}
	if( tStyleImg.isValid && tState.pageItems[0].images.length==1 )
		{
		tState.pageItems[0].images[0].applyObjectStyle(tStyleImg);
		}
	};

var convertToThumbButton = function(/*PageItem*/obj, /*int*/bCount, /*str*/pgName)
	{
	var ret = convertToButton(obj, bTmbName(bCount,pgName), 'Click to show this image'),
		tState = ret.states[0],
		pIt = tState.pageItems[0],
		oStyle = pIt.appliedObjectStyle,
		pObjStyles = oStyle.parent.objectStyles,
		sn = oStyle.name,
		tStyle, tStyleImg;


	ret.visibilityInPdf = VisibilityInPdf.VISIBLE_IN_PDF;
	

	tStyle = pObjStyles.item(sn + '_off');
	tStyleImg = pObjStyles.item(sn + '_img_off');
	stylizeState(tState,tStyle,tStyleImg);

	tStyle = pObjStyles.item(sn + '_over');
	tStyleImg = pObjStyles.item(sn + '_img_over');
	if( tStyle.isValid || tStyleImg.isValid )
		{
		tState = ret.states.add({stateType:StateTypes.ROLLOVER});
		stylizeState(tState,tStyle,tStyleImg);
		}
	
	tStyle = pObjStyles.item(sn + '_click');
	tStyleImg = pObjStyles.item(sn + '_img_click');
	if( tStyle.isValid || tStyleImg.isValid )
		{
		tState = ret.states.add({stateType:StateTypes.DOWN});
		stylizeState(tState,tStyle,tStyleImg);
		}

	ret.label = pIt.images[0].itemLink.filePath;
	return ret;
	};

var convertToScreenButton = function(/*PageItem*/obj, /*int*/bCount, /*str*/pgName)
	{
	var ret = convertToButton(obj, bScreenName(bCount,pgName), 'Click to hide this window');
	ret.visibilityInPdf = VisibilityInPdf.HIDDEN_IN_PDF;
	return ret;
	};

var hiddenRevert = function(doc)
	{
	var f = doc.fullName;
	doc.close(SaveOptions.NO);
	app.open(f);
	};
	
var s = app.selection.concat(),
	doc = app.activeDocument,
	bThumbs = [],
	bScreens = [],
	bCount = 0,
	container, i, tmb, ctn, sz, pgName;

for( i=s.length-1 ; i>=0 ; i-- )
	{
	if( !('images' in s[i]) ) continue;
	
	if( !pgName && s[i].parent.constructor == Page )
		pgName = s[i].parent.name;

	if( s[i].images.length == 1 )
		{
		tmb = s[i].duplicate(undefined,[0,0]);
		bThumbs.push(convertToThumbButton(tmb, ++bCount, pgName||''));
		continue;
		}
		
	container = container||s[i];
	}

var endScript = function(/*?str*/msg)
	{
	hiddenRevert(doc);
	app.menuActions.item('$ID/$$$/Panel/States').invoke();
	if( msg ) alert(msg);
	}
	

if( !container )
	{
	endScript( "Unable to find a container frame.");
	return;
	}

sz = bThumbs.length;
for( i=0 ; i<sz ; i++ )
	{
	ctn = container.duplicate(undefined,[0,0]);
	tmb = bThumbs[i];
	ctn.place(File(tmb.label), false);
	ctn.fit(FitOptions.PROPORTIONALLY);
	ctn.fit(FitOptions.FRAME_TO_CONTENT);
	bScreens.push(convertToScreenButton(ctn, i+1, pgName||''));
	}

for( i=0 ; i<sz ; i++ )
	{
	bThumbs[i].showHideFieldsBehaviors.add({
		behaviorEvent: BehaviorEvents.MOUSE_DOWN,
		// hide all screens AND this button
		fieldsToHide: bScreens.concat([bThumbs[i]]),
		// show bScreens[i] AND all other buttons
		fieldsToShow: [bScreens[i]].concat(bThumbs.slice(0,i)).concat(bThumbs.slice(i+1,sz))
		});
	bScreens[i].showHideFieldsBehaviors.add({
		behaviorEvent: BehaviorEvents.MOUSE_DOWN,
		// hide this screen
		fieldsToHide: [bScreens[i]],
		// show bThumbs[i]
		fieldsToShow: [bThumbs[i]]
		});
	}
container.nonprinting = true;

var fPDF = File.saveDialog("Export to PDF (FlyingButtons)", "PDF files:*.pdf");

if( !fPDF )
	{
	endScript();
	return;
	}

var pdfExPreset;

try	{
	pdfExPreset = app.pdfExportPresets.add({
	name: 'FlyingButtons',
	acrobatCompatibility: AcrobatCompatibility.ACROBAT_7,
	bleedMarks: false,
	colorBars: false,
	colorBitmapCompression: BitmapCompression.ZIP,
	colorBitmapQuality: CompressionQuality.EIGHT_BIT,
	colorBitmapSampling: Sampling.BICUBIC_DOWNSAMPLE,
	colorBitmapSamplingDPI: 96,
	compressionType: PDFCompressionType.COMPRESS_OBJECTS,
	contentToEmbed: PDFContentToEmbed.EMBED_ALL,
	cropImagesToFrames: true,
	cropMarks: false,
	exportGuidesAndGrids: false,
	exportLayers: false,
	exportNonprintingObjects: false,
	exportWhichLayers: ExportLayerOptions.EXPORT_VISIBLE_PRINTABLE_LAYERS,
	generateThumbnails : false,
	grayscaleBitmapCompression: BitmapCompression.NONE,
	grayscaleBitmapSampling: Sampling.NONE,
	includeBookmarks: true,
	includeHyperlinks: true,
	includeICCProfiles: true,
	includeSlugWithPDF: false,
	includeStructure: false,
	interactiveElements: true,
	monochromeBitmapCompression: MonoBitmapCompression.NONE,
	monochromeBitmapSampling: Sampling.NONE,
	omitBitmaps: false,
	omitEPS: false,
	omitPDF: false,
	optimizePDF: true,
	pdfColorSpace : PDFColorSpace.RGB,
	pageInformationMarks: false,
	registrationMarks: false,
	standardsCompliance: PDFXStandards.NONE,
	useDocumentBleedWithPDF: false
	});
	}
catch(ex)
	{
	endScript("Unable to create the PDF Preset.");
	return;
	}

if( pdfExPreset )
	{
	doc.exportFile(
		ExportFormat.PDF_TYPE,
		fPDF,
		true,
		pdfExPreset,
		undefined,
		true
		);
	pdfExPreset.remove();
	}

endScript();
};

app.scriptPreferences.enableRedraw = false;
flyingButtons();
app.scriptPreferences.enableRedraw = true;
