//-----------------------------------------------------------------
// Licensed Materials - Property of IBM
//
// WebSphere Commerce
//
// (C) Copyright IBM Corp. 2008 All Rights Reserved.
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with
// IBM Corp.
//-----------------------------------------------------------------

/**
 * @fileOverview This javascript contains declarations of AJAX services used within
 * WebSphere Commerce.
 */

/* Import dojo classes */
dojo.require("wc.service.common");

/**
 * @class This class stores common parameters needed to make the service call.
 */
MyAccountServicesDeclarationJS = {
	/* The common parameters used in service calls */
	langId: "-1",
	storeId: "",
	catalogId: "",
	/* flag set on successful profile update which is used to display the success message. */ 
	profileUpdated: "false",
	/**
	 * This function initializes common parameters used in all service calls.
	 * @param {int} langId The language id to use.
	 * @param {int} storeId The store id to use.
	 * @param {int} catalogId The catalog id to use.
	 */

	setCommonParameters:function(langId,storeId,catalogId){
			this.langId = langId;
			this.storeId = storeId;
			this.catalogId = catalogId;
	}
}

    /**
	 *  Updates the current Personal Information of the customer.
	 *  @constructor
	 */
	wc.service.declare({
		id: "UserRegistrationUpdate",
		actionId: "UserRegistrationUpdate",
		url: "AjaxPersonChangeServicePersonUpdate",
		formId: "address_Form"
	
	/**
     * @param (object) serviceResponse The service response object, which is the
     * JSON object returned by the service invocation.
     */
	 
		,successHandler: function(serviceResponse) {
			MyAccountServicesDeclarationJS.profileUpdated='true';
			cursor_clear();
		}

	/**
     * display an error message.
     * @param (object) serviceResponse The service response object, which is the
     * JSON object returned by the service invocation.
     */
		,failureHandler: function(serviceResponse) {
			var form = document.forms["Register"];
			form.logonPassword_old.value = "";
			form.logonPasswordVerify_old.value = "";
			if(serviceResponse){
				Util.hideOverlay('addressWrapper'); 
				Util.hideOverlay('overlayBackground');
				 if (serviceResponse.errorMessage) {
				 	dojo.create("div", {"id": "errors"}, "contentHeader", "last");
					var innerDiv = dojo.create("div",{innerHTML:"<p>The following requires your attention before proceeding:</p>"}, "errors");
						dojo.attr(innerDiv, {"id": "errorsInner",
																 "tabindex": "1"});
				
					var ul = dojo.create("ul", null, "errorsInner");
				
					dojo.create("li", { innerHTML: serviceResponse.errorMessage }, ul);
					dojo.byId("errorsInner").focus();
					
				 
					//MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				} else {
					if (serviceResponse.errorMessageKey) {
					 	dojo.create("div", {"id": "errors"}, "contentHeader", "last");
						var innerDiv = dojo.create("div",{innerHTML:"<p>The following requires your attention before proceeding:</p>"}, "errors");
						dojo.attr(innerDiv, {"id": "errorsInner",
																 "tabindex": "1"});
				
						var ul = dojo.create("ul", null, "errorsInner");
						
						dojo.create("li", { innerHTML: serviceResponse.errorMessageKey }, ul);
						dojo.byId("errorsInner").focus();
						//MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
					}
				}
			}
			cursor_clear();
		}

	}),


	/**
	 *  Removes an item from the customer wishlist in Ajax mode.
	 *  @constructor
	 */
	wc.service.declare({
		id: "InterestItemDelete",
		actionId: "InterestItemDelete",
		url: "AjaxInterestItemDelete",
		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.displayStatusMessage(MessageHelper.messages["WISHLIST_REMOVEITEM"]);
			cursor_clear();
			Util.hideOverlay('addressWrapper'); 
			Util.hideOverlay('overlayBackground');
			dojo.create("div", {"id": "confirmation"}, "contentHeader" , "last");
			var wishListSuccessVar = MessageHelper.messages["WISHLIST_REMOVEITEM"];
			var innerDiv = dojo.create("div", {innerHTML:"<p>"+wishListSuccessVar+"</p>"}, "confirmation");
			dojo.attr(innerDiv, {"id": "confirmationInner","tabindex": "1"});
			dojo.byId("confirmationInner").focus();
			for (var prop in serviceResponse) {
				console.debug(prop + "=" + serviceResponse[prop]);
			}
			cursor_clear();
		}
	/**
     * 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) {
				MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
			} 
			else {
				 if (serviceResponse.errorMessageKey) {
					MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
				 }
			}
			cursor_clear();
		}

	}),
	
	/**
	 *  Adds an item to the customer wishlist in Ajax mode.
	 *  @constructor
	 */
	wc.service.declare({
		id: "AjaxInterestItemAdd",
		actionId: "AjaxInterestItemAdd",
		url: "AjaxInterestItemAdd",
		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) {
			cursor_clear();
			Util.hideOverlay('addressWrapper'); 
			Util.hideOverlay('overlayBackground');
			Util.hideOverlay('productQuickviewWrapper');
			Util.hidePageSuccessMsgForWishlist();
			dojo.create("div", {"id": "confirmation"}, "contentHeader" , "last");
			var wishListSuccessVar = MessageHelper.messages["WISHLIST_ADDED"];
			var innerDiv = dojo.create("div", {innerHTML:"<p>"+wishListSuccessVar+"</p>"}, "confirmation");
			dojo.attr(innerDiv, {"id": "confirmationInner","tabindex": "1"});
			dojo.byId("confirmationInner").focus();
			//MessageHelper.displayStatusMessage(MessageHelper.messages["WISHLIST_ADDED"]);
		}
	/**
     * 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) {
				MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
			} 
			else {
				 if (serviceResponse.errorMessageKey) {
					MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
				 }
			}
			cursor_clear();
		}

	}),	

	/**
	 *  This service enables the customer to email his/her wishlist. 
	 *  @constructor
	 */
	wc.service.declare({
		id: "InterestItemListMessage",
		actionId: "InterestItemListMessage",
		url: "AjaxInterestItemListMessage",
		formId: ""

	/**
     * hdes the progress bar and displays a success message.
     * @param (object) serviceResponse The service response object, which is the
     * JSON object returned by the service invocation.
     */
		,successHandler: function(serviceResponse) {
			for (var prop in serviceResponse) {
				console.debug(prop + "=" + serviceResponse[prop]);			
			}
			cursor_clear();
		}
	/**
     * 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) {
				MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
			} 
			else {
				 if (serviceResponse.errorMessageKey) {
					MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
				 }
			}
			cursor_clear();
		}

	}),
	
	/**
	 * This service adds a billing address to the order(s).
	 * @constructor
	 */
	wc.service.declare({
		id: "AddBillingAddress",
		actionId: "AddBillingAddress",
		url: "AjaxPersonChangeServiceAddressAdd",
		formId: ""

	 /**
	  *	 calls the saveAddress function defined in the AddressHelper class.
	  *  @param (object) serviceResponse The service response object, which is the
	  *  JSON object returned by the service invocation. 
	  */
		,successHandler: function(serviceResponse) {
			requestSubmitted = false;
			javascript:AddressHelper.saveAddress('AddShippingAddress','shippingAddressCreateEditFormDiv_1');
		}
		
	/**
     * 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) {
						 MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				  } else {
						 if (serviceResponse.errorMessageKey) {
								MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
						 }
				  }
		}

	}),
	
	/**
	 *  This service adds a shipping address to the order(s).
	 *  @constructor
	 */
	wc.service.declare({
		id: "AddShippingAddress",
		actionId: "AddShippingAddress",
		url: "AjaxPersonChangeServiceAddressAdd",
		formId: ""
	
	/**
	 *  redirects to the Shipping and Billing Method page.
	 * @param (object) serviceResponse The service response object, which is the
     * JSON object returned by the service invocation.
	 */
		,successHandler: function(serviceResponse) {
			document.location.href="OrderShippingBillingView?langId="+MyAccountServicesDeclarationJS.langId+"&storeId="+MyAccountServicesDeclarationJS.storeId+"&catalogId="+MyAccountServicesDeclarationJS.catalogId+"&shipmentType=single&orderPrepare=true";
		}

	/**
     * 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) {
						 MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				  } else {
						 if (serviceResponse.errorMessageKey) {
								MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
						 }
				  }
		}

	}),
	
  /**
   * This services adds or removes a coupon from the order(s).
   * @constructor
   */
	wc.service.declare({
		id: "AjaxCouponsAddRemove",
		actionId: "AjaxCouponsAddRemove",
		url: "AjaxCouponsAddRemove",
		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();
		}
		
	/**
     * 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) {
				MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
			} 
			else {
				 if (serviceResponse.errorMessageKey) {
					MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
				 }
			}
			cursor_clear();
		}

	}),
	
	/**
	 *  calls the QASPostalAddressValidateCmd to validate the postal address against QAS server
	 *  @constructor
	 */
	wc.service.declare({
		id: "QASAddressValidate",
		actionId: "QASAddressValidate",
		url: "AjaxQASAddressValidate",
		formId: "",
		page: "",
		jsSvcNameForAddrBook: ""

	/**
     * display a success message.
     * @param (object) serviceResponse The service response object, which is the
     * JSON object returned by the service invocation.
     */
		,successHandler: function(serviceResponse) {
			for (var prop in serviceResponse) {
				if(prop == 'result') {
					cursor_clear();
					var addrVal = serviceResponse[prop];
					var formIdfr = wc.service.getServiceById("QASAddressValidate").formId;
					var pageNam = wc.service.getServiceById("QASAddressValidate").page;
					var jsSvcName = wc.service.getServiceById("QASAddressValidate").jsSvcNameForAddrBook;
					var addrArr = new Array();
					
					for(var entry in addrVal) {
						addrArr.push(entry);
					}
					
					if(addrArr.length == 0) {
						var address = dojo.byId(formIdfr).address1.value;
						if(address!=""){
							dojo.query(".select_warranty_details").orphan();
							Util.showOverlay('addressWrapper');
							Util.showOverlay('overlayBackground');
							if(dojo.trim(dojo.byId(formIdfr).address2.value)!=""){
								address = address+","+dojo.byId(formIdfr).address2.value;
							}
							dojo.byId("addressSelectQAS").innerHTML = "<input id=\"noneaddress\" type=\"radio\" name=\"first_address\" value=\"none\">"+address+", "+dojo.byId(formIdfr).city.value+" "+dojo.byId(formIdfr).zipCode.value+"</input>&nbsp;-- entered address<hr style=\"color:white;background-color:white\"/>";
							
							//coremetrics tag
							cmCreatePageviewTag("Address Check", null, null, null, storeId);
							return;
						}else{
							if(pageNam == 'Register' || pageNam == 'billing') {
								dojo.byId(formIdfr).submit();
							}
							else if(pageNam == 'ProfileUpdate') {
								wc.service.invoke("UserRegistrationUpdate");
							}
							else if(pageNam == 'AddressBook') {
								wc.service.invoke(jsSvcName);
							}
						}						
					}
					else if(addrArr.length == 1) {
						for(var entry in addrVal) {
							var usedAddr = addrVal[entry];
							var addr_array = usedAddr.split("|||");
							console.debug(addr_array[0]+" "+addr_array[1]+" "+addr_array[2]+" "+addr_array[3]+" "+addr_array[4]+" "+addr_array[5]);
							dojo.byId(formIdfr).address1.value = addr_array[0];
							dojo.byId(formIdfr).address2.value = addr_array[1];
							dojo.byId(formIdfr).city.value = addr_array[2];
							dojo.byId(formIdfr).zipCode.value = addr_array[4];
							dojo.byId(formIdfr).addressField2.value = addr_array[6];
							
							if(pageNam == 'Register' || pageNam == 'billing') {
								dojo.byId(formIdfr).submit();
							}
							else if(pageNam == 'ProfileUpdate') {
								wc.service.invoke("UserRegistrationUpdate");
							}
							else if(pageNam == 'AddressBook') {
								wc.service.invoke(jsSvcName);
							}
						}
					}
					
					else if(addrArr.length>1){	
						dojo.query(".select_warranty_details").orphan();
						Util.showOverlay('addressWrapper');
						Util.showOverlay('overlayBackground');
						var address = dojo.byId(formIdfr).address1.value;
						if(dojo.trim(dojo.byId(formIdfr).address2.value)!=""){
							address = address+","+dojo.byId(formIdfr).address2.value;
						}
						dojo.byId("addressSelectQAS").innerHTML = "<input id=\"noneaddress\" type=\"radio\" name=\"first_address\" value=\"none\">"+address+", "+dojo.byId(formIdfr).city.value+" "+dojo.byId(formIdfr).zipCode.value+"</input>&nbsp;-- entered address<hr style=\"color:white;background-color:white\"/>";
						var ul = dojo.create("ul", {"class": "select_warranty_details"}, dojo.byId("addressSelectQAS"), "last");
						var count = 1;
						for(var entry in addrVal){
							if(count<=6){
								dojo.create("li", { innerHTML: '<input id="'+count+'address" type="radio" name="first_address" value="'+addrVal[entry]+'">'+entry+'</input>'}, ul);
							}
							count++;
						}
						//dojo.create("li", { innerHTML: '<input id="noneaddress" type="radio" name="first_address" value="none">None of the above, use address as entered.</input>'}, ul);
						
						//coremetrics tag
						cmCreatePageviewTag("Address Check", null, null, null, storeId);
						return;
					}
				}
				console.debug(prop + "=" + serviceResponse[prop]);
			}
			cursor_clear();
		}
	/**
     * display an error message.
     * @param (object) serviceResponse The service response object, which is the
     * JSON object returned by the service invocation.
     */
		,failureHandler: function(serviceResponse) {
			
			var formIdfr = wc.service.getServiceById("QASAddressValidate").formId;
			var pageNam = wc.service.getServiceById("QASAddressValidate").page;
			var jsSvcName = wc.service.getServiceById("QASAddressValidate").jsSvcNameForAddrBook;
			cursor_clear();
			if(pageNam == 'Register' || pageNam == 'billing') {
				dojo.byId(formIdfr).submit();
			}
			else if(pageNam == 'ProfileUpdate') {
				wc.service.invoke("UserRegistrationUpdate");
			}
			else if(pageNam == 'AddressBook') {
				wc.service.invoke(jsSvcName);
			}
		}

	}),
	
	/**
	 *  This service enables customer to Reorder an already existing order.
	 *  @constructor
	 */
	wc.service.declare({
		id: "OrderCopy",
		actionId: "OrderCopy",
		url: "AjaxOrderCopy",
		formId: ""

	 /**
	  *  Copies all the items from the existing order to the shopping cart and redirects to the shopping cart page.
	  *  @param (object) serviceResponse The service response object, which is the
	  *  JSON object returned by the service invocation.
	  */
		,successHandler: function(serviceResponse) {
			for (var prop in serviceResponse) {
				console.debug(prop + "=" + serviceResponse[prop]);			
			}	
			document.location.href="OrderProcessServiceOrderPrepare?langId="+MyAccountServicesDeclarationJS.langId+"&storeId="+MyAccountServicesDeclarationJS.storeId+"&catalogId="+MyAccountServicesDeclarationJS.catalogId+"&orderId="+serviceResponse.orderId+"&URL=OrderItemDisplay?langId="+MyAccountServicesDeclarationJS.langId+"&storeId="+MyAccountServicesDeclarationJS.storeId+"&catalogId="+MyAccountServicesDeclarationJS.catalogId;
		}
		
	/**
     * 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.errorMessageKey == "_ERR_PROD_NOT_ORDERABLE") {
				MessageHelper.displayErrorMessage(MessageHelper.messages["PRODUCT_NOT_BUYABLE"]);
			} else {
				if (serviceResponse.errorMessage) {
					MessageHelper.displayErrorMessage(serviceResponse.errorMessage);
				} 
				else {
					 if (serviceResponse.errorMessageKey) {
						MessageHelper.displayErrorMessage(serviceResponse.errorMessageKey);
					 }
				}
			}
			cursor_clear();
		}

	});

