var ajaxUrl = "../gameDBajax.php";

var table = null;
var recipe = new Array();
var mainCats = new Array();
var curSubCat = null;
var prevCat = null;
var prevSubCat = null;
var subID = 1;

var subCatId = null;

var head = new Array();
var items = new Array();
var tableHead = new Array();
var matches = new Array();

var startTable 	= "<table class='itemTable dbItems'>";
var endTable	= "</table>";

tableHead['weapon'] = new Array();
tableHead['weapon']['EN'] = new Array('Name', 'Grade', 'Worn<br />slot', 'P.<br>Att.', 'M.<br>Att.', 'Crystal<br>Count');
tableHead['weapon']['RU'] = new Array('Название', 'Грейд', 'Слот', 'Физ.<br>Атака', 'Магич.<br>Атака.', 'Кол-во<br>кристалов');
tableHead['armor'] = new Array();
tableHead['armor']['EN'] = new Array('Name', 'Grade', 'P.Def.', 'Weight', 'MB Bonus', 'Crystal<br>Count');
tableHead['armor']['RU'] = new Array('Название', 'Грейд', 'Физ.<br/>Защита', 'Вес', 'МП бонус', 'Кол-во<br>кристалов');
tableHead['accessary'] = new Array();
tableHead['accessary']['EN'] = new Array('Name', 'Grade', 'M.Def.', 'Weight', 'Crystal<br>Count');
tableHead['accessary']['RU'] = new Array('Название', 'Грейд', 'Магич.<br/>Защита', 'Вес', 'Кол-во<br>кристалов');
tableHead['etcitem'] = new Array();
tableHead['etcitem']['EN'] = new Array('Name', 'Grade', 'Weight');
tableHead['etcitem']['RU'] = new Array('Название', 'Грейд', 'Вес');

var sort_orderBy = -1;
var sort_greater = 1; 
var sort_less = -1;
var sort_subCat = 0;
var sort_pOrderBy = 2;

var ajax = new ajaxEngine();
ajax.Initialize();

var color = '#3d1e18';
var high = '';

/* *********************************************************
 * 	doSearch
 *	---
 *	Выполняет поиск предметов по заданному критерию
 * *********************************************************/
function doSearch()
{
	toSearch = document.getElementById('search').value;
	
	if( toSearch == '' )
	{
		alert(returnText('Пожалуйста, введите название предмета в поле поиска', 'Please enter an item name in the search box'));
		return false;
	}
	
	if( toSearch.length < 4 )
	{
		alert(returnText('Строка поиска должна быть не менее 4 символов', 'Pattern length must be 4 and more symbols'));
		return false;
	}
	
	if( ajax.active )
	{		
		var params = new Array();
		params['server'] 	= "3";		
		params['act'] 		= "item";
		params['mode'] 		= "find";
		params['cath'] 		= catName;
		params['find'] 		= toSearch;
				
		ajax.SendRequest(ajaxUrl, params, "GET", getAnswer);
	}
	else
		alert(returnText("Не активирован модуль ajax!", "Ajax is inactive!"));
		
	return false;
}

function compare(a, b)
{
	var _a = a[sort_orderBy];
	var _b = b[sort_orderBy];
	
	if( !isNaN(_a) || !isNaN(_b) )
	{
		_a = (!isNaN(_a)) ? _a : 0;
		_b = (!isNaN(_b)) ? _b : 0;
		
		if( (_a - _b) < 0 ) return sort_greater;
		if( (_a - _b) > 0 ) return sort_less;
		
		return 0;		
	}
	else
	{
		if(_a.toLowerCase() == 's')
			_a = '0';
		if(_b.toLowerCase() == 's')
			_b = '0';
		
		if(_a.toLowerCase() > _b.toLowerCase()) return sort_greater;
		if(_a.toLowerCase() < _b.toLowerCase()) return sort_less;
		
		return 0;		
	}	
}

/* *********************************************************
 * 	setSort( subCat, orderBy, pOrderBy )
 *		@subCat - string 	// Подкатегория, где осуществляется сортировка
 *		@orderBy - integer 	// Номер столбца, по которому осуществлять сортировку
 * 		@pOrderBy - integer // Номер столбца, по которому было отсортировано
 *	---
 *	Установить параметры сортировки
 * *********************************************************/
function setSort(subCat, orderBy, pOrderBy)
{	
	if( pOrderBy == orderBy && sort_greater == 1 )
	{		
		sort_greater = -1;
		sort_less = 1;
	}
	else
	{
		sort_greater = 1;
		sort_less = -1;	
	}	
	
	sort_orderBy = orderBy;
	sort_pOrderBy = orderBy;
	sort_subCat = subCat;	
	
	if( matches.length > 0 )
		dbShowSubCat(null, true);
	else
		dbShowSubCat(document.getElementById(subCat), true);
}

/* *********************************************************
 * 	returnText( rus, eng )
 *		@rus - string // Русский вариант
 *		@eng - string // Английский вариант 
 *	---
 *	Возвращает текст согласно выбранному языку
 * *********************************************************/
function returnText(rus, eng)
{
	if( lang == "RU" )
		return rus;
	else if( lang == "EN" )
		return eng;
		
	return "";
}

function initDBTable(){
	if( !document.getElementById('dbHead') )
		return;

	var heads = document.getElementById('dbHead').getElementsByTagName("TH");
	for( i = 0; i < heads.length; i++ )
	{
		heads[i].id = "h"+i;
		mainCats['h'+i] = heads[i]['title'];
		heads[i]['title'] = '';
		heads[i].onclick 		= function () {	 dbChangeCat(this); }
		heads[i].onmouseover 	= function () {	 this.className += ' hover'; }
		heads[i].onmouseout 	= function () {	 this.className = this.className.replace(' hover',''); }
	}
	
	dbChangeCat(document.getElementById('h0'));
}

/* *********************************************************
 * 	dbChangeCat( obj )
 *		@obj - object // Категория
 *	---
 *	Меняет категорию
 * *********************************************************/
function dbChangeCat(obj)
{
	if( prevCat != null && prevCat != obj )
		prevCat.className = prevCat.className.replace('dbSelected','');
		
	obj.className = 'dbSelected';
	prevCat = obj;
	catName = mainCats[obj.id];
	
	if( head[catName] == undefined )
		head[catName] = new Array();
	
	if( items[catName] == undefined )
		items[catName] = new Array();
		
	matches = new Array();
	
	if( ajax.active )
	{		
		if( head[catName][lang] == undefined )
		{
			var params = new Array();
			params['server'] 	= "3";		
			params['act'] 		= "item";
			params['mode'] 		= "load_cath";
			params['cath'] 		= mainCats[obj.id];
			params['lang'] 		= lang;
				
			ajax.SendRequest(ajaxUrl, params, "GET", getAnswer);
		}
		else
			printCathegories(); 
	}
	else
		alert(returnText("Не активирован модуль ajax!", "Ajax is inactive!"));
}

/* *********************************************************
 * 	getAnswer
 *	---
 *	Получает ответ от сервера. Callback функция
 * *********************************************************/
function getAnswer()
{
	if( ajax.GetState() == 3 )
		document.getElementById('dbItemsDiv').innerHTML = '<div align="center"><b>'+returnText("Загрузка...", "Loading...")+'</b></div>';
	
	if( ajax.GetState() == 4 )
	{
		document.getElementById('dbItemsDiv').innerHTML = "";
		if( ajax.GetStatus() == 200 )
		{			
			var xml = ajax.GetXML().documentElement;			
			var mode = xml.getElementsByTagName("mode").item(0).firstChild.data;
			
			switch( mode )
			{
				case 'cathegories': loadCathegories(xml); break;
				case 'items': loadItems(xml); break;
				case 'find': loadMatches(xml); break;
			}
		}
		else
			alert(ajax.GetStatusText());
	}	
}

/* *********************************************************
 * 	loadMatches
 *		@xml - object // Объект XML
 *	---
 *	Загружает результаты поиска
 * *********************************************************/
function loadMatches( xml )
{
	var result = xml.getElementsByTagName("item");
	
	if( result.length == 0 )
	{
		alert(returnText('В этой категории нет предметов согласно вашим кретериям поиска', 'There are no items in this category matching your search criteria'));
		return false;
	}
	
	for( i = 0; i < result.length; i++ )
	{
		matches[i] = new Array();
		var it = result.item(i).childNodes;
		for( j = 0; j < it.length; j++ )
		{
			if( it.item(j).firstChild == null )
				matches[i].push('');
			else
				matches[i].push(it.item(j).firstChild.data);	
		}
	}
	
	printItems();
}

/* *********************************************************
 * 	loadCathegories
 *		@xml - object // Объект XML
 *	---
 *	Загружает категорию
 * *********************************************************/
function loadCathegories( xml )
{	
	head[catName][lang] = new Array();
	
	var cats = xml.getElementsByTagName("cath");
	for( i = 0; i < cats.length; i++ )
	{
		var cat = cats.item(i).childNodes;
		
		head[catName][lang][i] = new Array();
		head[catName][lang][i]['id'] = cat.item(0).firstChild.data;
		head[catName][lang][i]['name'] = cat.item(1).firstChild.data;	
	}
	
	printCathegories();
}

/* *********************************************************
 * 	printCathegories
 *	---
 *	Выводит загруженную категорию
 * *********************************************************/
function printCathegories()
{
	if( head[catName][lang] == undefined )	
		return;	
	
	var numTR = Math.ceil(head[catName][lang].length / 5);
	var tblSub = document.createElement("table");
	var tBody = document.createElement("tbody");
	
	tblSub.className = "itemTable";
	tblSub.appendChild(tBody);
	i = 0;
	for( k = 0; k < numTR; k++ )
	{
		var newTR = document.createElement("tr");
		for( r = 0; r < 5; r++ )
		{				
			if( head[catName][lang][i] == undefined )
				break;
				
			var newTD = document.createElement("td");	
			
			newTD.innerHTML 		= show ? head[catName][lang][i]['name'] : '';
			newTD.id 				= head[catName][lang][i]['id'];
			newTD.style.display		= '';
			newTD.className 		= 'subCatTD';
			newTD.onclick 			= function () {	 dbShowSubCat(this, false); }
			
			newTD = newTR.appendChild(newTD);
			i++;
		}
		newTR = tBody.appendChild(newTR);
		if( head[catName][lang][i] == undefined )
			break;
	}
	
	sort_orderBy 	= -1;
	sort_greater 	= 1; 
	sort_less 		= -1;
	sort_subCat 	= 0;
	sort_pOrderBy 	= 2;	
	
	document.getElementById('dbItemsDiv').innerHTML = "";
	
	document.getElementById('tableSub').innerHTML = "";
	document.getElementById('tableSub').appendChild(tblSub);
}

function showRecipe(id)
{		
	var recId = 'rec' + id;
	var recDivId = 'recCont' + id;
	
	if( document.getElementById(recDivId).innerHTML == "" )
	{		
		var r = recipe[id]['rates'];
		for( i = 0; i < r.length; i++ )
		{
			document.getElementById(recDivId).innerHTML += "<a href=\"javascript: showRateRec('"+id+"', '"+r[i]+"');\">Success Rate: "+r[i]+"%</a>\n<br>";
			document.getElementById(recDivId).innerHTML += "<div id='"+recId+"Rate"+r[i]+"' style='display: none; padding-left: 20px;'>" + getSubRec(id, r[i], 1) + "</div>";			
		}
	}
	
	if( document.getElementById(recId).style.display == "" )
		document.getElementById(recId).style.display = "none";
	else
		document.getElementById(recId).style.display = "";
}

function showRateRec(id, rate)
{
	var recId = 'rec' + id + 'Rate' + rate;	
	
	if( document.getElementById(recId).style.display == "block" )
		document.getElementById(recId).style.display = "none";
	else
		document.getElementById(recId).style.display = "block";	
}

function showSubRec(id)
{
	var subId = 'sub' + id;
	var pmId = 'pm' + id;
	
	if( document.getElementById(subId).style.display == "block" )
	{
		document.getElementById(subId).style.display = "none";
		document.getElementById(pmId).innerHTML = "+";
	}
	else
	{
		document.getElementById(subId).style.display = "block";	
		document.getElementById(pmId).innerHTML = "-";
	}
}

function getSubRec(item_id, sRate, count)
{	
	if( recipe[item_id] )
	{		
		var rec = recipe[item_id][sRate];
		var out = "";
		for( var r = 0; r < rec.length; r++ )
		{		
			var c = rec[r][0] * count;
			if( recipe[rec[r][2]] )
			{				
				out += "<a href=\"javascript: showSubRec('" + subID + "');\">";
				out += "(" + c + ") " + rec[r][1] + " [<span id=\"pm" + subID + "\">+</span>]";
				out += "</a><br>\n";
				out += "<div id=\"sub" + subID + "\" style=\"padding-left: 20px; display: none;\">\n";	
				subID++;
				out += getSubRec(rec[r][2], 100, c);
				out += "</div>\n";
				
			}
			else
				out += "(" + c + ") " + rec[r][1] + "<br>\n";		
		}
		return out;
	}
	else
		return "";
}

/* *********************************************************
 * 	loadItems
 *		@xml - object // Объект XML
 *	---
 *	Загружает предметы из данной категории
 * *********************************************************/
function loadItems(xml)
{
	items[catName][subCatId] = new Array();
	
	var itemArray = xml.getElementsByTagName("item");
	for( i = 0; i < itemArray.length; i++ )
	{
		items[catName][subCatId][i] = new Array();
		
		var itemList = itemArray.item(i).childNodes;
		for( j = 0; j < itemList.length; j++ )
		{
			if( itemList.item(j).firstChild == null )
				items[catName][subCatId][i].push('');
			else
				items[catName][subCatId][i].push(itemList.item(j).firstChild.data);	
		}
	}
	
	printItems();
}

/* *********************************************************
 * 	printItems
 *	---
 *	Выводит список загруженных предметов
 * *********************************************************/
function printItems()
{		
	var itemArray = new Array();
		
	if( matches.length > 0 )
		itemArray = matches;
	else
		itemArray = items[catName][subCatId];
	
	var head = tableHead[catName][lang];
	
	var output = "<tr><th colspan=2 class='r0'><a href=\"javascript: setSort('" + subCatId + "', 1, " + sort_pOrderBy + ");\">" + head[0] + "</a></th>";
	
	for( i = 1; i < head.length; i++ )
		output += "<th class='r" + (i+1) + "'><a href=\"javascript: setSort('" + subCatId + "', " + (i+1) + ", " + sort_pOrderBy + ");\">" + head[i] + "</a></th>";
	
	output += "</tr>\n";
	
	// Сортировка
	if( sort_orderBy != -1 )
		itemArray.sort(compare);

	high = '';
	for( i = 0; i < itemArray.length; i++ )
	{
		var item = itemArray[i];
		
		/*
		rec = "";
		recButton = "";
		if( recipe[item[0]] )
		{
			rec = "<tr id=\"rec" + item[0] + "\" style=\"display: none;\"><td></td><td colspan=\""+(item.length - 4)+"\">";
			rec += "<div style=\"text-align: left;\" id=\"recCont" + item[0] + "\">";
			rec += "</div></td></tr>\n";
			
			recButton = " [<a href=\"javascript: showRecipe('" + item[0] + "');\">" + returnText('рецепт', 'recipe') + "</a>] ";
		}
		*/
		var sub_name = item[item.length - 3] == '' ? '' : "<br /><span class='dbSubName'>"+item[item.length-3]+"</span>";
		
		desc = item[item.length - 2].replace(/\n/g,"\\n");	
		desc = desc.replace(/</g, "-= ");
		desc = desc.replace(/>/g, " =-");
		if( item[item.length - 1] != '' )
		{
			var soulCry = item[item.length - 1].split('|');
			
			desc += "\\n\\n<img src=http://la2.theabyss.ru/images/la2/items/" + soulCry[1] + ".jpg> " + soulCry[0];
		}
		
		high = (high == color) ? '' : color;
		
		output +="<tr style='background: "+high+";'><td class='r0'><img src='http://la2.theabyss.ru/images/la2/items/"+item[0]+".jpg'></td>";
		output +="<td onMouseOver=\"show_tooltip('"+desc+"', event, this);\" class='r1'>"+item[1] + /*recButton*/"" + sub_name + "</td>";

		for( x = 2; x < item.length - 3; x++ )
			output += "<td class='r" + x + "'>" + item[x] + "</td>";
		
		output += "</tr>\n";			
		//output += rec;
	}

	document.getElementById('dbItemsDiv').innerHTML = startTable + output + endTable;
}

/* *********************************************************
 * 	dbShowSubCat( obj, srch )
 *		@obj - object // Подкатегория
 *		@srch -
 *	---
 *	Выводит подкатегорию
 * *********************************************************/
function dbShowSubCat(obj, srch)
{
	if( prevSubCat != null && prevSubCat != obj )
		prevSubCat.className = prevSubCat.className.replace('subCatSel', 'subCatTD');

	if( obj != null )
	{
		obj.className = 'subCatSel';
		prevSubCat = obj;
		subCatId = obj.id;
	}
	
	if( !srch )
		matches = new Array();

	if( ajax.active )
	{	
		if( items[catName][subCatId] == undefined )
		{
			var params = new Array();
			params['server'] 	= "3";		
			params['act'] 		= "item";
			params['mode'] 		= "load_items";
			params['cath'] 		= catName;
			params['sub_cath'] 	= subCatId;
				
			ajax.SendRequest(ajaxUrl, params, "GET", getAnswer);
		}
		else
			printItems(); 
	}
	else
		alert(returnText("Не активирован модуль ajax!", "Ajax is inactive!"));
}
