shoppingCart = Class.create({
	// method that updates model and view when an item is inserted from any lookup
	initialize:function() {
		try {
		// go through meals, add handlers, get $ total (in case they are redirecting back to page).
		this.myItems = [];
		this.symbols = {'Dollars Off':'$', 'Percent Off':'%', 'Dollars Off Per':'$'};
		myMeals = $$('.myMenuItems');
		if (myMeals.length > 0) {
			this.myType = 'meals';
			this.sidesPrice = parseFloat($('mysidesPrice').value)||0;
			this.mySideCount = parseFloat($('mysideCount').value)||0;
			if ($('myAssemblyPriceOverride')) {
				this.assemblyPriceOverride = parseFloat($('myAssemblyPriceOverride').value)||0;
			}
			if ($('myDeliveryPriceOverride')) {
				this.deliveryPriceOverride = parseFloat($('myDeliveryPriceOverride').value)||0;
			}
		} else {
			myMeals = $$('.mySideItems');
			this.myType = 'sides';
			this.mealsPrice = parseFloat($('mymealsPrice').value)||0;
			this.myFullCount = parseFloat($('myfullCount').value)||0;
			this.myHalfCount = parseFloat($('myhalfCount').value)||0;
			this.assemblyPrice = parseFloat($('myAssemblyPrice').value)||0;
			this.deliveryPrice = parseFloat($('myDeliveryPrice').value)||0;
			this.splitPrice = parseFloat($('mySplitPrice').value)||0;
		}
		// use html elements in myMeals to create an array of usable JS objects
		myMeals.inject(this.myItems,function(array,myMeal) {
			myItem={};
			var myRE = /(\d+)-(\d+)-(\d+)/;
			myIdNum = myRE.exec(myMeal.id);		// create array of mvid, version_type_id, and menu_id
			myItem.versionId=myIdNum[1];
			myItem.versionType=myIdNum[2];
			myItem.menuId=myIdNum[3];
			myItem.price=parseFloat($('price'+myIdNum[1]).innerHTML)||0;  // get price printed in html
			myItem.discountPrice = myItem.price;
			myItem.upgrades=[];
			if ($('upgrade'+myIdNum[3]) && $('upgrade'+myIdNum[3]).value) {
				var upgrades=$('upgrade'+myIdNum[3]).value.split(',');
				upgrades.each(function(upgradeId) {
					upgradeId = parseInt(upgradeId);
					var myChecked = $('upgrade'+myItem.menuId+'-'+upgradeId).checked;
					// this if statement should be removed in time.  it is there temporarily
					// since they have only one per meal upgrade, and it is available for full
					// size only
					if (myItem.versionType==1) {
						$('upgrade'+myItem.menuId+'-'+upgradeId).observe('click',this.updateUpgrade.bindAsEventListener(this));
						myItem.upgrades.push({'upgradeId':upgradeId,'checked':myChecked});
					}
				},this);
			}
			myItem.name=$('price'+myIdNum[1]).up('.menuItem').down('h4').innerHTML;;
			myMeal.value = parseInt(myMeal.value)||0;
			myItem.qty = parseInt(myMeal.value)||0;
			myItem.element=myMeal;				// get element with qty value
			myMeal.onchange = this.updateQty.bindAsEventListener(this);
			array.push(myItem);					// add new object to this.myItems
			return array;
		}.bind(this));
		$('menuItemsForm').onsubmit=this.save.bindAsEventListener(this);
		$('summary_continue').onclick=function() {this.save();$('menuItemsForm').submit()}.bindAsEventListener(this);
		myAjax = new Ajax.Request('lookup_upgrades.php',{asynchronous:false});
		eval("var upgrades="+myAjax.transport.responseText);
		var upgrade_types = upgrades.partition(function(upgrade) {
			switch (upgrade.upgrade_type_id) {
				case 1:
					return true;
				case 2:
					return false;
				default:
					return false;
			}
		});
		var perMeal = upgrade_types[0];
		var perRes = upgrade_types[1];
		perMeal = perMeal.partition(function(upgrade) {
			switch (upgrade.link_to_menu) {
				case 'Y':
					return true;
				case 'N':
					return false;
				default:
					return false;
			}
		});
		var perMealMenu = perMeal[0];
		perMeal = perMeal[1];
		var splitPerMeal = perMeal.inject([],function(array,upgrade) {
			upgrade.sizes.each(function(size) {
				array.push({
					'upgrade_id':upgrade.upgrade_id,
					'size':size.version_type_id,
					'price':size.price
				});
			});
			return array;
		});
		var splitPerMealMenu = perMealMenu.inject([],function(array,upgrade) {
			upgrade.sizes.each(function(size) {
				array.push({
					'upgrade_id':upgrade.upgrade_id,
					'size':size.version_type_id,
					'price':size.price
				});
			});
			return array;
		});
		this.upgrades={};
		this.upgrades.perRes = perRes.inject([],function(array,upgrade) {
			upgrade.sizes.each(function(size) {
				array.push({
					'upgrade_id':upgrade.upgrade_id,
					'price':size.price
				});
			});
			return array;
		});;
		splitPerMeal = splitPerMeal.partition(function(upgrade) {
			return (upgrade.size==1);
		});
		this.upgrades.perMeal={};
		this.upgrades.perMeal.full = splitPerMeal[0];
		this.upgrades.perMeal.half = splitPerMeal[1];
		splitPerMealMenu = splitPerMealMenu.partition(function(upgrade) {
			return (upgrade.size==1);
		});
		this.upgrades.perMealMenu={};
		this.upgrades.perMealMenu.full = splitPerMealMenu[0];
		this.upgrades.perMealMenu.half = splitPerMealMenu[1];
		this.minMeals = parseInt($('myMinMeals').value)||0;
		this.assemblyUpgrade = ($('myTogo') && $('myTogo').value) ? $('myTogo').value : 'N';
		this.deliveryUpgrade = ($('myDeliv') && $('myDeliv').value) ? $('myDeliv').value : 'N';
		this.element = $('float_area');
		this.element.show();
		myDims = Element.getDimensions(this.element);
		this.myWidth = myDims.width;
		this.myHeight = myDims.height;
		myBottomPos = $('footer').cumulativeOffset();
		this.bottom = (myBottomPos[1] - this.myHeight);
		myTopPos = $('scrollTop').cumulativeOffset();
		myTopDims = Element.getDimensions($('scrollTop'));
		this.top = (myTopPos[1] + myTopDims.height);
		this.floatObject();
		myAjax = new Ajax.Request('lookup_discounts.php',{asynchronous:false});
		eval("var discounts="+myAjax.transport.responseText);
		this.thresholds = discounts.thresholds;
		this.discounts = discounts.thresholds_options;
		this.updateTotal();
		} catch(e) {logError(e);}
	},
	floatObject:function() {
		myDims = Element.getDimensions(this.element);
		this.myWidth = myDims.width;
		this.myHeight = myDims.height;
		this.myHeight = myDims.height;
		myBottomPos = $('footer').cumulativeOffset();
		this.bottom = (myBottomPos[1] - this.myHeight);
		var mainAreaPos = $('mainContent').cumulativeOffset();
		var mainAreaRight = $('mainContent').getDimensions().width + mainAreaPos[0] - this.myWidth;
		var xPos = (mainAreaRight);
		yPos = this.element.cumulativeOffset().top;
		yPos += (document.viewport.getScrollOffsets().top + ((document.viewport.getHeight()+this.myHeight)/2) - this.myHeight - yPos - 10)/8;
		calYPos = yPos;
		if ((this.top) > yPos)
			yPos = (this.top);
		else if (yPos > (this.bottom))
			yPos = (this.bottom);
		this.element.style.top=yPos+'px';
		this.element.style.left=xPos+'px';
		setTimeout(function(){this.floatObject()}.bind(this), 5);
	},
	updateQty:function(e) {
		try {
			if (!e.target) e.target = e.srcElement;
			this.myItems.find(function(myItem) {
				if (e.target == myItem.element) {
					myItem.qty = parseFloat(e.target.options[e.target.selectedIndex].value)||0;
					return true;
				}
			}.bind(this));
			this.updateTotal();
		} catch(e) {logError(e);}
	},
	updateUpgrade:function(e) {
		var myRE = /upgrade(\d+)-(\d+)/;
		var myIdNum = myRE.exec(e.element().id);
		var myMenuId = myIdNum[1];
		var myUpgradeId = myIdNum[2];
		var myChecked = e.element().checked;
		this.myItems.each(function(myItem) {
			myRE2 = new RegExp('menu[\\d]+-[\\d]+-'+myMenuId+'');
			if (myRE2.match(myItem.element.id)) {
				myItem.upgrades.find(function(myUpgrade) {
					if (myUpgrade.upgradeId == myUpgradeId) {
						myUpgrade.checked=myChecked;
						return true;
					}
				},this);
			}
		}, this);
		this.updateTotal();
	},
	updateTotal:function() {
		try {
			subtotal=0;
			if (this.myType=='meals') {
				this.mealsPrice=0;
				this.myFullCount=0;
				this.myHalfCount=0;
				this.assemblyPrice=(0);
				this.deliveryPrice=(0);
				this.splitPrice=(0);
				this.upgrades.perMeal.full.each(function(upgrade) {upgrade.total=0;});
				this.upgrades.perMeal.half.each(function(upgrade) {upgrade.total=0;});
				this.upgrades.perMealMenu.full.each(function(upgrade) {upgrade.total=0;});
				this.upgrades.perMealMenu.half.each(function(upgrade) {upgrade.total=0;});
				this.upgrades.perRes.each(function(upgrade) {upgrade.total=0});
				$('selectedMeals').update();
				myItems = this.myItems.partition(function(myItem) {
					return (myItem.versionType==1);
				}.bind(this));
				[myItems[0],myItems[1]].each(function(myItemSize) {
					myItemSize.each(function(myItem) {
						if (myItem.versionType==1) {
							this.myFullCount += myItem.qty;
							myType='full';
							myAbbr = 'L';
						} else {
							this.myHalfCount += myItem.qty;
							myType='half';
							myAbbr = 'M';
						}
						this.mealsPrice += parseFloat(myItem.qty * myItem.price)||0;
						upgrade_cost=0;
						this.upgrades.perMeal[myType].each(function(upgrade) {
							switch (upgrade.upgrade_id) {
								case 5:
									if (this.assemblyUpgrade=='Y') {
										var myPrice = parseFloat(upgrade.price*myItem.qty)||0;
										upgrade.total+=myPrice;
										this.assemblyPrice+=myPrice;
										upgrade_cost+=parseFloat(upgrade.price)||0;
									}
									break;
								default:
									break;
							}
						}.bind(this));
						this.upgrades.perMealMenu[myType].each(function(upgrade) {
							if (myItem.upgrades.collect(function(myUpgrade) {if (myUpgrade.checked) return myUpgrade.upgradeId;}).indexOf(upgrade.upgrade_id) > -1) {
								switch (upgrade.upgrade_id) {
									case 6:
										var myPrice = parseFloat(upgrade.price*myItem.qty)||0;
										upgrade.total+=myPrice;
										this.splitPrice+=myPrice;
										upgrade_cost+=parseFloat(upgrade.price)||0;
										break;
									default:
										break;
								}
							}
						}.bind(this));
						// update price with upgrade_cost
						if (upgrade_cost > 0) {
							//$('price'+myItem.versionId).update(myItem.price.toFixed(2)+' + $'+upgrade_cost.toFixed(2));
						} else {
							$('price'+myItem.versionId).update(myItem.price.toFixed(2));
						}
					}, this);
				}, this);
				this.upgrades.perRes.each(function(upgrade) {
					switch (upgrade.upgrade_id) {
						case 7:
							if (this.deliveryUpgrade=='Y') {
								var myPrice = upgrade.price;
								upgrade.total=myPrice;
								this.deliveryPrice=myPrice;
							}
						break;
					}
				},this);
			} else {
				this.sidesPrice=0;
				this.mySideCount=0;
				$('selectedSides').update();
				myItems = this.myItems.partition(function(myItem) {
					return (myItem.versionType==12);
				}.bind(this));
				[myItems[0],myItems[1]].each(function(myItemSize) {
					myItemSize.each(function(myItem) {
						if (myItem.versionType==12) {
							//myAbbr = 'L';
							myAbbr = '';
						} else {
							//myAbbr = 'M';
							myAbbr = '';
						}
						if (myItem.qty > 0) {
							$('selectedSides').insert(new Element('li').update('<span class="details">'+myItem.qty+' <strong>'+myAbbr+'</strong> '+myItem.name+'</span><span class="price">$'+(myItem.price*myItem.qty).toFixed(2)+'</span>'));
						}
						this.sidesPrice += parseFloat(myItem.qty * myItem.price)||0;
					},this);
				},this);
			}
			if (this.assemblyPriceOverride) this.assemblyPrice = this.assemblyPriceOverride;
			if (this.deliveryPriceOverride) this.deliveryPrice = this.deliveryPriceOverride;
			subtotal+=(this.mealsPrice+this.sidesPrice+this.assemblyPrice+this.splitPrice+this.deliveryPrice);
			$('myAssembly').innerHTML='$'+(this.assemblyPrice).toFixed(2);
			$('myDelivery').innerHTML='$'+(this.deliveryPrice).toFixed(2);
			$('mySplit').innerHTML='$'+(this.splitPrice).toFixed(2);
			if (this.assemblyPrice > 0) {
				$('assembly').style.display='block';
			} else {
				$('assembly').style.display='none';
			}
			if (this.deliveryPrice > 0) {
				$('delivery').style.display='block';
			} else {
				$('delivery').style.display='none';
			}
			if (this.splitPrice > 0) {
				$('split').style.display='block';
			} else {
				$('split').style.display='none';
			}
			//$('myfullitems').innerHTML=this.myFullCount;
			//$('myhalfitems').innerHTML=this.myHalfCount;
			//$('mysides').innerHTML=this.mySideCount;
			myServings = parseFloat(this.myFullCount*6 + this.myHalfCount*3)||0;
			this.discount=(0);
			this.discount_minimum='';
			this.discount_type='';
			// we want to find the lowest threshold that has been met, so reverse the order
			this.discounts.reverse();
			this.discounts.find(function(discount) {
				base = this.mealsPrice;
				if (this.thresholds.discount_thresholds_type_id==1) {
					// based on servings
					if (discount.minimum <= myServings) {
						if (discount.discount_type_id == 1) {
							this.discount=parseFloat((discount.discount/100)*base)||0;
						} else if (discount.discount_type_id == 2) {
							this.discount=parseFloat(discount.discount);
						} else if (discount.discount_type_id == 7) {
							this.discount=parseFloat(discount.discount*myServings);
						}
						this.discount_unit=discount.discount;
						this.discount_minimum=discount.minimum;
						this.discount_type=discount.discount_type_id;
						return true;
					}
				} else if (this.thresholds.discount_thresholds_type_id==2) {
					// based on menu price
					if (discount.minimum <= this.mealsPrice) {
						if (discount.discount_type_id == 1) {
							this.discount=parseFloat((discount.discount/100)*base)||0;
						} else if (discount.discount_type_id == 2) {
							this.discount=parseFloat(discount.discount);
						} else if (discount.discount_type_id == 7) {
							// this discount type discounts by the criteria type.  Since we're
							// dealing with a criteria of dollars, the discount should be per meal
							// instead of taking $x per total dollar spent
							this.discount=parseFloat(discount.discount*(this.myFullCount+this.myHalfCount));
						}
						this.discount_unit=discount.discount;
						this.discount_minimum=discount.minimum;
						this.discount_type=discount.discount_type_id;
						return true;
					}
				} else if (this.thresholds.discount_thresholds_type_id==3) {
					// based on total meals
					if (discount.minimum <= (this.myFullCount+this.myHalfCount)) {
						if (discount.discount_type_id == 1) {
							this.discount=parseFloat((discount.discount/100)*base)||0;
						} else if (discount.discount_type_id == 2) {
							this.discount=parseFloat(discount.discount);
						} else if (discount.discount_type_id == 7) {
							this.discount=parseFloat(discount.discount*(this.myFullCount+this.myHalfCount));
						}
						this.discount_unit=discount.discount;
						this.discount_minimum=discount.minimum;
						this.discount_type=discount.discount_type_id;
						return true;
					}
				}
			}.bind(this));
			this.myItems.each(function(myItem) {
				if (myItem.qty > 0) {
					var discountPerMeal = 0;
					var myServings = (myItem.versionType==1) ? 6 : 3;
					switch (this.discount_type) {
						case 1:
							discountPerMeal = (this.discount_unit/100)*myItem.price||0;
							break;
						case 7:
							discountPerMeal = (this.discount_unit*myServings)||0;
							break;
					}
					discountPerMeal = parseFloat(discountPerMeal)||0;
					myItem.discountPrice = myItem.price-discountPerMeal;
					if (this.myType=='meals') {
						if (myItem.versionType==1) {
							myType='full';
							myAbbr = 'L';
						} else {
							myType='half';
							myAbbr = 'M';
						}
						$('selectedMeals').insert(new Element('li').update('<span class="details">'+myItem.qty+' <strong>'+myAbbr+'</strong> '+myItem.name+'</span><span class="price">$'+((myItem.discountPrice)*myItem.qty).toFixed(2)+'</span>'));
					}
				}
			},this);
			$('mydiscount').innerHTML='$'+parseFloat(this.discount).toFixed(2);
			if (this.discount_type==1) {
				$('mydiscount').innerHTML+=' ('+this.discount_unit+'%)';
			}
			if (this.discount > 0) {
				//$('discount').style.display='block';
			} else {
				$('discount').style.display='none';
			}
			subtotal-=this.discount;
			$('mysubtotal').innerHTML='$'+subtotal.toFixed(2);
			myAvg = (!myServings) ? 0 : parseFloat((this.mealsPrice-this.discount)/myServings)||0;
			$('myavg').innerHTML='$'+myAvg.toFixed(2);
			myNag='';
			// now we want to find the first threshold that has NOT been met.  reverse again
			// note we need it reversed a little further down, but we don't want it to be part
			// of a conditional statement.
			this.discounts.reverse();
			if (this.myFullCount+this.myHalfCount<this.minMeals) {
				needed = this.minMeals-this.myFullCount-this.myHalfCount;
				myNag='Please select at least '+this.minMeals+' meals'; 
				//$$('.registerButton').invoke('disable');
				//$('summary_continue').src = '/images/buttons/continue_gray.jpg';
				//$('registerContinue').src = '/images/buttons/continue_big_gray.jpg';
			} else {
				//$$('.registerButton').invoke('enable');
				//$('summary_continue').src = '/images/buttons/continue.jpg';
				//$('registerContinue').src = '/images/buttons/continue_big.jpg';
				if (this.myType=='meals') {
					// myNags
					switch (this.thresholds.discount_thresholds_type_id) {
						case 1:
							this.discounts.find(function(discount) {
								if (myServings < discount.minimum) {
									if (discount.discount_type_id==1) {
										var myDiscount = discount.discount+'%';
									} else if (discount.discount_type_id==7) {
										var myDiscount = '$'+(discount.discount*6).toFixed(2)+' or $'+(discount.discount*3).toFixed(2)+' per meal';
									} else if (discount.discount_type_id==2) {
										var myDiscount = '$'+discount.discount.toFixed(2);
									}
									myNag = "<span class='emphasize'>Order only "+((discount.minimum - myServings)/6).toFixed(0)+"</b> more Large or "+((discount.minimum - myServings)/3).toFixed(0)+" more Medium and save "+myDiscount+'</span>';
									return true;
								} else {
									return false;
								}
							}.bind(this));
							break;
						case 2:
							this.discounts.find(function(discount) {
								if (this.mealsPrice < discount.minimum) {
									myNag = "Spend <b>$"+(discount.minimum - this.mealsPrice).toFixed(2)+"</b> more on meals to get "+discount.discount+this.symbols[discount.discount_type]+ '</b> off';
									return true;
								} else {
									return false;
								}
							}.bind(this));
							break;
						case 3:
							this.discounts.find(function(discount) {
								if ((this.myFullCount+this.myHalfCount) < discount.minimum) {
									myNag = "Order <b>"+(discount.minimum - (this.myFullCount+this.myHalfCount))+"</b> more meal(s) to get <b>"+discount.discount+this.symbols[discount.discount_type]+ '</b> off';
									return true;
								} else {
									return false;
								}
							}.bind(this));
							break;
					}
				}
			}
			//$('myNags').innerHTML=myNag;
			$('myNags').innerHTML='Please select at least '+this.minMeals+' meals'; 
			if ($('float_area').scrollHeight > $('float_area').getHeight()) {
				$('float_area').setStyle({'height':$('float_area').scrollHeight+'px'});
			} else {
				var myHeight = ($('float_area').scrollHeight > 450) ? $('float_area').scrollHeight : 450;
				$('float_area').setStyle({'height':myHeight+'px'});
			}
		} catch(e) {logError(e);}
	},
	save:function() {
		try {
			var qtys=[];
			var prices=[];
			var discountPrices=[];
			var versions=[];
			var versionIds=[];
			var menuIds=[];
			var menuNames=[];
			this.myItems.each(function(item,i) {
				qtys[i]=item.qty;
				prices[i]=item.price;
				discountPrices[i]=item.discountPrice;
				versions[i]=item.versionType;
				versionIds[i]=item.versionId;
				menuIds[i]=item.menuId;
				menuNames[i]=item.name;
				if (item.upgrades.length) {
					upgrades=[];
					item.upgrades.each(function(upgrade) {
						if (upgrade.checked)
							upgrades.push(upgrade.upgradeId);
					});
					if (upgrades.length)
						$('menuItemsForm').insert(new Element('input',{type:'hidden',name:'upgrades['+item.menuId+']['+item.versionType+']',value:upgrades}));
				}
			},this);
			if (this.myType=='meals') {
				this.upgrades.perMeal.full.each(function(upgrade) {
					myInput = new Element('INPUT', {'type':'hidden','value':upgrade.price, 'name':'upgrade_unit['+upgrade.upgrade_id+']['+upgrade.size+']'});
					$('menuItemsForm').insert(myInput);
					myInput = new Element('INPUT', {'type':'hidden','value':upgrade.total, 'name':'upgrade_total['+upgrade.upgrade_id+']['+upgrade.size+']'});
					$('menuItemsForm').insert(myInput);
				});
				this.upgrades.perMeal.half.each(function(upgrade) {
					myInput = new Element('INPUT');
					myInput.type='hidden';
					myInput.name='upgrade_unit['+upgrade.upgrade_id+']['+upgrade.size+']';
					myInput.value=upgrade.price;
					$('menuItemsForm').insert(myInput);
					myInput = new Element('INPUT');
					myInput.type='hidden';
					myInput.name='upgrade_total['+upgrade.upgrade_id+']['+upgrade.size+']';
					myInput.value=upgrade.total;
					$('menuItemsForm').insert(myInput);
				});
				this.upgrades.perMealMenu.full.each(function(upgrade) {
					myInput = new Element('INPUT');
					myInput.type='hidden';
					myInput.name='upgrade_unit['+upgrade.upgrade_id+']['+upgrade.size+']';
					myInput.value=upgrade.price;
					$('menuItemsForm').insert(myInput);
					myInput = new Element('INPUT');
					myInput.type='hidden';
					myInput.name='upgrade_total['+upgrade.upgrade_id+']['+upgrade.size+']';
					myInput.value=upgrade.total;
					$('menuItemsForm').insert(myInput);
				});
				this.upgrades.perMealMenu.half.each(function(upgrade) {
					myInput = new Element('INPUT');
					myInput.type='hidden';
					myInput.name='upgrade_unit['+upgrade.upgrade_id+']['+upgrade.size+']';
					myInput.value=upgrade.price;
					$('menuItemsForm').insert(myInput);
					myInput = new Element('INPUT');
					myInput.type='hidden';
					myInput.name='upgrade_total['+upgrade.upgrade_id+']['+upgrade.size+']';
					myInput.value=upgrade.total;
					$('menuItemsForm').insert(myInput);
				});
				$('myAssemblyPrice').value=this.assemblyPrice;
				$('myDeliveryPrice').value=this.deliveryPrice;
				$('mySplitPrice').value=this.splitPrice;
				$('mymealsPrice').value=this.mealsPrice;
				$('myDiscountTotal').value=this.discount;
				$('myDiscountUnit').value=this.discount_unit;
				$('myMinimum').value=this.discount_minimum;
				$('myDiscountType').value=this.discount_type;
				$('myDiscountThresholdType').value=this.thresholds.discount_thresholds_type_id;
			} else {
				$('mysidesPrice').value=this.sidesPrice;
			}
			$('myqtys').value=qtys;
			$('myprices').value=prices;
			$('mydiscountprices').value=discountPrices;
			$('myversions').value=versions;
			$('myversionIds').value=versionIds;
			$('mymenuIds').value=menuIds;
			$('mymenuNames').value=menuNames;
		} catch(e) {logError(e);}
	}
});
