var Contacts = {
	nodeMask: null,
	nodeContainer: null,
	nodeForm: null,
	
	URL: '/order',
	
	'fields': function () {
		return this.nodeContainer.find('input.txt,textarea.txt'); 
	},
	
	'text': function() {
		return this.nodeContainer.find('div.text');
	},
	
	'result': function() {
		return this.nodeContainer.find('div.result');
	},
	
	'reset': function () {
		this.fields().each(function(index) {
			$(this).parent().removeClass("error");
			$(this).val('');
		});
		this.nodeForm.removeClass('hidden');
		this.text().removeClass('hidden');
		this.result().addClass('hidden');
	},
	
	'hide': function () {
		this.nodeMask.addClass('hidden');
		this.nodeContainer.addClass('hidden');
		this.reset();
	},
	
	'show': function () {
		this.nodeMask.removeClass('hidden');
		this.nodeContainer.removeClass('hidden');
	},
	
	'send': function () {
		var method = this.nodeForm.attr('method'),
			url = this.nodeForm.attr('action'),
			data = this.nodeForm.serialize();

		$[method](url, data, $.proxy(function (errors) {
			if (errors.length) {
				this.fields().each(function(index) {
					if ($.inArray(this.name, errors) >= 0) {
						$(this).parent().addClass("error");
					} else {
						$(this).parent().removeClass("error");
					}
				});
			} else {
				this.nodeForm.addClass('hidden');
				this.text().addClass('hidden');
				this.result().removeClass('hidden');
			}
		}, this), 'json');
		
		return false;
	},
	
	'init': function () {
		this.nodeMask = $('div.contacts-mask');
		this.nodeContainer = $('div.contacts-lb');
		this.nodeForm = this.nodeContainer.find('form');
		
		this.nodeContainer.find('a.close').click($.proxy(this.hide, this));
		
		this.nodeForm.submit($.proxy(this.send, this));
		
		this.nodeContainer.find('a.button').click($.proxy(function () {
			this.nodeForm.submit();
			return false;
		}, this));
	}
};

$(function () {
	var loaded = false,
		loading = false;
	
	$('a.contact-button').click(function () {
		if (loading) return false;
		
		if (loaded) {
			Contacts.show();
		} else {
			loading = true;
			$.get(Contacts.URL, function(data){
				$('body').append(data);
				loading = false;
				loaded = true;
				Contacts.init();
			}, 'html');
		}
		
		return false;
	});
});

