var itemIndex = 0;

function loadItem () {
	var itemId		=	items[itemIndex++];
	if (itemIndex <= items.length)
		loadXmlObject("/xmlcache/ajax/" + itemId  + ".xml", itemId);
}


function handleIcon () {
	if (xmlhttp.readyState < 4) {
		return false;
	}
	if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    	handleIconData(xmlhttp.responseText);
 	else if (xmlhttp.itemId && xmlhttp.status == 404) {
  	loadXmlObject("http://www.wowhead.com/?item=" + xmlhttp.itemId  + "&xml");
  }
}


function handleIconData (xmlText) {
	var xmlDoc			 	= parseXmlText(xmlText);
	setTimeout(loadItem, 20);
	
	if (!xmlDoc.getElementsByTagName("icon")[0])
		return false;
	
	var iconName			=	xmlDoc.getElementsByTagName("icon")[0].childNodes[0].nodeValue.toLowerCase();
	var itemCode			= xmlDoc.getElementsByTagName("item")[0].getAttribute('id');
	var itemSlot			= slots[itemCode];
	var targetNode		=	$('item_' + itemSlot);

	if (!targetNode)
		return false
	targetNode.appendChild(createImageLink(iconName, itemCode));		
}


function createImageLink (iconName, itemCode) {
	var imageNode 		= document.createElement('img');
	imageNode.src 		= "http://static.wowhead.com/images/icons/medium/" + iconName + ".jpg";
	imageNode.height 	= "36";
	imageNode.width  	= "36";
	
	var linkNode	=	document.createElement('a');
	linkNode.href = "http://www.wowhead.com/?item=" + itemCode;
	linkNode.appendChild(imageNode);
	return linkNode;
}	


function parseXmlText (input) {
	try {
	  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	  xmlDoc.async = "false";
	  xmlDoc.loadXML(input);
	}
	catch(e) {
	  try {
		  parser = new DOMParser();
		  xmlDoc = parser.parseFromString(input, "text/xml");
	  }
	  catch(e) {}
	}	
	return xmlDoc;
}	


var xmlhttp;

function loadXmlObject (location, itemId) {
	var newUrl 			= itemId ? location : "/ajaxProxy.php?page=" + urlencode(location);
	xmlhttp 				= null;

	if (window.XMLHttpRequest)
	  xmlhttp = new XMLHttpRequest();
	else if (window.ActiveXObject) 
	  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

	if (itemId && xmlhttp)
		xmlhttp.itemId	=	itemId;
	if (!xmlhttp)
		return false;

  xmlhttp.onreadystatechange = handleIcon;
  xmlhttp.open("GET", newUrl, true);
  xmlhttp.send(null);
}

loadItem();
