//
//-------------------------------------------------------------------
// Licensed Materials - Property of IBM
//
// WebSphere Commerce
//
// (c) Copyright IBM Corp. 2007
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//-------------------------------------------------------------------
//

ProductJS={
	entitledItems:[],
	selectedProducts:new Object(),
	selectedAttributes:new Object(),
	errorMessages: new Object(),
	langId: "-1",
	storeId: "",
	catalogId: "",
	storeField2:0,
	updateParamObject:function(params, key, value, toArray, index){
		// summary		: This function updates the given params object with Key value pair.
		// description	: This function updates the given params object with Key value pair.
		//				  If the toArray value is true, It creates an Array for duplicate entries.
		//				  else, It overwrites the old value.
		//				  It is useful while making a service call which excepts few paramters of type array
		// params		: JavaScript Object
		//				  It could be a JavaScript Object or JavaScript Array. JavaScript traats Array as Object only.
		// key			: String
		// value		: String
		// toArray		: Boolean
		//				  If true, creates an Array for duplicate entries
		//				  If false, does not creat an Array for duplicate entries. It overwrites the old value.
		// assumptions	: None.
		// dojo API		: None.
		// returns		: A JavaScript Object having key - value pair.
	   if(params == null){
		   params = [];
	   }

	   if(params[key] != null && toArray)
	   {
			if(dojo.lang.isArrayLike(params[key]))
			{
				//3rd time onwards
			    if(index != null && index != "")
				{
					//overwrite the old value at specified index
				     params[key][index] = value;
				}
				else
				{
				    params[key].push(value);
			     }
		    }
			else
			{
			     //2nd time
			     var tmpValue = params[key];
			     params[key] = [];
			     params[key].push(tmpValue);
			     params[key].push(value);
		    }
	   }
	   else
	   {
			//1st time
		   if(index != null && index != "" && index != -1)
		   {
		      //overwrite the old value at specified index
		      params[key+"_"+index] = value;
		   }
		   else if(index == -1)
		   {
		      var i = 1;
		      while(params[key + "_" + i] != null)
			  {
			       i++;
		      }
		      params[key + "_" + i] = value;
		   }
		   else
		   {
		      params[key] = value;
		    }
	   }
	   return params;
	 },
	setCommonParameters:function(langId,storeId,catalogId,storeField2){
		// summary		: This function initializes common parameters used in all service calls
		// description	: This function initializes storeId, catalogId, and langId.
		// langId	: The language id to use.
		// storeId : The store id to use.
		// catalog : The catalog id to use.
		this.langId = langId;
		this.storeId = storeId;
		this.catalogId = catalogId;
		this.storeField2=storeField2;
	},
	
	setEntitledItems : function(entitledItemArray){
		this.entitledItems = entitledItemArray;
	},

	setQuantityEntitledItems : function(quantityItemArray){
			for(x in this.entitledItems){
				for(y in quantityItemArray){
					 if(this.entitledItems[x].catentry_id == quantityItemArray[y].catentry_id){
						this.entitledItems[x].quantity=quantityItemArray[y].quantity;
						this.entitledItems[x].invflags=quantityItemArray[y].invflags;
						break;
					}
					
				}
			}
	},
	
	setPriceEntitledItems : function(priceItemArray){
			for(x in this.entitledItems){
				for(y in priceItemArray){
					 if(this.entitledItems[x].catentry_id == priceItemArray[y].catentry_id){
						this.entitledItems[x].price=priceItemArray[y].price;
						break;
					}
					
				}
			}
	},
	
	getQuantity : function(catId){
			for(x in this.entitledItems){
					 if(this.entitledItems[x].catentry_id == catId){
					 	return this.entitledItems[x].quantity;
					 }
			}
			return 0;
	},
	checkForStock : function(catId){
			for(x in this.entitledItems){
					 if(this.entitledItems[x].catentry_id == catId && (this.entitledItems[x].invflags == '1' || this.entitledItems[x].invflags =='2' )){
					 	return true;
						break;
	  				 }
			}
			return false;
	},
	checkForStockFlag: function(catId){
			for(x in this.entitledItems){
					 if(this.entitledItems[x].catentry_id == catId){
					 	return this.entitledItems[x].quantity;
						break;
	  				 }
	  		}
			return false;
	},
	
	checkForPrice: function(catId){
			for(x in this.entitledItems){
					 if(this.entitledItems[x].catentry_id == catId){
					 	return this.entitledItems[x].price;
						break;
	  				 }
	  		}
			return false;
	},
	
	setSelectedAttribute : function(selectedAttributeName , selectedAttributeValue){
		this.selectedAttributes[selectedAttributeName] = selectedAttributeValue;
		//if(this.getCatalogEntryId() != null){
			//if(this.checkForStock(this.getCatalogEntryId())){
				//document.getElementById("stockMessage").innerHTML=this.checkForStockFlag(this.getCatalogEntryId());
				//document.getElementById("stockPrice").innerHTML=this.checkForPrice(this.getCatalogEntryId());
				//dojo.html.show(document.getElementById("stockMessage"));
				//dojo.html.show(document.getElementById("addToCart")); 
				//dojo.html.hide(document.getElementById("showEmailStock")); 
				//dojo.html.show(document.getElementById("stockPrice"));
			//}
			//else {
					//document.getElementById("stockMessage").innerHTML=this.checkForStockFlag(this.getCatalogEntryId());
					//document.getElementById("stockPrice").innerHTML=this.checkForPrice(this.getCatalogEntryId());
					//dojo.html.hide(document.getElementById("addToCart"));
					//dojo.html.show(document.getElementById("stockMessage"));
					//dojo.html.show(document.getElementById("showEmailStock"));
					//dojo.html.show(document.getElementById("stockPrice"));
			//}
		//}
		
	},
	setSelectedAttributeOfProduct : function(productId,selectedAttributeName,selectedAttributeValue){
		
		selectedAttributesForProduct = new Object();

		if(this.selectedProducts[productId]) selectedAttributesForProduct = this.selectedProducts[productId];
		
		selectedAttributesForProduct[selectedAttributeName] = selectedAttributeValue;
		this.selectedProducts[productId] = selectedAttributesForProduct;
		
	},
	getCatalogEntryId : function(){
		var attributeArray = [];
		for(attribute in this.selectedAttributes){
			attributeArray.push(attribute + "_" + this.selectedAttributes[attribute]);
		}
		return this.resolveSKU(attributeArray);
	},
	getCatalogEntryIdforProduct : function(selectedAttributes){
		var attributeArray = [];
		for(attribute in selectedAttributes){
			attributeArray.push(attribute + "_" + selectedAttributes[attribute]);
		}
		return this.resolveSKU(attributeArray);
	},

	resolveSKU : function(attributeArray){
		//alert("Resolving SKU >> " + attributeArray +">>"+ this.entitledItems);
		var catentry_id = "";
		var attributeArrayCount = attributeArray.length;
		
		for(x in this.entitledItems){
			var catentry_id = this.entitledItems[x].catentry_id;
			var Attributes = this.entitledItems[x].Attributes;
			var attributeCount = 0;
			for(index in Attributes)
				attributeCount ++;

			if(attributeArrayCount >= attributeCount){
				var matchedAttributeCount = 0;

				for(attributeName in attributeArray){
					var attributeValue = attributeArray[attributeName];
					//alert(attributeName + ":" + attributeValue);
					if(attributeValue in Attributes){
						matchedAttributeCount ++;
					}
				}
				
				if(attributeCount == matchedAttributeCount){
					//alert("CatEntryId:" + catentry_id + " for Attribute: " + attributeArray);
					return catentry_id;
				}
			}
		}
		return null;
	},
	
	PopUpAdd2ShopCartAjax : function(entitledItemInbutBoxId){
		var params = [];
		var entitledItemJSON = eval('('+ dojo.byId(entitledItemInbutBoxId).innerHTML +')');
		this.setEntitledItems(entitledItemJSON);
		var catalogEntryId = this.getCatalogEntryId();

		if(catalogEntryId != null){
			params.storeId		= this.storeId;
			params.catalogId	= this.catalogId;
			params.langId			= this.langId;
			params.orderId		= ".";
			params.quantity		= "1";
			params.catEntryId	= catalogEntryId;
			wc.service.invoke("AjaxAddOrderItem", params);
			cursor_wait();
		}
		else{
			alert(this.getErrorMessage("ERR_RESOLVING_SKU"));
		}
	},

	PopUpAdd2WishListAjax : function(entitledItemInbutBoxId){
		var params = [];
		var entitledItemJSON = eval('('+ dojo.byId(entitledItemInbutBoxId).innerHTML +')');
		this.setEntitledItems(entitledItemJSON);
		var catalogEntryId = this.getCatalogEntryId();

		if(catalogEntryId != null){
			params.storeId		= this.storeId;
			params.catalogId	= this.catalogId;
			params.langId			= this.langId;
			params.URL = "SuccessfulAJAXRequest";
			params.catEntryId	= catalogEntryId;
			wc.service.invoke("AjaxInterestItemAdd", params);
			cursor_wait();
		}
		else{
			alert(this.getErrorMessage("ERR_RESOLVING_SKU"));
		}
	},

	BundleAdd2ShopCartAjax : function(form){
		
		var params = [];
		var queryString = dojo.io.encodeForm(dojo.byId(form));

		params.storeId		= this.storeId;
		params.catalogId	= this.catalogId;
		params.langId		= this.langId;
		params.orderId		= ".";
			
		var catEntryArray = [];
		catEntryArray = form.catEntryIDS.value.toString().split(",");
		
		for(var i = 0; i < catEntryArray.length; i++){
			var qty = document.getElementById("quantity_" + catEntryArray[i]).value;
			var catEntryId = catEntryArray[i];
			if(this.selectedProducts[catEntryArray[i]])
				catEntryId = this.getCatalogEntryIdforProduct(this.selectedProducts[catEntryArray[i]]);
			
			if(Common.IsNumeric(qty,false) && qty!=null && qty!='' && catEntryId!=null){
				if(qty!=0){
					this.updateParamObject(params,"catEntryId",catEntryId,false,-1);
					this.updateParamObject(params,"quantity",qty,false,-1);
				}
			}
			else{
				alertDialog(this.getErrorMessage("ERR_RESOLVING_SKU"),this.storeId,this.catalogId,this.langId);
				return;
			}
		}
		wc.service.invoke("AjaxAddOrderItem", params);
		cursor_wait();

	},
	
	BundleAdd2WishListAjax : function(form){
		
		var params = [];
		var queryString = dojo.io.encodeForm(dojo.byId(form));

		params.storeId		= this.storeId;
		params.catalogId	= this.catalogId;
		params.langId		= this.langId;
		params.URL          = "SuccessfulAJAXRequest";
			
		var catEntryArray = [];
		catEntryArray = form.catEntryIDS.value.toString().split(",");
		
		for(var i = 0; i < catEntryArray.length; i++){
			var qty = document.getElementById("quantity_" + catEntryArray[i]).value;
			var catEntryId = catEntryArray[i];
			if(this.selectedProducts[catEntryArray[i]])
				catEntryId = this.getCatalogEntryIdforProduct(this.selectedProducts[catEntryArray[i]]);
			
			if(Common.IsNumeric(qty,false) && qty!=null && qty!='' && catEntryId!=null){
				if(qty!=0){
					this.updateParamObject(params,"catEntryId",catEntryId,false,-1);
					this.updateParamObject(params,"quantity",qty,false,-1);
				}
			}
			else{
				alertDialog(this.getErrorMessage("ERR_RESOLVING_SKU"),this.storeId,this.catalogId,this.langId);
				return;
			}
		}
		wc.service.invoke("AjaxInterestItemAdd", params);
		cursor_wait();

	},
	ProductPageAdd2ShopCartAjax : function(formId, productId, resolveSKU)
	{
		var params = [];
		var queryString = dojo.io.encodeForm(dojo.byId(formId));
		var catalogEntryId = "";

		if(resolveSKU)
			catalogEntryId = this.getCatalogEntryId();
		else
			catalogEntryId = productId;

		params = queryToParamObject(queryString, params, false);
		
		if(catalogEntryId != null){
			params.storeId		= this.storeId;
			params.catalogId	= this.catalogId;
			params.langId			= this.langId;
			params.orderId		= ".";
			params.catEntryId	= catalogEntryId;
			wc.service.invoke("AjaxAddOrderItem", params);

			//objAddToCartMessage = eval(document.getElementById('AddedToCartMessage_' + productId));
			//objAddToCartMessage.innerHTML = "Added to Basket";

			cursor_wait();
		}
		else{
			alert(this.getErrorMessage("ERR_RESOLVING_SKU"));
		}
	},
	
	GobacktoQuickOrder : function(formId, productId, resolveSKU,productcode,url)
	{
		
		var form = document.forms[formId];		
		var quantity = document.OrderItemAddForm.quantity.value;
		
		var params = [];
		var queryString = dojo.io.encodeForm(dojo.byId(formId));
		var catalogEntryId = "";

		if(resolveSKU)
			catalogEntryId = this.getCatalogEntryId();
		else
			catalogEntryId = productId;

		params = queryToParamObject(queryString, params, false);

		if(catalogEntryId != null){
			params.storeId		= this.storeId;
			params.catalogId	= this.catalogId;
			params.langId			= this.langId;
			params.orderId		= ".";
			params.catEntryId	= catalogEntryId;
			params.method = 'post';
			wc.service.invoke("AjaxAddOrderItem", params);
			
			///objAddToCartMessage = eval(document.getElementById('AddedToCartMessage_' + productId));
			///objAddToCartMessage.innerHTML = "Added to Basket";
			
			document.location.href=url+"&productcode="+productcode+"&quantity="+quantity;
			
			cursor_wait();
		}
		else{
			alert(this.getErrorMessage("ERR_RESOLVING_SKU"));
		}
	},
	
	ProductPageAdd2WishListAjax : function(formId, productId, resolveSKU)
	{
		var params = [];
		var queryString = dojo.io.encodeForm(dojo.byId(formId));
		var catalogEntryId = "";

		if(resolveSKU)
			catalogEntryId = this.getCatalogEntryId();
		else
			catalogEntryId = productId;

		params = queryToParamObject(queryString, params, false);
		
		if(catalogEntryId != null){
			params.storeId		= this.storeId;
			params.catalogId	= this.catalogId;
			params.langId			= this.langId;
			params.URL = "SuccessfulAJAXRequest";
			params.catEntryId	= catalogEntryId;
			params.productId = productId;
			wc.service.invoke("AjaxInterestItemAdd", params);
			cursor_wait();
		}
		else{
			alert(this.getErrorMessage("ERR_RESOLVING_SKU"));
		}
		 cursor_clear();
	},

	Add2NewsLetterAjax : function(form)
	{
		//alert("<fmt:message key="FUTURE_DIRECTION" bundle="${storeText}" />");
	},

	Add2RSSFeedsAjax : function(form)
	{
		//alert("<fmt:message key="FUTURE_DIRECTION" bundle="${storeText}" />");
	},
	
	Add2EmailNoStockAjax : function(formId,resolveCustomer)
	{	
		var params = [];
		var queryString = dojo.io.encodeForm(dojo.byId(formId));
		params = queryToParamObject(queryString, params, false);
		params.storeId		= this.storeId;
		params.catalogId	= this.catalogId;
		params.langId			= this.langId;
		if(this.getCatalogEntryId() != null){
			params.skuId =this.getCatalogEntryId();
		}
		else
			params.skuId=formId.skuID.value;
		params.fmCenter_id=formId.fmCenter_id.value;
		params.actionId='AjaxEmailItemBackInfo';
		params.URL = "SuccessfulAJAXRequest";
		if(formId.emailInStock.checked && resolveCustomer && formId.usrEml.value == 'true'){
				    params.emailId=formId.xemailID.value;
				    formId.emailIdStock.value="";
					wc.service.invoke("AjaxEmailItemBackInfo", params);
					cursor_wait();
		}
		else{
			if(formId.emailInStock.checked && resolveCustomer){
				dojo.html.show(document.getElementById("emailStockId"));
				formId.emailIdStock.focus();
			}
			else if(formId.emailIdStock.value != null && !formId.emailIdStock.value == ""){
				if(formId.emailIdStock.value.length>0 && Common.isValidEmail(formId.emailIdStock.value)){
					params.emailId=formId.emailIdStock.value;
					formId.emailIdStock.value="";
					wc.service.invoke("AjaxEmailItemBackInfo", params);	
					dojo.html.hide(document.getElementById("emailStockId"));
					cursor_wait();
				}
				else{
						Common.formErrorHandleClient('emailIdStock',Common.errorMessages["ERROR_INVALIDEMAILADDRESS"],formId.name,'ewewr');			
						formId.emailIdStock.focus();
				}
			}
			else if(formId.emailInStock.checked && (formId.emailIdStock.value == null || formId.emailIdStock.value == "")){
					
						Common.formErrorHandleClient('emailIdStock',Common.errorMessages["ERROR_INVALIDEMAILADDRESS"],formId.name,'ewewr');			
						formId.emailIdStock.focus();
			}
			else
				dojo.html.hide(document.getElementById("emailStockId"));
			cursor_clear();
		}
	},
	AjaxEmailItemBackInfoCallback:function(data){
		if(data.eStatus == 'Y'){
			 document.getElementById("EmailConfirm").innerHTML=data.emailId;
			 dojo.html.show(document.getElementById("emailStockConfirmId"));
			 cursor_clear();
		}
	},
	AjaxProductReviewAdd : function(formId)
	{	
	
		formId = dojo.byId(formId);
	
		var params = [];
		var queryString = dojo.io.encodeForm(formId);
		params = queryToParamObject(queryString, params, false);
		params.storeId		= this.storeId;
		params.catalogId	= this.catalogId;
		params.langId			= this.langId;
		params.productId=formId.reviewId.value;
		params.rating=formId.rating.value;
		params.review=formId.review.value;
		params.userId=formId.userId.value;
		if(formId.rating.value == '0')
				Common.formErrorHandleClient('rating',Common.errorMessages["ERROR_SELECTRATING"],formId.name,'ewewr');			
		else if(formId.review.value.length > 300)
			Common.formErrorHandleClient('review',Common.errorMessages["ERROR_INVALIDTEXTLENGTH"],formId.name,'ewewr');			
		else if (formId.review.value.length == 0) 
			Common.formErrorHandleClient('review',Common.errorMessages["ERROR_INVALIDVALUE"],formId.name,'ewewr');			
		else{
		wc.service.invoke("AjaxProductReviewAdd", params);	
		dojo.html.hide(document.getElementById("productReviewId"));
		cursor_wait();
		}
		
	},
	AjaxProductReviewAddCallback:function(data){
		if(data.eStatus == 'Y'){
			 //document.getElementById("productReviewConfirmId").innerHTML=data.emailId;
			 dojo.html.show(document.getElementById("productReviewConfirmId"));
			 cursor_clear();
		}
	},
	setErrorMessage : function(key, value){
		this.errorMessages[key] = value;
	},
	getErrorMessage : function(key){
		var value = this.errorMessages[key];
		if(value == null)
			value = "Could not get the message value for specified key " + key;
		return value;
	},
	showPopup:function (){   
	    
	    var popUp = document.getElementById("popupcontent");    
	    popUp.style.top = "50px";   
	    popUp.style.left = "50px"; 
	    popUp.style.border = "2px solid #687A9E";
	    popUp.style.padding = "10px";
	    popUp.style.backgroundColor = "#ffffff";
	    
		popUp.style.visibility = "visible";
		
		dojo.html.hide(document.getElementById("dropdown_id1"));
		dojo.html.hide(document.getElementById("dropdown_id2"));
		
		var attributeDropDown = document.getElementById("attributesID");
		
		if (attributeDropDown != null)
			dojo.html.hide(document.getElementById("attributesID"));	
	},
	
	hidePopup:function (){   
	    
	    var popUp = document.getElementById("popupcontent");   
	    popUp.style.visibility = "hidden";
	    dojo.html.show(document.getElementById("dropdown_id1"));
	    dojo.html.show(document.getElementById("dropdown_id2"));
	    dojo.html.show(document.getElementById("attributesID"));
	}
}
