/*
 * JavaScript Functions for Comments
 */

var cmm_id = null;
var cmm_action = null;

function showCommentAction(action,id) {
	if (action == cmm_action && id == cmm_id) return;
	setVisible('cmm_delete',false);
	setVisible('cmm_editor',false);
	setVisible('cmm_toolbar',false);
	showCommentMessage('');
	if (cmm_id) setVisible('cmm_content'+cmm_id,true);
	cmm_id = id;
	cmm_action = action;
	if (!action) return;
	setVisible('cmm_content'+cmm_id,false);
	var e = getElement('cmm_'+(action == 'delete' ? 'delete' : 'editor'));
	insertAfter(cmm_id ? 'cmm'+cmm_id : 'cmm_add',e);
	insertAfter(e,'cmm_toolbar');
	setVisible(e,true);
	setVisible('cmm_toolbar',true);
	var e = getElement('cmm_editor');
	e.value = (action == 'update' ? decodeEntities(getElement('cmm_content'+cmm_id).innerHTML.replace(/<br>/ig,"\n")) : '');
	e.focus();
}

function showCommentMessage(msg,icon) {
	getElement('cmm_message').innerHTML = (icon ? "<img alt='' class='icon' src='"+getPath('images/'+icon)+"' />&nbsp;" : '')+(icon == 'icon_error.gif' ? '<strong>'+getConstant('_ERROR')+': </strong>' : '')+msg;
}

function actionComment(record_id,record_type) {
	var v = getValue('cmm_editor');
	if (cmm_action != 'delete' && isEmpty(v)) return showAlert(getConstant('_ERR_NO_COMMENT'));
	var xmlhttp = new XMLHttp;
	xmlhttp.id = cmm_id;
	xmlhttp.action = cmm_action;
	xmlhttp.onReceive = function(xmlhttp) {
		var xmlroot = xmlhttp.parse();
		if (xmlroot) {
			if (xmlroot.error) {
				showCommentMessage(xmlroot.error.text,'icon_error.gif');
			} else {
				if (xmlhttp.action == 'delete') {
					getElement('cmm_comments').removeChild(getElement('cmm'+xmlhttp.id));
				} else {
					var e = getElement('cmm'+xmlroot.comment.id);
					if (!e) {
						e = document.createElement('div');
						e.id = 'cmm'+xmlroot.comment.id;
						e.className = 'note';
						getElement('cmm_comments').appendChild(e);
					}
					var t = xmlhttp.getResponseText();
					t = t.substring(t.indexOf('<html>')+6,t.indexOf('</html>'));
					t = t.substring(t.indexOf('>')+1,t.lastIndexOf('</div>'));
					e.innerHTML = t;
				}
				var found = false;
				var l = getElement('cmm_comments').childNodes;
				for (var i = 0, n = l.length; i < n; i++) if (/^cmm[0-9a-f]{13}$/.test(l[i].id)) found = true;
				setVisible('cmm_comments',found);
				setVisible('cmm_no_comments',!found);
				showCommentAction(false);
			}
		} else showCommentMessage(getConstant('_INVALID_XML_DATA'),'icon_error.gif');
	};
	xmlhttp.onError = function(xmlhttp) {
		showCommentMessage(getConstant('_ERR_AJAX_ERROR'),'icon_error.gif');
	};
	showCommentMessage(getConstant('_MSG_PLEASE_WAIT'),'loading.gif');
	var url = {
		'add':"add_comment?record_id="+record_id+"&record_type="+record_type+"&comment="+encodeURIComponent(v),
		'update':"update_comment?id="+cmm_id+"&comment="+encodeURIComponent(v),
		'delete':"delete_comment?id="+cmm_id
	};
	xmlhttp.receive(getPath(url[cmm_action]));
}

