$(document).ready(function(){
	$("#comment_add").bind("click", add_Comment);
	$("#captcha_reset").bind("click", reset_Captcha);
	$("#sec_captcha").bind("click", reset_Captcha);
});

function add_Comment(event)
{
	event.preventDefault();
	var errors = new Array();
	var checks = new Array('name','title','country','comment','captcha');
	var i;
	for(i=0;i<checks.length;i++)
	{
		jQuery.trim($("#"+checks[i]).val())==''?errors.push(checks[i]):true;
	}
	
	if(errors.length >0)
	{
		var alert_result='';
		for(i=0;i<errors.length;i++)
		{
			alert_result+='- You must fill the field ['+errors[i]+'] to continue\n';
		}
		alert(alert_result);
		return false;
	}

	var name 	= $("#name").val();
	var title   = $("#title").val();
	var country = $("#country").val();
	var comment = $("#comment").val();
	var article = $("#article_id").val();
	var captcha = $("#captcha").val();
	
	if(isNaN(article))
	{
		return false;
	}

	var loading = '<h3>Loading ... <img src="images/ajax_load.gif"></h3>';
	$("#comment_result").html(loading).fadeIn("slow"); 
	$.post("ajax.php",{action:'comment',name:name,title:title,country:country,comment:comment,article:article,captcha:captcha},function(data){
		if(jQuery.trim(data)=='true')
		{
			$("#comment_result").html('<h3><img src="images/compare_y.png"> Your comment has been successfully posted .. It will be published after review</h3>');
			reset_Captcha();
			$("#comment_add").attr("disabled", true);
			$("#name").attr("disabled", true);
			$("#title").attr("disabled", true);
			$("#country").attr("disabled", true);
			$("#comment").attr("disabled", true);
			$("#captcha").attr("disabled", true);
		}
		
		else {
			$("#comment_result").html('<h3>'+data+'</h3>');
			reset_Captcha();
		}
    });
	
}

function reset_Captcha()
{
	$("#sec_captcha").attr("src", 'security_image.gif?'+Math.random());
	$("#captcha").attr("value", '');
}

// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}
