projectMy = 'http://r.mail.ru/cln4577/my.mail.ru/';


//  формирование контекстной помощи
function plugin_help( id, img, w, h, alt, title, url, urlname ){
  var retval = ( id > 0 ? '<a onclick="return contHelp(this, event, '+ id
        + ( typeof(url) != 'undefined' ? ', 0, \''+ url + '\', \''+ urlname +'\'' : '') + ');" href="'
        + ( typeof(url) != 'undefined' ? url : '/help/' )
        + '">' : '' )
        + '<img align="absmiddle" src="' + img + '"'
        + ( w > 0 ? ' width="'+ w +'"': '')
        + ( h > 0 ? ' height="'+ h +'"' : '' )
        + ( alt ? ' alt="'+ alt +'"' : '' ) 
        + ( title ? ' title="'+ title +'"' : '' )
        +  '/>' + ( id >0 ? '</a>' : '');
  return retval;
}

//  Получение параметра из атрибута
function plugin_get_param( str, type ){
  var re  = new RegExp("^"+ type +":(.*)$", "");
  var arr = re.exec(str);
  return RegExp.$1;
}
                                                                  

//  плагин "был ли вопрос лидером"
function plugin_showleader( qid, status ){
  if ( status == 1 ){
    doc = document.getElementById("list" + qid);
    if ( doc.getAttribute('rel') != 'opros' ){
      doc.innerHTML = "<a onclick='return contHelp(this, event, 35);'" 
        + "href='/help/'><img border='0' src='/img/ico_x2.gif' width='16' height='16' "
        + "alt='Получи в 2 раза больше баллов за ответ на вопрос-лидер!' "
        + "title='Получи в 2 раза больше баллов за ответ на вопрос-лидер!' class='mbm3 mr3' /></a>" 
      + doc.innerHTML;
    }
  }
}


//  плагин "был ли пользователь отблагодарён"
function plugin_showtnxleader( email, medal ){
  medal = typeof medal == 'undefined' ? 0 : medal;
  if ( medal < 1  || medal > 4 ) return;
  var title = ( medal == 1 ? 'Бронзовая' : ( medal == 2 ? 'Серебряная' : 'Золотая')) + ' медаль';

    var doc     = document.getElementById('user:' + email);
  //  Получаем ID пункта помощи
  var help    = plugin_get_param( doc.getAttribute('rel'), 'help');
  
  // Разбираем email
  var re = new RegExp("(.+)@([^\.]+)", "");
  var arr = re.exec(email);
  var box = RegExp.$1;
  var domain = RegExp.$2;
  
  //  И формируем нужный код
  doc.innerHTML = plugin_help(help, '/img/ico_medal_'+ medal +'.gif', 16, 16, ' ', title, '/thanks/user/' + domain + '/' + box + '/', 'Узнать код для отправки благодарности');
}

function plugin_showfriend(email, check){
	if ( document.getElementById('dropDown:' + email) ){
		document.getElementById('dropDown:' + email).dropDown = check;
	}
	friendEmails[email] = check;
}
                                                                       
function plugin_showfriendqst(qst, check){
	if ( ! check ) return;	

	var quizspan    = document.getElementById('quizspan:' + qst);
	var qheader     = document.getElementById('qheader:'  + qst);
	var doc         = document.getElementById("list"    + qst);
          
	quizspan.style.backgroundColor	= "#2b8d04";
	quizspan.style.color			= "white"
	quizspan.style.display			= "inline";
	qheader.style.color				= "#48a763";
                            
	quizspan.innerHTML = (doc.getAttribute('rel') == 'opros' ? 'Опрос' : 'Вопрос') + ' друга';
}

//  плагин вывода вопросов новичков
function plugin_helpnewcomers(id, text, anscnt, email, nick, name, urlname){
    var hint, parsedEmail, tbl, row, cell;
    parsedEmail = parseEMail(email);
    hint = "<div class=\"det2 mb5\"><a href=\"/question/" + id + "/\" class=\"subj2\">"+ text + "</a>"
             + "&nbsp;&rarr;&nbsp;<a href=\"/" + urlname + "/\">" + name + "</a>"                                            
         + "<div class=\"add\"><a href=\"http://www.mail.ru/agent?message&to=" + email + "\"><img src=\"http://status.mail.ru/?" + email + "&9x9\" width=\"9\" height=\"9\" alt=\"\" /></a>"
         + "<a href=\"http://otvet.mail.ru/" + parsedEmail.domain + "/" + parsedEmail.box + "/\">" + nick + "</a>&nbsp;<a href=\"http://otvet.mail.ru/#url?to=" + email + "\" target=\"_blank\" onclick=\"return userMenuShow(this, event,0)\"><img src=\"http://otvet.mail.ru/img/ico_flips.gif\" width=\"9\" height=\"9\" alt=\"Меню пользователя\" title=\"Меню пользователя\" /></a>"
                 + "&nbsp;<span><img src=\"/img/ico_answ_s.gif\" width=\"9\" height=\"9\" alt=\"\" />" + anscnt + "&nbsp;" + getplural(anscnt, 'голос', 'голоса', 'голосов') +"</span>&nbsp;";

//    document.getElementById('help_newcomers').innerHTML += hint;
        tbl = document.getElementById('helpnewcomers_table');
        row = tbl.insertRow(tbl.rows.length);
        cell = row.insertCell(0);
        cell.setAttribute("class", "data p0 pb5");
        cell.innerHTML = hint;
}

// плагин вывода суммы проголосовавших в опросе
function plugin_sumpollvotes(id, sum){
        var doc;
        doc = document.getElementById('pv:' + id);
        doc.innerHTML = "<img src=\"/img/ico_answ_s.gif\" width=\"9\" height=\"9\" alt=\"\" />" + ( sum > 0 ? sum + "&nbsp;" + getplural(sum, 'голос', 'голоса', 'голосов') : 'голосов&nbsp;нет');
}

// плагины отображения VIP-пользователей

// VIP-пользователи в списке ответов на вопрос
function plugin_vipcheckans(email, aid, isvip, picnum){
	var doc, help, parsedEmail, parsedFileName;
	doc = document.getElementById('answer:' + aid);
	if ( doc.getAttribute("rel") != "best" ){
		if ( doc.getAttribute("className") ){
			doc.setAttribute("className", "AnswV");
		}
		else{
			doc.setAttribute("class", "AnswV");
		}
	}
	
	parsedEmail = parseEMail(email);
	help    = plugin_get_param( 'help:40', 'help');
	document.getElementById("user:" + email).innerHTML += plugin_help(help, '/img/ico_diamond.gif', 16, 16, ' ', 'VIP-пользователь', '/smsvip/user/' + parsedEmail.domain + '/' + parsedEmail.box + '/', 'Подробнее');
	
	if ( picnum != 0 ){
		doc = document.getElementById('ansstar:' + aid);
		parsedFileName = parseFilePath(doc.src);
		doc.src = parsedFileName.begin + '/' + picnum + parsedFileName.end;
	}
}

// VIP-пользователи в списке вопросов
function plugin_vipcheckqsts(email, qid, isvip, picnum){
	var doc, parsedFileName;
	doc = document.getElementById('tdleft:' + qid);
    if ( doc.getAttribute("className") ){
		doc.setAttribute("className", doc.getAttribute("className") + " qvip");
		doc = document.getElementById("vipav:" + qid);
		doc.setAttribute("className", doc.getAttribute("className") + " qvip");
		doc = document.getElementById("vipstar:" + qid);
		doc.setAttribute("className", doc.getAttribute("className") + " qvip");
		doc = document.getElementById("tdright:" + qid);
		doc.setAttribute("className", doc.getAttribute("className") + " qvip");
	}
	else{
		doc.setAttribute("class", doc.getAttribute("class") + " qvip");
		doc = document.getElementById("vipav:" + qid);
		doc.setAttribute("class", doc.getAttribute("class") + " qvip");
		doc = document.getElementById("vipstar:" + qid);
		doc.setAttribute("class", doc.getAttribute("class") + " qvip");
		doc = document.getElementById("tdright:" + qid);
		doc.setAttribute("class", doc.getAttribute("class") + " qvip");
	}

	if ( picnum == 0 ) return;
//	parsedFileName = parseFilePath(imgs.item(1).src);
}

function plugin_vipcheckuser(email, isvip, picnum){
	var doc, help, parsedEmail, parsedFileName;
	doc     = document.getElementById('userdiamond:' + email);
	help    = plugin_get_param( 'help:40', 'help');

	parsedEmail = parseEMail(email);

	//  И формируем нужный код
	doc.innerHTML = plugin_help(help, '/img/ico_diamond.gif', 16, 16, ' ', 'VIP-пользователь', '/smsvip/user/' + parsedEmail.domain + '/' + parsedEmail.box + '/', 'Подробнее');
	
	if ( document.getElementById('userstars') && picnum >0 ){
		parsedFileName = parseFilePath(document.getElementById('userstars').src);
		document.getElementById('userstars').setAttribute('src', parsedFileName.begin + '/' + picnum + parsedFileName.end);
	}
}

function parseFilePath(fileName){
	var re = new RegExp("(.*)\/(.*)$", "");
	var arr = re.exec(fileName);
	var result = { begin: RegExp.$1, end: RegExp.$2 };
	return result;
}

function plugin_usronline(email, online){
	if ( online != 1 )	return;
	var doc = document.getElementById('online:' + email);
	if ( ! doc )		return;

	if ( doc.getAttribute("className") ){
		doc.setAttribute("className", "online");
	}else{
		doc.setAttribute("class", "online");
	}
	doc.innerHTML = 'на&nbsp;ответах';
}

//Инициализация подарков и плашек "кто дарил" 
function plugin_sticker_init(gifts)
{
    for (var k in gifts) 
    {
        var id = k;

        // Разбираем email
        var re = new RegExp("(.+)_([^\.]+)", "");
        var arr = re.exec(id);
        var box = RegExp.$1;
        var domain = RegExp.$2;

        var pdiv = document.getElementById('podarok_'+box+'_'+domain);
        var html = '';

        if (pdiv)
        {
            

            html = '<div id="paidGiftsMain_' + box + '_' + domain + '" style="position: relative;"> <div id="paidGiftsAll_' + box + '_' + domain + '" class="paidGifts"> <div id="podarki_' + box + '_' + domain + '" style="top: 0px; position: relative;">';
            var add_html = '';

            for (var i = 0; i < gifts[k].length; i++)
            {
                var show_action = '';
                if (box == show_box && domain == show_domain)
                {
                    show_action='onmouseover="userTooltipShow(\''+gifts[k][i]['Email']+'\',\''+gifts[k][i]['Online']+'\',\''+gifts[k][i]['Private']+'\', \'\', \''+gifts[k][i]['isVip']+'\', this);" onmouseout="userTooltipHide(\''+gifts[k][i]['Email']+'\', \'\');"';
                }

                html = html + '<a '+show_action+' href="http://my.mail.ru/' + domain + '/' + box + '/gifts?id=' + gifts[k][i]['ID'] + '"> <i class="ava45_nobg IEpng" style="background:url(http://img.mail.ru/r/my/gifts/' + gifts[k][i]['FileCut45'] + '.png) center no-repeat;"> <i class="ava45_nobg" style="background-image:url(http://img.mail.ru/r/my/gifts/' + gifts[k][i]['FileCut45'] + '.gif);"> </i> </i> </a>';  

                name_del  = ' ';
                name_full = gifts[k][i]['FirstName'] + name_del + gifts[k][i]['LastName'];

                if (!gifts[k][i]['Private'])
                    if (name_full.length > 20 || gifts[k][i]['FirstName'].length > 16 || gifts[k][i]['LastName'].length > 16)
                        name_del = '<br />';

                html = html + '<span style="display: none;" id="'+gifts[k][i]['Email']+'_name"> '+gifts[k][i]['FirstName']+name_del+gifts[k][i]['LastName']+'</span>';
                add_html = '';
            }
            
            html = html + '</div> </div> </div>' + add_html;


            pdiv.innerHTML = html;
        }
    }
}

//Ротация стикеров 
function showManyGifts(gifts){
    for (var k in gifts) 
    {
        var id = k;
        var topGifts = 45 * giftSteps[id];
        var p = document.getElementById('podarki_' + id);
        if (p) p.style.top = '-' + topGifts + 'px';
        giftSteps[id] = giftSteps[id] + 1;
        if (giftSteps[id] == GiftsItems[id]){giftSteps[id] = 0;} 
    }
    showNewGiftsTimer = setTimeout("showManyGifts(gifts)",4000);
}

// Всплывающая подсказка, кто дарил подарок
var userTooltipTimer        = null;
var userTooltipOverInterval = 500;
var userTooltipOutInterval  = 500;
var userTooltip             = null;
var tooltipUserPics         = [];

function userTooltipShow (email,online,pr,date,vip,img,is) {
    if (!is)  {
        hideNewGifts();
        clearTolltipTimer();
        tooltipUserPics[email] = img;
        userTooltipTimer = setTimeout("userTooltipShow('"+email+"','"+online+"','"+pr+"','"+date+"','"+vip+"',0,1)", userTooltipOverInterval);
        return;
    }
    var ut, login, domain;
    img = tooltipUserPics[email];

    if (!(ut = document.getElementById('utMega'))) return;
    var re = /^(.*?)@/;
    if (re.test(email)) login = RegExp.$1;
    re = /@(.*?)\./;
    if (re.test(email)) domain = RegExp.$1;

    var name= document.getElementById(email + '_name').innerHTML;

    var prneed = '';
    if (pr) {
        if(vip) prneed = "Приватный VIP-стикер";
        else prneed = "Приватный стикер";
    }
    else {
        if(vip) prneed = "VIP-стикер от пользователя";
        else prneed = "Стикер от пользователя";
    }

    if (0 || !pr) {
        var main = "<img src='http://avt.foto.mail.ru/" + domain + "/" + login + "/_avatarsmall'/> <div><a href=\"http://www.mail.ru/agent?message&to=" + email + "\" title=\"Щелкни, чтобы пообщаться с этим человеком в Mail.Ru Агенте\"><img width=\"9\" height=\"9\" valign=\"absmiddle\" src=\"http://status.mail.ru/?" + email + "&amp;9x9\" alt=\"Щелкни, чтобы пообщаться с этим человеком в Mail.Ru Агенте\" class=\"mr3\"/></a> <a href=\"http://otvet.mail.ru/" + domain + "/" + login + "/\">" + name + "</a></div>";
    }
    else var main = "";

    ut.innerHTML = '<div class=\"orange lh11 t95 mb3\"><b>' + prneed + '</b></div>' + main;
    ut.className = "utMegaS";

    var nn = navigator.userAgent.toLowerCase();
    ut.style.display = 'block';
    ut.onmouseover = clearTolltipTimer;
    ut.onmousemove = clearTolltipTimer;
    ut.onmouseout = function() {
    userTooltipHide(email,online,pr,date,vip);
    }
}

function hideNewGifts(){
    clearTimeout(showNewGiftsTimer);
}

function clearTolltipTimer() {
    clearTimeout(userTooltipTimer);
    userTooltipTimer = null;
}

// Скрытие подсказки, кто дарил подарок
function userTooltipHide(email,online,pr,date,vip,is) {
    if (!tooltipUserPics[email]) return;
    if (!is) {
        clearTolltipTimer();
        userTooltipTimer = setTimeout("userTooltipHide('"+email+"','"+online+"','"+pr+"','"+date+"','"+vip+"',1)", userTooltipOutInterval);
        return;
    }
    var ut = document.getElementById('utMega');
    if (ut)  ut.style.display = 'none';
    showManyGifts();
}








