$(function(){
	
	// ------------------ переменные
	var bchat_path = '/bchat';		// путь к чату
	var img_src; 					// путь к картинке (кнопке)
	var oper_online = true;			// статус оператора
	var btn = $('#bchat');			// кнопка вызова оператора
	var sid;						// sid пользователя
	var user_ie = $.browser.msie; 	// 
	
	jQuery.getScript(bchat_path+"/js/jquery.timers.js",function(){
	jQuery.getScript(bchat_path+"/js/jquery.pngFix.js",function(){
	jQuery.getScript(bchat_path+"/js/utils.js",function(){
	jQuery.getScript(bchat_path+"/js/func.js",function(){
		
		// ------------------ определяем сид пользователя
		$.ajax({
			type: "GET",
			url: bchat_path+"/user_actions.php",
			data: "action=get_sid",
			success: function(data){
				if(data)
					sid = data;
			}
		}); 
		
		// ------------------ извещаем систему каждые 5 сек
		$(document).everyTime(5000, 'timer1', function() {
			// что пользователь на сайте + браузер
			$.ajax({
				type: "GET",
				url: bchat_path+"/user_actions.php",
				data: "action=user_online&ie="+(user_ie ? '1' : '0')
			});
			// проверка наличия свободного оператора
			$.ajax({
				type: "GET",
				url: bchat_path+"/user_actions.php",
				data: "action=operator_online",
				success: function(msg){
				 	oper_online = msg=='online' ? true : false;
			   	}
			});
		});
		
		// ------------------ вставка кнопки чата
		$.preloadImg(bchat_path+'/img/offline.gif',bchat_path+'/img/online.gif');
		
		var img = new Image();
		img_src = bchat_path+'/img/'+(oper_online?'online':'offline')+'.gif';
		
		$(img).attr({
			width: 1,
			height: 1,
			src: img_src,
			title: "вызов консультанта",
			alt: "вызов консультанта",
			border: 0
		});
		
		btn.css({'cursor':'pointer'});
		btn.prepend(img);
		
		// ------------------ ВЕШАЕМ НА КНОПКУ ЗАДАЧИ -----------
		// каждые 10 сек меняем картинку  
		// в зависимости от наличия оператора
		$(img).everyTime(5000, 'timer2', function() {
			var new_src = bchat_path+'/img/'+(oper_online?'online':'offline')+'.gif';
			if($(this).attr('src')!=new_src) 
				$(this).attr('src',new_src);
		});
		
		// вызов оператора
		btn.click(function(){
			openWindow(455,420,bchat_path+'/user_dialog.php');
		});
		
		// ------------------ ОКНО ВЫЗОВА ПОЛЬЗОВАТЕЛЯ ------------------
		$.preloadImg(bchat_path+'/img/dialogs/bcd.png',bchat_path+'/img/dialogs/bcd_close.png');
		
		var bcd = document.createElement('DIV');
		$(bcd).attr({'id':'bcd','align':'left'});
		$(bcd).css({
			'position' : 'absolute', 
			'width' : '412px',
			'height' : '228px',
			'display' : 'none',
			'z-index' : '1000'
		});
		btn.after(bcd);
		
		// проверяем отправлено ли приглашение пользователю
		$(document).everyTime(5000, 'timer3', function() {
			$.ajax({
				type: "GET",
				url: bchat_path+"/user_actions.php",
				data: "action=get_message",
				success: function(data){
				 	// есть новое сообщение
					if(data=='new_message')
					{
						$(document).stopTime('timer3');
						
						$(bcd).load(bchat_path+'/user_actions.php?show=call_dialog',{},function(){
							
							$('#bcd').pngFix();
							
							$('#bcd').css("left",absPosition(btn.get(0)).x-412+"px");
							$('#bcd').css("top", Math.round(screen.availHeight/2)-500+document.documentElement.scrollTop+"px");
							$('#bcd').show("slide", { direction: "right" }, 300, function(){
								// отметить сообщение как принятое
								$(document).oneTime(3000, 'timer4', function() {
									$.ajax({
										type: "GET",
										url: bchat_path+"/user_actions.php",
										data: "action=take_message"
									});
								});
							});							
						});
					}
			   	}
			});
		});
		
	});
	});
	});	
	});
		
});
