//********************************************************************
//*-------------------------------------------------------------------
//* 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.
//*
//*-------------------------------------------------------------------

shopCartObjectJS={
	updateWaitTimeOut:150,
	showSelectBoxFor: 4000,
	langId: "-1",
	storeId: "",
	catalogId: "",
	errorMessages: {},


	setErrorMessage:function(key, msg) {
	///////////////////////////////////////////////////////////////////
	// summary: This function is used to initialize the error messages object 
	//		with all the required error messages.
	// Description: Setup a JS object with any key/value.
	// key: The key used to access this error message.
	// msg: The error message in the correct language.
	//////////////////////////////////////////////////////////////////
		this.errorMessages[key] = msg;
	},

	setCommonParameters:function(langId,storeId,catalogId){
		this.langId = langId;
		this.storeId = storeId;
		this.catalogId = catalogId;
	},

	initializeShoppingCartPage:function(){
		// summary		: initialize the shipment page
		// description	: Executed onLoad of AjaxShippingDetails page
		//				  This function sends the addressId/shipModeId of the first shipment block in this page
		//				  to the quick cart, so that when items are moved to quick cart, they are added with this
		//				  info by default..
		//				  Then defines the drop targets.. each shipment block will be on drop area
		//				  Also hides the default input date field that comes with Dojo's date picker
		//
		// assumptions	: None
		// dojo API		: None
		// returns		: null

		//Connect the updateCartWait function with updateCart, so that whenever updateCartWait function
		//get called updateCart function will be called after updateWaitTimeOut miliseconds.
		dojo.event.kwConnect({
			srcObj:     this, 
			srcFunc:    "updateCartWait", 
			targetObj:  this, 
			targetFunc: "updateCart",
			delay:      this.updateWaitTimeOut,
			once:		true
		});
	},

	updateCartWait:function(quantityBox, orderItemId) {
		// summary		: This function updates the Order after waiting for 'updateWaitTimeOut' miliseconds.
		// description	: This function updates the Order after waiting for 'updateWaitTimeOut' miliseconds.
		//				  with new quantity specified by user for particular order item.
		// quantityBox	: DOM Node 
		//				  DOM node representing the quantity testbox.
		// orderItemId	: Number
		//				  OrderItemId for the Item being updated.
		// assumptions	: None.
		// dojo API		: None.
	},
	
	updateCart:function(quantityBox, orderItemId){
		// summary		: This function updates the Order
		// description	: This function updates the Order with new quantity specified by user for
		//				  particular order item.
		// quantityBox	: DOM Node 
		//				  DOM node representing the quantity testbox.
		// orderItemId	: Number
		//				  OrderItemId for the Item being updated.
		// assumptions	: None.
		// dojo API		: None.

		var quantity = parseInt(quantityBox.value);
		if(!isNaN(quantity)){
			var params = [];
			params.orderId		= ".";
			params["storeId"] = this.storeId;
			params["catalogId"] = this.catalogId;
			params["langId"] = this.langId;
			this.updateParamObject(params,"orderItemId",orderItemId,false,-1);
			this.updateParamObject(params,"quantity",quantity,false,-1);
			wc.service.invoke("AjaxUpdateOrderItem", params);
			cursor_wait();
		}else{
				alert("Please Enter a Valid Quantity.");
		}
	},
	
	addToCartWait:function(quantity, catentryId){
		// summary		: This function adds and item to the Order
		// description	: This function adds an item to the order and updates it
		//
		// quantity	: an integer 
		//				  DOM node representing the quantity testbox.
		// catentryId	: Number
		//				  catentryId for the Item being added.
		// assumptions	: catentryId and quantity are not null.
		// dojo API		: None.
		
		dojo.debug("add to cart, catentryId:" + catentryId + ", with quantity:" + quantity);
		if (quantity > 0) {
			var params = [];
			params.orderId		= ".";
			params["storeId"] = this.storeId;
			params["catalogId"] = this.catalogId;
			params["langId"] = this.langId;
			
			this.updateParamObject(params,"catEntryId",catentryId,false,-1);
			this.updateParamObject(params,"orderId",".",false,-1);
			this.updateParamObject(params,"quantity",quantity,false,-1);			

			wc.service.invoke("AjaxAddOrderItem",params);
			cursor_wait();
		}
	},
	
	updateCartRefresh:function(params,nothing, widget){
		// summary		: Updates the shipModeId and addressId of the orderItemId present in the params
		// description	: On Successfull OrderItemShipmentBlockUpdate service invocation, this functions is
		//				  called in the model changed script of orderItemDetailsByShipmentBlockController
		//				  after some time delay. This function refreshes the widgets associated with 
		//				  orderItemDetailsByShipmentBlockController	
		// params		: renderContext.properties object available in the modelChangedSCript.. This should
		//				  contains atleast the orderItemId and orderId.
		// widget		: The widget that needs to be refreshed	
		// assumptions	: None
		// dojo API		: None
		// returns		: Java script array object, where array size = number of shipments selected
		//var addressId = document.getElementById(shipmentMapping.addressSelection+shipmentBlockNumber).value;
		//var shipModeId = document.getElementById(shipmentMapping.shippingModesSelection+shipmentBlockNumber).value;
		//params = this.updateParamObject(params,"langId",langId,true);
		//params = this.updateParamObject(params,"storeId",storeId,true);
		//params = this.updateParamObject(params,"catalogId",catalogId,true);
		widget.refresh(params);
		cursor_clear(); 
	},
	

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



miniShopCartPageJS={	
	aDropDownTarget:"f",
	
	updateMiniCartRefresh:function(params,nothing, widget){
		widget.refresh(params);
		cursor_clear(); 
	},
	
	defineDropTargets:function(){
		// summary		: Function which defines the drop targets.
		// description	: User can drag and drop items from quick cart to the different shipment area.
		//				  This functions defines each shipment Area as one drop target that accepts
		//				  items of type "quickcart_item". It doesnt accept items from wish list or from
		//				  eMarketing spots. It also defines a handler function (handleDrop) which will
		//				  be called on successful drop of quick cart items. It sets the property "ship"
		//				  on Drop Target object, which helps in identifying whether the object is dropped
		//				  in shipment area 1 or 2 or.. n...	
		// assumptions	: None
		// dojo API		: wc.widget.WCHtmlDropTarget widgets functions
		// returns		: null		
		var dropTarget = document.getElementById("miniShoppingCartDropArea");  

		//These targets should accept items only...  
		var temp = new wc.widget.WCHtmlDropTarget(dropTarget, ["item","product"]);  

		//this is the drop handler which will be called on drop..  
		temp.onDrop = this.miniCartDropEventHandler;

		dojo.debug("Initialized drag and drop handler: miniCartDropEventHandler");
	},
	
	dover:function(event){
	},
	
	/*
	* Even handler for onDrop even on quickCart
	* Work around applies in this case
	*/
	 miniCartDropEventHandler:function(event){
		alert('just a test');
		this.onDragOut(event);
		
		var catEntryId = event.dragSource.dragObject.catentryId;
		var quantity = parseInt(event.dragSource.dragObject.quantity);
		dojo.debug("Add catentryId:" + catEntryId + ", with quantity:" + quantity);
		
		if(!isNaN(quantity) && !isNaN(catEntryId)){
			shopCartObjectJS.addToCartWait(quantity, catEntryId);
		}
		else
		{
			//Quantity is not number
			//Do you want me to alert user for this?
		}

		return true;
	}
}
