
String.prototype.isEmail = function () { 
	var rx = new RegExp("\\w+([-+.\']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); 
	var matches = rx.exec(this); 
	return (matches != null && this == matches[0]); 
}

var WPMLComments = {
	version : '1.0.0.0 beta'
}

WPMLComments.Manager = Class.create({

	onsuccess: function(transport) {
		this.form_control.value = transport.responseText;
	},

	onreply: function(event) {
		var el = event.element();
		Event.stop(event);
		el.wpml_container.insert({ after : this.form_wrap.setStyle({'marginLeft' : parseInt(el.wpml_container.getStyle('marginLeft'))+ (el.wpml_cpid == 0 ? 0 : 20) +'px'}).show() });
		this.form_pid.value = el.wpml_pid;
		this.form_cpid.value = el.wpml_cpid;
		(this.form_author || this.form_text).focus();
	},
	
	onsubmit: function(event) {
		var error = false;
		if (this.form_author) {
			if (this.form_author.value.length == 0 ) 
			{
				this.form_author.setStyle({'borderColor' : '#f00'});
				this.form_author.focus();
				Event.stop(event);
				error = true;
			}
			else { this.form_author.setStyle({'borderColor' : '#383838'}); };
		}
		if (this.form_email) {
			if (!this.form_email.value.isEmail()) {
				this.form_email.setStyle({'borderColor' : '#f00'});
				if(!error) this.form_email.focus();
				Event.stop(event);
				error = true;
			}
			else{ this.form_email.setStyle({'borderColor' : '#383838'}); }
		}
		if (this.form_text.value.length == 0) {
				this.form_text.setStyle({'borderColor' : '#f00'});
				if(!error) this.form_text.focus();
				Event.stop(event);
		}
		else{ this.form_text.setStyle({'borderColor' : '#383838'}); }
		
		if (!error) {
			new Ajax.Request('?wpmlsecurity' , {
				parameters: {
					pid:		this.form_pid,
					cpid:		this.form_cpid
				},
				evalScripts : false,
				asynchronous : false,
				onSuccess: this.onsuccess.bind(this)
			});

		}
	},

	initialize: function() {
		if (!$('wpml-comment-wrap')) return;
		this.form_author = $('author');
		this.form_email = $('email');
		this.form_text = $('comment');
		this.form_pid = $('comment_post_ID');
		this.form_cpid = $('comment_parent');
		this.form_control = $('comment_control');
		this.form_form = $('commentform');
		this.form_wrap = $('wpml-comment-wrap').show();

		this.reply_click = this.onreply.bindAsEventListener(this);
		this.submit_click = this.onsubmit.bindAsEventListener(this);

		$$('a.wpml-reply').each(function(a) { 
			a.observe('click', this.reply_click); 
				var v = a.href.split('#')[1].split('-');
				a.wpml_pid = parseInt(v[1]);
				a.wpml_cpid = parseInt(v[2]);
				a.wpml_container = a.wpml_cpid == 0 ? a.up() : a.up().up();
			},
			this 
		);			
		this.form_form.observe('submit', this.submit_click);
	}
	
});

document.observe("dom:loaded", function() {
		var CommentManager = new WPMLComments.Manager();
});