var mySelects = new Array("prof1", "prof2", "filter_all", "filter_prof", "filter_company", "filter_unic", "filter_mode", "filter_type");

var dragObj = new Object();
var draggedSkill = new Object();
var dragContent;
var currentObj;

var NN = (document.all ? false : true);
var dx, dy;
document.onmousedown = startDrag;
document.onmouseup = endDrag;

// Предварительная загрузка элитных рамок
var e1 = new Image(); e1.src = "/img/build/border_elite_1.gif";
var e2 = new Image(); e1.src = "/img/build/border_elite_2.gif";
var e3 = new Image(); e1.src = "/img/build/border_elite_3.gif";
var e4 = new Image(); e1.src = "/img/build/border_elite_4.gif";
var e5 = new Image(); e1.src = "/img/build/border_elite_5.gif";
var e6 = new Image(); e1.src = "/img/build/border_elite_6.gif";
var e7 = new Image(); e1.src = "/img/build/border_elite_7.gif";
var e8 = new Image(); e1.src = "/img/build/border_elite_8.gif";


var ProfImages = new Array("unknown", "warrior", "ranger", "elementalist", "monk", "necromancer", "mesmer", "assassin", "ritualist", "dervish", "paragon");
var ProfTitle = new Array("*", "W", "R", "E", "Mo", "N", "Me", "A", "Rt", "D", "P");

var ProfSelector = new Array();
ProfSelector[0]  = new Array(0, "* Любая професссия");
ProfSelector[1]  = new Array(7, "Assassin [Ассасин]");
ProfSelector[2]  = new Array(9, "Dervish [Дервиш]");
ProfSelector[3]  = new Array(3, "Elementalist [Маг Стихий]");
ProfSelector[4]  = new Array(6, "Mesmer [Месмер]");
ProfSelector[5]  = new Array(4, "Monk [Монах]");
ProfSelector[6]  = new Array(5, "Necromancer [Некромант]");
ProfSelector[7]  = new Array(10, "Paragon [Совершенный]");
ProfSelector[8]  = new Array(2, "Ranger [Рейнджер]");
ProfSelector[9]  = new Array(8, "Ritualist [Ритуалист]");
ProfSelector[10] = new Array(1, "Warrior [Воин]");

// Список PvP версий
var pvpSkill = new Array();
pvpSkill[1365] = 146; //Ward Against Melee (PvP)  
pvpSkill[1366] = 120; //Lightning Orb (PvP)       
pvpSkill[1367] = 484; //Aegis (PvP)
pvpSkill[1368] = 1090; //"Watch Yourself!" (PvP)
pvpSkill[1369] = 618; //Enfeeble (PvP)
pvpSkill[1370] = 974; //Flesh of My Flesh (PvP)
pvpSkill[1371] = 931; //Ancestors' Rage (PvP)
pvpSkill[1372] = 947; //Splinter Weapon (PvP)
pvpSkill[1373] = 85; //Assassin's Remedy (PvP)
pvpSkill[1374] = 226; //Blinding Surge (PvP)
pvpSkill[1375] = 571; //Light of Deliverance (PvP)
pvpSkill[1376] = 294; //Mystic Sweep (PvP)
pvpSkill[1377] = 291; //Eremite's Attack (PvP)
pvpSkill[1378] = 1034; //Death Pact Signet (PvP)
pvpSkill[1379] = 783; //Harrier's Toss (PvP)
pvpSkill[1380] = 762; //Ballad of Restoration (PvP)
pvpSkill[1381] = 776; //Song of Restoration (PvP)
pvpSkill[1382] = 736; //"Never Surrender!" (PvP)
pvpSkill[1383] = 348; //Energy Drain (PvP)
pvpSkill[1384] = 349; //Energy Tap (PvP)
pvpSkill[1385] = 150; //Ether Renewal (PvP)
pvpSkill[1386] = 837; //Penetrating Attack (PvP)
pvpSkill[1387] = 67; //Shadow Form (PvP)
pvpSkill[1388] = 688; //Discord (PvP)
pvpSkill[1389] = 899; //Sundering Attack (PvP)
pvpSkill[1390] = 1001; //Ritual Lord (PvP)
pvpSkill[1391] = 733; //"Incoming!" (PvP)
pvpSkill[1392] = 748; //Defensive Anthem (PvP)

// Список PvE версий
var pveSkill = new Array();
pveSkill[146] = 1365; //Ward Against Melee (PvE)
pveSkill[120] = 1366; //Lightning Orb (PvE)
pveSkill[484] = 1367; //Aegis (PvE)
pveSkill[1090] = 1368; //"Watch Yourself!" (PvE)
pveSkill[618] = 1369; //Enfeeble (PvE)
pveSkill[974] = 1370; //Flesh of My Flesh (PvE)
pveSkill[931] = 1371; //Ancestors' Rage (PvE)
pveSkill[947] = 1372; //Splinter Weapon (PvE)
pveSkill[85] = 1373; //Assassin's Remedy (PvE)
pveSkill[226] = 1374; //Blinding Surge (PvE)
pveSkill[571] = 1375; //Light of Deliverance (PvE)
pveSkill[294] = 1376; //Mystic Sweep (PvE)
pveSkill[291] = 1377; //Eremite's Attack (PvE)
pveSkill[1034] = 1378; //Death Pact Signet (PvE)
pveSkill[783] = 1379; //Harrier's Toss (PvE)
pveSkill[762] = 1380; //Ballad of Restoration (PvE)
pveSkill[776] = 1381; //Song of Restoration (PvE)
pveSkill[736] = 1382; //"Never Surrender!" (PvE)
pveSkill[348] = 1383; //Energy Drain (PvE)
pveSkill[349] = 1384; //Energy Tap (PvE)
pveSkill[150] = 1385; //Ether Renewal (PvE)
pveSkill[837] = 1386; //Penetrating Attack (PvE)
pveSkill[67] = 1387; //Shadow Form (PvE)
pveSkill[688] = 1388; //Discord (PvE)
pveSkill[899] = 1389; //Sundering Attack (PvE)
pveSkill[1001] = 1390; //Ritual Lord (PvE)
pveSkill[733] = 1391; //"Incoming!" (PvE)
pveSkill[748] = 1392; //Defensive Anthem (PvE)

var AttributePoints = new Array(0, 1, 3, 6, 10, 15, 21, 28, 37, 48, 61, 77, 97);

var remember = 0;
var oldType = 0;
var CurrentSkill = 0;

// Включаем Ajax
function newAjax()
{
	/* Создание нового объекта XMLHttpRequest для общения с Web-сервером */
	var xmlHttp = false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try 
	{
	  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e) 
	{
		try 
		{
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (e2) 
		{
			xmlHttp = false;
		}
	}
	@end @*/

	if (!xmlHttp && typeof XMLHttpRequest!='undefined') 
	{
		try 
		{
			xmlHttp = new XMLHttpRequest();
		} 
		catch (e) 
		{
			xmlHttp = false;
		}
	}
	if (!xmlHttp && window.createRequest) 
	{
		try 
		{
			xmlHttp = window.createRequest();
		} 
		catch (e) 
		{
			xmlHttp = false;
		}
	}

	return xmlHttp;
}

// Действия при выборе первой профессии
function changeProf()
{
	// Получаем индекс первой профессии
	var prof = Math.round(document.editor.prof1.value);
	if (prof > 10 || prof < 0) { prof = 0;}

	document.editor.tcode.value = "";
	
	// Задаем картинку первой профессии
	document.getElementById("prof_image").className = "profimage " + ProfImages[prof];

	// Обнуляем список атрибутов, список и фильтр скилов (?), 
	document.getElementById("primary_attributes").innerHTML = "";
	document.getElementById("secondary_attributes").innerHTML = "";
	document.getElementById("filter_skill_list").innerHTML = "";		
	
	// Блокируем элементы формы
	document.editor.prof2.disabled = true;
	
	// Меняем заголовок по первой профессии
	if (prof != 0)
	{
		document.getElementById("prof_title").innerHTML = ProfTitle[prof] + " / *";
		var p2s = document.editor.prof2;
		
		p2s.options.length = 0;
		p2s.options.length = 10;
		var j = 0;
		for (i=0; i<=10; i++)
		{
			if (ProfSelector[i][0] != prof)
			{
				p2s.options[j].value = ProfSelector[i][0];
				p2s.options[j].text = ProfSelector[i][1];
				++j;
			}
		}
		document.editor.prof2.disabled = false;
	}
	else
	{
		document.getElementById("prof_title").innerHTML = "";
		document.editor.prof2.options.length = 0;
	}

	// Активируем элементы фильтра
	if (prof != 0)
	{
		// Убираем вторую профессию из списка профессий
		document.editor.filter_prof.length = 1;
		document.editor.filter_prof[0].value = 1;
		document.editor.filter_prof[0].text = "первой профессии";

		document.editor.filter_all.disabled = false;
		document.editor.filter_prof.disabled = false;
		document.editor.filter_company.disabled = false;
		document.editor.filter_unic.disabled = false;
		document.editor.filter_mode.disabled = false;
		document.editor.filter_type.disabled = false;
	}
	// Блокируем элементы фильтра
	else
	{
		document.editor.filter_all.disabled = true;
		document.editor.filter_prof.disabled = true;
		document.editor.filter_company.disabled = true;
		document.editor.filter_unic.disabled = true;
		document.editor.filter_mode.disabled = true;
		document.editor.filter_type.disabled = true;
	}
	
	changeMode(1);
	clearSB();
	
	// Вызов Ajax для загрузки списка атрибутов первой профессии
	var url = "/cgi-bin/include/ajax/getAttributes.pl?type=primary&id=" + escape(prof);
	ajaxProf = newAjax();
	ajaxProf.open("GET", url, true);
	ajaxProf.onreadystatechange = updateAttributes1;
	ajaxProf.send(null);	
	
	attributeInText();
}


// Действия при выборе второй профессии
function changeProf2()
{
	// Получаем индекс первой профессии
	var prof = Math.round(document.editor.prof1.value);
	if (prof > 10 || prof < 0) { prof = 0;}

	document.editor.tcode.value = "";
	
	// Получаем индекс второй профессии
	var prof2 = Math.round(document.editor.prof2.value);
	if (prof2 > 10 || prof2 < 0) { prof2 = 0;}
	if (prof2 == prof) { prof2 = 0;}
	
	document.getElementById("prof_title").innerHTML = ProfTitle[prof] + " / " + ProfTitle[prof2];
	document.getElementById("secondary_attributes").innerHTML = "";

	if (prof2 != 0)
	{
		// Добавляем вторую профессию в спиской профессий
		document.editor.filter_prof.length = 2;
		document.editor.filter_prof[0].value = 1;
		document.editor.filter_prof[0].text = "первой профессии";
		document.editor.filter_prof[1].value = 2;
		document.editor.filter_prof[1].text = "второй профессии";
	}
	
	if (document.editor.filter_prof.value != 1)
	{
		document.getElementById("filter_skill_list").innerHTML = "";	
	}
	
	changeMode(1);
	clearSB();
	
	// Вызов Ajax для загрузки списка атрибутов второй профессии
	var url = "/cgi-bin/include/ajax/getAttributes.pl?type=secondary&id=" + escape(prof2);
	ajaxProf2 = newAjax();
	ajaxProf2.open("GET", url, true);
	ajaxProf2.onreadystatechange = updateAttributes2;
	ajaxProf2.send(null);
}


// Обновление списка праймери-аттрибутов
function updateAttributes1()
{
	if (ajaxProf.readyState == 4) 
	{
    	var response = ajaxProf.responseText;
		document.getElementById("primary_attributes").innerHTML = response;
		attributeInText();
		resetAttr();
	}
}

// Обновление списка секондари-аттрибутов
function updateAttributes2()
{
	if (ajaxProf2.readyState == 4) 
	{
    	var response = ajaxProf2.responseText;
		document.getElementById("secondary_attributes").innerHTML = response;
		attributeInText();
		resetAttr();
	}
}

// Изменение режима выбора кампании
function companyChange()
{
	// Получаем индекс селектора кампании
	var company = Math.round(document.editor.filter_company.value);
	if (company > 4 || company < 0) { company = 0;}
	
	if (company != 0)
	{
		// Добавляем режим выбора
		document.editor.filter_unic.length = 2;

		document.editor.filter_unic[0].value = 0;
		document.editor.filter_unic[0].text = "все доступные умения";
		document.editor.filter_unic[1].value = 1;
		document.editor.filter_unic[1].text = "уникальные для кампании";
	}
	else
	{
		// Урезаем режим выбора
		document.editor.filter_unic.length = 1;
		document.editor.filter_unic[0].value = 0;
		document.editor.filter_unic[0].text = "все доступные умения";
	}
}

// Изменение режима выборки в фильтре
function changeMode(myMode)
{
	if (myMode == 1) { remember = 1;} else { remember = 0;}
	
	// Получаем режим выборки
	var mode = Math.round(document.editor.filter_mode.value);
	if (mode != 1 && mode != 2) { mode = 0;}

	// Получаем профессию выборки 
	var fprof = Math.round(document.editor.filter_prof.value);
	if (fprof != 2) { fprof = 1;}
	
	// Получаем индекс первой профессии
	var prof = Math.round(document.editor.prof1.value);
	if (prof > 10 || prof < 0) { prof = 0;}

	// Получаем индекс второй профессии
	var prof2 = Math.round(document.editor.prof2.value);
	if (prof2 > 10 || prof2 < 0) { prof2 = 0;}
	if (prof2 == prof) { prof2 = 0;}
	
	if (remember == 1)
	{
		oldType = Math.round(document.editor.filter_type.value);
	}
	else
	{
		oldType = 0;
	}
	
	// Вызов Ajax для загрузки списка атрибутов первой профессии
	var url = "/cgi-bin/include/ajax/getTypeList.pl?mode=" + mode;
	if (fprof == 2) { url += "&prof=" + prof2; } else { url += "&prof=" + prof; }
	ajaxMode = newAjax();	
	ajaxMode.open("GET", url, true);
	ajaxMode.onreadystatechange = updateTypeList;
	ajaxMode.send(null);	
}

// Обновление списка секондари-аттрибутов
function updateTypeList()
{
	if (ajaxMode.readyState == 4) 
	{
		var typeList = ajaxMode.responseText.split(";");
		document.editor.filter_type.length = 0;
		document.editor.filter_type.length = (typeList.length)/2;
		j = 0; var rememberJ = 0; rememberV = 0;
		for (i=0; i<typeList.length; i=i+2)
		{
			document.editor.filter_type[j].value = typeList[i];
			document.editor.filter_type[j].text = typeList[i+1];
			if (remember == 1 && typeList[i] == oldType)
			{
				document.editor.filter_type.selectedIndex = j;
			}
			++j;
		}
	}
}


// Отправляем запрос на список скилов по фильру
function getSkillList()
{
	// Меняем кнопку на "Занято"
	document.getElementById("filter_skill_list").innerHTML = '<div align="center"><img src="/img/build/buttons/loading.gif" alt="" /></div>';

	// Вызов Ajax для загрузки списка атрибутов первой профессии
	var url = "/cgi-bin/include/ajax/getSkillList.pl?all=" + escape(document.editor.filter_all.value);
	url += "&prof=" + escape(document.editor.filter_prof.value);
	url += "&company=" + escape(document.editor.filter_company.value);
	url += "&unic=" + escape(document.editor.filter_unic.value);	
	url += "&mode=" + escape(document.editor.filter_mode.value);
	url += "&type=" + escape(document.editor.filter_type.value);
	url += "&prof1=" + escape(document.editor.prof1.value);
	url += "&prof2=" + escape(document.editor.prof2.value);
	url += "&pvp=" + escape(document.editor.pvp.value);
	ajaxSkillList = newAjax();	
	ajaxSkillList.open("GET", url, true);
	ajaxSkillList.onreadystatechange = updateSkillList;
	ajaxSkillList.send(null);	
}

// Вывод списка скилов в нужное место
function updateSkillList()
{
	if (ajaxSkillList.readyState == 4) 
	{
		document.getElementById("filter_skill_list").innerHTML = ajaxSkillList.responseText;
		document.getElementById("filter_skill_list").scrollTop = 0;
		// Меняем кнопку на "Готово"
	}
}

// Очищаем template-code
function clearTCode()
{
	document.editor.tcode.value = "";
}

// Обнуление ненужных аттрибутов
function resetAttr()
{
	// Получаем сумму аттрибут-поинтов
	var attrSumm = 0;
	for (i=0; i<document.editor.elements.length; ++i)
	{
		if (document.editor.elements[i].name.indexOf("attrValue_") != -1)
		{
			var myV = Math.abs(document.editor.elements[i].value);
			if (myV > 12) { myV = 12;}
			if (myV < 1)  { myV = 0;}
			attrSumm += AttributePoints[myV];
		}
	}
	document.getElementById("attr_summ").innerHTML = attrSumm + " (из 200)";
	attrButtonSwitch();
}

// Отключение лишних кнопок
function attrButtonSwitch()
{
	var attrSumm = 0;
	for (i=0; i<document.editor.elements.length; ++i)
	{
		if (document.editor.elements[i].name.indexOf("attrValue_") != -1)
		{
			var myV = Math.abs(document.editor.elements[i].value);
			if (myV > 12) { myV = 12;}
			if (myV < 1)  { myV = 0;}
			attrSumm += AttributePoints[myV];
		}
	}

	for (i=0; i<document.editor.elements.length; ++i)
	{
		if (document.editor.elements[i].name.indexOf("attrValue_") != -1)
		{
			var bData = document.editor.elements[i].name.split("_");
			b2check = Math.abs(document.editor.elements[i].value);
			
			bMinus = document.getElementById("buttonMinus_"+bData[1]);
			bPlus  = document.getElementById("buttonPlus_"+bData[1]);
			ost = 200 - attrSumm;
			
			if (isNaN(b2check) || b2check == "")
			{
				bMinus.src = "/img/build/buttons/formdownoff.gif";
				if (ost < AttributePoints[b2check+1] - AttributePoints[b2check])
				{
					bPlus.src = "/img/build/buttons/formupoff.gif";
				}
				else
				{
					bPlus.src = "/img/build/buttons/formup.gif";
				}
			}
			else if (b2check >= 12)
			{
				bPlus.src = "/img/build/buttons/formupoff.gif";
				bMinus.src = "/img/build/buttons/formdown.gif";
			}
			else
			{			
				if (ost < AttributePoints[b2check+1] - AttributePoints[b2check])
				{
					bPlus.src = "/img/build/buttons/formupoff.gif";
				}
				else
				{
					bPlus.src = "/img/build/buttons/formup.gif";
				}
				
				bMinus.src = "/img/build/buttons/formdown.gif";
			}
		}
	}
}


// Вычисление значения аттрибута
function calcAttr(attrId, act)
{
	if (act != "-") { act = "+"; }
	var vName = document.getElementById("attrValue_" + attrId);
	var vValue = Math.abs(vName.value);
	if (isNaN(vValue) || vValue == "") { vValue = 0;}

	// Получаем сумму аттрибут-поинтов
	var attrSumm = 0;
	for (i=0; i<document.editor.elements.length; ++i)
	{
		if (document.editor.elements[i].name.indexOf("attrValue_") != -1)
		{
			var myV = Math.abs(document.editor.elements[i].value);
			if (myV > 12) { myV = 12;}
			if (myV < 1)  { myV = 0;}
			attrSumm += AttributePoints[myV];
		}
	}

	if (attrSumm <= 200)
	{
		var nextValue = Math.abs(vValue) + 1;
		// Проверяем на доступность аттрибут-поинтов
		if (
			(act == "+" && vValue < 12 && (attrSumm - AttributePoints[vValue] + AttributePoints[nextValue]) <= 200 ) 
			|| act != "+" && vValue > 0
		   )
		{
			if (act == "+")	 { ++vValue;   } else { --vValue;}
			if (vValue >= 0 && vValue <= 12) { document.editor.tcode.value = "";}
			if (vValue > 12) { vValue = 12;}	
			if (vValue < 1)  { vValue = 0;}
		
			if (act == "+")  { attrSumm += AttributePoints[vValue] - AttributePoints[vValue-1];}
			else			 { attrSumm += AttributePoints[vValue] - AttributePoints[vValue+1];}

			if (vValue == 0) { vValue = "";}
			vName.value = vValue;
		}
	}
	
	document.getElementById("attr_summ").innerHTML = attrSumm + " (из 200)";
	
	// Отключение лишних кнопок
	attrButtonSwitch();
	
	// Переписываем раскладку аттрибутов
	attributeInText();
}

// Вычисляем головной убор
function calcHead(attrId)
{
	var hName = document.getElementById("headValue_" + attrId);
	var hValue = hName.value;

	if (hValue == "+1") 
	{
		hValue = "";
		document.getElementById("buttonCheck_"+attrId).src = "/img/build/buttons/checkno.gif";
	}
	else 
	{
		hValue = "+1";
		document.getElementById("buttonCheck_"+attrId).src = "/img/build/buttons/checkyes.gif";
	}
	hName.value = hValue;

	// Убираем другой головной убор
	for (i=0; i<document.editor.elements.length; ++i)
	{
		if (document.editor.elements[i].name.indexOf("headValue_") != -1)
		{
			cData = document.editor.elements[i].name.split("_");
			if (cData[1] != attrId)
			{
				document.editor.elements[i].value = "";
				document.getElementById("buttonCheck_"+cData[1]).src = "/img/build/buttons/checkno.gif";
			}
		}
	}
	
	document.editor.tcode.value = "";
	
	// Переписываем раскладку аттрибутов
	attributeInText();
}


// Формируем текстовую раскладку аттрибутов
function attributeInText()
{
	var attrText = new Array();
	var z = -1;
	for (i=0; i<document.editor.elements.length; ++i)
	{
		if (document.editor.elements[i].name.indexOf("attrValue_") != -1)
		{
			aBase = 0;
			aHead = 0;
			aRune = 0;
			
			var aData = document.editor.elements[i].name.split("_");
			aBase = Math.abs(document.editor.elements[i].value);
			if (isNaN(aBase) || aBase == "") { aBase = 0;}
			if (aBase > 12) { aBase = 12;}

			if (document.getElementById("headValue_"+aData[1]))
			{
				aHead = document.getElementById("headValue_"+aData[1]).value;
				if (aHead != "+1") { aHead = 0;} else { aHead = 1;}

				aRune = Math.abs(document.getElementById("runeValue_"+aData[1]).value);
				if (aRune >= 1 && aRune <= 3) { } else { aRune = 0;}
			}
			
			aName = document.getElementById("attrName_"+aData[1]).innerHTML;
			aTotal = aBase + aHead + aRune;
			
			if (aTotal > 0)
			{
				++z;
				attrText[z] = "<div class=\"name\"><div class=\"level\">";
				if (aBase < 10) { spacer = "&nbsp;&nbsp;&nbsp;" } else { spacer = "&nbsp;"}
				if (document.getElementById("headValue_"+aData[1]))
				{
					attrText[z] += aTotal + spacer + "(" + aBase + "+" + aRune + "+" + aHead + ")";
				}
				else
				{
					attrText[z] += aTotal + spacer + "(" + aBase + ")";
				}
				attrText[z] += "</div>" + aName + "</div>";
			}
		}
	}

	if (z <= 5) { maxSize = 3; }
	else 		{ maxSize = Math.ceil((z+1)/2); }

	var attrHtml = "";
	if (z >= 0)
	{
		attrHtml = "<div>";	
		for (i=0; i<=z; ++i)
		{
			if (i == maxSize) { attrHtml += "</div><div>";}
			attrHtml += attrText[i];
		}
		attrHtml += "</div>";
	}
	document.getElementById("attributeInText").innerHTML = attrHtml;
	
}


// Показ полного описания скила в фильтре
function sfd(mylink, sID, aID, dMode)
{
	var skillPos = 0;
	if (dMode == 1)
	{
		skillPos = sID;
		sID = SkillBar[skillPos][0];
		aID = SkillBar[skillPos][4];
	}
	CurrentSkill = sID;
	
	// Получение уровня аттрибута
	var aTotal = 0;
	if (document.getElementById("attrValue_"+aID))
	{
		var aBase = Math.abs(document.editor.elements["attrValue_"+aID].value);;
		if (isNaN(aBase) || aBase == "") { aBase = 0;}
		if (aBase > 12) { aBase = 12;}

		var aHead = 0;
		var aRune = 0;
			
		if (document.getElementById("headValue_"+aID))
		{
			aHead = document.getElementById("headValue_"+aID).value;
			if (aHead != "+1") { aHead = 0;} else { aHead = 1;}

			aRune = Math.abs(document.getElementById("runeValue_"+aID).value);
			if (aRune >= 1 && aRune <= 3) { } else { aRune = 0;}
		}
		aTotal = aBase + aHead + aRune;
	}
	
	// Вызов Ajax для загрузки описания скила
	if (sID > 0)
	{
		// Показ картинки "Загружаю"
		document.getElementById("skillinfo").innerHTML = '<img src="/img/build/buttons/loading.gif" alt="" />';

		var url = "/cgi-bin/include/ajax/showSkillDescription.pl?" + escape(sID) + "." + escape(aTotal);
		ajaxSkillDesc = newAjax();	
		ajaxSkillDesc.open("GET", url, true);
		ajaxSkillDesc.onreadystatechange = updateSFD;
		ajaxSkillDesc.send(null);	

		var obj = document.getElementById("skillinfo");
		var coors = findPos(mylink);
		var xoff, yoff;
	
		// Если показываем описания в скилбаре
		if (dMode == 1)
		{
			yoff = window.Event ? 67 : 67;
			xoff = skillPos == 8 ? -20 : 0;
			
			// Скрываем селекты в IE
			if (document.all && !window.opera)
			{
				for (z=0; z<mySelects.length; z++)
				{
					document.editor.elements[mySelects[z]].style.visibility = "hidden";
				}
			}
		}
		else
		{
			yoff = window.Event ? -22 : 1;
			// Обрабатываем смещение для Оперы 
			if (window.opera)
			{
				yoff = 0;
			}
			else
			{
				yoff -= document.getElementById("filter_skill_list").scrollTop;
			}
			xoff = 40;
		}
	
		obj.style.top = (coors[1]+yoff) + 'px';
		obj.style.left = (coors[0]+xoff) + 'px';
		obj.style.display = 'block';
	}
}

function updateSFD()
{
	if (ajaxSkillDesc.readyState == 4) 
	{
		document.getElementById("skillinfo").innerHTML = ajaxSkillDesc.responseText;
	}
}

// Скрытие полного описания скила в фильтре
function hideSkillInfo()
{
	document.getElementById("skillinfo").innerHTML = "";
	document.getElementById("skillinfo").style.display = "none";
	
	// Делаем видимыми select'ы
	if (document.all && !window.opera)
	{
		for (z=0; z<mySelects.length; z++)
		{
			document.editor.elements[mySelects[z]].style.visibility = "visible";
		}
	}
}



// Добавление скила в скилбар
function AddSB(sid)
{
	if (document.editor.elements["skill_full_id_"+sid].value != '')
	{
		var skillData = document.editor.elements["skill_full_id_"+sid].value.split("@");
		var state = 0; var free = 0;

		// Запускаем перебор 
		for (i=1; i<=8; i++)
		{
			// Запоминаем свободную ячейку
			if (free == 0 && SkillBar[i][0] == 0) { free = i;}

			// Делаем чек-ап наличия скила в билде
			if (skillData[0] == SkillBar[i][0]) { state = 2; free = 0; break;}
			
			// Делаем чекап на альтернативные версии скилов
			if (pveSkill[skillData[0]] == SkillBar[i][0] || pvpSkill[skillData[0]] == SkillBar[i][0])
			{ state = 2; free = 0; break;}
			
			// Делаем чек-ап элитного скила
			if (skillData[1] == 1 && SkillBar[i][1] == 1) { state = 1; free = 0; break;}
		}

		// Обрабатываем результат перебора
		if (free == 0)
		{
			if (state == 2)
			{
				alert("Это умение уже добавлено в линейку.");
			}
			else if (state == 1)
			{
				alert("Нельзя разместить в линейке два элитных умения.");
			}
			else
			{
				alert("Нет свободных мест в линейке умений. Прежде чем добавить новое умение, удалите какое-либо умение из линейки.");
			}
		}
		else
		{
			// Добавляем скил в скиллбар
			var skillHTML = '';
			if (skillData[1] == 1) 
			{
				skillHTML += "<div class=\"border elite elite" + free + "\"></div>";
			}
			else
			{
				skillHTML += "<div class=\"border normal" + free + "\"></div>";
			}
			
			var icoHref = skillData[7].toLowerCase();
			var reg = /(«|»|'|\!| |\.|,|(\(pv[pe]\)))/gi;
			icoHref = icoHref.replace(reg, "");
			var reg = /[\(\)]/gi;
			icoHref = icoHref.replace(reg, "");
			
			if (ProfImages[skillData[3]] != "unknown" && ProfImages[skillData[3]] != "")
			{
				icoHref = "/img/skills/" + ProfImages[skillData[3]] + "/" + icoHref +".jpg";
			}
			else
			{
				icoHref = "/img/skills/" + icoHref +".jpg";
			}
			var cashIco = new Image();
			cashIco.src = icoHref;
			cashIco.onLoad = yahoo();
			
			skillHTML += "<div class=\"ico\"><img src=\"" + icoHref + "\" alt=\"\" /></div>";
			
			var countType = ""; 
			if (skillData[6] == 10)			{ countType = "enchantment";}
			else if (skillData[6] == 12)	{ countType = "hex";}
			else if (skillData[6] == 13)	{ countType = "lead";}
			else if (skillData[6] == 9)		{ countType = "offhand";}
			else if (skillData[6] == 11)	{ countType = "dual";}
			else if (skillData[6] == 24)	{ countType = "weapon";}
			if (countType != "")			{ skillHTML += "<div class=\"type " + countType + "\"></div>";}

			var mustFollow = "";
			if (skillData[5] == 12)			{ mustFollow = "musthex";}
			else if (skillData[5] == 13)	{ mustFollow = "mustlead";}
			else if (skillData[5] == 9)		{ mustFollow = "mustoffhand";}
			else if (skillData[5] == 11)	{ mustFollow = "mustdual";}
			if (mustFollow != "")			{ skillHTML += "<div class=\"must " + mustFollow + "\"></div>";}
			
			var iecheck = 0;
			if (NN || window.opera) { iecheck = 1;}
			else
			{
				if (confirm(skillData[7]+"\n\nХотите добавить это умение в линейку?")) { iecheck = 1;}
			}

			if (iecheck == 1)
			{
				document.getElementById("skill_" + free).innerHTML = skillHTML;
				document.getElementById("skillname_" + free).innerHTML = skillData[7];
			
				// Записываем данные в контрольную таблицу
				SkillBar[free] = skillData;
				document.editor.elements["skill_data_"+free].value = skillData.join("@");

				document.editor.tcode.value = "";
			}			
		}
	}
}

// Заглушка для IE
function yahoo () {}


// Очищаем скиллбар при смене профессии
function clearSB()
{
	// Получаем индекс первой профессии
	var prof = Math.round(document.editor.prof1.value);
	if (prof > 10 || prof < 0) { prof = 0;}

	// Получаем индекс второй профессии
	var prof2 = Math.round(document.editor.prof2.value);
	if (prof2 > 10 || prof2 < 0) { prof2 = 0;}
	if (prof2 == prof) { prof2 = 0;}

	// Перебираем скиллбар
	for (i=1; i<=8; ++i)
	{
		if (SkillBar[i][3] != prof && SkillBar[i][3] != prof2 && SkillBar[i][3] != 0)
		{
			// Удаляем скилл из линейки
			document.getElementById("skill_" + i).innerHTML = "<div class=\"border normal" + i +"\"></div>";
			SkillBar[i] = Array(0, 0, 0, 0, 0, 0, 0, "");
			document.editor.elements["skill_data_"+i].value = "0@0@0@0@0@0@0@";
			document.getElementById("skillname_" + i).innerHTML = "&nbsp;";
		}
	}
}


// Прячем драгдив
function hideDD()
{
	if (dragContent != "")
	{
		draggedSkill.innerHTML = dragContent;
	}
	document.getElementById("dragdiv").style.display = "none";
	document.getElementById("dragdiv").innerHTML = "";
	dragContent = "";	
}

function hideDDFull()
{
	if (dragContent != "" && ddSID >= 1 && ddSID <= 8)
	{
		// Определяем координаты сброса драгдива
		var DD = document.getElementById("dragdiv");
		var coors = findPos(DD);
		var ddX, ddY;
		ddX = coors[0]; ddY = coors[1];

		// Удаление скила 
		if (ddY > 610 || ddY < 482 || ddX > 704 || ddX < 107)
		{
			document.getElementById("skill_" + ddSID).innerHTML = "<div class=\"border normal" + ddSID +"\"></div>";
			SkillBar[ddSID] = Array(0, 0, 0, 0, 0, 0, 0, "");
			document.editor.elements["skill_data_" + ddSID].value = "0@0@0@0@0@0@0@";
			document.getElementById("skillname_" + ddSID).innerHTML = "&nbsp;";
		}
		// Перемещение скила
		else
		{
			var newSID = 0;
			for (i=1; i<=8; ++i)
			{
				if (ddX < SBcellsX[i])
				{
					newSID = i;
					break;
				}
			}
			
			// Если позиция изменилась
			if (newSID != ddSID)
			{
				document.editor.tcode.value = "";
				
				// Сохраняем данные для обмена
				var tmpSkills = new Array();
				tmpSkills[0] = new Array();
				tmpSkills[0][0] = SkillBar[ddSID];
				tmpSkills[0][1] = dragContent;
				tmpSkills[0][2] = document.editor.elements["skill_data_"+ddSID].value;
				
				tmpSkills[1] = new Array();
				tmpSkills[1][0] = SkillBar[newSID];
				tmpSkills[1][1] = document.getElementById("skill_" + newSID).innerHTML;
				tmpSkills[1][2] = document.editor.elements["skill_data_"+newSID].value;

				// Переставляем номера в рамках
				var border1, border2;
				if (tmpSkills[0][0][1] == 1) { border1 = "border elite elite";}
				else						 { border1 = "border normal";}
				
				if (tmpSkills[1][0][1] == 1) { border2 = "border elite elite";}
				else						 { border2 = "border normal";}

				
				var reg1 = new RegExp(border1+ddSID, "g");
				tmpSkills[0][1] = tmpSkills[0][1].replace(reg1, border1+newSID);

				var reg2 = new RegExp(border2+newSID, "g");
				tmpSkills[1][1] = tmpSkills[1][1].replace(reg2, border2+ddSID);

				// Выполняем обмен
				SkillBar[ddSID] = tmpSkills[1][0];
				document.getElementById("skill_" + ddSID).innerHTML = tmpSkills[1][1];
				document.editor.elements["skill_data_"+ddSID].value = tmpSkills[1][2];
				document.getElementById("skillname_" + ddSID).innerHTML = (!tmpSkills[1][0][7]) ? "&nbsp;" : tmpSkills[1][0][7];
			
				SkillBar[newSID] = tmpSkills[0][0];
				document.getElementById("skill_" + newSID).innerHTML = tmpSkills[0][1];
				document.editor.elements["skill_data_"+newSID].value = tmpSkills[0][2];
				document.getElementById("skillname_" + newSID).innerHTML = (!tmpSkills[0][0][7]) ? "&nbsp;" : tmpSkills[0][0][7];
			}
			else
			{
				draggedSkill.innerHTML = dragContent;
			}
		}

		ddSID = 0;
		DD.style.display = "none";
		dragContent = "";
	}
}

//Заполняем драгДИВ
function htmlContDefine(myid)
{
	if (SkillBar[myid][0] > 0)
	{
		draggedDiv = document.getElementById("dragdiv");
		me = document.getElementById("skill_"+myid);
		ddSID = myid;
		var coors = findPos(me);

		dragContent = me.innerHTML;
		draggedDiv.innerHTML = dragContent;
	
		draggedSkill = me;
		draggedSkill.innerHTML = "<div class=\"border normal" + myid + "\"></div>";
	
		draggedDiv.style.display = "block";
		var yoff = 0;
		if (document.all && !window.opera) { yoff = 1;}
		draggedDiv.style.left = coors[0] + "px";
		draggedDiv.style.top = coors[1] + yoff + "px";
		dragObj = draggedDiv;
	}
	else
	{
		dragObj = null;
	}
}

// Объявление обработки перетаскивания
function startDrag(e) 
{
	if (ddSID >=1 && ddSID <=8)
	{
		currentObj = whichObj(e);
		document.onmousemove = moveIt;
	}
}

// Перетаскивание драгдива
function moveIt(e) 
{
	hideSkillInfo();
	if (currentObj != null) 
	{
		if (NN) 
		{
			dragObj.style.left = e.pageX - dx + "px";
			dragObj.style.top = e.pageY - dy + "px";
		}  
		else 
		{
			dragObj.style.left = event.x - dx + "px";
			dragObj.style.top = event.y - dy + "px";
		}  
	}
}

// Конец перетаскивания драгдива
function endDrag(e) 
{
	if (ddSID >=1 && ddSID <=8)
	{
		currentObj = null;
		document.onmousemove = null;
		hideDDFull();
	}
}

// Вычисление смещения при перетаскивании драгдива
function whichObj(e) 
{
	var hit = null;
  
	var coors = findPos(dragObj);
	oX = coors[0];
	oY = coors[1];
	var size = 64;

	if (NN) 
	{
	    if ((oX < e.pageX) && 
            (oX + size > e.pageX) &&
            (oY < e.pageY) && 
            (oY + size > e.pageY)) 
		{
        	hit = 1;
			dx = e.pageX - oX;
			dy = e.pageY - oY;
  		}
	}
	else 
	{
		var Xoff, Yoff;
		
		if (window.opera) 	{ 
								Xoff = window.pageXOffset;
								Yoff = window.pageYOffset;
							}
		else			  	{
								Xoff = document.body.scrollLeft;
								Yoff = document.body.scrollTop;
							}
		
		if ((oX - Xoff < event.x) && 
            (oX + size - Xoff > event.x) &&
            (oY - Yoff < event.y) && 
            (oY + size - Yoff > event.y)) 
		{
			hit = 1;
			dx = event.x - oX;
			dy = event.y - oY;
		}
	}

	return hit;
}

// Загрузка данных для расчета темплейт-кода
function tcodeCalculate()
{
	// Получаем индекс первой профессии
	var prof = Math.round(document.editor.prof1.value);
	if (prof > 10 || prof < 0) { prof = 0;}

	// Получаем индекс второй профессии
	var prof2 = Math.round(document.editor.prof2.value);
	if (prof2 > 10 || prof2 < 0) { prof2 = 0;}

	// Получаем список аттрибутов
	var attrForm = "";
	for (i=0; i<document.editor.elements.length; ++i)
	{
		if (document.editor.elements[i].name.indexOf("attrValue_") != -1)
		{
			aBase = 0;
			var aData = document.editor.elements[i].name.split("_");
			aBase = Math.abs(document.editor.elements[i].value);
			if (isNaN(aBase) || aBase == "") { aBase = 0;}
			if (aBase > 12) { aBase = 12;}
			if (attrForm != "") { attrForm += ":";}
			attrForm += aData[1] + "." + aBase;
		}
	}		

	// Формируем список скилов
	var sbForm = "";
	for (i=1; i<=8; ++i)
	{
		if (sbForm != "") { sbForm += ".";}
		sbForm += SkillBar[i][0];
	}
	
	// Вызов Ajax для дешифровки темплей-кода
	var url = "/cgi-bin/include/ajax/getTcode.pl?prof1=" + escape(prof) + "&prof2=" + escape(prof2);
	url += "&attr=" + escape(attrForm) + "&skillbar=" + sbForm;
	
	ajaxTcodeCalc = newAjax();	
	ajaxTcodeCalc.open("GET", url, true);
	ajaxTcodeCalc.onreadystatechange = tcodeShow;
	ajaxTcodeCalc.send(null);
}

// Вывод рассчитанного темплейт-кода
function tcodeShow()
{
	if (ajaxTcodeCalc.readyState == 4) 
	{
		var Answer = ajaxTcodeCalc.responseText.split("%%");
		if (Answer[0] == 1)
		{
			document.editor.tcode.value = Answer[1];
		}
		else
		{
			alert(Answer[1]);
		}		
	}
}
