/*
@@@BUILDINFO@@@ st00Core.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.
**************************************************************************/
stockphoto.init.lazyinited = true;
stockphoto.bIsVCInitialized = undefined;
if( ( stockphoto.timeKeeperOn != undefined )&&( stockphoto.timeKeeperOn ) )
{
	stockphoto.timeKeeper.st00core        = {};
	stockphoto.timeKeeper.st00core.StTime = new Date();
}

stockphoto.timeKeeperNewOn = true;
/* PERF */ stockphoto.timeKeeper["st00Core.jsx Load"] = stockphoto.timeKeeper["Since st00Core Load"] = new Date();

stockphoto.core.proxydialogPreferredSize={
preferredSize_Win: "[70,20]",
preferredSize_Mac: "[80,20]"
};

stockphoto.core.folderCreationErrorShown = false;

stockphoto.core.isBridge20OrAfter=function()
{
	var vstr1 = ( app.version ).split( " " );
	var vstr2 = ( vstr1[0] ).split( "." );
	if( ( vstr2[0] ).charCodeAt( 0 ) > 49 )
		return( true );
	return( false );
}
if( stockphoto.core.isBridge20OrAfter() )
{
	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";
}
else
{
	stockphoto.core.BM_VersionMajor       = 1; // 1.0.9
	stockphoto.core.BM_VersionMinor       = 0;
	stockphoto.core.BM_VersionVertertiary = 9;
	stockphoto.core.version				  = 010009; // 1.0.9

	stockphoto.core.installFolderSub	  = "Stock Photos";
}
stockphoto.core.installFolder = "Adobe " + stockphoto.core.installFolderSub;

stockphoto.core.BM_3Version = stockphoto.core.BM_VersionMajor+"."+stockphoto.core.BM_VersionMinor+"."+stockphoto.core.BM_VersionVertertiary;

stockphoto.core.lastActiveDocumentID = 0;

stockphoto.core.dontQuit      = false;
stockphoto.core.quitRequested = false;
stockphoto.core.orderTaskID   = undefined;
stockphoto.core.quitTaskID    = undefined;

stockphoto.core.isASPFavEnabled = true; // Not foolproof, but still should work in the same session...

stockphoto.core.stockphotoNS = "http://ns.adobe.com/StockPhoto/1.0/";

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

// Default to MediaID
stockphoto.core.ImageID = { };
stockphoto.core.ImageID.ID = stockphoto.core.ImageIDs.MediaID;
stockphoto.core.ImageID.ASPRefFilenamePrefix = "";
stockphoto.core.ImageID.ASPRefFilenameSuffix = "";

//AK:for ValueCollection
//GP: give appropriate name for this displayValueCollectionflag & displayPhotoObjectCollectionflag..D
stockphoto.core.displayValueCollectionFeatureflag = false;
stockphoto.core.displayPhotoObjectCollectionFeatureflag = false;
stockphoto.core.displayCurrency = "";

// open with menu
stockphoto.core.openWith = {};
stockphoto.core.openWith.pathArray = {};
stockphoto.core.openWith.length=0;
stockphoto.core.openWith.noShow=1;
stockphoto.core.openWith.displayMenu = {};
stockphoto.core.openWith.defaultIndex = 0;
stockphoto.core.openWith.selectedIndex = {};

stockphoto.thumbs    = { initialized: false };
stockphoto.places    = { initialized: false };
stockphoto.NavBar    = { };

stockphoto.logLevel = 0; // Default value

stockphoto.DL        = 
{ // Dynamic Loading functions
	NavBar:        {},
	search:        {},
	GetComp:       {},
	imgDetail:     {},
	ShoppingCart:  {},
	Download:      {},
	HTMLUtil:      {},
	LocalURL:      {},
	HomePage:      {},
	LangCountry:   {},
	MiscDlgs:      {},
	MiscUtils:     {}
};

stockphoto.log = function(str)
{
	app.console("[StockPhoto] " + str + "\n");
};

stockphoto.core.getInfo = 
{
    // Constants for use with request.params.FetchInfoAs (stockphoto.impl.getInfo call)
    // Default is stockphoto.imgDetail.FetchInfoAsFile
    FetchInfoAsFile         : 0,
    FetchInfoAsString       : 1,

    // Constants for use with request.params.FetchInfo (stockphoto.impl.getInfo call)
    // Default is stockphoto.imgDetail.FetchResolutionsInfo 
    FetchResolutionsInfo    : 0,
    FetchMetadataInfo       : 1,
    FetchAllInfo            : 2
};

// Stock Photos Help
// These topics (URLs) will be overwritten by partners.xml entries if the entries are present
// For non-English locales - ASP will append the language code to the Base: "_fr", "_de"
stockphoto.core.helpTopicBase = "http://www.adobe.com/go/adobe_help_stockphotos_1_5"
stockphoto.core.helpTopicProxy = "STOCK_PHOTO_PROXY_HELP";

// This can also be overridden by partners.xml entry
stockphoto.core.helpTopicBridgeVersion = "2.0";

// Survey
stockphoto.core.survey = {};
stockphoto.core.survey.GPK = {};
stockphoto.core.survey.GPK.showSurvey = false;
stockphoto.core.survey.GPK.minCount = 3;   // 0 ==> Always Display
stockphoto.core.survey.GPK.maxCount = -1;  // -1 ==> No MaxCount
stockphoto.core.survey.GPK.allowSkipSurvey = -1; // -1 ==> Don't allow.

stockphoto.core.SaveComp = {};
stockphoto.core.SaveComp.CurrentCompFolder = "";
stockphoto.core.SaveComp.DoNotRenameComp =false;
stockphoto.core.SaveComp.DoNotRenamePur =false;
stockphoto.core.SaveComp.CurrentPurchaseFolder = "";
stockphoto.core.SaveComp.CheckBoxState =false ;
stockphoto.core.SaveComp.CheckBoxPurchaseState =false ;
stockphoto.core.SaveComp.AddToFavoriteFolderStateComp = false;
stockphoto.core.SaveComp.AddToFavoriteFolderStatePur =false ;
stockphoto.core.SaveComp.MediaType =1;
stockphoto.core.SaveComp.MultipleImage= 0;
stockphoto.core.SaveComp.AdobeIdList="";
//stockphoto.core.SaveComp.CustomName="";
stockphoto.core.SaveComp.oDialogResult=0;
stockphoto.core.SaveComp.iDonotSaveTo = 0;	// None
stockphoto.core.SaveComp.numOfImagesSelected = 0;
stockphoto.core.SaveComp.aImagesSavedComp = [];
stockphoto.core.SaveComp.aImagesSavedHiRez = [];

stockphoto.core.SaveComp.PurchaseImagesShowDialog = true;
stockphoto.core.SaveComp.PurchaseImagesUserCancel = false;

stockphoto.core.SaveComp.NONE = 0;
stockphoto.core.SaveComp.USER_DEFINED_FOLDER = 1;
stockphoto.core.SaveComp.DEFAULT_FOLDER = 2;
stockphoto.core.SaveComp.BOTH_LOCATIONS = 3;

var sDummySaveAs11 = "$$$/StockPhoto/SaveAs/DwnCompFolder=Downloaded Comps Folder";
var sDummySaveAs12 = "$$$/StockPhoto/SaveAs/PurchasedImgFolder=Purchased Images Folder";

// Constants for SaveAs Dialog	
stockphoto.core.SaveComp.LBL_FILES = "$$$/StockPhoto/SaveAs/Files=Files";
stockphoto.core.SaveComp.LBL_FILE = "$$$/StockPhoto/SaveAs/File=File";
stockphoto.core.SaveComp.LBL_SAVE_COPY_IN = "$$$/StockPhoto/SaveAs/SaveCopyIn=Save a copy in ";
stockphoto.core.SaveComp.LBL_DOWNLOADED_COMP_FLD = "$$$/StockPhoto/SaveAs/SaveCopyInDwnCompFolder=Save a copy in Downloaded Comps Folder";
stockphoto.core.SaveComp.LBL_PURCHASED_IMAGE_FLD = "$$$/StockPhoto/SaveAs/SaveCopyInPurchasedImg=Save a copy in Purchased Images Folder";
stockphoto.core.SaveComp.LBL_DO_NOT_RENAME = "$$$/StockPhoto/SaveAs/DoNotRename=Do Not Rename";
stockphoto.core.SaveComp.LBL_RENAME = "$$$/StockPhoto/SaveAs/Rename=Rename";
stockphoto.core.SaveComp.LBL_001 = "$$$/StockPhoto/SaveAs/Lbl_001=001";
stockphoto.core.SaveComp.LBL_002 = "$$$/StockPhoto/SaveAs/Lbl_002=002";
stockphoto.core.SaveComp.LBL_COMMA = "$$$/StockPhoto/SaveAs/LblComma=, ";
stockphoto.core.SaveComp.LBL_ELLIPSES = "$$$/StockPhoto/SaveAs/LblEllipse=...";
stockphoto.core.SaveComp.LBL_DOWNLOADING = "$$$/StockPhoto/SaveAs/Downloading=Downloading: ";
stockphoto.core.SaveComp.LBL_DOWNLOAD_OPTN = "$$$/StockPhoto/SaveAs/Downloadoptions=Download Options";
stockphoto.core.SaveComp.LBL_FILE_NAME_OPTN = "$$$/StockPhoto/SaveAs/FileNameOptions=File Naming Options:";
stockphoto.core.SaveComp.LBL_NEW_FILE_NAME = "$$$/StockPhoto/SaveAs/FileName=New File Name:";
stockphoto.core.SaveComp.LBL_SAVE_AS = "$$$/StockPhoto/SaveAs/SaveAs=Save As";
stockphoto.core.SaveComp.FirstInit = 0;
stockphoto.core.SaveComp.MSG_FILE_ALREADY_EXIST = "$$$/StockPhoto/SaveAs/MsgFileExistSaveDiffName=An image by the name %1 already exists. Adobe Stock Photos will save this image as %2. \n\nDo you want to continue?";

stockphoto.core.SaveComp.BLANK_FILE_NAME_ERR = "$$$/StockPhoto/SaveAs/BlankFileNameErr=Filename cannot be blank.";
stockphoto.core.SaveComp.INVALID_FILE_NAME_ERR = "$$$/StockPhoto/SaveAs/MsgFileAlreadyExist=%1\nThe above file name is invalid.";

stockphoto.core.SaveComp.LBL_00X = "$$$/StockPhoto/SaveAs/Lbl_00X=00X";
stockphoto.core.SaveComp.LBL_00Y = "$$$/StockPhoto/SaveAs/Lbl_00Y=00Y";
stockphoto.core.SaveComp.LBL_SAVE = "$$$/StockPhoto/AuthProxy/Save=Save"; // KR authProxy is also using this.
stockphoto.core.SaveComp.LBL_CANCEL = "$$$/StockPhoto/AuthProxy/Cancel=Cancel";
stockphoto.core.SaveComp.LBL_SAVE_IN = "$$$/StockPhoto/SaveAs/SaveIn=Save in:";

stockphoto.core.SaveComp.LBL_YES = "$$$/StockPhoto/AuthProxy/BtnYes=Yes";
stockphoto.core.SaveComp.LBL_NO = "$$$/StockPhoto/AuthProxy/BtnNo=No";

stockphoto.core.Proxy = {};
stockphoto.core.Proxy.HttpOpen = 0;
stockphoto.core.Proxy.HttpsOpen = 0;
stockphoto.core.Proxy.BothOpen = 0;
stockphoto.core.Proxy.ImplCalled = 0;

// partnerName to PartnerDisplayname mapping
stockphoto.core.partnerDispNameToPartnerNameMap = {};

stockphoto.core.SearchInfoRelPath = "/CACHE/SearchInfo.txt";

stockphoto.core.zstringFiles = {
    NavBar: "st11NavBar"
};

stockphoto.search =
{
	active: { },
	setFolder: false,
	// The settings array stores the current settings for each document.
	settings: [ ],
	showAdvancedDrawer: [ ],
	previousSettings: [ ],
    showPreviousSettings: [ ],
    searchKeyword: [ ],
	searchMediaTypes: [ ],
}

// defaultSettings is the default template for a new window's settings
stockphoto.search.defaultSettings = 
{
      orientation: 
      {
        portrait: true,
        square:   true,
        landscape:true,
        panoramic:true,
      },
      
      colorFormat:
      {
        color:  true,
        bw:     true,
      },
      
      mediaType:
      {
        photography:   true,
        illustration: true,
        photoobject: true,
      },
      
      collectionsAll: true,
      collectionSelected: [ ],
      collectionDisplayNames: '',
      collectionNames: '',
      
      isDefault: true,
      autoOpen: true
}

stockphoto.search.defaultSettingsActionHistory = ["","","","","",""];

// stockphoto.providers stores the list of partners
// and collections read from partners.xml
stockphoto.providers =
{
  partners: [ ],
  collections: [ ],
  loaded: false
};

stockphoto.search.textPhotography = "Photography";
stockphoto.search.textIllustration = "Illustration";
stockphoto.search.textPhotoObjects = "Masked";

stockphoto.core.SetCurrentCompFolder = function (sCurrentPath)
{
	if( (undefined == sCurrentPath) || ("" != sCurrentPath) )
	{
		stockphoto.core.SaveComp.CurrentCompFolder = sCurrentPath;
		app.preferences.bm_Current_Comp_Folder=sCurrentPath;
	}
}

stockphoto.core.GetCurrentCompFolder = function ()
{
	if( (undefined == app.preferences.bm_Current_Comp_Folder) 
	     || ("" == app.preferences.bm_Current_Comp_Folder ) 
	     || (!(Folder(app.preferences.bm_Current_Comp_Folder)).exists) )// Unable to open folder
	{
		stockphoto.core.SetCurrentCompFolder(stockphoto.core.folder.getMyCompFolder());
		return stockphoto.core.folder.getMyCompFolder();
	}
	else
	{
		return app.preferences.bm_Current_Comp_Folder ;
	}
}

stockphoto.core.GetOrigCurrentCompFolder = function ()
{
	if( (undefined == app.preferences.bm_Current_Comp_Folder) 
	     || ("" == app.preferences.bm_Current_Comp_Folder ))// Unable to open folder
	{
		stockphoto.core.SetCurrentCompFolder(stockphoto.core.folder.getMyCompFolder());
		return stockphoto.core.folder.getMyCompFolder();
	}
	else
	{
		return app.preferences.bm_Current_Comp_Folder ;
	}
}

stockphoto.core.SetCurrentPurchaseFolder = function (sCurrentPath)
{
	if( (undefined == sCurrentPath) || ("" != sCurrentPath) )
	{
		stockphoto.core.SaveComp.CurrentPurchaseFolder = sCurrentPath;
		app.preferences.bm_Current_Purchase_Folder=sCurrentPath;
	}	
}

stockphoto.core.GetCurrentPurchaseFolder = function ()
{
	if( (undefined == app.preferences.bm_Current_Purchase_Folder) 
	    || ( "" == app.preferences.bm_Current_Purchase_Folder) 
	    || ( ! (Folder(app.preferences.bm_Current_Purchase_Folder)).exists) ) // Unable to open user folder
	{
		stockphoto.core.SetCurrentPurchaseFolder(stockphoto.core.folder.getMyPurchasesFolder());
		return stockphoto.core.folder.getMyPurchasesFolder();
	}
	else
	{
		return app.preferences.bm_Current_Purchase_Folder ;
	}
}

stockphoto.core.GetOrigCurrentPurchaseFolder = function ()
{
	if( (undefined == app.preferences.bm_Current_Purchase_Folder) 
	    || ( "" == app.preferences.bm_Current_Purchase_Folder)) // Unable to open user folder
	{
		stockphoto.core.SetCurrentPurchaseFolder(stockphoto.core.folder.getMyPurchasesFolder());
		return stockphoto.core.folder.getMyPurchasesFolder();
	}
	else
	{
		return app.preferences.bm_Current_Purchase_Folder ;
	}
}

//Change for Proxy 

var sDummyStringLocaliz = "$$$/StockPhoto/AuthProxy/LoadStockPhotos=Loading Adobe Stock Photos..."; 
	

var sDummySaveAs17 ="$$$/AlertBox/ERROR_ATTEMPTING_IN_DEFAULT=Attempting download in default folder.";
var sDummySaveAs18 ="$$$/AlertBox/ERROR_ADAPTER_NO_FOLDER_ACCESS=Cannot write to the folder %1. The folder may be locked or in use, the disk may be full, or you may not have access privileges.\n\n%2";
 
var sDummySaveAs19 =stockphoto.core.SaveComp.LBL_SAVE ; // KR TODO Clean
var sDummySaveAs20 ="$$$/AlertBox/IMAGES_SAVED_IN_DEFAULT=Some images are saved in the Default Folder.";
var sDummySaveAs21 ="$$$/AlertBox/N_IMAGES_SAVED_IN_DEFAULT=%1 images are saved in the Default Folder.";

var sDummySaveAs23 ="$$$/StockPhoto/SaveAs/SaveAsColon=Save As: ";
var sDummySaveAs24 ="$$$/StockPhoto/SaveAs/NewFolder=New Folder";
 
//KR TODO .. Use the string.

var sDummyProxy1 = "$$$/StockPhoto/AuthProxy/DialogTitle=Enter Proxy Credentials";
var sDummyProxy2 = "$$$/StockPhoto/AuthProxy/HttpTitle=HTTP Proxy Credentials";
var sDummyProxy3 = "$$$/StockPhoto/AuthProxy/UserNameProxy=Username";
var sDummyProxy4 = "$$$/StockPhoto/AuthProxy/PasswordProxy=Password ";
var sDummyProxy5 = "$$$/StockPhoto/AuthProxy/HttpsTitle=HTTPS Proxy Credentials";
var sDummyProxy6 = "$$$/StockPhoto/AuthProxy/SameCredentialsTitle=Same Credentials for Both";
var sDummyProxy7 = "$$$/StockPhoto/AuthProxy/Server=Server:";
var sDummyProxy8 = "$$$/StockPhoto/AuthProxy/ProxyName=Proxy Name:";
var sDummyProxy9 = "$$$/StockPhoto/AuthProxy/Ok=OK";
var sDummyProxy10 = stockphoto.core.SaveComp.LBL_CANCEL; //TODO Clean
var sDummyProxy11 = "$$$/StockPhoto/AuthProxy/Save=Save";

// More Strings

var sDummyProxy12 = "$$$/StockPhoto/AuthProxy/MacEnterCrediantialMsg=Please enter the network login credentials in the System Preferences.";
var sDummyProxy13 = "$$$/StockPhoto/AuthProxy/MacEnterDetailMsg=Please enter the network login details in the System Preferences.";
var sDummyProxy15 = "$$$/StockPhoto/AuthProxy/IncorrectCredentialMsg=Adobe Stock Photos could not connect to the server using the network login credentials in the System Preferences. Please update the network credentials in the System Preferences.";
var sDummyProxy16 = "$$$/StockPhoto/AuthProxy/IncorrectDetailMsg=Adobe Stock Photos could not connect to the server using the network login details in the System Preferences. Please update the network details in the System Preferences";
var sDummyProxy18 = "$$$/StockPhoto/AuthProxy/IncorrectCredentialMsgShort=Adobe Stock Photos could not connect to the server using the network credentials in the System Preferences.";
var sDummyProxy19 = "$$$/StockPhoto/AuthProxy/IncorrectDetailMsgShort=Adobe Stock Photos could not connect to the server using the network details in the System Preferences.";
var sDummyProxy20 = "$$$/StockPhoto/AuthProxy/BtnUpdateCredentials=Update Credentials";
var sDummyProxy21 = "$$$/StockPhoto/AuthProxy/BtnUpdateDetails=Update Details";

var sDummyProxy22 = "$$$/StockPhoto/AuthProxy/UpgradeOSMsg=You are attempting to access Adobe Stock Photos from a network server that requires you to log in to access the Internet. This feature is available only on Mac OS X version 10.3.x and above. Please upgrade your Operating System.";
var sDummyProxy23 = "$$$/StockPhoto/AuthProxy/UpgradeOSVerMsg=You are attempting to access Adobe Stock Photos from a network server that requires you to log in to access the Internet. This feature is available only on Mac OS X version 10.3.x and above. Please upgrade to a higher version of Operating System.";
var sDummyProxy24 = "$$$/StockPhoto/AuthProxy/LoginChangeCredWar=Warning: The changes made to the network login credentials will also modify the global System Network Preferences.";
var sDummyProxy25 = "$$$/StockPhoto/AuthProxy/LoginChangeDetailWar=Warning: The changes made to the network login details will also modify the global System Network Preferences.";
var sDummyProxy26 = "$$$/StockPhoto/AuthProxy/WantToContinueMsg=Would you like to continue?";
var sDummyProxy29 = "$$$/AlertBox/ERROR_CORE_PROXY_ATTEMPTS_OVER=Incorrect Credentials. You have exceeded the allowed number of login attempts.";

var sDummyProxy30 = "$$$/StockPhoto/AuthProxy/MacInconsistentSettingsMessage=The network credentials have been changed in System Preferences. Would you like to continue with the old credentials or reload the new credentials from system preferences?"; 
var sDummyProxy31 = "$$$/StockPhoto/AuthProxy/MacBlankPasswordMessage=The network server username and/or password have been changed to blank. Are you sure you want to continue?";
var sDummyProxy32 = "$$$/StockPhoto/AuthProxy/MacGetNewOSMessage=You will need to upgrade your operating system in order to use Adobe Stock Photos.";
var sDummyProxy33 = "$$$/StockPhoto/AuthProxy/MacGlobalChangesWarningMessage=Warning: changes made to these network proxy settings will also modify your Network System Preferences.";
var sDummyProxy34 = "$$$/StockPhoto/AuthProxy/NotSupported1028Message=Your network has an authenticating proxy server. Adobe Stock Photos only support this configuration on Mac OS 10.3 and above.  Please upgrade your Operating System to continue using Adobe Stock Photos.";


var sDummyProxy35 = "$$$/StockPhoto/SaveAs/DownloadingSingleComp=Downloading Comp...";
var sDummyProxy36 = "$$$/StockPhoto/SaveAs/DownloadingMultipleComp=Downloading Comps...";
var sDummyProxy37 = "$$$/StockPhoto/SaveAs/FileSaveError=Error Saving File.";
var sDummyProxy38 = "$$$/StockPhoto/SaveAs/FileNameTooLongMessage=File Name too long.";

var sDisabledForMacTenTwo = "$$$/StockPhoto/AuthProxy/NotSupported1028Message=Your network has an authenticating proxy server. Adobe Stock Photos only support this configuration on Mac OS 10.3 and above.  Please upgrade your Operating System to continue using Adobe Stock Photos.";

stockphoto.core.singleCompDown = "";
stockphoto.core.multipleCompDown = "";

stockphoto.core.getdownloadCompString = function()
{
	stockphoto.core.singleCompDown = zc.get("$$$/StockPhoto/SaveAs/DownloadingSingleComp=Downloading Comp...");
	stockphoto.core.multipleCompDown = zc.get("$$$/StockPhoto/SaveAs/DownloadingMultipleComp=Downloading Comps...");
}


stockphoto.core.GetProxyCredentials = function(bDecryptAndSend)
{

	var sHttpProxyUser="";
	var sHttpProxyPassword="";
	var sHttpsProxyUser="";
	var sHttpsProxyPassword="";
	var oProxyCredentials = {};
	var result = {};
	
	
	if( stockphoto.isWin )
	{
		if( undefined != app.preferences.bm_Http_Proxy_User)
		{
			sHttpProxyUser = app.preferences.bm_Http_Proxy_User;
		}
	
		if( undefined != app.preferences.bm_Http_Proxy_Password)
		{
			sHttpProxyPassword = app.preferences.bm_Http_Proxy_Password;
		}
	
		if( undefined != app.preferences.bm_Https_Proxy_User)
		{
			sHttpsProxyUser = app.preferences.bm_Https_Proxy_User;
		}
	
		if( undefined != app.preferences.bm_Https_Proxy_Password)
		{
			sHttpsProxyPassword = app.preferences.bm_Https_Proxy_Password;
		}
		
		 oProxyCredentials =
		{
			sHttpUser : sHttpProxyUser,
			sHttpPassword : sHttpProxyPassword,
			sHttpsUser : sHttpsProxyUser,
			sHttpsPassword : sHttpsProxyPassword,
			iEncryptionState : 1,
			iDoFetchOrSave: 0
		};
	
		if( "undefined" != typeof (bDecryptAndSend) )
		{
			if( true == bDecryptAndSend )
			{
				result = stockphoto.impl.DecryptProxyCredentials(oProxyCredentials);
				if( "undefined" != typeof(result) && 4 == result.length )
				{
					oProxyCredentials =
					{
						sHttpUser : result[0],
						sHttpPassword : result[1],
						sHttpsUser : result[2],
						sHttpsPassword : result[3],
						iEncryptionState : 0,
						iDoFetchOrSave: 0
					};
				}
			
			}
		}
	}
	else
	{
		oProxyCredentials =
		{
			sHttpUser : sHttpProxyUser,
			sHttpPassword : sHttpProxyPassword,
			sHttpsUser : sHttpsProxyUser,
			sHttpsPassword : sHttpsProxyPassword,
			iEncryptionState : 1,
			iDoFetchOrSave: 0
		};
		
		result = stockphoto.impl.DecryptProxyCredentials(oProxyCredentials);
		if( "undefined" != typeof(result) && 4 == result.length )
		{
			if( "undefined" != typeof(result[0]) )
			{
				sHttpProxyUser = result[0];
			}
			
			if( "undefined" != typeof(result[1]) )
			{
				sHttpProxyPassword = result[1];
			}
			if( "undefined" != typeof(result[2]) )
			{
				sHttpsProxyUser = result[2];
			}
			if( "undefined" != typeof(result[3]) )
			{
				sHttpsProxyPassword = result[3];
			}
			
			oProxyCredentials =
			{
				sHttpUser : sHttpProxyUser,
				sHttpPassword : sHttpProxyPassword,
				sHttpsUser : sHttpsProxyUser,
				sHttpsPassword : sHttpsProxyPassword,
				iEncryptionState : 1,
				iDoFetchOrSave: 0
			};
		}
	}
	return oProxyCredentials;
}

stockphoto.core.SetProxyCredentials = function(oProxyCredentials)
{
	
	if ("undefined" == typeof(oProxyCredentials))
	{
		return false;
	}
	
	var result = stockphoto.impl.SetProxyCredentials(oProxyCredentials);
	

	if (stockphoto.isWin  && "undefined" != typeof(result) && 8 < result.length &&
		"undefined" != typeof(result[5]) && "undefined" != typeof(result[6]) &&
		"undefined" != typeof(result[7]) && "undefined" != typeof(result[8]))
	{
		
			app.preferences.bm_Http_Proxy_User = result[5];
			app.preferences.bm_Http_Proxy_Password = result[6];
		
		
			app.preferences.bm_Https_Proxy_User = result[7];
			app.preferences.bm_Https_Proxy_Password = result[8];
	}
}

stockphoto.core.makeAlertIconPath= function(type, doubleUp)
{
	// The input parameter type is a number indicating which icon to display (0: note, 1: caution, 2: stop, 3: sm_yellow info)
	// The doubleUp flag indicates that backslashes in win filepaths should be doubled up.
	
	if ( "undefined" == typeof(type) || "undefined" == typeof(doubleUp) )
	{
		return "";
	}
	var iconPath = "";
	var iconExt = "";
	var baseName = "";
	var result = "";
	
	switch(type)
	{
		case 0:
			{
				baseName = "P_Alert";
				break;
			}
		case 1:
			{
				baseName = "P_Info";
				break;
			}
		default:
			{
				break;
			}
	}

	if ( "Windows" == File.fs)
	{
		iconPath = Folder.startup + "/../Adobe Stock Photos CS3/Icons/";
		iconExt = "_win.png";
		var iconFile = new File(iconPath + baseName + iconExt);
	
		if ("undefined" != typeof(iconFile) && iconFile.exists)
		{
			result = iconFile.fsName;
		
			if (doubleUp)
			{
				var finalStr = "";
				var arr = result.split("\\");
				for (var iIndex = 0; iIndex < arr.length; iIndex++)
				{
					finalStr += arr[iIndex];
					if (iIndex+1 < arr.length)	// filepath never ends with slash
						finalStr += "\\\\";
				}
					result = finalStr;
			}
		}
		else
		{
			result = "";
		}
	}
	else
	{
		iconPath = stockphoto.startUpFolderForMac + "/Resources/Icons/";
		iconExt = "_mac.png";
		result = iconPath + baseName + iconExt;
		
	}
	return result;
}

stockphoto.core.ProxyOkButtonAction = function(sHttpUsername, sHttpPassword, sHttpsUsername, sHttpsPassword)
{


	if (undefined != sHttpUsername && undefined != sHttpPassword && undefined != sHttpsUsername && undefined != sHttpsPassword)
	{
		var oProxyCredentials =
		{
			sHttpUser : sHttpUsername.substring(0, 100),
			sHttpPassword : sHttpPassword.substring(0, 100),
			sHttpsUser : sHttpsUsername.substring(0, 100),
			sHttpsPassword : sHttpsPassword.substring(0, 100),
			iEncryptionState : 0,
			iDoFetchOrSave: 1
		};
		stockphoto.impl.ResetProxyCheck();
		stockphoto.core.SetProxyCredentials(oProxyCredentials);
	}
}

stockphoto.core.ProxyHelp = function()
{
	stockphoto.DL.MiscDlgs.HelpTopic( stockphoto.core.helpTopicProxy );
}


stockphoto.core.BuildCommonDialog = function(sCredentialUser, sCredentialPassword, sServerIP, sPaneltext, bShowAlert)
{
	
  	stockphoto.core.util.loadLocaleData( "st00Core.par" );
  	
  	var preferredSize;
	if(stockphoto.isWin)
	{
		preferredSize = stockphoto.core.proxydialogPreferredSize.preferredSize_Win;
	}
	else
	{
		preferredSize = stockphoto.core.proxydialogPreferredSize.preferredSize_Mac;
	}
		
							
	var dProxyDialog =   "dialog { alignChildren: 'fill', text:'Enter Proxy Credentials' , \
				header_text: Group { orientation: 'column', alignChildren:'fill', \
				header_1: StaticText { properties:{multiline:'true'}, text:'You are attempting to access Adobe Stock Photos from a network server that requires you to log in to access the Internet.' },\
				header_itext: Group { orientation: 'row', alignChildren:'right', \
				header_3: StaticText { text:'Click on the icon for more details.' },\
				header_icon: IconButton {}\
				}\
				},\
				http_panel: Panel { orientation: 'column', alignChildren:'left', \
				text: 'HTTP Proxy Credentials', \
				http_name: Group { orientation: 'column',alignChildren:'left', \
				s: StaticText { text:'Server: 10.40.59.97' }, \
				http_align: Group { orientation: 'row',alignChildren:'left',\
				http_icon: Group { orientation: 'column',alignChildren:'left',\
				icon_u: Image {style:button,preferredSize:[15,18]}, \
				icon_p: Image {preferredSize:[15,18]}},\
				http_static: Group { orientation: 'column',alignChildren:'left',\
				username_u: StaticText { text:'UserName',preferredSize:"+preferredSize+" }, \
				username_p: StaticText { text:'Password',preferredSize:"+preferredSize+"}}, \
				http_edit: Group { orientation: 'column',alignChildren:'left',\
				user: EditText { preferredSize: [200, 20] }, \
				password: EditText { preferredSize: [200, 20] ,properties:{noecho:'true'}}} \
				} \
				}\
				}, \
				buttons: Group { orientation: 'row', alignment: 'right', \ ";
				
				
				var dActionButton = "";
				
				if(stockphoto.isWin)
				{
					dActionButton = "okBtn: Button { text:'OK', properties:{name:'ok'} }, \
					cancelBtn: Button { text:'Cancel', properties:{name:'cancel'} } \ ";
				}
				else
				{
					dActionButton = "cancelBtn: Button { text:'Cancel', properties:{name:'cancel'}},\
					okBtn: Button { text:'OK', properties:{name:'ok'} } \ " ;
				}
				
				var dEndDialog = "} \
									}";
				
		
		dProxyDialog = dProxyDialog + dActionButton + dEndDialog;
				
				
	if("undefined" == typeof(sCredentialUser) || "undefined" == typeof(sCredentialPassword) || 
		"undefined" == typeof(sServerIP) || "undefined" == typeof(sPaneltext))
		{
			return 0;
		}
		
				
	var wProxyWindow = new Window (dProxyDialog);
		
	var oProxyCredentials = stockphoto.core.GetProxyCredentials(true);
	
	wProxyWindow.http_panel.http_name.http_align.http_edit.user.text = sCredentialUser;
	wProxyWindow.http_panel.http_name.http_align.http_edit.password.text = sCredentialPassword;
	
	wProxyWindow.http_panel.http_name.s.text = zc.get(sDummyProxy7)  + " "  + sServerIP;

	wProxyWindow.text = zc.get(sDummyProxy1);
	wProxyWindow.http_panel.text = sPaneltext;	
	wProxyWindow.http_panel.http_name.http_align.http_static.username_u.text = zc.get(sDummyProxy3);	
	wProxyWindow.http_panel.http_name.http_align.http_static.username_p.text = zc.get(sDummyProxy4);
	wProxyWindow.buttons.okBtn.text = zc.get(sDummyProxy9);
	wProxyWindow.buttons.cancelBtn.text = zc.get(sDummyProxy10);
	
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ) )
		{
			var imgVals = stockphoto.core.makeAlertIconPath(0,false);
			stockphoto.alertBox.PopulateProxyStrings();
			wProxyWindow.header_text.header_1.text = stockphoto.alertBox.sProxyHeaderWarning;
			wProxyWindow.header_text.header_itext.header_3.text = stockphoto.alertBox.sProxyIconDetails;
			
			if("undefined" != typeof(bShowAlert) && true == bShowAlert)
			{
				wProxyWindow.http_panel.http_name.http_align.http_icon.icon_u.icon = imgVals;
				wProxyWindow.http_panel.http_name.http_align.http_icon.icon_p.icon = imgVals;
			}
			
			wProxyWindow.header_text.header_itext.header_icon.icon = stockphoto.core.makeAlertIconPath(1,false);
		}
	
	wProxyWindow.http_panel.http_name.http_align.http_edit.user.onChanging = function()
	{
		wProxyWindow.http_panel.http_name.http_align.http_icon.icon_u.visible = false;
		wProxyWindow.http_panel.http_name.http_align.http_icon.icon_p.visible = false;
	}
	
	wProxyWindow.http_panel.http_name.http_align.http_edit.password.onChanging = function()
	{
		wProxyWindow.http_panel.http_name.http_align.http_icon.icon_u.visible = false;
		wProxyWindow.http_panel.http_name.http_align.http_icon.icon_p.visible = false;
	}
	
	wProxyWindow.header_text.header_itext.header_icon.onClick = function()
	{
		stockphoto.core.ProxyHelp();
	}
	
	
	return wProxyWindow;

}

stockphoto.core.ShowHttpProxyDialog = function(bShowAlert)
{


	if( 0 == stockphoto.core.Proxy.HttpOpen)
	{
		stockphoto.core.Proxy.HttpOpen = 1;
	}
	else
	{
		return 1;
	}
	
	var iDlgResult = 1;
	
	var oProxyCredentials = stockphoto.core.GetProxyCredentials(true);
	
	if ("undefined" == oProxyCredentials)
	{
		return 1;
	}
	
	var aInputCredentials = stockphoto.impl.SetProxyCredentials(oProxyCredentials);
	
	if ("undefined" != typeof(aInputCredentials) && "undefined" != typeof(oProxyCredentials["sHttpUser"]) && 
		"undefined" != typeof(oProxyCredentials["sHttpPassword"]) && "undefined" != typeof(aInputCredentials) && 3 < aInputCredentials.length &&
		"undefined" != typeof(bShowAlert))
		{
			var wProxyWindow = stockphoto.core.BuildCommonDialog(oProxyCredentials["sHttpUser"], oProxyCredentials["sHttpPassword"], aInputCredentials[3], zc.get(sDummyProxy2), bShowAlert);
		}
	
	if("undefined" != typeof(wProxyWindow) && 0 != wProxyWindow )
	{
	
		wProxyWindow.buttons.okBtn.onClick = function()
		{
	
			if ("undefined" != typeof(oProxyCredentials) && "undefined" != typeof(oProxyCredentials["sHttpsUser"]) && 
				"undefined" != typeof(oProxyCredentials["sHttpsPassword"]))
			{
				stockphoto.core.ProxyOkButtonAction(this.parent.parent.http_panel.http_name.http_align.http_edit.user.text,
												     	this.parent.parent.http_panel.http_name.http_align.http_edit.password.text,
												  	  	oProxyCredentials["sHttpsUser"],
												 	  	oProxyCredentials["sHttpsPassword"]);
												  
			}
			
				this.parent.parent.close(4);
		}

		wProxyWindow.buttons.cancelBtn.onClick = function()
		{
			this.parent.parent.close(1);
		}
	
		
		wProxyWindow.center();  
		wProxyWindow.modal = true;
		iDlgResult = wProxyWindow.show();
	
		stockphoto.core.Proxy.HttpOpen = 0;
	}
	return iDlgResult;
}


stockphoto.core.ShowHttpsProxyDialog = function(bShowAlert)
{
		
	if( 0 == stockphoto.core.Proxy.HttpsOpen)
	{
		stockphoto.core.Proxy.HttpsOpen = 1;
	}
	else
	{
		return 1;
	}
	
	var iDlgResult = 1;
	
	var oProxyCredentials = stockphoto.core.GetProxyCredentials(true);
	
	var aInputCredentials = stockphoto.impl.SetProxyCredentials(oProxyCredentials);
	
	if ("undefined" != typeof(aInputCredentials) && "undefined" != typeof(oProxyCredentials["sHttpUser"]) && 
		"undefined" != typeof(oProxyCredentials["sHttpPassword"]) && "undefined" != typeof(aInputCredentials) && 4 < aInputCredentials.length &&
		"undefined" != typeof(bShowAlert) )
		{
			var wProxyWindow = stockphoto.core.BuildCommonDialog(oProxyCredentials["sHttpsUser"], oProxyCredentials["sHttpsPassword"], aInputCredentials[4], zc.get(sDummyProxy5), bShowAlert);
		}
		
		
	if ("undefined" != wProxyWindow && 0 != wProxyWindow)
	{
	
		wProxyWindow.buttons.okBtn.onClick = function()
		{
			if ("undefined" != typeof(oProxyCredentials) && "undefined" != typeof(oProxyCredentials["sHttpUser"]) && 
				"undefined" != typeof(oProxyCredentials["sHttpPassword"]))
			{
				stockphoto.core.ProxyOkButtonAction(oProxyCredentials["sHttpUser"],
												    	 oProxyCredentials["sHttpPassword"],
												  	  	this.parent.parent.http_panel.http_name.http_align.http_edit.user.text,
												 	  	this.parent.parent.http_panel.http_name.http_align.http_edit.password.text);
												  
			}
				this.parent.parent.close(4);
		}
	
	
		wProxyWindow.buttons.cancelBtn.onClick = function()
		{
		
			this.parent.parent.close(1);
		}

		
		wProxyWindow.center();  
		wProxyWindow.modal = true;
		iDlgResult = wProxyWindow.show();
	
		stockphoto.core.Proxy.HttpsOpen = 0;
	}
	
	return iDlgResult;
}


stockphoto.core.ShowProxyDialog = function(bShowAlert)
{

	if( 0 == stockphoto.core.Proxy.BothOpen)
	{
		stockphoto.core.Proxy.BothOpen = 1;
	}
	else
	{
		return 1;
	}

  				stockphoto.core.util.loadLocaleData( "st00Core.par" );
  				
  				var preferredSize;
				if(stockphoto.isWin)
				{
					preferredSize = stockphoto.core.proxydialogPreferredSize.preferredSize_Win;
				}
				else
				{
					preferredSize = stockphoto.core.proxydialogPreferredSize.preferredSize_Mac;
				}
			
							
				var dProxyDialog =   "dialog { alignChildren: 'fill', text:'Enter Proxy Credentials' , \
				header_text: Group { orientation: 'column', alignChildren:'fill', \
				header_1: StaticText { properties:{multiline:'true'}, text:'You are attempting to access Adobe Stock Photos from a network server that requires you to log in to access the Internet.' },\
				header_itext: Group { orientation: 'row', alignChildren:'right', \
				header_3: StaticText { text:'Click on the icon for more details.' },\
				header_icon: IconButton {}\
				}\
				},\
				http_panel: Panel { orientation: 'column', alignChildren:'left', \
				text: 'HTTP Proxy Credentials', \
				http_name: Group { orientation: 'column',alignChildren:'left', \
				s: StaticText { text:'Server: 10.40.59.97' }, \
				http_align: Group { orientation: 'row',alignChildren:'left',\
				http_icon: Group { orientation: 'column',alignChildren:'left',\
				icon_u: Image {style:button,preferredSize:[15,18]}, \
				icon_p: Image {preferredSize:[15,18]}},\
				http_static: Group { orientation: 'column',alignChildren:'left',\
				username_u: StaticText { text:'UserName' ,preferredSize:"+preferredSize+"}, \
				username_p: StaticText { text:'Password' ,preferredSize:"+preferredSize+"}}, \
				http_edit: Group { orientation: 'column',alignChildren:'left',\
				user: EditText { preferredSize: [200, 20] }, \
				password: EditText { preferredSize: [200, 20] ,properties:{noecho:'true'}}} \
				} \
				}\
				}, \
				https_panel: Panel { orientation: 'column', alignChildren:'left', \
				text: 'HTTPS Proxy Credentials', \
				https_name: Group { orientation: 'column',alignChildren:'left', \
				s: StaticText { text:'Server: 10.40.59.97' }, \
				https_align: Group { orientation: 'row',alignChildren:'left',\
				https_icon: Group { orientation: 'column',alignChildren:'left',\
				icon_u: Image {preferredSize:[15,18]}, \
				icon_p: Image {preferredSize:[15,18]}},\
				https_static: Group { orientation: 'column',alignChildren:'left',\
				username_u: StaticText { text:'UserName',preferredSize:"+preferredSize+" }, \
				username_p: StaticText { text:'Password',preferredSize:"+preferredSize+"}}, \
				https_edit: Group { orientation: 'column',alignChildren:'left',\
				user: EditText { preferredSize: [200, 20] }, \
				password: EditText { preferredSize: [200, 20] ,properties:{noecho:'true'}}} \
				} \
				}\
				}, \
				checkbox: Checkbox {text :'Same Credentials for Both'} ,\
				buttons: Group { orientation: 'row', alignment: 'right', \ ";
				
				
				var dActionButton = "";
				
				if(stockphoto.isWin)
				{
					dActionButton = "okBtn: Button { text:'OK', properties:{name:'ok'} }, \
					cancelBtn: Button { text:'Cancel', properties:{name:'cancel'} } \ ";
				}
				else
				{
					dActionButton = "cancelBtn: Button { text:'Cancel', properties:{name:'cancel'}},\
					okBtn: Button { text:'OK', properties:{name:'ok'} } \ " ;
				}
				
				var dEndDialog = "} \
									}";
				
		
		dProxyDialog = dProxyDialog + dActionButton + dEndDialog;
		var wProxyWindow = new Window (dProxyDialog);
		
		wProxyWindow.checkbox.value=true;
		wProxyWindow.https_panel.enabled = false;
		
		var oProxyCredentials = stockphoto.core.GetProxyCredentials(true);
		
		if ("undefined" == typeof(oProxyCredentials) || undefined == oProxyCredentials["sHttpUser"] ||
			 undefined == oProxyCredentials["sHttpPassword"] || undefined == oProxyCredentials["sHttpsUser"] ||
			 undefined == oProxyCredentials["sHttpsPassword"] )
		{
			return 1;
		}
		
		var aInputCredentials = stockphoto.impl.GetProxyAddress();
		
		if ("undefined" == typeof(aInputCredentials) && 1 > aInputCredentials.length)
		{
			return 1;
		}
		
		
		wProxyWindow.http_panel.http_name.http_align.http_edit.user.text = oProxyCredentials["sHttpUser"];
		wProxyWindow.http_panel.http_name.http_align.http_edit.password.text = oProxyCredentials["sHttpPassword"];
		wProxyWindow.https_panel.https_name.https_align.https_edit.user.text = oProxyCredentials["sHttpsUser"];
		wProxyWindow.https_panel.https_name.https_align.https_edit.password.text = oProxyCredentials["sHttpsPassword"];
		
		wProxyWindow.http_panel.http_name.s.text = zc.get(sDummyProxy7)  + " "  + aInputCredentials[0];
		wProxyWindow.https_panel.https_name.s.text =zc.get(sDummyProxy7) + " " + aInputCredentials[1];
		
		if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ) )
		{
			var imgVals = stockphoto.core.makeAlertIconPath(0,false);
			
			stockphoto.alertBox.PopulateProxyStrings();
			wProxyWindow.header_text.header_1.text = stockphoto.alertBox.sProxyHeaderWarning;
			wProxyWindow.header_text.header_itext.header_3.text = stockphoto.alertBox.sProxyIconDetails;
			
			
			if("undefined" != typeof(bShowAlert) && true == bShowAlert)
			{
				wProxyWindow.http_panel.http_name.http_align.http_icon.icon_u.icon = imgVals;
				wProxyWindow.http_panel.http_name.http_align.http_icon.icon_p.icon = imgVals;
				wProxyWindow.https_panel.https_name.https_align.https_icon.icon_u.icon = imgVals;
				wProxyWindow.https_panel.https_name.https_align.https_icon.icon_p.icon = imgVals;
			}
			
			wProxyWindow.header_text.header_itext.header_icon.icon = stockphoto.core.makeAlertIconPath(1,false);
		}
		
		wProxyWindow.text = zc.get(sDummyProxy1);
		wProxyWindow.http_panel.text = zc.get(sDummyProxy2);
		wProxyWindow.https_panel.text = zc.get(sDummyProxy5);
		wProxyWindow.http_panel.http_name.http_align.http_static.username_u.text = zc.get(sDummyProxy3);
		wProxyWindow.https_panel.https_name.https_align.https_static.username_u.text = zc.get(sDummyProxy3);
		wProxyWindow.http_panel.http_name.http_align.http_static.username_p.text = zc.get(sDummyProxy4);
		wProxyWindow.https_panel.https_name.https_align.https_static.username_p.text = zc.get(sDummyProxy4);
		
		wProxyWindow.checkbox.text = zc.get(sDummyProxy6);
		wProxyWindow.buttons.okBtn.text = zc.get(sDummyProxy9);
		wProxyWindow.buttons.cancelBtn.text = zc.get(sDummyProxy10);
		
		
		wProxyWindow.checkbox.onClick = function()
		{
			this.parent.https_panel.enabled = !(this.value);
			if(true == this.value)
			{
				this.parent.https_panel.https_name.https_align.https_edit.user.text = this.parent.http_panel.http_name.http_align.http_edit.user.text;
				this.parent.https_panel.https_name.https_align.https_edit.password.text = this.parent.http_panel.http_name.http_align.http_edit.password.text;
			}
		}
		
		
		wProxyWindow.buttons.okBtn.onClick = function()
		{		
		
			if(true == this.parent.parent.checkbox.value)
			{
				this.parent.parent.https_panel.https_name.https_align.https_edit.user.text = this.parent.parent.http_panel.http_name.http_align.http_edit.user.text;
				this.parent.parent.https_panel.https_name.https_align.https_edit.password.text = this.parent.parent.http_panel.http_name.http_align.http_edit.password.text;
			}
			
		
			stockphoto.core.ProxyOkButtonAction(this.parent.parent.http_panel.http_name.http_align.http_edit.user.text,
												     this.parent.parent.http_panel.http_name.http_align.http_edit.password.text,
												  	  this.parent.parent.https_panel.https_name.https_align.https_edit.user.text,
												 	  this.parent.parent.https_panel.https_name.https_align.https_edit.password.text);
												  
				this.parent.parent.close(4);
			
		}
		
		
		wProxyWindow.buttons.cancelBtn.onClick = function()
		{
			this.parent.parent.close(1);
		}
		
		wProxyWindow.http_panel.http_name.http_align.http_edit.user.onChanging = function()
		{
			wProxyWindow.http_panel.http_name.http_align.http_icon.icon_u.visible = false;
			wProxyWindow.http_panel.http_name.http_align.http_icon.icon_p.visible = false;
			
			if(wProxyWindow.checkbox.value)
			{
				wProxyWindow.https_panel.https_name.https_align.https_edit.user.text = wProxyWindow.http_panel.http_name.http_align.http_edit.user.text;
				wProxyWindow.https_panel.https_name.https_align.https_icon.icon_u.visible = false;
				wProxyWindow.https_panel.https_name.https_align.https_icon.icon_p.visible = false;
			}
		}
	
		wProxyWindow.http_panel.http_name.http_align.http_edit.password.onChanging = function()
		{
			wProxyWindow.http_panel.http_name.http_align.http_icon.icon_u.visible = false;
			wProxyWindow.http_panel.http_name.http_align.http_icon.icon_p.visible = false;
			if(wProxyWindow.checkbox.value)
			{
				wProxyWindow.https_panel.https_name.https_align.https_edit.password.text = wProxyWindow.http_panel.http_name.http_align.http_edit.password.text;
				wProxyWindow.https_panel.https_name.https_align.https_icon.icon_u.visible = false;
				wProxyWindow.https_panel.https_name.https_align.https_icon.icon_p.visible = false;
			}
		}
	
		wProxyWindow.https_panel.https_name.https_align.https_edit.user.onChanging = function()
		{
			wProxyWindow.https_panel.https_name.https_align.https_icon.icon_u.visible = false;
			wProxyWindow.https_panel.https_name.https_align.https_icon.icon_p.visible = false;
		}
	
		wProxyWindow.https_panel.https_name.https_align.https_edit.password.onChanging = function()
		{
			wProxyWindow.https_panel.https_name.https_align.https_icon.icon_u.visible = false;
			wProxyWindow.https_panel.https_name.https_align.https_icon.icon_p.visible = false;
		}
		
		wProxyWindow.header_text.header_itext.header_icon.onClick = function()
		{
			stockphoto.core.ProxyHelp();
		}
		
		var iDlgResult = 0;
		
		wProxyWindow.center();
		wProxyWindow.modal = true;
		
		iDlgResult = wProxyWindow.show();
		
		stockphoto.core.Proxy.BothOpen = 0;
		
		return iDlgResult;
}

stockphoto.core.ShowProxyDialogs = function(iReturnValue, iNumberOfTries)
{
	if ( "undefined" != typeof(iReturnValue) && "undefined" != typeof(iNumberOfTries))
	{
		var bShowAlert = (iNumberOfTries > 1);
		
		if(2 == iReturnValue)
		{
			return stockphoto.core.ShowHttpsProxyDialog(bShowAlert);
		}
		else
		{
			if(3 == iReturnValue)
			{
				return stockphoto.core.ShowHttpProxyDialog(bShowAlert);
			}
			else
			{
				if(4 == iReturnValue)
				{
					return stockphoto.core.ShowProxyDialog(bShowAlert);
				}
			}
		}
	}
	
}

stockphoto.core.InitProxyCredentials = function()
{
	var oProxyCredentials = stockphoto.core.GetProxyCredentials(false);

	if ("undefined" != typeof(oProxyCredentials))
	{
		stockphoto.impl.InitializeProxyCredentials(oProxyCredentials);
	}
}

stockphoto.core.checkProxyOnFail = function()
{
	stockphoto.impl.ResetProxyCheck();
	stockphoto.core.SendProxyCredentials();
}

stockphoto.core.SendProxyCredentials = function()
{

	if(0 == stockphoto.core.Proxy.ImplCalled)
	{
		stockphoto.core.Proxy.ImplCalled =1;
	}
	else
	{
		return 0;
	}

	var oProxyCredentials = {};
	var result = {};
	var iReturnValue = 0;
	var iDlgResult = 0;
	var iNumberOfTries = 0 ;
	var success = 1;
	var iResultLength = 9;
	var bReturnValue = true;
	do
	{
		oProxyCredentials = stockphoto.core.GetProxyCredentials(false);
		
		if( "undefined" != typeof(oProxyCredentials))
		{
			result = stockphoto.impl.SetProxyCredentials(oProxyCredentials);
		
			if("undefined" != typeof(result) && (iResultLength == result.length))
			{
				 iReturnValue = stockphoto.core.util.convertToInteger(result[0]);
		
				if (iReturnValue > 1)
				{	
						if (2 < iNumberOfTries++)
						{
							if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ) )
							{
								stockphoto.alertBox.alertBox(1031);
							}
							bReturnValue = false;
							break;
						}
					
						iReturnValue = stockphoto.core.ShowProxyDialogs(iReturnValue, iNumberOfTries);
					
						if(iReturnValue < 4)
						{
							bReturnValue = false;
							break;
						}
					
				}
				else
				{
					if (success == iReturnValue && iDlgResult > 0)
					{
						if (undefined != stockphoto.core.init.partnersXMLfsObj)
						{
							stockphoto.impl.UpdatePartnersXML(stockphoto.core.init.partnersXMLfsObj);
						}
					}
					bReturnValue = true;
					break;
				}
			}
			else
			{
				break;
			}
		}
		else
		{
			break;
		}
	}
	while (true)
	
	stockphoto.core.Proxy.ImplCalled =0;
	return bReturnValue;
			
}
//change ends
stockphoto.seachRequestKeys = [ [ "SearchRequest", "" ] ];

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

stockphoto.search.setFilter = function ( filterID, value, docID )
{
    if (stockphoto.search.showPreviousSettings[docID] == true)
    {
        stockphoto.search.settings[docID] = stockphoto.DL.NavBar.GetDrawerSettings(docID);
        stockphoto.search.showPreviousSettings[docID] = false;
    }
    
    var evalStr = "stockphoto.search.settings[" + docID + "]." + filterID + " = " + value + ";";
    eval(evalStr);

    // For autoOpen, update the default settings too, for subsequent prev search folders.
    if (filterID == 'autoOpen')
    {
        stockphoto.search.defaultSettings.autoOpen = value;
        stockphoto.prefs.SetAdvancedSearchAutoOpen(value);
    }
    stockphoto.DL.NavBar.setIsDefault(docID);
}

stockphoto.search.getSimplifiedKeyword = function ( docID )
{
	return stockphoto.search.searchKeyword[docID];
}

stockphoto.core.findDoc = function(docId)
{
	var docs = app.documents;

	for (i = 0; i < docs.length; i++)
	{
		var doc = docs[i];
		if (doc.id == docId)
		{
			stockphoto.DL.NavBar.PrepareNavBar( docId );
			return doc;
		}
	}
	return undefined;
}

stockphoto.core.eventTaskDelay = 0;
stockphoto.core.eventWatchdogID = 0;

stockphoto.core.dispatchEvents = function()
{
	if (stockphoto.impl.dispatchEvents())
	{
		if (stockphoto.core.eventWatchdogID != 0)
		{
			app.cancelTask(stockphoto.core.eventWatchdogID);
			stockphoto.core.eventWatchdogID = 0;
		}
		stockphoto.core.eventTaskDelay = 0;
	}
	else
	{
		if (stockphoto.core.eventWatchdogID == 0)
		{
			stockphoto.core.eventWatchdogID = app.scheduleTask("stockphoto.core.eventTaskDelay = 100;", 15000, false);
		}
		else if (stockphoto.core.eventTaskDelay > 0)
		{
			stockphoto.core.eventTaskDelay = Math.min(stockphoto.core.eventTaskDelay + 100, 500);
		}
	}
	stockphoto.core.eventTaskID = app.scheduleTask("stockphoto.core.dispatchEvents();", stockphoto.core.eventTaskDelay, false);
}

// ---------
// Utilities
// ---------

//stockphoto.core.util={};
stockphoto.core.util.NoOfSecondFrom01Jan1990=function( year, month, day, hour, minute, second ) 
{
	// 1 sec. from 1990/1/1
	stockphoto.core.util.MonthDaysTab=[0,31,59,90,120,151,181,212,243,273,304,334];
	var y, w, k, m, d, s;
	y = year;
	if( y < 80 ) 
	{
		y += 2000;
	} 
	else if( y < 100 )
	{
			y += 1900;
	}

	if( y <= 1901 )
	{
		w = 0;
	}
	else
	{
		w = y - 1901;
	}
	m  = w % 4;  // m=0,1,2,3(=leap year)
	k  = ( w-m ) / 4;
	d  = ( k * 1461 ) + ( m * 365 );
	d += ( stockphoto.core.util.MonthDaysTab[ month ] ) + ( day );
	if( ( m == 3 )&&( month > 1 ) )
	{
		d++; // 86400 
	}
	s = ( hour * 360 ) + ( minute * 60 ) + second;
	stockphoto.core.util.MonthDaysTab=[];
	return( s + ( 86400 * d ) );
}

stockphoto.core.util.convertToInteger=function( str ) 
{
	// strictly use only '0'-'9' characters / parseInt() does not work is there is a preceeding '0'
	var i, v=0, Bt;
	if (str != undefined)
	{
    	for( i=0; i<str.length; i++ ) 
    	{
    		Bt = str.charCodeAt( i );
    		if( ( Bt >= 48 )&&( Bt <= 57 ) ) v = ( 10*v ) + ( Bt-48 );
    	}
    	
		if (str.length > 0 && str.charCodeAt(0) == 45)
    	{
            v *= -1;
        }
	}
	
	return( v );
}

stockphoto.core.util.convertToBoolean=function( str )
{
	if( (undefined == str) || (1 > str.length) )
	{
		return false;
	}
	else
	{
		if( '1' == str.charAt(0))
		{
			return true;
		}
		else
		{
			return false;
		}
	}

}
stockphoto.core.util.resetFileName=function( name )
{
    var oResult;    
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
    {
        oResult = stockphoto.MiscUtils.file.resetFileName( name );
    }
    return oResult;
}

stockphoto.core.util.GetXMPObj = function(srcFile)
{
	var target, saveLevel=$.level;
	$.level = 0;
	try
	{
		if( srcFile instanceof Thumbnail )
			 target = srcFile;
		else target = new Thumbnail(srcFile);
	} catch(e) {
		$.level = saveLevel;
		return( undefined );
	}
	$.level = saveLevel;
	if (target instanceof Thumbnail)
	{
        target.refresh("metadata"); // Request a refresh before we get metadata
		if (stockphoto.core.isImageFile(target))
		{
			var m = target.metadata; // We don't need synchronous metadata here.
			if (m != undefined)
			{
				m.namespace = "http://ns.adobe.com/StockPhoto/1.0/";
				return m;
			}
		}
	}	
	return undefined;
}

stockphoto.core.util.isBMImageFile = function(target)
{
	var m = stockphoto.core.util.GetXMPObj( target );
	return (m != undefined) && ((m.KindOfImage == "Thumbnail") || (m.KindOfImage == "Comp") || (m.KindOfImage == "Purchased"));  
}

stockphoto.core.util.isBMCompImage = function(target)
{
	var m = stockphoto.core.util.GetXMPObj( target );	
	return (m != undefined) && (m.KindOfImage == "Comp");    
}

stockphoto.core.util.isBMPurchasedImage = function(target)
{
	var m = stockphoto.core.util.GetXMPObj( target );
	return (m != undefined) && (m.KindOfImage == "Purchased");    	
}

stockphoto.core.util.isBMThumbnailOrCompImage = function(target)
{
	var m = stockphoto.core.util.GetXMPObj( target );
	return (m != undefined) && ((m.KindOfImage == "Thumbnail") || (m.KindOfImage == "Comp"));  
}

stockphoto.core.util.allAreBMImages = function()
{
	var i;
	var	selection = app.document.selections;
	var count = selection.length;
	
	for (i = 0; i < count; i++)
	{
		if (! stockphoto.core.util.isBMImageFile(selection[i]))
		{
			return false;
		}
	}
	
	return true;
}

stockphoto.core.util.allAreBMCompImages = function()
{
	var i;
	var	selection = app.document.selections;
	var count = selection.length;
	
	for (i = 0; i < count; i++)
	{
		if (! stockphoto.core.util.isBMCompImage(selection[i]))
		{
			return false;
		}
	}
	
	return true;
}

stockphoto.core.util.allAreBMPurchasedImages = function()
{
	var i;
	var	selection = app.document.selections;
	var count = selection.length;
	
	for (i = 0; i < count; i++)
	{
		if (! stockphoto.core.util.isBMPurchasedImage(selection[i]))
		{
			return false;
		}
	}
	
	return true;
}

stockphoto.core.util.allAreBMThumbnailOrCompImages = function()
{
	var i;
	var	selection = app.document.selections;
	var count = selection.length;
	
	for (i = 0; i < count; i++)
	{
		if (! stockphoto.core.util.isBMThumbnailOrCompImage(selection[i]))
		{
			return false;
		}
	}
	
	return true;
}

//Watson:1337327
stockphoto.core.util.getASPImagesCount = function( bBreakAtFirstMatch )
{
    // Check if cache for this document+selection is still available
    // This does not check if previous value of bBreakAtFirstMatch is same - but we KNOW it won't be different...
    if (("undefined" != typeof stockphoto.core.getSelectInfoLastDoc)
        && (app.document.id == stockphoto.core.getSelectInfoLastDoc)
        && ("undefined" != typeof stockphoto.core.getASPImagesCountData))
     {
        return stockphoto.core.getASPImagesCountData;
     }

	var result = 0 ;

	var count = app.document.selectionLength;
    if (count <= 0) { return result; }
    if (count > 200) { count = 200; }  // Max

    var	selection = app.document.selections;
    var bBreakAtFirst = ("undefined" != typeof bBreakAtFirstMatch) && (true == bBreakAtFirstMatch);
    
	for (iter = 0; iter < count; iter ++)
	{
		var	thumbnail = selection[iter];
		if ((undefined == thumbnail) || (!stockphoto.core.isImageFile(thumbnail)))
		{
			continue;
		}
		
        var sKindOfImage = thumbnail.stockPhotoKind; // can be undefined
        
		if (("undefined" != typeof sKindOfImage)
		  && ("none" != sKindOfImage))
		{
			result++;
			if (true == bBreakAtFirst) { break; }
		}
	}
	
    // Store for next cache
	stockphoto.core.getSelectInfoLastDoc = app.document.id;
	stockphoto.core.getASPImagesCountData = result;
	
	return result;
}

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

stockphoto.core.util.normalizeFileName= function(inFilename)
{
	if ("undefined" == typeof(inFilename))
	{
		return "";
	}
	
	var outFilename = inFilename;
	var filename;

	if (inFilename.path == undefined)
	{
		filename = File.decode(inFilename);
	}
	else
	{
		filename = File.decode(inFilename.name);
	}


	//stockphoto filename must have at least 6 char in a name
	if (filename.length < 6)
	{
		return inFilename;
	}

	var first4Chars = filename.substr(0, 4);
	var next2Chars = filename.substr(4,2);
	var areFirst4Chars = isNaN(first4Chars);
	var areNext2Chars = isNaN(next2Chars);

	if ((areFirst4Chars == false) && (areNext2Chars == true))
	{	//4 digits follow by 2 characters.  then strip the 4 digits.
		filename = filename.substring(4, filename.length);
		while (filename.charAt(0) == ' ')
		{
			filename = filename.substring(1);
		}
	}
	
	if ((filename.length > 0) && ( '.' != filename.charAt(0)))
	{
		if (inFilename.path== undefined)
		{
			outFilename = filename;
		}
		else
		{
			outFilename = File (inFilename.path + "/" + filename);
		}
	}
	
	return outFilename;
}

// sLocale is optional
stockphoto.core.util.getLocaleFolderPath = function(startupPath, filename, sLocale)
{
	var pathSpec = "";
	
	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.core.util.loadLocaleData=function( filename ) 
{
	var fsIn   = undefined;
	var fsOpen = false;
  
	try
	{
		var fsNm = stockphoto.core.util.getLocaleFolderPath(Folder.startup, filename);
  
		fsIn = new File(fsNm);
  
		if ((fsIn != undefined) && (fsIn.exists))
		{
			if(fsIn.open())
			{
				fsOpen = true;
				var js = fsIn.read();
				eval(js);
			}
		}
	}
	catch (e)
	{
		// Do nothing here.
	}
  
	if (fsOpen)
	{
		fsIn.close();
	}
  
	if (fsIn != undefined)
	{
		delete fsIn;
	}

	return fsOpen;
}

stockphoto.core.util.addStockPhotoMetadata = function(thumbPath, params, synch)
{
    var oResult;    
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
    {
        oResult = stockphoto.MiscUtils.metadata.addStockPhotoMetadata(thumbPath, params, synch);
    }
    return oResult;
}

stockphoto.core.util.alertReadOnlyFolder = function(folder)
{
	if (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ))
	{
		stockphoto.alertBox.alertBox(stockphoto.alertBox.adapterComponentID + 14, unescape(folder));
	}
}

stockphoto.core.util.alertReadOnlyFolderExtraMsg = function(sFolder, sExtraMessage)
{
	if("undefined" == typeof sExtraMessage || "" == sExtraMessage)
	{
		stockphoto.core.util.alertReadOnlyFolder(sFolder);
	}
	else if (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ))
	{
		stockphoto.alertBox.alertBox(stockphoto.alertBox.adapterComponentID + 17, unescape(sFolder), zc.get(sExtraMessage));
	}
}

stockphoto.core.util.getDocumentWindowSizeAndLocation = function(doc)
{
	// Size and location in the returned object will be left as 'undefined' if
	// doc.content or app.document.content is invalid.

	var sizeAndLocation = {size:undefined, location:undefined};
	var size = {width:0, height:0};
	var location = {x:0, y:0};

	if (doc == undefined)
	{
		if ((0 < app.documents.length) && (app.document != undefined))
		{
			doc = app.document;
		}
	}

	if ((doc != undefined) && (doc.content != undefined))
	{
		if (doc.content instanceof Window)
		{
			sizeAndLocation.size = doc.content.size;
			sizeAndLocation.location = doc.content.location;
		}
	}

	return sizeAndLocation;
}

stockphoto.core.currentTime = new Date();
stockphoto.core.CurrentProcessID = stockphoto.core.util.NoOfSecondFrom01Jan1990
						( stockphoto.core.currentTime.getFullYear(), stockphoto.core.currentTime.getMonth(), stockphoto.core.currentTime.getDate(),
						  stockphoto.core.currentTime.getHours(), stockphoto.core.currentTime.getMinutes(), stockphoto.core.currentTime.getSeconds() );
delete stockphoto.core.currentTime; 
stockphoto.core.currentTime = undefined;

stockphoto.core.util.removeIllegalSearchChars = function(kwd)
{
	var modkwd = "";
	var i;
	for(i = 0; i < kwd.length; i++)
	{
	  // Currently remove only backslash char.	
    if (kwd.charCodeAt(i) != 92) // '\' (0x5C)
    {
			modkwd += kwd.charAt(i);    
    }
	}

	return modkwd;
}

stockphoto.core.util.bringParentToFront=function( doc_id /* this.parent.doc_id */ )
{
	if( ( doc_id >= 0 )&&( doc_id < stockphoto.documents.length ) )
	{
		var doc = stockphoto.documents[ doc_id ].document;
		if( doc != undefined )
		{
			app.bringToFront();
		}
	}
}

stockphoto.core.util.shortenString=function( inStr, MaxCharNo, NoOfTrailingWordsToRetain )
{
    var oResult;    
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
    {
        oResult = stockphoto.MiscUtils.strings.shortenString( inStr, MaxCharNo, NoOfTrailingWordsToRetain );
    }
    return oResult;
}

stockphoto.core.util.appendSearchParam = function ( sInStr, sAppParam)
{
	var sOutStr = sInStr;
	
	if (undefined != sOutStr)
	{
		if ("" != sOutStr)
		{
			sOutStr += " OR ";
		} 
	}
	else
	{
		sOutStr = "";
	}
	
	sOutStr += sAppParam;
	
	return sOutStr;
}

// Workaround for Bridge 316 -BEGIN-
stockphoto.core.util.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 = "";
	}
	if( stockphoto.core.log.DebugINIData.log != undefined ) 
	{
		if( thumb == undefined )
		{
			stockphoto.core.log.logString( 0, "["+where+"] thumb is undefined\n" );
		}
		else if( thumb.displayPath == undefined )
		{
			stockphoto.core.log.logString( 0, "["+where+"] thumb.displayPath is set to be: "+displayPath+"\n" );
		}
	}
	return( displayPath )
}

stockphoto.core.util.isDisplayPathEqual=function( displayPath1, displayPath2 )
{	// Another candidate of stockphoto.core.log.DebugINIData.Watson1280287
	try
	{
		if( stockphoto.isWin )
		{
			if( displayPath1.toUpperCase() == displayPath2.toUpperCase() )
				return( true );
		}
		else
		{
			if( displayPath1 == displayPath2 )
				return( true );
		}
	} catch(e) { Window.alert( "isDisplayPathEqual("+displayPath1+","+displayPath2+")\n"+e ); }
	return( false );
}
stockphoto.core.util.fixPathName=function( path )
{	// Another candidate of stockphoto.core.log.DebugINIData.Watson1280287
	var kPrefix, tmpPath, ff;
	try
	{
		kPrefix = path.indexOf( "bridge:fs:file:///" );
		if( kPrefix >= 0 )
		{
			tmpPath = path.substring( kPrefix+18, path.length );
			f = File( unescape( tmpPath ) );
			tmpPath = unescape( f.fsName );
			return( tmpPath );
		}
	} catch(e) { Window.alert( "fixPathName("+path+")\n"+e ); }
	return( path );
}
// Workaround for Bridge 316 -END-

// -------------------------------------------------------------------------------------- Util

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( "st00Core" );
var zc        = stockphoto.zc;

// ---------
// Constants
// ---------

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

stockphoto.core.consts.localizedErrorString=[
	/*00*/ zc.get("$$$/StockPhoto/ErrorMessage/NoSysTemp=A system temp directory can not be found."),
	/*01*/ zc.get("$$$/StockPhoto/ErrorMessage/JSXSystaxErr=Jsx file has a syntax problem: "),
	/*02*/ zc.get("$$$/StockPhoto/ErrorMessage/NoSuchScript=Script can not be found: "),
	/*03*/ "en",
	/*04*/ "US",
	/*05*/ zc.get("$$$/StockPhoto/ErrorMessage/NoCompSel=No Comp is selected."),
	/*06*/ zc.get("$$$/StockPhoto/ErrorMessage/Missing=Missing "),
	/*07*/ zc.get("$$$/StockPhoto/ErrorMessage/NoMyDoc=Can't create 'My Documents' folder"),
	/*08*/ zc.get("$$$/StockPhoto/ErrorMessage/NoSuchFolder=Could not create folder : "),
	/*09*/ zc.get("$$$/StockPhoto/ErrorMessage/NoPartners=Unable to load an image provider due to missing or damaged file. You may need to re-install Adobe Bridge."),
	/*10*/ zc.get("$$$/StockPhoto/ErrorMessage/InitBMailed=Unable to Initialize Stock Photos services. You may need to re-install Adobe Bridge.")
];
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..."
];

// these are strings we want localized but currently do not use in the source.
stockphoto.core.consts.unusedStrings=[
	/*00*/ zc.get("$$$/StockPhoto/Message/Loading=Loading Adobe Stock Photos...")
];

// -------------------------------------------------------------------------------------- Const

// ----
// init
// ----

stockphoto.core.init={};

stockphoto.core.init.isScriptLoaded      =false;
stockphoto.core.init.isInitDll           =false;

stockphoto.core.init.partnersXMLfsObj    =undefined;
stockphoto.core.init.partnersXMLnoOfCheck=0;

// The search.loadCollections function populates stockphoto.providers
// structure with the entries read from partners.xml
stockphoto.search.loadCollections = function()
{
    if ((stockphoto.providers.loaded == true)
        && (stockphoto.providers.collections != undefined)
        && (stockphoto.providers.collections.length > 0))
    {
        return;
    }
    
    // Load partner's xml
	if ( typeof stockphoto.core.BoxCar.AnalyzeXmlFileObj == "undefined" )
	{
		stockphoto.core.BoxCar.AnalyzeXmlFileObj = new stockphoto.core.BoxCar.AnalyzeXmlFile( stockphoto.core.init.partnersXMLfsObj, stockphoto.core.BoxCar.HTMLUtil.CheckKeys );
		if( ( typeof stockphoto.core.BoxCar.AnalyzeXmlFileObj == "undefined" )||
		    ( typeof stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners == "undefined" ) )
		{
			// we failed to load partner's xml
			return;
		}
	}
	
	stockphoto.providers.partners = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner;
	if( ( typeof stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Collections == "undefined" )||
	    ( typeof stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Collections[0].Collection == "undefined" ) )
	{
		stockphoto.providers.collections = [];
	} 
	else
	{
		stockphoto.providers.collections = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Collections[0].Collection;
	};
	
	stockphoto.providers.loaded = true;
}

// search.getCollectionList returns the list of collections
// available for display in the Advanced Options list
stockphoto.search.getCollectionsList = function()
{
  var cList = [];
  if ((stockphoto.providers != undefined) && (stockphoto.providers.collections != undefined))
  {
    cList = stockphoto.providers.collections;
  }

  return cList;
}

stockphoto.core.init.checkPartnersXML = function()
{
	// After calling this, stockphoto.core.init.partnersXMLfsObj
	// is "undefined" if partners.xml can not be found.
	var fsORGname, fsORGobj, verORGf, verORG, fsNEWdir, fsNEWname, fsNEWobj, verNEWf, verNEW,
		fsNEWcerNm, fsNEWcerObj, fsORGcerNm, fsORGcerObj, bNEWexist, j;

	// --- internal ---
	this.GetXmlVersion=function( fileObj )
	{
		var js, p1, p2, i, Bt, k=0, q=0;
		this.ver=[0,0,0,0];
		if( (fileObj != undefined )&&( fileObj.exists ) )
		{
			try 
			{
				fileObj.open();
				for( ; ; ) 
				{
					try
					{
						js = fileObj.readln();
						if( fileObj.eof )
						{
							break;
						}
						p1 = js.indexOf( "Partners" );
						if( p1 >= 0 )
						{
							p2 = js.indexOf( "=", p1+8 );
							if( p2 >= 0 )
							{
								for( i=p2+1; i<js.length; i++ )
								{
									Bt = js.charCodeAt( i );
									if( Bt == 46 /*.*/ )
									{
										if( ( ++k ) > 3 )
											break;
										continue;
									}
									if( ( Bt == 34 /*"*/ )||( Bt == 39 /*'*/ ) )
									{
										if( ( ++q ) > 1 )
											break;
										continue;
									}
									if( ( 48 /*0*/ <= Bt )&&( Bt <= 57 /*9*/ ) )
									{
										this.ver[ k ] = ( 10 * this.ver[ k ] ) + ( Bt - 48 /*0*/ );
									}
								}; // for
								fileObj.close();
								return;
							} // if( p2 >= 0 )
						} // if( p1 >= 0 )
					} catch(e) {
						; // No special error handling
					}
				} // for( ; ; ) 
				fileObj.close();
			} catch(e) {
				; // No special error handling
			}
		} // if( (fileObj != undefined )&&( fileObj.exists ) )
	}
	// --- internal --- End
	if( ( typeof stockphoto.core.init.partnersXMLfsObj == "undefined" )&&
	    ( stockphoto.core.init.partnersXMLnoOfCheck < 1 ) )
	{
		stockphoto.core.init.partnersXMLnoOfCheck ++; // for not testing redundantly
		if( stockphoto.isWin )    
		{
			fsORGname  = Folder.startup + "/../"+stockphoto.core.installFolder+"/Resources/partners.xml";
			fsORGcerNm = Folder.startup + "/../"+stockphoto.core.installFolder+"/Resources/bmcertificates.cer";
		}
		else // if( stockphoto.isMac )
		{
			fsORGname = stockphoto.startUpFolderForMac + "/Resources/partners.xml";
			fsORGcerNm = stockphoto.startUpFolderForMac + "/Resources/bmcertificates.cer";
		}
		fsORGobj   = new File( fsORGname );
		verORG     = new this.GetXmlVersion( fsORGobj ); // fsORGobj could be undefined
		if( verORG == undefined )
		{
			verORG  = [0,0,0,0];
			verORGf = false;
		}
		else
		{
			verORGf = true;
		}

		fsNEWdir   = ( Folder( stockphoto.core.folder.getMyShoppingCartFolder() ) ).parent;
		fsNEWname  = fsNEWdir + "/partners.xml";
		fsNEWcerNm = fsNEWdir + "/bmcertificates.cer";
		fsNEWobj   = new File( fsNEWname ); // fsNEWobj can be undefined
		verNEW     = new this.GetXmlVersion( fsNEWobj );
		if( verNEW == undefined )
		{
			verNEW  = [0,0,0,0];
			verNEWf = false;
		}
		else
		{
			verNEWf = true;
		}

		// Check and copy partners.xml
		for( j=0; j<4; j++ )
		{
			if( verORG.ver[j] < verNEW.ver[j] )
			{	// we already have new one
				break;
			} 
			else if( verORG.ver[j] > verNEW.ver[j] ) 
			{	// now we need to copy them
				if( stockphoto.core.folder.checkAndCreateFolder( fsNEWdir, true ) )
				{
					try	
					{
						if( ! fsORGobj.copy( fsNEWobj.fsName ) )
						{ // copy fails
							fsNEWobj.remove();
						}
					} catch(e) { ; /* No special error handling */ };
				}
				break;
			}
		}
		if( fsORGobj != undefined ) delete fsORGobj;
		if( verORGf )               delete verORG;
		if( fsNEWobj != undefined ) delete fsNEWobj;
		if( verNEWf )               delete verNEW;

		// Copy bmcertificates.cer
		fsNEWcerObj = new File( fsNEWcerNm );
		bNEWexist   = true;
		if( fsNEWcerObj == undefined )
		{
			bNEWexist = false;
		}
		else
		{
			if( ! fsNEWcerObj.exists )
			{
				bNEWexist = false;
			}
			delete fsNEWcerObj;
		}
		if( ! bNEWexist )
		{
			fsORGcerObj = new File( fsORGcerNm );
			if( fsORGcerObj != undefined )
			{
				if( fsORGcerObj.exists )
				{
					fsORGcerObj.copy( fsNEWcerNm );
				}
				delete fsORGcerObj;
			}
		} 

		// Set stockphoto.core.init.partnersXMLfsObj
		fsNEWobj = new File( fsNEWname );
		if( fsNEWobj != undefined )
		{
			if( fsNEWobj.exists )
			{
				fsNEWcerObj = new File( fsNEWcerNm );
				if( fsNEWcerObj != undefined )
				{
					if( fsNEWcerObj.exists )
					{ // both partners.xml and bmcertificates.cer exist
						stockphoto.core.init.partnersXMLfsObj = new File( fsNEWname );
					}
					delete fsNEWcerObj;
				}
			}
			delete fsNEWobj;
		}
		if( typeof stockphoto.core.init.partnersXMLfsObj == "undefined" )
		{
			stockphoto.core.init.partnersXMLfsObj = new File( fsORGname );
		}
	} // for the case stockphoto.core.init.partnersXMLfsObj = undefined
	// If still stockphoto.core.init.partnersXMLfsObj == undefined, it is the hopeless case

	if( stockphoto.core.init.partnersXMLfsObj != undefined )
	{
		if( ! stockphoto.core.init.partnersXMLfsObj.exists )
		{
			delete stockphoto.core.init.partnersXMLfsObj;
			stockphoto.core.init.partnersXMLfsObj = undefined;
		}
		stockphoto.search.loadCollections();
	}

} 

stockphoto.core.BoxCar=
{
	HTMLUtil:	{},
	LangCountry:{},
	NavBar: 	{ NavIntDt_t:[] }
}
stockphoto.core.BoxCar.HTMLUtil.CheckKeys=[ [ "Partners", "AdobeSupports" ],
											[ "Partners", "Collections" ],
											[ "Partners", "EComPartners" ],
											[ "Partners", "Partner" ] ];

// Analyze xml file
stockphoto.core.BoxCar.makeKey=function( s, bNoSpace )
{
	var i, v="", btcode, bSkip=false;
	for( i=0; i<s.length; i++ )
	{
		btcode = s.charCodeAt( i );
		if( btcode >= 32 )
		{
			switch( btcode )
			{
				case 39: // quote1v:
				case 34: // quote2v:
				case 43: // plusv:
						bSkip = true;
						break;
				case 32: // spacev:
						bSkip = bNoSpace;
						break;
				default:
						bSkip = false;
			}
		} else {
			bSkip = true;
		}
		if( ! bSkip )
			v += s.charAt( i );
	}
	return( v );
}
stockphoto.core.BoxCar.removeKeyData=[];
stockphoto.core.BoxCar.AnalyzeXmlFileObj=undefined;
stockphoto.core.BoxCar.AnalyzeXmlFile=function( XMLFileObj, CheckKeys )
{
	var i, j, k, szRec, nRec, nxmlTab, iDep, iDep_1, nGroup;
	var ncTab, wTmp, sTmp, tTmp, tree, bSw, j, i, chkResult, xmlTab, nRemoveDt;
	nxmlTab   = 0; 
	iDep      = 0; 
	nGroup    = 0;
	nRemoveDt = 0;
	xmlTab    = [];
	// --- Internal -----
	this.setContext=function( lpRec, iSt, nlpRec )
	{
		var i, j, Bt, prevBt, bInQuote1, bInQuote2, BtStart, BtEnd;
		for( i=iSt; i<nlpRec; i++ ) 
		{
			if( lpRec.charAt( i ) == '<' )
				break;
		} // finding 1st "<"
		if( i >= nlpRec )
		{
			this.type = "bad";
			return;
		}
		this.iSt  = i+1; // Pos of '<' + 1
		BtStart   = lpRec.charAt( this.iSt );
		bInQuote1 = false;
		bInQuote2 = false;
		prevBt    = " ";
		for( ; i<nlpRec; i++ )
		{
			Bt = lpRec.charAt( i );
			if( prevBt != '\\' )
			{
				if( bInQuote2 ) { if( Bt == '"' ) bInQuote2 = false; continue; }
				if( bInQuote1 ) { if( Bt == "'" ) bInQuote1 = false; continue; }
				// Not within quote
				if( Bt == '"' ) { bInQuote2 = true; continue; }
				if( Bt == "'" ) { bInQuote1 = true; continue; }
			}
			if( Bt == ">" ) break;
			prevBt = Bt;
		}
		this.iEd = i-1; // (pos of '>' or length) - 1
		BtEnd    = lpRec.charAt( this.iEd );
		if( ( BtStart == "?" )&&( BtEnd == "?" ) )
		{
			this.type = "head";
			( this.iEd )--;
		}
		else 
		{
			if( BtEnd == "/" )
			{
				this.type = "item";
				( this.iEd )--;
			}
			else if( BtStart == "/" )
			{
				this.type = "groupend";
				( this.iSt )++;
			}
			else 
			{
				this.type = "groupbegin";
			}
			for( i=this.iSt; i<=this.iEd; i++ )
			{
				if( lpRec.charAt( i ) != ' ' )
				{
					for( j=i+1; j<=this.iEd; j++ )
					{
						if( lpRec.charAt( j ) == ' ' )
						{
							break;
						}
					}
					this.id  = lpRec.substring( i, j );
					this.iSt = j;
					return;
				}
			}
		}
		this.id = "";
	}
	// --- Internal -----
	this.checkKey=function( cTab, dCont, ndCont )
	{
		var i, j, bAllOk;
		if( ndCont <= 0 )
			return( true );
		for( i=0; i<cTab.length; i++ )
		{
			bAllOk = true;
			for( j=0; j<ndCont; j++ )
			{
				if( cTab[i].key[j] == undefined )
					break;
				if( cTab[i].key[j] != dCont[j].idU )
				{
					bAllOk = false;
					break;
				}
			}
			if( bAllOk )
				return( true ); // for this i, keys are same
		}
		return( false );
	}
	// --- Internal -----
	this.MakeItemObj=function( lpRec, iSt, iEd )
	{
		var i, kSt, key, vSt, c1, bInQuote1, bInQuote2, Bt, value, wTmp;
		i = iSt;
		while( i <= iEd )
		{
			kSt = i;
			for( ; i<=iEd; i++ )
			{
				if( lpRec.charAt( i ) == "=" ) break;
			} 
			key = stockphoto.core.BoxCar.makeKey( lpRec.substring( kSt, i ), true );
			i++;
			for( ; i<=iEd; i++ ) 
			{
				if( lpRec.charAt( i ) != " " ) break;
			} // for i to find the first non-space character
			if( i > iEd ) break; // end of while
			vSt = i;
			c1  = lpRec.charAt( i );
			bInQuote1 = false;
			bInQuote2 = false;
			for( ; i<=iEd; i++ )
			{
				Bt = lpRec.charAt( i );
				if( bInQuote2 ) { if( Bt == '"' ) bInQuote2 = false; continue; }
				if( bInQuote1 ) { if( Bt == "'" ) bInQuote1 = false; continue; }
				// Not within quote
				if( Bt == '"' ) { bInQuote2 = true; continue; }
				if( Bt == "'" ) { bInQuote1 = true; continue; }
				if( Bt == " " ) break;
			} 
			value = stockphoto.core.BoxCar.makeKey( lpRec.substring( vSt, i ), false );
			if( c1 == "'" )
			     wTmp = "this."+key+"='"+value+"';\n";
			else wTmp = "this."+key+'="'+value+'";\n';
			try { eval( wTmp ); } catch(e) { ; };
			i++;
		}
	}
	// --- Internal -----
	this.registerMem=function( s )
	{
		this.s = s;
	}
	// --- Internal -----
	this.removeMem=function()
	{
		var iSaveLevel = $.level;
	    $.level = 0;
	
		var i;
		for( i=stockphoto.core.BoxCar.removeKeyData.length-1; i>=0; i-- )
		{
		    try
            {
                eval( "delete "+stockphoto.core.BoxCar.removeKeyData[i].s+";\n"+stockphoto.core.BoxCar.removeKeyData[i].s+"=undefined;\n" );
                delete stockphoto.core.BoxCar.removeKeyData[i];
    			stockphoto.core.BoxCar.removeKeyData[i] = undefined;
			}
			catch (ex)
			{
            }
		}
		
		$.level = iSaveLevel;
	}
		
		// --- Internal -----
	// Note: Changes szRec in-place
	this.convertEscapeSequence=function( sSequence, sReplacement )
	{
	    var bReplaced = false; 
	    if (szRec != undefined)
        {
            while (szRec.search(sSequence) != -1)
            {
                szRec = szRec.replace(sSequence,sReplacement);
                bReplaced = true;
            }
        }
        return bReplaced;
    }
    // --- Internal -----
    // Parses 'szRec' and converts XML Escape Sequences
	this.convertEscapeSequences=function()
	{
        if (szRec != undefined)
        {
            var bFoundEscapeSequence;    
            do
            {
                bFoundEscapeSequence = this.convertEscapeSequence(/&quot;/g,'"')
                        || this.convertEscapeSequence(/&apos;/g,'\'')
                        || this.convertEscapeSequence(/&amp;/g,'&')
                        || this.convertEscapeSequence(/&lt;/g,'<')
                        || this.convertEscapeSequence(/&gt;/g,'>'); 
            } while (bFoundEscapeSequence);
        }
    }
	// --- Internal ----- End -----

	if( XMLFileObj.exists )
	{
		if( XMLFileObj.open() )
		{
			try
			{
				szRec = XMLFileObj.read();
			} catch(e) { ; };
			nRec = szRec.length;

			this.convertEscapeSequences();
			
			for( k=0; ; k++ )
			{
				xmlTab[ nxmlTab ] = new this.setContext( szRec, k, nRec );
				if( ( xmlTab[ nxmlTab ] == undefined )||
				    ( xmlTab[ nxmlTab ].type == "bad" ) )
					break;
				k = xmlTab[ nxmlTab ].iEd+1;
				if(	( xmlTab[ nxmlTab ].iSt > k )||( k >= nRec ) )
					break;
				switch( xmlTab[ nxmlTab ].type )
				{
					case "groupbegin":
							nGroup++;
							iDep++;
							break;
					case "groupend":
							iDep--;
				}
				nxmlTab++;
			}

			ncTab = CheckKeys.length;
			wTmp  = "var cTab=[";
			for( k=0; k<ncTab; k++ ) 
			{
				if( k > 0 ) wTmp += ",\n";
				wTmp += ( "{ key:[" );
				for( j=0; j<CheckKeys[k].length; j++ )
				{
					if( j > 0 ) wTmp += ", ";
					wTmp += '"'+( ( stockphoto.core.BoxCar.makeKey( CheckKeys[k][j], false ) ).toUpperCase() )+'"';
				} 
				wTmp += "] }";
			}
			wTmp += "];\n";
			try { eval( wTmp );  } catch(e) { ; }; // Create var cTab[]

			wTmp = "var dCont=[";
			for( k=0; k<=nGroup+2; k++ )
			{
				if( k > 0 ) wTmp += ",";
				wTmp += '{ n:0, id:"", idU:"" }';
			} // Create dCont
			wTmp += "]\n";
			try { eval( wTmp ); } catch(e) { ; }; // Create var dCont

			iDep = 0;
			for( k=0; k<=nxmlTab; k++ )
			{
				if( xmlTab[ k ] != undefined  )
				{
					switch( xmlTab[ k ].type )
					{
						case "groupbegin":
								iDep      = ( iDep_1 = iDep ) + 1;
								dCont[ iDep_1 ].id  = stockphoto.core.BoxCar.makeKey( xmlTab[ k ].id, false );
								dCont[ iDep_1 ].idU = ( dCont[ iDep_1 ].id ).toUpperCase();
								chkResult = this.checkKey( cTab, dCont, iDep );
								wTmp      = "this.";
								for( i=0; i<iDep_1; i++ )
								{
									wTmp += dCont[ i ].id+"["+dCont[ i ].n+"].";
								}
								wTmp += dCont[ iDep_1 ].id;
								sTmp = "if("+wTmp+"==undefined) "+wTmp+"=[];\n";
								try { eval( sTmp ); } catch(e) { ; };
								tree = "// ";
								for( i=0; i<nGroup; i++ )
								{
									bSw  = false;
									sTmp = "if("+wTmp+"["+i+"]==undefined) bSw=true;\n";
									try { eval( sTmp ); } catch(e) { ; };
									if( bSw )
									{
										tree = wTmp+"["+i+"]";
										stockphoto.core.BoxCar.removeKeyData[ nRemoveDt ] = new this.registerMem( tree );
										nRemoveDt++;
										try { eval( tree+"=new this.MakeItemObj(szRec,"+xmlTab[k].iSt+","+xmlTab[k].iEd+");\n" ); } catch(e) { ; };
										dCont[ iDep_1 ].n = i;
										break;
									}
								}	
								break;
						case "groupend":
								iDep--;
								dCont[ iDep ].n = 0;
								chkResult = this.checkKey( cTab, dCont, iDep );
								break;
						case "item":
								if( chkResult )
								{
									tTmp = tree + "." + xmlTab[k].id;
									stockphoto.core.BoxCar.removeKeyData[ nRemoveDt ] = new this.registerMem( tTmp );
									nRemoveDt++;
									wTmp = tTmp+"=new this.MakeItemObj(szRec,"+xmlTab[k].iSt+","+xmlTab[k].iEd+");\n";
									try { eval( wTmp ); } catch(e) { ; };
								}
								break;
						case "head": // continue - for k
						case "bad":
						default:
					} // switch
				}
			} // for k

			XMLFileObj.close();
		}
	} // XML file exists
	for( k=0; k<=nxmlTab; k++ )
	{
		if( xmlTab[k] != undefined )
		{
			delete xmlTab[k];
			xmlTab[k] = undefined;
		}
	}
	xmlTab = [];
	cTab   = [];
	dCont  = [];
}

stockphoto.core.setOpenWithArrays = function( aArray )
{
	if (aArray == undefined || stockphoto.core.util.convertToInteger(aArray[0]) == -1 || aArray.length==0)
	{
		stockphoto.core.openWith.noShow=0;
		// if SPSUI returns a undefined value, we dont have any backup open with list
		return;
	}
	stockphoto.core.openWith.noShow=1;
	stockphoto.core.openWith.defaultIndex = stockphoto.core.util.convertToInteger(aArray[0]);
	var iIndex;
	var iArrIndex = 0;
	for (iIndex=1; iIndex < aArray.length; iIndex += 2)
	{
		stockphoto.core.openWith.displayMenu[iArrIndex] = aArray[iIndex];
		stockphoto.core.openWith.pathArray[iArrIndex] = aArray[iIndex + 1];
		iArrIndex++;
	}
	var iDefaultIndex = stockphoto.core.openWith.defaultIndex;
	if (stockphoto.core.openWith.displayMenu[iDefaultIndex] != undefined)
	{
		stockphoto.core.openWith.displayMenu[iDefaultIndex] = stockphoto.core.openWith.displayMenu[iDefaultIndex] + zc.get("$$$/StockPhoto/OpenWith/default= (default)");
	}
}

stockphoto.core.init.loadVC = function()
{
	var oRequest =
	{
		sCurrentLocale : stockphoto.core.getValidLocale(),
		sLblFiles : zc.get(stockphoto.core.SaveComp.LBL_FILES),
		sLblFile : zc.get(stockphoto.core.SaveComp.LBL_FILE),
		sLblSaveCompIn : zc.get(stockphoto.core.SaveComp.LBL_SAVE_COPY_IN),
		sLblDownloadedCompFolder : zc.get(stockphoto.core.SaveComp.LBL_DOWNLOADED_COMP_FLD),
		sLblPurchasedImgFolder : zc.get(stockphoto.core.SaveComp.LBL_PURCHASED_IMAGE_FLD) ,
		sLblDoNotRename : zc.get(stockphoto.core.SaveComp.LBL_DO_NOT_RENAME) ,
		sLblRename : zc.get(stockphoto.core.SaveComp.LBL_RENAME) ,
		sLbl001 : zc.get(stockphoto.core.SaveComp.LBL_001) ,
		sLbl002 : zc.get(stockphoto.core.SaveComp.LBL_002) ,
		sLblComma : zc.get(stockphoto.core.SaveComp.LBL_COMMA ),
		sLblEllipse : zc.get(stockphoto.core.SaveComp.LBL_ELLIPSES) ,
		sLblDownloading : zc.get(stockphoto.core.SaveComp.LBL_DOWNLOADING) ,
		sLblDownloadOptions : zc.get(stockphoto.core.SaveComp.LBL_DOWNLOAD_OPTN) ,
		sLblFileNameOptions : zc.get(stockphoto.core.SaveComp.LBL_FILE_NAME_OPTN) ,
		sLblNewFileName : zc.get(stockphoto.core.SaveComp.LBL_NEW_FILE_NAME) ,
		sLblSaveAs : zc.get(stockphoto.core.SaveComp.LBL_SAVE_AS),
		sLblSave : zc.get(stockphoto.core.SaveComp.LBL_SAVE),
		sLblCancel : zc.get(stockphoto.core.SaveComp.LBL_CANCEL),
		sLblSaveIn : zc.get(stockphoto.core.SaveComp.LBL_SAVE_IN),
		sErrFileAlreadyExist : zc.get2Arg(stockphoto.core.SaveComp.MSG_FILE_ALREADY_EXIST, "\"%1\"", "\"%2\""),
		sErrInvalidFileName : zc.get1Arg(stockphoto.core.SaveComp.INVALID_FILE_NAME_ERR, "\"%1\"") ,
		sErrBlankFileName : zc.get(stockphoto.core.SaveComp.BLANK_FILE_NAME_ERR),
		sLblYes : zc.get(stockphoto.core.SaveComp.LBL_YES),
		sLblNo : zc.get(stockphoto.core.SaveComp.LBL_NO)
	};
	stockphoto.bIsVCInitialized = stockphoto.impl.initSaveAsZStrings(oRequest);
}

stockphoto.core.init.loadBMScripts = function(noDMQCheck)  
{

	// stockphoto.core.init.isInitDll == true implies that this function is called
	// stockphoto.core.init.isScriptLoaded == true implies that this function is called and BM is loaded successfully
	// function returns "stockphoto.core.init.isScriptLoaded".
	var zc = stockphoto.zc;
	var dllPath;
	var dllFileObj;
	var CurrFolder, DllFolder;
	var partnerList = [ ];

	if (stockphoto.core.init.isInitDll == false) 
	{

		stockphoto.core.log.logString( 0, "\n***** stockphoto.core.init.loadBMScripts starts *****\n" );
		stockphoto.core.log.logString( 0, "ScriptUI version:" + Window.version);

		stockphoto.core.init.isInitDll = true;

        // Removed status bar message
		//app.document.status = 
        var appdocstatus = zc.get("$$$/StockPhoto/StatusBarMessage/InitializingStarted=Initializing Adobe Stock Photos");
        
		if (stockphoto.isWin)    
		{
			dllPath = Folder.startup + "/../"+stockphoto.core.installFolder+"/spsui.dll";
		}
		else // if (stockphoto.isMac)
		{
			dllPath = stockphoto.startUpFolderForMac + "/Plugins/spsui.bundle";
		}

		if ( typeof stockphoto.core.init.partnersXMLfsObj == "undefined" )  //check if 1st time and set value in function.
		{
			stockphoto.core.init.checkPartnersXML();
		}

		if ( typeof stockphoto.core.init.partnersXMLfsObj == "undefined" )  //check 2nd time.  value may have changed.
		{
			stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[9], 2);
			return( false );
		}

		dllFileObj = new File(dllPath);
		if (!dllFileObj.exists) 
		{
			//show message of which component missing
			stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[6] + dllPath, 2);

			//show error message for user what to do.
			stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[9], 2);
			return( false );
		}

		CurrFolder = Folder.current;
		DllFolder  = stockphoto.core.folder.getDllFolder();
		if( DllFolder != "/./" )
		{
			Folder.current = DllFolder;
		}
		try
		{
		    /* PERF */ if (stockphoto.timeKeeperNewOn) { stockphoto.core.util.startTimer("Loading C++ LiveObject"); }
            // Try to load SPSUI.dll (on Windows) or spsui.bundle (on Macintosh)
			stockphoto.lib = new ExternalObject("lib:" + File.decode(dllPath));
			/* PERF */ if (stockphoto.timeKeeperNewOn) { stockphoto.core.util.writeTimer("Loading C++ LiveObject"); }
		}
		catch(e)
		{
			stockphoto.DL.generalAlertBox(zc.get("$$$/StockPhoto/ErrorMessage/Error=Error: ") + e, 2);
		}
		try 
		{
            // If SPSUI.dll / spsui.bundle is loaded successfully without problems,
            // it makes the StockPhotos LiveObject available in ExtendScript as 'stockphoto.impl' .
            // If it's not defined yet, we can't proceed to load Stock Photos...
            if (typeof stockphoto.impl == "undefined")
            {
                stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[10], 2);
                return( false );
            }
            
//			partnerList = stockphoto.impl.initialize(stockphoto.core.init.partnersXMLfsObj);
			stockphoto.core.InitProxyCredentials();
			stockphoto.core.SaveComp.FirstInit = 1 ;
			partnerList = stockphoto.impl.initialize( stockphoto.core.init.partnersXMLfsObj, stockphoto.core.folder.BMTempFolderObj );
			if( stockphoto.Burp.doCheckFurther ) // in loadBMScripts(), initialize
			{
			/*B*/	try
			/*B*/	{
			/*B*/		if( ! stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Burp ) )
			/*B*/		{
			/*B*/			stockphoto.Burp.doCheckFurther = false;
			/*B*/		}
			/*B*/	}	
			/*B*/	catch( e )
			/*B*/	{
			/*B*/		stockphoto.Burp.doCheckFurther = false;
			/*B*/	}
			/*B*/	try 
			/*B*/	{
			/*B*/		if( stockphoto.Burp.doCheckFurther )
			/*B*/		{
			/*B*/			stockphoto.Burp.initialize( stockphoto.core.init.partnersXMLfsObj.fsName );
			/*B*/		}
			/*B*/	} catch(e) { ; }
			}
		}
		catch (e)
		{
			stockphoto.DL.generalAlertBox(zc.get("$$$/StockPhoto/ErrorMessage/Error=Error: ") + e, 2);
			return( false );
		}

		if (partnerList == undefined)
		{
			stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[10], 2);
			return( false );
		} 
		if (partnerList.length == 0)
		{
			stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[9] + xmlFileObj, 2);
			return( false );
		}
		//save the partner list in registry.
		app.preferences.bm_partners = partnerList.toSource();
		if( DllFolder != "/./" )
		{
			Folder.current = CurrFolder;
			// Removed status bar message
			//app.document.status = 
            var appdocstatus = zc.get("$$$/StockPhoto/StatusBarMessage/InitializingCompleted=Completed initializing Adobe Stock Photos");
		}

		// get the URL filter key for eCom
		//
		var request =
		{
			group: "EComPartners",
			xmlPath: Folder.decode(stockphoto.core.init.partnersXMLfsObj.fsName),
			keyword: "HistoryFilterKey",
			iteration: 1,
			eventHandler: function() {}
		};
		
		stockphoto.core.historyFilterKey = stockphoto.impl.getValue(request);
 
		stockphoto.core.init.isScriptLoaded = true;

		stockphoto.core.eventTaskID = app.scheduleTask("stockphoto.core.dispatchEvents();", 0, false);

		var doDMQCheck = (noDMQCheck == undefined) || (noDMQCheck == false);
		if (doDMQCheck == true)
		{
			// check download mgr for files on bridge startup
			var cmdStr = "stockphoto.DL.doCheckDownloadMgrQueueOnStartup();";
			app.scheduleTask(cmdStr, 1000, false);
		}
		stockphoto.core.ui.initAboutText();
		
		// init partner display name to partner name mapping
		stockphoto.core.createPartnerDisplayNameToPartnerNameMap();

		// KR sending the locale value for save-as dlg localization.
		
		// send a call to fetch the 'open with' menu
		try
		{
			var aOpenWithArr = stockphoto.impl.initOpenWith();
		}
		catch(exception)
		{
			aOpenWithArr = undefined;
		}
		if( undefined == aOpenWithArr )
		{
			stockphoto.core.openWith.length=0;
			stockphoto.core.openWith.noShow=0;
		}
		else
		{
			stockphoto.core.openWith.length = aOpenWithArr.length;
			stockphoto.core.setOpenWithArrays(aOpenWithArr);
		}
		
		// Initialize ASP Reference
		stockphoto.impl.initASPRef({ imageIDType: stockphoto.core.ImageID.ID, ASPRefFilenamePrefix: stockphoto.core.ImageID.ASPRefFilenamePrefix,
                                        ASPRefFilenameSuffix: stockphoto.core.ImageID.ASPRefFilenameSuffix});

		
		if(("Macintosh" == File.fs) && ($.os.indexOf("10.5") >= 0) )
		{                           
			if ((stockphoto.core.BoxCar != undefined)
				&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj != undefined)
				&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners != undefined)
				&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0] != undefined)
				&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports != undefined)
				&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0] != undefined)
				&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].LeopardSaveAs != undefined)
				&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].LeopardSaveAs.Value != undefined)
				&& ("no" == stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].LeopardSaveAs.Value))
			{
			   //Disable SaveAs for Leopard
				stockphoto.bIsVCInitialized = false;
			}                                        
		}
	}
	return( stockphoto.core.init.isScriptLoaded );
}

stockphoto.core.init.initializeBM = function( thumbnail )
{
	if (!stockphoto.thumbs.initialized)
	{
		stockphoto.thumbs = new stockphoto.core.Thumbs();
	}
	if (!stockphoto.places.initialized)
	{
		stockphoto.core.log.logString(0,"\n***** stockphoto.places Initializing *****\n");
		stockphoto.places = new stockphoto.core.Places( thumbnail );
	}
}

// -------------------------------------------------------------------------------------- init

// === log / dump ===

stockphoto.core.dumpObj = function(obj)
{
	var e = "";
	for (i in obj)
	{
		if (e == "")
		{
			e += "{ ";
		}
		else
		{
			e += ", ";
		}
		e += i + ":" + obj[i];
	}
	e += " }";
	return e;
}

stockphoto.core.log={};	

stockphoto.core.log.DebugINIData={};

stockphoto.core.log.dumpObj = function(prefix, obj)
{
	stockphoto.log(prefix + stockphoto.core.dumpObj(obj));
}

stockphoto.core.log.logString=function( lev, iStr )
{	// lev: 0:Everything 1:important only 2:very important only<=default>
	if( stockphoto.core.log.DebugINIData != undefined ) 
	{
		if (( stockphoto.core.log.DebugINIData.log != undefined ) 
		  && (lev >= stockphoto.logLevel))
		{
			var fsName = stockphoto.core.log.DebugINIData.log;   
			var fs = new File( fsName );
			if( fs != undefined ) 
			{
				if( fs.exists ) 
				{
					if( stockphoto.core.log.DebugINIData.logISW ) 
					{
						stockphoto.core.log.DebugINIData.logISW = false;
						fs.remove();
						delete fs; fs = undefined;
						fs = new File( fsName );
						fs.encoding = "UTF-8";
						fs.open( "w" , "TEXT", "????" );
						fs.close();
					}
				}
			}
			if( fs != undefined ) 
			{
				fs.open( "e" , "TEXT", "????" );
				fs.seek( 0, 2 );
				fs.write( iStr+"\n" );
				fs.close();
				delete fs;
			}
		}
	}
}

stockphoto.core.log.logObject=function( lev, prefix, obj ) 
{
	// lev: 0:Everything 1:important only 2:very important only<=default>
//	var e = "";
	var i, e = "";
	for (i in obj) 
	{
		if (e == "")
		{
			 e += "{ ";
		}
		else 
		{
			e += ", ";
		}
		e += i + ":" + obj[i];
	}
	e += " }";
	stockphoto.core.log.logString( lev, prefix+e );
}

stockphoto.core.log.getDebugSwitch = function()
{
	// If there is Debug.ini, it set stockphoto.core.log.DebugINIData object.
	// Format of Debug.ini.
	//  DebugURL: "DebugURL.htm"
	//  log: <path of logfile>, MUST be a full path
	//  lev: 0:Everything 1:important only 2:very important only<=default>
	if( stockphoto.core.log.DebugINIData != undefined )
	{
 		var fs = new File( stockphoto.core.folder.getResourceFolder() + "/DebugES.ini" ), bUseThis=true;
 		if( fs == undefined ) 
		{
 			bUseThis = false;
 		} 
		else 
		{ 
 			if( ! fs.exists ) 
			{
 				delete fs;
 				bUseThis = false;
 			}
 		}
 		if( ! bUseThis )
		{
 			fs = new File( stockphoto.core.folder.getResourceFolder() + "/Debug.ini" );
		}
 		if( ( fs != undefined )&&( fs.exists ) ) 
		{
			fs.open();
			js = "";
			for( ; ; ) 
			{
				jsNx = fs.readln();
				if(( jsNx == "" )||( fs.eof )) 
				{
					break;
				}
				if( js == "" )
				{
					 js  ="logISW: true,\n";
				}
				else 
				{
					js += ",\n";
				}
				js += jsNx;
			}
			fs.close();
			jsNx = "stockphoto.core.log.DebugINIData={\n"+js+"}\n";
			try 
			{
				eval(jsNx);
				if( stockphoto.core.log.DebugINIData.log != undefined )
				{
					if( stockphoto.core.log.DebugINIData.log.charAt(0) != '/' )
					{
						stockphoto.core.log.DebugINIData.log = ( Folder( stockphoto.core.folder.getMyShoppingCartFolder() ) ).parent+"/"+stockphoto.core.log.DebugINIData.log;
					}
				}
			} 
			catch(e) 
			{ // this is to catch syntax error
				stockphoto.DL.generalAlertBox(stockphoto.core.folder.getResourceFolder()+"/Debug.ini has a syntax problem.", 2);
				stockphoto.core.log.DebugINIData={};
			}
			delete fs;
		}
	}
	if( stockphoto.core.log.DebugINIData.log != undefined ) 
	{
		$.level=1;
	}

	if (undefined != stockphoto.core.log.DebugINIData.lev)
	{
        stockphoto.logLevel = stockphoto.core.log.DebugINIData.lev;
    }
    if (undefined != stockphoto.core.log.DebugINIData.timekeepernew)
    {
        stockphoto.timeKeeperNewOn = stockphoto.core.log.DebugINIData.timekeepernew;
    }
}

// -------------------------------------------------------------------------------------- log

// === folders ===

stockphoto.core.createFolderNamespace = function()
{
	var prefix = "";
	var flattened = app.preferences.bm_folderNamesArray;
	
	if (stockphoto.isWin)
	{
		prefix = "./";
	}
	else
	{
		prefix = "/";
	}
	
	if (flattened != undefined)
	{
		stockphoto.core.folder = eval(flattened);
		
		// check that all properties are defined in prefs entry
		if ((stockphoto.core.folder.MySearches == undefined)
			|| (stockphoto.core.folder.MyComp == undefined)
			|| (stockphoto.core.folder.MyPurchased == undefined)
			|| (stockphoto.core.folder.MyShoppingCart == undefined))
		{
			flattened = undefined;
		}
	}
	
	// if any property missing, create new prefs entry
	if (flattened == undefined)
	{
		stockphoto.core.folder = {};
		stockphoto.core.folder.MySearches		= prefix + stockphoto.core.consts.localizedMenuString[4];
		stockphoto.core.folder.MyComp			= prefix + stockphoto.core.consts.localizedMenuString[1];
		stockphoto.core.folder.MyPurchased		= prefix + stockphoto.core.consts.localizedMenuString[2];
		stockphoto.core.folder.MyShoppingCart	= prefix + "ShoppingCart";		// Do Not localize this string
		
		app.preferences.bm_folderNamesArray = stockphoto.core.folder.toSource();
	}
}

stockphoto.core.createFolderNamespace();

stockphoto.core.folder.getScriptFolder = function() 
{
	if (stockphoto.isWin)
	{
		return Folder.startup + "/../"+stockphoto.core.installFolder ;
	}
	return stockphoto.startUpFolderForMac + "/Resources/Scripts";
}

stockphoto.core.folder.getResourceFolder = function() 
{
	if (stockphoto.isWin) 
	{
		return Folder.startup + "/../"+stockphoto.core.installFolder ;
	}
	return stockphoto.startUpFolderForMac + "/Resources";
}

stockphoto.core.folder.getDllFolder = function() 
{
	if (stockphoto.isWin)
	{
		return Folder.startup + "/../"+stockphoto.core.installFolder ;
	}
	return "/./";
}

stockphoto.core.folder.checkAndCreateFolder = function( d, bCheckWrite ) 
{
	var f=new Folder(d);
	if( f == undefined ) 
	{
		return( false );
	} 
	else 
	{
		if( f.exists ) 
		{
			if( f instanceof File )
			{
				return( false );
			}
		} 
		else 
		{
			f.create();
			if( ! f.exists )
			{
				return( false );	
			}
		}
		delete f;
	}
	if( ! bCheckWrite )
	{
		return( true );
	}
	// check if this folder is writable
	var Nm    =d+"/__test_test__.txt";
	var testfl=new File( Nm );
	if( testfl != undefined ) 
	{
		if( testfl.open( "w", "TEXT", "????" ) ) 
		{
			testfl.write( "?" );
			testfl.close();
			delete testfl;
			var checkfl=new File( Nm );
			if( checkfl != undefined ) 
			{
				if( checkfl.exists ) 
				{
					checkfl.remove();
					delete checkfl;	
					return( true );
				}
				delete checkfl;
			}
		}
		delete testfl;
	}
	return( false );
}  

stockphoto.core.folder.BMTempFolderObj = new Folder(Folder.temp + "/"+stockphoto.core.installFolder);

// Given an array of directory names such as [a,b,c,d], it creates a folder /a/b/c/d.
stockphoto.core.folder.createFolderTree = function(d,s) 
{
	var f=d, iMax=s.length-1, bCheckWrite;
	for( i=0; i<=iMax; i++ ) 
	{
		f += ( "/"+s[i] );
		if( i == iMax )
		{
			bCheckWrite = true;
		}
		else 
		{
			bCheckWrite = false;
		}
		if( ! stockphoto.core.folder.checkAndCreateFolder( f, bCheckWrite ) )
		{
			return( false );
		}
	}
	stockphoto.core.folder.BMTempFolderObj = f;
	return( true );
}

stockphoto.core.folder.copyFolderContents = function(s,d) 
{
	var Nm, j, fls, sFldr=new Folder( s );
	if( sFldr.exists ) 
	{
		fls = sFldr.getFiles( "*" ); // in folder.copyFolderContents()
		if( ( fls != undefined )&&( fls != null ) ) 
		{
			for( j=0; j<fls.length; j++ ) 
			{
				Nm = fls[j].name;
				if( fls[j] instanceof File ) 
				{
					try 
					{
						if( ( fls[j].name ).toUpperCase() != "THUMBS.DB" )
						{
							fls[j].copy( d+"/"+Nm );
						}
					} 
					catch(e) 
					{
						; // do next
					}
				} 
				else 
				{
					stockphoto.core.folder.checkAndCreateFolder( d+"/"+Nm, true );
					stockphoto.core.folder.copyFolderContents( s+"/"+Nm, d+"/"+Nm );
				}
			} // j
		} // valid fls
	}
	delete sFldr;
}

stockphoto.core.folder.getTempFolder = function() 
{
	if (!stockphoto.core.folder.BMTempFolderObj.exists)
	{
		stockphoto.core.folder.BMTempFolderObj.create();
	}

	// Until all NavBar script uses the absolute path to the folder that
	// contains images, the \template\images\... are copied to this temporary place.
	var bOk, lpDst, dTab=[];
	var d=stockphoto.core.folder.BMTempFolderObj.fsName;
	if( stockphoto.core.folder.checkAndCreateFolder(d, true) ) 
	{
		bOk = true;
	} 
	else 
	{
		if (stockphoto.isWin)
		{
			dTab=[ "StockPhotosTemp", "tmp" ];
		}
		else 
		{
			dTab=[ "Library", "Application Support", "Adobe", "StockPhotos", "tmp" ];
		}
		
    bOk = stockphoto.core.folder.createFolderTree( "~", dTab ); 
	}
	if( bOk ) 
	{
		// stockphoto.core.folder.BMTempFolderObj has a full path
		lpDst = stockphoto.core.folder.BMTempFolderObj+"/images";

        if (!(Folder(lpDst).exists))
        {
			stockphoto.core.folder.checkAndCreateFolder( lpDst, true );
			stockphoto.core.folder.copyFolderContents( stockphoto.core.folder.getTemplateFolder()+"/images", lpDst );
		}
		return( stockphoto.core.folder.BMTempFolderObj );
	}
	stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[0], 2);
		
	stockphoto.core.folder.BMTempFolderObj = "";

	return( stockphoto.core.folder.BMTempFolderObj );
}

// Adobe Stock Photos' temporary directory:
//	<OS's temp>/Adobe Stock Photos/images
//	                              /nnnnnnnnnn
//	                              /<Locale><NavVersion>
//		where nnnnnnnn is an integer that is a number of seconds since 1990/1/1.
//		The folder "nnnnnnnnnn" will remain undeleted for 24 hours.
//		this contains all temporary data files and html files. 
//		The folder <Locale><NavVersion> contains html files and stylesheet
//		for Navbars. The folder will be kept until <NavVersion> is equal to
//		stockphoto.impl.version. 
//		See stockphoto.NavExtFnc.finalCleanUp() on how the temporary folders are removed.
stockphoto.core.folder.getSaveNavbarFolder = function()
{
	var f, verStr="0.0.0";
	if( stockphoto.core.init.isInitDll )
	{
		verStr = stockphoto.impl.version + "." + stockphoto.impl.build;
	}
	f = stockphoto.core.folder.getTempFolder()+"/"+stockphoto.core.getValidLocale()+verStr;
	return( f );
}

stockphoto.core.folder.getTemplateFolder = function() 
{
	return( stockphoto.core.folder.getResourceFolder()+"/Template" );
}

stockphoto.core.folder.createMyFolder = function(subFolder)
{
	var myFolder = Folder(app.preferences.bm_myFolder + subFolder);
	myFolder = stockphoto.core.folder.resolvePath(myFolder);
	if (!myFolder.exists)
	{
		if (stockphoto.isWin)
		{
	 		var mydoc = Folder.myDocuments;
			if (!mydoc.exists)
			{
				if (!mydoc.create())
				{
					throw (stockphoto.core.consts.localizedErrorString[7]);
				}
			}
		}

		if (!myFolder.create())
		{
		    /********Watson: 1314179 ***********/
		    // In mocha, throw was not working. Debugging level
		    // is set to '0' to solve this issue
		    $.level=0;
			throw (stockphoto.core.consts.localizedErrorString[8] + myFolder.fsName);
		}
	}
}

// given a folder object, returns a folder object with all aliases in path resolved
// 
stockphoto.core.folder.resolvePath = function(inFolder)
{
	var path = inFolder.absoluteURI;
	var pathElements = path.split ('/');
	var result = undefined;
	var resolveIsOK = true;
	var folderExists = true;
	
	//app.console("stockphoto.core.folder.resolvePath in: " + inFolder.fsName + "\n");
	// the first element may contain '~'
	path = pathElements[0];
	for (var i = 1; i < pathElements.length; i++)
	{
		path += '/';
		path += pathElements [i];
		var f = new Folder (path);
		
		// skip alias check when first folder does not exist
		if (folderExists)
		{
			if (f.alias)
			{
				f = f.resolve();
				if (!f)
				{	// kErrCannotResolve
					//app.console("Can not resolve folder alias: " + path + "\n");
					resolveIsOK = false;
					break;
				}
				else
				{
					path = f.absoluteURI;
				}
			}
			if (!f.exists)
			{	// kErrNoFile
				//app.console("Folder does not exist, skip future resolves: " + path + "\n");
				folderExists = false;
			}
		}
	}
	
	if (resolveIsOK)
	{
		result = new Folder(path);
	}
	
	return result;
}

stockphoto.core.folder.getMyFolder = function(defaultPathOnly)
{
  var zc = stockphoto.zc;
  var myFolder;
  var revertToDefaultLocation = false;
  /********Watson: 1314179 ***********/
  var save = $.level;
  
  if ((app.preferences.bm_myFolder == undefined) || (defaultPathOnly == true))
  {
  	myFolder = stockphoto.core.folder.setDefaultFolderName();
  	if (defaultPathOnly)
  	{
  		return myFolder.fsName;
  	}
  	app.preferences.bm_myFolder = myFolder.fsName;	
  }
  
  try
  {
	 stockphoto.core.folder.createMyFolder("");
  }
  catch (e)
  {
    /********Watson: 1314179 ***********/
    $.level=save;
  	// revert to default location if custom location fails
  	myFolder = stockphoto.core.folder.setDefaultFolderName();
	  app.preferences.bm_myFolder = myFolder.fsName;	
  	revertToDefaultLocation = true;
  }
  
  try
  {
  	if (revertToDefaultLocation)
  	{
  		stockphoto.core.folder.createMyFolder("");
  	}
  }
  catch (e)
  {
    /********Watson: 1314179 ***********/
    $.level=save;
	if(false == stockphoto.core.folderCreationErrorShown)
	{
		stockphoto.core.folderCreationErrorShown = true;
	  	stockphoto.DL.generalAlertBox(stockphoto.zc.get("$$$/StockPhoto/ErrorMessage/Error=Error: ") + e, 2);
	}
  	return undefined;
  }

  try
  {
  	stockphoto.core.folder.createMyFolder(stockphoto.core.folder.MySearches);
  	stockphoto.core.folder.createMyFolder(stockphoto.core.folder.MyComp);
  	stockphoto.core.folder.createMyFolder(stockphoto.core.folder.MyPurchased);
  	
  	return app.preferences.bm_myFolder;
  }
  catch (e)
  {
    /********Watson: 1314179 ***********/
    $.level=save;
	if(false == stockphoto.core.folderCreationErrorShown)
	{
		stockphoto.core.folderCreationErrorShown = true;
	  	stockphoto.DL.generalAlertBox(stockphoto.zc.get("$$$/StockPhoto/ErrorMessage/Error=Error: ") + e, 2);
	}
  	return undefined;
  }
}

stockphoto.core.folder.setDefaultFolderName = function()
{
	var myFolder;
	var folderName = "AdobeStockPhotos"; // Should this folder name get localized?
	if (File.fs == "Windows")
	{
		myFolder = Folder(Folder.myDocuments + "/" + folderName);
	}
	else
	{
		myFolder = Folder(Folder.myDocuments.fsName + "/" + folderName);
	}
	myFolder = stockphoto.core.folder.resolvePath(myFolder);
	return myFolder;
}

stockphoto.core.folder.getSubFolder = function(mySubFolder)
{
	var folder = stockphoto.core.folder.getMyFolder();
	if (folder == undefined)
	{
		return undefined;
	}

	var myFolder;
	myFolder = Folder(folder + mySubFolder);
	myFolder = stockphoto.core.folder.resolvePath(myFolder);

	return unescape(myFolder.fsName);
}

stockphoto.core.folder.getMySearchesFolder = function ()
{
	return stockphoto.core.folder.getSubFolder(stockphoto.core.folder.MySearches);
}

stockphoto.core.folder.getMyCompFolder = function()
{
	return stockphoto.core.folder.getSubFolder(stockphoto.core.folder.MyComp);
}

stockphoto.core.folder.getMyPurchasesFolder = function()
{
	return stockphoto.core.folder.getSubFolder(stockphoto.core.folder.MyPurchased);
}

stockphoto.core.folder.getMyShoppingCartFolder = function ()
{
	var bmFolderName = Folder.userData + "/Adobe";
	var bmFolder = Folder(bmFolderName);
	if (!bmFolder.exists)
	{
		if (!bmFolder.create())
		{
			throw (stockphoto.core.consts.localizedErrorString[8] + bmFolder.fsName);
		}
	}

	bmFolderName = bmFolderName +  "/" + stockphoto.core.installFolderSub;
	bmFolder = Folder(bmFolderName);
	if (!bmFolder.exists)
	{
		if (!bmFolder.create())
		{
			throw (stockphoto.core.consts.localizedErrorString[8] + bmFolder.fsName);
		}
	}

	bmFolderName = bmFolderName +  stockphoto.core.folder.MyShoppingCart;
	bmFolder = Folder(bmFolderName);
	if (!bmFolder.exists)
	{
		if (!bmFolder.create())
		{
			throw (stockphoto.core.consts.localizedErrorString[8] + bmFolder.fsName);
		}
	}

	return bmFolder.fsName;		
}

stockphoto.core.folder.isInCompFolder = function( thumb )
{
	var bResult = false;
	if (thumb.parent instanceof Thumbnail)
	{
		if (thumb.parent == stockphoto.places.comps)
		{
			bResult = true;
		}
	}
	return bResult;
}

stockphoto.core.folder.openVirtualFolder = function(document, phyFolder)
{
	stockphoto.search.setFolder = true;
	with (document)
	{
	    var saveLevel = $.level;
	    $.level=0;
	    try
	    {
			thumbnail = new Thumbnail(phyFolder);
		}
		catch(e)
		{
		}
		$.level = saveLevel;
		 
		allowDrags = false;
		showThumbnailName = false;
		noItems = "";
		additionalMetadata = [ "stock-sequence", "stock-media-title", undefined ];
		sorts = [ { type: "name", reverse: false } ];
		stockphoto.eventHandler.bRememberThumbSortOrder = false;
   	}
    
    if (("undefined" != typeof stockphoto.NavBar) && ("undefined" != typeof stockphoto.NavBar.zc))
    {
        document.noItems = stockphoto.NavBar.zc.get(stockphoto.NavBar.zstr_GettingImages);
    }
    
	stockphoto.eventHandler.pathAnalyzer.ChangeContentPaneMode( document, "filesystem" );
	stockphoto.search.setFolder = false;
	return;
}

stockphoto.core.folder.createNewSearchFolder = function(isearchKeyword, doc_id)
{
    var oResult;    
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
    {
        oResult = stockphoto.MiscUtils.folder.createNewSearchFolder(isearchKeyword, doc_id);
    }
    return oResult;
}

stockphoto.core.folder.isStockFolder = function( thumbnail )
{
	if (stockphoto.core.isSearchFolder(thumbnail))
	{
		return true;
	}
	with (stockphoto.places)
	{
		if (thumbnail == recentSearches)
		{
			return true;
		}
		else if (thumbnail.path == recentSearches.path)
		{
			return true;
		}
//		else if (thumbnail.displayPath == recentSearches.displayPath)
		else if( stockphoto.core.util.isDisplayPathEqual( stockphoto.core.util.getDisplayPath(thumbnail,""), stockphoto.core.util.getDisplayPath( recentSearches, "isStockFolder()-1" ) ) )
		{
			return true;
		}
		else if (thumbnail == comps)
		{
			return true;
		}
		else if (thumbnail.path == comps.path)
		{
			return true;
		}
//		else if (thumbnail.displayPath == comps.displayPath)
		else if ( stockphoto.core.util.isDisplayPathEqual( stockphoto.core.util.getDisplayPath(thumbnail,""), stockphoto.core.util.getDisplayPath( comps, "isStockFolder()-2" ) ) )
		{
			return true;
		}
		else if (thumbnail == purchases)
		{
			return true;
		}
		else if (thumbnail.path == purchases.path)
		{
			return true;
		}
//		else if (thumbnail.displayPath == purchases.displayPath)
//		{
//			return true;
//		}
		else
		{ 
			var tmpThumbDisp = stockphoto.core.util.getDisplayPath( thumbnail, "isStockFolder()-3" );
			var tmpPurchDisp = stockphoto.core.util.getDisplayPath( purchases, "isStockFolder()-4" );
			if ( stockphoto.core.util.isDisplayPathEqual( tmpThumbDisp, tmpPurchDisp ) )
			{
				return true;
			}
		}
	}
	return false;	
}

stockphoto.core.folder.isReadOnly = function(folderPath)
{
	var ret = false;

	var folderObj = new Folder(folderPath);

	if (folderObj.exists)
	{
		var f = new File(folderObj.fsName + "/_rotf_"); // Read-Only Test File

		if (f.open("w"))
		{
			f.close();
			f.remove();
		}
		else
		{
			ret = true;
		}
	}

	return ret;
}

// -------------------------------------------------------------------------------------- folder

// -------------------------
// === On Demand Loading ===
// -------------------------

stockphoto.DL.DemandLoadJSXTable=[
	/* 00 */ { n:"-Unused slot-", e:false },
	/* 01 */ { n:"st01AddToCart", e:false },
	/* 02 */ { n:"st02CheckOut", e:false },
	/* 03 */ { n:"st03BasicSearch", e:false },
	/* 04 */ { n:"st04AdvanceSearch", e:false },
	/* 05 */ { n:"st05LocalURL", e:false },
	/* 06 */ { n:"st06HomePage", e:false },
	/* 07 */ { n:"st07eCom", e:false },
	/* 08 */ { n:"st08TerminateStock", e:false },
	/* 09 */ { n:"st09GetComp", e:false },
	/* 10 */ { n:"st10Preferences", e:false },
	/* 11 */ { n:"st11NavBar", e:false },
	/* 12 */ { n:"st12SaveSearch", e:false },
//	/* 13 */ { n:"st13RedoSearch", e:false },
	/* 13 */ { n:"st13Burp", e:false },
	/* 14 */ { n:"st14ShoppingCart", e:false },
	/* 15 */ { n:"st15DownloadStock", e:false },
	/* 16 */ { n:"st16AlertBox", e:false },
	/* 17 */ { n:"st17ImgDetail", e:false },
	/* 18 */ { n:"st18HTMLUtil", e:false },
	/* 19 */ { n:"st19LangCountry", e:false },
	/* 20 */ { n:"st20MiscDlgs", e:false },
    /* 21 */ { n:"st21MiscUtils", e:false } ];

stockphoto.DL.jsx_AddToCart      =1;
stockphoto.DL.jsx_CheckOut       =2;
stockphoto.DL.jsx_BasicSearch    =3;
stockphoto.DL.jsx_AdvancedSearch =4;
stockphoto.DL.jsx_LocalURL       =5;
stockphoto.DL.jsx_HomePage       =6;
stockphoto.DL.jsx_eCom           =7;
stockphoto.DL.jsx_GetComp        =9;
stockphoto.DL.jsx_Preference     =10;
stockphoto.DL.jsx_NavBar         =11;
stockphoto.DL.jsx_Burp           =13;
stockphoto.DL.jsx_ShoppingCart   =14;
stockphoto.DL.jsx_DownloadStock  =15;
stockphoto.DL.jsx_AlertBox       =16;
stockphoto.DL.jsx_ImgDetail      =17;
stockphoto.DL.jsx_HTMUtil        =18;
stockphoto.DL.jsx_LangCountry    =19;
stockphoto.DL.jsx_MiscDlgs       =20;
stockphoto.DL.jsx_MiscUtils      =21;
	
stockphoto.DL.isAlreadyLoaded=function( id )
{
	return( stockphoto.DL.DemandLoadJSXTable[ id ].e );
}

stockphoto.DL.demandJsxLoading=function( id ) 
{
	var bRet=false;
	var js="";
	if( ( id > 0 )&&( id < stockphoto.DL.DemandLoadJSXTable.length ) ) 
	{
		if( stockphoto.DL.DemandLoadJSXTable[id].e )
		{
			return true;
		}
		var fs = new File( stockphoto.core.folder.getScriptFolder() + "/" + stockphoto.DL.DemandLoadJSXTable[id].n + ".jsx" );
		if( fs != undefined ) 
		{
			if( fs.exists ) 
			{
				fs.open();
				js = fs.read();
				fs.close();
				try 
				{
					eval(js);
				} 
				catch(e) 
				{ // this is to catch .jsx error
					stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[1]+stockphoto.DL.DemandLoadJSXTable[id].n, 2);
					delete fs;
					return false;
				}
				stockphoto.DL.DemandLoadJSXTable[id].e = true;
				bRet = true;
			}
			delete fs;
		}
		if( ! bRet )
		{
			stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[2]+stockphoto.DL.DemandLoadJSXTable[id].n, 2);
		}
	}
	return bRet;    
}

stockphoto._CheckBillingCountry=function( cmdString, docIn ) 
{
	var doc;
	if( docIn == undefined )
	{
		doc = app.document;
	}
	else 
	{
		doc = docIn;
	}
	if( (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscDlgs ) )  && (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AddToCart ) ) )
	{
		if( stockphoto.DL.MiscDlgs.BillingCountry_Status == 1 ) 
		{
			// do the followings only when the dialog is modal
			stockphoto.MiscDlgs.closeDialog();
			stockphoto.DL.MiscDlgs.BillingCountry_Status = 0;
		}
		switch( stockphoto.DL.MiscDlgs.BillingCountry_Status ) 
		{
			case -1:return( -1 );
			case 0: // 1st time user
				if (stockphoto.addToCart.LSCGetItemCount() > 0)
				{
					stockphoto.addToCart.LSCRemoveAllItems();
				}
				if( ! stockphoto.DL.MiscDlgs.BillingCountry( doc ) ) // OOps error or CANCELLed
				{
					return( 0 );
				}
				if( stockphoto.DL.MiscDlgs.BillingCountry_Status > 1 )
				{
					// if the dialog is modal or process is completed rapidly enough.
					return( 2 );
				}
				stockphoto.DL.MiscDlgs.BillingCountry_Status = 1; // Now in progress
			case 1: // awaiting "country selection dialog" is answered.
				return( 1 );
		}
	}
	return( 2 );
}


stockphoto.DL.search.basicSearch=function( terms, f, numPerPg, doc_id, sDisplayKeyword )
{
    // If the Adv Search drawer is open, close it
    if (stockphoto.DL.NavBar.IsDrawerShown(doc_id) == true)
    {
        stockphoto.NavExtFnc.ToggleAdvDrawerFromES(doc_id);
    }
    
	// Watson 1153127
	if( ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ) )&&
	    ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_BasicSearch ) ) )
	{
		stockphoto.search.basicSearch( terms, f, numPerPg, doc_id, sDisplayKeyword );
	}
}

stockphoto.DL.search.LoadSearchInfoFromFS = function( oFSObj, sInfoTag )
{
    var arResult = [ ];
    
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_BasicSearch ) )
	{
		arResult = stockphoto.search.LoadSearchInfoFromFS( oFSObj, sInfoTag );
	}
	
	return arResult;
}

stockphoto.DL.MiscUtils.validateFilterSelection = function (doc_id)
{
    var oResult;    
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
    {
        oResult = stockphoto.MiscUtils.search.validateFilterSelection(doc_id);
    }
    return oResult;
}

stockphoto.DL.search.basicSearchFromES=function( ekeyword, sDisplayKeyword, doc_id , lang ) 
{
	var ukeyword, numPerPg, f, langID, k, maxHits, thumSize, terms={};
   	ukeyword = unescape( ekeyword );
   	sDisplayKeyword = unescape( sDisplayKeyword );
	numPerPg = stockphoto.DL.getThumbPerGroup();
	f        = Folder( stockphoto.core.folder.createNewSearchFolder( sDisplayKeyword, doc_id ) );
	langID   = stockphoto.prefs.GetSearchLanguageCode(); //set some kind of default.
	if ((lang != undefined) && (lang != ""))
	{
		langID = lang;
	}

	if( stockphoto.DL.LoadBasicSearchAndPreference() ) 
	{
		var maxHits = stockphoto.prefs.GetMaxHits();
		var thumSize = stockphoto.prefs.thumbnailSizes[stockphoto.prefs.GetThumbnailSize()];
		var terms = 
		{
			Keyword:  ukeyword,
			LangID:         langID,
			MaxHits:        maxHits,
			ItemsPerGroup:  maxHits,
			ThumbnailSize:  thumSize               
		};
		
		var oSettings = stockphoto.DL.NavBar.GetDrawerSettings(doc_id);
		// If we are using previousSettings, copy it to the current settings now...
        stockphoto.search.settings[doc_id] = eval(oSettings);
        stockphoto.search.showPreviousSettings[doc_id] = false;
    
		var bValidateResult = stockphoto.DL.MiscUtils.validateFilterSelection( doc_id );
		if (bValidateResult == false)
		{
            return;
        }

        terms = stockphoto.DL.NavBar.addFiltersToTerms( oSettings, terms);
    
		stockphoto.DL.search.basicSearch( terms, f, numPerPg, doc_id, sDisplayKeyword );
	}
}

stockphoto.DL.search.AdvSearch=function( doc_id ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AdvancedSearch ) ) 
	{
		/*B*/	stockphoto.Burp.searchFrom[ doc_id] = "adv";
		stockphoto.advancedSearch.AdvanceSearch( doc_id );
	}
}

stockphoto.DL.search.MoreThumbs=function( doc_id ) 
{
	var numPerPg = stockphoto.DL.getThumbPerGroup();
	var f;
	if( ( app.document != undefined )&&
	    ( app.document.thumbnail != undefined )&&
//	    ( app.document.thumbnail.displayPath != undefined ) ) 
	    ( stockphoto.core.util.getDisplayPath( app.document.thumbnail, "MoreThumbs()-1" ) != "" ) ) 
	{
//		f = Folder (app.document.thumbnail.displayPath);
		f = Folder ( stockphoto.core.util.getDisplayPath( app.document.thumbnail, "MoreThumbs()-2" ) );
		if( stockphoto.DL.LoadBasicSearchAndPreference() ) 
		{
			stockphoto.search.moreThumbs( f, numPerPg, doc_id );
		}
	}
}

stockphoto.DL.GetComp.KeepComp=function( doc_id ) 
{
	// find the current selection
	if( app.document.selections.length < 1 ) 
	{
		stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[5], 2);
	} 
	else 
	{
		if((stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_GetComp ))  && (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox )))
		{
			stockphoto.getComp.KeepComp_Body(doc_id);

		}
	}
}

stockphoto.DL.imgDetail.getPriceFin=function( doc_id ) // Use old stockphoto.DL.imgDetail.getPriceFin for htm gate
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_ImgDetail ) ) 
	{
		stockphoto.gpk3.getPrice3fin( doc_id );
	}
}

stockphoto.DL.imgDetail.getPrice=function( doc_id ) 
{
	if( app.document.selections.length < 1 ) //making sure that we are not proceeding with the get-keywords action when no thumnail is selected
	{
		stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[5], 2);
	} 
	else
	{
		if( stockphoto._CheckBillingCountry( "imgDetail.getPrice", app.document ) != 2 )
		{
			return; // means the request is denied
		}
		if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_ImgDetail ) ) 
		{
			if( stockphoto.Burp.doIt ) // in DL.MiscDlgs.aboutPreference
			{
			/*B*/	try
			/*B*/	{
			/*B*/		stockphoto.Burp.callSPSUI( doc_id, stockphoto.Burp.code_gpk, "EventSubType", stockphoto.Burp.gpkSource, "", "" ); 
			/*B*/	} catch(e) { ; }
			}
			stockphoto.gpk3.getPrice3( doc_id, "", "pane1" );
		}
	}
}

stockphoto.DL.imgDetail.getKeywords=function( doc_id ) 
{
	if( app.document.selections.length < 1 ) //making sure that we are not proceeding with the get-keywords action when no thumnail is selected
	{
		stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[5], 2);
	} 
	else
	{
		if( stockphoto._CheckBillingCountry( "imgDetail.getPrice", app.document ) != 2 )
		{
			return; // means the request is denied
		}
		if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_ImgDetail ) ) 
		{
			if( stockphoto.Burp.doIt ) // in DL.MiscDlgs.aboutPreference
			{
			/*B*/	try
			/*B*/	{
			/*B*/		stockphoto.Burp.callSPSUI( doc_id, stockphoto.Burp.code_gpk, "EventSubType", stockphoto.Burp.gpkSource, "", "" ); 
			/*B*/	} catch(e) { ; }
			}
			stockphoto.gpk3.getPrice3( doc_id, "", "pane2" );
		}
	}
}

stockphoto.DL.ShoppingCart.AddToCart=function( doc_id ) 
{
	if( app.document.selections.length < 1 ) //making sure that we are not proceeding with the get-keywords action when no thumnail is selected
	{
		stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[5], 2);
	} 
	else
	{
		stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_CheckOut );
		if( stockphoto._CheckBillingCountry( "st01_AddToCart", app.document ) != 2 )
		{
			return; // means the request is denied
		}
		if( ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AddToCart )) &&
		    ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Preference ))&&
		    ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ))&&
		    ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_LangCountry )) ) 
		{
			stockphoto.addToCart.AddToCart_Body( doc_id );
		}
	}
	//execStr = "glb_b0=0;";
	//app.scheduleTask("app.document.execJS(" + quote + execStr + quote + ")");
}

stockphoto.core.updateJS = function()
{
	
}

stockphoto.DL.ShoppingCart.ShoppingCartX=function( doc_id ) 
{
    var oResult;    
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
    {
        oResult = stockphoto.MiscUtils.core.ShoppingCartX( doc_id );
    }
    return oResult;
}

//stockphoto.DL.Download.DownloadStock=function(loadBM, autoDL, doc_id) 
stockphoto.DL.Download.DownloadStock=function( loadBM, autoDL, doc_id, fromSource ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_DownloadStock ) ) 
	{
//		stockphoto.st15_DownloadStock_Body(loadBM, autoDL, doc_id);
		stockphoto.st15_DownloadStock_Body( loadBM, autoDL, doc_id, fromSource );
	}
}

stockphoto.DL.HTMLUtil.ConvertToInteger=function( inBuff ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_HTMUtil ) ) 
	{
		return( stockphoto.HTMLUtil.ConvertToInteger( inBuff ) );
	}
	return 0;
}

stockphoto.DL.HTMLUtil.ConvertToIEAddress=function( inBuff ) 
{ // inBuff must be = File( <filename/path> ).fsName
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_HTMUtil ) ) 
	{
		return( stockphoto.HTMLUtil.ConvertToIEAddress( inBuff ) );
	}
	return "";
}

stockphoto.DL.HTMLUtil.LocalHTMLbyDoc=function( TemplatePath, ConvTable, OutputName, folder, bSpecial, doc ) 
{
	if( ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_ImgDetail ) )&&
	    ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_HTMUtil ) ) ) 
	{
		var doc_id = doc.id;
		stockphoto.DL.NavBar.PrepareNavBar( doc_id );
		return( stockphoto.HTMLUtil.LocalHTMLmain( TemplatePath, ConvTable, OutputName, folder, bSpecial, doc_id ) );
	}
	return( false );
}

stockphoto.DL.HTMLUtil.SubLocalHTMLbyDocID=function( TemplatePath, ConvTable, OutputName, doc_id, bIsForNavHtm ) 
{ 
	// availability of "dInd" implies that st11NavBar.jsx is already loaded
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_HTMUtil ) ) 
	{
		return( stockphoto.HTMLUtil.SubLocalHTMLbyDocID( TemplatePath, ConvTable, OutputName, doc_id, bIsForNavHtm ) );
	}
	return( false );
}

stockphoto.DL.HTMLUtil.ConvertToPriceString=function( priceStr, bForScript )
{
    var outObj={};
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_HTMUtil ) ) 
	{
		outObj = stockphoto.HTMLUtil.ConvertToPriceString( priceStr, bForScript );
		return( outObj );
	}
	return( undefined );
}

stockphoto.DL.LocalURL.CheckLocalURL=function(url,sz1Ky,doc_id) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_LocalURL ) ) 
	{
		return( stockphoto.LocalURL.CheckLocURL(url,sz1Ky,doc_id) );
	}
	return false;
}

stockphoto.DL.HomePage.Promotion=function(srcStr, doc_id) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_HomePage ) )  
	{
		stockphoto.HomePage.PromotionURL(srcStr,doc_id);
	}
}

stockphoto.DL.MiscDlgs.DecodeXMLString=function( inStr ) 
{ // returning decoded string
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_HTMUtil ) ) 
	{
		return( stockphoto.HTMLUtil.DecodeXMLString( inStr ) );
	}
	return( "" );
}

stockphoto.DL.MiscDlgs.MyAccount=function( doc_id ) 
{
	// Bring up billing country dialog if it has not previously been displayed. - rwe
	if( stockphoto._CheckBillingCountry( "MiscDlgs.MyAccount", app.document ) != 2 )
	{
		return 0; // means the request is denied
	}
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscDlgs ) ) 
	{
		stockphoto.MiscDlgs.MyAccount( doc_id );
	}
}

stockphoto.DL.MiscDlgs.aboutPreference=function( doc_id ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscDlgs ) ) 
	{
		if( stockphoto.Burp.doIt ) // in DL.MiscDlgs.aboutPreference
		{
		/*B*/	try
		/*B*/	{
		/*B*/		stockphoto.Burp.callSPSUI( doc_id, stockphoto.Burp.code_changeView, "searchUsing", "", "", "" ); 
		/*B*/	} catch(e) { ; }
		}
		stockphoto.MiscDlgs.HelpTopic( stockphoto.core.helpTopicBase );
	}
}

stockphoto.DL.MiscDlgs.SearchTips=function( doc_id ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscDlgs ) ) 
	{
		stockphoto.MiscDlgs.SearchTips( doc_id );
	}
}

stockphoto.DL.MiscDlgs.HelpTopic=function( helpTopic ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscDlgs ) ) 
	{
		stockphoto.MiscDlgs.HelpTopic( helpTopic );
	}
}

stockphoto.DL.MiscDlgs.GotoFolder=function( WhichOne, doc_id ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscDlgs ) ) 
	{
			stockphoto.MiscDlgs.GotoFolder( WhichOne, doc_id );
	}
}

stockphoto.DL.MiscDlgs.NoSearchResults=function( keyword, docIn ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscDlgs ) ) 
	{
		var doc;
		if( docIn == undefined )
		{
			doc = app.document;
		}
		else 
		{
			doc = docIn;
		}
		return( stockphoto.MiscDlgs.NoSearchResults( keyword, doc ) );
	}
	return( -1 );
}

//SA: TODO Write a similar funciton for comps
// Adding a function to display the current purchased images folder
stockphoto.DL.MiscDlgs.ShowCurrentPurchasedFolder = function(doc_id)
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscDlgs ) ) 
	{
			stockphoto.MiscDlgs.ShowCurrentPurchasedFolder( doc_id );
	}
}
//Change Ends

stockphoto.DL.MiscDlgs.PhotographersDirectory=function( doc_id ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscDlgs ) ) 
	{ 
		stockphoto.MiscDlgs.PhotographersDirectory( doc_id );
	}
}

stockphoto.DL.MiscDlgs.BillingCountry_Status=2; // -1: Cancelled 0:Yes, 1st time | 1:In progress | 2:Not 1st time   
if( app.preferences.bm_billing_region == undefined ) 
{	
	stockphoto.DL.MiscDlgs.BillingCountry_Status=0;
}

stockphoto.DL.MiscDlgs.BillingCountry=function( docIn ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscDlgs ) ) 
	{
		var doc;
		if( docIn == undefined )
		{
			doc = app.document;
		}
		else 
		{
			doc = docIn;
		}
		return( stockphoto.MiscDlgs.BillingCountry( doc ) );
	}
	return( false );
}

stockphoto.DL.LoadBasicSearchAndPreference=function() 
{
	if( ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_BasicSearch ) )&&( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Preference ) ) )
	{
		return true;
	}
	return false;
}

stockphoto.DL.NavBar.PrepareNavBar=function( doc_id ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		stockphoto.NavExtFnc.PrepareNavBar( doc_id );
	}
}

stockphoto.DL.NavBar.CreateStyleSheet=function( doc_id ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		return( stockphoto.NavExtFnc.CreateStyleSheet( doc_id ) );
	}
	return( true ); // No further thing is requested.
}

stockphoto.DL.NavBar.addBMNavBar=function( args, type, doc ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		return( stockphoto.NavExtFnc.addBMNavBar( args, type, doc ) ); /* DL call */
	}
	return( true ); // No further thing is requested.
}

stockphoto.DL.NavBar.GetKeywordFromES=function( Cd, doc_id ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		return( stockphoto.NavExtFnc.GetKeywdFromES( Cd, doc_id ) );
	}
	return( "" );
}

stockphoto.DL.NavBar.updateXofY=function( status, xIn, yIn, sub, doc_id, searchID, from ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		stockphoto.NavExtFnc.updateXofYfromExternal( status, xIn, yIn, sub, doc_id, searchID, from );	
	}
}

stockphoto.DL.NavBar.ProgressGIFOn=function( doc_id ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		stockphoto.NavExtFnc.ProgressGIFOn( doc_id );
	}
}

stockphoto.DL.NavBar.GetFontNames=function() 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) {
		return( stockphoto.NavExtFnc.GetFontNames() );
	}
	return( "'Lucida Grande', tahoma" );
}

stockphoto.DL.NavBar.SpiningWheelOn=function( Label, doc_id ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		stockphoto.NavExtFnc.SetAdd3Field( "+", doc_id );
		stockphoto.NavExtFnc.SpiningWheelOn( Label, doc_id );
	}
}

stockphoto.DL.NavBar.SpiningWheelOff=function( doc_id ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		stockphoto.NavExtFnc.SetAdd3Field( "-", doc_id );
		stockphoto.NavExtFnc.SpiningWheelOff( doc_id );
	}
}

stockphoto.DL.addGroupThumbsToCart=function( f, priceIndex ) 
{
	if( (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AddToCart ))  && 
	    (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Preference )) && 
	    (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox )) && 
	    (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_LangCountry )) )
	{
		stockphoto.addToCart.AddGroupThumbsToCart_Body( f, priceIndex, undefined );
	}
}

stockphoto.DL.checkOutImages=function() 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_CheckOut ) ) 
	{
		stockphoto.DL.checkOutImages_Body();
	}
}

stockphoto.DL.ShowLicenseAgreement=function( imageIdList) 
{
	if( ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_CheckOut ) )  &&
	   ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Preference )) )
	{
		stockphoto.checkout.ShowLicenseAgreement(imageIdList);
	}
}

stockphoto.DL.GetComp.GetCompFile=function(thumbPath) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_GetComp ) ) 
	{   //reportErr=false;
		stockphoto.getComp.GetComp_Body( thumbPath, undefined, undefined, undefined ,false, "", false, undefined, 0, true, -1);
	}
}

stockphoto.DL.GetComp.GetCompFileExtended=function(thumbPath, dest, openIt, onComplete, reportErr, bFrmImgDetail) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_GetComp ) ) 
	{   
		stockphoto.getComp.GetComp_Body(thumbPath, dest, openIt, onComplete, reportErr,"", bFrmImgDetail, undefined, 0, true, -1);
	}
}

stockphoto.DL.GetComp.GetAndCopyComp=function(thumbPath, onCompleteConfirm, isImageDetails, reportErr) 
{
	if((stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_GetComp ))  && 
	   (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox )))
	{
		//reportErr=true;  for now.
		stockphoto.getComp.GetAndCopyComp_Body(thumbPath, onCompleteConfirm, isImageDetails,reportErr, -1);
	}
}

stockphoto.DL.GetComp.GetAndOpenComp=function(thumbPath, appPath) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_GetComp ) ) 
	{
		stockphoto.getComp.GetAndOpenComp_Body(thumbPath, appPath);
	}
}

stockphoto.DL.getAdvSearchAutoOpenPref=function() 
{
	if (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Preference )) 
	{
		return (stockphoto.prefs.GetAdvancedSearchAutoOpen());
	}
	else
	{
	   return false;
	}
}

stockphoto.DL.getCurrencyType=function() 
{
	if( (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Preference )) && (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_LangCountry )))
	{
		return (stockphoto.prefs.GetCurrencyType_Body());
	}
	return "USD";
}

stockphoto.DL.getCurrencySymbol=function() 
{
	if( (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Preference )) && (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_LangCountry ))) 
	{
		return (stockphoto.prefs.GetCurrencySymbol_Body());
	}
	return "$";
}

stockphoto.DL.GetLanguage=function()
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Preference ) )
	{
		return( stockphoto.prefs.GetLanguage() );
	}
	return( stockphoto.core.getValidLocale() );
}

stockphoto.DL.getThumbPerGroup=function() 
{
	if( stockphoto.DL.LoadBasicSearchAndPreference() )
	{
		return( stockphoto.prefs.GetThumbPerGroup_Body() );
	}
	return 10;
}

stockphoto.DL.preference=function(dialog) 
{
	if( stockphoto.DL.LoadBasicSearchAndPreference() )
	{
		stockphoto.prefs.Preference_Body(dialog);
	}
}

stockphoto.DL.getLanguageCode=function() 
{
	if( stockphoto.DL.LoadBasicSearchAndPreference() )
	{
		return( stockphoto.prefs.GetLanguageCode_Body() );
	}
	return stockphoto.core.consts.localizedErrorString[3]; 
}

stockphoto.DL.getCountryCodeFromLanguageCode=function() 
{
	if( stockphoto.DL.LoadBasicSearchAndPreference() )
	{
		return( stockphoto.prefs.GetCountryCodeFromLanguageCode_Body() );
	}
	return stockphoto.core.consts.localizedErrorString[4];
}

stockphoto.DL.doShoppingCart=function( doc_id ) 
{
	if( stockphoto._CheckBillingCountry( "st14_ShoppingCart", app.document ) != 2 )
	{
		return; // means the request is denied
	}
	if( ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AddToCart ) )&&( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_ShoppingCart ) ) ) 
	{
		stockphoto.shoppingCart.shoppingCart_Body( true, doc_id );
	}
}

stockphoto.DL.doCheckDownloadMgrQueueBeforeQuitting=function() 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_DownloadStock ) )
	{
		return (stockphoto.DL.doCheckDownloadMgrQueueBeforeQuitting_Body());
	}
}

stockphoto.DL.doCheckDownloadMgrQueueOnStartup=function() 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_DownloadStock ) ) 
	{
		stockphoto.DL.doCheckDownloadMgrQueueOnStartup_Body();
	}
}

stockphoto.DL.doclearAllItemsInList=function() 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_DownloadStock ) ) 
	{
		stockphoto.DL.doclearAllItemsInList_Body();
	}
}

stockphoto.DL.alertBox=function( errorCode, arg1, arg2, sAppendMessage ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ) ) 
	{
		return stockphoto.alertBox.alertBox( errorCode , arg1, arg2, sAppendMessage);
	}
}

stockphoto.DL.confirmationBox=function( cancelButtonAction, imageCount, imageTitle, onCompleteConfirm, addedCount, addedTitle, doc_id, reqIndex) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ) ) 
	{
		stockphoto.alertBox.confirmationBox( cancelButtonAction, imageCount, imageTitle , onCompleteConfirm, addedCount, addedTitle, doc_id, reqIndex);
	}
}

stockphoto.DL.downloadAlertBox=function( alertType, messageStr ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ) )
	{
		return (stockphoto.alertBox.downloadAlertBox( alertType, messageStr ));
	}
}

stockphoto.DL.alertDialog=function( errorCode, iconType, buttonType, messageString ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ) )
	{
    		return (stockphoto.alertBox.alertDialog( errorCode, iconType, buttonType, messageString ));
	}
}

stockphoto.DL.generalAlertBox=function(messageString, iconType) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AlertBox ) )
	{
		stockphoto.alertBox.generalAlertBox(messageString, iconType);
	}
}

stockphoto.DL.LangCountry.StockCountry=function( CountryIndex ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_LangCountry ) ) 
	{
		return( stockphoto.LangCountry.StockCountry_Body( CountryIndex ) );
	}
	return( "US" );
}

stockphoto.DL.LangCountry.StockCurrency=function( CountryCd ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_LangCountry ) ) 
	{
		return( stockphoto.LangCountry.StockCurrency_Body( CountryCd ) );
	}
	return( "USD" );
}

// === local html file and filter ===
stockphoto.core.html={};
stockphoto.core.html.LengthOfUrlForBMHome         =0;
stockphoto.core.html.LengthOfUrlForPhotographerDir=0;
stockphoto.core.html.urlForBMHPFamily      = "xyzabc";
stockphoto.core.html.urlForBMHPatBrowseSche= undefined;
stockphoto.core.html.urlForBMHome          = undefined;
stockphoto.core.html.urlForMoreWaysFindImg = undefined;
stockphoto.core.html.urlForBMPDFamily      = "xyzabc";
stockphoto.core.html.urlForPhotographerDir = undefined;
stockphoto.core.html.urlForEBFamily        = "xyzabc";
stockphoto.core.html.urlForExplicitBMDir   = undefined;
stockphoto.core.html.browserForPhotoGDir   = "";
stockphoto.core.html.urlArgsForPhotoGDirInBridge = "";

stockphoto.core.html.urlPrinciple          = "~!~2!3!5!7~";
stockphoto.core.html.HtmlScriptReadyStatus =false; // set from HTML

stockphoto.core.html.urlUILanguage         = "";

stockphoto.core.html.setUrlFilter = function( document ) 
{
	if( document != undefined ) 
	{
		document.visitUrl = stockphoto.core.html.doBMUrlFilter;
		return( true );
	}
	return( false );
}


stockphoto.core.html.doBMEmptyFilter=function(url) 
{
	return( url );
}

stockphoto.core.html.forceToDisplayStockPhoto=function()
{
	var t = undefined;
	
	var saveLevel = $.level;
	$.level=0;
	try
	{
		t = new Thumbnail("stockphoto://emptypage");
	}
	catch(e)
	{
	}
	$.level = saveLevel;
	
	if( t != undefined )
	{
		if( t.name != undefined )
		{
			t.name = "";
		}
		t.displayMode = "web";
		t.displayPath = unescape( File( stockphoto.core.folder.getTemplateFolder()+"/Empty.htm" ).fsName );
		app.document.thumbnail = t;
	}
	app.scheduleTask( "stockphoto.displayStartPage( undefined );", 1000, false );
}

// Watson : 1249207 
// There is no need to remove the parameters.
// Reverting back the changes done by Aki in Revision history number 21
stockphoto.core.html.doCreateNewThumb=function( doc_id, url ) 
{
    if ( "undefined" != typeof url )
    {
		var doc = stockphoto.core.findDoc( doc_id );
		if( "undefined" != typeof doc )
			doc = app.document;
		if( "undefined" != typeof doc )
		{	
		    var saveLevel = $.level;
		    $.level=0;
		    try
		    {
				doc.thumbnail = new Thumbnail( url);
			}
			catch(e)
			{
			}
			$.level = saveLevel;
			
			stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, true, "doBMUrlFilter-3" );
			stockphoto.core.log.logString( 0, "--- .. .. doc_id="+doc_id+", url="+url );
		}
	}
}

stockphoto.core.html.doPhotoDirInDefaultBrowser=function()
{
	if( stockphoto.Burp.doIt ) // in stockphoto.core.html.doPhotoDirInDefaultBrowser
	{
	/*B*/	try
	/*B*/	{
	/*B*/		stockphoto.Burp.callSPSUI( app.document.id, stockphoto.Burp.code_favorite, "item", "PhotoDir", "", "" ); 
	/*B*/	} catch(e) { ; }
	}
	var billing = "us";
	if( ( app.preferences.bm_billing_region != undefined )&&
		( app.preferences.bm_billing_region != "" ) )
		billing = ( app.preferences.bm_billing_region ).toLowerCase();
	stockphoto.core.html.openInDeafaultBrowser( stockphoto.core.html.urlForPhotographerDir+"&language="+stockphoto.core.html.urlUILanguage+"&billing="+billing);
	if( stockphoto.eventHandler.pathAnalyzer.panePreviousPath2 != "" ) {
	    var saveLevel = $.level;
	    $.level=0;
	    try
	    {
			app.document.thumbnail = new Thumbnail( File(stockphoto.eventHandler.pathAnalyzer.panePreviousPath2) );
			app.document.thumbnail.displayPath = stockphoto.eventHandler.pathAnalyzer.panePreviousDispPath2;
			app.document.thumbnail.displayMode = stockphoto.eventHandler.pathAnalyzer.panePreviousMode2;
		}
		catch(e)
		{
		}
		$.level = saveLevel;
	}
}

stockphoto.core.html.doBMUrlFilter=function(url) 
{
	var sKy1, sKy2, nUrl, nKey, ind, doc, lcb, HPurl, isEComPage, place=undefined,
		script, bSpecialRoot, bSpecialSub, fPos, verVal="1.1"; // Change for V.1.1
	var res={ result:true, url:url, toHistory:true };
	stockphoto.core.log.logString( 0, "\n\n---BMURLFilter---: "+url );
	stockphoto.core.log.logString( 0, "   contentPaneMode="+app.document.contentPaneMode+"\n" );
	if(	stockphoto.core.BoxCar.szInFailedHomePage != "" )
	{
		if( stockphoto.core.BoxCar.szOriginalHomePage == url )
		{	
			res.url       = stockphoto.core.BoxCar.szInFailedHomePage;
			res.toHistory = false;
			stockphoto.core.BoxCar.NavBar.SetInECOMFlag( false, this.id );
			return( res );	
		}
	}
	with( stockphoto.places )
	{
		switch( url )
		{
			case home.path:
				place = "home";
				break;
			case comps.path:
				place = "comps";
				break;
			case purchases.path:
				place = "purchases";
				break;
			case recentSearches.path:
				place = "recentSearches";
				break;
		}
	}
	if (place != undefined)
	{
		script = "app.document.thumbnail = stockphoto.places." + place + ";";
		app.scheduleTask(script, 0, false);
		stockphoto.core.BoxCar.NavBar.SetInECOMFlag( false, this.id );
		return undefined;
	}

	// Process ReEntrancy
	doc = stockphoto.core.findDoc( this.id );
	if( doc == undefined )
	{
		doc = app.document;
	}
	
	//folder/thumbnail sorting related code starts here
 	//if(("undefined" != typeof(doc.thumbnail)) && ("undefined" != typeof(stockphoto.core.menu)) && ("undefined" != typeof(stockphoto.places.recentSearches) ) )
	 //{
	 	var displayPath = stockphoto.core.util.getDisplayPath(app.document.thumbnail,"");
	 	if(-1 != displayPath.indexOf(stockphoto.core.folder.getMySearchesFolder() ) ) 
		{
			if(stockphoto.eventHandler.bRememberThumbSortOrder == true)
			{
				stockphoto.eventHandler.lastRemeberedSortOrder = doc.sorts;
				if( stockphoto.core.util.getDisplayPath(app.document.thumbnail,"") == stockphoto.core.folder.getMySearchesFolder() )
				{
					doc.sorts = [ { type: "date-created", reverse: true } ];
				}
				else
				{
					doc.sorts = [ { type: "name", reverse: false } ];
				}
			}
			stockphoto.eventHandler.bRememberThumbSortOrder = false;
		}
		else
		{
			if(stockphoto.eventHandler.bRememberThumbSortOrder == true)
			{
				//doc.sorts = stockphoto.eventHandler.lastRemeberedSortOrder;
				stockphoto.eventHandler.lastRemeberedSortOrder = doc.sorts;
			}
			else
			{
				doc.sorts = stockphoto.eventHandler.lastRemeberedSortOrder;
			}
			stockphoto.eventHandler.bRememberThumbSortOrder = true;		
		}
	//}
	//sorting related code ends
	

	fPos = url.indexOf( "BMHomeReEntrant=yes" );
	if( fPos >= 0 )
	{
		stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, true, "doBMUrlFilter-1" );
		stockphoto.core.log.logString( 0, "--- .. Reentrant Return -> result="+res.result+" url='"+res.url+"' His="+res.toHistory );
		return( res );
	}

	// Process Photographer's Directory - Open default browser if necessary
	// This should work for any URL that contains the base URL for Photographer's Directory
	if( url.indexOf( stockphoto.core.html.urlForBMPDFamily ) >= 0 )
	{
		if( stockphoto.core.isAPDLang( stockphoto.core.html.urlUILanguage ) )
		{
			if( stockphoto.core.html.browserForPhotoGDir != "opera"
                && stockphoto.core.html.browserForPhotoGDir != "bridge" )
			{
				stockphoto.core.log.logString( 0, "--- .. Photographer's Directory in Opera -> undefined." );
				app.scheduleTask( "stockphoto.core.html.doPhotoDirInDefaultBrowser();\n", 1000, false );
				return( undefined );
			}
			else
			{	// display in the contentpane
				if( stockphoto.Burp.doIt ) // in stockphoto.core.html.doBMUrlFilter
				{
				/*B*/	try
				/*B*/	{
				/*B*/		stockphoto.Burp.callSPSUI( this.id, stockphoto.Burp.code_favorite, "item", "PhotoDir", "", "" ); 
				/*B*/	} catch(e) { ; }
				}
				//stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, true, "doBMUrlFilter-2" );
				//doc.topNavbar.visible = true;
				stockphoto.core.BoxCar.NavBar.SetInECOMFlag( false, this.id );
			}
		}
		else
		{
			return( undefined );
		}
	}

	// Process /bridgecenter:.+stockphoto:\/\/home/
	if (url.search(/bridgecenter:.+stockphoto:\/\/home/) != -1)
	{
		lcb   = stockphoto.core.html.GetLanguageCountryBilling();
		HPurl = stockphoto.core.html.urlForBMHome+"?language="+lcb.szLanguage+"&country="+lcb.szCountry+"&billing="+lcb.szBilling;
		lcb = {};
		stockphoto.core.log.logString( 0, "--- .. Special 1 -> '"+HPurl+"'" );
		stockphoto.core.BoxCar.NavBar.SetInECOMFlag( false, this.id );
		return( HPurl );
	}
	if (url.search(/bridgecenter:.+stockphoto:.+/) != -1)
	{
		HPurl = "startpage:reveal=" + url.match(/stockphoto:.+/);
		stockphoto.core.log.logString( 0, "--- .. Special 2 -> '"+HPurl+"'" );
		stockphoto.core.BoxCar.NavBar.SetInECOMFlag( false, this.id );
		return( HPurl );
	}

	// Process "about:blank"
	if( url == "about:blank" )
	{
		res.toHistory = false;
		stockphoto.core.log.logString( 0, "--- .. about:blank -> result="+res.result+" url='"+res.url+"' His="+res.toHistory );
		stockphoto.core.BoxCar.NavBar.SetInECOMFlag( false, this.id );
		return( res );
	}

	// Process Promotion
	sKy1 = "/stockphotosdefaulturl.";
	nUrl = url.length;
	nKey = sKy1.length;
	if( nUrl > nKey ) 
	{
		ind = ( url.toLowerCase() ).indexOf( sKy1 );
		if( ind > 0 ) 
		{
			/*B*/	stockphoto.Burp.searchFrom[ doc.id ] = "brs";
			app.scheduleTask("stockphoto.DL.HomePage.Promotion( '"+url.substring( ind + nKey - 1, nUrl )+"', "+this.id+" );", 0, false);
			// Case for promotion
			stockphoto.core.log.logString( 0, "--- .. Promotion -> undefined." );
			stockphoto.core.BoxCar.NavBar.SetInECOMFlag( false, this.id );
			return( undefined );
		}
	}

	// Process eCom page having sptrigger
	sKy2 = "sptrigger";
	nKey = sKy2.length;
	if( nUrl > nKey ) 
	{
		ind = url.indexOf( sKy2 );
		if( ind > 0 ) 
		{
			if( stockphoto.DL.LocalURL.CheckLocalURL( url, sKy2, this.id ) ) 
			{
				// Case for eCom
				
				// if this was a 'complete' trigger, make sure the Bridge displays the local shopping cart
				// the next time the 'checkout' ScriptNode is requested.
				if (url.indexOf( "complete" ) > -1)
				{
					// stockphoto.browseScheme.sessionUrl = stockphoto.core.folder.getMyShoppingCartFolder() + "/" + stockphoto.core.consts.ShoppingCartName;
				}
				stockphoto.core.log.logString( 0, "--- .. eCom -> undefined." );
				return( undefined );
			}  
		}
	}

	stockphoto.core.BoxCar.NavBar.SetInECOMFlag( false, this.id )

	if( stockphoto.Burp.doIt ) // in updateXofYfromExternal to register searchID
	{
/*B*/			try
/*B*/			{
/*B*/				stockphoto.Burp.URLFilter( this.id, url );
/*B*/			} catch(e) { ; }
	}	

	doc = stockphoto.core.findDoc( this.id );

	bSpecialRoot = false;
	bSpecialSub  = false;
	if( url.indexOf( stockphoto.core.html.urlForBMHPFamily ) >= 0 )
	{	// in the family of ASP Home
		bSpecialSub = true;
		if( url.indexOf( stockphoto.core.html.urlForBMHome ) >= 0 )
		{
			bSpecialRoot = true;
		}
	}
	if( stockphoto.core.html.browserForPhotoGDir == "opera" )
	{
		if( url.indexOf( stockphoto.core.html.urlForBMPDFamily ) >= 0 )
		{	// in the family of ASP Home
			bSpecialSub = true;
			if( url.indexOf( stockphoto.core.html.urlForPhotographerDir ) >= 0 )
			{
				bSpecialRoot = true;
			}
		}
		if( stockphoto.core.html.urlForExplicitBMDir != undefined )
		{
			if( url.indexOf( stockphoto.core.html.urlForEBFamily ) >= 0 )
			{	// in the family of ASP Home
				bSpecialSub = true;
				if( url.indexOf( stockphoto.core.html.urlForExplicitBMDir ) >= 0 )
				{
					bSpecialRoot = true;
				}
			}
		}
	}

	// process sub-url of HomePage
	if( this.thumbnail != undefined ) 
	{
		if( verVal == "1.0" )
		{	// Version 1.0
//			if( this.thumbnail.displayPath == stockphoto.core.html.urlForBMHPatBrowseSche )
			if( stockphoto.core.util.isDisplayPathEqual( stockphoto.core.util.getDisplayPath( this.thumbnail, "doBMUrlFilter()-1" ), stockphoto.core.html.urlForBMHPatBrowseSche ) )
			{ // The same Url at GetFileSpec of browseSchema.jsx
				if( url == stockphoto.core.html.urlForBMHPatBrowseSche ) 
				{ // Asking main url
					stockphoto.core.log.logString( 0, "--- .. ASP Home -> url='"+url+"'" );
				} 
				else
				{ // Switching to sub url
					doc.visitUrl  = stockphoto.core.html.doBMEmptyFilter;
					var saveLevel = $.level;
					$.level=0;
					try
					{
						doc.thumbnail = new Thumbnail( File(url) );
					}
					catch(e)
					{
					}
					$.level = saveLevel;
					doc.visitUrl  = stockphoto.core.html.doBMUrlFilter;
					stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, true, "doBMUrlFilter-3" );
					stockphoto.core.log.logString( 0, "--- .. ASP Home SUB -> result=undefined." );
					return( undefined );
				}
			}
		}
		else
		{ 	// ver "1.1"
			if( bSpecialSub )
			{	// in the family of ASP Home
				stockphoto.core.init.loadBMScripts(); // We can load ASP, since ASP Home is requested
				if( bSpecialRoot )
				{
					stockphoto.core.log.logString( 0, "--- .. ASP Home -> url='"+url+"'" );
				} 
				else
				{
					//doc.visitUrl  = stockphoto.core.html.doBMEmptyFilter;
					if( url.indexOf( '?' ) < 0 )
					     HPurl = url+"?BMHomeReEntrant=yes";
					else HPurl = url+"&BMHomeReEntrant=yes";
					//doc.visitUrl  = stockphoto.core.html.doBMUrlFilter;

                    // Check if we need to set the correct height of the NavBar...
                    var iNavType = stockphoto.DL.NavBar.GetNavHeightType(doc.id);
                    if (("undefined" != typeof iNavType) && (stockphoto.NavIntDt._kNavHeight_high != iNavType))
					{
                        stockphoto.core.NavBar.SwitchNavBar( "DISPLAYSTARTPAGE", 0, 1, doc );
                    }

					stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( app.document, true, "doBMUrlFilter-4" );
					var Script = "stockphoto.core.html.doCreateNewThumb("+this.id+",'"+HPurl+"');\n";
					app.scheduleTask( Script, 50, false );
					stockphoto.core.log.logString( 0, "--- .. ASP Home SUB -> result=undefined." );
					// stockphoto.core.log.logString( 0, "--- .. ASP Home SUB -> result="+res.result+" url='"+res.url+"' His="+res.toHistory );
					return (res.url = HPurl); // Talisman
				}
			}
		}
	}

	if( ( stockphoto.core.historyFilterKey == undefined )||
	    ( stockphoto.core.historyFilterKey == "" ) )
	{
		if( ( stockphoto.core.BoxCar.AnalyzeXmlFileObj != undefined )&&
		    ( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners != undefined )&&
		    ( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0] != undefined )&&
		    ( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].EComPartners != undefined )&&
		    ( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].EComPartners[0] != undefined )&&
		    ( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].EComPartners[0].HistoryFilterKey != undefined )&&
		    ( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].EComPartners[0].HistoryFilterKey.Value != undefined ) )
		{
			stockphoto.core.historyFilterKey = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].EComPartners[0].HistoryFilterKey.Value;
		}
	}

	if( ( stockphoto.core.historyFilterKey != undefined )&&
	    ( url.indexOf( stockphoto.core.historyFilterKey ) > -1 ) )
	{
	   isEComPage = true;
	}
	else
	{
	   isEComPage = false;
	}
	if( ( url.indexOf( stockphoto.core.html.urlPrinciple ) < 0 )&&
		( url.indexOf( "st14Shopping" ) < 0 )&& // not "st14Shopping"
		( url.indexOf( "st20NewNoResult." ) < 0 )&& 
//		( url.indexOf( "st20SearchTips." ) < 0 )&& 
//		( url.indexOf( "st20ProxyAuth." ) < 0 )&& 
		( url.indexOf( "noConnection" ) < 0 )&& 
		( ! isEComPage )&&
		( url.indexOf( "\\"+stockphoto.core.installFolder+"\\" ) < 0 )&& // Stock photo temp for html
	    ( url.indexOf( "&stockphotosURL=yes" ) < 0 )&&
	    ( url.indexOf( "?stockphotosURL=yes" ) < 0 ) )
	{
		stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( app.document, false, "URLFilter" );
	}
	else
	{	// if it is a BM's URL, we set "Enter..." to editbox of Navbar
		if( ! isEComPage )
		{ // not eCom page
			if( stockphoto.NavIntFnc != undefined ) 
			{
				stockphoto.NavIntFnc.SetKeyWord( stockphoto.NavIntDt.TheEnter, false /*=unescaped*/, doc.id, true );
				// #1135772 set "Search ..." to web Navbar
				stockphoto.NavExtFnc.SendKeyWordToHTM( escape( stockphoto.NavIntDt.TheEnter ), doc.id, 0 /* web */, 0 );
			}
			if( url.indexOf( "st14Shopping" ) >= 0 ) // "st14Shopping"
				stockphoto.core.NavBar.SwitchNavBar( "st14_ShoppingCart", 0, 0, doc );
		};
		stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( app.document, true, "URLFilter" );
	}
	if (stockphoto.core.historyFilterKey != undefined)
	{
		//
		// don't add DR URLs to Bridge MRU list
		//
		if ( url.indexOf( stockphoto.core.historyFilterKey ) > -1 )
		{
			res.toHistory = false;
		}
	}

	stockphoto.core.log.logString( 0, "--- .. General Return -> result="+res.result+" url='"+res.url+"' His="+res.toHistory );

	    // Add language, billing and additional parameters for Photographers directory
    if ( url == stockphoto.core.html.urlForPhotographerDir )
	{
		var billing = "us";
		if( ( app.preferences.bm_billing_region != undefined )&&
			( app.preferences.bm_billing_region != "" ) )
			billing = ( app.preferences.bm_billing_region ).toLowerCase();
					
		// If the URL contains a '?' already, append with an '&'
		if (url.search(/\?/) == -1)
		{
            res.url = url + "?";
        }
        else
        {
            res.url = url + "&";
        }
        
		res.url = res.url+"language="+stockphoto.core.html.urlUILanguage+"&billing="+billing
                    + "&" + stockphoto.core.html.urlArgsForPhotoGDirInBridge;
        //res.toHistory = false; 
	}

	if (true == res.toHistory)
	{
		return ( res.url );
	}
	else
	{
		return ( res );
	}
}

stockphoto.core.BoxCar.LangCountry.getBillingCountry = function()
{
	// Core prefers "" to 'undefined'.
	var bc = "";
	var i;
	
	if (app.preferences.bm_billing_region != undefined)
	{
		bc = app.preferences.bm_billing_region;
	}

	return bc;
}

stockphoto.core.html.GetLanguageCountryBilling=function()
{
	var szlocale, Ret={};
	szlocale = stockphoto.core.getValidLocale(true);
	Ret.szLanguage = ( ( szlocale ).substr( 0,2 ) ).toLowerCase();
	Ret.szCountry  = ( ( szlocale ).substr( 3,2 ) ).toLowerCase();
	if( ( app.preferences != undefined )&&
	    ( app.preferences.bm_billing_region != undefined )&&
	    ( app.preferences.bm_billing_region != "" ))
	{
		var lang = stockphoto.core.BoxCar.LangCountry.getBillingCountry();
		Ret.szBilling = lang.toLowerCase();
	}
	else
	{
		Ret.szBilling  = "us";
	}
	return( Ret );
}

stockphoto.core.html.loadUrl = function() 
{
	var szlocale, p1, p2, p3;
	var DefDir="http://www.adobe.com"; // ultimate URL for no-case
	if( stockphoto.core.html.urlForBMHome == undefined ) 
	{
			stockphoto.core.BoxCar.HTMLUtil.GetURLFromPartnersXML();
	}
	if( stockphoto.core.html.urlForBMHome.length < 8 )
	{
		stockphoto.core.html.urlForBMHome  = DefDir;
	}

	// Obtain URL part
	if( stockphoto.core.html.urlForExplicitBMDir != undefined )
	{
		p3 = stockphoto.core.html.urlForExplicitBMDir.split('/');
		stockphoto.core.html.urlForEBFamily = p3[0]+'/'+p3[1]+'/'+p3[2]+'/';
	}
    p3 = stockphoto.core.html.urlForPhotographerDir.split('/');
	stockphoto.core.html.urlForBMPDFamily = p3[0]+'/'+p3[1]+'/'+p3[2]+'/';
    p3 = stockphoto.core.html.urlForBMHome.split('/');
	stockphoto.core.html.urlForBMHPFamily = p3[0]+'/'+p3[1]+'/'+p3[2]+'/';
	p3 = [];

	stockphoto.core.html.LengthOfUrlForBMHome = ( stockphoto.core.html.urlForBMHome ).length;
	if( stockphoto.core.html.urlForMoreWaysFindImg.length < 8 )
	{
		stockphoto.core.html.urlForMoreWaysFindImg = DefDir;
	}

	p1 = ( stockphoto.core.html.urlForBMHome ).indexOf( "://" ); 
	p2 = ( ( stockphoto.core.html.urlForBMHome ).substr( p1+3 ) ).indexOf( "/" ); 
	stockphoto.core.html.urlPrinciple = ( stockphoto.core.html.urlForBMHome ).substr( p1, p2 );
	return( stockphoto.core.html.urlForBMHome );
}

stockphoto.core.html.LocalHtmlCallBacks={
	/*B*/ // -------------------------------------------------------------------------------------
	/*B*/	_burpUrl_omitBurpUrl: function()
	/*B*/	{
	/*B*/		stockphoto.Burp.omitUrl = false;
	/*B*/ 	},
	/*B*/ 	_cbMisc_changePriceBegin: function( arg ) 
	/*B*/	{
	/*B*/		if( stockphoto.Burp.doIt )
	/*B*/		{	
	/*B*/			stockphoto.Burp.changePriceBegin( app.document.id, arg );
	/*B*/		}
	/*B*/ 	},
	/*B*/ 	_cbMisc_changePrice: function( arg ) 
	/*B*/	{
	/*B*/		if( stockphoto.Burp.doIt )
	/*B*/		{	
	/*B*/			stockphoto.Burp.changePrice( app.document.id, arg );
	/*B*/		}
	/*B*/ 	},
	/*B*/ 	_cbMisc_changePriceEnd: function( arg ) 
	/*B*/	{
	/*B*/		if( stockphoto.Burp.doIt )
	/*B*/		{	
	/*B*/			stockphoto.Burp.changePriceEnd( app.document.id, arg );
	/*B*/		}
	/*B*/ 	},
	/*B*/ 	_cbMisc_endShCart: function( arg ) 
	/*B*/ 	{
	/*B*/		if( stockphoto.Burp.doIt )
	/*B*/		{	
	/*B*/			stockphoto.Burp.endShCart( app.document.id, arg );
	/*B*/		}
	/*B*/ 	},
	/*B*/ // -------------------------------------------------------------------------------------
	_cbMisc_HTMScriptReady: function( Dummy ) 
	{
		stockphoto.core.html.HtmlScriptReadyStatus = true;
	},
	_cbMisc_execAdobeHelpCenter: function( Dummy ) 
	{
		// only called from NoSearchResult dialog
		app.scheduleTask( "stockphoto.MiscDlgs.SearchTips("+app.document.id/*Ok*/+");", 10, false );
	},
	_cbMisc_execMoreWas: function( eString )
	{
		// only called from NoSearchResult dialog
		var uString, title, url, separator;
		uString   = unescape( eString );
		separator = uString.indexOf( ",,,," );
		if( separator > 0 )
		{
			title = uString.substr( 0, separator );
			url   = uString.substring( separator+4, uString.length );
			stockphoto.core.html.openInDeafaultBrowser( url );
		}
	}
}  

stockphoto.core.html.doLocalHtm=function( Title, LocalHTMpath, FirstTime, doc_id, path) 
{
	if (doc_id == undefined)
	{
		doc_id = app.document.id;
	}

	var doc = stockphoto.documents[doc_id].document;

	var a, t;
	
	var saveLevel = $.level;
	$.level=0;
	try
	{
		t = new Thumbnail((path != undefined) ? path : "stockphoto://nothing");
	}
	catch(e)
	{
        t = new Thumbnail("stockphoto://nothing");	
	}
	$.level = saveLevel;
		
	stockphoto.core.log.logString( 0, "LocalHTML: "+LocalHTMpath );
	if( FirstTime )
	{
		stockphoto.core.html.HtmlScriptReadyStatus = false;
	}
		
	// BrowseScheme do not allow reset name (case "CanSetName":)
	// Watson : 1316135
	if( ("undefined" != typeof t ) && ("undefined" != typeof t.name) && 
	(0 == t.name.length || 0 <= (t.name).indexOf("stockphoto://nothing")) || (t.name).indexOf("shoppingcart") >= 0 )
	{
		t.name = Title;
	}

	t.displayMode = "web";
	t.displayPath = unescape( File( LocalHTMpath ).fsName );
	stockphoto.core.log.logString( 0, "LocalHTML (displayPath) : "+t.displayPath );
	a = stockphoto.core.html.setUrlFilter( doc );
	stockphoto.core.log.logString( 0, "LocalHTML UrlFilter: "+a );
	if( a ) 
	{ // do it once more
		stockphoto.core.html.setUrlFilter(doc);
	}
	doc.jsFuncs = stockphoto.core.html.LocalHtmlCallBacks;
	if( stockphoto.Burp.doIt ) // in doLocalHTML
	{
	/*B*/	try
	/*B*/	{
	/*B*/		stockphoto.Burp.setOmitBurpurl();
	/*B*/	} catch(e) { ; }
	}
	doc.thumbnail = t;
}

stockphoto.core.html.openInDeafaultBrowser = function(url)  
{
	var fname = "/urlLink";
	var fname1 = fname;
	var i = 0;
	while (true)
	{
		var urlLink = File(stockphoto.core.folder.getTempFolder() + fname1 + ".url");
		if (!urlLink.exists)
		{
			break;
		}
		else
		{
			i = i + 1;
			fname1 = fname + "-" + i;
		}
	}

	urlLink.open("w");
	urlLink.write("[InternetShortcut]\nURL=" + url + "\n");
	urlLink.close();
	
	urlLink.execute();
}

// -------------------------------------------------------------------------------------- html

//executed when st00Core.jsx is loaded.
//need to check that XML is ok before we load browseScheme.jsx and eventhandler.jsx.
stockphoto.core.init.checkPartnersXML();
if( stockphoto.core.init.partnersXMLfsObj != undefined )
{
//	stockphoto.loadScript(stockphoto.paths.scripts + "/browseScheme.jsx");
}


// --
// ui
// --

stockphoto.core.ui={};
stockphoto.core.ui.initAboutText = function()
{
	var title	= "Adobe Stock Photos";
	var	text;
	if (stockphoto.impl != undefined)
	{
		text = stockphoto.impl.version + "." + stockphoto.impl.build;
	}
	else
	{
		text = zc.get("$$$/About/version=Not loaded.");
	}
	text += '\n';
	
	var copyright = '\n';

	app.addCredits(title, text);
	// removed per legal app.addLegalNotice(title, copyright);
}

stockphoto.core.ui.setAlertDisplayPrefsDef = function(srcObj)
{
	with (stockphoto.core.consts)
	{
		srcObj[MsgAfterDownloadComp]        = true;
		srcObj[MsgAfterAddingImageToCart]   = true;
		srcObj[AutoDlImagesAfterCheckout]   = false;
		srcObj[ResumeDlsWhenBridgeStarts]   = true;
		srcObj[AlertDlsOnQuit]              = true;
		srcObj[MsgDlsInBackground]          = true;
	}

	app.preferences.bm_alertDisplayArray = srcObj.toSource();
}

stockphoto.core.ui.getAlertDisplayPrefs = function(key)
{
	var flattened = app.preferences.bm_alertDisplayArray;
	var srcObj;
	if (flattened == undefined)
	{
		srcObj = {};
		stockphoto.core.ui.setAlertDisplayPrefsDef(srcObj);
	}
	else
	{
		srcObj = eval(flattened);
	}
	
	// For unknown key, return true.
	if (srcObj[key] == undefined)
	{
		srcObj[key] = true;
	}

	return srcObj[key];
}

stockphoto.core.ui.setAlertDisplayPrefs = function(key, value)
{
	var flattened = app.preferences.bm_alertDisplayArray;
	var srcObj;
	if (flattened == undefined)
	{
		srcObj = {};
		stockphoto.core.ui.setAlertDisplayPrefsDef(srcObj);
	}
	else
	{
		srcObj = eval(flattened);
	}
	
	// store the value
	srcObj[key] = value;
	app.preferences.bm_alertDisplayArray = srcObj.toSource();
}

// -------------------------------------------------------------------------------------- ui

stockphoto.core.NavBar={};
stockphoto.core.NavBar.hideAllNavbars = function(doc)
{
	with (doc.navbars)
	{
		web.top.visible = false;
		web.bottom.visible = false;
		filesystem.top.visible = false;
		filesystem.bottom.visible = false;
	}
}

// SwitchNavBar()
stockphoto.core.NavBar.SwitchNavBar=function( Name, h, t, doc, kKeyWd ) 
{
	if( ( doc == undefined )||
	    ( doc.browserMode == "compact" ) )
	{
		return;
	}
	var args={};
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{ // Just to be sure that NavBar thing has been loaded
		if (( Name == "impl.checkout" ) || ( Name == "st20_MyAccount"))
		{
			stockphoto.core.BoxCar.NavBar.SetInECOMFlag( true, app.document.id );
		}
		
		args.specifier = Name;
		args.TNBarType = h;
		if( ( kKeyWd != undefined )&&( kKeyWd != "" ) )
		{
			args.kKeyWd = kKeyWd;
		}
		if( doc==undefined )
			stockphoto.core.log.logString( 0, "SwitchMenu: ?doc? "+Name+" [h:"+h+",t:"+t+"]" );
		else
			stockphoto.core.log.logString( 0, "SwitchMenu: [doc] "+Name+" [h:"+h+",t:"+t+"]" );

		stockphoto.core.log.logString( 0, "                  id="+doc.id );
		stockphoto.NavExtFnc.addBMNavBar( args, t, doc ); // In SwichNavBar(), Nav bar is already loaded
	}
}

stockphoto.core.removePhotoDir=function(enableBeforeDelete)
{
    // Insert Photographer's directory after Adobe Stock Photos
	if( app.favorites != undefined )
	{
		// if it already exists, remove it first
		app.favorites.section = 'standard';
		
		try
		{
			if(enableBeforeDelete && app.favorites.contains(stockphoto.uris.APDScript))
			{
				app.favorites.enable(stockphoto.uris.APDScript);
			}	
		}catch(e){}
		
        var oAPDItem = stockphoto.findFavoritesItem( stockphoto.uris.APDScript );
        if (undefined != oAPDItem.thumb)
        {
            app.favorites.remove(oAPDItem.thumb);
        }
    }
}

stockphoto.core.insertPhotoDir=function()
{
    // Insert Photographer's directory after Adobe Stock Photos
	if (( undefined != app.favorites ) && (undefined != stockphoto.core.BoxCar.HomePage.APSPhotoDir.root))
	{
		 // if it already exists, just update the thumbnail
        var oAPDItem = stockphoto.findFavoritesItem( stockphoto.uris.APDScript );
        var oAPDFav = stockphoto.core.BoxCar.HomePage.APSPhotoDir.root;
        if (undefined != oAPDItem.thumb)
        {
        	var oAPDThumb = oAPDItem.thumb;
        	oAPDThumb.displayPath = stockphoto.core.util.getDisplayPath(oAPDFav,"");
        	oAPDThumb.name = oAPDFav.name;
        	oAPDThumb.path = oAPDFav.path;
        	oAPDThumb.displayMode = oAPDFav.displayMode;
        	oAPDThumb.iconPath = oAPDFav.iconPath;
        }
        else
        {
			app.favorites.section = 'standard';
			var oASPHomeItem = stockphoto.findFavoritesItem( stockphoto.uris.homeScript );
			app.favorites.insert( stockphoto.core.BoxCar.HomePage.APSPhotoDir.root,  oASPHomeItem.position );
		 }
    }
}


// -------------------------------------------------------------------------------------- NavBar

//initialization
stockphoto.core.makeIconPath = function(baseName)
{
	var iconPath;
	var	iconExt;
	if (Folder.fs == "Macintosh")
	{
		iconPath = stockphoto.startUpFolderForMac + "/Resources/Icons/";
		iconExt = ".icns"; 
		return iconPath + baseName + iconExt;
	}
	else
	{
		iconPath = Folder.startup + "/../"+stockphoto.core.installFolder+"/Icons/";
		iconExt = ".ico";
		var iconFile = new File(iconPath + baseName + iconExt);
		return iconFile.fsName;
	}
}

//
// Top-level file system thumbnails
//
stockphoto.core.Thumbs = function()
{
	this.setPaths = function()
	{
		with (stockphoto.core.folder)
		{
		    var saveLevel = $.level;
		    $.level=0;
		    try
		    {
				this.root			= new Thumbnail(File(getMyFolder()));
			}
			catch(e)
			{}
		    try
		    {
				this.comps			= new Thumbnail(File(getMyCompFolder()));
			}
			catch(e)
			{}
		    try
		    {
				this.purchases		= new Thumbnail(File(getMyPurchasesFolder()));
			}
			catch(e)
			{}
		    try
		    {
				this.recentSearches	= new Thumbnail(File(getMySearchesFolder()));
			}
			catch(e)
			{}
			$.level = saveLevel;
		}
	}
	this.setPaths();
	this.initialized = true;
}

// Update an existing Favorites child of ASP
// Do not remove/add unnecessarily (it may confuse Bridge's caching algo)
// Returns the updated thumbnail
stockphoto.core.updateASPChildItem = function(oThumb, oParent)
{
	var oFavItem = oThumb; // default return value
	
	if (undefined != oThumb)
	{
	
	    if (undefined != oParent && app.favorites.contains(oParent.uri))
	    {
	       var childList = app.favorites.getChildren(oParent.uri);
	       
	       if (undefined != childList)
	       {
	          var counter;

	          for (counter = 0; counter < childList.length; counter++)
	          {
	             if (childList[counter] == oThumb.uri)
	             {
	                oFavItem = new Thumbnail(childList[counter]);
	                oFavItem.displayPath = stockphoto.core.util.getDisplayPath(oThumb,"");
	                break;
	             }
	          }
	          
	          if (counter == childList.length)
	          {
	              app.favorites.addChild( oParent, oThumb );
	          }
	       }
	       else
	       {
	           app.favorites.addChild( oParent, oThumb );
	       }
	    }
	    
		// See if the child node exists ...
   }
   
   return oFavItem;
}

// Return the Number of .jpg images in folder <strFolderName>
stockphoto.core.getjpgImagecount = function(strFolderName)
{
	var iImageCount = 0;
	if( ("undefined" != typeof strFolderName) && ("" != strFolderName) ){
	
		var keyFolder = Folder( strFolderName );
		if( ("undefined" != typeof keyFolder) && (keyFolder.exists) ){
		
			var thumbList = keyFolder.getFiles("*.jpg");
			if( ("undefined" != typeof thumbList) && (thumbList.length >= 0)){
			
				iImageCount = thumbList.length;
			}
		}
	}
	return iImageCount;
}

//
// "Places" thumbnails ("stockphoto://" browse scheme)
//
stockphoto.core.Places = function( thumbnail )
{
	this.setPaths = function()
	{
		try
		{
			var lcb=stockphoto.core.html.GetLanguageCountryBilling();
			stockphoto.core.html.urlForBMHPatBrowseSche 
	//			= stockphoto.core.html.urlForBMHome+"?language="+lcb.szLanguage+"&country="+lcb.szCountry+"&billing="+lcb.szBilling;
				= stockphoto.core.html.urlForBMHome+"?language="+lcb.szLanguage+"&country="+lcb.szCountry+"&billing="+lcb.szBilling+"&version="+stockphoto.core.BM_3Version;

			if (("undefined" == typeof this.home.displayPath) || (this.home.displayPath != stockphoto.core.html.urlForBMHPatBrowseSche))
			{		
				this.home.displayPath = stockphoto.core.html.urlForBMHPatBrowseSche;
			}
			this.comps.displayPath 			= stockphoto.core.folder.getMyCompFolder();
			this.purchases.displayPath 		= stockphoto.core.folder.getMyPurchasesFolder();
			this.recentSearches.displayPath = stockphoto.core.folder.getMySearchesFolder();
			this.comps.path 		 = stockphoto.core.folder.getMyCompFolder();
			this.purchases.path 	 = stockphoto.core.folder.getMyPurchasesFolder();
			this.recentSearches.path = stockphoto.core.folder.getMySearchesFolder();
			
			// Keep note of what Locale we formed the URLs with...
			app.preferences.bm_PrevLocale = stockphoto.core.getValidLocale();
		}
		catch(e)
		{
			//alert(e);
		}
	}

	this.addMainStockFavs = function()
	{
        app.favorites.section = "standard";
        
        var oASPHomeFavItem = stockphoto.findFavoritesItem( stockphoto.uris.homeScript );

        if (undefined != oASPHomeFavItem.thumb)
        {
        	oASPHomeThumb = oASPHomeFavItem.thumb;
        	oASPHomeThumb.displayPath = stockphoto.core.util.getDisplayPath(this.home,"");
        	oASPHomeThumb.name = this.home.name;
        	oASPHomeThumb.path = this.home.path;
        	oASPHomeFavItem.displayMode = this.home.displayMode;
        	oASPHomeFavItem.iconPath = this.home.iconPath;
        }
        else
        {
        	app.favorites.insert(this.home);
        }
		
		var oLCB = stockphoto.core.html.GetLanguageCountryBilling();
		 //KR .. Chek..Get the locale to be checked for APD from Bridge (and not ASP)
		var sLocale = stockphoto.core.getOrigLocale();
		var sLang = oLCB.szLanguage;
		if (undefined != sLocale)
    	{
     	   sLang = sLocale.substr( 0,2 ).toLowerCase();
    	}
		if (stockphoto.core.isAPDLang(sLang))
		{
            stockphoto.core.BoxCar.HomePage.startPhotoDir();
            stockphoto.core.insertPhotoDir();
		}
		else
		{
            stockphoto.core.removePhotoDir(true);
        }
    }
    
    this.addStockItems = function()
	{
        app.favorites.section = "standard";

		// app.favorites.addChild( this.home, this.recentSearches );
		this.recentSearches = stockphoto.core.updateASPChildItem(this.recentSearches, this.home);
		// app.favorites.addChild( this.home, this.comps );
		this.comps = stockphoto.core.updateASPChildItem(this.comps, this.home);
		// app.favorites.addChild( this.home, this.purchases );
		this.purchases = stockphoto.core.updateASPChildItem(this.purchases, this.home);
	}

	with (thumbnail)
	{
		name 		= stockphoto.core.consts.localizedMenuString[0];
		displayMode = "web";
		displayPath = stockphoto.core.html.loadUrl();
		iconPath 	= stockphoto.core.makeIconPath("AdobeStockPhotos");
	}

	this.home = thumbnail;

	this.comps 				= new Thumbnail( "stockphoto://comps", stockphoto.core.consts.localizedMenuString[1] );
	// this.comps 				= new Thumbnail( stockphoto.core.folder.getMyCompFolder(), stockphoto.core.consts.localizedMenuString[1] );
	
	this.comps.displayMode 	= "filesystem";
	this.comps.iconPath 	= stockphoto.core.makeIconPath( "SavedLowResolution" );
//	this.comps.displayath 	= stockphoto.core.folder.getMyCompFolder();
//	this.comps.path 		= stockphoto.core.folder.getMyCompFolder();

	this.purchases 				= new Thumbnail( "stockphoto://purchases", stockphoto.core.consts.localizedMenuString[2] );
	// this.purchases 				= new Thumbnail( stockphoto.core.folder.getMyPurchasesFolder(), stockphoto.core.consts.localizedMenuString[2] );
	this.purchases.displayMode 	= "filesystem";
	this.purchases.iconPath 	= stockphoto.core.makeIconPath( "PurchasedImages" );
//	this.purchases.displayPath 	= stockphoto.core.folder.getMyPurchasesFolder();
//	this.purchases.path 		= stockphoto.core.folder.getMyPurchasesFolder();

	this.recentSearches 			= new Thumbnail( "stockphoto://searches/recent", stockphoto.core.consts.localizedMenuString[4] );
	// this.recentSearches 			= new Thumbnail( stockphoto.core.folder.getMySearchesFolder(), stockphoto.core.consts.localizedMenuString[4] );
	this.recentSearches.displayMode = "filesystem";
	this.recentSearches.iconPath 	= stockphoto.core.makeIconPath( "RecentSearches" );
//	this.recentSearches.displayPath = stockphoto.core.folder.getMySearchesFolder();
//	this.recentSearches.path 		= stockphoto.core.folder.getMySearchesFolder();


	// Additions
	this.scFooter 				= new Thumbnail( "stockphoto://scFooter", "scFooter" );
	this.scFooter.name 			= stockphoto.core.consts.localizedMenuString[0];
	this.scFooter.displayMode 	= "web";
	this.scFooter.displayPath 	= stockphoto.core.html.loadUrl();
	this.scFooter.iconPath 		= stockphoto.core.makeIconPath("AdobeStockPhotos");

	this.shoppingcart 				= new Thumbnail( "stockphoto://shoppingcart", "shoppingcart" );
	this.shoppingcart.iconPath  	= stockphoto.core.makeIconPath("AdobeStockPhotos");
	this.shoppingcart.displayMode 	= "web";
	this.shoppingcart.displayPath 	= stockphoto.core.folder.getMyShoppingCartFolder() + "/" + stockphoto.core.consts.ShoppingCartName;

	this.setPaths();

	this.initialized = true;
}

//executed when st00Core.jsx is loaded.
//need to check that XML is ok before we load browseScheme.jsx and eventhandler.jsx.
if( stockphoto.core.init.partnersXMLfsObj != undefined )
{
	stockphoto.loadScript(stockphoto.paths.scripts + "/eventHandler.jsx");
}
else
{
	stockphoto.DL.generalAlertBox(stockphoto.core.consts.localizedErrorString[9], 2);
}

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

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.core.init.loadBMScripts())
		{
//-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 = stockphoto.places.initialized && 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.core.init.loadBMScripts())
		{
//-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 = stockphoto.places.initialized && 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()
	{
		//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 = stockphoto.places.initialized && this.parObj.selectionInfo.somePurchased;
	}

	// 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()
	{
		//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 = stockphoto.places.initialized
			&& (! this.parObj.selectionInfo.inSearchFolder)
			&& (this.parObj.selectionInfo.someComps && !this.parObj.selectionInfo.somePurchased);
	}

	// 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.core.init.loadBMScripts())
		{
//-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 = stockphoto.places.initialized
			&& this.parObj.selectionInfo.inSearchFolder
			&& 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.core.init.loadBMScripts())
		{
//-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 = stockphoto.places.initialized && this.parObj.selectionInfo.unpurchased;
	}

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

stockphoto.core.menu.thumbContextMenuObj = new stockphoto.core.menu.thumbnailContextMenu;

stockphoto.core.log.getDebugSwitch();

/*B*/	// -----   Burp() --- Begin --- /*B*/
/*B*/	stockphoto.Burp={
/*B*/		doubleQuote:			 "\"",
/*B*/		doubleClickSec:          3, /* means < 3 sec. */ 
/*B*/		code_initialize:         0,
/*B*/		code_search:             1,
/*B*/		code_getComp:            2,
/*B*/		code_addToCart:          3,
/*B*/		code_removeFromCart:     4,
/*B*/		code_checkOut:           5,
/*B*/		code_url:       	     6,  // URLfilter
/*B*/		code_changeRel:          7,  // User change resolution in the cart
/*B*/		code_sptrigger:          8,  // spTrigger
/*B*/		code_result:             9,  // Search result
/*B*/		code_download:           10, // Search result
/*B*/		code_terminate:          11, // terminate
/*B*/		code_chkoutComp:         12, // checkout completed / return from DR
/*B*/		code_favorite:           13,
/*B*/		code_doubleClick:        14,
/*B*/		code_gpk:                15,
/*B*/		code_ignore:             16,
/*B*/		code_officialLast:       16, // <---- Last one
/*B*/		code_viewProviderTab:	 17, // For Provider tab
/*B*/		code_submitSurvey:		 18, // For Survey
/*B*/		code_changeView :		 20,
/*B*/		code_favoriteIcon:		 21,
/*B*/		// ---------------------------------------------------------------------------------
/*B*/		doIt:                    false, // master switch
/*B*/		doCheckFurther:          false,
/*B*/		// ---------------------------------------------------------------------------------
/*B*/		logFileInit:             true,
/*B*/		logFile:                 "",
/*B*/		sendToServer:            true,
/*B*/	//	userID:					 "",
/*B*/		Name_ID_Tab:             [],
/*B*/		searchFrom:              [], 	// "basic", "advanced", "gpk", or "browse"
/*B*/		searchId:                [],	// init at search()
/*B*/		searchFolder:			 [],	//		"
/*B*/		searchWritten:           [],	//		"
/*B*/		searchLang:              [],  	//		"
/*B*/		searchPageNo:            [],	//		"			// 1,2,3,..
/*B*/		// ---------------------------------------------------------------------------------
/*B*/		dispCode:                [],
/*B*/		dispValue:               [],
/*B*/		dispRef:                 [],
/*B*/		prevArgK:				 [],
/*B*/		// ---------------------------------------------------------------------------------
/*B*/		menuSorce:				 [],
/*B*/		addCartSource:			 "btn",
/*B*/		downloadSource:			 [],
/*B*/		getCompSource:	         [],
/*B*/		getCompMediaID:	         [],
/*B*/		getCompList:             [],
/*B*/		gpkSource:				 "btn",
/*B*/		// ---------------------------------------------------------------------------------
/*B*/		currSc: 				 undefined,
/*B*/		currSc_Sum:				 "0.0",
/*B*/		currSc_SumCurrency:		 "USD",
/*B*/		// ---------------------------------------------------------------------------------
/*B*/		prevTimeStamp:			 [],
/*B*/		// --------------------------------------------------------------------------------
/*B*/	//	inGetComSaving:			 false,
/*B*/	//	noInBuff:				 0,
/*B*/	//	maxNoInBuff:			 128,
/*B*/	//	buff:					 [],
/*B*/		// ---------------------------------------------------------------------------------
/*B*/		omitUrl:				 false,
/*B*/		// ---------------------------------------------------------------------------------
/*B*/		exist_partnersXMLfsObj:  true,	// temporary switch
/*B*/		exist_AnalyzeXmlFileObj: true   // temporary switch
/*B*/	};
/*B*/	
/*B*/	if( typeof stockphoto.core.init.partnersXMLfsObj == "undefined" ) 
/*B*/	{
/*B*/		stockphoto.Burp.exist_partnersXMLfsObj = false;
/*B*/		stockphoto.core.init.checkPartnersXML();
/*B*/	}
/*B*/	if( typeof stockphoto.core.BoxCar.AnalyzeXmlFileObj == "undefined" )
/*B*/	{
/*B*/		stockphoto.Burp.exist_AnalyzeXmlFileObj = false;
/*B*/	}
/*B*/	if( typeof stockphoto.core.init.partnersXMLfsObj != "undefined" )
/*B*/	{
/*B*/		if( typeof stockphoto.core.BoxCar.AnalyzeXmlFileObj == "undefined" )
/*B*/		{
/*B*/			if( typeof stockphoto.core.init.partnersXMLfsObj == "undefined" ) 
/*B*/			{
/*B*/				stockphoto.core.init.checkPartnersXML();
/*B*/			}
/*B*/			if( typeof stockphoto.core.init.partnersXMLfsObj != "undefined" )
/*B*/			{
/*B*/				stockphoto.core.BoxCar.AnalyzeXmlFileObj = new stockphoto.core.BoxCar.AnalyzeXmlFile( stockphoto.core.init.partnersXMLfsObj, stockphoto.core.BoxCar.HTMLUtil.CheckKeys );
/*B*/			}
/*B*/		}
/*B*/		if( typeof stockphoto.core.BoxCar.AnalyzeXmlFileObj != "undefined" )
/*B*/		{
/*B*/		//	// partners.xml is ready
/*B*/			for( var ij=0; ij<stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner.length; ij++ )
/*B*/			{
/*B*/				stockphoto.Burp.Name_ID_Tab[ ij ] = { id:"", Name:"" };
/*B*/				try
/*B*/				{
/*B*/					stockphoto.Burp.Name_ID_Tab[ ij ].id   = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner[ij].PartnerFilenameCode.Value;
/*B*/					stockphoto.Burp.Name_ID_Tab[ ij ].Name = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner[ij].PartnerName.Value.toLowerCase();
/*B*/				} catch(e) {;};
/*B*/			}
/*B*/			stockphoto.Burp.doCheckFurther = true;
/*B*/		//	stockphoto.Burp.url            = "http://Doraemon";
/*B*/		//	stockphoto.Burp.randomize      = 100;
/*B*/			if( stockphoto.Burp.logFile == "" )
/*B*/			{
/*B*/				if( stockphoto.core.log.DebugINIData.burp != undefined ) 
/*B*/				{
/*B*/					if( stockphoto.core.log.DebugINIData.burp.charAt(0) != '/' )
/*B*/					 	 stockphoto.Burp.logFile = ( Folder( stockphoto.core.folder.getMyShoppingCartFolder() ) ).parent+"/"+stockphoto.core.log.DebugINIData.burp;
/*B*/					else stockphoto.Burp.logFile = stockphoto.core.log.DebugINIData.burp;
/*B*/				}
/*B*/				if( stockphoto.core.log.DebugINIData.comm != undefined ) 
/*B*/				{
/*B*/					stockphoto.Burp.sendToServer = stockphoto.core.log.DebugINIData.comm;
/*B*/				}
/*B*/			}
/*B*/			// -------------------------------- Let Burp partners.xml to use regardless
/*B*/		} // if( stockphoto.core.BoxCar.AnalyzeXmlFileObj != undefined )
/*B*/	} // if( stockphoto.core.init.partnersXMLfsObj != undefined )
/*B*/	
/*B*/	// Restoration
/*B*/	if( ! stockphoto.Burp.exist_AnalyzeXmlFileObj )
/*B*/	{	// used to be false
/*B*/		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj != undefined )
/*B*/		{
/*B*/			stockphoto.core.BoxCar.AnalyzeXmlFileObj.removeMem();
/*B*/			delete stockphoto.core.BoxCar.AnalyzeXmlFileObj;
/*B*/			stockphoto.core.BoxCar.AnalyzeXmlFileObj = undefined;
/*B*/		}
/*B*/	}
/*B*/	if( ! stockphoto.Burp.exist_partnersXMLfsObj )
/*B*/	{	// used to be false
/*B*/		if( stockphoto.core.init.partnersXMLfsObj != undefined )
/*B*/		{
/*B*/			delete stockphoto.core.init.partnersXMLfsObj;
/*B*/			stockphoto.core.init.partnersXMLfsObj = undefined;
/*B*/		}
/*B*/	}
/*B*/	// -----   Burp() --- End --- /*B*/

// Given a Thumbnail, determine if it is within or equal to the
// same physical folder as the hierarchy Thumbnail.
// 
stockphoto.core.menu.isInFolderHierarchy = function(thumb, hierarchy)
{
	var result = false;
	var localThumb;
	
	if ((thumb instanceof Thumbnail) && (hierarchy instanceof Thumbnail))
	{
		var	realHierarchy;
//		if (hierarchy.path != hierarchy.displayPath)
		if ( ! stockphoto.core.util.isDisplayPathEqual( hierarchy.path, stockphoto.core.util.getDisplayPath( hierarchy, "isInFolderHierarchy()-1" ) ) )
		{
//			realHierarchy = new Thumbnail(hierarchy.displayPath);
            var saveLevel = $.level;
            $.level=0;
            try
            {
				realHierarchy = new Thumbnail( File(stockphoto.core.util.getDisplayPath( hierarchy, "isInFolderHierarchy()-2" )) );
			}
			catch(e)
			{	
			   $.level = saveLevel;	
			   return false;	
			}
			$.level = saveLevel;
		}
		else
		{
			realHierarchy = hierarchy;
		}
		
		var saveLevel = $.level;
		$.level=0;
		try
		{
			localThumb = new Thumbnail(thumb);
		}
		catch(e)
		{
		    $.level = saveLevel;
		    return false;
		}
		$.level = saveLevel;
		
		// Workaround for Bridge 316 -BEGIN-
		var tmpRelHier = stockphoto.core.util.getDisplayPath( realHierarchy,  "isInFolderHierarchy()-3" );
		var tmpLocHier;
		// Workaround for Bridge 316 -END-
		while (true)
		{
			if (localThumb instanceof Thumbnail)
			{
				if (localThumb == realHierarchy)
				{
					result = true;
					break;
				}
				tmpLocHier = stockphoto.core.util.getDisplayPath( localThumb,  "isInFolderHierarchy()-4" );
				if( stockphoto.core.util.isDisplayPathEqual( tmpRelHier, tmpLocHier ) )
				{
					result = true;
					break;
				}
			}
			else
			{
				// parent can not be checked
				result = false;
				break;
			}
			
			if (typeof localThumb.parent != "undefined")
			{
				// move up to next level of hierarchy
				var saveLevel = $.level;
				$.level=0;
				try
				{
					localThumb = new Thumbnail(localThumb.parent);
				}
				catch(e)
				{
				    $.level = saveLevel;
					result = false;
					break;
				}
				$.level = saveLevel;
			}
			else
			{
				// root has no parent
				result = false;
				break;
			}
		}
	}
	
	return result;
}

// *************************
// Point App's API in Bridge
// *************************

stockphoto.PointApp = function()
{
	this.displayStartPage = function( maximize )
	{
		if (!stockphoto.places.initialized)
		{
			return;
		}
		var	url = "stockphoto://home";
		var	length = app.documents.length;
		var	doc;
		for (i = 0; i < length; i++)
		{
			doc = app.documents[i];
			if ( doc.thumbnail.path == url )
			{
				doc.bringToFront();
				break;
			}
			doc = undefined;
		}
		if ( doc == undefined )
		{
			app.browseTo( url );
			doc = app.document;
		}
		if ( maximize )
		{
			doc.maximize();
		}
	};

	this.buy = function( imageIdList )
	{
	};
}

stockphoto.pointApp = new stockphoto.PointApp();

stockphoto.internaldisplayStartPage = function( doc_id )
{
	if (stockphoto.places.initialized)
	{
		if( doc_id == undefined )
		{
			if (undefined == app.document)
			{
				app.browseTo(stockphoto.uris.home);
			}
			
			doc_id = app.document.id;
		}
		stockphoto.DL.NavBar.PrepareNavBar( doc_id );
		if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_HomePage ) ) 
		{
			stockphoto.HomePage.displayStartPage( doc_id );
		}
	}
}

stockphoto.displayStartPage = function( doc_id )
{
    app.bringToFront();
	stockphoto.core.log.logString( 0, "\n\n\n\n\n<<Point App API>> displayStartPage()" );

	with (stockphoto.eventHandler.displayStartPage)
	{
		if (scheduled > 0)
		{
			scheduled--;
			if (altTask != undefined)
			{
				if (scheduled > 0)
					return;
				stockphoto.core.log.logString( 0, "Performing alternative task in displayStartPage()" );
				eval(altTask);
				altTask = undefined;
				return;
			}
		}
	}

	stockphoto.internaldisplayStartPage( doc_id );
}

stockphoto.core.doBMbuy = function( f )
{
	if (!stockphoto.places.initialized)
	{
		return;
	}

	var priceIndex = 0; // always default to first price in list
	var i, fStr, fsIn, e="", ee=[];
	if( stockphoto._CheckBillingCountry( "st01_AddToCart", app.document ) != 2 )
	{
		return 0; // means the request is denied
	}
	if( stockphoto.core.init.loadBMScripts() ) 
	{
		if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) )
		{
			stockphoto.NavExtFnc.SetFromBuyFlag();
		}
		stockphoto.core.NavBar.SwitchNavBar( "st01_AddToCart", 0, 1, app.document );
		if( f.length > 0 ) 
		{
			if( f[0] instanceof File ) 
			{
				stockphoto.DL.addGroupThumbsToCart( f, priceIndex ) ;
				return( 1 );
			} 
			else 
			{
				for( i=0; i<f.length; i++ ) 
				{
					if( i != 0 ) 
					{
						e += ",";
					}
					if( f[i].substr( 0,4 ) == "//?/" )
					{
						fStr = f[i].substr( 4, f[i].length - 4 );
					}
					else 
					{
						fStr = f[i];
					}
					fsIn = new File( fStr );
					if( fsIn.exists )
					{
						e += 'File("' + fStr + '")';
					}
					delete fsIn;
				}
				e = "var ee = [ " + e + "];";
				try 
				{
					eval( e );

					stockphoto.DL.addGroupThumbsToCart( ee, priceIndex ) ;

					return( 1 );
				} 
				catch(m) 
				{

					stockphoto.DL.generalAlertBox("Cann't happen.", 2);
				}
			}
		}
	}
	return( 0 ); 
}

stockphoto.internalbuy = function( f )
{
	if (stockphoto.documents.length != 0)
 	{
		var doc_id=app.document.id;
	
		if( doc_id != undefined ) 
		{

			var doc = stockphoto.core.findDoc( doc_id );

   			if(( doc != undefined )&&(stockphoto.documents[doc_id]!=undefined)) 
			{
				app.document.bringToFront();
				stockphoto.core.doBMbuy(f);
				return;
			}
		}
	}
	
	var tarray = '"' + f[0] + '"';
	for (i = 1; i < f.length; i++)
	{
		tarray += "," + '"' + f[i] + '"';
	}
	app.scheduleTask("stockphoto.internalbuy([" +tarray+"])", 100, false);
}

stockphoto.buy = function( f )
{
    app.bringToFront();
    
	var tarray = '"' + File.decode(f[0]) + '"';
	for (i = 1; i < f.length; i++)
	{
		tarray += "," + '"' + File.decode(f[i]) + '"';
	}

	/*B*/ stockphoto.Burp.addCartSource = "pnt";
	
	// Must add this task to the end of the task list to give time to finish NavBar tasks.
	app.scheduleTask("stockphoto.internalbuy([" +tarray+"])", 500, false);
				
	app.scheduleTask("if( app.document != undefined ) app.document.bringToFront()", 100, false );
	app.scheduleTask("if( app.document != undefined ) app.document.bringToFront()", 2000, false );
}

stockphoto.checkLicense = function( imageIdList )
{
    app.bringToFront();
	stockphoto.DL.ShowLicenseAgreement(imageIdList);
}

stockphoto.partnerNameToFilenameCode = function(partnerName)
{
    var oResult;    
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
    {
        oResult = stockphoto.MiscUtils.file.partnerNameToFilenameCode(partnerName);
    }
    return oResult;
}

stockphoto.partnerNameToPartnerDisplayName = function(sPartnerName)
{
	if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
    {
        return stockphoto.MiscUtils.core.partnerNameToPartnerDisplayName(sPartnerName);
    }
    else
    {
		return sPartnerName;
	}
}

stockphoto.partnerEComIDToPartnerName = function(partnerEComID)
{
	// This code is partners.xml scheme dependent: <PartnerEComID> has to
	// follow <PartnerName>.
	/***** Watson: 1172167 *******/
	var bFound = false;
	
	var partnerRegExp       = /<Partner +Version=\"(.*)\"/;
	var partnerNameRegExp   = /<PartnerName .*Value=\"(.*)\"/;
	var partnerEComIDRegExp = /<PartnerEComID .*Value=\"(.*)\"/;

	var partnerName = undefined;

	try
	{
		if( typeof stockphoto.core.init.partnersXMLfsObj == "undefined" )
		{
			throw( "Hopeless" );
		}
		var px = stockphoto.core.init.partnersXMLfsObj;

		px.open();

		while (!px.eof)
		{
			var line = px.readln();

			var mtch = partnerRegExp.exec(line);
			if (mtch != null)
			{
				partnerName = undefined;
				continue;
			}

			var mtch = partnerNameRegExp.exec(line);
			if (mtch != null)
			{
				partnerName = RegExp.$1;
				continue;
			}

			mtch = partnerEComIDRegExp.exec(line);
			if (mtch != null && partnerName != undefined)
			{
				if (RegExp.$1 == partnerEComID)
				{
				   /***** Watson: 1172167 *******/
				   bFound = true;
					break;
				}
			}
		}

		px.close();
	}
	catch (e)
	{
		partnerName = undefined;
	}

    /***** Watson: 1172167 *******/
    if (false == bFound)
    { 
       var text1 = zc.get("$$$/AlertBox/ERROR_WEBSERVICE_INVALIDPURCHASEID=The requested Image is not available for download. ");
       var text2 = zc.get("$$$/AlertDialog/Dialog/CustomerServiceButton=Contact Customer Service"); 
       var text3 = zc.get("$$$/AlertDialog/Dialog/PleaseInclude=. Please include the following info in your communication: ASP version: ");
       
       if ( ("undefined" != typeof stockphoto) && ("undefined" != typeof stockphoto.core) && ("undefined" != typeof stockphoto.core.BM_3Version))
       {
           text3 = text3 + stockphoto.core.BM_3Version;
       }
       
       stockphoto.DL.generalAlertBox(text1 + text2 + text3, 2);
       partnerName = undefined;
    }

	return partnerName;
}

// If we start from ShoppingCart, move to Bridge//desktop
if( app.preferences != undefined ) 
{
	if( app.preferences.target != undefined ) 
	{
		var fsIn = new File( app.preferences.target );
		if( fsIn.name.toLowerCase() == "shoppingcart" ) 
		{
			var fsOut = new Folder( fsIn.path );
			app.preferences.target = "stockphoto://home";
			delete fsOut;
		}
		delete fsIn;
	}
}

//added by aman
stockphoto.core.removeEmptyFolder=function( fs )
{
	var j, f;
	f = fs.getFiles("*");
	if( f != null )
	{
		for( j=0; j<f.length; j++ )
		{ 
			if( f[j] instanceof File )
			{
				f[j].remove();
			}
			else
			{
				stockphoto.core.removeEmptyFolder( f[j] );
			}
		}
		fs.remove();
	}
}

//end of added by aman



// === ----------------------- ===
// === Additional for Box Car. ===
// === ----------------------- ===

stockphoto.core.BoxCar.HTMLUtil.GetURLFromPartnersXML=function() 
{
	var fsIn, line, nL, bInAdobe=false, j, nn, i, k, s, Bt;
	var xmlPath;
 	if( typeof stockphoto.core.init.partnersXMLfsObj == "undefined" ) 
	{
		stockphoto.core.init.checkPartnersXML();
	}
	if( typeof stockphoto.core.BoxCar.AnalyzeXmlFileObj == "undefined" )
	{
		stockphoto.core.BoxCar.AnalyzeXmlFileObj = new stockphoto.core.BoxCar.AnalyzeXmlFile( stockphoto.core.init.partnersXMLfsObj, stockphoto.core.BoxCar.HTMLUtil.CheckKeys );
	}
	if( typeof stockphoto.core.BoxCar.AnalyzeXmlFileObj != "undefined" )
	{
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners =  [];
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0] == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0] = {};
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports = [];
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0] == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0] = {};
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HomeURL == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HomeURL = {};
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HomeURL.Value == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HomeURL.Value = "http://cs2-stockphotos.adobe.com/dcs_photo_home.html";
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].MoreWaysFindImgURL == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].MoreWaysFindImgURL =  {};
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].MoreWaysFindImgURL.Value == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].MoreWaysFindImgURL.Value =  "http://cs2-stockphotos.adobe.com/get_more_images";
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirURL == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirURL =  {};
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirURL.Value == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirURL.Value =  "http://www.photographersdirectory.adobe.com/?c=main";
		stockphoto.core.html.urlForBMHome            = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HomeURL.Value;
		stockphoto.core.html.urlForMoreWaysFindImg   = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].MoreWaysFindImgURL.Value;
		stockphoto.core.html.urlForPhotographerDir   = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirURL.Value;
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ExplicitBMURL != undefined )
		{
			stockphoto.core.html.urlForExplicitBMDir = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ExplicitBMURL.Value;
		}
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirBrowser == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirBrowser =  {};
		if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirBrowser.Value == undefined )
			stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirBrowser.Value =  "default";
		stockphoto.core.html.browserForPhotoGDir     = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirBrowser.Value;
			
			
        // Arguments for Photographers Directory in Bridge
        if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirBridgeArgs != undefined
            &&  stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirBridgeArgs.Value != undefined )
		{
            stockphoto.core.html.urlArgsForPhotoGDirInBridge = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotographersDirBridgeArgs.Value;
        }
        // Change for APD Locales
		if( "undefined" != typeof(stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].APDLocales) )
		{
			app.preferences.bm_APDLocales = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].APDLocales.Value;
		}
		
		// ASP Help Topic Display
		if (( "undefined" != typeof(stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HelpTopicBase) )
			&& ( "undefined" != typeof(stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HelpTopicBase.Value) ) )
		{
            // Overwrite our helpTopicBase...
            stockphoto.core.helpTopicBase = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HelpTopicBase.Value;
        }
        
        // ASP Help Topic Display
		if (( "undefined" != typeof(stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HelpTopicProxy) )
			&& ( "undefined" != typeof(stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HelpTopicProxy.Value) ) )
		{
            // Overwrite our helpTopicProxy...
            stockphoto.core.helpTopicProxy = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HelpTopicProxy.Value;
        }

        // ASP Help Topic Display
		if (( "undefined" != typeof(stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HelpTopicBridgeVersion) )
			&& ( "undefined" != typeof(stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HelpTopicBridgeVersion.Value) ) )
		{
            // Overwrite our helpTopicBridgeVersion...
            stockphoto.core.helpTopicBridgeVersion = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].HelpTopicBridgeVersion.Value;
        }

        // Show MediaID or ASPRefID
        if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ImageID != undefined)
        {
            // Check and create an empty array for ImageID if it's not defined, so we can check for [0]
            if (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ImageID == undefined)
            {
                stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ImageID = [];
            }
            
            if (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ImageID[0] != undefined)
            {
                var ImageID = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ImageID[0];

                if ((ImageID.ID != undefined) && (ImageID.ID.Value != undefined))
                {
                    switch (ImageID.ID.Value)
                    {
                        case "MediaID": { stockphoto.core.ImageID.ID = stockphoto.core.ImageIDs.MediaID; break; }
                        case "ASPRefID": { stockphoto.core.ImageID.ID = stockphoto.core.ImageIDs.ASPRefID; break }
                        default: // leave the default value as it is...
                    }
                }

                if ((ImageID.ASPRefFilenamePrefix != undefined) && (ImageID.ASPRefFilenamePrefix.Value != undefined))
                {
                    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
                    {
                        stockphoto.core.ImageID.ASPRefFilenamePrefix = stockphoto.MiscUtils.file.convertToPOSIXCompliant(ImageID.ASPRefFilenamePrefix.Value, false, true);
                    }
                }
                
                if ((ImageID.ASPRefFilenameSuffix != undefined) && (ImageID.ASPRefFilenameSuffix.Value != undefined))
                {
                    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
                    {
                        stockphoto.core.ImageID.ASPRefFilenameSuffix = stockphoto.MiscUtils.file.convertToPOSIXCompliant(ImageID.ASPRefFilenameSuffix.Value, false, true);
                    }
                }
            }
        }
        
        ///AK:added by aman for Value Collection.
        //GP: compare with undefined.
        
        if( undefined != stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ValueCollections)
        {
            var ValueCollections = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ValueCollections[0];
            
            var bisLocale=false;
               
            var CurrentLocale = stockphoto.core.getValidLocale();
              
            // Billing Supported
            var bisBillingCountry = false;
           	
            if (("undefined" != typeof ValueCollections))
            {
                            
               //check if the locale is same as the locales for which we have to display value collection.
               // if current locale not set, then do not display value collection.
               //GP:use boolean convention in naming.D
                              
                if((undefined != ValueCollections.BillingCurrency) )
              	 {  			  			  
                      for(var indx = 0;indx < ValueCollections.BillingCurrency.length ; ++indx)
                      { 
                            var oBillingStrings = ValueCollections.BillingCurrency[indx];
        					if( (undefined != oBillingStrings.BillingCountry) && (undefined != oBillingStrings.BillingCountry.name)
                                && (undefined != oBillingStrings.BillingCountry.value) && (undefined != oBillingStrings.Locale) 
                                && (undefined != oBillingStrings.Locale.Value))
        					{
                            
                                var key = oBillingStrings.BillingCountry.name; // key corresponds to Billing Country
            					var value = oBillingStrings.BillingCountry.value; //value corresponds to currency value.
            					if(key == app.preferences.bm_billing_region) 
            					{
            						bisBillingCountry = true;
            						stockphoto.core.displayCurrency = value;
            						
            						var olocales= oBillingStrings.Locale.Value.split(",");
                					
                                    if("undefined" == typeof CurrentLocale )
                                    {
                                        bisLocale = false;
                                    } 
                                    else
                                    {	  
                              			for(var indx = 0;indx< olocales.length; ++indx)
                              			{
                                        	if(CurrentLocale == olocales[indx])
                                        	{
                                				bisLocale = true;
                              				}
                              			}	
                                    }                      
            						
            					}
            				}
                      }
                 }

              //GP: use constants on left..D
              stockphoto.core.displayValueCollectionFeatureflag = 
              ((undefined != ValueCollections.Enabled)&& (undefined != ValueCollections.Enabled.Value) 
              && ("yes" == ValueCollections.Enabled.Value ) && (true == bisBillingCountry ) && (true == bisLocale ));
                                                         
              //added to clear cache
              if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Preference ))
			  {   
			   	var bValueCollectionToDelete = stockphoto.prefs.SetValueCollectionFlag(stockphoto.core.displayValueCollectionFeatureflag);
        								
        		if(true == bValueCollectionToDelete)
        		{
          			var tempFolder = Folder(stockphoto.core.folder.BMTempFolderObj);
           					 	   
          			if(tempFolder.exists)
          			{
           				stockphoto.core.removeEmptyFolder(tempFolder);
          			}
 	            }
 	          }
            }
         	        	        
        }
        
        if( undefined != stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotoObjectCollections)
        {
            var PhotoObjectCollections = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].PhotoObjectCollections[0];
			
            if ((undefined != PhotoObjectCollections) && (undefined != PhotoObjectCollections.Enabled ) && (undefined != PhotoObjectCollections.Enabled.Value))
            {
               stockphoto.core.displayPhotoObjectCollectionFeatureflag = ("yes" == PhotoObjectCollections.Enabled.Value );
            }
         	        	        
        }
        
        //AK:end of added by aman for Value Collection and PhotoObjects.
                
        // Survey Settings
        if ( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].Survey != undefined)
        {
            // Check and create an empty array for Survey if it's not defined, so we can check for [0]
            if (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].Survey == undefined)
            {
                stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].Survey = [];
            }
            if (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].Survey[0] != undefined)
            {
                if (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].Survey[0].SurveyGPK == undefined)
                {
                    stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].Survey[0].SurveyGPK = [];
                }
                if (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].Survey[0].SurveyGPK[0] != undefined)
                {
                    var SurveyGPK = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].Survey[0].SurveyGPK[0];

					if (SurveyGPK.ShowSurvey != undefined)
					{
						if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Preference ))
						{
		                    if (SurveyGPK.ShowSurvey.Value == "yes")
		                    {
		                        stockphoto.core.survey.GPK.showSurvey = true;
		                    }
		                    stockphoto.prefs.setSurveySwitch(SurveyGPK.ShowSurvey.Value);
		                    
		                    // Override if submitted
		                    if (stockphoto.prefs.getSurveySubmitted() != 0)
		                    {
                                stockphoto.core.survey.GPK.showSurvey = false;
                            }
	                   }
	                }                 
                    // stockphoto.core.util.convertToInteger handles 'undefined' values automatically... 
                    if (SurveyGPK.MinCount != undefined)
                    {
                        stockphoto.core.survey.GPK.minCount = stockphoto.core.util.convertToInteger(SurveyGPK.MinCount.Value);
                    }
                    if (SurveyGPK.MaxCount != undefined)
                    {
                        stockphoto.core.survey.GPK.maxCount = stockphoto.core.util.convertToInteger(SurveyGPK.MaxCount.Value);
                    }
                    if (SurveyGPK.AllowSkipSurvey != undefined)
                    {
                        switch(SurveyGPK.AllowSkipSurvey.Value)
                        {
                            case "no" : stockphoto.core.survey.GPK.allowSkipSurvey = -1; break;
                            case "yes": stockphoto.core.survey.GPK.allowSkipSurvey = 0; break;
                            default: stockphoto.core.util.convertToInteger(SurveyGPK.AllowSkipSurvey.Value);
                        }
                    }                    
                }
            }
        }
	}
}

stockphoto.core.html.loadPhotographerDirUrl = function() 
{
	if( stockphoto.core.html.urlForPhotographerDir == undefined ) 
	{
			stockphoto.core.html.loadUrl();
		if( stockphoto.core.html.urlForPhotographerDir.length < 8 )
		{
			stockphoto.core.html.urlForPhotographerDir = stockphoto.core.html.urlForBMHome;
		}
		stockphoto.core.html.LengthOfUrlForPhotographerDir = stockphoto.core.html.urlForPhotographerDir.length;
	}
	return( stockphoto.core.html.urlForPhotographerDir );
}

stockphoto.core.BoxCar.NavBar.GetBrowseModeTableContext = function( doc_id )
{
	this.id                   = doc_id;
	this.close                = function() { this.id = undefined; };
	this.BrowseMode           = "";
	this.core                 = {};
	this.core.RecentPrevDir   = "";
	this.core.RecentFolder    = "";
	this.core.RecentSearDir   = "";
	this.core.IsCompact       = [0,0]; // 1:Standard 2:Compact
	this.Ext                  = {};
	this.Ext.InTheHPLoadError = false;
	this.Ext.InTheeCom        = false;
}

stockphoto.core.BoxCar.NavBar.GetBrowseModeTable=function( doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.NavIntDt_t[ doc_id ] == undefined )
	{
		stockphoto.core.BoxCar.NavBar.NavIntDt_t[ doc_id ] = new stockphoto.core.BoxCar.NavBar.GetBrowseModeTableContext( doc_id );
		if( stockphoto.core.BoxCar.NavBar.NavIntDt_t[ doc_id ] == undefined )
		{
			return( false );
		}
	}
	return( true );
}

stockphoto.core.BoxCar.NavBar.Prepare=function( doc_id )
{
	if( stockphoto.DL.isAlreadyLoaded( stockphoto.DL.jsx_NavBar ) )
	{
		stockphoto.NavExtFnc.PrepareNavBar( doc_id );
	}
	return( stockphoto.core.BoxCar.NavBar.GetBrowseModeTable( doc_id ) );
}

stockphoto.core.BoxCar.NavBar.GetPreviousBrowseMode=function( doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		return( stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].BrowseMode );
	}
	return( "" );
}

stockphoto.core.BoxCar.NavBar.SetPreviousBrowseMode=function( m, doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].BrowseMode = m;
	}
}

stockphoto.core.BoxCar.NavBar.GetPreviousSearchFolder=function( doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		return( stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].core.RecentPrevDir );
	}
	return( "" );
}

stockphoto.core.BoxCar.NavBar.SetPreviousSearchFolder=function( f, doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].core.RecentPrevDir = f;
	}
}

stockphoto.core.BoxCar.NavBar.GetRecentFolder=function( doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		return( stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].core.RecentFolder );
	}
	return( "" );
}

stockphoto.core.BoxCar.NavBar.SetRecentFolder=function( f, doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].core.RecentFolder = f;
	}
}

stockphoto.core.BoxCar.NavBar.GetRecentSearchFolder=function( doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		return( stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].core.RecentSearDir );
	}
	return( "" );
}

stockphoto.core.BoxCar.NavBar.SetRecentSearchFolder=function( f, doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].core.RecentSearDir = f;
	}
}

stockphoto.core.BoxCar.NavBar.GetIsCompactFlag=function( doc_id, k )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		return( stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].core.IsCompact[k] );
	}
	return( "" );
}

stockphoto.core.BoxCar.NavBar.SetIsCompactFlag=function( v, doc_id, k )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].core.IsCompact[k] = v;
	}
}

stockphoto.core.BoxCar.NavBar.GetInTheHPLoadError=function( doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		return( stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].Ext.InTheHPLoadError );
	}
	return( false );
}

stockphoto.core.BoxCar.NavBar.SetInTheHPLoadError=function( n, doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].Ext.InTheHPLoadError = n;
	}
}

stockphoto.core.BoxCar.NavBar.GetInECOMFlag=function( doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		return( stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].Ext.InTheeCom );
	}
	return( false );
}

stockphoto.core.BoxCar.NavBar.SetInECOMFlag=function( b, doc_id )
{
	if( stockphoto.core.BoxCar.NavBar.Prepare( doc_id ) )
	{
		stockphoto.core.BoxCar.NavBar.NavIntDt_t[doc_id].Ext.InTheeCom = b;
	}
}

stockphoto.core.BoxCar.HomePage={}
stockphoto.core.BoxCar.szInFailedHomePage="";
stockphoto.core.BoxCar.szOriginalHomePage="";
stockphoto.core.BoxCar.cntHomePage       =0;
stockphoto.core.BoxCar.HomePage.SubCheckIfCompactView=function( a, aName, bBMQuick )
{
	if( ( a.document != undefined )&&
	    ( a.document instanceof Document ) )
	{
		var doc=a.document;
		// workaround for Bridge 316 -BEGIN-
		var displayPath=undefined;
		if( doc.thumbnail != undefined )
		{
//			if( doc.thumbnail.displayPath == undefined )
//				 displayPath = doc.thumbnail.path;
//			else displayPath = doc.thumbnail.displayPath;
			displayPath = stockphoto.core.util.getDisplayPath( doc.thumbnail, "SubCheckIfCompactView()-1" );  	
		}
		if( displayPath == undefined )
		{
			if( a.object != undefined )
			{
				if( a.object.displayPath == undefined )
					 displayPath = a.object.path;
				else displayPath = a.object.displayPath;
				displayPath = stockphoto.core.util.getDisplayPath( a.object, "SubCheckIfCompactView()-2" );  	
			}
		}
		// workaround for Bridge 316 -END-
		// changed for "selectionsChanged"
		// "select" and "deselect" event are no longer used
		if( "selectionsChanged" == a.type )
		{
			if( stockphoto.DL.isAlreadyLoaded( stockphoto.DL.jsx_NavBar ) )
			{
			    // <BC3> This needs bScheduleTask == true, to enable document.selections update
				stockphoto.NavExtFnc.SendRequestToHTM( doc.id, true );
			}
		}
		if( a.type != "deselect" )
		{
			if( ( doc.contentPaneMode == "web" )&&
			    ( doc.thumbnail != undefined )&&
			    ( displayPath != undefined ) ) 
			{
				var url  = new File( displayPath );
				if( url.name == "startpage.html" ) 
				{
					var Nm2  = ( File( url.path ) ).name;
					if( Nm2 == "Bridge%20Center" ) 
					{
						// - Bridge Center -
						stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, false, "HomePage.SubCheckIfCompactView #0" );
					}
				}
				delete url;
			}
			if( ( doc.topNavbar != undefined )&&
			    ( doc.browserMode != undefined )&&
			    ( stockphoto.core.BoxCar.NavBar.GetPreviousBrowseMode( doc.id ) != doc.browserMode ) ) 
			{
				if( doc.browserMode == "compact" ) 
				{
					stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, false, "HomePage.SubCheckIfCompactView #1" );
 				} 
				else 
				{ // full mode
					var args={};
					if( doc.thumbnail != undefined ) 
					{
						args = stockphoto.eventHandler.pathAnalyzer.AnalyzingPath( displayPath, bBMQuick, false, doc );
						if( ( doc.topNavbar.file == undefined )||
						    ( doc.topNavbar.file == "" ) ) 
						{
							args.doc = doc;
							if( ( args.k >= 0 )&&( args.k <= 14 )&&
							    ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) ) 
							{
								stockphoto.NavExtFnc.PrepareNavBar( doc.id );
								if( args.k <= 9 )
								{
									// - Browsing recent earch folder
									if( args.k == 0 )
										stockphoto.NavIntFnc.SetKeyWord( stockphoto.NavIntDt.TheEnter, false /*=unescaped*/, doc.id, true );
									stockphoto.core.NavBar.SwitchNavBar( "ST03_BB", 0, /* std */ 1 /* 0:w 1:f */, doc, args.kKeyWd );
								} 
								else 
								{
									if( args.k == 10 ) 
									{
										// search folder
										stockphoto.NavIntFnc.SetKeyWord( stockphoto.NavIntDt.TheEnter, false /*=unescaped*/, doc.id, true );
										stockphoto.core.NavBar.SwitchNavBar( "SEARCHE", 0, /* std */ 1 /* 0:w 1:f */, doc );
									} 
									else 
									{
										if( args.k == 11 ) 
										{
											stockphoto.NavIntFnc.SetKeyWord( stockphoto.NavIntDt.TheEnter, false /*=unescaped*/, doc.id, true );
											stockphoto.core.NavBar.SwitchNavBar( "COMPSCO", 0, /* std */ 1 /* 0:w 1:f */, doc );
										} 
										else 
										{
											if( ( args.k == 12 )||( args.k == 13 ) ) 
											{
												stockphoto.core.NavBar.SwitchNavBar( "PURCHAS", 0, /* std */ 1 /* 0:w 1:f */, doc );
											} 
											else 
											{	
												if( args.k == 14 ) 
												{
													//stockphoto.NavIntFnc.SetKeyWord( stockphoto.NavIntDt.TheEnter, false /*=unescaped*/, doc.id, true );
													stockphoto.core.NavBar.SwitchNavBar( "DISPLAYSTARTPAGE", 0, /* std */ 1 /* 0:w 1:f */, doc );
												}
												//else doc.topNavbar.visible = false;
												else 
												{
													stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, false, "HomePage.SubCheckIfCompactView #2" );
												}
											}
										}
									}
								}
							}
						} 
						else 
						{
							if( args.k < 15 )
							{
							     stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, true, "HomePage.SubCheckIfCompactView #3" );
							}
							else 
							{
								stockphoto.eventHandler.pathAnalyzer.ChangeNavVisiblity( doc, false, "HomePage.SubCheckIfCompactView #4" );
							}
						}
					}
				}
				stockphoto.core.BoxCar.NavBar.SetPreviousBrowseMode( doc.browserMode, doc.id );
				return( true );
			}
		} // not "deselect
	}
	return( false );
}
stockphoto.core.BoxCar.HomePage.CheckIfCompactView=function( event, bBMQuick ) 
{
	if( ! stockphoto.core.BoxCar.HomePage.SubCheckIfCompactView( event, "event", bBMQuick ) )
	{
		stockphoto.core.BoxCar.HomePage.SubCheckIfCompactView( app, "app", bBMQuick );
	}
}

stockphoto.core.BoxCar.HomePage.APSPhotoDir           = { root:undefined, installedFavorite:false };
stockphoto.core.BoxCar.HomePage.APSPhotoDir_iconLabel = "Adobe Photographers Directory";

stockphoto.core.BoxCar.HomePage.endPhotoDir=function()
{
	var f, k
	f         = app.favorites;
	f.section = "standard";
	for( k=0; k<f.length; k++ )
	{
		if ( f[ k ].name == stockphoto.core.BoxCar.HomePage.APSPhotoDir_iconLabel )
		{
			f.remove( f[ k ] );
			if( stockphoto.core.BoxCar.HomePage.APSPhotoDir.root != undefined )
				delete stockphoto.core.BoxCar.HomePage.APSPhotoDir.root;
			stockphoto.core.BoxCar.HomePage.APSPhotoDir.root              = undefined;
			stockphoto.core.BoxCar.HomePage.APSPhotoDir.installedFavorite = false;
			break; // one photographers directory
		}
	}
}

stockphoto.core.BoxCar.HomePage.getUrlLanguage4PhotoDir=function()
{
	var bOk=false;
	if( ( app.preferences.Language != undefined )&&( app.preferences.Language != "" ) )
	{
		if( app.preferences.Language.length == 2 )
		{
			bOk = true;
		}
		else if( ( app.preferences.Language.length > 2 )&&
				 ( ( app.preferences.Language.charAt(2) == '-' )||
				   ( app.preferences.Language.charAt(2) == '_' ) ) )
		{
			bOk = true;
		}
	}
	if( ! bOk )
	{
		locle = stockphoto.core.getValidLocale(true);
	} 
	else
	{
		locle = app.preferences.Language;
	}
//	stockphoto.core.html.urlUILanguage = ( locle.substr( 0,2 ) ).toLowerCase();
	return(  ( locle.substr( 0,2 ) ).toLowerCase() );
}

stockphoto.core.BoxCar.HomePage.startPhotoDir=function()
{
//	stockphoto.core.html.setUrlFilter( app.document );
//	app.eventHandlers.push( { handler: stockphoto.core.BoxCar.HomePage.APSPhotoDir.eventHandler } );
	stockphoto.core.html.urlUILanguage = stockphoto.core.BoxCar.HomePage.getUrlLanguage4PhotoDir();
	if( ( stockphoto.core.html.urlUILanguage == "ja" )||
		( stockphoto.core.html.urlUILanguage == "zh" )||
		( stockphoto.core.html.urlUILanguage == "ko" ) )
		stockphoto.core.BoxCar.HomePage.APSPhotoDir_iconLabel = "Photographers Directory";
	stockphoto.core.BoxCar.HomePage.APSPhotoDir.root             = new Thumbnail( "APSPhotoDir://root" );
	stockphoto.core.BoxCar.HomePage.APSPhotoDir.root.iconPath    = stockphoto.core.makeIconPath( "PhotographersDirectory" );
	stockphoto.core.BoxCar.HomePage.APSPhotoDir.root.name        = stockphoto.core.BoxCar.HomePage.APSPhotoDir_iconLabel;
	stockphoto.core.BoxCar.HomePage.APSPhotoDir.root.displayMode = "web";
	stockphoto.core.BoxCar.HomePage.APSPhotoDir.root.displayPath = stockphoto.core.html.loadPhotographerDirUrl();
	stockphoto.core.doInsertPhotoDirName       					 = stockphoto.core.BoxCar.HomePage.APSPhotoDir.root.name;
}

if (stockphoto.core.init.partnersXMLfsObj != undefined)
{
	stockphoto.core.BoxCar.HomePage.startPhotoDir();

	if( ( stockphoto.timeKeeperOn != undefined )&&( stockphoto.timeKeeperOn ) )
	{
		stockphoto.core.util.JsxTab=[
			/* 00 */ { n:"st00core", p:0 },
			/* 01 */ { n:"st01AddToCart", p:0 },
			/* 02 */ { n:"st02CheckOut", p:0 },
			/* 03 */ { n:"st03BasicSearch", p:0 },
			/* 04 */ { n:"st04AdvanceSearch", p:0 },
			/* 05 */ { n:"st05LocalURL", p:0 },
			/* 06 */ { n:"st06HomePage", p:0 },
			/* 07 */ { n:"st07eCom", p:0 },
			/* 08 */ { n:"st08TerminateStock", p:0 },
			/* 09 */ { n:"st09GetComp", p:0 },
			/* 10 */ { n:"st10Preferences", p:0 },
			/* 11 */ { n:"st11NavBar", p:0 },
			/* 12 */ { n:"st12SaveSearch", p:0 },
			/* 13 */ { n:"st13RedoSearch", p:0 },
			/* 14 */ { n:"st14ShoppingCart", p:0 },
			/* 15 */ { n:"st15DownloadStock", p:0 },
			/* 16 */ { n:"st16AlertBox", p:0 },
			/* 17 */ { n:"st17ImgDetail", p:0 },
			/* 18 */ { n:"st18HTMLUtil", p:0 },
			/* 19 */ { n:"st19LangCountry", p:0 },
			/* 20 */ { n:"st20MiscDlgs", p:0 },
			/* 21 */ { n:"st21MiscUtils", p:0 },
			/* 22 */ { n:"browseScheme", p:0 },
			/* 23 */ { n:"eventHandler", p:0 },
			/* 24 */ { n:"StartUpJsx", p:0 } ];

		stockphoto.core.util.stTime=function( k )
		{
			eval( "stockphoto.timeKeeper."+(stockphoto.core.util.JsxTab[ k ].n)+" = {};" );
			eval( "stockphoto.timeKeeper."+(stockphoto.core.util.JsxTab[ k ].n)+".StTime = new Date();" );
		} // function stockphoto.core.util.stTime()

		stockphoto.core.util.edTime=function( k )
		{
			eval( "stockphoto.timeKeeper."+(stockphoto.core.util.JsxTab[ k ].n)+".EdTime = new Date();" );
			stockphoto.core.util.JsxTab[ k ].p = 1;
			if( k == 0 ) 
			{
				stockphoto.core.util.JsxTab[21].p = 1;
				stockphoto.core.util.JsxTab[22].p = 1;
				stockphoto.core.util.JsxTab[23].p = 1;
			}
			if( ( k < 21 )||( k == 23 ) )
			{ // k=0,1,..,20
				for( var i=0; i<=23; i++ )
				{
					if( stockphoto.core.util.JsxTab[i].p == 1 )
					{
						var sNm, ss, sst, sed, sGo=false;
						sNm = stockphoto.core.util.JsxTab[i].n;
						sst = "stockphoto.timeKeeper."+(sNm)+".StTime";
						sed = "stockphoto.timeKeeper."+(sNm)+".EdTime";
						eval( "if ( ( "+sst+" != undefined )&&( "+sed+" != undefined ) ) sGo = true;" );
						if( sGo ) 
						{
							ss = "s ='"+sNm+" '+"+sst+".getHours()+':'"+
								"+"+sst+".getMinutes()+':'"+
								"+"+sst+".getSeconds()+' -> '"+
								"+"+sed+".getMinutes()+':'"+
								"+"+sed+".getSeconds();";
							eval( ss );
							stockphoto.core.log.logString( 0, "\n***** "+s+" *****\n" );
							stockphoto.core.util.JsxTab[i].p = 2;
						}
					}
				} // for
			}
		} 

		stockphoto.core.util.edTime( 0 );
	}
	
	stockphoto.core.util.startTimer = function( timerName )
	{ if( stockphoto.timeKeeperNewOn ) { stockphoto.timeKeeper[timerName] = new Date(); } }
    
    stockphoto.core.util.writeTimer = function ( timerName )
    { if( stockphoto.timeKeeperNewOn ) {
            if (undefined != stockphoto.timeKeeper[timerName])
            {  var diffTime = (new Date()) - stockphoto.timeKeeper[timerName];
                stockphoto.core.log.logString( 3, "PERF TIMER: " + timerName + " : " + diffTime);  }  } 
    }
    
    stockphoto.core.util.pauseORresumeTimer = function( timerName )
    { if( stockphoto.timeKeeperNewOn ) {
            if (undefined != stockphoto.timeKeeper[timerName])
            {  stockphoto.timeKeeper[timerName] = (new Date()) - stockphoto.timeKeeper[timerName];  }
            else { stockphoto.timeKeeper[timerName] = new Date(); } }
    }
    
}

stockphoto.DL.NavBar.ToggleAdvanceDrawer=function( doc_id, sShowHide ) 
{
	if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		stockphoto.NavExtFnc.ToggleAdvanceDrawer( doc_id, sShowHide );
	}
	
}


// <TODO> Move the logic to NavBar jsx
stockphoto.DL.NavBar.IsDrawerShown = function( doc_id )
{
  if (stockphoto.search.showAdvancedDrawer[doc_id] == undefined)
  {
    if (stockphoto.core.lastActiveDocumentID != 0)
    {
      stockphoto.search.showAdvancedDrawer[doc_id] = stockphoto.search.showAdvancedDrawer[stockphoto.core.lastActiveDocumentID];
    }
    else
    {
      stockphoto.search.showAdvancedDrawer[doc_id] = stockphoto.search.showAdvancedDrawer[stockphoto.core.lastActiveDocumentID];
    }
  }

  return stockphoto.search.showAdvancedDrawer[doc_id];
}

stockphoto.DL.NavBar.GetDrawerSettings = function( doc_id )
{
  var oResult = { };
  
  if( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		oResult = stockphoto.NavExtFnc.GetDrawerSettings( doc_id );
	}
	
	return oResult;
} 

// <TODO:manish> Move logic to NavBar jsx
stockphoto.DL.NavBar.getValuesFromES = function( doc_id )
{
  var oESValues = { };
  
  oESValues.showAdvancedDrawer = stockphoto.DL.NavBar.IsDrawerShown(doc_id);
  oESValues.settings = stockphoto.DL.NavBar.GetDrawerSettings(doc_id);
  
  return oESValues;
}

stockphoto.DL.NavBar.ParseAdvSettingsFromXmlObj = function ( oXmlParsedObj, oInitSettings )
{
  var oResult = { };
  
  if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		oResult = stockphoto.NavExtFnc.ParseAdvSettingsFromXmlObj( oXmlParsedObj, oInitSettings );
	}
  
  return oResult;
}

stockphoto.DL.NavBar.ParseAdvCollectionsFromFSObj = function ( oFSObj, settings )
{
    var oResult = { };
  
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		oResult = stockphoto.NavExtFnc.ParseAdvCollectionsFromFSObj( oFSObj, settings );
	}
	
    return oResult;
}

// Returns: Integer: stockphoto.NavIntDt._kNavHeight_short / stockphoto.NavIntDt._kNavHeight_high
stockphoto.DL.NavBar.GetNavHeightType = function ( doc_id )
{
    var iResult; // There's no default. Undefined.
    
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
	{
		iResult = stockphoto.NavExtFnc.GetNavHeightType( doc_id );
	}
	
    return iResult;
}


stockphoto.DL.NavBar.setIsDefault = function ( docID, oSettings )
{
    var oResult;
  
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
    {
        oResult = stockphoto.NavExtFnc.setIsDefault ( docID, oSettings );
    }
  
    return oResult;
}

stockphoto.DL.NavBar.addFiltersToTerms = function( settings, terms )
{
    var oResult;    
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
    {
        oResult = stockphoto.MiscUtils.search.addFiltersToTerms( settings, terms );
    }
    return oResult;
}

stockphoto.core.getASPSearchLangLocale = function()
{
    // Fetch ASP's search language (SL)
    var sSL = stockphoto.DL.GetLanguage();
    if ((sSL == undefined) || (sSL.length < 2))
    {
        // Use Bridge's locale
        return stockphoto.core.getValidLocale();
    }
    
    // Try to find SL in locale table
    var sLangLocale = stockphoto.core.localesTable[sSL];
    
    // Try to find SL.substr(0,2) in locale table (this will do the deed for English (UK), etc.)
    if (sLangLocale == undefined)
    {
        if (sSL.length > 2)
        {
            sSL = sSL.substr(0,2);
            sLangLocale = stockphoto.core.localesTable[sSL];
        }
        
        // Last resort - Use Bridge's locale
        if (sLangLocale == undefined)
        {
            sLangLocale = stockphoto.core.getValidLocale();
        }
    }
    
    return sLangLocale;
}

stockphoto.DL.NavBar.changeMediaTypeFocus = function(doc_id)
{
    var oResult;
    
    if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_NavBar ) ) 
    {
        oResult = stockphoto.NavExtFnc.changeMediaTypeFocus(doc_id);
    }
    
    return oResult;
}

// Get ASP Reference encoding for any given string
stockphoto.core.encodeASPReference = function(sSource)
{
    var sResult; // default return value is 'undefined'
    if ((stockphoto.impl != undefined) && (sSource != undefined))
    {
        sResult = stockphoto.impl.encodeASPReference({ source: sSource });
    }
    return sResult;
}

// Get ASP Ref from Filename Code, MediaID.
// Note: PurchaseID is optional and can be undefined or blank.
stockphoto.core.getASPRefFromFM = function(sFilenameCode, sMediaID)
{
    var sResult; // default return value is 'undefined'
    if ((stockphoto.impl != undefined) && (sFilenameCode != undefined) && (sMediaID != undefined))
    {
        sResult = stockphoto.impl.getASPRefFromFM({ filenameCode: sFilenameCode, mediaID: sMediaID });
    }
    return sResult;
}

// Get ASP Filename Prefix & Suffix added to a given ASP Reference
stockphoto.core.ASPRefToFilename = function(sSource)
{
    var sResult; // default return value is 'undefined'
    if ((stockphoto.impl != undefined) && (sSource != undefined))
    {
        sResult = stockphoto.impl.aspRefToFilename({ source: sSource });
    }    
    return sResult;
}

stockphoto.core.getASPRefFromPartner = function(sPartnerName, sMediaID)
{
	return stockphoto.core.getASPRefFromFM(stockphoto.partnerNameToFilenameCode(sPartnerName),sMediaID);
}

stockphoto.core.getKeepCompFilename = function(sThumbFilename, sThumbExt, oThumbFileObj)
{
    if ((sThumbFilename != undefined) && (oThumbFileObj != undefined) && (typeof oThumbFileObj == "Thumbnail")) //// && (stockphoto.core.ImageID.ID == stockphoto.core.ImageIDs.ASPRefID)
    {
        	oMeta = oThumbFileObj.metadata; // We don't need synchronous Metadata here
        	if (oMeta != undefined)
			{	
				oMeta.namespace = "http://ns.adobe.com/StockPhoto/1.0/";
				var sPartnerName = oMeta["Media/bmsp:PartnerName"];
				var sMediaID = oMeta.MediaID;
				if (sMediaID != undefined && sPartnerName != undefined)
				{
                  return stockphoto.core.ASPRefToFilename(stockphoto.core.getASPRefFromPartner(sPartnerName,sMediaID)) + "." + sThumbExt;
             	}
        	}
    }
    
    return sThumbFilename;
}

stockphoto.core.getPartnerNameFromPartnerDisplayName = function(sPartnerDisplayName)
{ 	
	return stockphoto.core.partnerDispNameToPartnerNameMap[sPartnerDisplayName];
}

stockphoto.core.getEscapedPath = function (sPath)
{
	if (sPath != undefined)
	{
		sPath.replace(/\\/g,'\\\\');
	}
	return sPath;
}

stockphoto.core.createPartnerDisplayNameToPartnerNameMap = function()
{
	var iPartnersCount=0;
	var iIndex;
	
	if( stockphoto.core.BoxCar.AnalyzeXmlFileObj == undefined )
	{
		stockphoto.core.BoxCar.AnalyzeXmlFileObj = new stockphoto.core.BoxCar.AnalyzeXmlFile( stockphoto.core.init.partnersXMLfsObj, stockphoto.core.BoxCar.HTMLUtil.CheckKeys );
		if( ( stockphoto.core.BoxCar.AnalyzeXmlFileObj == undefined )||
		    ( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners == undefined ) )
		{
			// we failed to load partner's xml
			return false;
		}
	}
	if ((stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners != undefined) 
		&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0] != undefined) 
		&& (stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner != undefined))
	{
		iPartnersCount = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].Partner.length;
	}
	var oPartnerElement = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0];
	for (iIndex=0; iIndex < iPartnersCount; iIndex++)
	{
		if ((oPartnerElement.Partner[iIndex].PartnerDisplayName != undefined) && (oPartnerElement.Partner[iIndex].PartnerDisplayName.Value !=undefined)
			&& (oPartnerElement.Partner[iIndex].PartnerName != undefined) && (oPartnerElement.Partner[iIndex].PartnerName.Value !=undefined))
		{
			stockphoto.core.partnerDispNameToPartnerNameMap[oPartnerElement.Partner[iIndex].PartnerDisplayName.Value] = oPartnerElement.Partner[iIndex].PartnerName.Value
		}
	}
	
	return true;
}

stockphoto.core.getAdobeIDFileNameFromPath = function(sSourcePath)
{
	var sAdobeIDFileName = "";
	
	var fSourceFile = new File(sSourcePath);
	
	if("undefined" != typeof fSourceFile)
	{
		var tn = new Thumbnail(fSourceFile);
		if("undefined" != typeof tn)
		{
			var md = tn.metadata; // We don't need synchronous Metadata here
			if("undefined" != typeof md)
			{
				md.namespace = "http://ns.adobe.com/StockPhoto/1.0/";
				var sASPRefID = "";
				if("undefined" != typeof md.Media)
				{
					if( ("undefined" != typeof md.Media["bmsp:Media/bmsp:PartnerName"]) && ("undefined" != typeof md.MediaID) )
					{
						sASPRefID = stockphoto.core.getASPRefFromPartner(md.Media["bmsp:Media/bmsp:PartnerName"], md.MediaID);
						if("" != sASPRefID)
						{
							 sAdobeIDFileName = stockphoto.core.ASPRefToFilename(sASPRefID);
						}
					}
				}	
			}
		}
	}
	
	return sAdobeIDFileName;
}

// iNamingOption = 0 - Do Not Rename 1- Rename
// bSaveToDefault = true - save file to default folder as well, false - don't
// sImageType = "comp"/"Hi-Rez"
// sCustomName will be allready trimmed (plus not empty in case of option 2)
// Move the file from one source to destination
stockphoto.core.fileHandle = function(sSourceFolder, sDestFolder)
{
	this.sDestFolder = sDestFolder;
	this.sSourceFolder = sSourceFolder;
	this.aDefaultFolderFileList = "";
	this.bSaveToUserFolder = false;
	this.bSaveToDefaultFolder = false;
	this.MAX_PATH = 256;

	// return true in case of success and false in case of failour
	// iSaveFolder = stockphoto.core.SaveComp.NONE = 0;
	//	stockphoto.core.SaveComp.USER_DEFINED_FOLDER = 1;
	//	stockphoto.core.SaveComp.DEFAULT_FOLDER = 2;
	//	stockphoto.core.SaveComp.BOTH_LOCATIONS = 3;

	this.saveFile = function( sAdobeIDFileName, sCustomName, iNamingOption, bSaveToDefault, sImageType, reqIndex)
	{

		var iSaveFolder = stockphoto.core.SaveComp.BOTH_LOCATIONS;
		if(stockphoto.core.SaveComp.BOTH_LOCATIONS == stockphoto.core.SaveComp.iDonotSaveTo)
		{
			iSaveFolder = stockphoto.core.SaveComp.NONE;
		}
		else if(stockphoto.core.SaveComp.DEFAULT_FOLDER == stockphoto.core.SaveComp.iDonotSaveTo)
		{
			iSaveFolder = stockphoto.core.SaveComp.USER_DEFINED_FOLDER;
		}
		else if(stockphoto.core.SaveComp.USER_DEFINED_FOLDER == stockphoto.core.SaveComp.iDonotSaveTo)
		{
			iSaveFolder = stockphoto.core.SaveComp.DEFAULT_FOLDER;
		}
	
		this.bSaveToUserFolder = (stockphoto.core.SaveComp.USER_DEFINED_FOLDER == iSaveFolder) || (stockphoto.core.SaveComp.BOTH_LOCATIONS == iSaveFolder); 
		this.bSaveToDefaultFolder = (stockphoto.core.SaveComp.DEFAULT_FOLDER == iSaveFolder) || (stockphoto.core.SaveComp.BOTH_LOCATIONS == iSaveFolder); 

		if( !(this.bSaveToUserFolder || this.bSaveToDefaultFolder) )	// dont save to any folder.
		{
			return true;
		}
		
		var sFileExtention = sAdobeIDFileName.substring(sAdobeIDFileName.lastIndexOf(".") +1);
		var sAdobeIDFileNameWithoutExt = "";
		if("comp" == sImageType)
		{
			sAdobeIDFileNameWithoutExt = stockphoto.core.getAdobeIDFileNameFromPath(sSourceFolder);
		}

		if( ("" == sAdobeIDFileNameWithoutExt) || ("comp" != sImageType) )
		{
			sAdobeIDFileNameWithoutExt =  sAdobeIDFileName.substring(0,sAdobeIDFileName.lastIndexOf("."));
		}
		
		var fInFile = new File(this.sSourceFolder );
		
		if( ("undefined" == typeof this.sSourceFolder) || ("" == sAdobeIDFileNameWithoutExt) || (!fInFile.exists) )
		{  
			stockphoto.alertBox.alertBox(stockphoto.alertBox.coreComponentID + 34); 
			return false;
		}
		
		// File level error - If network connection breaks in the middle.
		if(  this.bSaveToUserFolder	&& ( "undefined" == typeof this.sDestFolder || ! (new Folder(sDestFolder)).exists ) )
		{
			stockphoto.alertBox.alertBox(stockphoto.alertBox.coreComponentID + 32);
			return false;
		}
		var sOutFileName = sCustomName;
		var iFileNameCounter = 1;
		var count;
		
		if ( ("undefined" != typeof reqIndex) && (reqIndex >= 0) && ("undefined" != typeof stockphoto.getComp.requests) 
		     && ("undefined" != typeof stockphoto.getComp.requests[ reqIndex ]) 
		     && ("undefined" != typeof stockphoto.getComp.requests[ reqIndex ].count) )
		{
		   count = stockphoto.getComp.requests[reqIndex].count;		        
		}
		else
		{
		   count = stockphoto.core.SaveComp.numOfImagesSelected;
		}
		
		if(iNamingOption == 0)
		{
			sOutFileName = sAdobeIDFileNameWithoutExt;
		}
		else if( (1 == iNamingOption) && ( "undefined" != typeof stockphoto.core.SaveComp) && (count > 1) ) // and not single file
		{
			if( ("undefined" == typeof sCustomName) || ("" == sCustomName) ) // Move this Check to C++
			{
				stockphoto.alertBox.alertBox(stockphoto.alertBox.coreComponentID + 33);
				return false;
			}
			sOutFileName = sCustomName + "001";
			iFileNameCounter++; 
		}
		var sOutFilePath = this.sDestFolder;
		sOutFilePath += (stockphoto.isMac) ? ("/") : ("\\"); 
		sOutFilePath += sOutFileName;
		
		return this.copyFileToFolder(fInFile, sOutFileName, sFileExtention, iNamingOption, iFileNameCounter, bSaveToDefault, sImageType, reqIndex);

	}
	
	this.copyFileToFolder = function(fInFile, sOutFileName, sFileExtention, iNamingOption, iFileNameCounter, bSaveToDefault, sImageType, reqIndex)
	{
		var sOutFilePathDefault = "";
		var sOutFilePathCustom = this.sDestFolder;

		if(this.bSaveToUserFolder)		
		{
			sOutFilePathCustom += (stockphoto.isMac) ? ("/") : ("\\"); 
		}
		
		var sDefaultDestFolder = (sImageType == "comp")? (stockphoto.core.folder.getMyCompFolder()): (stockphoto.core.folder.getMyPurchasesFolder());

		if( ("undefined" != typeof sDefaultDestFolder) && (this.bSaveToDefaultFolder) )
		{
			if(bSaveToDefault == true)
			{
				if( ("undefined" != typeof sDefaultDestFolder) && (sDefaultDestFolder != this.sDestFolder) )
				{
					sOutFilePathDefault = sDefaultDestFolder;
					sOutFilePathDefault += (stockphoto.isMac) ? ("/") : ("\\"); 
				}
			}
		}
		
		var bFileExist = true;
		var fOutFileCustom;
		var fOutFileDefault;	
		var sFileNameWithExt = ""; 
		
		var initial_filename = sOutFileName; 
        
		while(bFileExist)
		{
			sFileNameWithExt = sOutFileName + "." + sFileExtention;
			var bFileExistInNone = true;
			
			if(this.bSaveToUserFolder)
			{
				bFileExistInNone = !((new File(sOutFilePathCustom + sFileNameWithExt)).exists);
			}
			
			if( this.bSaveToDefaultFolder && (true == bSaveToDefault) && (sDefaultDestFolder != this.sDestFolder) )
			{
				bFileExistInNone = bFileExistInNone && !((new File(sOutFilePathDefault + sFileNameWithExt)).exists);
			}
			
			if(bFileExistInNone)
			{
				if(this.bSaveToUserFolder)
				{
					fOutFileCustom = new File(sOutFilePathCustom + sFileNameWithExt);
				}
				if(this.bSaveToDefaultFolder && bSaveToDefault)
				{
					fOutFileDefault = new File(sOutFilePathDefault + sFileNameWithExt);
				}
				// Check the existence only if trying to save in the folder.
				if( (!this.bSaveToUserFolder || !fOutFileCustom.exists) && (!(this.bSaveToDefaultFolder && bSaveToDefault) || !fOutFileDefault.exists) )	
				{
					bFileExist = false;
					continue;
				}
			}
			// If it is first time of either donot rename or Rename but single file
            var count;

			if ( ("undefined" != typeof reqIndex) && (reqIndex >= 0) && ("undefined" != typeof stockphoto.getComp.requests) 
				 && ("undefined" != typeof stockphoto.getComp.requests[ reqIndex ]) 
				 && ("undefined" != typeof stockphoto.getComp.requests[ reqIndex ].count))
			{
			   count = stockphoto.getComp.requests[reqIndex].count;		        
			}
			else
			{
			   count = stockphoto.core.SaveComp.numOfImagesSelected;
			}
			
			count = (count <= 0 ) ? 1:count;
            			
			if( ( 0 == iNamingOption || (( "undefined" != typeof stockphoto.core.SaveComp) && (1 == count ) )) && (1 == iFileNameCounter) ) // Append Only the First time
			{
			    sOutFileName += "001";
			    initial_filename = sOutFileName;
			}
			else
			{ 
				// subtract the character equal to lenght of counter from end and then add the cout.
				var tempOutFileName = sOutFileName.substring(0, sOutFileName.length - 3);
				
				//AMAN
				if(iFileNameCounter < 1000)
				{
				
    				if(iFileNameCounter < 10)
    				{
    					tempOutFileName += "00";
    				}
    				else if(iFileNameCounter < 100)
    				{
    					tempOutFileName += "0";
    				}
			    }
			    else
			    {
			        tempOutFileName = initial_filename.substring(0, initial_filename.length - 3);
                }
                
                	
				tempOutFileName += iFileNameCounter;
				
				sOutFileName = tempOutFileName;
			}
			
			iFileNameCounter++;
		}

		if(this.bSaveToUserFolder)
		{
			if(("Windows"==File.fs)? (File(fOutFileCustom).fsName.length > this.MAX_PATH) : false)
			{
				this.displayDialog(1, File(fOutFileCustom).fsName, undefined);
				return false;
			}
			if(!fInFile.copy(fOutFileCustom)) // Not Able to save file..
			{
				stockphoto.alertBox.alertBox(stockphoto.alertBox.coreComponentID + 34);		// Unable to save file %1 in %2
				return false;
			}
			if("comp" == sImageType && "undefined" != typeof stockphoto.core.SaveComp.aImagesSavedComp)
			{
				stockphoto.core.SaveComp.aImagesSavedComp[stockphoto.core.SaveComp.aImagesSavedComp.length] = (0 == iNamingOption) ? unescape(sFileNameWithExt) : sFileNameWithExt; // KR unescaping twice does not have any impact.
				if ( ("undefined" != typeof reqIndex) && (reqIndex >= 0) && ("undefined" != typeof stockphoto.getComp.requests) 
				     && ("undefined" != typeof stockphoto.getComp.requests[ reqIndex ]) 
				     && ("undefined" != typeof stockphoto.getComp.requests[ reqIndex ].SavedFileNames) 
				     && ("undefined" != typeof stockphoto.getComp.requests[ reqIndex ].SavedFileCounter) )
				{
					stockphoto.getComp.requests[ reqIndex ].SavedFileNames[ stockphoto.getComp.requests[ reqIndex ].SavedFileCounter ] = (0 == iNamingOption) ? unescape(sFileNameWithExt) : sFileNameWithExt;
					stockphoto.getComp.requests[ reqIndex ].SavedFileCounter++;								
				}
			}
			else if("Hi-Rez" == sImageType && "undefined" != typeof stockphoto.core.SaveComp.aImagesSavedHiRez)
			{
				stockphoto.core.SaveComp.aImagesSavedHiRez[stockphoto.core.SaveComp.aImagesSavedHiRez.length] = (0 == iNamingOption) ? unescape(sFileNameWithExt) : sFileNameWithExt; // KR unescaping twice does not have any impact.
			}
		}
		// Don't shout if unable to save to default folder
		
		if( (true == bSaveToDefault) && (sDefaultDestFolder != this.sDestFolder) )
		{
			if(("Windows"==File.fs) ? (File(fOutFileDefault).fsName.length > this.MAX_PATH) : false)
			{
				this.displayDialog(1, File(fOutFileDefault).fsName, undefined);
				return true;
			}
			this.bSaveToDefaultFolder = this.bSaveToDefaultFolder && !fInFile.copy(fOutFileDefault)
			if(this.bSaveToDefaultFolder)
			{
				stockphoto.alertBox.alertBox(stockphoto.alertBox.coreComponentID + 34);		// Unable to save file %1 in Default Folder
				return true;	// Because confirmation dialog is not for default folder.
			}
		}
		return true;
	}
	
	// iErrorType =1 Above filename is invalid dialog.
	this.displayDialog = function(iErrorType, arg1, arg2)
	{
		var sMsg = "";
		if(1 == iErrorType)
		{
			sMsg = stockphoto.core.SaveComp.INVALID_FILE_NAME_ERR;
		}
		if("undefined" != typeof arg1 && "undefined" != typeof arg2)
		{
			sMsg = zc.get2Arg(sMsg, arg1, arg2);
		}
		else if("undefined" != typeof arg1 )
		{
			if(arg1.length > 60)
				arg1 = arg1.substr(0,10) + "..." + arg1.substr((arg1.length-45));
			sMsg = zc.get1Arg(sMsg, "\""+arg1+"\"");				
		}
		if("" != sMsg)
		{
			this.showOkDialog(sMsg);
		}
	}
	
	this.showOkDialog = function(sMsg)
	{
		var dlgSaveAs = new Window('dialog', zc.get("$$$/AlertBox/Dialog/Title=Adobe Stock Photos"), undefined, { resizable: true, orientation: "row" } );
		dlgSaveAs.add('statictext', { x: 100, y: 100, width: 450, height: 43}, sMsg, {multiline:true} );
		dlgSaveAs.okButton = dlgSaveAs.add( 'button', undefined, zc.get("$$$/ConfirmationBox/Dialog/Btn/OK/Text=OK"));
	
		dlgSaveAs.okButton.onClick = function()
       	{
       		this.parent.close();
       	}
       			
		dlgSaveAs.center();
		dlgSaveAs.show();
	}
}

stockphoto.core.getFolderNameFromPath = function(folderPath)
{
	var chSeparater = ("Windows" == File.fs)?"\\":"/";
	var folderName = undefined;
	if( ("undefined" != typeof folderPath ) || (-1 != folderPath.indexOf(chSeparater) )	)
	{
		folderName = folderPath.substring(folderPath.lastIndexOf(chSeparater)+1);
//		alert("folderName : " + folderName);
	}
	return folderName;
}

//AK:added by aman for changing pricing dynamically when billing country changes based on partners.xml 
stockphoto.core.setValueAmt = function()
{
  //GP:club first 2 ifs..D
  if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_Preference ) &&
       ( undefined != stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ValueCollections) ) 
  {
    if( stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ValueCollections != undefined)
    {
      var ValueCollections = stockphoto.core.BoxCar.AnalyzeXmlFileObj.Partners[0].AdobeSupports[0].ValueCollections[0];
      //GP: Take current region variable defn up and club the two ifs..ND
      if (("undefined" != typeof ValueCollections ) && (undefined != ValueCollections.Enabled ) 
           && (undefined != ValueCollections.Enabled.Value )&& (undefined != ValueCollections.BillingCurrency))
      {
      
        var CurrentRegion = stockphoto.prefs.GetCurrencyRegion(); // TODO - use a Getter function
        if (undefined != CurrentRegion)
        {
        	for(var indx = 0;indx < ValueCollections.BillingCurrency.length ; ++indx)
        	{ 
          		var oBillingStrings = ValueCollections.BillingCurrency[indx];
          		
          		if( (undefined != oBillingStrings.BillingCountry) && (undefined != oBillingStrings.BillingCountry.name)
                   && (undefined != oBillingStrings.BillingCountry.value) && (undefined != oBillingStrings.Locale) 
                   && (undefined != oBillingStrings.Locale.Value))
        		{
              		var key = oBillingStrings.BillingCountry.name;
              		var value = oBillingStrings.BillingCountry.value;
              		if(key == CurrentRegion)
              		{
                		var olocales= oBillingStrings.Locale.Value.split(",");
    					
                        var CurrentLocale = stockphoto.core.getValidLocale();
                           
                        for(var indx = 0;indx< olocales.length; ++indx)
                        {
                            if("undefined" != typeof CurrentLocale && undefined != CurrentLocale && CurrentLocale == olocales[indx])
                            {
                    			stockphoto.core.displayCurrency = value;
                  			}
                  		}   
                    }
               } 
        	}
        
      	}
     }
    } 
  }
}

/* PERF */ if (stockphoto.timeKeeperNewOn) { stockphoto.core.util.writeTimer("st00Core.jsx Load"); }
