// Max number of cells (i.e. sections) per table row.
var cellPerRow = 3;

var currentCellCount = 0;

// Reference to current row, if the number of cells is less 
// then cellPerRow, add the new section to the end of the row.
var currentRow;

var allSectionsArray = new Array();

// TODO: XML on error handler
// Not implemented yet. Low posibilities

// TODO: Test refresh to find out if recipe items always come back.
// Tested, it always come back and it should come back.
function addSections(sectionNameArray, sectionIdArray, 
			sectionItemNameArray, sectionItemIdArray) {

	var glTable = document.getElementById("gr_list");
	if (glTable == null) {
		return;
	}

	var number_of_sections = sectionNameArray.length;
	if ((number_of_sections == 0) ||
		(number_of_sections != sectionIdArray.length) ||
		(number_of_sections != sectionItemNameArray.length) ||
		(number_of_sections != sectionItemIdArray.length)) {
		
		return;
	}

	/*
	// Get total number of items, plus section title, and input 
	// textarea.
	var total_items = 0;
	var i;
	for (i = 0; i < number_of_sections; i++) {
		var nameArray = sectionItemNameArray[i];
		total_items++; // section name
		total_items++; // break between sections
		total_items += 3; // textarea
		if (typeof nameArray != undefined) {
			total_items += nameArray.length;
		}
	}
	
	total_items += 2; // You may have two continue section titles
	var rows_per_col = (total_items - total_items%3)/3 + 1;
	
	alert("rows_per_col: " + rows_per_col);
	*/
	
	var rows_per_col = 133;

	// Insert the first row
	var glTBody = document.createElement("TBODY");
	glTable.appendChild(glTBody);
	var firstRow = document.createElement("TR");
	glTable.appendChild(firstRow);
	glTBody.appendChild(firstRow);
	// Insert the first cell
	var firstCell = document.createElement("TD");
	firstCell.id = "sec_td";
	firstRow.appendChild(firstCell);
	var currentCell = firstCell;
	var currentCol = 0;

	var j; currentRowCount = 0;
	for (i = 0; i < number_of_sections; i++) {
		var htmlInputItems = new Array();
		allSectionsArray[i] = htmlInputItems;
		var sectionName = sectionNameArray[i];
		var sectionId = sectionIdArray[i];
		var itemNameArray = sectionItemNameArray[i];
		var itemIdArray = sectionItemIdArray[i];
		
		for (j = 0; j < itemNameArray.length; j++) {
	
			// Taking care of the section title
			if (currentRowCount >= rows_per_col) {
				currentRowCount = 0;
				currentCell = document.createElement("TD");
				currentCol++;
				if ((currentCol%2) > 0) {
					currentCell.id = "sec_td_2";
				} else {
					currentCell.id = "sec_td";
				}
				
				firstRow.appendChild(currentCell);
			}
			
			if ((currentRowCount == 0) || (j == 0)) {
				var secNameText;
				if (j == 0) {
					secNameText = 
							document.createTextNode(sectionName.toUpperCase());
				} else {
					secNameText = 
							document.createTextNode(sectionName.toUpperCase() + " (Cont'd)");
				}
				var titleSpan = document.createElement("SPAN");
				titleSpan.appendChild(secNameText);
				titleSpan.id = "blk11bld";
				currentCell.appendChild(titleSpan);
				currentCell.appendChild(document.createElement("br"));
				currentRowCount++;
			}
			
			var inputElement, textElement;
			inputElement = document.createElement("INPUT");
			inputElement.type = "checkbox";
			inputElement.setAttribute("NAME", sectionId + "_" + itemIdArray[j]);
			currentCell.appendChild(inputElement);
                        htmlInputItems[j] = inputElement;		
	
			textElement = document.createTextNode(itemNameArray[j]); 
			currentCell.appendChild(textElement);
			currentCell.appendChild(document.createElement("br"));	
			currentRowCount++;
		}
		
		// Textarea
		var secMoreItem = document.createElement("TEXTAREA");
		secMoreItem.rows = "3";
		secMoreItem.cols = "15";
		secMoreItem.id = "sec_textarea"
		secMoreItem.setAttribute("NAME", "M" + sectionId);
		currentCell.appendChild(secMoreItem);
		currentCell.appendChild(document.createElement("br"));	
		currentCell.appendChild(document.createElement("br"));	
		currentRowCount += 4;
	}
	
};

function loadRecipes(recipeList) {	

	if ((recipeList == "") ||
		(recipeList == null) ||
		(typeof recipeList == undefined)) {
		
		return;
	}
	
	var recipeItemArray = new Array();
	var recipeItemCount = 0;
	
	var rl = recipeList.split('|');
	var idx;
	
	for (idx = 0; idx < rl.length; idx++) {
        if ((rl[idx] != "") &&
			(rl[idx] != null) &&
			(typeof rl[idx] != undefined)) {
			
			var fn = rl[idx];
			var xmlIsland = loadXMLDoc("/xml/recipe_" + fn + ".xml");
		
			var seciontList;
			if (browserType == "ie") {
				sectionList = xmlIsland.selectNodes("//section");
			} else {
				sectionList = xmlIsland.getElementsByTagName("section");
			}
		
			var i;
			for (i = 0; i < sectionList.length; i++) {
		
				var section = sectionList.item(i);
				if (section != null) {
					var sectionId = section.getAttribute("id");
								
					var itemList = section.getElementsByTagName("ITEM");
					var j;
					for (j = 0; j < itemList.length; j++) {
						var item = itemList[j];
						if (item !=  null) {
							
							recipeItemArray[recipeItemCount++] = 
								sectionId + "_" + item.getAttribute("id");
						} 
					}
				}	
			}
		}
	}
	
	// Check recipe items
	for (idx = 0; idx < recipeItemCount; idx++) {
		var inputItems = document.getElementsByTagName("INPUT");
		var j;
		for (j = 0; j < inputItems.length; j++) {
			var itemName;
			if (browserType == "ie") {
				itemName = inputItems[j].NAME;
			} else {
				itemName = inputItems[j].getAttribute("NAME");
			}

			if (recipeItemArray[idx] == itemName) {
				inputItems[j].checked = true;
			}
		}		
	}
};	

// Parse XML file and display grocery list
function displayGroceryList() {	

	var xmlIsland = loadXMLDoc("/xml/grocery_list.xml");
	
	var seciontList;
	if (browserType == "ie") {
		sectionList = xmlIsland.selectNodes("//section");
	} else {
		sectionList = xmlIsland.getElementsByTagName("section");
	}
	
	var i;
	var sectionNameArray = new Array();
	var sectionIdArray = new Array();
	var sectionItemNameArray = new Array();
	var sectionItemIdArray = new Array();
	
	for (i = 0; i < sectionList.length; i++) {
	
		var section = sectionList.item(i);
		if (section != null) {
			// Get section name
			var sectionName;
			if (browserType == "ie") {
				sectionName = section.selectSingleNode("NAME").text;
			} else {
				sectionName = 
					section.getElementsByTagName("NAME")[0].firstChild.nodeValue;
			}
			sectionNameArray[i] = sectionName;

			var sectionId = section.getAttribute("id");
			sectionIdArray[i] = sectionId;
							
			var itemList = section.getElementsByTagName("ITEM");
			var itemNameArray = new Array();
			var itemIdArray = new Array();

			var j;
			for (j = 0; j < itemList.length; j++) {
				var item = itemList[j];
				if (item !=  null) {
					// Get item name
					if (browserType == "ie") {
						itemNameArray[j] = item.selectSingleNode("NAME").text;
					} else {
						itemNameArray[j] = 
							item.getElementsByTagName("NAME")[0].firstChild.nodeValue;
					}
					
					itemIdArray[j] = item.getAttribute("id");
				} else {
					itemNameArray[j] = "";
					itemIdArray[j] = "";
				}
			}
			
			sectionItemNameArray[i] = itemNameArray;
			sectionItemIdArray[i] = itemIdArray;
		}	
	}
	
	// Insert table in GR_LIST table	
	addSections(sectionNameArray, sectionIdArray, sectionItemNameArray, sectionItemIdArray);

	loadListFromCookie();

	loadEnteredItemFromCookie();
	
	if ((recipeList != "") &&
		(recipeList != null) &&
		(typeof recipeList != undefined)) {
	
		loadRecipes(recipeList);
	}
};

function saveListToCookie() {
	var itemList = document.getElementsByTagName("INPUT");
	var i;
	var cookieStr = "";
	for (i = 0; i < itemList.length; i++) {
		var itemType = itemList[i].type;

		var itemChecked = itemList[i].checked;
		
		if ((itemType == "checkbox") && (itemChecked)) {
			var itemName;
			if (browserType == "ie") {
				itemName = itemList[i].NAME; 
			} else {
				itemName = itemList[i].getAttribute("NAME");
			}
			
			var idx = itemName.indexOf('_');
			// Make sure the _ is in the middle of the name
			if ((idx > 0) && (idx < (itemName.length - 1))) {
				var numbs = itemName.split('_');
				// Make sure there is only one '_'
				if (numbs.length == 2) {
					var secNum = parseInt(numbs[0]);
					var itemNum = parseInt(numbs[1]);
					// Make sure these numbers are valid
					if (secNum != NaN && itemNum != NaN) {
						// The name looks good here.
						if (cookieStr == "") {
							cookieStr = itemName;
						} else {
							cookieStr += "|" + itemName;
						}
					}
				}	
			}
		}
	}

	var now = new Date();
	var milliSec = now.getTime() + cExpInterval; 
	var expDate = new Date(milliSec);
	document.cookie = "glitems=" + escape(cookieStr) + 
			"; expires=" + expDate.toGMTString() + 
            "; path=/";
	
}

function saveEnteredItemToCookie() {
	var now = new Date();
	var milliSec = now.getTime() + cExpInterval; 
	var expDate = new Date(milliSec);

	var itemList = document.getElementsByTagName("TEXTAREA");
	var i;
	var cookieStr = "";
	for (i = 0; i < itemList.length; i++) {
		var enteredValue = itemList[i].value;
		
		// Make sure this is not an empty field
		var itemName;
		if (browserType == "ie") {
			itemName = itemList[i].NAME;
		} else {
			itemName = itemList[i].getAttribute("NAME");
		}
		
		if ((typeof itemName == undefined) ||
			(itemName == "") || 
			(itemName == null)) {
			
			continue;
		}
		
		if (itemName.charAt(0) == 'M') {
			var secNumStr = itemName.substring(1);
			var secNum = parseInt(secNumStr);
			
			// Make sure the section number is valid
			if (secNum != NaN) {
				document.cookie = itemName + "=" + escape(enteredValue) +
						"; expires=" + expDate.toGMTString() +
						"; path=/";
			}
		}
	}
};

function loadListFromCookie() {

	var itemList = GetCookie("glitems");		
	
	if ((typeof itemList == undefined) ||
            (itemList == "") || 
	    (itemList == null)) {
		
		return;
	}

	var itemNameArray = itemList.split('|');
	var i;
	for (i = 0; i < itemNameArray.length; i++) {
                var savedItem = itemNameArray[i];
		if ((typeof savedItem == undefined) ||
		    (savedItem == null) ||
		    (savedItem == "")) {
                
                    continue;
		}

		var idx = savedItem.indexOf('_');
		// Make sure the _ is in the middle of the name
		if ((idx > 0) && (idx < (savedItem.length - 1))) {
			var numbs = savedItem.split('_');
			// Make sure there is only one '_'
			if (numbs.length == 2) {
				var secNum = parseInt(numbs[0]);
				var itemNum = parseInt(numbs[1]);
				// Make sure these numbers are valid
				if (secNum != NaN && itemNum != NaN) {
                                        ((allSectionsArray[--secNum])[--itemNum]).checked = true;
				}
			}	
        }
	}
};
	
function loadEnteredItemFromCookie() {
	var itemList = document.getElementsByTagName("TEXTAREA");
	var i;
	for (i = 0; i < itemList.length; i++) {
		var itemName;
		if (browserType == "ie") {
			itemName = itemList[i].NAME;
		} else {
			itemName = itemList[i].getAttribute("NAME");
		}
		
		if ((typeof itemName == undefined) ||
			(itemName == null) ||
			(itemName == "")) {
			
			continue;
		}
		
		if (itemName.charAt(0) == 'M') {
			var secNumStr = itemName.substring(1);
			var secNum = parseInt(secNumStr);
			
			// Make sure the section number is valid
			if (secNum != NaN) {
				var enteredValue = GetCookie(itemName);
				if ((enteredValue != null) && 
					(typeof enteredValue != undefined) &&
					(enteredValue != null)) {
						
					itemList[i].value = enteredValue;
				}
			}
		}
	}		
};

function unloadEventHandler() {
	saveEnteredItemToCookie(); 
	saveListToCookie();
}

function submitForPrint() {
	var form2 = document.getElementById("gl_form_2");
	if ((typeof form2 == undefined) ||
		(form2 == "") ||
		(form2 == null)) {
	
		return false;
	}
	
	var inputIList_1 = document.getElementById("item_list_1");
	if ((typeof inputIList_1 == undefined) ||
		(inputIList_1 == "") ||
		(inputIList_1 == null)) {
		
		return false;
	}
	
	var inputIList_2 = document.getElementById("item_list_2");
	if ((typeof inputIList_2 == undefined) ||
		(inputIList_2 == "") ||
		(inputIList_2 == null)) {
		
		return false;
	}
	
	var inputIList_3 = document.getElementById("item_list_3");
	if ((typeof inputIList_3 == undefined) ||
		(inputIList_3 == "") ||
		(inputIList_3 == null)) {
		
		return false;
	}
	
	var inputMoreList = document.getElementById("more_list");
	if ((typeof inputMoreList == undefined) ||
		(inputMoreList == "") ||
		(inputMoreList == null)) {
		
		return false;
	}

	var inputUserComment = document.getElementById("user_comment");
	if ((typeof inputUserComment == undefined) ||
		(inputUserComment == "") ||
		(inputUserComment == null)) {
		
		return false;
	}


	var itemList = document.getElementsByTagName("INPUT");
	var i;
	var iList = "";
	for (i = 0; i < itemList.length; i++) {
		var itemType = itemList[i].type;

		var itemChecked = itemList[i].checked;
		
		//- change false to true, just testing now.
		if ((itemType == "checkbox") && (itemChecked)) {
			var itemName;
			if (browserType == "ie") {
				itemName = itemList[i].NAME; 
			} else {
				itemName = itemList[i].getAttribute("NAME");
			}
			
			var idx = itemName.indexOf('_');
			// Make sure the _ is in the middle of the name
			if ((idx > 0) && (idx < (itemName.length - 1))) {
				var numbs = itemName.split('_');
				// Make sure there is only one '_'
				if (numbs.length == 2) {
					var secNum = parseInt(numbs[0]);
					var itemNum = parseInt(numbs[1]);
					// Make sure these numbers are valid
					if (secNum != NaN && itemNum != NaN) {
						// The name looks good here.
						if (iList == "") {
							iList = escape(itemName);
						} else {
							iList += escape("|" + itemName);
						}
					}
				}	
			}
		}
	}

	if (iList.length > 1500) {
		inputIList_1.value = iList.substring(0, 1499);
		var iList2 = iList.substring(1500, iList.length);
		if (iList2.length > 1500) {
			inputIList_2.value = iList2.substring(0, 1499);
			inputIList_3.value = iList2.substring(1500, iList2.length);
		} else {
			inputIList_2.value = iList2;
		}
	} else {
		inputIList_1.value = iList;
	}	
	
	itemList = document.getElementsByTagName("TEXTAREA");
	var mList = "";

	for (i = 0; i < itemList.length; i++) {
		
		var enteredValue = itemList[i].value;
		
		if ((enteredValue != "") &&
			(enteredValue != null) &&
			(typeof enteredValue != undefined)) { 
		
			// Make sure this is not an empty field
			var itemName;

			if (browserType == "ie") {
				itemName = itemList[i].name;
				if ((typeof itemName == undefined) ||
                                    (itemName == "") ||
                                    (itemName == null)) {
					itemName = itemList[i].NAME;
				}
			} else {
				itemName = itemList[i].getAttribute("NAME");
			}
			
			if ((typeof itemName == undefined) ||
				(itemName == null) ||
				(itemName == "")) {
				
				continue;
			}
 
			// Add user comments
			if (itemName == "user_comment_input") {
                                inputUserComment.value = escape(enteredValue);
			}
			
			if (itemName.charAt(0) == 'M') {
				var secNumStr = itemName.substring(1);
				var secNum = parseInt(secNumStr);
				
				// Make sure the section number is valid
				if (secNum != NaN) {
					var inputTX = document.createElement("INPUT");
					inputTX.type = "hidden";
					
					inputTX.name = itemName;
					inputTX.value = escape(enteredValue);
					form2.appendChild(inputTX);
					
					// escape escape
					if (mList == "") {
						mList = itemName;
					} else {
						mList += "|" + itemName;
					}
				}
			}
		}
	}
	
	if (mList != "") {
		inputMoreList.value = mList;
	}
	
	form2.submit();
}

function clearAll() {
	var rv = confirm("Clear your checklist?");
        if (!rv) {
             return;
        }

	var itemList = document.getElementsByTagName("INPUT");
	var i;
	var iList = "";
	for (i = 0; i < itemList.length; i++) {
		var itemType = itemList[i].type;

		var itemChecked = itemList[i].checked;
		
		//- change false to true, just testing now.
		if ((itemType == "checkbox") && (itemChecked)) {
			var itemName;
			if (browserType == "ie") {
				itemName = itemList[i].NAME; 
			} else {
				itemName = itemList[i].getAttribute("NAME");
			}
			
			var idx = itemName.indexOf('_');
			// Make sure the _ is in the middle of the name
			if ((idx > 0) && (idx < (itemName.length - 1))) {
				var numbs = itemName.split('_');
				// Make sure there is only one '_'
				if (numbs.length == 2) {
					var secNum = parseInt(numbs[0]);
					var itemNum = parseInt(numbs[1]);
					// Make sure these numbers are valid
					if (secNum != NaN && itemNum != NaN) {
                                                itemList[i].checked = false;
					}
				}	
			}
		} else if (itemType == "hidden"){
			itemList[i].value = "";
                }
	}

	itemList = document.getElementsByTagName("TEXTAREA");
	for (i = 0; i < itemList.length; i++) {
            itemList[i].value = "";
        }
}

if (browserType == "ie") {
	window.attachEvent("onload", displayGroceryList);
	window.attachEvent("onunload", unloadEventHandler);
} else {
	window.addEventListener('load', displayGroceryList, false);
	window.addEventListener('unload', unloadEventHandler, false);
}
