dojo.require("dojo.lang.*");
dojo.require("dojo.io.*");
dojo.require("wc.render.*");

OrderItemDisplay=
{
	//contextChanged boolean
	//		 indicating if an context change happened
	//isHistory boolean
	//		 indicating if the refresh are caused by browser back/forward event.
	contextChanged:false, 
	isHistory:false,
	busy:false,
	
	langId: "100",
	storeId: "",
	catalogId: "",
	orderItemId: "",
	count: "",
	stateSet: false,
	showImages: true,
	itemId: "",
	field1: "",
	
	setShowImages: function(showImages)
	{
		OrderItemDisplay.showImages = showImages;
	},
	getShowImages: function()
	{
		return OrderItemDisplay.showImages;
	},
	setItemId: function(itemId)
	{
		OrderItemDisplay.itemId = itemId;
	},
	setField1: function(fld1)
	{
		OrderItemDisplay.field1 = fld1;
	},
	
	setCommonParameters:function(langId,storeId,catalogId){
		// 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;
	},
	
	loadContentFromURL:function(workAreaModeValue, controllerId, contextId, resultPageURL)
	{
		//Cannot set book mark on forward otherwise the transaction never stops
		cursor_wait();
		wc.render.getRefreshControllerById(controllerId).url = resultPageURL;
		wc.render.updateContext(contextId, {workAreaMode:workAreaModeValue});
	},
	
	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;
	 },
	
	 submitQuickShop: function(form)
	 {
		removeErrorBar();
		
		if (!getBusy())
		{
			setBusy(true);
			cursor_wait();
			wc.service.getServiceById("AJAXQuickShop").formId = form.name;
			wc.service.invoke("AJAXQuickShop");
			form.productCode.value = "";
		}
	 },
	 
	 //Added because of problems using AJAX on the Basket page, cannot get the proceed button to appear if using AJAX
	 submitQuickShopNonAJAX: function(form)
	 {
		removeErrorBar();
		
		if (!getBusy())
		{
			setBusy(true);
			cursor_wait();
			form.submit();
			form.productCode.value = "";
		}
	 },
	 
	 submitPromotionCode: function(form)
	 {
		removeErrorBar();
		
		if (!getBusy())
		{
			setBusy(true);
			cursor_wait();
			wc.service.getServiceById("AjaxPromotionCodeManage").formId = form.name;
			wc.service.invoke("AjaxPromotionCodeManage");
		}
	 },
	 
	 updateShopCart:function( orderItmId, preOrder, availableInventory, requestedQuantity, status )
	 {
	 	removeErrorBar();
	 	
		var params = [];
		params.storeId = this.storeId;
		params.catalogId = this.catalogId;
		params.langId = this.langId;
		params.orderId	= ".";
		params.orderItemId = orderItmId;
		params.quantity = requestedQuantity;
		
		if( availableInventory < requestedQuantity && !preOrder)
		{
			alert('This item is not available in the quantity you have requested. We only have ' + availableInventory + ' in stock');
			document.getElementById("qty" + status).value = availableInventory;
			setError(true);
		}

		if (preOrder)
		{
			alert("This title is due into the warehouse soon, but please be aware it may delay your order");
		}
		
		if (!getBusy() && !getError())
		{
			setBusy(true);
			cursor_wait();
			wc.service.invoke("AjaxUpdateOrderItem", params);
		}
	},
	
	//Works in the same way as updateShopCart (above) but instead of changing the quantity field1 is updated to make this a free / paid for book
	redeemWithBookPoints:function( orderItmId, itemId, preOrder, availableInventory, requestedQuantity, status, field1, availableBookPoints, receivedOnBook, costOfBook )
	 {
	 	removeErrorBar();
	 	
	 	var bookPoints = parseInt(availableBookPoints);
	 	var fromBook = parseInt(receivedOnBook);
	 	var bookCost = parseInt(costOfBook);
	 	var quantity = parseInt(requestedQuantity);
	 	var field   = parseInt(field1);
	 	
	 	//If field is 1 then the user is redeeming an item to their free book basket using points
		if (quantity > 1 && field == 1)
		{
			//Order item update of order item followed by order item add
			if (bookPoints - fromBook - bookCost < 0)
			{
				setStandardErrorMessage("There are not enough book points available to redeem this as a free book");
				setError(true);
			}
			else
			{
				OrderItemDisplay.setItemId(itemId);
				OrderItemDisplay.setField1(field);
		 		OrderItemDisplay.updateShopCart(orderItmId, preOrder, availableInventory, quantity - 1, status);
		 	}
		}
		else
		{
			//If field is 1 then the user is redeeming an item to their free book basket using points
			if (quantity > 1 && field == 0)
			{
				OrderItemDisplay.setItemId(itemId);
				OrderItemDisplay.setField1(field);
				OrderItemDisplay.updateShopCart(orderItmId, preOrder, availableInventory, quantity - 1, status);
			}
			else
			{
				if (parseInt(requestedQuantity) == 1)
				{
					//Move item from paid basket to free basket or visa versa
					OrderItemDisplay.updateRedeemedBook(orderItmId, requestedQuantity, field1);
				}
			}
		}
	},
	
	addRedeemedBook: function(itemId)
	{
		var field1Value = OrderItemDisplay.field1;
		var params = [];
		params.storeId = this.storeId;
		params.catalogId = this.catalogId;
		params.langId = this.langId;
		params.orderId = ".";
		params.catEntryId = itemId;
		params.quantity = 1;
		params.field1 = field1Value;
		
		if (!getBusy() && !getError())
		{
			setBusy(true);
			cursor_wait();
			wc.service.invoke("AjaxOrderItemUpdate", params);
		}
	},
	
	updateRedeemedBook: function(ordrItmId, quantity, field1)
	{
		var params = [];
		params.storeId = this.storeId;
		params.catalogId = this.catalogId;
		params.langId = this.langId;
		params.orderId = ".";
		params.orderItemId = ordrItmId;
		params.quantity = quantity;
		params.field1 = field1;
		
		if (!getBusy() && !getError())
		{
			setBusy(true);
			cursor_wait();
			wc.service.invoke("AjaxOrderItemUpdate", params);
		}
	},
	
	deleteFromShopCart: function(orderItmId)
	{
		removeErrorBar();
		
		var params = [];
		params.storeId = this.storeId;
		params.catalogId = this.catalogId;
		params.langId = this.langId;
		params.orderId	= ".";
		params.orderItemId = orderItmId;
		
		if (!getBusy())
		{
			setBusy(true);
			cursor_wait();
			wc.service.invoke("AjaxDeleteOrderItem", params);
		}
	},
	
	deleteAllFromShopCart: function(orderItmIds)
	{
		removeErrorBar();
	
		var orderItems = orderItmIds.split(",");
		
		var params = [];
		params.storeId = this.storeId;
		params.catalogId = this.catalogId;
		params.langId = this.langId;
		params.orderId	= ".";
		for (x = 0; x < orderItems.length; x++)
		{
			params["orderItemId_" + x] = orderItems[x];
		}
		
		if (!getBusy())
		{
			setBusy(true);
			cursor_wait();
			wc.service.invoke("AjaxDeleteOrderItem", params);
		}
	}
}

