$(function() {
		   
	var ajaxDone = true;
	
	$("#tabs").tabs();

	$("#dateOrdered").datepicker({changeMonth: true, changeYear: true , dateFormat: "yy-mm-dd", numberOfMonths: 3}).change(function() {validateDate(this)});

	$("#dateDelivered").datepicker({changeMonth: true, changeYear: true , dateFormat: "yy-mm-dd", numberOfMonths: 3}).change(function() {validateDate(this)});
	
	$("#customerObjId").change(function() {
										
		changeCustomer();
	});

	// Order Item Table Section
	$("#tblOrderItems tbody .tabRowOdd").each(function(cnt) {
											  
		$("#dateDelivered" + (cnt + 1)).datepicker({changeMonth: true, changeYear: true , dateFormat: "yy-mm-dd", numberOfMonths: 3});
		$("#productEntry" + (cnt + 1)).click(function() {displayRowOrderItem(cnt + 1)});
	});
	
	// Payment Item Table Section
	$("#tblPayments tbody tr").each(function(cnt) {
											  
		if (cnt > 0) {
			
			$("#datePaid" + (cnt)).datepicker({changeMonth: true, changeYear: true , dateFormat: "yy-mm-dd", numberOfMonths: 3});
		}
	});
	
	$("#dialogTblOrderItem").dialog({
									
		bgiframe: true,
		height: 430,
		width: 680,
		modal: true,
		autoOpen: false
	});
	
	$("#dialogTblOrderItem #productEntryD").change(function() {

		retrieveProduct($(this).val());
	});
	
	$("#dialogTblOrderItem #qtyOrderedD").change(function() {
									  
		changeQty();
	});

	$("#dialogTblOrderItem #deliveryD").change(function() {
												 
		getDeliveryOption($(this).val());
	});

	$("#addProduct").click(function() {

		$("#dialogTblOrderItem").dialog("option", "buttons", {
			'Add Order Item': function() {
				
				if (validateQuantity($("#dialogTblOrderItem #qtyOrderedD").val())) {
					
					addRowToOrderItemsTable();
					$(this).dialog('close');
					orderCostCalc();
				}
			},
			Cancel: function() {
				
				$(this).dialog('close');
			}
		});
		$("#dialogTblOrderItem #productEntryD option:nth(0)").attr("selected","selected"); 
		$("#dialogTblOrderItem #productObIdD").attr("value", "");
		$("#dialogTblOrderItem #unitPriceD").attr("value", "");
		$("#dialogTblOrderItem #unitTaxD").attr("value", "");
		$("#dialogTblOrderItem #givingD").attr("value", "");
		$("#dialogTblOrderItem #qtyOrderedD").attr("value", "");
		$("#dialogTblOrderItem #deliveryD ")[0].checked = true;
		getDeliveryOption($("input[name='deliveryD']").val());
		$("#dialogTblOrderItem #deliveryCostD").attr("value", 0);
		$("#dialogTblOrderItem #deliveryDescD").attr("value", "");
		$("#dialogTblOrderItem #errorDivOrderItem").hide();
		$("#dialogTblOrderItem #totGivingD").attr("value", "");
		$("#dialogTblOrderItem #calcTaxD").attr("value", "");
		$("#dialogTblOrderItem #costD").attr("value", "");
		$("#dialogTblOrderItem").dialog('open');
	});
	
	$().ajaxStop(function() {
						  
		ajaxDone = true;
	});
	
	changeCustomer();
	orderCostCalc();
	paymentCalc();
	
	$("#customerObjId").focus();
});

var errors = '';

function retrieveProduct(productObjId) {

	$.get("getProductInfo.php", { inputText: productObjId }, function(data) {

console.log(data);
		$("#dialogTblOrderItem #errorDivOrderItem").hide();
		$("#dialogTblOrderItem #productObjIdD").attr("value", productObjId);
		$("#dialogTblOrderItem #unitPriceD").attr("value", parseFloat($(data).find("unitPrice").text()).toFixed(2));
		$("#dialogTblOrderItem #unitTaxD").attr("value", parseFloat($(data).find("unitTax").text()).toFixed(2));
		$("#dialogTblOrderItem #unitTaxIndD").attr("value", $(data).find("unitTaxInd").text());
		
		var orgAmtInd = $(data).find("orgAmtInd").text();
		var orgAmt = $(data).find("orgAmt").text();
		if (!isEmpty(orgAmt)) {
			
			if (orgAmtInd == 1) {
				
				$("#dialogTblOrderItem #givingD").val(parseFloat(orgAmt).toFixed(2));
			}
			else {
				
				$("#dialogTblOrderItem #givingD").attr("value", parseFloat(orgAmt).toFixed(2));
			}
			$("#dialogTblOrderItem #givingIndD").attr("value", orgAmtInd);
		}
		else {
			
			$("#dialogTblOrderItem #givingD").attr("value", "");
			$("#dialogTblOrderItem #givingIndD").attr("value", "");
		}
		
		$("#dialogTblOrderItem #organizationD").attr("value", $(data).find("organization").text());
		$("#dialogTblOrderItem #qtyOrderedD").focus();
	});
}

function changeCustomer() {

	$.get("findCustomer.php", { inputText: $("#customerObjId").val() }, function(data) {

		$("#customerAddress").attr("innerHTML", $(data).find("address").text());
		$("#customerPhone").attr("innerHTML", $(data).find("phone").text());
		$("#customerCell").attr("innerHTML", $(data).find("cell").text());
		$("#customerEmail").attr("innerHTML", $(data).find("email").text());
	});

	getCustomerBalance();
}

function getCustomerBalance() {

	$.get("findCustomerBalance.php", { inputText: $("#customerObjId").val() }, function(data) {
		
		if (parseFloat(data) > 0) {
			
			$("#customerBalanceSpan").show();
		}
		else {
			
			$("#customerBalanceSpan").hide();
		}
		$("#customerBalance").val(data);
	});
}

function getDeliveryOption(deliveryObjId) {

	$.get("getDeliveryOption.php", { inputText: deliveryObjId }, function(data) {
		
		$("#dialogTblOrderItem #deliveryDescD").attr("value", $(data).find("description").text());
		$("#dialogTblOrderItem #deliveryCostD").attr("value", $(data).find("amount").text());
		changeQty();
	});
}

function displayRowOrderItem(rowId) {
	
	$("#dialogTblOrderItem").dialog("option", "buttons", {
		'Update Order Item': function() {

			if (validateQuantity($("#qtyOrderedD").val())) {

				updateRowOrderItemTable(rowId);
				$(this).dialog('close');
				orderCostCalc();
			}
		},
		Cancel: function() {
			
			$(this).dialog('close');
		}
	});
	$("#dialogTblOrderItem #productEntryD").val($("#productObjId" + rowId).val()); 
	$("#dialogTblOrderItem #productObjIdD").attr("value", $("#productObjId" + rowId).val());
	retrieveProduct($("#productObjId" + rowId).val());
	$("#dialogTblOrderItem #qtyOrderedD").attr("value", $("#qtyOrdered" + rowId).val());
//	$("#dialogTblOrderItem #deliveryObjIdD").attr("value", $("#deliveryObjId" + rowId).val());
	$("#dialogTblOrderItem #deliveryD").val($("#deliveryObjId" + rowId).val());
	$("#dialogTblOrderItem #deliveryCostD").attr("value", $("#deliveryCost" + rowId).val());
	getDeliveryOption($("#deliveryObjId" + rowId).val());
/*	for (var i = 0; i < 3; i++) {
	
		if (ajaxDone) {
			
			break;
		}
		else {
			
		}
	}*/
//	setTimeout("changeQty()", 1250);
	$("#dialogTblOrderItem").dialog('open');
}

function validateQuantity(val) {
	
	if (!parseInt(val)) {

		$("#dialogTblOrderItem #errorDivOrderItem #errorMsgOrderItem").text("You must enter a numeric value.");
		$("#dialogTblOrderItem #errorDivOrderItem").show("slow");
		return false;
	}
	return true;
}

function orderCostCalc() {

	var orderTotal = 0;
	
	$("#tblOrderItems tbody .tabRowOdd").each(function(cnt) {

		var val = ($("#cost" + (cnt + 1)).val());
		orderTotal += parseFloat(isNaN(val) ? 0 : val);
	});

	$("#orderTotal").val(parseFloat(orderTotal).toFixed(2));
}

function paymentCalc() {

	var paymentTotal = 0;
	
	$("#tblPayments tbody .tabRowOdd").each(function(cnt) {
													 
		var val = ($("#amountPaid" + (cnt + 1)).val());
		paymentTotal += parseFloat(isNaN(val) ? 0 : val);
	});
	
	$("#paymentTotal").val(parseFloat(paymentTotal).toFixed(2));
}

function addRowToOrderItemsTable() {

	var n = $("#orderItemCount").attr("value");
	console.log("klc:" + n);
	var nn = parseInt(n) + 1;
	var r = $("#tblOrderItems #blankRowProduct1").clone().removeAttr("id");
	
	$("#productEntry", r)
			.text($.trim($("#productEntryD option:selected").text()))
			.attr("id", "productEntry" + nn)
			.click(function() {displayRowOrderItem(nn)});

	$("#organization", r)
			.attr("value", $("#organizationD").val())
			.attr("name", "organization" + nn)
			.attr("id", "organization" + nn);

	$("#productObjId", r)
			.text($.trim($("#productEntryD option:selected").val()))
			.attr("id", "productObjId" + nn)
			.attr("name", "productObjId" + nn);

	$("#unitPrice", r)
			.attr("value", $("#unitPriceD").val())
			.attr("name", "unitPrice" + nn)
			.attr("id", "unitPrice" + nn);

	$("#taxIncluded", r)
			.attr("name", "taxIncluded" + nn)
			.attr("id", "taxIncluded" + nn);

	$("#unitTax", r)
			.attr("value", $("#unitTaxD").val())
			.attr("name", "unitTax" + nn)
			.attr("id", "unitTax" + nn);

	$("#qtyOrdered", r)
			.attr("value", $("#qtyOrderedD").val())
			.attr("name", "qtyOrdered" + nn)
			.attr("id", "qtyOrdered" + nn);

	$("#cost", r)
			.attr("value", $("#costD").val())
			.attr("name", "cost" + nn)
			.attr("id", "cost" + nn);

	$("#giving", r)
			.attr("value", $("#totGivingD").val())
			.attr("name", "giving" + nn)
			.attr("id", "giving" + nn);

	$("#calcTax", r)
			.attr("value", $("#calcTaxD").val())
			.attr("name", "calcTax" + nn)
			.attr("id", "calcTax" + nn);

	$("#removeItem", r)
			.attr("checked", false)
			.attr("name", "removeItem" + nn)
			.attr("id", "removeItem" + nn);

	$("#tblOrderItems").append(r);

	r = $("#tblOrderItems #blankRowProduct2").clone().removeAttr("id");
	
	$("#comment", r)
			.attr("name", "comment" + nn)
			.attr("id", "comment" + nn);

	$("#deliveryDesc", r)
			.attr("value", $("#deliveryDescD").val())
			.attr("name", "deliveryDesc" + nn)
			.attr("id", "deliveryDesc" + nn);

	$("#deliveryCost", r)
			.attr("value", $("#deliveryCostD").val())
			.attr("name", "deliveryCost" + nn)
			.attr("id", "deliveryCost" + nn);

	$("#deliveryObjId", r)
			.attr("value", $("#deliveryD").val())
			.attr("name", "deliveryObjId" + nn)
			.attr("id", "deliveryObjId" + nn);

	$("#dateDelivered", r)
			.attr("name", "dateDelivered" + nn)
			.attr("id", "dateDelivered" + nn);

	$("#tblOrderItems").append(r);

	$("#orderItemCount").attr("value", nn);
}

function updateRowOrderItemTable(rowId) {
	
	$("#productEntry" + rowId)
			.text($.trim($("#dialogTblOrderItem #productEntryD option:selected").text()));
			
	$("#productObjId" + rowId)
			.text($.trim($("#dialogTblOrderItem #productObjIdD").val()));

	$("#unitPrice" + rowId)
			.attr("value", $("#dialogTblOrderItem #unitPriceD").val());

	$("#unitTax" + rowId)
			.attr("value", $("#dialogTblOrderItem #unitTaxD").val());

	$("#qtyOrdered" + rowId)
			.attr("value", $("#dialogTblOrderItem #qtyOrderedD").val());

	$("#delivery" + rowId)
			.attr("value", $("#dialogTblOrderItem #deliveryD").val());
			
	$("#deliveryCost" + rowId)
			.attr("value", $("#dialogTblOrderItem #deliveryCostD").val());
			
	$("#deliveryDesc" + rowId)
			.attr("value", $("#dialogTblOrderItem #deliveryDescD").val());
			
	$("#deliveryObjId" + rowId)
			.attr("value", $("#dialogTblOrderItem #deliveryD").val());
			
	$("#giving" + rowId)
			.attr("value", $("#dialogTblOrderItem #totGivingD").val());
			
	$("#calcTax" + rowId)
			.attr("value", $("#dialogTblOrderItem #calcTaxD").val());
			
	$("#cost" + rowId)
			.attr("value", $("#dialogTblOrderItem #costD").val());

	$("#dialogTblOrderItem #errorDivOrderItem").hide();
}

function addRowToPaymentTable() {

	var tbl = document.getElementById('tblPayments');
	var n = $("#paymentCount").attr("value");
	var nn = parseInt(n) + 1;
	var r = $("#tblPayments #blankRowPayment1").clone().removeAttr("id");
	
	$("#paymentObjId", r)
			.attr("name", "paymentObjId" + nn)
			.attr("id", "paymentObjId" + nn);

	$("#datePaid", r)
			.attr("id", "datePaid" + nn)
			.attr("name", "datePaid" + nn);

	$("#amountPaid", r)
			.attr("name", "amountPaid" + nn)
			.attr("id", "amountPaid" + nn);

	$("#paymentMethod", r)
			.attr("name", "paymentMethod" + nn)
			.attr("id", "paymentMethod" + nn);

	$("#checkNumber", r)
			.attr("name", "checkNumber" + nn)
			.attr("id", "checkNumber" + nn);

	$("#cardNumber", r)
			.attr("name", "cardNumber" + nn)
			.attr("id", "cardNumber" + nn);

	$("#cardNumber", r)
			.attr("name", "cardNumber" + nn)
			.attr("id", "cardNumber" + nn);

	$("#securityCode", r)
			.attr("name", "securityCode" + nn)
			.attr("id", "securityCode" + nn);

	$("#expireDate", r)
			.attr("name", "expireDate" + nn)
			.attr("id", "expireDate" + nn);

	$("#tblPayments").append(r);

	r = $("#tblPayments #blankRowPayment2").clone().removeAttr("id");
	
	$("#description", r)
			.attr("name", "description" + nn)
			.attr("id", "description" + nn);

	$("#tblPayments").append(r);

	$("#paymentCount").attr("value", nn);
}

function changeQty() {

	var qtyOrdered = $("#dialogTblOrderItem #qtyOrderedD");
	var totPrice = 0.00;
	
	if (isNaN(qtyOrdered.val())
			|| qtyOrdered.val() == null
			|| qtyOrdered.val() == "") {
		
		qtyOrdered.val(0);
	}
	else {
	
		var unitPrice = $("#dialogTblOrderItem #unitPriceD").val();
		if (!isNaN(unitPrice)) {
	
			totPrice += parseFloat(qtyOrdered.val()) * parseFloat(unitPrice);
		}
	}

	var givingInd = $("#dialogTblOrderItem #givingIndD").val();
	var giving = $("#dialogTblOrderItem #givingD").val();
	if (givingInd == 1) {

		$("#dialogTblOrderItem #totGivingD").val(parseFloat(totPrice * (giving / 100)).toFixed(2));
	}
	else {
		
		$("#dialogTblOrderItem #totGivingD").val(parseFloat(totPrice - (giving * qtyOrdered.val())).toFixed(2));
	}
	
	var unitTaxInd = $("#dialogTblOrderItem #unitTaxIndD").val();
	var unitTax = $("#dialogTblOrderItem #unitTaxD").val();
	if (unitTaxInd == 1) {
		
		$("#dialogTblOrderItem #calcTaxD").val((totPrice - parseFloat(totPrice * 100 / (100 + parseFloat(unitTax)))).toFixed(2));
	}
	else {
	
		$("#dialogTblOrderItem #calcTaxD").val(parseFloat(totPrice * unitTax / 100).toFixed(2));
	}
	
	if (!isNaN($("#dialogTblOrderItem #deliveryCostD").val())
			&& $("#dialogTblOrderItem #deliveryCostD").val().length > 0) {
		
		totPrice += parseFloat($("#dialogTblOrderItem #deliveryCostD").val());
	}
	
	$("#dialogTblOrderItem #costD").val(parseFloat(totPrice).toFixed(2));
}

function changeAmountPaid(rowId) {

	el = 'amountPaid' + rowId;
	amountPaid = document.getElementById(el);

	el = 'amountPaidVal' + rowId;
	amountPaidVal = document.getElementById(el);

	if (isNaN(amountPaid.value)) {
		
		if (isNaN(amountPaid.value.substring(2))) {
			
			amountPaidVal.value = 0;
		}
		else {
			
			amountPaidVal.value = 1 * amountPaid.value.substring(2);
		}
	}
	else {
		
		amountPaidVal.value = 1 * amountPaid.value;
	}
	
	paymentCalc();
}

function changeCost(rowId) {

	var cost;
	var costVal;

	el = 'cost' + rowId;
	cost = document.getElementById(el);

	el = 'costVal' + rowId;
	costVal = document.getElementById(el);

	if (!isNaN(cost.value)) {
		
		costVal.value = cost.value;
		cost.value = (Math.round(cost.value * 100) / 100).toFixed(2);
	}
}

function changeGiving(rowId) {

	var giving;
	var givingVal;

	el = 'giving' + rowId;
	giving = document.getElementById(el);

	el = 'givingVal' + rowId;
	givingVal = document.getElementById(el);

	if (!isNaN(giving.value)) {
		
		givingVal.value = giving.value;
		giving.value = (Math.round(giving.value * 100) / 100).toFixed(2);
	}
}

function changeTax(rowId) {

	var calcTax;
	var taxVal;

	el = 'calcTax' + rowId;
	calcTax = document.getElementById(el);

	el = 'taxVal' + rowId;
	taxVal = document.getElementById(el);

	if (!isNaN(calcTax.value)) {
		
		taxVal.value = calcTax.value;
		calcTax.value = (Math.round(calcTax.value * 100) / 100).toFixed(2);
	}
}

function selectPaymentMethod(rowId) {

	var paymentMethod;
	var el;

	el = 'paymentMethod' + rowId;
	paymentMethod = document.getElementById(el).selectedIndex;

	var checkNumber = 'checkNumber' + rowId;
	var cardNumber = 'cardNumber' + rowId;
	var securityCode = 'securityCode' + rowId;
	var expireDate = 'expireDate' + rowId;

	// Cash or Account
	if (paymentMethod == 0 || paymentMethod == 4) {
		
		document.getElementById(checkNumber).disabled = true;
		document.getElementById(checkNumber).value = '';
		document.getElementById(cardNumber).disabled = true;
		document.getElementById(cardNumber).value = '';
		document.getElementById(securityCode).disabled = true;
		document.getElementById(securityCode).value = '';
		document.getElementById(expireDate).disabled = true;
		document.getElementById(expireDate).value = '';

		if (paymentMethod == 4) {

			getCustomerBalance();
		}

	}
	// Check or Refund
	else if (paymentMethod == 1 || paymentMethod == 3) {
		
		document.getElementById(checkNumber).disabled = false;
		document.getElementById(cardNumber).disabled = true;
		document.getElementById(cardNumber).value = '';
		document.getElementById(securityCode).disabled = true;
		document.getElementById(securityCode).value = '';
		document.getElementById(expireDate).disabled = true;
		document.getElementById(expireDate).value = '';

		document.getElementById(checkNumber).focus();
	}
	// Credit Card
	else if (paymentMethod == 2){
		
		document.getElementById(checkNumber).disabled = true;
		document.getElementById(checkNumber).value = '';
		document.getElementById(cardNumber).disabled = false;
		document.getElementById(securityCode).disabled = false;
		document.getElementById(expireDate).disabled = false;

		document.getElementById(cardNumber).focus();
	}
}

function validateForm(submitForm) {

	var i;
	
	errors = '';

	var paymentCount = $("#paymentCount");
	var accountPayments = (+0);
	
	for (i = 1; i <= paymentCount.val(); i++) {
		
		if (!validateDate($("#datePaid" + i).val())) {

			errors = (isEmpty(errors) ? "" : errors + "<br>") + "Please enter a valid paymet date. Row " + i + ".";
			$("#datePaid" + i).focus();
		}
		if ($("#amountPaidVal" + i).val() == 0) {

			errors = (isEmpty(errors) ? "" : errors + "<br>") + "Please enter a valid payment amount greater than zero. Row " + i + ".";
			$("#amountPaidVal" + i).focus();
		}

		var aRow = document.getElementById('paymentMethod' + i);
		if (document.getElementById('paymentMethod' + i) && aRow.selectedIndex == 4) {

			accountPayments = (+accountPayments) + (+document.getElementById('amountPaidVal' + i).value);
		}
	}

	var customerBalance = (+0);

	if (!isEmpty(document.getElementById('customerBalance'))) {

		customerBalance = document.getElementById('customerBalance').value;
	}

	if ((+accountPayments) > (+customerBalance)) {

		errors = (isEmpty(errors) ? '' : '<br>') + 'Account payments exceed available balance.';
	}

	if (!isEmpty(errors)) {
		
		document.getElementById("errorView").style.display = "block";
		document.getElementById("errorInfo").innerHTML = errors;
		document.getElementById("errorInfo").style.color = "red";
		return;
	}
	
	if (submitForm == 'true') {

		document.orderForm.submit();
	}
}
