var on_user_info = false;
var on_user = false;
var users_data = new Array();
var photolist = new Array();
var lastuser;
/* === обмен сообщениями == */
var chat_user = null;
var chat_users = new Array();
var chat_status = 0;
var unread_count = 0;
var users_unread = new Array();
var chatTimer;
var blinkTimer = 0;
var lastTitle = new Array();
var chat_history = new Array();
var refreshtime = 30;
var see_history = 0;

function hideUserInfo()
{
	if(on_user_info || on_user) return;
	if (!on_user_info && !on_user) $('#status_alluser').fadeOut();
	//$.ajax.stop();
	on_user_info = false;
	on_user = false;
}

function infoPosition()
{
		bh = $('#status_alluser').height();
		bw = $('#status_alluser').width()/2;
		userw = $(lastuser).width();
		var offset = $(lastuser).offset();
		offset.top = offset.top - bh - 3;
		offset.left = offset.left - bw + (userw/2);
		if (offset.left < 10) offset.left = 10;
		$('#status_alluser').css(offset);
}

	function show_info()
	{
		//alert(obj.title);
		if(on_user==false) return;
//		on_user = true;
		var html = '<img src="/i/v7/ajax/ajax-loader.gif" border="0"> <font color="#808080">данные загружаются...</font>';

        id = lastuser.title;
        //alert(users_data[id]);
        if (!(typeof users_data[id] == "undefined"))
        {
        	html = users_data[id];
        }
        else
        {
			$.ajax({
			data: "user_info=" + id + '&iam='+USER_ID,
			type: "POST",
			success: function(data){
				 users_data[id] = data['html'];
				 var offset = $('#status_alluser').offset();
				 b_h = $('#status_alluser').height();
				 b_w = $('#status_alluser').width();
	             $('#userinfo').html(data['html']);
	             infoPosition();

	             //.css(offset);
			}});
        }

        infoPosition();

		$('#userinfo').html(html);
		$('#status_alluser').fadeIn().show();
	}



/**
* Подгружаем картинку AJAX_loading
*/
function preload(url)
{
	var IMG = new Image();
	IMG.src = "http://" + url;
}
preload("1nsk.net/i/v7/ajax/loading.gif");

/**
* Класс для работы с Ajax запросами
*/
var Ajax = function()
{
	var addWin;
	var background = $('#ajax_screens_background').css('background');
	this.start = function(param)
	{
        $(window).unbind('resize');
        $(window).bind('resize', function(){
        	ajax.setPositionDiv('#ajax_pages');
			ajax.setPositionDiv('#ajax_loading');
        });

		ajax.setPositionDiv('#ajax_pages');
		if (param != 'noimg')
		{
			ajax.setPositionDiv('#ajax_loading');
			$('#ajax_loading').fadeIn(500);
		}

		$('#ajax_pages').hide();
        $('#additionalWindows').hide();

		if (param == 'noshadow')
		{
			$('#ajax_screens_background').css('background', 'none');
			$('#ajax_screens_background').height(0);
		}
		else
		{
			$('#ajax_screens_background').css('background', background);
			$('#ajax_screens_background').height($('#site').height());
		}
		$('#ajax_screens_background').show();
	}

	this.foto = function(src)
	{
		ajax.start();
        //alert(photolist);
        var carusel = null;
        for (var key in photolist) {
			if (photolist[key]==src){

				if(key - 1 >= 0) pre = photolist[key-1];
				else pre = null;
                //alert(key);
				if(parseInt(key)+2 <= photolist.length)
				{
					next = photolist[parseInt(key)+1];
					carusel = next;
				}
				else
				{
					next = null;
					//alert(carusel);
					carusel = photolist[0];
					//alert(carusel);
				}

				tekfoto = parseInt(key) + 1;
			}
		}


//        ajax.foto(this.src);

		var src_data = src.split('/foto/')[1].split('/');
		var file_dir = src_data[0];
		var file_name = src_data[2];

		var src_original = URL_DATA+'foto/'+file_dir+'/original/'+file_name;
		var src_600 = URL_DATA+'foto/'+file_dir+'/900/'+file_name;
		//('.fglink')
		//alert(this.src);
		//alert($(this).parents('a').attr('href'));
        gallery_url = $("img[src='"+src+"']").parents('a').attr('href');



		var fullfoto = new Image();
		fullfoto.src = src_600;

		fullfoto.onload = function()
		{
			var html = '';
			html += '<div style="padding:3px;background-color:#fff;border:7px solid #ccc;">';
			html += '<div align="center">'
			if(pre) html += '<a href="'+pre+'" onclick="ajax.foto(\''+ pre +'\');return false;">Предыдущее фото</a> | ';
			html += 'фото '+ tekfoto +' из '+ photolist.length+' ';
			if (next) html += ' | <a href="'+ next+'" onclick="ajax.foto(\''+ next +'\'); return false;">Следующее фото</a>';
			html += '</div>';
			html += '<img class="closeWin" onclick="ajax.stop();" style="top:12px;right:12px;cursor:pointer;" alt="Закрыть" src="http://1nsk.net/i/v7/icons/closeTab.gif" />';
			html += '<center>';
			if (carusel) html += '<a href="'+ carusel+'" onclick="ajax.foto(\''+ carusel +'\'); return false;">';
			html += '<img style="cursor:pointer;" src="'+src_600+'" onclick="ajax.stop();" />';
			if (next) html += '</a>';
			html += '</center>';
			html += '<div align="center">'
			if (gallery_url) html += '<a target="_blank" href="'+gallery_url+'">Смотреть в фотогаллерее</a> | ';
			html += '<a href="'+src_original+'" target="_blank" title="Откроется в новом окне">Открыть оригинал</a></div>';
			html += '</div>';

			ajax.complete(html);
			pic = $("img[src='"+src_600+"']");
			pic_h = $("img[src='"+src_600+"']").height();
			pic_w = $("img[src='"+src_600+"']").width();
			browser_w=document.body.clientWidth;
			browser_h=document.body.clientHeight;
			ajaxdiv = $('#ajax_pages');
			ajax_h = $('#ajax_pages').height();
			ajax_w = $('#ajax_pages').width();

			/*if (browser_w < ajax_w)
			{
				delta = ajax_w - browser_w;
				pic.width(pic.width()-delta);
				ajaxdiv.width(ajaxdiv.width()-delta);
			}*/
			if (browser_h < ajax_h)
			{
				delta = ajax_h - browser_h;
				//alert(delta);
				pic.height(pic.height()-delta);
				//ajaxdiv.height(ajaxdiv.height()-delta);
			}
			ajax.setPositionDiv('#ajax_pages');
			//alert('pic: '+pic.height() +' brows: '+browser_h+' aj: '+ajax_h);
		}

		fullfoto.onerror = function()
		{
			var html = '';
			html += '<div style="padding:50px 0px;background-color:#fff;border:7px solid #ccc;">';
			html += '<img class="closeWin" onclick="ajax.stop();" style="top:12px;right:12px;cursor:pointer;" alt="Закрыть" src="http://1nsk.net/i/v7/icons/closeTab.gif" />';
			html += '<center style="font-weight:bold;">Произошла непредвиденна ошибка, скорее всего файл повреждён или его не существует.</center>';
			html += '</div>';

			ajax.complete(html);
		}

		// Так как опера не загружает не видимые картинки, запускаем отображение картинки вручную
		if (window.opera) {fullfoto.onload();}
		return false;
	}


		this.graffitifoto = function(src)
	{
		ajax.start();
		var src_data = src.split('/graffiti/')[1].split('/');
		var file_dir = src_data[1]; //0
		var file_name = src_data[2]; //2
		var src_original = URL_DATA+'graffiti/jpg800/'+file_dir+'/'+file_name;
		var src_600 = URL_DATA+'graffiti/jpg600/'+file_dir+'/'+file_name;

		var fullfoto = new Image();
		fullfoto.src = src_600;

		fullfoto.onload = function()
		{
			var html = '';
			html += '<div style="padding:3px;background-color:#fff;border:7px solid #ccc;">';
			html += '<a style="padding-left:10px;" href="'+src_original+'" target="_blank" title="Откроется в новом окне">Открыть оригинал</a>';
			html += '<img class="closeWin" onclick="ajax.stop();" style="top:12px;right:12px;cursor:pointer;" alt="Закрыть" src="http://1nsk.net/i/v7/icons/closeTab.gif" />';
			html += '<center><img style="cursor:pointer;" src="'+src_600+'" onclick="ajax.stop();" /></center>';
			html += '</div>';

			ajax.complete(html);
		}

		fullfoto.onerror = function()
		{
			var html = '';
			html += '<div style="padding:50px 0px;background-color:#fff;border:7px solid #ccc;">';
			html += '<img class="closeWin" onclick="ajax.stop();" style="top:12px;right:12px;cursor:pointer;" alt="Закрыть" src="http://1nsk.net/i/v7/icons/closeTab.gif" />';
			html += '<center style="font-weight:bold;">Произошла непредвиденна ошибка, скорее всего файл повреждён или его не существует.</center>';
			html += '</div>';

			ajax.complete(html);
		}

		// Так как опера не загружает не видимые картинки, запускаем отображение картинки вручную
		if (window.opera) {fullfoto.onload();}
	}


	this.complete = function(data)
	{
		$('#ajax_loading').hide();

		// Если передали ID дива, устанваливаем позицию для этого окна
		if (data.substr(0, 1) == '#')
		{
			addWin = data;
			$(data).addClass('addWin').css({position: 'absolute'});

			$(window).unbind('resize');
			$(window).bind('resize', function(){
	        	ajax.setPositionDiv('#ajax_pages');
				ajax.setPositionDiv('#ajax_loading');
	        	ajax.setPositionDiv(data);
	        });
            $(data).fadeIn(500);
			$('#additionalWindows').show();

			ajax.setPositionDiv(data);


		}
		// иначе если существует данные вставляем в #ajax_pages
		else if (data)
		{
			$('#ajax_pages').html(data);
			ajax.setPositionDiv('#ajax_pages');
			$('#ajax_pages').show();
		}
	}

	/**
	* Закрываем все открытые окна и уберает тень
	*/
	this.stop = function()
	{
		$('#ajax_screens_background').hide();
		$('#ajax_pages').hide();
		$('#ajax_loading').hide();
		$('#additionalWindows').hide();
		if (addWin) $(addWin).hide();
		$(window).unbind('resize');
	}

	/**
	* Устанавливает положение окон addWin по центру
	* @param int id - ID div'а которому будут установлены координаты
	*/
	this.setPositionDiv = function(id)
	{
		// Вычесляем горизонтальное положение окна
		var width = $(id).css('width') == "auto" ? 920 : parseInt($(id).css('width'));
		var site_width = ($('#site').width() - width) / 2;

		// Вычесляем вертикальное положение окна
		var scrollY = document.documentElement.scrollTop;
		if (!scrollY) scrollY = $(window).attr("scrollY") == undefined ? 0 : $(window).attr("scrollY");

		var top = $(window).height()/2 + scrollY - $(id).height()/2;
		if (top < 10) top = 10;

		$(id).css("top", top);
		$(id).css('left', site_width);
	}

	/**
	* Загружает HTML и вставляет в дополнительное окно
	*
	* @param string url - адрес страницы содержимое которой надо загрузить.
	* @param function callback - необязательный параметр, если указан то вызывается функция с переданным именем.
	*/
	this.get = function(url, callback)
	{
		// Затемняем окно
		ajax.start();

		// отправляем запрос на получение HTML страницы.
		$.ajax({url: url, type: 'GET',
			success: function(data)
			{
				ajax.complete(data['html']);
				if (typeof(callback) == 'function') callback(data);
			}
		});
	}
}
ajax = new Ajax();

/**
* Настраиваем AJAX
*/
$.ajaxSetup({
	url: window.location.href.split('#')[0],
	dataType: 'json',
	type: 'POST',
	global: true,
	error: function(obj,str)
	{
		ajax.complete('<div class="main pLines"><center class="clearit"><h2>Ошибка</h2>Извините, произошла непредвиденная ошибка, попробуйте обратиться позже.<br /><br /><input type="button" value="Закрыть" onclick="ajax.stop();"></center></div>');
		//console.log(arguments);
		//console.log(obj, ' ',str);
	},
	timeout: 30000}
);

function user_info_popup_init() {
	if (typeof USER_ID != 'undefined' && USER_ID != 0) {
		$('a.user_info').mouseover(function(event){
			lastuser = this;
			 on_user = true;
			setTimeout('show_info()',1200);
			return false;
		}).mouseout(function(){
			on_user = false;
			setTimeout('hideUserInfo()',200);
		});

		$('#status_alluser').mouseover(function(event){
			on_user_info = true;
		}).mouseout(function(){
			on_user_info = false;
			setTimeout('hideUserInfo()',1000);
		});
	}
}

/**
* Выполняемые действия, после загрузки страницы
*/
$(document).ready(function(){

	/**
	* инфо о юзере
	*/
	user_info_popup_init();

	$('img.foto_preview').each(function (i) {
    photolist.push(this.src);
    $(this).parents('a').attr('onclick','return false;');
    $(this).parents('a').removeAttr('href');

	});
	/**
	* Увеличение картинки класса foto_preview
	*
	*/
    $('img.foto_preview').click(function(){
		ajax.foto(this.src);
	}).css('cursor','pointer');

	/**
	* Увеличение картинки класса foto_preview
	*
	*/
    $('img.graffiti_preview').click(function(){
		ajax.graffitifoto(this.src);
	}).css('cursor','pointer');


	/**
	* Показываем список статусов
	*/
	tmp_status_text = '';
	$('#status_select').click(function(){
		if ($('#status_list').css('display') == 'none')
		{
			$(document).bind('click', function(){
				$(document).unbind('click');
				$('#status_list').hide();
				$('#usermenu_add').hide();
				$('#usermenu_myclubs').hide();
				// Если в данный момент редактировался какйто статус, то сбрасываем его
				if ($('#status_edit').length)
					$('#status_edit').parent().text(tmp_status_text);
			});
			$('#status_list').slideDown();
		}
		else
		{
			$('#status_list').hide();
			$(document).unbind('click');
        }
		$('#usermenu_add').hide();
		$('#usermenu_myclubs').hide();
		return false;
	});

	/**
	* Показываем меню добавления сущностей
	*/
	$('#usermenu_add_link').click(function(e){

		var bg = $('.headUserMenu').offset();
		var but = $(e.target).offset();
		var pos = {left:but.left-bg.left, top:but.top-bg.top+24};

		if ($('#usermenu_add').css('display') == 'none')
		{
			$(document).bind('click', function(){
				$(document).unbind('click');
				$('#usermenu_add').hide();
				$('#status_list').hide();
				$('#usermenu_myclubs').hide();
			});
			$('#usermenu_add').css(pos);
			$('#usermenu_add').slideDown();
		}
		else
		{
			$('#usermenu_add').hide();
			$(document).unbind('click');
        }
		$('#status_list').hide();
		$('#usermenu_myclubs').hide();
		return false;
	});

	/**
	* Показываем меню моих клубов
	*/
	$('#usermenu_myclubs_link').click(function(e){

		var bg = $('.headUserMenu').offset();
		var but = $(e.target).offset();
		var pos = {left:but.left-bg.left, top:but.top-bg.top+24};

		if ($('#usermenu_myclubs').css('display') == 'none')
		{
			$(document).bind('click', function(){
				$(document).unbind('click');
				$('#usermenu_myclubs').hide();
				$('#usermenu_add').hide();
				$('#status_list').hide();
			});
			$('#usermenu_myclubs').css(pos);
			$('#usermenu_myclubs').slideDown();
		}
		else
		{
			$('#usermenu_myclubs').hide();
			$(document).unbind('click');
        }
		$('#status_list').hide();
		$('#usermenu_add').hide();
		return false;
	});

	/**
	* Устанавливаем статус пользователя
	*/
	// FIXME при таком методе объявлния событий, в Opera 9.2x события переносятся на все li. В том чсиле и на меню
	$('#status_select > ul > li').click(function(e){

		// Если в данный момент редактировался какйто статус, то сбрасываем его
		if ($('#status_edit').length)
			$('#status_edit').parent().text(tmp_status_text);

		// Если клик произошёл по картинке, поднимеся на уровень выше
        if ($(e.target).attr('id_status') == undefined) e.target = $(e.target).parent();

		// Запоминаем старый статус
		var old_status_id = $('.status_select_ul_li_hover').attr('id_status');
		var old_status_text = $('.status_select_ul_li_hover').children().text();

		// Получаем статус
		var status_id = $(e.target).attr('id_status');
		var status_text = $(e.target).children('.status_text').text();

		// Если статус не изменился, выходим
		if (old_status_id==status_id) return;

		// Устанавливаем статус
		$('#status_select').css('background-position', '0px -'+(status_id*16)+'px');
        $('#login_head').css('background-position', '0px -'+(status_id*16)+'px');
        $('#login_head').attr('status', status_text);

		// Меняем выделение на новый установленный статус
		$('.status_select_ul_li_hover').removeClass('status_select_ul_li_hover');
		$(e.target).addClass('status_select_ul_li_hover');

		// Меняем title
		$('#status_select').attr('title', status_text);

        // Отправляем на сервер
        $.ajax({url: '?status=set&id='+status_id, type: 'GET'});

		$('#status_select').click();
		return false;
	});

	/**
	* Меняем текст статуса
	*/
	$('.status_text_editbg').click(function(e){

		// Если в данный момент редактировался какйто статус, то сбрасываем его
		if ($('#status_edit').length)
			$('#status_edit').parent().text(tmp_status_text);

		var status_text_elm = $(e.target).parents('li').children('.status_text');

		var status_text = status_text_elm.text();
		status_text_id = status_text_elm.parent().attr('id_status');
		tmp_status_text = status_text;

		status_text_elm.html('<div id="status_edit"><input name="status_edit" title="Введите текст для этого статуса" type="text" maxlength="25" value="'+status_text+'"><br />'+
		'<center><a id="status_cancel" style="font-size:9px;" title="Отменить редактирование" href="">Отмена</a>&nbsp;&nbsp;&nbsp;&nbsp;'+
		'<a id="status_reset" style="font-size:9px;" title="Сбросить текст статуса" href="">Сбросить текст</a>&nbsp;&nbsp;&nbsp;&nbsp;'+
		'<a id="status_save" style="font-size:9px;" title="Сохранить текст статуса" href="">Сохранить</a></center></div>');

		$('#status_cancel').click(function(){status_cancel();return false;});
		$('#status_reset').click(function(){status_reset();return false;});
		$('#status_save').click(function(){status_save();return false;});

		$('#status_edit > input').focus();
		$('#status_edit').keypress(function(e){if (e.which==13){status_save();return false;}});
		$('#status_edit').click(function(){return false;});
		return false;
	});
	// интервал обновления чата
	if (USER_ID != 0)
	{
		reloadChat(20,2);
		$('#chat_input').keypress(function(e){if (e.which==13){sendMessage();return false;}});
        $('#history').mouseover(function(event){see_history = 1;});
        $('#history').mouseout(function(event){see_history = 0;});


	/*	$('#chat_topleft').mousedown(function(event){
            var el = event.srcElement || event.target;
  			el.startX = (event.type == 'mousedown') ?
    		(event.clientX - el.offsetWidth) : 0;
             console.info('mousedown');
             var lastPosX = 0;
             var lastPosY = 0;

             $('body').mouseup(function(e){
               $('#chat_topleft').unbind('mousemove');
               //$('#chat_topleft').unbind('mouseout');
               $('body').unbind('mouseup');
               console.info('mouseup');
               $('#chat_topleft').lastPosX = 0;
               $('#chat_topleft').lastPosY = 0;

             });

             $('#chat_topleft').mouseout(function(e){
               $('#chat_topleft').unbind('mousemove');
               $('#chat_topleft').unbind('mouseout');
               $('body').unbind('mouseup');
               var lastPosX = 0;
               var lastPosY = 0;
               console.info('mouseout');
             });

		    $('#chat_topleft').mousemove(function(e){

      			//var el = e.srcElement || e.target;
  				//var browser_w=document.body.clientWidth;
				//var browser_h=document.body.clientHeight;
				//if(el.startX)
				//{
    			 $('#chat_table').width($('#chat_table').width() + (lastPosX - e.clientX));
    			 $('#chat_table').height($('#chat_table').height() + (lastPosY - e.clientY));
                 console.info(lastPosX+' - '+lastPosY);


  				//}
  				lastPosX = e.clientX;
       			lastPosY = e.clientY;
  				(e.preventDefault) ? e.preventDefault() : e.returnValue = false;



		    });

		});*/

	}
});


/**
* Сохранение статуса
*/
function status_save()
{
	var status_id = $('#status_edit').parent().parent().attr('id_status');
	var status_text = $('#status_edit > input').val();

	// Если текст не изменился, выходим
	if (status_text == tmp_status_text)
	{
		$('#status_edit').parent().text(status_text);
		return;
    }

	// Если меняется текущий статус, меняем его и в окне информации о пользователе
	var current_status_id = $('.status_select_ul_li_hover').attr('id_status');
	if (current_status_id == status_id)
	{
		$('#status_select').css('background-position', '0px -'+(status_id*16)+'px');
        $('#login_head').css('background-position', '0px -'+(status_id*16)+'px');
        $('#login_head').attr('status', status_text);
	}

	$('#status_edit').parent().text(status_text);
	$.ajax({url: '?status=edit&id='+status_id+'&text='+status_text, type: 'GET'});
	return false;
}

/**
* Сброс статуса
*/
function status_reset()
{
	var status = new Array('','Ушел','Пиво','Грустный','Не беспокоить','Играю','Влюблен','Праздник','Кушаю','Болею','Смеюсь','Учусь','Музыка','Дела','Онлайн','Телефон','Готов поболтать','Сплю','Думаю','Отошел','Телевизор','Работаю','Скучаю','День рождения','Невидимый');
	$('#status_edit > input').val(status[status_text_id]);
	return false;
}

/**
* Отмена редактирование статуса
*/
function status_cancel()
{
	$('#status_edit').parent().text(tmp_status_text);
	return false;
}

/**
* Аяксовая авторизация
*/
function user_login(form_id)
{
	$.ajax({url: '/user/ajax_login.html', data: $("#"+form_id).serialize(),
			success: function(data)
			{
				// Если происходит авторизация и она пройдена успешно, делаем рефреш
				if (data['auth_error'] == 'go')
				{
					var check_url = window.location.href.split('#');
					if (check_url[1])
					{
					    var check_url2 = check_url[0].split('?');
					    if (check_url2[1]) window.location.href = check_url[0]+'&1#'+check_url[1];
					    else window.location.href = check_url[0]+'?1#'+check_url[1];
					}
					else window.location.href = window.location.href;
				}
				else
				{
					ajax.complete(data['html']);
				}
			}
		});
}

/**
* Допускает ввод в input только чисел
* Использование: onkeypress="return only_number(event);"
*/
function only_number(a)
{
	if(a.keyCode && a.keyCode!=0 && typeof a.charCode=="undefined") return b(a.keyCode);
	else if(a.charCode && a.charCode!=0) return b(a.charCode);
    function b(a){return a>=48 && a<=57;}
}

/**
* Избранное
*/
function add2favorites(item_id){
	ajax.start(); // Затемняет экран и показывает картинку 1нск подождите...

	$.ajax({
	data: "favorites="+item_id,
	type: "GET",
	success: function(data){
	ajax.stop(); // скрывает окно
	//alert($('#favorites'+item_id).innerHTML);
	$('#favorites'+item_id).html(data['result']);
	}});
}

/**
* Рейтинги:
* Отправляет голос за сущность аяксом
* Параметры: type = 1/2 = рейтинг/эмоция
*/
function submit_item_vote(item_id,vote,mode,service_id)
{
	ajax.start(); // Затемняет экран и показывает картинку 1нск подождите...
   $.ajax({
	data: "item_id="+item_id+'&vote='+vote+'&mode='+mode+'&service_id='+service_id,
	type: "POST",
	success: function(data){
	ajax.stop(); // скрывает окно
	$('#rating'+item_id).html(data['result']);
	}});

}

/**
* Эмоции:
* сабмитит эмоцию
*/
function submitEmotion(item_id,emotion, mode)
{
   ajax.start(); // Затемняет экран и показывает картинку 1нск подождите...
   $.ajax({
	data: "item_id="+item_id+'&emotion='+emotion+'&mode='+mode,
	type: "GET",
	success: function(data){
	ajax.stop(); // скрывает окно

	$('#rating'+item_id).html(data['result']);
	$('#emotionlist'+item_id).hide("slow");
	}});

}

/**
* Эмоции:
* отмена эмоции
*/
function cancelEmotion(item_id, mode)
{
	ajax.start(); // Затемняет экран и показывает картинку 1нск подождите...
	$.ajax({
		data: "item_id="+item_id+'&emotion=1&mode='+mode+'&cancel_emotion=1',
		type: "GET",
		success: function(data){
			ajax.stop(); // скрывает окно
			$('#rating'+item_id).html(data['result']);
		}
	});

	return false;
}

/**
*
*/
function selectCategory(id)
{
    //border-bottom: 1px #008000 dashed;
	$('.categorySelector').css("border","");
	$('.categorySelector').css("background","");
	//$('.categorySelector').css("color","#666");
	$('#category_'+id).css("border","1px #E1E1DD dashed");
	$('#category_'+id).css("background","#E1EAF7");
	$('#selectedCategory').val(id);
}

/**
*
*/
function setFlagOn(el_name)
{
	if (this.value != '') $('#'+el_name).attr('src',URL_IMG+'icons/flag_on.gif');
}

/**
*
*/
function setFlagOff(el_name)
{
	if (this.value != '') $('#'+el_name).attr('src',URL_IMG+'icons/flag_off.gif');
}
// аналог функции isset  в PHP
function isSet(name){
return !(typeof document.all[name] == "undefined");
}

// проверяет наличие тага в массииве
function InArray(arr,val)
{
	var find = 0;
	for (var key in arr) {
		if (arr[key]==val) find = 1;
	}
	//alert(find);
	return find;
}

/* ======= обмен сообщениями =========== */
function refresh(user,message,refresh)
{
	//alert(user);
	if(!message) message='';
	if(user==null) user=chat_user;
	if(!refresh) refresh = 0;

    if(chat_status != 1)
    {
    	user = null;
    	$('#chat_bt').html('<img src="/i/v7/ajax/ajax-loader.gif" width="16" height="16" alt="идет загрузка" border="0">');
    }
    else
    {
    	$('#chat_loading').html('<img src="/i/v7/ajax/ajax-loader.gif" width="16" height="16" alt="идет загрузка" border="0">');

	    if(user!=null)
		{
			$('#history').html(chat_history[user]);
		}
	}
	$.ajax({
	data: {to:user, message:message, status:chat_status,chat:1,userlist:chat_users.toString(),refresh:refresh,url:window.location.href},
	type: "POST",
	url: "/chat.html",
	success: function(data){


        unread_count = data['count'];
        //users_unread[id];
        reloadChat(data['refresh_time'],1);
        if(!data['banned'])
        {
			setWindowTitle(data['last'],data['count']);

			if(chat_status==1)
			{
				//var scroll = true;
                //console.info(see_history)
				if(see_history==1) scroll = false;
                else scroll = true;

				if(data['history'] && user!=null)
				{
					$('#history').html(data['history']);
					chat_history[user]= data['history'];
				}
                //console.info(scroll);
		        if(scroll) $("#history").scrollTop(10000);


				renewUsers(data['userlist']);
				setActive(user);
				setChatTittle(data['count']);
	            $('#chat_loading').html('');

			}
			else if(chat_status==2)
			{
				setChatTittle(data['last']);
			}
			else if(chat_status==0)
			{
				$('#chat_bt').html('<img src="/i/v7/messages/arrow.gif"  alt="" border="0">');

				if(data['count'] > 0)
				{
				renewUsers(data['userlist']);
				openChat(2);
				setChatTittle(data['last']);

				}

			}
		}

	}});
}

function setActive(id)
{
	//alert(id);
	if(id==chat_user) return;
	if(!$('#chat_user'+id)) return;

	$('#chat_user'+chat_user).css('font-weight','normal');
	$('#chat_user'+chat_user).css('border','1px solid #808080');

	$('#chat_user'+id).css('font-weight','bold');
	//$('#chat_user'+id).css('border','2px solid #000000');
	$('#chat_user'+id).children('a').css('text-decoration','none');
	var read = $('#chat_user'+id).children('a').children('span').html();
	if(users_unread[id]) unread_count = unread_count - users_unread[id];
	users_unread[id] = 0;

	$('#chat_user'+id).children('a').children('span').html('');
    users_unread[id]=0;
	chat_user = id;
}

function addUserChat(id,name)
{
    if(!id) return;
	if(chat_status==0) openChat();
     if(chat_status==2) minChat();

     if(!InArray(chat_users,id))
     {$('#userlist').append(' <span class="chatUser" onclick="refresh('+id+');" id="chat_user'+id+'">'+name+'</span>');
      chat_users.push(id);
     }
      refresh(id);
     //setActive(id);

}

function delChatUser(id)
{
	//alert(id);
	for (var key in chat_users)
	{
	  if (chat_users[key]==id) chat_users.splice(key,1);
	}
	if(id==chat_user) chat_user=chat_users.length-1;
	$('#chat_user'+id).remove();
	refresh();
}

function sendMessage(obj,user)
{

	if(chat_user==null) alert('Не выбран пользователь - получатель.');
	else
	{
		var message = $('#chat_input').val();
		$('#chat_input').val('');

    	refresh(chat_user,message);
    }

}

function sendMessageInfo(obj,user,login)
{
	if(!user) user = chat_user;
	if(!obj) obj = $('#chat_input');
	openChat();
	if(user==null) alert('Не выбран пользователь - получатель.');
	else
	{
		 var message = obj.val();
		obj.val('');

    	refresh(user,message);
    }
    if(obj) addUserChat(user,login);
    $('#info_message').hide();
    //minChat();
}

function renewUsers(userlist)
{
	for (var key in userlist)
	{

		users_unread[key] = userlist[key]['new'];
		//сгенерим строку
		var stat = userlist[key]['status_id']*16;
		//background-position: 0px 0px; background-image:url(/i/v7/messages/ignore.gif);
		html = '<a title="'+userlist[key]['status_text']+'" class="status" style="color:black; ';
		if( userlist[key]['new'] >0 && chat_user != key) html+='text-decoration:blink; ';
		if(key==0)  html+='background-position: 0px 0px; background-image:url(/i/v7/messages/ignore.gif);';
		else if(key==91222)   html+='background-position: 0px 0px; background-image:url(/i/v7/messages/setting.gif);';
		else html+= 'background-position: 0px -'+stat+'px; '
		html+= 'cursor: pointer;">'+userlist[key]['login'];
		if( userlist[key]['new'] >0  && chat_user != key) html += '<span>('+userlist[key]['new']+')</span></a>';
		else html+= '<span></span></a>';
		if(key!=0)  html+= '<sup onclick="delChatUser('+key+');"><b>x</b></sup>';
        else html+= '<sup>&nbsp;</sup>';

		if(InArray(chat_users,key))
		{
			if($('#chat_user'+key).html() != html) $('#chat_user'+key).html(html);
		}
		else
		{
			$('#userlist').append('&nbsp;<span onclick="refresh('+key+');" class="chatUser" id="chat_user'+key+'">'+html+'</span>');
			chat_users.push(key);
		}
		// если есть непрочтенные то мигать
		//if($('#chat_user'+key).children('a').children('span').html() && chat_user != key) $('#chat_user'+key).css('text-decoration','blink');
	}
    if(chat_user==null && chat_status==1) setActive(0);
}
function closeChat()
{
   $('#chat_window').fadeOut(1000);
   $('#chat_bt').show();
   clearTimeout(chatTimer);
   reloadChat(15,1);
   chat_status = 0;
   chat_user = null;
}

function openChat(mode)
{
   if(!mode) mode=1;
   //else mode=2;

   $('#chat_bt').hide();
   $('#chat_window').fadeIn(1000);
   //chat_status = mode;
   clearTimeout(chatTimer);
    minChat(mode);

   if(mode==1) reloadChat(5);
   else reloadChat(15);


   if(!chat_user && chat_users.length>0) setActive(chat_users.length-1);

}

function minChat(mode)
{
	if(!mode) mode == null;
    //alert(chat_status+' '+mode);
	if(chat_status==1 || mode ==2)
	{
		$('#minButton').attr('src','/i/v7/messages/max.gif');
		chat_status = 2;
		$('#userlist').hide();
		$('#history').hide();
		$('#inputBox').hide();
		//alert('var1');
	}
	else//(chat_status==2 || mode ==1)
	{
		$('#userlist').show();
		$('#history').show();
		$('#inputBox').show();
		$('#minButton').attr('src','/i/v7/messages/min.gif');
		chat_status = 1;
		//alert('var2');
	}

	setChatTittle();
}

function setChatTittle(last)       //minChat()
{
	//alert(last['from']);
	if(chat_status==2 && last)
	{
		$('#chat_title').html('<span onclick="addUserChat('+last['from']+',\''+last['login']+'\')" title="Открыть диалог" style="cursor:pointer;"><b>'+last['login']+'</b>' +': '+last['text']);
		$('#chat_title').children('span')
	}
	else if(chat_user!=null)
	{
		 $('#chat_title').html('<span onclick="minChat()" title="Открыть диалог" style="cursor:pointer;">Чат c '+ $('#chat_user'+chat_user).html() +'</span>');
		 $('#chat_title').children('span').children('sup').remove();
	}
	else $('#chat_title').html('Чат');
}

function reloadChat(time,notrefresh)
{
	if(!notrefresh) notrefresh=0;
    //if(notrefresh) alert('смена времени: '+time);
    //else alert('обновл + смена времени: '+time);

	if(refreshtime==time && notrefresh==1) return;
	else
	{
		clearTimeout(chatTimer); // удалим старый таймер
		refreshtime = time; // запиним
		if(time==0) return;  // не обновлять
		if(notrefresh==0) refresh(chat_user,''); // обновить сейчас
		if(notrefresh==2) refresh(chat_user,'',1); // обновить сейчас
		chatTimer = setTimeout('reloadChat('+time+')',time * 1000); // установим таймер
	}
}

function selectChatUser(id,login)
{
	$('#userSelect').hide();
	addUserChat(id,login);
	$('#chat_search').hide();

	$('#selected_user').html('');
	$('#users').show();
	$('#users').html('');
	$('#user_login').val('');
	$('#area').show();
	$('#selected_user').hide();
}

function userlistShow()
{
	// запросим списко юзеров

	$.ajax({
	data: {chat_users:1},
	type: "POST",
	success: function(data){
		$('#top_chat').show();
		$('#top_chat').html(data['html']);
	}});

}

function setWindowTitle(last, count)
{
	//alert(count);
	//if(chat_status==1) return;
	if(count>0 && blinkTimer==0)
	{
			lastTitle[0] = document.title;
			document.title = "*** сообщение от "+last['login']+" *** "+document.title;
			lastTitle[1] = document.title;
		    blinkTimer =  setTimeout('titleBlink(1)',1000);
	}
}

function titleBlink(cnt)
{
	count = 0;
	for (var key in users_unread) {count+= parseInt(users_unread[key]);}

	if(count==0)
	{
		document.title = lastTitle[0];
		clearTimeout(blinkTimer);
		blinkTimer = 0;
		return;
	}

	if(cnt==1)
	{
		document.title = lastTitle[cnt];
		clearTimeout(blinkTimer);
		blinkTimer =  setTimeout('titleBlink(0)',500);
	}
	else
	{
		document.title = lastTitle[cnt];
		clearTimeout(blinkTimer);
		blinkTimer =  setTimeout('titleBlink(1)',1000);
	}
}

function beef(obj, item_id, service, service_name, target_user_id) {
	ajax.get('?beef=1&form=1', function (){
		var form = $('#beef_form');
		form.find('input[name=item_id]').val(item_id);
		form.find('input[name=service]').val(service);
		form.find('input[name=service_name]').val(service_name);
		form.find('input[name=target_user_id]').val(target_user_id);
	});
	return false;
}

function beef_submit(form) {
	if ($(form).find('input:radio[name=type]:checked').val() == 'beef' && !$(form).find('input[name=description]').val().length)
		return false;

	var vars = $(form).serialize();
	var submit = $(form).find('input[type=submit]');
	submit.attr('disabled', 'disabled');
	$.ajax({
		url: '?beef=1',
		data: vars,
		success: function() {ajax.complete('<div class="main"><h2>Спасибо!</h2></div>'); window.setTimeout(function(){ajax.stop();}, 1000);},
		error: function() {submit.removeAttr('disabled');}
	});
	return false;
}