﻿function UserNameAvailablity()
{
	this.timeoutDuration = 1000
	this.lastCheckValue = ""
}

UserNameAvailablity.prototype.PerformCheck = function(self, userNameTextBox)
{
	var userName = userNameTextBox.value;
	var userNameDefined = userName.replace(/\s/g, "").length > 0;
	
	if(userNameDefined && userName != self.lastCheckValue)
	{
		self.lastCheckValue = userName;
		
		$.getJSON(
            "IsEmailAddressAvailable.ashx?EmailAddress=" + userName.replace(/ /g, "%20"),
            function(response) {
                self.SetMessageVisible(self, !response.isUserNameAvailable, response.userName);
            });
	}
}

UserNameAvailablity.prototype.SetMessageVisible = function(self, visible, emailAddress)
{
	if(visible)
	{
		$("#emailAlreadyExists").show();
		$("#emailAlreadyExistsLink").attr("href", "Retrieve.aspx?EmailAddress=" + emailAddress);
	}
	else
		$("#emailAlreadyExists").hide();
}

UserNameAvailablity.prototype.Check = function(userNameTextBox)
{
	var userName = userNameTextBox.value;
	var userNameDefined = userName.replace(/\s/g, "").length > 0;
	
	if(!userNameDefined)
	{
		this.SetMessageVisible(this, false);
		clearTimeout(this.timeout);
	}
	else if(userName != this.lastCheckValue)
	{
		this.SetMessageVisible(this, false);
		clearTimeout(this.timeout);
	
		var self = this;
		this.timeout = setTimeout(
			function()
			{
				self.PerformCheck(self, userNameTextBox);
			},
			this.timeoutDuration);	
	}
}

var emailAvailablity = new UserNameAvailablity();

