var IE = false;
function ajax(url, id){
	var ajaxRequest;  // The variable that makes Ajax possible!
	document.getElementById(id).innerHTML = "<div class=\"loading\"><img src=\"/library/images/lytebox/loading.gif\" alt=\"Loading\"/></div>"
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			var ajaxDisplay = document.getElementById(id);
			ajaxDisplay.innerHTML = ajaxRequest.responseText;
		}
	}
	ajaxRequest.open("GET", url, true);
	ajaxRequest.send(null); 
}
function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}
function calendar(id, month, year) {
	var url = '/calendar.php?month='+month+'&year='+year;
	ajax(url, 'calendar');
}
function icons(page) {
	var url = '/displayIcons.php?p='+page;
	ajax(url, 'iconDisplay');
}
function changeIcon(icon) {
	var img = document.getElementById('iconImage');
	var txtField = document.getElementById('iconField');
	txtField.value = icon;
	img.src = "/library/images/icons/"+icon;
	Slide('icons').toggle();
}
function obtainedBy(id, type) {
	url = "/editItemExtras2.php?i="+id+"&o="+type;
	ajax(url, 'obtainedBox');
}
function searchAbilities(query, id) {
	if (query.length >= 3) {
		var url = '/searchAbilities.php?q='+query;
		document.getElementById(id).innerHTML = "<img src=\"/library/images/lytebox/loading.gif\" alt=\"Loading\"/>"
		ajax(url, id);
	} else {
		alert("Search must be greater than 3 characters");
	}
}
function searchItems(query, id) {
	if (query.length >= 3) {
		var url = '/findItems.php?q='+escape(query);
		document.getElementById(id).innerHTML = "<img src=\"/library/images/lytebox/loading.gif\" alt=\"Loading\"/>"
		ajax(url, id);
	} else {
		alert("Search must be greater than 3 characters");
	}
}
function addAbility(id, ability, desc) {
	var add = true;
	if (abilitiesAdded["ability"+id] == id) {
		add = false;
	}
	if (add) {
		//Slide('addAbilities').toggle(); 
		abilitiesAdded["ability"+id] = id;
		var table = document.getElementById('abilities');
		var addAbility = document.getElementById('addAbility'+id);
		var newRow = table.insertRow(table.rows.length);
		var cell1 = newRow.insertCell(0);
		var cell2 = newRow.insertCell(1);
		var cell3 = newRow.insertCell(2);
		
		addAbility.innerHTML = "Ability Added";
		addAbility.style.color = "#44d235";
		addAbility.style.fontWeight = "bold";
		
		newRow.id = "ability"+id;
		cell2.align = "center";
		cell3.align = "center";
		
		cell1.innerHTML = stripslashes(ability);
		//cell2.innerHTML = stripslashes(desc);
		cell2.innerHTML = "<a href=\"javascript:;\" onclick=\"window.open('/page/editAbilities/$abilityID','_blank','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=yes, width=1024, height=768');\"><img src=\"/library/images/edit.gif\" alt=\"Edit\"/></a>";
		//cell3.innerHTML = "<input type=\"hidden\" name=\"abilities[]\" value=\""+id+"\"/><input type=\"checkbox\" name=\"delAbilities[]\" value=\""+id+"\" onclick=\"deleteNewAbility(this, 'ability"+id+"', 'abilities')\"/>";
		cell3.innerHTML = "<input type=\"hidden\" name=\"abilities[]\" value=\""+id+"\"/><a href=\"javascript:;\" onclick=\"deleteNewAbility(this, 'ability"+id+"', 'abilities')\"><img src=\"/library/images/delete.gif\" alt=\"Edit\"/></a>";
		
		/* OLD INNERHTML Version
		var temp = "";
		temp = "<tr id=\"ability"+id+"\" valign=\"top\"><td valign=\"top\">"+stripslashes(ability)+"</td><td>"+stripslashes(desc)+"</td><td align=\"center\"><input type=\"hidden\" name=\"abilities[]\" value=\""+id+"\"/><input type=\"checkbox\" name=\"delAbilities[]\"value=\""+id+"\" onclick=\"deleteNewAbility('ability"+id+"')\"/></td></tr>";
		table.innerHTML += temp;
		*/
	} else {
		alert("You cannot add the same ability twice");
	}
}
function deleteAbility(id) {
	var cBox = document.getElementById('del'+id);
	var cells = document.getElementById('ability'+id).childNodes;
	if (IE)
		firstCell = 0;
	else
		firstCell = 1;
	
	cBox.checked = !cBox.checked;
	if (cells[firstCell].style.textDecoration == 'line-through')
		cells[firstCell].style.textDecoration = 'none';
	else
		cells[firstCell].style.textDecoration = 'line-through';
}
function deleteNewAbility(r, id, table) {
	var i=r.parentNode.parentNode.rowIndex;
	document.getElementById(table).deleteRow(i);
	abilitiesAdded[id] = 0;
	/* OLD using innerHTML
	var row = document.getElementById(id);
	row.innerHTML = "";
	row.style.display = 'none';
	*/
}
function toggleDisabledFields(s) {
	if (s.value == 'Chance on Hit') {
		document.myForm.chance.disabled = false;
	} else {
		document.myForm.chance.disabled = true;
		document.myForm.chance.value = '';
		document.getElementById('chance').innerHTML = '';
	}
	if (s.value == 'Weapon Bonus' || s.value == 'Statements Unlocked') {
		document.myForm.abilityName.disabled = true;
		document.myForm.abilityName.value = '';
		document.getElementById('abilityName').innerHTML = '';
	} else {
		document.myForm.abilityName.disabled = false;
	}
}
function addChunk(chunk) {
	var add = true;
	var id = chunk.value;
	var name = chunk.options[chunk.selectedIndex].text;
	if (abilitiesAdded["ability"+id] == id) {
		add = false;
	}
	if (add) {
		var temp = "";
		abilitiesAdded["ability"+id] = id;
		var table = document.getElementById('chunks');
		var newRow = table.insertRow(table.rows.length);
		var cell1 = newRow.insertCell(0);
		var cell2 = newRow.insertCell(1);
		
		newRow.id = "ability"+id;
		newRow.vAlign = "top";
		cell2.align = "center";
		
		cell1.innerHTML = name;
		//cell2.innerHTML = "<input type=\"hidden\" name=\"chunks[]\" value=\""+id+"\"/><input type=\"checkbox\" name=\"delChunks[]\"value=\""+id+"\" onclick=\"deleteNewAbility(this, 'chunks"+id+"', 'chunks')\"/>";
		cell2.innerHTML = "<input type=\"hidden\" name=\"chunks[]\" value=\""+id+"\"/><a href=\"javascript:;\" onclick=\"deleteNewAbility(this, 'ability"+id+"', 'chunks')\"><img src=\"/library/images/delete.gif\" alt=\"Edit\"/></a>";
	} else {
		alert("You cannot add the same chunks twice");
	}
}
function addType(id1, id2) {
	var input1 = document.getElementById(id1);
	var input2 = document.getElementById(id2);
	input1.style.display = 'none';
	input2.style.display = 'inline';
}
function clearText(id) {
	document.getElementById(id).value = '';
}
function spoiler(id) {
	var spoiler = document.getElementById(id);
	if (spoiler.offsetHeight == 0) {
		spoiler.style.display = "block";
	} else {
		spoiler.style.display = "none";
	}
}
function confirmation(confText) {
	var answer = confirm(confText)
	if (answer)
		return true;
	else
		return false;
}//end confirmation
function checkRegExp(r, s, id, msg) {
	if (s.length > 0) {
		if(s.match(r)) {
			document.getElementById(id).innerHTML = "";
			return true;
		} else {
			document.getElementById(id).innerHTML = ((msg.length > 0) ? msg : "Invalid");
			return false;
		}
	} else {
		document.getElementById(id).innerHTML = "";
		return false;
	}
}//End checkRegExp

function validate(type, s, msg, id) {
	switch (type) {
		case 0:
			regex = "^[a-zA-Z ]*$";
			checkRegExp(regex, s, id, msg);
			break;
		case 1:
			regex = "^[a-zA-Z\, &\(\):'\.0-9\-\"]*$";
			checkRegExp(regex, s, id, msg);
			break;
		case 2:
			regex = "^[0-9]*$";
			checkRegExp(regex, s, id, 'Invalid - Must contain only numbers');
			break;
		case 3:
			regex = "^[0-9]{1,3}[\.][0-9]{1,2}$";
			checkRegExp(regex, s, id, 'Invalid - Must be a decimal (5.2, 25.97)');
			break;
		case 4:
			regex = "^[0-9]{1,3}[\.][0-9]{1,3}$";
			checkRegExp(regex, s, id, 'Invalid - Must be a decimal (5.2, 25.97)');
			break;
		case 5:
			regex = "^[\+\-](([0-9]{1,3})|([0][\.][0-9]{1,3})) [a-zA-Z\- \(\)0-9]+$";
			var lines = s.split("\n");
			for (var i = 0; i < lines.length; i++) {
				temp = lines[i];
				if (!checkRegExp(regex, temp, id, 'Invalid - Must be in this format:<br/>[+ or -]## Attribute'))
					break;
			}
			break;
	}//end switch
}

/* ******************** */
/* Unobtrusive Javascript */
/* ******************** */
window.onload = function() {
	var box = document.getElementById('media');
	if (box != null) {
		initmediascroll();
	}
	//Dynamically Change Item Type Form
	if (document.getElementById('itemType') != null) {
		document.getElementById('itemType').onchange=function() {
			//var answer = confirm("Are you sure?\nChanging the item type will DELETE the existing stats.")
			//if (answer) {
				var url = '/editItemType2.php?itemType=' + document.getElementById('itemType').value + "&itemID=" + document.myform.itemID.value;
				ajax(url, 'itemTypeForm');
				for (i = 1; i <= 11; i++) {
					if (i != 10) {
						temp = 'help-itemType'+i;
						if (i != document.getElementById('itemType').value)
							document.getElementById(temp).style.display = 'none';
						else
							document.getElementById(temp).style.display = 'inline';
					}
				}
			//}
		}
	}
	if (IE6 == true) {
		navRoot = document.getElementById("networknav");
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
		}
		navRoot = document.getElementById("snffMenu");
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="DIV") {
				node.onmouseover=function() {
					this.className+=" over";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" over", "");
				}
			}
		}
	}
}
//jquery
$(document).ready(
	function() {
		var tooltipGet = true;
		var tooltipID = 0;
		
		//AJAX Set Up - Jquery
		var ajax;
		
		//Tablesort - list items
		$("#listItems").tablesorter({headers: { 0: { sorter: false}}, debug: false}).tablesorterPager({container: $(".pager"), positionFixed: false});

		//hover tooltip
		$('#listItemsBody a').live("mouseover",function(e) {
				var url = this.toString();
				var id = url.substr(url.lastIndexOf('/')+1);
				
				//Get Tooltip Info - Ajax
				if (tooltipGet && id != tooltipID) {
					tooltipGet = false;
					tooltipID = id;
					$('#floatingTooltip').html('<img src=\"/library/images/ajax-loader.gif\" alt=\"Loading\"/>');
					ajax = $.get('/tooltip.php', {id:id}, function(data){
						$('#floatingTooltip').html(data);
						tooltipGet = true;
						if ($(window).height() + $(window).scrollTop() <= e.pageY+$('#floatingTooltip').outerHeight()+20) {
							$('#floatingTooltip').css("top", e.pageY-$('#floatingTooltip').outerHeight());
						}
					});
				}
				
				//Move Div to follow mouse
				$('#listItemsBody a').mousemove(function(e) {
					id = url.substr(url.lastIndexOf('/')+1);
					if ($(window).height() + $(window).scrollTop() <= e.pageY+$('#floatingTooltip').outerHeight()+20)
						$('#floatingTooltip').css("top", e.pageY-$('#floatingTooltip').outerHeight());
					else
						$('#floatingTooltip').css("top", e.pageY+20);
					$('#floatingTooltip').css("left", e.pageX+20);
				});
				$('#floatingTooltip').show();
			}
		);
		$('#listItemsBody a').live("mouseout",
			function() {
				$('#floatingTooltip').hide();
				ajax.abort();
				tooltipGet = true;
				tooltipID = 0;
			}
		);
		$('#listItemsBody a').live("click", function() {
			ajax.abort();
		});
		
		//Open/Close add abilities window
		$('#openAddAbilities').click(
			function() {
				$('#addAbilities').width($('#addAbilities').width());
				//$('#addAbilities').toggle('clip', { direction: "horizontal" });
				$('#addAbilities').toggle('puff');
			}
		);
		$('#closeAddAbilities').click(
			function() {
				$('#addAbilities').width($('#addAbilities').width());
				$('#addAbilities').hide('puff');
			}
		);
		$('#advSearch').click(function() {
			$('#advSearchOpts').toggle('blind');
		});
		
		//Sortable Attributes
		$("#attributes, #delAttribute").sortable({placeholder: 'ui-sortable-placeholder', handle: '#moveHandle', connectWith: ['.attributeLists'], update: function(){
				var order = $("#attributes").sortable("toArray");
				var newOrder = '';
				for (var i = 0; i < order.length; i++) {
					newOrder += order[i]+":";
				}
				$('#attributesOrder').val(newOrder);
			}, receive: function() {
				$('#delAttribute li').html('');
			}
		});
		$('#attributes li input:text').live('keyup', function() {
			var s = this.value;
			var regex = "^([+-]|)([0-9]+|([0-9]+\\.[0-9]+))$";
			checkRegExp(regex, s, 'attributesError', 'Invalid Value - Must be an integer');
		});
		$('#attributeList').change(function() {
			if (this.selectedIndex) {
				var attributeID = this.options[this.selectedIndex].value;
				var stat = this.options[this.selectedIndex].text;
				var order = $("#attributes").sortable("toArray");
				var used = false;
				for (var i = 0; i < order.length; i++) {
					if (order[i] == attributeID)
						used = true;
				}
				if (used) {
					alert('You cannot add the same ability twice')
				} else {
					$('#attributes').append("<li id=\""+attributeID+"\"><img class=\"floatRight\" id=\"moveHandle\" alt=\"Delete\" src=\"/library/images/move.gif\"/><input type=\"text\" name=\"value[]\" size=\"2\"/> "+stat+"<input type=\"hidden\" name=\"stat[]\" value=\""+attributeID+"\"/></li>");
					$('#attributesOrder').val($('#attributesOrder').val()+attributeID+":");
					$('#attributesError').html('Invalid Value - Must be an integer');
				}
				this.selectedIndex = 0;
			}
		});
	}
);