/**
 * @fileOverview Account Management namespace for loading pages/forms from Registration SOAP services
 *
 * @namespace AccountManagement.loaders
 * @author Jon Ferrer <jon.ferrer@mlb.com>
 */
AccountManagement.loaders = (function(){

    /** @exports _module as AccountManagement.loaders */
    var _module;

	/**
	 * Populates form fields based on an Registration Services object
     *
	 * @param	{String}	type Registration service type to parse [profile|email|password|address]
	 * @param	{Object}	obj  Registration service object used to populate form fields
     * @private
	 */
	function _populateByObj(type,obj) {

		var o, el, v, fieldIdentifier, isGender;

		for (o in obj) {
            if( obj.hasOwnProperty( o ) ) {
                isGender = "gender".indexOf( o ) !== -1;

                if( isGender ) {
                    fieldIdentifier = "[id*='" + type + "_" + o + "_" + obj[o].value[0] + "']";
                } else {
                    fieldIdentifier = "[id*='" + type +"_" + o + "']";
                }

                el = $( fieldIdentifier );
                if (el.size()>0){				
                    v  = obj[o] ? obj[o].value ? obj[o].value : obj[o] : '';
                    v  = bam.string.unescapeHTML(v);
                    if ( el.is(':input') ) {
                        if( isGender ) {
                            el.attr( "checked", true );
                        } else {
                            el.val(v);
                        }
                    }
                    else {
                        el.html( obj[o].value && obj[o].value.length > 1 ? v[0] : v );
                    }
                }
			}
		}
	}


	/**
	 * Render fan info section and bind appropriate validation
     *
     * @param {Object} profile ProfileService data object
     * @private
	 */
	function _loadFanInfo(profile){
		_module.loadAvatar();		

		// render team tables
		$(":input[id^='profile'][id*='Team']").each(
			function(){
				var n = this.id.match(/^profile_(.*)$/)[1];
				if(this.value !== "") {
					var tarr = this.value.split(",");
					AccountManagement.fan.getTeamTable(tarr,n);
				} else {
					$("#"+n+"List").html("<p>Please select a Team</p>");
				}	
				$(this).remove();
			}
		);

		// render player tables
		$(":input[id^='profile'][id*='Player']").each(
			function(){
				var n = this.id.match(/^profile_(.*)$/)[1],
				    parr;

				if(this.value !== "") {
					parr = this.value.split(",");
					setTimeout(function(){ AccountManagement.fan.getPlayerData(parr,n,AccountManagement.fan.getPlayerTable); }, 500);
				} else {
					$("#"+n+"List").html("<p>Please select your Favorite Players</p>");
				}

				$(this).remove();
			}
		);

		
	}

    /**
     * Initalizes Fan Information autocomplete components 
     *
     * @private
     */
	function _initFanInfo(){
		AccountManagement.validation.bindCharLimitCount('profile_aboutMe',200);

		/**
		 * set autocomplete dropdowns
		 */ 
		$("#textFavoriteTeam").focus(function() { $(this).val(""); }).autocomplete("/components/account/v2/clubs.jsp",{
			delay:10,
			autoFill:false,
			matchContains:1,
			matchSubset:1,
			cacheLength:10,
			minChars:3,
			extraParams: { key:"teamId" },
			selectFirst: true,
			onItemSelect:function (li) { $("#addFavoriteTeam").val( li.extra ); }
		});

		$("#textLeastFavoriteTeam").focus(function() { $(this).val(""); }).autocomplete("/components/account/v2/clubs.jsp",{
			delay:10,
			autoFill:false,
			matchContains:1,
			matchSubset:1,
			cacheLength:10,
			minChars:3,
			extraParams: { key:"teamId" },
			selectFirst: true,
			onItemSelect:function (li) { $("#addLeastFavoriteTeam").val( li.extra ); }
		});

		$("#textFavoritePlayer").focus(function() { $(this).val(""); }).autocomplete("/mlb/components/community/playersearch.jsp",{
			delay:10,
			autoFill:false,
			matchContains:1,
			matchSubset:1,
			cacheLength:10,
			minChars:3,
			selectFirst: false,
			extraParams: { searchBy:"lastName" },
			onItemSelect:function (li) { $("#addFavoritePlayer").val( li.extra ); }
		});
	}

    /**
     * Binds form validation for Fan Information components
     *
     * @private
     * @param {boolean} isWizard    Should be TRUE if user registration is in Wizard Flow mode
     */
	function _bindValidationFanInfo(isWizard){
		var profile_fanInformation;

		bam.loadSync(bam.homePath + "bam.forms.js");

	    profile_fanInformation = document.profile_fanInformation;
		profile_fanInformation.setAttribute("trigger","onsubmit");
		bam.forms.CheckForm(profile_fanInformation);

		profile_fanInformation.onerror = function(error) { 
			profile_fanInformation.setAttribute("isError","true");
			return AccountManagement.validation.handleFormValidationErrors({
				"e": error,
				"formContainer" : ".profile_fanInformation",
				"msgContainer"  : ".msg",
				"labelTags"     : ".labelBlock",
				"scrollTo"      : "msgContainer"
			});
		};

		profile_fanInformation.addCheck(AccountManagement.validation.isInvalidLength);
		profile_fanInformation.addCheck(AccountManagement.validation.isAlphaExtendedCommonPunctuation);

		// set char limits on form fields
		$("#profile_firstName").addClass("fc-isInvalidLength").attr("min",0).attr("max",20).attr("maxlength",20);
		$("#profile_lastName").addClass("fc-isInvalidLength").attr("min",0).attr("max",20).attr("maxlength",20);
		$("#profile_hometown").addClass("fc-isInvalidLength").attr("max",20).attr("maxlength",20);
		$("#profile_aboutMe").addClass("fc-isAlphaExtendedCommonPunctuation").addClass("fc-isInvalidLength").attr("min",0).attr("max",200);

		// set onsubmit for form
		$(profile_fanInformation).submit(function(){ 
            var doSubmit;
			
			if(this.getAttribute("isError") == "true") {
				this.setAttribute("isError","false");

			} else {

				$(".profile_fanInformation .error").removeClass("error");
				$(".profile_fanInformation .msg").html('').hide();

				doSubmit = AccountManagement.actions.saveFanInfo(isWizard); 
			}
			return doSubmit;
		});
	}

    /**
     * Binds form validation for Personal Information component
     *
     * @private
     * @param {boolean} isWizard    Should be TRUE if user registration is in Wizard Flow mode
     */
	function _bindValidationPersonalInfo(isWizard){
		var profileform;

		bam.loadSync(bam.homePath + "bam.forms.js");

		profileform = document.profileForm;
		profileform.setAttribute("trigger","onsubmit");
		bam.forms.CheckForm(profileform);

		profileform.onerror = function(error) { 
			profileform.setAttribute("isError","true");
			return AccountManagement.validation.handleFormValidationErrors({
				"e": error,
				"formContainer" : ".profile_personalInformation",
				"msgContainer"  : ".msg",
				"labelTags"     : ".labelBlock",
				"scrollTo"      : "msgContainer"
			});
		};

		profileform.addCheck(AM.validation.isInvalidLength);
		profileform.addCheck(AM.validation.isAlphaCommonPunctuation);

		$('#profile_firstName').addClass('fc-isAlphaCommonPunctuation');
		$('#profile_lastName').addClass('fc-isAlphaCommonPunctuation');
		$('#addess_city').addClass('fc-isAlphaCommonPunctuation');

		// set form on submit event
		$(profileform).submit(
			function(){
                var doSubmit;

				if(this.getAttribute("isError") == "true") {

					this.setAttribute("isError","false");

				} else {

					$(".profile_personalInformation .error").removeClass("error");
					$(".profile_personalInformation .msg").html('').hide();

					doSubmit = AccountManagement.actions.savePersonalInfo(isWizard); 
				}

                return doSubmit;
			}
		);

		StatusManager.onError(
			function(e) {
				return AccountManagement.validation.handleFormValidationErrors({
					"e": e,
					"formContainer" : ".profile_personalInformation",
					"msgContainer"  : ".msg",
					"labelTags"     : ".labelBlock",
					"scrollTo"      : "msgContainer"
				});
			}
		);

		StatusManager.onSuccess(
			function() {
				AccountManagement.message.display("<p>Your Personal Information has been saved!</p>","#profile_personalInformation .msg","success");
				return true;
			}
		);
	}

	_module = {
		
		/**
		 * Retrieves user's email information from EmailService and renders view for returned data 
         *
         * @public
         * @methodOf AccountManagement.loaders
		 */
		getEmail : function() {

            var dfdServiceCall = $.Deferred();

			EmailService.findPrimary( 
				function(email) {
                    var verifiedLabelContainer = $("#verify-email-container"),
                        verifiedLabel = "Your email address is unverified. <span class='change'><a href='#/verify-email' id='btn-verify-email'>Click here to verify</a></span>";

					_populateByObj('email',email);

                    if (email.verified === false) {
                       
                        if (verifiedLabelContainer.length > 0) {

                            verifiedLabelContainer.html(verifiedLabel);

                        } else {
                            $("<div />", {
                                    id : "verify-email-container",
                                    html : verifiedLabel,
                                    css : {
                                        width : "400px",
                                        margin : ".5em 0 2em 4px"
                                    }
                                }).appendTo($("#email_address").parent());
                        }

                        $("#btn-verify-email").click(function() {
                            EmailService.sendVerification({
                                    identification : {
                                        type : "fingerprint",
                                        id : bam.cookies.get("ipid"),
                                        fingerprint : unescape(bam.cookies.get("fprt"))
                                    },

                                    success : function() {
                                        $("#verify-email-container").html("A verification email has been sent to this address. Please check your email and follow the instructions to complete verification.");

                                    },

                                    error : function() {
                                        $("#verify-email-container").html("There was an error with verifying your email address. Please try again in a few minutes.");
                                    }
                                });
                                
                            return false;
                        });
                    }

                    dfdServiceCall.resolve();
				}, 
				function(serviceOperation,status){ 
					AccountManagement.validation.handleServerErrors({source:serviceOperation,msg:status,formContainer:'#profile_accountInformation'});
                    dfdServiceCall.reject();
				});

            return dfdServiceCall.promise();
		},

		/**
		 * Retrieves user's address information from AddressService and renders view for returned data 
         *
         * @public
         * @methodOf AccountManagement.loaders
		 */
		getAddress : function() {
            var dfdServiceCall = $.Deferred();

			AddressService.findShipping(
				function(address) {
					_populateByObj('address',address);
                    dfdServiceCall.resolve();
				}, 
				function(serviceOperation,status){ 

					if (serviceOperation=='Address.findShipping' && status.code==-4000) {
                        dfdServiceCall.resolve();
						return false;
                    }

					AccountManagement.validation.handleServerErrors({source:serviceOperation,msg:status,formContainer:'#profile_personalInformation'});
                    dfdServiceCall.reject();

				}
			);

			$(":input[id^='address']").live("blur",
				function() {
					if ( $(this).val() !== '' ) {
						StatusManager.set("isAddressSubmission");
					}
				}
			);

            return dfdServiceCall.promise();
		},

		/**
		 * Retrieves user's profile and fan information from ProfileService and renders view for returned data 
         *
         * @public
         * @methodOf AccountManagement.loaders
		 */
		getFullProfile : function(isWizard) {
            var dfdServiceCall = $.Deferred();

			ProfileService.find( 
				function(profile) {
				
					_populateByObj('profile', profile);
					_loadFanInfo(profile);
					_initFanInfo();
					_bindValidationFanInfo(isWizard); // is not wizard
					_bindValidationPersonalInfo(isWizard); // is not wizard

                    dfdServiceCall.resolve();
				},
				function(serviceOperation,status){ 
					AccountManagement.validation.handleServerErrors({source:serviceOperation,msg:status,formContainer:'#profile_personalInformation'});

                    dfdServiceCall.reject();
				}
			);

            return dfdServiceCall.promise();
		},

		/**
		 * Retrieves user's profile information from ProfileService and renders view for returned data 
         * Used for Wizard Flow view.
         *
         * @public
         * @methodOf AccountManagement.loaders
		 */
		"getPersonalInfo" : function() {
			var isWizard = (arguments.length>0 && typeof arguments[0]==='boolean') ? arguments[0] : true;

			ProfileService.find( 
				function(profile) {	
					var nickname;
		
					_populateByObj('profile', profile);
					_bindValidationPersonalInfo(isWizard); // is wizard?

					$("#pageloading").remove();
					$("#mc").css("visibility","visible");

					// if missing nickname, display nickname overlay
					nickname = $("span#profile_nickname").html();
					if (nickname === "&nbsp;" || nickname === "" || nickname === ' ') {
						$("a#changeNickname").click();
					}
				},

				function(serviceOperation,status) { 
					AccountManagement.validation.handleServerErrors({
                        "source" : serviceOperation,
                        "msg"    : status,
                        "formContainer" :'#profile_personalInformation'
                    });
				}
			);
		},
		
		/**
		 * Retrieves user's fan information from ProfileService and renders view for returned data 
         * Used for Wizard Flow view.
         *
         * @public
         * @methodOf AccountManagement.loaders
		 */
		"getFanInfo" : function(){
			/**
			 * populate profile information
			 */
			ProfileService.find( 
				function(profile) {
				
					_populateByObj('profile', profile);
					_loadFanInfo(profile);
					_initFanInfo();
					_bindValidationFanInfo(true); // is wizard

					$("#pageloading").remove();
					$("#mc").css("visibility","visible");
				},
				function(serviceOperation,status) { 
					AccountManagement.validation.handleServerErrors({
                        "source" : serviceOperation,
                        "msg"    : status,
                        "formContainer" : "#profile_fanInformation"
                    });
				}
			);
		},

		/**
		 * Retrieves user's avatar from PhotoService and renders correct sized image from returned data 
         *
         * @public
         * @methodOf AccountManagement.loaders
		 */
		"loadAvatar" : function() {
			// avatar logo
			//$("#curAvatar").attr("src", profile.avatar ? '/images/account/avatars/200x200/' + profile.avatar.value : '/images/account/avatars/200x200/generic.jpg').width("200px").height("200px");

			var $curAvatar = $("#curAvatar").attr('src', '/images/loading.gif');

			PhotoUploadService.findAvatar(
				function(photo) {
					$curAvatar.attr("src", photo.filePath.replace('{sizeKey}','200x200'));
				},
				function(serviceOperation,status) { 
					AccountManagement.validation.handleServerErrors({
                        "source" : serviceOperation,
                        "msg"    : status,
                        "formContainer" : "#profile_accountInformation"
                    });
				}
			);
		},

		/**
		 * Retrieves user's privacy settings from CommunityService and blocked users from 
         * FriendService, then renders the Privacy Settings page based on returned data.
         *
         * @public
         * @methodOf AccountManagement.loaders
		 */
		"getPrivacySettings" : function() {
			// community
			CommunityService.findPrivacySettings(
				function(privacy) {
					var p=0, 
						pLen = privacy.length,
						name, level;

					do {
						name  = privacy[p].name;
						level = (privacy[p].level !== '') ? privacy[p].level : privacy[p].defaultLevel;
						$("#community_" + privacy[p].name).val([level]);
						p++;
					} while (p<pLen);
				}, 
				function(serviceOperation,status) { 
					Community.AccountManagement.displayServerErrors(serviceOperation, status, "profile_privacy");
				}
			);

			FriendService.findBlocked(
				function(arrBlocked){
					var b          = 0,
						lenBlocked = arrBlocked.length,
						user,
						html = ['<ul>'];


					if (lenBlocked>0){			
						do {
							user = arrBlocked[b];
							html.push('<li id="bu_'+user.identityPointId+'">'+user.nickname+' <a href="#" class="unblock" onclick="AM.actions.unblockUser('+user.identityPointId+',\''+user.nickname+'\');return false;">unblock</a></li>');
							b++;
						} while (b<lenBlocked);
						html.push('</ul>');

						$('#friends_blockedList').html(html.join(''));
					}
					else {
						$('#friends_blockedList').html('<p>You have not blocked any users.</p>');
					}
				},

				function(serviceOperation,status){ 
					AccountManagement.validation.displayServerErrors({
                        "source" : serviceOperation,
                        "msg"    : status,
                        "formContainer" :'#profile_privacy'
                    });
				}
			);
		}
	};

	return _module;

})();

