/*
Copyright (c) 2010, Taco Bell Corp. All rights reserved.
Code licensed under the MIT License:
http://www.opensource.org/licenses/mit-license.php

Author: Draftfcb Chicago
Developer: scott.boyce@draftfcb.com

Modified: R/GA San Francisco
Developer: giles.peng@rga.com
*/

var helper = new Class({
	Implements: Options,
	options: {
	},
	initialize: function(options) {
		this.setOptions(options);
	},
	printPage: function() {
		if (window.print) {
			window.print()
		} else {
			alert("Sorry, your browser doesn't support this feature. Please print from your browser's \"Print...\" menu.");
		}
	},
	formatLinks: function() {
		$$('a').each(function(item) {
			switch (item.getProperty('rel')) {
				case 'external': // open in a new window
					item.setProperty('target', '_blank');
				break;
				case 'print':
					item.addEvent('click', function(e) {
						e.stop();
						this.printPage();
						item.blur();
					}.bind(this));
				break;
			}
		}, this);
	}
});

// quickmenu
var quickmenu = new Class({
	Implements: helper,
	initialize: function() {
		$$('#show').addEvent('click', function(e) {
			e = new Event(e).stop();
			
			$$('#show').addClass('selected');
			$$('#hide').removeClass('selected');
			$$('#quickmenu ul').removeClass('hidden');

		}); // end click event for '#show'

		$$('#hide').addEvent('click', function(e) {
			e = new Event(e).stop();

			$$('#show').removeClass('selected');
			$$('#hide').addClass('selected');
			$$('#quickmenu ul').addClass('hidden');

		}); // end click event for '#hide'
		
	}
}); // end class quickmenu

// toggle the state of the "regular"/"custom" links
var toggleCustomLinks = new Class({
	Implements: helper,
	initialize: function(status, target) {
		switch(status) {
			case 'customize':
				$$('.regular-item').each(function(item) {
					if (item.getProperty('rel') == target) {
						item.removeClass('selected');
						if (tacoBell.isIE6) {
							DD_belatedPNG.fix('.regular-item');
						}
					}
				});		
				
				$$('.customize-item').each(function(item) {
					if (item.getProperty('rel') == target) {
						item.addClass('selected');
						if (tacoBell.isIE6) {
							DD_belatedPNG.fix('.selected');
						}
					}
				});
			break;
			case 'regular':
				$$('.regular-item').each(function(item) {
					if (item.getProperty('rel') == target) {
						item.addClass('selected');
						if (tacoBell.isIE6) {
							DD_belatedPNG.fix('.selected');
						}	
					}
				});		
				
				$$('.customize-item').each(function(item) {
					if (item.getProperty('rel') == target) {
						item.removeClass('selected');
						if (tacoBell.isIE6) {
							DD_belatedPNG.fix('.customize-item');
						}
					}
				});
			break;
		}
	}
}); // end class toggleCustomLinks

// set an item's ingredients to "regular"
var customizeItem = new Class({
	Implements: helper,
	initialize: function(itemID, ingredients) {
			// get the session ID
			var sessionID = document.id('session').getProperty('html');
		
			// get the object data via JSON and use it to render the HTML
			var request = new Request.JSON({
				url: '/nutrition_calc_proxy/proxy.ashx',
				method: 'post',
				data: '{"id":1, "method":"customizeItemByID", "params":{ "sessionID" : "'+sessionID+'", "itemTrackingID" : "'+itemID+'", "selectedIngredients" : '+ingredients+' }}',
				onComplete: function(jsonObj,text) {

					if (jsonObj.result.sessionID == document.id('session').getProperty('html')) {
						// render the HTML
						var updateTrayExec = new updateTray(jsonObj.result);
					}
	
					// for debugging only
					//document.id('test').setProperty('html', text);
				}
			}).setHeader('X-JSON-RPC', 'customizeItemByID').send();
	}
}); // end class customizeItem

// change the quantity of an item on the tray
var changeItemQuantity = new Class({
	Implements: helper,
	initialize: function(itemID, qty) {
		// if the quantity is negative or not an integer, delete the item
		if (qty == 0 || (qty % 1) != 0) {
			var deleteItemExec = new deleteItem(itemID);
		} else {
			if (qty < 0) {
				qty = 1;
				document.id('qty'+itemID).setProperty('value', '1');
			}
			// get the session ID
			var sessionID = document.id('session').getProperty('html');
		
			// get the object data via JSON and use it to render the HTML
			var request = new Request.JSON({
				url: '/nutrition_calc_proxy/proxy.ashx',
				method: 'post',
				data: '{"id":1, "method":"changeItemQuantity", "params":{ "sessionID" : "'+sessionID+'", "itemTrackingID" : "'+itemID+'", "newQuantity" : '+qty+' }}',
				onComplete: function(jsonObj,text) {
					document.id('item'+itemID).destroy();
					document.id('print'+itemID).destroy();

					if (jsonObj.result.sessionID == document.id('session').getProperty('html')) {
						// render the HTML
						var updateTrayExec = new updateTray(jsonObj.result);
					}
	
					// for debugging only
					//document.id('test').setProperty('html', text);
				}
			}).setHeader('X-JSON-RPC', 'changeItemQuantity').send();
		}
	}
}); // end class changeItemQuantity

// delete an item from the tray
var deleteItem = new Class({
	Implements: helper,
	initialize: function(itemID) {
							
		// get the session ID
		var sessionID = document.id('session').getProperty('html');
	
		// get the object data via JSON and use it to render the HTML
		var request = new Request.JSON({
			url: '/nutrition_calc_proxy/proxy.ashx',
			method: 'post',
			data: '{"id":1, "method":"deleteItemFromTray", "params":{ "sessionID" : "'+sessionID+'", "itemTrackingID" : "'+itemID+'" }}',
			onComplete: function(jsonObj,text) {
				document.id('item'+itemID).destroy();
				document.id('print'+itemID).destroy();
		
				// update totals
				document.id('ser').setProperty('html', Math.round(jsonObj.result.servingSize));
				document.id('cal').setProperty('html', jsonObj.result.caloriesRounded);
				document.id('fat').setProperty('html', jsonObj.result.totalFatRounded);
				document.id('sfat').setProperty('html', jsonObj.result.saturatedFatRounded);
				document.id('tfat').setProperty('html', jsonObj.result.transFatRounded);
				document.id('cho').setProperty('html', jsonObj.result.cholesterolRounded);
				document.id('sod').setProperty('html', jsonObj.result.sodiumRounded);
				document.id('car').setProperty('html', jsonObj.result.carbohydratesRounded);
				document.id('fib').setProperty('html', jsonObj.result.dietaryFiberRounded);
				document.id('sug').setProperty('html', jsonObj.result.sugarsRounded);
				document.id('pro').setProperty('html', jsonObj.result.proteinRounded);
		
				// update print
				document.id('pser').setProperty('html', Math.round(jsonObj.result.servingSize));
				document.id('pcal').setProperty('html', jsonObj.result.caloriesRounded);
				document.id('pfat').setProperty('html', jsonObj.result.totalFatRounded);
				document.id('psfat').setProperty('html', jsonObj.result.saturatedFatRounded);
				document.id('ptfat').setProperty('html', jsonObj.result.transFatRounded);
				document.id('pcho').setProperty('html', jsonObj.result.cholesterolRounded);
				document.id('psod').setProperty('html', jsonObj.result.sodiumRounded);
				document.id('pcar').setProperty('html', jsonObj.result.carbohydratesRounded);
				document.id('pfib').setProperty('html', jsonObj.result.dietaryFiberRounded);
				document.id('psug').setProperty('html', jsonObj.result.sugarsRounded);
				document.id('ppro').setProperty('html', jsonObj.result.proteinRounded);

				// for debugging only
				//document.id('test').setProperty('html', text);
			}
		}).setHeader('X-JSON-RPC', 'deleteItemFromTray').send();

	}
}); // end class changeItemQuantity

var updateTray = new Class({
	Implements: helper,
	initialize: function(menuitems) {
		// target the parent <ul>
		var el = document.id('tray-content');
		// and the print table
		var pl = document.id('printcontent');
		// empty it
		el.empty();
		// remove the print rows
		$$('.print-row').destroy();

		// build an array of items
		var k = 0;
		var itmList = [];

		menuitems.itemsOnTray.each(function(menuitem) {

			// create the nodes
			var rowDiv = new Element('div', {
				'class': 'row',
				'id': 'item'+menuitem.trackingID
			}).inject(el);
			var msieDiv = new Element('div', {
				'class': 'row-container'
			}).inject(rowDiv);
			
			// print node
			var rowTr = new Element('tr', {
				'class': 'print-row',
				'id': 'print'+menuitem.trackingID
			}).inject(pl, 'before');

			var itemDiv = new Element('div', {
				'class': 'tray-item'
			}).inject(msieDiv);

			// check to see if the item has an associated image
			if (menuitem.imageFile != '') {
				imageFile = menuitem.imageFile;
			} else {
				imageFile = ''; //todo
			}

			new Element('img', {
				'class': 'item',
				'src': 'http://static.tacobell.com/menucalculator/images/'+imageFile,
				'alt': menuitem.displayName,
				'title': '',
				'width': '60',
				'height': '60'
			}).inject(itemDiv);
			
			var nameDeleteDiv = new Element('div', {
				'class': 'item-name-delete'
			}).inject(itemDiv);
			
			new Element('h3', {
				'class': 'item-name',
				'html': '('+menuitem.quantity+') '+menuitem.displayName
			}).inject(nameDeleteDiv);
			
			var deleteSpan = new Element('span', {
				'class': 'delete-link'
			}).inject(nameDeleteDiv);

			var deleteLink = new Element('a', {
				'href': '#delete',
				'class': 'delete',
				'rel': 'item'+menuitem.trackingID,
				'events': {
					'click': function(e){
						e = new Event(e).stop();
						var deleteItemExec = new deleteItem(menuitem.trackingID);
					}
				}
			}).inject(deleteSpan);
			
			new Element('img', {
				'src': '/images/nutritioncalculator/item_close.png',
				'alt': 'Delete This Item',
				'class': 'row-delete',
				'title': '',
				'width': '19',
				'height': '19'
			}).inject(deleteLink);
			
			if (tacoBell.isIE6) {
				DD_belatedPNG.fix('.row-delete');
			}

			// build an array of ingredients
			var j = 0;
			var ingList = [];
			menuitem.ingredientList.each(function(ingItem) {
				if (ingItem.selectedID != ingItem.noneID) {
					switch (ingItem.selectedID) {
						case ingItem.regularID: //'regular':
							ingList[j] = ingItem.displayName;
							j++;
						break;
						case ingItem.extraID: //'extra':
							ingList[j] = 'Extra '+ingItem.displayName;
							j++;
						break;
					}
				}
			});
			
			// convert the ingredients list into a string
			var ings = ingList.join(', ');

			var itemIng = new Element('p', {
				'class': 'item-contents',
				'html': ings
			}).inject(itemDiv);

			// print nodes
			var rowTh = new Element('th').inject(rowTr);
			new Element('strong', {
				'html': '('+menuitem.quantity+') '+menuitem.displayName
			}).inject(rowTh);
			new Element('p', {
				'html': ings
			}).inject(rowTh);

			var detailsDiv = new Element('div', {
				'class': 'item-details'
			}).inject(msieDiv);

			var detailsList = new Element('ul', {
				'class': 'item-values'
			}).inject(detailsDiv);
				new Element('li', {
					'class': 'serving-size',
					'title': 'Serving Size (g)',
					'html': Math.round(menuitem.servingSize)
				}).inject(detailsList);
				new Element('li', {
					'class': 'calories',
					'title': 'Calories',
					'html':  menuitem.caloriesRounded
				}).inject(detailsList);
				new Element('li', {
					'class': 'total-fat',
					'title': 'Total Fat (g)',
					'html': menuitem.totalFatRounded
				}).inject(detailsList);
				new Element('li', {
					'class': 'saturated-fat',
					'title': 'Saturated Fat (g)',
					'html': menuitem.saturatedFatRounded
				}).inject(detailsList);
				new Element('li', {
					'class': 'trans-fat',
					'title': 'Trans Fat (g)',
					'html': menuitem.transFatRounded
				}).inject(detailsList);
				new Element('li', {
					'class': 'cholesterol',
					'title': 'Cholesterol (mg)',
					'html': menuitem.cholesterolRounded
				}).inject(detailsList);
				new Element('li', {
					'class': 'sodium',
					'title': 'Sodium (mg)',
					'html': menuitem.sodiumRounded
				}).inject(detailsList);
				new Element('li', {
					'class': 'carbohydrates',
					'title': 'Carbohydrates (g)',
					'html': menuitem.carbohydratesRounded
				}).inject(detailsList);
				new Element('li', {
					'class': 'dietary-fiber',
					'title': 'Dietary Fiber (g)',
					'html': menuitem.dietaryFiberRounded
				}).inject(detailsList);
				new Element('li', {
					'class': 'sugars',
					'title': 'Sugars (g)',
					'html': menuitem.sugarsRounded
				}).inject(detailsList);
				new Element('li', {
					'class': 'protein',
					'title': 'Protein (g)',
					'html': menuitem.proteinRounded
				}).inject(detailsList);

				new Element('div', {
					'class': 'spacer'
				}).inject(detailsDiv); // need this or safari won't render the "table" correctly

				// print nodes
				new Element('td', {
					'class': 'serving-size',
					'title': 'Serving Size (g)',
					'html': Math.round(menuitem.servingSize)
				}).inject(rowTr);
				new Element('td', {
					'class': 'calories',
					'title': 'Calories',
					'html':  menuitem.caloriesRounded
				}).inject(rowTr);
				new Element('td', {
					'class': 'total-fat',
					'title': 'Total Fat (g)',
					'html': menuitem.totalFatRounded
				}).inject(rowTr);
				new Element('td', {
					'class': 'saturated-fat',
					'title': 'Saturated Fat (g)',
					'html': menuitem.saturatedFatRounded
				}).inject(rowTr);
				new Element('td', {
					'class': 'trans-fat',
					'title': 'Trans Fat (g)',
					'html': menuitem.transFatRounded
				}).inject(rowTr);
				new Element('td', {
					'class': 'cholesterol',
					'title': 'Cholesterol (mg)',
					'html': menuitem.cholesterolRounded
				}).inject(rowTr);
				new Element('td', {
					'class': 'sodium',
					'title': 'Sodium (mg)',
					'html': menuitem.sodiumRounded
				}).inject(rowTr);
				new Element('td', {
					'class': 'carbohydrates',
					'title': 'Carbohydrates (g)',
					'html': menuitem.carbohydratesRounded
				}).inject(rowTr);
				new Element('td', {
					'class': 'dietary-fiber',
					'title': 'Dietary Fiber (g)',
					'html': menuitem.dietaryFiberRounded
				}).inject(rowTr);
				new Element('td', {
					'class': 'sugars',
					'title': 'Sugars (g)',
					'html': menuitem.sugarsRounded
				}).inject(rowTr);
				new Element('td', {
					'class': 'protein',
					'title': 'Protein (g)',
					'html': menuitem.proteinRounded
				}).inject(rowTr);

			// var optionsDiv = new Element('div', {
			// 	'class': 'item-options'
			// }).inject(itemDiv);

				var qtyForm = new Element('form', {
					'class': 'quantity',
					'action': './',
					'method': 'get'
				}).inject(itemDiv); //items 

				var qtyP = new Element('p').inject(qtyForm);

				var qtyLabel = new Element('label', {
					'for': 'qty'+menuitem.trackingID,
					'html': '&nbsp;'
				}).inject(qtyP);

				var qtyAcro = new Element('acronym', {
					'title': 'Quantity',
					'html': 'Qty'
				}).inject(qtyLabel, 'top');

				var qtyInput = new Element('input', {
					'type': 'text',
					'class': 'text',
					'maxlength': '2',
					'id': 'qty'+menuitem.trackingID,
					'value': menuitem.quantity
				}).inject(qtyP);
				
				var qtySubmit = new Element('a', {
					'href': '#update',
					'class': 'update',
					'rel': 'item'+menuitem.trackingID,
					'events': {
						'click': function(e){
							e = new Event(e).stop();
							var changeItemQuantityExec = new changeItemQuantity(menuitem.trackingID, document.id('qty'+menuitem.trackingID).getProperty('value'));
						}
					}
				}).inject(qtyP);

				new Element('img', {
					'src': '/images/nutritioncalculator/update_button.png',
					'alt': 'Update Quantity',
					'class': 'row-update',
					'title': '',
					'width': '52',
					'height': '20'
				}).inject(qtySubmit);

				if (tacoBell.isIE6) {
					DD_belatedPNG.fix('.row-update');
				}
				
				if (menuitem.customizable) {

					var styleP = new Element('p', {
						'class': 'item-style'
					}).inject(itemDiv);
	
					var styleStr = new Element('strong', {
						'html': 'Style: '
					}).inject(styleP);
	
					var styleReg = new Element('a', {
						'href': '#regular',
						'class': 'regular-item',
						'rel': 'item'+menuitem.trackingID,
						'html': 'Regular',
						'events': {
							'click': function(e){
								e = new Event(e).stop();
	
								// hide the appropriate panel
								target = 'customize'+menuitem.trackingID;
								document.id(target).addClass('hidden');
								
								// get the ingredients
								var i = 0;
								var ingredients = []
								menuitem.ingredientList.each(function(custom) {
									if (custom.defaultID > -1) {
										ingredients[i] = custom.defaultID;
										i++;
									}
								});

								// serialize the data for JSON
								var myJSON = JSON.encode(ingredients);
								
								// make the item regular
								var customizeItemExec = new customizeItem(menuitem.trackingID, myJSON);
								
								// ensure the proper link is highlighted
								var toggleCustomLinksExec = new toggleCustomLinks('regular', 'item'+menuitem.trackingID);
							}
						}
					}).inject(styleP);
	
					var styleCst = new Element('a', {
						'href': '#custom',
						'class': 'customize-item',
						'rel': 'item'+menuitem.trackingID,
						'html': 'Custom',
						'events': {
							'click': function(e){
								e = new Event(e).stop();
				
								// ensure panels are stacked properly
								var i = 99;
								$$('.customize').each(function(item) {
									item.setStyle('z-index',i);
									i = i-1;
								});
				
								// IE6 & IE7 use an improper method of calculating z-index
								// http://www.mail-archive.com/wsg@webstandardsgroup.org/msg26789.html
								var i = 99;
								$$('.row').each(function(item) {
									item.setStyle('z-index',i);
									i = i-1;
								});
				
								// reveal the appropriate panel
								target = 'customize'+menuitem.trackingID;
								document.id(target).removeClass('hidden');
								// ensure the most rescent panel is on top
								document.id(target).setStyle('z-index','100');
								
								// ensure the proper link is highlighted
								var toggleCustomLinksExec = new toggleCustomLinks('customize', 'item'+menuitem.trackingID);
							}
						}
					}).inject(styleP);
					
					if (tacoBell.isIE6) {
						DD_belatedPNG.fix('.regular-item');
						DD_belatedPNG.fix('.customize-item');
					}
					
					// have any ingredients been customized for this item?
					var customized = 0;
					menuitem.ingredientList.each(function(type) {
						if (type.selectedID != type.defaultID) {
							customized++;
						}
					});

					// highlight the appropriate option based on customization status
					if (customized > 0) {
						$$('#item'+menuitem.trackingID+' .regular-item').removeClass('selected');
						$$('#item'+menuitem.trackingID+' .customize-item').addClass('selected');
						document.id('item'+menuitem.trackingID).addClass('custom');
					} else {
						$$('#item'+menuitem.trackingID+' .regular-item').addClass('selected');
						$$('#item'+menuitem.trackingID+' .customize-item').removeClass('selected');
						document.id('item'+menuitem.trackingID).removeClass('custom');						
					}

				var customDiv = new Element('div', {
					'class': 'customize hidden',
					'id': 'customize'+menuitem.trackingID
				}).inject(rowDiv);
				
				var customHeaderDiv = new Element('div', {
					'class': 'customize-header'
				}).inject(customDiv);
				
				var customContentDiv = new Element('div', {
					'class': 'customize-content'
				}).inject(customDiv);
				
				if (tacoBell.isIE6) {
					DD_belatedPNG.fix('.customize-header');
					DD_belatedPNG.fix('.customize-content');
				}
	
					new Element('img', {
						'class': 'customize-text',
						'src': '/images/nutritioncalculator/customize.png',
						'alt': 'Customize',
						'title': '',
						'width': '115',
						'height': '20'
					}).inject(customContentDiv);
					
					if (tacoBell.isIE6) {
						DD_belatedPNG.fix('.customize-text');
					}
					
					var cancelLink = new Element('a', {
						'href': '#cancel',
						'class': 'cancel',
						'rel': 'customize'+menuitem.trackingID,
						'events': {
							'click': function(e){
								e = new Event(e).stop();
	
								// hide the appropriate panel
								target = 'customize'+menuitem.trackingID;
								document.id(''+target).addClass('hidden');
								
								// check to see if item is customized or not
								var result = false;
				
								// highlight the appropriate link ("regular" or "custom")
								if (result) {
									var toggleCustomLinksExec = new toggleCustomLinks('customize', 'customize'+menuitem.trackingID);
								} else {
									var toggleCustomLinksExec = new toggleCustomLinks('regular', 'customize'+menuitem.trackingID);
								}
							}
						}
					}).inject(customContentDiv);
					
						new Element('img', {
							'src': '/images/nutritioncalculator/customize_close.png',
							'class': 'customize-close',
							'alt': 'Close Customize',
							'title': '',
							'width': '15',
							'height': '15'
						}).inject(cancelLink);
						
						if (tacoBell.isIE6) {
							DD_belatedPNG.fix('.customize-close');
						}
	
					var customForm = new Element('form', {
						'id': 'fcustomize'+menuitem.trackingID,
						'action': './',
						'method': 'get'
					}).inject(customContentDiv);
	
					var customTable = new Element('table').inject(customForm);
	
					var customThead = new Element('thead').inject(customTable);
					var customTr = new Element('tr').inject(customThead);
					new Element('th', {
						'class': 'tag',
						'html': '&nbsp;'
					}).inject(customTr);
					new Element('th', {
						'html': 'None'
					}).inject(customTr);
					var customThReg = new Element('th').inject(customTr);
					new Element('acronym', {
						'title': 'Regular',
						'html': 'Reg.'
					}).inject(customThReg);
					new Element('th', {
						'html': 'Extra'
					}).inject(customTr);
					var customTr2 = new Element('tr').inject(customThead);
					var customTr2Th = new Element('th', {
						'colspan': '4'
					}).inject(customTr2);
					new Element('img', {
						'src': '/images/nutritioncalculator/customize_header_line.png',
						'alt': 'Customize Table Divider',
						'title': '',
						'width': '235',
						'height': '2'
					}).inject(customTr2Th);
					
	
					var customTbody = new Element('tbody').inject(customTable);
					
					// create a table row for each custom ingredient
					menuitem.ingredientList.each(function(option) {
							var customTrow = new Element('tr', {
								'id': 'cust'+menuitem.trackingID+option.ingredientID
							}).inject(customTbody);

							new Element('th', {
								'html': option.displayName
							}).inject(customTrow);

							var customTdNone = new Element('td').inject(customTrow);
							var customTdRegular = new Element('td').inject(customTrow);
							var customTdExtra = new Element('td').inject(customTrow);

							if (option.noneID > -1) {
								var radioNone = new Element('input', {
									'type': 'radio',
									'name': 'cs'+menuitem.trackingID+option.ingredientID,
									'id': 'cst'+menuitem.trackingID+option.noneID,
									'value': 'no',
									'title': 'No '+option.displayName
								}).inject(customTdNone);
								// FancyForm.add(radioNone);
							}

							if (option.regularID != -1) {
								var radioReg = new Element('input', {
									'type': 'radio',
									'name': 'cs'+menuitem.trackingID+option.ingredientID,
									'id': 'cst'+menuitem.trackingID+option.regularID,
									'value': 'regular',
									'title': option.displayName
								}).inject(customTdRegular);
								// FancyForm.add(radioReg);
							}

							if (option.extraID > -1) {
								var radioExtra = new Element('input', {
									'type': 'radio',
									'name': 'cs'+menuitem.trackingID+option.ingredientID,
									'id': 'cst'+menuitem.trackingID+option.extraID,
									'value': 'extra',
									'title': 'Extra '+option.displayName
								}).inject(customTdExtra);
								// FancyForm.add(radioExtra);
							}

							var selected = document.id('cst'+menuitem.trackingID+''+option.selectedID);
							selected.setProperty('checked', 'checked');
							// FancyForm.update(selected.getParent());
					}); // end custom ingrdient loop
					
					var customSubmit = new Element('a', {
						'href': '#customize',
						'class': 'submit rollover',
						'events': {
							'click': function(e){
								e = new Event(e).stop();
								var tester = '#fcustomize'+menuitem.trackingID+' input';
								var i = 0;
								var ingredients = []
								$$(tester).each(function(input) {
									if (input.getProperty('checked')) {
										ingredients[i] = input.getProperty('id').substring(4);
										i++;
									}
								});

								// serialize the data for JSON
								var myJSON = JSON.encode(ingredients);
								
								// make the item regular
								var customizeItemExec = new customizeItem(menuitem.trackingID, myJSON);
							}
						}
					}).inject(customForm);
					
					new Element('img', {
						'src': '/images/nutritioncalculator/btn_customize_off.png',
						'alt': 'Submit Customize',
						'class': 'customize-submit',
						'title': '',
						'width': '82',
						'height': '26'
					}).inject(customSubmit);
					
					if (tacoBell.isIE6) {
						DD_belatedPNG.fix('.customize-submit');
					}
	
					new Element('div', {
						'class': 'spacer'
					}).inject(customContentDiv);

			} // end if (menuitem.customizable)
	
			new Element('div', {
				'class': 'spacer'
			}).inject(msieDiv);

			itmList[k] = '('+menuitem.quantity+') '+menuitem.displayName;
			k++;

		});
		
		// update totals
		document.id('ser').setProperty('html', Math.round(menuitems.servingSize));
		document.id('cal').setProperty('html', menuitems.caloriesRounded);
		document.id('fat').setProperty('html', menuitems.totalFatRounded);
		document.id('sfat').setProperty('html', menuitems.saturatedFatRounded);
		document.id('tfat').setProperty('html', menuitems.transFatRounded);
		document.id('cho').setProperty('html', menuitems.cholesterolRounded);
		document.id('sod').setProperty('html', menuitems.sodiumRounded);
		document.id('car').setProperty('html', menuitems.carbohydratesRounded);
		document.id('fib').setProperty('html', menuitems.dietaryFiberRounded);
		document.id('sug').setProperty('html', menuitems.sugarsRounded);
		document.id('pro').setProperty('html', menuitems.proteinRounded);
		
		// update print totals
		document.id('pser').setProperty('html', Math.round(menuitems.servingSize));
		document.id('pcal').setProperty('html', menuitems.caloriesRounded);
		document.id('pfat').setProperty('html', menuitems.totalFatRounded);
		document.id('psfat').setProperty('html', menuitems.saturatedFatRounded);
		document.id('ptfat').setProperty('html', menuitems.transFatRounded);
		document.id('pcho').setProperty('html', menuitems.cholesterolRounded);
		document.id('psod').setProperty('html', menuitems.sodiumRounded);
		document.id('pcar').setProperty('html', menuitems.carbohydratesRounded);
		document.id('pfib').setProperty('html', menuitems.dietaryFiberRounded);
		document.id('psug').setProperty('html', menuitems.sugarsRounded);
		document.id('ppro').setProperty('html', menuitems.proteinRounded);
		
		// convert the items list into a string
		var itms = itmList.join(', ');

		var sum = $$('.summary p')[0];

		//sum.setProperty('html', itms);
	}
}); // end class updateTray

// display menu items for a given category
var showMenuListings = new Class({
	Implements: helper,
	initialize: function(menuitems) {
		// target the parent <ul>
		var el = document.id('menulist');
		i = 0;
		menuitems.each(function(menuitem) {
			if (menuitem.displayName != null) {
				// insert an <li> and <a> for every category name
				var itemname = new Element('li').inject(el);
				var itemlink = new Element('a', {
					'html': menuitem.displayName,
					'href': '#menu-item',
					'rel': menuitem.itemID,
					'events': {
						// add the onclick event for each menu item
						'click': function(e){
							e = new Event(e).stop();
							
							// get the session ID
							var sessionID = document.id('session').getProperty('html');
							
							// get the item ID from the link so we can use it to get the relevant menu listing
							var itmID = ''+this.getProperty('rel');
							
							// for debugging only
							//document.id('test').setProperty('html', 'rel (itmID): '+itmID);
									
							//<div class="row" id="loading"><img class="loading" src="..//images/nutritioncalculator/loading.gif" alt="Loading content" title="" width="36" height="36" /></div>
							
							// target the parent <div>
							var el = document.id('tray-content');
							var rowDiv = new Element('div', {
								'class': 'row',
								'id': 'loading'
							}).inject(el);
							var rowImg = new Element('img', {
								'class': 'loading',
								'src': '..//images/nutritioncalculator/loading.gif',
								'alt': 'Loading content&hellip;',
								'title': '',
								'width': '36',
								'height': '36'
							}).inject(rowDiv);

							// serialize the data for JSON
							//var myJSON = JSON.encode(menuitem);

							// get the object data via JSON and use it to render the HTML
							var request = new Request.JSON({
								url: '/nutrition_calc_proxy/proxy.ashx',
								method: 'post',
								data: '{"id":1, "method":"addItemToTray", "params":{ "sessionID" : "'+sessionID+'", "itemID" : '+menuitem.itemID+' }}',
								onComplete: function(jsonObj,text) {

									if (jsonObj.result.sessionID == document.id('session').getProperty('html')) {
										// render the HTML
										var updateTrayExec = new updateTray(jsonObj.result);
									}

									// for debugging only
									//document.id('test').setProperty('html', text);
								}
							}).setHeader('X-JSON-RPC', 'addListingToTray').send();

						}
					}
				}).inject(itemname);

				// check to see if the item has an associated image
				if (menuitem.imageFile != '') {
					imageFile = menuitem.imageFile;
				} else {
					imageFile = menuitem.defaultImage;
				}

				// insert the <img> tag (above the caption)
				var itemimg = new Element('img', {
					'src': 'http://static.tacobell.com/menucalculator/images/'+imageFile,
					'alt': 'Image:'+menuitem.displayName,
					'title': '',
					'width': '85',
					'height': '85'
				}).inject(itemlink, 'top');
				
				i++;
			}
		});

		width = i * 105;
		document.id('menulist').setStyle('width', width+'px');
	}
}); // end class showMenuListings

// make a scrollbar
var makeScrollbar = new Class({
	Implements: helper,
	initialize: function(direction) {
		if (direction == 'vertical') {
			// first, get the height of the entire category ul
			// then create the vertical scrollbar for categories
			var scrollSize = document.id('catlist').getSize();
			// only create the scrollbar if required
			var difference = scrollSize.y-135;
			if (difference > 0) {
				// create the scrollbar track
				var scrollbar = new Element('div', {
					'id': 'vslider'
				}).inject(document.id('catwrap'));
				// create the knob and scale its height according to how much content is hidden
				if (difference < 35) {
					var vheight = 70;
				} else if (145-difference > 42) {
					var vheight = 135-difference;
				} else {
					var vheight = 42;
				}
				var scrollknob = new Element('div', {
					'id': 'vknob'
				}).inject(scrollbar);
				new Element('div', {
					'id': 'vknobTop',
					'styles': {
						'width': '100%'
					}
				}).inject(scrollknob);
				new Element('div', {
					'id': 'vknobMiddle',
					'styles': {
						'height': vheight+'px'
					}
				}).inject(scrollknob);
				new Element('div', {
					'id': 'vknobBottom',
					'styles': {
						'width': '100%'
					}
				}).inject(scrollknob);
				var slider = new Slider(document.id('vslider'), document.id('vknob'), {
					steps: difference,
					mode: 'vertical',
					wheel: 'true',
					onChange: function(step){
						document.id('catlist').setStyle('top', -step);
						
						// for debugging only
						//document.id('test').setProperty('html', 'Vertical scrollbar value: '+(-step));
					}
				}).set(0);
				// Scroll the content element when the mousewheel is used within the
				// content or the scrollbar element.
				$$(document.id('catlist'), document.id('vslider')).addEvent('mousewheel', function(e) {
					e = new Event(e).stop();
					var step = slider.step - e.wheel * 30;
					slider.set(step);
				});
				// Stops the handle dragging process when the mouse leaves the document body.
				document.id(document.body).addEvent('mouseleave', function() { slider.drag.stop() });
			}
		} else { // default to horizontal scrollbar
			// delete any existing scrollbars
			if (document.id('hslider')) {
				document.id('hslider').dispose();
			}
			// first, get the height of the entire items ul
			// then create the horizontal scrollbar for the menu listing
			var scrollSize = document.id('menulist').getSize();
			// only create the scrollbar if required
			var difference = scrollSize.x-637;
			if (difference > 0) {
				// create the scrollbar track
				var scrollbar = new Element('div', {
					'id': 'hslider'
				}).inject(document.id('items'));
				// create the knob and scale its width according to how much content is hidden
				if (541-difference > 42) {
					var vwidth = 637-difference;
				} else {
					var vwidth = 42;
				}
				var scrollknob = new Element('div', {
					'id': 'hknob'
				}).inject(scrollbar);
				new Element('span', {
					'id': 'hknobLeft',
					'styles': {
						'float': 'left'
					}
				}).inject(scrollknob);
				new Element('span', {
					'id': 'hknobMiddle',
					'styles': {
						'width': vwidth+'px',
						'float': 'left'
					}
				}).inject(scrollknob);
				new Element('span', {
					'id': 'hknobRight',
					'styles': {
						'float': 'left'
					}
				}).inject(scrollknob);
				var slider = new Slider(document.id('hslider'), document.id('hknob'), {
					steps: difference,
					wheel: 'true',
					onChange: function(step){
						document.id('menulist').setStyle('left', -step);
						
						// for debugging only
						//document.id('test').setProperty('html', 'Horizontal scrollbar value: '+(-step));
					}
				}).set(0);
				// Scroll the content element when the mousewheel is used within the
				// content or the scrollbar element.
				$$(document.id('menulist'), document.id('hslider')).addEvent('mousewheel', function(e) {
					e = new Event(e).stop();
					var step = slider.step - e.wheel * 30;
					slider.set(step);
				});
				// Stops the handle dragging process when the mouse leaves the document body.
				document.id(document.body).addEvent('mouseleave', function() { slider.drag.stop() });
			} else { //make sure any left adjustment is removed if no scrollbar
				document.id('menulist').setStyle('left', 0);				
			} 
		}
	}
}); // end class makeScrollbar

// display menu categories
var showCategories = new Class({
	Implements: helper,
	initialize: function(categories) {
		// target the parent <ul>
		var el = document.id('catlist');
		categories.each(function(category) {
			if (category.name != null) {
				// insert an <li> and <a> for every category name
				var fullname = new Element('li').inject(el);
				var desc = new Element('a', {
					'html': category.name,
					'href': '#category',
					'rel': category.id,
					'events': {
						// IE6 isn't correctly applying pseudo-classes to generated content
						// so do it here:
						'mouseover': function(){
							this.addClass('iehover');
						},
						'mouseout': function(){
							this.removeClass('iehover');
						},
						// add the onclick event for each menu category
						'click': function(e){
							e = new Event(e).stop();
							$$('#catlist a').removeClass('selected');
							this.removeClass('iehover');
							this.addClass('selected');
							
							// Category Name removed
							// $$('#items h2 strong').setProperty('html', category.name);
							
							// get the category ID from the link so we can use it to get the relevant menu listing
							var catID = ''+this.getProperty('rel');
							
							// for debugging only
							//document.id('test').setProperty('html', 'rel (catID): '+catID);
							
							// remove any current menu listing
							document.id('menulist').empty();
		
							var el = document.id('menulist');
							var newLi = new Element('li').inject(el);
							var newImg = new Element('img', {
								'class': 'loading',
								'src': '/images/nutritioncalculator/loading.gif',
								'alt': 'Loading content&hellip;',
								'title': '',
								'width': '36',
								'height': '36'
							}).inject(newLi);

							// get the object data via JSON and use it to render the HTML
							var request = new Request.JSON({
								url: '/nutrition_calc_proxy/proxy.ashx',
								method: 'post',
								data: '{"id":1, "method":"getMenuListing", "params":{ "categoryID" : '+catID+' }}',
								onComplete: function(jsonObj,text) {
									// remove the throbber
									var el = $$('#menulist li');
									el.destroy();

									var showMenuListingsExec = new showMenuListings(jsonObj.result.menuListings);

									// menu listing may be bigger than the visible area, so we make a scrollbar
									var makeScrollbarExec = new makeScrollbar('horizontal');
							
									// for debugging only
									//document.id('test').setProperty('html', 'categoryID: '+jsonObj.result.id);
								}
							}).setHeader('X-JSON-RPC', 'getMenuListing').send();

						}
					}
				}).inject(fullname);
			}

		});

		// category list may be bigger than the visible area, so we make a scrollbar
		var makeScrollbarExec = new makeScrollbar('vertical');

	}
}); // end class showCategories

// get menu categories
var menuCategories = new Class({
	Implements: helper,
	initialize: function() {
		
		// alert("Menu Catagories make call to proxy");
		// get the object data via JSON and use it to render the HTML
		var request = new Request.JSON({
			url: '/nutrition_calc_proxy/proxy.ashx',
			method: 'post',
			data: '{"id":1, "method":"getMenuCategories", "params":{ /* void */ }}',
			onComplete: function(jsonObj,text) {
				// remove the throbber
				var el = $$('#catlist li');
				el.destroy();
				// show the category list
				var showCategoriesExec = new showCategories(jsonObj.result.menuCategories);
				// get the category ID from the first list item's link so we can use it to get the relevant menu listing
				var catID = $$('#catlist a')[0].getProperty('rel');
				var catName = $$('#catlist a')[0].getProperty('html');
				// highlight the first list item on page load
				$$('#catlist a').removeClass('selected');
				$$('#catlist a')[0].addClass('selected');
				$$('#items h2 strong').setProperty('html', catName);

				// get the object data via JSON and use it to render the HTML
				var request = new Request.JSON({
					url: '/nutrition_calc_proxy/proxy.ashx',
					method: 'post',
					data: '{"id":1, "method":"getMenuListing", "params":{ "categoryID" : '+catID+' }}',
					onComplete: function(jsonObj,text) {
						// remove the throbber
						var el = $$('#menulist li');
						el.destroy();
						// remove any current menu listing (in case someone was quick with the clicking)
						document.id('menulist').empty();
						// show the menu listing
						var showMenuListingsExec = new showMenuListings(jsonObj.result.menuListings);
	
						// menu listing may be bigger than the visible area, so we make a scrollbar
						var makeScrollbarExec = new makeScrollbar('horizontal');
					}
				}).setHeader('X-JSON-RPC', 'getMenuListing').send();

			}
		}).setHeader('X-JSON-RPC', 'getMenuCategories').send();
	}
}); // end class menuCategories

var getNewTray = new Class({
	Implements: helper,
	initialize: function() {
		// get the object data via JSON and use it to render the HTML
		var request = new Request.JSON({
			url: '/nutrition_calc_proxy/proxy.ashx',
			method: 'post',
			data: '{"id":1, "method":"getNewTray", "params":{ /* void */ }}',
			onRequest: function() {
				//<li><img class="loading" src="..//images/nutritioncalculator/loading.gif" alt="Loading content" title="" width="36" height="36" /></li>
				
				// target the parent <ul>s
				var el = document.id('catlist');
				var newLi = new Element('li').inject(el);
				var newImg = new Element('img', {
					'class': 'loading',
					'src': '/images/nutritioncalculator/loading.gif',
					'alt': 'Loading content&hellip;',
					'title': '',
					'width': '36',
					'height': '36'
				}).inject(newLi);
				
				var el = document.id('menulist');
				var newLi = new Element('li').inject(el);
				var newImg = new Element('img', {
					'class': 'loading',
					'src': '/images/nutritioncalculator/loading.gif',
					'alt': 'Loading content&hellip;',
					'title': '',
					'width': '36',
					'height': '36'
				}).inject(newLi);
			},
			onComplete: function(jsonObj,text) {								
				// store the session ID in the page
				document.id('session').setProperty('html', jsonObj.result.sessionID);
		
				// reset totals
				document.id('ser').setProperty('html', jsonObj.result.servingSize);
				document.id('cal').setProperty('html', jsonObj.result.caloriesRounded);
				document.id('fat').setProperty('html', jsonObj.result.totalFatRounded);
				document.id('sfat').setProperty('html', jsonObj.result.saturatedFatRounded);
				document.id('tfat').setProperty('html', jsonObj.result.transFatRounded);
				document.id('cho').setProperty('html', jsonObj.result.cholesterolRounded);
				document.id('sod').setProperty('html', jsonObj.result.sodiumRounded);
				document.id('car').setProperty('html', jsonObj.result.carbohydratesRounded);
				document.id('fib').setProperty('html', jsonObj.result.dietaryFiberRounded);
				document.id('sug').setProperty('html', jsonObj.result.sugarsRounded);
				document.id('pro').setProperty('html', jsonObj.result.proteinRounded);
		
				// reset print totals
				document.id('pser').setProperty('html', jsonObj.result.servingSize);
				document.id('pcal').setProperty('html', jsonObj.result.caloriesRounded);
				document.id('pfat').setProperty('html', jsonObj.result.totalFatRounded);
				document.id('psfat').setProperty('html', jsonObj.result.saturatedFatRounded);
				document.id('ptfat').setProperty('html', jsonObj.result.transFatRounded);
				document.id('pcho').setProperty('html', jsonObj.result.cholesterolRounded);
				document.id('psod').setProperty('html', jsonObj.result.sodiumRounded);
				document.id('pcar').setProperty('html', jsonObj.result.carbohydratesRounded);
				document.id('pfib').setProperty('html', jsonObj.result.dietaryFiberRounded);
				document.id('psug').setProperty('html', jsonObj.result.sugarsRounded);
				document.id('ppro').setProperty('html', jsonObj.result.proteinRounded);
			}
		}).setHeader('X-JSON-RPC', 'getNewTray').send();
	}
}); // end class getNewTray

window.addEvent('domready', function() {

	// alert("Dom Ready Function");
	
	// execute!
	var quickmenuExec = new quickmenu();
		quickmenuExec.formatLinks();
	
	if (document.id('wrapper').getProperty('class') == 'calculator') {
		var menuCategoriesExec = new menuCategories();
		var getNewTrayExec = new getNewTray();
	}

}); // end domready function
