packages = {
	"platinum6" : [ 1250.00, 1250.00, TYPE_SUB, SUB_TYPE_PLATINUM ],
	"phomt"     : [    0.00,    0.00, TYPE_SUB, SUB_TYPE_PHOMT    ],
	"silver6"   : [  325.00,  325.00, TYPE_SUB, SUB_TYPE_SILVER   ],
	"anytime6"  : [  275.00,  275.00, TYPE_SUB, SUB_TYPE_ANYTIME  ],
	"anytime5"  : [  230.00,  230.00, TYPE_SUB, SUB_TYPE_ANYTIME  ],
//	"anytime4"  : [  210.00,  210.00, TYPE_SUB, SUB_TYPE_ANYTIME  ],
	"anytime4a" : [  185.00,  185.00, TYPE_SUB, SUB_TYPE_ANYTIME  ],
	"anytime4b" : [  210.00,  210.00, TYPE_SUB, SUB_TYPE_ANYTIME  ],
	"anytime3"  : [  160.00,  160.00, TYPE_SUB, SUB_TYPE_ANYTIME  ],
	"matinees6" : [  245.00,  245.00, TYPE_SUB, SUB_TYPE_MATINEE  ],
	"matinees4" : [  180.00,  180.00, TYPE_SUB, SUB_TYPE_MATINEE  ],
	"previews6" : [  255.00,  255.00, TYPE_SUB, SUB_TYPE_PREVIEW  ],
	"previews4" : [  190.00,  190.00, TYPE_SUB, SUB_TYPE_PREVIEW  ],
	"corporate6": [  230.00,  230.00, TYPE_SUB, SUB_TYPE_CORP     ],
	"corporate4": [  165.00,  165.00, TYPE_SUB, SUB_TYPE_CORP     ],
	"series3a"  : [  120.00,  120.00, TYPE_SUB, SUB_TYPE_SERIES   ],
	"series3b"  : [  120.00,  120.00, TYPE_SUB, SUB_TYPE_SERIES   ],
	"series2"   : [   90.00,   90.00, TYPE_SUB, SUB_TYPE_SERIES   ],
	"fp6"       : [  280.00,  280.00, TYPE_FP,  FP_TYPE_NORMAL    ],
	"fp4"       : [  215.00,  215.00, TYPE_FP,  FP_TYPE_NORMAL    ],
	"30ufp6"    : [  120.00,  120.00, TYPE_FP,  FP_TYPE_30U       ],
	"30ufp4"    : [   80.00,   80.00, TYPE_FP,  FP_TYPE_30U       ],
	"stufp6"    : [   60.00,   60.00, TYPE_FP,  FP_TYPE_STUDENT   ],
	"stufp4"    : [   40.00,   40.00, TYPE_FP,  FP_TYPE_STUDENT   ],
	"stumem"    : [   10.00,   10.00, TYPE_MEM, MEM_TYPE_STUDENT  ],
	"30umem"    : [   20.00,   20.00, TYPE_MEM, MEM_TYPE_30U      ]
};

var box_count = 3;
var renewal = false;
// var freebie_eligible = false;

VERIFY_ALERT = "Please check the box indicating that you have "
	+ "read and understood the conditions of membership.";

EMPTY_VALUE = "------------";

order = new Order();
var gItemMenu;

function boxCount() {
//	if (order.containsMembership())
//		return box_count - 1;
//	else
		return box_count;
}

function updateInvoice() {
	clearInvoice();

	// Add a line to invoice for each item in the order.
	var inv = document.getElementById("invoice_body");
	var foot = document.getElementById("invoice_foot");
	var subtotal = 0; 
	var sandh = false;
	for (var i = 0; i < order.size(); ++i) {
		var item = order.items[i];
		var del = document.createElement("img");
		del.setAttribute("src", "/images/delete.gif");
		del.setAttribute("alt", "Remove item");
		del.setAttribute("class", "delete_btn");
		del.setAttribute("name", i);
		addEvent(del, "click", deleteFromOrder, false);

		var qty = document.createTextNode(item.quantity);
		var desc = document.createTextNode(item.description());
		var price = document.createTextNode("$" + item.price.toFixed(2));
		var tot = document.createTextNode("$" + (item.price * item.quantity).toFixed(2));

		var row = inv.insertRow(inv.rows.length);
		var nodes = [del, qty, desc, price, tot];
		for (var n = 0; n < nodes.length; ++n)
			row.insertCell(row.cells.length).appendChild(nodes[n]);
		subtotal += item.price * item.quantity;
	}
	if (row)
		row.id = "last_item";

	// subtotal, S&H
	var sc = order.shippingCharge();
	if (sc > 0) {
		appendFooterRow("Subtotal:", subtotal);
		appendFooterRow("Service charge:", sc);
	}

	// grand total
	appendFooterRow("Order total:", subtotal + sc);
}

function appendFooterRow(desc, amount) {
	var foot = document.getElementById("invoice_foot");
	var row = foot.insertRow(foot.rows.length);
	var desc_node = document.createTextNode(desc);
	var amount_node = document.createTextNode("$" + amount.toFixed(2));
	row.insertCell(0);
	row.insertCell(1);
	row.insertCell(2);
	row.insertCell(3).appendChild(desc_node);
	row.insertCell(4).appendChild(amount_node);
}

function clearInvoice() {
	var body = document.getElementById("invoice_body");
	var foot = document.getElementById("invoice_foot");
	if (body)
		removeChildren(body);
	if (foot)
		removeChildren(foot);
}

function getRadioById(formid, name) {
	var form = document.getElementById(formid);
	return getRadio(form, name);
}

function getRadio(form, name) {
	var radio = form[name];
	if (!radio)
		return undefined;
	for (var i = 0; i < radio.length; ++i) {
		if (radio[i].checked)
			return form[name][i].value;
	}
}

/* 
function validateQuantity() {
	var qty = document.getElementById("qty");
	var value = Math.abs(parseInt(qty.value));
	if (isNaN(value) || value < 1)
		qty.value = 1;
	else
		qty.value = value;
}
*/

function validateDonation() {
	var don = document.getElementById("donation");
	var value = parseInt(don.value);
	if (isNaN(value) || value < 1) {
		don.value = "";
		setDisplay("thanks", "none");
	} else {
		don.value = value;
		setDisplay("thanks", "inline");
	}
}

function validateForm() {
	var flds = document.checkout.getElementsByTagName("input");
	for (var i = 0; i < flds.length; ++i) {
		var name = flds[i].name;
		if (name && name.match(/required_/) && flds[i].value == "") {
			alert("Please complete all fields marked with an asterisk.");
			return false;
		}
	}
	
	if (renewal) {
		var idfield = document.getElementById("memberid");
	 	if (!idfield.value.match(/[0-9][0-9][0-9][0-9]/)) {
			idfield.select();
			alert("Please enter a valid 4-digit member ID number.");
			return false;
		}
	}
	
	return true;
}

function placeOrder() {
	if (validateForm()) {
		with (document.checkout) {
			// defeat overzealous browser auto-complete
			order_total.value = order_detail.value = "";

			for (var i = 0; i < order.size(); ++i) {
				with (order.items[i]) {
					var l = quantity + " " + description() + " [" + quantity + " @ $" + price + " = $" + quantity * price + "]";
					order_detail.value += l + "\n";
				}
			}
			var shipping = order.shippingCharge();
			var total = order.total() + shipping;
			order_detail.value += "\n";
			if (order.shippingCharge()) {
				order_detail.value += "Subtotal: $" + order.total().toFixed(2) + "\n";
				order_detail.value += "Service charge: $" + shipping.toFixed(2) + "\n";
			}
			order_detail.value += "Order total: $" + total.toFixed(2);
			order_total.value = "$" + total.toFixed(2);
			is_renewal.value = renewal ? "Yes" : "No";
			submit();
		}
	}
}

var shows_checked = 0;

jQuery.fn.append_price = function(prefix) {
	return this.each(function() {
		var id = $(this)[0].id;
		if (id) {
			var pkgname = id.split("_")[1];
			$(this).text(prefix + packages[pkgname][renewal ? 1 : 0].toFixed(2));
		}
	});
};

$(document).ready(function() {
	correctPNG();
	reset_package_options();
	$(".price").append_price("$");
	$("#memberid_box").hide();

	$("DIV.package").hover(function() {
		$(this).addClass("selected");
	}, function() {
		$(this).removeClass("selected");
	});
	
	$("#neworderbtn").click(function() {
		startOrder(false);
	});
	
	$("#renewalbtn").click(function() {
		startOrder(true);
	});

	$("A.moreinfo").click(function() {
		$(this).fadeOut("fast");
		
		pkg = $(this).parent();
		var id = pkg[0].id
		var others = $(".package:not(#" + id + ")");
		var pkgdiv = pkg[0];
		var counter = 0;
		var dest = $("#wrap_above");
		var details = pkg.children(".details");

		pkg.addClass("active");
		pkgdiv.style.borderColor = "#404980";
		others.fadeTo("fast", 0, function() {
			others.slideUp("normal", function() {
				if (++counter >= boxCount() - 1) {
					switch (pkgdiv.id) {
						case "pkg_anytime":
						case "pkg_matinees":
						case "pkg_previews":
						case "pkg_flexpass":
						case "pkg_series5":
						case "pkg_series4":
						case "pkg_series3":
						case "pkg_series":
						case "pkg_corporate":
							append_prime(details);
							$("#prime_cblabel").show();
//							if (order.contains_stufp || order.contains_30fp)
//								$("#discounts").hide();
							break;
						case "pkg_silver":
						case "pkg_platinum":
							append_prime(details);
							$("#prime_cblabel").hide();
							break;
					}
					details.slideDown("normal");
				}
			});
		});
	});

	$("A.nothanks_btn").click(function() {
		var pkg = $(this).parents(".package");
		var pkgdiv = pkg[0];
		pkg.children(".details").slideUp("normal", function() {
			pkg.removeClass("active");
			pkgdiv.style.borderColor = "white";
			$(".moreinfo:hidden").show();
			$(".package:hidden").slideDown("normal", function() {
				$(this).fadeTo("fast", 1);	
			});
		});
		reset_package_options();
	});

	// Reveal show details
	$("A.reveal_details").click(function() {
		$(this).fadeOut("fast");
		var details = $(this).parent().children(".show_details");
		var others = $(".show_details:visible");
		others.slideUp("normal", function() {
			$(this).parents(".show").children(".reveal_details").fadeIn("fast");
		});
		details.slideDown();
	});

	// Hide show details
	$("A.hide_details").click(function() {
		var details = $(this).parents(".show_details");
		details.slideUp("normal", function() {
			$(this).parent().children(".reveal_details").show();
		});
	});

	$(".2show_cb").click(function() {
		if (this.checked) {
			if (++shows_checked >= 2) {
				$(".2show_cb:not(:checked)").each(function() {
					this.disabled = "disabled";
					$(this).next().addClass("grayout");
				});
			}
		} else {
			if (--shows_checked < 2) {
				$(".2show_cb").each(function() {
					$(this).attr("disabled", "");
					$(this).next().removeClass("grayout");
				});
			}
		}
	});
	
//	$(".phomt_tixcount").change(function() {
//		selected_phomt_show();
//	});

	$(".addtoorder_btn").click(function() {
		var pkg = $(this).parents(".package");
		var pkgid = pkg[0].id;
		var pkgname = pkgid.split("_")[1];
		var form = pkg.find("form")[0];

		var numtix = getRadio(form, "tix");
		var appendix = "";
		var sharpshow = getRadio(form, "sharp");
		var itemcode = null;
		var qty = null;
		var price = null;
		var note = "";
		var showcount = 0;

		switch (pkgname) {
			case "platinum":
			case "silver":
				numtix = 6;
				break;

			case "anytime":
				if (!numtix) {
					alert("Please select 3, 4, 5, or 6 shows.");
					return;
				}
				if (numtix == 4) {
					if ($("#anytime_4shows_a")[0].checked) {
						appendix = "a";
						if (!sharpshow) {
							alert("Please select a Sharp Theater production.");
							return;
						}
						itemcode = pkgname + numtix + sharpshow;
						if (sharpshow == "1")
							note = "3 Mainstage plus After the Revolution";
						else
							note = "3 Mainstage plus Go Back To Where You Are";
					}
					else {
						appendix = "b";
						note = "Mainstage only";
					}
					itemcode = pkgname + numtix + appendix;
				}
				break;

			case "matinees":
			case "previews":
			case "corporate":
				if (!numtix) {
					alert("Please select 4 or 6 shows.");
					return;
				}
				break;
			
			case "series":
				if (!numtix) {
					alert("Please select 3 or 5 shows.");
					return;
				}
				break;

			case "series2":
				$(".2show_cb").each(function() {
					if (showcount < 2 && this.checked) {
						if (showcount++ > 0)
							note += "; ";
						note += this.value;
					}
				});
				if (showcount < 2) {
					alert("Please select two productions.");
					return;
				}
				itemcode = "series2";
				numtix = 2;
				break;

			case "series3":
				itemcode = "series3";
				numtix = 3;
				break;

			case "series4":
				itemcode = "series4";
				numtix = 4;
				break;

			case "series5":
				itemcode = "series5";
				numtix = 5;
				break;

			case "flexpass":
				itemcode = getRadio(form, "tix");
				if (!itemcode) {
					alert("Please select 4 or 6 tickets.")
					return;
				}
				numtix = itemcode.charAt(itemcode.length - 1);
				break;
			
/*
			case "phomt":
				if (!phomt_validate(form))
					return;
				qty = 1;
				itemcode = "phomt";
				numtix = 0;
				var pricenote = phomt_pricenote(form);
				price = pricenote[0];
				note = pricenote[1];
				break;
*/
			
			case "mem":
				if (order.containsMembership()) {
					alert("Sorry, there's a limit of one Student or 30&Under Membership per order.");
					return;
				}
			
				if ($("#stumemcb")[0].checked)
					itemcode = "stumem";
				else if ($("#30umemcb")[0].checked)
					itemcode = "30umem";
				else {
					alert("Please select a type of membership.");
					return;
				}
			
				if (!$("#verify_cb")[0].checked) {
					alert(VERIFY_ALERT);
					return;
				}
				qty = 1;
				numtix = 0;
				break;
			
			default: return;
		}

		if (!itemcode)
			itemcode = pkgname + numtix;
		if (!qty)
			qty = parseInt(form.qty.value);
		if (!price)
			price = packages[itemcode][renewal ? 1 : 0];
		var prime = $("#prime")[0].checked;
		
		var item = packages[itemcode];
		order.addItem(new Item(qty, item[2], item[3], numtix, price, note));
		if (prime)
			order.addItem(new Item(qty, TYPE_PRIME, SUB_TYPE_NONE, 0, 50, note));
		updateInvoice();
		$("#invoice:hidden").slideDown();
		$("#offers").slideUp("normal", reset_packages);
		$("#additem:hidden").fadeIn("fast");
	});

	$("#stumemcb").click(function() {
		$("#prime_box:visible").hide();
		$("#stumem_note:hidden").fadeIn();
		$("#30umem_note:visible").hide();
		$("#verify:hidden").fadeIn();
	});

	$("#30umemcb").click(function() {
		$("#prime_box:visible").hide();
		$("#stumem_note:visible").hide();
		$("#30umem_note:hidden").fadeIn();
		$("#verify:hidden").fadeIn();
	});
	
	$(".tixcount input[name=tix]").click(function() {
		if ($(this)[0].id == "anytime_4shows_a")
			$("#anytime4_sharpshow").slideDown("fast");
		else
			$("#anytime4_sharpshow").slideUp("fast");
	});
	
	var selected_box = page_anchor();
	if (selected_box)
		open_box(selected_box);
});

function open_box(name) {
	$("#pkg_" + name + " a.moreinfo").trigger("click");
}

/*
function selected_phomt_show() {
	var count = 0;
	var names = ["burnt", "clybourne", "cooldip"];
	for (var i in names) {
		if ($("#" + names[i] + "_tixcount").val() > 0) {
			count++;
			phomt_freebie_setenabled(names[i], true);
		} else
			phomt_freebie_setenabled(names[i], false);
	}
	if (count >= 3) {
		$("#phomt_freebie").slideDown("fast");
		freebie_eligible = true;
	} else {
		$("#phomt_freebie").slideUp("fast");
		freebie_eligible = false;
	}
}

function phomt_freebie_setenabled(name, enabled)
{
	var eltid = "#phomt_free_" + name;
	if (enabled) {
		$(eltid).removeAttr("disabled");
		$(eltid).next("label").removeClass("grayout");
	} else {
		$(eltid).attr("disabled", "disabled");
		$(eltid).removeAttr("checked");
		$(eltid).next("label").addClass("grayout");
	}
}

function phomt_validate(form)
{
	// check for at least two tickets ordered
	var names = ["burnt", "clybourne", "cooldip"];
	var tixcount = 0;
	for (var i in names)
		tixcount += parseInt($("#" + names[i] + "_tixcount").val());
	if (tixcount < 2) {
		alert("PH On My Terms has a minimum purchase of two tickets.");
		return false;
	}
	if (freebie_eligible) {
		var freebie = getRadio(form, "phomt_freebie_show");
		if (!freebie) {
			alert("Please select a production for your free ticket.");
			return false;
		}
	}
	return true;
}

function phomt_pricenote(form)
{
	var note = "";
	var tix;
	var price = 0;
	tix = parseInt($("#clybourne_tixcount").val());
	if (tix > 0) {
		note += " " + tix + " x CLYBOURNE @ 50.00;";
		price += tix * 50;
	}
	tix = parseInt($("#cooldip_tixcount").val());
	if (tix > 0) {
		price += tix * 35;
		note += " " + tix + " x COOL DIP @ 35.00;";
	}
	tix = parseInt($("#burnt_tixcount").val());
	if (tix > 0) {
		price += tix * 50;
		note += " " + tix + "x BURNT @ 50.00;";
	}
	if (freebie_eligible) {
		var freebie = getRadio(form, "phomt_freebie_show");
		if (freebie)
			note += " 1 FREE ticket to " + freebie.toUpperCase();
	}
	note = note.replace(/;$/, "");
	return [price, note];
}
*/

function startOrder(isRenewal) {
//	renewal = isRenewal;
	if (renewal) {
		$("#memberid_box").show();
	} else {
		$("#memberid_box").hide();
	}
	$("#paymentplan").show();
	$(".price").append_price("$");
	$("#ordertype").text(renewal ? "renewal" : "new subscription");
	$("#initial").fadeOut("fast", function() {
		$("#shopping").slideDown("fast", correctPNG);
	});
}

function reset_packages() {
	$(".details").hide();
	$(".package").each(function() {
		$(this).removeClass("active");
		$(this)[0].style.borderColor = "white";
//		if (!order.containsMembership() || this.id != "pkg_mem") {
			$(this).animate({ opacity: 1 }, "fast");
			$(this).show();
//		} else {
//			$(this).hide();
//		}
	})
	$(".moreinfo").show();
	reset_package_options();
}

function reset_package_options() {
	var uncheck = function() { $(this)[0].checked = false; }
	$("#offers").find("input[type='radio']").each(uncheck);
	$("#offers").find("input[type='checkbox']").each(uncheck);
	$("#offers").find("input[name='qty']").each(function() {
		$(this)[0].value = "1";
		$(this)[0].disabled = false;
	});

	$(".note").hide();
	$("#verify").hide();
	$(".prod_choice label").removeClass("grayout");
	$(".prod_choice input").attr("disabled", "");
	$("#anytime4_sharpshow").hide();
	shows_checked = 0;
	
/*
	$(".phomt_tixcount").val("0");
	$("#phomt_freebie label").addClass("grayout");
	$("#phomt_freebie input").attr("disabled", "disabled");
	$("#phomt_freebie").hide();
	freebie_eligible = false;
*/
}

function priceof(elt) {
	return elt.id;
}

function append_prime(elt) {
	elt.find(".prime_marker").after($("#prime_box")[0]);
	$("#prime_box").show();
}

function addItem() {
	$("#additem").fadeOut("fast");
	$("#offers").slideDown();
}

function cancelOrder() {
	if (confirm("Are you sure you want to cancel your order?")) {
		$("#shopping").fadeOut("normal", function() {
			$("#initial").slideDown("fast");
			$("#invoice").hide();
			$("#offers:visible").hide();
			order.clear();
			reset_packages();
			$("#offers").show();
//			$("#shopping").fadeIn("fast");
		});
	}
}


/*
function cancelOrder() {
	if (confirm("Are you sure you want to cancel your order?")) {
		$("#invoice").slideUp("fast");
		$("#offers").slideDown("fast");
		order.clear();
		reset_packages();
//		$("#offers").show();
	}
}
*/

function checkOut(what) {
	if (what) {
		if (order.containsMembership() && order.size() == 1) {
			$("#paymentplan").hide();
		} else {
			var total = order.total();
			$("#inst1_amt").text("$" + total.toFixed(2));
			$("#inst2_amt").text("$" + (total/2).toFixed(2));
			$("#inst3_amt").text("$" + (total/3).toFixed(2));
			$("#paymentplan").show();
		}
	
		$("#invoice_body").find("img").hide();
		$("#instructions").hide();
		$("#pitch").slideUp();
		$("#offers:visible").slideUp(reset_packages);
		$("#shows").slideUp();
		$("#inv_buttons").slideUp();
		reset_packages();
		$("#checkout").slideDown();

	} else {
		$("#invoice_body").find("img").show();
		$("#instructions").show();
		$("#pitch").slideDown();
		$("#shows").slideDown();
		$("#checkout").slideUp();
		$("#additem:hidden").show();
		$("#inv_buttons").slideDown();
	}
}

function deleteFromOrder(e) {
	if (window.event)
		var target = window.event.srcElement;
	else
		var target = e.target;
	
	order.deleteItem(target.name);
	if (order.size() == 0) {
		$("#invoice").slideUp();
		$("#offers:visible").slideUp();
		order.clear();
		reset_packages();
		$("#offers").slideDown();
	} else {
		updateInvoice();
//		if (!order.containsMembership()) {
//			$("#pkg_mem").animate({ opacity: 1 }, "fast");
//			$("#pkg_mem").fadeIn();
//		}
	}
}

function showPopup(url, width, height) {
	var win = window.open(url, 'patron_details', 'height=' + height + ',width=' + width + ',scrollbars=1,resizable=0');
	win.focus();
}

function showPatronPopup() {
	showPopup("/patron_details.html", 500, 400);
}

function showInvitePopup() {
	showPopup("/invite_a_friend.html", 500, 455);
}

