var item;
var INPUT_NAME_PREFIX = 'items';
var tableRows = 0;
var itemArray = new Array();
var newForm = 1;
var theItems="";
var INPUT_NAME_PREFIX = 'inputName'; // this is being set via script
var ROW_BASE = 1; // first number (for display)
var rowNumber = 0;
var theItemCouponNum = 0;
var numberOfItems = 0;
var checkNumber = 0;

function addRowToTable() {
	//Inititialize the variables for use
	this.itemInput = document.listCreationForm.items.value;
	if(itemInput == ''){
		alert("Please enter a value!");
		return;
	}
	addRowToTableHelper(this.itemInput, null, null, null, false);
}
function addRowToTableHelper(item, discount_id, matchedKeyword, matchedKeywordPrice, disableDelete) {
	//see if the form is new...if so generate the makelist button and sendlist button
		if(newForm==1){
			newForm=0;
			rowNumber=0;
		}
		if(rowNumber == 0) {
			showDiv('checkCoupons');
		}
		var itemInput = TrimUsingWhileLoop(item);		
		itemInput = checkCharacters(itemInput);
		
		var tbl = document.getElementById('itemTable');
		
		var rowDiv = document.createElement('div');
		rowDiv.setAttribute('id', 'rowDiv' + rowNumber);
		setClassAttribute(rowDiv, 'items');
		
		var rowDisp = document.createElement('ul');
		setClassAttribute(rowDisp, 'itemline');
		
		var listField;
		var showDiscount;
		
		
		if(listField == undefined)
		{
			listField = document.createElement('li');
			if(itemInput.length > 30) {
				lastspace = itemInput.lastIndexOf(" ");
				low = itemInput.substr(0, lastspace);
				high = itemInput.substr(lastspace, itemInput.length);
				listField.appendChild(document.createTextNode(low));
				listField.appendChild(document.createElement('br'));
				listField.appendChild(document.createTextNode(high));			
				setheight = setRowDivHeight(itemInput);
				rowDiv.style.height = setheight;
			} else {
				listField.appendChild(document.createTextNode(itemInput));
			}
			setClassAttribute(listField, 'item');
		}
		
		if(!disableDelete)
		{
			var btnfield = document.createElement('li');
			setClassAttribute(btnfield, 'deleteBtn');
			var buttonImage = document.createElement('img');
			buttonImage.setAttribute('src', '../graphics/cross.gif');
			buttonImage.setAttribute('id', 'image' + rowNumber);
			buttonImage.setAttribute('alt', "Delete " + itemInput);
			buttonImage.onclick = function () {deleteCurrentRow(this)};
			setClassAttribute(buttonImage, 'deleteImg');
			btnfield.appendChild(buttonImage);
			rowDisp.appendChild(btnfield);
		}
		rowDisp.appendChild(listField);
		
		if(discount_id!=-1 && discount_id != "" && matchedKeyword!=null && matchedKeywordPrice!=null) {
			var dscField = document.createElement('li');
			dscImage = document.createElement('img');
			dscImage.setAttribute('src', '../graphics/star_icon.gif');
			setClassAttribute(dscField, 'dscField');
			dscField.appendChild(dscImage);
			rowDisp.appendChild(dscField);
			
			var discountIdField = document.createElement('li');
			discountIdField.appendChild(document.createTextNode(discount_id));
			discountIdField.style.display = 'none';
			rowDisp.appendChild(discountIdField);
			
			var matchedKeywordField = document.createElement('li');
			matchedKeywordField.appendChild(document.createTextNode(matchedKeyword));
			matchedKeywordField.style.display = 'none';
			rowDisp.appendChild(matchedKeywordField);
			
			var matchedKeywordPriceField = document.createElement('li');
			matchedKeywordPriceField.appendChild(document.createTextNode(matchedKeywordPrice))
			matchedKeywordPriceField.style.display = 'none';
			rowDisp.appendChild(matchedKeywordPriceField);
		}
		
		rowDiv.appendChild(rowDisp);
		
		if(rowNumber%2 == 0) 
			rowDiv.style.background = '#f1f5fa';
		
		if(numberOfItems==0) {
			tbl.appendChild(rowDiv);
		} else {
			var nodes = tbl.getElementsByTagName('div');
			var topDiv = nodes[0].id; //get the very top div to append above
			var prevRow = document.getElementById(topDiv);
			tbl.insertBefore(rowDiv,prevRow);
		}
		rowNumber++;
		numberOfItems++;
		document.listCreationForm.items.value = "";
		document.listCreationForm.items.focus();
}

function constructShoppingList(item) {
		var tbl = document.getElementById('itemTable');
		var rowDiv = document.createElement('div');
		setClassAttribute(rowDiv, 'iconelement blankcheck');
		
		var txt = document.createElement('span');
		setClassAttribute(txt, 'labstyle');
		txt.appendChild(document.createTextNode(item));
		
		rowDiv.appendChild(txt);
		tbl.appendChild(rowDiv);
		rowDiv.onclick = function () {toggle(this)};
	//	if(checkNumber%2 == 0) 
		//	rowDiv.style.background = '#f1f5fa';
		checkNumber++;
}

function toggle(obj) {
	if(obj.title == "checked") {
		obj.setAttribute('title', '');
		setClassAttribute(obj, 'iconelement blankcheck');
	} else {
		obj.setAttribute('title', 'checked');
		setClassAttribute(obj, 'iconelement checked');
	}
}
function addSpecialOrIncentiveToTable(itemName, coupon_id, matchedKeyword, matchedKeywordPrice, disDelete)
{
	if(itemName == "" || coupon_id == "") {return;}
	if(disDelete == null || disDelete == "") {disDelete = false;}
	
	addRowToTableHelper(itemName, coupon_id, matchedKeyword, matchedKeywordPrice, disDelete);
}
function fillDiscountListDynamically(discountString)
{
	discountString = decodeURIComponent(discountString);
	if(discountString != "") {
		var pieces = discountString.split('~');
		for(var i = 0; i<pieces.length; i++) {
			strips = pieces[i].split('_-_');
			id = strips[1].split('-:');
			matchedKey = id[1].split('-__');
			price = matchedKey[1];
			//console.log('HERE',strips[0]+' '+id[0]+' '+matchedKey[0]+' '+price);
			addSpecialOrIncentiveToTable(strips[0], id[0], matchedKey[0], price, false);
		}
		document.getElementById('cklist').innerHTML = '<span style="text-align:center;"><span class="blk">View check list</span> <span class="blk">and</span> <span class="blk">redeem coupons.</span></span>';
	}	
}
function constructExistingList(listid, isshopping) {
	constructList_xmlHttp=GetXmlHttpObject();
	if (constructList_xmlHttp==null) {
		alert ("Browser does not support HTTP Request");
		return;
	}
	if (constructList_xmlHttp.readyState != 0) {
        constructList_xmlHttp.abort();
        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
    }     
	var url="../scripts/get_list.php";
	url=url+"?id="+listid;
	constructList_xmlHttp.open("GET",url,true);
	
	constructList_xmlHttp.onreadystatechange = function() {
	if (constructList_xmlHttp.readyState==4 || constructList_xmlHttp.readyState == "completed"){ 
		var listResponse = constructList_xmlHttp.responseText;
		var listDiv = document.getElementById('itemTable');
			if (window.ActiveXObject) {
				var xmlobject = new ActiveXObject("Microsoft.XMLDOM");
				xmlobject.async="false";
				xmlobject.loadXML(incentiveResponse);
			} else {
				var xmlobject = (new DOMParser()).parseFromString(listResponse, "text/xml");
			}
			var root = xmlobject.getElementsByTagName('userList')[0];
			var list = root.getElementsByTagName("list"); //get the list
			for(var i=0; i < list.length; i++) {
				var theList = list[i];
				var items = theList.getElementsByTagName("item");
				for(var j=0; j <items.length; j++) {
					if(items[j].firstChild != null) 
						if(!isshopping)
							addRowToTableHelper(items[j].firstChild.nodeValue, null, null, null, false);
						else
							constructShoppingList(items[j].firstChild.nodeValue);
				}
			}
		}
	}; 
	constructList_xmlHttp.send(null);
}
function constructListFromRecipeId(recipeid, isshopping) {
	constructList_xmlHttp=GetXmlHttpObject();
	if (constructList_xmlHttp==null) {
		alert ("Browser does not support HTTP Request");
		return;
	}
	if (constructList_xmlHttp.readyState != 0) {
        constructList_xmlHttp.abort();
        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
    }     
	var url="../scripts/get_ingredients.php";
	url=url+"?id="+recipeid;
	constructList_xmlHttp.open("GET",url,true);
	
	constructList_xmlHttp.onreadystatechange = function() {
	if (constructList_xmlHttp.readyState==4 || constructList_xmlHttp.readyState == "completed"){
		var listResponse = constructList_xmlHttp.responseText;
		var listDiv = document.getElementById('itemTable');
			if (window.ActiveXObject) {
				var xmlobject = new ActiveXObject("Microsoft.XMLDOM");
				xmlobject.async="false";
				xmlobject.loadXML(incentiveResponse);
				
			} else {
				var xmlobject = (new DOMParser()).parseFromString(listResponse, "text/xml");
			}
			
			var root = xmlobject.getElementsByTagName('recipes')[0];
			var recipe = root.getElementsByTagName("recipe"); //get the recipe
			for(var i=0; i < recipe.length; i++) {
				var theRecipe = recipe[i];
				var ingrs = theRecipe.getElementsByTagName("ingredient");
				for(var j=0; j < ingrs.length; j++) {
					if(!isshopping) {
						var theItem = ingrs[j].firstChild.nodeValue;
						var rowDiv = document.createElement('div');
						rowDiv.setAttribute('id', j);
						rowDiv.setAttribute('class', 'items');
						var itemCell = document.createElement('input');
						itemCell.setAttribute('type', 'text');
						itemCell.setAttribute('size', '15');
						itemCell.setAttribute('class', 'item');
						itemCell.setAttribute('value', theItem);
						itemCell.setAttribute('disabled', 'disabled');
						rowDiv.appendChild(itemCell);
						btnDiv = document.createElement('div');
						btnDiv.setAttribute('class', 'btn');
						var btnEl = document.createElement('img');
						btnEl.setAttribute('src', '../graphics/cross.gif');
						btnEl.setAttribute('id', theItem);
						btnEl.setAttribute('alt', j);
						btnEl.setAttribute('class', 'deleteBtn');
						btnEl.onclick = function () {deleteCurrentRow(this)};
						btnDiv.appendChild(btnEl);
						rowDiv.appendChild(btnDiv);
						rowNumber++;
						if(j==0)
							listDiv.appendChild(rowDiv);
						else {
							var prevRow = document.getElementById(''+(j-1));
							listDiv.insertBefore(rowDiv,prevRow);
						}
					} else {
					constructShoppingList(theItem);
					}
				}
			}
			newForm = 0;
		}
	}; 
	constructList_xmlHttp.send(null);
}
function saveList() {
	var itemTable = document.getElementById('itemTable');
	var usersItems = itemTable.getElementsByTagName('ul');
	var itemString = "";
	for(var i = 0; i < usersItems.length; i++)
	{	
		var indvItem = usersItems[i];
		if(indvItem.childNodes[5] != null){
			itemString += indvItem.childNodes[1].firstChild.nodeValue + "_-_";//item name
			itemString += indvItem.childNodes[3].firstChild.nodeValue + "-:"; //discount id
			itemString += indvItem.childNodes[4].firstChild.nodeValue + "-__"; // matched keyword
			itemString += indvItem.childNodes[5].firstChild.nodeValue + "#"; // matched keyword price end of group
		}else{
			itemString += indvItem.childNodes[1].firstChild.nodeValue + "_";
		}
	}
	var lddiv = document.getElementById('status');
	var ldimg = document.createElement('img');
	ldimg.setAttribute('src', '../graphics/loading.gif');
	lddiv.appendChild(ldimg); 
	remoteSaveList(itemString);
}
function sharelist() {
	var itemString = getItemString();
	var listid = document.getElementById('listid').value;
	if(itemString == '') {
		alert('Your list is empty. Please make a list first and then share it.');
		return;
	}
	reg = new RegExp("[^a-zA-Z0-9&+:()._%$# -]");
	itemString = itemString.replace(reg, "");
	//Get the name of the list.  If generic, use the date.
	var listName = document.getElementById('listName').value;
	if(listName == "Name your list" || listName == "")
	{
		var d = new Date();
		listName = "Shared: "+(d.getMonth()+1) + "-" + d.getDate() + "-" + d.getFullYear();
	}
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}
	if (xmlHttp.readyState != 0) 
	{
        xmlHttp.abort();
        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
    }
	var url="../scripts/save_mobile_list.php";
	
	//Append the arguments for each type of list
	if(listid == "")
	{
		url += "?itemString=" + encodeURIComponent(itemString);
		url += "&listName=" + encodeURIComponent(listName);
		url += "&share=1"; 
	}
	else //updating an existing list
	{
		//list id is in newOrListID variable
		url += "?listID=" + listid;
		url += "&itemString=" + encodeURIComponent(itemString);
		url += "&listName=" + encodeURIComponent(listName);
		url += "&share=1";
	}
	
	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4 || xmlHttp.readyState == "completed")
		{
			var response = xmlHttp.responseText;
			var parts = response.split("#");
			if(parts[0] == '0')
				window.location = "?act=4&id="+parts[1];
			else
				alert("Sorry an error occured saving your list to be shared.\nPlease try again.");
		}
	} 
	xmlHttp.send(null);
}

function remoteSaveList(items) {	
	remoteSave_xmlHttp=GetXmlHttpObject();
	if (remoteSave_xmlHttp==null)
	{
	alert ("Browser does not support HTTP Request");
	return;
	}
	if (remoteSave_xmlHttp.readyState != 0) {
        remoteSave_xmlHttp.abort();
        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
    }     
	var url="../scripts/save_mobile_list.php?list="+items;
	url += "&listid="+document.getElementById('listid').value;
	
	//alert(items);
	remoteSave_xmlHttp.open("GET",url,true);
	//remoteSave_xmlHttp.send(items);
	remoteSave_xmlHttp.onreadystatechange = function() {
		if (remoteSave_xmlHttp.readyState==4 || remoteSave_xmlHttp.readyState == "completed"){
			var stat = document.getElementById('status');
			clearInnerHTML(stat); 
			saveResponse = remoteSave_xmlHttp.responseText
			if(saveResponse == "fail") 
				alert("fail")
			var saveimg = document.createElement('img');
			var txt = document.createTextNode('List was successfully saved!');
			var ptxt = document.createElement('p');
			ptxt.setAttribute('class' , 'pstat');
			ptxt.appendChild(txt); 
			saveimg.setAttribute('src', '../graphics/tick.gif');
			stat.appendChild(ptxt);
			stat.appendChild(saveimg);
		}
	}; 
	remoteSave_xmlHttp.send(null);
}
function showUserList() {
	//if(num!=0) {
	//deletePreviousList();
	//}
	box = document.forms[0].selected_list;
	if(box != 'undefined' && box != null) {
	var params = box.options[box.selectedIndex].value;
	var params_array = params.split(",");
	var list_id = params_array[0];
	var items = getUserListByID(list_id); // this function fills the table with the items
	}
}

function getUserListByID(list_id){
	totalItems = 0;
	if (list_id.length==0)
	{ 
		return "";
	}
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
	alert ("Browser does not support HTTP Request");
	return;
	}
	if (xmlHttp.readyState != 0) {
        xmlHttp.abort();
        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
    }     
	var url="../scripts/get_list.php";
	url=url+"?id="+list_id;
	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange=function() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState == "completed"){ 
		totalItems++;
		var listItems = document.getElementById('theListItems');	
		listItems.setAttribute('value', xmlHttp.responseText);
		var listResponse = xmlHttp.responseText;
		if (window.ActiveXObject) {
			var xmlobject = new ActiveXObject("Microsoft.XMLDOM");
			xmlobject.async="false";
			xmlobject.loadXML(incentiveResponse);
			} else {
				var xmlobject = (new DOMParser()).parseFromString(listResponse, "text/xml");
			}
			theListDiv = document.getElementById('showList');
			clearInnerHTML(theListDiv);
			var root = xmlobject.getElementsByTagName('userList')[0];
			var list = root.getElementsByTagName("list"); //get the list
			var listid = document.getElementById('listid');
			var list_id = list[0].getElementsByTagName('listid');
			listid.setAttribute('value', list_id[0].firstChild.nodeValue);
			for(var i=0; i < list.length; i++) {
				var theList = list[i];
				var posted = theList.getElementsByTagName("posted")[0].firstChild.nodeValue;
				theListPostTime = document.createElement("h4");
				theListPostTime.setAttribute('style', 'margin-top:5px;');
				theListPostTime.appendChild(document.createTextNode("This list was saved "+posted));
				theListDiv.appendChild(theListPostTime);
				var items = theList.getElementsByTagName("item");
				var orderedList = document.createElement('ol');
				for(var j=0; j <items.length; j++) {
					if(items[j].firstChild != null) {
						var theItem = items[j].firstChild.nodeValue;
						var listEle = document.createElement('li');
						var itemtxt = document.createTextNode(theItem);
						listEle.appendChild(itemtxt);
						orderedList.appendChild(listEle);
					}
				}
				theListDiv.appendChild(orderedList);
			}
			actions = document.getElementById('actions');
			clearInnerHTML(actions);
			var update = document.createElement('input');
			setInputAttributes(update, 'Update List', 'button', 'updatelist();');
			setClassAttribute(update, 'updatelist');
			actions.appendChild(update);
			var deleteme = document.createElement('input');
			setInputAttributes(deleteme, 'Delete List', 'button', 'deletelist();');
			setClassAttribute(deleteme, 'deletelist');
			actions.appendChild(deleteme);
		} 
	}; 
	xmlHttp.send(null);
	var listItems = document.getElementById('theListItems');
	return listItems.value;
}

function setInputAttributes(obj, title, type, onclick) {
	obj.setAttribute('value', title);
	obj.setAttribute('type', type);
	obj.setAttribute('onclick', onclick);
}

function updatelist() {
	box = document.forms[0].selected_list;
	var listid = box.options[box.selectedIndex].value;
	var url ="?act=6";
	url += "&id="+listid;
	window.location = url;
}

function deletelist() {
	box = document.forms[0].selected_list;
	var listid = box.options[box.selectedIndex].value;
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
	alert ("Browser does not support HTTP Request");
	return;
	}
	if (xmlHttp.readyState != 0) {
        xmlHttp.abort();
        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
    }
    var url="../scripts/delete_list_mobile.php";
	url=url+"?id="+listid;
	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4 || xmlHttp.readyState == "completed"){ 
			if(xmlHttp.responseText == 'Success')
				window.location = window.location;
			else
				alert(xmlHttp.repsonseText+" id "+listid );
		}
	};
	xmlHttp.send(null);         
}

function stateChanged_list(){	
	
	
} 

function TrimUsingWhileLoop(str){ 	
	while(str.charAt(0) == (" ")) {
		str = str.substring(1);
  	}
  	while(str.charAt(str.length-1) == " " ) {
  		str = str.substring(0,str.length-1);
  	}
  	return str;
}

function confirmSend(){
	if(theItems == "") {
		return alert("Please add items to your list before sending");
	} else {
		return confirm('Do you want to send your list now?');
	}
}

function confirmSendFromPrintView(){	
		return confirm('Do you want to send your list now?');
}



function showDiv(id) {
if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'block';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'block';
		}
		else { // IE 4
			document.all.id.style.display = 'block';
		}
	}
}


function hideDiv(id) {
if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'none';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'none';
		}
		else { // IE 4
			document.all.id.style.display = 'none';
		}
	}
}


function setEnabled() {
	var btn = document.getElementById("manualSendToCell");
	btn.setAttribute('disabled', false);
}

function confirmSendOtherPhone() {
	regex = /^[- ()0-9]+$/;
	if(theItems == "") {
		return alert("Please add items to your list before sending");
	} else {
		confirmSend = confirm('Do you want to send your list now?');
		if(confirmSend) {
			if(document.itemForm.txtphone.value != "") {
				if(document.itemForm.txtphone.value.length > 9 && document.itemForm.txtphone.value.length < 15) {
					if(document.itemForm.txtphone.value.match(regex)) {
							if(checkReservedNums(document.itemForm.txtphone.value)) {
							return true;
							} else {
								alert("You entered a reserved phone number, please verify the number you intend to send the list to.");
							}
						} else {
							alert("Please enter a valid phone number, including the area code");
							return false;
						}
				} else {
					alert("Please enter a valid phone number, including the area code");
					return false;
				}
			} else {
				alert("Please enter a valid phone number, including the area code");
				return false;
			}
		}
	}
}

function checkReservedNums(num) {
	var theNum = num.replace("(", "");
	theNum = theNum.replace(")", "");
	theNum = theNum.replace("-", "");
	var area = theNum.substr(0,3);	
	var middleNum = theNum.substr(3,3);
	if(area == "900") {
		return false;	
	}
	if(area == "866") {
		return false;
	}
	if(area == "877") {
		return false;
	}
	if(middleNum == "555") {
		return false;
	}
	return true;
}

function confirmSendEmail() {
	regex = /^.+?@.+?\..+$/;
	if(theItems == "") {
		return alert("Please add items to your list before sending");
	} else {
		confirmSend = confirm('Do you want to send your list now?');
		if(confirmSend) {
			if(document.itemForm.email.value != "") {
				if(document.itemForm.email.value.match(regex)) {
					return true;
				} else {
					alert("Please enter a valid email address");
					return false;
				}				
			} else {
				alert("Please enter a valid email address");
				return false;
			}
		}
	}
} 

function pausecomp(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
} 

function setItemsFocus() {
	if(document.listCreationForm.items != null) {
		document.listCreationForm.items.focus();
	}
}

function GetXmlHttpObject()
{ 
var objXMLHttp=null
	
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	return objXMLHttp;
}
function clearInnerHTML(obj) {
	// so long as obj has children, remove them
	while(obj.firstChild) { 
		obj.removeChild(obj.firstChild);
	}
}
function email_friend_current_list(){
	box = document.forms[0].selected_list;
	var list_id = box.options[box.selectedIndex].value;
	var listBox = document.getElementById('selected_list');
	window.location= "?act=4&id="+list_id;
}
function checkCharacters(itemstr) {
		reg = new RegExp("[^a-zA-Z0-9&+:()._%$# -]");
		itemstr = itemstr.replace(reg, " ");
		return itemstr;
}
function setClassAttribute(settingElement, value)
{
	if(settingElement == undefined || value == "")
		return;
	else
	{
		if(navigator.appName == "Microsoft Internet Explorer")
		{
			settingElement.setAttribute('className', value);
		}
		else
		{
			settingElement.setAttribute('class', value);
		}
	}
}

function deleteCurrentRow(obj) {
	var tbl = document.getElementById('itemTable');
	
	//Get the cross' ID
	var substr = obj.id;
	//It should be something like 'image1', but we don't want the 'image' part. Strip it.
	substr = substr.substring(5,substr.length);
	
	try {
		//Get the entire rowDiv and remove it.
		var cell = document.getElementById('rowDiv' + substr);
		tbl.removeChild(cell);
		numberOfItems--;
	} catch(exp) {
		alert(exp+"   "+substr);
	}
}
function enterShoppingMode() {
	var listid =document.getElementById('listid');
	var recipeid = document.getElementById('recipeid');
	var thelist = document.getElementById('thelist');
	var prevact = document.getElementById('prevact');
	
	listidstr = listid.value;
	recipeidstr = recipeid.value;
	var theliststr = thelist.value;
	var prevactstr = prevact.value;
	theliststr = getItemString();
	if(prevactstr == '1' || prevactstr == 'undefined' || prevactstr == "" || prevactstr == '8') {
		theliststr = getItemString();
	}
	var url = "?act=7";
	if(listidstr != 'undefined')
		url += "&id=";
	else
		url += '&id=';
	if(recipeidstr != 'undefined')
		url += "&recipe_id="+recipeidstr;
	else
		url += '&recipe_id=';
	if(theliststr != 'undefined')
		url += "&list="+encodeURIComponent(theliststr);
	else
		url += '&list=';
	if(prevactstr != 'undefined')
		url += "&prevact="+prevactstr;
	else
		url += '&prevact=';
	window.location = url;
}
function fillList(itemStr) {
	var items = itemStr.split("#");
	for(var i = 0; i <items.length; i++) {
		if(items[i]!= "")
			addRowToTableHelper(items[i], null, null, null, false);
	}
}

function setRowDivHeight(itemstr) {
	strlen = itemstr.length;
	heightCnt = 0;
	pad = 0;
	while(strlen > 0) {
		heightCnt += 20;
		pad += 3.2;
		strlen -= 30;
	} 
	return heightCnt+Math.floor(pad)+'px';
}


function getItemString()
{
	//Get all items from within the list.  Consolidate into one string
	/* Layout
	* 0 <li>delete button</li> 
	* 1 <li>item name</li>
	* 2 <li>discount star</li>
	* 3 <li>discount_id</li>
	* 4 <li>matched keyword</li>
	* 5 <li>matchedkeyword price</li>
	*/
	var itemTableArea = document.getElementById('itemTable');
	var usersItems = itemTableArea.getElementsByTagName('ul');
	var itemString = "";
	for(var i = 0; i < usersItems.length; i++)
	{	
		//alert(userItems[i]);
		var indvItem = usersItems[i];
		if(indvItem.childNodes[5] != null){
			itemString += indvItem.childNodes[1].firstChild.nodeValue + "_-_";//item name
			itemString += indvItem.childNodes[3].firstChild.nodeValue + "-:"; //discount id
			itemString += indvItem.childNodes[4].firstChild.nodeValue + "-__"; // matched keyword
			itemString += indvItem.childNodes[5].firstChild.nodeValue + "#"; // matched keyword price end of group
		}else{
			itemString += indvItem.childNodes[1].firstChild.nodeValue + "#";
		}
	}
	return itemString;
}

function preparesave() {
	var itemTable = document.getElementById('itemTable');
	var usersItems = itemTable.getElementsByTagName('ul');
	var itemString = "";
	for(var i = 0; i < usersItems.length; i++)
	{	
		var indvItem = usersItems[i];
		if(indvItem.childNodes[5] != null){
			itemString += indvItem.childNodes[1].firstChild.nodeValue + "_-_";//item name
			itemString += indvItem.childNodes[3].firstChild.nodeValue + "-:"; //discount id
			itemString += indvItem.childNodes[4].firstChild.nodeValue + "-__"; // matched keyword
			itemString += indvItem.childNodes[5].firstChild.nodeValue + "#"; // matched keyword price end of group
		}else{
			itemString += indvItem.childNodes[1].firstChild.nodeValue + "_";
		}
	}
	var items = encodeURIComponent(itemString);
	window.location = "../account/create_account.php?items="+items;
}

function showOptions(option) {
	switch(option) {
		case 'check':
			highlightoption('check');
			hideDiv('divSendPhone'); hideDiv('divMyPhones'); 
			hideDiv('mobileoptions'); 
			hideDiv('emailoptions'); hideDiv('divSendSavedEmail'); 
			hideDiv('status'); hideDiv('savebtn'); hideDiv('sharelist');hideDiv('savelist');
			hideDiv('divSendEmail'); //Effect.Appear('divMyPhones', { duration: 0.8 });
			showDiv('checkmode');
		break;
		case 'mobile':
			highlightoption('mobile');
			hideDiv('divSendPhone'); hideDiv('divMyPhones'); 
			hideDiv('emailoptions'); hideDiv('divSendSavedEmail'); 
			hideDiv('status'); hideDiv('savebtn'); hideDiv('sharelist'); hideDiv('checkmode');
			hideDiv('divSendEmail'); //Effect.Appear('divMyPhones', { duration: 0.8 });
			showDiv('divMyPhones'); 
			showDiv('mobileoptions'); 
		break;
		case 'email':
			highlightoption('email');
			hideDiv('divSendPhone'); hideDiv('divMyPhones'); 
			hideDiv('divSendEmail'); hideDiv('mobileoptions'); hideDiv('checkmode');
			hideDiv('status'); hideDiv('savebtn'); hideDiv('sharelist');
			//Effect.Appear('divSendSavedEmail', { duration: 0.8 });
			showDiv('divSendSavedEmail'); 
			showDiv('emailoptions'); 
		break;
		case 'save':
			highlightoption('savethelist');
			hideDiv('mobileoptions'); hideDiv('divSendPhone'); 
			hideDiv('divMyPhones'); hideDiv('emailoptions'); hideDiv('checkmode');
			hideDiv('divSendSavedEmail'); hideDiv('sharelist');
			hideDiv('status'); hideDiv('divSendEmail');
			//Effect.Appear('savelist', { duration: 0.8 });
			showDiv('savelist'); 
			showDiv('savebtn'); 
		break;
		case 'share':
			highlightoption('sharethelist');
			hideDiv('mobileoptions'); hideDiv('divSendPhone'); 
			hideDiv('divMyPhones'); hideDiv('emailoptions'); 
			hideDiv('divSendSavedEmail'); hideDiv('savebtn'); 
			hideDiv('status'); hideDiv('divSendEmail'); hideDiv('checkmode');
			//Effect.Appear('savelist', { duration: 0.8 });
			showDiv('savelist'); 
			showDiv('sharelist'); 
		break;		
	}
}
function highlightoption(id) {
	div = document.getElementById('optionheader');
	tags = div.getElementsByTagName('a');
	for(var i=0; i<tags.length; i++) {
		var tagid = tags[i].id;
		setClassAttribute(document.getElementById(tagid), 'normaltext');
	}
	setClassAttribute(document.getElementById(id),'boldtext');
}
function setMinus(id) {
	setClassAttribute(document.getElementById(id), 'iconelement minusicon');
}

function setPlus(id) {
	setClassAttribute(document.getElementById(id), 'iconelement plusicon');
}
function checktoggle(id) {
 	var val = document.getElementById(id);
	if(val.value == 'off') {
		val.value = 'on';
		return true;
	} else {
		val.value= 'off';
		return false;
	}
 }
 function submitNewOrUpdateList(newOrListID, share)
{
	isshare = share;
	var itemString = getItemString();
	if(itemString == '') {
		alert('Your list is empty. Please make a list first and then share it.');
		return;
	}
	/*if(share)
		showdivlayer(this, 'sharefriend', 'no');*/
	reg = new RegExp("[^a-zA-Z0-9&+:()._%$# -]");
	itemString = itemString.replace(reg, "");
	itemString = encodeURIComponent(itemString);
	//Get the name of the list.  If generic, use the date.
	var listName = document.getElementById('listName').value;
	if(listName == "Name your list" || listName == "")
	{
		var d = new Date();
		if(!isshare)
			listName = (d.getMonth()+1) + "-" + d.getDate() + "-" + d.getFullYear();
		else
			listName = "Shared: "+(d.getMonth()+1) + "-" + d.getDate() + "-" + d.getFullYear();
	}
	
		//Indicate to user that the list is being saved.
	if(!isshare)
		var loadingDiv = document.getElementById("status");
	else
		var loadingDiv = document.getElementById("status");
		
		var loadingImg = document.getElementById('statusImg');
		if(loadingImg == null)
		{
			loadingImg = document.createElement('img');
		}
		showDiv('status');
		loadingImg.setAttribute('src', '../graphics/loading.gif');
		loadingImg.setAttribute('id', 'statusImg');
		loadingDiv.appendChild(loadingImg);
	
	
	//Get the AJAX stuff ready
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}
	if (xmlHttp.readyState != 0) 
	{
        xmlHttp.abort();
        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
    }
	var url="../scripts/save_mobile_list.php";
	
	//Append the arguments for each type of list
	if(newOrListID == "new")
	{
		url += "?itemString=" + itemString;
		url += "&listName=" + listName;
		if(share)
			url += "&share=1"; 
	}
	else //updating an existing list
	{
		//list id is in newOrListID variable
		url += "?listID=" + document.getElementById('listid').value;
		url += "&itemString=" + itemString;
		url += "&listName=" + listName;
		if(share)
			url += "&share=1";
	}
	
	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange=stateChanged_saveList; 
	xmlHttp.send(null);
}

function stateChanged_saveList()
{
	if (xmlHttp.readyState==4 || xmlHttp.readyState == "completed")
	{
		var response = xmlHttp.responseText;
		var statusDiv = document.getElementById('status');
		var statusImg = document.getElementById('statusImg');
		var statusPElement = document.getElementById('statusPElement');
		//If the p element doesn't exist, create it
		if(statusPElement == null)
		{
			statusPElement = document.createElement('p');
		}
		else //but if it does exist, clear it's status message
		{
			clearInnerHTML(statusPElement);
		}

		statusPElement.setAttribute('id', 'statusPElement');
		setClassAttribute(statusPElement, 'statusPElement');

		//first case is for sharing a saved list
		if(response.substr(0,1) == '0' && response.search('Error') == -1 && isshare)
		{
			statusImg.setAttribute('src', '../graphics/tick.gif');
			listid = document.getElementById('listid');
			listid.value = response.substr(2, response.length);
			var successText = document.createTextNode('List was successfully updated!');
			statusPElement.appendChild(successText);
			hideDiv('saveagain');
		}
		else if(response.substr(0,1) == '0')
		{
			//Edit the status image
			statusImg.setAttribute('src', '../graphics/tick.gif');
			
			//Create the text to go with it
			var successText = document.createTextNode('List was successfully saved!');
			statusPElement.appendChild(successText);
			hideDiv('saveagain');
			//showDiv('sendfriend');
			
		} 
		else if(response.substr(0,1) == '2') 
		{
			if(!isshare) {
				//Edit the status image
				statusImg.setAttribute('src', '../graphics/cross.gif');
				
				//Create the text to go with it
				var unsuccessText = document.createTextNode(response);
				statusPElement.appendChild(unsuccessText);
				showDiv('saveagain');
			} else {
				hideDiv('shareloading');
				var stat = document.getElementById('sharestatus');
				stat.appendChild(document.createTextNode('There was a problem saving your list to be shareed. Please try again'));
				showDiv('sharestatus'); 
			}
		}
		else
		{
			if(!isshare) {
				//Edit the status image
				statusImg.setAttribute('src', '../graphics/cross.gif');
				
				//Create the text to go with it
				var unsuccessText = document.createTextNode(response);
				statusPElement.appendChild(unsuccessText);
			} else {
				hideDiv('shareloading');
				var stat = document.getElementById('sharestatus');
				stat.appendChild(document.createTextNode('There was a problem saving your list to be shareed. Please try again'));
				showDiv('sharestatus'); 
			}
		}
		
		//Add them to the document
		statusImg.refresh;
		statusDiv.appendChild(statusPElement);
	}
}

function sendlist(obj) {
	if(obj.value == "" || obj.value == 'undefined') {
		alert("Please enter an adress to send the list.");
		return false;
	}
	var list = getItemString();
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}
	if (xmlHttp.readyState != 0) 
	{
        xmlHttp.abort();
        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
    }
	var url="../scripts/iphone_send_list.php?list="+encodeURIComponent(list);
	if(obj.id == 'sendsavedcell') {
		var sel = document.getElementById('phone_number');
		var num = sel.options[sel.selectedIndex].value;
		url+= "&phone="+encodeURIComponent(num);
	} else if(obj.id == 'sendsavedmail') {
	 	var sel = document.getElementById('selectEmail');
		var mail = sel.options[sel.selectedIndex].value;
		url+= "&mail="+encodeURIComponent(mail);
	} else if(obj.id == 'mail') {
		var mail = document.getElementById('mailval').value;
		regex = /^.+?@.+?\..+$/;
		if(mail != "" && mail != undefined && mail.match(regex))
			url += "&mail="+encodeURIComponent(mail);
		else
			alert('Please enter a valid email address');
	} else {
		var num = document.getElementById('phoneval').value;
		if(num != "" && num != 'undefined')
			url += "&phone="+encodeURIComponent(num);
		else
			alert('Please enter a valid number');
	
	}
	showdivlayer('sendliststatus');
	var loading = document.getElementById('sendingimg');
	loading.setAttribute('style', 'display:block;');
	showDiv('sendliststatus');
	var listid = document.getElementById('listid').value;
	var lname = document.getElementById('listName');
	if(lname != null)
		lname = lname.value;
	else
		lname = '';
	url += "&lid="+encodeURIComponent(listid);
	url += "&name="+encodeURIComponent(lname);
	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange=function() {
		if (xmlHttp.readyState==4 || xmlHttp.readyState == "completed")
		{ 
			var response = xmlHttp.responseText;
			if(response != '-1') {
				var loading = document.getElementById('sendingimg');
				loading.setAttribute('src','../graphics/tick.gif');
				clearInnerHTML(document.getElementById('sendingstatus'));
				var stat = document.getElementById('sendingstatus');
				stat.appendChild(document.createTextNode('Your list was successfully sent'));
			} else {
				var loading = document.getElementById('sendingimg');
				loading.setAttribute('src','../graphics/cross.gif');
				clearInnerHTML(document.getElementById('sendingstatus'));
				var stat = document.getElementById('sendingstatus');
				stat.appendChild(document.createTextNode('Sorry there was an error sending your list. Please try again.'));
			} 
		}	
	}
	xmlHttp.send(null);
}

function showdivlayer(divID) {
	if (document.getElementById){
		var divobj=document.getElementById(divID);
		divobj.style.zIndex = 4000;				
		centerDiv(divID);
	}
}
function centerDiv(divID){
		var divobj = document.getElementById(divID);	
		var xpos = (document.body.clientWidth/2);
		var ypos = ((document.documentElement.clientHeight/2 + document.documentElement.scrollTop)) - (divobj.offsetHeight/2);
		divobj.style.left=(xpos-150)+"px";
		divobj.style.top=(ypos-50)+"px";
}
function showMakeOptions(option)
{
	switch(option) {
		case 'single':
			highlightMakeOption('single');
			hideDiv('addItemTextArea'); 
			//Effect.Appear('addItemSingle', { duration: 0.8 });
			 
			showDiv('addItemSingle'); 
		break;
		case 'multiple':
			highlightMakeOption('multiple');
			hideDiv('addItemSingle'); 
		//	Effect.Appear('addItemTextArea', { duration: 0.8 }); 
			showDiv('addItemTextArea'); 
		break;
	}
}
function highlightMakeOption(id) {
	div = document.getElementById('addItemOptionRow');
	tags = div.getElementsByTagName('a');
	for(var i=0; i<tags.length; i++) {
		var tagid = tags[i].id;
		setClassAttribute(document.getElementById(tagid), 'normaltext');
	}
	setClassAttribute(document.getElementById(id),'boldtext');
}
function submitMultipleEntries()
{
	var mea = document.getElementById('multipleEntryArea'); 
	parseMultipleEntries(mea.value); 
	mea.value='';
}

function parseMultipleEntries(input)
{
	if(input == "")
	{
		return;
	}
	
	var tokens = new Array();
	tokens = input.split('\n');
	
	for(var i = 0; i < tokens.length; i++)
	{
		//TODO: Clean input
		if(tokens[i] != "")
			addRowToTableHelper(tokens[i], -1, null, null, false);
	}
}
function checkListForCoupons() {
	var tbl = document.getElementById('itemTable');
	var lis = tbl.getElementsByTagName('li');
	var liclass = '';
	var js = '';
	for(var i = 0;i<lis.length; i++) {
			liclass = lis[i].className;
			if(liclass == 'item')
				js += '{"item":'+'"'+lis[i].firstChild.nodeValue+'"}--_--';
	}
	if(js != '') {
		jsStr = js.substr(0, js.length-5);
		console.log('items', jsStr);
		//Get the AJAX stuff ready
		xmlHttp=GetXmlHttpObject();
		if (xmlHttp==null)
		{
			alert ("Browser does not support HTTP Request");
			return;
		}
		if (xmlHttp.readyState != 0) 
		{
	        xmlHttp.abort();
	        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
	    }
		var url="../scripts/check_for_coupons.php";
		xmlHttp.open("POST",url,true);
		xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xmlHttp.onreadystatechange=function() {
			if (xmlHttp.readyState==4 || xmlHttp.readyState == "completed") {
				hideDiv('cpdisplayload');
				coupons = "("+xmlHttp.responseText+")";
				console.log(coupons);
				var cpObj = eval(coupons) ;
				cp = cpObj.coupons;
				clearInnerHTML(document.getElementById('cpdisplay'));
				cpdisp = document.getElementById('cpdisplay');
				cpdisp.style.display = 'inline';
				cl = document.createElement('p');
				cl.className = 'cpclose';
				cl.appendChild(document.createTextNode('Close'));
				cl.onclick = function() {
					hideDiv('cpdisplay');
				}
				cpdisp.appendChild(cl);
						
				if(cp.length > 0) {
					head = document.createElement('h3');
					head.appendChild(document.createTextNode('We found coupons close to you.'));
					cpdisp.appendChild(head);
					for(var i = 0; i< cp.length; i++) {
						crow = document.createElement('div');
						crow.className = 'crow';
						var title = cp[i].title;
						var mkey = cp[i].key;
						var p = cp[i].price;
						crow.onclick = function(){addCoupon(this);};
						
						chead = document.createElement('p');
						chead.className = 'chead';
						chead.appendChild(document.createTextNode(cp[i].title));
						crow.appendChild(chead);
						cpdisp.appendChild(crow);
						
						cdesc = document.createElement('p');
						cdesc.className = 'cdesc';
						cdesc.appendChild(document.createTextNode(cp[i].description));
						crow.appendChild(cdesc);
						cpdisp.appendChild(crow);
						
						tbl = document.createElement('table');
						tbl.className = "ctbl";
						tbl.insertRow(0);
						tbl.rows[0].insertCell(0);
						tbl.rows[0].insertCell(1);
						tbl.rows[0].cells[0].setAttribute('align', 'left');
						tbl.rows[0].cells[0].setAttribute('align', 'top');
						tbl.rows[0].cells[1].setAttribute('align', 'right');
						tbl.rows[0].cells[1].setAttribute('valign', 'bottom');
						biz = document.createElement('p');
						setClassAttribute(biz, 'bizname');
						biz.appendChild(document.createTextNode(cp[i].store_name));
						tbl.rows[0].cells[0].appendChild(biz);
					
						bizadr = document.createElement('p');
						setClassAttribute(bizadr, 'bizadr');
						bizadr.appendChild(document.createTextNode(cp[i].address));
						sc = document.createElement('span');
						sc.style.display = 'block';
						cityst = cp[i].city+", "+cp[i].state;
						sc.appendChild(document.createTextNode(cityst));
						bizadr.appendChild(sc);
						tbl.rows[0].cells[0].appendChild(bizadr);
					
						logohnt = document.createElement('img');
						setClassAttribute(logohnt, 'logocp');
						if(cp[i].logo != "")
							logohnt.setAttribute('src', cp[i].logo);
						else
							logohnt.setAttribute('src', 'http://www.thingamalist.com/Graphics/tamlicon.png');
						logohnt.setAttribute('border', '0');
						tbl.rows[0].cells[1].appendChild(logohnt);
						crow.appendChild(tbl);
						
						var inpc = document.createElement('input');
						inpc.setAttribute('type','hidden');
						inpc.setAttribute('id','coupon_id');
						inpc.setAttribute('value',cp[i].coupon_id);
						crow.appendChild(inpc);
						
						var inpt = document.createElement('input');
						inpt.setAttribute('type','hidden');
						inpt.setAttribute('id','title');
						inpt.setAttribute('value',cp[i].title);
						crow.appendChild(inpt);
						
						var inpk = document.createElement('input');
						inpk.setAttribute('type','hidden');
						inpk.setAttribute('id','key');
						inpk.setAttribute('value',cp[i].key);
						crow.appendChild(inpk);
						
						var inpp = document.createElement('input');
						inpp.setAttribute('type','hidden');
						inpp.setAttribute('id','price');
						inpp.setAttribute('value',cp[i].price);
						crow.appendChild(inpp);
					}
				} else {
					head = document.createElement('h4');
					head.appendChild(document.createTextNode('Sorry we were unable to find coupons that related to your list.'));
					cpdisp.appendChild(head);
				}
			}
			 
			
		}
		send = "json="+jsStr+"&zip="+document.getElementById('userzip').value;
		xmlHttp.send(send);
		showDiv('cpdisplayload');
	} else {
		cpdisp = document.getElementById('cpdisplay');
		cpdisp.style.display = 'inline';
		cl = document.createElement('p');
		cl.className = 'cpclose';
		cl.appendChild(document.createTextNode('Close'));
		cl.onclick = function() {
			hideDiv('cpdisplay');
		}
		cpdisp.appendChild(cl);
		head = document.createElement('h4');
		head.appendChild(document.createTextNode('Please make your list first.'));
		cpdisp.appendChild(head);
	}
}

function addCoupon(obj) {
	tags = obj.getElementsByTagName('input');
	id = tags[0].value;
	title = tags[1].value;
	mkey = tags[2].value;
	p = tags[3].value;
	console.log(title, ' ', mkey, ' ',p);
	//item, discount_id, matchedKeyword, matchedKeywordPrice, disableDelete
	addRowToTableHelper(title,id, mkey, p, false);
	document.getElementById('cklist').innerHTML = '<span style="text-align:center;"><span class="blk">View check list</span> <span class="blk">and</span> <span class="blk">redeem coupons.</span></span>';
	obj.className = "crow disabled";
	document.listCreationForm.items.blur();
}


