$(document).ready(function()
	{
	postRecountTextLenght();
	$('#Message_text').keyup(postRecountTextLenght);
	});

/** **/
function postMessageListener()
	{
	return false;
	}

function postRecountTextLenght()
	{
	var value = $('#Message_text').val() || $('#Mail_text').val() || '';
	var lengthToGo = (210 - value.length);
	$('.count span').html(lengthToGo.toString());
	}

function prepost()
	{
	var id_group = $('#Message_id_group').val();

	if(id_group==0) id_group=id_group_global;

	// Если мы постим в группу, проверяем, в ней ли мы
	if (id_group !== 0)
		{
		$.ajax(
			{
			type: "POST" ,
			url: '/ajax/isingroup',
			data: 'id_group='+id_group
				+ '&ajax=isingroup',

			beforeSend:function()
				{
	       		$('#form_sendpost').addClass('disabled');
	    		},
			error: function(html)
				{
				alert('ERROR: '.html);
				},

			success: function(html)
				{
				if (html == 'ingroup')
					{
					post();
					}
				else if (html == 'notingroup')
					{
					var header = 'Ошибка';
					var body = 'Вы отвечаете на сообщение в группе, в которой не состоите. '
					  + 'Вы не можете ответить на это сообщение, чтобы ответь вы должны состоять в группе ';
					  + 'Добавиться в группу?';
					var oConfirm = new messageBox('confirm',header,body,
						{
						close:
							{
							title: 'Отменить',
							onclick: function()
								{
								oConfirm.actionDestroy();
								setTimeout("$('#form_sendpost').removeClass('disabled')",300);
								}
							},
						setmember:
							{
							title: 'Добавиться в группу',
							onclick: function()
								{
								oConfirm.actionDestroy();
								$.ajax(
									{
									type: "GET" ,
									url: '/ajax/setmember',
									data: 'id_group='+id_group
									  + '&ajax=setmember',
									error: function(html)
										{
										alert('ERROR: '.html);
										},
									success: function(html)
										{
										post();
										}
									});
								}
							}
						});
					oConfirm.actionCreate();
					}
				}
			});
		}
	else
		{
		post();
		}
	}



/*
* Постинг сообщения аяксом
*/
function post()
	{
	var text = $('textarea').val() || '';
	if (text != '' && text.length <= 210)
		{
		var reply_to=	$('#Message_reply_to').val();
		var id_group=	$('#Message_id_group').val();
		var id_recepient=	$('#Message_id_recepient').val();
		var id_trend=	$('#Message_id_trend').val();

		if(reply_to==0)reply_to=id_message;
		if(id_group==0)id_group=id_group_global;

		text = encodeURI(text);
		// переворачиваем ручками плюсик
		var re = /\+/g;
		text = text.replace(re, "%2B");
		text = base64Encode(text);
		$.ajax(
			{
			type: "POST" ,
			url: '/' + controller + '/' + action,
			data:  'text='+text+'&reply_to='+reply_to+
					'&id_group='+id_group+
					'&id_message='+id_message+
					'&id_recepient='+id_recepient+
					'&id_trend='+id_trend+
					'&ajax=message',
			beforeSend:function()
				{
				accessToNotification = false;
		       	$('#form_sendpost').addClass('disabled');
		    	},
		    complete:function()
		    	{
				setTimeout("$('#form_sendpost').removeClass('disabled')",300);
				},
			error: function(html)
				{
				alert('ERROR: '.html);
				},

			success: function(html)
				{
				if (html == 'blocked')
					{
					alertMessage('Внимание', 'Ваш аккаунт заблокирован, вы не можете оставлять сообщения');
					}
				else
					{
					$(html).replaceAll('#listMessages');
					}
				$('#listMessages').html(html);
				$("#Message_text").val(autor_message);
				$("#Message_id_recepient").val('0');
				$("#Message_reply_to").val('0');
				if (controller !== 'groups')
					{
					$('#Message_id_group').val('0');
					}
				rpmy_msgCountIncrease();
				initHoverable();
				postRecountTextLenght();

				// Разрешаем обновление количества новых сообщение
				// Ставим счетчик на ноль
				// Выводим обновленный счетчик новых сообщений
				accessToNotification = true;
				countNewMessage = 0;
				showNewMessageNotification()
				}
			});
		}
	else
		{
		if(text.length > 210)
			{
			alertMessage('Отправка сообщения', 'Сообщение слишком длинное');
			}
		else
			{
			alertMessage('Отправка сообщения', 'Нельзя отправить пустое сообщение');
			}
		}
	}

//$().ready(function()
//	{


function addImage(){
	new AjaxUpload('#upload_image',
	  {
	  // Location of the server-side upload script
	  // NOTE: You are not allowed to upload files to another domain
	  action: '/ajax/uploadimage',
	  // File upload name
	  name: 'image',
	  // Additional data to send
	  data:
	  	{
	    ajax: 'msgaddimage'
	  	},
	  // Submit file after selection
	  autoSubmit: true,
	  // The type of data that you're expecting back from the server.
	  // HTML (text) and XML are detected automatically.
	  // Useful when you are using JSON data as a response, set to "json" in that case.
	  // Also set server response type to text/html, otherwise it will not work in IE6
	  responseType: false,
	  // Fired after the file is selected
	  // Useful when autoSubmit is disabled
	  // You can return false to cancel upload
	  // @param file basename of uploaded file
	  // @param extension of that file
	  onChange: function(file, extension){},
	  // Fired before the file is uploaded
	  // You can return false to cancel upload
	  // @param file basename of uploaded file
	  // @param extension of that file
	  onSubmit:function(file , ext)
	  	{
		if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext)))
			{
			// extension is not allowed
			alert('Данный тип файла не поддерживается: '+ext);
			// cancel upload
			return false;
			}
		else
			{
			$('#form_sendpost').addClass('disabled');
			}
        },
	  // Fired when file upload is completed
	  // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
	  // @param file basename of uploaded file
	  // @param response server response
	  onComplete: function(file, response)
	  	{
	  	$('#form_sendpost').removeClass('disabled');
	  	$('#Message_text').val($('#Message_text').val()+' '+response+' ');
		formFocus('#Message_text');
	  	postRecountTextLenght();
	  	}
	  });
//	});
}
/* Добавляем смайлик в сообщение */
function smileAdd(smile)
	{
	$("#Message_text").val($("#Message_text").val() + ' :' + smile + ': ');
	formFocus('#Message_text');
	postRecountTextLenght();
	$('#smilebox').hide();
	}

/* Туглим блок с смайликами */
function smileShow()
	{
	$('#smilebox').toggle();
	}

	/** Кнопка упоминания пользователя **/
function msgAddUser()
	{
	var body = 'Введите имя пользователя, которого хотите упомянуть:<br />'
	+ '<input type="text" id="msgAddUser_input" class="text username">'
	+ '<input type="hidden" id="msgAddUser_username">'
	+ '';
	var oMsgAddUser = new messageBox('msgAddUser','Добавить пользователя',body,
		{
		close:
			{
			title: 'Отмена',
			onclick: function()
				{
				oMsgAddUser.actionDestroy();
				}
			},
		add:
			{
			title: 'Добавить пользователя',
			onclick: function()
				{
				var username = $('#msgAddUser_input').val();
				var text = $('#Message_text').val();
				text =  text + ' @' + username + ' ';
				$('#Message_text').val(text);
				formFocus('#Message_text');
				oMsgAddUser.actionDestroy();
				}
			}
		});
		oMsgAddUser.actionCreate();
		$("#msgAddUser_input").autocomplete("/ajax/AutocompleteUser",
			{
			delay:10,
			minChars:2,
			matchSubset:1,
			autoFill:true,
			matchContains:1,
			cacheLength:10,
			selectFirst:true,
			formatItem:liFormat_friendsList,
			maxItemsToShow:10,
			onItemSelect:msgAddUser_selectItem
		});
	}

/** Кнопка упоминания группы **/
function msgAddGroup()
	{
	var body = 'Введите название группы, которую хотите упомянуть:<br />'
	+ '<input type="text" id="msgAddGroup_input" class="text username">'
	+ '<input type="hidden" id="msgAddGroup_id">'
	+ '<input type="hidden" id="msgAddGroup_canpost">'
	+ '';
	var oMsgAddGroup = new messageBox('msgAddGroup','Добавить группу',body,
		{
		close:
			{
			title: 'Отмена',
			onclick: function()
				{
				oMsgAddGroup.actionDestroy();
				}
			},
		add:
			{
			title: 'Добавить группу',
			onclick: function()
				{
				var name = $("#msgAddGroup_input").val();
				var text = $('#Message_text').val();
				var canpost = $('#msgAddGroup_canpost').val();
				if (text == '' && canpost !== '')
					{
					var id_group = $('#msgAddGroup_id').val();
					$('#Message_id_group').val(id_group);
					}
				text =  text + '!' + name + ' ';
				$('#Message_text').val(text);
				oMsgAddGroup.actionDestroy();
				formFocus('#Message_text');
				}
			}
		});
	oMsgAddGroup.actionCreate();
	$("#msgAddGroup_input").autocomplete("/ajax/AutocompleteGroup",
		{
		delay:10,
		minChars:2,
		matchSubset:1,
		autoFill:true,
		matchContains:1,
		cacheLength:10,
		selectFirst:true,
		formatItem:liFormat_friendsList,
		maxItemsToShow:10,
		onItemSelect:msgAddGroup_selectItem
		});
	}
	
// Кнопка для добавления скрытого текста
function msgAddHide()
{
	var body = 'Введите скрытый текст:<br />'
	+ '<input type="text" id="msgAddHide_input" class="text username">'
	+ '';
	var oMsgAddHide = new messageBox('msgAddHide','Добавить скрытый текст',body,
		{
		close:
			{
			title: 'Отмена',
			onclick: function()
				{
				oMsgAddHide.actionDestroy();
				}
			},
		add:
			{
			title: 'Добавить скрытый текст',
			onclick: function()
				{
				var name = $("#msgAddHide_input").val();
				var text = $('#Message_text').val();
				text =  text + ' [h]' + name.substring(0, (201-text.length)) + '[/h] ';
				$('#Message_text').val(text);
				oMsgAddHide.actionDestroy();
				formFocus('#Message_text');
				}
			}
		});
	oMsgAddHide.actionCreate();
}


// Функции для автозаполнения - Упоминание пользователя
function msgAddUser_selectItem(li)
	{
	$('#msgAddUser_username').val(li.extra[0]);
	$('#msgAddGroup_canpost').val(li.extra[1]);
	}

// Функции для автозаполнения - Упоминание группы
function msgAddGroup_selectItem(li)
	{
	$('#msgAddGroup_id').val(li.extra[0]);
	$('#msgAddGroup_canpost').val(li.extra[1]);
	}