// Shopping Cart


// active purchases
var purchases = new Array();
// active performance container
var performances = new Array();

/** Coded Aug 11 08 bbarstow@imap.cc **/
var donations = new Array();
/** end **/

// Adds one or more elements to the end of an array and returns
// the new length of the array.
// This is a fix for older browsers that do not support the push method
if (!Array.prototype.push) {
	Array.prototype.push = function() {
		for (var i = 0; i < arguments.length; ++i) {
			this[this.length] = arguments[i];
		}
		return this.length;
	};
}

// adds unique values to an array
Array.prototype.addUnique = function() {
	var matched = false;
	for (var i = 0; i < this.length; ++i) {
		if (arguments[0] == this[i]) {
			matched=true;
		}
	}
	if (!matched) {
		this[this.length] = arguments[0];
		return true;
	} else {
		return false;
	}
};

// Ticket Class
function Ticket(title ,cost_adult, cost_senior, cost_student, perfdate, perfID) {
	var dateArr = perfdate.split(",");
	this.title = title;
	this.cost = new Object();
	this.cost.general_admission = cost_adult;
	this.cost.senior = cost_senior;
	this.cost.student = cost_student;
	if (dateArr.length == 6) {
		this.perfdate = new Date(parseInt(dateArr[0]),parseInt(dateArr[1]),parseInt(dateArr[2]),parseInt(dateArr[3]),parseInt(dateArr[4]),parseInt(dateArr[5]));
	} else if (dateArr.length == 3) {
		this.perfdate = new Date(parseInt(dateArr[0]),parseInt(dateArr[1]),parseInt(dateArr[2]));
	} else {
		this.perfdate = new Date(perfdate);
	}
	this.perfID = perfID;
}

/** Coded Aug 11 08 bbarstow@imap.cc **/
function Donation(title, cost, donationID) {
	this.title = title;
	this.cost = cost;
	this.donationID = donationID;
}
/** end **/

// create on-page error output
function displayError(errHTML, msec) {
	var linkDiv = document.getElementById("cart_error");
	var linkDiv2 = document.getElementById("cart_error_detail");
	var stickResults = (arguments[2] == undefined) ? false : arguments[2] ;
	if (linkDiv.style.visibility != "visible") {
		linkDiv2.innerHTML = errHTML;
		linkDiv.style.display = "block";
		linkDiv.style.visibility = "visible";
		linkDiv.style.height = "auto";
		timer = setTimeout(function (t) {
			linkDiv2.innerHTML = "";
			linkDiv.style.height = "0";
			linkDiv.style.display = "none";
			linkDiv.style.visibility = "hidden";
			clearTimeout(timer);
		}, parseInt(msec), true);
	} else {
		linkDiv2.innerHTML += ("<br />"+errHTML);
	}
	if (stickResults) {
		clearTimeout(timer);
		linkDiv.onclick = function() {
			linkDiv2.innerHTML = "";
			linkDiv.style.height = "0";
			linkDiv.style.display = "none";
			linkDiv.style.visibility = "hidden";
		}
	}
}

// sort() helper to re-order the performance dates for the dropdown menu.
function sortPerfDatesByLength(a,b){
	var ayr = a["perfdate"].getFullYear();
	var amo = a["perfdate"].getMonth();
	var adt = a["perfdate"].getDate();
	var byr = b["perfdate"].getFullYear();
	var bmo = b["perfdate"].getMonth();
	var bdt = b["perfdate"].getDate();
	if (ayr > byr) {
		return 1;
	} else if (ayr == byr) {
		if (amo > bmo) {
			return 1;
		} else if (amo == bmo) {
			if (adt > bdt) {
				return 1;
			} else {
				return -1;
			}
		} else {
			return -1;
		}
	} else {
		return -1;
	}
}

// populate the ticket selection dropdown
function populateTicketSelect(byDate) {
	var perfSelect = document.getElementById("performance_list");
	var perfsTemp = new Array();
	var rightNow = new Date();
	for (var i=0; i<performances.length ; i++) {
		perfsTemp.push(performances[i]);
	}
	if (byDate) {
		perfsTemp.sort(sortPerfDatesByLength);
	}
	for (var i=0; i < perfsTemp.length ;i++) {
		if (rightNow < perfsTemp[i]["perfdate"]) {
			var dateStamp = perfsTemp[i]["perfdate"].getMonth()+1 + " / " + perfsTemp[i]["perfdate"].getDate() + " / " + perfsTemp[i]["perfdate"].getFullYear();
			
			if(perfsTemp[i]["perfID"]==(ticketid)) {
				addOption(perfSelect,perfsTemp[i]["title"]+" - ("+dateStamp+")",perfsTemp[i]["perfID"],true);
			} else {
				addOption(perfSelect,perfsTemp[i]["title"]+" - ("+dateStamp+")",perfsTemp[i]["perfID"],false);
			}
		}
	}
}

// create the selection table from the available performances.
function createTicketTable() {
	// populate the ticket table
	var tbl = document.getElementById("ticket_items");
	var tbod_old = tbl.getElementsByTagName("tbody")[0];
	var tbod = document.createElement("tbody");
	var count = 0;
	var perfsTemp = new Array();
	var rightNow = new Date();
	for (var i=0; i<performances.length ; i++) {
		perfsTemp.push(performances[i]);
	}
	perfsTemp.sort(sortPerfDatesByLength);
	for (var i=0; i < perfsTemp.length; i++) {
		count = i;
		if (rightNow <= perfsTemp[i]["perfdate"]) {  // CHANGE TO < [less than] FOR PROPER FUNCTION
			var dateStamp = perfsTemp[i]["perfdate"].getMonth()+1 + " / " + perfsTemp[i]["perfdate"].getDate() + " / " + perfsTemp[i]["perfdate"].getFullYear();
			var tr = document.createElement("tr");
			var td_title = document.createElement("td");
			var td_date = document.createElement("td");
			var td_ga = document.createElement("td");
			var td_senior = document.createElement("td");
			var td_student = document.createElement("td");
			td_title.innerHTML = perfsTemp[i]["title"];
			td_date.innerHTML = dateStamp;
			td_ga.innerHTML = "<a href=\"JavaScript: addTicket("+perfsTemp[i]["perfID"]+",'general_admission','"+perfsTemp[i]["title"].replace("'", "")+"', 1, "+ perfsTemp[i]["cost"]["general_admission"]+", '"+dateStamp+"')\">Add Ticket</a> ($"+ perfsTemp[i]["cost"]["general_admission"]+")";
			td_senior.innerHTML = "<a href=\"JavaScript: addTicket("+perfsTemp[i]["perfID"]+",'senior','"+perfsTemp[i]["title"].replace("'", "")+"', 1, "+ perfsTemp[i]["cost"]["senior"]+", '"+dateStamp+"')\">Add Ticket</a> ($"+ perfsTemp[i]["cost"]["senior"]+")";
			td_student.innerHTML = "<a href=\"JavaScript: addTicket("+perfsTemp[i]["perfID"]+",'student','"+perfsTemp[i]["title"].replace("'", "")+"', 1, "+ perfsTemp[i]["cost"]["student"]+", '"+dateStamp+"')\">Add Ticket</a> ($"+ perfsTemp[i]["cost"]["student"]+")";
			td_ga.className = td_senior.className = td_student.className = "ticket";
			tbod.appendChild(tr);
			tr.appendChild(td_title);
			tr.appendChild(td_date);
			tr.appendChild(td_ga);
			tr.appendChild(td_senior);
			tr.appendChild(td_student);
		}
	}
	if (count == 0) {
		var td = document.createElement("td");
		td.setAttribute("style", "padding:1em;");
		td.innerHTML = "There are no tickets currently available for purchase."
		var tr = document.createElement("tr");
		tr.setAttribute("colspan", "4");
		tr.appendChild(td);
		tbod.appendChild(tr);
	}
	tbl.replaceChild(tbod,tbod_old);
}

/** Coded Aug 11 08 bbarstow@imap.cc **/
function createDonationTable() {
	// populate the ticket table
	var tbl = document.getElementById("donations_items");
	var tbod_old = tbl.getElementsByTagName("tbody")[0];
	var tbod = document.createElement("tbody");
	var count = 0;

	var donsTemp = new Array();
	var rightNow = new Date();
	for (var i=0; i<donations.length ; i++) {
		donsTemp.push(donations[i]);
	}
	//donsTemp.sort();
		
	var tr = document.createElement("tr");
	
	for (var i=0; i < donsTemp.length; i++) {
		count = i;
				
		var td_title = document.createElement("td");
		td_title.innerHTML = donsTemp[i]["title"] + "<br /><a href=\"JavaScript: addTicket("+donsTemp[i]["donationID"]+",'donation','" + donsTemp[i]["title"].replace("'", "") + "' ,1, "+ donsTemp[i]["cost"]+", 0)\">Donate</a> ($"+ donsTemp[i]["cost"]+")";
	
		td_title.className = "donation";
			
		tr.appendChild(td_title);
	}
	
	tbod.appendChild(tr);
	
	if (count == 0) {
		var td = document.createElement("td");
		td.setAttribute("style", "padding:1em;");
		td.innerHTML = "We are not accepting donations at this time."
		var tr = document.createElement("tr");
		tr.appendChild(td);
		tbod.appendChild(tr);
	}
	tbl.replaceChild(tbod,tbod_old);
}

/** end **/

// add the selected ticket to the cart
function addSelectedTicket() {
	var performanceSelect = document.getElementById("performance_list");
	var ticketTypeSelect = document.getElementById("ticket_type");
	var idx = performanceSelect.options[performanceSelect.selectedIndex].value;
	var ticketType = ticketTypeSelect.options[ticketTypeSelect.selectedIndex].value;
	addTicket(idx, ticketType, 1);
}

// add a ticket by perfID# to the cart
function addTicket(idx, ticketType, ticketName, quantity, price, perfDate) {
	var duplicate = false;
	var allpurchases = "";

	if(ticketType == "donation"){
		purchases.push(new Array(parseInt(idx), ticketType, parseInt(quantity), ticketName, price, perfDate));
	}	
	else {
		// displayError(idx,5000,true);
		for (var i=0; i<purchases.length; i++) {
			if (purchases[i][0] == idx && purchases[i][1] == ticketType) {
				purchases[i][2] += parseInt(quantity);
				duplicate = true;
			}
		}
		if (!duplicate) {
			purchases.push(new Array(parseInt(idx), ticketType, parseInt(quantity), ticketName, price, perfDate));
		}
	}
		
	drawCart();
	resetPurchaseCookie();
};

// sets the cookie for storing the ticket selections
// used whenever cart contents change.
function resetPurchaseCookie() {
	var allpurchases = new Array();
	for (var i=0; i<purchases.length ;i++) {
		var formattedPurchase = purchases[i].join("|");
		formattedPurchase.replace();
		allpurchases.push(formattedPurchase);
	}
	setCookieExpDays("purchases", allpurchases.toString(), (1/24));
}

// removes a line item, independent of quantity.
function removeTicket(n) {
	var tmp = new Array();
	for (var i=0; i<purchases.length ;i++) {
		if (n != i) {
			tmp.push(purchases[i]);
		}
	}
	purchases = tmp;
	resetPurchaseCookie();
	drawCart();
}

function removeZeroQuantities() {
	for (var i=0; i<purchases.length ;i++) {
		if (purchases[i][2] <= 0) {
			purchases.splice(i,1);
		}
	}
	resetPurchaseCookie();
	drawCart();
}
// if there is a cookie for purchases, add it into the cart's contents.
function populateCartFromCookie(performances, donations) {
	if (getCookie("purchases")) {
		var items = getCookie("purchases").split(",");
		for (var i=0; i < items.length ; i++) {
			var splitVals = items[i].split("|");
			
			addTicket(splitVals[0], splitVals[1], splitVals[3], splitVals[2], splitVals[4], splitVals[5]);
//			displayError(unescape(document.cookie)+" -- "+splitVals.toString(), 5000);
		}
	}
}

// draw the cart's contents
function drawCart() {
	var tbl = document.getElementById("cart_items");
	var tbod_old = tbl.getElementsByTagName("tbody")[0];
	var tbod = document.createElement("tbody");
	
	if (purchases.length > 0) {
		for (var i=0; i < purchases.length ; i++) {
			//i = purchase id.			
			var tr = document.createElement("tr");
			var td_title = document.createElement("td");
			var td_type = document.createElement("td");
			var td_quantity = document.createElement("td");
			var td_cost = document.createElement("td");
			td_title.setAttribute("class", "sc_item");
			td_type.setAttribute("class", "sc_type");
			td_quantity.setAttribute("class", "sc_quant");
			td_cost.setAttribute("class", "sc_cost");
			
			td_title.innerHTML = "<a href='JavaScript: void(0)' onclick='removeTicket("+i+")' class='remove_item'>remove</a>";
			td_title.innerHTML += purchases[i][3];			
			//td_title.innerHTML += performances[(purchases[i][0]-1)]["title"];
			td_title.innerHTML += "<input type='hidden' id='id_"+i+"' name='id_"+i+"' value='"+(purchases[i][0]-1)+"' />"; 
			td_title.innerHTML += "<input type='hidden' id='title_"+i+"' name='title_"+i+"' value='"+purchases[i][3]+"' />";
			td_title.innerHTML += "<input type='hidden' id='performanceDate_"+i+"' name='performanceDate_"+i+"' value='"+purchases[i][5]+"' />";
			//td_title.innerHTML += "<input type='hidden' id='title_"+i+"' name='title_"+i+"' value='"+performances[(purchases[i][0]-1)]["title"]+"' />";
			
			td_type.innerHTML = purchases[i][1].split("_").join(" ") + "<input type=\"hidden\" id=\"type_"+i+"\" name=\"type_"+i+"\" value=\""+purchases[i][1]+"\" size=\"2\" />";

			td_quantity.innerHTML = "<div class='arrows'><a href='JavaScript: void(0)' onclick='increase("+i+")' class='inc_arrow'>more</a>";
			td_quantity.innerHTML += "<a href='JavaScript: void(0)' onclick='decrease("+i+")' class='dec_arrow'>less</a></div>";
			td_quantity.innerHTML += "<input type='text' id='quantity_"+i+"' name='quantity_"+i+"' value='"+purchases[i][2]+"' size='2' onkeypress='return handleEnter(this, event, "+i+");' />";
			td_quantity.innerHTML += "<input type='hidden' id='unitcost_"+i+"' name='unitcost_"+i+"' value='"+purchases[i][4]+"' size='2' />\n";
			
			td_cost.innerHTML = "$<span id=\"cost_"+i+"\"></span>";
			tr.setAttribute("id", "item_"+i);
			tbod.appendChild(tr);
			tr.appendChild(td_title);
			tr.appendChild(td_type);
			tr.appendChild(td_quantity);
			tr.appendChild(td_cost);
	//		htmlRows += ticketTr(i,purchases[i][0],purchases[i][1],purchases[i][2]);
		}
	} else {
		var td = document.createElement("td");
		td.setAttribute("style", "padding:1em;");
		td.innerHTML = "There are no items in your cart."
		var tr = document.createElement("tr");
		tr.setAttribute("colspan", "4");
		tr.appendChild(td);
		tbod.appendChild(tr);
	}
	tbl.replaceChild(tbod,tbod_old);
	recalcAll();
//	tbod.innerHTML = htmlRows;
	zebraStripe("cart_items");
}

// show the contents of the purchases array.
function showDebug(extra) {
	document.getElementById("debug").innerHTML = purchases.toString().split(",").join(" ") + ((extra != undefined) ? extra : "");
}

// increment quantity and recalculate
function increase(idx) {
	if (purchases[idx][2] < 20) {
		purchases[idx][2]++;
	} else {
		displayError("No more than 20 Tickets are allowed for each performance", 5000);
	}
	resetPurchaseCookie();
	recalcAll();
}

// decrement quantity and recalculate
function decrease(idx) {
	if (purchases[idx][2] > 0) {
		purchases[idx][2]--;
	}
	resetPurchaseCookie();
	recalcAll();
}

function sortPurchasesByPriceTitleType(a,b) {
	if (a.quantity < b.quantity) {
		return 1;
	} else if (a.quantity > b.quantity) {
		return -1;
	} else {
		if (a.unitcost > b.unitcost) {
			return -1;
		} else if (a.unitcost < b.unitcost) {
			return 1;
		} else {
			if (a.type > b.type) {
				return 1;
			} else if (a.type < b.type) {
				return -1;
			} else {
				if (a.title > b.title) {
					return 1;
				} else {
					return -1;
				}
			}
		}
	}
}

Array.prototype.addUniqueObject = function(obj) { // object [attribute 1, ... ,attribute n]
	var matches = 0;
	var matched = false;
	if (this.length == 0) {
		this[this.length] = obj;
		return true;
	} else {
		for (var i = 0; i < this.length; i++) {
			for (var j = 1; j < arguments.length; j++) {
				if (obj[arguments[j]] == this[i][arguments[j]]) {
					matches++;
				}
			}
			if (matches == (arguments.length-1)) {
				matched = true;
			}
			matches = 0;
		}
		if (matched) {
			return false;
		} else {
			this[this.length] = obj;
			return true;
		}
	}
};

function getIndiciesOfDiscountedTickets(arrayToUse,type) {
	var prevTicket = "";
	var packSize = 5;
	var packNum = 0;
	var pttl = new Array();
	var ticketIndicies = new Array();
	var packs = new Array(new Array());
	var numberOfPacks = 0;
	for (var i=0; i < arrayToUse.length; i++){
		if (arrayToUse[i].type == type) {
			pttl.push(arrayToUse[i]);
		}
	}
	var i = 0;
	// while it is possible to create a set or sets of five...
	while (((pttl.length + packs[packNum].length) >= packSize) && (i < pttl.length)) {
		// if the pack size is a multiple of five greater than zero...
		if (((packs[packNum].length % packSize) == 0) && (packs[packNum].length > 0)) {
			//displayError("packlen : "+packs[packNum].length,5000,true);
			// create a new pack array in the packs array
			packs.push(new Array());
			// increment the packnumber in runtime memory
			packNum++;
			// set i back to zero so it will start sorting the array anew.
			i=0;
		// if the index does not exist in the current pack, add it and...
		} else if (packs[packNum].addUniqueObject(pttl[i],"title","type")) {
			// remove the corresponding ticket object from the master array.
			pttl.splice(i,1);
		} else {
			// if the ticket is not unique, go to the next
			// by incrementing the counter variable.
			i++;
		}
	}
	// ...return the indicies as a unidimensional array.
	for (var i = 0; i < packs.length; i++) {
		for (var j = 0; j < packs[i].length; j++) {
			ticketIndicies.push(packs[i][j].origIndex);
		}
	}
	return ticketIndicies.splice(0,(ticketIndicies.length - (ticketIndicies.length % packSize))); // packs.toString().split(",");
}

function recalcAll() {
	var discount = new Object();
	var discountedTicketIndicies = new Object();
	var packSize = 5;
	discount["general_admission"] = 65;
	discount["senior"] = 45;
	discount["student"] = 15;
	var subtotal = 0;
	var finalTotal = 0;
	var pttl = new Array();
	for (var i = 0; i < purchases.length; i++) {
		recalc(i);
		//subtotal = cost * qty
		subtotal += purchases[i][4] * purchases[i][2]; //(performances[purchases[i][0]-1]["cost"][purchases[i][1]]*purchases[i][2]);
		// depending on rules, you may have to change this to num*Tickets++ only
		for (var j = 0; j < purchases[i][2]; j++) {
			var cntnr = new Object();
			cntnr.title = purchases[i][3]; //performances[purchases[i][0]-1]["title"];
			cntnr.type = purchases[i][1]; 
			cntnr.unitcost = purchases[i][4]; //performances[purchases[i][0]-1]["cost"][purchases[i][1]];
			cntnr.quantity = purchases[i][2];
			pttl.push(cntnr);
		}
	}
	pttl.sort(sortPurchasesByPriceTitleType);
	
	for (var i = 0; i < pttl.length; i++) {
		pttl[i].origIndex = i;
	}
	gaTix = getIndiciesOfDiscountedTickets(pttl,"general_admission");
	seTix = getIndiciesOfDiscountedTickets(pttl,"senior");
	stTix = getIndiciesOfDiscountedTickets(pttl,"student");
	allDiscountTickets = gaTix.concat(seTix,stTix);
	if (gaTix.length > 0) {
		finalTotal += parseFloat((gaTix.length / packSize)*discount["general_admission"]);
//		displayError("gaTix: "+gaTix.toString(),5000,true);
	}
	if (seTix.length > 0) {
		finalTotal += parseFloat((seTix.length / packSize)*discount["senior"]);
//		displayError("seTix: "+seTix.toString(),5000,true);
	}
	if (stTix.length > 0) {
		finalTotal += parseFloat((stTix.length / packSize)*discount["student"]);
//		displayError("stTix: "+stTix.toString(),5000,true);
	}
	for (var i = 0; i < pttl.length ; i++) {
		if (allDiscountTickets.addUnique(pttl[i].origIndex)) {
//			displayError("is "+ pttl[i].origIndex +"unique?: "+ allDiscountTickets.addUnique(pttl[i].origIndex),5000,true);
			finalTotal += parseFloat(pttl[i].unitcost);
		}
	}
//	displayError("disc tix: "+ allDiscountTickets.toString(),5000,true);
	document.getElementById("cart_subtotal").innerHTML =
	document.getElementById("cart_subtotal_fld").value = subtotal;
	document.getElementById("cart_discounts").innerHTML = subtotal-finalTotal;
	document.getElementById("cart_total").innerHTML =
	document.getElementById("cart_total_fld").value = finalTotal;
//	showDebug();
}

// recalculate a single row for quantity changes
function recalc(idx) {
	//cost per lineitem
	var unitCost = purchases[idx][4]; //performances[(purchases[idx][0]-1)]["cost"][purchases[idx][1]];
	var quantity = purchases[idx][2];
	document.getElementById("quantity_"+idx).value = quantity;
	document.getElementById("cost_"+idx).innerHTML = unitCost*quantity;
}

// stripe the table by setting odd and even attributes to the tr tags
function zebraStripe(tableID) {
	var tbods = document.getElementById(tableID).getElementsByTagName("tbody");
	var trows = tbods[0].getElementsByTagName("tr");
	for (var i = 0; i < trows.length; i++) {
		if ((i%2) != 0) {
			trows[i].setAttribute("class", "odd");
		} else {
			trows[i].setAttribute("class", "even");
		}
	}
}

// diable the enter key to restrict form submission
function handleEnter (field, event, idx) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		var i;
		for (i = 0; i < field.form.elements.length; i++) {
			if (field == field.form.elements[i]) {
				break;
			}
		}
		i = (i + 1) % field.form.elements.length;
		purchases[idx][2] = field.value;
		recalcAll();
		field.form.elements[i].focus();
		return false;
	} else if (keyCode == 38) {
		increase(idx)
		return true;
	} else if (keyCode == 40) {
		decrease(idx)
		return true;
	} else {
		return true;
	}
}      

function copyFromBilling() {
	document.getElementById("cc_name").value =
		(document.getElementById("billing_firstname").value + " " + document.getElementById("billing_lastname").value).toUpperCase();
}

function copyFromMailing() {
	var fields = new Array("firstname","lastname","company","address","city","state","zip");
	var fieldsets = new Array("mailing","billing");
	for (var i=0; i<fields.length; i++) {
		document.getElementById(fieldsets[1]+"_"+fields[i]).value =
			document.getElementById(fieldsets[0]+"_"+fields[i]).value;
	}
}

function showCCV() {
	document.getElementById("ccv_example").style.display = "block";
}

function checkCartSubmit() {
	removeZeroQuantities();
	if(purchases.length <= 0) {
		alert("Please add a ticket to your cart first.");
		return false;
	} else {
		return true;
	}
}

function isEmailAddress(addr) {
	if (addr.indexOf('@',0)==-1 || addr.indexOf('@',0)== 0 || addr.indexOf('.',0)==-1) {
		return false;
	} else {
		return true;
	}
}

function stripToNumber(str) {
	return str.replace(/[\(\)\.\-\+\ ]/g, "")
}

function isPhone(str) {
	if (isNaN(parseInt(stripToNumber(str)))) {
		return false;
	} else {
		return true;
	}
}

function isLen(str, min_len, max_len) {
//	alert(str+" | "+str.length+" | "+min_len+" | "+max_len);
	if ((max_len != undefined) && (str.length > max_len)) {
		return false;
	}
	if (str.length < min_len) {
		return false;
	}
	return true;
}

function focusFieldAndNotify(fld, alrt) {
	alert("\n"+alrt+"\n");
	fld.select();
	fld.focus();
	return false;
}

function verifyCustomerInfo(f) {
	var addressSets = new Array("mailing","billing");
	var addressFields = new Array("firstname","lastname","address","city","state","zip");
	var addressFieldsLen = new Array(1,1,1,1,2,5);
	var otherFields = new Array("email","phone_day","password1","password2","cc_name","cc_number","cvv2");
	var flds = new Object();
	for (var i=0; i < otherFields.length ; i++) {
		flds[otherFields[i]] = document.getElementById(otherFields[i]);
	}
	if (!isEmailAddress(flds["email"].value)) {
		return focusFieldAndNotify(flds["email"],
			"Invalid email address, please correct.");
	}
	if (!isPhone(flds["phone_day"].value)) {
		return focusFieldAndNotify(flds["phone_day"],
			"The phone number you supplied does not seem to be correct. Please remove any unnecessary characters and try again.");
	}
	if (!isLen(flds["phone_day"].value,10)) {
		return focusFieldAndNotify(flds["phone_day"],
			"The phone number you supplied does not seem to be complete. Please make sure you have included your area code.");
	}
	if (!isLen(flds["password1"].value,6,12)) {
		return focusFieldAndNotify(flds["password1"],
			"The password you provded is not the correct length.  Please make sure it is between 6 and 12 characters.");
	}
	if (flds["password1"].value != flds["password2"].value) {
		return focusFieldAndNotify(flds["password1"],
			"The passwords do not match.  Please re-type your password in both fields.");
	}
	for (var i=0; i < addressSets.length ; i++) {
		for (var j=0; j < addressFields.length ; j++) {
			var fldname = addressSets[i]+"_"+addressFields[j];
			var addyfld = document.getElementById(fldname);
			if(!isLen(addyfld.value,addressFieldsLen[j])) {
				return focusFieldAndNotify(addyfld,"The " + fldname.split("_").reverse().join(" in the ") + " address field does not appear to be correct.  Please check it and try again.");
			}
		}
	}
	if (!isLen(flds["cc_name"].value,3)) {
		return focusFieldAndNotify(flds["cc_name"],
			"Please fill in the full name on your credit card.");
	}
	flds["cc_number"].value = stripToNumber(flds["cc_number"].value);
	if (!isLen(flds["cc_number"].value,15)) {
		return focusFieldAndNotify(flds["cc_number"],
			"The credit card you've used does not seem to be entered correctly.  Please check the number and enter it again.");
	}
	if (!isLen(flds["cvv2"].value,3,4)) {
		return focusFieldAndNotify(flds["cvv2"],
			"The Verification # (CVV#) does not seem to be entered correctly.  Please check the number and enter it again.");
	}
	//return true;
}
