/*
@@@BUILDINFO@@@ st22Init.jsx 466 16-March-2007
*/

/*************************************************************************
*
* ADOBE CONFIDENTIAL
* ___________________
*
*  Copyright 2005 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.
**************************************************************************/
//$.level = 2;

//***********************************************
//***********************************************
//***********************************************
// DATA INITIALIZATION:

var previousSyncMode;

stockphoto.init = { };
stockphoto.init.lazyinited = false;
stockphoto.core =
{
	eventTaskID: 0
};

stockphoto.core.BM_VersionMajor       = 1; // 1.5.0
stockphoto.core.BM_VersionMinor       = 5;
stockphoto.core.BM_VersionVertertiary = 0;
stockphoto.core.version				  = 010500; // 1.5.0

stockphoto.core.installFolderSub      = "Stock Photos CS3";

stockphoto.core.installFolder = "Adobe " + stockphoto.core.installFolderSub;
stockphoto.core.BM_3Version = stockphoto.core.BM_VersionMajor+"."+stockphoto.core.BM_VersionMinor+"."+stockphoto.core.BM_VersionVertertiary;

stockphoto.documents = [ ];

stockphoto.core.util = { };
stockphoto.core.ImageIDs =
{
    // Constants for denoting type of ImageID in use
    MediaID         : 0,
    ASPRefID        : 1
};
stockphoto.core.ImageID = { };
stockphoto.core.ImageID.ID = stockphoto.core.ImageIDs.MediaID;
stockphoto.core.ImageID.ASPRefFilenamePrefix = "";
stockphoto.core.ImageID.ASPRefFilenameSuffix = "";

stockphoto.core.stockphotoNS = "http://ns.adobe.com/StockPhoto/1.0/";
stockphoto.uris = {
    homeScript: 'bridge:script:stockphoto://home',
    home: 'stockphoto://home',
    recentSearchesScript: 'bridge:script:stockphoto://searches/recent',
    recentSearches: 'stockphoto://searches/recent',
    compsScript: 'bridge:script:stockphoto://comps',
    comps: 'stockphoto://comps',
    purchasedScript: 'bridge:script:stockphoto://purchased',
    purchased: 'stockphoto://purchased',
    APDScript: 'bridge:script:APSPhotoDir://root',
    APD: 'APSPhotoDir://root'
};

// ---  Contextual menus ---
stockphoto.core.menu = { selectionInfo: undefined };

// ----------------------------------------
// === Locale dependent data / z-string ===
// ----------------------------------------

// map language-only locales to lang_region
// This is for MAC system Locale. Do not move to Lang-Country module
stockphoto.core.localesTable =
{
	da: "da_DK",
	da_DK: "da_DK",
	de: "de_DE",
	de_DE: "de_DE",
	en: "en_US",
	en_US: "en_US",
	es: "es_ES",
	es_ES: "es_ES",
	fi: "fi_FI",
	fi_FI: "fi_FI",
	fr: "fr_FR",
	fr_FR: "fr_FR",
	it: "it_IT",
	it_IT: "it_IT",
	ja: "ja_JP",
	ja_JP: "ja_JP",
	ko: "ko_KR",
	ko_KR: "ko_KR",
	nb: "nb_NO",
	nb_NO: "nb_NO",
	no: "nb_NO",
	no_NO: "nb_NO",
	nl: "nl_NL",
	nl_NL: "nl_NL",
	pt: "pt_BR",
	pt_BR: "pt_BR",
	sv: "sv_SE",
	sv_SE: "sv_SE",
	zh: "zh_CN",
	zh_CN: "zh_CN",
	zh_TW: "zh_TW"
};

stockphoto.core.consts=
{
	MaxLengthOfKeywordInSearchFolderName: 25,
	MaxLengthOfSearchFolderName: 150,
	MaxLengthOfSearchFolderPath: 200,
	ShoppingCartName:           "st14ShoppingCart.htm",
	MsgAfterDownloadComp:       "MessageAfterDownloadComp",
	MsgAfterAddingImageToCart:  "MessageAfterAddingImageToCart",
	AutoDlImagesAfterCheckout:  "AutoDownloadImagesAfterCheckout",
	ResumeDlsWhenBridgeStarts:  "ResumeDownloadsWhenBridgeStarts",
	AlertDlsOnQuit:             "AlertDownloadsOnQuit",
	MsgDlsInBackground:         "MessageDownloadsInBackground",
	ReadOnlyFolder:				"_rof_",
	comps:                      "comps",
	purchases:                  "purchases",
	recentSearches:             "recentSearches"
};


//***********************************************
//***********************************************
//***********************************************
// FUNCTIONS:

stockphoto.core.isBridge20OrAfter=function()
{
	var vstr1 = ( app.version ).split( " " );
	var vstr2 = ( vstr1[0] ).split( "." );
	if( ( vstr2[0] ).charCodeAt( 0 ) > 49 )
		return( true );
	return( false );
}


// Workaround for Bridge 316 -BEGIN-
stockphoto.init.getDisplayPath=function( thumb, where )
{
	var displayPath, f, g;
	if( thumb == undefined )
	{
		displayPath = "";
	}
	else if( (thumb.displayPath != undefined ) && (thumb.displayPath != "" ))
	{
		displayPath = thumb.displayPath;
	}
	else if( thumb.path != undefined )
	{
		var pathORG, path, kPrefix;

		pathORG = thumb.path;
		if( ( kPrefix = pathORG.indexOf( "bridge:fs:file:///" ) ) >= 0 )
		{
			path = pathORG.substring( kPrefix+18, pathORG.length );
		}
		else
		{
			path = pathORG;
		}
		displayPath = path;
		if( thumb.container == true )
		{
			f = Folder( unescape( path ) );
			if( f != undefined )
			{
				displayPath = f.fsName;
			}
		}
		else
		{
			g = File( unescape( path ) );
			if( g != undefined )
			{
				displayPath = g.fsName;
			}
		}
	}
	else
	{
		displayPath = "";
	}
	return( displayPath )
}

stockphoto.core.Context = function( document )
{
	this.document = document;
	this.id = document.id;
	this.NavInitialized = false;
	this.close = function() { this.document = undefined; };
}

stockphoto.core.getValidLocale = function(useOldNorwegianCode)
{
	var currentLocale;
	if( ( $.locale == undefined )||( $.locale == "" ) )
		 currentLocale = "en_US";
	else currentLocale = stockphoto.core.localesTable[$.locale];
	if (currentLocale == undefined)
	{
		currentLocale = "en_US";
	}
	// switch Norwegian ISO code from nb_NO to no_NO for URL locale parameter
	else if ((useOldNorwegianCode != undefined) && (useOldNorwegianCode) && (currentLocale == "nb_NO"))
	{
	  currentLocale = "no_NO";
	}
	
	return currentLocale;
}

stockphoto.core.getOrigLocale = function(useOldNorwegianCode)
{
	var currentLocale = $.locale;
	
	if( ( currentLocale == undefined )||( currentLocale == "" ) )
		 currentLocale = "en_US";
		
	// switch Norwegian ISO code from nb_NO to no_NO for URL locale parameter
	else if ((useOldNorwegianCode != undefined) && (useOldNorwegianCode) && (currentLocale == "nb_NO"))
	{
	  currentLocale = "no_NO";
	}
	
	return currentLocale;
}




stockphoto.core.isAPDLang = function(sLang)
{
	var sLocales = "en es de fr it";
	
	if( "undefined" != typeof(app.preferences) &&
		"undefined" != typeof( app.preferences.bm_APDLocales ) )
	{
		sLocales = app.preferences.bm_APDLocales;
	}

	return ( sLocales.indexOf( sLang ) != -1 );
}


// Checks whether a change in APD favorite icon placement
// is required. Checks whether we are 
stockphoto.core.isAPDChangeRequired = function()
{
	var sLocale = stockphoto.core.getOrigLocale();
    var sLang = "";
    var bIsAPDChangeRequired = false;
    
    if (undefined != sLocale)
    {
        sLang = sLocale.substr( 0,2 ).toLowerCase();
    }

    var sOriginalSection = app.favorites.section;
    app.favorites.section = 'standard';

    if ( stockphoto.core.isAPDLang(sLang) ^ app.favorites.contains(stockphoto.uris.APDScript) ) 
    {
            bIsAPDChangeRequired = true;
    } 

    app.favorites.section = sOriginalSection;

    return bIsAPDChangeRequired;
}

// sLocale is optional
stockphoto.core.util.getLocaleFolderPath = function(startupPath, filename, sLocale)
{
	if(File.fs == "Macintosh")
	{
		pathSpec = stockphoto.startUpFolderForMac + "/Resources/";
	}
	else
	{
		pathSpec = startupPath + "/../" + stockphoto.core.installFolder+"/Resources/" ;
	}
	
	if (typeof sLocale == "undefined")
	{
		pathSpec += stockphoto.core.getValidLocale();
	}
	else
	{
		pathSpec += sLocale;
	}
	pathSpec += (File.fs == "Macintosh") ? ".lproj" : "";
	pathSpec += "/" + filename;
	return pathSpec;
}

stockphoto.zstringCache = function(filename, sLocale)
{
	this.cache  = { };
	this.filename = filename;
	this.locale = sLocale;

	this.get = function(zstring)
	{
		var key = zstring.slice(0, zstring.indexOf('='));

		if (this.cache[key] == undefined)
		{
			var savePathSpec = app.zStringPathSpecifier;
			var pathSpec = stockphoto.core.util.getLocaleFolderPath("{STARTUP}", this.filename + ".txt", this.locale);
			app.zStringPathSpecifier = pathSpec;
			this.cache[key] = localize(zstring);
			app.zStringPathSpecifier = savePathSpec;
			// stockphoto.log(key + "=" + this.cache[key]);
		}

		return this.cache[key];
	}
  	this.get1Arg = function (zstring, arg1)
  	{
  		var key = zstring.slice(0, zstring.indexOf('='));
  		{
			var savePathSpec = app.zStringPathSpecifier;
  			var pathSpec = stockphoto.core.util.getLocaleFolderPath("{STARTUP}", this.filename + ".txt", this.locale);
  			app.zStringPathSpecifier = pathSpec;
  			this.cache[key] = localize(zstring, arg1);
			app.zStringPathSpecifier = savePathSpec;
  		}
  		return this.cache[key];
  	}
  
  	this.get2Arg = function (zstring, arg1, arg2)
  	{
  		var key = zstring.slice(0, zstring.indexOf('='));
  		{
			var savePathSpec = app.zStringPathSpecifier;
  			var pathSpec = stockphoto.core.util.getLocaleFolderPath("{STARTUP}", this.filename + ".txt", this.locale);
  			app.zStringPathSpecifier = pathSpec;
  			this.cache[key] = localize(zstring, arg1, arg2);
			app.zStringPathSpecifier = savePathSpec;
  		}
  		return this.cache[key];
  	}
}

stockphoto.zc = new stockphoto.zstringCache( "st22Init" );
var zc        = stockphoto.zc;

stockphoto.core.consts.localizedMenuString=[
	/*00*/ zc.get("$$$/StockPhoto/Menu/StockPhotography=Adobe Stock Photos"),
	/*01*/ zc.get("$$$/StockPhoto/Menu/SavedLowRes=Downloaded Comps"),
	/*02*/ zc.get("$$$/StockPhoto/Menu/MyPurchases=Purchased Images"),
	/*03*/ "deprecated03",
	/*04*/ zc.get("$$$/StockPhoto/Menu/RecentSearches=Previous Searches"),
	/*05*/ zc.get("$$$/StockPhoto/Menu/AddToCart=Add to Cart"),
	/*06*/ zc.get("$$$/StockPhoto/Menu/SaveLowResImage=Download Comp"),
	/*07*/ "deprecated07",
	/*08*/ zc.get("$$$/StockPhoto/Menu/SearchPreferences=Search Preferences"),
	/*09*/ zc.get("$$$/StockPhoto/Menu/DownloadPurchasedImages=Download Purchased Images"),
	/*10*/ "deprecated10",
	/*11*/ "deprecated11",
	/*12*/ zc.get("$$$/StockPhoto/Menu/SearchStockPhotos=Search Adobe Stock Photos..."),
	/*13*/ zc.get("$$$/StockPhoto/Menu/ImageDetails=Get Price..."),
	/*14*/ zc.get("$$$/StockPhoto/Menu/LicenseAgreement=License Agreement..."),
	/*15*/ zc.get("$$$/StockPhoto/Menu/gpk3Keywordss=Find Similar/Keywords..."), // Watson 1259517, used to be "Get Keywords..."
];


stockphoto.core.menu.BridgeMenuItems = function()
{
    stockphoto.core.removeMenuElement("HomePageButton15");
    
	this.searchStockPhotos = new MenuElement( "command", stockphoto.core.consts.localizedMenuString[12], "after Search", "HomePageButton15");
	this.searchStockPhotos.enabled   = true;
	this.searchStockPhotos.onEnable  = function ()
	{
		return true;
	}
	this.searchStockPhotos.onDisplay = function ()
	{
		this.enabled = !(app.document.browserMode == "compact");
		return true;
	}
	this.searchStockPhotos.onSelect  = function ()
	{
		stockphoto.displayStartPage();
		return true;
	}

    stockphoto.core.removeMenuElement("DownloadManager");
	this.downloadStatus = new MenuElement( "command", zc.get("$$$/StockPhoto/Menu/DownloadStatus=Download Status"), "at the end of Window", "DownloadManager" );
	this.downloadStatus.enabled   = true;
	this.downloadStatus.onEnable  = function ()
	{
		return true;
	}
	this.downloadStatus.onDisplay = function ()
	{
		this.enabled = !(app.document.browserMode == "compact");
        return true;
	}
	this.downloadStatus.onSelect  = function ()
	{
		var iDocID;
		if (undefined != app.document)
		{
			iDocID = app.document.id; // undefined is valid value for iDocID
		}
		
		// If we're loading for the first time, initialize ASP...
		if (false == stockphoto.init.lazyinited)
		{
			stockphoto.displayStartPage();
		}
		
        stockphoto.DL.Download.DownloadStock(true, false, iDocID, "dl");		
		return true;
	}
}

stockphoto.core.isImageFile = function(thumbnail)
{
	var result = false;

    if (null == thumbnail) { return result; }
   
	// if ((thumbnail.type == "file") ||
	// ((thumbnail.type == "alias") && (thumbnail.aliasType == "file")))
 	// In addition to checking for type 'file' / 'alias', also check if the file type is 'other' AND the file contains
	// valid 'stockPhotoKind' metadata. This particularly happens with temporary Comp files downloaded for GP&K,
	// and also for file paths (not cached by Bridge) sent by Point Products.
    if ( (thumbnail.type == "file") ||
	   ((thumbnail.type == "alias") && (thumbnail.aliasType == "file")) ||
       (("other" == thumbnail.type) && (undefined != thumbnail.stockPhotoKind) && ("none" != thumbnail.stockPhotoKind)) )
	{
		var mimeType = thumbnail.mimeType;
		if ((mimeType == "application/photoshop") ||
		 (mimeType == "application/pdf") ||
		 (mimeType.search(/^image\//) != -1))
		{
			result = true;
		}
		
		if ((mimeType == "image/jpeg") ||
			(mimeType == "image/tiff") ||
			(mimeType == "image/epsf"))
		{ 
			// EPS files
			if ((mimeType == "application/binary") && (thumbnail.hasMetadata == true))
			{
				// Check if it's a stockphoto image
				var sStockPhotoKind = thumbnail.stockPhotoKind;
				if (("undefined" != typeof sKindOfImage)
		              && ("none" != sKindOfImage))
		        {
                    result = true;
                }
			}
        }
	}
	return result;
}

stockphoto.core.removeMenuElement = function ( sID )
{
    if ( (sID != undefined) && (sID != null) && (MenuElement.find(sID) != null) )
    {
        MenuElement.remove( sID );
    }
}

//pass in a filename (full path is ok)
stockphoto.core.util.getExtension = function(srcFilePath)
{
	var file= File(srcFilePath);
	
	var fileName = file.name;
	var fileBaseNameIdx = fileName.lastIndexOf(".");
	if (fileBaseNameIdx <= 0)
	{	
			return ""; //no extension
	}
	else
	{
		return ( fileName.slice(fileBaseNameIdx+1, fileName.length));
	}
}


stockphoto.core.util.getSelectionInfo = function()
{
    // Check if cache for this document+selection is still available
    if (("undefined" != typeof stockphoto.core.getSelectInfoLastDoc)
        && (app.document.id == stockphoto.core.getSelectInfoLastDoc)
        && ("undefined" != typeof stockphoto.core.getSelectInfoData))
     {
        return stockphoto.core.getSelectInfoData;
     }
    
	var result = { stock: 0, comp: 0, purchased: 0, unpurchased: 0 };

	var	selection = app.document.selections;
	var count = selection.length;

    if (count <= 0)
    {
        return result;
    }
    else
    {
        if (count == 1) // Request refresh if there's only one image
        {
            var oThumb = selection[0];
            oThumb.refresh("metadata"); // Request refresh
        }
        
        if (count > 200) { count = 200; }   
    }
    
	for (iter = 0; iter < count; iter ++)
	{
		var	thumbnail = selection[iter];
		
		if (!stockphoto.core.isImageFile(thumbnail))
		{
			iter = count;
			break;
		}
		
		var sKindOfImage = thumbnail.stockPhotoKind; // can be undefined

		with (result)
		{
			switch (sKindOfImage)
			{
				case "comp":
					comp++;
				case "thumbnail":
					stock++;
					unpurchased++;
					break;

				case "purchased":
					stock++;
					purchased++;
					break;

				default:
					iter = count;
			}
		}
	}
	
	var iOriginalCompCount = result.comp;
    var iOriginalPurchasedCount = result.purchased;

	for (property in result)
	{
		result[property] = (result[property] == count);
	}

    if (true == stockphoto.init.lazyinited) // Once st00Core is loaded, add new functionality
    {
        result.inSearchFolder = stockphoto.core.menu.isInFolderHierarchy(selection[0], stockphoto.places.recentSearches);
        result.inCompsFolder = stockphoto.core.menu.isInFolderHierarchy(selection[0], stockphoto.places.comps);
        result.someComps = (0 < iOriginalCompCount);
        result.somePurchased = (0 < iOriginalPurchasedCount);
	}

	// Store for next cache
	stockphoto.core.getSelectInfoLastDoc = app.document.id;
	stockphoto.core.getSelectInfoData = result;
    
	return result;
}

stockphoto.core.menu.thumbnailContextMenu = function()
{
	var	menuID = "before Thumbnail/Open";
	
	this.selectionInfo = undefined;

	// Get Price...
	var GetPriceContextMenuItem = "GetPriceContextMenuItem";
	stockphoto.core.removeMenuElement(GetPriceContextMenuItem);
	this.imgDetail = new MenuElement("command", stockphoto.core.consts.localizedMenuString[13], menuID, GetPriceContextMenuItem);
	this.imgDetail.parObj = this;
	this.imgDetail.onSelect = function()
	{
		if (stockphoto.init.lazyinited == false)
		{
			stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
		}
		
		if (stockphoto.core.init.loadBMScripts())
		{
		
		    if (!stockphoto.places.initialized)
			{	
				stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
			}
			stockphoto.places.addStockItems();
				
//-dbl-		/*B*/ stockphoto.core.burpClearDblClkBuffer( app.document.id ); // contectMenu - GetPrice
			/*B*/ stockphoto.Burp.menuSorce[ app.document.id ] = "contextMenu";    
			/*B*/ stockphoto.Burp.gpkSource ="rtclk"; 
			stockphoto.DL.imgDetail.getPrice( app.document.id );
		}
	}
	this.imgDetail.onDisplay = function()
	{
		this.parObj.selectionInfo = stockphoto.core.util.getSelectionInfo();
		this.enabled = this.parObj.selectionInfo.stock;
	}
	
	// Get Keywords...
	var GetKeywordsContextMenuItem = "GetKeywordsContextMenuItem";
	stockphoto.core.removeMenuElement(GetKeywordsContextMenuItem);
	this.getKeyWds = new MenuElement("command", stockphoto.core.consts.localizedMenuString[15], menuID, GetKeywordsContextMenuItem);
	this.getKeyWds.parObj = this;
	this.getKeyWds.onSelect = function()
	{
		if (stockphoto.init.lazyinited == false)
		{
			stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
		}
		
		if (stockphoto.core.init.loadBMScripts())
		{
		    if (!stockphoto.places.initialized)
			{	
				stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
			}
			stockphoto.places.addStockItems();
		
//-dbl-		/*B*/ stockphoto.core.burpClearDblClkBuffer( app.document.id ); // contectMenu - GetPrice
			/*B*/ stockphoto.Burp.menuSorce[ app.document.id ] = "contextMenu";    
			/*B*/ stockphoto.Burp.gpkSource ="rtclk"; 
			stockphoto.DL.imgDetail.getKeywords( app.document.id );
		}
	}
	this.getKeyWds.onDisplay = function()
	{
		this.parObj.selectionInfo = stockphoto.core.util.getSelectionInfo();
		this.enabled = this.parObj.selectionInfo.stock;
	}

	// License Agreement for Purchased images
	var PurchLicenseContextMenuItem = "PurchLicenseContextMenuItem";
	stockphoto.core.removeMenuElement(PurchLicenseContextMenuItem);	
	this.licenseAgreement = new MenuElement("command", stockphoto.core.consts.localizedMenuString[14], menuID + "-", PurchLicenseContextMenuItem);
	this.licenseAgreement.parObj = this;
	this.licenseAgreement.onSelect = function()
	{
		if (stockphoto.init.lazyinited == false)
		{
			stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
		}
		
		if (!stockphoto.places.initialized)
		{	
			stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
		}
		stockphoto.places.addStockItems();
			
			//Removed ASP initialization
			//-dbl-		/*B*/ stockphoto.core.burpClearDblClkBuffer( app.document.id ); // contectMenu - license
			stockphoto.DL.ShowLicenseAgreement();
	}
	this.licenseAgreement.onDisplay = function()
	{
		this.parObj.selectionInfo = stockphoto.core.util.getSelectionInfo();
		this.enabled = this.parObj.selectionInfo.purchased;
	}

	// License Agreement for Comps
	var CompLicenseContextMenuItem = "CompLicenseContextMenuItem";
	stockphoto.core.removeMenuElement(CompLicenseContextMenuItem);	
	this.licenseAgreementComp = new MenuElement("command", stockphoto.core.consts.localizedMenuString[14], menuID, CompLicenseContextMenuItem);
	this.licenseAgreementComp.parObj = this;
	this.licenseAgreementComp.onSelect = function()
	{
		if (stockphoto.init.lazyinited == false)
		{
			stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
		}

        if (!stockphoto.places.initialized)
		{	
			stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
		}
		stockphoto.places.addStockItems();
		
		//Removed ASP initialization
		/*B*/ stockphoto.Burp.menuSorce[ app.document.id ] = "contextMenu";  	
		stockphoto.DL.ShowLicenseAgreement();
	}
	this.licenseAgreementComp.onDisplay = function()
	{
		this.parObj.selectionInfo = stockphoto.core.util.getSelectionInfo();
		this.enabled = this.parObj.selectionInfo.comp;
	}

	// Download Comp
	var DLCompContextMenuItem = "DLCompContextMenuItem";
	stockphoto.core.removeMenuElement(DLCompContextMenuItem);	
	this.keepComp = new MenuElement("command", stockphoto.core.consts.localizedMenuString[6], menuID, DLCompContextMenuItem);
	this.keepComp.parObj = this;
	this.keepComp.onSelect = function()
	{
		if (stockphoto.init.lazyinited == false)
		{
			stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
		}
		
		if (stockphoto.core.init.loadBMScripts())
		{
		    if (!stockphoto.places.initialized)
    		{	
	       		stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
		    }
		    stockphoto.places.addStockItems();
		
//-dbl-		/*B*/ stockphoto.core.burpClearDblClkBuffer( app.document.id ); // contectMenu - DownloadComp
//-dbl-		/*B*/ stockphoto.Burp.listDlComps( app.document.id, app.document.selections, 0, "rtclk" ); // contextMenu download
/*-dblnew-*//*B*/ stockphoto.Burp.getCompSource[ app.document.id ] = "rtclk"; // contextMenu download
			/*B*/ stockphoto.Burp.menuSorce[   app.document.id ] = "contextMenu";  	
			stockphoto.DL.GetComp.KeepComp(    app.document.id );
			stockphoto.DL.GetComp.KeepComp( app.document.id );
		}
	}
	this.keepComp.onDisplay = function()
	{
		this.parObj.selectionInfo = stockphoto.core.util.getSelectionInfo();
		this.enabled = this.parObj.selectionInfo.unpurchased;
	}
	
	// Add to Cart
	var AddCartContextMenuItem = "AddCartContextMenuItem";
	stockphoto.core.removeMenuElement(AddCartContextMenuItem);	
	this.addToCart = new MenuElement("command", stockphoto.core.consts.localizedMenuString[5], menuID + "-", AddCartContextMenuItem);	// append separator line after this item
	this.addToCart.parObj = this;
	this.addToCart.onSelect = function()
	{
		if (stockphoto.init.lazyinited == false)
		{
			stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
		}
		
		if (stockphoto.core.init.loadBMScripts())
		{
		
    		if (!stockphoto.places.initialized)
    		{	
    			stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
    		}
    		stockphoto.places.addStockItems();
    		
//-dbl-		/*B*/ stockphoto.core.burpClearDblClkBuffer( app.document.id ); // contectMenu - addToCart
			/*B*/ stockphoto.Burp.addCartSource 			   = "rtclk";
			/*B*/ stockphoto.Burp.menuSorce[ app.document.id ] = "contextMenu";  	
			stockphoto.DL.ShoppingCart.AddToCart(app.document.id);
		}
	}
	this.addToCart.onDisplay = function()
	{
		this.parObj.selectionInfo = stockphoto.core.util.getSelectionInfo();
		this.enabled = this.parObj.selectionInfo.unpurchased;
	}

	this.invalidateSelectionInfo = function()
	{
		this.selectionInfo = undefined;
	}
}

stockphoto.findFavoritesItem = function ( sURI, sSection )
{
    var oResult = { thumb: undefined, position: undefined };
    
    if (undefined == sSection)
    {
        sSection = 'standard'; // default value
    }
    if (undefined != sURI)
    {
        var sOriginalSection = app.favorites.section;
        app.favorites.section = sSection;
        
        for (var iFavIter = 0, iFavLen = app.favorites.length; iFavIter < iFavLen; ++iFavIter)
        {
            if ( sURI == app.favorites[iFavIter].uri )
            {
                oResult.thumb = app.favorites[iFavIter];
                oResult.positon = iFavIter;
                break;
            }
        }
        
        app.favorites.section = sOriginalSection;
    }
    return oResult;
}

// Point App APIs
stockphoto.displayStartPage = function( maximize )
{
    if (stockphoto.init.lazyinited == false)
    {
		stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
		stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
   		stockphoto.places.addStockItems();
	    stockphoto.core.BoxCar.NavBar.SetIsCompactFlag( 1, app.document.id, 0 );

		// Now call the actual (redefined) function
        stockphoto.displayStartPage(maximize);
	}
}

stockphoto.buy = function( imageIdList )
{
    if (stockphoto.init.lazyinited == false)
    {
		stockphoto.displayStartPage();
		
		// Now call the actual (redefined) function
        stockphoto.buy(imageIdList);
	}
}

stockphoto.checkLicense = function( imageIdList )
{
    if (stockphoto.init.lazyinited == false)
    {
		stockphoto.displayStartPage();
		
		stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
		
		// Now call the actual (redefined) function
        stockphoto.checkLicense(imageIdList);
	}
}



//*************************************************
// EVENT HANDLER FUNCTIONS
stockphoto.init.startupThumbEvent = function(event)
{
	var target		= event.object
	var type		= event.type;
	var	result		= { handled: false };

	var displayPath = stockphoto.init.getDisplayPath(event.object,"");

	switch (type)
	{
		case "hover":
		{
			if (stockphoto.core.isImageFile(target))
			{
				// %%% needs localization
               var sStockPhotoKind = target.stockPhotoKind;
               if ( ( "undefined" != typeof sStockPhotoKind )
				   && ("none" != sStockPhotoKind) )
			   {
				  var m = target.metadata;
				  if ("undefined" != typeof m)
				  {
					m.namespace = "http://ns.adobe.com/StockPhoto/1.0/";
	 				if ((m.KindOfImage == "Thumbnail") || (m.KindOfImage == "Comp") || (m.KindOfImage == "Purchased"))
					{
						title = m["Media/bmsp:MediaTitle"];
						if (title == undefined)
						{
							title = "";
						}

						supplier = m["Media/bmsp:ProviderName"];
						if (supplier == undefined)
						{
							supplier = "";
						}
						
						// <TODO> The same code is repeated - this should be optimized
						sPartnerName = m["Media/bmsp:PartnerName"];
						if (sPartnerName == undefined)
						{
							sPartnerName = "";
						}
						
						var zc = stockphoto.init.zc;

						var titleStr = zc.get("$$$/EventHandler/ThumbEvent/Titles/Title=Title: ");
						var pathStr = zc.get("$$$/EventHandler/ThumbEvent/Titles/Path=Path: ");
						var providerStr;
						var imageIDStr;
						/* Changes added to show ImageId/ASPRefId */
						if ((stockphoto.core.ImageID.ID == stockphoto.core.ImageIDs.MediaID) || (m.ASPRefID == undefined)
							|| (m.ASPRefID == "") || (m.ASPRefID == m.MediaID))
						{
							imageIDStr = zc.get("$$$/EventHandler/ThumbEvent/Titles/ImageID=Image ID: ");
							providerStr = zc.get("$$$/EventHandler/ThumbEvent/Titles/Provider=Provider: ");
                            hoverText = imageIDStr + m.MediaID + "\n" + titleStr + title + "\n" + providerStr + supplier;							
						}
						else
						{
						//	imageIDStr = zc.get("$$ $/EventHandler/ThumbEvent/Titles/AdobeID=Adobe ID: ");
							imageIDStr = "Adobe ID: ";
							providerStr = "";
							hoverText = imageIDStr + m.ASPRefID + "\n" + titleStr + title + "\n" + providerStr + "Adobe Stock Photos";
						}
						
	 					
						var displayPath = stockphoto.init.getDisplayPath(event.document.thumbnail,"");
						if (displayPath.split(':', 1)[0] == "bridgesearch")
						{
							hoverText += "\n" + pathStr + target.path;
						}
						result =
						{
							handled: true,
							tipText: hoverText
						};
						return result;
					}
				   } // if ("undefined" != typeof m)
				}		
			}
			break;
		}
		case "openwith":
		case "open":
		{
			if ((target.path).substr(0, 11) == "stockphoto:")
			{
				if (stockphoto.init.lazyinited == false)
				{
					stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
				}
				
                if (!stockphoto.places.initialized)
				{	
					stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
				}
				stockphoto.places.addStockItems();
				
				return stockphoto.core.doThumbEvent(event);
			}
			else if ((target.path).substr(0, 12) == "APSPhotoDir:")
			{
                if (stockphoto.init.lazyinited == false)
				{
					stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
  			    }
	            if (!stockphoto.places.initialized)
				{	
					stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
				}
				stockphoto.places.addStockItems();
  			    return stockphoto.core.doThumbEvent(event);
            } else if ( ! target.container )  // GP&K
            {
                var sTargetPath = target.path;
                var sKind = target.stockPhotoKind;
                
                if ( ("undefined" != typeof sKind) && ( ('thumbnail' == sKind) || ('comp' == sKind) )
                    && ("filesystem" == target.displayMode) && (0 != sTargetPath.indexOf('http://')) && (0 != sTargetPath.indexOf('https://') ) )
				{
				    // Should open GP&K
				    if (stockphoto.init.lazyinited == false)
		            {
			             stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
		            }
		
		            if ( !stockphoto.places.initialized && stockphoto.core.init.loadBMScripts() )
		            {
	   	    			 stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
						 stockphoto.places.addStockItems();
						
                         var sDisplayPath = stockphoto.core.util.getDisplayPath( event.object, "" );
                         var sKindOfImage = ('thumbnail' == sKind)?"Thumbnail":"Comp";
			             switch( stockphoto.core.checkDblClick.doit( event.document.id, target, sDisplayPath, true, sKindOfImage ) )
						 {
							case 1:  app.scheduleTask( "stockphoto.gpk3.getPrice3ByOpen("+event.document.id+");", 10, false );
							case 2:  result.handled = true;
							default: break;
						 }
						
			        }
		        }
            }
			break;
		}		
	}
	return result
}

// Minimal Doc Event Handler
stockphoto.init.startupDocEvent = function(event)
{
	var result = { handled: false };
	
	if (event != undefined)
	{
		var doc = event.object;
		var type = event.type;

		// Make sure the stockphotos.documents[] array is in sync
		if ((type != undefined) && (doc != undefined) && (doc.id != undefined))
		{
			switch (type)
			{
				case "close":
				case "destroy":
					if (stockphoto.documents[doc.id] != undefined)
					{
						delete stockphoto.documents[doc.id];
						stockphoto.documents[doc.id] = undefined;
					}
					break;
				case "selectionsChanged":
                {
                    // Invalidate the getSelectInfo() cache
                    stockphoto.core.getSelectInfoLastDoc = undefined;
                    stockphoto.core.getSelectInfoData = undefined;
                    stockphoto.core.getASPImagesCountData = undefined;
                }
                break;
				case "create":
				    { 
                       //  doc.visitUrl = stockphoto.init.URLFilter;
                        // no break
                    }
				default:
					if (stockphoto.documents[doc.id] == undefined)
					{
						stockphoto.documents[doc.id] = new stockphoto.core.Context( doc );
					}
			}
		}
  	}
  	
  	return result;
}

// Minimal Preferences Event Handler
stockphoto.init.startupPrefsEvent = function(event)
{
	var result = { handled: false };
    
    if (event != undefined)
	{
        var type = event.type;
        var target = event.object
        
        if ((type != undefined) && (target != undefined))
        {
            switch (type)
            {
                case "create":
                {
                    if (stockphoto.init.lazyinited == false)
			        {
				       stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
			        }
			        
                    stockphoto.core.init.loadBMScripts(true);
                    stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
			       	 stockphoto.DL.preference(target.addPanel("Adobe Stock Photos"));
			        break;
                }
            }
        }
    }
    
    return result;
}

// stockphoto.aspExtHandler = new ExtensionHandler("aspExtHandler");
// stockphoto.aspExtHandler.getBridgeUriForPath = function(path)
// {
	// alert("getBridgeUriForPath: " + path);
	
//	return undefined;
// }

// app.registerExtension(stockphoto.aspExtHandler);

stockphoto.init.startupEventHandler = function( event )
{
	var result = { handled: false };
	var target = event.object;
	var sLocation = event.location;

//$.level = 2;

	if (stockphoto.init.lazyinited)
		return result;

    // Thumbnail events
    if ( (('document' == sLocation) || ('favorites' == sLocation))
        && (target instanceof Thumbnail) )
	{
		return stockphoto.init.startupThumbEvent(event);
	}
	// App events
	else if ( ('app' == sLocation) && (target instanceof App) )
	{
		; // Do nothing for App events right now...
	}
	// Document events
	else if ( (('app' == sLocation) || ('document' == sLocation) || ('web' == sLocation))
            && (target instanceof Document) )
	{
		return stockphoto.init.startupDocEvent(event);
	}
	// PreferencesDialog events
	else if (( 'prefs' == sLocation) && (target instanceof PreferencesDialog) )
	{
		return stockphoto.init.startupPrefsEvent(event);
	}

	return result;
}

//***********************************************
//***********************************************
//***********************************************
//EXECUTED CODE:

stockphoto.init.zc = new stockphoto.zstringCache("eventHandler");

stockphoto.browseScheme = {};
stockphoto.browseScheme.sessionUrl = undefined;
stockphoto.core.menu.thumbContextMenuObj = new stockphoto.core.menu.thumbnailContextMenu;

app.registerBrowseScheme( "stockphoto" );
app.registerBrowseScheme( "APSPhotoDir" );

if ('undefined' == typeof stockphoto.core.bridgeMenuItems)
{
	stockphoto.core.bridgeMenuItems = new stockphoto.core.menu.BridgeMenuItems();
}

var bNeedToInitASP = false;

// If ASP favorite item is already there in Bridge favorites (cached),
// then we just need to set our init event handler
app.favorites.section = "standard";
if (! app.favorites.contains(stockphoto.uris.homeScript) )
{
    bNeedToInitASP = true;
}
else
{
    // Check if reloading scripts is required..
    var oASPHomeFavItem = stockphoto.findFavoritesItem( stockphoto.uris.homeScript );
    if (undefined != oASPHomeFavItem.thumb)
    {
        if (undefined == oASPHomeFavItem.thumb.displayMode) // override only if already not cached...
        {
            oASPHomeFavItem.thumb.displayMode = 'web';
        }
        if (undefined == oASPHomeFavItem.thumb.displayPath) // override only if already not cached...
        {
            if (undefined != app.preferences.bm_ASPHomeURL)  // Load the ASP's cached URL..
            {
                oASPHomeFavItem.thumb.displayPath = app.preferences.bm_ASPHomeURL;
            }
            else
            {
                bNeedToInitASP = true;
            }
        }
    }
    else
    {
        bNeedToInitASP = true;
    }
    
     if ( (undefined == app.preferences.bm_PrevLocale)
       || (app.preferences.bm_PrevLocale != stockphoto.core.getValidLocale())
		||((undefined == app.preferences.bm_PrevBillingRegion)
		||(app.preferences.bm_PrevBillingRegion != app.preferences.bm_billing_region))
		)
    {
		if(undefined == app.preferences.bm_PrevBillingRegion)
		{
			if(undefined != app.preferences.bm_billing_region)
			{
				app.preferences.bm_PrevBillingRegion = app.preferences.bm_billing_region;
			}
			else
			{
				app.preferences.bm_PrevBillingRegion = 'US';
			}
		}
		else
		{
			// alert('Need to Init ASP. Language does not match...');
        	bNeedToInitASP = true;
        }
    }
}

// Additional checks for Second-level folders
if ( (app.preferences.target == stockphoto.uris.homeScript )
	&& (! app.favorites.contains(stockphoto.uris.recentSearchesScript)
	|| ! app.favorites.contains(stockphoto.uris.compsScript)
	|| ! app.favorites.contains(stockphoto.uris.purchasedScript) ) )
{
	bNeedToInitASP = true;
}

// Check for APD
if (true == stockphoto.core.isAPDChangeRequired())
{
    bNeedToInitASP = true;
}

// Finally, check if we need to initialize ASP at this point...
// If Favorite-caching works, and Bridge's locale didn't change since last start,
// ASP won't be init-ed here...
if (true == bNeedToInitASP)
{
    if (stockphoto.init.lazyinited == false)
    {
		stockphoto.loadScript(stockphoto.paths.scripts + "/st00Core.jsx");
	}
	// app.registerPrefix("stockphoto:", stockphoto.aspExtHandler);
	
	stockphoto.core.removeASPNode(true, false);
	
	stockphoto.core.init.initializeBM( new Thumbnail(stockphoto.uris.home, "Adobe Stock Photos") );
    stockphoto.places.addMainStockFavs();
    stockphoto.places.addStockItems();
}
else
{
    app.eventHandlers.push( { handler: stockphoto.init.startupEventHandler } );
}
