﻿/*
@@@BUILDINFO@@@ VersionCue.jsx 1.0.0.1 3.1.0.0client51 6-July-2007
*/

/*
@@@START_XML@@@
    <?xml version="1.0" encoding="UTF-8"?>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="en_US">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Enable Version Cue in Bridge and CS3 applications</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="da_DK">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Aktiver Version Cue i Bridge og programmer til CS3</dc:description>
	</ScriptInfo>	
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="de_DE">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Version Cue in Bridge und CS3-Anwendungen aktivieren</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="es_ES">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Activar Version Cue en las aplicaciones Bridge y CS3</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="fi_FI">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Ota Version Cue käyttöön Bridgessä ja CS3-sovelluksissa</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="fr_FR">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Activer Version Cue dans Bridge et les applications CS3</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="it_IT">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Abilita Version Cue nelle applicazioni Bridge e CS3</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="ja_JP">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Version Cue を Bridge および CS3 アプリケーションで有効にする</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="ko_KR">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Bridge 및 CS3 응용 프로그램에서 Version Cue 활성화</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="nl_NL">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Version Cue in Bridge en CS3-toepassingen inschakelen</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="nb_NO">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Aktiver Version Cue i Bridge og CS3-programmer</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="pt_BR">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Ativar o Version Cue em aplicativos Bridge e CS3</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="sv_SE">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>Aktivera Version Cue i Bridge och CS3-program</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="zh_CN">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>在 Bridge 和 CS3 应用程序中启用 Version Cue</dc:description>
	</ScriptInfo>
	<ScriptInfo xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="zh_TW">
		 <dc:title>Adobe Version Cue</dc:title>
		 <dc:description>在 Bridge 和 CS3 應用程式裡啟動 Version Cue</dc:description>
	</ScriptInfo>
@@@END_XML@@@
*/

//------------------------------------------------------------------------------
//	ADOBE SYSTEMS INCORPORATED
//	Copyright 2007 Adobe Systems Incorporated 
//	All Rights Reserved
//	NOTICE: Adobe permits you to use, modify, and distribute 
//			this file in accordance with the terms of the Adobe license 
//			agreement accompanying it. If you have received this file 
//			from a source other than Adobe, then your use, modification, 
//			or distribution of it requires the prior written permission of Adobe.
//------------------------------------------------------------------------------


#target bridge
if ( BridgeTalk.appName == "bridge" ) 
{
	if (app.debugMode)
		$.level = 1;
	else
		$.level = 0;

	if (typeof versioncue != "undefined")
		throw "VersionCue.jsx already run";
	
	
	//----------------------------------------------------------------------------
	// VersionCue Object: The main object where everything that needs to persist is stored at
	//----------------------------------------------------------------------------		
	versioncue = new Object; //we noticed that due to var, on mac this object is getting Gc'ed
	
	versioncue.uri = "bridge:vc:intrinsic://localhost/session/";		// root URI for VC
	
	versioncue.resourcesFolder = new Folder(File ($.fileName).parent + "/resources");
	
	//----------------------------------------------------------------------------
	// VC enablement
	//----------------------------------------------------------------------------
	versioncue.isVCEnabled = function()
	{
		var vcEnabled = true;
		if (File.fs == "Windows")
			settingsPath = Folder.userData;
		else if (File.fs == "Macintosh")
		{
			settingsPath = Folder.userData.parent;
			settingsPath += "/Preferences";
		}
		settingsPath += "/Adobe/Workflow/settings.xml";
		settingsFile = new File(settingsPath);
		settingsFile.open("r:");
		settingsString = settingsFile.read();
		settingsFile.close();
		vcStateIndex = settingsString.indexOf("q:section name=\"state\" on=\"false\"");
		if (vcStateIndex >= 0)
			vcEnabled = false;

		return vcEnabled;
	}
	
	//----------------------------------------------------------------------------
	// localization stuff
	//----------------------------------------------------------------------------
	
	versioncue.getLocaleFilePath = function()
	{
		var pathSpec = versioncue.resourcesFolder.fsName + "/Dictionaries/";
		
	    //let us set locale path
	   	pathSpec += "versioncue_bridge_";
		
		var localeName = app.locale;

		if (localeName.toLowerCase() == "nb_no")
		{
			localeName = "no_no";
		}

		pathSpec += localeName;
		pathSpec += ".zstring";
		return pathSpec;
	}
	// we cache this path once since it never changes
	versioncue.localeFilePath = versioncue.getLocaleFilePath();

	versioncue.getLocalizedString = function( zstring )
	{
		var savePathSpec = undefined;
		var localizedStr = "";
		try
		{
			savePathSpec = app.zStringPathSpecifier;
			app.zStringPathSpecifier = versioncue.localeFilePath;
			localizedStr = localize(zstring);
			app.zStringPathSpecifier = savePathSpec;
			return localizedStr;
		} catch(error)
		{
			if( savePathSpec != undefined )
				app.zStringPathSpecifier = savePathSpec;
		}
		return localizedStr;
	}
	
	versioncue.getLocalizedString_n = function( zstring, arg1, arg2, arg3 )
	{
		var localizedStr = versioncue.getLocalizedString( zstring );
		if( localizedStr != "" )
		{
			try
			{
				//we have got a valid localized string
				if (arg3 != undefined) 
					localizedStr = localizedStr.replace( "(3)" , arg3 );
				if (arg2 != undefined) 
					localizedStr = localizedStr.replace( "(2)" , arg2 );
				if (arg1 != undefined) 
					localizedStr = localizedStr.replace( "(1)" , arg1 );
									
			}catch(error) { Window.alert(error); }
		}
		return localizedStr;
	}
	
	//----------------------------------------------------------------------------
	// Bridge version check
	//----------------------------------------------------------------------------
	versioncue.isBridgeVersionOK = function()
	{
		var bridgeVersion = app.version;
		var versionComponents = bridgeVersion.split(".");
		if ((versionComponents[0] == 2 && versionComponents[1] >= 1) || versionComponents[0] > 2 )
			return true;
		else
			return false;
	}
	
	//----------------------------------------------------------------------------
	// Bridge Update event handler
	// Should not do UI as a startup script since this causes an timer alert
	// also app.document is not defined at this time
	// so create an event handler to pop the alert after the document create event
	//----------------------------------------------------------------------------
	versioncue.bridgeUpdateHandler = function( event )
	{
		try 
		{
			if ((event == undefined) || (event.object == undefined) || (event.type == undefined))
				return {handled:false};
				
			if (event.object instanceof Document && event.type == "create")
			{
				app.eventHandlers.pop( { handler:versioncue.bridgeUpdateHandler } );
				if (versioncue.didUpdateUI == false)
				{
					versioncue.didUpdateUI = true;
					versioncue.popHandleBridgeVersionUpdateUI();
				}
			}
		}
		catch(error) { Window.alert(error); }
		return {handled:false};
	}
	
	//----------------------------------------------------------------------------
	// Bridge Update
	//----------------------------------------------------------------------------
	versioncue.doBridgeUpdate = function()
	{
		try {
		if (app.document != undefined)
			app.document.chooseMenuItem("Updates");
				
		} catch(error) { Window.alert(error); }
	}

	//----------------------------------------------------------------------------
	// Bridge Update dialog
	//----------------------------------------------------------------------------
	versioncue.popHandleBridgeVersionUpdateUI = function( )
	{
		try 
		{
			// Dialog resource definition using the ExtendScript auto layout.
			var dialogDef =  
				"dialog { orientation: 'column', alignChildren: 'fill', text: 'Adobe Version Cue', \
						info: Panel { orientation: 'column', alignChildren: 'center', \
							text: 'Update Action', \
	        				alertText: Group { orientation: 'row', margins: 0, \
								s: StaticText { text:'', properties:{multiline:true} } \
							}, \
						}, \
					buttons: Group { orientation: 'row', \
					firstOp: 	Button { text: 'Update', properties:{name:'firstOp'} }, \
					secondOp: 	Button { text: 'Continue', properties:{name:'secondOp'} }, \
					thirdOp: 	Button { text: 'Quit', properties:{name:'thirdOp'} }, \
					} \
				}";
	
			/* Create a window with resource definition */
			var handleBridgeVersionUpdateUI = new Window(dialogDef);
			
			var displayStr = '$$$/Bridge/VCAdapter/Update_Alert=The Version Cue startup script requires ' +
			'Bridge 2.1 or greater. Clicking the Update button launch the Adobe Updater ' +
			'where you can download and install the latest updates. ' + 
			'Clicking Continue will disable the Version Cue startup script. ' +
			'Clicking Quit will exit Bridge.';

			//support for localization
			handleBridgeVersionUpdateUI.info.alertText.s.text = versioncue.getLocalizedString(displayStr);
						
			handleBridgeVersionUpdateUI.info.text = versioncue.getLocalizedString( "$$$/Bridge/VCAdapter/Update_Action=Update Action" );
			
			handleBridgeVersionUpdateUI.buttons.firstOp.text = versioncue.getLocalizedString( "$$$/Bridge/VCAdapter/Update_Update=Update" );
			handleBridgeVersionUpdateUI.buttons.secondOp.text = versioncue.getLocalizedString( "$$$/Bridge/VCAdapter/Update_Continue=Continue" );
			handleBridgeVersionUpdateUI.buttons.thirdOp.text = versioncue.getLocalizedString( "$$$/Bridge/VCAdapter/Update_Quit=Quit" );

			handleBridgeVersionUpdateUI.layout.layout(true);
			
			// Function handling a click on the "Update" Button.
			handleBridgeVersionUpdateUI.buttons.firstOp.onClick = function()
			{
				// wait some time before trying to do update
				app.scheduleTask("versioncue.doBridgeUpdate()", 60000, false);
				handleBridgeVersionUpdateUI.close(0);
			}

			// Function handling a click on the "Continue" Button.
			handleBridgeVersionUpdateUI.buttons.secondOp.onClick = function()
			{
				handleBridgeVersionUpdateUI.close(0);
			}

			// Function handling a click on the "Quit" Button.
			handleBridgeVersionUpdateUI.buttons.thirdOp.onClick = function()
			{
				if (app.document != undefined)
					app.document.chooseMenuItem("mondo/command/quit");
				handleBridgeVersionUpdateUI.close(0);
			}
	
			handleBridgeVersionUpdateUI.center(); 
			handleBridgeVersionUpdateUI.show();
			return;
	
		} catch(error) { Window.alert(error); }
	}
	
	//----------------------------------------------------------------------------

	//Imp: SDK need to be loaded & unloaded only once
	//This is the global handle to ExternalObject for versioncueSDK.dll
	versioncue.vcSDKHandle = null;
	
	versioncue.isMac = (File.fs == "Macintosh");
	versioncue.isWin = (File.fs == "Windows");
	

	//----------------------------------------------------------------------------
	// Debugging functionality
	//----------------------------------------------------------------------------
	
	versioncue.timeStamp = function ( dateobj ) 
	{
		var year = dateobj.getFullYear();
		var month = dateobj.getMonth() + 1;
		var day = dateobj.getDate();
		var hr = dateobj.getHours();
		var min = dateobj.getMinutes();
		var sec = dateobj.getSeconds();				
		var milliSeconds = dateobj.getMilliseconds();		
		var tz = dateobj.getTimezoneOffset();
		
		//$.writeln(tz);
		var sign = "-";
		if (tz < 0 )
			sign = "+";
		else if( tz == 0 )
			sign = "Z";
				
		tz = Math.abs(tz);
		
		var tzhr = tz / 60;
		var tzmin = tz % 60;
		var iso = String(year) + "-";
		if( month < 10 ) 
			iso += "0";

		iso += month;
		iso += "-";
		if ( day < 10 )
			iso += "0";
		iso += day;
				
		iso += "T";
				
		if( hr < 10 )
			iso += "0";
		iso += hr;
		iso += "_";
		if( min < 10 )
			iso += "0";
		iso += min;
		iso += "_";
		if( sec < 10 )
			iso += "0";

		iso += sec;
		iso += "_m" + milliSeconds;
		return iso;
	}		

	versioncue.debugFile = function( name ) 
	{
		if (false == app.debugMode) return;

		var now		= new Date();
		var nowISO 	= versioncue.timeStamp( now );
		var logsHome	= new Folder( "~/VC.jsx Logs" );
		if( ! logsHome.exists ) 
		{
			var c = logsHome.create();
		}
		this.uname = name + "_" + nowISO; 
		this.logFolder = new Folder( logsHome.fsName + "/" + this.uname);
		this.logFolder.create();
		this.log = new File(this.logFolder.fsName + "/" + "Log.txt");
	}
			
	versioncue.debugLog = function( message ) 
	{				
//		if (false == app.debugMode) return;

		this.log.open("e:");
		this.log.seek(0,2);
	
		var dateobj = new Date();
		var dateobj = new Date();
		var now = versioncue.timeStamp( dateobj );
		this.log.writeln( now + "\t" + message );
		this.log.close();
	}
			
//	versioncue.debugFile( "versioncue.jsx.log" );
//	versioncue.debugLog( "*** VC.jsx Execution Start ***" );

	///////////////////////////////////////////////////////////////////////////////
	// Main logic of script
	///////////////////////////////////////////////////////////////////////////////
	if (!versioncue.isVCEnabled())
	{
		// disable VC favorite
		app.favorites.disable(versioncue.uri);
		
		// and don't do anything else
		
	}
	else if (!versioncue.isBridgeVersionOK())
	{
		versioncue.didUpdateUI = false;
		// set up an event handler to wait for document create before doing UI
		app.eventHandlers.push( {handler:versioncue.bridgeUpdateHandler} );
	}
	else
	{
		versioncue.extensionPath = File ($.fileName).parent;
		versioncue.mainFile = versioncue.extensionPath + "/resources/Scripts/VersionCueMain.jsx";

//		versioncue.debugLog("mainFile: " + versioncue.mainFile );
		
		versioncue.defaultMountRoot = "bridge:fs:file://";
		if (File.fs == "Windows")
			versioncue.defaultMountRoot += "/";
			
		versioncue.defaultMountRoot += Folder.myDocuments.fsName + "/Version Cue";
		versioncue.defaultMountRoot = versioncue.defaultMountRoot.replace(/\\/g, "/");
		versioncue.defaultMountRoot = File.encode(versioncue.defaultMountRoot);
		
//		versioncue.debugLog("defaultMountRoot: " + versioncue.defaultMountRoot );
		
		versioncue.defaultMountRootFSPath = File(Folder.myDocuments + "/Version Cue").fsName;
	
//		versioncue.debugLog("defaultMountRootFSPath: " + versioncue.defaultMountRootFSPath );
		
		vcLightHandler = new ExtensionHandler("vcLightExtensionHandler");
		vcLightHandler.initPrefixes = [
			"bridge:vc:", 
			"instrinsic:", 
			"vcstable:", 
			versioncue.defaultMountRoot, 
			versioncue.defaultMountRootFSPath ];
		
		vcLightHandler.getBridgeUriForPath = function (path)
		{
//			versioncue.debugLog("vcLightHandler.getBridgeUriForPath called, path= " + path );
			
			// getting called means that we need the full VC loaded
			// unregister prefixes from vcLightHandler
			for(var i = 0; i < vcLightHandler.initPrefixes.length; i++)
			{
				app.unregisterPrefix(vcLightHandler.initPrefixes[i], vcLightHandler );
			}
			// unregister vcLightHandler
			app.unregisterExtension(vcLightHandler);

			// load full version cue
			$.evalFile( versioncue.mainFile );

			return "";
		}

		vcLightHandler.getBridgeUriForSearch = function ()
		{
			// don't need to do anything here
		}
		
		// If Version Cue favorite is not defined then load full Version Cue handler so that 
		// favorite can be created.
		// If Version Cue Favorite is defined then use the light weight handler to delay loading
		// of full Version Cue support until the light handler gets a request for a BridgeUri
		if (!app.favorites.contains(versioncue.uri))
		{
			// load full version cue
//			versioncue.debugLog("Version Cue favorite not defined, load full version cue" );
			
			$.evalFile( versioncue.mainFile );
		}
		else
		{
//			versioncue.debugLog("Version Cue favorite defined, register light handler" );
			
			app.favorites.enable(versioncue.uri);
			
			app.registerExtension(vcLightHandler);
			
			for(var i = 0; i < vcLightHandler.initPrefixes.length; i++)
			{
				app.registerPrefix(vcLightHandler.initPrefixes[i], vcLightHandler );
			}
		}		
	}
//	versioncue.debugLog( "*** VersionCue.jsx Execution End ***" );
}
