/**
 * comment.js
 *
 * Methods for handling posting & listing comments
 *
 * @author     Daniel Z
 * @copyright  2007 Comet Information Systems Ltd, All Rights Reserved.
 * @requires   common.js
 * @requires   prototype.js
 */


/*
 * Post a new comment
 * @param {String} suffix If sent, the suffix will be added to all conventional
 * input text fields while gathering data
 */

function init() {
	cfv.config({fail:cfv.failHandler,failMessageHandler : showError})
	setOpinionValidation();
}

function setOpinionValidation(){
	hideErrors();
	cfv.resetObservers();
	//opinons
	cfv.add('commentName', ['blur'], ['not_empty'], {messages:"Please provide your name"});
	cfv.add('commentVerify', ['blur'], ['not_empty'], {messages:"Please type the text here"});
//	cfv.add('commentEmail', ['blur'], ['is_email'], {messages:"Please enter a valid email"});
//	cfv.add('commentUrl', ['blur'], ['is_match',URL_REGEXP], {messages:"Please enter your blog's URL"});
}

function setEmailValidation(){
	hideErrors();
	cfv.resetObservers();	
	// email
	cfv.add('email1', ['blur'], ['is_email'], {messages:"Please enter a valid email"});
	cfv.add('email2', ['blur'], ['is_email'], {messages:"Please enter a valid email" , optional:true});
	cfv.add('email3', ['blur'], ['is_email'], {messages:"Please enter a valid email" , optional:true});
	cfv.add('mailSubject', ['blur'], ['not_empty'], {messages:"Please enter a subject"});
	cfv.add('mailMessage', ['blur'], ['not_empty'], {messages:"Please enter a message"});
	cfv.add('emailVerify', ['blur'], ['not_empty'], {messages:"Please type the text here"});
}

function postComment(suffix) {
	if (validate()) {
		//
		var addon;
		if (!isEmptyString(suffix)) addon = "_" + suffix;
		else addon = "";

		//Gather params
		var commentEntityId = gebi("commentEntityId" + addon).value;
		var commentEntityType = gebi("commentEntityType" + addon).value;
		var commentName = gebi("commentName" + addon).value;
		var commentEmail = gebi("commentEmail" + addon).value;
		var commentUrl = gebi("commentUrl" + addon).value;
		var commentBody = gebi("commentBody" + addon).value;
		var commentVerify = gebi("commentVerify" + addon).value;

		//Validate
		//todo daniel

		//Hide any previous errors
		gebi('opinionErrors' + (isEmptyString(suffix) ? "" : "_" + suffix)).style.display = 'none';

		//Send AJAX request
		var params = [
				"entityId=",commentEntityId,
				"&entityType=",commentEntityType,
				"&parentCommentOid=",gOpinionId,
				"&name=",escape(commentName),
				"&email=",escape(commentEmail),
				"&url=",escape(commentUrl),
				"&body=",escape(commentBody),
				"&captcha=",commentVerify,
				"&suffix=",suffix
				];

		new Ajax.Request('/comment/index/post/', {
			method:'post',
			parameters: params.join(''),
			onException:generalAJAXFailure,
			onFailure:generalAJAXFailure,
			onSuccess: function(response) {
				//Eval JSON
				var json = response.responseText.evalJSON();

				//
				var msg;
				var msgElem = gebi('opinionErrors' + (isEmptyString(json.suffix) ? "" : "_" + json.suffix))

				//Display appropriate message according to server's response
                reloadImage('captchaImg');
                switch (json.statusCode) {
					case ERRORS.SUCCESS:
						msg = 'Your comment was successfully added';
					//reset all fields
						resetCommentFields();
					//Hide the comment box
					//gebi('commentFrm' + (isEmptyString(json.suffix) ? "" : "_" + json.suffix)).style.display = 'none';

					//Refresh comments list
						listComments(json.entityId, json.entityType, 'commentsContainer');
                        gOpinionId = -1;
						break;
					case ERRORS.ERROR_DATA_VALIDATION:
						msg = 'There was a problem with your data.';
						break;
					case ERRORS.ERROR_CAPTCHA_WRONG:
						showError("commentVerify", "Your text wasn\'t matching the image!")
						msg = '';
						break;
					default:
						alert('No suitable statusCode');
				}

				msgElem.style.display = 'block';
				msgElem.innerHTML = msg;
			}
		});
	}
}
/////////reset comment fields////////////
function resetCommentFields() {
	gebi("commentName").value = "";
	gebi("commentEmail").value = "";
	gebi("commentUrl").value = "";
	gebi("commentBody").value = "";
	gebi("commentVerify").value = "";

}

/////////////////////////////////////////
/////////comment on opinion;/////////////
var gOpinionId = -1;
function setOpinionId(opinionId) {
	gOpinionId = opinionId;
    try{gebi("opinionErrors").innerHTML = "";}catch(e){}
}
/////////////////////////////////////////
/*
 * Send mails to up to 3 friends with a link to a blog
 * input text fields while gathering data
 */
function postEmails() {
	if (validate()) {
		//Gather params
		var email1 = gebi("email1").value;
		var email2 = gebi("email2").value;
		var email3 = gebi("email3").value;
		var mailSubject = gebi("mailSubject").value;
		var mailMessage = gebi("mailMessage").value;
		var ourText = gebi("ourText").value;
		var emailVerify = gebi("emailVerify").value;

		//Hide any previous errors
		gebi('emailItErrors').style.display = 'none';

		//Send AJAX request
		var params = [
				"email1=",email1,
				"&email2=",email2,
				"&email3=",email3,
				"&mailSubject=",mailSubject,
				"&mailMessage=",mailMessage,
				"&ourText=",ourText,
				"&emailVerify=",emailVerify
				];

		new Ajax.Request('/blog/index/mail/', {
			method:'post',
			parameters: params.join(''),
			onException:generalAJAXFailure,
			onFailure:generalAJAXFailure,
			onSuccess: function(response) {
				//Eval JSON
				var json = response.responseText.evalJSON();

				//
				var msg;
				var msgElem = gebi('emailItErrors')

				//Display appropriate message according to server's response
				switch (json.statusCode) {
					case ERRORS.SUCCESS:
						msg = 'Your mail was successfully sent';
                        gebi('emailFrm').reset();
                        reloadImage('mailCaptchaImg');
                        hideErrors();
                        break;
					case ERRORS.ERROR_DATA_VALIDATION:
						msg = 'There was a problem with your data.';
						break;
					case ERRORS.ERROR_CAPTCHA_WRONG:
						showError("emailVerify","Your text wasn't matching the image!");
						msg = "";
						break;
//					default:
//						alert('No suitable statusCode');
				}

				msgElem.style.display = 'block';
				msgElem.innerHTML = msg;
            }
		});
	}


}


/*
 * Retrieve list of comments for a specific entity
 * @param {long} entityId Entity's ID
 * @param {int} entityType Entity's type as defined in EntityTypes.php
 * @param {String} htmlContainerId The ID of the html element to display the comments in
 */
function listComments(entityId, entityType, htmlContainerId) {

	//Send AJAX request
	var params = [
			"entityId=",entityId,
			"&entityType=",entityType,
			"&containerId=",htmlContainerId
			];

	var request = new Ajax.Request('/comment/index/list/', {
		method:'get',
		parameters: params.join(''),
		onException:generalAJAXFailure,
		onFailure:generalAJAXFailure,
		onSuccess: function(response) {
			//Extract container ID
			var containerId = request.getHeader('X-CONTAINER-ID');

			//Set innerHTML
			gebi(containerId).innerHTML = response.responseText;
		}
	});

}