		// hak_wine_form v0.1
		var store = {
		    totalBottles: 0,
		    shippingBottles:0,
		    zone1States:["Washington","Oregon","Idaho"],
		    zone2States:[""],
		    subTotal: 0,
		    discount:0,
		    caseDiscount: 0,
		    halfCaseDiscount: 0,
		    clubDiscount: 0,
		    clubLevel: 0,
		    lookupDiscount: false,
		    fetchTax: true,
		    defaultTaxRate: 0,
		    defaultClubDiscount: 0,
		    exclusiveDiscount: true,
		    tax: 0,
		    taxCache:{},
		    discountCache:{},
		    levelCache:{},
		    shipping:25,
		    total:0,
		    // quantity lookup for cases/bottles dropdown
		    caseSelect: {
					cases:12,
					bottles:1
		    },
    shippingRate: function(t) {
			var rate = 0;
			if (store.clubLevel != 0 && 0 != 0)
			{
				
			}
			else if (store.inZone1State())
			{
				if ( t >= 7 ) rate = 25;
 else if ( t >= 4 ) rate = 23;
 else if ( t >= 1 ) rate = 17;

			}
			else if (store.inZone2State())
			{
				
			}
			else
			{
				if ( t >= 7 ) rate = 35;
 else if ( t >= 4 ) rate = 30;
 else if ( t >= 1 ) rate = 22;

			}
			return rate;

    },
    getTax: function(callback) {

			if (!store.fetchTax) {
			    if (callback) {
				callback();
			    }
			    return;
			}
			var request = new Json.Remote(
			    '/index.php?js=hak_tax_lookup&s=null',
			    {
				method:'get',
				onComplete: function(jsonObj) {
				    $extend(store.taxCache, jsonObj);
				    if (callback) {
					callback();
				    }
				},
				onFailure: function(xhr) {
				    if (callback) {
					callback();
				    }

				}

			    }
			).send();

    },
    taxRate: function() {
			var zip = $("zip").value;
			var taxRate = (store.taxCache[zip]) ? store.taxCache[zip] : store.defaultTaxRate;
			return taxRate;
    },
    // figure out the shipping state
    inZone1State: function() {
			var shippingState;
			if ($("differentAddress").checked) {
			    shippingState = store.selectValue($("shippingState"));
			} else {
			    shippingState = store.selectValue($("state"));
			}
			var result = (store.zone1States.contains(shippingState)) ? true : false;
			return result;
    },
    // figure out the shipping state
    inZone2State: function() {
			var shippingState;
			if ($("differentAddress").checked) {
			    shippingState = store.selectValue($("shippingState"));
			} else {
			    shippingState = store.selectValue($("state"));
			}
			var result = (store.zone2States.contains(shippingState)) ? true : false;
			return result;
    },
    shippingToggle: function(visible, animate) {
			var show = visible || ($("differentAddress").checked && $("wineryPickup").checked == false);
			animate = (animate) ? true : false;
			var field = $('shippingFields');
			field.setStyle('overflow', 'hidden');
			store.shippingFieldsSize =  store.shippingFieldsSize || field.getSize(); //save original height
			var height = field.getSize().size.y; // get current height
			var heightChange = new Fx.Styles(field, {duration:600, transition: Fx.Transitions.linear});
			if (!!show) {
			    if (animate) {
				heightChange.start({
						       'height': [height,store.shippingFieldsSize.size.y],
						       'opacity': [0, 1]
						   });
			    } else {
				field.setStyle('height', store.shippingFieldsSize.size.y + 'px');
			    }
			} else {
			    if (animate) {
				heightChange.start({
						       'height': [height,0],
						       'opacity': [1, 0]
						   });
			    } else {
				field.setStyle('height', 0);
			    }
			}
    },
    // the wine selections
    selections:[],
    // prepare the shop
    prepare: function() {
			// build the wine selection objects
			$$("div.wineSelection").each(function(selection, i){
							 var newWine = new wineSelection(selection);
							 //attach event listener to input and select
							 newWine.input.onkeyup =
							     newWine.input.onkeydown =
							     newWine.select.onchange = store.update.bindAsEventListener(newWine);


							 // Update bottles and totals
							 store.totalBottles += newWine.getBottles();
							 store.subTotal += newWine.getSubTotal();
							 newWine.updateSubTotal();

							 // add wine to sleections array
							 store.selections.push(newWine);
						     });
			//attach event listener to state drop downs and shipping checkboxes
			$("shippingState").onchange =
			    $("state").onchange = store.shippingChange.bindAsEventListener();

			$("zip").onkeyup =
			    $("zip").onchange = store.taxChange.bindAsEventListener();

			$("zip").onkeyup =
			    $("zip").onchange =
			    $("zip").onblur = store.checkClubDiscount.bindAsEventListener();

			$("storeEmail").onblur = store.checkClubDiscount.bindAsEventListener();

			$E('input[type="reset"]').onclick = store.clearBottles.bindAsEventListener();

			$("wineryPickup").onclick = store.wineryPickup.bindAsEventListener($("wineryPickup"));
			$("differentAddress").onclick = store.differentAddress.bindAsEventListener($("differentAddress"));

			// update everything
			store.getTax(function() {
					 store.shippingToggle(null, false);
					 store.getClubDiscount(function() {
								   store.updateAll();
							       });
				     });
    },
    checkClubDiscount: function() {
			store.getClubDiscount(function() {
						  store.updateDiscount();
						  store.updateShipping();
						  store.updateTax();
						  store.updateTotal();
					      } );
		    },
		    getClubDiscount: function(callback) {

			if (!store.lookupDiscount) {
			    store.clubDiscount = store.defaultClubDiscount;
			    if (callback) {
						callback();
			    }
			    return;
			}

			var zip = $("zip").value;
			var email = $("storeEmail").value;
			if (!!(zip.length > 4)  && !!email) {
			    var cacheKey = email + zip +'';
			    if (store.discountCache[cacheKey] !== undefined && store.levelCache[cacheKey] !== undefined) {
						store.clubDiscount = store.discountCache[cacheKey];
						store.clubLevel = store.levelCache[cacheKey];
						if (callback) {
						    callback();
						}
			    } else {
						var request = new Json.Remote(
						    '/index.php?js=hak_get_discount&hak_wine_email='+encodeURIComponent(email) + '&hak_wine_zipcode='+ encodeURIComponent(zip),
						    {
									method:'get',
									onComplete: function(jsonObj) {
											store.clubLevel = jsonObj.level;
									    store.clubDiscount = jsonObj.discount;
									    store.discountCache[cacheKey] = jsonObj.discount;
									    store.levelCache[cacheKey] = jsonObj.level;
									    if (callback) {
												callback();
									    }
									}
						    }
						).send();
			    }
			} else {
			    store.clubDiscount = 0;
			    store.clubLevel = 0;
			    if (callback) {
						callback();
			    }
			}
    },
    update: function(evt) {
			this.updateSubTotal();
			store.updateAll();
    },
    clearBottles: function() {
			store.selections.each(function(selection) {
						  selection.setBottles(0);
						  selection.updateSubTotal();
					      });
			store.updateAll();
    },
    updateAll:function() {
			store.updateBottles();
			store.updateSubTotal();
			store.updateDiscount();
			store.updateShipping();
			store.updateTax();
			store.updateTotal();
    },
    shippingChange: function() {
			store.updateShipping();
			store.updateTax();
			store.updateTotal();
    },
    taxChange: function() {
			store.updateTax();
			store.updateTotal();
    },
    wineryPickup: function() {
			if (this.checked) {
			    $("differentAddress").checked = false;
			    store.shippingToggle(false, true);
			}
			store.shippingChange();
    },
    differentAddress: function() {
			if (this.checked) {
			    $("wineryPickup").checked = false;
			    store.shippingToggle(true, true);
			} else {
			    store.shippingToggle(false, true);
			}
			store.shippingChange();
    },
    updateBottles: function() {
			var bottles = 0;
			var shippingBottles = 0;
			store.selections.each(function(selection) {
						  var theBottles = selection.getBottles();
						  bottles += theBottles;
						  shippingBottles += (selection.chargeShipping) ? theBottles : 0;
					      });
			$E("span", "totalWine").innerHTML = bottles + " bottles";
			$E("input", "totalWine").value = bottles + " bottles";
			store.totalBottles = bottles;
			store.shippingBottles = shippingBottles;
    },
    updateSubTotal: function() {
			var subTotal = 0;
			store.selections.each(function(selection) {
						  subTotal += selection.getSubTotal();
					      });
			$E("span", "subtotal$").innerHTML = "$" + subTotal.toFixed(2);
			$E("input", "subtotal$").value = "$" + subTotal.toFixed(2);
			store.subTotal = subTotal;
    },
    updateDiscount: function() {
			// get the club dicountrate
			var  clubDiscountRate = store.clubDiscount;
			// do they get a case discount?
			var caseDiscountRate = (store.totalBottles > 11) ? store.caseDiscount : 0;
			if (store.totalBottles > 5 && store.totalBottles < 12)
			{
				caseDiscountRate = store.halfCaseDiscount;
			}

			// get total discount rate depending on exclusive flag
			var totalDiscountRate = store.calculateTotalDiscount(clubDiscountRate,caseDiscountRate, store.exclusiveDiscount);
			// calculate discounts
			var caseDiscount = store.subTotal * ( caseDiscountRate / 100 );
			var clubDiscount = store.subTotal * ( clubDiscountRate / 100 );
			var totalDiscount = store.subTotal * ( totalDiscountRate / 100 );

			if (store.showCaseDiscount(clubDiscountRate) && caseDiscountRate > 0 ) {
			    // Update the case discount
			    $E("span", "caseDiscount").innerHTML = "-$" + caseDiscount.toFixed(2);
			    $E("input", "caseDiscount").value = "-$" + caseDiscount.toFixed(2);
			    $E("em", "caseDiscount").innerHTML = caseDiscountRate + '%';
			    $("caseDiscount").setStyle("display", "block");

			} else {
			    $("caseDiscount").setStyle("display", "none");
			}

			// Update club discount
			$E("span", "clubDiscount").innerHTML = "-$" + clubDiscount.toFixed(2);
			$E("input", "clubDiscount").value = "-$" + clubDiscount.toFixed(2);
			$E("em", "clubDiscount").innerHTML = clubDiscountRate + '%';
			// display or don't display clubDiscount
			var clubDiscountDisplay = (!!clubDiscountRate) ? "block" : "none";

			$("clubDiscount").setStyle("display", clubDiscountDisplay);

			$$("div.clubRelease").each(function(selection,i){
				$(selection).setStyle('display', clubDiscountDisplay);
			});

			store.discount = totalDiscount;
    },
    updateTax: function() {
			var tax = 0;
			var rate = store.taxRate();
			var displayRate = rate * 100;
			tax = (store.subTotal - store.discount) * rate;
			$E("span", "tax").innerHTML = "$" + tax.toFixed(2);
			$E("input", "tax").value = "$" + tax.toFixed(2);
			$E("em", "tax").innerHTML = Math.round(displayRate * 100)/100 + '%';
			store.tax = tax;
    },
    updateShipping: function() {
			store.shipping = 0;
			if (!$("wineryPickup").checked) {
			    var calcBottles = store.shippingBottles;
			    store.calculateShipping(calcBottles);
			} else {
			    store.shipping = 0;
			}


			$E("span", "totalShipping").innerHTML = "$" + store.shipping.toFixed(2);
			$E("input", "totalShipping").value = "$" + store.shipping.toFixed(2);
    },
    updateTotal: function() {
			var total = store.subTotal - store.discount + store.tax + store.shipping;
			if (total != store.total) {
			    $E("span", "grandTotal").innerHTML = "$" + total.toFixed(2);
			    $E("input", "grandTotal").value = "$" + total.toFixed(2);
			    store.total = total;
			}
    },
    selectValue: function(select) {
			var value = null;
			if (!select.value) {
			    value = select.options[select.selectedIndex].innerText;
			} else {
			    value = select.value;
			}
			return value;
    },
    calculateShipping: function(t) {
			store.shipping += store.shippingRate(t);
			if (t > 12) {
			    t -= 12;
			} else {
				t=0;
			}
			if (t > 0) {
			    store.calculateShipping(t);
			}
    },
    calculateTotalDiscount: function(clubRate, caseRate, exclusive) {
			var totalRate = clubRate + caseRate;

			if (!!clubRate && !!exclusive) {
			    totalRate = clubRate;
			}
			return totalRate;
    },
    showCaseDiscount: function(clubRate) {
			if (!!clubRate && store.exclusiveDiscount) {
			    return false;
			}
			return true;
    }
};

var wineSelection = function(container) {
    var _input = $(container).getElement("input.zemText");
    var _select = $(container).getElement("select");
    this.input = _input;

    this.select = _select;
    this.container = container;
    this.chargeShipping = $(container).hasClass("noShipping") ? false : true;
    this.name = this.input.id;
    this.getPrice = function () {
			var price = $(container).getElement("span.winePrice").getText();
			price = price.match(/^\$(.*)/)[1];
			return price.toFloat(2);
    };

    this.getInventory = function() {
    	var inv = $(container).getElement("span.wineInventory").getText();
    	inv = isNaN(parseInt(inv)) ? -1 : inv;
    	return inv;
    }

    this.getBottles = function() {
			var value = isNaN(parseInt(_input.value)) ? 0 : _input.value;
			value = (value < 0) ? value * -1 : value;
			var bottles = value * store.caseSelect[store.selectValue(_select)];
			var inv = this.getInventory();
			if (inv > 0 && inv < bottles) {
				bottles = inv;
				this.setBottles(bottles);
			}
			return bottles;
    };

    this.setBottles = function(bottles) {
			var value = isNaN(parseInt(bottles)) ? 0 : bottles;
			value = (value < 0) ? value * -1 : value;
			if (bottles % 12 == 0) {
				_input.value = (value/12);
				_select.options[0].selected = true;
			}
			else {
				_input.value = value;
				_select.options[1].selected = true;
			}
    };

    this.getSubTotal = function() {
			return (this.getBottles() * this.getPrice());
    };

    this.updateSubTotal = function() {
			var subTotal = $(container).getElement("div.wineSubTotal");
			var subTotalField = $(container).getElement("div.wineSubTotalField input");
			subTotal.innerHTML = "$" + this.getSubTotal().toFixed(2);
			subTotalField.value = "$" + this.getSubTotal().toFixed(2);
    };

    this.isNumber = function(evt) {
			var charCode = (evt.which) ? evt.which : evt.keyCode;
			if (charCode > 31 && (charCode < 48 || charCode > 57)) {
			    return false;
			}
			return true;
    };

    this.input.onkeypress = this.isNumber.bindAsEventListener(this);

    return this;
};

window.addEvent('domready', function(){
	if ($E("body.store form.zemContactForm")) {
//		store.zone1States = ["Washington"];
//		store.exclusiveDiscount = true;
		store.prepare();
	}
});
