/*
@@@BUILDINFO@@@ st15DownloadStock.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.
**************************************************************************/

if( ( stockphoto.timeKeeperOn != undefined )&&( stockphoto.timeKeeperOn ) )
{
	stockphoto.timeKeeper.st15DownloadStock        = {};
	stockphoto.timeKeeper.st15DownloadStock.StTime = new Date();
}

//
// download stock window object hierarchy
//
// stockphoto.downloadStock.instance (or dsInst)
//	 win(window)
//	   DSPanel(group)
//		 Status(StaticText): "Downloading xxx... (z%)"
//		 ItemList(ListBox)
//		 _propstick_(group)
//		 ProgressGroup(group)
//		   DLStatus(StaticText)
//		   DLProgress(Progressbar)
//		   DLPercent(StaticText)
//		 ButtonGroup(group)
//		   GoToFolderBtn(Button)
//		   DownloadBtn(Button)
//

//
// download stock namespace and zc and object instances
//
stockphoto.downloadStock = {};
stockphoto.downloadStock.zc = new stockphoto.zstringCache("st15DownloadStock");
stockphoto.downloadStock.instance = undefined;
stockphoto.downloadStock.standardCntTab = {};
stockphoto.downloadStock.locale = "";
stockphoto.downloadStock.downloadBoxWidth=26;
stockphoto.downloadStock.CustomName = "";
stockphoto.downloadStock.BaseName = "";
stockphoto.downloadStock.ImagesInBatch = 0;
		
stockphoto.downloadStock.standardCntTab =
{
	PROPSTICK_DIMENSIONS : "{width:370, height:0}",
	DSPANEL_OFFSET		: "{x:-40, y:30}",
	DSPANEL_LINE0		: "group { margins:0, alignment:'fill', orientation:'column', alignChildren:'center', Status: StaticText { text:'' }",
	DSPANEL_LINE1		: ", ItemList: ListBox { alignment:'fill', preferredSize: [370, 150] }, _propstick_: Group {}",
	DSPANEL_LINE2		: ", ProgressGroup: Group {alignment:'fill', orientation:'column', alignChildren:'left', DLStatus:StaticText {text:'' , properties:{ multiline:'true'} }",
	DSPANEL_LINE3		: ", DLProgress:Progressbar{preferredSize: [370, 12]}, DLPercent:StaticText{text:''}}", 
	DSPANEL_LINE4		: ", ButtonGroup: Group {alignment:'right', orientation:'row', alignChildren:'right', GoToFolderBtn: Button { preferredSize: [180, 20], text:'",
	DSPANEL_LINE5		: "' }, DownloadBtn: Button { preferredSize: [135, 20], text:'' }}}"
};

//
// constants
//
stockphoto.downloadStock.maxDispNameLen = 30;

stockphoto.st15_SetStandardCnvTab = function() 
{
	if (stockphoto.downloadStock.locale != stockphoto.core.getValidLocale()) 
	{
		if (stockphoto.core.util.loadLocaleData( "st15DownloadStock.par"))
		{
			stockphoto.downloadStock.locale = stockphoto.core.getValidLocale();
		}
	}
}

stockphoto.st15_SetStandardCnvTab();


//
// download stock object
//
stockphoto.downloadStock.object = function()
{

	//
	// Properties
	//
	this.win	   = undefined;
	this.winHelper = new stockphoto.downloadStock.winhelper();
	this.zc		   = stockphoto.downloadStock.zc;

	//
	// This holds the current getImage request object and is also used to
	// serialize download requests and test the current download state.
	//
	this.downloading = undefined;

	//
	// This object is used to remember failed downloads.
	//
	this.failedItems = {};

	//
	// These flags are used when user clicked OK for quit Bridge.
	//
	this.quitBridge = false;
	this.doAppQuit	= false;

	//
	// The startDownload method
	//
	this.startDownload = function(startOver)
	{
		// Sanity check

		if (this.downloading != undefined)
		{
			return;
		}

		// Check if the Purcahsed Images folder is read-only.

		var purchasedImagesFolder = stockphoto.core.folder.getMyPurchasesFolder();

		// If user folder is not reachable then don't save to default and return.
		if( ("undefined" != typeof stockphoto.core.SaveComp)
			 && stockphoto.core.folder.isReadOnly(stockphoto.core.SaveComp.CurrentPurchaseFolder)
			 && ( stockphoto.core.SaveComp.USER_DEFINED_FOLDER != stockphoto.core.SaveComp.iDonotSaveTo ))
		{
			if(stockphoto.core.SaveComp.CheckBoxPurchaseState)
			{
				stockphoto.core.util.alertReadOnlyFolderExtraMsg(stockphoto.core.SaveComp.CurrentPurchaseFolder, "$$$/AlertBox/ERROR_ATTEMPTING_IN_DEFAULT=Attempting download in default folder.");
			}
			else
			{
				stockphoto.core.util.alertReadOnlyFolderExtraMsg(stockphoto.core.SaveComp.CurrentPurchaseFolder);
				return;
			}
			
			stockphoto.core.SaveComp.iDonotSaveTo = stockphoto.core.SaveComp.USER_DEFINED_FOLDER;
		}

		// If saving to default folder also and the default is not reachable
		if ( (stockphoto.core.SaveComp.DEFAULT_FOLDER != stockphoto.core.SaveComp.iDonotSaveTo) // Msg not allready displayed
			&& stockphoto.core.SaveComp.CheckBoxPurchaseState && stockphoto.core.folder.isReadOnly(purchasedImagesFolder) )
		{
			stockphoto.core.util.alertReadOnlyFolder(purchasedImagesFolder);
					
			if(stockphoto.core.SaveComp.USER_DEFINED_FOLDER == stockphoto.core.SaveComp.iDonotSaveTo)
			{
				stockphoto.core.SaveComp.iDonotSaveTo = stockphoto.core.SaveComp.BOTH_LOCATIONS;
				return;	// If both the folders are not accessable.
			}
			stockphoto.core.SaveComp.iDonotSaveTo = stockphoto.core.SaveComp.DEFAULT_FOLDER;	// Incase the user clicks download again			
		}

		// Clear the failedItems array if user clicked download button.

		if (startOver)
		{
			this.failedItems = {};
		}

		var currentItem = this.getCurrentItem();
		
		if (currentItem <= -1)
		{
			return;
		}

		stockphoto.core.log.logString(0, "downloadstock:start download");

		// Prevent the next download request until this request finishes. For
		// now, we put an empty object just to signify that a download began.

		this.downloading = {};

		// Get the download object.

		var item = stockphoto.checkout.DLLGetItem(currentItem);

		var dlObject = stockphoto.checkout.DLLConvertItem2Object(item);

		// First, check authorization for this download.

		this.isdlAuthorized(dlObject);
	}

	this.GetImageExtn = function()
	{
		
		var currentItem = this.getCurrentItem();
		
		if (currentItem <= -1)
		{
			return;
		}
		var item = stockphoto.checkout.DLLGetItem(currentItem);

		var dlObject = stockphoto.checkout.DLLConvertItem2Object(item);
		
		// Check to see whether there is the same file downloaded in the
		// Purchased Images folder already. If there is, generate a unique name
		// from baseName to make it downloadable without overwriting the
		// existing one.

		var baseName = this.createBaseName(dlObject);
		stockphoto.downloadStock.BaseName = baseName;
		
		var destFolder = Folder(stockphoto.core.GetOrigCurrentPurchaseFolder());

		// KR shifted the logic for unique name generation to core
//		baseName = this.findUniqBaseName(destFolder, baseName); 

		// baseName and sourcePath need to be unique for each request.
		// Creating a File object from baseName satisfies the requirement.

		var sourcePath = new File(baseName);

		// Get billing country.

		stockphoto.DL.demandJsxLoading(stockphoto.DL.jsx_LangCountry);

		var billingCountry = stockphoto.core.BoxCar.LangCountry.getBillingCountry();

		// Make a hi-res image download request.

		var params =
		{
			Algorithm:			dlObject.algorithm,
			BillingCountry:		billingCountry,
			CheckoutDate:		dlObject.checkoutDate,
			CurrencyType:		dlObject.selectedCurrency,
			ID:					dlObject.mediaXMLMediaID,
			LanguageID:			dlObject.mediaXMLLanguageID,
			LineItemID:			dlObject.lineItemID,
			MediaTitle:			dlObject.mediaXMLMediaTitle,
			Price:				dlObject.selectedPrice,
			RootDomain:			dlObject.rootDomain,
			Signature:			dlObject.signature,
			SizeCode:			dlObject.selectedPurchaseID,
			SourceConnection:	dlObject.mediaXMLPartnerID,
			TransactionID:		dlObject.orderID,
			Version:			dlObject.mediaXMLVersion
		};

		var req =
		{
			baseName:		baseName,
			eventHandler:	this.getImageRequestEventHandler,
			folder:			stockphoto.core.folder.getMyPurchasesFolder(),//AK:added by aman
			params:			params,
			sourcePath:		sourcePath,
			iGetPurchImageUrlOnly: 	1
		};

		// Add a private property for Download Stock use only.

		var dsPrivate =
		{
			downloadObject: dlObject,
			oldPercent:		0,
			totalBytes:		0,
			sender:			this
		};

		req.dsPrivate = dsPrivate;

		// Save this 'real' getImage request to this.downloading and start
		// downloading image.

		this.downloading = req;

		if (this.win != undefined)
		{
			this.updateWindow();
		}

		stockphoto.core.log.logString(0, "downloadstock:call getImage");

		this.saveLevel(0);
		try
		{
			stockphoto.core.SendProxyCredentials();
			stockphoto.impl.getImage(req);
		}
		catch (e)
		{
			stockphoto.core.log.logString(0, "Exception while getting extension");
		}
		finally
		{
			this.restoreLevel();
		}	
		

		
	}
	// The isdlAuthorized caller method
	//
	this.isdlAuthorized = function(dlObject)
	{
		var xmlPath = stockphoto.core.init.partnersXMLfsObj.fsName;

		var req =
		{
			algorithm:		dlObject.algorithm,
			checkoutDate:	dlObject.checkoutDate,
			currencyType:	dlObject.selectedCurrency,
			eventHandler:	this.isdlAuthorizedEventHandler,
			lineItem:		dlObject.lineItemID,
			partnersPath:	xmlPath,
			price:			dlObject.selectedPrice,
			rootDomain:		dlObject.rootDomain,
			signature:		dlObject.signature
		};

		// Add a private property for download stock use only.

		var dsPrivate =
		{
			dlObject:	dlObject,
			sender:		this
		};

		req.dsPrivate = dsPrivate;

		// Set true to enable the isdlAuthorized call.

		if (false)
		{
			stockphoto.core.log.logString(0, "downloadstock:call isdlAuthorized");

			var idaResult = false;

			this.saveLevel(0);
			try
			{
				stockphoto.impl.isdlAuthorized(req);

				idaResult = true;
			}
			catch (e)
			{
				stockphoto.core.log.logString(0, "Exception on isdlAuthorized");
			}
			finally
			{
				this.restoreLevel();
			}

			if (idaResult == false)
			{
				this.downloading = undefined;

				if (this.win != undefined)
				{
					this.updateWindow();

					this.win.DSPanel.Status.text = this.zc.get("$$$/DownloadStock/ErrorMessage/System/isdlauthorized=System error on isdlAuthorized");
				}
			}
		}
		else
		{
			// Skip the isdlAuthorized call and pretend as though this download
			// is authorized.

			this.doDownload(true, dlObject);
		}
	}

	//
	// The isdlAuthorized event handler
	//
	this.isdlAuthorizedEventHandler = function(event)
	{
		if (event.eventClass == "DLAuthorized" && event.eventName == "authorized")
		{
			var dsInst = this.dsPrivate.sender;

			switch (event.status)
			{
				case "true":
				{
					stockphoto.core.log.logString(0, "downloadstock:isdlAuthorized true");
					dsInst.doDownload(true, this.dsPrivate.dlObject);
					break;
				}

				case "false":
				{
					stockphoto.core.log.logString(0, "downloadstock:isdlAuthorized false");

					stockphoto.DL.alertBox(event.errorCode);

					dsInst.doDownload(false, this.dsPrivate.dlObject);
					break;
				}
			}

			return true;
		}

		return false;
	}

	//
	// The doDownload method
	//
	this.doDownload = function(isAuthorized, dlObject)
	{
		if (isAuthorized == false)
		{
			stockphoto.core.log.logString(0, "downloadstock:download is not authorized for\n"
									+ "	  PartnerID:" + dlObject.mediaXMLPartnerID + "\n"
									+ "		MediaID:" + dlObject.mediaXMLMediaID + "\n"
									+ "	 PurchaseID:" + dlObject.selectedPurchaseID);

			this.downloading = undefined;

			if (this.win != undefined)
			{
				this.updateWindow();
			}

			return;
		}

		// Check to see whether there is the same file downloaded in the
		// Purchased Images folder already. If there is, generate a unique name
		// from baseName to make it downloadable without overwriting the
		// existing one.

		var baseName = this.createBaseName(dlObject);

		var destFolder = Folder(stockphoto.core.GetOrigCurrentPurchaseFolder());

		// KR shifted the logic for unique name generation to core
//		baseName = this.findUniqBaseName(destFolder, baseName); 

		// baseName and sourcePath need to be unique for each request.
		// Creating a File object from baseName satisfies the requirement.

		var sourcePath = new File(baseName);

		// Get billing country.

		stockphoto.DL.demandJsxLoading(stockphoto.DL.jsx_LangCountry);

		var billingCountry = stockphoto.core.BoxCar.LangCountry.getBillingCountry();

		// Make a hi-res image download request.

		var params =
		{
			Algorithm:			dlObject.algorithm,
			BillingCountry:		billingCountry,
			CheckoutDate:		dlObject.checkoutDate,
			CurrencyType:		dlObject.selectedCurrency,
			ID:					dlObject.mediaXMLMediaID,
			LanguageID:			dlObject.mediaXMLLanguageID,
			LineItemID:			dlObject.lineItemID,
			MediaTitle:			dlObject.mediaXMLMediaTitle,
			Price:				dlObject.selectedPrice,
			RootDomain:			dlObject.rootDomain,
			Signature:			dlObject.signature,
			SizeCode:			dlObject.selectedPurchaseID,
			SourceConnection:	dlObject.mediaXMLPartnerID,
			TransactionID:		dlObject.orderID,
			Version:			dlObject.mediaXMLVersion
		};

		var req =
		{
			baseName:		baseName,
			eventHandler:	this.getImageRequestEventHandler,
			folder:			stockphoto.core.folder.getMyPurchasesFolder(),//AK:added by aman
			params:			params,
			sourcePath:		sourcePath
		};

		// Add a private property for Download Stock use only.

		var dsPrivate =
		{
			downloadObject: dlObject,
			oldPercent:		0,
			totalBytes:		0,
			sender:			this
		};

		req.dsPrivate = dsPrivate;

		// Save this 'real' getImage request to this.downloading and start
		// downloading image.

		this.downloading = req;

		if (this.win != undefined)
		{
			this.updateWindow();
		}

		stockphoto.core.log.logString(0, "downloadstock:call getImage");

		this.saveLevel(0);
		try
		{
			stockphoto.impl.getImage(req);
		}
		catch (e)
		{
			stockphoto.core.log.logString(0, "Exception on getImage");

			this.downloading = undefined;

			if (this.win != undefined)
			{
				this.updateWindow();

				this.win.DSPanel.Status.text = this.zc.get("$$$/DownloadStock/ErrorMessage/System/getImage=System error on getImage");
			}

			// Keep track of items that failed to download so we can skip
			// over them and work our way down the list.

			var errObj = new Object();
			errObj.Failed = true;
			errObj.ErrCode = 0;

			this.failedItems[dlObject.mediaXMLMediaID] = errObj;
		}
		finally
		{
			this.restoreLevel();
		}
	}

	//
	// The getImage request event handler and its sub handlers
	//
	this.getImageRequestEventHandler = function(event)
	{
		// 'this' is the request object for the stockphoto.impl.getImage call
		// in this context. The stockphoto.impl.getImage call calls this
		// handler back like this: req.eventHandler(event).

		if (event.eventClass == "imageRequest" && event.eventName == "status")
		{
			var dsInst = this.dsPrivate.sender;

			// Special test to see whether quitting Bridge or not.

			if (dsInst.quitBridge)
			{
				// Don't run this section next time.

				dsInst.onBridgeQuit = false;

				// Instead, call app.quit() when cancellation is complete.

				dsInst.doAppQuit = true;

				// Need "resume=true" to make a cancel request a "stop and
				// resume later" request.

				this.resume = true;

				stockphoto.impl.cancelRequest(this);
			}

			switch (event.status)
			{
				case "begin":
				case "resume":
				case "continue":
				{
					dsInst.getImageRequestStatusHandler(this, event);
					break;
				}

				case "complete":
				{
					dsInst.getImageRequestCompleteHandler(this, event);
					break;
				}

				case "userCancel":
				{
					dsInst.getImageRequestCancelHandler(this, event);
					break;
				}

				case "abort":
				{
					dsInst.getImageRequestAbortHandler(this, event);
					break;
				}

				case "error":
				{	
					if (true == stockphoto.core.SaveComp.PurchaseImagesUserCancel)
					{
						dsInst.getImageRequestCancelHandler(this, event);
					}
					else
					{
						dsInst.getImageRequestErrorHandler(this, event);
					}
					break;
				}
			}

			return true;
		}

		return false;
	}

	this.getImageRequestStatusHandler = function(request, event)
	{
		// Save the total bytes for later use in the imageRequestCompleteHandler.

		request.dsPrivate.totalBytes = event.totalBytes;

		// Update the status of this download.

		this.updateImageRequestStatus(request, event.bytesReceived, event.totalBytes);
	}

	this.getImageRequestCompleteHandler = function(request, event)
	{
		stockphoto.core.log.logString(0, "downloadstock:complete download");

		// Let the progress bar show 100%.

		var totalBytes = request.dsPrivate.totalBytes;

		this.updateImageRequestStatus(request, totalBytes, totalBytes);

		// Notify completion of image download to the eCom server.
		// The endDownload method is called from its event handler.
		this.dlcomplete(request, event);
	}

	this.getImageRequestCancelHandler = function(request, event)
	{
		stockphoto.core.log.logString(0, "downloadstock:user Cancel download");

		this.endDownload(false, request, event);
	}

	this.getImageRequestAbortHandler = function(request, event)
	{
		stockphoto.core.log.logString(0, "downloadstock:abort download");

		this.endDownload(false, request, event);
	}

	this.getImageRequestErrorHandler = function(request, event)
	{
		stockphoto.core.log.logString(0, "downloadstock:error download");

		// Notify error to the user.

		if (event.status == "error")
		{
			// The 1st param of this function is a getImage request object.

			var dlobj = {};

			this.createSimpleDownloadObjectForBaseName(request.params, dlobj);

			var dispName = this.createBaseName(dlobj);

			var dispName = this.createBaseName(dlobj);
			if (true == stockphoto.core.SaveComp.PurchaseImagesShowDialog)
			{
				stockphoto.DL.alertBox(event.message, dispName);
				stockphoto.core.checkProxyOnFail();
				stockphoto.core.SaveComp.PurchaseImagesShowDialog = false;
				
			}

		}

		this.endDownload(false, request, event);
	}

	//
	// The dlcomplete caller method
	// This is simply a back-end data collection mechanism. Regardless the call
	// succeeds or not, the endDownload method will be called and successfully
	// downloaded image should be moved to the purchased folder.
	//
	this.dlcomplete = function(getImageRequest, getImageEvent)
	{
		var dlo = getImageRequest.dsPrivate.downloadObject;
		var xmlPath = stockphoto.core.init.partnersXMLfsObj.fsName; 
		var billingCntry = stockphoto.core.BoxCar.LangCountry.getBillingCountry();

		var req =
		{
			eventHandler:	this.dlcompleteEventHandler,
			lineItem:		dlo.lineItemID,			// used by both LogDownloadComplete() and isDownloadAuthorized()
			mediaID:		dlo.mediaXMLMediaID,	// needed if isDownloadAuthorized() is called from LogDownloadComplete() in adapter
			partnersPath:	xmlPath,
			billingCountry:	billingCntry,			// needed for BEER
			partnerID:		dlo.mediaXMLPartnerID,	// needed for BEER
			purchaseID:		dlo.selectedPurchaseID	// needed if isDownloadAuthorized() is called from LogDownloadComplete() in adapter
		};

		// Add a private property for download stock use only.

		var dsPrivate =
		{
			getImageEvent:		getImageEvent,
			getImageRequest:	getImageRequest
		};

		req.dsPrivate = dsPrivate;

		// Set true to enable the dlcomplete call.

		if (true)
		{
			stockphoto.core.log.logString(0, "downloadstock:call dlcomplete");

			this.saveLevel(0);
			try
			{
				// The dlComplete function may also call isDLAuthorized down in
				// the adapter.

//				stockphoto.impl.dlcomplete(req);
				stockphoto.impl.dlcomplete( req );
				if( stockphoto.Burp.doIt ) { // dlComplete
				/*B*/  		try
				/*B*/		{
				/*B*/			stockphoto.Burp.dlComplete( app.document.id, dlo.mediaXMLMediaID, dlo.selectedPurchaseID, dlo.orderID, dlo.mediaXMLPartnerID );
				/*B*/		} catch(e) { ; }
				}
			}
			catch (e)
			{
				stockphoto.core.log.logString(0, "Exception on dlcomplete");

				this.endDownload(true, getImageRequest, getImageEvent);
			}
			finally
			{
				this.restoreLevel();
			}
		}
		else
		{
			this.endDownload(true, getImageRequest, getImageEvent);
		}
	}

	//
	// The dlcomplete event handler
	//
	this.dlcompleteEventHandler = function(event)
	{
		if (event.eventClass == "dlcomplete")
		{
			var giReq	= this.dsPrivate.getImageRequest;
			var giEvent = this.dsPrivate.getImageEvent;
			var dsInst	= giReq.dsPrivate.sender;

			if (event.eventName == "status")
			{
				switch (event.status)
				{
					case "success":
					{
						stockphoto.core.log.logString(0, "downloadstock:dlcomplete success");
						dsInst.endDownload(true, giReq, giEvent);
						break;
					}

					case "error":
					{
						stockphoto.core.log.logString(0, "downloadstock:dlcomplete error");

						// We don't need to notify this error to user.
						// stockphoto.DL.alertBox(event.errorCode);

						dsInst.endDownload(true, giReq, giEvent);
						break;
					}
				}
			}
			else if (event.eventName == "error")
			{
				// If the error callback was called, just log it but proceed - rwe
				stockphoto.core.log.logString(0, "downloadstock:dlcomplete error = " + event.errorCode);
				dsInst.endDownload(true, giReq, giEvent);
			}

			return true;
		}

		return false;
	}

	//
	// The endDownload method
	//
	this.endDownload = function(isComplete, getImageRequest, getImageEvent)
	{
		stockphoto.core.log.logString(0, "downloadstock:end download");

		var bAbort = false;

		var statusMessage = undefined;

		if (isComplete)
		{
			//
			// Move image file from the downloaded location to My Purchases folder.
			//

			// Get the destination file object.

			//AK:Added by aman
			var dstPath = stockphoto.core.GetOrigCurrentPurchaseFolder();
			
			var dstName = getImageRequest.baseName;

			dstPath += "/" + dstName;

			var ext = getImageEvent.path.substr(getImageEvent.path.lastIndexOf("."));

			dstPath += ext;

			var dst = new File(dstPath);

			// Copy the source file to the destination.

			var srcPath = getImageEvent.path;

			var src = new File(srcPath);
			
			var oCopyPurchaseImages = new stockphoto.core.fileHandle(srcPath, stockphoto.core.GetOrigCurrentPurchaseFolder());
			var bSavedFile = oCopyPurchaseImages.saveFile(( dstName+=ext), stockphoto.downloadStock.CustomName, stockphoto.core.SaveComp.DoNotRenamePur, stockphoto.core.SaveComp.CheckBoxPurchaseState, "Hi-Rez", -1);

			src.remove();
			try
			{
			     var oDstThumb = new Thumbnail(dst);
			     oDstThumb.refresh("metadata");
			} catch(e) { };
			
			// Set the Mac type and creator code on destination file
			
			stockphoto.impl.setTypeCreator(dst, 0x3f3f3f3f, 0x3f3f3f3f); // '????', '????'

			stockphoto.core.log.logString(0, "downloadstock:image moved\n	 from:" + srcPath + "\n	   to:" + dstPath);

			// Mark the current item as done if saved successfuly.
			if(true == bSavedFile)
			{
				this.markCurrentItem(getImageRequest.params.ID, stockphoto.checkout.DLLKeywords.dlDone);
			}
			else
			{
				var dispName = dstName;
				dispName = this.shortenName(dispName);
				statusMessage = this.zc.get("$$$/DownloadStock/ErrorMessage/Downloading=Downloading error:") + dispName;
				this.markCurrentItem(getImageRequest.params.ID, stockphoto.checkout.DLLKeywords.dlFailed);
			}
		}
		else
		{
			// Download is cancelled or failed. Leave the partially downloaded
			// image on the disk for resume download later when cancelled.

			var dlobj = {};

			this.createSimpleDownloadObjectForBaseName(getImageRequest.params, dlobj);

			var dispName = this.createBaseName(dlobj);

			dispName = this.shortenName(dispName);

			// Either cancel or error (or abort)

			if (getImageEvent.status == "userCancel")
			{
				// Don't continue downloading.

				bAbort = true;

				// Get the cancel message.

				statusMessage = this.zc.get("$$$/DownloadStock/ErrorMessage/DownloadAbort=Download abort:")
									+ dispName;
			}
			else
			{
				// Keep track of items that failed to download so we can
				// skip over them and work our way down the list.

				var errObj = new Object();

				errObj.Failed = true;

				errObj.ErrCode = getImageEvent.message;

				this.failedItems[getImageRequest.params.ID] = errObj;

				this.markCurrentItem(getImageRequest.params.ID, stockphoto.checkout.DLLKeywords.dlFailed);

				// Get the error message.

				statusMessage = this.zc.get("$$$/DownloadStock/ErrorMessage/Downloading=Downloading error:")
									+ dispName;
			}
		}

		// Delete this getImage request object being held in the core.

		this.saveLevel(0);
		try
		{
			stockphoto.core.log.logString(0, "downloadstock:deleting getImage request");

			stockphoto.impl.deleteGetImage(getImageRequest.sourcePath);
		}
		catch (e)
		{
			stockphoto.core.log.logString(0, "Exception on deleteGetImage");

			// Something went wrong. Stop continuing download and show error
			// message.

			isComplete = false;

			statusMessage = this.zc.get("$$$/DownloadStock/ErrorMessage/System/deleteGetImage=System error on deleteGetImage");
		}
		finally
		{
			this.restoreLevel();
		}

		// Allow staring the next download.

		this.downloading = undefined;

		// Update the UI, with a messsage if needed.

		if (this.win != undefined)
		{
			this.updateWindow();

			if (statusMessage != undefined)
			{
				this.win.DSPanel.Status.text = statusMessage;
			}
		}

		// Move on to the next download item, if there is more to download.
		if(true == stockphoto.core.SaveComp.PurchaseImagesUserCancel)
		{
			bAbort = true;
		}

		if ((0 < this.getNoFailItemCount()) && (bAbort == false))
		{
			this.startDownload(false);
		}
		else if (getImageEvent.status == "userCancel" && this.doAppQuit)
		{
			stockphoto.core.log.logString(0, "downloadstock:calling app quit");
			app.quit();
		}
	}
	// Download item list handling methods
	this.isItemValid = function(itemIndex)
	{
		var ret = false;

		var itm = stockphoto.checkout.DLLGetItem(itemIndex);

		// DLLGetItem returns an array with three elements.

		if (0 < itm[0].length)
		{
			ret = true;
		}

		return ret;
	}
	
	this.isWaitingItem = function(itemIndex)
	{
		var ret = false;
		
		var itm = stockphoto.checkout.DLLGetItem(itemIndex);
		var obj = stockphoto.checkout.DLLConvertItem2Object(itm);

		if (obj.flag == stockphoto.checkout.DLLKeywords.dlWaiting)
		{
			ret = true;
		}

		return ret;
	}

	this.isDoneItem = function(itemIndex)
	{
		var ret = false;
		
		var itm = stockphoto.checkout.DLLGetItem(itemIndex);
		var obj = stockphoto.checkout.DLLConvertItem2Object(itm);

		if (obj.flag == stockphoto.checkout.DLLKeywords.dlDone)
		{
			ret = true;
		}

		return ret;
	}

	this.isFailedItem = function(itemIndex)
	{
		var ret = true;
		
		var itm = stockphoto.checkout.DLLGetItem(itemIndex);
		var obj = stockphoto.checkout.DLLConvertItem2Object(itm);
		var mID = obj.mediaXMLMediaID;

		if (this.failedItems[mID] == undefined)
		{
			ret = false;
		}
		
		return ret;
	}

	this.getItemCount = function()
	{
		// Count only valid items.

		var itemCount = 0;

		var count = stockphoto.checkout.DLLGetItemCount();

		for (var i = 0; i < count; i++)
		{
			if (this.isItemValid(i))
			{
				if (this.isDoneItem(i) == false)
				{
					itemCount++;
				}
			}
		}
		return itemCount;
	}
	
	this.getNoFailItemCount = function()
	{
		// Count only valid items and items that have not failed to download.

		var itemCount = 0;

		var count = stockphoto.checkout.DLLGetItemCount();

		for (var i = 0; i < count; i++)
		{
			if (this.isItemValid(i))
			{
				if (this.isFailedItem(i) == false)
				{
					if (this.isWaitingItem(i))
					{
						itemCount++;
					}
				}
			}
		}

		return itemCount;
	}

	this.markCurrentItem = function(mediaID, flag)
	{
		var count = stockphoto.checkout.DLLGetItemCount();

		for (var i = 0; i < count; i++)
		{
			if (this.isItemValid(i))
			{
				var itm = stockphoto.checkout.DLLGetItem(i);
				var obj = stockphoto.checkout.DLLConvertItem2Object(itm);
				
				if (obj.mediaXMLMediaID == mediaID)
				{
					stockphoto.checkout.DLLSetFlag(flag, i);
					break;
				}
			}
		}
	}

	this.getCurrentItem = function()
	{
		var currentItem = -1;

		var count = stockphoto.checkout.DLLGetItemCount();

		for (var i = 0; i < count; i++)
		{
			if (this.isItemValid(i))
			{
				if (this.isFailedItem(i) == false)
				{
					if (this.isWaitingItem(i))
					{
						currentItem = i;
						break;
					}
				}
			}
		}
		
		return currentItem;
	}

	this.addDLObjectToItemList = function(itemList, dlObject)
	{
		var separator	 = this.zc.get("$$$/DownloadStock/Window/Separator= / ");
		var checkoutDate = new Date(dlObject.checkoutDate * 1000);
		var yr			 = "" + checkoutDate.getFullYear();
		var dateString	 = "" + (checkoutDate.getMonth() + 1) + "-" + checkoutDate.getDate() + "-" + yr.substr(2, 2);
		var flag		 = "";

		with (stockphoto.checkout.DLLKeywords)
		{
			if (dlObject.flag == dlWaiting)
			{
				flag = this.zc.get("$$$/DownloadStock/Message/Flag/Waiting=Waiting");
			}
			else if (dlObject.flag == dlDownloading)
			{
				flag = this.zc.get("$$$/DownloadStock/Message/Flag/Downloading=Downloading");
			}
			else if (dlObject.flag == dlFailed)
			{
				flag = this.zc.get("$$$/DownloadStock/Message/Flag/Failed=Failed. Try again later");
			}
			else if (dlObject.flag == dlDone)
			{
				flag = this.zc.get("$$$/DownloadStock/Message/Done=Done");
			}
		}

		var displayBaseName = this.createBaseName(dlObject);

		displayBaseName = this.shortenName(displayBaseName);

		var txt = displayBaseName  + separator	+ dateString + separator + flag;

		itemList.add("item", txt);
	}

	//
	// Download object name handling methods
	// Assumption: dlObject is never 'undefined' (it should never be...)
	//
	this.createBaseName = function(dlObject)
	{
		var sFC	 = stockphoto.partnerNameToFilenameCode(dlObject.mediaXMLPartnerID);
		var sBase = stockphoto.core.getASPRefFromFM(sFC, dlObject.mediaXMLMediaID + '-' + dlObject.selectedPurchaseID);
		
        if (sBase == undefined)
		{
            // An (unexpected) error? Continue with the original FilenameCode, MediaID and PurchaseID
            sBase = sFC + "-" + dlObject.mediaXMLMediaID + "-" + dlObject.selectedPurchaseID;
        }
        
		var sBaseMediaName = sBase;
        
        if ( stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_MiscUtils ) ) 
        {
            sBaseMediaName = stockphoto.MiscUtils.file.convertToPOSIXCompliant( sBase );
        }

		// Add Filename prefix/suffix after the mediaID portion has been converted to POSIX
        var sBaseName = stockphoto.core.ASPRefToFilename(sBaseMediaName);
        
        if (sBaseName == undefined)
        {
            // Again, an (expected) error? Continue with just the Base Media Name
            sBaseName = sBaseMediaName;
        }
        
        return sBaseName;
	}

	this.convertToPOSIXCompliant = function(name, toHex)
	{
		// POSIX compliant chars: 0-9, a-z, A-Z, '.', '_', and '-'

		var newname = "";

		// For each char of the given name, if the char code is
		// 0x0000~0x00FF: make it POSIX compilant
		// 0x0100~: convert to char or its hex value if toHex is true

		var len = name.length;

		for (var i = 0; i < len; i++)
		{
			var uc = name.charCodeAt(i);

			if (uc < 0x0100)
			{
				var nuc = 0x005F; // Default '_'

				if ((uc == 0x002D) || (uc == 0x002E))		// '-' or '.'
				{
					nuc = uc;
				}
				else if ((0x0030 <= uc) && (uc <= 0x0039))	// 0-9
				{
					nuc = uc;
				}
				else if ((0x0041 <= uc) && (uc <= 0x005A))	// A-Z
				{
					nuc = uc;
				}
				else if ((0x0061 <= uc) && (uc <= 0x007A))	// a-z
				{
					nuc = uc;
				}

				newname += String.fromCharCode(nuc);
			}
			else
			{
				if (toHex)
				{
					newname += uc.toString(16);
				}
				else
				{
					newname += String.fromCharCode(uc);
				}
			}
		}

		return newname;
	}

	this.shortenName = function(name)
	{
		if (stockphoto.downloadStock.maxDispNameLen < name.length)
		{
			name = name.substr(0, stockphoto.downloadStock.maxDispNameLen - 1);
			name = name + "...";
		}

		return name;
	}

	this.createSimpleDownloadObjectForBaseName = function(girParams, obj)
	{
		obj.mediaXMLPartnerID  = girParams.SourceConnection;
		obj.mediaXMLMediaID	   = girParams.ID;
		obj.selectedPurchaseID = girParams.SizeCode;

		return obj;
	}

	//
	// UI methods
	//
	this.createWindow = function()
	{
		var winHelper = this.winHelper;

		// Create the default window.

		this.win = winHelper.createDefaultWindow('Adobe Stock Photos - ' + this.zc.get("$$$/DownloadStock/Window/Title=Download Status"));

		if (this.win)
		{
			// Point back to the download stock instance for later use.

			this.win.rootOwner = this;

			// Add event handlers.

			winHelper.addWindowEventHandlers(this.win);

			// Add download stock panel (DSPanel)

			var propstick_size = "propstick_size=" + stockphoto.downloadStock.standardCntTab.PROPSTICK_DIMENSIONS;
			eval(propstick_size);
			winHelper.addDSPanel(this.win, propstick_size);

			// Set a location.

			var dspanel_offset = "dspanel_offset=" + stockphoto.downloadStock.standardCntTab.DSPANEL_OFFSET;
			eval(dspanel_offset);
			winHelper.setWindowLocation(this.win, propstick_size, dspanel_offset);

			var DSPanel = this.win.DSPanel;
			DSPanel.ProgressGroup.DLProgress.hide();
			DSPanel.ProgressGroup.DLPercent.hide();
			DSPanel.ProgressGroup.DLStatus.hide();
		}
	}

	this.updateStatus = function()
	{
		var DSPanel		  = this.win.DSPanel;
		var status		  = DSPanel.Status;
		var itemCount	  = this.getItemCount();
		var doneItemCount = stockphoto.checkout.DLLGetGroupCount(true, false, false);

		if (0 < itemCount)
		{
			if (this.downloading == undefined)
			{
				status.text = "" + itemCount;

				if (1 == itemCount)
				{
					status.text += this.zc.get("$$$/DownloadStock/Message/Status/Image= Image");
				}
				else
				{
					status.text += this.zc.get("$$$/DownloadStock/Message/Status/Images= Images");
				}

				status.text += this.zc.get("$$$/DownloadStock/Message/Status/ToDownloadToPurchasedImagesFolder= to Download to Purchased Images Folder");
			}
			else
			{
				status.text = this.zc.get("$$$/DownloadStock/Message/Status/Downloading=Downloading ") + itemCount;

				if (1 == itemCount)
				{
					status.text += this.zc.get("$$$/DownloadStock/Message/Status/Image= Image");
				}
				else
				{
					status.text += this.zc.get("$$$/DownloadStock/Message/Status/Images= Images");
				}

				status.text += this.zc.get("$$$/DownloadStock/Message/Status/ToPurchasedImagesFolder= to Purchased Images Folder");
			}
		}
		else if (0 < doneItemCount)
		{
			status.text = this.zc.get("$$$/DownloadStock/Message/Status/Downloaded=Downloaded ") + doneItemCount;

			if (1 == doneItemCount)
			{
				status.text += this.zc.get("$$$/DownloadStock/Message/Status/Image= Image");
			}
			else
			{
				status.text += this.zc.get("$$$/DownloadStock/Message/Status/Images= Images");
			}

			status.text += this.zc.get("$$$/DownloadStock/Message/Status/ToPurchasedImagesFolder= to Purchased Images Folder");

		}
		else
		{
			status.text = this.zc.get("$$$/DownloadStock/Message/NoItemToDownload=No items to download");
		}

		if (this.downloading == undefined)
		{
			with (DSPanel.ProgressGroup)
			{
				DLProgress.value = 0;
				DLPercent.text = "";
				DLStatus.text = "";
	
				DLProgress.hide();
				DLPercent.hide();
				DLStatus.hide();
			}
		}
	}

	this.updateItemList = function()
	{
	
	
		var itemList  = this.win.DSPanel.ItemList;
		var dwnldBtn  = this.win.DSPanel.ButtonGroup.DownloadBtn;
		var itemFound = -1;
		var displayBaseName="";
		var maxDisplayLength = stockphoto.downloadStock.downloadBoxWidth;
		var textLen=0;

		itemList.removeAll();

		itemCount = stockphoto.checkout.DLLGetItemCount();
		stockphoto.downloadStock.ImagesInBatch = itemCount;
				
		// some changes for save as
		stockphoto.core.SaveComp.AdobeIdList="";

		for (var i = 0; i < itemCount; i++)
		{
			if (this.isItemValid(i))
			{
				var itm = stockphoto.checkout.DLLGetItem(i);
				var obj = stockphoto.checkout.DLLConvertItem2Object(itm);
				
				if ((itemFound < 0)
					&& (obj.flag == stockphoto.checkout.DLLKeywords.dlWaiting)
					&& (this.downloading != undefined))
				{
					obj.flag = stockphoto.checkout.DLLKeywords.dlDownloading;
					itemFound = i;
				}
				displayBaseName= this.createBaseName(obj);
				if( displayBaseName.length > maxDisplayLength)
				{
					maxDisplayLength=displayBaseName.length;
				}
				displayBaseName= '"' + displayBaseName + '"';
				stockphoto.core.SaveComp.AdobeIdList = stockphoto.core.SaveComp.AdobeIdList+',' + displayBaseName;
				this.addDLObjectToItemList(itemList, obj);
			}
		}
		stockphoto.core.SaveComp.AdobeIdList = 	stockphoto.core.SaveComp.AdobeIdList.slice(1);
		
		// change ends

		if (0 <= itemFound)
		{
		   itemList.selection = itemFound;
		}
		if(maxDisplayLength > stockphoto.downloadStock.downloadBoxWidth)
		{
			textLen= this.zc.get("$$$/DownloadStock/Message/Status/AddingMetadata=Adding metadata to ").length;
			maxDisplayLength=(maxDisplayLength-stockphoto.downloadStock.downloadBoxWidth)*5 + (textLen -20)*5;
			this.win.DSPanel.ProgressGroup.DLStatus.preferredSize = [(370+maxDisplayLength),22];
			this.win.DSPanel.ProgressGroup.DLProgress.preferredSize = [(370+maxDisplayLength),12];
		}

		return itemCount;
	}

	this.updateDownloadBtn = function()
	{
		var dsPanel = this.win.DSPanel;

		var dwnldBtn = dsPanel.ButtonGroup.DownloadBtn;
		var gtfldBtn = dsPanel.ButtonGroup.GoToFolderBtn;

		if (this.downloading != undefined)
		{
			dwnldBtn.text = this.zc.get("$$$/DownloadStock/Window/Btn/Text/StopDownload=Stop Download");

			dsPanel.ButtonGroup.DownloadBtn.resumeDownload = false;

			if (dsPanel.ProgressGroup.DLProgress.visible == false)
			{
				dsPanel.ProgressGroup.DLProgress.show();
				dsPanel.ProgressGroup.DLPercent.show();
				dsPanel.ProgressGroup.DLStatus.show();

				gtfldBtn.enabled = false;
			}
		}
		else 
		{
			if (dsPanel.ButtonGroup.DownloadBtn.resumeDownload == true)
			{
				dwnldBtn.text = this.zc.get("$$$/DownloadStock/Window/Btn/Text/ResumeDownload=Resume Download");
				gtfldBtn.enabled = true;
			}
			else
			{
				dwnldBtn.text = this.zc.get("$$$/DownloadStock/Window/Btn/Text/StartDownload=Start Download");
			}
		}

		var itemCount = this.getItemCount();

		if ((0 < itemCount) && (0 < this.getNoFailItemCount()))
		{
			dwnldBtn.enabled = true;
		}
		else
		{
			dwnldBtn.enabled = false;
			gtfldBtn.enabled = true;
			if(stockphoto.core.SaveComp.aImagesSavedHiRez.length > 0)
			{
				stockphoto.DL.confirmationBox(9, stockphoto.core.SaveComp.aImagesSavedHiRez.length, "", "", undefined, undefined, 1); // KR TODO .. Check the doc_id value..
				stockphoto.core.SaveComp.aImagesSavedHiRez = [];
			}
		}
	}

	this.updateWindow = function()
	{
		this.updateItemList();
		this.updateStatus();
		this.updateDownloadBtn();
	}

	this.show = function(show, autoDL)
	{
		if (show)
		{
			if (this.win == undefined)
			{
				this.createWindow();
			}

			if (this.win != undefined)
			{
				this.updateWindow();

				this.win.show();

				this.win.active = true;

				// Rebounds Status and DownloadBtn.

				this.winHelper.reboundObj(this.win, this.win.DSPanel.Status);
				this.winHelper.reboundObj(this.win, this.win.DSPanel.ProgressGroup.DLStatus);
				this.winHelper.reboundObj(this.win, this.win.DSPanel.ProgressGroup.DLPercent);

				// If caller wants dl to begin automatically, simulate click on dl button now - rwe

				if (autoDL)
				{
					this.win.DSPanel.ButtonGroup.DownloadBtn.onClick();
				}
			}
		}
		else
		{
			if (this.win)
			{
				this.win.hide();
			}
		}
	}

	this.updateImageRequestStatus = function(request, bytesReceived, totalBytes)
	{
		if (this.win != undefined)
		{
			var percent = Math.ceil(bytesReceived / totalBytes * 100);
			var imageSize, sizeType;
			var tempIdx;

			if ((1024 * 1024) <= totalBytes)
			{
				imageSize = "" + (totalBytes / (1024 * 1024) + 0.005);
				sizeType = this.zc.get("$$$/DownloadStock/Message/MB=MB");
			}
			else
			{
				imageSize = "" + (totalBytes / 1024 + 0.005);
				sizeType = this.zc.get("$$$/DownloadStock/Message/KB=KB");
			}

			tempIdx = imageSize.indexOf(".");

			if (0 <= tempIdx)
			{
				imageSize = imageSize.slice(0, tempIdx + 3);
			}

			imageSize += sizeType;			  

			if (request.dsPrivate.oldPercent < percent)
			{
				request.dsPrivate.oldPercent = percent;

				var status		= "";
				var percentText = "";
				var statusText	= "";
				var DSPanel		= this.win.DSPanel;

				// Set false for alternate format.

				if (true)
				{
					var dispName = this.createBaseName(request.dsPrivate.downloadObject);

					if (percent < 100)
					{
						percentText = percent + "%"; //this.zc.get("$$ $/DownloadStock/Message/PercentRight=%");
						statusText	= this.zc.get("$$$/DownloadStock/Message/Status/Downloading=Downloading ") + dispName;
					}
					else
					{
						// Don't allow stop downloading because it's too late.

						DSPanel.ButtonGroup.DownloadBtn.enabled = false;

						statusText	= this.zc.get("$$$/DownloadStock/Message/Status/AddingMetadata=Adding metadata to ") + dispName;
					}
				}
				else
				{
					status = bytesReceived + ":" + totalBytes;
				}

				DSPanel.ProgressGroup.DLPercent.text = imageSize + " " + percentText;
				DSPanel.ProgressGroup.DLStatus.text = statusText;
				DSPanel.ProgressGroup.DLProgress.value = percent;
			}
		}
	}

	this.findUniqBaseName = function(destFolder, baseName)
	{
		// First, check to see if there is a file with the base name only.

		var dirContents = new Array;
		
		dirContents = destFolder.getFiles(baseName + ".*");

		if (dirContents.length == 0)
		{
			return baseName;
		}

		// If there is, then find a unique name that doesn't exist yet.

		var uniqBaseName;
		var suffix = 1;
		var found = false;

		while (found == false)
		{
			uniqBaseName = baseName + "_" + suffix;

			dirContents = destFolder.getFiles(uniqBaseName + ".*");

			if (dirContents.length == 0)
			{
				found = true;
			}
			else
			{
				suffix++;
			}
		}

		return uniqBaseName;
	}

	//
	// Properties and methods for debug
	//
	this.oldLevel = $.level;

	this.saveLevel = function(newLevel)
	{
		this.oldLevel = $.level;
		$.level = newLevel;
	}

	this.restoreLevel = function()
	{
		$.level = this.oldLevel;
	}
}

//
// download stock window helper
//
stockphoto.downloadStock.winhelper = function()
{
	this.createDefaultWindow = function(title)
	{
		// Create a modeless 'window' type Window object

		var win = new Window('window', title, undefined, {closeOnKey:"OSCmnd+W", closeButton:true, maximizeButton:false, minimizeButton:true, independent: true});
		win.modal = true;

		return win;
	}

	this.addWindowEventHandlers = function(win)
	{
		win.onClose = function()
		{
			stockphoto.core.SaveComp.MultipleImage=0;
			if (this.rootOwner.downloading != undefined)
			{
				var zc = stockphoto.downloadStock.zc;
				var msg = zc.get("$$$/DownloadStock/Dialog/ClosingWindowMessage=The images you purchased will continue to download in the background and will be placed in the Purchased Images folder. To view the list of downloads, choose Window > Download Status.");
				stockphoto.DL.downloadAlertBox(2, msg);
			}
			else
			{
				if (this.rootOwner.getNoFailItemCount() == 0)
				{
				   this.rootOwner.failedItems = {};
				}
			}

			stockphoto.checkout.DLLClean(true, false, false);

			// This window is being destroyed, so clear the pointer
			// to this window held by the owner of this window (dsInst).

			this.rootOwner.win = undefined;

			return true;
		}
	}

	this.getDSPanelResource = function(rootOwner)
	{
		var res = stockphoto.downloadStock.standardCntTab.DSPANEL_LINE0;
		res +=	  stockphoto.downloadStock.standardCntTab.DSPANEL_LINE1;
		res +=	  stockphoto.downloadStock.standardCntTab.DSPANEL_LINE2;
		res +=	  stockphoto.downloadStock.standardCntTab.DSPANEL_LINE3;
		res +=	  stockphoto.downloadStock.standardCntTab.DSPANEL_LINE4;
		res +=	  rootOwner.zc.get("$$$/DownloadStock/ViewPurchasedImages=View Purchased Images");
		res +=	  stockphoto.downloadStock.standardCntTab.DSPANEL_LINE5;

		return res;
	}

	this.addDSPanelEventHandlers = function(rootOwner, DSPanel)
	{
		with (DSPanel)
		{
			ButtonGroup.DownloadBtn.resumeDownload	= false;
			ButtonGroup.DownloadBtn.rootOwner		= rootOwner;

			ButtonGroup.DownloadBtn.onClick = function()
			{
				// Note: 'this' is a DownloadBtn object in this context.
	 					
				var dsInst	 = this.rootOwner;
				var gtfldBtn = ButtonGroup.GoToFolderBtn;

				if (dsInst.downloading == undefined)
				{
				//Change for Save As
					stockphoto.core.SaveComp.MediaType=1;
					var oFolderPath;
					var oDialogResult=0;
				// KR - If the current hi-rez folder donot have permissions then display default hi-rez folder.
					if(stockphoto.core.folder.isReadOnly(stockphoto.core.GetCurrentPurchaseFolder()))
					{
						stockphoto.core.SetCurrentPurchaseFolder(stockphoto.core.folder.getMyPurchasesFolder());
					}
					/* Adding Default Folder Path also - To desable the Chk Box */
					var oFolderRequest =
					{
						bDoNotRenameFlag : true,
						bSaveCopyFlag : stockphoto.core.SaveComp.CheckBoxPurchaseState,
						bAddToFavoriteFlag : stockphoto.core.SaveComp.AddToFavoriteFolderStatePur,
						sImageName : stockphoto.core.SaveComp.AdobeIdList,
						sImagePath : stockphoto.core.GetCurrentPurchaseFolder(),
						iImageTypeFlag : stockphoto.core.SaveComp.MediaType,
						iSingleOrMultipleFlag : stockphoto.core.SaveComp.MultipleImage,
						sDefaultFolderPath : stockphoto.core.folder.getMyPurchasesFolder()
					};
					ButtonGroup.DownloadBtn.enabled=false;
					gtfldBtn.enabled=false;
					stockphoto.core.SaveComp.iDonotSaveTo = stockphoto.core.SaveComp.NONE;
					stockphoto.core.SaveComp.aImagesSavedHiRez = [];
					if( "undefined" != typeof(app.preferences) &&
		   			 undefined != app.preferences.bm_SaveCopyFlagPurchased )
					{			
						oFolderRequest.bSaveCopyFlag = app.preferences.bm_SaveCopyFlagPurchased;
					}
					// Watson : 1370007
					else
					{
						oFolderRequest.bSaveCopyFlag = true;
						app.preferences.bm_SaveCopyFlagPurchased = true;
					}

					if((undefined != stockphoto.downloadStock.instance)&& (1 == stockphoto.downloadStock.ImagesInBatch))
					{
						stockphoto.downloadStock.instance.GetImageExtn();
					}
					
					stockphoto.core.SaveComp.PurchaseImagesShowDialog = true;
					stockphoto.core.SaveComp.PurchaseImagesUserCancel = false;

					if (undefined == stockphoto.bIsVCInitialized )
					{
						stockphoto.core.init.loadVC();
					} 
 		
					var aFolderArray;
					
					if (true == stockphoto.bIsVCInitialized )
					{
						aFolderArray = stockphoto.impl.openSaveAsDialog(oFolderRequest);
					}
					else
					{
					   aFolderArray = [];
					   aFolderArray[0]= "0";
					   aFolderArray[1] = "1";
					   aFolderArray[2] = "0";
					   aFolderArray[3] = "";
					   aFolderArray[4] = stockphoto.core.folder.getMyPurchasesFolder();
					   aFolderArray[5] = "0";
					}
 		
					
					if(1 == stockphoto.downloadStock.ImagesInBatch)
					{
						dsInst.saveLevel(0);
						try
						{
							stockphoto.core.log.logString(0, "downloadstock:deleting getImage request");
							var baseName = stockphoto.downloadStock.BaseName;
							var sourcePath = new File(baseName);
							stockphoto.impl.moveExtnGetImage(sourcePath);
							app.scheduleTask('var sourcePath = new File("' + sourcePath + '"); stockphoto.impl.deleteExtnGetImage(sourcePath);', 20000, false); 
							
							var currentItem = dsInst.getCurrentItem();
							var item = stockphoto.checkout.DLLGetItem(currentItem);
							var dlObject = stockphoto.checkout.DLLConvertItem2Object(item);
							dlObject.flag = 	stockphoto.checkout.DLLKeywords.dlWaiting		 			
			 				
			 				// Allow staring the next download.
							dsInst.downloading = undefined;
						}
						catch (e)
						{
							stockphoto.core.log.logString(0, "Exception on deleteGetImage");

						}
						finally
						{
							dsInst.restoreLevel();
						}
					}


					stockphoto.core.SaveComp.numOfImagesSelected = stockphoto.checkout.DLLGetItemCount();// KR TEST..
					ButtonGroup.DownloadBtn.enabled=true;
					gtfldBtn.enabled=true;
					

				 	//latest
				 	if(undefined != aFolderArray && (aFolderArray.length == 6))
					{
						oDialogResult= stockphoto.core.util.convertToInteger(aFolderArray[5]);
						if(oDialogResult != 0)
						{
						    dsInst.updateDownloadBtn();
							return true;			
						}
				
						stockphoto.core.SendProxyCredentials();

						stockphoto.core.SaveComp.DoNotRenamePur = stockphoto.core.util.convertToInteger(aFolderArray[0]);
						stockphoto.core.SaveComp.CheckBoxPurchaseState = stockphoto.core.util.convertToBoolean(aFolderArray[1]);
						app.preferences.bm_SaveCopyFlagPurchased = stockphoto.core.SaveComp.CheckBoxPurchaseState;
						stockphoto.core.SaveComp.AddToFavoriteFolderStatePur = stockphoto.core.util.convertToBoolean(aFolderArray[2]);
						stockphoto.downloadStock.CustomName = aFolderArray[3];
						oFolderPath = aFolderArray[4];
			
						if("" != oFolderPath)
						{
							destFolder=oFolderPath;
						}
	 				}
	 				else
	 				{	
	 				    dsInst.updateDownloadBtn();
						return true;	
	 				}
				 	//latest
				 	
		 			stockphoto.core.SetCurrentPurchaseFolder(destFolder);


		 			//Change Ends
					dsInst.startDownload(true);

					gtfldBtn.enabled = false;

					if (dsInst.win != undefined)
					{
						dsInst.updateDownloadBtn();
					}
				}
				else
				{
					// Send "stop" download request to SPSUI.
					stockphoto.core.SaveComp.PurchaseImagesUserCancel = true;

					stockphoto.core.log.logString(0, "downloadstock:cancel download");

					// Make sure that the downloading object is holding a valid
					// getImage request object before calling cancelRequest().

					if (dsInst.downloading.baseName != undefined)
					{
						// Need "resume=true" to make the getImage request
						// a "stop and resume later" request.

						dsInst.downloading.resume = true;

						dsInst.resumeDownload = true;

						stockphoto.impl.cancelRequest(dsInst.downloading);
					}
				}
			}
			
			ButtonGroup.GoToFolderBtn.onClick = function()
			{
// KR When user clicks on the "View Purchased Images Folder" button..
				// Browse the folder where user has saved the purchased images... Changes for save-as 
				if (stockphoto.core.GetCurrentPurchaseFolder() != stockphoto.core.util.getDisplayPath(app.document.thumbnail,""))
				{
					stockphoto.DL.MiscDlgs.ShowCurrentPurchasedFolder(app.document.id);
				}			
				
				var winToClose = this.parent.parent.parent;

				if (winToClose instanceof Window)
				{
					winToClose.close();
				}
			}

			ItemList.onChange = function()
			{
				ItemList.selection = null;
				return true;
			}
		}

		// Make the Local Shopping Cart functions available.

		stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_AddToCart );
	}

	this.addDSPanel = function(win, propSize)
	{
		var res = this.getDSPanelResource(win.rootOwner);

		win.DSPanel = win.add(res);

		// Set propSize to _propstick_: a trick to reserve a predefined width.

		win.DSPanel._propstick_.size = propSize;

		// Set up the event handlers for each control.

		this.addDSPanelEventHandlers(win.rootOwner, win.DSPanel);
	}

	this.setWindowLocation = function(win, propSize, panelOffset)
	{
		// Position the panel at the upper right of the current window.

		var dwsl = stockphoto.core.util.getDocumentWindowSizeAndLocation();

		var bws = dwsl.size;
		var bwl = dwsl.location;

		if (bws != undefined && bwl != undefined)
		{
			var loc =
			{
				x:	(bwl.x + bws.width - propSize.width + panelOffset.x),
				y:	(bwl.y + panelOffset.y)
			};

			win.location = loc;
		}
		else
		{
			win.center(); // fallback
		}
	}

	this.reboundObj = function(win, obj)
	{
		var DSPanel = win.DSPanel;

		var xyz = obj;

		var bounds = xyz.bounds;

		if (bounds != undefined)
		{
			var margin	 = DSPanel.parent.margins.left;
			bounds.width = DSPanel.size.width - margin * 2;
			bounds.x	 = 0; //margin;
			xyz.bounds	 = bounds;
		}
	}

	this.reboundDownloadBtn = function(win)
	{
		var DSPanel = win.DSPanel;

		var dsb = DSPanel.ButtonGroup.DownloadBtn;

		var bounds = dsb.bounds;

		if (bounds != undefined)
		{
			bounds.width = DSPanel.size.width / 2;
			bounds.x	 = bounds.width / 2 - DSPanel.parent.margins.left * 2;
			dsb.bounds	 = bounds;
		}
	}
}

//
// download stock object factory
//
//stockphoto.st15_DownloadStock_Body = function(loadBM, autoDLin)
stockphoto.st15_DownloadStock_Body = function( loadBM, autoDLin, doc_id, fromSource )
{
	var autoDL;

	if (undefined != doc_id)
	{
		/*B*/	stockphoto.Burp.downloadSource[ doc_id ] = fromSource;
	}

	if( autoDLin == undefined )
	     autoDL = false;
	else autoDL = autoDLin;
	if (loadBM != undefined)
	{
		if (loadBM == true)
		{
			stockphoto.core.init.loadBMScripts(true); // 'true' means no dwnld mgr queue check in the LoadBMScripts.

			if (stockphoto.core.init.isScriptLoaded != true)
			{
				return;
			}
		}
	}

	// Make the Download List functions available.

	stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_CheckOut );

	// If the download stock instance is not created yet, create and run it.
	// If it's already created, show it on the display.

	if (stockphoto.downloadStock.instance == undefined)
	{
		try
		{
			stockphoto.core.SaveComp.MultipleImage =0;
			stockphoto.downloadStock.instance = new stockphoto.downloadStock.object();
			stockphoto.downloadStock.instance.show(true, autoDL);
		}
		catch (e)
		{
			stockphoto.core.log.logString(0, "Exception on st15_DownloadStock_Body");
		}
	}
	else
	{
		stockphoto.downloadStock.instance.show(true, autoDL);
	}
}

stockphoto.DL.doclearAllItemsInList_Body = function()
{
	if (stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_CheckOut ))
	{
		stockphoto.checkout.DLLRemoveAll();
	}

	if (stockphoto.downloadStock.instance != undefined)
	{
		var dsInst = stockphoto.downloadStock.instance;

		if (dsInst.win != undefined)
		{
			if (dsInst.win.DSPanel != undefined)
			{
				dsInst.win.DSPanel.ItemList.removeAll();
				dsInst.updateWindow();
			}
		}
	}
}

//
// CheckDownloadMgrQueueOnStartup
// This returns 1 for NOW button click and 2 for LATER button click.
// 
stockphoto.DL.doCheckDownloadMgrQueueOnStartup_Body = function()
{
	stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_CheckOut );

	var count = stockphoto.checkout.DLLGetItemCount();

	if (0 < count)
	{
		var alertResult = stockphoto.DL.downloadAlertBox(0);

		if (alertResult == 1)
		{
			// If we are here, it means preferences say ask to resume downloads,
			// and the user has said NOW. No need to make them press yet another button.

//			stockphoto.DL.Download.DownloadStock(false, true);
			stockphoto.DL.Download.DownloadStock(false, true, app.document.id, "dl");
		}
	}
}

//
// CheckDownloadMgrQueueBeforeQuitting
// This returns 1 for YES button click and 2 for NO button click.
//
// When and only when hi-res download is going on, user is asked whether to
// quit Bridge or not. But when user clicked YES, in order to cancel download
// and close the file safely, we return 2(NO) and let the download manager
// cancel the download and quit Bridge by setting the quitBridge flag.
// 
stockphoto.DL.doCheckDownloadMgrQueueBeforeQuitting_Body = function()
{
	// Do download object cleanup first.
	stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_CheckOut );

	stockphoto.checkout.DLLClean(true, false, false);

	var result = 1;	// default to "Yes, Quit the Bridge"

	if (stockphoto.downloadStock == undefined)
	{
		return result;
	}

	if (stockphoto.downloadStock.instance == undefined)
	{
		return result;
	}

	if (stockphoto.downloadStock.instance.downloading != undefined)
	{
		result = stockphoto.DL.downloadAlertBox(1);

		if (result == 1)
		{
			stockphoto.downloadStock.instance.quitBridge = true;

			stockphoto.core.log.logString(0, "downloadstock:quitBridge flag is raised");

			result = 2;
		}
	}

	return (result);
}

if( ( stockphoto.timeKeeperOn != undefined )&&( stockphoto.timeKeeperOn ) )
{
	stockphoto.core.util.edTime( stockphoto.DL.jsx_DownloadStock );
}

