document.observe('dom:loaded', function() {
	var validate = function() {
		var valid = true;
		$('contact_form_whitepaper').getInputs().each(function(e) {
			var match;
			if (e.name === "email") {
				match = /^([\w]+)(.[\w]+)*@([\w\-]+\.){1,5}([A-Za-z]){2,4}$/.test($F(e).strip());
			} else if (e.name === "phone") {
				match = "ok";
			} else if (e.name === "newsletter_subscribe") {
				match = "ok";
			} else if (e.name === "newsletter_subscribe_check") {
				if(e.checked){
					$('newsletter_subscribe').value = "True";				
				} else {
					$('newsletter_subscribe').value = "False";				
				}
				match = "ok";
			} else {
				match = $F(e).strip();
			}
			if (!match) {
				e.addClassName('invalid');
				valid = false;
			} else {
				e.removeClassName('invalid');
			}
		});
		return valid;
	};

	$('contact_form_whitepaper').getInputs().each(function(e) {
		e.observe('blur', function() {validate();});
	});

	$('contact_form_whitepaper').observe('submit', function(e) {
		e.stop();
		if (!validate()) {
			$('register-error').show();
			return;
		}
		var s = $('contact_form_whitepaper').serialize();
		$(document.body).insert(new Element('script', {'src': 'http://extcomm.whatever-company.com/form/api/whitepaper?url='+encodeURIComponent(window.location.href)+'&callback=kp.contact&'+s, 'type': 'text/javascript'}));
		//window.kp.contact({done: true});
	});
});
window.kp = {
	contact: function(response) {
		if (response.done) {
			var page = "/wp-thankyou.html";
			/* This crashes if KP_LANG is not defined !!!
			 * should detect if from the page path but I have
			 * no idea how to do that so ...
			 */
			/*
			if (KP_LANG) {
				page += "?lang=" + KP_LANG;
			}
			*/
			$(document.body).insert(new Element('iframe', {'src': page, 'style': 'display: none;'}));
			$('register-form').hide();
			$('register-success').show();
		}
	}
};

