var clientAjaxLogin = Class.create({
	
	initialize: function()
	{
		this.authUrl = '/clients/index/authenticate';
		
		this.loginForm = $('clientLogin');
		this.errorBox = $('clientLoginErrorBox');
		this.attemptingBox = $('clientLoginAttemptingBox');
		this.successBox = $('clientLoginSuccessBox');
		
		this.linkObj = $('clientLoginLink');
    	this.boxObj = $('clientLoginBox');
    	this.isDown = false;
    	
    	this._initObservers();
	},
	
	_initObservers: function()
	{
		Event.observe(this.linkObj, 'click', this.linkClickHandler.bindAsEventListener(this));
		Event.observe(this.loginForm, 'submit', this.submit.bind(this), false);
	},
	
	submit: function(event)
	{
		Event.stop(event);
		this.hideForm();
		this.hideErrorBox();
		this.showAttemptingBox();
		this.ajaxLogin(event);
	},
	
	ajaxLogin: function(event)
    {
    	new Ajax.Request(this.authUrl,{
    		method: 'post',
    		parameters: this.loginForm.serialize(),
    		onSuccess: this.processAjaxValidationResult.bind(this),
    		onFailure: this.processAjaxFailure.bind(this)
    	});
    },
    
    processAjaxFailure: function(transport)
    {
    	this.hideAttemptingBox();
		this.showForm();
    	this.showErrorBox('Unknown Error');
    },
    
    processAjaxValidationResult: function(transport)
	{
		var response = transport.responseText.evalJSON();
		if (response.is_authorized == 'true') {
			this.hideErrorBox();
			this.hideForm();
			this.hideAttemptingBox();
			this.showSuccessBox();
			window.location = '/billing';
		} else {
			this.hideAttemptingBox();
			this.showForm();
			this.showErrorBox(response.auth_message);
		}
	},
	
	showErrorBox: function(message)
	{
		this.errorBox.show();
		this.errorBox.innerHTML = message;
	},
	
	hideErrorBox: function()
	{
		this.errorBox.hide();
		this.errorBox.innerHTML = '';
	},
	
	showAttemptingBox: function()
	{
		this.attemptingBox.show();
	},
	
	hideAttemptingBox: function()
	{
		this.attemptingBox.hide();
	},
	
	showSuccessBox: function()
	{
		this.successBox.show();
	},
	
	hideSuccessBox: function()
	{
		this.successBox.hide();
	},
	
	showForm: function()
	{
		this.loginForm.show();
	},
	
	hideForm: function()
	{
		this.loginForm.hide();
	},
	
	linkClickHandler: function(event)
	{
		if (!this.isDown) {
			var linkOffset = this.linkObj.cumulativeOffset();
			var linkDimensions = this.linkObj.getDimensions();
			var boxDimensions = this.boxObj.getDimensions();
			
			this.boxObj.style.top = (linkOffset.top + linkDimensions.height) + 'px';
			
			var newLeft = boxDimensions.width - linkDimensions.width;
			newLeft = (linkOffset.left - newLeft) - 2;
			
			this.boxObj.style.left = newLeft + 'px';
			this.boxObj.show();
			this.linkObj.addClassName('active');
			this.isDown = true;
		} else {
			this.boxObj.hide();
			this.linkObj.removeClassName('active');
			this.isDown = false;
		}
	}
});