var isIE = (navigator.userAgent.indexOf("MSIE") != -1) ? true : false;
var ie5 = (navigator.userAgent.indexOf("MSIE 5") != -1) ? true : false;
var ie6 = (navigator.userAgent.indexOf("MSIE 6") != -1) ? true : false;
var ie7 = (navigator.userAgent.indexOf("MSIE 7") != -1) ? true : false;
var ie8 = (navigator.userAgent.indexOf("MSIE 8") != -1) ? true : false;

var isFF = (navigator.userAgent.indexOf("Firefox") != -1) ? true : false;
var ff1 = (navigator.userAgent.indexOf("Firefox/1") != -1) ? true : false;
var ff2 = (navigator.userAgent.indexOf("Firefox/2") != -1) ? true : false;

var op9 = (navigator.userAgent.indexOf("Opera/9") != -1) ? true : false;

	// ========== Превью-листы на морде =========
function definePermitWidth() {
	var winWidth = screenSize().w <= 1024 ? 720 : parseInt(screenSize().w * 0.9 * 0.73);
	return winWidth;
}



//"На сервисе Фото@Mail.Ru мы вводим новую систему оценок фото. Вместо пятибалльной шкалы вводится трёхбалльная, со значениями от +1 до +3. <br /><br /> Теперь рейтинг фото измеряется не средним баллом, а общим количеством выставленных баллов. <br /><br /> Баллы за работу считаются простым арифметическим сложением. Подробнее с системой голосования вы можете ознакомится <a href=\"/catalog/static/vote.html\" target=\"_blank\">здесь<\/a>"

// ========= AJAX-switcher метки/категории ==========
var f2_id_num;
function f2_cloudoftags(f2_id_num)
{
	var a = 1;
	while (a < 3) //сдесь условием а<3 мы задаем сколько у нас сейчас закладок, в данном случае 2
	{
		gebi('f2_choose'+a).style.display='none';
		gebi('f2_choose'+a+a).style.background='url(http://img.mail.ru/r/foto2/cloud_bg_8bit.png) 100% -40px';
		gebi('f2_choose'+a+a).style.zIndex= 9 - f2_id_num;
		gebi('f2_choose'+a+a+a).className = "cloud1";
		gebi('f2_choose'+a+a+a+a).style.display='none';
		a++;
	}
	gebi('f2_choose'+f2_id_num).style.display='inline';
	gebi('f2_choose'+f2_id_num+f2_id_num).style.background='url(http://img.mail.ru/r/foto2/cloud_bg_8bit.png) 100% 0px';
	gebi('f2_choose'+f2_id_num+f2_id_num).style.zIndex='10';
	gebi('f2_choose'+f2_id_num+f2_id_num+f2_id_num).className = "cloud2";
	gebi('f2_choose'+f2_id_num+f2_id_num+f2_id_num+f2_id_num).style.display='block';
}
// ======== /AJAX-switcher метки/категории ==========

// ============= DHTML gallery-s thumbnails  =============
var f2_location;
var f2_showinfo = 1;
var f2_activeuseremail;
var f2_currentMyHost;
var f2_thumbsINrow = 9;
var f2_clientwidth = 0;
var f2_time = 0;

function f2_enable_dropdown_usermenu(emailz) { f2_showinfo = 1; f2_activeuseremail = emailz; }

function f2_creatediv(f2_name) // создаем пустые DIV-ы для последующего набивания превьюшками;
{
	var f2_start = 0;
	document.write('<div class=\"f2_gallery\"><div style=\"float:left;clear:both;width:2500px\">');
	while(f2_start < f2_thumbsINrow) {document.write('<div class=\"f2_block\" id=\"'+f2_name+f2_start+'\"><\/div>');f2_start++;}
	document.write('<\/div><\/div>');
	f2_createcontent(f2_name);
}

function f2_createcontent(f2_rname)
{
	var f2_clientwidth = document.body.clientWidth;
	var mname;
	var f2_counter = 0;
	var f2_clear = 1;	
	
	var f2_photoblockwidth = f2_clientwidth - f2_clientwidth*0.1;
	if (f2_photoblockwidth <= 984) { f2_photoblockwidth = 984; f2_clientwidth = 1093; }
	f2_photoblockwidth = f2_photoblockwidth - 264; // получаем ширину content_block
	var f2_howmanyblocks = parseInt(f2_photoblockwidth / 130);
	var f2_margins = f2_photoblockwidth - (f2_howmanyblocks) * 120;
	f2_margins = Math.round(f2_margins / (f2_howmanyblocks - 1));
	
	if (f2_rname == 'f2_Srow2_' || f2_rname == 'f2_Srow1_') { mname = f2_sms; }
	if (f2_rname == 'f2_Brow2_' || f2_rname == 'f2_Brow1_') { mname = f2_best; }
	if (f2_rname == 'f2_Nrow2_' || f2_rname == 'f2_Nrow1_') { mname = f2_new; }

	while (f2_counter < f2_howmanyblocks)
	{	
		if (f2_rname == 'f2_Srow2_' || f2_rname == 'f2_Brow2_' || f2_rname == 'f2_Nrow2_') {var f2_target = 0; f2_target = f2_counter + f2_howmanyblocks;} else {var f2_target = f2_counter;}
		if (gebi(f2_rname+f2_counter)) 
		{	
			if (f2_showinfo==1) { var f2_work = "<span class=\"user-info-menu\" onclick=\"return f2_userInfo('"+mname[f2_target*6+3]+"', this,event,'"+mname[f2_target*6+5]+"');\"><img src=\"http://img.mail.ru/0.gif\" class=\"ico_dropdown\" \/><\/span>"; } else { var f2_work = '';}
			gebi(f2_rname+f2_counter).style.marginRight = f2_margins+'px';		
			gebi(f2_rname+f2_counter).innerHTML = '<a href=\"'+mname[f2_target*6]+'\" style=\"background-image: url('+mname[f2_target*6+1]+');\" class=\"f2_thumb\"><img src=\"'+mname[f2_target*6+1]+'\" class=\"f2_hiddenimg\" /><\/a><a href=\"'+mname[f2_target*6]+'\" class=\"f2_title\">'+mname[f2_target*6+2]+'<\/a><br /><a href=\"http://www.mail.ru/agent?message&amp;to='+mname[f2_target*6+3]+'\"><img src=\"http://status.mail.ru/?'+mname[f2_target*6+3]+'\" class=\"f2_ico\" style=\"margin-right:5px;\" /><\/a><a href=\"'+mname[f2_target*6+5]+'\" class=\"f2_author\" style=\"margin-right:5px; margin-left:0;\">'+mname[f2_target*6+4]+'<\/a>'+f2_work+'<\/div>';
		}
	f2_counter++;
	}
}
function f2_refreshcontent()
{
	if (gebi('f2_Srow1_8')) {f2_createcontent('f2_Srow1_');}
	if (gebi('f2_Srow2_8')) {f2_createcontent('f2_Srow2_');}
	if (gebi('f2_Brow1_8')) {f2_createcontent('f2_Brow1_');}
	if (gebi('f2_Brow2_8')) {f2_createcontent('f2_Brow2_');}
	if (gebi('f2_Nrow1_8')) {f2_createcontent('f2_Nrow1_');}
}
// ============= /DHTML gallery-s thumbnails  =============

// MainPage photos thumbnails dropdown usermenu - Показываем ДИВ с юзеринфо
var f2_userpath;
var f2_hideSELFinfo;
var f2_userCashe;
function f2_userInfo( _email, a, evt, f2_userpath, f2_userInfo_popup)
{
	if (f2_userInfo_popup && f2_userInfo_popup != 'undefined')
	{
		if (f2_userInfo_popup == true) var f2_userInfo_targetPath = ' target="_blank"';
		else var f2_userInfo_targetPath = '';
	}
	else if (!f2_userInfo_popup || f2_userInfo_popup == 'undefined') {var f2_userInfo_targetPath = '';}


	cancelBubbling(evt);
	var mail = _email;
	var re = /(.*?)@(.*?)\./;
	var perlhost=VideoPerlHost();
	var imaginehost=VideoImagineHost();
		
	re.exec(mail);
	var login = RegExp.$1;
	var domain = RegExp.$2;
	var infoDiv;
	if (!gebi("infoDivId"))
	{
		var div = document.createElement("div");
		div.id = "infoDivId";
		div.className = "userInfoDiv";
		div.style.top = "0px";
		div.style.left = "0px";
		div.style.position = "absolute";
		div.style.display = "none";
		document.body.appendChild(div);
	}
	if (mail==f2_activeuseremail) { f2_hideSELFinfo = 1; } else { f2_hideSELFinfo = 0; }

	infoDiv = gebi('infoDivId');
	if (infoDiv.style.display != "none" && f2_userCashe == a)
	{
		infoDiv.style.display = "none";
		return false;
	}
	f2_userCashe = a;

	// Выключает строчку, если не IE
	var mailagent_link = window.attachEvent ? '<a class="grey" href="http://www.mail.ru/agent?message&to=' + mail + '&from=foto"><img class="sobaka" src="http://status.mail.ru/?' + mail + '" width="13" height="13" border="0" align="absmiddle" /><\/a><a class="grey" href="http://www.mail.ru/agent?message&to=' + mail + '&from=foto">Добавить в Mail.Ru Агент<\/a><br />' : '';

	infoDiv.innerHTML = '' +
	'<table border="0" cellspacing="0" cellpadding="0"><tr valign="middle">' +
	'<td class="f2_useravatar_td"><a href="' + f2_userpath + '" class="f2_useravatar"' + f2_userInfo_targetPath + '><img src="http://avt.foto.mail.ru' + f2_userpath + '_avatar" /><\/a><\/td>' +
	'<td width="5">&nbsp;<\/td>' +
	'<td>' +
	'<a class="orange t100" href="http://my.mail.ru' + f2_userpath + '"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/r/foto2/ico_my.gif" width="16" height="16" border="0" align="absmiddle" /><\/a><a class="orange t100" href="http://my.mail.ru' + f2_userpath + '"' + f2_userInfo_targetPath + '>Мир<\/a><br />' +
	'<a class="orange t100" href="http://blogs.mail.ru' + f2_userpath + '"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/r/foto2/ico_blogs2.gif" width="16" height="16" border="0" align="absmiddle" /><\/a><a class="orange t100" href="http://blogs.mail.ru' + f2_userpath + '"' + f2_userInfo_targetPath + '>Блог<\/a><br />' +
	'<a class="orange t100" href="http://foto.mail.ru' + f2_userpath + '"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/r/foto2/ico_foto2.gif" width="16" height="16" border="0" align="absmiddle" /><\/a><a class="orange t100" href="http://foto.mail.ru' + f2_userpath + '"' + f2_userInfo_targetPath + '>Фото<\/a><br />' +
	'<a class="orange t100" href="http://video.mail.ru' + f2_userpath + '"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/r/foto2/ico_video.gif" width="16" height="16" border="0" align="absmiddle" /><\/a><a class="orange t100" href="http://video.mail.ru' + f2_userpath + '"' + f2_userInfo_targetPath + '>Видео<\/a><br />' +
	'<\/td>' +
	'<\/tr><\/table>' +
	'<a href="http://' + perlhost + '/cgi-bin/photo/rating_all?sort=rate&email=' + mail + '"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/r/foto2/ico_best.gif" width="16" height="16" border="0" align="absmiddle" /><\/a><a href="http://' + imaginehost + '/cgi-bin/photo/rating_all?sort=rate&email=' + mail + '"' + f2_userInfo_targetPath + '>Лучшие ролики<\/a><br />' +
	'<a href="http://' + perlhost + '/cgi-bin/photo/phototag?tag=' + mail + '"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/r/foto2/marking.gif" width="16" height="16" border="0" align="absmiddle" /><\/a><a href="http://' + (f2_hideSELFinfo == 1 ? perlhost : imaginehost)  + '/cgi-bin/photo/tag?email=' + mail + '"' + f2_userInfo_targetPath + '>Посмотреть метки<\/a><br />' +
	'<a href="http://' + imaginehost + f2_userpath + 'rss"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/r/foto2/ico_rss.png" width="16" height="16" border="0" align="absmiddle" /><\/a><a href="http://' + imaginehost + f2_userpath + 'rss"' + f2_userInfo_targetPath + '>Поток rss<\/a><br />' +
	(f2_hideSELFinfo == 1 ? '' : ('<a href="http://my.mail.ru/my/invitation?single=1&email=' + mail + '"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/r/foto2/ico_addfriend.gif" width="16" height="16" border="0" align="absmiddle" ><\/a><a href="http://my.mail.ru/my/invitation?single=1&email=' + mail + '"' + f2_userInfo_targetPath + '>Добавить в друзья<\/a><br />')) +
	(f2_hideSELFinfo == 1 ? '' : ('<a href="#" onclick="ajax_call(\'perl_add_subscription\',\'' + mail + '\',f2_AddSubscriptionCallback)"><img src="http://img.mail.ru/r/foto2/ico_posts_subscribe.gif" width="16" height="16" border="0" align="absmiddle" /><\/a><a href="#" onclick="ajax_call(\'perl_add_subscription\',\'' + mail + '\',f2_AddSubscriptionCallback)">Подписаться на обновления<\/a><br />')) +
	'<div class="line"><br /><\/div>' +
	(f2_hideSELFinfo == 1 ? '' : mailagent_link) +
	(f2_hideSELFinfo == 1 ? '' : ('<a href="http://my.mail.ru/my/dialogues?thread=' + mail + '"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/r/my/send.gif " width="16" height="16" border="0" align="absmiddle" ><\/a><a href="http://my.mail.ru/my/dialogues?thread=' + mail + '"' + f2_userInfo_targetPath + '>Написать сообщение<\/a><br />')) +
	(ActiveDir() != '' ? (f2_hideSELFinfo == 1 ? '' : ('<a href="http://my.mail.ru'+ActiveDir()+'gifts?send=' + mail + '"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/mail/ru/images/my/send_gift2.gif" width="16" height="16" border="0" align="absmiddle" ><\/a><a href="http://my.mail.ru'+ActiveDir()+'gifts?send=' + mail + '"' + f2_userInfo_targetPath + '>Отправить подарок<\/a><br />')) : "" ) +
	'<a class="grey" href="http://win.mail.ru/cgi-bin/sentmsg?To=' + mail + '&from=foto"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/r/foto2/ico_write.gif" width="18" height="17" border="0" align="absmiddle" /><\/a><a class="grey" href="http://win.mail.ru/cgi-bin/sentmsg?To=' + mail + '&from=foto"' + f2_userInfo_targetPath + '>Написать письмо<\/a><br />' +
	'<a class="grey" href="http://cards.mail.ru/rnd_card.html?rcptemail=' + mail + '&from=foto"' + f2_userInfo_targetPath + '><img src="http://img.mail.ru/r/foto2/ico_cards.gif" width="16" height="16" border="0" align="absmiddle" /><\/a><a class="grey" href="http://cards.mail.ru/rnd_card.html?rcptemail=' + mail + '&from=foto"' + f2_userInfo_targetPath + '>Отправить открытку<\/a><br />';

	infoDiv.style.display = '';
	if (a.nodeName == 'A' && a.firstChild.nodeName == 'IMG') a = a.firstChild;
	if (a.nodeName == 'IMG') a = a;

	var xRem = yRem = 0;
	if (screenSize().w - absPosition(a).x < 300) {
		xRem = infoDiv.offsetWidth - a.offsetWidth;
		xRem = xRem < 0 ? 0 : xRem;
	}
	if (screenSize().h - absPosition(a).y + defScroll().y < infoDiv.offsetHeight) {
		yRem = infoDiv.offsetHeight + a.offsetHeight + 2;
	} else yRem = -2;

	infoDiv.style.left = (absPosition(a).x - xRem) + 'px';

	if (f2_userInfo.arguments[3]) yRem = 0;//если есть 4й аргумент
	infoDiv.style.top = (absPosition(a).y + a.offsetHeight - yRem) + 'px';

	addHandler(gebi('infoDivId'), 'click', function(evt) {
		var evt = evt || window.event;
		if (evt.button == 0) f2_hideUserInfo();//убирать див только по левому клику
	});

	return false;
}

// MainPage photos thumbnails dropdown usermenu Скрываем ДИВ с юзеринфо
function f2_hideUserInfo() {
	if (gebi('infoDivId')) gebi('infoDivId').parentNode.removeChild(gebi('infoDivId'));//gebi("infoDivId").style.display = "none";
}






addHandler(document, 'click', function(evt) {
	var evt = evt || window.event; 
	if (evt.button == 0) f2_hideUserInfo() ;//убирать див только по левому клику
	});

//MainPage photos thumbnails dropdown usermenu on error
function f2_AddSubscriptionCallback(st,errorcode,errortext) {
	if (st==1) {
		alert('Подписка добавлена');
	} else {
		alert('Организовать подписку не получилось: '+errortext);
		return false;
	}	
	f2_hideUserInfo();
}

//End of MainPage photos thumbnails dropdown usermenu

// ============= AJAX-switcher альбомы  =============
function albumSwitcher(vis, a) {
	var method = "POST";
	var url = "album.php";
	var params = "id=" + vis;
	var onload = albumSwitshHandler;
	var onerror = albumSwitshError;
	showHandleMessage(
		"Запрос обрабатывается",
		absPosition(a).x,
		absPosition(a).y + 20
	);
	return setAjaxRequest(method, url, params, onload, onerror);
}
function albumSwitshHandler() {
	var code = this.req.responseText;
	if (code == "error") bookmarkSwitshError();
	else {
		gebi("commonAlbumId").style.display = gebi("commonAlbumId").style.display == "none" ? "" : "none";
		gebi("specialAlbumId").style.display = gebi("specialAlbumId").style.display == "none" ? "" : "none";
		hideHandleMessage();
		gebi("albumListId").innerHTML = code;
	}
}
function albumSwitshError() {
	showHandleMessage("При обработке запроса произошла ошибка.<br>Повторите попытку снова.");
}
// ============ /AJAX-switcher альбомы  =============

// ========== Информация о пользователе =============
// Скрываем ДИВ с юзеринфо
function hideUserInfo() {
	if (gebi("infoDivId")) gebi("infoDivId").style.display = "none";
}
addHandler(document, 'click', function(evt) {
	var evt = evt || window.event; 
	if (evt.button == 0) hideUserInfo() ;//убирать див только по левому клику
	});
// ========= /Информация о пользователе =============

function f1_AddSubscriptionCallback(st,errorcode,errortext) {
	if (st==1) {
		alert('Подписка добавлена');
	} else {
		alert('Организовать подписку не получилось: '+errortext);
		return false;
	}
	hideUserInfo();
}

// =========== Изменить название фото ===============
// Показываем форму для смены имени
var f2_elementID;
var strForNewFotoName;
function showFotoNameDialog(id, el, cat) {
	f2_elementID = el;
	gebi(f2_elementID).style.display = "none";
	gebi("foto" + cat + "Id").style.display = "";
	//gebi("foto" + cat + "FormId").elements[0].value = objForNewFotoName.firstChild.nodeValue;
	gebi("foto" + cat + "FormId").elements[1].value = id;
}
// Проверка количества введенных символов
function checkLength(textarea, limit, showId) {
	limit = parseInt(limit);
	var b = document.getElementById(showId);
	if (textarea.value.length <= limit) {
		b.innerHTML = limit - textarea.value.length;
	} else {
		b.innerHTML = 0;
		textarea.value = textarea.value.substring(0, limit);
	}
}
// Скрываем форму для смены имени
function hideFotoNameDialog(el, cat) {
	f2_elementID = el;
	gebi("foto" + cat + "Id").style.display = "none";
	gebi(f2_elementID).style.display = "";
}
// Обработка сабмита новоги имени
function newFotoCommentCallback (newname,imageid) {
	if (imageid) {
		if (newname == undefined || newname == null || newname == '') {
			newname = 'Нет описания';
		}
		gebi('imageComment').innerHTML = '<a id="imageCommentSpan" href="#" onclick="return false;">' + str_replace("\n","<br>",newname) + '<\/a>';
		hideFotoNameDialog('imageComment', 'Description');
	} else {
		alert ('Ошибка');
	}
}
function newFotoNameCallback (newname,imageid) {
	if (imageid) {
		if (newname == undefined || newname == null || newname == '') {
			newname = 'Без названия';
		}
		gebi('f2_albumdescr1').innerHTML = '<span id="imageNameSpan" onmouseover="colorNSpavOver(this, 1)" onmouseout="colorNSpavOut(this, 1)">' + newname + '<\/span>';
		gebi('path_image_title').innerHTML = newname;
		hideFotoNameDialog('f2_albumdescr1', 'Name');
	} else {
		alert ('Ошибка');
	}
}
function submitNewFotoName(form) {
	var info = form.elements[0].value;
	var image_id = form.elements[1].value;
	var album_id = form.elements[2].value;
	var st=ajax_call('perl_change_image_name',image_id,album_id,info,newFotoNameCallback);
	/*if (info.length > 0) { // новое имя всё-таки ввели
		var st=ajax_call('perl_change_image_name',image_id,album_id,info,newFotoNameCallback);
	} else { // В форму пустая строка
		alert("Вы не ввели текст.");
		return false;
	}*/
}
function changeAlbumCommentCallback(comment) {
	if (comment == undefined || comment == null || comment == '') {
		comment='Нет описания';
	}
	gebi('albumCommentSpan').innerHTML = str_replace("\n","<br>",comment) + '<br />';
	gebi('albumDescriptionFormId').elements['comment'].value = comment;
	gebi('albumDescriptionFormId').elements['hidden_comment'].value = comment;
	gebi('albumDescriptionId').style.display = 'none';
	gebi('albumCommentSpanOver').style.display = '';
}

function changeImageNameCallback(name,id) {
	gebi('change_name_form_'+id).elements['title'].value=name;
		if(name == undefined || name == null || name == ''){
		name='Без названия';
		}
		gebi('inameSpan_'+id).innerHTML = name;
	gebi('change_name_'+id).style.display='none';
	gebi('name_'+id).style.display='';
}

function changeAlbumNameCallback(name) {
	gebi('albumNameFormId').elements['edit'].value = name;
	if(name == undefined || name == null || name == ''){
		name='Без названия';
	}
	gebi('anameSpan').innerHTML = name;
	if (document.getElementById('pathAName')) {
		gebi('pathAName').innerHTML = name;
	}
	gebi('albumNameId').style.display='none';
	gebi('aname').style.display='';
}

function submitNewFotoComment(form) {
	var info = form.elements[0].value;
	var image_id = form.elements[1].value;
	var album_id = form.elements[2].value;
	var st=ajax_call('perl_change_image_comment',image_id,album_id,info,newFotoCommentCallback);
	/*if (info.length > 0) { // новое имя всё-таки ввели
		var st=ajax_call('perl_change_image_comment',image_id,album_id,info,newFotoCommentCallback);
	} else { // В форму пустая строка
		alert("Вы не ввели текст.");
		return false;
	}*/
}
// Обработка ответа на запрос
function newNameHandler() {
	var code = this.req.responseText;
	if (code == "error") newNameError();
	else {
		objForNewFotoName.firstChild.nodeValue = strForNewFotoName;
		hideFotoNameDialog();
		hideHandleMessage();
	}
}
// Обработка ошибки при запросе
function newNameError() {
	showHandleMessage("<span style=\"color:#F26D00;\">При обработке запроса произошла ошибка.<br />Повторите попытку снова.<\/span>");
}
// ========== /Изменить название фото ===============

// ========= Изменить название фото: II =============
var objForNewFotoNameUnic = {};
var strForNewFotoNameUnic = {};
// Инициализация mouseover/mouseout
function initFotoNameOverOut() {
	var spans = document.getElementsByTagName("span");
	var span;
	for (var i = 0; i < spans.length; i++) {
		if (spans[i].className != "n") continue;
		span = spans[i];
		var ua = navigator.userAgent.toLowerCase();
		var isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1); 
		span.onmouseover = colorNSpavOver;
		span.onmouseout = colorNSpavOut;
	}
}
function colorNSpavOver(el, flag) {
	if (flag) el.style.backgroundColor = "#FFFF66";
	else this.style.backgroundColor = "#FFFF66";
}
function colorNSpavOut(el, flag) {
	if (flag) el.style.backgroundColor = "transparent";
	else this.style.backgroundColor = "transparent";
}
// Показываем форму для смены имени
function showFotoNameDialog2(id, el) {
	objForNewFotoNameUnic[id] = el;
	var parent = el.parentNode;
	while (parent.nodeType != 1) parent = parent.parentNode;
	var fotoNameDiv;
	if (!gebi("fotoNameDivId" + id))  {
		var div = document.createElement("div");
		div.id = "fotoNameDivId" + id;
		div.className = "name";
		div.style.display = "none";
		parent.parentNode.insertBefore(div, parent);
	}
	var charLimit = 32;
	fotoNameDiv = gebi("fotoNameDivId" + id);
	fotoNameDiv.innerHTML = "<form action=\"\" method=\"post\" onsubmit=\"return submitNewFotoName2(this);\">\
		<div class=\"name_edit\">\
			<textarea rows=\"1\" cols=\"1\">" + el.firstChild.nodeValue + "<\/textarea>\
			<input type=\"hidden\" name=\"id\" value=\"" + id + "\">\
			<div class=\"ok\"><input type=\"submit\" value=\"OK\" /><\/div>\
			<div class=\"cancel\"><input onclick=\"hideFotoNameDialog2('" + id + "')\" type=\"button\" value=\"Отмена\" /><\/div>\
		<\/div>\
		<\/form>";
	parent.style.display = "none";
	fotoNameDiv.style.display = "";
}
// Скрываем форму для смены имени
function hideFotoNameDialog2(id) {
	if (!gebi("fotoNameDivId" + id)) return;
	if (typeof objForNewFotoNameUnic[id] == "undefined") return;
	gebi("fotoNameDivId" + id).style.display = "none";
	var parent = objForNewFotoNameUnic[id].parentNode;
	while (parent.nodeType != 1) parent = parent.parentNode;
	parent.style.display = "";
}
// Обработка сабмита новоги имени
function submitNewFotoName2(form) {
	var info = form.elements[0].value;
	var id = form.elements[1].value;
	if (info.length > 0) { // новое имя всё-таки ввели
		strForNewFotoNameUnic[id] = info;
		var method = "POST";
		var url = "newname2.php";
		var params = "id=" + id + "&newname=" + info;
		var onload = newNameHandler2;
		var onerror = newNameError2;
		showHandleMessage(
			"Запрос обрабатывается",
			absPosition(form).x,
			absPosition(form).y + 20
		);
		return setAjaxRequest(method, url, params, onload, onerror);
	} else { // В форму пустая строка
		alert("Вы не ввели новое название ролика.");
		return false;
	}
}
// Обработка ответа на запрос
function newNameHandler2() {
	var code = this.req.responseText;
	if (code == "error") newNameError2();
	else if (typeof objForNewFotoNameUnic[code] == "undefined") newNameError2();
	else {
		objForNewFotoNameUnic[code].firstChild.nodeValue = strForNewFotoNameUnic[code];
		hideFotoNameDialog2(code);
		hideHandleMessage();
	}
}
// Обработка ошибки при запросе
function newNameError2() {
	showHandleMessage("<span style=\"color:#F26D00;\">При обработке запроса произошла ошибка.<br />Повторите попытку снова.<\/span>");
}
// ========== /Изменить название фото ===============

// ========== Изменить название альбома =============
// Показываем форму для смены названия альбома
var objForNewAlbumName = [];
var strForNewAlbumName;
function showAlbumNameDialog(id, el, cat) {
	if (objForNewAlbumName.parentNode) hideAlbumNameDialog();
	objForNewAlbumName = el;
	objForNewAlbumName.parentNode.style.display = "none";
	gebi("album" + cat + "Id").style.display = "";
	gebi("album" + cat + "FormId").elements[0].value = el.firstChild.nodeValue;
	gebi("album" + cat + "FormId").elements[1].value = id;
}
// Скрываем форму для смены имени
function hideAlbumNameDialog() {
	gebi("albumNameId").style.display = "none";
	gebi("albumDescriptionId").style.display = "none";
	objForNewAlbumName.parentNode.style.display = "";
}
// Обработка сабмита новоги имени
function submitNewAlbumName(form) {
	var info = form.elements[0].value;
	var id = form.elements[1].value;
	if (info.length > 0) { // новое имя всё-таки ввели
		strForNewAlbumName = info;
		var method = "POST";
		var url = "newname.php";
		var params = "id=" + id + "&newname=" + info;
		var onload = newAlbumNameHandler;
		var onerror = newAlbumNameError;
		showHandleMessage(
			"Запрос обрабатывается",
			absPosition(form).x,
			absPosition(form).y + 20
		);
		return setAjaxRequest(method, url, params, onload, onerror);
	} else { // В форму пустая строка
		alert("Вы не ввели новое название ролика.");
		return false;
	}
}
// Обработка ответа на запрос
function newAlbumNameHandler() {
	var code = this.req.responseText;
	if (code == "error") newAlbumNameError();
	else {
		objForNewAlbumName.firstChild.nodeValue = strForNewAlbumName;
		hideAlbumNameDialog();
		hideHandleMessage();
	}
}
// Обработка ошибки при запросе
function newAlbumNameError() {
	showHandleMessage("<span style=\"color:#F26D00;\">При обработке запроса произошла ошибка.<br />Повторите попытку снова.<\/span>");
}
// ========== /Изменить название альбома ============

// ====== Показываем состояние AJAX-запроса =========
// Показываем подсказку, что запрос обрабатывается
function showHandleMessage(html, x, y) {
	var mesDiv;
	if (!gebi("mesDivId"))  {
		var div = document.createElement("div");
		div.id = "mesDivId";
		div.className = "ajaxTooltip";
		div.style.top = "0px";
		div.style.left = "0px";
		div.style.display = "none";
		document.body.appendChild(div);
	}
	mesDiv = gebi("mesDivId");
	mesDiv.innerHTML = "<a onclick=\"return hideHandleMessage();\" href=\"\">\
			<img src=\"http://img.mail.ru/r/foto2/ico_close.gif\" width=\"7\" height=\"7\" style=\"float:right\" alt=\"Закрыть\" />\
		<\/a>";
	mesDiv.innerHTML += html;
	if (x) mesDiv.style.left = x + "px";
	if (y) mesDiv.style.top  = y + "px";
	mesDiv.style.display = "";
	return false;
}
// Скрываем подсказку, что запрос обрабатывается
function hideHandleMessage() {
	gebi("mesDivId").style.display = "none";
	return false;
}
// ====== /Показываем состояние AJAX-запроса ========

// ========== Размещение в блоге/на сайте ===========
// Показать ДИВ с размещением
function showDistribDiv(evt, a, code) {
	cancelBubbling(evt);
	hideDistribDiv();
	if (!gebi("distDivCode"))  {
		var div = document.createElement("div");
		div.id = "distDivCode";
		div.className = "distDiv";
		div.style.top = "0px";
		div.style.left = "0px";
		div.style.zIndex = 3;
		div.style.display = "none";
		document.body.appendChild(div);
	}
	var distDiv = gebi("distDivCode");
	distDiv.innerHTML = code;
	distDiv.style.top = (absPosition(a).y + a.offsetHeight) + "px";
	distDiv.style.left = absPosition(a).x + "px";
	distDiv.onclick = cancelBubbling;
	distDiv.style.display = "block";
}
// Скрыть ДИВ с размещением
function hideDistribDiv() {
	if (gebi("distDivCode")) gebi("distDivCode").style.display = "none";
}
// Разместить на сайте
function distribInSite(evt, a, type) {
	var insert = "";
	if (type == "url" && typeof fotoI != "indefined") insert = fotoI;
	else if (type == "bb" && typeof fotoBB != "indefined") insert = fotoBB;
	else insert = fotoNothing;
	var code = "<div><a onclick=\"hideDistribDiv(); return false;\" href=\"#\"><img src=\"http://img.mail.ru/r/foto2/ico_close.gif\" style=\"margin-bottom:7px;float:right;\"><\/a><br />\
		Вы можете скопировать этот код на свою страницу.<br />\
		<img src=\"http://img.mail.ru/0.gif\" width=\"1\" height=\"5\" /><br />\
		<img src=\"http://img.mail.ru/0.gif\" width=\"1\" height=\"5\" /><br />\
		<form><input id=\"areaForLink\" onclick=\"gebi('areaForLink').select();\" onmouseover=\"removeHandler(document, 'click', hideDistribDiv);\" onmouseout=\"addHandler(document, 'click', hideDistribDiv);\" value='" + insert + "' style=\"width:100%;\" /><\/form><\/nobr>\
	<\/div>";
	showDistribDiv(evt, a, code);
	gebi("areaForLink").focus();
	gebi("areaForLink").select();
	return false;
}
// Выбрать вариант кода для размещения на сайте
function setSiteDistribCode() {
	if (!gebi("areaForLink")) return;
	var area = gebi("areaForLink");
	area.value = fotoNothing;
}
addHandler(document, 'click', hideDistribDiv);
// ========= /Размещение в блоге/на сайте ===========

// =========== AJAX: Редактирование меток ===========
// Показываем форму для редактирования меток
function showLabelsEditDiv() {
	var labelSpan = gebi("labelLinkListId");
	var div = gebi("editLabelsBlockId");
	div.style.top = (absPosition(labelSpan).y + labelSpan.offsetHeight) + "px";
	div.style.left = absPosition(labelSpan).x + "px";
	div.style.display = "";
	return false;
}
// Скрываем форму для редактирования меток
function hideLabelsEditDiv() {
	if (gebi("editLabelsBlockId")) gebi("editLabelsBlockId").style.display = "none";
	return false;
}
// Запрос на обновление списка меток
function editLabelsRequest(form) {
	var method = "POST";
	var url = "labeList.php";
	var params = "list=" + form.elements[0].value;
	var onload = labelUpdateHandler;
	var onerror = labelUpdateError;
	showHandleMessage(
		"Запрос обрабатывается",
		absPosition(form).x,
		absPosition(form).y + 20
	);
	return setAjaxRequest(method, url, params, onload, onerror);
}
// Обработка ответа
function labelUpdateHandler() {
	hideLabelsEditDiv();
	if (this.req.responseXML) {
		hideHandleMessage();
		var xml = this.req.responseXML.firstChild;
		if (xml.nodeType != 1) xml = xml.nextSibling; // fix for Opera
		var labels = this.req.responseXML.getElementsByTagName('label');
		var code = "";
		for (var i = 0; i < labels.length; i++) {
			if (labels[i].firstChild) code += "<a class=\"additional\" href=\"" + labels[i].id + "\">" + labels[i].firstChild.nodeValue + "<\/a>&nbsp;&nbsp;";
		}
		gebi("labelLinkListId").innerHTML = code ? code : "У ролика нет ни одной метки";
	} else {
		labelUpdateError();
	}
}
// Обработка ошибки при запросе
function labelUpdateError() {
	showHandleMessage("<span style=\"color:#F26D00;\">При обработке запроса произошла ошибка.<br>Повторите попытку снова.<\/span>");
}
// Добавление метки из списка
function addLabel(label, id) {
	var textarea = gebi(id);
	var value = textarea.value;
	// Обрезаем концевые пробелы
	while (value != "" && value.charCodeAt(value.length - 1) == 32) {
		value = value.substring(0, value.length - 2);
	}
	textarea.value = value;
	if (textarea.value == "") textarea.value = label.firstChild.nodeValue;
	else if (textarea.value.charCodeAt(textarea.value.length - 1) == 44) textarea.value += " " + label.firstChild.nodeValue;
	else textarea.value += ", " + label.firstChild.nodeValue;
	return false;
}
// ========== /AJAX: Редактирование меток ===========

// ========= Изменение размеров фотографии ==========
function changeFotoSize(a) {
	var curSize = parseInt(a.firstChild.nodeValue);
	drawFotoSizeSelect(curSize);
	setCookie("fotosize", curSize);
	return false;
}
function drawFotoSizeSelect(curSize) {
	if (curSize == null) return;
	var img = gebi("centralImgId");
	img.src = urlForSize[curSize][0];
	img.style.width = urlForSize[curSize][1][0] + "px";
	img.style.height = urlForSize[curSize][1][1] + "px";
	var code = "";
	for (size in urlForSize) {
		if (curSize == size) code += size + "px ";
		else code += "<a onclick=\"return changeFotoSize(this);\" href=\"#\">" + size + "px<\/a> ";
	}
	gebi("spanForFotoSizeId").innerHTML = code;
}
// ======== /Изменение размеров фотографии ==========

// ============== Добавить в избранное ==============
// Показать ДИВ для добавления меток в избранное фото
function showAddToFavorites(a) {
	var div = gebi("addLabelsForFavorites");
	div.style.top = (absPosition(a).y + a.offsetHeight) + "px";
	div.style.left = absPosition(a).x + "px";
	div.style.display = "";
	return false;
}
// Скрыть ДИВ для добавления меток в избранное фото
function hideAddToFavorites() {
	gebi("addLabelsForFavorites").style.display = "none";

	return false;
}

var addedtofav=false;
function addToFavoritesCallback (st,errortext) {
    if (st==1) {
           addedtofav=true;
          
           alert ('Ролик добавлен в "Избранное"');
    } else {
    
	   alert ('Ошибка добавления в альбом "Избранное": '+errortext);
    }   
   	enableAddButton(); 
}	
	
function addToFavorites (image_id,album_id,tagstr) {
    if (addedtofav) {
	alert('Вы уже добавили ролик в "Избранное"');
	hideAddToFavorites();
  enableAddButton();
  
	return false;
    }
    disableAddButton();
    var st=ajax_call('perl_add_to_favorites',image_id,album_id,tagstr,addToFavoritesCallback);
    if (!st) {
	alert('Добавить в "Избранное" не получилось');
	enableAddButton();
    }	
    hideAddToFavorites();

    return false;
}

function disableAddButton() {
  document["addLabelsForFavoritesForm"]["add"].disabled=true;
  document["addLabelsForFavoritesForm"]["add"].value="Подождите...";
}

function enableAddButton() {
  document["addLabelsForFavoritesForm"]["add"].disabled=false;
  document["addLabelsForFavoritesForm"]["add"].value="Добавить";
}

// ============= /Добавить в избранное ==============

// ======= AJAX-switcher метки свои/избранные =======
function allTagsSwitcher(vis, a) {
	var method = "POST";
	var url = "allTags.php";
	var params = "id=" + vis;
	var onload = allTagsHandler;
	var onerror = allTagsError;
	showHandleMessage(
		"Запрос обрабатывается",
		absPosition(a).x,
		absPosition(a).y + 20
	);
	return setAjaxRequest(method, url, params, onload, onerror);
}
function allTagsHandler() {
	var code = this.req.responseText;
	if (code == "error") allTagsError();
	else {
		gebi("tagsOfMyFotoId").style.display = gebi("tagsOfMyFotoId").style.display == "none" ? "" : "none";
		gebi("tagsOfFavorFotoId").style.display = gebi("tagsOfFavorFotoId").style.display == "none" ? "" : "none";
		hideHandleMessage();
		gebi("PopularMark").innerHTML = code;
	}
}
function allTagsError() {
	showHandleMessage("При обработке запроса произошла ошибка.<br>Повторите попытку снова.");
}
// ====== /AJAX-switcher метки свои/избранные =======

// ==== Переключение закладок: выбор типа загрузки ===
// Отправить запрос для получения формы
function switchLoadBookmark(a, num) {
	var td, tr, node, tdCount =0, parent = a;
	while (parent.parentNode && parent.nodeName.toLowerCase() != "tr") {
		if (parent.nodeName.toLowerCase() == "td") td = parent;
		parent = parent.parentNode;
	}
	tr = parent;
	var i, j = 0, remJ;
	for (i = 0; i < tr.childNodes.length; i++) if (tr.childNodes[i].nodeType == 1) tdCount++;
	for (i = 0; i < tr.childNodes.length; i++) {
		if (tr.childNodes[i].nodeType != 1) continue;
		j++;
		node = tr.childNodes[i];
		if (j == 1) node.className = "l";
		else if (j == tdCount) node.className = "r";
		else if (node == td) {
			node.className = "act";
			remJ = j;
		} else if (j == remJ + 1) node.className = "aftact";
		else node.className = "pas";
	}
	if (typeof num != "undefined") {
		num = parseInt(num);
		globalLoadType = num;
		for (i = 1; i <= 5; i++) if(gebi('uploadFoto_' + i)){gebi('uploadFoto_' + i).style.display = i == num ? '' : 'none';};
	}
	return false;
}
// Выбор аватарки
var selectAvatarCurCell = null;
function selectAvatarSwitcher(num, a) {
	switchLoadBookmark(a);
	for (var i = 1; i <= 3; i++) {
		gebi("selectAvContId_" + i).style.display = (i == num) ? "" : "none";
	}
	return false;
}
// === /Переключение закладок: выбор типа загрузки ===

// ============ Скрытие/показ блока логина ===========
var loginBlockShow = false;
function loginBlockShowHide() {
	loginBlockShow = !loginBlockShow;
	gebi("BlockLogin").style.display = loginBlockShow ? "" : "none";
	gebi("LinkLogin").style.display = loginBlockShow ? "none" : "";
	gebi("brLoginId").style.display = loginBlockShow ? "none" : "";
	return false;
}
// =========== /Скрытие/показ блока логина ===========


// ================= Рейтинг фото ====================
function f2_highLight(f2_r)
{
var i = 1;
while (5 >= i) {gebi('f2_r'+i).style.background='#fff';gebi('f2_r'+i+i).style.color='#999';i++}
if (f2_r != 0) {gebi('f2_r'+f2_r).style.background='#14CE0F';gebi('f2_r'+f2_r+f2_r).style.color='#fff'}	
}

function highLightReit(a, ev, order) {
	var cell = a.parentNode;
	if (order == "+") {
		cell.className = ev == "over" ? "green" : "";
		while (cell.previousSibling && cell.previousSibling.nodeName.toLowerCase() != "th") {
		cell = cell.previousSibling;
			if (cell.nodeType == 1) {
				cell.className = ev == "over" ? "green" : "";
			}
		}
	} else if (order == "-") {
		cell.className = ev == "over" ? "red" : "";
		while (cell.nextSibling && cell.nextSibling.nodeName.toLowerCase() != "th") {
		cell = cell.nextSibling;
			if (cell.nodeType == 1) {
				cell.className = ev == "over" ? "red" : "";
			}
		}
	}
}
function fotoReitingVote(a, est, id) {
	a = a.parentNode.parentNode;
	var method = "POST";
	var url = "fotoReit2.php";
	var params = "id=" + id + "&estimate=" + est;
	var onload = fotoReitingVoteHandler;
	var onerror = fotoReitingVoteError;
	showHandleMessage(
		"Запрос обрабатывается",
		absPosition(a).x - 50,
		absPosition(a).y + 20
	);
	return setAjaxRequest(method, url, params, onload, onerror);
}
function fotoReitingVoteHandler() {
	var showReitInterval = 2000;
	var code = this.req.responseText;
	if (code == "error") {
		allTagsError();
		return;
	}
	hideHandleMessage();
	var contDiv = gebi("reitConteinerId");
	contDiv.innerHTML = "<div class=\"rating\">\
		<div class=\"vote_done\">Спасибо,<br />Ваш голос принят<\/div>\
	<\/div>";
	window.setTimeout("showVoteResult(" + code + ")", showReitInterval);
}
function fotoReitingVoteError() {
	showHandleMessage("При обработке запроса произошла ошибка.<br>Повторите попытку снова.");
}
function showVoteResult(estim, all) {
	gebi("reitConteinerId").innerHTML = "<div class=\"voiting\">\
		<span class=\"t90\">Рейтинг ролика:<\/span>\
		<span class=\"bold text2\">" + estim + "<\/span><br />\
		<a href=\"#\" class=\"t70 tahoma\">" + all + " голосов<\/a>\
	<\/div>";
}
// ================ /Рейтинг фото ====================

// ============= Пожаловаться модератору =============
function showModerComplaint(a) {
	if (!gebi("complaintModerDivId")) return;
	gebi("complaintModerDivId").style.top = (absPosition(a).y + a.offsetHeight) + "px";
	gebi("complaintModerDivId").style.left = absPosition(a).x + "px";
	gebi("complaintModerDivId").style.display = "";
	gebi("complaintModerDivId").style.zIndex = 100000;
	return false;
}
function hideModerComplaint() {
	if (gebi("complaintModerDivId")) {
		gebi("complaintModerDivId").style.display = "none";
		return false;
	}
}
// ============ /Пожаловаться модератору =============

// =========== Добавить еще одного пользователя ============
var globalAuthorLimit = 10;

var globalAuthorCount = new Array();

function addAuthorMail(a, containerid, containernumber, countemailid) {
	if(containerid == undefined){ containerid = 'authorContainerId' }
	if(containernumber == undefined){ containernumber = 0 }
	if(globalAuthorCount[containernumber] == undefined){ globalAuthorCount[containernumber] = 1 }
	if(countemailid == undefined){ countemailid='countemailId' }

	if (globalAuthorCount[containernumber] >= globalAuthorLimit) {
		alert("Превышено максимальное число полей - " + globalAuthorLimit);
		return false;
	}
	globalAuthorCount[containernumber]++;
	var div = document.createElement("div");
	var parent = gebi(containerid);

	div.innerHTML = "<table class=\"add_favs\">\
		<tr>\
			<td><input type=\"text\" id=\"id"+containernumber+"_email_"+globalAuthorCount[containernumber]+"\" name=\"email_"+globalAuthorCount[containernumber]+"\" /><\/td>\
			<th><a href=\"#\" onclick=\"currentcontainer="+containernumber+"; currentmailline="+globalAuthorCount[containernumber]+"; return sw('email');\"><img src=\"http://img.mail.ru/r/foto2/ico_add.gif\" width=\"13\" height=\"16\" alt=\"\" /><\/a><\/th>\
		<\/tr>\
	<\/table>";

	if (parent != undefined) {
		var ob = gebi(countemailid);
		if( ob != undefined ){ ob.value = globalAuthorCount[containernumber]; }
		parent.appendChild(div);

		var ob = gebi('NewInputTextID');
		if(ob != undefined){
			ob.id = '';
			ob.focus();
		}	
	}else{
		alert('Не найден контейнер по id='+containerid);
	}
	return false;
}
// ========== /Добавить еще одного пользователя ============

// ==== Изменить форму настроек без перезагрузки =====
function settingsBlock(flag) {
	for (var i = 1; i <= 5; i++) {
		var ob = gebi("settingsBlock_" + i);
		if(ob){
			ob.style.display = (i == flag) ? "" : "none";
		}
	}
}
// === /Изменить форму настроек без перезагрузки =====

// ====== Переключалка простой/расширеный поиск ======
function advancedSimpleSwitch(a) {
	var display = gebi("ExpandedSearchFoto").style.display;
	a.firstChild.nodeValue = display == "none" ? "Простой поиск" : "Расширенный поиск";
	gebi("ExpandedSearchFoto").style.display = display == "none" ? "" : "none";
	return false;
}
// ===== /Переключалка простой/расширеный поиск ======
/* Глобальная переменная для типа закрузки
	1 : Обычная загрузка,
	2 : Быстрая загрузка,
	3 : Загрузка архивом,
	4 : Загрузка из Интернета
*/
var globalLoadType = 1;


// ============ Настройка доступа к фото ============
// Обработка изменения селекта "Доступ"
function setAccess(sel, flag) {
	if (flag) gebi("albumPassId").style.display = (sel.selectedIndex == 3) ? "" : "none";
	if (gebi("albumPassId_" + globalLoadType)) gebi("albumPassId_" + globalLoadType).style.display = (sel.selectedIndex == 3) ? "" : "none";
	if (gebi("albumVisForSearchId_" + globalLoadType)) gebi("albumVisForSearchId_" + globalLoadType).style.display = (sel.selectedIndex == 0) ? "" : "none";
}
function setAccess2(sel, type) {
	var ob = gebi("albumPassId_" + type);
	if(ob){ ob.style.display = (sel.selectedIndex == sel.options.length - 1) ? "" : "none"; };
	if (gebi("albumVisForSearchId_" + type)) gebi("albumVisForSearchId_" + type).style.display = (sel.selectedIndex == 0) ? "" : "none";
}
// Выбор (или скрытие) опции "Создание нового альбома"
function selectAlbumForUpload(sel) {
	var display = (sel.selectedIndex == sel.options.length - 1) ? "" : "none";
	if (gebi("albumNameId_" + globalLoadType)) gebi("albumNameId_" + globalLoadType).style.display = display;
	if (gebi("albumURLId_" + globalLoadType)) gebi("albumURLId_" + globalLoadType).style.display = display;
	if (gebi("albumCreateId_" + globalLoadType)) gebi("albumCreateId_" + globalLoadType).style.display = display;
	if (gebi("albumAccessId_" + globalLoadType)) gebi("albumAccessId_" + globalLoadType).style.display = display;
	if (gebi("albumVisForSearchId_" + globalLoadType)) gebi("albumVisForSearchId_" + globalLoadType).style.display = display;
	setAccess(gebi("selectAccessId_" + globalLoadType));
	var ob = gebi("albumPassId_" + globalLoadType); if(ob && (display == "none")) { ob.style.display = display; };
}
function selectAlbumForUpload2(sel, type) {
	var display = (sel.selectedIndex == sel.options.length - 1) ? "" : "none";
	gebi("albumCreateId_" + type).style.display = display;
	gebi("albumAccessId_" + type).style.display = display;
	setAccess2(gebi("selectAccessId_" + type), type);
	var ob = gebi("albumPassId_" + type); if(ob && (display == "none")) { ob.style.display = display; };
}
// =========== /Настройка доступа к фото ============

// ============ Создание нового альбома =============
// Проверка количества введенных символов 
// и подстановка соот-их форм слов
var endingArray = ["", "а", "ов"]
function checkLengthWithForm(input, limit, showId, word) {
	limit = parseInt(limit);
	var b = document.getElementById(showId);
	if (input.value.length <= limit) {
		var ost = limit - input.value.length
		b.innerHTML = ost + " " + word + wordForms(ost, endingArray);
	} else {
		b.innerHTML = 0 + " " + word + "ов";
		input.value = input.value.substring(0, limit);
	}
}
function wordForms(num, arr) {
	var out;
	num = parseInt(num);
	if (num % 10 == 1 && num % 100 != 11) out = arr[0];
	else if ((num % 100 != 12 && num % 10 == 2) || (num % 100 != 13 && num % 10 == 3) || (num % 100 != 14 && num % 10 == 4)) out = arr[1];
	else out = arr[2];
	return out;
}
// ============ /Создание нового альбома =============

// ======= Добавление полей при загрузке Нетом =======
var countUrlFieldsHash = {
	"urlfoto_" : 0,
	"fotobrowse_" : 0
}
// Добавление поля выбора фото
function addField(blName, num) {
	num = parseInt(num);
	var addF = gebi("addFId_" + globalLoadType);
	var prevNum = num - 1;
	blName += "_";
	var parDiv = gebi(blName + prevNum).parentNode;
	var addingBlock = document.createElement("div");
	addingBlock.id = blName + num;
	if (blName == "urlfoto_") addingBlock.innerHTML = "\
		<div id=\"urlfoto_" + num + "\">\
		<table class=\"mt7\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" id=\"addurl_table_" + num + "\">\
			<tr>\
				<td width=\"100%\">\
					<input type=\"text\" name=\"URL\" value=\"http://\" />\
				<\/td>\
				<td nowrap=\"nowrap\">\
					&nbsp;&nbsp;&nbsp;&nbsp;<a class=\"t70 tahoma\" onclick=\"return delField('urlfoto_', 'addurl_table_','" + num + "');\" href=\"#\">Удалить<\/a>\
				<\/td>\
			<\/tr>\
		<\/table>\
		<div id=\"add_urlfoto_" + (num + 1) + "\">\
			<a class=\"t70 tahoma\" onclick=\"return addField('urlfoto', '" + (num + 1) + "');\" href=\"#\">Еще один ролик<\/a>\
		<\/div>";
	else if (blName == "fotobrowse_") addingBlock.innerHTML = "\
		<div id=\"fotobrowse_" + num + "\">\
		<table class=\"mt7\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" id=\"addbrowse_table_" + num + "\">\
			<tr>\
				<td width=\"100%\">\
					<input type=\"file\" name=\"foto\" />\
				<\/td>\
				<td nowrap=\"nowrap\">\
					&nbsp;&nbsp;&nbsp;&nbsp;<a class=\"t70 tahoma\" onclick=\"return delField('fotobrowse_', 'addbrowse_table_','" + num + "');\" href=\"#\">Удалить<\/a>\
				<\/td>\
			<\/tr>\
		<\/table>\
		<div id=\"add_fotobrowse_" + (num + 1) + "\">\
			<a class=\"t70 tahoma\" onclick=\"return addField('fotobrowse', '" + (num + 1) + "');\" href=\"#\">Еще однин ролик<\/a>\
		<\/div>";
	if (countUrlFieldsHash[blName] < 30 - 1){
		gebi("add_" + blName + num).style.display = "none";
		countUrlFieldsHash[blName]++;
		parDiv.appendChild(addingBlock);
	} else alert("Превышен лимит на количество одновременно загружаемых роликов, максимум - 30.");
	if (countUrlFieldsHash[blName] > 0) {
		addF.Title.disabled = true;
		addF.Comment.disabled = true;
		var iRd1 = addF["iRd1_" + globalLoadType];
		var iRd3 = addF["iRd3_" + globalLoadType];
		var iRd4 = addF["iRd4_" + globalLoadType];
		if (iRd3.checked) iRd1.checked = true;
		if (iRd4.checked) iRd1.checked = true;
		iRd3.disabled = true;
		iRd4.disabled = true;
		addF.Contest.disabled=true;
		addF.Contest.options[0].selected=true;
		showAgreement(addF.Contest);
	}
	return false;
}
// Удаление поля
function delField(blName, id, num) {
	var addF = gebi("addFId_" + globalLoadType);
	gebi(id + num).style.display = "none";
	countUrlFieldsHash[blName]--;
	if (countUrlFieldsHash[blName] == 0) {
		addF.Title.disabled = false;
		addF.Comment.disabled = false;
		var iRd3 = addF["iRd3_" + globalLoadType];
		var iRd4 = addF["iRd4_" + globalLoadType];
		iRd3.disabled = false;
		iRd4.disabled = false;
		addF.Contest.disabled = false;
	}
	return false;
}
// ====== /Добавление полей при загрузке Нетом =======

function albumCasheSwitcher(type, switchFlag,host)
{
	button_delete_state = OwnAlbumVar ? true : false;//(type != 'special' && )
	// Проверка
	if (typeof albumsArray[type] == "undefined") return false;
	// Переключение закладок
	if (switchFlag) {
		gebi("commonAlbumId").style.display = gebi("commonAlbumId").style.display == "none" ? "" : "none";
		gebi("specialAlbumId").style.display = gebi("specialAlbumId").style.display == "none" ? "" : "none";
		albumPage = 1;
		albumType = type;
	}
	// Отрисовка
	var arr = albumsArray[type];
	var cols = 2, rows = parseInt(albumOnPage / cols) + (albumOnPage % cols ? 1 : 0);
	var i, j, k = -1;
	var code = "<table class='preview'>\n";

	for (i = 1; i <= rows; i++) {
		if (typeof arr[k + 1] == "undefined") break;
		code += "<tr" + (type == "special" ? "" : "") + ">\n";//
		for (j = 1; j <= cols; j++) {
			k = ((albumPage - 1) * albumOnPage) + ((i - 1) * cols + j) - 1;
			if ((i - 1) * cols + j > albumOnPage) continue;
			if (typeof arr[k] != "undefined") {
				var favoritesVar = (arr[k][0] == '_myphoto') ? true : false;
				var properties = OwnAlbumVar ? '<p><a href="http://'+VideoPerlHost()+'/cgi-bin/photo/editalbum?id=' +arr[k][0] + '"><img src="http://img.mail.ru/r/foto2/ico_pencil.gif" width="16" height="16" alt="Свойства" title="Свойства" />Свойства<\/a><\/p>' : '';
				
				var button_delete = button_delete_state ? '<p><a onclick="return confirm(\'Вы действительно хотите удалить альбом &laquo;' + arr[k][1] + '&raquo; со всеми находящимися в нем роликами?\');" href="http://'+VideoPerlHost()+'/cgi-bin/photo/editalbum?delete=1&id=' +arr[k][0] + '"><img src="http://img.mail.ru/r/foto2/ico_delete.gif" width="16" height="16" alt="Удалить" title="Удалить" />Удалить<\/a><\/p>' : '';
				code += '<td>'+
				'<table><tr><td><a ' + (arr[k][7]? '' : 'onclick="return showProtectAlbum(event, \'' + arr[k][0] + '\', this);" ') + 'href="' + albumsPath + arr[k][0] + '"><img src="' + arr[k][2] + '" alt="' + arr[k][1] + '" title="' + arr[k][1] + '" /><\/a> <\/td><\/tr><\/table><a href="' + albumsPath + arr[k][0] + '" ' + (arr[k][7] ? '' : 'onclick="return showProtectAlbum(event, \'' + arr[k][0] + '\', this);" ') + '>' + arr[k][1] + '<\/a><br />' +
				'<span>' + (arr[k][3] ? arr[k][3] + ' ' + arr[k][4] : '') + '<br />' + (arr[k][5] ? arr[k][5] + ' ' + arr[k][6] : '') + '<br /><\/span><br />' +
				
				properties +
				button_delete +
				'<\/td>\n';
			} else code += "<td class=\"no_frame\">&nbsp;<\/td>";
		}
		code += "<\/tr>\n";
	}
	code += "<\/table>";
	gebi("albumListId").innerHTML = code;
	albumCasheChangePage(albumPage, 1)
	return false;
}
function albumCasheChangePage(num, from) {
	// Проверка
	if (typeof albumsArray[albumType] == "undefined") return;
	var allPages = parseInt(albumsArray[albumType].length / albumOnPage) + (albumsArray[albumType].length % albumOnPage ? 1 : 0);
	if (allPages <= 1) {
		if (gebi("albumListalkaId")) {gebi("albumListalkaId").innerHTML = " ";}//
		return false;
	}
	// Отрисовка
	albumPage = num;
	if (!from) albumCasheSwitcher(albumType);
	var code = "";
	if (albumPage != 1) code += "&nbsp;<a onclick=\"albumCasheChangePage(" + (albumPage - 1) + ");\" href=\"#albums_top\"><b>&lsaquo;<\/b>&nbsp;Назад&nbsp;<\/a>&nbsp;\n";
	for (var i = 1; i <= allPages; i++) {
		if (i == albumPage) code += "<b class=\"black\">&middot;&nbsp;" + i + "&nbsp;&middot;<\/b>\n";
		else code += "&nbsp;<a onclick=\"albumCasheChangePage(" + i + ");\" href=\"#albums_top\">" + i + "<\/a>&nbsp;\n";
	}
	if (albumPage != allPages) code += "&nbsp;<a onclick=\"albumCasheChangePage(" + (albumPage + 1) + ");\" href=\"#albums_top\">Далее&nbsp;<b>&rsaquo;<\/b><\/a>&nbsp;\n";
	gebi("albumListalkaId").innerHTML = code;
	return false;
}
// ============ /CASHE-switcher альбомы  =============


// =========== Закрыть доступ к альбому ==============
function showProtectAlbum(evt, id, _link) {
	cancelBubbling(evt);
	var div, hidden;
	if (div = gebi("secureAlbumDivId")) {
		div.style.display = "";
		div.onclick = cancelBubbling;
		div.style.top = (absPosition(_link).y + _link.offsetHeight) - 30 + "px";
		div.style.left = absPosition(_link).x + 60 + "px";
		if (hidden = gebi("secalbid")) {
			hidden.value = id;
		}
		gebi('secalbpass').focus();
		gebi('secalbpass').value='';
		return false;
	}
	return;
}

function hideProtectAlbum() {
	var div;
	if (div = gebi("secureAlbumDivId")) {
		div.style.display = "none";
	}
}

addHandler(document, 'click', hideProtectAlbum);

function checkAlbumPasswordCallback (st,redirurl) {
    hideProtectAlbum();
    if (st==1) {
	   document.location.href=redirurl;
    } else {
	    alert ('Неправильный пароль');
    }   
}	
	
function checkAlbumPassword (album_id,passwd,redirurl) {
    var st=ajax_call('perl_check_album_password',album_id,passwd,redirurl,checkAlbumPasswordCallback);
}

function checkAlbumPasswordNoLogin (album_id,passwd,redirurl) {
    var st=ajax_call_nologin('perl_check_album_password_nologin',album_id,passwd,redirurl,checkAlbumPasswordCallback);
}
// ========== /Закрыть доступ к альбому ==============

// ======= Функциональность работы с друзьями ========

function AddSubscriptionCallback(st,errorcode,errortext) {
	if (st==1) {
		alert('Подписка добавлена');
	} else {
		alert('Организовать подписку не получилось: '+errortext);
	}	
}

function AddSubscription () {
    var st=ajax_call('perl_add_subscription',AddSubscriptionCallback);
    if (!st) {
		alert('Подписаться не получилось');
    }	
    return false;
}

// ======= /Функциональность работы с друзьями =======


//substring
function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}

//обрубает длинные ники и имена роликов
function cutName(){
    if (cutName.arguments[0]){
        var tmp_nickname = cutName.arguments[0];
    } else { 
        if(cutName.arguments[2]){
            var cbox = cutName.arguments[2].toString();
        } else if(cutName.arguments[1] && cutName.arguments[1] != 145 && cutName.arguments[1] != 240){
            var cbox = cutName.arguments[1].toString();
        } else {
            return;
        }

        if (cbox){
            var xyz = cbox.split('/');
            if(xyz.length == 4){
                var tmp_nickname = xyz[2] + '@';
                tmp_nickname += (xyz[1] == 'corp') ? 'corp.mail.ru' : xyz[1] + '.ru';
            } else {
                return;
            }
        } else {
            return;
        }
    }
    
    tmp_nickname=str_replace("&quot;","\"",tmp_nickname); 
    tmp_nickname=str_replace("&amp;quot;","\"",tmp_nickname);
    var nicknameL = tmp_nickname.length;

    var dlength = 12;
    if (cutName.arguments[1]){
        dlength = (cutName.arguments[1] == 120) ? 14 : dlength; 
        dlength = (cutName.arguments[1] == 145) ? 16 : dlength;
        dlength = (cutName.arguments[1] == 240) ? 24 : dlength;
    }

    if (nicknameL < dlength) {return tmp_nickname;}
    var qUpLetters = 0;
    for (var i =0; i < dlength; i++){
        tmp_Letter = tmp_nickname.substring(i, i + 1);
        tmp_Letter_u = tmp_Letter.toUpperCase();
        if (tmp_Letter == tmp_Letter_u){
            if( !(/[,\.?!;:\/<>()\{\}\[\]\"\'=@&\s\\]/i.test(tmp_Letter)) ){
                if (tmp_Letter_u != 'W' || tmp_Letter_u != 'M' || tmp_Letter_u != 'G' || tmp_Letter_u != 'М' || tmp_Letter_u != 'Ш' || tmp_Letter_u != 'Щ' || tmp_Letter_u != 'Ф' || tmp_Letter_u != 'Ж') {qUpLetters++;} else {qUpLetters += 1.3;}
            }
        }
    }

    var lengthName = qUpLetters > dlength/1.5 ? (dlength/1.5) : ((qUpLetters < (dlength/1.5) && qUpLetters > 2) ? (dlength/1.5 + (dlength/1.5)/1.5) : dlength);
    var deltaLength = nicknameL - lengthName;
    lengthName = deltaLength > 2 ? lengthName : lengthName + deltaLength;

    tmp_nickname = nicknameL > lengthName ? (tmp_nickname.substring(0,lengthName) + '&hellip;') : tmp_nickname;
    return tmp_nickname;
}



//======определяем размеры окна ============

function getWinSize() {
	var myWidth = 0, myHeight = 0;
	
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	}
	else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	}
	else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	return {w:984,h:myHeight};
}


//=====================================


//=========отображаем 4й блок на морде============================

function show_trailer() {

var code = gebi('hidden_slot').innerHTML;

var client_width = getWinSize().w;
var top_slots = gebi("top_slots").getElementsByTagName("tr");

if (client_width >= 1600) {
	
	if(!gebi("added_slot"))  {
	
	var th = document.createElement('th');
	var td = document.createElement('td');
	
	
	th.innerHTML = "&nbsp;";
	td.id="added_slot";
	th.id="added_slot_th";
	td.innerHTML = code;
	
	top_slots[0].appendChild(th);
	top_slots[0].appendChild(td);
	}
	
	} 
	
	if (client_width < 1600) {
	
		if(gebi("added_slot")) { 
		top_slots[0].removeChild(gebi("added_slot"));
		top_slots[0].removeChild(gebi("added_slot_th"));
		}
	
	}
	
//=====================================

}

//=================   Кодировка символов в windows-1251 и функция выбора "Другой метки"
Char2Hex = new Object();
for(var i =  0; i<=255;i++ ) {
     var j = parseInt(i/16); var j2 = parseInt(i%16);
    Char2Hex[''+String.fromCharCode(i)] = ('%' + j.toString(16) + j2.toString(16) ).toUpperCase();
}
Char2Hex['_']='%5F';
Char2Hex['А']='%C0';
Char2Hex['Б']='%C1';
Char2Hex['В']='%C2';
Char2Hex['Г']='%C3';
Char2Hex['Д']='%C4';
Char2Hex['Е']='%C5';
Char2Hex['Ж']='%C6';
Char2Hex['З']='%C7';
Char2Hex['И']='%C8';
Char2Hex['Й']='%C9';
Char2Hex['К']='%CA';
Char2Hex['Л']='%CB';
Char2Hex['М']='%CC';
Char2Hex['Н']='%CD';
Char2Hex['О']='%CE';
Char2Hex['П']='%CF';
Char2Hex['Р']='%D0';
Char2Hex['С']='%D1';
Char2Hex['Т']='%D2';
Char2Hex['У']='%D3';
Char2Hex['Ф']='%D4';
Char2Hex['Х']='%D5';
Char2Hex['Ц']='%D6';
Char2Hex['Ч']='%D7';
Char2Hex['Ш']='%D8';
Char2Hex['Щ']='%D9';
Char2Hex['Ъ']='%DA';
Char2Hex['Ы']='%DB';
Char2Hex['Ь']='%DC';
Char2Hex['Э']='%DD';
Char2Hex['Ю']='%DE';
Char2Hex['Я']='%DF';
Char2Hex['а']='%E0';
Char2Hex['б']='%E1';
Char2Hex['в']='%E2';
Char2Hex['г']='%E3';
Char2Hex['д']='%E4';
Char2Hex['е']='%E5';
Char2Hex['ж']='%E6';
Char2Hex['з']='%E7';
Char2Hex['и']='%E8';
Char2Hex['й']='%E9';
Char2Hex['к']='%EA';
Char2Hex['л']='%EB';
Char2Hex['м']='%EC';
Char2Hex['н']='%ED';
Char2Hex['о']='%EE';
Char2Hex['п']='%EF';
Char2Hex['р']='%F0';
Char2Hex['с']='%F1';
Char2Hex['т']='%F2';
Char2Hex['у']='%F3';
Char2Hex['ф']='%F4';
Char2Hex['х']='%F5';
Char2Hex['ц']='%F6';
Char2Hex['ч']='%F7';
Char2Hex['ш']='%F8';
Char2Hex['щ']='%F9';
Char2Hex['ъ']='%FA';
Char2Hex['ы']='%FB';
Char2Hex['ь']='%FC';
Char2Hex['э']='%FD';
Char2Hex['ю']='%FE';
Char2Hex['я']='%FF';
Char2Hex['ё']='%B8';
Char2Hex['Ё']='%A8';
Char2Hex[' ']='%20';

function urlencode(str) {
    if(!str || typeof(str) == "undefined" || str == null || str == "") return "";
    var res = '';
    for(var i=0;i<str.length;i++) {
        var char = str.substr(i,1);
        res = '' + res + ( (typeof(Char2Hex[char]) != "undefined" ) ? Char2Hex[char] : char);
    }
    return res;
}

function ShowOtherTag(evt) {
	cancelBubbling(evt);
	gebi('tag_other').onclick = cancelBubbling;
	if (gebi('tag_other').style.display == 'none') {
		gebi('tag_other').style.display = 'block';
		gebi('tag_other_form').elements['tag_other_name'].focus();
	} else HideOtherTag();
}
function HideOtherTag() {
	if (gebi('tag_other')) {gebi('tag_other').style.display = 'none';}
}
addHandler(document, 'click', HideOtherTag);

function GoOtherTag(host, name) {
	location.href ='http://' + host + '/tags/' + urlencode(name) + '?from_other_tag';
}

//====================== Всплывающая подсказка "SMS-игры"
var SMStop_opened  = "";
function ShowSMStop(evt, img, right, top, PhotoUserID, id, AlbumAccess, Ero, AlbumVote, host, gameCode, ActiveUserID, link) {
	SMStop_opened = (SMStop_opened == id)  ? id : SMStop_opened;
	cancelBubbling(evt);
	if (SMStop_opened == id) {HideSMStop();return false;}
	
	ActiveUserID = (ActiveUserID) ? ActiveUserID : 0;
	
	//убираем подсказку к рейтингу (цветы и медали)
	awardHelpHide();
	//убираем подсказку к +10
	contextHelpVoteHide();
	//hide hint
	contextHelpHide();
	
	if (img.childNodes) {
		var arrChildIMG = img.childNodes;
		arrChildIMG = arrChildIMG.length ? arrChildIMG : [arrChildIMG];
		arrChildIMG_length = arrChildIMG.length;
		var varIMG;
		for (var i = 0; i < arrChildIMG_length; i++) {
			if (arrChildIMG[i].nodeName == 'IMG') {varIMG = arrChildIMG[i];}
		}
	}
	if (link == 0) img = varIMG;
	var rightFlag = typeof right == 'undefined' || !right ? false : true;
	var topFlag = typeof top == 'undefined' || !top ? false : true;
	top = parseInt(top);
	top = top == 1 ? -50 : top;
	if (screenSize().w - absPosition(img).x < 300) rightFlag = true;

	var targetDiv;
	if (!gebi('smstopHelpDiv')) {
		var div = document.createElement('div');
		div.id = 'smstopHelpDiv';
		div.style.top = '0';
		div.style.left = '0';
		div.style.display = 'none';
		div.style.zIndex = '100000000';
		document.body.appendChild(div);
	}
	
	var str = new Array();
	
	var out = '';
	
		str[1] = '<span class="title">Видео-Лидер</span> <a href="http://' + host + '/catalog/static/show_yourself.html#leader" class="more">Подробнее</a><br />' +
		'<p>' + 
			'<span class="block1">Размещение ролика на главной <br />странице в рубрике &laquo;Видео-лидер&raquo;.</span><br />' +
			'<span class="block2">Для участия отправьте SMS с кодом<br /><b>31+' + PhotoUserID + '+' + id + '</b>.<br/>Для России и Украины на короткий номер&nbsp;<b>7099</b>, для Казахстана&nbsp;&mdash;&nbsp;<b>7502</b>.</span><br />' +
			'<span class="block3">Стоимость услуги: 0,99 у.е. без НДС.</span>' +
		'</p>';
		str[2] = '<span class="title">SMS-топ</span> <a href="http://' + host + '/catalog/static/show_yourself.html#smscodes1" class="more">Подробнее</a><br />' +
		'<p>' + 
			'<span class="block1">Размещение ролика на главной <br />странице в рубрике &laquo;SMS-топ&raquo;.</span><br />' +
			'<span class="block2">Для участия отправьте SMS с кодом<br /><b>30+' + PhotoUserID + '+' + id + '</b>.<br/>Для России и Украины на короткий номер&nbsp;<b>7099</b>, для Казахстана&nbsp;&mdash;&nbsp;<b>7502</b>.</span><br />' +
			'<span class="block3">Стоимость услуги: 0,99 у.е. без НДС.</span>' +
		'</p>';

		str[3] = '<span class="title">Дайте две!</span> <a href="http://' + host + '/catalog/static/show_yourself.html#smscodes2" class="more">Подробнее</a><br />' +
		'<p>' + 
			'<span class="block1">Каждый голос за ролик удваивается. Срок действия &mdash; 1 час.</span><br />' +
			'<span class="block2">Для участия отправьте SMS с кодом<br /><b>32+' + PhotoUserID + '+' + id + '</b>.<br/>Для России и Украины на короткий номер&nbsp;<b>7250</b>, для Казахстана&nbsp;&mdash;&nbsp;<b>7504</b>.</span><br />' +
			'<span class="block3">Стоимость услуги: 2,6 у.е. без НДС.</span>' +
		'</p>';
	
		str[4] = '<span class="title">Держи десять!</span> <a href="http://' + host + '/catalog/static/show_yourself.html#d10" class="more">Подробнее</a><br />' +
		'<p>' + 
			'<span class="block1">Возможность ставить оценку +10 в течение 1 часа.</span><br />';
		if (ActiveUserID) str[4] += '<span class="block2">Для участия отправьте SMS с кодом<br /><b>27+' + ActiveUserID + '</b>.<br/>Для России и Украины на короткий номер&nbsp;<b>7099</b>, для Казахстана&nbsp;&mdash;&nbsp;<b>7502</b>.</span><br />';
		else str[4] += '<span class="block2">Для участия отправьте SMS с кодом<a href=\"http://' + host + '/cgi-bin/login?page=' + encodeURI(window.location.href) + '\">авторизоваться<\/a>.<br />';
		str[4] +=	'<span class="block3">Стоимость услуги: 0,99 у.е. без НДС.</span>' +
		'</p>';
		
			if (!gameCode) {
				if ((AlbumAccess == 2) && (Ero == 0))  out = str[1] + str[2];
				if (AlbumVote == 1) out += str[3];
				out += str[4];
			}else out = str[gameCode];
		
		
		
	targetDiv = gebi('smstopHelpDiv');
	targetDiv.innerHTML = '<div class="infoblock"><h1>SMS-игры</h1><a href="#" onclick="HideSMStop(); return false;"><img src="http://img.mail.ru/r/foto2/ico_close.gif" width="7" height="7" alt="Закрыть" class="close" /></a>' + out + '</div>';
	if (link == 0) {
		var xRemainder = (rightFlag) ? -222 - img.width + 2 : 0;
		var yRemainder = (topFlag) ? top : 0;
		targetDiv.style.top = (absPosition(img).y + yRemainder) + img.height + 2 + "px";
		targetDiv.style.left = (absPosition(img).x + xRemainder) + "px";
	} else {
		var x = absPosition(img).x + 55;
		var y = absPosition(img).y + 16;
		var div_width = 250;
		var rightFlag = true;
		targetDiv.style.top = y + "px";
		targetDiv.style.left = (rightFlag) ? x - div_width + "px" : x +"px";
	}
	targetDiv.onclick = cancelBubbling;
	targetDiv.style.display = 'block';
	SMStop_opened = id;
	return false;
}

function HideSMStop() {
	if (gebi('smstopHelpDiv')) gebi('smstopHelpDiv').parentNode.removeChild(gebi('smstopHelpDiv'));
	SMStop_opened = "";
}
addHandler(document, 'click', HideSMStop);
					

//=====x2===========

function hide2x() {
	if(gebi("2x")) gebi("2x").style.display="none";
}

//=================


//формат времени 
function show_duration(num) {

	var arr;
	var out = "";
	
	if (!num) return "00:00";
	
	arr = num.split(":");
	
	if (arr.length > 1 ) { //если чч:мм:сс
		if (arr.length == 3) {
			if (arr[0] != '00' ) out = arr[0] + ":" +arr[1] + ":" + arr[2]; else out = arr[1] + ":" + arr[2];
		}
		else out = arr[0] + ":" + arr[1];
	}
	
	else { //если сек
	
	num = Math.floor(num); 

	var hours = Math.floor(num / 3600);
	var min = Math.floor((num - hours * 3600) / 60);
	var sec = Math.floor(num - hours * 3600 - min * 60) ; 

	if (sec < 10 ) sec = "0" +  eval(sec); 
	if (min < 10 ) min = "0" +  eval(min);

	if (hours != 0 ) 
		if (hours < 10 ) hours = "0" + eval(hours);

	if (hours != 0 ) out = hours + ":" + min + ":" + sec;
	else out = min + ":" + sec;
	
	}
	
	return out;
}

//попап для подписки

function openPopUp(src, width, height)
{
	var videoperlhost = VideoPerlHost();
	var _width = width;
	var _height = height;
	var top = 0;
	var left = ( getWinSize().w - _width ) / 2;
	var path = 'http://r.mail.ru/cln4235/' + videoperlhost + '/' + src; 
	var newWin = window.open(path,'_new','width='+_width+',height='+_height+',top='+top+',left='+left+',resizable');
}

//подписка на метку 
function subscribe_tag(tagname) {
	if (confirm("Подписаться на ежедневную рассылку новых роликов с меткой \"" + tagname + "\" ?")) ajax_call('perl_add_subscription_tag', tagname ,AddSubscriptionTagCallback); 
	
	return false;
}



// Листалка страницы через клавиатуру Ctrl+стрелка 
function listpage(event)
{
	if (!event) event = window.event;
	var key = event.keyCode;
	if (event.ctrlKey)
	{
		var tagName = (event.target || event.srcElement).tagName;
		if (tagName != 'INPUT' && tagName != 'TEXTAREA')
		{
			var doc;
			if (key == 37) doc = gebi('previous_page');
			if (key == 39) doc = gebi('next_page');
			if (doc) location.href = doc.href;
		}
	}
}

//всплывающие окна
var InfoBlock = {
	defaultClassName : "contextInfo",
	mainMenuId : "MainMenu",
	spacer : "http://img.mail.ru/0.gif",
	itemClassPrefix : "m",
	toggle : false,
	light: "",
	lightItem : "",
	openObject : "",
	opened : "",
	openedGame : "",
	
	host : "",
	PhotoUserID: "",
	ActiveUserID : "",	
	image_id: "",
	
	initSMSHelp : function(h,pu,au,i) {
	this.host = h;
	this.PhotoUserID = pu;
	this.ActiveUserID =	 au;
	this.image_id = i;
	},
	
	show : function(id,evt,obj, cn, pos, offsetY, offsetX, toggleMM, item, gameCode, gameParams) { 
		if (this.isOpened(id)) { 
			if(!gameCode) {
				this.hide(); 
				return false;
			}else if(this.openedGame == gameCode) { 
					this.hide(); 
					return false;
			}
		}
			this.hide(); 
			this.openObject = obj;

			cancelBubbling(evt);
			
			hideContext();
						
			var targetDiv;
			if(gebi(id)) targetDiv = gebi(id); 
			else if(!gameCode) 
					targetDiv = false;
				else
					targetDiv = document.createElement("div"); 

			var coordinates = {};
			targetDiv.className = cn + " " + this.defaultClassName;
			targetDiv.style.zIndex = '100000000';
			targetDiv.onclick = cancelBubbling;
			
			targetDiv.id = id;
			targetDiv.style.position = "absolute";
			if(!gebi(id)) document.body.appendChild(targetDiv);
			
			if(gameCode) { 
				var html = "", gameHTML = "", gameHash = {}, pre;
				targetDiv.innerHTML = '<div class="text-right close"><a href="#" onclick="InfoBlock.hide();return false;"><img src="http://img.mail.ru/r/foto2/ico_close.gif" border="0" alt="Закрыть" title="Закрыть" /></a></div>';
				gameHash = this.getSMSHelp(gameCode, gameParams);
				
				for(var i = 0, j = gameHash.length; i < gameHash.length; i++, j--) {
				gameHTML = "";
				pre = (gameCode == 'all') ? gameHash[i]["id"] : gameCode;
				gameHTML += 	"<span class=\"title\">" + gameHash[i]["name"] + "</span> <a class=\"more\" href=\"http://" + this.host + "/catalog/static/show_yourself.html#" + gameHash[i]["id"] + "\">Подробнее</a><br/>"+
							"<p>";
				if(!this.ActiveUserID && gameCode == 'megavote') 
				gameHTML += "<span class=\"block1\">" + gameHash[i]["descr"] + "</span><br/>";
				else {
				gameHTML +=	"<span class=\"block1\">" + gameHash[i]["descr"] + "</span><br/>"+
							"<span class=\"block2\">Для участия отправьте SMS</span>"+
							"</p>"+
							"<div class=\"numberSelectForm\">"+
							"<div class=\"numberSelect\">"+
								"<ins>с кодом</ins>";
								if(gameHash[i]["id"] != 'megavote') gameHTML += "<div class=\"frame\"><strong>" + gameHash[i]["prefix"] + "+" + this.PhotoUserID + "+" + this.image_id + "</strong></div>";
								else 					   gameHTML += "<div class=\"frame\"><strong>" + gameHash[i]["prefix"] + "+<span id=\"auid\">" + this.ActiveUserID + "</span></strong></div>";
				
				gameHTML +=	"</div>"+
							"<div class=\"numberSelect\" style=\"z-index:"+j+"\">"+
								"<ins>на номер</ins>"+
								"<div class=\"frame\">"+
									"<dl>"+
										"<dt id=\"UserShortNumber_" + gameHash[i]["id"]+ "\">" + SMSInfo.sms_number + "</dt>"+
										"<dd>"+
											"Если вы находитесь в <span class=\"UserCountry\">" + SMSInfo.user_location + "</span><br/><a href=\"#\" onclick=\"SMSInfo.show('" + pre + "',event); return false;\" class=\"dashed\">Другая&nbsp;страна</a><br/>";
				
				gameHTML += SMSInfo.getNumbersHTML(pre, gameHash[i]["kat"]);
								
				gameHTML +=				"</dd>"+
									"</dl>"+
								"</div>"+
							"</div>"+
							"</div>"+
							"<p>";
				}				
				gameHTML +=	"<span class=\"block3\">Стоимость услуги: " + gameHash[i]["price"] + " без НДС.<br/>"+
							"<a href=\"http://rates.mail.ru/\">Условия предоставления услуги</a></span>"+
							"</p>";
				
				targetDiv.innerHTML += gameHTML;
				
				SMSInfo.getCountry(); 
				SMSInfo.getParams(gameHash[i]["kat"]);
				SMSInfo.setParams(gameHash[i]["id"]);
				}
				
				this.openedGame = gameCode; 
			}
			
			targetDiv.style.display = 'block';	
			pos = (pos) ? pos : 'abs';
			coordinates = this.getPosition(targetDiv, obj, offsetY, offsetX, pos); 

			targetDiv.style.top  = coordinates["top"]  + "px";				
			targetDiv.style.left = coordinates["left"] + "px";	
			
			this.opened = id;
			
			if(toggleMM) {
				this.toggle = true;
				this.toggleMainMenu();
			}
			
			if(item) { 
				this.lightItem = item;
				this.light = true;
				this.lightMenuItem();
				obj.parentNode.style.zIndex = 2; //IE z-index fix
			}
			
			addHandler(document, 'click', function(e) {
			var e = e || window.event;
			if (e.button == 0 )	InfoBlock.hide();
			});
								
			return false;
		
	},
	
	getSMSHelp : function(i, p) { 
		var out =[];
		var album_access = 2, vote_access = 1, ero = 0, fav = 0;
		if(typeof p != 'undefined') {
			album_access = p['album_access'];
			vote_access = p['vote_access'];
			ero = p['ero'];
			fav = p['fav'];
		} 
		var games = { 
				'smstop' :
				{ 
					"prefix" : "30",
					"name" : "SMS-топ",
					"descr" : "Размещение ролика на главной странице в рубрике «SMS-топ».",
					"price" : "0.99 у.е.",
					"id" : "smstop",
					"kat" : "0"
				},
				'leader' : 
				{ 
					"prefix" : "31",
					"name" : "Видео-Лидер",
					"descr" : "Размещение ролика на главной странице в рубрике «Видео-лидер».", 
					"price" : "0.99 у.е.",
					"id" : "leader",
					"kat" : "0"
				},
				'x2': 
				{ 
					"prefix" : "42",
					"name" : "Дайте две!",
					"descr" : "Каждый голос за ролик удваивается. Срок действия &mdash; 1 час.",
					"price" : "2.99 у.е.",
					"id" : "x2",
					"kat" : "1"
				},
				'megavote': 
				{
					"prefix" : "27",
					"name" : "Держи десять!",
					"descr" : "Возможность ставить оценку +10 в течение 1 часа.",
					"price" : "0.99 у.е.",
					"id" : "megavote", 
					"kat" : "0"
				},
				'skinfoto' : {
					"prefix" : "48",
					"name" : "Оформить ролик",
					"descr" : "",
					"price" : "1 у.е.",
					"id" : "skinfoto", 
					"kat" : "2"
				},
				'skinalbum' : {
					"prefix" : "49",
					"name" : "Оформить альбом",
					"descr" : "",
					"price" : "2.99 у.е.",
					"id" : "skinalbum", 
					"kat" : "3"
				}
			};
				
			if (!this.ActiveUserID) games["megavote"]["descr"]  += '<br/>Для участия в игре вы должны <a href=\"http://' + this.host + '/cgi-bin/login?page=' + encodeURI(window.location.href) + '\">авторизоваться</a>.';
								  
			if(typeof i == 'object') {
					for(var n = 0; n < i.length; n++)  
						out.push(games[i[n]]);
				}
				else if (i != 'all') out = [games[i]];
				else {
						if (fav == 0 && album_access == 2 && ero == 0)  out = [games['leader'],games['smstop']];
						if (vote_access == 1) out.push(games['x2']);
						out.push(games['megavote']);
				}
		return out;
	},
	
	getPosition: function(target, obj, offsetY, offsetX, pos) {
		var _top = 0, _left = 0, deltaY = 0, deltaX = 0;
		
		if(offsetY != '' && parseInt(offsetY)) deltaY = parseInt(offsetY);  
		if(offsetX != '' && parseInt(offsetX)) deltaX = parseInt(offsetX);
		
		if (getWinSize().h + defScroll().y - absPosition(obj).y - deltaY < target.offsetHeight + 50) deltaY = target.offsetHeight *(-1) - 20;
		if (getWinSize().w + defScroll().x - absPosition(obj).x - deltaX < target.offsetWidth + 50)  deltaX = target.offsetWidth *(-1) - 20;

		if(offsetX == 'left') deltaX = target.offsetWidth *(-1) - 20;
			else if(offsetX == 'right') deltaX = 0;
	
		if(offsetY == 'top') deltaY = target.offsetHeight *(-1) - 20;
			else if(offsetY == 'bottom') deltaY = 0;
			
		
		if(pos == 'abs') {
			_top =  absPosition(obj).y;
			_left = absPosition(obj).x;
		}
		
		_top += deltaY + 20;
		_left+= deltaX + 20;
		
		return {top:_top,left:_left};
	},
	
	isOpened : function(id) {
		if (gebi(id)) {
			if(gebi(id).style.display == 'block') 
				return true; 
			else return false;
		}else return false;
	},
	
	hide : function() { 
		var els = gebc(this.defaultClassName, "div");
		for(var i = 0; i < els.length; i++) 
			if (els[i]) 
				if (els[i].style.display == 'block') {
					if(!this.openedGame) els[i].style.display = 'none';
						else els[i].parentNode.removeChild(els[i]);
					this.opened = "";
				}
		if(this.toggle) {
				this.toggle = false;
				this.toggleMainMenu();
		}

		if(this.light) {
				this.light = false;
				this.lightMenuItem();
				var obj = this.openObject;
				if (obj) obj.parentNode.style.zIndex = ""; //IE z-index fix
				this.openObject = "";
		}
		
		if (this.openedGame) this.openedGame = "";
		
	},
	
	toggleMainMenu : function() { 
					
			var mm = gebi(this.mainMenuId) ? gebi(this.mainMenuId) : false;
			if(!mm) return false;
			var overlay = gebi("__overlay") ? gebi("__overlay") : false;
						
			if (overlay) {
				overlay.parentNode.removeChild(overlay);
				return false;
			}else {
				var overlay = document.createElement("div");
				overlay.id = "__overlay";
				overlay.style.position = "absolute";
				overlay.style.top = "0";
				overlay.style.left = "0";
				overlay.style.width = mm.offsetWidth + "px";
				overlay.style.height = mm.offsetHeight + "px";
				var i = document.createElement("img");
				i.src = this.spacer;
				i.alt = "";
				i.style.width = mm.offsetWidth + "px";
				i.style.height = mm.offsetHeight + "px";
				overlay.appendChild(i);
				mm.appendChild(overlay);
				overlay.style.display = "block";
			}
	},
	
	lightMenuItem : function() {
		if (this.light) { //подсветить
			var _itemClass = this.itemClassPrefix + this.lightItem; 
			var _item = gebc(_itemClass, "li")[0];
			this.defaultClass = _item.className; 
			if(_item.className.indexOf(_itemClass + "-opened") == -1) {
				var pattern = new RegExp("("+ _itemClass + ")(\\s|$)");
				_item.className=_item.className.replace(pattern,"$1-opened$2");
				_item.getElementsByTagName("ul")[0].style.display = "block";
			}
		}else { 
			var _itemClass = this.itemClassPrefix + this.lightItem;
			var _item = gebc(_itemClass + "-opened", "li")[0];
			_item.className = str_replace(_itemClass + "-opened", _itemClass, _item.className);
			_item.getElementsByTagName("ul")[0].style.display = "";
		}
	}
};

var SMSInfo = {
		numbers : [
		{
		'4446' : [
					{"country" : "Россия" , "location" : "России", "id" : "rus"}, 
					{"country" : "Беларусь" , "location" : "Беларуси", "id" : "bel"}, 
					{"country" : "Украина" , "location" : "Украине", "id" : "ukr"}, 
					{"country" : "Молдова" , "location" : "Молдове", "id" : "mol"}, 
					{"country" : "Казахстан" , "location" : "Казахстане", "id" : "kaz"}, 
					{"country" : "Армения" , "location" : "Армении", "id" : "arm"}, 
					{"country" : "Грузия" , "location" : "Грузии", "id" : "geo"}, 
					{"country" : "Таджикистан" , "location" : "Таджикистане", "id" : "taj"}, 
					{"country" : "Азербайджан" , "location" : "Азербайджане", "id" : "aze"},
					{"country" : "Узбекистан" , "location" : "Узбекистане", "id" : "uzb"}
				],
		'1824'  :  { "country" : "Латвия" , "location" : "Латвии", "id" : "lat" },
		'1624'  :  { "country" : "Литва" , "location" : "Литве", "id" : "lit" },
		'1302'  :  { "country" : "Эстония" , "location" : "Эстонии", "id" : "est" },
		'82300' :  { "country" : "Германия" , "location" : "Германии", "id" : "ger" },
		'4070'  :  { "country" : "Израиль" , "location" : "Израиле", "id" : "izr" }
		},
	 
		{
		'4449' : [
					{"country" : "Россия" , "location" : "России", "id" : "rus"},
					{"country" : "Беларусь" , "location" : "Беларуси", "id" : "bel"}, 
					{"country" : "Молдова" , "location" : "Молдове", "id" : "mol"}, 
					{"country" : "Казахстан" , "location" : "Казахстане", "id" : "kaz"}, 
					{"country" : "Армения" , "location" : "Армении", "id" : "arm"}, 
					{"country" : "Таджикистан" , "location" : "Таджикистане", "id" : "taj"}, 
					{"country" : "Азербайджан" , "location" : "Азербайджане", "id" : "aze"},
					{"country" : "Узбекистан" , "location" : "Узбекистане", "id" : "uzb"}
				],
		'4161'  :  {"country" : "Украина" , "location" : "Украине", "id" : "ukr"}, 
		'4107'  :  {"country"  : "Грузия" , "location" : "Грузии", "id" : "geo"}, 
		'1824'  :  { "country" : "Латвия" , "location" : "Латвии", "id" : "lat" },
		'1624'  :  { "country" : "Литва" , "location" : "Литве", "id" : "lit" },
		'1206'  :  { "country" : "Эстония" , "location" : "Эстонии", "id" : "est" },
		'82300' :  { "country" : "Германия" , "location" : "Германии", "id" : "ger" },
		'4070'  :  { "country" : "Израиль" , "location" : "Израиле", "id" : "izr" }
		},
		
		
		{
		'4446' : [
					{"country" : "Россия" , "location" : "России", "id" : "rus"},
					{"country" : "Беларусь" , "location" : "Беларуси", "id" : "bel"}, 					
					{"country" : "Украина" , "location" : "Украины", "id" : "ukr"}, 
					{"country" : "Молдова" , "location" : "Молдовы", "id" : "mol"}, 
					{"country" : "Казахстан" , "location" : "Казахстана", "id" : "kaz"}, 
					{"country" : "Армения" , "location" : "Армении", "id" : "arm"}, 
					{"country" : "Грузия" , "location" : "Грузии", "id" : "geo"}, 
					{"country" : "Таджикистан" , "location" : "Таджикистана", "id" : "taj"}, 
					{"country" : "Азербайджан" , "location" : "Азербайджана", "id" : "aze"}
				],
		'1824'  :  { "country" : "Латвия" , "location" : "Латвии", "id" : "lat" },
		'1624'  :  { "country" : "Литва" , "location" : "Литвы", "id" : "lit" },
		'1302'  :  { "country" : "Эстония" , "location" : "Эстонии", "id" : "est" },
		'82300' :  { "country" : "Германия" , "location" : "Германии", "id" : "ger" },
		'4070'  :  { "country" : "Израиль" , "location" : "Израиля", "id" : "izr" }
		},
	 
		{
		'4449' : [
					{"country" : "Россия" , "location" : "России", "id" : "rus"},
					{"country" : "Беларусь" , "location" : "Беларуси", "id" : "bel"}, 
					{"country" : "Молдова" , "location" : "Молдовы", "id" : "mol"}, 
					{"country" : "Казахстан" , "location" : "Казахстана", "id" : "kaz"}, 
					{"country" : "Армения" , "location" : "Армении", "id" : "arm"}, 
					{"country" : "Таджикистан" , "location" : "Таджикистана", "id" : "taj"}, 
					{"country" : "Азербайджан" , "location" : "Азербайджана", "id" : "aze"},
					{"country" : "Узбекистан" , "location" : "Узбекистана", "id" : "uzb"}
				],
		'4161'  :  {"country" : "Украина" , "location" : "Украины", "id" : "ukr"}, 
		'4107'  :  {"country" : "Грузия" , "location" : "Грузии", "id" : "geo"}, 
		'1824'  :  {"country" : "Латвия" , "location" : "Латвии", "id" : "lat" },
		'1624'  :  {"country" : "Литва" , "location" : "Литвы", "id" : "lit" },
		'1206'  :  {"country" : "Эстония" , "location" : "Эстонии", "id" : "est" },
		'82300' :  {"country" : "Германия" , "location" : "Германии", "id" : "ger" },
		'4070'  :  {"country" : "Израиль" , "location" : "Израиля", "id" : "izr" }
		}
	],
	id: "",
	opened : false,
	cookie :  "",
	cookieEnabled : navigator.cookieEnabled,
	userNumCont : "UserShortNumber",
	userCountryCont: "UserCountry",
	user_country : "",
	sms_number : "",
	user_location : "",
	default_sms_numbers : ["4446","4449","4446","4449"],
	default_user_location : "России",
	default_user_country : "Россия",
	defaultClassName : "numberList",
	
	getCountry: function() { 
		this.user_country = getCookie("country_id"); 
		if (!this.user_country) this.user_country = this.default_user_country ;
	},
	
	setCountry: function(c,n,l,id) { 
		setCookie("country_id",c);
		this.user_country = c;
		this.setParams(id,n,l);
		this.hide();
	},
	
	getParams : function(k) { 
	this.sms_number = this.default_sms_numbers[k];
	this.user_location = this.default_user_location;
		for(var i in this.numbers[k]) 
			if(this.numbers[k][i].length) {
				for (var j=0 ; j< this.numbers[k][i].length; j++){
				if (this.numbers[k][i][j]["id"] == this.user_country) { 
						this.sms_number = i;
						this.user_location = this.numbers[k][i][j]["location"];
						break;
				}}
			}else{
				if (this.numbers[k][i]["id"] == this.user_country) {  
						this.sms_number = i;
						this.user_location = this.numbers[k][i]["location"];
						break;
				}
			}
	},
			
	setParams: function(id,n,l) {  
		n = (typeof n == 'undefined') ? this.sms_number : n;
		l = (typeof l == 'undefined') ? this.user_location : l; 
		var uc = gebc(this.userCountryCont, "span"); 
	
		if (InfoBlock.openedGame != 'all') {
		var nc = gebi(this.userNumCont + "_" + id);  
		if (nc) nc.innerHTML = n; 
				
		}else {
			var gameHash = InfoBlock.getSMSHelp('all'); 
			for(var i = 0 ; i < gameHash.length; i++) {
			var nc = gebi(this.userNumCont + "_" + gameHash[i]["id"]); 
			this.getParams(gameHash[i]["kat"]); 
			if (nc) nc.innerHTML = this.sms_number;
		}
		}
		
		if (uc) for (var i = 0; i < uc.length; i++) if (uc[i]) uc[i].innerHTML = l;
	},
	
	getNumbersHTML : function(code, kat) { 
		var html = "";
		
		html = "								<div id=\"numberList_" + code + "\" class=\"smsgame contextInfo numberList\">\
													<div class=\"text-right close\"><a href=\"#\" onclick=\"SMSInfo.hide();return false;\"><img src=\"http://img.mail.ru/r/foto2/ico_close.gif\" border=\"0\" alt=\"Закрыть\" title=\"Закрыть\" /></a></div>\
													<div class=\"head\">\
														<span>Номер</span>\
														<span>Страна</span>\
													</div>\
													<ul class=\"ShortNumbers\">";
													for (var i in this.numbers[kat]) {
													if(i != "toJSONString") {
														if(this.numbers[kat][i].length > 1) {
															html += "<li class=\"group\">\
																		<div class=\"num\">" + i + "</div>\
																			<ul>";
															for (var j=0 ; j < this.numbers[kat][i].length; j++) 
																html += "<li onclick=\"SMSInfo.setCountry('" + this.numbers[kat][i][j]["id"] + "', '" + i + "', '" + this.numbers[kat][i][j]["location"] + "', '" + code + "')\">" + this.numbers[kat][i][j]["country"] + "</li>";
															
															html += "		</ul>\
																		<div class=\"t\" ></div>\
																		<div class=\"b\" ></div>\
																	</li>\
																	<li class=\"space\"></li>";
														}else {
															html += "<li>" + i ;
															html += "	<ul>\
																			<li onclick=\"SMSInfo.setCountry('" + this.numbers[kat][i]["id"] + "', '" + i + "', '" + this.numbers[kat][i]["location"] + "', '" + code + "')\">" + this.numbers[kat][i]["country"] + "</li>\
																		</ul>\
																	</li>";
															}
													}
													}
													html += "</ul>\
												</div>";
														
		return html;
	},
	
	show: function(id,evt) {
		id = "numberList_" + id;
		
		if(this.opened == id) {
			this.hide();
			return false;
		}
		this.hide();
		cancelBubbling(evt);
		if(gebi(id)) {
			gebi(id).style.display = "block";
			gebi(id).style.visibility = "visible"; /*IE fix who knows why?*/
		}
		this.opened = id;
		this.id = id;
		addHandler(document, 'click', function(e) {
			var e = e || window.event;
			if (e.button == 0 )	SMSInfo.hide();
		});
		
		return false;
	},

	hide: function() {
		var els = gebc(this.defaultClassName, "div");
		for(var i = 0; i < els.length; i++) 
			if (els[i]) 
				if (els[i].style.display == 'block') {
					els[i].style.display = 'none';
					els[i].style.display.visibility = "hidden"; /*IE fix who knows why?*/
				}
		this.opened = false;
	},
	
	init : function(id, k) {
		this.getCountry();
		this.getParams(k);
		this.setParams(id);
		document.write(this.getNumbersHTML(id,k));
	}

}


//убираем все подсказки
function hideContext() {
	//убираем подсказку к рейтингу (цветы и медали)
	awardHelpHide();
	//убираем подсказку к +10
	contextHelpVoteHide();
	//hide hint
	contextHelpHide();
	//убрираем смс подсказку 
	HideSMStop();
	//убираем сабменю
	InfoBlock.hide();
	
}

//метки в albumindex
function pasteTags(host) {
var i,j,k;
var tags_str;
	for (i in Tags) {
		if (i != 'toJSONString' ) {
			for(j in Tags[i]) {
				if (j != 'toJSONString' && j!= 'curbox' && j!= 'ownalbum') {
					tags_str = "";
					for (k=0 ; k < Tags[i][j].length; k++) {
						if (!Tags[i]["ownalbum"]) {
							if(k != 0) tags_str += "&nbsp; ";
							tags_str += "<a href=\"http:\/\/" + host + Tags[i]["curbox"] +"tags/" + Tags[i][j][k]["name"]+ "\">" + Tags[i][j][k]["tag"] + "</a>";
						}
						else {//ownalbum
							if(k != 0) tags_str += ", ";
							tags_str += Tags[i][j][k]["tag"];
						}
					}
				if (!Tags[i]["ownalbum"]) {
					if(tags_str != "") {
						if (gebi('tags_'+i+'_'+j)) gebi('tags_'+i+'_'+j).style.display = "block";
						if (gebi('links_'+i+'_'+j)) gebi('links_'+i+'_'+j).innerHTML = tags_str;
					}
				}
				else if (gebi('edit_tags_'+i+'_'+j)) gebi('edit_tags_'+i+'_'+j).value = tags_str;
				}
			}
		}
	}
}



/* bayan's */

function addInOurAlbDiv() {
	if (gebi('addinouralbDiv')) {
		if (gebi('addinouralbDiv').style.display == 'block') {
			gebi('addinouralbDiv').style.display = 'none';
			return;
		} else {
			//getAlbumsCallback();
			gebi('addinouralbDiv').style.display = 'block';
		}
	}
	else {
		var box = gebi('addInOurAlbBox');
		var coor = absPosition(box);
		var strDiv = '';
		var addinouralbDiv = document.createElement('DIV');
		addinouralbDiv.id = 'addinouralbDiv';
		strDiv = '<div class="addinouralbDivIn"><div id="addinouralbDivClose"><a href="javascript:;"><img alt="Закрыть" src="http://img.mail.ru/r/foto2/ico_close.gif"/></a></div>' +
		'<div id="addinouralbDivContent"><form method="post" id="addinouralbDivForm" name="addinouralbDivForm" onsubmit="return false;">' +
			'<h3>Добавить ролик в альбом</h3>' +
			'<p id="myAlbumsBlock">Получение списка альбомов</p>' +
			'<p class="button_add"><input id="addinouralb_submit" type="submit" value="Добавить" /></p>' +
		'</form></div>' + 
		'</div>';

		addinouralbDiv.innerHTML = strDiv;
		document.body.appendChild(addinouralbDiv);
		var y_amendment = ( window.attachEvent && (navigator.userAgent.toUpperCase().indexOf('OPERA') == -1) && parseFloat(window.navigator.userAgent.match(/msie\s(\d+.\d+)/i)[1]) < 8
		) ? -32 : 0;
		addinouralbDiv.style.top = coor.y + box.parentNode.offsetHeight + y_amendment + 2 + 'px';
		addinouralbDiv.style.left = coor.x + 'px';

		addHandler(document,'click', function() { if (gebi('addinouralbDiv')) gebi('addinouralbDiv').style.display = 'none'; });
		addHandler(gebi('addinouralb_submit'), 'click', function(){ addinouralbDiv_submit(); gebi('addinouralb_submit').disabled = 'true'; return false; });
		addHandler(gebi('addinouralbDivClose').firstChild,'click', function(e) {
			if (gebi('addinouralbDiv')) gebi('addinouralbDiv').style.display = 'none';
			cancelBubbling(e);
			return false;
		});
		addHandler(addinouralbDiv,'click', function(e) {					cancelBubbling(e); });
		addHandler(gebi('addInOurAlbBox'),'click', function(e) {	cancelBubbling(e); });
		addinouralbDiv.style.display = 'block';

		var result = ajax_call('perl_get_my_albums',i_hs,getAlbumsCallback);
	}
}

function getAlbumsCallback(status,obj) {
	if (status == 1) {
		if (myAlb.length == 0) {
			if (obj.Albums.length) myAlb = obj.Albums; 
			//else myAlb = [{'ID': '','AccDefault': 1,'Name': 'Moё видео'}];
			var myAlbL = myAlb.length;
			var optionsStr = '';
			var flag_myvideo = false;
			for (var i = 0; i < myAlbL; i++) {
				var selected = '';
				if (myAlb[i].AccDefault == 1) selected = 'selected="selected"';
				myAlb[i].Name = myAlb[i].Name.replace(/([^-a-zа-яёЁ0-9_\s\'])/ig, '_');
				if (myAlb[i].ID != '_vfavorites') optionsStr += '<option value="' + myAlb[i].ID + '"' + selected + '>' + myAlb[i].Name + '</option>';
			}
			if (gebi('myAlbumsBlock')) {
				gebi('myAlbumsBlock').style.padding = '0';
				gebi('myAlbumsBlock').style.border = '0 none';
				gebi('myAlbumsBlock').style.color = 'black';
				gebi('myAlbumsBlock').innerHTML = '<select id="myAlbums" name="myAlbums">' + optionsStr + '</select>';
			}
			else return;
		} else {
			if (!gebi('addinouralbDiv')) {
				if (confirm('У вас нет ни одного видеоальбома. \nВам будет создан альбом "Мои видео" и ролик будет помещён в него.')) {
					addinouralbDiv_submit();
				} else return;
			} else {
				gebi('addinouralbDiv').style.display = 'block';
			}
		}
	} else if (status == 0) {
			obj.AlbumName = obj.AlbumName.replace(/([^-a-zа-яёЁ0-9_\s\'])/ig, '_');
			gebi('addinouralbDivContent').innerHTML = '<p>У вас уже есть этот ролик в альбоме "' + obj.AlbumName + '"</p><p class="button_ok"><input type="button" value="Ok" onclick="if (gebi(\'addinouralbDiv\')) gebi(\'addinouralbDiv\').style.display = \'none\';" /></p>';
	}
}
function addinouralbDiv_submit() {
	var myAlbumsSel = document.addinouralbDivForm.myAlbums;
	var target_album_id = myAlbumsSel.options.length > 0 ? myAlbumsSel.options[myAlbumsSel.selectedIndex].value : '';
	var addinouralb_source_album_id = CurrentAlbumId();
	var addinouralb_source_item_id = CurrentImageId();
	var result = ajax_call('perl_move_to_me',addinouralb_source_album_id,addinouralb_source_item_id,target_album_id,moveToMeCallback) ;
}
function moveToMeCallback(status,obj) {
	if (typeof status != 'undefined') {
		if (status == 1) {
			obj.AlbumName = obj.AlbumName.replace(/([^-a-zа-яёЁ0-9_\s\'])/ig, '_');
			gebi('addinouralbDivContent').innerHTML = '<p>Ролик успешно добавлен<br />в ваш альбом<br />"<a href="' + obj.Url + '"><b>' + obj.AlbumName + '</b></a>"</p><p class="button_ok"><input type="button" value="Ok" onclick="if (gebi(\'addinouralbDiv\')) gebi(\'addinouralbDiv\').style.display = \'none\';" /></p>';
			gebi('addInOurAlbBox').style.visibility = 'hidden';
		} else {
			gebi('addinouralbDivContent').innerHTML = '<p>Ошибка добавления ролика в свой альбом:<br />' + obj.Error + '</p><p class="button_ok"><input type="button" value="Ok" onclick="if (gebi(\'addinouralbDiv\')) gebi(\'addinouralbDiv\').style.display = \'none\';" /></p>';
		}
	} else alert('Добавить ролик в свой альбом не получилось. Попробуйте ещё раз.');
}
/* bayan's end */

// Status dogs-icon onload
var arrMRIMStatus;
var arrTagsI, arrTagsA;
function getTagsMrimStatus(class_name,tag_name)
{
	var mrimstatus_url;
	var arrTags, emails = [];
	
	switch (tag_name) {
		case "I" : arrTags = arrTagsI; break;
		case "A" : arrTags = arrTagsA; break;
	}
	var arrTags = gebc(class_name,tag_name);
	var arrTagsL = arrTags.length;
	arrMRIMStatus = [];
	for (var i = 0; i < arrTagsL; i++)
	{
		if (arrTags[i].className && arrTags[i].className != 'undefined' && arrTags[i].className.indexOf(class_name) != -1) {
			arrMRIMStatus[arrMRIMStatus.length] = arrTags[i];
			
			if(arrTags[i].getAttribute("email")) 
				emails.push(arrTags[i].getAttribute("email")); 
			else if(arrTags[i].getAttribute("href")) {
				var arr = arrTags[i].href.match(/to\=(\S*)$/);
				if(arr[1]) emails.push(arr[1]);
			}	
			
		}
	}
	
	switch (tag_name) {
		case "I" : arrTagsI = arrTags; break;
		case "A" : arrTagsA = arrTags; break;
	}
	
	if(emails.length > 0) {
		mrimstatus_url = emails.join(","); 
		if (mrimstatus_url != '') return mrimstatus_url;
	}
	else return "";
}


function mrimstatus_callback(mrimstatus,error)
{
	var arrMrimStatus_callback = mrimstatus.split('');
	var arrMrimStatus_callbackL = arrMrimStatus_callback.length;
	for (var i = 0; i < arrTagsI.length; i++)
	{
		switch (arrMrimStatus_callback[i]) {
		case '1' :
			arrTagsI[i].className = 'f2_mrim_status f2_on';
			break;
		case '2' :
			arrTagsI[i].className = 'f2_mrim_status f2_left';
			break;
		default :
			arrTagsI[i].className = 'f2_mrim_status f2_off';
			break;
		}
	}
	
	for (var a = 0; a < arrTagsA.length; a++)
	{
		switch (arrMrimStatus_callback[i+a]) {
		case '1' :
			arrTagsA[a].className += ' mrim-online_9';
			break;
		case '2' :
			arrTagsA[a].className += ' mrim-away_9';
			break;
		default :
			arrTagsA[a].className += ' mrim-offline_9';
			break;
		}
	}
}
register_dready( function(){
	var mrimstatus_url = "";
	mrimstatus_url += getTagsMrimStatus('f2_mrim_status','I');
	mrimstatus_url += (mrimstatus_url != "") ? "," : "" ;
	mrimstatus_url += getTagsMrimStatus('spr-mrim-9','A');
	if (mrimstatus_url) {
		mrimstatus_url = "http://" + VideoPerlHost() + "/proxy-mrim-status?" + mrimstatus_url;
		ajax_call_nomagick(mrimstatus_url, mrimstatus_callback);
	}
});

function checkTitleLength(el,max) {
	var len,st;
	if(el) {
		st = el.value;
		len = el.value.length;
		if(len > max) {  
			st = st.substr(0,max);
			el.value = st; 
			return false;
		}
	}	
}

function switch_wanttalk(s) {
	var d = $$(".mf_divWantTalk")[0], a1 = $$(".mf_divWantTalkHide a")[0], a2 = $$(".mf_divWantTalkHide a")[1];
	var c,w;
	
	c = getCookie("wanttalk"); 
	
	if(s == 1) { 
		w = (c == 0) ? 0 : 1;
	}
	else {
		w = (c == 0) ? 1 : 0;
		setCookie("wanttalk", w);
	}
				
	if(w) { 
		a2.removeClassName("hidden");
		a1.addClassName("hidden");
		d.removeClassName("hidden");
	}
	else {	
		a2.addClassName("hidden");
		a1.removeClassName("hidden");
		d.addClassName("hidden");
	}
}

function req_stat(url, dstId, oncontready, append, timeout, onerror) {
	
	var _s = arguments.callee;
	if(!_s.urls) _s.urls = {};
	
	var key = url+'_'+dstId;
	if( _s.urls[key] && _s.urls[key] == 2 ){
		return oncontready();
	}
		
	_s.urls[key] = 1;
		
	if(typeof onerror != 'function')
		onerror = function(){}
		
	try {
		var req = !!window.XMLHttpRequest ? (new XMLHttpRequest()) : (new ActiveXObject("Microsoft.XMLHTTP"));
	} catch(e) {
		onerror(1, '', e);
	}
	
	if (req) {
		try {
			var tmr = false;
			var timeoutFired = false;
			if(timeout)
				tmr = window.setTimeout(function(){
					onerror(0, '', {});
					timeoutFired = true;
				}, timeout*1000);
				
			req.onreadystatechange=function() {
				if (req.readyState==4) {
					window.clearTimeout(tmr);
					if(timeoutFired)
						return;
					if (req.status==200 || req.status==0) {
						
						var e = document.getElementById(dstId);
						if(!e) {
							onerror(4, req.responseText, {});
							return;
						}
							
						if(!append) {
							e.innerHTML += req.responseText;
						} else {
							var d = document.createElement('div');
							d.innerHTML = req.responseText;
							var len = d.childNodes.length;
							for(var i=0; i<len; i++) {
								e.appendChild(d.childNodes[i]);
							}
							d=null;
						}
						e=null;
						_s.urls[key] = 2;
						try {
							oncontready();
						} catch (e){
							onerror(5, req.responseText, e);
						}
						
					} else {
						onerror(2, '', {});
					}
				}
				
			}
			
			if(/*@cc_on!@*/false && parseInt(window.navigator.userAgent.match(/msie\s(\d+.\d+)/i)[1]) == 6 ) {
				if( url.indexOf('?') != -1 )
					url += '&r' + Math.random();
				else
					url += '?r' + Math.random();
			}
				
			req.open('GET', url, true);
			req.send('');
		} catch (e){
			onerror(3, '', e);
		}
	}
}
