/**************************************************************************
*
*  @@@BUILDINFO@@@ 10application-2.jsx 2.0.1.69  25-May-2007
*  Copyright 2006-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.
**************************************************************************/

// The current folder to use for open/save dialogs
app.currentFolder = Folder.myDocuments.absoluteURI;
// file watches
app.fileWatches = [];

app.onNotify = function( reason, shift )
{
    switch( reason )
    {
	    case 'shutdown':
	    {
	        globalBroadcaster.unregisterClient( this );
    	    
	        if( !arguments[1] )
		        this.writePrefs();
	    }
	    break;
	    
	    case 'preferencesDialog':
	    {
	        openPreferencesDialog( arguments[1] );
	    }
	    break;
    }
}

app.open = function()
{
	var f = File (this.currentFolder);
	var files = f.openDlg (localize ("$$$/ESToolkit/FileDlg/Open=Open"),
						     lang.buildFileTypes(), true);
	if (files)
	{
	    var progress = null;
	    
	    if( files.length > 1 )
	    {
            progress = new ProgressBox('');	
            progress.setProgress( 0, files.length );
        }
            
		for (var i = 0; i < files.length; i++)
		{
			f = files [i];

		    if( progress )
		    {
		        progress.setText( f.name );
		        
		        if( !progress.increment(1) )
		            return false;
		    }
		        
			// remember the folder
			this.currentFolder = f.parent ? f.parent.absoluteURI : "/";
			// resolve any alias
			if (f.alias)
			{
				var resolved = f.resolve();
				if (!resolved)
				{
					errorBox( "$$$/ESToolkit/FileDlg/CannotResolve=Cannot resolve alias to file %1", decodeURIComponent( f.name ) );
					return false;
				}
				f = resolved;
			}
			// user selected a file; test if the file has been loaded
			var doc = Document.find( f.absoluteURI );
			
			if (doc)
				doc.activate();
			else if (!Document.load( f ))
			{
			    if( progress )
			        progress.stop();
			        
				return false;
			}
		}
		
		if( progress )
            progress.stop();		
	}
	return true;
}

app.loadPrefs = function()
{
    if( prefs.app.currentFolder.toString() != '' )
    	this.currentFolder = prefs.app.currentFolder.toString();

    if( prefs.app.scriptsFolder.toString() != '' )
    	this.scriptsFolder = prefs.app.scriptsFolder.toString();
    if( !this.scriptsFolder.exists )    	
        this.scriptsFolder = Folder.current.absoluteURI;
}

app.writePrefs = function()
{
	prefs.app.currentFolder = this.currentFolder;
}

app.toFront = function()
{
    var ret = false;
    
    //
	// ask the target to bring myself to front
	//
	if( currentDebugger )
		ret = currentDebugger.toFront();
		
	//
	// try it by myself
	//
	if( !ret )
	    app.bringToFront();
}

// Launch an app and wait till the BT debug queue has been
// established. Return true if the app was launched and is connective.
// Takes an optional launch message.

app.launchTarget = function (target, launchMsg)
{
	// OK if the target is myself or running
	if (target == "estoolkit-2.0")
		return true;

	// Not OK if the app is unknown (should never happen)
	var name = targetMgr.getTargetDisplayName (target);
	if (!name)
		return false;
	
	if (!launchMsg)
		launchMsg = "$$$/ESToolkit/Alerts/Launch=Target %1 is not running.^nDo you want to launch %1?";
	if (!queryBox (launchMsg, name))
		return false;

	// initiate the launch
	if (!BridgeTalk.launch (target))
	{
		errorBox ("$$$/ESToolkit/Alerts/CannotConnect=Cannot connect to target %1!", targetMgr.getTargetDisplayName (target));
		return false;
	}
	// display a non-modal dialog
	var dlg = new Window (
		 "palette {															\
			properties: { closeOnKey:'Escape' },								\
			text: '" + app.title + "',												\
			orientation:'column',													\
			msg:   StaticText { text:'$$$/ESToolkit/Status/Sleeping=Waiting; press ESC to abort...' },\
			cancelBtn: Button { text:'$$$/CT/ExtendScript/UI/Cancel=&Cancel', properties:{name:'cancel'} }			\
			}																		\
		 }");
	dlg.cancel.onClick = function()
	{
		this.parent.aborted = true;
		this.parent.close();
	}
	dlg.onClose = function()
	{
		this.abort=true;
	}
	dlg.aborted = false;
	dlg.center();
	dlg.show();
	
	// Launch this baby; when launched wait for the BT debug queue to run
	var passes = 0;
	while (!dlg.aborted)
	{
		if (BridgeTalk.isRunning (target))
		{
			if (++passes == 1)
				target += "#estk"; 	// app runs, check for BT queue
			else
				break;				// app runs and BT queue is active
		}
		$.sleep (20);
		// returns false on Quit
		if (!app.pumpEventLoop())
		{
			dlg.aborted = true;
			dlg.close();
			return false;
		}
	}
	dlg.onClose = null;
	dlg.close();
	if (dlg.aborted)
	{
		errorBox ("$$$/ESToolkit/Alerts/CannotConnect=Cannot connect to target %1!", targetMgr.getTargetDisplayName (target));
		return false;
	}
	else
		return true;
}

///////////////////////////////////////////////////////////////////////////////
//
// file watches
//

app.onFilesChanged = function( files )
{
	for( var i=0; i<files.length; i++ )
	{
		for( var c=0; c<this.fileWatches.length; c++ )
		{
			if( this.fileWatches[c].file.absoluteURI == files[i].absoluteURI )
				this.fileWatches[c].client.onNotify( 'filechanged', files[i] );
		}
	}
}

app.addFileWatch = function( clientObj, file )
{
	if( clientObj && clientObj.onNotify )
	{
		for( var i=0; i<this.fileWatches.length; i++ )
			if( this.fileWatches[i].client == clientObj && this.fileWatches[i].file.absoluteURI == file.absoluteURI )
				return;
				
		this.fileWatches.push( { client : clientObj, file : file } );
		this.addFileToWatchList( file );
	}
}

app.removeFileWatch = function( clientObj, file )
{
	for( var i=0; i<this.fileWatches.length; i++ )
	{
		if( this.fileWatches[i].client == clientObj && this.fileWatches[i].file.absoluteURI == file.absoluteURI )
		{
			this.fileWatches.splice(i,1);
			this.removeFileFromWatchList( file );
			break;
		}
	}
}

///////////////////////////////////////////////////////////////////////////////
//
// Busy animations
//

var __busyID__ = 0;
var __busyPlaceholder__ = {};

app.startBusyFor = function( busyID )
{
    var imgObj = __busyPlaceholder__[busyID];
    
    if( imgObj )
    {
        imgObj.instance++;
        
        if( imgObj.timer == -1 )
        {
            imgObj.icon      = imgObj.icons[0];
            imgObj.visible   = true;
            imgObj.timer     = app.scheduleTask( 'app.__busystep__(' + busyID + ');', 75, true );
        }
    }
}

app.stopBusyFor = function( busyID )
{
    var imgObj = __busyPlaceholder__[busyID];
    
    if( imgObj )
    {
        imgObj.instance--;
        
        if( imgObj.instance <= 0 )
        {
			if( imgObj.timer != -1 )
				app.cancelTask( imgObj.timer );
            
            imgObj.visible     = false;
            imgObj.timer       = -1;
            imgObj.currentIdx  = 0;
            imgObj.instance    = 0;
        }
    }
}

app.isBusy = function( busyID )
{
    var ret = false;
    
    var imgObj = __busyPlaceholder__[busyID];
    
    if( imgObj )
        ret = imgObj.instance > 0;
        
    return ret;        
}

app.initBusyPlaceholderImage = function( imageObj )
{
    imageObj.visible     = false;
    imageObj.currentIdx  = 0;
    imageObj.timer       = -1;
    imageObj.icons       = new Array;
    imageObj.instance    = 0;

    for( var i=1; i<9; i++ )
        imageObj.icons.push( '#Busyan0' + i );
        
    __busyID__++;        
    __busyPlaceholder__[__busyID__] = imageObj;
    
    return __busyID__;
}

app.__busystep__ = function( id )
{
    var imgObj = __busyPlaceholder__[id];
    
    if( imgObj )
    {
        imgObj.currentIdx++;
        
        if( imgObj.currentIdx > 8 )
            imgObj.currentIdx = 1;

        imgObj.visible      = false;
        var nextImg         = imgObj.icons[imgObj.currentIdx-1];        
        imgObj.icon         = nextImg;
        imgObj.visible      = true;
    }
}
