var tabList = ['display','consumables','settings','encounter'];

var tab2List = ['gear','manual'];

function armoryIconError( slot, text ) {
	if( obj = document.getElementById('gearselect_href_' + slot) ) {
		if( !obj.errorOnce ) {
			obj.innerHTML += text;
			obj.errorOnce = true;
		}
	}
	
	if( obj = document.getElementById('gearselector_error') ) {
		if( !obj.errorOnce ) {
			obj.innerHTML = "<b>Error</b>: Armory currently unavailable; some icons may not appear.";
		}
	}
}

function tabShow( id, list ) {
	for( x = 0; x < list.length; x++ ) {
		if( obj = document.getElementById(list[x]) ) {
			obj.style.display = 'none';
		}
		
		if( obj = document.getElementById('tabhead_' + list[x]) ) {
			obj.className = 'tabIn click';
		}
	}
	
	if( obj = document.getElementById(id) ) {
		obj.style.display = '';
	}
	
	if( obj = document.getElementById('tabhead_' + id) ) {
		obj.className = 'tabOut click';
	}
}

function toggleAllBuffs( status ) {
	list = document.getElementsByTagName('INPUT');
	
	for( x = 0; x < list.length; x++ ) {
		if( list[x].id.indexOf('buff_menu_') == 0 ) {
			list[x].checked = status;
		}
	}
}
	
function addSpec() {
	document.mainform.action = '?action=newspec';
	document.mainform.submit();
}

function calculate() {
	document.mainform.action = '?action=calculate';
	document.mainform.submit();
}

function deleteSpec( id ) {
	if( confirm("Are you sure you want to delete this spec?") ) {
		document.mainform.action = '?action=deletespec&spec=' + id;
		document.mainform.submit();
	}
}

function editSpec( id ) {
	document.mainform.action = '?action=newspec&spec=' + id;
	document.mainform.submit();
}

function redirectMainFormAction( action ) {
	document.mainform.action = '?action=' + action;
	document.mainform.submit();
}

function toggleDiv( id ) {
	if( obj = document.getElementById( id ) ) {
		if( obj.style.display == "none" )
			obj.style.display = '';
		else
			obj.style.display = "none";
	}
}

function mode( setMode ) {
	if( setMode == "manual" )
		hideThis = "gear_all";
	else
		hideThis = "manual_all";
	
	showThis = setMode + "_all";
	
	if( obj = document.getElementById(showThis) )
		obj.style.display = '';
	if( obj = document.getElementById(hideThis) )
		obj.style.display = 'none';
	if( obj = document.getElementById(setMode) )
		obj.style.display = '';
		
	if( obj = document.getElementById('statModeInput') )
		obj.value = setMode;
}

function setStatMode( mode ) {
	if( obj = document.getElementById('statModeInput') ) {
		obj.value = mode;
	}
}

var httpRequest;
if( window.XMLHttpRequest)
	httpRequest = new XMLHttpRequest();
else if( window.ActiveXObject)
	httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

function requestHandle() {
	if( typeof httpRequest != "undefined") {
		if(httpRequest.readyState == 4) {
			if(httpRequest.responseText.substring(0, 8) == 'itemslot') {
				handleItemSlotReplace(httpRequest.responseText);
			} else if(httpRequest.responseText.substring(0, 5) == 'stats') {
				handleNewStats(httpRequest.responseText);
			} else {
				handleNewTextList(httpRequest.responseText);
			}
		}
	}
}

function handleNewStats(text) {
	text = text.substring(5, text.length);
	
	list = text.split(',');
	
	updateTotalStat('gearselector_total_Intellect', list[0], 'Intellect');
	updateTotalStat('gearselector_total_Spell Power', list[2], 'Spell_Power');
	
	updateTotalStat('gearselector_total_Hit Rating', list[3], 'Hit_Rating', list[4]);
	updateTotalStat('gearselector_total_Crit Rating', list[5], 'Crit_Rating', list[6]);
	updateTotalStat('gearselector_total_Haste Rating', list[7], 'Haste_Rating', list[8]);
	updateTotalStat('gearselector_total_Mastery Rating', list[9], 'Mastery_Rating', list[10]);
}

function updateTotalStat(obj_name, value, orig_stat_name, percent) {
	if (obj = document.getElementById(obj_name)) {
		obj.innerHTML = '<b>' + value + '</b>';
		
		var diff = value - originalStats[orig_stat_name];
		
		if (diff < 0) {
			obj.innerHTML += ' <b style="color: red;">('+diff+')</b>';
		} else if (diff > 0) {
			obj.innerHTML += ' <b style="color: green;">(+'+diff+')</b>';
		}
		
		if (percent) {
			obj.innerHTML += ' (' + percent + '%)';
		}
	}	
}

var replacementItem = '';
var replacementItemID = 0;
var replacementItemIcon = '';
function handleItemSlotReplace(text) {
	list = text.split(',');
	
	var equipType = list[0].substring(9, list[0].length);
	
	if(equipType != '') {
		targetSlot = slotMap[equipType];
		
		itemSlotReplace(targetSlot, equipType, list[1], list[2])
	}
}

var slotReplace = '';
function itemSlotReplace(targetSlot, equipType, itemID, icon) {
	if(targetSlot == 'ring') {
		var opt1 = '';
		var opt2 = '';
		
		if(ringInput1 = document.getElementById('gearselect_profile_ring1')) {
			opt1 = ringInput1.value;
		}
		
		if(ringInput2 = document.getElementById('gearselect_profile_ring2')) {
			opt2 = ringInput2.value;
		}
		
		slotReplace = 'ring';
		
		replacementItemID = itemID;
		
		replacementItemIcon = icon;
		
		showCenterMessage("REPLACE WHICH RING?", opt1, opt2);
	} else if(targetSlot == 'trinket') {
		var opt1 = '';
		var opt2 = '';
		
		if(trinketInput1 = document.getElementById('gearselect_profile_trinket1')) {
			opt1 = trinketInput1.value;
		}
		
		if(trinketInput2 = document.getElementById('gearselect_profile_trinket2')) {
			opt2 = trinketInput2.value;
		}
		
		slotReplace = 'trinket';
		
		replacementItemID = itemID;
		
		replacementItemIcon = icon;
		
		showCenterMessage("REPLACE WHICH TRINKET?", opt1, opt2);
	} else {
		if(obj = document.getElementById('gearselect_display_' + targetSlot)) {
			if(obj2 = document.getElementById('gearselect_profile_' + targetSlot)) {
				obj2.itemname = replacementItem;
				
				obj2.value = itemID;
			}
			
			if (obj2 = document.getElementById('gearselect_item_name_' + targetSlot)) {
				obj2.innerHTML = replacementItem;
			}
			
			if (obj2 = document.getElementById('gearselect_reforge_to_' + targetSlot)) {
				obj2.selectedIndex = 0;	
			}
			if (obj2 = document.getElementById('gearselect_reforge_from_' + targetSlot)) {
				obj2.selectedIndex = 0;	
			}
			
			if(obj2 = document.getElementById('gearselect_href_' + targetSlot)) {
				obj2.href = "http://www.wowhead.com/?item=" + itemID;
				
				if( obj3 = document.getElementById('gearselect_icon_' + targetSlot)) {
					obj3.src = 'http://static.wowhead.com/images/wow/icons/medium/' + icon + '.jpg';
					
					obj3.alt = replacementItem;
				}
				
				//obj2.innerHTML = replacementItem;
				
				obj2.style.color = "#F00";
			}
		}
		
		if(equipType == 17) {
			if(obj = document.getElementById('gearselect_display_offhand')) {
				//obj.innerHTML = 'N/A';
				
				if( obj3 = document.getElementById('gearselect_icon_offhand')) {
					obj3.src = 'http://' + SERVER_url + '/img/empty.png';
					obj3.alt = '';
				}
				
				//obj.style.backgroundColor = "#F8E0E0";
				
				if(obj2 = document.getElementById('gearselect_profile_offhand')) {
					obj2.value = 0;
					
					obj2.itemname = 0;
				}
				
				if(obj2 = document.getElementById('gearselect_href_offhand')) {
					obj2.href = "";
				}
			}
		}
		
		if( obj = document.getElementById('calculate_button') ) {
			obj.value = "Recalculate";
			
			obj.style.color = 'black';
		}
		
		recalculateStats();
	}
	
	hideList();
	
	document.getElementById('equip_box').value = '';
}

function statsChanged() {
	recalculateStats();
}

function recalculateStats() {
	var index = 0;
	
	var gearselect_race = document.getElementById('gearselect_race');
	
	var qstring = '?m=' + mode_Int + '&race=' + gearselect_race.value + '&';
	
	qstringIndex = 0;
	
	qstring += advancedQueryString('head');
	qstring += advancedQueryString('neck');
	qstring += advancedQueryString('shoulders');
	qstring += advancedQueryString('back');
	qstring += advancedQueryString('chest');
	qstring += advancedQueryString('wrist');
	qstring += advancedQueryString('mainhand');
	qstring += advancedQueryString('offhand');
	qstring += advancedQueryString('ranged');
	qstring += advancedQueryString('hands');
	qstring += advancedQueryString('waist');
	qstring += advancedQueryString('legs');
	qstring += advancedQueryString('feet');
	qstring += advancedQueryString('ring1');
	qstring += advancedQueryString('ring2');
	qstring += advancedQueryString('trinket1');
	qstring += advancedQueryString('trinket2');
	
	/*
	qstring += addToQueryString('gearselect_profile_head');
	qstring += addToQueryString('gearselect_profile_neck');
	qstring += addToQueryString('gearselect_profile_shoulders');
	qstring += addToQueryString('gearselect_profile_back');
	qstring += addToQueryString('gearselect_profile_chest');
	qstring += addToQueryString('gearselect_profile_wrist');
	qstring += addToQueryString('gearselect_profile_mainhand');
	qstring += addToQueryString('gearselect_profile_offhand');
	qstring += addToQueryString('gearselect_profile_ranged');
	qstring += addToQueryString('gearselect_profile_hands');
	qstring += addToQueryString('gearselect_profile_waist');
	qstring += addToQueryString('gearselect_profile_legs');
	qstring += addToQueryString('gearselect_profile_feet');
	qstring += addToQueryString('gearselect_profile_ring1');
	qstring += addToQueryString('gearselect_profile_ring2');
	qstring += addToQueryString('gearselect_profile_trinket1');
	qstring += addToQueryString('gearselect_profile_trinket2');
	*/
	var url = "http://" + SERVER_url + "/ajax/statsfromgear.php" + qstring;
	
	httpRequest.open("GET", url, true);
	httpRequest.send(null);
}

function advancedQueryString(slot) {
	var q = '';
	
	if(obj = document.getElementById('gearselect_profile_'+slot)) {
		q += 'gearselect_profile_'+slot+'='+obj.value+'&';
	}
	if(obj = document.getElementById('gearselect_reforge_from_'+slot)) {
		q += 'gearselect_reforge_from_'+slot+'='+obj.value+'&';
	}
	if(obj = document.getElementById('gearselect_reforge_to_'+slot)) {
		q += 'gearselect_reforge_to_'+slot+'='+obj.value+'&';
	}
	if(obj = document.getElementById('gearselect_enchant_'+slot)) {
		q += 'gearselect_enchant_'+slot+'='+obj.value+'&';
	}
	
	return q;
}

var qstringIndex = 0;
function addToQueryString( id ) {
	if(obj = document.getElementById(id)) {
		qstringIndex++;
		
		return id + '=' + obj.value + '&';
	} else {
		return '';	
	}
}


function showCenterMessage(message, opt1, opt2) {
	if(box = document.getElementById('centerBox')) {
		box.style.display = '';
	}
	
	if(messageBox = document.getElementById('centerBoxMessage')) {
		messageBox.innerHTML = message;
	}
	
	if(optInput1 = document.getElementById('centerBoxOpt1')) {
		optInput1.value = opt1;
	}
	
	if(optInput2 = document.getElementById('centerBoxOpt2')) {
		optInput2.value = opt2;
	}
}

function hideCenterMessage() {
	if(box = document.getElementById('centerBox')) {
		box.style.display = 'none';
	}
}

function clickCenterBoxOption(optionNumber) {
	itemSlotReplace(slotReplace + optionNumber, '', replacementItemID, replacementItemIcon);
	
	hideCenterMessage();
}

var displayList = [];
var displayListIds = [];
var fullList = [];
var fullListIds = [];
var listText = '';
function handleNewTextList(text) {
	//displayList = text.split(';');
	tempList = text.split(';');
	
	var theSwitch = false;
	for(var i = 0; i < tempList.length; i++) {
		theSwitch = !theSwitch;
		
		if( theSwitch ) {
			if( tempList[i] != '' )
				fullList[Math.floor(i / 2)] = tempList[i];
		} else {
			if( tempList[i] != '' )
				fullListIds[Math.floor(i / 2)] = tempList[i];
		}
	}
	
	filterList(document.getElementById('equip_box').value);
	
	showTextList();
}

function filterList(sendText) {
	displayList = [];
	
	if(sendText.length <= 0) {
		return;
	}
	
	for(var i = 0; i < fullList.length; i++) {
		displayList[i] = fullList[i];
		
		displayListIds[i] = fullListIds[i];
	}
	
	for(var i = displayList.length - 1; i >= 0; i--) {
		if(displayList[i].substring(0, sendText.length).toLowerCase() != sendText.toLowerCase()) {
			displayList.splice(i, 1);
			displayListIds.splice(i, 1);
		}
	}

	itemSelected = -1;
	lastItemSelected = -1;
}


var lastItemSelected = -1;
function mouseoverItem(index) {
	if( lastItemSelected == index ) {
		return;
	}
	
	selectItem(index);
	
	lastItemSelected = index;
}

var itemSelected = -1;
function selectItem(index) {
	if(index < -1) {
		index = displayList.length - 1;
	}
	
	if(index >= displayList.length) {
		index = -1;
	}
	
	if(itemSelected >= 0 && itemSelected < displayList.length) {
		var oldSelection = document.getElementById('selection' + itemSelected);

		oldSelection.style.backgroundColor = "#FFFFFF";
	}
	
	itemSelected = index;
	
	if(index >= 0 && index < displayList.length) {		
		var selection = document.getElementById('selection' + index);
		
		selection.style.backgroundColor = "#A9D0F5";
		
		document.getElementById('equip_box').value = document.getElementById('selection' + index).getAttribute("name");
		
		var selectionhref = document.getElementById('selectionhref' + index);
		
		//selectionhref.href = 
	}
}

function hideList() {
	var listBox = document.getElementById('box-select');
	
	listBox.style.display = 'none';
	
	var inputObj = document.getElementById('equip_box');
	
	itemSelected = -1;
	lastItemSelected = -1;
}

function showTextList() {	
	var listBox = document.getElementById('box-select');
	
	var length = displayList.length;
	
	if(length > 30) {
		length = 30;
	}
	
	var boxText = document.getElementById('equip_box').value;
	
	var newValue = '';
	var showBox = false;
	for(var i = 0; i < length; i++) {
		if(displayList[i].length > 0) {
			newValue += "<a class='plainlink' id=\"selectionhref" + i + "\" href=\"http://www.wowhead.com/?item=" + displayListIds[i] + "\"><div onmousedown=\"submitQuery();\" onmousemove=\"mouseoverItem(" + i + ");\" name=\"" + displayList[i] + "\" id=\"selection" + i + "\" style='background-color:#FFFFFF;cursor:default;'>" + displayList[i].substring(0, boxText.length) + "<b>" + displayList[i].substring(boxText.length, displayList[i].length) + "</b></div></a>";
			
			showBox = true;
		}
	}
	
	if(showBox) {
		listBox.style.display = '';
	} else {
		listBox.style.display = 'none';
	}
	
	if(newValue != listBox.innerHTML) {
		listBox.innerHTML = newValue;
	}
}

httpRequest.onreadystatechange = requestHandle;

var delayedFunction;

function keyDownHandle(eventObj) {
	clearTimeout(delayedFunction);
	
	if(eventObj.keyCode == 40 || eventObj.keyCode == 9) {
		selectItem(itemSelected + 1);
		
		return false;
	} else if(eventObj.keyCode == 38) {
		selectItem(itemSelected - 1);
	} else if(eventObj.keyCode == 27) {
		hideList();
	} else if(eventObj.keyCode == 13) {
		submitQuery();
		
		return false;
	} else {
		delayedFunction = setTimeout("requestAutoComplete();", 50);
	}
	
	return true;
}

function submitQuery() {
	var url = "http://" + SERVER_url + "/ajax/iteminfo.php?m=" + mode_Int + "&name=" + escape(document.getElementById('equip_box').value);
	
	httpRequest.open("GET", url, true);
	httpRequest.send(null);
	
	replacementItem = document.getElementById('equip_box').value;
}

function debug(text) {
	if(obj = document.getElementById('debug')) {
		obj.value = text;
	}
}

function requestAutoComplete() {
	var inputObj = document.getElementById('equip_box');

	var sendText = inputObj.value;
	
	var requestNewList = false;
	
	if(sendText.length >= 3) {
		if(listText.length < 3) {
			requestNewList = true;
		} else {			
			if(sendText.substring(0, 3) != listText.substring(0, 3)) {
				requestNewList = true;
			}
		}
	}
	
	if(requestNewList) {
		listText = sendText;
		
		if(sendText.length > 3) {
			sendText = sendText.substring(0, 3);
		}
		
		var url = "http://" + SERVER_url + "/ajax/autocomplete.php?m=" + mode_Int + "&text=" + sendText.substring(0, 3);
		
		httpRequest.open("GET", url, true);
		httpRequest.send(null);
	} else {
		filterList(sendText);
		showTextList();
	}
}

var slotMap = ['',
			   'head',
			   'neck',
			   'shoulders',
			   '',
			   'chest',
			   'waist',
			   'legs',
			   'feet',
			   'wrist',
			   'hands',
			   'ring',
			   'trinket',
			   '',
			   '',
			   '',
			   'back',
			   'mainhand',
			   '',
			   '',
			   'chest',
			   'mainhand',
			   '',
			   'offhand',
			   '',
			   '',
			   'ranged'
			   ];
