/**
 * @author $Author: kmattson $
 * @date $DateTime: 2009/02/11 08:02:48 $
 * @version	$Revision: #1 $
 * 
 * ADOBE CONFIDENTIAL
 *
 * Copyright 1997-2009 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.
*/


//-----------------------------------------------------------------------------
//--------  BEGIN   BUG  2334616     -------------------------------------
//-----------------------------------------------------------------------------
//
//
//
// #include "../shared/reviewpanel.jsx"
//
//
//  As per bug#2334616, we can't yet use #include in CSXS, so instead 
//    the contents of it is duplicated below. If you have to change this
//    code before the bug is fixed, please also change reviewpanel-shared.jsx
//    as well as the other apps' scripts
//

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
//
// Refer to reviewpanel-id.jsx for an explanation of this function.
//
//********************************************************************************************

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;
}


//-----------------------------------------------------------------------------
//--------  END   BUG  2334616     -------------------------------------
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
//
// Entry Points
//
//-----------------------------------------------------------------------------

var getCSXSCredentials = function () {
	return ReviewPanelUtilities.callMainFunction(_getCSXSCredentials);
}

function _getCSXSCredentials() {
//	alert('jmork: about to return hardcoded credentials!');
    return '<credentials username="' + emailAddress + '" password="' + password + '" />';
}


//********************************************************************************************
// getEventsSupport
//
// determines whether the application support events to notify of selection and document changes
//********************************************************************************************

var getEventsSupport = function () {
	return ReviewPanelUtilities.callMainFunction(_getEventsSupport);
}

function _getEventsSupport() {
    return "<root><eventsSupported>false</eventsSupported></root>";

}


//********************************************************************************************
// getDocumentList
//
// returns an XML snippet that contains information on the open documents
//
// Notice that for Photoshop we currently don't list all open documents since we are only interested in the active one
//********************************************************************************************

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

var _getDocumentList = function () {
	var list = new XML('<documents />');
	
	// The active sequence becomes the pseude active document

	if (
		(app.project != undefined) &&
		(app.project.activeSequence != undefined) &&
		(app.project.activeSequence.end > 0)
	) {
		list.@activeDocument = app.project.activeSequence.sequenceID;
	}		
	
	// Fetch all the sequences that belong to the currently active project
	var sequences = app.project.sequences;

	var projectName = app.project.name;
	list.@projectName = projectName;
	
	var document;
	var id;
	var name;
	// Loop through all the sequences and store their sequence id and name
	for(var count = 0; count < sequences.numSequences; count++)
	{
        var sequence = sequences[count];
		document = new XML("<document />");
		id = sequence.sequenceID;
		name = sequence.name;
		document.@id = id;
		document.@name = name;
		list.appendChild(document);
	}
	return list.toXMLString();
}

//********************************************************************************************
// getSequenceName
//
// returns name of the active sequence
//********************************************************************************************

var getSequenceName = function () {
	return ReviewPanelUtilities.callMainFunction(_getSequenceName);
}

var _getSequenceName = function () {
	var retval = new XML('<success />');
	retval.appendChild(app.project.activeSequence.name);
	return retval;
}



//********************************************************************************************
// jumpToComment
//
// brings the document to front, goes to the spread and centers the comment in the window
//********************************************************************************************

var jumpToComment = function (args) {
	return ReviewPanelUtilities.callMainFunction(_jumpToComment, args);
}

var _jumpToComment = function (args) {
	var arguments = new XML(args);
	var comment = new XML(arguments.@comment.toString());
	var sequenceId = new XML(arguments.@documentId.toString());

//	make sure that the needed sequence of a project is active

	var result = app.project.openSequence(sequenceId);
	if (Number(comment.@time) <= Number(app.project.activeSequence.end)) {
	    app.project.activeSequence.setPlayerPosition(comment.@time);
		return ("<success />");
	} else {
		return ("<error>LocationNotFoundPR</error>");
	}
}

//********************************************************************************************
// checksIfProjectOpen
//
// checks if the subsequent file-open will lead to the closing of the current project
//********************************************************************************************

var checkIfProjectOpen = function (args) {
	return ReviewPanelUtilities.callMainFunction(_checkIfProjectOpen, args);
}

var _checkIfProjectOpen = function (args) {
	var retval = "<error/>";
	var arguments = new XML(args);
	var path = arguments.@filePath.toString();
	var rootVolume = arguments.@rootVolumeName.toString();
	path = ReviewPanelUtilities.fixPathIfNeeded(path, 1);
	path = ReviewPanelUtilities.fixVolumeIfNeeded(path, rootVolume);
	var myFile = File(path);
	if (myFile.exists) {
		if (!isProjectOpen(path))
		{
			retval = "<error>NeedToOpenNewProject</error>";
		}
		else
		{
			retval = "<success />";
		}
	}
	return retval;
}

//********************************************************************************************
// openFile
//
// Opens the project file associated with the sequence
//********************************************************************************************

var openFile = function (args) {
	return ReviewPanelUtilities.callMainFunction(_openFile, args);
}

var _openFile = function (args) 
{
	var arguments = new XML(args);
	var retval = "<success />";

	// open the file
	var path = arguments.@filePath.toString();
	var sequenceId = arguments.@instanceId.toString();
	var isSameApp = arguments.@sameApp.toString();
	var rootVolume = arguments.@rootVolumeName.toString();
	// Check if the path is NA - this means the user had not saved the project/document.
	// Projects should always have a path. Hence we return error by default as this condition
	// will only be satisfied if isSameApp = false
	if(path == "NA") 
	{
		retval = "<error/>";	
	}
	else
	{
		// First check whether the part originated from Premiere Pro
		// If not, then we can directly skip this action
		if (isSameApp == "true")
		{
			path = ReviewPanelUtilities.fixPathIfNeeded(path, 1);
			path = ReviewPanelUtilities.fixVolumeIfNeeded(path, rootVolume);
			return(openProjectWithSequence(path, sequenceId));
		}
		else
		{
			retval = "<error/>";
		}
	}
	return retval;
}
//********************************************************************************************
// isProjectOpen
//
// Tests whether the project currently open is what we want
// If the project is open, it sets the active sequence to the sequence id
//********************************************************************************************
function isProjectOpen (path)
{
	var retval = false;
	var project = app.project;
	if(project != null && project != 'undefined')
	{	
		var projPath = project.path;
		if(projPath != 'undefined')
		{
			projPath = fixProjectPath(projPath);
		}
		// We cannot compare the paths directly as path variable may be in the form of url
		var file1 = File(projPath);
		var file2 = File(path);
		if(file1.exists && file2.exists && file1.fsName == file2.fsName)
		{
			retval = true;
		}
	} 
	return retval;
}

var openFileAtPath = function (args) 
{
	return ReviewPanelUtilities.callMainFunction(_openFileAtPath, args);
}

var _openFileAtPath = function (args) 
{
	var arguments = new XML(args);
	var retval = "<success />";
	
	var path = arguments.@filePath.toString();
	var rootVolume = arguments.@rootVolumeName.toString();
	path = ReviewPanelUtilities.fixPathIfNeeded(path, 1);
	path = ReviewPanelUtilities.fixVolumeIfNeeded(path, rootVolume);
	var myFile = File(path);
	var isSameApp = arguments.@sameApp.toString();
    if(myFile.exists) {
        if(isSameApp == "true") {
	    	try {
				var sequenceId = arguments.@instanceId.toString();
				var possibleErrorMessage = arguments.@possibleErrorMessage.toString();
				return (openProjectWithSequence(path, sequenceId, possibleErrorMessage ));
	    	}
	    	catch(e) {
	    		
	    	}
	    }
		if(!myFile.execute()) {
        	return ("<error>CannotOpenFile</error>"); 
        }
    }
	else {
		// try to open the file using the url
		retval = "<error/>";
	}
	return retval;
}


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

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

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


//********************************************************************************************
// getGuid
//
// gets GUID of active sequence
//********************************************************************************************

function getGuid() {
	return ReviewPanelUtilities.callMainFunction(_getGuid);
}

function _getGuid() {
	return app.project.activeSequence.sequenceID;
}

// Premiere pro returns the project path in the form of
// '\\?\C:\project\project.prproj'
// These back slashes do not go down well with premiere pro
function fixProjectPath(path) {
	if(File.fs == 'Windows')
	{
		// Replace all backslashes with forward slashes
		path = path.replace (/\\/g, "/");

		// Replace the initial junk characters
		if(path.indexOf('//?/') == 0)
		{
			path = path.substring(4);
			if (path.indexOf('UNC') == 0) {
				path = '/' + path.substring(3);
			}
		}
	}
	return path;
}

//********************************************************************************************
// getActiveDocument
//
// returns an XML snippet that contains information on the currently active document
//********************************************************************************************

var getActiveDocument = function () {
	return ReviewPanelUtilities.callMainFunction(_getActiveDocument);
}

var _getActiveDocument = function () {
    var doc = app.project.activeSequence;
    var document = new XML("<document />");
    document.@name = doc.name;
    var guid = _getGuid();
    if(guid != null) {
        document.@id = guid;
    }
	
	return document.toXMLString();
}



//********************************************************************************************
// generateContentsFromDocument
//
// generates contents, structure and previews of the whole document
//********************************************************************************************

var generateContentsFromDocument = function(args) {
	return ReviewPanelUtilities.callMainFunction(_generateContentsFromDocument, args);
}

var _generateContentsFromDocument = function (args) {
	var generator = new ContentsGenerator();
	var arguments = new XML(args);
	var result = generator.generateContentsOfDocument(app.activeDocument,  ReviewPanelUtilities.fixPathIfNeeded(arguments.@previewFile, 0), 
																		parseInt(arguments.@previewWidth.toString()), 
																		parseInt(arguments.@previewHeight.toString()),  
																		ReviewPanelUtilities.fixPathIfNeeded(arguments.@contentFile, 0),
																		arguments.@docId);
	return result.toXMLString();
}


//-----------------------------------------------------------------------------
//
// ContentsGenerator
//
//-----------------------------------------------------------------------------


//********************************************************************************************
// ContentsGenerator
//
// Generates the contents.xml file for a document
//********************************************************************************************

function ContentsGenerator() {
}

//********************************************************************************************
// 
// generateContentsOfDocument
//
// main function of the contents generator
//********************************************************************************************

ContentsGenerator.prototype.generateContentsOfDocument = function(doc, previewPath, previewWidth, previewHeight, contentPath, docId) {
	this.guid = _getGuid(doc);
	if(this.guid == null) {
		this.guid = docId;
	}
	// initialize properties
	this.contents = new XML('<contents />');
	
	this.parts = new XML('<parts />');
	
	// build the data model
			var partData = new XML('<part />');
			partData.@type = "video";
			partData.@id = this.guid;
			partData.@documentId = this.guid;
			partData.@originalFrameRate = app.project.activeSequence.timebase;
			partData.@zeroPoint = app.project.activeSequence.zeroPoint;

			var videoData = new XML('<video />');
			videoData.@id = this.guid;
			this.parts.appendChild(videoData);

			this.contents.appendChild(partData);
				
			var previewData = new XML('<previews />');
			
			jobId = app.encoder.encodeForCSReview(app.project.activeSequence, contentPath, previewPath, previewHeight, previewWidth, 'PNG');
            
            //force extensions until Premiere honors a path with no extension.
	        previewData.appendChild(new XML('<preview partId="' +  this.guid + '" type="video" thumbnail="' + previewPath + '.png' + '" >' + contentPath + '.f4v' + '</preview>'));
		
			var result = new XML('<result documentId="' + this.guid + '" jobId="' + jobId + '" />');
			result.appendChild(this.contents);
			result.appendChild(this.parts);
			result.appendChild(previewData);
		
			result = this.appendMetadata(result, doc);
	
	return result;
}

/**
 * escapeFilePath enters escape sequences for &, <, "
 * We cannot use these strings as attribute values
 */
function escapeFilePath(filePath) {
	try {
		filePath = filePath.replace(/&/g, "&amp;");
		filePath = filePath.replace(/"/g, "&quot;");
		filePath = filePath.replace(/</g, "&lt;");
		return filePath;
	}
	catch (e) {
		return filePath;	
	}
}

//********************************************************************************************
// 
// appendMetadata
//
// appends metadata to contents xml
 //********************************************************************************************

ContentsGenerator.prototype.appendMetadata = function(data, doc) {
		var result = new XML(data);
		var metadata = new XML('<metadata />');
	try {
		var instanceId = _getGuid();
		var instanceDetails = new XML('<instanceIdAtReview id="'+instanceId+'"/>');
		var projectPath = app.project.path;
		projectPath = fixProjectPath(projectPath);
		projectPath = escapeFilePath(projectPath);
		var path = new XML('<filePath path="' + projectPath + '"/>');
		
		metadata.appendChild (instanceDetails);
		metadata.appendChild (path);
		
		result.appendChild (metadata);
	}
	catch (e) {
	return result;
}
	return result;
}


//-----------------------------------------------------------------------------
//
// Job Management
//
//-----------------------------------------------------------------------------


//********************************************************************************************
// 
// getJobStatus
//
// cancels rendering job
//********************************************************************************************

// jmork: Switchback will use this to get status of a rendering request from Premiere
function getJobStatus( jobId )
{
//	return encoder.getJobStatus( jobId )
}

//********************************************************************************************
// 
// cancelJob
//
// cancels rendering job
//********************************************************************************************

// jmork: Switchback will use this to notify Premiere of a cancellation to a rendering request
function cancelJob(jobId)
{
//	return app.encoder.cancelJob( jobId )
}

//********************************************************************************************
// 
// openProjectWithSequence
//
// open a project and a sequence
//********************************************************************************************

function openProjectWithSequence(path, sequenceId, possibleErrorMessage) {
	var myFile = File(path);
	if (myFile.exists) {
		var projectOpen = isProjectOpen(path);
		if (!projectOpen) {
			// using fsName here. fsName is the full file-system name.
			var result = app.openDocument(myFile.fsName);
			if (! result)
				return ("<error />");
		}	
		// Try to open the sequence for this project
		if (app.project.openSequence(sequenceId))
			return ("<success />")
		else {
			// If the project was already open then we can display an error dialog
			if (projectOpen)
				return ("<error>ProjectOpenSequenceNotFoundPR</error>");
			else {
				if (possibleErrorMessage) {
					alert(possibleErrorMessage);
				}
				return ("<error>SequenceNotFoundPR</error>");
		}
		}
	} else
		return ("<error />");
}


//********************************************************************************************
// getDocumentId
//
// returns the instance id of the document at the path
//********************************************************************************************


var getDocumentId = function (args) {
	return ReviewPanelUtilities.callMainFunction(_getDocumentId, args);
}

var _getDocumentId = function (args)  {
	var retval = new XML('<success />');
	var arguments = new XML(args);
	var path = arguments.@filePath.toString();
	var rootVolume = arguments.@rootVolumeName.toString();
	path = ReviewPanelUtilities.fixPathIfNeeded(path, 1);
	path = ReviewPanelUtilities.fixVolumeIfNeeded(path, rootVolume);
	var instanceId = arguments.@documentId.toString();
	var possibleErrorMessage = arguments.@possibleErrorMessage.toString();
	var result = openProjectWithSequence(path, sequenceId, possibleErrorMessage );
	if (result == "<success />") {
		var original = new XML('<instance id="' + instanceId + '"/>');
		retval.appendChild(original);
		return (retval);
	} 
	else
		return (result);
}

// Constants and variables for handling remote repairs
var INDESIGN = "ID";
var PHOTOSHOP = "PS";
var ILLUSTRATOR = "IL";
var PREMIEREPRO = "PP";
var DREAMWEAVER = "DW";
var TIME_TO_WAIT = 100;
var PARTIAL_SUCCESS_RETVAL = 'partialSuccess';
var FAILURE_RETVAL = 'failure';

var callSourceApplicationToRepair = function(args) {
    return ReviewPanelUtilities.callMainFunction(_callSourceApplicationToRepair, args);
}

var _callSourceApplicationToRepair = function(args) {
	var retval = '<error />'; 
	var arguments = new XML(args);
    // Store the passed arguments
    var sourceApp = arguments.@appName.toString();
    var docId = arguments.@documentId;
    var fileURL = arguments.@filePath.toString();
    var rootVolume = arguments.@rootVolumeName.toString();
    fileURL = ReviewPanelUtilities.fixPathIfNeeded(fileURL, 1);
    fileURL = ReviewPanelUtilities.fixVolumeIfNeeded(fileURL, rootVolume);
    // Fetch the application specifier for the source app
    var appSpecifier = BridgeTalk.getSpecifier(appNames[sourceApp]);
    
    // Check if the application specifier is valid
    if (appSpecifier != null && appSpecifier != 'undefined') {
    	// Get the status of the host application
        var status = BridgeTalk.getStatus (appSpecifier);
        if (status != 'ISNOTINSTALLED' && status != 'BUSY' && status != 'UNDEFINED') {
        	// The valid status's are - ISNOTRUNNING, IDLE, PUMPING.
        	// Create a bridgetalk object aimed at the necessary app
            var bt = new BridgeTalk;
            bt.target = appSpecifier;
            
            // DreamWeaver has its own custom code to fix the url
		    if (sourceApp == DREAMWEAVER) {
		    	var tempFile = File (fileURL);
		    	bt.body = appScripts[sourceApp] + " repairAssociation('"+fileURL+"', '"+tempFile.fsName+"', '"+PARTIAL_SUCCESS_RETVAL+"', '"+FAILURE_RETVAL+"', '"+docId+"');";
		    }
		    else
            	bt.body = appScripts[sourceApp] + " repairAssociation('"+fileURL+"', '"+PARTIAL_SUCCESS_RETVAL+"', '"+FAILURE_RETVAL+"', '"+docId+"');";

            bt.onResult = function(msg) {
            	// Repair worked :)
                var btResult = msg.body;
                if (btResult != FAILURE_RETVAL)
                {
            		if (btResult != PARTIAL_SUCCESS_RETVAL) {
            			retval = new XML('<success />');
		                var returnId = new XML('<instance id="'+btResult+'"/>');        
		                retval.appendChild(returnId);
	                }
	                else {
	                	retval = '<success />'; 
	                }
            	}
            }
            bt.onReceived = function (msg) {
               // alert ("received");
            }
            bt.onError = function(msg) {
                // alert ("error "+msg.body);
            }
            bt.onTimeout = function (msg) {
                // not sure what to do here. The request can time out because the app took a while to launch.
                // This doesn't necessarily mean that the request won't complete.
                // A solution will be to increase the value of TIME_TO_WAIT so that we do not get false negatives. 
          		// TO-DO.
                // alert ("time out");
            }
            bt.send(TIME_TO_WAIT);
        }
	}
    
    return retval;
}

var repairScriptID = "\
    function repairAssociation(fileURL, partialSuccessMessage, failureMessage) {\
	    var retval = failureMessage;\
	    var output;\
	    var doc = null;\
		var myFile = File(fileURL);\
		try {\
			doc = app.open (myFile);\
		}\
		catch (e) {\
		    if(myFile.execute())\
		    	retval = partialSuccessMessage;\
			else\
				retval = failureMessage;\
		}\
	    if (doc != null) {\
	    	try {\
	        	var instanceId = doc.metadataPreferences.getProperty('http://ns.adobe.com/xap/1.0/mm/', 'InstanceID');\
	        	instanceId = instanceId.split(':').pop();\
	        	retval = instanceId;\
	    	}\
	    	catch (innerE) {\
	    		//  just ensuring that we do not go out\
	    		retval = partialSuccessMessage;\
	    	}\
	    }\
	    return retval;\
    }\
";

var repairScriptPS = "\
    function repairAssociation(fileURL, partialSuccessMessage, failureMessage) {\
	    var retval = failureMessage;\
	    var output;\
	    var doc = null;\
		var myFile = File(fileURL);\
		try {\
			doc = app.open (myFile);\
		}\
		catch (e) {\
		    if(myFile.execute())\
		    	retval = partialSuccessMessage;\
			else\
				retval = failureMessage;\
		}\
	    if (doc != null) {\
	    	try {\
	    		var metadata = new XML(doc.xmpMetadata.rawData);\
				var id = metadata.descendants('xmpMM:InstanceID')[0].toString();\
				retval = id.split(':').pop();\
	    	}\
	    	catch (innerE) {\
	    		//  just ensuring that we do not go out\
	    		retval = partialSuccessMessage;\
	    	}\
	    }\
	    return retval;\
    }\
";

var repairScriptIL = "\
    function repairAssociation(fileURL, partialSuccessMessage, failureMessage) {\
	    var retval = failureMessage;\
	    var output;\
	    var doc = null;\
		var myFile = File(fileURL);\
		try {\
			doc = app.open (myFile);\
		}\
		catch (e) {\
		    if(myFile.execute())\
		    	retval = partialSuccessMessage;\
			else\
				retval = failureMessage;\
		}\
	    if (doc != null) {\
	    	try {\
	    		var metadata = new XML(doc.XMPString);\
				var id = metadata.descendants('xmpMM:InstanceID')[0].toString();\
				retval = id.split(':').pop();\
	    	}\
	    	catch (innerE) {\
	    		//  just ensuring that we do not go out\
	    		retval = partialSuccessMessage;\
	    	}\
	    }\
	    return retval;\
    }\
";

var repairScriptPP = "\
	function fixProjectPath(path) {\
		if(File.fs == 'Windows')\
		{\
			path = path.replace (/\\/g, '/');\
			if(path.indexOf('//?/') == 0) {\
				path = path.substring(4);\
				if (path.indexOf('UNC') == 0) {\
					path = '/' + path.substring(3);\
				}\
			}\
		}\
		return path;\
	}\
	function isProjectOpen(path) {\
		try {\
		var projPath = app.project.path;\
		projPath = fixProjectPath(projPath);\
		var pFile = File(projPath);\
		var nFile = File(path);\
		if(pFile.exists && nFile.exists && pFile.fsName == nFile.fsName)\
			return true;\
		}\
		catch(e) {\
		\
		}\
		return false;\
	}\
    function repairAssociation(fileURL, partialSuccessMessage, failureMessage, docId) {\
	    var retval = failureMessage;\
	    var output;\
		var myFile = File(fileURL);\
		try {\
			if (!isProjectOpen(fileURL)){\
				if (!app.openDocument(myFile.fsName)){\
					if(myFile.execute())\
				    	retval = partialSuccessMessage;\
					else\
						retval = failureMessage;\
				}else{\
					app.project.openSequence(docId);\
				}\
			}\
			else {\
				app.project.openSequence(docId);\
			}\
		}\
		catch (e) {\
		    if(myFile.execute())\
		    	retval = partialSuccessMessage;\
			else\
				retval = failureMessage;\
		}\
        retval = docId;\
	    return retval;\
    }\
";

var repairScriptDW = "\
	function repairAssociation(fileURL, dwURL, partialSuccessMessage, failureMessage, docId) {\
		var retval = failureMessage;\
		if (DWfile.exists(dwURL)) {\
			var doc = dreamweaver.openDocument(dw.convertURIToFilePath(dwURL));\
			if (doc == null || doc == undefined) {\
				if(dreamweaver.openFileInOSDefaultApp(fileURL)) {\
	        		retval = partialSuccessMessage;\
	        	}\
				else {\
					retval = failureMessage;\
				}\
			}\
			else {\
				try {\
					retval = doc.getOpenPathName();\
				} catch (e) {\
					retval = partialSuccessMessage;\
				}\
			}\
		}\
		// return is not supported in DW.\
		//return 'abc';\
	}\
";


// Maintain an array for the app names
var appNames = new Array();
appNames[INDESIGN] = "indesign";
appNames[PHOTOSHOP] = "photoshop";
appNames[ILLUSTRATOR] = "illustrator";
appNames[PREMIEREPRO] = "premierepro";
appNames[DREAMWEAVER] = "dreamweaver";


// Maintain an array for the script which should be executed for a particular product
var appScripts = new Array();
appScripts[INDESIGN] = repairScriptID;
appScripts[PHOTOSHOP] = repairScriptPS;
appScripts[PREMIEREPRO] = repairScriptPP;
appScripts[ILLUSTRATOR] = repairScriptIL;
appScripts[DREAMWEAVER] = repairScriptDW;

