LChat = {
	
	_Path: 			'/lchat/',
	_PathScripts: 	'/lchat/js/',
	_PathCSS: 		'/lchat/css/',
	_Url: 			'/lchat/client.php',
	timeOut: 		3000,
	clientID: 		null,
	operator:		null,
	timer:			null,
	run:			0,
	
	//Инициализация слиента
	Init: function()
	{
		this._LoadScripts();
		
		if ($.cookie('LChat_Client_IsBad') == 1)
			return false;
			
		this._LoadCSS();
		
		this.ClientInit();
		$('body').attr('onUnload', 'LChat.CloseChat();');
		
		var html = '<div id="LChat_Client_container"><div id="LChat_Client">';
		
		html+= '<div id="LChat_Client_Toolbar">';
		html+= ' <a href="http://lchat.nlinepro.ru" target="_blank"><img src="'+ this._Path +'img/about.gif" height="11" width="11"></a>';
		html+= ' <a href="javascript:LChat.Minimize();"><img src="'+ this._Path +'img/minimize.gif" height="11" width="11"></a>';
		html+= ' <a href="javascript:LChat.CloseChatWindow();"><img src="'+ this._Path +'img/close.gif" height="11" width="11"></a>';
		html+= '</div>';
		
		html+= '<div id="LChat_Client_Workspace" style="display:';
		if ($.cookie('LChat_Client_Minimize') == 1)
			html+= 'none';
		else
			html+= 'block';
		html+= '">';
	
		html+= '<div id="LChat_Client_Info">';
		html+= '<img src="'+ this._Path +'img/avatars/_default.gif" height="58" width="58" id="LChat_operator_photo">';
		html+= '<div>Вас обслуживает:</div>';
		html+= '<div id="LChat_operator_position"></div>';
		html+= '<div class="LChat_title" id="LChat_operator_fio"></div>';
		html+= '</div>';
		
		html+= '<div id="LChat_Client_WMessages"></div>';
		html+= '<div id="LChat_Client_TextField">';
		html+= '<textarea id="LChat_Client_Textarea"></textarea>';
		html+= '<div>';
		html+= '<input type="button" onClick="LChat.PostMessage();" id="LChat_submit_button"/>';
		html+= ' <img src="'+ this._Path +'img/loading.gif" id="LChat_loading" width="16" height="16" style="display:none;">';
		html+= '</div></div>';
		
		html+= '</div></div>';
		$('body').prepend(html);
		
		$('#LChat_Client_container').hide();
		
		$('#LChat_Client_Textarea').bind('keypress', function(e) {
			if((e.ctrlKey) && ((e.keyCode == 0xA)||(e.keyCode == 0xD)))
			{
				LChat.PostMessage();
			}
		});
		this.GetMessages(0);
	},
	
	DelCookie: function() 
	{
		$.cookie('LChat_Client', null);
	},
	
	UnLoad:function()
	{
		var params = {
			Action:			'ClientOffLine',
			clientID: 		this.clientID
		};
		this.SendQuery(params, null);
	},
	
	//Идентификация клиента
	ClientInit: function()
	{
		var isNewClient = 1;
		
		if ($.cookie('LChat_Client') != null)
		{
			isNewClient = 0;
			this.clientID = $.cookie('LChat_Client');
		}
		
		var params = {
			Action:			'ClientInit',
			isNewClient: 	isNewClient,
			clientID: 		this.clientID,
			location:		document.location.href,
			referrer:		document.referrer,
			title:			$('title').html()
		};
		
		this.SendQuery(params, this.ClientInitResponse);
	},
	
	ClientInitResponse: function(data)
	{
		LChat.clientID = data.clientID;
		this.clientID = data.clientID;
		if (data.newClient == '1')
		{
			$.cookie('LChat_Client', data.clientID, {expires: 365, path: '/', secure: false});
		}
	},
	
	//Отправка запроса на сервер
	SendQuery: function(params, callback)
	{
		return $.ajax(
			{
				url: this._Url,
				type: 'POST',
				dataType: 'json',
				data:params,
				success: callback
			}
		);
	},
	
	//Получение сообщений
	GetMessages: function(is_new)
	{
		var params = {
			Action:			'GetMessages',
			clientID: 		LChat.clientID,
			is_new: 		is_new
		};
		this.SendQuery(params, this.ProcessMessages);
	},
	
	//Разбор полученных сообщений
	ProcessMessages: function(data)
	{
		html = '';
		
		for (var i =0; i < data.messages.length; i++)
		{
			if (typeof data.operator != 'undefined')
			{
				LChat.operator = data.operator;
				$('#LChat_operator_position').html(LChat.operator.Position);
				$('#LChat_operator_fio').html(LChat.operator.FIO);
				if (LChat.operator.Photo != '')
					$('#LChat_operator_photo').attr('src', LChat._Path + 'img/avatars/'+ LChat.operator.Photo);
			}
			
			html+= '<div class="lchat_message">';
			if (data.messages[i].Type == 1)
			{
				html+= '<div class="LChat_operator"><b>'+ LChat.operator.Position +' '+ LChat.operator.FIO +'</b>';
			}
			else
				html+= '<div class="LChat_client"><b>Вы</b>';
			html+= ':<div class="LChat_date">'+ data.messages[i].Date +'</div></div>';
			html+= data.messages[i].Text +'</div>';
		}
		
		if (html != '')
		{
			$('#LChat_Client_WMessages').append(html);
			
			$('#LChat_Client_container').show();
			
			LChat._Scroll();
		}
		this.timer = setTimeout('LChat.GetMessages(1)', 3000);
	},
	
	PostMessage: function(data)
	{
		var text = $('#LChat_Client_Textarea').val();
		if (text.length == 0)
		{
			alert('Введите текст сообщения.');
			$('#LChat_Client_Textarea').focus();
			return;
		}
		
		$('#LChat_loading').show();
		$('#LChat_submit_button').attr('disabled', true);
		$('#LChat_Client_Textarea').val('');
		
		var params = {
			Action:			'PostMessage',
			clientID: 		this.clientID,
			text: 			text,
			operator:		LChat.operator.ID
		};
		this.SendQuery(params, this.ProcessMessages);
		$('#LChat_loading').hide();
		$('#LChat_submit_button').attr('disabled', false);
	},
	
	//Отмена чата
	StopChat: function()
	{
		this.UnLoad();
		clearTimeout(this.timer);
	},
	
	//Закрыть чат
	CloseChat: function()
	{
		this.StopChat();
		$('#LChat_Client_container').fadeOut('fast');
	},
	
	CloseChatWindow: function()
	{
		if (confirm('Внимание!\r\nЕсли Вы закроете это окно, то Вы больше не сможете общаться с Оператором.\r\nВы действительно хотите прекратить общение с Оператором?'))
		{
			$.cookie('LChat_Client_IsBad', 1, {expires: 1, path: '/', secure: false});
			this.CloseChat();
			var params = {
				Action:			'CloseChatWindow',
				clientID: 		LChat.clientID
			};
			this.SendQuery(params, null);
		}
	},
	
	//Сворачивание/разворачивание
	Minimize: function()
	{
		$('#LChat_Client_Workspace').slideToggle('fast', function(){
			if ($('#LChat_Client_Workspace').css('display') == 'none')
				var minimize = 1;
			else
				var minimize = 0;
			$.cookie('LChat_Client_Minimize', minimize, {expires: 1, path: '/', secure: false});
		});
	},
	
	//Подгрузка нужных скриптов
	_LoadScripts: function()
	{
		var n = 0;
		var Script = Array();
		
		if (typeof jQuery == 'undefined')
			Script[n++] = this._PathScripts + 'jquery/jquery-1.3.2.min.js';

		Script[n++] = this._PathScripts + 'jquery/jquery.cookie.js';

		for (var i = 0; i < Script.length; i++)
			this._IncludeScript(Script[i]);
	},
	
	//Подгрузка CSS
	_LoadCSS: function()
	{
		var n = 0;
		var CSS = Array();
		
		CSS[n++] = this._PathCSS + 'client.css';
		if ($.browser.msie)
			CSS[n++] = this._PathCSS + 'client_ie.css';
		
		for (var i = 0; i < CSS.length; i++)
			this._IncludeCSS(CSS[i]);
	},
	
	//Include для Javascript
	_IncludeScript: function(filename) 
	{
		var transport = this.getXHTTPTransport();
		transport.open('GET', filename, false);
		transport.send(null);
	
		var code = transport.responseText;
		eval(code);

	},
	
	_IncludeCSS: function(filename)
	{
		var js = document.createElement('link');
		js.setAttribute('type', 'text/css');
		js.setAttribute('rel', 'stylesheet');
		js.setAttribute('media', 'all');
		js.setAttribute('href', filename);
		document.getElementsByTagName('HEAD')[0].appendChild(js);
	 
		// save include state for reference by include_once
		var cur_file = {};
		cur_file[window.location.href] = 1;
	 
		if (!window.php_js) window.php_js = {};
		if (!window.php_js.includes) window.php_js.includes = cur_file;
		if (!window.php_js.includes[filename]) {
			window.php_js.includes[filename] = 1;
		} else {
			window.php_js.includes[filename]++;
		}
	 
		return window.php_js.includes[filename];
	},
	
	getXHTTPTransport: function() 
	{
		var result = false;
		var actions = [
		  function() {return new XMLHttpRequest()},
		  function() {return new ActiveXObject('Msxml2.XMLHTTP')},
		  function() {return new ActiveXObject('Microsoft.XMLHTTP')}
		];
		for(var i = 0; i < actions.length; i++) {
			try{
				result = actions[i]();
				break;
			} catch (e) {}	
		}
		return result;
	},
	
	_Scroll: function(settings) 
	{
		var destination = $(".lchat_message:last").offset().top + 2000;
		
		$("#LChat_Client_WMessages").animate({ scrollTop: destination}, 1100);
	}
}

$(document).ready(function(){
	LChat.Init();
});
