// Переменные для формы добавления клуба
var oTownCustomName;
var oTown;

var oMetroAddBtn;
var oMetroAddBtnFirstParent;
var aMetroLines = new Object();
var iMetroCount = 1;

var oPhoneAddBtn;
var oPhoneAddBtnFirstParent;
var aPhoneNumbers = new Object();
var iPhoneCount = 1;

var oPhotoAddBtn;
var oPhotoAddBtnFirstParent;
var aPhotos = new Object();
var iPhotoCount = 1;

var o24h;
var o24hLabel;
var oWorkSheet;

// Переменные словаря
var oResultList;
var aListItems = new Array();
var iSelected = 0;

// как обычно, объявляем переменные
var oRatingContainer;
var oVoteValueInput;
var oRatingValue;
var iRatingBorder = 0;
var iBeginX = 0;
var iBeginY = 0;
var iNewPosition = 0;
var bMousePressed = false;
var bFirstTime = true;
var iLeftAddon = -18;
var iValue = 1;

// переменные для работы с комментариями

var oReadCommentsLink;
var oAddCommentLink;
var oCommentsList;
var oAddingCommentForm;

// переменные и метод для формы добавления тренера
var bTwo = false;

// переменные для схемы мышц

var oFrontManMap;
var aFrontMaps;
var aMaps = new Object();
aMaps["Front"] = new Array();
aMaps["Back"] = new Array();
var aImgShown = new Object();

// Переменная для поиска

var oSearchInput;

// Переменные для фотогаллереи

var oPhotoGallery;
var oGalleryFullImg;
var aGalleryImages = new Array();
var oGallerySelected;

// Методы для фотогаллереи

function InitPhotoGallery()
{
		oPhotoGallery		= document.getElementById('Photogallery');
		oGalleryFullImg		= document.getElementById('FullImg').firstChild;

	var aTemp				= oPhotoGallery.getElementsByTagName('div');
		
		for( var i = 0; i < aTemp.length; i++ )
			if( aTemp[i].className == 'PvImg' )
				aGalleryImages[aGalleryImages.length] = new PhotoGalleryItem( aTemp[i] );
			else if (aTemp[i].className == 'PvImg Selected')
			{
				aGalleryImages[aGalleryImages.length] = oGallerySelected = new PhotoGalleryItem( aTemp[i] );
			}
}

function PhotoGalleryItem( oContainer )
{
	var self = this;
		this.oContainer		= oContainer;
		this.oLink			= this.oContainer.firstChild;
		this.oPreview		= this.oLink.firstChild;
		this.sSrcBig		= this.oPreview.getAttribute('src-big');

		this.oLink.onclick	= function()
		{
			self.EnableSelf();
			return false;
		}
}

PhotoGalleryItem.prototype.EnableSelf = function()
{
	if( oGallerySelected )
		oGallerySelected.DisableSelf();
	
	oGalleryFullImg.src = this.sSrcBig;
	this.oContainer.className = 'PvImg Selected';
		
	oGallerySelected = this;
}

PhotoGalleryItem.prototype.DisableSelf = function()
{
	this.oContainer.className = 'PvImg';
	oGallerySelected = null;
}


function CheckIfEmpty() {
	if(oSearchInput.value == '') oSearchInput.value = 'поиск по форуму';
	oSearchInput.className = (oSearchInput.value == 'поиск по форуму') ? 'Empty' : '';
}

function CheckIfEmptyForFocus() {
	if(oSearchInput.value == 'поиск по форуму') oSearchInput.value = '';
		oSearchInput.className = '';
}

function InitCheckExpirience() {
	var oExpInput = document.getElementById('ExpInput');
	var oExpLabel = document.getElementById('ExpLabel');
	oExpInput.onchange = function() {CheckExpirience(oExpLabel, oExpInput);}
}

function CheckExpirience(oExpLabel, oExpInput) {
	bTwo = (oExpInput.value.length == 2 && parseInt(oExpInput.value.substr( oExpInput.value.length - 2, 1 )) == 1) ? true : false;
	switch(parseInt(oExpInput.value.substr(oExpInput.value.length - 1 ))) {
		case 1:
			oExpLabel.innerHTML = bTwo ? 'лет' : 'год';
			break;
		case 2:
			oExpLabel.innerHTML = bTwo ? 'лет' : 'года';
			break;
		case 3:
			oExpLabel.innerHTML = bTwo ? 'лет' : 'года';
			break;
		case 4:
			oExpLabel.innerHTML = bTwo ? 'лет' : 'года';
			break;
		default:
			oExpLabel.innerHTML = 'лет';
			break;
	}
}
										


// инициализация

window.onload = function() {	 
	if (document.getElementById('FullImg')) InitPhotoGallery();
	if (document.getElementById('SiteMapSearch')) { 
		oSearchInput = document.getElementById('SiteMapSearch');
		oSearchInput.onblur = CheckIfEmpty;
		oSearchInput.onfocus = CheckIfEmptyForFocus;
		CheckIfEmpty();
	}
	if (document.getElementById('AddAdvice')) { document.getElementById('AddAdvice').onclick = function(){ window.open('/netcat/?catalogue=1&sub=419','advice'); return false; } }
	if (document.getElementById('NewsSubscription')) { document.getElementById('NewsSubscription').onclick = function(){ window.open('/maillist/subscription/','subscription','toolbar=0,status=0,menubar=0,scrollbars=0,resizable=0,width=500,height=400,dependent=yes'); return false; } }
	if (document.getElementById('WindowClose')) { opener.location=opener.location; document.getElementById('WindowClose').onclick = function(){ window.close(); return false; } }
	if (document.getElementById('AddWordLink')) { document.getElementById('AddWordLink').onclick = function(){ window.open('/fitnes/dictionary/newword/','addword','toolbar=0,status=0,menubar=0,scrollbars=0,resizable=0,width=520,height=500,dependent=yes'); return false; } }
	if (document.getElementById('AuthLink')) { document.getElementById('AuthLink').onclick = function(){ window.open('/auth/','auth','toolbar=0,status=0,menubar=0,scrollbars=0,resizable=0,width=400,height=440,dependent=yes'); return false; } }
	if (document.getElementById('RecoveryLink')) { document.getElementById('RecoveryLink').onclick = function(){ window.open('/auth/recovery/','recovery','toolbar=0,status=0,menubar=0,scrollbars=0,resizable=0,width=400,height=440,dependent=yes'); return false; } }
	if (document.getElementById('DoPollLink')) { document.getElementById('DoPollLink').onclick = function(){ window.open('/poll/','poll','toolbar=0,status=0,menubar=0,scrollbars=0,resizable=0,width=400,height=500,dependent=yes'); return false; } }
	if (document.getElementById('PhotoEdit') || document.getElementById('Photos')) onPhotoPageLoad();
	if (document.getElementById('AddingClubForm')) onClubPageLoad();
	if (document.getElementById('DictionaryHeader') || document.getElementById('DictionaryResultList')) InitList();
	if (document.getElementById('HistoryRatingForm')) InitRating(); 
	if (document.getElementById('CommentsCount')) InitComments();
	if (document.getElementById('ExpInput') && document.getElementById('ExpLabel')) InitCheckExpirience();
	if (document.getElementById('FrontMan') && document.getElementById('BackMan')) InitMaps();
	if (document.getElementById('MemberSearchForm') && document.getElementById('MemberSearchLink') && document.getElementById('MemberSearchArrow')) InitFindFriends();
	if (document.getElementById('AddToFavorite')) { document.getElementById('AddToFavorite').onclick = function() {addBookmark('http://www.getfit.ru', 'GetFit.ru | Главный фитнес портал');} }
	return false;
}

// Действие при загрузке страницы
function onPhotoPageLoad() {
	oPhotoAddBtn = document.getElementById('PhotoAdd');
	oPhotoAddBtnFirstParent = oPhotoAddBtn.parentNode;
	oPhotoAddBtn.onclick = AddPhoto;
}

function onClubPageLoad() {

	if (document.getElementById('oTownCustomName')) {
		oTownCustomName = document.getElementById('TownCustomName');
		oTown = document.getElementById('City');
		oTownCustomName.onchange = function(){ CheckTown(); }
	}
	
	oWorkSheet = document.getElementById('WorkSheet');
	
	o24h = document.getElementById('ClubWholeDay');
	o24hLabel = document.getElementById('ClubWholeDayLabel');
	o24h.onclick = o24hLabel.onclick = CheckWorkTime;
	
//	oMetroAddBtn = document.getElementById('MetroAdd');
//	oMetroAddBtnFirstParent = oMetroAddBtn.parentNode;
	
	oPhoneAddBtn = document.getElementById('PhoneAdd');
	oPhoneAddBtnFirstParent = oPhoneAddBtn.parentNode;

	oPhotoAddBtn = document.getElementById('PhotoAdd');
	oPhotoAddBtnFirstParent = oPhotoAddBtn.parentNode;

	InitForm();
}

// Проверяем, не надо ли выключить селект с городами 
function CheckTown() {
	oTown.disabled = ( oTownCustomName.value != '' );
}

// Проверяем при нажатии на "круглосуточно", что там надо включить/выключить
function CheckWorkTime() {
	if(o24h.checked) {
		oWorkSheet.style.display = 'none';
	} else {
		oWorkSheet.style.display = '';
	}
}

//
// Метро
//
function MetroStation() {
	var self = this;
	this.ID = iMetroCount;
	this.oNewMetroInput = document.createElement('input');
	this.oNewMetroInput.type = 'text';
	this.oNewMetroInput.className = 'MediumText';
	this.oNewMetroInput.name = 'Metro[' + iMetroCount + ']';

	this.oMetroMinusBtn = document.createElement('input');
	this.oMetroMinusBtn.type = 'button';
	this.oMetroMinusBtn.name = 'MetroMinus';
	this.oMetroMinusBtn.className = 'MinusBtn';
	this.oMetroMinusBtn.value = '-';
	this.oMetroMinusBtn.onclick = function(){ self.RemoveSelf(); return false; }

	this.oRow = document.createElement('tr');
	this.oRow.id = 'MetroLine' + this.ID;

	var oTempElement = document.createElement('td');
	oTempElement.className = 'Label';
	this.oRow.appendChild(oTempElement);

	oTempElement = document.createElement('td');
	oTempElement.appendChild(this.oNewMetroInput);
	this.oRow.appendChild(oTempElement);

	oTempElement = document.createElement('td');
	oTempElement.className = 'Right';

	this.oRow.appendChild(oTempElement);

	oMetroAddBtn.parentNode.parentNode.parentNode.insertBefore(this.oRow,  oMetroAddBtn.parentNode.parentNode.nextSibling);
	oTempElement.appendChild(oMetroAddBtn);
	oTempElement.appendChild(this.oMetroMinusBtn);

	this.bLast = true;
}

// Добавляем строчку для станции метро
function AddMetro() {
	if(aMetroLines[iMetroCount]) aMetroLines[iMetroCount].bLast = false;

	iMetroCount++;
	aMetroLines[iMetroCount] = new MetroStation();

}

// Удаляем строчку со станцией метро
MetroStation.prototype.RemoveSelf = function() {
	if(this.bLast) {
		var bHaveSome = 0;
		for( var bJ in aMetroLines ) {
			if(aMetroLines[bJ] != false) bHaveSome++; 
		}
		if( bHaveSome > 1) {
			for( var j = this.ID - 1; j > 0;  j--) {
				if( aMetroLines[j] ) {
					aMetroLines[j].bLast = true;
					aMetroLines[j].oMetroMinusBtn.parentNode.insertBefore( oMetroAddBtn, aMetroLines[j].oMetroMinusBtn );
					break;
				}
			}
		} else {
			oMetroAddBtnFirstParent.appendChild( oMetroAddBtn );
		}
	}
	this.oRow.parentNode.removeChild( this.oRow );
	aMetroLines[this.ID] = false;
}

//
// Телефон
//
function PhoneNumber() {
	var self = this;
	this.ID = iPhoneCount;
/*
	this.oNewPhoneCodeInput = document.createElement('input');
	this.oNewPhoneCodeInput.type = 'text';
	this.oNewPhoneCodeInput.name = 'PhoneCode[' + iPhoneCount + ']';
	this.oNewPhoneCodeInput.className = 'Code';
	this.oNewPhoneCodeInput.setAttribute("maxlength", "3");
	this.oNewPhoneCodeInput.setAttribute("size", "3");
*/
	
	this.oNewPhoneInput = document.createElement('input');
	this.oNewPhoneInput.type = 'text';
	this.oNewPhoneInput.name = 'Phone[' + iPhoneCount + ']';
	this.oNewPhoneInput.value = '(495)';

	this.oPhoneMinusBtn = document.createElement('input');
	this.oPhoneMinusBtn.type = 'button';
	this.oPhoneMinusBtn.name = 'PhoneMinus';
	this.oPhoneMinusBtn.className = 'MinusBtn';
	this.oPhoneMinusBtn.value = '-';
	this.oPhoneMinusBtn.onclick = function(){ self.RemoveSelf(); return false; }
											
	this.oRow = document.createElement('tr');

	var oTempElement = document.createElement('td');
	oTempElement.className = 'Label';
	this.oRow.appendChild( oTempElement );


	oTempElement = document.createElement('td');
	oTempElement.className = 'Phone';
	this.oRow.appendChild( oTempElement );
											
//	oTempElement.appendChild( document.createTextNode('+7') );
//	oTempElement.appendChild( this.oNewPhoneCodeInput );
	oTempElement.appendChild( this.oNewPhoneInput );
											
	oTempElement = document.createElement('td');
	oTempElement.className = 'Right';
										
	this.oRow.appendChild(oTempElement);
											
	oPhoneAddBtn.parentNode.parentNode.parentNode.insertBefore(this.oRow,  oPhoneAddBtn.parentNode.parentNode.nextSibling);
	oTempElement.appendChild(oPhoneAddBtn);
	oTempElement.appendChild(this.oPhoneMinusBtn);

	this.bLast = true;
}
									
// Добавляем номер телефона
function AddPhone() {
	if(aPhoneNumbers[iPhoneCount]) {
		aPhoneNumbers[iPhoneCount].bLast = false;
	}

	iPhoneCount++;
	aPhoneNumbers[iPhoneCount] = new PhoneNumber();
}
									
// Удаляем номер телефона
PhoneNumber.prototype.RemoveSelf = function() {
	if(this.bLast) {
		var bHaveSome = 0;
		for(var bJ in aPhoneNumbers) {
			if(aPhoneNumbers[bJ] != false) bHaveSome++; 
		}
		if(bHaveSome > 1) {
			for(var j = this.ID - 1; j > 0;  j--) {
				if(aPhoneNumbers[j]) {
					aPhoneNumbers[j].bLast = true;
					aPhoneNumbers[j].oPhoneMinusBtn.parentNode.insertBefore(oPhoneAddBtn, aPhoneNumbers[j].oPhoneMinusBtn);
					break;
				}
			}
		} else {
			oPhoneAddBtnFirstParent.appendChild(oPhoneAddBtn);
		}
	}
	this.oRow.parentNode.removeChild(this.oRow);
	aPhoneNumbers[this.ID] = false;
}


//
// Фотографии
//
function Photo() {
	var self = this;
	this.ID = iPhotoCount;
	this.oNewPhotoThumbFileInput = document.createElement('input');
	this.oNewPhotoThumbFileInput.type = 'file';
	this.oNewPhotoThumbFileInput.className = 'MediumText';
	this.oNewPhotoThumbFileInput.name = 'PhotoThumb[' + iPhotoCount + ']';

	this.oNewPhotoThumbFileInputComment = document.createElement('span');
	this.oNewPhotoThumbFileInputComment.className = 'SmallGrey';
	this.oNewPhotoThumbFileInputComment.appendChild(document.createTextNode('Размер файла не должен привышать 1 Мегабайт.'));
	
	this.oNewPhotoFileInput = document.createElement('input');
	this.oNewPhotoFileInput.type = 'file';
	this.oNewPhotoFileInput.className = 'MediumText';
	this.oNewPhotoFileInput.name = 'Photo[' + iPhotoCount + ']';

	this.oNewPhotoFileInputComment = document.createElement('span');
	this.oNewPhotoFileInputComment.className = 'SmallGrey';
	this.oNewPhotoFileInputComment.appendChild(document.createTextNode('Размер файла не должен привышать 1 Мегабайт.'));	
	
	this.oNewPhotoNameInput = document.createElement('input');
	this.oNewPhotoNameInput.type = 'text';
	this.oNewPhotoNameInput.className = 'MediumText';
	this.oNewPhotoNameInput.name = 'PhotoName[' + iPhotoCount + ']';

	this.oPhotoMinusBtn = document.createElement('input');
	this.oPhotoMinusBtn.type = 'button';
	this.oPhotoMinusBtn.name = 'PhotoMinus';
	this.oPhotoMinusBtn.className = 'MinusBtn';
	this.oPhotoMinusBtn.value = '-';
	this.oPhotoMinusBtn.onclick = function(){ self.RemoveSelf(); return false; }
											
	this.oRow = document.createElement('tr');
	this.oRow.className = 'Photos';
	var oTempElement = document.createElement('td');
	oTempElement.className = 'Label';
	this.oRow.appendChild(oTempElement);

	oTempElement = document.createElement('td');
	oTempElement.className = 'Medium';
	this.oRow.appendChild(oTempElement);
																
										
	oTempElement.appendChild(document.createTextNode('Название фотографии'));
	oTempElement.appendChild(document.createElement('br'));
	oTempElement.appendChild(this.oNewPhotoNameInput);
	oTempElement.appendChild(document.createElement('br'));
	oTempElement.appendChild(document.createTextNode('Фотография'));
	oTempElement.appendChild(document.createElement('br'));
	oTempElement.appendChild(this.oNewPhotoFileInput);
	oTempElement.appendChild(document.createElement('br'));
	oTempElement.appendChild(this.oNewPhotoFileInputComment);
	oTempElement.appendChild(document.createElement('br'));
											
	oTempElement = document.createElement('td');
	oTempElement.className = 'Right';
										
	this.oRow.appendChild(oTempElement);
											
	oPhotoAddBtn.parentNode.parentNode.parentNode.insertBefore(this.oRow, oPhotoAddBtn.parentNode.parentNode.nextSibling);
	oTempElement.appendChild(oPhotoAddBtn);
	oTempElement.appendChild(this.oPhotoMinusBtn);

	this.bLast = true;
}
									
// Добавляем фотографию
function AddPhoto() {
	if(aPhotos[iPhotoCount]) {
		aPhotos[iPhotoCount].bLast = false;
	}

	iPhotoCount++;
	aPhotos[iPhotoCount] = new Photo();
}
									
// Удаляем фотографию
Photo.prototype.RemoveSelf = function() {
	if(this.bLast) {
		var bHaveSome = 0;
		for(var bJ in aPhotos) {
			if(aPhotos[bJ] != false) bHaveSome++; 
		}
		if(bHaveSome > 1) {
			for(var j = this.ID - 1; j > 0;  j--) {
				if(aPhotos[j]) {
					aPhotos[j].bLast = true;
					aPhotos[j].oPhotoMinusBtn.parentNode.insertBefore(oPhotoAddBtn, aPhotos[j].oPhotoMinusBtn);
					break;
				}
			}
		} else {
			oPhotoAddBtnFirstParent.appendChild(oPhotoAddBtn);
		}
	}
	this.oRow.parentNode.removeChild(this.oRow);
	aPhotos[this.ID] = false;
}


// Инициализация реакций.
function InitForm() {
	if (document.getElementById('oTownCustomName')) {
		oTownCustomName.onchange = CheckTown;
	}
//	oMetroAddBtn.onclick = AddMetro;
	oPhoneAddBtn.onclick = AddPhone;
	oPhotoAddBtn.onclick = AddPhoto;
}


function InitList() {
	var oResultList = document.getElementById('DictionaryResultList');

	if(oResultList) aTempListItems = oResultList.getElementsByTagName('li');

	for(var i = 0; i < aTempListItems.length; i++) aListItems[(i+1)] = new ListItem(aTempListItems[i], (i+1));
}


function ListItem(oParent, iNumber) {
	var self = this;
	this.ID = iNumber;
	this.oContainer = oParent;
	this.oTitle = this.oContainer.getElementsByTagName('span')[0];
	if(this.oTitle) {
		this.oDescription = this.oContainer.getElementsByTagName('div')[0];
													
		this.oTitle.onclick = function(){ self.SelectMe(); return false; }
													
		if(this.oContainer.className == "Selected") iSelected = this.ID;
	}
}

											
ListItem.prototype.SelectMe = function() {
	if(iSelected) aListItems[iSelected].oContainer.className = "";
												
	this.oContainer.className = "Selected";
	iSelected = this.ID;
}

// функции для работы с комментариями

function InitComments() {
	if (document.getElementById('ReadComments')) oReadCommentsLink = document.getElementById('ReadComments');
	oAddCommentLink = document.getElementById('AddComment');
	oCommentsList = document.getElementById('CommentsList');
	oAddingCommentForm = document.getElementById('CommentLoginForm');
	
	if(oReadCommentsLink && oCommentsList) oReadCommentsLink.onclick = ShowComments;

	if(oAddCommentLink && oAddingCommentForm) oAddCommentLink.onclick = ShowAddCommentForm;
}

function ShowComments() {
	if(oAddCommentLink) oAddCommentLink.className = "";

	if(oAddingCommentForm) oAddingCommentForm.className = "";

	if(oReadCommentsLink) oReadCommentsLink.className = "Selected";

	if(oCommentsList) oCommentsList.className = "Enabled";
}

function ShowAddCommentForm() {
	if(oReadCommentsLink) oReadCommentsLink.className = "";

	if(oCommentsList) oCommentsList.className = "";

	if(oAddCommentLink) oAddCommentLink.className = "Selected";

	if(oAddingCommentForm) oAddingCommentForm.className = "Enabled";
}

// конец функций для работы с комментариями

// инициализация этого таскательного добра.
function InitRating() 
{
	oRatingContainer = document.getElementById('RatingContainer');
	oRatingValue = document.getElementById('RatingValue');
	oVoteValueInput = document.getElementById('VoteValueInput');

	// говорим, мол, все это должно работать, если нажали
	// на левую кнопку мыши.
	if( document.addEventListener )
	{
		// это если Мозилла и т.д.
		document.addEventListener("mousedown", GotIt, true);
	} else {
		// это оставшимся (IE)
		document.onmousedown = GotIt;
	}
}

function GotIt( oEvent )
{
	if( !iRatingBorder )
	{
		// если мы тут первый раз вообще нажали,
		// то определим границы таскания
		// и интервалы. Считаем что у нас 9 интервалов
		// (можно вынести в переменную и менять интервалы,
		// как захочется ;-)
		iRatingBorder = oRatingContainer.parentNode.offsetWidth;
		iOneValue = iRatingBorder / 9;
	
		// берем значение по умолчанию. В целом можно и не делать,
		// но в HTML пустые дивы лучше не оставлять, поэтому там
		// уже что-то есть. Его и возьмем, чтобы не прыгало число.
		iValue = oRatingValue.innerText;
	}
	
	// как обычно, проверяем разные браузеры на всякую фигню
	oEvent = ( oEvent ) ? oEvent : event;
	oTargetElement = ( oEvent.target ) ? oEvent.target : oEvent.srcElement;
	if(
		oTargetElement
		&& ( 
				oTargetElement.id == "RatingContainer"
				|| (
					oTargetElement.parentNode
					&& oTargetElement.parentNode.id == "RatingContainer"
					)
				|| (
					oTargetElement.parentNode
					&& oTargetElement.parentNode.parentNode
					&& oTargetElement.parentNode.parentNode.id == "RatingContainer"
					)
			)
	){
		// мол, если нажали в нужном месте на мышку,
		// то тогда начинаем таскать. 
		// Проверка, конечно, настроена на конкретно этот случай,
		// поэтому при изменении HTML имеет смысл поменять проверку.
		// (скажем на цикл while с вложенностью parentNode)

		if( document.body.setCapture )
			document.body.setCapture();

		if( bFirstTime )
		{
			// Если нажали первый раз,
			// определим место, где бегунок вообще стоял в начале.
			// (относительно мышки, конечно)
			iBeginX = oEvent.clientX;
			iBeginY = oEvent.clientY;
			bFirstTime = false;
		}
		// не используемая переменная, но пусть будет :-)
		bMousePressed = true;
		if( document.addEventListener )
		{
			document.addEventListener("mouseup", StopIt, true);
			document.addEventListener("mousemove", TrailingRatingMoving, true);
		} else {
			document.onmouseup = StopIt;
			document.onmousemove = TrailingRatingMoving;
		}
	}
}

// Собственно, движение.
function TrailingRatingMoving( oEvent )
{
	oEvent = ( oEvent ) ? oEvent : event;
	
	// считаем нужный сдвиг
	iNewPosition = ( oEvent.clientX - iBeginX ) + iLeftAddon;
	// если он вышел за пределы допустимого, возвращаем к границам
	if( iNewPosition < iLeftAddon )
		iNewPosition = iLeftAddon;
	else if ( iNewPosition > (iRatingBorder + iLeftAddon ))
		iNewPosition = (iRatingBorder + iLeftAddon);
	
	// двигаем бегунок
	oRatingContainer.style.left = iNewPosition + "px";
	// смотрим, не пора ли сменить большую цифру
	iTempNewValue = Math.round( ( iNewPosition - iLeftAddon ) / iOneValue ) + 1;
	if( iTempNewValue != iValue )
	{
		// меняем, если пора
		// (это нужно делать именно вот так редко, иначе IE сильно тормозит
		// на подобных заменах. 
		// На innerHTML и innerText тормозит еще больше. ;-)
		iValue = iTempNewValue;
		oRatingValue.replaceChild( document.createTextNode( iValue ),  oRatingValue.firstChild);
		// и hidden input тоже обновляем, ессно.
		oVoteValueInput.value = iValue;
	}
	// это для IE, чтобы он все остальные теоретически навешенные функции
	// на onmousemove не вызывал
	// (например, таким образом не даем ему делать selection текста)
	oEvent.cancelBubble = true;
	return false;
}

// Довольно! (с) мультик "Золотая Антилопа"
function StopIt( oEvent )
{
	oEvent = ( oEvent ) ? oEvent : event;
	bMousePressed = false;
	var iTemp = iOneValue * ( oRatingValue.innerHTML - 1) + iLeftAddon;
	
	// хотим пла-а-авно сдвинуть бегунок ровно на соответствующую цифре засечку на шкале,
	// мол, прилипает он к ней
	// (выключено, но если захочется - можно раскомментировать, а след. строчку закомментировать ;-)
	
	//setTimeout('SlowMotionToCorrectPlace(' + iNewPosition + ',' + iTemp + ', 1)' , 10);
	
	oRatingContainer.style.left = iTemp + "px";
	
	if( document.removeEventListener )
	{
		document.removeEventListener("mouseup", StopIt, true);
		document.removeEventListener("mousemove", TrailingRatingMoving, true);
	} else {
		// всем спасибо, все свободны. ;-)
		document.onmouseup = null;
		document.onmousemove = null;
		document.body.releaseCapture()
	}
}

// "мягкая" функция, вызываемая по таймауту
function SlowMotionToCorrectPlace( iFrom, iTo, iCount )
{
	iStep = ( iTo - iFrom ) / 10;
	iCount++;
	if( Math.abs( iTo - iFrom ) <= Math.abs( iStep ) || ( iStep < 1 && iCount > 30 ))
	{
		oRatingContainer.style.left = iTo + "px";
		return false;
	}
	iFrom = iFrom + iStep;
	oRatingContainer.style.left = iFrom + "px";
	setTimeout('SlowMotionToCorrectPlace(' + iFrom + ',' + iTo + ',' + iCount +')' , 10);
}


// 	Мужское тельце

function InitMaps() {
	oFrontManMap = document.getElementById('FrontMan_Map');
	if(oFrontManMap) aMaps["Front"] = oFrontManMap.getElementsByTagName('area');
	aBackManMap = document.getElementById('BackMan_Map');
	if(aBackManMap) aMaps["Back"] = aBackManMap.getElementsByTagName('area');
	if(aMaps) {
		for(var j in aMaps) {
			for(var i=0; i < aMaps[j].length; i++) {
				if(isNaN(parseInt(aMaps[j][i].id.substr(aMaps[j][i].id.length - 1)))) {
					aMaps[j][i].setAttribute('imgtoshow', aMaps[j][i].id.substr(4));
				} else {
					aMaps[j][i].setAttribute('imgtoshow', aMaps[j][i].id.substr(4, aMaps[j][i].id.length - 5));
				}
				aMaps[j][i].setAttribute('pictoshow', j);
				aMaps[j][i].onmouseover = function(){ ShowImg(this.getAttribute('imgtoshow'), this.getAttribute('pictoshow')); return false; }
//						aMaps[j][i].onmouseout = function(){ HideImg(eval(j)); return true; }
			}
		}
	}
}
	
function ShowImg(sTempID, sIsFront) {
	if(aImgShown[sIsFront]) aImgShown[sIsFront].className = "";
	aImgShown[sIsFront] = document.getElementById(sTempID);
	if(aImgShown[sIsFront]) aImgShown[sIsFront].className = "Enabled";
}

function HideImg(sIsFront) {
	if(aImgShown[sIsFront]) aImgShown[sIsFront].className = "";
	aImgShown[sIsFront] = null;
}


// Поиск друзей

//
// Это другой кусок: для показа вообще формы поиска. ;)
//

function InitFindFriends() {
	var oMemberSearchForm = document.getElementById('MemberSearchForm');
	var oMemberSearchLink = document.getElementById('MemberSearchLink');
	var oMemberSearchArrow = document.getElementById('MemberSearchArrow');
	if (oMemberSearchLink && oMemberSearchForm) oMemberSearchLink.onclick = function(){ ShowHideMemberSearchForm(oMemberSearchForm, oMemberSearchLink, oMemberSearchArrow); return false; }
}

function ShowHideMemberSearchForm(oMemberSearchForm, oMemberSearchLink, oMemberSearchArrow) {
	if(oMemberSearchForm.className == "Enabled") {
		oMemberSearchForm.className = "";
		oMemberSearchArrow.src = "/i/ArrowDownObjectHidden.gif";
	} else {
		oMemberSearchForm.className = "Enabled";
		oMemberSearchArrow.src = "/i/ArrowUpObjectShown.gif";
	}
}

function addBookmark(url, title) {
	if (!url) url = location.href;
	if (!title) title = document.title;
 
	//Gecko
	if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) window.sidebar.addPanel (title, url, "");
	//IE4+
	else if (typeof window.external == "object") window.external.AddFavorite(url, title);
	//Opera7+
	else if (window.opera && document.createElement) {
		var a = document.createElement('A');
		if (!a) return false; //IF Opera 6
		a.setAttribute('rel','sidebar');
		a.setAttribute('href',url);
		a.setAttribute('title',title);
		a.click();
	} else return false;
	return true;
}