// adding items to the cart is a multi-step process using javascript, AJAX, and PHP.
// FIRST:	onChange of input fields:
// 			the item is added/removed from the input field `atc` via javascript function listItem('theUPC')
// input `atc` is used (not `p` and not individual item fields) for the actual push to the cart
// so that the same functions can be used on pages with mutiple items
// SECOND:	onSubmit or [ADD] button push:
//			`atc` value is sent via AJAX where it is parsed for item(s)
//			added to the current cookie (or qty updated)
// THIRD:	the results from AJAX are used to:
//			update the 'X in cart' for item(s) updated
//			update the cartSummary at the top of the page

// REMOVE AN ITEM:	user may:
// 			go to the cart and do it there
// click `trash icon` found in 'X in cart'



function listItem(theForm, theUPC){
	theQTY = document[theForm]['atcQ_' + theUPC].value;
	showQtyError = document.getElementById('errorQty_' + theUPC);
	if(theQTY == ""){
		theQTY = 0; // set QTY to zero to remove (or not add) the item
		// showQtyError.innerHTML = "QTY Required";
		// return false;
	}else{
		showQtyError.innerHTML = ""; // clear previous error warning when fixed
	}
	
	foundUPC = 0;
	brokenATC = document[theForm].atc.value.split("|");
	for(var i in brokenATC){
		thisItem = brokenATC[i] + "";
		thisItem = thisItem.split("~");
		if(thisItem[0] == theUPC){
			foundUPC += 1;	// mark as found
			thisItem[1] = theQTY; // change the qty for this UPC
		}
		thisJoined = thisItem.join("~");
		
		brokenATC[i] = thisJoined;
	}
	if(foundUPC == 0){
		// add this UPC~qty to array
		brokenATC.push(theUPC + "~" + theQTY);
	}
	joinedATC = brokenATC.join("|");	// put it all back together
	
	joinedATC = cleanList(joinedATC);
	
	document[theForm].atc.value = joinedATC;
	
	// not submitted here.  Submitted via submitProduct (by ENTER or button push)
}





// remove an item (UPC~QTY) from field
function unlistItem(theForm, theUPC){
	brokenATC = document[theForm].atc.value.split("|");
	newATC = new Array();
	for(var i in brokenATC){
		thisItem = brokenATC[i] + "";
		thisItem = thisItem.split("~");
		if(thisItem[0] != theUPC){
			newATC.push(thisItem[0] + "~" + thisItem[1]);
		}
	}
	
	joinedATC = newATC.join("|");	// put it all back together
	
	joinedATC = cleanList(joinedATC);
	
	document[theForm].atc.value = joinedATC;
}





// clean up the list
function cleanList(theList){
	re = "/4001[0-9]{8}\~0{1,}/";			// item removed by user
	re = eval(re);
	theList = theList.replace(re, "")
	
	re = "/\\|{2,}/";						// multiple consecutive | anywhere within string
	re = eval(re);
	theList = theList.replace(re, "|")
	
	re = "/^\\|/";							// errant | at beginning of string
	re = eval(re);
	theList = theList.replace(re, "")
	
	re = "/\\|$/";							// errant | at end of string
	re = eval(re);
	theList = theList.replace(re, "")
	
	return theList;
}