(function() { 

	var _u = m2.widget.user;
	var _rp; 

	/**
	 * @namespace
	 * Widget that handles the reset password rules
	 */
	_rp = m2.widget.user.ResetPassword = {
	
		/**
		 * Property tracks the initialization state of the registration dialog
		 * @type {boolean} 
		 */
		isResetPasswordInit : false,

		/**
		 * 
		 */		
		hasDialogCloseListener : false,
	
		/**
		 * Function will show the reset password dialog
		 * @scope httpParent
		 */
		showResetPasswordDialog : function() {
			this.isResetPasswordInit = false;
			var iframeConfig = {
				id    : "resetPasswordFrame",
				src   : m2.util.getSecureUrl() + "/signup" + "#" + m2.util.toJson(m2.util.getBaseUrlForHash()),
				// NOTE: Position absolute is required or the page will jump around as the frame gets added to the 
				// end of the document
				style : {height:"920px",width:"530px",opacity:0,position:"absolute",left:"-900px",top:"-900px"}
			};
	        
			// if the dialog exists fade out the login content and then create the reset password content
			if (m2.dialog.hasDialog("loginDialog")) {
				m2.dialog.loading("Loading Data ...");
				m2.util.setStyle("loginFrame","opacity",0);
				m2.util.Iframe.create(iframeConfig);
			// if the dialog doesn't exist, create it
			} else {
				this.dialog = m2.dialog.open({
					dialogName: "loginDialog",
					content: '<div style="text-align:center;font-weight:bold;">Loading ...</b></div>',
					modal: true,
					backgroundClass: "diagBackground",
					showCloseButton: true,
					size: {width: 535,height:44},
					position: {y: 100},
					allowOverflow: false
				});
				// create the iframe
				m2.util.Iframe.create(iframeConfig);
			}
			
			// add a listener for dialog close so that we can clean up session data on cancellation
			this.disconnectCloseListener();
			m2.util.Event.add(this.dialog,"close", function(){_rp.cancelResetPassword();});
			this.hasDialogCloseListener = true;
		},
	
		/**
		 * Function will initialize the reset password dialog
		 * @param {Object} data  The data object from the httpsChild.  Contains the dialog size.
		 * @scope httpParent
		 */
		initResetPasswordDialog : function(data) {
			// This check is necessary because the updateDialogContent method causes the iframe to reload, and 
			// thus this will be called mulitple times.
			if (this.isResetPasswordInit) {
				// The data always has the dimensions of the dialog so update the size.
				m2.dialog.update(data, "loginDialog");
				return;
			}
	
			// when the dialog is the correct size, move the iframe into the dialog and show the content
			data.onEnd = function() {
				var f = m2.$("resetPasswordFrame");
				f.style.position = "static";
				m2.widget.dialog.updateDialogContent("loginDialog",m2.$("resetPasswordFrame"));
				// update the loading message
				m2.widget.dialog.hideLoading();
				m2.util.setStyle("resetPasswordFrame","opacity",1);
			};
	
			// animate the dialog to the correct size based on the data
			m2.widget.dialog.updateDialogDimensions("loginDialog",data);
	
			// set init state
			this.isResetPasswordInit = true;
		},
		
		/**
		 * Function will call the service to set the contents of the captcha image.
		 * @param {String} type  Registration type.
		 * @scope httpsChild
		 */
		initResetPasswordContents : function() {
			m2.util.DWR.callService(RegistrationService.initResetPassword,_rp.handleInitResetPasswordContents);
		},
	
		/**
		 * Object handles the response from the server for populating the reset password dialog
		 * @scope httpsChild
		 */
		handleInitResetPasswordContents : {
	        /**
	         * Function will populate the dialogs security areas based on the response.
	         * @param {Object} r  the response
	         */
	        SUCCESS: function(r){
	            var form = m2.$("validateLoginIdForm");
	            // set initial captcha image
	            _u.getCaptchaImage();
	        }
	    },
	    
	    submitValidateLoginId : function(form) {
			m2.util.Iframe.sendMessage("loading", {message:"Processing..."});
			var self = this;
	        m2.util.DWR.callService(RegistrationService.validateLoginId,self.handleValidateLoginId,m2.util.FormUtil.getValuesForDWR(form));
	    },
	    
	    handleValidateLoginId : {
			// successful valdidation
			SUCCESS: function(r){
	            // carry over form data
				var vForm = m2.$("validateLoginIdForm");
				var rForm = m2.$("resetPasswordForm");
	            rForm.loginId.value = vForm.loginId.value;
	            rForm.captchaWord.value = vForm.captchaWord.value;
	
	            // update security question
	            var text = m2.$("asqText");
	            var question = r.data.questions[0];
	            rForm.asqId.value = question.id;
	            text.innerHTML = question.text;
	            
	            // clear any errors
	            var message = m2.$("")
	
	            // show reset password form
	            var vEl = m2.$("validateLoginId");
	            var rEl = m2.$("resetPassword");
	            vEl.style.display = "none";
	            rEl.style.display = "block";            
	
				// update the parent to the appropriate view
				m2.util.Iframe.sendMessage("hideLoading");
				m2.util.Iframe.sendDocumentDimensions();
			},
	
			// show the errors		
			VALIDATION_ERROR : function(r) {
				// mark errors
				m2.util.FormUtil.markErrors(r.errors, m2.$("validateLoginIdForm"), "vMessageArea", "error");
				// check if the captcha word was incorrect
				for (var i = 0;i < r.errors.length;i++) {
					if (r.errors[i].code == "captchaWordMismatch") {
						_u.getCaptchaImage();
						m2.$("captchaWord").value = "";
					}
				}
				// update the parent to the appropriate view
				m2.util.Iframe.sendMessage("hideLoading");
				m2.util.Iframe.sendDocumentDimensions();
			},
	
			// some sort of failure
			FAILURE : function(r) {
				// update the parent to the appropriate view
				m2.util.Iframe.sendMessage("hideLoading");
				m2.util.Iframe.sendDocumentDimensions();
				alert('Service Error...\n status code: ' + r.statusCode);
			}
	    },
	           
	    submitResetPassword : function(form) {
			m2.util.Iframe.sendMessage("loading", {message:"Processing..."});
			var self = this;
	        m2.util.DWR.callService(RegistrationService.submitResetPassword,self.handleSubmitResetPassword,m2.util.FormUtil.getValuesForDWR(form));
	    },
	    
	    handleSubmitResetPassword : {
			// successful reset password
			SUCCESS: function(r){
	            // complete process
	            m2.util.Iframe.sendMessage("resetPassword");
			},
	
			// show the errors		
			VALIDATION_ERROR : function(r) {
				// mark errors
				m2.util.FormUtil.markErrors(r.errors, m2.$("resetPasswordForm"), "rMessageArea", "error");
				// update the parent to the appropriate view
				m2.util.Iframe.sendMessage("hideLoading");
				m2.util.Iframe.sendDocumentDimensions();
			},
	
			// some sort of failure
			FAILURE : function(r) {
				// update the parent to the appropriate view
				m2.util.Iframe.sendMessage("hideLoading");
				m2.util.Iframe.sendDocumentDimensions();
				alert('Service Error...\n status code: ' + r.statusCode);
			}
	    },
	    
	 	/**
		 * Calls the cancel reset password service to clear out server session data for this user
		 * @scope httpParent
		 */
		cancelResetPassword : function(type) {
			// disconnect close listener
			_rp.disconnectCloseListener();
			m2.util.DWR.callService(RegistrationService.cancelResetPassword,_rp.handleCancelResetPassword);
		},
	
		/**
		 * Disconnects the listener
		 */
		disconnectCloseListener : function() {
			if (this.hasDialogCloseListener) {
				m2.util.Event.remove(this.dialog,"close", function(){_rp.cancelResetPassword();});
				this.hasDialogCloseListener = false;
			}
		},
	
		/**
		 * function handles the service callback for cancelling reset password.
		 * @scope httpParent
		 */
		handleCancelResetPassword: {
			SUCCESS: function(){
				// do nothin
			},
			FAILURE : function() {
				// do nothin
			}
		},
	
	   resetPassword : function(data) {
	        // display success message
			m2.dialog.close("loginDialog");
			m2.dialog.loading("Your password was successfully reset!");
			setTimeout(function() {m2.dialog.hideLoading();},1000);
	    } 
	};


})();
