/**
 * Account Management module for loading pages/forms from Registration SOAP services
 * @class loaders
 * @author jferrer
 */
AccountManagement.loaders = (function(){
	/**
	 * Populates form fields based on an Registration Services object
	 * @param	{type}	Registration service type to parse [profile|email|password|address]
	 * @param	{obj}	Registration service object used to populate form fields
	 */
	function _populateByObj(type,obj) {
		var o, el, v;
		for (o in obj) {
			el = $("[id*='"+type+"_"+o+"']");
			if (el.size()>0){				
				v  = obj[o] ? obj[o].value ? obj[o].value : obj[o] : '';
				v  = bam.string.unescapeHTML(v);
				if (el.is(':input')) {
					el.val(v);
				}
				else {
					el.html(obj[o].value ? v[0] : v);
				}
			}
		}
	}


	/**
	 * render fan info section and bind appropriate validation
	 */
	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];
				var 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();
			}
		);

		
	}

	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 ); }
		});
	}

	function _bindValidationFanInfo(isWizard){
		// set validation
		bam.imports(bam.forms);
		var profile_fanInformation = document.profile_fanInformation;
		profile_fanInformation.setAttribute("trigger","onsubmit");
		bam.forms.CheckForm(profile_fanInformation);

		profile_fanInformation.onerror = function(e) { 
			profile_fanInformation.setAttribute("isError","true");
			return AccountManagement.validation.handleFormValidationErrors({
				e: e,
				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(){ 
			
			if(this.getAttribute("isError") == "true") {
				this.setAttribute("isError","false");
			}
			else {
				$(".profile_fanInformation .error").removeClass("error");
				$(".profile_fanInformation .msg").html('').hide();

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

	function _bindValidationPersonalInfo(isWizard){
		/**
		 * set form validation
		 */
		bam.imports(bam.forms);
		var profileform = document.profileForm;
		profileform.setAttribute("trigger","onsubmit");
		bam.forms.CheckForm(profileform);

		profileform.onerror = function(e) { 
			profileform.setAttribute("isError","true");
			return AccountManagement.validation.handleFormValidationErrors({
				e: e,
				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(){
				if(this.getAttribute("isError") == "true") {
					this.setAttribute("isError","false");
				} else {
					$(".profile_personalInformation .error").removeClass("error");
					$(".profile_personalInformation .msg").html('').hide();

					var 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;
			}
		);
	}

	var _module = {
		
		/**
		 * populate email address
		 */
		getEmail : function() {
			EmailService.findPrimary( 
				function(email) {
					_populateByObj('email',email);
				}, 
				function(serviceOperation,status){ 
					AccountManagement.validation.handleServerErrors({source:serviceOperation,msg:status,formContainer:'#profile_accountInformation'});
				}
			);
		},

		/**
		 * populate address
		 */
		getAddress : function() {
			AddressService.findShipping(
				function(address) {
					_populateByObj('address',address);
				}, 
				function(serviceOperation,status){ 
					if (serviceOperation=='Address.findShipping' && status.code==-4000)
						return false;
					AccountManagement.validation.handleServerErrors({source:serviceOperation,msg:status,formContainer:'#profile_personalInformation'});
				}
			);

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

		getFullProfile : function(){
			/**
			 * populate profile information
			 */
			ProfileService.find( 
				function(profile) {
				
					_populateByObj('profile', profile);
					_loadFanInfo(profile);
					_initFanInfo();
					_bindValidationFanInfo(false); // is not wizard
					_bindValidationPersonalInfo(false); // is not wizard

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

		getPersonalInfo : function(){
			var isWizard = (arguments.length>0 && typeof arguments[0]==='boolean') ? arguments[0] : true;
			/**
			 * populate profile information
			 */
			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");
					if (nickname.html()=='&nbsp;' || nickname.html()=='' || nickname.html()==' ') {
						$("a#changeNickname").click();
					}
				},
				function(serviceOperation,status){ 
					AccountManagement.validation.handleServerErrors({source:serviceOperation,msg:status,formContainer:'#profile_personalInformation'});
				}
			);
		},
		
		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'});
				}
			);
		},

		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'});
				}
			);
		},

		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){ 
					AM.validation.displayServerErrors({source:serviceOperation,msg:status,formContainer:'#profile_privacy'});
				}
			);
		}
	};
	return _module;
})();