var active_id = 0;
var active_obj = null;

var active_div_mess = null;
var active_form = '';

function openchat(id) {
	if(!id) return false;
	if( active_div_mess !== null && active_div_mess == 'chat-messages-' + id) return false;
	active_div_mess = 'chat-messages-' + id;
	active_form		= 'chat-mess-' + id;
	var modal_window  = '<div id="modal-chat-window-'+ id +'" style="display:none" title="Чат">';
		modal_window += '<div id="chat-messages-'+id+'" style="width:100%;height:250px; overflow:auto; background-color:#fff;"></div>';
		modal_window += '<fieldset><legend>Введите сообщение</legend><textarea id="chat-mess-' + id + '" style="width:100%;"/></textarea></td></fieldset>';
		modal_window += '</div>';
		
	$("body").append( modal_window );
	
	$('#modal-chat-window-' + id).dialog({
			autoOpen: true,
			show: 'fade',
			hide: 'fade',			
			width: 600,	
			height: 440,
			buttons: {
				"Отправить" : function() {					
					chat_sendmessage(id, true);
				},
				"Обновить" : function() {					
					chat_messages(id, true);
				},				
				"Закрыть окно" : function() {
					$(this).dialog("close");
					active_div_mess = null;
				},
				"Завершить чат" : function() {
					active_id  = id;
					active_obj = this;					
					dwc_confirm('Вы уверены, что хотите завершить данный чат?', 'Внимание', chat_finish);
					active_div_mess = null;
				},
																
			}
	});
	setInterval(function() {
		if(active_div_mess !== null ) {
			chat_messages(id, false);		
		}
	}, 3000);
		
	
	return chat_messages(id, false, true);
}

function chat_messages(id, loading, create) {	
	if(create) action = 'create';
	else action = 'show';
	$("#" + active_div_mess).animate({scrollTop: $("#" + active_div_mess).position().top + $("#" + active_div_mess).height()}, 700);
	if(loading) ajax_loading(active_div_mess, 1);
	$.post(home_url + 'system/chat/chat.php', {exp_id:id, act:action}, function( response )
	{
			$("#" + active_div_mess).html(response);
	});
}

function chat_sendmessage(id) {
	
	var mess = $("#" + active_form).val();
	$("#" + active_form).attr('disabled', true);
	$("#" + active_div_mess).animate({scrollTop: $("#" + active_div_mess).position().top + $("#" + active_div_mess).height()}, 700);
	$.post(home_url + 'system/chat/chat.php', {exp_id:id, act:'add', message: mess}, function( response )
	{
			$("#" + active_div_mess).html(response);
			$("#" + active_form).val('');
			$("#" + active_form).attr('disabled', false);
	});
}

function chat_finish() {
	
	if( active_obj !== null) $(active_obj).dialog("close");
	$("#activch" + active_id).hide('fast');
	$.post(home_url + 'system/chat/chat.php', {act:'finish', exp_id:active_id}, function( response )
	{
			$("#" + active_div_mess).html(response);
	});
}


