//------------------------------------------------------------------------------
//
// ADOBE SYSTEMS INCORPORATED
// Copyright 2004 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.
//
// $LastChangedRevision: 161 $
//------------------------------------------------------------------------------
$.level = 0;
if ( BridgeTalk.appName == "bridge" )	 {	
	BC_RSS_DEFAULT_FEEDS = [
		'http://rss.adobe.com/events.rss?locale='+$.locale,
		'http://rss.adobe.com/studio.rss?locale='+$.locale,
		'http://rss.adobe.com/exchange.rss?locale='+$.locale
	];


	bridgecenter = {};
		
	// ********** SESSION FUNCS ****************
		bridgecenter.saveSession = function(sessionname) {
			var sessions = mydefaults.valueForKey('sessions');
			var name = sessions.length;
			// make sure the name is unique
			for (var i=0; i<name; i++) {		
				if (sessions[i].name.toLowerCase() == sessionname.toLowerCase()) {
					var result = Window.confirm('A Saved File Group with that name exists. Would you like to replace it?');
					if (!result) return;
					name = i;
					break;
				}
			}
			pendingsession.name = sessionname;
			sessions[name] = pendingsession;
			// update the sessions and save the defaults
			mydefaults.setValueForKey(sessions, 'sessions');
			mydefaults.write();
			// redraw the sessions table with js
			var myTaskID = app.scheduleTask('app.document.execJS("loadSessions();writeSessions();boxes[0].updateScrollbar();")', 0, false);
		}



		bridgecenter.getSessionData = function() {		
			// create session object
			pendingsession = new Object();
			pendingsession.date			= new Date().toString();
			pendingsession.photoshop 	= [];
			pendingsession.illustrator	= [];
			pendingsession.golive 		= [];
			pendingsession.indesign 	= [];
	
			// talk to the CS suite apps and get their info
			// since the communication is async, 
			// go through each app, when the return
			// value is recieved, ask the next in line
			// doing this by making a list of the apps and scripts to talk to them
			// and walking through it
			 btmsgs = [
				{
					app:	'photoshop',
					appname: 'Photoshop',
					script:	'allfiles = function(){var output = [];for(var i=0;i<app.documents.length;i++) {var fullName = null;try { fullName = app.documents[i].fullName;} catch (e) {fullName = null;} if (fullName != null) {output.push(app.documents[i].fullName.absoluteURI);} else {output.push("unsaved");}}return output.toSource();}allfiles();'
				},
				{
					app:	'illustrator',
					appname: 'Illustrator',
					script:	'allfiles = function(){var output = [];for(var i=0;i<app.documents.length;i++) {var fullName = null;try { fullName = app.documents[i].fullName;} catch (e) {fullName = null;} if (fullName != null) {output.push(app.documents[i].fullName.absoluteURI);} else {output.push("unsaved");}}return output.toSource();}allfiles();'
				},
				{
					app:	'indesign',
					appname: 'InDesign',
					script:	'allfiles = function(){var output = [];for(var i=0;i<app.documents.length;i++) {var fullName = null;try { fullName = app.documents[i].fullName;} catch (e) {fullName = null;} if (fullName != null) {output.push(app.documents[i].fullName.absoluteURI);} else {output.push("unsaved");}}return output.toSource();}allfiles();'
				},
				{
					app:	'golive',
					appname:'GoLive',
					script:	'allfiles = function(){var output = [];for(var i=0;i<documents.length;i++) {if(documents[i].file!=null)output.push(documents[i].file.absurl);}return output.toSource();}allfiles();'
				}
			];

			var btclose = [
				{
					app:	'photoshop',
					script:	'while(app.documents.length) {app.activeDocument.close();}'
				},
				{
					app:	'illustrator',
					script:	'while(app.documents.length) {app.activeDocument.close();}'
				},
				{
					app:	'indesign',
					script:	'while(app.documents.length) {app.activeDocument.close();}'
				},
				{
					app:	'golive',
					script:	'while(documents.length) {document.close();}'
				}
			];


			
			btmsgs.current = 0;						// counter for current app
			btmsgs.bt = new BridgeTalk;				// bt msg object
			btmsgs.bt.parent = btmsgs;
			btmsgs.bt.onError = function(msg) {		// error func
				bridgecenter.throwError(msg.body);
			}
			
			btmsgs.next = function() {
				if (this.current == this.length) {
					this.finish();
					return;
				}
				var me = this[this.current];
				this.current++;
				if (BridgeTalk.isRunning(me.app)) {
					this.bt.target = me.app;
					this.bt.body = me.script;
					var par = this.parent;
					this.bt.onResult = function(msg) {
						pendingsession[me.app] = eval("("+msg.body+")");
						for (var i=0; i<pendingsession[me.app].length; i++) {
							if (pendingsession[me.app][i] == 'unsaved') {
								pendingsession[me.app].splice(i,1);
								pendingsession[me.app].unsaved = true;
							}
						
						}
						this.parent.next();
					}
					this.bt.send();
				} else {
					this.next();
				}

			}

			btmsgs.finish = function() {
				// total up the items
				var t = 0;
				var unsaved = false;
				var unsavedmsg = [];
				for (var i=0; i<this.length; i++) {
					t += pendingsession[this[i].app].length;
					if (pendingsession[this[i].app].unsaved) {
						pendingsession[this[i].app].unsaved = false;
						unsaved = true;
						unsavedmsg.push(this[i].appname);
					}
				}
				if (unsaved) {
					Window.alert(unsavedmsg.join(' and ') + ' had unsaved documents.\n All unsaved documents were skipped.\n');
				}
				if (t == 0) {
					Window.alert("There are no open documents.");
					return;
				}
				pendingsession.totalitems = t;

				// display the prompt
				var display = '';
				// get ps
				display = (pendingsession.photoshop.length)?'\n'+pendingsession.photoshop.length+' Photoshop file(s)':'';
				// get ai
				display += (pendingsession.illustrator.length)?'\n'+pendingsession.illustrator.length+' Illustrator file(s)':'';
				// get id
				display += (pendingsession.indesign.length)?'\n'+pendingsession.indesign.length+' InDesign file(s)':'';
				// get gl
				display += (pendingsession.golive.length)?'\n'+pendingsession.golive.length+' GoLive file(s)':'';

				var name = prompt("Enter file group name. (64 Character Max).\r" + display);
				if (!name) return;
				while (name.length > 64) {
					name = prompt("The name you entered was too long, enter a new file group name:\r" + display);
				}
				bridgecenter.saveSession(name);
				
				
				// ----------------------------
				// close all open files
				for (var i=0; i<btclose.length; i++) {
					var btcls = new BridgeTalk;
					btcls.onError = function(msg) {		// error func
						bridgecenter.throwError(msg.body);
					}
					var me = btclose[i];
					if (BridgeTalk.isRunning(me.app)) {
						btcls.target = me.app;
						btcls.body = me.script;
						btcls.send();
					}	
				}
				
				
			}
			
			// start it up
			btmsgs.next();
	
		}
	
		bridgecenter.loadSessions = function() {
			var sessions = mydefaults.valueForKey('sessions');
			return sessions.toSource();
		}
	
		bridgecenter.openSession = function(id) {
			var session, i, prop;
			session = mydefaults.valueForKey('sessions')[id];
			for (prop in session) {
				if (prop == 'date' || prop == 'name' || prop == 'totalitems') continue;
				for (i=0; i<session[prop].length; i++) {
					eval(prop).open(new File(File.decode(session[prop][i])));
					eval(prop).reveal(new File(File.decode(session[prop][i])));
				}
			}
		}

		bridgecenter.removeSession = function(id) {
			var sessions = mydefaults.valueForKey('sessions');
			sessions.splice(id,1);
			
			// update the sessions and save the defaults
			mydefaults.setValueForKey(sessions, 'sessions');
			mydefaults.write();

			// redraw the sessions table with js
			var myTaskID = app.scheduleTask('app.document.execJS("loadSessions();writeSessions();")', 0, false);
		}
	

	// ********** RSS ****************
		bridgecenter.addRSSFeed = function(url) {
			var rssfeeds = mydefaults.valueForKey('rssfeeds');
			rssfeeds.push(url);
	
			// update the rss feeds and save the defaults
			mydefaults.setValueForKey(rssfeeds, 'rssfeeds');
			mydefaults.write();
			
			// tell JS to rewrite rss loader
			var myTaskID = app.scheduleTask('app.document.execJS("reloadRSS()")', 0, false);
		}
	
		bridgecenter.removeRSSFeed = function(url) {
			var rssfeeds = mydefaults.valueForKey('rssfeeds');
			// find one to kill
			for (var i=0; i<rssfeeds.length; i++) {
				if (rssfeeds[i] == url) {
					rssfeeds.splice(i,1);
				}
			}
			// update the sessions and save the defaults
			mydefaults.setValueForKey(rssfeeds, 'rssfeeds');
			mydefaults.write();
			var myTaskID = app.scheduleTask('app.document.execJS("reloadRSS();")', 0, false);
		}
	

		bridgecenter.setRefresh = function(time) {
			// update and save the defaults
			mydefaults.setValueForKey(time, 'rssrefresh');
			mydefaults.write();
		}

	
		bridgecenter.loadRefresh = function() {
			return mydefaults.valueForKey('rssrefresh');
		}

		bridgecenter.loadRSSFeeds = function() {
			var rssfeeds = mydefaults.valueForKey('rssfeeds');

			// join with double spaces, since it isn't a valid character
			var adobe = BC_RSS_DEFAULT_FEEDS.join('  ');
			var feeds = (rssfeeds.length > 0)?rssfeeds.join('  '):'';

			return adobe + '    ' + feeds;
		}
		
		bridgecenter.setRSSToggleState = function(state) {
			// update and save the defaults
			mydefaults.setValueForKey(state, 'rssstate');
			mydefaults.write();
		}

		bridgecenter.getRSSToggleState = function() {
			return mydefaults.valueForKey('rssstate');
		}
	
		
		bridgecenter.setSkipRSSKill = function(url) {
			// update and save the defaults
			rsskill.push(url);
			mydefaults.setValueForKey(rsskill, 'rsskill');
			mydefaults.write();
		}

		bridgecenter.getSkipRSSKill = function() {
			var skip =  mydefaults.valueForKey('rsskill');
			return skip.join('  ');
		}
	
		
		
	// ********** MISC ****************
		// counts number of files in a directory
		bridgecenter.getFileCountForDirectory = function(dir) {
			var f = new Folder(dir);
			var files = f.getFiles();
			return files.length;
		}

		// checks that a thumbnail is non-0 btyes
		bridgecenter.checkForThumbnail = function(path) {
			var f = new File(path);
			if (f.length < 0) {
				return '_media/defaulticon.png';
			} else {
				return "file://"+path;
			}
		}
		
		bridgecenter.getLocale = function() {
			return $.locale;
		}

	
	// ********** ERROR FUNC ****************
		bridgecenter.throwError = function(msg) {
			bridge.executeScript('Window.alert("'+msg+'")');
		}
	
	
	
	
	//----------------------------------------------------------------------- 
	// Install Callbacks

	bridgecenter.urlFilter = function(url)
	{
		if (url.search(/stockphoto:.+/) != -1)
		{
			url = "startpage:reveal=" + url.match(/stockphoto:.+/);
		}
		return url;
	};

	bridgecenter.handler = function(event) {
		if
		(
			(event.object instanceof Thumbnail) &&
			(event.type == "open") &&
			(event.object.path == "bridge://startpage")
		)
		{
			event.document.visitUrl = bridgecenter.urlFilter;
			event.document.jsFuncs = {
				saveSession: 	bridgecenter.saveSession,
				loadSessions: 	bridgecenter.loadSessions,
				addRSSFeed: 		bridgecenter.addRSSFeed,
				setRefresh: 	bridgecenter.setRefresh,
				loadRefresh: 	bridgecenter.loadRefresh,
				removeRSSFeed: 	bridgecenter.removeRSSFeed,
				loadRSSFeeds: 	bridgecenter.loadRSSFeeds,
				openSession: 	bridgecenter.openSession,
				getSessionData: 	bridgecenter.getSessionData,
				removeSession: 	bridgecenter.removeSession,
				getFileCountForDirectory: 	bridgecenter.getFileCountForDirectory,
				getRSSToggleState: 	bridgecenter.getRSSToggleState,
				setRSSToggleState: 	bridgecenter.setRSSToggleState,
				checkForThumbnail: 	bridgecenter.checkForThumbnail,
				setSkipRSSKill: 	bridgecenter.setSkipRSSKill,
				getSkipRSSKill: 	bridgecenter.getSkipRSSKill,
				getLocale:			bridgecenter.getLocale

			};
		}
		return { handled: false };
	};
	
	app.eventHandlers.push( { handler: bridgecenter.handler } );
	





//----------------------------------------------------------------------- 
	// user defaults object
	// encapulates the preferences system
	bridgecenter.Defaults = function(){
		this.data = false;
		this.read();
	}

	bridgecenter.Defaults.prototype.read = function() {
		this.data = eval('('+app.preferences.startpage+')');
		if (!this.data) {
			this.data = new Object();
		}
		
	
		var rssfeeds = this.valueForKey('rssfeeds');
		if (!rssfeeds.length) {
			//rssfeeds = rssfeeds.concat(BC_RSS_DEFAULT_FEEDS);	
			// update the rss feeds and save the defaults
			rssfeeds = new Array();
			this.setValueForKey(rssfeeds, 'rssfeeds');
			this.write();
		}

		// update refresh in hours
		var rssrefresh = this.valueForKey('rssrefresh');
		if (isNaN(rssrefresh)) {
			this.setValueForKey(4, 'rssrefresh');
			this.write();
		}

		// update state
		var rssstate = this.valueForKey('rssstate');
		if (!rssstate.length) {
			this.setValueForKey('open', 'rssstate');
			this.write();
		}
		
		// reset the list of sites who have not been asked to be removed
		rsskill = new Array();
		this.setValueForKey(rsskill, 'rsskill');
		this.write();


	}

	bridgecenter.Defaults.prototype.setValueForKey = function(value, key) {
		this.data[key] = value;
	}

	bridgecenter.Defaults.prototype.valueForKey = function(key) {
		if (typeof this.data[key] == 'undefined') this.data[key] = new Array();
		return this.data[key];
	}
	
	bridgecenter.Defaults.prototype.write = function() {
		app.preferences.startpage = this.data.toSource();
	}

	// create defaults obj
	mydefaults = new bridgecenter.Defaults();

}