Profile = Class.create({
	initialize: function(element) {
		this.initializeElement(element);
	},
	
	initializeElement: function(element) {
		this.element = $(element);
		if (this.element)
		{
			this.validator = new Validator(element);
			this.url = this.element.readAttribute("url");
			this.resultDisplayer = $("profileResultDisplayer");
			$("saveButton_profile").observe("click", this.saveListener.bindAsEventListener(this));
		}
	},
	
	saveListener: function(e) 
	{
		this.save();
	},
	
	save: function ()
	{
		if(this.validator.checkAllFields()) {
			var nameVal			= $F('name_profile');
			var genderVal		= $F('gender_profile');
			var countryVal		= $F('country_profile');
			var usernameVal		= $F('username_profile');
			var passwordVal		= $F('password_profile');
			var password2Val	= $F('password2_profile');
			var emailVal		= $F('email_profile').replace("@", "(at)");
			var captchaVal		= $F('profileCaptcha');
		
			if(passwordVal == password2Val) {
				new Ajax.Request(this.url, {
					method		: 'get',
					parameters	: {
						name		: nameVal, 
						gender		: genderVal,
						country		: countryVal,
						username	: usernameVal,
						password	: passwordVal,
						email		: emailVal,
						captcha		: captchaVal}, 
					onComplete 	: this.saveResponse.bind(this)
				});			
			}
			else {
				this.resultDisplayer.update("Passwords do NOT match!");
			}
		}
		else {
			this.resultDisplayer.update("Please fill the marked fields correctly!");		
		}
	},
	
	saveResponse: function(transport)
	{
		var response = transport.responseText.evalJSON();
		if(response.status && response.status == 'success') 
		{
			this.resultDisplayer.update("Your profile information saved successfully.");
		}
		else
		{
			this.resultDisplayer.update(response.message);		
		}
	}
});

function windowLoadedProfile()
{
	new Profile("profileTable");
}

(function() {
	Event.observe(window, "load", windowLoadedProfile);
})();

