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


var addresses = [];

shipmentPageJS={
	 addressJSONContainerName: "addressJSONContainer", // div which holds the addressJSON object
	 addressDetailsSpanName:"addressDetailsInShort_",  // div where address details are displayed
	 addressCreateEditFormDivName:"addressCreateEditFormDiv_", //div which holds address form
	 editAddressButtonDivName:"editAddress_", //Edit button name.. for editing address
	 addressFormName:"AddressForm_", //Address form name
	 specifyAdvanceShippingOptionsDivName:"specifyAdvanceShippingOptionsDiv_", //Advance shipping options div (instructions and ship date)
	 addressDropDownBoxValuePrefix:"prefix", //prefix for address drop down box values.. ex prefix_10001
	 shippingBlockDivName:"shippingBlock_", //Shipping block div name..there will be 3 shipping blocks
     globalParams:null,	 //Used while splitting the qty b/w two shipment blocks...
	 updateWaitTimeOut:1500,
	 showSelectBoxFor: 4000,
	 langId: "-1",
     storeId: "",
     catalogId: "",
     prCd:"",
     entitledItems:[],
     selectedAttributes:new Object(),
	 errorMessages: {},

	//This is the div, which holds the Addresses JSON object.. This div is refreshed when
	//the user updates or creates a new address.
	 setAddressJSONContainerName:function(addressJSONContainerName){
		this.addressJSONContainerName = addressJSONContainerName;
	 },

	//This div contains the address details of the selected address.. this is placed next to the drop down box of addresses,
	// and whenever the user selects different address, this div is populated with the selected address details using Address JSON object
	 setAddressDetailsSpanName:function(addressDetailsSpanName){
		this.addressDetailsSpanName = addressDetailsSpanName;
	 },

	//This div holds the address form, used to create or edit address..its displayed when user selects Create Address option or clicks on Edit link for existing address
	setAddressCreateEditFormDivName:function(addressCreateEditFormDivName){
		this.addressCreateEditFormDivName = addressCreateEditFormDivName
	},
	
	//This is the div which holds the "edit" button/hyperlink..
	setEditAddressButtonDivName:function(editAddressButtonDivName){
		this.editAddressButtonDivName = editAddressButtonDivName;
	},
	
	//This is the name of the Address form, used to create/edit address
	setAddressFormName:function(addressFormName){
		this.addressFormName = addressFormName;
	},

	//this is the prefix which is used while populating the Address JSON object..
	//ex: prefix10052 for address ID 10052..
	setAddressDropDownBoxValuePrefix:function(addressDropDownBoxValuePrefix){
		this.addressDropDownBoxValuePrefix = addressDropDownBoxValuePrefix;
	},

	//This is the top level div for a single shipment block..it contains items, address and everythign else related to one shipment block..
	setShippingBlockDivName:function(shippingBlockDivName){
		this.shippingBlockDivName = shippingBlockDivName;
	},

	//this div contains info related to advance shipping options like Shipping instructions and Requested Ship Date
	setSpecifyAdvanceShippingOptionsDivName:function(specifyAdvanceShippingOptionsDivName){
		this.specifyAdvanceShippingOptionsDivName = specifyAdvanceShippingOptionsDivName;
	},
	
	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;
	},

	initializeShipmentPage: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
		this.setAddressIdAndShipModeId();
		this.defineDropTargets();
		this.hideDefaultDateFields();
		var totalOptions = document.getElementById(shipmentMapping.numberOfShipments).value;
		this.updateMasterShipmentBlockSelectBox(totalOptions);
		this.setDialogProperties();
		//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
		});
	},


	setDialogProperties:function(){
		// summary		: This function sets the Dialog Properties
		// description	: When the item is moved from one shipment to another and if qty > 1, then a dialog
		//				  box is presented to user, where in the user can split the quantity. This dialog box
		//				  properties are set in this function. The close control buttons for the dialog are set
		//				  in this function. On click of these buttons, the dialog box will be closed..
		//				  This function is called onLoad of Shipment Page.
		//				  To Do - dont hardcode, dialog box name and also button names..
		//
		// assumptions	: None
		// dojo API		: dojo.widget.Dialog.setCloseControl(object)
		// returns		: None
		var dlg = dojo.widget.byId(shipmentMapping.splitQty);
		//On clicking of the "X" image.
		var btn1 = document.getElementById(shipmentMapping.iconx1);
		//On Clicking of Cancel button
		var btn2 = document.getElementById(shipmentMapping.Cancel);
		dlg.setCloseControl(btn2);
		dlg.setCloseControl(btn1);
		//We should not close the dlg on click of "ok' button..user might have entered wrong value..so in that case we just need to display the error message
		// var btn = document.getElementById("split");
		// dlg.setCloseControl(btn);
	},
	
	hideDefaultDateFields:function(){
		// summary		: Hide the default date fields of the dojo date picker widget
		// description	: The Dojo Date Picker comes with a default input box, where user can enter the date
		//				  We are displaying customized read only date fields and hence need to hide the
		//				  default input box that comes with dojo's date picker. This functions serves that 
		//				  purpose.
		// assumptions	: None
		// dojo API		: dojo.html.hide(obj)
		// returns		: null
		var x = null;
		for(var i = 1; i < 4; i++){
			x = dojo.widget.byId("datePicker_"+i);
			dojo.html.hide(x.inputNode);

		}
		x = null;
	},

	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 = null;
		for(var i = 1; i < 4; i++){
			dropTarget = document.getElementById(shipmentMapping.topLevelShipmentBlockDetailsDiv+i);
			//These targets should accept items only from quick cart..not from anywhere else ...
			var temp = new wc.widget.WCHtmlDropTarget(dropTarget, [shipmentMapping.quickcart_item]);
			//this is the drop handler which will be called on drop..
			temp.onDrop = this.handleDrop;
			temp.ship = i;
		}
	},
	
	handleDrop:function(event){
		// summary		: Handler function for successfull drop operation
		// description	: This function will be called on successfull drop of quick cart items to
		//				  Shipment page area. This function first clears the drop indicator (Horizontal Line)
		//				  and then processes the dropped order item	
		// assumptions	: None
		// event		: dojo.dnd.DropEvent object.
		//				  An event object class for passing state information between participants in a 
		//				  drag-and-drop operation cycle.
		// dojo API		: onDragOut function of wc.widget.WCHtmlDropTarget widget
		// returns		:None

		//remove the dropIndicator..
		this.onDragOut(event);
		//this.ship contains the shipment Number..whether its dropped in shipment area 1 or 2 or 3..
		return(shipmentPageJS.processDroppedOrderItem(event,this.ship));
	},

	processDroppedOrderItem:function(event,blockNumber){
		// summary		: Function to handle dropped order items.
		// description	: This function first validates that its a valid drop. Its a valid drop only
		//				  if (its dropped in shipment area, which as proper addressId and shipMode Id selected)	
		//				  and if(the item doesn't belong to the same shipment area)
		//				  If its not a valid drop,then display message and return.
		//				  Check the qty for valid drop. If qty == 1, then update the order by calling "OrderItemShipmentBlockUpdate" service.
		//				  If qty > 1, then display dialog, where user can enter the qty which he wants to move to this shipment.
		//				  The dialog box takes over the processing of order item from here..
		// assumptions	: None
		// dojo API		: DragSource widgets functions
		// returns		: false for invalid drop and true for valid drop

		//check if its dropped in proper area or not..
		if(!this.isValidBlock(blockNumber)){
			alertDialog(this.errorMessages["SHIPPING_INVALID_ADDRESS_SHIPPING"],this.storeId,this.catalogId,this.langId);
			return false;
		}
		if(!this.isValidDrop(event,blockNumber)){
			alertDialog(this.errorMessages["SHIPPING_SAME_SHIP_BLOCK"],this.storeId,this.catalogId,this.langId);
			return false;
		}

		//Its a valid drop...Update the order..
		var addressAtDrop = document.getElementById(shipmentMapping.addressSelection+blockNumber).value;
		var shipModeAtDrop = document.getElementById(shipmentMapping.shippingModesSelection+blockNumber).value;
		var droppedOrderItemId = event.dragSource.dragObject.orderItemId;
		var catEntryId = event.dragSource.dragObject.catentryId;
		var qty = event.dragSource.dragObject.quantity;
		//Check the qty..if qty = 1, then directly update..
		if(qty == 1){
			var params = [];
			params.orderId = ".";
			params["storeId"] = this.storeId;
			params["catalogId"] = this.catalogId;
			params["langId"] = this.langId;
			this.updateParamObject(params,"orderItemId",droppedOrderItemId,false,-1);
			this.updateParamObject(params,"addressId",addressAtDrop,false,-1);
			this.updateParamObject(params,"shipModeId",shipModeAtDrop,false,-1);
			wc.service.invoke("OrderItemShipmentBlockUpdate", params);
			cursor_wait();
			return true;
		}
		else{
			// qty > 1..ask user, if he wants to split the order..
			var dlg = dojo.widget.byId(shipmentMapping.splitQty);
			//Set the values for hidden elements in the dialog, which can be used in splitOrderItemQty function..
			//Qty, orderItemId, newshipModeId,newAddressId
			document.getElementById("totalQty").value = qty;
			document.getElementById("requiredQty").value = qty;
			document.getElementById("newAddressId").value = addressAtDrop;
			document.getElementById("newShipModeId").value = shipModeAtDrop;
			document.getElementById("movedOrderItemId").value = droppedOrderItemId;
			document.getElementById("catEntryId").value = catEntryId;
			dlg.show();
			//focusElement property is set during dialog definition itself.no need to set the focus explicitly again
			// document.getElementById("requiredQty").focus();
			return true;
		}
	},

	splitOrderItemQty:function(){
		// summary		: Handler for onClick event of Split Qty button in the Dialog box.
		// description	: User enters some value in the input text box element and clicks on 
		//				  Split Qty button, this function gets called. 
		//				  This functions kicks of by checking whether the value entered in input area is
		//				  a valid number or not. If not display message to user and return false.
		//				  Next, it performs a check to see, if user has entered more than allowed qty (Maximum qty in the shop cart)
		//				  Ex; If user has 4 items in the shop cart and then enters 5, then error message is displayed
		//                If  valid value is entered, then it updates the server with new addressId and shipMode id for the orderItem dropped
		// assumptions	: None
		// dojo API		: None
		// returns		: false for invalid entry and true for valid entry in input field.

		//First lets see if user has entered a valid number..
		var requiredQty = document.getElementById("requiredQty").value;
		var totalQty = document.getElementById("totalQty").value;
		if(!this.isValidNumberField(requiredQty)){
			alertDialog(this.errorMessages["SHIPPING_INVALID_QTY"],this.storeId,this.catalogId,this.langId);
			document.getElementById("requiredQty").focus();
			return;
		}
		//Is customer is entering more than allowed..
		if(parseInt(requiredQty) > parseInt(totalQty)){
			var messageToUse = this.errorMessages["SHIPPING_MOVE"];
			messageToUse = messageToUse.replace(/%0/, totalQty);
			alertDialog(messageToUse,this.storeId,this.catalogId,this.langId);
			return;
		}
		//Everything is fine till now..lets update the server..
		//close the dialog first..
		var dlg = dojo.widget.byId(shipmentMapping.splitQty);
		dlg.hide();

		var newAddressId = document.getElementById("newAddressId").value;
		var newShipModeId = document.getElementById("newShipModeId").value;
		var movedOrderItemId = document.getElementById("movedOrderItemId").value;
		var catEntryId	= document.getElementById("catEntryId").value;;
		var remainingQty = parseInt(totalQty) - parseInt(requiredQty);
		var params = [];
		var params1 = [];
		params["storeId"] = this.storeId;
		params1["storeId"] = this.storeId;
		params["catalogId"] = this.catalogId;
		params1["catalogId"] = this.catalogId;
		params["langId"] = this.langId;
		params1["langId"] = this.langId;
		params = this.updateParamObject(params,"orderId",".",true);
		params1 = this.updateParamObject(params,"orderId",".",true);
		params = this.updateParamObject(params,"addressId",newAddressId,false,-1);
		params1 = this.updateParamObject(params,"addressId",newAddressId,true);
		params = this.updateParamObject(params,"shipModeId",newShipModeId,false,-1);
		params1 = this.updateParamObject(params,"shipModeId",newShipModeId,true);
		params = this.updateParamObject(params,"requiredQty",requiredQty,false,-1);
		params1 = this.updateParamObject(params,"requiredQty",requiredQty,true);
		params = this.updateParamObject(params,"remainingQty",remainingQty,false,-1);
		params1 = this.updateParamObject(params,"remainingQty",remainingQty,true);
		params = this.updateParamObject(params,"movedOrderItemId",movedOrderItemId,false,-1);
		params1 = this.updateParamObject(params,"movedOrderItemId",movedOrderItemId,true);
		params = this.updateParamObject(params,"catEntryId",catEntryId,false,-1);
		params1 = this.updateParamObject(params,"catEntryId",catEntryId,true);
		//Set them in global store..
		this.setInGlobalStore(params1);
		//Need to reset this param object some time...TODO ..decide where to do..
		//if the customer is moving all the items, then the job is easy..just update the ship info
		if(parseInt(totalQty) == parseInt(requiredQty)){
			//just invoke the service..
			params = this.updateParamObject(params,"orderItemId",movedOrderItemId,false,-1);
			wc.service.invoke("OrderItemShipmentBlockUpdate", params);
			cursor_wait();
			return;
		}
		else{
			//Now the customer is moving only a part of total qty....say 2 out of 4..so we have more work to do :-)
			//Step 1: call addOrderItem and create a new order Item..
			//Step 2: onSuccessfull completion of Step 1, For this new order Item, update the shipping Info...
			//Step 3: onSuccessfull completion of Step 2,Modify the old order item and reduce the qty..
			//In the end, update our refresh areas and also the quickCart..
			//Dont reuse old services..Create our own new services, so that we dont call modelChangedScripts for each of the service..
			this.updateParamObject(params,"quantity",requiredQty,true);
			this.addItemWithShipingInfo(params);
		}
		return;
	},

	addItemWithShipingInfo:function(params){
		// summary		: add an order item to the shop cart
		// description	: This function adds an order item to the shopping cart. When an item is moved partly (some part of total available qty)
		//				  this function is called. This function  adds the order item, with qty passed in params object.
		//				  It declares its own service with unique actionId and id, since we dont want to do anything else in modelChangedScript.   	
		//				  When an item is added to shopCart, it will be added to default addressId and shipMode Id.. 
		//				  So on successfully adding the item, we need to update the addressId and shipModeId for this item.			
		//				  This is done by calling updateItemShipingInfo function in successHandler, and this relationship is established
		//				  by using dojo.event.kwConnect 
		// params		: Java script array which should contain catEntryId and orderId and quantity	
		// assumptions	: None
		// dojo API		: dojo.event.kwConnect
		// returns		: null

		//this function will call addOrderItem function and on successful execution, calls updateItemShippingInfo..
		//make id and actionId unique so that it wont affect other modelChangedScripts..
		
			var service = wc.service.declare({
			id: "AjaxAddSplitQtyOrderItemWithShipingInfo",
			actionId: "AjaxAddSplitQtyOrderItemWithShipingInfo",
			url: "AjaxOrderChangeServiceItemAdd",
				
			successHandler: function(serviceResponse) {
				cursor_clear();
			},
			failureHandler: function(serviceResponse) {
				cursor_clear();
				//TO DO Do not ignore errors...
				//alert("Error ");
			}
		});

		dojo.event.kwConnect({
			srcObj:     service, 
			srcFunc:    "successHandler", 
			targetObj:  this, 
			targetFunc: "updateItemShipingInfo",
			once:		true
		});
		wc.service.invoke("AjaxAddSplitQtyOrderItemWithShipingInfo", params);
		cursor_wait();
	},

	updateItemShipingInfo:function(params){
		// summary		: update the shipping info of an order item
		// description	: This function updates the shipping info(addressId, shipModeId) of the orderItem 
		//				  present in params object passed.
		//				  This function declares its own service, since we dont want to do anything
		//				  in modelChangedScript and this service is just a part of split order Qty process.
		//				  On successfull updation of shipping Info, we need to reduce the quantity of original order item
		//				  and this is handled in updateSplitOrderItemShipInfoQty function. This function is called
		//				  on success handler and the relationship is established using dojo.event.kwConnect
		// params		: Java script array containing orderId, orderItemId, shipModeId, addressId
		// assumptions	: None
		// dojo API		: dojo.event.kwConnect
		// returns		: null

		var service = wc.service.declare({
			id: "AjaxUpdateSplitQtyOrderItemShipInfo",
			actionId: "AjaxUpdateSplitQtyOrderItemShipInfo",
			url: "AjaxOrderChangeServiceShipInfoUpdate",
				
			successHandler: function(serviceResponse) {
				cursor_clear();
			},
			failureHandler: function(serviceResponse) {
				cursor_clear();
				//TO DO - handle error
				//alert("Error ");
			}
		});

		dojo.event.kwConnect({
			srcObj:     service, 
			srcFunc:    "successHandler", 
			targetObj:  this, 
			targetFunc: "updateSplitOrderItemShipInfoQty",
			once:		true
		});

		//params contains whatever is there in serviceResponse of addItemWithShipingInfo function..
		var tempParams = [];
		tempParams["storeId"] = this.storeId;
		tempParams["catalogId"] = this.catalogId;
		tempParams["langId"] = this.langId;
		tempParams.orderId = ".";
		var addressId = this.globalParams.addressId;
		var shipModeId = this.globalParams.shipModeId;
		//newly added orderItemId..
		var orderItemId = params.orderItemId;
		//May be we wont need this udpateParamObject function here..just tempParam.orderItemId should do..TODO
		this.updateParamObject(tempParams,"orderItemId",orderItemId,false,-1);
		this.updateParamObject(tempParams,"addressId",addressId,false,-1);
		this.updateParamObject(tempParams,"shipModeId",shipModeId,false,-1);
		wc.service.invoke("AjaxUpdateSplitQtyOrderItemShipInfo", tempParams);
		cursor_wait();
	},

	updateSplitOrderItemShipInfoQty:function(params){
		// summary		: reduce the quantity of moved item
		// description	: When user moves an item from one shipment to another shipment partly (part of the total available qty)
		//				  this function is called and it updates the qty at server by invoking "AjaxUpdateOrderItem" service.
		// params		: This is the object passed from success handler of AjaxUpdateSplitQtyOrderItemShipInfo service. Not used 	
		//				  for time being. Use the parameters available in global store.
		// assumptions	: None
		// dojo API		: None
		// returns		: null

		//Now we are done with adding new orderItem and updating its shipping Info..
		//Now we need to reduce the qty of the movedOrderItem..
		//There is a service "AjaxUpdateOrderItem", which is used in quickCart..lets us same thing..
		//Moreover this service will update our refresh areas also...and then clears the cursor..
		var tempParams = [];
		tempParams["storeId"] = this.storeId;
		tempParams["catalogId"] = this.catalogId;
		tempParams["langId"] = this.langId;
		tempParams.orderId		= ".";
		this.updateParamObject(tempParams,"quantity",this.globalParams.remainingQty,false,-1);
		this.updateParamObject(tempParams,"orderItemId",this.globalParams.movedOrderItemId,false,-1);
		wc.service.invoke("AjaxUpdateOrderItem",tempParams);
		cursor_wait();
	},

	justDisappear:function(){
		// summary		: Dummy function
		// description	: function called on click of Cancel button in the split qty dialog
		// assumptions	: None
		// dojo API		: None
		// returns		: None
	},

	isValidDrop:function(event, shipmentBlockNumber){
		// summary		: checks if object is dropped in same shipment block or different block
		// description	: get the current addressId and shipMode id of the dropped object from the
		//				  event object and test it against the addressId and shipModeId selected in the 
		//				  shipment_<shipmentBlockNumber>. If both are same, then item already belongs	
		//				  to this shipment area only.
		// event		: dojo.dnd.DropEvent object.
		//				  An event object class for passing state information between participants in a 
		//				  drag-and-drop operation cycle.
		// shipmentBlockNuber : Against which this validation function runs.
		// assumptions	: None
		// dojo API		: None
		// returns		: false - if dropped in same shipment block.
		//				: true - if dropped in different shipment block. 

		//Get the current shipping mode and address Id of the object.
		var currentAddressId = event.dragSource.dragObject.addressId;
		var currentShipModeId = event.dragSource.dragObject.shipModeId;
		//Get the shipping and address Id at the dropped place..
		var addressAtDrop = document.getElementById(shipmentMapping.addressSelection+shipmentBlockNumber).value;
		var shipModeAtDrop = document.getElementById(shipmentMapping.shippingModesSelection+shipmentBlockNumber).value;
		if((currentAddressId == addressAtDrop) && (currentShipModeId == shipModeAtDrop)){
			//The object is dropped in the same area to which it belongs
			return false;
		}
		return true;
	},

	isValidBlock:function(blockNumber){
		// summary		: is this a valid shipment block
		// description	: Checks if this is a valid shipment block. If this shipment block
		//				  contains valid addressId and shipModeId, then return true
		// blockNumber  : Block number which needs to be validated
		// assumptions	: None
		// dojo API		: None
		// returns		: true - if valid addressId and shipModeId exists
		//				: false - if addressId or shipModeId == -1

		var addressId = document.getElementById(shipmentMapping.addressSelection+blockNumber).value;
		var shipModeId = document.getElementById(shipmentMapping.shippingModesSelection+blockNumber).value;
		if(addressId == "-1" || shipModeId == "-1"){
			return false;
		}
		return true;
	},

	setAddressIdAndShipModeId:function(){
		// summary		: update the shipping info params, used by quick cart
		// description	: This function sends the addressId/shipModeId of the first shipment block
		//				  to the quick cart page. Whenever an item is dragged into quick cart, say from wish list,
		//				  this info will be used and item will be added to this shipmentBlock (ie, block 1)
		//				  by default.
		// assumptions	: StoreAccordionJS, contains a function by name updateShippingInfoParams, which takes params (java script array object)
		// dojo API		: None
		// returns		: null
		var params = [];
		var temp = document.getElementById(shipmentMapping.addressSelection+"1").value;
		if(temp != -1){
			params.addressId = temp;
		}
		temp = document.getElementById(shipmentMapping.shippingModesSelection+"1").value;
		if(temp != -1){
			params.shipModeId = temp;
		}
		storeAccordionJS.updateShippingInfoParams(params);
	},

	updateSelectBox:function(selectbox, newAddressId){
		// summary		: Updates the number of options in the address select box..
		// description	: Whenever  a new address is created in some shipment block, we need to
		//				  update all the address select box in all the shipment blocks, to add this new address as an option
		//				  Also, when user edits the address, the server assigns a new addressId for this edited address.
		//				  So we need to update all the address select boxes, with this new values, which is done by this function..
		// selectbox	: Select box object, which needs to be updated..
		// newAddressId : addressId of the newly created address or edited address..
		// assumptions	: None
		// dojo API		: None
		// returns		: null
		var temp = dojo.byId(this.addressJSONContainerName).innerHTML;
		addresses = eval('('+ temp +')');
		var i = 0;
		var j = 0;
		//Get the current Selected addressId..
		var currentSelected = selectbox.options[selectbox.selectedIndex].value;
		if(currentSelected == -1){
			//then address is created..so select the new address id..
			currentSelected = newAddressId;
		}
		for(address in addresses){
			selectbox.options[i] = new Option(addresses[address].nickName,addresses[address].addressId);
			if(selectbox.options[i].value == currentSelected){
				j = i;
			}
			i++;
		}
		if(j == 0){
			//then its edit address.. and new address id has been assigned to old address..
			currentSelected = newAddressId;
			for(var k = 0; k < selectbox.length; k++){
				if(selectbox.options[k].value == currentSelected){
					selectbox.options[k].selected = true;
				}
			}
		}
		else {
			selectbox.options[j].selected = true;
		}
		var shippingBlockNumber = ((selectbox.id).split("_")[1]);
		//call address changed..
		this.addressChanged(shippingBlockNumber,selectbox);
	},

	 isEmpty:function(value){
		// summary		: checks if value passed is empty or not
		// description	: checks if value passed is empty or not
		// value		: value that needs to be tested for empty condition
		// assumptions	: None
		// dojo API		: None
		// returns		: false - if not empty
		//				: true - if empty	
		if(value != null && value.length != 0){
			return false;
		}
		return true;
	},

	numberOfShipmentsChanged:function(selectBox){
		// summary		: User changes the number of shipments option
		// description	: When user changes the number of shipments option. If user increases the number
		//				  of shipment, then just display the shipment block div's. But if user
		//				  reduces the number of shipments (say from 2 to 1), then ask him whether to move
		//				  the items from shipment (n) to shipment (1). If so move the items to block 1
		//				  and hide the shipment block divs. If not, just cancel the selection and display
		//				  previously selected option only
		// selectBox	: selectBox object, which contains number of shipments option
		// assumptions	: None
		// dojo API		: None
		// returns		: null
		var current = selectBox.value;
		var shippingDiv = null;
		//Now get the previous number of shipments
		var previous = document.getElementById(shipmentMapping.currentShipmentNumber).value;
		if(current > previous){
			//Its fine..just display the div's ..nothign else to do..
			//ex: previously he had selected 2 , now he has selected 3..
			for(var i = previous; i < parseInt(current)+1; i++){
				var obj = document.getElementById(shipmentMapping.topLevelShipmentBlockDetailsDiv+i);
				dojo.html.show(obj);
			}
			storeAccordionJS.updateShipmentSelectBoxes();
			this.updateMasterShipmentBlockSelectBox(current);
		}
		else{
			//user has decided to reduce the number of shipments..may be from 3 to 1 :-)
			//we always move the extra items to shipment 1...
			var temp = "";
			var message = "";
			var from = "";
			var needToMove = false;
			for(var j = previous; j > current; j--){
				//if Shipment(current) contains items, then it should be moved to shipment 1...
				var orderItemsList = document.getElementById(shipmentMapping.orderItemsList+j).value;
				if(orderItemsList != null && orderItemsList.length > 0){
					needToMove = true;
					//so shipment (j) contains some items..move it to 1...
					if(message == ""){
						message = "Shipment Block "+ j;
						from = j;
					}
					else {
						message = message + "," + "Shipment Block "+ j;
						from = from +","+j;
					}
				}
			}
			if(needToMove){
				//Got the idea of which shipment blocks are moved to shipment 1..ask for confirmation..
				message = "Do you want to move all items from "+message+" to Shipment Block 1"; 
			  	var answer = confirm(message);
				if(answer == true){
					//Hide the shipment blocks, from which items are moved out..
					var fromArray = [];
					from = from+"";
					fromArray = from.split(",");
					for(var n = 0; n < fromArray.length; n++){
						var obj = document.getElementById(shipmentMapping.topLevelShipmentBlockDetailsDiv+fromArray[n]);
						dojo.html.hide(obj);
					}
					//Update our copy of current shipment number...
					document.getElementById(shipmentMapping.currentShipmentNumber).value = current;
					storeAccordionJS.updateShipmentSelectBoxes();
					this.updateMasterShipmentBlockSelectBox(current);

					//Now update the ship id and addressId at the server side...
					this.changeOrderItemsShipmentBlock(from,1);
				}
				else{
					//Dont allow the user to change number of shipments...
					selectBox.value = previous;
					current = previous;
				}
			}
			else {
				//No need to move..just hide the div's 
				for(var i = previous; i > parseInt(current); i--){
					var obj = document.getElementById(shipmentMapping.topLevelShipmentBlockDetailsDiv+i);
					dojo.html.hide(obj);
				}
			}

		}
		//Update our copy of current shipment number...
		document.getElementById(shipmentMapping.currentShipmentNumber).value = current;
		storeAccordionJS.updateShipmentSelectBoxes();
		this.updateMasterShipmentBlockSelectBox(current);
	},
	
	isAddressIdShipModeIdUnique:function(blockNumber){
		// summary		: check for uniquness of shipMode and addressId across all blocks
		// description	: checks if the addressId+shipModeId of the blockNumber passed,
		//				  is equal to addressId+shipModeId of any other block in the shipment page.
		// blockNumber  : the blockNumber, which needs to be tested
		// assumptions	: None
		// dojo API		: None
		// returns		: -1 - if addressId+shipModeId is unique in the entire shipment page
		//				: blockNumber of the block, which contains the same addressId+shipModeId

		//here take care of addressid and shipmode = -1;
		var thisAddressId = document.getElementById(shipmentMapping.addressSelection+blockNumber).value;
		var thisShipModeId = document.getElementById(shipmentMapping.shippingModesSelection+blockNumber).value;
		var thisKey = thisAddressId+"_"+thisShipModeId;
		for(var i = 1; i < 4; i++){
			if( i != blockNumber){
				var addressId = document.getElementById(shipmentMapping.addressSelection+i).value;
				var shipModeId = document.getElementById(shipmentMapping.shippingModesSelection+i).value;
				var key = addressId+"_"+shipModeId;
				if(thisKey == key){
					return i;
				}
			}
		}
		return -1;
	},


	//Show hide advance shipping optiosn
	advanceShippingOptions:function(checkBox,shipmentBlockNumber){
		// summary		: Show/Hide advance shipping options
		// description	: Shows or hides the advance shipping options (instructions and shipping date)
		//				  based on the checkBox value
		// checkBox		: check box object based on which show/hide is decided			  
		// shipmentBlockNumber : The shipment block in which this options needs to be hidden/showed				  
		// assumptions	: None
		// dojo API		: dojo.html.hide
		// returns		: null
		var advanceShippingArea = document.getElementById(this.specifyAdvanceShippingOptionsDivName+shipmentBlockNumber);
		if(checkBox.checked){
			dojo.html.show(advanceShippingArea);
		}
		else{
			//User doesnt want to specify shipping instructions and requested ship date..hide this div..
			dojo.html.hide(advanceShippingArea);
		}
	},

	changeOrderItemsShipmentBlock:function(from,to){
		// summary		: Move the order items from one block to another block
		// description	: This function moves the orderItems from on shipment block to another
		//				  block by invoking "OrderItemShipmentBlockUpdate" service
		//				  Moving from one block to another block means changing the addressId and
		//				  shipModeId of the orderItems which are moved
		// from			: The current shipment block number				  
		// to			: The shipment block number to which items are moved				  
		// assumptions	: None
		// dojo API		: None
		// returns		: null

		//Take care of requested date also.. ..TODO..
		var params = [];
		params.orderId = ".";
		params["storeId"] = this.storeId;
		params["catalogId"] = this.catalogId;
		params["langId"] = this.langId;
		var addressId = document.getElementById(shipmentMapping.addressSelection+to).value;
		var shipModeId = document.getElementById(shipmentMapping.shippingModesSelection+to).value;
		//We can move from more than one block at a time...if from = 2,3.. then all items in shipment 2 and shipment 3 will be moved to shipment 1..
		var fromArray = [];
		from = from+"";
		fromArray = from.split(",");
		//get the orderItems list in fromArray[0]th block..then we can add ","..
		var orderItemsList = document.getElementById(shipmentMapping.orderItemsList+fromArray[0]).value;
		for(var k = 0; k < fromArray.length; k++){
			var t = document.getElementById(shipmentMapping.orderItemsList+fromArray[k]).value;
			if( t != null && t.length > 0){
				orderItemsList = orderItemsList + ","+t;
			}
		}
		//just add the items in the shipment(to) block also..this is needed in a specific case, where a user select address in shipment (1) and the block 1 and block 2 becomes same..
		//so we will move from block 2 to block 1..but since the user has changed address in 1, which is 'to' block, we need to update items inthat block also..
		orderItemsList = orderItemsList + ","+document.getElementById(shipmentMapping.orderItemsList+to).value;
		//alert("this order items will be mvoed..."+orderItemsList);
		var orderItemsArray = [];
		orderItemsArray = orderItemsList.split(",");
		for(var i = 0; i < orderItemsArray.length; i++){
			this.updateParamObject(params,"orderItemId",orderItemsArray[i],false,-1);
			this.updateParamObject(params,"addressId",addressId,false,-1);
			this.updateParamObject(params,"shipModeId",shipModeId,false,-1);
		}

		//Before moving the items from Shipment(from), reset the Shipment(from) blocks shipModeId to 'select shipping Method', so that it becomes unique..
		for(var m = 0; m < fromArray.length; m++){
			document.getElementById(shipmentMapping.shippingModesSelection+fromArray[m]).value = -1;
			document.getElementById(shipmentMapping.shippingModesSelection+fromArray[m]).focus;
		}
		//Also, since we are moving all the items from shipment(from) block, make the requested shipDate and shippingInstructiosn null -- IS THIS NEEDED TODO?
		wc.service.invoke("OrderItemShipmentBlockUpdate", params);
		cursor_wait();
	},

	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;
	 },
	
	updateShippingMethods:function(){
		// summary		: updates the shipping methods of shipment blocks with zero order items
		// description	: Loop through all the shipment blocks and if any shipment block with 0 
		//			      order Items are found, then set the shipping method of that block 
		//				  to 'select Shipping Method'
		// assumptions	: None
		// dojo API		: None
		// returns		: null

		//do not use 4..use total number of shipments variable..TO DO
		for(var i = 1; i < 4; i++){
			var orderItemsList = document.getElementById(shipmentMapping.orderItemsList+i).value;
			if(orderItemsList == null || orderItemsList.length == 0){
				document.getElementById(shipmentMapping.shippingModesSelection+i).value = "-1";
			}
		}
	},

	updateShippingInstructionsForShipmentBlock:function(blockNumber){
		// summary		: Update the shipping instructions
		// description	: Whenever a shipping instructions of a particular shipping block changes,
		//				  update it at the server by invoking "OrderItemAddressShipMethodUpdate" service
		// blockNumber	: the shipment block whose shipping instructions changed
		// assumptions	: None
		// dojo API		: None
		// returns		: null

		//This method is called on change of shipping instructions...
		var params = [];
		params.orderId = ".";
		params["storeId"] = this.storeId;
		params["catalogId"] = this.catalogId;
		params["langId"] = this.langId;
		var addressId = document.getElementById(shipmentMapping.addressSelection+blockNumber).value;
		var shipModeId = document.getElementById(shipmentMapping.shippingModesSelection+blockNumber).value;
		var shipInstructions =  document.getElementById(shipmentMapping.shipInstructions+blockNumber).value;
		var orderItemsList = document.getElementById(shipmentMapping.orderItemsList+blockNumber).value;
		var orderItemsArray = [];
		orderItemsArray = orderItemsList.split(",");

		for(var i = 0; i < orderItemsArray.length; i++){
			this.updateParamObject(params,"orderItemId",orderItemsArray[i],false,-1);
			this.updateParamObject(params,"shipInstructions",shipInstructions,false,-1);
			this.updateParamObject(params,"addressId",addressId,false,-1);
			this.updateParamObject(params,"shipModeId",shipModeId,false,-1);
			
		}
		wc.service.invoke("OrderItemAddressShipMethodUpdate", params);
		cursor_wait();
	},
	

	updateShippingDateForShipmentBlock:function(date,blockNumber){
		// summary		: Update the requested shipment date
		// description	: Whenever a requeseted shipping date of a particular shipping block changes,
		//				  update it at the server by invoking "OrderItemAddressShipMethodUpdate" service
		// blockNumber	: the shipment block whose requested shipping date changed
		// assumptions	: None
		// dojo API		: None
		// returns		: null
		var params = [];
		params.orderId = ".";
		params["storeId"] = this.storeId;
		params["catalogId"] = this.catalogId;
		params["langId"] = this.langId;
		var orderItemsList = document.getElementById(shipmentMapping.orderItemsList+blockNumber).value;
		var orderItemsArray = [];
		orderItemsArray = orderItemsList.split(",");
		for(var i = 0; i < orderItemsArray.length; i++){
			this.updateParamObject(params,"orderItemId",orderItemsArray[i],false,-1);
			this.updateParamObject(params,"requestedShipDate",date,false,-1);
			
		}
		wc.service.invoke("OrderItemAddressShipMethodUpdate", params);
		cursor_wait();
	},

	isValidNumberField:function(UserNumber) {
		// summary		: Verifies for a valid positive number
		// description	: utility function which verifies whether the given number is a valid
		//				  positive number or not..
		// UserNumber	: number which needs to be verified
		// assumptions	: None
		// dojo API		: None
		// returns		: true - if UserNumber is a valid positive number, false - otherwise
	    var validChars = "0123456789";
		// if the string is empty it is not a valid integer
	    if (!UserNumber.match(/[^\\s]/)) return false;
		    // look for non numeric characters in the input string\n");
		  for (var i=0; i<UserNumber.length; i++) {
		       if (validChars.indexOf(UserNumber.substring(i, i+1)) == "-1") {
			         return false;
		        }
		    }
		    // look for bad leading zeroes in the input string
		    if (UserNumber.length > 1 && UserNumber.substring(0,1) == "0") {
				return false;
		   }
	    return true;
	},

	setInGlobalStore:function(params){
		// summary		: Sets the params object in global variable
		// description	: Set the passed params object in global variable (globalparams)
		//				  so that other functions can use them..
		// params		: Java script array object				  
		// assumptions	: a java script object with name globalParams is defined globally
		// dojo API		: None
		// returns		: null
		this.globalParams = params;
	},

	customizedOnSetDateForDojo3:function(event){
		// summary		: Handle the date change in dojo's date picker
		// description	: This function is for dojo0.3 version. Whenever user selects a different
		//				  date in the dataPicker, this function gets called. Here we separate out
		//				  the month,day and year fields and set them in respective readOnly input boxes
		//				  present in the shipment page. Also format the date according to "%Y-%m-%dT%H:%m:%S.%SZ"
		//				  and update the date at server side.
		// event		: event object containing the datePicker variables.
		// assumptions	: None
		// dojo API		: datePicker widgets API's
		// returns		: null
		//Now on select of date in the calendar, this function will be called..
		//separate out month, year and day..and display them in separate text fields..
		var d = new Date(dojo.date.format(this.datePicker.date, this.dateFormat));
		var year = ((d.getYear() % 1900) + 1900);
		shipmentPageJS.setDateFields(d.getDate(),d.getMonth()+1,year,this.inputName);
		this.hideContainer();
		//Now update at the server side..
		var jsDate = this.datePicker.date;
		var t = dojo.date.format(jsDate,"%Y-%m-%dT%H:%m:%S.%SZ");
		//alert(t);
		shipmentPageJS.updateShippingDateForShipmentBlock(t,this.inputName);

	},

	customizedOnSetDateForDojo4:function(event){
		// summary		: Handle the date change in dojo's date picker
		// description	: This function is for dojo0.4 version. Whenever user selects a different
		//				  date in the dataPicker, this function gets called. Here we separate out
		//				  the month,day and year fields and set them in respective readOnly input boxes
		//				  present in the shipment page. Also format the date according to "%Y-%m-%dT%H:%m:%S.%SZ"
		//				  and update the date at server side.
		// event		: event object containing the datePicker variables.
		// assumptions	: None
		// dojo API		: datePicker widgets API's
		// returns		: null

		//Now on select of date in the calendar, this function will be called..
		//separate out month, year and day..and display them in separate text fields..
		var d = new Date(this.datePicker.value);
		var year = ((d.getYear() % 1900) + 1900);
		shipmentPageJS.setDateFields(d.getDate(),d.getMonth()+1,year,this.inputName);
		this.hideContainer();
		//Now update at the server side..
		var jsDate = this.datePicker.value;
		var t = dojo.date.format(jsDate,"%Y-%m-%dT%H:%m:%S.%SZ");
		shipmentPageJS.updateShippingDateForShipmentBlock(t,this.inputName);

	},
	
	setDateFields:function(day,month,year,blockNumber){
		// summary		: Sets the date fields
		// description	: Sets the values passed to this function into the readOnly text boxes
		//				  on the shipment block <blockNumber>
		// day			: Day of the month				  
		// month		: Month (1 to 12)				  
		// year			: Year					  
		// blockNumber	: shipment block number, where these values needs to be set				  
		// assumptions	: None
		// dojo API		: None
		// returns		: null
		document.getElementById("year_"+blockNumber).value = year;
		document.getElementById("month_"+blockNumber).value = month;
		document.getElementById("day_"+blockNumber).value = day;
	},
	
	shipAsComplete:function(checkBox){
		// summary		: Sets shipAsComplete option at the server side.
		// description	: When user toggles the shipAscomplete checkbox, the same will be
		//				  updated at the server side by invoking OrderItemAddressShipMethodUpdate 
		//				  service
		// checkBox		: checkBox object				  
		// assumptions	: Atleast one item is present in the shipment block 1.
		// dojo API		: None
		// returns		: null
		var params = [];
		params.orderId = ".";
		params["storeId"] = this.storeId;
		params["catalogId"] = this.catalogId;
		params["langId"] = this.langId;
		//Params.orderItemId is not needed..but there is some problem with foundation code, so need to pass it as a workaround
		//if there are no items intially, and user checks this box, then it wont work..
		var orderItemsList =  document.getElementById(shipmentMapping.orderItemsList+"1").value;
		var orderItemsArray = [];
		orderItemsArray = orderItemsList.split(",");
		if(orderItemsArray != null){
			this.updateParamObject(params,"orderItemId",orderItemsArray[0],false,-1);
		}
		if(checkBox.checked){
			this.updateParamObject(params,"ShipAsComplete","Y",true);
		}
		else{

			this.updateParamObject(params,"ShipAsComplete","N",true);
		}
		wc.service.invoke("OrderItemAddressShipMethodUpdate", params);
		cursor_wait();
	},

	approveCheckOut:function(){
		// summary		: Is user ready for check Out
		// description	: When user clicks on checkOut, we first need to verify that all
		//				  the shipment blocks contains valid shipModeId and addressId. If not,
		//				  we should not allow him to checkOut
		// assumptions	: None
		// dojo API		: None
		// returns		: true - if all items/shipment block have valid addressId and shipModeId
		//				  false - otherwise		

		//there should not be any invalid addressId, shipModeId in a block containing items..
		for(var i = 1; i < 4; i++){
			var orderItemsList =  document.getElementById(shipmentMapping.orderItemsList+i).value;
			if(orderItemsList != null){
				//This block contains items..so it should have valid address and shipMode id
				var addressId = document.getElementById(shipmentMapping.addressSelection+i).value;
				var shipModeId = document.getElementById(shipmentMapping.shippingModesSelection+i).value;
				if(addressId == "-1" || shipModeId == "-1"){
					return false;
				}
			}
		}
		return true;
	},

	getQuickCartHelperObjects:function(){
		// summary		: Updates the quick cart helper objects
		// description	: Updates the helper objects used by the quick cart to display
		//				  the shipment drop down boxes inside the quick cart.
		// assumptions	: None
		// dojo API		: None
		// returns		: Java script array object, where array size = number of shipments selected

		storeAccordionJS.resetShipmentBlockObject();
		var numberOfShipments = document.getElementById(shipmentMapping.numberOfShipments).value;
		var shipMentBlockobject = [];
		for(var i = 1; i <= numberOfShipments; i++){
			var addressId = document.getElementById(shipmentMapping.addressSelection+i).value;
			var shipModeId = document.getElementById(shipmentMapping.shippingModesSelection+i).value;
			//Update in quick cart page..
			var temp = new Object();
			temp["addressId"] = addressId;
			temp["shipModeId"] = shipModeId;
			shipMentBlockobject.push(temp);
		}
		storeAccordionJS.updateShipmentBlockObject(shipMentBlockobject);
		return shipMentBlockobject;
	},

	temp:function(params,shipmentBlockNumber,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.
		// shipmentBlockNumber : The block number from which address and shipModeId are taken
		// 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,"addressId",addressId,true);
		params = this.updateParamObject(params,"shipModeId",shipModeId,true);
		widget.refresh(params);
	},


	//VVStore Function Start
	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(quantity, orderItemId, gbQty,sltElement){
		// 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.
		//alert(gbQty);
		//var quantity = quantityBox.options[quantityBox.selectedIndex].value;
		if(!isNaN(quantity)){
			var params = [];
			params.orderId		= ".";
			params["storeId"] = this.storeId;
			params["catalogId"] = this.catalogId;
			params["langId"] = this.langId;
			params.calculateOrder="1";
			params["updatePrices"]="1";
			params["calculationUsageId"]="-1";
			params["calculateOrder"] = "1";
			params["backorder"] = "*aig";
			params["backorder"] = "*ubg";
			params["backorder"] = "**";
			params["reverse"] = "*n";
            params["merge"] =  "*n";
            params["remerge"] = "*";
            params["reverse"] = "*n";
			
			if(quantity < gbQty)
				gbQty = quantity;
			this.updateParamObject(params,"orderItemId",orderItemId,false,-1);
			this.updateParamObject(params,"check",orderItemId,false,-1);
			this.updateParamObject(params,"quantity",quantity,false,-1);
			this.updateParamObject(params,"gbQty",gbQty,false,-1);
			this.updateParamObject(params,"allocate","***",false,-1);
			this.updateParamObject(params,"doInventory","Y",false,-1);
			 
			var service = wc.service.declare({
			id: "AjaxUpdateOrderItem",
			actionId: "AjaxUpdateOrderItem",
			url: "AjaxOrderChangeServiceItemUpdate",
			successHandler: function(serviceResponse){
				//wc.service.invoke("AjaxPrepareOrder");
			}, 	
			failureHandler: function(serviceResponse) 
			{
				var message = "Error";
		     	if (serviceResponse.errorMessage) 
		     	{
		     		message = serviceResponse.errorMessage;
	            } 
	            else 
	            {
	            	if (serviceResponse.errorMessageKey) 
	            	{
			     		message = serviceResponse.errorMessageKey;
	                }
	            }
	            var div = document.getElementById("checkOutForm_errorloc");
				div.innerHTML = message;
				jQuery("#checkOutForm_errorloc").slideDown("slow");
				for(var i = 0; i < sltElement.options.length; i++)
				{
					if(sltElement.options[i].value == "")
						{
							sltElement.options[i].selected=true;
						}
				}
	            
			}
		});
			wc.service.invoke("AjaxUpdateOrderItem",params);
			//cursor_wait();
		}
		else
		{
			//Quantity is not number
			//Do you want me to alert user for this?
		}
	},
	
	deleteFromCart:function(orderItemId){
		// summary		: This function removes item(s) from Order.
		// description	: This function removes selected item(s) from current Order.
		//				  Calling this function leads to change in current Order.
		// assumptions	: Form id for 'Quick Cart' should be 'QuickCartForm' and CSS class for the checkbox 
		//				  associated with each orderItem in 'QuickCartForm' shold be 'QuickCartForm_checkboxItems'.
		// dojo API		: dojo.html.getElementsByClass(), dojo.lang.isArrayLike() and dojo.lang.forEach().
		//alert(orderItemId);
		var params = [];
		params.storeId = this.storeId;
		params.catalogId = this.catalogId;
		params.langId = this.langId;
		params.orderId	= ".";
		params.orderItemId = orderItemId;
		params.calculateOrder  = 1;
		wc.service.invoke("AjaxDeleteOrderItem", params);
	},
	refreshSize : function(selColor,productId){
		var params = [];
		params.storeId = this.storeId;
		params.catalogId = this.catalogId;
		params.langId = this.langId;
		params.orderId	= ".";
		params.color = selColor;
		params.productId = productId;
		//alert(selColor);
		wc.service.invoke("AjaxSizeDisplay", params);
	
	},
	addToWishList:function(catEntryIdentifier,orderItemId){
		var params = [];
		params.storeId = this.storeId;
		params.catalogId = this.catalogId;
		params.langId = this.langId;
		params.catEntryId	= catEntryIdentifier;
		params.URL = "WishListInformationView";
		params.orderId	= ".";
		params.orderItemId = orderItemId;
		params.calculateOrder  = 1;
		
		var service = wc.service.declare({
			id: "AjaxInterestItemAdd",
			actionId: "AjaxInterestItemAdd",
			url: "AjaxInterestItemAdd",
				
			successHandler: function(serviceResponse) {
				wc.service.invoke("AjaxDeleteOrderItem", params);
			},
			failureHandler: function(serviceResponse) {
				//TO DO - handle error
				alert(serviceResponse.errorMessage);
			}
		});
		
		wc.service.invoke("AjaxInterestItemAdd", params);
	},
	
	deleteToWishList:function(catEntryIdentifier){
		var params = [];
		params.storeId = this.storeId;
		params.catalogId = this.catalogId;
		params.langId = this.langId;
		params.catEntryId	= catEntryIdentifier;
		params.quantity = 1;
		params.URL = "WishListInformationView";
		wc.service.invoke("AjaxInterestItemDelete", params);
	},

	ajaxMoveToCart:function(catEntryIdentifier){
		var params = [];
		params.storeId = this.storeId;
		params.catalogId = this.catalogId;
		params.langId = this.langId;
		params.catEntryId	= catEntryIdentifier;
		params.quantity = 1;
		params.calculateOrder="1";
		
		var shipModeDOMObj = document.getElementById("shpMode");
		
		if (shipModeDOMObj != null) {
			if(shipModeDOMObj.value !="" && shipModeDOMObj.value != null) {
				params["shipModeId"]=shipModeDOMObj.value;
			}
		}
		
		var service = wc.service.declare({
			id: "AjaxInterestItemMove",
			actionId: "AjaxInterestItemMove",
			url: "AjaxOrderChangeServiceItemAdd",
				
			successHandler: function(serviceResponse) {
				wc.service.invoke("AjaxInterestItemDelete", params);
				wc.service.invoke("AjaxPrepareOrder");
			},
			failureHandler: function(serviceResponse) {
				//TO DO - handle error
				alert(serviceResponse.errorMessageKey);
			}
		});
		
		wc.service.invoke("AjaxInterestItemMove", params);
	},

	
	 
	applyPromotionCode:function(formName) {
		var form = document.forms[formName];
		if (form.lpromoCode.value == "") {
			return;
		} else {
			form.promoCode.value = form.lpromoCode.value;
			service = wc.service.getServiceById('AjaxPromotionCodeManage');
			service.formId = formName;
			wc.service.invoke('AjaxPromotionCodeManage');
		}
	},
	
	removePromotionCode:function(formName, promoCode) {
		var form = document.forms[formName];
		service = wc.service.getServiceById('AjaxPromotionCodeManage');
		service.formId = formName;
		form.taskType.value='R';
		form.promoCode.value=promoCode;
		wc.service.invoke('AjaxPromotionCodeManage');
	},
	setPromoCode:function(prCode){
		this.prCd = prCode;
	},
	getPromoCode:function(){
		return this.prCd;
	},
	clearPromoCode:function(){
		this.prCd = "";
		jQuery("#coupon-code-accepted").html("");
		
	},
	applyAttributeChange:function(itemColor,itemSize,entitledItemInbutBoxId,quantity,giftbox,orderItemId,sltElement) {
		
		var colorString = "select_color_" + orderItemId;
		var sizeString = "select_size_" + orderItemId;
		
		var domObjectColor = document.getElementById(colorString);
		var colorAttr = domObjectColor.options[domObjectColor.selectedIndex].value;

		var domObjectSize = document.getElementById(sizeString);
		var sizeAttribute = domObjectSize.options[domObjectSize.selectedIndex].value;

		if(colorAttr == -1 && sizeAttribute == -1)
			return;
		
		if (colorAttr == -1)
			colorAttr = itemColor;

		if (sizeAttribute == -1)
			sizeAttribute = itemSize;		

		// Call the modify order item attribute function
		this.modifyOIAttribute(colorAttr,sizeAttribute,entitledItemInbutBoxId,quantity,giftbox,orderItemId,sltElement);
	},	
	modifyOIAttribute:function(colorAttr,sizeAttribute,entitledItemInbutBoxId,quantity,giftbox,orderItemId,sltElement){
		if(colorAttr == -1 || sizeAttribute == -1)
			return;
		var params = [];
		var entitledItemJSON = eval('('+ dojo.byId(entitledItemInbutBoxId).innerHTML +')');
		this.setEntitledItems(entitledItemJSON);
		this.setSelectedAttribute("Color",colorAttr);
		this.setSelectedAttribute("Size",sizeAttribute);
		var catalogEntryId = this.getCatalogEntryId();
			
		if(catalogEntryId != null){
		
			params.storeId		= this.storeId;
			params.catalogId	= this.catalogId;
			params.langId			= this.langId;
			params.orderId		= ".";
			params.catEntryId	= catalogEntryId;
			params.quantity = quantity;
			params.gbQty = giftbox;
			params.calculateOrder  = 1;
		
			var service = wc.service.declare({
		
			id: "AjaxModifyOrderItemAttribute",
			actionId: "AjaxModifyOrderItemAttribute",
			url: "AjaxOrderChangeServiceItemAdd",
				
			successHandler: function(serviceResponse) {
				shipmentPageJS.deleteFromCart(orderItemId);
			},
			failureHandler: function(serviceResponse) {
				var div = document.getElementById("checkOutForm_errorloc");
				div.innerHTML = serviceResponse.errorMessageKey;
				jQuery("#checkOutForm_errorloc").slideDown("slow");
				for(var i = 0; i <sltElement.options.length; i++){
					if(sltElement.options[i].value == -1)
					{
						sltElement.options[i].selected=true;
					}
				}
			}
		});
			
			wc.service.invoke("AjaxModifyOrderItemAttribute", params);
		}
		else{
			alert(this.getErrorMessage("ERR_RESOLVING_SKU"));
		}
	},
	
	addCatEntry:function(colorAttr,sizeAttribute,entitledItemInbutBoxId,quantity,giftbox){
		if(colorAttr == -1 || sizeAttribute == -1)
			return;
		var params = [];
		var entitledItemJSON = eval('('+ dojo.byId(entitledItemInbutBoxId).innerHTML +')');
		this.setEntitledItems(entitledItemJSON);
		this.setSelectedAttribute("Color",colorAttr);
		this.setSelectedAttribute("Size",sizeAttribute);
		var catalogEntryId = this.getCatalogEntryId();
		if(dojo.byId("shpMode")!=null && dojo.byId("shpMode").value !="" && dojo.byId("shpMode").value != null){
			params["shipModeId"]=dojo.byId("shpMode").value;
		}
		
		if(catalogEntryId != null){
			params.storeId		= this.storeId;
			params.catalogId	= this.catalogId;
			params.langId			= this.langId;
			params.orderId		= ".";
			params.catEntryId	= catalogEntryId;
			params.quantity = quantity;
			params.gbQty = giftbox;
			params.calculateOrder  = 1;
			wc.service.invoke("AjaxAddOrderItem", params);
		}
		else{
			alert(this.getErrorMessage("ERR_RESOLVING_SKU"));
		}
	},
	
	
	setEntitledItems : function(entitledItemArray){
		this.entitledItems = entitledItemArray;
	},
	
	setSelectedAttribute : function(selectedAttributeName , selectedAttributeValue){
		//alert(selectedAttributeName +" : "+ selectedAttributeValue);
		this.selectedAttributes[selectedAttributeName] = selectedAttributeValue;
	},
	
	getCatalogEntryId : function(){
		var attributeArray = [];
		for(attribute in this.selectedAttributes){
			attributeArray.push(attribute + "_" + this.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 ++;
			//alert(attributeArrayCount + ":" + 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;
	},
	
	guestLogon : function(formName){
		var params = [];
		params.type="";
		wc.service.invoke('AjaxGuestLogon',params);		
	},
	
	doShopSubmit : function(formName,vUrl){ 
		
		document.forms[formName].action = vUrl;
		document.forms[formName].submit();
		
	},
	
	
	// VVStore Function End.
	
	showAvailableShippingBlocks:function(imageId,itemId,shipmentBlock){
		// summary		: Display the select box to select the shipment block to move the item
		// description	: Gets the number of shipments currently available and updates the select box
		//				  with this number of options. Hides the shopCart image and displays the select box 	
		//				  This function is called onMouseOver of the shopCart image, in shipment page	
		// imageId		: Id of the image on which mouseOver event occured.
		// itemId		: The itemId corresponding to this image. Means, the itemId which will be moved
		//				  when user selects the shipment block from the drop down box
		// shipmentBlock: The current shipmentBlock, to which this itemId belongs to.
		// assumptions	: None.
		// dojo API		: None.

		var temp = document.getElementById(imageId);
		temp.innerHTML = document.getElementById(shipmentMapping.masterShipmentBlockSelectBoxDiv).innerHTML;
		document.getElementById(shipmentMapping.shipmentBlockChangedForThisOrderItemId).value = itemId;
		document.getElementById(shipmentMapping.currentShipmentBlockOfThisOrderItemId).value= shipmentBlock;
		dojo.html.show(temp);
		dojo.html.hide(document.getElementById(shipmentMapping.cart_icon_div+itemId));
		document.getElementById(shipmentMapping.masterShipmentBlockSelectBox).value=shipmentBlock;
		//We dont want to keep showing the select box..need to hide it after showSelectBoxFor time elapses.
		dojo.lang.setTimeout(shipmentPageJS,"showImage",this.showSelectBoxFor,itemId);
	},

	orderItemShipmentBlockChanged:function(selectBox){
		// summary		: When a different shipmentBlock is selected for the item
		// description	: This function will be called onChange of the shipment block in the drop down
		//				  box, which will be used to move item from one block to another. This function
		//				  checks whether the current shipping block and selected block are same or not.. If same
		//				  it just returns, if not, it verifies that there is a valid addressId and the shipModeId
		//				  in the selected shipmentBlock. If so, it moves the item to that block by calling
		//				  OrderItemShipmentBlockUpdate service.	
		// selectBox	: The selectBox object, in which ONChange event occured.
		// assumptions	: None.
		// dojo API		: None.

		//hide the select box and show the image again..
		this.showImage();
		var newShippingBlock = selectBox.value;
		var currentShippingBlock = document.getElementById(shipmentMapping.currentShipmentBlockOfThisOrderItemId).value;
		if(newShippingBlock == currentShippingBlock){
			return;
		}
		else
		{
			//check if its dropped in proper area or not..
			if(!this.isValidBlock(newShippingBlock)){
				var messageToUse = this.errorMessages["SHIPPING_VALID_ADDRESS_SHIPPING"];
				messageToUse = messageToUse.replace(/%0/, newShippingBlock);
				alertDialog(messageToUse,this.storeId,this.catalogId,this.langId);
				selectBox.value = currentShippingBlock;
				return false;
			}
			//Need to move..
			var newAddressId = document.getElementById(shipmentMapping.addressSelection+newShippingBlock).value;
			var newShipModeId = document.getElementById(shipmentMapping.shippingModesSelection+newShippingBlock).value;
			var movedOrderItemId = document.getElementById(shipmentMapping.shipmentBlockChangedForThisOrderItemId).value;
			var params = [];
			params.orderId = ".";
			params["storeId"] = this.storeId;
			params["catalogId"] = this.catalogId;
			params["langId"] = this.langId;
			this.updateParamObject(params,"orderItemId",movedOrderItemId,false,-1);
			this.updateParamObject(params,"addressId",newAddressId,false,-1);
			this.updateParamObject(params,"shipModeId",newShipModeId,false,-1);
			wc.service.invoke("OrderItemShipmentBlockUpdate", params);
			cursor_wait();
		}
	},

	updateMasterShipmentBlockSelectBox:function(totalOptions){
		// summary		: Updates the master shipment block select box with number of shipments available
		// description	: Will be called, whenever the number of shipments changes.
		// totalOptions	: The number of shipments currently available to shopper
		// assumptions	: None.
		// dojo API		: None.
		var selectBox = document.getElementById(shipmentMapping.masterShipmentBlockSelectBox);
		selectBox.options.length = 0;
		for(var i = 0; i < totalOptions; i++){
			selectBox.options[i] = new Option(i+1,i+1);
		}
		var temp = document.getElementById(shipmentMapping.masterShipmentBlockSelectBoxDiv);
		temp.innerHTML = document.getElementById(shipmentMapping.masterShipmentBlockSelectBoxDiv).innerHTML;
	},
	
	showImage:function(itemId){
		// summary		: Hides the shopCart image and displays the select box to choose a
		//				  different shipment block for the item.
		// description	: Will be called, whenever the number of shipments changes.This
		//				  select box will be visible for <showSelectBoxFor> seconds...	
		// totalOptions	: The number of shipments currently available to shopper
		// assumptions	: None.
		// dojo API		: None.
		//hide the select box and show the image again..
		if(itemId == null || itemId == 0){
			itemId = document.getElementById(shipmentMapping.shipmentBlockChangedForThisOrderItemId).value;
		}
		dojo.html.hide(document.getElementById(itemId));
		dojo.html.show(document.getElementById(shipmentMapping.cart_icon_div+itemId));
	},

	showSelectBox:function(itemId){
		// summary		: Hides the select box used to choose a
		//				  different shipment block for the item.
		// description	: will be called after <showSelectBoxFor> time elapses.
		// itemId		: The itemId for which the select box was displayed.
		// assumptions	: None.
		// dojo API		: None.
		//hide the image and show the select box again..
		if(itemId == null || itemId == 0){
			itemId = document.getElementById(shipmentMapping.shipmentBlockChangedForThisOrderItemId).value;
		}
		dojo.html.show(document.getElementById(itemId));
		dojo.html.hide(document.getElementById(shipmentMapping.cart_icon_div+itemId));
	},

	updateAddressIdForOrderItem:function(itemIds, addressId){
		if(itemIds == null || itemIds.length == 0 || addressId == null || addressId.length == 0){
			return true;
		}
		var params = [];
		params.orderId = ".";
		params["storeId"] = this.storeId;
		params["catalogId"] = this.catalogId;
		params["langId"] = this.langId;
		var orderItemsList =  itemIds;
		var orderItemsArray = [];

		orderItemsArray = orderItemsList.split(",");
		for(var i = 0; i < orderItemsArray.length; i++){
			this.updateParamObject(params,"orderItemId",orderItemsArray[i],false,-1);
			this.updateParamObject(params,"addressId",addressId,false,-1);
		}

		//Declare the service...
		var service = wc.service.declare({
			id: "AjaxSetAddressIdOfOrderItems",
			actionId: "AjaxSetAddressIdOfOrderItems",
			url: "AjaxOrderChangeServiceShipInfoUpdate",
			successHandler: function(serviceResponse) {
				cursor_clear();
				document.location.href="AjaxCheckoutDisplayView?langId="+shipmentPageJS.langId+"&storeId="+shipmentPageJS.storeId+"&catalogId="+shipmentPageJS.catalogId;
			},
			failureHandler: function(serviceResponse) {
				cursor_clear();
			}
		});
		wc.service.invoke("AjaxSetAddressIdOfOrderItems", params);
		cursor_wait();
	},
	
	addItemToWishList:function(colorAttr,sizeAttribute,entitledItemInbutBoxId,quantity){
	
	if(colorAttr == -1 || sizeAttribute == -1)
			return;
		var params = [];
		var entitledItemJSON = eval('('+ dojo.byId(entitledItemInbutBoxId).innerHTML +')');
		this.setEntitledItems(entitledItemJSON);
		this.setSelectedAttribute("Color",colorAttr);
		this.setSelectedAttribute("Size",sizeAttribute);
		var catalogEntryId = this.getCatalogEntryId();
		if(catalogEntryId != null){
			params.storeId		= this.storeId;
			params.catalogId	= this.catalogId;
			params.langId		= this.langId;
			params.orderId		= ".";
			params.catEntryId	= catalogEntryId;
			params.quantity = quantity;
			params.calculateOrder  = 1;

		}
		else{
			alert(this.getErrorMessage("ERR_RESOLVING_SKU"));
		}
		
		var service = wc.service.declare({
			id: "AjaxInterestItemAdd",
			actionId: "AjaxInterestItemAdd",
			url: "AjaxInterestItemAdd",
			failureHandler: function(serviceResponse) {
				alert(serviceResponse.errorMessage);
			}
		});
		
		wc.service.invoke("AjaxInterestItemAdd", params);
	}
}

// TO DO.. AjaxUpdateOrderItem is the service.. do we need to call prepareOrder after this service call also..
