/**
 * @author $Author: rhorns $
 * @date $DateTime: 2009/03/06 11:12:40 $
 * @version	$Revision: #2 $
 * 
 * ADOBE CONFIDENTIAL
 *
 * Copyright 1997-2007 Adobe Systems Incorporated. All rights reserved.
 *  
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
*/

#include "../shared/dmppanel.jsx"

//-----------------------------------------------------------------------------
//
// Utilities
//
//-----------------------------------------------------------------------------

function ReviewPanelUtilities() {
}

// this is a wrapper that takes care of logging, handling exceptions and return values
ReviewPanelUtilities.callMainFunction = function(entryPointFunction) {
	try {
		// construct a new argument array for the function
		var args = [];
		for(var i = 1; i<arguments.length; i++) {
			args.push (arguments[i]);
		}
	
		// call the entry point function with the remaining arguments
		var result = entryPointFunction.apply(undefined, args);
	} catch (x1) {
		return "<string><![CDATA[<error>" + x1 +  "</error>]]></string>";
	}
	return "<string><![CDATA[" + result +  "]]></string>";
}

//********************************************************************************************
// Utils.fixPathIfNeeded
//
// Windows-specific file path fix
//********************************************************************************************

ReviewPanelUtilities.fixPathIfNeeded = function(pathIn, checkForWindowsOS)
{
	var path = pathIn;
	var validOS = true;
	if(checkForWindowsOS) {
		if(File.fs == 'Windows') 
			validOS = true;
		else
			validOS = false;
	}
	if (RegExp("^file:///").test(path) && validOS) 
	{
		// On Windows, paths of the form 'file:///c:/etc' will fail -- it's that third
		// slash that throws it off. So replace the /// with //. -MJP
		// enabling this code for Mac -roey
		
		// Test if the path is in the form of file:////*. This will happen when file is on an
		// unmapped network drive on Windows. 
		if (RegExp("^file:////").test(path)) {
			path = path.substr(7); // Convert the file path from file:////* to //* so that javascript can understand
		}
		else {
			path = path.substr(0,7) + path.substr(8);
		}
	}
	return path;
}

//********************************************************************************************
// ReviewPanelUtilities.fixVolumeIfNeeded
//
// This is Mac specific. Extendscript has a limitation where, if the name of the local directory
// under the root volume is the same as one of the mounted volumes, then there is no way to 
// uniquely specify the path to a file inside the local directory.
//
// i.e. Assume there is local directory called Transfer under the root volume and it contains
// a file named Illustrator.jsx. Also, there is mounted volume called Transfer. Due to the limitation
// there is no way to create a File object which points to /Transfer/Illustrator.jsx under the
// root volume. ExtendScript always gives priority to the mounted volume if there is a name clash
// and will try to find the file Illustrator.jsx under the mounted volume 'Transfer'.
//
// The fix here is to catch such cases and change the file name such that ExtendScript points 
// to the file on the local file system.
//
// We catch such cases by looking for the file path in the extendScript File object and the file
// path we got from ActionScript.
//
// eg. filePath from AS = file:///Transfer/Illustrator.jsx and
//	   filePath in ES = /Volumes/Transfer/Illustrator.jsx
//
// Here we can see that the filePath in ES was wrongly redirected to the remote file system. The
// way we fix this is by inserting the name of the root volume in between. So if the name
// of the root volume is MacintoshHD, then the returned path will be
// /Volumes/MacintoshHD/Transfer/Illustrator.jsx
//
// It is also possible that user actually referred to the file on the mounted file system. In those cases,
// the file url from ActionScript should be file:///Volumes/... We detect this in the second if loop,
// and prevent any changes to the filePath in ES in such cases.
//
// This shouldn't be a problem on Windows as each remote volume is identified by a separate alphabet.
//********************************************************************************************

ReviewPanelUtilities.fixVolumeIfNeeded = function (path, rootVolumeName) 
{
    var fileAtPath = File (path);
    // 1) We have rootVolumeName. This will be null on windows
    // 2) Check if the ExtenScript path includes a /Volumes in the beginning. If not, then we can ignore
    if (rootVolumeName != 'null' && RegExp("^/Volumes").test(fileAtPath.fsName)) {
    	
    	// Check if the path is in the form of url. This will happen when the path is formed in ActionScript.
    	if (RegExp("^file:///").test(path)) {
	                
	        // Now decide which location should get preference. The remote volume or the local directory under the root volume
	        // If the ActionScript path starts with file:///Volumes, then remote volume should get the preference.
	        if (RegExp("^file:///Volumes").test(path)) {
	             return path;
	        }
	        else {
	              // The user intended to access the local volume
	              // Try to construct a local path
	              var newPath = "/Volumes/"+rootVolumeName+fileAtPath.fullName;
	              // Check if the file exists at that location
	              var newFile = File (newPath);
	              // This is just to be safe.
	              if (newFile.exists)
	              	return newPath;
	        }
	    }
    }
    return path;
}

//********************************************************************************************
// scriptAlert
//
// shows an alert
//********************************************************************************************

var scriptAlert = function(msg)
{
	return ReviewPanelUtilities.callMainFunction(_scriptAlert, msg);
}

var _scriptAlert = function(msg)
{
	alert(msg);
	return "<success />";
}

//********************************************************************************************
// getDocumentList
//
// returns an XML snippet that contains information on the open documents
//********************************************************************************************

var getDocumentList = function () {
	return ReviewPanelUtilities.callMainFunction(_getDocumentList);
}

var _getDocumentList = function () {
	return app.getDocumentsIds();
}

//********************************************************************************************
// getDocument
//
// Get the Indesign document for the specified file path 
// from all open documents. 
//********************************************************************************************
function getDocument(inddFile)
{
	if(!inddFile || !inddFile.exists)
		return null;

	// see if the document is already open...
	var numDocs = app.documents.length;
	for(var i = 0; i < numDocs; i++)
	{
        var d = app.documents[i];
        if (_isDocumentSaved(d) != 'true')
            continue;
            
        var file = d.fullName;
        // document matches if file name matches
        if(file && file.fsName == inddFile.fsName) 
  			return d;
	}
	 
	return null;
}

//********************************************************************************************
// openDocument
//
// Open the Indesign document for the specified file. 
//********************************************************************************************
function openDocument(inddFile, openInUI)
{
	if(!inddFile || !inddFile.exists)
		return null;

	// turn off user interaction.
    var doc = null;
	var userInteractionLevel = app.scriptPreferences.userInteractionLevel;
	app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;

    try 
    {
        doc = app.open(inddFile, openInUI);
    }
	catch (e)
    {
        doc = null;
    }
    finally
    {
        // turn back user interaction.
        app.scriptPreferences.userInteractionLevel = userInteractionLevel;
    }
	return doc;
}

//********************************************************************************************
// getAttachedDevices
//
// Retrieves list of attached devices
//********************************************************************************************

var getAttachedDevices=function(args)
{
    return ReviewPanelUtilities.callMainFunction(_getAttachedDevices, args);
}

var _getAttachedDevices=function(args)
{
    var arguments = new XML(args);
    var deviceType = arguments.@deviceType.toString();
    var type = AttachedDevices.all;
    
    switch (deviceType)
    {
        case 'IOsDevices':
            type = AttachedDevices.ios;
            break;
        
        case 'AndroidDevices':
            type = AttachedDevices.android;
            break;
            
        default:
            break;
    }

    var attDev = app.getAttachedDevices(type);
    var attDevSize = attDev.length;
    var deviceList = new XML('<devices />');
    
    // loop through the devices
    for (i = 0 ; i < attDevSize; i++)	
    {
        var devInfo = attDev[i];
        var device = new XML('<device id="'+devInfo[0]+'" type="'+devInfo[4]+'" viewerReleaseVersion="'+devInfo[7]+'"/>');     
        deviceList.appendChild(device);
    }

    return deviceList.toXMLString();
}

//********************************************************************************************
// sideloadFolio
//
// Side load the folio to specified attached device
//********************************************************************************************

var sideloadFolio=function(args)
{
    return ReviewPanelUtilities.callMainFunction(_sideloadFolio, args);
}

var _sideloadFolio=function(args)
{
    var arguments = new XML(args);
    var deviceId = arguments.@deviceId.toString();
    var folioFile = new File(arguments.@folioPath.toString());
    
    app.sideloadFolio(deviceId, folioFile);    
    return '<success />';
}

//********************************************************************************************
// DigpubVersion.all          // all types
// DigpubVersion.plug-in   // plug-in version 
// DigpubVersion.folio      // folio format version
// DigpubVersion.plist      // plist version
//********************************************************************************************
var getVersion = function(args) {
	return ReviewPanelUtilities.callMainFunction(_getVersion, args);
}

var _getVersion = function(args)
{
    var retval;
	var arguments = new XML(args);
    var pluginFound = false;
    var result;
    try {
        var versionPlugin = app.getDigpubVersion(DigpubVersion.plugin);
        if(versionPlugin){
            pluginFound = true;
        // return only plugin version for now
        retval = new XML('<success />');
        var pluginVersion = versionPlugin;
        var pluginXML = new XML('<pluginVersion id="'+versionPlugin+'"/>');
        retval.appendChild(pluginXML);
        }
        
    } catch (x1) {
    	result = "<error>"+x1+"</error>";
    }
    finally{
        if(!pluginFound)
            result = "<error>PluginNotFound</error>";
        else
             result = retval.toXMLString();
             
        return result;
    }
     
}

//********************************************************************************************
// checkInstanceId
//
// checks if the DocumentID or InstanceID is for the specified document. 
//********************************************************************************************
function checkInstanceId(doc, documentId, instanceId)
{
    if ((!documentId || documentId.length <= 0) && (!instanceId || instanceId.length <= 0))  // if no document ID or instance ID is specified no check is needed.
        return true;
        
    if (documentId && documentId.length > 0)
{
        // 1. check document ID
        var docId = doc.metadataPreferences.getProperty('http://ns.adobe.com/xap/1.0/mm/', 'DocumentID');
        if(docId != null)
            docId = docId.split(':').pop();
        if(docId != null && documentId == docId)
            return true;
    
        // 2. check original document ID
        docId = doc.metadataPreferences.getProperty('http://ns.adobe.com/xap/1.0/mm/', 'OriginalDocumentID');
        if(docId != null)
            docId = docId.split(':').pop();
        if(docId != null && documentId == docId)
            return true;
            
        // 3. check derived document ID
        docId = doc.metadataPreferences.getProperty('http://ns.adobe.com/xap/1.0/mm/', 'DerivedFrom/stRef:documentID');
        if(docId != null)
            docId = docId.split(':').pop();
        if(docId != null && documentId == docId)
        return true;
    }
        
    // 4. check current instance ID
    var curId = doc.metadataPreferences.getProperty('http://ns.adobe.com/xap/1.0/mm/', 'InstanceID');
    if(curId != null)
        curId = curId.split(':').pop();
    if(curId != null && instanceId == curId)
        return true;

    // 5. check all instance ID's in history
    var list = getPreviousIds(doc);
    return isIdInHistory(list, instanceId);
}

function getPreviousIds(doc) {
	var oldIds = [];
	if(doc != null) {
		// Adding the instance id
		var historyCount = doc.metadataPreferences.countContainer('http://ns.adobe.com/xap/1.0/mm/', 'History');
		for( var loop = 1; loop <= historyCount; loop++) {
				var oldId = doc.metadataPreferences.getProperty('http://ns.adobe.com/xap/1.0/mm/', 'History/['+loop+']/stEvt:instanceID').split(':').pop();
				oldIds.push(oldId);
		}
	}
	return oldIds;
}

function isIdInHistory(list, id) {
	var retval = false;
	if(list.length > 0)
	{
		for(var i = 0; i < list.length; i++)
		{
			if(list[i] == id)
			{
				retval = true;
				break;
			}
		}	
	}
	return retval;
}

//********************************************************************************************
// getActiveDocInfo
//
// returns information about the active document.
//********************************************************************************************

var getActiveDocInfo = function () {
 	return ReviewPanelUtilities.callMainFunction(_getActiveDocInfo);
}

var _getActiveDocInfo = function () {
	var doc = app.activeDocument;
 
	var docInfo = new XML('<docInfo><hasFilePath /><isDirty /><filePath/><instanceId /><documentId /></docInfo>');
 	if(doc != null && doc != undefined) {
        var isSaved = _isDocumentSaved(doc);     
        docInfo.hasFilePath.setChildren(isSaved);
        docInfo.isDirty.setChildren((isSaved == 'false' || doc.modified) ? 'true' : 'false');
        if (isSaved == 'true')
        {
            doc.fullName.encoding = "UTF-8";
            docInfo.filePath.setChildren (doc.fullName.fsName);
        }
    
        var instanceId = doc.metadataPreferences.getProperty('http://ns.adobe.com/xap/1.0/mm/', 'InstanceID');
        instanceId = instanceId.split(':').pop();
        docInfo.instanceId.setChildren(instanceId);

        var docId = doc.metadataPreferences.getProperty('http://ns.adobe.com/xap/1.0/mm/', 'DocumentID');
        docId = docId.split(':').pop();
        docInfo.documentId.setChildren(docId);
	}
	return docInfo.toXMLString();
}

//********************************************************************************************
// getActiveDocDimension
//
// returns dimension about the active document.
//********************************************************************************************

var getActiveDocDimension = function () {
 	return ReviewPanelUtilities.callMainFunction(_getActiveDocDimension);
}

var _getActiveDocDimension = function () {
	var doc = app.activeDocument;
 
	var docInfo = new XML('<docSize><resolutionWidth /><resolutionHeight /><islLandscape/><isSinglePage/></docSize>');
 	if(doc != null && doc != undefined) {
        var curMeasurementUnit = app.scriptPreferences.measurementUnit;
        app.scriptPreferences.measurementUnit = MeasurementUnits.points;
        
        var bounds = doc.pages[0].bounds;

        app.scriptPreferences.measurementUnit = curMeasurementUnit;

        var width = bounds[3] - bounds[1];
        var height = bounds[2] - bounds[0];

        docInfo.isSinglePage.setChildren (doc.pages.length == 1 ? 'true' :  'false');
        if (width > height) // resolution width should always be greater than height
        {
            docInfo.resolutionWidth.setChildren(width.toString ());
            docInfo.resolutionHeight.setChildren(height.toString());
            docInfo.islLandscape.setChildren ('true');
        }
        else
        {
            docInfo.resolutionWidth.setChildren(height.toString ());
            docInfo.resolutionHeight.setChildren(width.toString());
            docInfo.islLandscape.setChildren ('false');
        }   
	}
	return docInfo.toXMLString();
}

//********************************************************************************************
// openSourceFile
//
// opens the specified file in UI if found.
//********************************************************************************************

var openSourceFile = function (args) {
 	return ReviewPanelUtilities.callMainFunction(_openSourceFile, args);
}

var _openSourceFile = function (args) {
    var arguments = new XML(args);

    var isOpened = false;
    var instanceId = arguments.@instanceId.toString();
    var documentId = arguments.@documentId.toString();
    var inddFile = new File(arguments.@filePath.toString());
    var doc = getDocument(inddFile);
    if (doc)
    {
        if (!checkInstanceId(doc, documentId, instanceId))
            doc = null;
    }
    else
    {
        // Open document in background and check for instance ID.
        // Only brings it up in UI if instance ID matches.
        doc = openDocument(inddFile, (arguments.@openInUI.toString() == 'true'));
        if (doc)
        {
            if (checkInstanceId(doc, documentId, instanceId))
            {
                isOpened = true;
            }
            else
            {
                doc.close(SaveOptions.NO);
                doc = null;
            }
        }
        else
        {
            return "<error>openFailed</error>";
        }
    }

    if (!doc)
        return "<error>layoutSourceFileMissing</error>";
        
    var docInfo = new XML('<docInfo><docId/><instanceId/><isOpened/></docInfo>');
    if (!instanceId || instanceId.length <= 0)
    {
        instanceId = doc.metadataPreferences.getProperty('http://ns.adobe.com/xap/1.0/mm/', 'InstanceID');
        if(instanceId != null)
            instanceId = instanceId.split(':').pop();
    }
    if (!documentId || documentId.length <= 0)
    {
        documentId = doc.metadataPreferences.getProperty('http://ns.adobe.com/xap/1.0/mm/', 'DocumentID');
        if(documentId != null)
            documentId = documentId.split(':').pop();
    }

    // if user choose to open in UI, bring the document to front;
    // otherwise if the file is opened but user chose to not open in UI, we close the document
    if (arguments.@openInUI.toString() == 'true')
    {
        if (doc)
            app.activeDocument = doc;
    }
    else if (isOpened)
    {
        doc.close(SaveOptions.NO);
        isOpened = false;
    }

    docInfo.instanceId.setChildren(instanceId);
    docInfo.docId.setChildren(documentId);
    docInfo.isOpened.setChildren(isOpened ? 'true' : 'false');
	return docInfo.toXMLString();
}

//********************************************************************************************
// closeSourceFile
//
// closes the specified file in InDesign if it is open.
//********************************************************************************************

var closeSourceFile = function (args) {
 	return ReviewPanelUtilities.callMainFunction(_closeSourceFile, args);
}

var _closeSourceFile = function (args) {
    var arguments = new XML(args);

    var inddFile = new File(arguments.@filePath.toString());
    var doc = getDocument(inddFile);
    if (doc)
        doc.close(SaveOptions.NO);
}

//********************************************************************************************
// generateMiniBundle
//
// exports mini bundle as the specified output file.
//********************************************************************************************

var generateMiniBundle = function (args) {
	return  ReviewPanelUtilities.callMainFunction(_generateMiniBundle, args);
}

var _generateMiniBundle = function (args) {
    var arguments = new XML(args);
    var result = "<success />";
    
    var openSource = (arguments.@openSource.toString() == 'true') ? true : false;
    var openFailed = false,  sourceNotFound = false;
    var closeDoc1 = false, closeDoc2 = false;
    var doc1 = null, doc2 = null;
    
    try
    {
        var inddFile1 = arguments.@vPath.toString().length > 0 ? new File(arguments.@vPath.toString()) : null;
        if (inddFile1)
        {
            doc1 = getDocument(inddFile1);
            if (doc1)
            {
                if (!checkInstanceId(doc1, arguments.@vDocId.toString(), arguments.@vInstanceId.toString()))
                    sourceNotFound = true;
            }
            else if (!doc1 && openSource)
        {
            doc1 = openDocument(inddFile1, false);
            if (doc1)
            {
                closeDoc1 = true;
                    if (!checkInstanceId(doc1, arguments.@vDocId.toString(), arguments.@vInstanceId.toString()))
                    sourceNotFound = true;
             }
            else
            {
                openFailed = true;
                sourceNotFound = true;
            }
        }
        }
        
        if (!sourceNotFound)
        {
            var inddFile2 = arguments.@hPath.toString().length > 0 ? new File(arguments.@hPath.toString()) : null;
            if (inddFile2)
            {
                doc2 = getDocument(inddFile2);
                if (doc2)
                {
                    if (!checkInstanceId(doc2, arguments.@hDocId.toString(), arguments.@hInstanceId.toString()))
                        sourceNotFound = true;
                }
                else if (!doc2 && openSource)
            {
                doc2 = openDocument(inddFile2, false);
                if (doc2)
                {
                    closeDoc2 = true;
                        if (!checkInstanceId(doc2, arguments.@hDocId.toString(), arguments.@hInstanceId.toString()))
                        sourceNotFound = true;
                }
                else
                {
                    openFailed = true;
                    sourceNotFound = true;
                }
            }
        }
        }
   
        if (!sourceNotFound)
        {
            var resolutionWidth = parseInt(arguments.@hWidth.toString());
            var resolutionHeight = parseInt(arguments.@vWidth.toString());
            var resolutionRatio = resolutionHeight/resolutionWidth;
            
            var smoothScrolling =  arguments.@smoothScrolling.toString();
            var flatten = (arguments.@flatten.toString() == 'true');
            
            //  adjust smooth scrolling & flatten
            if (arguments.@adjustSettings.toString() == 'true')
            {
                var portraitSmooth = false;
                var landscapeSmooth = false;
                if (doc1 && doc1.pages.length == 1)
                {
                    var page = doc1.pages.firstItem();
                    var bounds = page.bounds;
                    var width = bounds[3] - bounds[1];
                    var height = bounds[2] - bounds[0];
                    var pageRatio = width/height;
                    var resolutionRatio = resolutionHeight/resolutionWidth;
                    if (pageRatio < resolutionRatio)
                        portraitSmooth = true;
                    else if (pageRatio == resolutionRatio)
                        portraitSmooth = (smoothScrolling == 'portrait' || smoothScrolling == 'always');              
                }
                if (doc2 && doc2.pages.length == 1)
                {
                    var page = doc2.pages.firstItem();
                    var bounds = page.bounds;
                    var width = bounds[3] - bounds[1];
                    var height = bounds[2] - bounds[0];
                    var pageRatio = height/width;
                    if (pageRatio > resolutionRatio)
                        landscapeSmooth = true;
                    else if (pageRatio == resolutionRatio)
                        landscapeSmooth = (smoothScrolling == 'landscape' || smoothScrolling == 'always');
                }
                if (portraitSmooth && landscapeSmooth)
                    smoothScrolling = 'always';
                else if (portraitSmooth)
                    smoothScrolling = 'portrait';
                else if (landscapeSmooth)
                    smoothScrolling = 'landscape';
                else
                    smoothScrolling = 'never';

                // flatten
                if (smoothScrolling != 'never')
                    flatten = false;
            }
            
            // jpeq quality
            var jpegQuality;
            switch (arguments.@jpegQuality.toString())
            {
                case 'minimum':
                    jpegQuality = DynamicDocumentsJPEGQualityOptions.MINIMUM;
                    break;
                    
                case 'low':
                    jpegQuality = DynamicDocumentsJPEGQualityOptions.LOW;
                    break;
                    
                case 'medium':
                    jpegQuality = DynamicDocumentsJPEGQualityOptions.MEDIUM;
                    break;
                    
                case 'high':
                    jpegQuality = DynamicDocumentsJPEGQualityOptions.HIGH;
                    break;
                    
                case 'maximum':
                    jpegQuality = DynamicDocumentsJPEGQualityOptions.MAXIMUM;
                    break;
             }

            var outFile = new File(arguments.@outputBundle.toString());
            var miniIssueParams = [
                                        ["showprogressbar", (arguments.@showProgressBar.toString()=='true')],   
                                        ["assetformat", arguments.@assetFormat.toString()],   
                                        ["jpegquality", jpegQuality],
                                        ["contentStackID", arguments.@stackId.toString()],
                                        ["narrowdimensions", resolutionHeight],
                                        ["widedimensions", resolutionWidth],
                                        ["isFlattened", flatten],
                                        ["smoothscrollingbehavior", smoothScrolling],
                                        ["targetviewerversion", (arguments.@targetviewerversion.toString())],
                                     ];
            if (arguments.@tocFilePath.toString().length > 0)
                miniIssueParams.push (["tocimagefile", arguments.@tocFilePath.toString()]);
            if (arguments.@fpoAssetsDirectory.toString().length > 0)
                miniIssueParams.push (["fpoassetsdirectory", arguments.@fpoAssetsDirectory.toString()]);
            if (arguments.@cachedAssetsFolder.toString().length > 0)
                miniIssueParams.push (["locationforgeneratedassets", arguments.@cachedAssetsFolder.toString()]);
            if (arguments.@vLayout.toString().length > 0)
                miniIssueParams.push (["portraitlayout", arguments.@vLayout.toString()]);
            if (arguments.@hLayout.toString().length > 0)
                miniIssueParams.push (["landscapelayout", arguments.@hLayout.toString()]);
            if (arguments.@assetFormat.toString() == 'pgt')
            {
                miniIssueParams.push (["rasterformatforpgt", arguments.@htmlRasterFormat.toString()]);
                miniIssueParams.push (["rasterresolution", parseInt(arguments.@htmlResolution.toString())]);
                miniIssueParams.push (["honorpageitemimagesettings", (arguments.@ignorePageItem.toString() != 'true')]);
                if (arguments.@includeAllLayouts.toString() != 'true')
                {
                    var layouts = new Array();
                    var layoutCount = parseInt(arguments.@layoutCount.toString());
                    var index = 0;
                    while (index < layoutCount)
                    {
                        var layoutElement = arguments.attribute('layout' + (++index));
                        layouts.push (layoutElement.toString());
                    }

                    if (layouts.length > 0)
                        miniIssueParams.push(["alternatelayouts", layouts]);
                }
            }
        
            var metaData = [
                                        ["title", arguments.@title.toString()],
                                        ["author", arguments.@author.toString()],
                                        ["kicker", arguments.@kicker.toString()],
                                        ["description", arguments.@description.toString()],
                                        ["tags", arguments.@tags.toString()],
                                        ["isAdvertisement", arguments.@isAds.toString()],
                                        ["hideFromTOC", arguments.@hideTOC.toString()],
                                        ["section", decodeURIComponent(arguments.@section.toString())],
                                    ];    
            
            // For CS6, doc1 & doc2 should be set properly according to selected layout. See bug #3329194 & 3012775.
             if (parseInt(arguments.@apiVersion.toString()) > 7)
                 app.exportArticleFolio(outFile, doc1, doc2, metaData, miniIssueParams); 
            else // CS5 version
                app.exportMiniFolio(outFile, doc1, doc2, metaData, miniIssueParams);
        }
    }
    catch (e)
    {
        result = "<error>" + e +  "</error>";
    }
    finally
    {
        if (closeDoc1)
            doc1.close(SaveOptions.NO);
        if (closeDoc2)
            doc2.close(SaveOptions.NO);
        
        if (openFailed)
            result = "<error>openFailed</error>";
        else if (sourceNotFound)
            result = "<error>layoutSourceFileMissing</error>";
       
       return result; 
    }
}

//********************************************************************************************
// getSupportedViewerVersions
//
// Get the list of viewer versions the digital publishing plugin supports.
//********************************************************************************************

var getSupportedViewers = function (args) {
	return ReviewPanelUtilities.callMainFunction(_getSupportedViewers, args);
}

var _getSupportedViewers = function (args) {
    var resultInfo = app.getSupportedViewerVersions();
    return resultInfo;
}

//********************************************************************************************
// createHtmlMiniBundle
//
// Creates mini bundle as the specified output file from HTML sources.
//********************************************************************************************

var createHtmlMiniBundle = function (args) {
	return ReviewPanelUtilities.callMainFunction(_createHtmlMiniBundle, args);
}

var _createHtmlMiniBundle = function (args) {
    var arguments = new XML(args);
    
    var assets = new Array;
    if (arguments.@vPath.toString().length > 0)
    {
        var vAssets = [
                    ["file", new File(arguments.@vPath.toString())],
                    ["width", parseInt(arguments.@vWidth.toString())],
                    ["height", parseInt(arguments.@hWidth.toString())],
                    ["orientation", "portrait"],
                    ["type", "web"],
                            ];
        if (arguments.@vScrubber.toString().length > 0)
            vAssets.push(["scrubber", new File(arguments.@vScrubber.toString())]);
        assets.push (vAssets);   
    }
    if (arguments.@hPath.toString().length > 0)
    {
        var hAssets = [
                    ["file", new File(arguments.@hPath.toString())],
                    ["width", parseInt(arguments.@hWidth.toString())],
                    ["height", parseInt(arguments.@vWidth.toString())],
                    ["orientation", "landscape"],
                    ["type", "web"],
                            ];
        if (arguments.@hScrubber.toString().length > 0)
            hAssets.push(["scrubber", new File(arguments.@hScrubber.toString())]);
        assets.push (hAssets);
    }

    var miniFolioDescription = [
        ["showprogressbar", (arguments.@showProgressBar.toString()=='true')],   
        ["assets", assets],
        ["contentStackID", arguments.@stackId.toString()],
        ["narrowdimensions", parseInt(arguments.@vWidth.toString())],
        ["widedimensions", parseInt(arguments.@hWidth.toString())],
        ["smoothScrollingBehavior", arguments.@smoothScrolling.toString()],
        ["isFlattened", arguments.@flatten.toString()],
        ["targetviewerversion", arguments.@targetviewerversion.toString()],
        ["metadata",
            [
                ["title", arguments.@title.toString()],
                ["description", arguments.@description.toString()],
                ["author", arguments.@author.toString()],
                ["kicker", arguments.@kicker.toString()],
                ["tags", arguments.@tags.toString()],
                ["isAdvertisement", arguments.@isAds.toString()],
                ["hideFromTOC", arguments.@hideTOC.toString()],
                ["section", decodeURIComponent(arguments.@section.toString())],
                ["isTrustedContent", arguments.@isTrustedContent.toString()],
            ]
        ],
    ];

    if (arguments.@toc.toString().length > 0)
        miniFolioDescription.push (["tocImage", new File(arguments.@toc.toString())]);
    if (arguments.@cachedAssetsFolder.toString().length > 0)
        miniFolioDescription.push (["locationforgeneratedassets", arguments.@cachedAssetsFolder.toString()]);

    // these are additional files to include in the HTML stack that is 
	// referenced from the HTML, but will not appear in the issue manifest.
    var importFolder = new File(arguments.@importFolder.toString());
    var assetDependencies = new Array();
    var assetCount = parseInt(arguments.@assetCount.toString());
    var index = 0;
    while (index < assetCount)
    {
        var assetElement = arguments.attribute('asset' + (++index));
        var assetFile = new File(assetElement.toString());
        // Fix for #3000690: AIR Content Viewer: Android and Desktop: Image doesn't show in HTML stack if the linked image 
        // or linked folder is named with CJK
        // This problem occurs because the URI encoding is conducted twice: CJK file names are URI-encoded when a local cache is 
        // prepared by Folio Builder, then the previewer does URI encoding the '%' char, which eventually provides a wrong file path 
        // to the image. The first URI encoding is redundant. It is File.getRelativeURI() that does implicitly URI encoding for 
        // the local cache file name, so added decodeURIComponent() below. -- samitani
        var assetInfo = [
                ["file", assetFile],
                ["relativePath", decodeURIComponent(assetFile.getRelativeURI(importFolder))],
            ];
        assetDependencies.push (assetInfo);
    }
    
    // insert preview images to be included in the folio
    if (arguments.@vPreview.toString().length > 0)
    {
        var vPreview = new File(arguments.@vPreview.toString());
        var previewInfo = [
                ["file", vPreview],
                ["relativePath", 'previewThumbs/' + vPreview.name],
            ];
        assetDependencies.push (previewInfo); 
    }
    if (arguments.@hPreview.toString().length > 0)
    {
        var hPreview = new File(arguments.@hPreview.toString());
        var previewInfo = [
                ["file", hPreview],
                ["relativePath", 'previewThumbs/' + hPreview.name],
            ];
        assetDependencies.push (previewInfo); 
    }

    if (assetDependencies.length > 0)
        miniFolioDescription.push(["assetDependencies", assetDependencies]);

    //alert('start createCustomMiniFolio');
    app.createCustomMiniFolio(miniFolioDescription, arguments.@outputBundle.toString());      
    //alert('end createCustomMiniFolio');
}

//********************************************************************************************
// isDocumentSaved
//
// This method determines whether the document has an associated file-name
// If not, it returns an error
//********************************************************************************************

var isDocumentSaved = function(doc)
{
	return ReviewPanelUtilities.callMainFunction(_isDocumentSaved, doc);
}
var _isDocumentSaved = function(doc)
{
	try
	{
		var name = doc.fullName;
	}
	catch (e)
	{
		return "false";
	}
	return "true";
}

//********************************************************************************************
// saveDocument
//
// Saves the document at the location specified in the argument
//********************************************************************************************

var saveDocument = function(args)
{
	return ReviewPanelUtilities.callMainFunction(_saveDocument, args);
}
var _saveDocument = function(args)
{
    var arguments = new XML(args);
    var showSaveAsDialog = arguments.@showSaveAsDialog.toString() == 'true';
    
    if(showSaveAsDialog) {
        // we have to invoke the Save As menu action
        const saveAsKey = '$ID/Save &As...';
        var localizedActionName = app.translateKeyString(saveAsKey);
        var action = app.menuActions.itemByName(localizedActionName);
        action.invoke();
    } else {
        // we can simply call save
        app.activeDocument.save();
     }
}

//********************************************************************************************
// getFolderPath
//
// Retrieves a path to a folder
//  Work-around for bug 2851100
//********************************************************************************************

var getFolderPath=function(args)
{
    return ReviewPanelUtilities.callMainFunction(_getFolderPath, args);
}

var _getFolderPath=function(args)
{
	var arguments = new XML(args);
 	
    var retval = new XML('<path><folderPath/></path>');
	var folderSelected = (arguments.@lastSelectedPath.toString()!='' ? 
                                        new Folder (arguments.@lastSelectedPath.toString()).selectDlg(arguments.@title.toString()) : 
                                        Folder.myDocuments.selectDlg(arguments.@title.toString()));
    if (folderSelected) 
        retval.folderPath.setChildren(folderSelected.fsName);
    
	return retval.toXMLString();
}

//********************************************************************************************
// getDocumentLayouts
//
// returns an XML snippet that contains information on the layouts in the given document
//********************************************************************************************

var getDocumentLayouts = function (args) 
{
	return ReviewPanelUtilities.callMainFunction(_getDocumentLayouts,args);
}

var _getDocumentLayouts = function (args) 
{
    var doc = null;
    var result;
    var sourceNotFound = false;
    var closeDoc = false;
    try
    {
        var arguments = new XML(args);
        if(arguments.@fPath.toString().length > 0 )
        { 
            var inddFile = arguments.@fPath.toString().length > 0 ? new File(arguments.@fPath.toString()) : null;
            if (inddFile)
            {
                doc =getDocument(inddFile);
                if (doc)
                {
                    if (!checkInstanceId(doc, arguments.@documentId.toString(), arguments.@instanceId.toString()))
                        sourceNotFound = true;
                }
                else
            {
                doc = openDocument(inddFile, false);
                if (doc)
                {
                    closeDoc = true;
                        if (!checkInstanceId(doc, arguments.@documentId.toString(), arguments.@instanceId.toString()))
                        sourceNotFound = true;
                 }
                else
                {
                    sourceNotFound = true;
                }
            }
        } 
        } 
        else
            doc = app.activeDocument;

        if (sourceNotFound)
            doc = null;
            
        if(doc)
        {
            var layoutInfo = doc.getAlternateLayoutsForFolio();
            var layoutInfoSize = layoutInfo.length;
                    
            var resultXML = new XML('<layouts />');

            // loop through the layouts
            for (var i = 0 ; i < layoutInfoSize; i++)	
            {
                 var layout = layoutInfo[i];
            
                  if (layout)
                  {
                        // Pass name/page#/width/height/nopolicy out. We might pass other info as well. 
                        var layoutName = escape(layout[0]);	     
                        var layoutResult =  new XML('<layout name="'+layoutName+ '" pageNum="' + layout[1] + '" pagewidth="'+layout[2]+'" pageheight="'+layout[3]+'" anypageshavenopolicy="'+layout[7]+'"/>'); 
                        resultXML.appendChild(layoutResult);
                  }
             }
            result = resultXML.toXMLString();
         }
    }
    catch (e)
    {
       result = "<error>" + e +  "</error>";
    }
    finally
    {
        if (closeDoc)
            doc .close(SaveOptions.NO);    
         if (sourceNotFound)
            result = "<error>layoutSourceFileMissing</error>";
        return result;
     }
}


//********************************************************************************************
// cancelTask
//
// cancels the task identified by taskId
//********************************************************************************************

var cancelTask = function(args) {
	return ReviewPanelUtilities.callMainFunction(_cancelTask, args);
}

var _cancelTask = function(args) {
	var arguments = new XML(args);
    var taskId = parseInt(arguments.@taskId.toString());
    var task = app.backgroundTasks.itemByID(taskId);
    task.cancelTask();
    return "<success />";
}
