var recipes = new Array();
var axRecipeList, axRecipeDetail;
var open_idx = 0;

function getRecipeList() {
	var sXML = "xml/index.xml";
	if (window.XMLHttpRequest) {
		axRecipeList = new XMLHttpRequest();
		bIE = false;
	} else if (window.ActiveXObject) {
		axRecipeList = new ActiveXObject("Microsoft.XMLHTTP");
	}
	axRecipeList.open("GET", sXML, true);
	axRecipeList.onreadystatechange = parseList;
	axRecipeList.send(null);
}

function parseList() {
	if (axRecipeList.readyState == 4) {
		switch (axRecipeList.status) {
			case 200:
				//alert(axRecipeList.responseText);
				recipes = new Array();
				var xmldoc = axRecipeList.responseXML;
				var root = xmldoc.getElementsByTagName("list")[0];
				for (var i=0; i<root.childNodes.length; i++) {
					var nItem = root.childNodes.item(i);
					if (nItem.nodeName == "item") {
						var item_id = nItem.getAttribute("id");
						var item_name = nItem.firstChild.nodeValue;
						recipes.push(new Recipe(item_id, item_name));
					}
				}
				axRecipeList = null;
				if (document.location.search.length > 0) {
					var recipeparam = document.location.search.substring(1, document.location.search.length);
					for (var i=0; i<recipes.length; i++) {
						if (recipes[i].id == recipeparam) {
							open_idx = i;
						}
					}
				}
				showList();
				openRecipe(recipes[open_idx].id);
				break;
			case 404:
				alert("Recipe list is not available.");
				break;
			default: 
				alert("Error "+axCardFeature.status+" in loading recipe list.");
				break;
		}
	}
}

function Recipe(id, name) {
	this.id = id;
	this.name = name;
	this.opened = false;
	this.description = "";
	this.ingredient = "";
	this.method = "";
	this.serving = "";
}

function showList() {
	var out = '<table width="100%"  border="0" cellspacing="0" cellpadding="0">';
	
	for (var i=0; i<recipes.length; i++) {
		out += '<tr><td width="15" id="tdArrow'+i+'"></td>';
		out += '<td><a href="javascript:openRecipe(\''+recipes[i].id+'\');">'+recipes[i].name+'</a></td></tr>';
	}
	document.getElementById("recipelist").innerHTML = out;
}


function getRecipeIdx(id) {
	for (var i=0; i<recipes.length; i++) {
		if (recipes[i].id == id) return i;
	}
	return -1;
}

function openRecipe(id) {
	track('recipe/'+id);
	var idx = getRecipeIdx(id);
	if (idx>-1) {
		if (recipes[idx].opened) showRecipeDetail(idx);
		else getRecipeDetail(idx);	
	}
}


getRecipeList();