﻿var Users = (function(
	initValues)
{
	var users = { SyndicationUtilities: {}, UserUtilities: {} },
		window = this,
		syndicatorID = (initValues.SyndicatorID || 0),
		syndicationLoginPopupID = (initValues.SyndicationLoginPopupID || 0),
		syndicationLoginPopupEmailAddressFieldID = (initValues.SyndicationLoginPopupEmailAddressFieldID || 0),
		createUpdateSyndicatedPersonOnFailure = true,
		userLoggedIn = false,
		registrationType = 0,
		registrationTypeSet = false,
		disableValidationVariableNames = [];

	users.NewUserEmailAddressValidationFailed = false;

	users.SetRegistrationType = function(
		registrationTypeLocal)
	{
		if (!registrationTypeSet)
		{
			registrationType = registrationTypeLocal;

			registrationTypeSet = true;
		}
	};

	users.RemoveBrokerProfileImage = function(
        profileID,
        zAuthentication,
        imgType,
        linkElement,
        messageElement,
        imgElement)
	{
		var imageRemovedSuccessfully = false;

		if (typeof (RemoteScriptingCall) == 'function')
		{
			var xml = (
                '<DeleteProfileImage><ProfileImage ImageType="' +
                imgType +
                '" ProfileID="' +
                profileID +
                '" /></DeleteProfileImage>');

			var sReturn = RemoteScriptingCall(
                (ContentProviderUrl +
                    '/users/Services/Users.asmx?Z=' +
                    zAuthentication),
                xml,
                'RemoveBrokerProfileImage',
                'https://secure.bizbuysell.com/Users',
                'ResponseData');

			var result = 'false';

			if ((sReturn) &&
                (sReturn.documentElement))
			{
				if (sReturn.documentElement.hasChildNodes)
				{
					result = sReturn.documentElement.firstChild.getAttribute('value');
				}
			}

			imageRemovedSuccessfully = (result.toLowerCase() == 'true');

			if (imageRemovedSuccessfully)
			{
				document.getElementById(imgElement).src = (
                    ContentProviderUrl +
                    '/brokerdirectory/images/icons/photoPlaceholder_small.gif');

				document.getElementById(linkElement).style.display = 'none';

				alert('Image has been removed.');
			}

			if (typeof (HideRemoteScriptingMsg) == 'function')
			{
				HideRemoteScriptingMsg(
					messageElement);
			}
		}

		return imageRemovedSuccessfully;
	};

	users.RemoveCommunityProfileImage = function(
        profileID,
        imageType,
        txtFileUploadClientID,
        hlRemoveImageClientID,
        messageElement,
        imageClientID,
        noPhotoImageUrl)
	{
		var imageRemovedSuccessfully = false;

		noPhotoImageUrl = (noPhotoImageUrl || '');
		imageClientID = (imageClientID || '');

		if (typeof (RemoteScriptingCall) == 'function')
		{
			var xml = (
                '<DeleteProfileImage><ProfileImage ImageType="' +
                imageType +
                '" ProfileID="' +
                profileID +
                '" /></DeleteProfileImage>');

			var sReturn = RemoteScriptingCall(
                (ContentProviderUrl +
                    '/users/Services/Users.asmx'),
                xml,
                'RemoveCommunityProfileImage',
                'https://secure.bizbuysell.com/Users',
                'ResponseData');

			var result = 'false';

			if ((sReturn) &&
                (sReturn.documentElement))
			{
				if (sReturn.documentElement.hasChildNodes)
				{
					result = sReturn.documentElement.firstChild.getAttribute('value');
				}
			}

			imageRemovedSuccessfully = (result.toLowerCase() == 'true');

			if (imageRemovedSuccessfully)
			{
				var hlRemoveImage = document.getElementById(
                    hlRemoveImageClientID);

				if (hlRemoveImage != null)
				{
					hlRemoveImage.style.display = 'none';
				}

				var txtFileUpload = document.getElementById(
                    txtFileUploadClientID);

				if (txtFileUpload != null)
				{
					txtFileUpload.value = '';
				}

				if ((imageClientID != '') &&
					(noPhotoImageUrl != ''))
				{
					var image = document.getElementById(
						imageClientID);

					if (image)
					{
						image.src = noPhotoImageUrl;
					}
				}

				alert('Image has been removed.');
			}

			if (typeof (HideRemoteScriptingMsg) == 'function')
			{
				HideRemoteScriptingMsg(
					messageElement);
			}
		}

		return imageRemovedSuccessfully;
	};

	users.RegisterDisableValidationVariableName = function(
		disableValidationVariableName)
	{
		disableValidationVariableNames.push(
			disableValidationVariableName);
	};

	users.DisableValidation = function(
		validationGroupName)
	{
		if (disableValidationVariableNames.length > 0)
		{
			validationGroupName = validationGroupName || '';

			for (var index = 0; index < disableValidationVariableNames.length; index++)
			{
				eval(
					disableValidationVariableNames[index] +
					' = true;');
			}

			var hideErrorMessageListFunctionCall = (
				'if ((typeof(Validation) != "undefined") && (typeof(Validation.Hide' +
				validationGroupName +
				'ErrorMessageList) == "function")) Validation.Hide' +
				validationGroupName +
				'ErrorMessageList(true);');

			eval(
				hideErrorMessageListFunctionCall);
		}
	};

	users.ValidatePasswordLength = function(
		txtPasswordClientID,
		minPasswordLength)
	{
		var passwordLengthIsValid = true;

		var txtPassword = document.getElementById(
			txtPasswordClientID);

		if ((txtPassword != null) &&
			(txtPassword.value.length > 0) &&
			(minPasswordLength > 0))
		{
			if (txtPassword.value.length < minPasswordLength)
			{
				passwordLengthIsValid = false;
			}
		}

		return passwordLengthIsValid;
	};

	users.IsPersonEmailAddressValidForNewUser = function(
		txtEmailAddressClientID,
		validationGroup,
		validationAnchorName,
		forgotPasswordUrl,
		currentEmailAddress,
		txtPasswordClientID,
		showLoginLink)
	{
		var personEmailAddressIsValidForNewUser = true;

		if (typeof (showLoginLink) == 'undefined')
		{
			showLoginLink = false;
		}

		var txtEmailAddress = document.getElementById(
			txtEmailAddressClientID);

		if ((txtEmailAddress != null) &&
			(txtEmailAddress.value != '') &&
			(typeof (RemoteScriptingCall) == 'function'))
		{
			var emailAddress = txtEmailAddress.value;

			personEmailAddressIsValidForNewUser = false;

			if ((typeof (currentEmailAddress) != 'undefined') &&
                (currentEmailAddress == emailAddress))
			{
				personEmailAddressIsValidForNewUser = true;
			}
			else
			{
				var password = '';

				if (typeof (txtPasswordClientID) != 'undefined')
				{
					var txtPassword = document.getElementById(
						txtPasswordClientID);

					if (txtPassword)
					{
						password = txtPassword.value;
					}
				}

				var checkIfPersonEmailAddressIsValidForNewUsersXml = (
					'<CheckIfPersonEmailAddressIsValidForNewUsers EmailAddress="' +
					emailAddress +
					'" RegistrationType="' +
					registrationType +
					'" Password="' +
					password +
					'" />');

				var sReturn = RemoteScriptingCall(
					(ContentProviderUrl +
						'/users/Services/Users.asmx'),
					checkIfPersonEmailAddressIsValidForNewUsersXml,
					'IsPersonEmailValidForNewUser',
					'https://secure.bizbuysell.com/Users',
					'ResponseData');

				if ((sReturn) &&
					(sReturn != null) &&
					(sReturn.documentElement))
				{
					if (sReturn.documentElement.hasChildNodes)
					{
						var result = sReturn.documentElement.firstChild.getAttribute(
							'value');

						if (result.toLowerCase() == 'true')
						{
							personEmailAddressIsValidForNewUser = true;
						}
					}
				}
			}
		}

		if (!personEmailAddressIsValidForNewUser)
		{
			var clearErrorMessageListFunctionCall = (
				'if ((typeof(Validation) != "undefined") && (typeof(Validation.Clear' +
				validationGroup +
				'ErrorMessageList) == "function")) Validation.Clear' +
				validationGroup +
				'ErrorMessageList();');

			eval(clearErrorMessageListFunctionCall);

			users.NewUserEmailAddressValidationFailed = true;

			var errorMessage = (
				emailAddress +
				' is already a registered user on BizBuySell.');

			if (showLoginLink)
			{
				if ((window.MyBBS) &&
					(typeof (MyBBS.ToggleSignInPopup) == 'function'))
				{
					errorMessage += (
						'<br />Please click <a href="javascript:void(0);" onclick="MyBBS.ToggleSignInPopup({ ExistingEmailAddress: \'' +
						emailAddress +
						'\' });">here</a> to login.');
				}
			}
			else if ((typeof (forgotPasswordUrl) != 'undefined') &&
				(forgotPasswordUrl != null) &&
				(forgotPasswordUrl != ''))
			{
				if (forgotPasswordUrl.match('[%Email%]') != null)
				{
					forgotPasswordUrl = forgotPasswordUrl.replace(
                        '[%Email%]',
                        emailAddress);
				}

				errorMessage += (
					'  If you forgot your password, click <a href="' +
					forgotPasswordUrl +
					'">here</a> to retrieve it.');
			}

			var addErrorMessageFunctionCall = (
				'if ((typeof(Validation) != "undefined") && (typeof(Validation.Add' +
				validationGroup +
				'ErrorMessage) == "function")) Validation.Add' +
				validationGroup +
				'ErrorMessage(errorMessage);');

			eval(addErrorMessageFunctionCall);

			errorMessage = (
				emailAddress +
				' is already a registered user on BizBuySell.');

			var errorList = (
				'<ClientSideErrorList><ClientSideError PageUrl="http://www.bizbuysell.com/users/Default.aspx" ErrorSourceName="" ErrorTypeID="0" ErrorMessage="' +
				errorMessage +
				'" InputData="' +
				emailAddress +
				'"></ClientSideError></ClientSideErrorList>');

			TrackErrorList(
				errorList);

			window.location = (
				'#' +
				validationAnchorName);
		}

		return personEmailAddressIsValidForNewUser;
	};

	users.IsNewPersonPasswordValid = function(
		personID,
		txtCurrentPasswordClientID,
		txtNewPassword1ClientID,
		txtNewPassword2ClientID,
		validationGroup,
		validationAnchorName)
	{
		var currentPasswordIsValid = true;

		var txtCurrentPassword = document.getElementById(
			txtCurrentPasswordClientID);

		var txtNewPassword1 = document.getElementById(
			txtNewPassword1ClientID);

		var txtNewPassword2 = document.getElementById(
			txtNewPassword2ClientID);

		if ((personID > 0) &&
			(txtCurrentPassword != null) &&
			(txtNewPassword1 != null) &&
			(txtNewPassword2 != null))
		{
			var errorMessage = '';

			if ((txtNewPassword1.value.length > 0) ||
				(txtNewPassword2.value.length > 0))
			{
				if (txtCurrentPassword.value.length <= 0)
				{
					currentPasswordIsValid = false;

					errorMessage = 'Please enter your current password.'
				}
				else if (txtNewPassword1.value != txtNewPassword2.value)
				{
					currentPasswordIsValid = false;

					errorMessage = 'The Confirmed Password does not match your New Password.  Please carefully enter your passwords again.'
				}
				else if (typeof (RemoteScriptingCall) == 'function')
				{
					var checkIfCurrentPersonPasswordIsValidXml = (
						'<IsCurrentPersonPasswordValid PersonID="' +
						personID +
						'" EnteredPassword="' +
						txtCurrentPassword.value +
						'" />');

					var sReturn = RemoteScriptingCall(
						(ContentProviderUrl +
							'/users/Services/Users.asmx'),
						checkIfCurrentPersonPasswordIsValidXml,
						'IsCurrentPersonPasswordValid',
						'https://secure.bizbuysell.com/Users',
						'ResponseData');

					if ((sReturn) &&
						(sReturn != null) &&
						(sReturn.documentElement))
					{
						if (sReturn.documentElement.hasChildNodes)
						{
							var result = sReturn.documentElement.firstChild.getAttribute(
								'value');

							if (result.toLowerCase() == 'false')
							{
								currentPasswordIsValid = false;

								errorMessage = 'Your current password is not valid.'
							}
						}
					}
				}
			}
		}
		
		/*
		var clearErrorMessageListFunctionCall = (
			'if ((typeof(Validation) != "undefined") && (typeof(Validation.Clear' +
			validationGroup +
			'ErrorMessageList) == "function")) Validation.Clear' +
			validationGroup +
			'ErrorMessageList();');

		eval(clearErrorMessageListFunctionCall);
		*/

		if ((!currentPasswordIsValid) &&
			(errorMessage != ''))
		{
			var addErrorMessageFunctionCall = (
				'if ((typeof(Validation) != "undefined") && (typeof(Validation.Add' +
				validationGroup +
				'ErrorMessage) == "function")) Validation.Add' +
				validationGroup +
				'ErrorMessage(errorMessage);');

			eval(addErrorMessageFunctionCall);

			var errorList = (
				'<ClientSideErrorList><ClientSideError PageUrl="http://www.bizbuysell.com/users/Edit.aspx" ErrorSourceName="" ErrorTypeID="0" ErrorMessage="' +
				errorMessage +
				'" InputData=""></ClientSideError></ClientSideErrorList>');

			TrackErrorList(
				errorList);

			top.location = (
				'#' +
				validationAnchorName);
		}

		return currentPasswordIsValid;
	};

	users.ToggleLoginPopup = function()
	{
		var communityLoginPopup = document.getElementById(
			'loginPopupOverlay');

		if (communityLoginPopup != null)
		{
			if (communityLoginPopup.style.display.toLowerCase() == 'none')
			{
				communityLoginPopup.style.display = '';
			}
			else
			{
				communityLoginPopup.style.display = 'none';
			}
		}

		toggleOverlay();

		top.location = '#';
	};

	users.Login = function(
		userName,
		password,
		loginType)
	{
		userName = (userName || '');
		password = (password || '');
		loginType = (loginType || 0);

		if ((userName.length > 0) &&
			(password.length > 0) &&
			(typeof (users.UserUtilities.Login) == 'function'))
		{
			users.UserUtilities.Login(
				userName,
				password,
				loginType,
				function(
					loginResult)
				{
					loginResult = (
						loginResult ||
						{
							UserLoggedInSuccessfully: false,
							UserGreeting: '',
							IsBroker: false,
							OnBrokerLoginSuccessfulRedirectUrl: '',
							ReportedAbuseQuestionIDs: [],
							ReportedAbuseAnswerIDs: [],
							SavedSearches: []
						});

					userLoggedIn = !!loginResult.UserLoggedInSuccessfully;

					if (userLoggedIn)
					{
						var loginGreetingLabel = null;

						if (typeof (loginGreetingLabelClientID) != 'undefined')
						{
							loginGreetingLabel = document.getElementById(
								loginGreetingLabelClientID);
						}

						if ((loginResult.UserGreeting != '') &&
						    (loginGreetingLabel))
						{
							loginGreetingLabel.innerText = loginResult.UserGreeting;
						}

						if ((window.CommunityQnA) &&
							(typeof (CommunityQnA.OnLoginSuccessful) == 'function'))
						{
							CommunityQnA.OnLoginSuccessful(
								loginResult.ReportedAbuseQuestionIDs,
								loginResult.ReportedAbuseAnswerIDs);
						}

						if ((window.MyBBS) &&
							(typeof (MyBBS.OnLoginSuccessful) == 'function'))
						{
							MyBBS.OnLoginSuccessful(
								loginResult);
						}

						if ((window.Community) &&
							(typeof (Community.OnLoginSuccessful) == 'function'))
						{
							Community.OnLoginSuccessful();
						}

						if ((window.EmailAlerts) &&
							(typeof (EmailAlerts.OnLoginSuccessful) == 'function'))
						{
							EmailAlerts.OnLoginSuccessful();
						}

						if ((window.FSBOHomeLogin) &&
							(typeof (FSBOHomeLogin.OnLoginSuccess) == 'function'))
						{
							FSBOHomeLogin.OnLoginSuccess();
						}

						if ((window.CommunityRegistration) &&
							(typeof (CommunityRegistration.OnLoginSuccessful) == 'function'))
						{
							CommunityRegistration.OnLoginSuccessful();
						}

						if ((window.Listings) &&
							(typeof (Listings.OnLoginSuccessful) == 'function'))
						{
							Listings.OnLoginSuccessful(
								loginResult.SavedSearches);
						}
					}
					else
					{
						if ((window.MyBBS) &&
							(typeof (MyBBS.OnLoginFailed) == 'function'))
						{
							MyBBS.OnLoginFailed();
						}

						if ((window.FSBOHomeLogin) &&
							(typeof (FSBOHomeLogin.OnLoginFailed) == 'function'))
						{
							FSBOHomeLogin.OnLoginFailed();
						}
					}
				},
				function()
				{
					if ((window.MyBBS) &&
						(typeof (MyBBS.OnLoginFailed) == 'function'))
					{
						MyBBS.OnLoginFailed();
					}

					if ((window.FSBOHomeLogin) &&
						(typeof (FSBOHomeLogin.OnLoginFailed) == 'function'))
					{
						FSBOHomeLogin.OnLoginFailed();
					}
				});
		}
	};

	users.Logout = function()
	{
		if (typeof (users.UserUtilities.Logout) == 'function')
		{
			users.UserUtilities.Logout(
				function()
				{
					setTimeout(
						function()
						{
							window.location = 'http://www.bizbuysell.com/';
						},
						100);
				},
				function()
				{
					// Failed
				});
		}
	};

	users.IsUserLoggedIn = function()
	{
		return userLoggedIn;
	}

	users.ToggleChangePasswordFields = function()
	{
		var changePasswordFields = document.getElementById(
			'registration_form_changePasswordFields');

		if (changePasswordFields)
		{
			if (this.value.length > 0)
			{
				changePasswordFields.className = 'enabled';
			}
			else
			{
				changePasswordFields.className = 'disabled';

				var inputFields = changePasswordFields.getElementsByTagName(
					'input');

				if (inputFields.length > 0)
				{
					for (var index = 0; index < inputFields.length; index++)
					{
						inputFields[index].value = '';
					}
				}
			}
		}
	};

	users.SetOverlayHeightForIE6 = function()
	{
		if ((window.jQuery) &&
			($.browser.msie) &&
			($.browser.version < 7))
		{
			$('#bbs_page_overlay').height(
				$(document).height());

			$('select').toggle();
		}
	};

	users.ToggleSyndicationLoginPopup = function(
		syndicatedPersonSyndicatorEmailAddress,
		changeCredentials)
	{
		syndicatedPersonSyndicatorEmailAddress = (syndicatedPersonSyndicatorEmailAddress || '');
		changeCredentials = changeCredentials || false;

		if (syndicationLoginPopupID != '')
		{
			var syndicationLoginPopup = $('#' + syndicationLoginPopupID);

			if (syndicationLoginPopup)
			{
				if ((syndicatedPersonSyndicatorEmailAddress != '') &&
					(syndicationLoginPopupEmailAddressFieldID != ''))
				{
					syndicationLoginPopup.find(
						'#' + syndicationLoginPopupEmailAddressFieldID).val(
							syndicatedPersonSyndicatorEmailAddress);
				}

				syndicationLoginPopup.toggle();

				toggleOverlay();

				$(window).scrollTop(0);

				if (changeCredentials)
				{
					createUpdateSyndicatedPersonOnFailure = false;
				}
			}
		}
	};

	users.SyndicationLogin = function(
		personID,
		username,
		password,
		callback)
	{
		username = username || '';
		password = password || '';

		if ((syndicatorID > 0) &&
			(personID > 0) &&
			(username.length > 0) &&
			(password.length > 0) &&
			(typeof (users.SyndicationUtilities.Login) == 'function'))
		{
			users.SyndicationUtilities.Login(
				syndicatorID,
				personID,
				username,
				password,
				createUpdateSyndicatedPersonOnFailure,
				function(
					userValidated)
				{
					userValidated = (userValidated || false);

					if (typeof (callback) == 'function')
					{
						callback(
							userValidated);
					}
				},
				function()
				{
					if (typeof (callback) == 'function')
					{
						callback(
							false);
					}
				});
		}
	};

	users.UnlinkCredentials = function(
		personID)
	{
		personID = personID || 0;

		if ((syndicatorID > 0) &&
			(personID > 0) &&
			(typeof (users.SyndicationUtilities.UnlinkCredentials) == 'function'))
		{
			users.SyndicationUtilities.UnlinkCredentials(
				syndicatorID,
				personID,
				function(
					credentialsUnlinked)
				{
					if (credentialsUnlinked)
					{

					}
				});
		}
	};

	function toggleOverlay()
	{
		if (window.jQuery)
		{
			$('body').toggleClass(
				'showOverlay');
		}
		else
		{
			var bodyClass = document.body.className;

			if (bodyClass.indexOf('showOverlay') >= 0)
			{
				document.body.className = bodyClass.replace(
					'showOverlay',
					'');
			}
			else
			{
				if (bodyClass.length > 0)
				{
					bodyClass += ' ';
				}

				document.body.className = (
					bodyClass +
					'showOverlay');
			}
		}

		users.SetOverlayHeightForIE6();
	}

	return users;
})(window.UsersInitValues || {});