﻿Event.attach(document, "DOMContentLoaded", function() {
	var form = {
		ajax: new AjaxForm($i("feedback")),
		container: $i("feedback-container"),
		show: $i("feedback-show"),
		error: $i("feedback-error"),
		cancel: $i("feedback-cancel"),
		inputs: [ $i("feedback-email"), $i("feedback-message") ],
		notRobot: $i("feedback-notRobot")
	};
	
	var effects = {
		open: new Effects(0.6),
		close: new Effects(0.6)
	};
	
	effects.open.addEffect(Function.bind(animate), -332, -5);
	effects.close.addEffect(Function.bind(animate), -5, -332);
	
	// Toggle "selected" class.
	Event.attach(effects.open, "complete", function() { Class.add(form.container, "selected"); });
	Event.attach(effects.close, "complete", function() { Class.remove(form.container, "selected"); });
	
	function animate(value) {
		form.container.style.left = value + "px";
	}
	
	// Check notRobot and hide the parent nodes.
	if (form.notRobot) {
		form.notRobot.checked = true;
		var parents = $c("notRobot", null, form.ajax.form);
		for (var i = 0, parent; parent = parents[i]; i++) {
			parent.style.display = "none";
		}
	}
	
	// Clear error message on each input on blur if it was fixed.
	for (var i = 0, input; input = form.inputs[i]; i++) {
		Event.attach(input, "blur", function() {
			if (Class.get(this.parentNode, "error")) {
				verifyInput(this);
			}
		}, input);
	}
	
	// Validate fields on send.
	Event.attach(form.ajax, "beforesubmit", function() { return verifyForm(); }, this);
	Event.attach(form.ajax, "submit", function(response) {
		if (!response.Success) {
			form.error.innerHTML = response.Error;
		}
		
		return response.Success;
	}, this);
	
	// Show and hide feedback form.
	Event.attach(form.show, "click", function() {
		effects[Class.get(form.container, "selected") ? "close" : "open"].go();
		form.inputs[0].focus();
	}, this, [ Event.actions.PREVENT_DEFAULT, Event.actions.BLUR ]);
	
	// Hide form on cancel click.
	Event.attach(form.cancel, "click", function() { effects.close.go(); }, this, [ Event.actions.PREVENT_DEFAULT ]);
	
	// Validation
	function verifyForm() {
		var valid = true;
		for (var i = 0, input; input = form.inputs[i]; i++) {
			valid = (valid && verifyInput(input));
		}
		return valid;
	};
	
	function verifyInput(input) {
		var valid = (input.value.length > 0);
		notify(input, valid);
		return valid;
	};
	
	function notify(input, valid) {
		var parent = input.parentNode;
		Class[valid || valid == undefined ? "remove" : "add"](parent, "error");
		Class[valid ? "add" : "remove"](parent, "success");
	};
});