// JavaScript Document

//check for max number of characters in form fields
function checkChars(maxLength, name){
	if( document.getElementById(name).value.length >= maxLength){
		alert("You have reached the maximun number of characters allowed.");
		document.getElementById(name).value = document.getElementById(name).value.substr(0,maxLength);	
	}
}

//hid comments and show submit comments form
function hideComments(){
	document.getElementById('commentsBox').style.display = 'none';
	document.getElementById('postComment').style.display = 'inline';
}


//Get HTTP Object for AJAX Processing
function getHTTPObject(){
	if (window.ActiveXObject) 
		return new ActiveXObject("Microsoft.XMLHTTP");
	else if (window.XMLHttpRequest) 
		return new XMLHttpRequest();
	else {
		alert("Your browser does not support AJAX.");
		return null;
	}
}

//Submit comment to db
function commentSubmit(){
	//get values from form
	var blogID = document.getElementById('blogID').value;
	var name = document.getElementById('commentName').value;
	var comment = document.getElementById('commentText').value;
	
	//Validate form data
	if( name == '' || comment == '' ){
		alert('All field are required!');
	} else {
		httpObject = getHTTPObject();
		
		//Send comment data to submit_comment.php return all comments
		if (httpObject != null) {
			httpObject.open("GET", "/components/scripts/submit_comment.php?blog_id="+blogID+"&name="+name+"&comment="+comment, true);
			httpObject.send(null);
			httpObject.onreadystatechange = setOutput;
		} else {
			document.write('Failed to get httpObject');
		}	
	}
}

// Change the value of the outputText field
function setOutput(){
	if(httpObject.readyState == 4){
		document.getElementById('postComment').style.display = 'none';
		document.getElementById('commentsBox').style.display = 'inline';
		document.getElementById('blogComments').innerHTML = httpObject.responseText;
	}
}