var messageTargetDiv = '#mainpopupdiv';
var isPrivate = false;

function cancelMessaging() {
	cancelAny();
	clearMessaging();
}

function clearMessaging() {
	if (window.tinyMCE !== undefined) {
		tinymce.execCommand('mceRemoveControl', true, $('textarea.MCE',messageTargetDiv).attr('id'));
	}
	$('#messForm').text.value = '';
	$('#messForm .fileinput_message_attached_files[type="file"]').val('');
	var fileInputs = $('#messForm .fileinput_message_attached_files[type="file"]');
	var buttonInputs = $('#messForm .fileinput_message_attached_files[type="button"]');
	for (i = 0; i < fileInputs.length - 1; i++) {
		$(fileInputs[i]).remove();
		$(buttonInputs[i]).remove();
	}
	$('#messForm .errors').remove();
}

function showMessageForm(e, id, entityId) {
	messageTargetDiv = '#mainpopupdiv';
	$(messageTargetDiv).html('<img src="/images/design/ajax-loader.gif"/>');
	showAnyForm(e);
	$.ajax({
		url: '/ajax/sendmessage/',
		async: false,
        type: "POST",
		data: {
			'to_id' : id,
			'entityId' : entityId
		},
		success: function(response) {
			cancelAny();
			$(messageTargetDiv).html(decodeURIComponent(response));
			onehtml = $('.fileinputs', messageTargetDiv).html();
			$('#theme',messageTargetDiv).autocomplete(getTopics());
			setMessageHandler();
			showAnyForm(e);
		}
	});
}

function setMessageHandler() {
	var options = {
		beforeSubmit: function(formData, jqForm, options) {
			return true;
		},
		success: afterMessageChecked
	};
	$('#messForm').ajaxForm(options);
}

function afterMessageChecked(response, statusText, xhr, $form) {
	data = parseInt(response);

	if (!isNaN(data)) {		
		if (data < 0)
			alert("Произошла ошибка авторизации! Возможно, сессия завершилась.");
		else if (data == 1) {
			if (isPrivate) {
				$('#mainpopupdiv').html('<div style="width: 250px;"><p>Сообщение отправлено</p><button style="float:right">Ок</button></div>');
				showAnyForm();
				$('#mainpopupdiv').find('button').bind('click', function(){
					var href = location.href;
					href = href.split('/');
					href.pop();
					href.pop();
					href = href.join('/');
					window.location = href+'/';
				});
			}
			else {
				cancelAny('#mainpopupdiv');
				$('#mainpopupdiv').html('<p>Сообщение отправлено</p><button style="float:right">Ок</button>');
				showAnyForm();
				$('#mainpopupdiv').find('button').bind('click', function(){
					cancelAny();
					clearMessaging();
				});
			}
		}
	} else {
		if (window.tinyMCE !== undefined) {
			tinymce.execCommand('mceRemoveControl', true, $('textarea.MCE',messageTargetDiv).attr('id'));
		}
		
		$(messageTargetDiv).html(decodeURIComponent(response));
		$('#theme',messageTargetDiv).autocomplete(getTopics());
		addTinyMCE(messageTargetDiv);
		setMessageHandler();
	}
}

