var wpcf7_fadeout_time=500;

$(document).addEvent('domready',function() {
	$$('form.wpcf7-form')[0].addEvent('submit', function(e) {
    new Event(e).stop();
		clearResponseOutput();
		$$('img.ajax-loader', this).setStyle('visibility', 'visible' );
		new Element('input', {'type': 'hidden', 'name': '_wpcf7_is_ajax_call', 'value': 1}).injectInside(this);
		
		this.send({onComplete: processJson});
	});

  // Exclusive checkbox (why not just radios??)
  $$('input.exclusive').addEvent('click', function() {
		myname = $(this).getProperty('name');
    $$('input.exclusive').each(function(other) {
			if( other.getProperty('name')==myname ) other.checked=false;
		});
		$(this).checked=true;
  });
});

function notValidTip(input, message) {
	new Element('span', {
	   'id': input.getProperty('id')+"-not-valid",
	   'class': "wpcf7-not-valid-tip",
		 'events': {
		   'mouseover': function() {
			       new Fx.Style($(this), 'opacity', { 'duration' : wpcf7_fadeout_time }).start(0);
						}
		 }
	}).setHTML(message).injectAfter(input);
	input.addEvent('mouseover', function() {
     new Fx.Style($(this).getProperty('id')+"-not-valid", 'opacity', { 'duration' : wpcf7_fadeout_time }).start(0);
	} );
}

function processJson(text_data) {
  var data = new Json.evaluate(text_data);
	var wpcf7ResponseOutput = $$('div.wpcf7-response-output');
	wpcf7ResponseOutput.setProperty("id", "wpcf7-has-horrible-coding-practice");
	fadein = new Fx.Style( "wpcf7-has-horrible-coding-practice", 'opacity', { 'duration' : wpcf7_fadeout_time }).set(0);
	clearResponseOutput();
	if (data.invalids) {
		data.invalids.each( function(n) {
			notValidTip($(n.into), n.message);
		});
		wpcf7ResponseOutput.addClass('wpcf7-validation-errors');
	}
	if (data.captcha) {
		$each(data.captcha, function(n,i) {
			$('input-'+i).setProperty('value', '');
			$$('img.wpcf7-captcha-' + i).setProperty('src', n);
			var match = /([0-9]+)\.(png|gif|jpeg)$/.exec(n);
			$('_wpcf7_captcha_challenge_' + i).setProperty('value', match[1]);
		});
	}
	if (1 == data.spam) {
		wpcf7ResponseOutput.addClass('wpcf7-spam-blocked');
	}
	if (1 == data.mailSent) {
  	$$('form.wpcf7-form')[0].reset();
		wpcf7ResponseOutput.addClass('wpcf7-mail-sent-ok');
	} else {
		wpcf7ResponseOutput.addClass('wpcf7-mail-sent-ng');
	}
	wpcf7ResponseOutput.appendText(data.message);
	fadein.start(0, 1);
}

function clearResponseOutput() {
	$$('div.wpcf7-response-output').setStyle('visible','hidden').setHTML('').removeClass('wpcf7-mail-sent-ok').removeClass('wpcf7-mail-sent-ng').removeClass('wpcf7-validation-errors').removeClass('wpcf7-spam-blocked');
	$$('span.wpcf7-not-valid-tip').remove();
	$$('img.ajax-loader').setStyle('visibility', 'hidden');
}
