/*
@@@BUILDINFO@@@ st01AddToCart.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.st01AddToCart        = {};
	stockphoto.timeKeeper.st01AddToCart.StTime = new Date();
}

// AddToCart namespace and zstringCache instance
stockphoto.addToCart = {};
stockphoto.addToCart.zc = new stockphoto.zstringCache("st01AddToCart");
stockphoto.addToCart.zc.dict = "AddToCart.txt";
stockphoto.addToCart.requests = {};
stockphoto.addToCart.requestIndex = 0;

// Should not localize the following keywords
stockphoto.addToCart.LSCKeywords = 
{
	Version : "Version",
	MediaID : "MediaID",
	PartnerID : "PartnerID",
	MediaTitle : "MediaTitle",
	PurchaseID : "PurchaseID",
	Price : "Price",
	Currency : "Currency",
	LanguageID : "LanguageID",
	Description : "Description",
	Signature : "Signature",
	Algorithm : "Algorithm",
	ExpirationDate : "ExpirationDate",
	NewPrice : "NewPrice",
	ItemRemoved : "Removed",
	PartnerName : "PartnerName",
	ASPRefID : "ASPRefID"
};

//--------------------------------------------------------------------
// Shopping cart API
//--------------------------------------------------------------------

stockphoto.addToCart.LSCGetMediaKey = function(index)
{
	return "bm_scItem" + index + "_MediaXML";
}

stockphoto.addToCart.LSCGetResolutionsKey = function(mIndex, rIndex)
{
	return "bm_scItem" + mIndex + "_Resolution" + rIndex;
}

stockphoto.addToCart.LSCGetResolutionsCountKey = function(index)
{
	return "bm_scItem" + index + "_ResolutionCount";
}

stockphoto.addToCart.LSCGetThumbnailFilePathKey = function(index)
{
	return "bm_scItem" + index + "_ThumbnailPath";
}

stockphoto.addToCart.LSCGetItemStatusKey = function(index)
{
	return "bm_scItem" + index + "_Flag";
}

stockphoto.addToCart.LSCGetItemCount = function()
{
	if (app.preferences.bm_ShoppingCartCount == undefined)
	{
		app.preferences.bm_ShoppingCartCount = 0;
	}
	return  app.preferences.bm_ShoppingCartCount;
}

stockphoto.addToCart.LSCConvertObject2Item = function(cartObject)
{
	if ((cartObject == undefined) || (cartObject == null))
	{
		return null;
	}
   
	try
	{ 
		var resolutions = cartObject.resolutionXMLPurchaseID.length;
		var cartItem = {};

		with (stockphoto.addToCart.LSCKeywords)
		{
			cartItem[0] = Version + "=" + escape(cartObject.mediaXMLVersion) +
				"&" + MediaID + "=" + escape(cartObject.mediaXMLMediaID) +
				"&" + PartnerID + "=" + escape(cartObject.mediaXMLPartnerID) +
				"&" + MediaTitle + "=" + escape(cartObject.mediaXMLMediaTitle) +
				"&" + PurchaseID + "=" + escape(cartObject.selectedPurchaseID) +
				"&" + Price + "=" + escape(cartObject.selectedPrice) +
				"&" + Currency + "=" + escape(cartObject.selectedCurrency) +
				"&" + LanguageID + "=" + escape(cartObject.mediaXMLLanguageID) +
				"&" + ASPRefID + "=" + escape(cartObject.mediaXMLASPRefID);
		
			cartItem[1] = resolutions;

			for (var i = 0; i < cartItem[1]; i++)
			{
				cartItem[ i + 2] = PurchaseID + "=" + escape(cartObject.resolutionXMLPurchaseID[i]) +
					 "&&" + Description + "=" + unescape(cartObject.resolutionXMLDescription[i]) +
					 "&&" + Price + "=" + escape(cartObject.resolutionXMLPrice[i]) +
					 "&&" + Signature + "=" + escape(cartObject.signature[i])  +
					 "&&" + Algorithm + "=" + escape(cartObject.algorithm[i]) +
					 "&&" + ExpirationDate + "=" + escape(cartObject.expirationDate[i]);
			}
			
			cartItem[cartItem[1] + 2] = escape(cartObject.thumbnailPath);
			cartItem[cartItem[1] + 3] = escape(cartObject.flag);			
		}
		return cartItem;
	}
	catch (e)
	{
		stockphoto.core.log.logString( 2,"Exception in LSCConvertObject2Item" );
		return null;
	}
}

stockphoto.addToCart.LSCConvertItem2Object = function(cartItem)
{
	if ((cartItem == undefined) || (cartItem == null))
	{
		return null;
	}
	
	try
	{
		var cartObject = new Object();
		var mediaXML = cartItem[0].split("&");
		cartObject.mediaXMLASPRefID = "";
		for (var j = 0; j < mediaXML.length; j++)
		{
			var mediaXMLItems = new Array(2);
			var pIndex = mediaXML[j].indexOf("=");
			mediaXMLItems[0] = mediaXML[j].slice(0, pIndex);
			mediaXMLItems[1] = unescape(mediaXML[j].slice(pIndex + 1, mediaXML[j].length));

			with (stockphoto.addToCart.LSCKeywords)
			{
				if (mediaXMLItems[0] == Version)
					cartObject.mediaXMLVersion = mediaXMLItems[1];
				else if (mediaXMLItems[0] == MediaID)
					cartObject.mediaXMLMediaID = mediaXMLItems[1];
				else if (mediaXMLItems[0] == PartnerID)
					cartObject.mediaXMLPartnerID = mediaXMLItems[1];
				else if (mediaXMLItems[0] == MediaTitle)
					cartObject.mediaXMLMediaTitle = mediaXMLItems[1];
				else if (mediaXMLItems[0] == PurchaseID)
					cartObject.selectedPurchaseID = mediaXMLItems[1];
				else if (mediaXMLItems[0] == Price)
					cartObject.selectedPrice = mediaXMLItems[1];
				else if (mediaXMLItems[0] == Currency)
					cartObject.selectedCurrency = mediaXMLItems[1];
				else if (mediaXMLItems[0] == LanguageID)
					cartObject.mediaXMLLanguageID = mediaXMLItems[1];
				else if (mediaXMLItems[0] == ASPRefID)
					cartObject.mediaXMLASPRefID = mediaXMLItems[1];
			}
		}

		var resolutionCount = cartItem[1];
		
		cartObject.thumbnailPath = unescape(cartItem[resolutionCount + 2]);
		cartObject.flag = unescape(cartItem[resolutionCount + 3]);

		cartObject.resolutionXMLPurchaseID	= new Array(resolutionCount);
		cartObject.resolutionXMLDescription	= new Array(resolutionCount);
		cartObject.resolutionXMLPrice	 = new Array(resolutionCount);
		cartObject.signature		= new Array(resolutionCount);
		cartObject.algorithm		= new Array(resolutionCount);
		cartObject.expirationDate		= new Array(resolutionCount);

		for (var k = 0; k < resolutionCount; k++)
		{		   
			if (cartItem[k+2] == undefined)
			{
				stockphoto.core.log.logString( 2,"missing resolutionXML[" + k + "]!!");
				return null;
			}
			var resolutionXML = cartItem[k + 2].split("&&");
				
			for (var l = 0; l < resolutionXML.length; l++)
			{
				var resolutionItem = new Array(2);
				var pIndex = resolutionXML[l].indexOf("=");
				resolutionItem[0] = resolutionXML[l].slice(0, pIndex);
				resolutionItem[1] = unescape(resolutionXML[l].slice(pIndex + 1, resolutionXML[l].length));

				with (stockphoto.addToCart.LSCKeywords)
				{
					if (resolutionItem[0] == PurchaseID)
					{
						cartObject.resolutionXMLPurchaseID[k] = resolutionItem[1];
					}
					else if (resolutionItem[0] == Description)
					{
						cartObject.resolutionXMLDescription[k] = stockphoto.DL.MiscDlgs.DecodeXMLString(resolutionItem[1]);
					}
					else if (resolutionItem[0] == Price)
					{
						cartObject.resolutionXMLPrice[k] = resolutionItem[1];
					}
					else if (resolutionItem[0] == Signature)
					{
						cartObject.signature[k] = resolutionItem[1];
					}
					else if (resolutionItem[0] == Algorithm)
					{
						cartObject.algorithm[k] = resolutionItem[1];
					}
					else if (resolutionItem[0] == ExpirationDate)
					{
						cartObject.expirationDate[k] = resolutionItem[1];
					}
				}
			}
		}
		return cartObject;
	}
	catch (e)
	{
		stockphoto.core.log.logString( 2,"Exception in LSCConvertItem2Object" );
		return null;
	}
}

stockphoto.addToCart.LSCReplaceItem = function(cartItem)
{
	try
	{
		var itemIndex = stockphoto.addToCart.LSCGetItemCount();
		var propertyName = stockphoto.addToCart.LSCGetMediaKey(itemIndex);
		app.preferences[propertyName] = cartItem[0];

		var propertyName = stockphoto.addToCart.LSCGetResolutionsCountKey(itemIndex);
		app.preferences[propertyName] = cartItem[1];

		for (var i = 0; i < cartItem[1]; i++)
		{
			propertyName = stockphoto.addToCart.LSCGetResolutionsKey(itemIndex, i);
			app.preferences[propertyName] = cartItem[ i + 2];
		}

		propertyName = stockphoto.addToCart.LSCGetThumbnailFilePathKey(itemIndex);
		app.preferences[propertyName] = cartItem[cartItem[1] + 2];

		propertyName = stockphoto.addToCart.LSCGetItemStatusKey(itemIndex);
		if (cartItem[cartItem[1] + 3] != undefined)
		{
			app.preferences[propertyName] = cartItem[cartItem[1] + 3] ;
		}
		else
		{
			app.preferences[propertyName] = "";
		}

		app.preferences.bm_ShoppingCartCount += 1;

	}
	catch (e)
	{
		stockphoto.core.log.logString( 2,"Exception in stockphoto.addToCart.LSCReplaceItem" );
	}
}

stockphoto.addToCart.LSCGetItem = function(index)
{
	try
	{
		var propertyName = stockphoto.addToCart.LSCGetResolutionsCountKey(index);
		var cart = {};
		cart[1] = app.preferences[propertyName];

		for (var i = 0; i < cart[1]; i++)
		{
			propertyName = stockphoto.addToCart.LSCGetResolutionsKey(index, i);
			cart[ i + 2] = app.preferences[propertyName];
		}
		propertyName = stockphoto.addToCart.LSCGetMediaKey(index);
		cart[0] = app.preferences[propertyName];

		propertyName = stockphoto.addToCart.LSCGetThumbnailFilePathKey(index);
		cart[cart[1] + 2] = app.preferences[propertyName];

		propertyName = stockphoto.addToCart.LSCGetItemStatusKey(index);
		cart[cart[1] + 3] = app.preferences[propertyName];

		return cart;
	}
	catch (e)
	{
		stockphoto.core.log.logString( 2,"Exception in stockphoto.addToCart.LSCGetItem" );
		return null;
	}
}

stockphoto.addToCart.LSCRemoveItem = function(index, deleteFile)
{
	try
	{
		var propertyName = stockphoto.addToCart.LSCGetMediaKey(index);
		if (app.preferences[propertyName] != undefined)
		{
			app.preferences[propertyName] = "";
			app.preferences.clear(propertyName);
		}

		propertyName = stockphoto.addToCart.LSCGetResolutionsCountKey(index);
		for (var i = 0; i < app.preferences[propertyName]; i++)
		{
			var propertyName1 = stockphoto.addToCart.LSCGetResolutionsKey(index, i);
			if (app.preferences[propertyName1] == undefined)
			{
				break; 
			}
			app.preferences[propertyName1] = "";
			app.preferences.clear(propertyName1);
		}
		app.preferences[propertyName] = "";
		app.preferences.clear(propertyName);
	
		propertyName = stockphoto.addToCart.LSCGetThumbnailFilePathKey(index);
		if (deleteFile)
		{
			var f = File(app.preferences[propertyName]);
			f.remove();
		}
		app.preferences[propertyName] = "";
		app.preferences.clear(propertyName);

		propertyName = stockphoto.addToCart.LSCGetItemStatusKey(index);
		app.preferences[propertyName] = "";
		app.preferences.clear(propertyName);
	}
	catch (e)
	{
		stockphoto.core.log.logString( 2,"Exception in stockphoto.addToCart.LSCRemoveItem" );
	}
}

stockphoto.addToCart.LSCGetItemFlag = function(index)
{
	try
	{
		var propertyName = stockphoto.addToCart.LSCGetItemStatusKey(index);
		return  app.preferences[propertyName];
	}
	catch (e)
	{
		stockphoto.core.log.logString( 2,"Exception in stockphoto.addToCart.LSCGetItemFlag" );
		return "undefined";
	}
}

stockphoto.addToCart.LSCSetItemFlag = function(index, flag)
{
	try
	{
		var propertyName = stockphoto.addToCart.LSCGetItemStatusKey(index);
		app.preferences[propertyName] = flag;
	}
	catch (e)
	{
		stockphoto.core.log.logString( 2,"Exception in stockphoto.addToCart.LSCSetItemFlag" );
	}
}

stockphoto.addToCart.LSCClearAllItemFlag = function(flag)
{
	var count = stockphoto.addToCart.LSCGetItemCount();
	var itemFlag;

	for (var i = 0; i < count; i++)
	{
		itemFlag = stockphoto.addToCart.LSCGetItemFlag(i);
		if (itemFlag == flag)
		{
			stockphoto.addToCart.LSCSetItemFlag(i, "");
		}
	}
}

stockphoto.addToCart.LSCRemoveAllItems = function()
{
	var count = stockphoto.addToCart.LSCGetItemCount();
	for (var i = 0; i < count; i++)
	{
		stockphoto.addToCart.LSCRemoveItem(i, true);
	}
	app.preferences.bm_ShoppingCartCount = 0;
}

stockphoto.addToCart.LSCGetStockPhotoMetadata = function(cartItemIdx, params)
{
	var cartItem = stockphoto.addToCart.LSCGetItem(cartItemIdx);
	var cartObj = stockphoto.addToCart.LSCConvertItem2Object(cartItem);
	var suffix = 0;
	
	with (stockphoto.addToCart.LSCKeywords)
	{
		params["StockPhotoMetadata" + suffix++] = "KindOfImage/Comp";
		params["StockPhotoMetadata" + suffix++] = MediaID + "/" + cartObj.mediaXMLMediaID;
		params["StockPhotoMetadata" + suffix++] = "Sequence/   1";
		params["StockPhotoMetadata" + suffix++] = LanguageID + "/" + cartObj.mediaXMLLanguageID;
		params["StockPhotoMetadata" + suffix++] = ASPRefID + "/" + cartObj.mediaXMLASPRefID;
		params["StockPhotoMetadata" + suffix++] = MediaTitle + "/" + cartObj.mediaXMLMediaTitle;
		params["StockPhotoMetadata" + suffix++] = PartnerName + "/" + cartObj.mediaXMLPartnerID;
		params["StockPhotoMetadata" + suffix++] = Version + "/" + cartObj.mediaXMLVersion;
	}
}

stockphoto.addToCart.AddGroupThumbsToCartObject = function(onCompleteConfirm)
{
	this.getShoppingCartDocID = function()
	{
		var shoppingCartDocID = 0;
		try
		{
			var docs = app.documents;
			var tempDoc;

			for (i = 0; i < docs.length; i++)
			{
				tempDoc = docs[i];

				if (tempDoc == undefined)
				{
					stockphoto.core.log.logString( 0, "[ADD2CART] Can not get document from doc_id :" + i );
					continue;
				}

				stockphoto.core.log.logString( 0, "[ADD2CART] doc_id : " + tempDoc.id + " thumbnail.displayPath : " + stockphoto.core.util.getDisplayPath(tempDoc.thumbnail,""));
//				if ((tempDoc.thumbnail.displayPath.indexOf(stockphoto.core.consts.ShoppingCartName) > 0) &&
				if (( ( stockphoto.core.util.getDisplayPath( tempDoc.thumbnail, "getShoppingCartDocID()" ) ).indexOf(stockphoto.core.consts.ShoppingCartName) > 0) &&
					(tempDoc.thumbnail.displayMode == "web"))
				{
					shoppingCartDocID = tempDoc.id;
					tempDoc.visible = true;
					app.bringToFront();
					app.scheduleTask("stockphoto.shoppingCart.shoppingCart_Body( false, "+shoppingCartDocID+" )", 0, false);
					break;
				}
			}
		}
		catch (e)
		{
			stockphoto.core.log.logString( 2,"Exception in this.getShoppingCartDocID" );
		}
		return shoppingCartDocID;
	}

	this.stringSplit = function(inputStr, splitStr)
	{
		var resultArray = new Array(2);
		try
		{
			var index = inputStr.indexOf(splitStr);
			resultArray[0] = inputStr.slice(0, index);
			resultArray[1] = inputStr.slice(index + 1, inputStr.length);
		}
		catch (e)
		{
			stockphoto.core.log.logString( 2,"Exception in this.stringSplit, inputStr=" +inputStr+ " splitStr=" +splitStr);
		}
		return resultArray;
	}

	this.checkComplete = function(event, add2Cart, caller, addSuccess)
	{
		if ((add2Cart.addToCartIndex + 1) < add2Cart.addToCartCount)
		{ 
			add2Cart.addToCartIndex++;
			return
		}

        stockphoto.NavExtFnc.HideWheelFromES(caller.doc_id);
        // Turn off SpiningWheel
        stockphoto.DL.NavBar.SpiningWheelOff(caller.doc_id);

		if (!caller.replace)
		{
			 var successItems =  add2Cart.addToCartCount - add2Cart.dupItems - add2Cart.errorItems;
			 var imageTitleStr = add2Cart.successItemName;

			 if ((successItems > 0) || (add2Cart.dupItems) || addSuccess)
			 {
				 // if already in the shopping cart view, do not ask, update shopping cart 
				 var shoppingCartDocID = caller.sender.getShoppingCartDocID();
				 if (shoppingCartDocID == 0)
				 {
					stockphoto.DL.confirmationBox(0, successItems, imageTitleStr, caller.onCompleteConfirm, 
						add2Cart.dupItems, add2Cart.dupItemName, caller.doc_id);
					// Free request data object
					stockphoto.addToCart.requests[caller.reqID] = undefined;
				 }
			 }
		}
		else
		{
			 app.scheduleTask("stockphoto.shoppingCart.shoppingCartNewPrice(" + caller.firstTime + "," +caller.doc_id+  ")", 0, false);
			 // Free request data object
			 stockphoto.addToCart.requests[caller.reqID] = undefined;
		}
		if( stockphoto.Burp.doIt ) { // add-cart && caller.replace
/*B*/		try
/*B*/		{
/*B*/           stockphoto.Burp.checkSc( app.document.id ); // check.complete 
/*B*/		} catch(e) { ; }
		}
	}

	this.handleError = function(event, add2Cart, caller)
	{
		try
		{
			add2Cart.errorItems++;
			var zc = stockphoto.addToCart.zc;

			// can noot found item from partner web server. error  /*ERROR_WEBSERVICE_NOTFOUND*/
			if ((caller.replace) && ( event.message == (stockphoto.alertBox.webServiceComponentID+11) ))
			{
				stockphoto.addToCart.LSCSetItemFlag (caller.cartIndex, stockphoto.addToCart.LSCKeywords.ItemRemoved);
			}
			else if (stockphoto.DL.alertBox( event.message ) == false)
			{
				stockphoto.DL.generalAlertBox(stockphoto.alertBox.localizedStr4ErrMsg.MESSAGE_ES_ERROR_OCCURED, 2);
			}

			caller.sender.checkComplete(event, add2Cart, caller, false);
		}
		catch(e)
		{
			stockphoto.core.log.logString( 2,"Exception in this.handleError" );
		}		  
	}


	this.parsePartnerData = function(event, add2Cart, caller)
	{
		try
		{
			add2Cart.resolutionXMLPath = event.path;
			var infoFilePath = add2Cart.resolutionXMLPath.slice(0, add2Cart.resolutionXMLPath.lastIndexOf(".")) + ".txt";
			var infoFile	 = new File(infoFilePath);
			stockphoto.core.log.logString( 0,infoFile.fsName );
			thumbnailFile = caller.sourcePath;
			
			// Parse the resolution text file to get the data
			if (!infoFile.exists)
			{
				throw("error");
			}

			infoFile.open("r");

			// handle the first line - MediaXML
			line = infoFile.readln();
			parametersArray = line.split("&");
			for (var j = 0; j < parametersArray.length; j++)
			{
				var OneParam = new Array(2);
				var pIndex = parametersArray[j].indexOf("=");
				OneParam[0] = parametersArray[j].slice(0, pIndex);
				OneParam[1] = parametersArray[j].slice(pIndex + 1, parametersArray[j].length);

				with (stockphoto.addToCart.LSCKeywords)
				{
					if (OneParam[0] == MediaTitle)  
					{
						add2Cart.mediaTitleStr = OneParam[1];
					}
					else if (OneParam[0] == PartnerID)
					{
						add2Cart.partnerIDStr  = OneParam[1];
					}
					else if (OneParam[0] == MediaID)
					{
						add2Cart.mediaIDStr	= OneParam[1];
					}
					else if (OneParam[0] == Version)
					{
						add2Cart.mediaXMLVerStr = OneParam[1];
					}
					else if (OneParam[0] == LanguageID)
					{
						add2Cart.languageIDStr = OneParam[1];
						// default to en-US
						if (add2Cart.languageIDStr.length == 0)
						{
							add2Cart.languageIDStr = "en-US";
						}
					}
				}
			}
			
			// Now populate the ASP Ref ID
			if (stockphoto.core.ImageID.ID != stockphoto.core.ImageIDs.MediaID)
				add2Cart.ASPRefIDStr = stockphoto.core.getASPRefFromPartner(add2Cart.partnerIDStr,add2Cart.mediaIDStr);

			// handle rest lines - ResolutionXML
			if (infoFile.eof)
			{
				throw("error");
			}
			
			while (!infoFile.eof)
			{
			    line = infoFile.readln();
				parametersArray = line.split("&&");
				for (var j = 0; j < parametersArray.length; j++)
				{
					var OneParam = caller.sender.stringSplit(parametersArray[j], "=");
			
					with (stockphoto.addToCart.LSCKeywords)
					{
						if (OneParam[0] == PurchaseID)
						{
							add2Cart.imagePurchaseID[add2Cart.totalResolutions] = OneParam[1];
						}
						else if (OneParam[0] == Description)
						{
							add2Cart.imageDescStr[add2Cart.totalResolutions]	= OneParam[1];
						}
						else if ((OneParam[0] == Currency) || (OneParam[0] == Price))  // do not know which one comes first
						{
							var CurrencyPrice = caller.sender.stringSplit(parametersArray[j], "&");
							var currencyArray = caller.sender.stringSplit(CurrencyPrice[0], "=");
							var priceArray	  = caller.sender.stringSplit(CurrencyPrice[1], "=");
							if (currencyArray[0] == Currency)
							{
								add2Cart.imageCurrencyTypeStr[add2Cart.totalResolutions]   = currencyArray[1];
							}
							if (priceArray[0] == Price)
							{
								add2Cart.imagePriceStr[add2Cart.totalResolutions]   = priceArray[1];
							}
							if (currencyArray[0] == Price)
							{
								add2Cart.imagePriceStr[add2Cart.totalResolutions]   = currencyArray[1];
							}
							if (priceArray[0] == Currency)
							{
								add2Cart.imageCurrencyTypeStr[add2Cart.totalResolutions]   = priceArray[1];
							}
						}
						else if ((OneParam[0] == Algorithm) || (OneParam[0] == Signature))  // do not know which one comes first
						{
							var AlgorithmSign = caller.sender.stringSplit(parametersArray[j], "&");
							var firstArray		= caller.sender.stringSplit(AlgorithmSign[0], "=");
							var secondArray   = caller.sender.stringSplit(AlgorithmSign[1], "=");
							if (firstArray[0]  == Algorithm)
							{
								add2Cart.algorithmStr[add2Cart.totalResolutions]   = firstArray[1];
							}
							if (secondArray[0] == Signature)
							{
								add2Cart.signatureStr[add2Cart.totalResolutions]   = secondArray[1];
							}
							if (firstArray[0]  == Signature)
							{
								add2Cart.signatureStr[add2Cart.totalResolutions]   = firstArray[1];
							}
							if (secondArray[0] == Algorithm)
							{
								add2Cart.algorithmStr[add2Cart.totalResolutions]   = secondArray[1];
							}
						}
						else if (OneParam[0] == ExpirationDate)
						{
							add2Cart.expirationDateStr[add2Cart.totalResolutions]   = OneParam[1];
						}
					}
				}
				add2Cart.totalResolutions += 1;
			}
			infoFile.close();
			infoFile.remove();
				
			// only check first currency type in array
			if (stockphoto.DL.getCurrencyType() != add2Cart.imageCurrencyTypeStr[0])
			{
				var zc = stockphoto.addToCart.zc;
				stockphoto.DL.generalAlertBox(zc.get("$$$/AddToCart/Alert/PartnerCurrencyMissMatch=Error adding image to cart. Preference's Billing Country or Region does not match Stock Photos Partner Billing Country or Region."), 2);

				stockphoto.core.log.logString( 2,"Billing Country setting does not match partner's Billing Country.");
				return false;
			}
			return true;

		}
		catch (e)
		{
			stockphoto.core.log.logString( 2,"Exception in this.parsePartnerData" );
			return false;
		}
	}


	this.alreadyAdded = function(event, add2Cart, caller)
	{
		// Check existing item
		try
		{
			var ret = false;
			var count = stockphoto.addToCart.LSCGetItemCount();
			var cartItem, cartObject;

			if (!caller.replace)
			{
				// Check to see if the item already added in the cart
				for (var i = 0; i < count; i++) 
				{
					cartItem = stockphoto.addToCart.LSCGetItem(i);
					cartObject = stockphoto.addToCart.LSCConvertItem2Object(cartItem);
					if ((cartObject.mediaXMLMediaID == add2Cart.mediaIDStr) &&
						(cartObject.mediaXMLPartnerID == add2Cart.partnerIDStr))
					{
						add2Cart.dupItems++;
						add2Cart.dupItemName = add2Cart.mediaTitleStr;

						caller.sender.checkComplete(event, add2Cart, caller, true);
						return true;
					}
				}
			}
			else 
			{
				// Check to see if the price is realy changed.
				add2Cart.newPrice = false;

				if ((caller.cartIndex >= count) || (caller.cartIndex < 0))
				{
					throw("error");
				}
				var oldCartItem = stockphoto.addToCart.LSCGetItem(caller.cartIndex);
				var oldCartObj  = stockphoto.addToCart.LSCConvertItem2Object(oldCartItem);
				   
				// save old user selections index for refreshed price info.
				caller.oldPurchaseIDIdx = 0;
				for (i = 0; i < oldCartObj.resolutionXMLPurchaseID.length; i++)
				{
					if (oldCartObj.selectedPurchaseID == oldCartObj.resolutionXMLPurchaseID[i])
					{
						caller.oldPurchaseIDIdx = i;
						break;
					}
				}
				if (caller.oldPurchaseIDIdx >= add2Cart.totalResolutions)
				{
					caller.oldPurchaseIDIdx = 0;
				}
				if ( add2Cart.totalResolutions == oldCartObj.resolutionXMLPrice.length)
				{
					for (var i = 0; i < add2Cart.totalResolutions; i++)
					{
						if (oldCartObj.resolutionXMLPrice[i] != add2Cart.imagePriceStr[i])
						{
							add2Cart.newPrice = true;
							break;
						}
					}					
				}
				else
				{
					add2Cart.newPrice = true;
				}
			}
		}
		catch (e)
		{
			stockphoto.core.log.logString( 2,"Exception in this.alreadyAdded" );
			return true;
		}
		
		return false;
	}

	this.addTheItemToCart = function(event, add2Cart, caller)
	{
		// Add the item into cart
		try
		{
			var itemIndex;
			var propertyName;
			with (stockphoto.addToCart.LSCKeywords)
			{
				var  tempStr =   Version + "=" + escape(add2Cart.mediaXMLVerStr) +
					"&" + MediaID + "=" + escape(add2Cart.mediaIDStr) +
					"&" + PartnerID + "=" + escape(add2Cart.partnerIDStr) +
					"&" + ASPRefID + "=" + escape(add2Cart.ASPRefIDStr) +
					"&" + MediaTitle + "=" + escape(add2Cart.mediaTitleStr);
				if (caller.replace)
				{
					itemIndex = caller.cartIndex;
					propertyName = stockphoto.addToCart.LSCGetMediaKey(itemIndex);
					app.preferences[propertyName] = tempStr +
						"&" + PurchaseID + "=" + escape(add2Cart.imagePurchaseID[ caller.oldPurchaseIDIdx]) +
						"&" + Price + "=" + escape(add2Cart.imagePriceStr[caller.oldPurchaseIDIdx]) +
						"&" + Currency + "=" + escape(add2Cart.imageCurrencyTypeStr[caller.oldPurchaseIDIdx]) +
						"&" + LanguageID + "=" + escape(add2Cart.languageIDStr);
				}
				else
				{
					itemIndex = stockphoto.addToCart.LSCGetItemCount();
					propertyName = stockphoto.addToCart.LSCGetMediaKey(itemIndex);
					app.preferences[propertyName] = tempStr +
						"&" + PurchaseID + "=" + escape(add2Cart.imagePurchaseID[ add2Cart.priceIndex]) +
						"&" + Price + "=" + escape(add2Cart.imagePriceStr[add2Cart.priceIndex]) +
						"&" + Currency + "=" + escape(add2Cart.imageCurrencyTypeStr[add2Cart.priceIndex]) +
						"&" + LanguageID + "=" + escape(add2Cart.languageIDStr);
				}
			}

			propertyName = stockphoto.addToCart.LSCGetItemStatusKey(itemIndex);
			if (caller.replace && add2Cart.newPrice)
			{
				app.preferences[propertyName] = escape(stockphoto.addToCart.LSCKeywords.NewPrice);
			}
			else
			{
				app.preferences[propertyName] = "";
			}

			propertyName = stockphoto.addToCart.LSCGetResolutionsCountKey(itemIndex);
			app.preferences[propertyName] = add2Cart.totalResolutions;
		
			for (var i = 0; i < add2Cart.totalResolutions; i++)
			{
				if ((add2Cart.imagePurchaseID[i] == undefined) || (add2Cart.imagePriceStr[i]   == undefined))
				{
					break;
				}
				propertyName = stockphoto.addToCart.LSCGetResolutionsKey(itemIndex, i);
				with (stockphoto.addToCart.LSCKeywords)
				{
					app.preferences[propertyName] = PurchaseID + "=" + escape(add2Cart.imagePurchaseID[i]) +
						"&&" + Description + "=" + escape(add2Cart.imageDescStr[i]) +
						"&&" + Price + "=" + escape(add2Cart.imagePriceStr[i]) +
						"&&" + Signature + "=" + escape(add2Cart.signatureStr[i]) +
						"&&" + Algorithm + "=" + escape(add2Cart.algorithmStr[i]) +
						"&&" + ExpirationDate + "=" + escape(add2Cart.expirationDateStr[i]);
				}
			}

			var normTileName = stockphoto.core.util.normalizeFileName(thumbnailFile);
			var destFile = File(stockphoto.core.folder.getMyShoppingCartFolder() + "/" + normTileName.name);
			if (!caller.replace)
			{
				thumbnailFile.copy(destFile);
			}

			propertyName = stockphoto.addToCart.LSCGetThumbnailFilePathKey(itemIndex);
			app.preferences[propertyName] = escape(destFile.fsName);
		
			if (!caller.replace) 
			{			 
				app.preferences.bm_ShoppingCartCount += 1;
				add2Cart.successItemName = add2Cart.mediaTitleStr;
			}
				
			caller.sender.checkComplete(event, add2Cart, caller, true);
		}
		catch (e)
		{
			stockphoto.core.log.logString( 2,"Exception when adding to shopping cart" );  
		}
	}

	this.initTempData = function(add2Cart)
	{
		add2Cart.mediaIDStr	= "";
		add2Cart.ASPRefIDStr = "";
		add2Cart.partnerIDStr	= "";
		add2Cart.mediaTitleStr	= "";
		add2Cart.mediaXMLVerStr	= "";
		add2Cart.languageIDStr	= "";
		add2Cart.imagePurchaseID	= {};
		add2Cart.imageDescStr		= {};
		add2Cart.imagePriceStr		= {};
		add2Cart.imageCurrencyTypeStr = {};
		add2Cart.signatureStr		= {};
		add2Cart.algorithmStr		= {};
		add2Cart.expirationDateStr	= {};
		add2Cart.totalResolutions	= 0;
		add2Cart.newPrice		= false;
		add2Cart.resolutionXMLPath	= "";
	}

	this.getInfo_AddGroupThumbsEventHandler = function(event)
	{
		stockphoto.core.log.logString( 0,"[ADD2CART]  Enter GetInfo_AddGroupThumbsEventHandler  "  );
		stockphoto.core.log.logString( 0,event.eventClass + ":" + event.eventName );

		var currDoc = stockphoto.documents[this.doc_id].document;
		var add2Cart = stockphoto.addToCart.requests[this.reqID];

		this.sender.initTempData(add2Cart);

		if ((event.eventName == "status")  && (event.status == "error"))
		{
		    stockphoto.impl.deleteGetInfo(this.sourcePath, "" + this.reqID);
			this.sender.handleError(event, add2Cart, this);
			stockphoto.core.checkProxyOnFail();
			return;
		}
		
		if (event.eventName == "complete")
		{
			stockphoto.core.log.logString( 0, event.path );
			stockphoto.impl.deleteGetInfo(this.sourcePath, "" + this.reqID);
			if ( this.sender.parsePartnerData(event, add2Cart, this) == false)
			{
				add2Cart.errorItems++;
				this.sender.checkComplete(event, add2Cart, this, false);
				return;
			}
			
			if ( this.sender.alreadyAdded(event, add2Cart, this) == true)
			{
				return;
			}

			this.sender.addTheItemToCart(event, add2Cart, this);
			return;
		}
	}
	
	// if replace is true, the cart item pointed by index will be replaced 
	// Otherwise, a new cart item will be added at the bottom.

	this.getThumbInfo = function(thumbPath, replace, index, firstTime, doc_id, reqID, async)
	{
		// For Version Cue and PhotoShop file, We use this image in the shopping cart html
		var defaultImg = "img_not_avail_50x50.jpg";
		var currentDate = new Date();
		var mediaID = "" + Math.floor(currentDate.getTime() /1000); 
		var mediaIDBegin = -1;

		// Get billing country
		stockphoto.DL.demandJsxLoading( stockphoto.DL.jsx_LangCountry );
		var billingCountry = stockphoto.core.BoxCar.LangCountry.getBillingCountry();
		var params =
		{
			BillingCountry: billingCountry
		};

		var xtension = stockphoto.core.util.getExtension(thumbPath);
		xtension = unescape(xtension);

		var sourcePath = File(thumbPath);
		var thumbPathString = sourcePath.name;
		var isDefaultImg = (thumbPathString.indexOf(defaultImg) >= 0);

		if (replace && (isDefaultImg || (!sourcePath.exists)))
		{
			stockphoto.addToCart.LSCGetStockPhotoMetadata(index, params);
		}
		else
		{
			// the last parameter set to "true" to use Thumbnail.synchronousMetadata method in Bridge 522 or later.
			stockphoto.core.util.addStockPhotoMetadata(thumbPath, params, true);
		}
		
		var tempFolderPath = stockphoto.core.folder.getTempFolder()+"/"+stockphoto.core.CurrentProcessID;
		var tempFolder = new Folder( tempFolderPath );
		if ( !stockphoto.core.folder.checkAndCreateFolder( tempFolder, false ) )
		{
			stockphoto.core.log.logString( 0, "[ADD2CART] Can not create temp folder : " + tempFolderPath);
			stockphoto.DL.generalAlertBox(stockphoto.alertBox.localizedStr4ErrMsg.ERROR_CORE_CANT_CREATE_DIR, 2);
			return;
		}

		if ( (!sourcePath.exists) || (xtension.toLowerCase() != "jpg") )
		{
			var partnerName = Math.floor(currentDate.getTime() / 1000);
			var partnerNameBegin = -1;

			for (item in params)
			{
				mediaIDBegin = params[item].indexOf(stockphoto.addToCart.LSCKeywords.MediaID);
				if (mediaIDBegin >= 0)
				{
					mediaIDBegin += (stockphoto.addToCart.LSCKeywords.MediaID.length + 1);
					mediaID = params[item].slice(mediaIDBegin, params[item].length);
				}

				partnerNameBegin = params[item].indexOf(stockphoto.addToCart.LSCKeywords.PartnerName);
				if (partnerNameBegin >= 0)
				{
					partnerNameBegin += (stockphoto.addToCart.LSCKeywords.PartnerName.length + 1);
					partnerName = params[item].slice(partnerNameBegin, params[item].length);
					// Remove spaces inbetween the name
					var names = partnerName.split(" ");
					partnerName = "";
					for (var n in names)
					{
						partnerName += names[n];
					}
				}
			}

			inFile  = File(unescape( stockphoto.core.folder.getTemplateFolder()+"/images/ShopCart/" + defaultImg ));
			outFile = File(unescape( tempFolderPath + "/" + partnerName + "-" + mediaID + "-" + defaultImg ));
			inFile.copy(outFile);
			sourcePath = outFile;

			params["GetThumbForDefaultImage"] = outFile.fsName;
		}

		var fileName   = sourcePath.name;
		var baseName   = unescape(fileName.slice(0, fileName.lastIndexOf(".")));
		var sReqID     = "" + reqID; // reqID as string - for convenience in C++ handling

		var iRequest   =
		{
			params:		params,
			sourcePath:	sourcePath,
			folder:		tempFolder,
			baseName:	baseName, 
			replace:	replace,
			firstTime:	firstTime,
			cartIndex:	index,
			sender:		this,
			doc_id:		doc_id,
			reqID:		reqID,
			sReqID:     sReqID,
			eventHandler:	this.getInfo_AddGroupThumbsEventHandler,
			onCompleteConfirm: onCompleteConfirm
		};
		
		if ( ("undefined" != typeof async) && (true == async) )
		{
            iRequest.async = true;
        }
		
        stockphoto.core.SendProxyCredentials();
        stockphoto.impl.getInfo(iRequest);
	}
}

//---------------------------------------------------------
// st01_AddToCart
//

stockphoto.addToCart.initRequestObj = function( itemCount, priceIndex)
{
	var reqID = -1;
	
	with (stockphoto.addToCart)
	{
		for (var i = 0; i < requestIndex; i++)
		{
			if (requests[i] == undefined)
			{
				reqID = i;
				break;
			}
		}
		
		if (reqID == -1)
		{
			reqID = requestIndex;
			requestIndex++;
		}

		stockphoto.core.log.logString( 0,"[ADD2CART]  Request Index : " + reqID );

		requests[reqID] = {};
		requests[reqID].addToCartCount = itemCount;
		requests[reqID].addToCartIndex = 0;
		requests[reqID].dupItems = 0;
		requests[reqID].errorItems = 0;
		requests[reqID].dupItemName = "";
		requests[reqID].successItemName = "";
		requests[reqID].priceIndex = priceIndex;
	}
	return reqID;
}

stockphoto.addToCart.DoAddGroupThumbsToCartFree = function( doc_id )
{	// Called only when stockphoto.addToCart.temp != undefined
	var i, n;
	if( stockphoto.addToCart.temp[ doc_id ] != undefined )
	{
		if( stockphoto.addToCart.temp[doc_id].thumbPathArray != undefined )
		     n = stockphoto.addToCart.temp[doc_id].thumbPathArray.length;
		else n = -1;
		if( stockphoto.addToCart.temp[doc_id].AddGroupThumbsObj != undefined )
		{
			for( i=0; i<n; i++ )
			{
				if( stockphoto.addToCart.temp[ doc_id ].AddGroupThumbsObj[ i ] != undefined )
					delete stockphoto.addToCart.temp[ doc_id ].AddGroupThumbsObj[ i ];
				stockphoto.addToCart.temp[ doc_id ].AddGroupThumbsObj[ i ] = [];
			} 
			delete stockphoto.addToCart.temp[ doc_id ].AddGroupThumbsObj;
			stockphoto.addToCart.temp[ doc_id ].AddGroupThumbsObj = undefined;
		}
		if( n > 0 )
		{
			stockphoto.addToCart.temp[doc_id].thumbPathArray.splice( 0, n );
		}
		stockphoto.addToCart.temp[doc_id].thumbPathArray    = undefined;
		stockphoto.addToCart.temp[doc_id].onCompleteConfirm = undefined;
		stockphoto.addToCart.temp[doc_id].reqID             = undefined;

		stockphoto.addToCart.temp.splice( doc_id, 1 );
		stockphoto.addToCart.temp[ doc_id ]  = undefined;
	}
}

stockphoto.addToCart.DoAddGroupThumbsToCartIterate = function( priceIndex, doc_id, i, iMax )
{
	var script;
	if( i < 0 )
	{
		if( stockphoto.addToCart.temp == undefined )
			stockphoto.addToCart.temp  = [];
		if( stockphoto.addToCart.temp[doc_id] != undefined )
		{
			stockphoto.addToCart.DoAddGroupThumbsToCartFree( doc_id );
		}
		stockphoto.addToCart.temp[doc_id]                  ={};
		stockphoto.addToCart.temp[doc_id].thumbPathArray   =undefined; // array
		stockphoto.addToCart.temp[doc_id].onCompleteConfirm=undefined;
		stockphoto.addToCart.temp[doc_id].AddGroupThumbsObj=undefined; // array
		stockphoto.addToCart.temp[doc_id].reqID            =undefined;
		
		stockphoto.core.log.logString( 0,"[ADD2CART]  Enter DoAddGroupThumbsToCart, doc_id : " + doc_id );

		stockphoto.addToCart.temp[doc_id].thumbPathArray    = stockphoto.documents[doc_id].thumbPathArray;
		stockphoto.addToCart.temp[doc_id].onCompleteConfirm = stockphoto.documents[doc_id].onCompleteConfirm;

		stockphoto.addToCart.temp[doc_id].AddGroupThumbsObj = new Array( stockphoto.addToCart.temp[doc_id].thumbPathArray.length );	
		stockphoto.addToCart.temp[doc_id].reqID             = stockphoto.addToCart.initRequestObj( stockphoto.addToCart.temp[doc_id].thumbPathArray.length, priceIndex );
		script = "stockphoto.addToCart.DoAddGroupThumbsToCartIterate("+priceIndex+","+doc_id+",0,"+stockphoto.addToCart.temp[doc_id].thumbPathArray.length+");\n";
		var zc = stockphoto.addToCart.zc;
		stockphoto.DL.NavBar.SpiningWheelOn(zc.get("$$$/AddToCart/Text/AddingToShoppingCart=Adding to Shopping Cart..."), doc_id );
		app.scheduleTask( script, 100, false );
	}
	else if( i < iMax )
	{
		stockphoto.addToCart.temp[doc_id].AddGroupThumbsObj[i] = new stockphoto.addToCart.AddGroupThumbsToCartObject( stockphoto.addToCart.temp[doc_id].onCompleteConfirm );
        stockphoto.addToCart.temp[doc_id].AddGroupThumbsObj[i].getThumbInfo( stockphoto.addToCart.temp[doc_id].thumbPathArray[i], false, 0, true, doc_id, stockphoto.addToCart.temp[doc_id].reqID, true);
		script = "stockphoto.addToCart.DoAddGroupThumbsToCartIterate("+priceIndex+","+doc_id+","+(i+1)+","+iMax+");\n";
        if ((0 != i) && (i % 10 == 0))
        {
            app.scheduleTask( script, 2000, false ); // Wait for 2 seconds for every 10 getInfo requests so that we don't flood.
        }
        else
        {
            app.scheduleTask( script, 100, false );
        }
	}
}

stockphoto.addToCart.DoAddGroupThumbsToCart = function( priceIndex, doc_id )
{
	stockphoto.addToCart.DoAddGroupThumbsToCartIterate( priceIndex, doc_id, -1, 0 );
}

stockphoto.addToCart.AddGroupThumbsToCart_Body = function(thumbPathArray, priceIndex, onCompleteConfirm, doc_id)
{
	stockphoto.core.log.logString( 0,"[ADD2CART]  Enter AddGroupThumbsToCart_Body, doc_id : " + doc_id );

	if (doc_id == undefined)
	{
		doc_id = app.document.id;
	}
	else if (app.document.id != doc_id)
	{
		stockphoto.core.log.logString( 0,"[ADD2CART]  doc_id error in AddGroupThumbsToCart_Body, app.document.id : " + app.document.id );
	}

	// Turn on SpiningWheel
	var zc = stockphoto.addToCart.zc;
	stockphoto.DL.NavBar.SpiningWheelOn(zc.get("$$$/AddToCart/Text/AddingToShoppingCart=Adding to Shopping Cart..."), doc_id );

	stockphoto.documents[doc_id].thumbPathArray = thumbPathArray;
	stockphoto.documents[doc_id].onCompleteConfirm = onCompleteConfirm;

	var currDoc = stockphoto.documents[ doc_id ].document;
	if( currDoc != undefined )
	{
		app.bringToFront();
		if (currDoc.browserMode != "compact")
		{
			app.scheduleTask("stockphoto.addToCart.DoAddGroupThumbsToCart(" +priceIndex+ "," +doc_id+ ")", 1000, false);
		}
		else
		{
			stockphoto.addToCart.DoAddGroupThumbsToCart(priceIndex, doc_id);
		}
	}
}

stockphoto.addToCart.RefreshCartItemsPrice = function(thumbPathArray, itemsCount, priceIndex, firstTime, doc_id)
{
	stockphoto.core.log.logString( 0,"[ADD2CART]  Enter RefreshCartItemsPrice, doc_id : " + doc_id );

	if (doc_id == undefined)
	{
		doc_id = app.document.id;
	}

	var AddGroupThumbsObj = new Array(thumbPathArray.length);
	var reqID = stockphoto.addToCart.initRequestObj(itemsCount, priceIndex);
	
	for (i = 0; i < thumbPathArray.length; i++)
	{
		if (thumbPathArray[i] != undefined)
		{
			AddGroupThumbsObj[i] = new stockphoto.addToCart.AddGroupThumbsToCartObject(undefined);
			AddGroupThumbsObj[i].getThumbInfo(thumbPathArray[i], true, i, firstTime, doc_id, reqID);
		}
	}
}

stockphoto.addToCart.AddToCart_Body = function( doc_id )
{
	stockphoto.core.log.logString( 0,"[ADD2CART]  Enter AddToCart_Body, doc_id : " + doc_id );
	var j = 0;

	if (app.document.id != doc_id)
	{
		stockphoto.core.log.logString( 0,"[ADD2CART]  doc_id error in addToCart.AddToCart_Body, app.document.id : " + app.document.id );
	}

	var thumbArray = [];

	stockphoto.core.NavBar.SwitchNavBar( "st01_AddToCart", 0, 1, app.document );

    var oSel = app.document.selections;
    var iSelLength = app.document.selectionLength;
	for (var i = 0; i < iSelLength; i++)
	{
		if (File(oSel[i].path) instanceof File)
		{
			thumbArray[j] = oSel[i].path;
			j = j+1;
		}
	}
	var priceIndex = 0; // always default to first price index
	if (j > 0)
	{
		stockphoto.addToCart.AddGroupThumbsToCart_Body(thumbArray, priceIndex, undefined, doc_id);	  
	}
	else
	{
		stockphoto.DL.generalAlertBox(stockphoto.alertBox.localizedStr4ErrMsg.ERROR_CORE_CANT_OPEN_IMAGE_FILE, 2);
	}
}

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

