//
//-------------------------------------------------------------------
// Licensed Materials - Property of IBM
//
// WebSphere Commerce
//
// (c) Copyright IBM Corp. 2006
//
// US Government Users Restricted Rights - Use, duplication or
// disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
//-------------------------------------------------------------------
//

dojo.require("dojo.io.*");
dojo.require("wc.render.*");

dojo.addOnLoad(function(){
	// Make sure there is always a render context
	if(!wc.render.getContextById("default")){
		wc.render.declareContext("default", {}, "");
	}
	
	if(!wc.render.getContextById("MyAccountCenterLinkDisplay_Context")){
		wc.render.declareContext("MyAccountCenterLinkDisplay_Context", {workAreaMode: "myAccountMain"}, "");
	}
	
//	AddressBookFormJS.declareRefreshController("addressDisplayAreaController",  "addressDisplayAreaAction", "AjaxAddressBookForm");
//	AddressBookFormJS.declareRefreshController("addressFormAreaController", "addressFormAreaAction", "AjaxAccountAddressForm");
//	AddressBookFormJS.declareRefreshController("billing_statesDisplayAreaController", "statesDisplayAreaAction", "AjaxAddressStatesDisplay");
//	AddressBookFormJS.declareRefreshController("shipping_statesDisplayAreaController", "statesDisplayAreaAction", "AjaxAddressStatesDisplay");
});


AddressBookFormJS = {
	//Global parameters for the AddressBookFormJS
		cityInputTextBoxValue: "", 
		validateLoadFields: "",
		langId: "-1",
		storeId: "",
		catalogId: "",
		stateDivName : "stateDiv",
		
		setStateDivName:function(stateDivName){
	///////////////////////////////////////////////////////////////////
	// summary: This function is used to initialize the name of the div which holds the state/province 
	// text box or select box.
	// If for a selected country, the list of states exists, then this div contains a select box.
	// Otherwise, this div contains a text box.
	// Description: Setup the div name that holds the state/province field.
	// stateDivName: The name of the div element.
	//////////////////////////////////////////////////////////////////
		this.stateDivName = stateDivName;
	},
	
	//summary: All the functions needed to manipulate address book form. 
	//description: This object contains all the functions that creating, 
	//	updating, displaying, and deleting addresses in a user account.
	
	//Padmanabhan This is the setter method for cityInputTextBoxValue variable
	//This will be called when the user selects the APO/FPO so that we can 
	//save the city value in this variable. and uses this value when he selects some 
	//other option other than APO/FPO
	 setCityInputTextBoxValue:function(cityInputTextBoxValue){
		this.cityInputTextBoxValue = cityInputTextBoxValue;
	 },	
	 
	 setValidateLoadFields:function(){
	 this.validateLoadFields = 'true';
	 },
		setCommonParameters:function(langId,storeId,catalogId){
			// summary		: This function initializes common parameters used in all service calls
			// description	: This function initializes storeId, catalogId, and langId.
			// langId	: The language id to use.
			// storeId : The store id to use.
			// catalog : The catalog id to use.
			this.langId = langId;
			this.storeId = storeId;
			this.catalogId = catalogId;
			
		},

	getControllerActionHandler: function(handlerKey, actionName){
		dojo.debug("entering getControllerActionHandler(controller, handlerKey, actionName): "+actionName);
		var handler = AddressBookFormJS[actionName+'s'][handlerKey];
		if(handler){
			return function(message, widget, controller){
				handler(message, widget, controller);	
				
			}
		}else{
			return function(message, widget, controller){
				dojo.debug("empty handler. This is a no-op");	
			}	
		}	
	}, 
	
	declareRefreshController: function(/* String */controllerId, /*String*/actionName, /*String?*/defaultURL){
		//summary: declares a refresh area controller that has the given 
		//	controller ID, and optionally a url. 
		//description: This function will declare a refreshArea controller if
		//	and only no controller with the same controller ID exits yet. The
		//	declared controller is designed to handle address specific tasks. 
		//	If user passes a "url" parameter when updating context, it will 
		//	replace the value of its own "url" parameter to the one given by 
		//	the user. It also calls functions based on the value of the given
		//	property actionName. For example, if the given actionName is "action", 
		//  It will look up a function registered in AddressBookFormJS.actions using
		//  the value of the property "action" in render context as the key. 
		//controllerId: The ID of the controller that is going to be declared.
		//actionName: The name that identifies this controller's behaviors. It is 
		//	best described by an example. Say, we declare a controller whose actionName
		//	is AddressFormAreaAction. Then, the handler of renderContextChanged event
		//	of this declared controller will look up the value that is corresponding
		//	to AddressFormAreaAction in the render context. Once the value is found, 
		//	the controller will use the value to look up the registered function in 
		//	the associative array AddressBookFormJS.AddressFormAreaActions (note 
		//	plural is used for the associative array). If a function is found, 
		//	the found function will be called. The signature of found function should be
		//	function(message, widget, controller), where message and widget is as defined
		// 	for the controller's rendercontextChangedHandler, and controller is 
		//	the declared context. We normally implement the logic of updating 
		//	refreshed area in the found functions. See AddressBookFormJS.AddressDisplayAreaActions
		//	for example. 
		//defaultURL: The url this controller used for getting data from server. It will
		//	be set to controller.url. 
		dojo.debug("entering AddressBookFormJS.declareRefreshController with action name = "+actionName+" and controller id = "+controllerId);
		if(wc.render.getRefreshControllerById(controllerId)){
			dojo.debug("controller with id = "+controllerId+" already exists. No declaration will be done");
			return;
		}
		wc.render.declareRefreshController({
			id: controllerId, 
			renderContext: wc.render.getContextById("default"),
			url: defaultURL,
			renderContextChangedHandler: function(message, widget) {
				dojo.debug("entering renderContextChangedHandler for "+controllerId);
			
				var controller = this;
				var renderContext = this.renderContext;
				
				if(!Common.getRenderContextProperty(renderContext, actionName)){
					dojo.debug("no "+actionName+" is specified. This handler will not be called. Exiting...");
					return;	
				}
				
				if(Common.getRenderContextProperty(renderContext, "url")){
					controller.url = Common.getRenderContextProperty(renderContext, "url");
				}
				
				AddressBookFormJS.getControllerActionHandler(Common.getRenderContextProperty(renderContext, actionName), actionName)(message, widget, controller);
				
				// Make sure this handler will always know whether a user gives an addressDisplayAreaAction in the future. 
				delete renderContext.properties[actionName];
				// TODO: will there be a race condition here? It's possible that more
				// than one controllers will use their own "url" interleavingly.  
				delete renderContext.properties["url"];
			}, 
			
			modelChangedHandler: function(message, widget){
				
				AddressBookFormJS.getControllerActionHandler("handleModelChange", actionName)(message, widget, this);
				
				cursor_clear();
			}
		});
	}, 
	
	addressFormAreaActions: {
		//summary: function registries for handling address forms. 
		//description: We register functions that handle different operations
		//	on address forms. The key of each function will be the value
		//	of the property "addressFormAreaAction" in render context. Each
		//	function takes three parameters: message, widget, and controller. 
		//	The parameters message and widget are the same as those for
		//	a controller's renderContextChangedHandler(). The parameter 
		//	controller is the controller that will call this function. 
		//create: The function that loads an empty address for for creating new
		//	address. 
		//edit: The function that loads an address form that contains the
		//	information of currently displayed address, so that the
		//	address can be editted. 
		//clean: Destroy the address froms that are handled by this controller. 
		create: function(message, widget, controller){
			widget.refresh(controller.renderContext.properties);
			controller.renderContext.properties['addressFormAreaState'] = 'create';
		}, 	
		
		edit: function(message, widget, controller){
			dojo.debug("starting to getting editing area");
			widget.refresh(controller.renderContext.properties);
			controller.renderContext.properties['addressFormAreaState'] = 'edit';
		}, 
		
		clean: function(message, widget, controller){
			widget.setInnerHTML("");	
			controller.renderContext.properties['addressFormAreaState'] = 'clean';
		},
		
		handleModelChange: function(message, widget, controller){
			widget.setInnerHTML("");
			controller.renderContext.properties['addressFormAreaState'] = 'clean';
		}
			
	}, 
	
	addressDisplayAreaActions: {
		//summary: function registries for handling address display
		//description: The registered functions handle operations on 
		//	the refresh area that displays user addresses. Also see
		//	AddressBookFormJS.addressFormAreaActions
		//reload: reload the refresh areas that display user addresses. 
		reload: function(message, widget, controller){
			dojo.debug("reloading "+widget);
			widget.refresh(controller.renderContext.properties);
		},
		
		handleModelChange: function(message, widget, controller){
			dojo.debug("reloading "+widget);
			widget.refresh(controller.renderContext.properties);
		}
	}, 
	
	statesDisplayAreaActions: {
		//summary: function registries for handling the display of states/provinces
		//description: The registered functions displays states upon changes made 
		//in address coutry. 
		//countryUpdated: refreshes the area that displays states/provinces corresponding to the updated country
		
		
		countryUpdated: function(message, widget, controller){
			dojo.debug("IN countryUpdated handler: message = "+message);
			
			var paramPrefix = controller.renderContext.properties['paramPrefix'];
			if(widget.widgetId.match(paramPrefix)){
				dojo.debug("matchin paramPrefix: "+paramPrefix+" refreshing "+widget.widgetId);
				
				widget.refresh(controller.renderContext.properties);	
			}else{
				dojo.debug("no maching paramPrefix "+paramPrefix);
			}
			
		}
		
		
		
	}, 
	toggleAddressDisplay: function(selection /* DOMNode*/, tableClass /*String*/, tableIdPrefix /* String */){
		//summary: This function displays the address that has the selected address
		//	ID, and hides all the other addresses. 
		//description: This function is supposed to be called when an addressId
		//	is selected from an HTML form selection control. This functions 
		//	makes a few assumptions. It assumes each ddress is displayed in 
		//	the same way. Each chunk of address information
		//	has the same class, tableClass. It also assumes the area that displays
		//	an address has an ID in the form of <tableIdPrefix><addressId>. 
		//selection: the DOM node of a form selection. This node contains selected
		//	addressId. 
		//tableClass: the class of the table that contains an address. 
		//tableIdPrefix: the prefix of the ID of each address table. 
		dojo.debug('toggle address display');
		var selectedAddressId = selection.options[selection.selectedIndex].value;
		dojo.lang.forEach(dojo.html.getElementsByClass(tableClass), function(table){
			
			var tableId = tableIdPrefix+selectedAddressId;
			if(table.id == tableId){
				table.style.display="";	
			}else{
				table.style.display="none";
			}
		});
	}, 
	
	updateAddressArea: function(/*Object*/params){
		//summary: a wrapper that updates the default render context with the given
		//	parameters. 
		dojo.debug("to update with params: "+params);
		wc.render.updateContext("default", params);
		dojo.debug("updateArea done");	
	}, 

	validateAddressForm:function(formName, divElementId) {
		var failed = false;
		reWhiteSpace = new RegExp(/^\s+$/);
		var form = document.forms[formName];
		var addressTypeSelection = form.addressField2;
		var addressType = addressTypeSelection.options[addressTypeSelection.selectedIndex].value;
		
		Common.hideErrorNodes();
		
		//Trimming the nickname value as a fix for defect 1630.
		String.prototype.trim = function () {
    		return this.replace(/^\s*/, "").replace(/\s*$/, "");
		}
		if(form.nickName.value!=null){
			form.nickName.value=form.nickName.value.trim();
		}
		
		if(form.nickName.value=="" || reWhiteSpace.test(form.nickName.value)) { 
			Common.formErrorHandleClient("nickName", Common.errorMessages["ERROR_NicknameEmpty"], formName, divElementId);
			failed = true;
		} else if(!Common.isValidUTF8length(form.nickName.value, 254 )) {
			Common.formErrorHandleClient("nickName", Common.errorMessages["ERROR_NicknameTooLong"], formName, divElementId);
			failed = true;
		}
		
		if(form.firstName.value=="" || reWhiteSpace.test(form.firstName.value)) { 
			Common.formErrorHandleClient("firstName", Common.errorMessages["ERROR_FirstNameEmpty"], formName, divElementId);
			failed = true;
		}		
		else if(!Common.isValidUTF8length(form.firstName.value, 128 )) {
			Common.formErrorHandleClient("firstName", Common.errorMessages["ERROR_FirstNameTooLong"], formName, divElementId);
			failed = true;
		}
		if(form.lastName.value=="" || reWhiteSpace.test(form.lastName.value)) { 
			Common.formErrorHandleClient("lastName", Common.errorMessages["ERROR_LastNameEmpty"], formName, divElementId);
			failed = true;
		} else if(!Common.isValidUTF8length(form.lastName.value, 128 )) {
			Common.formErrorHandleClient("lastName", Common.errorMessages["ERROR_LastNameTooLong"], formName, divElementId);
			failed = true;
		}
		
		if(addressType=="" || reWhiteSpace.test(addressType)) {
			Common.formErrorHandleClient("businessTitle", Common.errorMessages["ERROR_AddressTypeEmpty"], formName, divElementId);
			failed = true;
		}
		else if (addressType == "Business") {
			if(form.officeAddress.value=="" || reWhiteSpace.test(form.officeAddress.value)) {
				Common.formErrorHandleClient("officeAddress", Common.errorMessages["ERROR_BusinessEmpty"], formName, divElementId);
				failed = true;
			}
			if(!Common.isValidUTF8length(form.officeAddress.value, 128 )) {
				Common.formErrorHandleClient("officeAddress", Common.errorMessages["ERROR_BusinessTooLong"], formName, divElementId);
				failed = true;
			}
		}
		if (addressType == "APO/FPO") {
			if(form.address1.value=="" || reWhiteSpace.test(form.address1.value)) {
				Common.formErrorHandleClient("address1", Common.errorMessages["ERROR_UnitNumberEmpty"], formName, divElementId);
				failed = true;
			}
			if(!Common.isValidUTF8length(form.address1.value, 50 )) {
				Common.formErrorHandleClient("address1", Common.errorMessages["ERROR_AddressTooLong"], formName, divElementId);
				failed = true;
			}
			if(form.address2.value=="" || reWhiteSpace.test(form.address2.value)) {
				Common.formErrorHandleClient("address2", Common.errorMessages["ERROR_BoxNumberEmpty"], formName, divElementId);
				failed = true;
			}
			if(!Common.isValidUTF8length(form.address2.value, 50 )) {
				Common.formErrorHandleClient("address2", Common.errorMessages["ERROR_AddressTooLong"], formName, divElementId);
				failed = true;
			}
		}

		
		else {
		
			if (addressType == "P.O. Box") {
				if((form.address1.value=="" || reWhiteSpace.test(form.address1.value) )&& form.address2.value=="") {
					Common.formErrorHandleClient("address1", Common.errorMessages["ERROR_POBOXAddressEmpty"], formName, divElementId);
					failed = true;
				}
				if(!Common.isValidUTF8length(form.address1.value, 50 )) {
					Common.formErrorHandleClient("address1", Common.errorMessages["ERROR_POBOXAddressTooLong"], formName, divElementId);
					failed = true;
				}
			}
			else{
					if((form.address1.value=="" || reWhiteSpace.test(form.address1.value) )&& form.address2.value=="") {
						Common.formErrorHandleClient("address1", Common.errorMessages["ERROR_AddressEmpty"], formName, divElementId);
						failed = true;
					}
					if(!Common.isValidUTF8length(form.address1.value, 50 )) {
						Common.formErrorHandleClient("address1", Common.errorMessages["ERROR_AddressTooLong"], formName, divElementId);
						failed = true;
					}
			}
					

		}
		
		if(!Common.isValidUTF8length(form.address2.value, 50 )) {
			Common.formErrorHandleClient("address2", Common.errorMessages["ERROR_AddressTooLong"], formName, divElementId);
			failed = true;
		}
		if(form.city.value=="" || reWhiteSpace.test(form.city.value)) {
			Common.formErrorHandleClient("city", Common.errorMessages["ERROR_CityEmpty"], formName, divElementId);
			failed = true;
		} else if(!Common.isValidUTF8length(form.city.value, 128)) {
			Common.formErrorHandleClient("city", Common.errorMessages["ERROR_CityTooLong"], formName, divElementId);
			failed = true;
		}
		if(form.state.value=="" || reWhiteSpace.test(form.state.value)) {
			Common.formErrorHandleClient("state", Common.errorMessages["ERROR_StateEmpty"], formName, divElementId);
			failed = true;
		} else if(!Common.isValidUTF8length(form.state.value, 128)) {
			Common.formErrorHandleClient("state", Common.errorMessages["ERROR_StateTooLong"], formName, divElementId);
			failed = true;
		}
		if(form.country.value=="" || reWhiteSpace.test(form.country.value)) {
			Common.formErrorHandleClient("country", Common.errorMessages["ERROR_CountryEmpty"], formName, divElementId);
			failed = true;
		} else if(!Common.isValidUTF8length(form.country.value, 128)) {
			Common.formErrorHandleClient("country", Common.errorMessages["ERROR_CountryTooLong"], formName, divElementId);
			failed = true;
		}
		if(form.zipCode.value=="" || reWhiteSpace.test(form.zipCode.value)) {
			Common.formErrorHandleClient("zipCode", Common.errorMessages["ERROR_ZipCodeEmpty"], formName, divElementId);
			failed = true;
		} else if(!Common.isValidUTF8length(form.zipCode.value, 40 )) {
			Common.formErrorHandleClient("zipCode", Common.errorMessages["ERROR_ZipCodeTooLong"], formName, divElementId);
			failed = true;
		}
		if(form.phone1.value!="" && !reWhiteSpace.test(form.phone1.value) && !Common.isValidPhone(form.phone1.value)) {
			Common.formErrorHandleClient("phone1", Common.errorMessages["ERROR_PhoneInvalid"], formName, divElementId);
			failed = true;
		} else if(!Common.isValidUTF8length(form.phone1.value, 32 )) {
			Common.formErrorHandleClient("phone1", Common.errorMessages["ERROR_Phone1OnlyNum"], formName, divElementId);
			failed = true;
		}
		if(form.phone2.value!="" && !reWhiteSpace.test(form.phone2.value) && !Common.isValidPhone(form.phone2.value)) {
			Common.formErrorHandleClient("phone2", Common.errorMessages["ERROR_PhoneInvalid"], formName, divElementId);
			failed = true;
		} else if(!Common.isValidUTF8length(form.phone2.value, 32 )) {
			Common.formErrorHandleClient("phone2", Common.errorMessages["ERROR_Phone2OnlyNum"], formName, divElementId);
			failed = true;
		}
		
		if (!failed) {
			form.phone1.value = Common.cleanPhone(form.phone1.value);
			form.phone2.value = Common.cleanPhone(form.phone2.value);
			//verify address fields #1-#2, if #2 is filled and not #1 then move the data for the user
			if (form.address1.value == "") {
				if (form.address2.value != "") {
					form.address1.value = form.address2.value;
					form.address2.value = "";
				}
			}
	 	}
	 	return !failed;
	},

	loadFields: function(city) {
		var cityTextbox = "<input type=\"text\" name=\"city\" id=\"QAS_city\" size=\"20\" maxlength=\"40\" class=\"addressSelectSmall\"	value=\"";
		var cityTextbox = cityTextbox+city+"\" />";
		var cityTextbox     = document.getElementById('cityTextbox').value;
		if(document.getElementById('QAS_city')){
			if (document.getElementById('QAS_city').nodeName == 'INPUT') {
			var cityInputTextBoxValue     = document.getElementById('QAS_city').value;		
			}
		}

		var citySelect = "<select name=\"city\" id=\"QAS_city\" class=\"addressSelectSmall\" style=\"width:auto\" /><option value=\"APO\">APO</option><option value=\"FPO\">FPO</option></select>";
		var dropdown        = document.getElementById('addressField2');
		var companyLabel    = document.getElementById('company_label');
		var address1Label   = document.getElementById('address1_label');
		var address2Label   = document.getElementById('address2_label');
		var address3Label   = document.getElementById('address3_label');
		var cityLabel       = document.getElementById('city_label');
		var militaryHelpRow = document.getElementById('militaryHelpRow');
		var cityInput       = document.getElementById('cityInput');
		//var companyStar     = document.getElementById('company_star');
		var address2Star    = document.getElementById('address2_star');
		var companyRow		= document.getElementById('organizationNameRow');
		var companyField 	= document.getElementById('WC_ShoppingCartAddressEntryForm_FormInput_company_1');		
		
		var type = dropdown.options[dropdown.selectedIndex].value;
		
		if (type == 'Residential') {
			// Residential
			companyLabel.innerHTML = 'Company:';
			address1Label.innerHTML = 'Address Line 1:';
			address2Label.innerHTML = 'Address Line 2:';
			address3Label.innerHTML = 'Address Line 3:';
			cityLabel.innerHTML = 'City:';
			militaryHelpRow.style.display = 'none';
			if(document.getElementById('QAS_city')){
			if (document.getElementById('QAS_city').nodeName == 'SELECT') {
				cityInput.innerHTML = cityTextbox;
				document.getElementById('QAS_city').value= this.cityInputTextBoxValue;		
			}
			}
			//cityInput.innerHTML = cityTextbox;
			//companyStar.style.display = 'none';
			address2Star.style.display = 'none';
			companyRow.style.display = 'none';
			//companyField.value = '';
		}
		else if (type == 'Business') {
			// Business
			companyLabel.innerHTML = 'Company:';
			address1Label.innerHTML = 'Address Line 1:';
			address2Label.innerHTML = 'Address Line 2:';
			address3Label.innerHTML = 'Address Line 3:';
			cityLabel.innerHTML = 'City:';
			militaryHelpRow.style.display = 'none';
			if(document.getElementById('QAS_city')){
			if (document.getElementById('QAS_city').nodeName == 'SELECT') {
				cityInput.innerHTML = cityTextbox;
				document.getElementById('QAS_city').value= this.cityInputTextBoxValue;		
			}			
			}
			//cityInput.innerHTML = cityTextbox;
			//companyStar.style.display = '';
			address2Star.style.display = 'none';
			companyRow.style.display = '';
		}
		else if (type == 'APO/FPO') {
			// APO/FPO
			companyLabel.innerHTML = 'Organization:';
			address1Label.innerHTML = 'Unit/Ship/PSC Number:';
			address2Label.innerHTML = 'Box/Hull NUmber';
			address3Label.innerHTML = 'Address Line 3:';
			cityLabel.innerHTML = 'APO/FPO';
			militaryHelpRow.style.display = '';
			if(document.getElementById('QAS_city')){
			if (document.getElementById('QAS_city').nodeName == 'INPUT') {
				cityInputTextBoxValue     = document.getElementById('QAS_city').value;				
				AddressBookFormJS.setCityInputTextBoxValue(cityInputTextBoxValue)
				cityInput.innerHTML = citySelect;
			}			
			}
			//cityInput.innerHTML = citySelect;
			//companyStar.style.display = 'none';
			address2Star.style.display = '';
			companyRow.style.display = 'none';
		}
		else if (type == 'P.O. Box') {
			// PO Box
			companyLabel.innerHTML = 'Company:';
			address1Label.innerHTML = 'P.O. Box:';
			address2Label.innerHTML = 'Address Line 2:';
			address3Label.innerHTML = 'Address Line 3:';
			cityLabel.innerHTML = 'City:';
			militaryHelpRow.style.display = 'none';
			if(document.getElementById('QAS_city')){
			if (document.getElementById('QAS_city').nodeName == 'SELECT') {
				cityInput.innerHTML = cityTextbox;
				document.getElementById('QAS_city').value= this.cityInputTextBoxValue;		
			}			
			}
			//cityInput.innerHTML = cityTextbox;
			//companyStar.style.display = 'none';
			address2Star.style.display = 'none';
			companyRow.style.display = 'none';
		}
		else {
			// -- Select One --
			companyLabel.innerHTML = 'Company:';
			address1Label.innerHTML = 'Address Line 1:';
			address2Label.innerHTML = 'Address Line 2:';
			address3Label.innerHTML = 'Address Line 3:';
			cityLabel.innerHTML = 'City:';
			militaryHelpRow.style.display = 'none';
			if(document.getElementById('QAS_city')){
			if (document.getElementById('QAS_city').nodeName == 'SELECT') {
				cityInput.innerHTML = cityTextbox;
				document.getElementById('QAS_city').value= this.cityInputTextBoxValue;		
			}			
			}
			//cityInput.innerHTML = cityTextbox;
			//companyStar.style.display = 'none';
			address2Star.style.display = 'none';
			companyRow.style.display = 'none';
		}
		this.loadStatesUI('AddressForm','');
		if(this.validateLoadFields=='true'){
		dojo.lang.setTimeout(AddressBookFormJS,"validateAddressForm",100,'AddressForm','refreshArea');
		}

	},

	updateAddress: function(/*String*/formName, /*String*/addressDisplayURL){
		//summary: updates a user account address. 
		//description: This function submits the given form that
		//	contains address information. After the address is 
		//	updated, this function will refreshes the address
		//	display area using the givne URL. 
		//formName: the name of the address form
		//addressDisplayURL: the URL used to refresh address display
		if (this.validateAddressForm(formName, "refreshArea")) {
			dojo.debug("creating with form id = "+formName+" and  address display url is: "+addressDisplayURL);
			dojo.require("wc.service.*");
			wc.service.declare({
				id: "updateAddress",
				actionId: "updateAddress",
				url: "AjaxPersonChangeServiceAddressAdd",
				formId: formName,
				successHandler: function(serviceResponse) {
					wc.render.getRefreshControllerById("MyAccountCenterLinkDisplay_Controller").url = addressDisplayURL;
					wc.render.updateContext("MyAccountCenterLinkDisplay_Context", {workAreaMode:"addressBook"});
				},
				failureHandler: function(serviceResponse) {
					alertDialog(serviceResponse.errorMessageKey,AddressBookFormJS.storeId,AddressBookFormJS.catalogId,AddressBookFormJS.langId);
				}
	
			});
	        this.validateLoadFields = 'false';
	        //resetting the flag. This means we have the validation true and we are going to call the service. Hence reset the flag
	        //So that the next time immedietely when the user comes to the add address page,after saving the address, the flag wont be true
			wc.service.invoke("updateAddress");
		}
		else
		this.setValidateLoadFields();
// padman for setting flat. this flag is true once we click the save button. and after that when we change location type, validation will be performed each time. 
	}, 
	
	deleteAddress: function(/*String*/addressDeleteUrl, /*String*/addressDisplayUrl, addressId){
		dojo.require("wc.service.*");
		wc.service.declare({
			id: "AddressDelete",
			actionId: "AddressDelete",
			url: addressDeleteUrl,
			successHandler: function(serviceResponse) {
//				wc.render.getRefreshControllerById("addressDisplayAreaController").url = addressDisplayUrl;
				wc.render.getRefreshControllerById("MyAccountCenterLinkDisplay_Controller").url = addressDisplayUrl;
				wc.render.updateContext("MyAccountCenterLinkDisplay_Context", {workAreaMode:"addressBookDelete" + addressId});
			},
			failureHandler: function(serviceResponse) {
				dojo.debug("error: "+serviceResponse);
				alertDialog(serviceResponse.errorMessageKey,this.storeId,this.catalogId,this.langId);
			}

		});
		
		wc.service.invoke("AddressDelete");
	}, 

	
	//loadStatesUI: function(formName, paramPrefix){
		//alert("entered loadStatesUI");
		//alert("formName-->" +formName);	
		//alert("paramPrefix-->" +paramPrefix);
		
//		var form = document.forms[formName];
//		dojo.debug("loadStatesUI: form is: "+form.name+" and paramPrefix is: "+paramPrefix);
	//	var currentCountryCode = form[paramPrefix+"country"].value;
		//var currentStateCode = form[paramPrefix+"state"].value;
		

//		AddressBookFormJS.statesDisplayAreaActions[paramPrefix+"countryUpdated"] = function(message, widget, controller){
	//		alert("firt in loadStatesUI");
		//	dojo.debug("IN countryUpdated handler: message = "+message);
			
			//if(widget.widgetId.match(paramPrefix)){
				//dojo.debug("matchin paramPrefix: "+paramPrefix+" refreshing "+widget.widgetId);
				
//				widget.refresh(controller.renderContext.properties);	
	//		}else{
		//		dojo.debug("no maching paramPrefix "+paramPrefix);
			//}
			
	//	}
		
	//	dojo.debug("updating context...");
	//	wc.render.updateContext("default", {countryCode:currentCountryCode, stateCode: currentStateCode, paramPrefix:paramPrefix, statesDisplayAreaAction:paramPrefix+'countryUpdated'});
//	},
	
	loadStatesUI:function(formName,paramPrefix){
	///////////////////////////////////////////////////////////////////
	// summary: This function will create the state field for a country.
	// Description: Creates a state field depending on the country.
	// formName: The name of the address form.
	// paramPrefix: The prefix to be appended to the state filed.
	//////////////////////////////////////////////////////////////////
		var form = document.getElementById(formName);
		var currentCountryCode = form["country"].value;
		var currentState = form["state"].value;
		var stateDivObj = document.getElementById(paramPrefix+this.stateDivName);
		//var stateDivObj = document.getElementById(paramPrefix+'stateDiv');
		/*
		while(stateDivObj.hasChildNodes()) {
			stateDivObj.removeChild(stateDivObj.firstChild);
		}
		*/
		if (countries[currentCountryCode].states) {
			// switch to state list
			stateDivObj.innerHTML = this.createStateWithOptions(paramPrefix, currentCountryCode, currentState);
			//stateDivObj.appendChild(this.createStateWithOptions(paramPrefix, currentCountryCode, currentState));
		} else {
			// switch to state text input
			stateDivObj.innerHTML = this.createState(paramPrefix, currentState);
			//stateDivObj.appendChild(this.createState(paramPrefix, currentState));
		}
	},
	
	createStateWithOptions:function(paramPrefix, currentCountryCode, currentState)
	{
	///////////////////////////////////////////////////////////////////
	// summary: This function creates a state select field with drop down options.
	// Description: Creates an select field for the state containing all the options for the specified country.
	// paramPrefix: The prefix to be appended to the state filed.
	// currentCountryCode: The country code.
	// currentState: The default value of the state field (used in cases of displaying an existing address).
	//////////////////////////////////////////////////////////////////
		// clear old options
		var optionsString = "";
		
		var addressType = document.getElementById('addressField2');
		for (state_code in countries[currentCountryCode].states) {
			if (!addressType ||
			 (addressType.options[addressType.selectedIndex].value == 'APO/FPO' &&
			 countries[currentCountryCode].states[state_code].substring(0,5) == 'Armed') ||
			 (addressType.options[addressType.selectedIndex].value != 'APO/FPO' &&
			 countries[currentCountryCode].states[state_code].substring(0,5) != 'Armed')) {
				if (state_code == currentState || countries[currentCountryCode].states[state_code] == currentState) {
					optionsString = optionsString + "<option selected = 'true' value='"+state_code+"'>"+ countries[currentCountryCode].states[state_code]+"</option>";
				}
				else{
					optionsString = optionsString + "<option value='"+state_code+"'>"+ countries[currentCountryCode].states[state_code]+"</option>";
				}
			}
		}
		var temp = "<select class='addressSelectSmallDropdown' name='state' id='"+paramPrefix+"QAS_state'>";
		temp = temp + optionsString+ "</select>";
		return temp;
	},
	
	createState:function(paramPrefix, currentState){
	///////////////////////////////////////////////////////////////////
	// summary: This function creates a state text field.
	// Description: Creates an input text field for the state.
	// paramPrefix: The prefix to be appended to the state filed.
	// currentState: The default value of the state field (used in cases of displaying an existing address).
	//////////////////////////////////////////////////////////////////
		var stateInput = document.createElement("input");
		var temp = "<input class='addressSelectSmall' type='text' name='state' id='"+paramPrefix+"state' value='"+currentState+"'>";
//		stateInput.setAttribute("name", "state");
//		stateInput.setAttribute("id", paramPrefix + "state");
//		stateInput.setAttribute("value", currentState);
//		dojo.html.setClass(stateInput, "shopcartAddressInput");
//		return stateInput;
		return temp;
	},
	
	
	clearFields: function(formName) {
	var docformName = document.forms[formName];
		Common.hideErrorNodes();
		var inputsText=document.forms[formName].getElementsByTagName('input');
		for (var i_tem = 0; i_tem < inputsText.length; i_tem++)
			if ((inputsText[i_tem].type=='text'))
				inputsText[i_tem].value='';
		var inputsSelect=document.forms[formName].getElementsByTagName('select');
		for (var i_tem = 0; i_tem < inputsSelect.length; i_tem++)
			//inputsSelect[i_tem].value='';
			inputsSelect[i_tem].options[0].selected = "1";
		if(docformName.selectShippingAddressId){	
		docformName.selectShippingAddressId.options[0].selected = "1";
		}
		// this is done to make the "select one " option as the selected option when clear field in clicked
	}
};

