var logError = function(e,myLog) {
	if (!myLog) {
		myLog = '/Admin/logs/debug.log';
	}
	//alert(e);
	parameters = {
log:myLog,
message:e
	},
	pars = $H(parameters).toQueryString();
	myAjax = new Ajax.Request('logEvent.php',{method:'post',parameters:pars});
	//try {
	throw(e);
	//} catch(e) {alert(e);}
};
var initCart=function(){
	if (!document.all&&!document.getElementById) {
		return false;
	}
	else {
		var myCart = new shoppingCart();
		//floatObject();
		document.getElementById("float_area").style.display='block';
	}
}
shoppingCart = Class.create();
shoppingCart.prototype = {
	// 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' : '%'};
		myMeals = document.getElementsByClassName('myMenuItems');
		if (myMeals.length > 0) {
			this.myType = 'meals';
			this.sidesPrice = parseFloat($('mysidesPrice').value)||0;
			this.mySideCount = parseFloat($('mysideCount').value)||0;
		} else {
			myMeals = document.getElementsByClassName('mySideItems');
			this.myType = 'sides';
			this.mealsPrice = parseFloat($('mymealsPrice').value)||0;
			this.myFullCount = parseFloat($('myfullCount').value)||0;
			this.myHalfCount = parseFloat($('myhalfCount').value)||0;
			this.fitPrice = parseFloat($('myfitPrice').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);		// array with menu id, version id and version type
			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.upgrades=$('upgrade'+myIdNum[3]).value.split(',');
			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);
		$A(document.getElementsByClassName('fit_solutions')).each(function(fitItem) {
			fitItem.onchange = this.updateFitQty.bindAsEventListener(this);
		}.bind(this));
		myAjax = new Ajax.Request('lookup_upgrades.php',{asynchronous:false});
		eval("var upgrades="+myAjax.transport.responseText);
		upgrade_types = upgrades.partition(function(upgrade) {
			switch (upgrade.upgrade_type_id) {
				case 1:
					return true;
				case 2:
					return false;
				default:
					return false;
			}
		});
		perMeal = upgrade_types[0];
		perMeal = perMeal.partition(function(upgrade) {
			switch (upgrade.link_to_menu) {
				case 'Y':
					return true;
				case 'N':
					return false;
				default:
					return false;
			}
		});
		perRes = upgrade_types[1];
		perMealMenu = perMeal[0];
		perMeal = perMeal[1];
		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;
		});
		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;
		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.allNatUpgrade = $('all_nat_upgrade');
		this.wholeWheatUpgrade = $('whole_wheat_upgrade');
		this.minMeals = parseInt($('myMinMeals').value)||0;
		this.allNatUpgrade.onchange=this.updateTotal.bind(this);
		if ($('fit_menu_checkbox')) $('fit_menu_checkbox').onchange=this.updateFitMenuType.bind(this);
		this.wholeWheatUpgrade.onchange=this.updateTotal.bind(this);
		this.assemblyUpgrade = ($('myTogo') && $('myTogo').value) ? $('myTogo').value : 'N';
		this.element = $('float_area');
		myDims = Element.getDimensions(this.element);
		this.myWidth = myDims.width;
		this.myHeight = myDims.height;
		myBottomPos = Position.cumulativeOffset($('footer'));
		this.bottom = (myBottomPos[1] - this.myHeight);
		myTopPos = Position.cumulativeOffset($('floatTop'));
		myTopDims = Element.getDimensions($('floatTop'));
		this.top = (myTopPos[1] + myTopDims.height);
		this.mainAreaPos = Position.cumulativeOffset($('mainArea'));
		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() {
		myPosition = Position.cumulativeOffset(this.element);
		xPos = (this.mainAreaPos[0]);
		yPos = myPosition[1];
		yPos += (document.body.scrollTop + ((document.body.clientHeight+this.myHeight)/2) - this.myHeight - yPos - 10)/8;
		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.value)||0;
					e.target.value=myItem.qty;
					return true;
				}
			}.bind(this));
			//setTimeout(function(){this.updateTotal()}.bind(this),1);
			this.updateTotal();
		} catch(e) {logError(e);}
	},
	updateFitQty:function(e) {
		try {
			if (!e.target) e.target = e.srcElement;
			e.target.value=parseFloat(e.target.value)||0;
			var myRE = /(\d+)-(\d+)/;
			var myIdNum = myRE.exec(e.target.id);		// array with fit menu id, limits
			var limit=parseFloat(myIdNum[2]);
			if (!limit) limit = 5;
			if (e.target.value > limit) {
				alert('The maximum for this item is '+limit);
				e.target.value = limit;
			}
			this.updateTotal();
		} catch(err) {logError(err);}
	},
	updateFitMenuType:function(e) {
		try {
			if (!e.target) e.target = e.srcElement;
			this.updateTotal();
		} catch(err) {logError(err);}
	},
	updateTotal:function() {
		try {
			subtotal=0;
			if ($('fit_menu_checkbox') && $('fit_menu_checkbox').checked==true) {
				$A(document.getElementsByClassName('fit_solutions')).each(function(el){el.disabled=false;el.style.display='block';});
				$('order_instructions').style.display='none';
				$('order_instructions_fit').style.display='block';
				$A(document.getElementsByClassName('fit_category_select_num')).each(function(el){el.style.display='inline';});
				$A(document.getElementsByClassName('fit_category_select_done')).each(function(el){el.style.display='none';});
			} else {
				$A(document.getElementsByClassName('fit_solutions')).each(function(el){el.disabled=true;el.style.display='none'});
				$('order_instructions').style.display='block';
				$('order_instructions_fit').style.display='none';
				$A(document.getElementsByClassName('fit_category_select_num')).each(function(el){el.style.display='none';});
				$A(document.getElementsByClassName('fit_category_select_done')).each(function(el){el.style.display='none';});
			}
			if (this.myType=='meals') {
				this.mealsPrice=0;
				this.myFullCount=0;
				this.myHalfCount=0;
				if ($('fit_menu_checkbox') && $('fit_menu_checkbox').checked==true)
					this.fitPrice=parseFloat($('fitPrice').value)||0;
				else
					this.fitPrice=0;
			} else {
				this.sidesPrice=0;
				this.mySideCount=0;
			}
			this.allNatBeefPrice=0;
			this.allNatChickenPrice=0;
			this.wholeWheatPrice=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.assemblyPrice=(0);
			// when finding prices, we only care about the items that have a qty > 0
			// this will reduce our iterations greatly
			/*
			myItems = this.myItems.findAll(function(myItem) {
				return (myItem.qty>0);
			});
			// get an array of the prices
			prices = myItems.pluck('price');
			// get an array of the qtys
			qtys = myItems.pluck('qty');
			// create an array of arrays, [[price,qty],[price,qty]]
			pricesQtys = prices.zip(qtys);
			*/
			if (this.myType=='meals') {
				myItems = this.myItems.partition(function(myItem) {
					return (myItem.versionType==1);
				}.bind(this));
				myItems.full = myItems[0];
				myItems.half = myItems[1];
				[myItems.full,myItems.half].each(function(myItemSize) {
					myItemSize.each(function(myItem) {
						if (myItem.versionType==1) {
							this.myFullCount += myItem.qty;
							myType='full';
						} else {
							this.myHalfCount += myItem.qty;
							myType='half';
						}
						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.indexOf(upgrade.upgrade_id) > -1) {
								switch (upgrade.upgrade_id) {
									case 1:
										if (this.allNatUpgrade.checked==true) {
											var myPrice=parseFloat(upgrade.price*myItem.qty)||0;
											this.allNatBeefPrice+=myPrice
											upgrade.total+=myPrice;
											upgrade_cost+=parseFloat(upgrade.price)||0;
										}
										break;
									case 2:
										if (this.allNatUpgrade.checked==true) {
											var myPrice=parseFloat(upgrade.price*myItem.qty)||0;
											this.allNatChickenPrice+=myPrice
											upgrade.total+=myPrice;
											upgrade_cost+=parseFloat(upgrade.price)||0;
										}
										break;
									case 3:
										if (this.wholeWheatUpgrade.checked==true) {
											var myPrice=parseFloat(upgrade.price*myItem.qty)||0;
											this.wholeWheatPrice+=myPrice;
											upgrade.total+=myPrice;
											upgrade_cost+=parseFloat(upgrade.price)||0;
										}
										break;
									default:
										break;
								}
							}
						}.bind(this));
						// update price with upgrade_cost
						if (upgrade_cost > 0)
							$('price'+myItem.versionId).innerHTML=myItem.price.toFixed(2)+' + $'+upgrade_cost.toFixed(2);
						else
							$('price'+myItem.versionId).innerHTML=myItem.price.toFixed(2);
					}.bind(this));
				}.bind(this));
			} else {
				this.sidesPrice = pricesQtys.inject(0,function(acc,a) {return acc + (a[0] * a[1]);});
				this.sidesCount = qtys.inject(0,function(acc,qty) {return acc + qty;});
			}
			subtotal+=(this.mealsPrice+this.sidesPrice+this.wholeWheatPrice+this.allNatChickenPrice+this.allNatBeefPrice+this.assemblyPrice+this.fitPrice);
			$('myAssembly').innerHTML='$'+(this.assemblyPrice).toFixed(2);
			$('myWheat').innerHTML='$'+(this.wholeWheatPrice).toFixed(2);
			$('myAllNat').innerHTML='$'+(this.allNatChickenPrice+this.allNatBeefPrice).toFixed(2);
			$('myFitSolutions').innerHTML='$'+(this.fitPrice).toFixed(2);
			if (this.assemblyPrice > 0) {
				$('assembly').style.display='block';
			} else {
				$('assembly').style.display='none';
			}
			if (this.wholeWheatPrice > 0) {
				$('wheat').style.display='block';
			} else {
				$('wheat').style.display='none';
			}
			if ((this.allNatBeefPrice+this.allNatChickenPrice) > 0) {
				$('allNat').style.display='block';
			} else {
				$('allNat').style.display='none';
			}
			if (this.discount > 0) {
				$('discount').style.display='block';
			} else {
				$('discount').style.display='none';
			}
			if (this.fitPrice > 0) {
				$('fitsolutions').style.display='block';
			} else {
				$('fitsolutions').style.display='none';
			}
			$('myfullitems').innerHTML=this.myFullCount;
			$('myhalfitems').innerHTML=this.myHalfCount;
			$('mysides').innerHTML=this.mySideCount;
			myServings = parseFloat(this.myFullCount*6 + this.myHalfCount*3)||0;
			$('myservings').innerHTML=myServings;
			this.discount=(0);
			this.discount_minimum='';
			this.discount_type='';
			this.discounts.reverse();
			this.discounts.find(function(discount) {
				// base = this.mealsPrice+this.allNatBeefPrice+this.allNatChickenPrice+this.wholeWheatPrice+this.assemblyPrice;
				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);
						}
						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);
						}
						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);
						}
						this.discount_unit=discount.discount;
						this.discount_minimum=discount.minimum;
						this.discount_type=discount.discount_type_id;
						return true;
					}
				}
			}.bind(this));
			this.discounts.reverse();
			$('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 = parseFloat((this.mealsPrice+this.allNatBeefPrice+this.allNatChickenPrice+this.wholeWheatPrice-this.discount)/myServings)||0;
			$('myavg').innerHTML='$'+myAvg.toFixed(2);
			myNag='';
			if ($('fit_menu_checkbox') && $('fit_menu_checkbox').checked == true) {
				myNag='Eat healthy without the effort';
				$A(document.getElementsByClassName('registerButton')).each(function(el){el.disabled=false});
				$('summary_continue').src = '/images/buttons/continue.jpg';
				$('registerContinue').src = '/images/buttons/continue_big.jpg';
				var categories = $('fit_categories').value.split(',');
				categories.each(function(category,i) {
					var total = $A(document.getElementsByClassName(category)).inject(0, function(acc,cat) { return acc + parseFloat(cat.value)||0; });
					if ((category == 'Grain' && total !== 3) || (category !== 'Grain' && total !== 5)) {
						$A(document.getElementsByClassName('registerButton')).each(function(el){el.disabled=true});
						$('summary_continue').src = '/images/buttons/continue_gray.jpg';
						$('registerContinue').src = '/images/buttons/continue_big_gray.jpg';
					} else {
						$(category+'_num_to_select').style.display='none';
						$(category+'_num_selected').style.display='inline';
					}
				});
			} else if (this.myFullCount+this.myHalfCount<this.minMeals) {
				needed = this.minMeals-this.myFullCount-this.myHalfCount;
				myNag='Order <b>'+needed+'</b> or more meals to continue'; 
				$A(document.getElementsByClassName('registerButton')).each(function(el){el.disabled=true});
				$('summary_continue').src = '/images/buttons/continue_gray.jpg';
				$('registerContinue').src = '/images/buttons/continue_big_gray.jpg';
			} else {
				$A(document.getElementsByClassName('registerButton')).each(function(el){el.disabled=false});
				$('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) {
									myNag = "Order <b>"+(discount.minimum - myServings)+"</b> more Serving(s) and get <b>"+discount.discount+this.symbols[discount.discount_type]+ '</b> off';
									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;
		} catch(e) {logError(e);}
	},
	save:function() {
		try {
			var qtys=[];
			var prices=[];
			var versions=[];
			var versionIds=[];
			var menuIds=[];
			this.myItems.each(function(item,i) {
				qtys[i]=item.qty;
				prices[i]=item.price;
				versions[i]=item.versionType;
				versionIds[i]=item.versionId;
				menuIds[i]=item.menuId;
			});
			this.upgrades.perMeal.full.each(function(upgrade) {
				myInput = document.createElement('INPUT');
				myInput.type='hidden';
				myInput.name='upgrade_unit['+upgrade.upgrade_id+']['+upgrade.size+']';
				myInput.value=upgrade.price;
				$(menuItemsForm).appendChild(myInput);
				myInput = document.createElement('INPUT');
				myInput.type='hidden';
				myInput.name='upgrade_total['+upgrade.upgrade_id+']['+upgrade.size+']';
				myInput.value=upgrade.total;
				$(menuItemsForm).appendChild(myInput);

			});
			this.upgrades.perMeal.half.each(function(upgrade) {
				myInput = document.createElement('INPUT');
				myInput.type='hidden';
				myInput.name='upgrade_unit['+upgrade.upgrade_id+']['+upgrade.size+']';
				myInput.value=upgrade.price;
				$(menuItemsForm).appendChild(myInput);
				myInput = document.createElement('INPUT');
				myInput.type='hidden';
				myInput.name='upgrade_total['+upgrade.upgrade_id+']['+upgrade.size+']';
				myInput.value=upgrade.total;
				$(menuItemsForm).appendChild(myInput);

			});
			this.upgrades.perMealMenu.full.each(function(upgrade) {
				myInput = document.createElement('INPUT');
				myInput.type='hidden';
				myInput.name='upgrade_unit['+upgrade.upgrade_id+']['+upgrade.size+']';
				myInput.value=upgrade.price;
				$(menuItemsForm).appendChild(myInput);
				myInput = document.createElement('INPUT');
				myInput.type='hidden';
				myInput.name='upgrade_total['+upgrade.upgrade_id+']['+upgrade.size+']';
				myInput.value=upgrade.total;
				$(menuItemsForm).appendChild(myInput);
			});
			this.upgrades.perMealMenu.half.each(function(upgrade) {
				myInput = document.createElement('INPUT');
				myInput.type='hidden';
				myInput.name='upgrade_unit['+upgrade.upgrade_id+']['+upgrade.size+']';
				myInput.value=upgrade.price;
				$(menuItemsForm).appendChild(myInput);
				myInput = document.createElement('INPUT');
				myInput.type='hidden';
				myInput.name='upgrade_total['+upgrade.upgrade_id+']['+upgrade.size+']';
				myInput.value=upgrade.total;
				$(menuItemsForm).appendChild(myInput);
			});
			$('myqtys').value=qtys;
			$('myprices').value=prices;
			$('myversions').value=versions;
			$('myversionIds').value=versionIds;
			$('mymenuIds').value=menuIds;
			$('myAllNatBeefPrice').value=this.allNatBeefPrice;
			$('myAllNatChickenPrice').value=this.allNatChickenPrice;
			$('myWholeWheatPrice').value=this.wholeWheatPrice;
			$('myAssemblyPrice').value=this.assemblyPrice;
			$('mymealsPrice').value=this.mealsPrice;
			$('mysidesPrice').value=this.sidesPrice;
			$('myfitPrice').value=this.fitPrice;
			$('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;
		} catch(e) {logError(e);}
	}
};

