/**
 * Account Management module for methods that interact with Registration SOAP 
 * services
 *
 * @class actions
 * @author jferrer
 */

window.AccountManagement.actions = (function(){
	/**
	 * Finds all form fields of a specified type and creates a JSON object representation of those fields
	 * @param	{type}	 Registration service type to parse [profile|email|password|address]
	 * @param	{formid} target container for jquery selector
	 * @param   {arrEmptyProps} array of property names to send as empty values to server
	 * @return	{object} 
	 */
	function _serializeRegistrationServicesData(type, formid, arrEmptyProps) {
		var n,
			v,
			re  = new RegExp("^"+type+"_(.*)$"),
			fields,
			obj = {};

		if (typeof(formid)!='undefined'&&formid!==null) {
			fields = $("#"+formid).find(":input[id^='"+type+"']");
		}
		else {
			fields = $(":input[id^='"+type+"']");
		}

		fields.each(function() {
			n = this.id.match(re)[1].split("_")[0];
			v = bam.string.escapeHTML(this.value)||'';
				if (obj[n] === undefined) {
					if(this.type !== 'radio' || (this.type==='radio' && !!this.checked)){
						obj[n] = v;
					}
				}
				else {
					if (this.type != 'radio') {
						if (typeof(obj[n]) == "string" ) {
							var tmp = obj[n];
							obj[n] = [];
							obj[n].push(tmp);
						}
						obj[n].push(v);
					}
				}
		});

		if (typeof(arrEmptyProps)!='undefined'){
			var lenArrEmptyProps = arrEmptyProps.length,
				i = 0;
			do {
				n = arrEmptyProps[i];
				if (typeof(obj[n])=='undefined') obj[n] = [''];
				i++;
			}
			while (i<lenArrEmptyProps);
		}

		return obj;
	}

	/** Returns privacy settings */
	function _serializePrivacySettings(){
		var re          = new RegExp("^community_(.*)$"),
			_arrPrivacy = [];

		$('select[id^="community_"]').each(
			function(){
				var n, v, el, 
					obj = {};
					
					el = $(this);
					n  = this.id.match(re)[1].split("_")[0];
					obj.name  = n;
					obj.level = el.val();
					_arrPrivacy.push(obj);
			}
		);

		return _arrPrivacy;
	}

	/** Returns service errors */
	function _parseServiceError(serviceOperation, status){
		var errors = {};
		//out = serviceOperation + ' ' + status.code + ' ' + status.message;

		if (status.detailList){
			for (var i = 0; i < status.detailList.length; i++){
				//out = "Status Detail (messageKey) = " + status.detailList[i].message; // status.detailList[i].messageKey; let's use messageKey for placing error message next to form field
				errors[status.detailList[i].messageKey] = status.detailList[i].message;
			}
		}
		return errors;
	}

	/**
	 * checks if doSubmit
	 * #TODO: are we still using this function?! if not, let's deprecate.
	 */
	function __isDoSubmit(doSubmit){
		if (!!StatusManager.isCriteriaChecked() && !!doSubmit)
				return doSubmit;
			else 
				__isDoSubmit(doSubmit);
	}
	

	var _module = {
		/**
		 * Saves personal information which includes Profile and Address information
		 */
		savePersonalInfo : function(doSubmit) {
			// serialize profile and address information into objects for service clients 
			var personalInfoProps = _serializeRegistrationServicesData('profile', 'profile_personalInformation'),
			    addressInfoProps  = _serializeRegistrationServicesData('address');

			// if account creation wizard flow, submit the form which loads the next step in workflow
			if (!!doSubmit){
				$(AccountManagement).one('onSavePersonalInfo', function(){
					var form = $('#form_personalInformation');
					form.unbind();
					form.submit();
					return true;
				});

			// stay on the page if user not in wizard flow
			} else {
				$(AccountManagement).one('onSavePersonalInfo', function(){
					AccountManagement.message.display('<p>Your Personal Information has been saved!</p>','#profile_personalInformation','success');
				});
			}

			// trigger onSavePersonalInfo event once all required save actions are successful
			StatusManager.onSuccess(
				function() {
					// event triggered; this should be the new way of doing things
					$(AccountManagement).trigger('onSavePersonalInfo', [{ personalInfo: personalInfoProps, addressInfo: addressInfoProps }]);
					return true;
				}
			);

			// funky address composite stuff
			if ((StatusManager.get('isAddressSubmission')===null)) {
				StatusManager.remove('isAddressSubmission');
			
				StatusManager.set('Address');
				
				// addressID is blank, which means we're creating a new address
				if (addressInfoProps.id === '') {
					AddressService.add(addressInfoProps,
						function(addressId) {
							AddressService.setShipping(addressId, 
								function(){
									StatusManager.update("Address","success");
								}, 
								function(serviceOperation, status){
									var errors = _parseServiceError(serviceOperation, status);
									StatusManager.update("Address",errors);
								}
							);
						},
						function(serviceOperation, status){
							var errors = _parseServiceError(serviceOperation, status);
							StatusManager.update("Address",errors);
						}
					);
				// edit existing address
				} else {
					AddressService.update(addressInfoProps, true,
						function(){
							StatusManager.update("Address","success");
						},
						function(serviceOperation, status){
							var errors = _parseServiceError(serviceOperation, status);
							StatusManager.update("Address",errors);
						}
					);
				}
			} 


			StatusManager.set('Profile');
			ProfileService.save(personalInfoProps,
				function() {
					StatusManager.update("Profile","success");
				},
				function(source,msg){
					AccountManagement.validation.handleServerErrors({source:source,msg:msg,formContainer:'#profile_personalInformation'});
				}
			);

			return false;
		},
		
		/**
		 * save fan information
		 */
		saveFanInfo : function(doSubmit) {
			var objProps = _serializeRegistrationServicesData('profile','profile_fanInformation',['favoriteTeam','leastFavoriteTeam','favoritePlayer']);

			// if account creation wizard flow, submit the form which loads the next step in workflow
			if (!!doSubmit){
				$(AccountManagement).one('onSaveFanInfo', function() {
					var form = $('#form_fanInformation');
					form.unbind();
					form.submit();
					return true;
				});
			}

			// stay on the page if user not in wizard flow
			else {
				$(AccountManagement).one('onSaveFanInfo', function() {
					AccountManagement.message.display('<p>Your Fan Information has been saved!</p>','#profile_fanInformation','success');
					return true;
				});
			}

			// display error message
			StatusManager.onError(function(e) {
				return AccountManagement.validation.handleFormValidationErrors({
					e: e,
					formContainer : '.profile_fanInformation',
					msgContainer  : '.msg',
					labelTags     : '.labelBlock',
					scrollTo      : 'msgContainer'
				});
			});

			// trigger onSaveFanInfo event on success
			StatusManager.onSuccess(function(){
				$(AccountManagement).trigger('onSaveFanInfo', [{ fanInfo: objProps }]);
				return true;
			});

			// clear messages and register Profile with status manager
			$("#wrp-messages").html('');
			StatusManager.set("Profile");

			// save fan info
			ProfileService.save(objProps,
				function() {
					StatusManager.update("Profile","success");
				},
				function(source,msg){
					AccountManagement.validation.handleServerErrors({
						source:source,
						msg:msg,
						formContainer:'#profile_fanInformation'
					});
				});

			return false;
		},

		/**
		 * save nickname
		 */
		 saveNickname : function() {
			var objProps = _serializeRegistrationServicesData('profile','form_nickname'),
			    params   = null,
			    callback = null;

			// check arguments for success callback
			if (arguments.length===1&&typeof arguments[0]==='object' ){
				params = arguments[0];
				if (!!params.success && typeof params.success==='function')	{ callback=params.success; }
			}
			// check function properties for success callback
			else if (!!this.success && typeof this.success==='function') { callback=this.success; }

			// bind successful nickname handler
			$(AccountManagement).one('onSaveNickname', function saveNicknameHndler( event, objProps ) {
				AccountManagement.message.reset('#form_nickname .msg');
				bam.popModule.exit({
				    postExit: function() {
				        $("span#profile_nickname").html( objProps.nickname );
				        AccountManagement.message.display('<p>Your Nickname has been updated!</p>','#profile_personalInformation','success');
				        if (!!callback) { callback(objProps.nickname); }
                    }
                });
			});

			ProfileService.save(objProps,
				// trigger onSaveNickname when successful save
				function(){
					$(AccountManagement).trigger('onSaveNickname', [ objProps ]);
				},
				//error
				function(source,msg){
					AccountManagement.validation.handleServerErrors({
						source : source,
						msg    : msg,
						formContainer : '#popup_nickname'
					});
				}
			);
		 },
	
		 /**
		 * save email
		 */
		 saveEmail : function() {
			var objProps = _serializeRegistrationServicesData('email');

			// bind successful email save handler
			$(AccountManagement).one('onSaveEmail', function saveEmailHandler( event, objProps ){
				bam.popModule.exit({
				    postExit: function() {
				        $("span#email_address").html(objProps.address);
				        AccountManagement.message.display('<p>Your Email has been updated!</p>','#profile_accountInformation','success');
                    }
                });
			});

			EmailService.update(objProps,false,
				function(){
					$(AccountManagement).trigger('onSaveEmail', [ objProps ]);
				},
				//error
				function(source,msg){
					AccountManagement.validation.handleServerErrors({source:source,msg:msg,formContainer:'#form_email'});
				}
			);
		 },

		/**
		 * save password
		 */
		 savePassword : function() {
			var email      = $("#email_address").html(),
			    currentpwd = $("#currentpwd").val(),
			    password   = $("#password").val();
			
			// bind successful password save handler
			$(AccountManagement).one('onSavePassword', function savePasswordHandler() {
				AccountManagement.message.reset('#form_password .msg');
				bam.popModule.exit({
				    postExit: function() {
				        AccountManagement.message.display('<p>Your Password has been updated!</p>','#profile_personalInformation','success');
                    }
                });
			});

			// if new password was entered, save it
			if ( !bam.validation.isEmpty(currentpwd) && !bam.validation.isEmpty(password) ) {
				PasswordService.update(email, currentpwd, password, 
					function(){
						$(AccountManagement).trigger('onSavePassword');
					},
					function(source,msg){
						AccountManagement.validation.handleServerErrors({source:source,msg:msg,formContainer:'#popup_password'});
					}
				);
			}
		 },

		/**
		 * Save Avatar. Will be deprecated when PhotoUploadService is done.
		 */
		saveAvatar : function() {
			var objProps = _serializeRegistrationServicesData('profile','form_avatar');

			// bind successful password save handler
			$(AccountManagement).one('onSaveAvatar', function saveAvatarHandler() {
                function avatarSuccess() {
				    //$('#curAvatar').attr('src','http://mlb.mlb.com/images/account/avatars/200x200/'+objProps.avatar);
				    AM.loaders.loadAvatar();
				    AM.message.reset('#form_avatar .msg');
				    AM.message.display('<p>Your Avatar has been updated!</p>','#profile_personalInformation','success');
                }

				if (!!bam.popModule) { 
				    bam.popModule.exit({
				        postExit: function() {
                           avatarSuccess();
                        }
                    });
			    } else {
                    avatarSuccess();   
                }
			});

			ProfileService.save(objProps,
				function(){
					$(AccountManagement).trigger('onSaveAvatar');
				},
				//error
				function(source,msg){
					AccountManagement.validation.handleServerErrors({
						source: source,
						msg: msg,
						formContainer: '#form_avatar'
					});
				}
			);
			
		},
		

		/**
		 * Save privacy settings
		 */
		 savePrivacy : function() {

			var arrPrivacy = _serializePrivacySettings();

			// bind successful password save handler
			$(AccountManagement).one('onSavePrivacy', function savePrivacyHandler() {
				AccountManagement.message.display('<p>Your Privacy Settings have been saved!</p>','#profile_privacy','success');
				//bam.popModule.exit();
			});

			CommunityService.savePrivacySettings(arrPrivacy, 
				function() { 
					$(AccountManagement).trigger('onSavePrivacy');
				},
				function(source,msg){
					AccountManagement.validation.handleServerErrors({source:source,msg:msg,formContainer:'#profile_privacy'});
				}
			);

		 },

		/**
		 * Unblock a user
		 */
		 unblockUser : function(ipid,nickname) {
			// bind successful password save handler
			$(AccountManagement).one('onUnblockUser', function unblockUserHandler() {
				AccountManagement.message.display('<p>'+nickname+' has been unblocked</p>','#profile_blockedList','success');
				$('#bu_'+ipid).remove();
			});

			FriendService.unblock(ipid, 
				function(){
					$(AccountManagement).trigger('onUnblockUser');
				},
				function(source,msg){
					AccountManagement.validation.handleServerErrors({source:source,msg:msg,formContainer:'#profile_blockedList'});
				}
			);
		 }
	};
	return _module;
})();

