//-----------------------------------------------------------------
// Licensed Materials - Property of IBM
//
// WebSphere Commerce
//
// (C) Copyright IBM Corp. 2007, 2009 All Rights Reserved.
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with
// IBM Corp.
//-----------------------------------------------------------------

/**
 * @fileOverview This Javascript file contains functions to declare the gift registry services.
 *
 * @version 1.0
 */


dojo.require("wc.render.common");

/** 
 * @class The GRServicesDeclaration class defines all the common variables and functions 
 * for the controllers of the defined render contexts across all store pages.
 */
GRServicesDeclaration = {
       /**
        * Sets the URL of the specified controller.
        * 
        * @param {string} controllerId The id of the target controller.
        * @param {string} url The link to specify for the controller.
        */       
       setControllerURL:function(controllerId,url){
			wc.render.getRefreshControllerById(controllerId).url = url;
       }

}
 
//Start of Services declaration section

/**
 * Declares the create gift registry service 
 */

wc.service.declare({
		id: "AjaxGiftRegistryCreateService",
		url: "AjaxGiftListServiceCreate",
		formId: "GiftRegistryCreateForm",
		/**
		 * display a success message
		 * @param (object) serviceResponse The service response object, which is the
		 * JSON object returned by the service invocation
		 */
		successHandler : function(serviceResponse){
			cursor_clear();
			var redirectURL = "GiftRegistryCreateSuccessView?storeId=" + GRCommonUtilsJS.storeId 
							+ "&catalogId=" + GRCommonUtilsJS.catalogId
							+ "&langId=" + GRCommonUtilsJS.langId
							+ "&externalId=" + serviceResponse.externalId;
			document.location.href = redirectURL;
		},
		/**
		 * display an error message
		 * @param (object) serviceResponse The service response object, which is the
		 * JSON object returned by the service invocation
		 */
		failureHandler : function(serviceResponse){
			cursor_clear();
			if (serviceResponse.errorMessage) {
				//If Gift Registry wants to override this errorMessage with it's own..
				if(MessageHelper.messages[serviceResponse.errorMessageKey] != null && MessageHelper.messages[serviceResponse.errorMessageKey] != undefined){
					MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessageKey]);
				}
				else {
					//Display default error message..
					MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				}
			} else if (serviceResponse.errorMessageKey) {
				//No message set..Display message key..
				MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
			}
			GRCreateRegistryHelper.displayGRCreateForm();
		}
});

/**
* Service declaration to add an item to gift regisry.
*/   
wc.service.declare({
	id: "AjaxAddOrderItemToGiftRegistry",
	actionId: "AjaxAddOrderItemToGiftRegistry",
	url: getAbsoluteURL() + "AjaxGiftListServiceAddItem",
	formId: ""

	 /**
	 * display a success message
	 * @param (object) serviceResponse The service response object, which is the
	 * JSON object returned by the service invocation
	 */

	,successHandler: function(serviceResponse) {
		MessageHelper.hideAndClearMessage();
		MessageHelper.displayStatusMessage(MessageHelper.messages["GR_ITEM_ADDED"]);
		cursor_clear();

		if(categoryDisplayJS){
			var attributes = document.getElementsByName("attrValue");
			var singleSKU = true;
			// Reset attributes
			for(var i = 0; i < attributes.length; i++){
				if (attributes[i].options.length > 1){
					singleSKU = false;
					break;
				}
			}
			
			if (!singleSKU){
				categoryDisplayJS.selectedAttributes = [];
				for(var i = 0; i < attributes.length; i++){
					if(attributes[i] != null){
						attributes[i].value = "";
					}
				}
			}
		}
	}
	 /**
	 * display an error message
	 * @param (object) serviceResponse The service response object, which is the
	 * JSON object returned by the service invocation
	 */
	,failureHandler: function(serviceResponse) {

		if (serviceResponse.errorMessage) {
			//If Gift Registry wants to override this errorMessage with it's own..
			if(MessageHelper.messages[serviceResponse.errorMessageKey] != null && MessageHelper.messages[serviceResponse.errorMessageKey] != undefined){
				MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessageKey]);
			}
			else {
				//Display default error message..
				MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
			}
		} else if (serviceResponse.errorMessageKey) {
			//No message set..Display message key..
			MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
		}
		cursor_clear();
	}

});

/**
 * Declares the service to delete an item from the gift registry
 */
wc.service.declare({
		id: "AjaxGiftRegistryItemDelete",
		actionId: "AjaxGiftRegistryItemDelete",
		url: "AjaxGiftListServiceDeleteItem",
		/**
		 * display a success message
		 * @param (object) serviceResponse The service response object, which is the
		 * JSON object returned by the service invocation
		 */
		successHandler : function(serviceResponse){
			dojo.publish("GR_itemDeleteSuccessful_" + serviceResponse.giftListItemId);
		},
		/**
		 * display an error message
		 * @param (object) serviceResponse The service response object, which is the
		 * JSON object returned by the service invocation
		 */
		failureHandler : function(serviceResponse){
			dojo.publish("GR_itemDeleteFailure_" + serviceResponse.giftListItemId);
			cursor_clear();
			if (serviceResponse.errorMessage) {
				//If Gift Registry wants to override this errorMessage with it's own..
				if(MessageHelper.messages[serviceResponse.errorMessageKey] != null && MessageHelper.messages[serviceResponse.errorMessageKey] != undefined){
					MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessageKey]);
				}
				else {
					//Display default error message..
					MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				}
			} else if (serviceResponse.errorMessageKey) {
				//No message set..Display message key..
				MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
			}
		}
});

/**
 * Declares the service to update an item in the gift registry.
 */
wc.service.declare({
		id: "AjaxGiftRegistryItemUpdate",
		actionId: "AjaxGiftRegistryItemUpdate",
		url: "AjaxGiftListServiceUpdateItem",
		/**
		 * display a success message
		 * @param (object) serviceResponse The service response object, which is the
		 * JSON object returned by the service invocation
		 */
		successHandler : function(serviceResponse){
			dojo.publish("GR_itemUpdateSuccessful_" + serviceResponse.giftListItemId);
		},
		/**
		 * display an error message
		 * @param (object) serviceResponse The service response object, which is the
		 * JSON object returned by the service invocation
		 */
		failureHandler : function(serviceResponse){
			dojo.publish("GR_itemUpdateFailure_" + serviceResponse.giftListItemId);
			cursor_clear();
			if (serviceResponse.errorMessage) {
				//If Gift Registry wants to override this errorMessage with it's own..
				if(MessageHelper.messages[serviceResponse.errorMessageKey] != null && MessageHelper.messages[serviceResponse.errorMessageKey] != undefined){
					MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessageKey]);
				}
				else {
					//Display default error message..
					MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				}
			} else if (serviceResponse.errorMessageKey) {
				//No message set..Display message key..
				MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
			}
		}
});

/**
 * Declares the service to update the gift registry profile.
 */
wc.service.declare({
		id: "AjaxGiftListServiceUpdateGiftList",
		url: "AjaxGiftListServiceUpdateGiftList",
		formId: "GiftRegistryCreateForm",
		successHandler : function(serviceResponse){
			cursor_clear();
			var redirectURL = "GiftRegistryProfileDisplayView?storeId=" + GRCommonUtilsJS.storeId 
							+ "&catalogId=" + GRCommonUtilsJS.catalogId
							+ "&langId=" + GRCommonUtilsJS.langId
							+ "&externalId=" + serviceResponse.externalId
							+ "&displayConfirmPage=true";
			document.location.href = redirectURL;
		},
		failureHandler : function(serviceResponse){
			cursor_clear();
			if (serviceResponse.errorMessage) {
				//If Gift Registry wants to override this errorMessage with it's own..
				if(MessageHelper.messages[serviceResponse.errorMessageKey] != null && MessageHelper.messages[serviceResponse.errorMessageKey] != undefined){
					MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessageKey]);
				}
				else {
					//Display default error message..
					MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				}
			} else if (serviceResponse.errorMessageKey) {
				//No message set..Display message key..
				MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
			}
		}
});

/**
 * Declares the service to delete the gift registry profile.
 */
wc.service.declare({
		id: "AjaxGiftListServiceDelete",
		url: "AjaxGiftListServiceDeleteGiftList",
		successHandler : function(serviceResponse){
			cursor_clear();
			var redirectURL = "GiftRegistryListSelectionView?storeId=" + GRCommonUtilsJS.storeId 
							+ "&catalogId=" + GRCommonUtilsJS.catalogId
							+ "&langId=" + GRCommonUtilsJS.langId;
			document.location.href = redirectURL;
		},
		failureHandler : function(serviceResponse){
			cursor_clear();
			if (serviceResponse.errorMessage) {
				//If Gift Registry wants to override this errorMessage with it's own..
				if(MessageHelper.messages[serviceResponse.errorMessageKey] != null && MessageHelper.messages[serviceResponse.errorMessageKey] != undefined){
					MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessageKey]);
				}
				else {
					//Display default error message..
					MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				}
			} else if (serviceResponse.errorMessageKey) {
				//No message set..Display message key..
				MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
			}
		}
});

/**
 * Declares the service to authenticate co-registrant in the edit registry flow.
 */
wc.service.declare({
		id: "GiftListServiceManageAuthenticate",
		url: "AjaxGiftListServiceAuthenticate",
		formId: "",
		successHandler : function(serviceResponse){
			cursor_clear();
			var redirectURL = "GiftRegistryManageView?storeId=" + GRCommonUtilsJS.storeId 
							+ "&catalogId=" + GRCommonUtilsJS.catalogId
							+ "&langId=" + GRCommonUtilsJS.langId
							+ "&externalId=" + serviceResponse.externalId;
			document.location.href = redirectURL;
		},
		failureHandler : function(serviceResponse){
			cursor_clear();
			if (serviceResponse.errorMessage) {
				//If Gift Registry wants to override this errorMessage with it's own..
				if(MessageHelper.messages[serviceResponse.errorMessageKey] != null && MessageHelper.messages[serviceResponse.errorMessageKey] != undefined){
					MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessageKey]);
				}
				else {
					//Display default error message..
					MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				}
			} else if (serviceResponse.errorMessageKey) {
				//No message set..Display message key..
				MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
			}
		}
});

/**
 * Declares the service to complete a gift registry.
 */
wc.service.declare({
		id: "AjaxGiftListServiceCompleteGiftList",
		url: "AjaxGiftListServiceCompleteGiftList",
		successHandler : function(serviceResponse){
			cursor_clear();
			var redirectURL = "GiftRegistryCompleteView?storeId=" + GRCommonUtilsJS.storeId 
							+ "&catalogId=" + GRCommonUtilsJS.catalogId
							+ "&langId=" + GRCommonUtilsJS.langId
							+ "&externalId=" + serviceResponse.externalId;
			document.location.href = redirectURL;
		},
		failureHandler : function(serviceResponse){
			cursor_clear();
			if (serviceResponse.errorMessage) {
				//If Gift Registry wants to override this errorMessage with it's own..
				if(MessageHelper.messages[serviceResponse.errorMessageKey] != null && MessageHelper.messages[serviceResponse.errorMessageKey] != undefined){
					MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessageKey]);
				}
				else {
					//Display default error message..
					MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				}
			} else if (serviceResponse.errorMessageKey) {
				//No message set..Display message key..
				MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
			}
		}
});

/**
 * Declares the service to update purchase record (registrant memo and thank you note setn) in received gifts page.
 */
wc.service.declare({
		id: "AjaxGiftListServiceUpdatePurchaseRecord",
		url: "AjaxGiftListServiceUpdatePurchaseRecord",
		formId: "",
		successHandler : function(serviceResponse){
			dojo.publish("GR_purchaseRecordUpdateSuccessful_" + serviceResponse.externalId);
			MessageHelper.hideAndClearMessage();
			MessageHelper.displayStatusMessage(MessageHelper.messages["GR_PURCHASE_RECORD_UPDATED"]);
		},
		failureHandler : function(serviceResponse){
			dojo.publish("GR_purchaseRecordUpdateFailure_" + serviceResponse.externalId);
			cursor_clear();
			if (serviceResponse.errorMessage) {
				//If Gift Registry wants to override this errorMessage with it's own..
				if(MessageHelper.messages[serviceResponse.errorMessageKey] != null && MessageHelper.messages[serviceResponse.errorMessageKey] != undefined){
					MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessageKey]);
				}
				else {
					//Display default error message..
					MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				}
			} else if (serviceResponse.errorMessageKey) {
				//No message set..Display message key..
				MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
			}
		}
});
/**
 * Declares the service to announce gift registry.
 */
wc.service.declare({
		id: "AjaxGiftListServiceAnnounceGiftList",
		url: "AjaxGiftListServiceAnnounceGiftList",
		formId: "SendAnnouncementForm",
		successHandler : function(serviceResponse){
			cursor_clear();
			var redirectURL = "GiftRegistryAnnouncementHistoryView?storeId=" + GRCommonUtilsJS.storeId 
							+ "&catalogId=" + GRCommonUtilsJS.catalogId
							+ "&langId=" + GRCommonUtilsJS.langId
							+ "&externalId=" + serviceResponse.giftListId;
			document.location.href = redirectURL;
		},
		failureHandler : function(serviceResponse){
			cursor_clear();
			if (serviceResponse.errorMessage) {
				//If Gift Registry wants to override this errorMessage with it's own..
				if(MessageHelper.messages[serviceResponse.errorMessageKey] != null && MessageHelper.messages[serviceResponse.errorMessageKey] != undefined){
					MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessageKey]);
				}
				else {
					//Display default error message..
					MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				}
			} else if (serviceResponse.errorMessageKey) {
				//No message set..Display message key..
				MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
			}
		}
});

/**
 * Declares an AJAX service that updates the shipping address for the gift items in single shipment scenario.
 * @constructor 
 */
wc.service.declare({
	id: "AjaxOrderChangeServiceGiftInfoUpdate",
	actionId: "",
	url: "AjaxOrderChangeServiceGiftInfoUpdate",
	formId: ""
	
	/**
	 * hides all the messages and the progress bar
	 * @param (object) serviceResponse The service response object, which is the
	 * JSON object returned by the service invocation
	 */
	,successHandler: function(serviceResponse) {
		MessageHelper.hideAndClearMessage();
		cursor_clear();
	}
	
	/**
	 * Displays the error message returned with the service response and hides the progress bar.
	 *
	 * @param (object) serviceResponse The service response object, which is the JSON object returned by the service invocation.
	 */
	,failureHandler: function(serviceResponse) {
		if (serviceResponse.errorMessage) {
			//If Gift Registry wants to override this errorMessage with it's own..
			if(MessageHelper.messages[serviceResponse.errorMessageKey] != null && MessageHelper.messages[serviceResponse.errorMessageKey] != undefined){
				MessageHelper.displayErrorMessage(MessageHelper.messages[serviceResponse.errorMessageKey]);
			}
			else {
				//Display default error message..
				MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
			}
		} else if (serviceResponse.errorMessageKey) {
			//No message set..Display message key..
			MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
		}
		cursor_clear();
	}

});
//End of Services declaration section

//Start of Contexts declaration section

/**
 * Declares a new render context for Gift Registry Create Page for the different registry types.
 */
wc.render.declareContext("registrantInfoDisplay_Context", {"registryType" : ""}, "");

/**
 * Declares a new render context for Gift Registry Search Results page.
 */
wc.render.declareContext("giftRegistrySearchResultsDisplay_Context", {findSimilarMatches: "false", beginIndex: "0", firstName: "", lastName: "", email: "", eventDate: "", state: "", externalId: ""}, "");
/**
 * Declares a new render context for My Registry List page.
 */
wc.render.declareContext("myRegistryListDisplay_Context", {beginIndex: "0"}, "");

//End of Contexts declaration section

//Start of Refresh Controllers declaration section

/** 
 * Declares a new refresh controller to refresh the registrant and/or co-registrant information
 * based on the registry type selected on the gift registry create page
 */

wc.render.declareRefreshController({
	id: "registrantInfoDisplay_Controller",
	renderContext: wc.render.getContextById("registrantInfoDisplay_Context"),
	url: "${DisplayRegistrantInfoURL}",
	
	renderContextChangedHandler: function(message, widget) {					
		var controller = this;
		var renderContext = this.renderContext;
		if(controller.testForChangedRC(["registryType"])) {
			var regType = renderContext.properties["registryType"];
			/* Handles multiple clicks */
			if(!submitRequest()){
				return;
			}
			cursor_wait();
			widget.refresh({"registryType": regType});
		}
	},									
	postRefreshHandler : function(widget){
		cursor_clear();
		var registryType = this.renderContext.properties["registryType"];		
		console.debug("postRefreshHandler() > Selected registry type : " + registryType);
		GRFormValidator.updateRegistrantInfo(registryType);
	}
});

/** 
 * Declares a new refresh controller to refresh the gift registry search information
 * based on the search type selected and search parameters provided on the gift registry search results page
 */
 
 wc.render.declareRefreshController({
	id: "giftRegistrySearchResultsDisplay_Controller",
	renderContext: wc.render.getContextById("giftRegistrySearchResultsDisplay_Context"),
	url: "",
	formId: "",
							
	renderContextChangedHandler: function(message, widget) {
		console.debug(" inside renderContextChangedHandler() function of giftRegistrySearchResultsDisplay_Controller");
		var controller = this;
		var renderContext = this.renderContext;	
		widget.refresh(renderContext.properties);
		console.debug("after widget.refresh() call in renderContextChangedHandler() function of giftRegistrySearchResultsDisplay_Controller");
	},
							
	postRefreshHandler: function(message, widget) {
		cursor_clear();
	}
});

/** 
 * Declares a new refresh controller to show Registry List on a user
 */
 
 wc.render.declareRefreshController({
	id: "myRegistryListDisplay_Controller",
	renderContext: wc.render.getContextById("myRegistryListDisplay_Context"),
	url: "",
							
	renderContextChangedHandler: function(message, widget) {
		console.debug(" inside renderContextChangedHandler() function of myRegistryListDisplay_Controller");
		var controller = this;
		var renderContext = this.renderContext;
		widget.refresh(renderContext.properties);
		console.debug("after widget.refresh() call in renderContextChangedHandler() function of myRegistryListDisplay_Controller");
	},
							
	postRefreshHandler: function(message, widget) {
		cursor_clear();
	}
});

//End of Refresh Controllers declaration section



