function elemOn(elem_id){
	if(document.getElementById(elem_id))
		document.getElementById(elem_id).style.display = "block";
}
function elemOff(elem_id){
	if(document.getElementById(elem_id))
		document.getElementById(elem_id).style.display = "none";
}
function hideAll(divToUse){
	for( var i = 1; i <= 8; i++ )
		elemOff( 'div'+i );
	//set all existing fields to blank values
	if(divToUse != "none"){
		var x = document.getElementById(divToUse).getElementsByTagName("input");
		for (var i=0;i<x.length;i++)
		{ 
			//only check text fields
			if(x[i].type == "text"){
				x[i].value = "";
			}
		}
	}
}
function showAll(){
	for( var i = 1; i <= 6; i++ )
		elemOn( 'div'+i );
}
function showOne(elem_id){
	hideAll("none");
	elemOn( elem_id );
}

//this function creates the object and populates the object attributes for each item in CMT 
function objItem(id,name,size,price){
	return objItem[id] = {id: id, name: name, size: size, price: price}
}

//this function gets items that have been selected and adds them as rows to the grocery list
function populateGroceryList(divToUse) {
	var currentItems = new Array();	
	var index = 0;
	
	//grab all 'div' items under TBODY tag in shopping list
	var y = document.getElementById('tblMasterListBody').getElementsByTagName("input");
	//populate array with items already in list
	for (var i=0;i<y.length;i++)
	{ 
		if(y[i].type == "text" && y[i].value != ""){
			currentItems[index] = y[i].id;
			index++;
		}
	}
	
	//get all items user selected
	var testStr;
	var itemInList;
	var x = document.getElementById(divToUse).getElementsByTagName("input");
	for (var i=0;i<x.length;i++)
	{ 
		if(x[i].type == "text" && x[i].value != "" && x[i].value != 0){
			//test to see if user has already selected item
			itemInList = false;
			for (var c=0;c<currentItems.length;c++){
				testStr = "input_" + x[i].id;
				if(testStr == currentItems[c]){
					//alert("MATCH = " + testStr );
					itemInList = true;
				}
			}
			//if item has not been selected already, add a new row
			if(!itemInList){
				addRow(x[i].value,objItem[x[i].id].name,objItem[x[i].id].size,objItem[x[i].id].price,objItem[x[i].id].id);	
			//otherwise, update existing row
			}else{
				var intQty = parseInt(document.getElementById('input_'+x[i].id).value);
				document.getElementById('input_'+x[i].id).value = intQty + parseInt(x[i].value);
				updateItemTotal(x[i].id,objItem[x[i].id].price);
			}		
		}
	}
	updateTotals();
}

var rowCount = 0;

//this function creates rows in the grocery list with what has been selected
function addRow(qty,name,size,price,id){
	var tbody = document.getElementById('tblMasterList').getElementsByTagName("TBODY")[0];
	var row = document.createElement("TR");
	if(rowCount % 2 == 0){
		row.className = "tblMasterListRowDark";
	}
	row.setAttribute('id','row_'+id);
		
	var td1 = document.createElement("TD");
	var inputName = 'input_' + id;
	td1.setAttribute('align','center');
	td1.innerHTML = "<input type=text name='" + inputName + "' id='" + inputName + "' size='2' maxlength='2' value='" + qty + "' onChange=updateItemTotal('" + id + "','" + price + "'); />";
		
	var td2 = document.createElement("TD");
	var itemText = name;
	if(size != ""){
		itemText += " - " + size;
	}
		
	td2.appendChild (document.createTextNode(itemText));
		
	var td3 = document.createElement("TD");
	var div3 = document.createElement("div");
	div3.className = "txtItemTotal";
	div3.setAttribute('id','price_' + id);
	var intQty = parseInt(qty);
	var fltPrice = parseFloat(price);
	if(intQty > 1){
		fltPrice = fltPrice * intQty;
	}
	div3.appendChild (document.createTextNode(formatCurrency(fltPrice)));
	td3.setAttribute('align','right');
	td3.appendChild (div3);
		
	var td4 = document.createElement("TD");
	var input4 = document.createElement("input");
	var checkName = 'check_' + id;
	input4.setAttribute('type','checkbox');
	input4.setAttribute('name',checkName);
	input4.setAttribute('id',checkName);
	td4.setAttribute('align','center');
	td4.appendChild(input4);
		
	row.appendChild(td1);
	row.appendChild(td2);
	row.appendChild(td3);
	row.appendChild(td4);
	tbody.appendChild(row);
	rowCount++;
}
	
//this function updates the lineitem when the qty is edited on the grocery list
function updateItemTotal(id,price){

	//this code resets the value to it's original if a bad character is entered
	if(!isNumeric(document.getElementById('input_'+id).value)){
		alert("Only Numerical Values are allowed!");
		document.getElementById('input_'+id).value = document.getElementById('input_'+id).defaultValue;
		return false;
	}

	var priceId = 'price_' + id;
		
	var intQty = parseInt(document.getElementById('input_'+id).value);
	var fltPrice = parseFloat(price);
	fltPrice = fltPrice * intQty;
		
	document.getElementById(priceId).innerHTML = formatCurrency(fltPrice);
		
	updateTotals();
}
	
//this function forces numbers into currency format (i.e. 2 decimal places and a '$')
function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
		
	if(isNaN(num))
		num = "0";
		
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
		
	if(cents<10)
		cents = "0" + cents;
			
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
		
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}
	
function removeRows() {
	var x = document.getElementById('tblMasterListBody').getElementsByTagName("input");
	var tbody = document.getElementById('tblMasterListBody');
		
	var idStr;
	var underscoreLoc;
	var idToRemove;
	var shadeId;
		
	var removeArray = new Array();
	var arrIndex = 0;
	
	//create array of id's to be removed - (those that have their box checked)
	for (var i=0;i<x.length;i++)
	{ 
		if((x[i].type == "checkbox" && x[i].checked) || (x[i].type == "text" && x[i].value == 0)){
			underscoreLoc = x[i].id.indexOf("_");
			idToRemove = "row" + x[i].id.substring(underscoreLoc);
			removeArray[arrIndex] = idToRemove;
			arrIndex++;
		}
	}
		
	//remove each row
	for (var i=0;i<removeArray.length;i++)
	{ 
		tbody.removeChild(document.getElementById(removeArray[i]));
	}
	
	//reset shading after rows have been removed
	rowCount = 0;
	for (var i=0;i<x.length;i++)
	{ 
		if(x[i].type == "text"){
			underscoreLoc = x[i].id.indexOf("_");
			shadeId = "row" + x[i].id.substring(underscoreLoc);
			if(rowCount % 2 == 0){
				document.getElementById(shadeId).className = "tblMasterListRowDark";
			}else{
				document.getElementById(shadeId).className = "";
			}
			rowCount++;
		}
	}
	
	updateTotals();
}

	
function updateTotals() {
	//grab all 'div' items under TBODY tag in shopping list
	var x = document.getElementById('tblMasterListBody').getElementsByTagName("div");
	var subTotal = 0;
	var totalStr;
	//starting at index 1 because the first div is not a price we want to sum
	for (var i=1;i<x.length;i++)
	{ 
		totalStr = x[i].innerHTML.substring(1);
		subTotal += parseFloat(totalStr);
	}
		
	//get sub total and display
	document.getElementById('subTotal').innerHTML = formatCurrency(subTotal);
		
	//get service charge (10% of sub total) and display
	var serviceCharge = subTotal * .1;
	document.getElementById('serviceCharge').innerHTML = formatCurrency(serviceCharge);
		
	//get flat fee value
	var flatFee = 3.50;
	document.getElementById('flatFee').innerHTML = formatCurrency(flatFee);
		
	//get final Total and display
	var finalTotal = parseFloat(subTotal) + parseFloat(serviceCharge) + parseFloat(flatFee);
	document.getElementById('combinedTotal').innerHTML = formatCurrency(finalTotal);
		
	//set hidden fields to pass this info to review page
	document.getElementById('hiddenTotal').value = formatCurrency(finalTotal);
	document.getElementById('hiddenSubTotal').value = formatCurrency(subTotal);
	document.getElementById('hiddenServiceCharge').value = formatCurrency(serviceCharge);
	document.getElementById('hiddenFlatFee').value = formatCurrency(flatFee);
}

//this function displays an error message if the user enters a non-numeric value
function validateListEntries(divToUse){

	//get all input fields within div
	var x = document.getElementById(divToUse).getElementsByTagName("input");
	var isValid = true;
	for (var i=0;i<x.length;i++)
	{ 
		//only check text fields
		if(x[i].type == "text"){
			if(!isNumeric(x[i].value)){
				isValid = false;
			}
		}
	}

	if(isValid){
		updateTotals();
		populateGroceryList(divToUse);
		hideAll(divToUse);
	}else{
		alert("Only Numerical Values are allowed!");
	}
		
	return false;
}
 
function validateForSubmission(){
	var isValid = true;
	//grab all 'div' items under TBODY tag in shopping list
	var x = document.getElementById('tblMasterListBody').getElementsByTagName("input");
	for (var i=0;i<x.length;i++)
	{ 
		if(x[i].type == "text" && x[i].value != ""){
			if(!isNumeric(x[i].value)){
				isValid = false;
			}
		}
	}
	if(isValid){
		removeRows();
		document.listForm.submit();
	}
}
 
function isNumeric(sText)
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}

function checkFormSubmit(direction) {
	var isValid = true;
	var alertStr = "";
	if(direction == "edit"){
		document.editForm.action = "/groceries.asp";
		return true;
	}else{
		if(submitForm.name.value == ""){
			alertStr += "Your Name is a required field. \n";
			isValid = false;
		}
		if(submitForm.arrivalDate.value == "" || submitForm.arrivalDate.value == "mm/dd/yyyy"){
			alertStr += "Arrival Date is a required field. \n";
			isValid = false;
		}
		if(submitForm.arrivalTime.value == ""){
			alertStr += "Arrival Time is a required field. \n";
			isValid = false;
		}
		if(submitForm.phone.value == ""){
			alertStr += "Phone Number is a required field. \n";
			isValid = false;
		}
		if(submitForm.email.value == ""){
			alertStr += "Email Address is a required field. \n";
			isValid = false;
		}
			
		if(isValid){
			document.editForm.action = "/groceries-thanks.asp";
			editForm.userName.value = submitForm.name.value;
			editForm.userArrivalDate.value = submitForm.arrivalDate.value;
			editForm.userArrivalTime.value = submitForm.arrivalTime.value;
			editForm.userResNumber.value = submitForm.resNumber.value;
			editForm.userPhone.value = submitForm.phone.value;
			editForm.userEmail.value = submitForm.email.value;
			editForm.userComment.value = submitForm.comments.value;
			return true;
		}else{
			alert(alertStr);
		}
			
	}
	return false;
}
