var nutritionCalculator;
var currentSandwich;
var productType;
var isSandwichPage = true;

var ProductTypes = new Object();
ProductTypes.footlong = "footlong";
ProductTypes.sixInch = "sixInch";
ProductTypes.flatbread = "flatbread";
ProductTypes.salad = "salad";
ProductTypes.mini = "mini";

var ProductOptions = new Object();
ProductOptions.bread = 'bread';
ProductOptions.cheese = 'cheeses';
ProductOptions.veggie = 'veggies';
ProductOptions.sauce = 'sauces';

var currentProductType;
var defaultProductType;
var dropMenuItemSelected = false;

var breads = new Array();
var cheeses = new Array();
var veggies = new Array();
var sauces = new Array();
var meats = new Array();
var sandwiches = new Array();
var defaultSettings = new Object();
var selectedOptions = [];
var loadOnce = false;

var categoryLookUp = new Array();
categoryLookUp['bread'] = breads;
categoryLookUp['cheeses'] = cheeses;
categoryLookUp['veggies'] = veggies;
categoryLookUp['sauces'] = sauces;
categoryLookUp['meats'] = meats;

var nutritionInfoLookUp = new Array();
nutritionInfoLookUp[0] = {id: 'serving_size', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[1] = {id: 'calories', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[2] = {id: 'calories_from_fat', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[3] = {id: 'total_fat', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[4] = {id: 'saturated_fat', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[5] = {id: 'trans_fat', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[6] = {id: 'cholesterol', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[7] = {id: 'sodium', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[8] = {id: 'carbohydrates', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[9] = {id: 'dietary_fiber', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[10] = {id: 'sugar', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[11] = {id: 'protein', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[12] = {id: 'vitamin_a', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[13] = {id: 'vitamin_c', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[14] = {id: 'calcium', value: 0.0, element: null,total:0.0};
nutritionInfoLookUp[15] = {id: 'iron', value: 0.0, element: null,total:0.0};

var saladSaucesExcludeList = new Array();
saladSaucesExcludeList[0] = 'sauces_light_mayonnaise';
saladSaucesExcludeList[1] = 'sauces_regular_mayonnaise';
saladSaucesExcludeList[2] = 'sauces_yellow_mustard';
saladSaucesExcludeList[3] = 'sauces_deli_brown_mustard';

var miniExcludeList = new Array();
miniExcludeList[0] = 'bread_9_grain_honey_oat';
miniExcludeList[1] = 'bread_italian_herbs_and_cheese';
miniExcludeList[2] = 'bread_parmesan_oreagano';
miniExcludeList[3] = 'bread_monterey_cheddar';
miniExcludeList[4] = 'bread_hearty_italian';
miniExcludeList[5] = 'bread_roasted_garlic';

var nutritionXMLLoaded = false;
var nutritionXMLLoadInProgress = false;

var showDebug = false;

var updateTimeOut;
var trackBuildClick = true;

function loadSandwich(sandwich){
    
	currentSandwich = sandwich;
	
	if(sandwich == ProductTypes.flatbread){
		productType = ProductTypes.flatbread;
		section = "external";
		isSandwichPage = false;
	}
	else if(sandwich == ProductTypes.salad){
		productType = ProductTypes.salad;
		section = "external";
		isSandwichPage = false;
	}
	else{
		productType = ProductTypes.sixInch;
		section = "internal";
		isSandwichPage = true;
	}
	
	defaultProductType = productType;
	currentProductType = defaultProductType;
	
	if(isSandwichPage){
		$('#options_nav_drop_menu').hide();
	}
	else{
	
		$('#options_nav_drop_menu').show();
		$('#options_nav').hide();
		$('#options_column_bread').hide();
		$('#options_column_cheese').css('width', '224px');
		$('#options_column_veggies').css('width', '230px');
		
		// Hide All Options and show graphic
		
		$('.options_column').hide();
		$('#subway_build_btn').hide();
		var graphic = $('<div id="nutrition_get_started"><img src="/images/nutrition_calculator/calc_choose_flavr_msg.png" width="555px" height="192px" border="0"/></div>');
		$('.options_block').append(graphic);
		
	}
	
	$(document).ready(function(){
		nutritionCalculator = new NutritionCalculator();
	});
	
};

function NutritionCalculator(){
	this.init();
};

NutritionCalculator.prototype.init = function(){
	
	// Store a reference to this class so we can call it onclick
	var ref = this; 
	
	// Customize button
	$("#customize_btn a").click(function(){
		$(this).toggleClass("active");
		$('#product_options').toggle();
		$('#product_flash').toggle();
		if($('#product_options').css('display').toString().toLowerCase() == 'block'){
			trackOmniClick(this, 'o', 'Nutrition Calculator: Your Build Button');
		}
		return false;
	});
	
	// Nutrition facts button
	var nutritionOpen = false;
	
	$("#nutrition_btn a").click(function(){
		
		//console.log("Nutrition Loaded: " + nutritionXMLLoaded);
		//console.log("XML Loaded: " + nutritionXMLLoadInProgress);
		
		if(!nutritionXMLLoaded && !nutritionXMLLoadInProgress){
			ref.loadData();
			nutritionXMLLoadInProgress = true;
			return;
		}
		
		$(this).toggleClass("active");
		$('#nutrition_info').toggle();
		if($('.print_btn').css('display').toString().toLowerCase() == 'none'){
			$('.print_btn').show();
			$('#customize_btn').show();
		}
		else{
			$('.print_btn').hide();
			$('#customize_btn').hide();
		}
		if(currentProductType == ProductTypes.flatbread || currentProductType == ProductTypes.salad){
			var display = $('#nutrition_info').css('display');
			if(display == 'none'){
				$('#customize_btn a').removeClass("active");
				$('#product_options').hide();
				$('#product_flash').show();
			}
			else{
				$('#customize_btn a').addClass("active");
				$('#product_options').show();
				$('#product_flash').hide();
			}
		}else{
			if($('#customize_btn a').attr("class") != null && $('#customize_btn a').attr("class").indexOf("active") > -1){
				$('#customize_btn a').click();
			}
		}
		return false;
	});
	
	// Print Button
	$(".print_btn").click(function(){return true;});
	$('.print_btn').hide();
	
	// Customize Button
	$('#customize_btn').hide();
	
	// Restore Defaults Button
	$('#subway_build_btn').click(function(){
		
		if(isSandwichPage){
			productType = ProductTypes.sixInch;
		}
		else{
			productType = currentProductType;
		}
		
		ref.restoreDefaults(productType, false);
		
		ref.check('product_type', ProductTypes.sixInch);
		
		if(isSandwichPage)
		{
			ref.showBread();
		}
		
		if(trackBuildClick){
			trackOmniClick(this, 'o', 'Nutrition Calculator: Subway Build Button');
		}
		
	});
	
	// Add loading icon
	$('#product_btns').append($('<div id="nutrition_loader">Loading Nutrition Facts...</div>'));
	
	// Update info array with html elements
	nutritionInfoLookUp[0].element = $('#nut_servingsize');
	nutritionInfoLookUp[1].element = $('#nut_calories');
	nutritionInfoLookUp[2].element = $('#nut_fatcalories');
	nutritionInfoLookUp[3].element = $('#nut_fat');
	nutritionInfoLookUp[4].element = $('#nut_satfat');
	nutritionInfoLookUp[5].element = $('#nut_transfat');
	nutritionInfoLookUp[6].element = $('#nut_cholesterol');
	nutritionInfoLookUp[7].element = $('#nut_sodium');
	nutritionInfoLookUp[8].element = $('#nut_carbs');
	nutritionInfoLookUp[9].element = $('#nut_fiber');
	nutritionInfoLookUp[10].element = $('#nut_sugar');
	nutritionInfoLookUp[11].element = $('#nut_protein');
	nutritionInfoLookUp[12].element = $('#nut_vita');
	nutritionInfoLookUp[13].element = $('#nut_vitc');
	nutritionInfoLookUp[14].element = $('#nut_calcium');
	nutritionInfoLookUp[15].element = $('#nut_iron');
	
};

NutritionCalculator.prototype.loadData = function(){
	$('#nutrition_loader').show();
	var ref = this;
	 $.ajax({
		type: "GET",
		url: "/nutritionXML/nutrition_db.xml",
		dataType: "xml",
		success: function(data){
			ref.onLoadDataComplete($(data));
		}
	});
};

NutritionCalculator.prototype.onLoadDataComplete = function(xml){
	
	var ref = this;
	
	// Get all of the menu options and store their values
	var optionsArray;
	
	xml.find('options').each(function(){
		// loop over all categories
		$(this).find('category').each(function(){
			
			var currentCat = $(this).attr('id');
			//var props = new Object();
			
			// loop over all items, build array based on category
			// Each array will hold all the values for each product type (6inch, fb, salad, mini)
			$(this).find('item').each(function(){
				
				var id = $(this).attr('id');
				
				switch(currentCat){
					case 'breads':
						optionsArray = breads;
					break;
					case 'cheeses':
						optionsArray = cheeses;
					break;
					case 'veggies':
						optionsArray = veggies;
					break;
					case 'sauces':
						optionsArray = sauces;
					break;
					case 'meats':
						optionsArray = meats;
					break;
				}
				
				optionsArray[id] = props = {
					name: $(this).find('name').text(),
					sixInch: [],
					footlong: [],
					flatbread: [],
					mini: [],
					salad: []
				};
				
				//Default (6inch)
				$(this).find('default').each(function(){
					$(this).each(function(){
						$(this).children().each(function(){
							optionsArray[id].sixInch[this.nodeName.toLowerCase()] = parseFloat($(this).text()).toFixed(2);
							optionsArray[id].flatbread[this.nodeName.toLowerCase()] = parseFloat($(this).text()).toFixed(2);
							optionsArray[id].footlong[this.nodeName.toLowerCase()] = parseFloat($(this).text() * 2).toFixed(2);
						});
					});
				});
				
				// Mini
				$(this).find('mini').each(function(){
					$(this).each(function(){
						$(this).children().each(function(){
							optionsArray[id].mini[this.nodeName.toLowerCase()] = parseFloat($(this).text()).toFixed(2);
						});
					});
				});
				
				// Salad
				$(this).find('salad').each(function(){
					$(this).each(function(){
						$(this).children().each(function(){
							optionsArray[id].salad[this.nodeName.toLowerCase()] = parseFloat($(this).text()).toFixed(2);
						});
					});
				});
				
			}); // End item
			
		});
		
	});
	
	var settings = {}
	
	// Get the current sandwich
	xml.find('products').find('category').each(function(){
		
		$(this).find('item').each(function(){
			
			var id = $(this).attr('id');
			
			sandwiches[id] = {
				id: $(this).attr('id'),
				name: $(this).find('name').text(),
				isFootlong: ($(this).find('footlong').text() == "true") ? true : false,
				isSixInch: ($(this).find('sixInch').text() == "true") ? true : false,
				isFlatbread: ($(this).find('flatbread').text() == "true") ? true : false,
				isMini: ($(this).find('mini').text() == "true") ? true : false,
				isSalad: ($(this).find('salad').text() == "true") ? true : false,
				mini:{bread:[], cheeses:[], meats:[], veggies:[],sauces:[]},
				sixInch:{bread:[], cheeses:[], meats:[], veggies:[],sauces:[]},
				footlong:{bread:[], cheeses:[], meats:[], veggies:[],sauces:[]},
				flatbread:{bread:[], cheeses:[], meats:[], veggies:[],sauces:[]},
				salad:{bread:[], cheeses:[], meats:[], veggies:[],sauces:[]}
			}
			
			// Mini Build
			$(this).find('mini_build').each(function(){
				$(this).children().each(function(){
					
					var globalQuantity = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
					
					switch(ref.trim(this.nodeName.toLowerCase())){
						// Bread
						case 'bread':
							var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
							sandwiches[id].mini.bread[ref.trim($(this).text())] = {id:ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
						break;
						// Cheese
						case 'cheeses':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].mini.cheeses[ref.trim($(this).text())] = {id:ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Meats
						case 'meats':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].mini.meats[ref.trim($(this).text())] = {id:ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Veggies
						case 'veggies':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].mini.veggies[ref.trim($(this).text())] = {id:ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Sauces
						case 'sauces':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].mini.sauces[ref.trim($(this).text())] = {id:ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						
					}
				});
			});
			
			// Six Inch Build && Footlong Build
			$(this).find('sixInch_build').each(function(){
				$(this).children().each(function(){
					
					var globalQuantity = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
					
					switch(ref.trim(this.nodeName.toLowerCase())){
						// Bread
						case 'bread':
							var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
							sandwiches[id].sixInch.bread[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							sandwiches[id].footlong.bread[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
						break;
						// Cheese
						case 'cheeses':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].sixInch.cheeses[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
								sandwiches[id].footlong.cheeses[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Meats
						case 'meats':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].sixInch.meats[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
								sandwiches[id].footlong.meats[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Veggies
						case 'veggies':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].sixInch.veggies[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
								sandwiches[id].footlong.veggies[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Sauces
						case 'sauces':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].sixInch.sauces[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
								sandwiches[id].footlong.sauces[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
					}
				});
			});
			
			// Flatbread
			$(this).find('flatbread_build').each(function(){
				$(this).children().each(function(){
					
					var globalQuantity = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
					
					switch(ref.trim(this.nodeName.toLowerCase())){
						// Bread
						case 'bread':
							var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
							sandwiches[id].flatbread.bread[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
						break;
						// Cheese
						case 'cheeses':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].flatbread.cheeses[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Meats
						case 'meats':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].flatbread.meats[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Veggies
						case 'veggies':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].flatbread.veggies[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Sauces
						case 'sauces':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].flatbread.sauces[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
					}
				});
			});
			
			// Salad
			$(this).find('salad_build').each(function(){
				
				$(this).children().each(function(){
					
					var globalQuantity = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
					
					switch(ref.trim(this.nodeName.toLowerCase())){
						// Bread
						case 'bread':
							var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
							sandwiches[id].salad.bread[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
						break;
						// Cheese
						case 'cheeses':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].salad.cheeses[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Meats
						case 'meats':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].salad.meats[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Veggies
						case 'veggies':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].salad.veggies[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
						// Sauces
						case 'sauces':
							$(this).children().each(function(){
								var qty = ($(this).attr('qty')) ? parseInt($(this).attr('qty')) : 1;
								sandwiches[id].salad.sauces[ref.trim($(this).text())] = {id: ref.trim($(this).text()), qty: qty, globalQty: globalQuantity};
							});
						break;
					}
				});
			});
			
		});
	});
	
	this.selectProductType(defaultProductType, true);
	
	// Add Product Type Click Actions
	$(':radio[name="product_type"]').each(function(){
		$(this).click(function(){
			ref.selectProductType($(this).attr('value').toString(), false);
		});
	});
	
	// Add click actions to options
	$(':radio[name="bread"]').each(function(){
		$(this).click(function(){
			ref.handleRadioOptionClick('bread', this);
		});
	});
	$(':radio[name="cheeses"]').each(function(){
		$(this).click(function(){
			ref.handleRadioOptionClick('cheeses', this);
		});
	});
	$(':checkbox[name="veggies"]').each(function(){
		$(this).click(function(){
			ref.handleCheckBoxClick('veggies', this);
		});
	});
	$(':checkbox[name="sauces"]').each(function(){
		$(this).click(function(){
			ref.handleCheckBoxClick('sauces', this);
		});
	});
	
	// Set the defaults if we're on a sandwich
	if(isSandwichPage && !$.browser.msie){
		this.restoreDefaults(ProductTypes.sixInch, false);
	}
	
	// Skin the form MUST BE CALLED HERE!! AFTER DEFAULTS ARE SET!!
	$("#nutrition_calculator_form").jqTransform({radio: true, checkbox: true, select: true});
	$('#product_options').css('position', 'relative');
	$('#product_options').css('left', '0px');
	$('#product_options').hide();
	
	if(!isSandwichPage){
		// Add Click actions to the drop menu items
		$('.jqSelectItem').click(function(){
			
			if(ref.trim($(this).attr('value')) == ""){
				
				$('input:checked').each(function(){
					$(this).attr('checked', false);
					$(this).parent().find('a').removeClass('jqTransformChecked');
					for(var i = 0; i < nutritionInfoLookUp.length; i++){
						nutritionInfoLookUp[i].value = 0;
						nutritionInfoLookUp[i].element.html("0.0");
					}
					$('.options_column:not(div[id="options_column_bread"])').hide();
					$('#subway_build_btn').hide();
					$('#nutrition_get_started').show();
					dropMenuItemSelected = false;
				});
			}
			else{
				if(!dropMenuItemSelected){
					
					$('.options_column:not(div[id="options_column_bread"]):not(div[id="options_column_meat"])').show();
					$('#subway_build_btn').show();
					$('#nutrition_get_started').hide();
					
					if(currentProductType == ProductTypes.salad){
						ref.hideNonSaladDressings();
					}
					
					// Fixes checkboxes and radios in IE6
					
					if($.browser.msie && $.browser.version < 7){
						$('input:not(:checked)').each(function(){
							$(this).attr('checked', false);
							$(this).parent().find('a').addClass('jqTransformChecked').removeClass('jqTransformChecked');
						});
					}
					
				}
				
				currentSandwich = $(this).attr('value');
				
				ref.restoreDefaults(currentProductType, false);
				dropMenuItemSelected = true;
			}
			
			ref.debugInit();
			
		});
		
	}
	
	// Check to see what options are available for sandys
	
	this.updateProductOptions(currentSandwich);
	
	// Now Show The Info Because we are done parsing the XML
	xmlLoadInProgress = false;
	this.check('product_type', 'sixInch');
	$('#nutrition_loader').hide();
	$("#nutrition_btn a").click();
	
	// Quick IE Fix for load data complete
	if($.browser.msie && isSandwichPage){
		trackBuildClick = false;
		$('#subway_build_btn').click();
		trackBuildClick = true;
	}
	
	// If this is the demo, enable output windows
	this.setupDebug();
	this.updateItemsSelected();
	this.showBread();
	
};

NutritionCalculator.prototype.updateProductOptions = function(sandwich){
	
	if(!isSandwichPage) return;
	
	if(!sandwiches[sandwich].isFootlong) $('#product_type_footlong').hide();
	if(!sandwiches[sandwich].isSixInch) $('#product_type_sixInch').hide();
	if(!sandwiches[sandwich].isFlatbread) $('#product_type_flatbread').hide();
	if(!sandwiches[sandwich].isMini) $('#product_type_mini').hide();
	if(!sandwiches[sandwich].isSalad) $('#product_type_salad').hide();
	
}

NutritionCalculator.prototype.selectProductType = function(id, check){
	
	var productType;
	
	switch(id){
		case "footlong":
			productType = ProductTypes.footlong;
		break;	
		case "sixInch":
			productType = ProductTypes.sixInch;
		break;
		case "flatbread":
			productType = ProductTypes.flatbread;
		break;
		case "mini":
			productType = ProductTypes.mini;
		break;
		case "salad":
			productType = ProductTypes.salad;
		break;
	}
	
	this.swapProductType(productType);
	
	loadOnce = true;
	
	$element = $('input[value="'+id+'"]');
	$element.attr('checked', true);
	$element.parent().find('a').addClass('jqTransformChecked');
	
};

NutritionCalculator.prototype.swapProductType = function(productType){
	
	var ref = this;
	
	if(productType == currentProductType) return;
	
	if(currentProductType == ProductTypes.salad || currentProductType == ProductTypes.flatbread){
		
		$('input[name="bread"]:checked').each(function(){
			ref.uncheck('bread', $(this).attr('value'));
		});
		
		for(var i in sandwiches[currentSandwich][productType].bread){
			this.check('bread', sandwiches[currentSandwich][productType].bread[i].id);
		}
		
	}
	
	switch(productType){
		case ProductTypes.mini:
			
			this.showBread(ProductTypes.mini);
			
			var updateMiniToDefault = false;
			
			// uncheck any salad dressings that are not available
			$('input[name="bread"]:checked').each(function(){
				if(inArray(miniExcludeList, "bread_" + $(this).attr('value'))){
					ref.uncheck($(this).attr('name'), $(this).attr('value'));
					updateMiniToDefault = true;
				}
			});
			
			if(updateMiniToDefault){
				for(var i in sandwiches[currentSandwich][productType].bread){
					this.check('bread', sandwiches[currentSandwich][productType].bread[i].id);
				}
			}
			
		break;
		case ProductTypes.sixInch:
		
			this.showBread('default');
			
		break;
		case ProductTypes.footlong:
			
			this.showBread('default');
			
		break;
		case ProductTypes.flatbread:
			
			$('input[name="bread"]:checked').each(function(){
				ref.uncheck('bread', $(this).attr('value'));
			});
			
			for(var i in sandwiches[currentSandwich][productType].bread){
				this.check('bread', sandwiches[currentSandwich][productType].bread[i].id);
			}
				
			this.hideBreadOptionsAndShowMessage(ProductTypes.flatbread);
			
			$('.sauces_on').show();
	
		break;
		case ProductTypes.salad:
			
			this.hideBreadOptionsAndShowMessage(ProductTypes.salad);
			
			this.hideNonSaladDressings();
			
			$('input[name="bread"]:checked').each(function(){
				ref.uncheck('bread', $(this).attr('value'));
			});
			
			// uncheck any salad dressings that are not available
			$('input[name="sauces"]:checked').each(function(){
				if(inArray(saladSaucesExcludeList, "sauces_" + $(this).attr('value'))){
					ref.uncheck($(this).attr('name'), $(this).attr('value'));
				}
			});
			
		break;
	}
	
	currentProductType = productType;
	
	if(loadOnce) this.updateItemsSelected();
	
}

NutritionCalculator.prototype.handleRadioOptionClick = function(name, element){
	
	var ref = this;
	
	if($(element).attr('checked')) return;
	
	this.updateItemsSelected();
	
}

NutritionCalculator.prototype.handleCheckBoxClick = function(name, element){
	
	if($(element).attr('value') == 'none'){
		$('input[name="'+name+'"]:checked').each(function(){
			if($(this).attr('value') != "none"){
				$(this).attr('checked', false);
				$(this).parent().find('a').removeClass('jqTransformChecked');
			}
		});
	}
	else{
		$('input[name="'+name+'"][value="none"]:checked').attr('checked', false).parent().find('a').removeClass('jqTransformChecked');
	}
	
	this.updateItemsSelected();
	
}

NutritionCalculator.prototype.restoreDefaults = function(productType, roundResults){
	
	currentProductType = productType;
	
	$('input[name="product_type"]').each(function(){
		$(this).parent().find('a').removeClass('jqTransformChecked');
		$(this).attr('checked', false);
	});
	
	$('.options_column').each(function(){
		$(this).find(':radio').each(function(){
			$(this).parent().find('a').removeClass('jqTransformChecked');
			$(this).attr('checked', false);
		});
		$(this).find(':checkbox').each(function(){
			$(this).parent().find('a').removeClass('jqTransformChecked');
			$(this).attr('checked', false);
		});
	});
	
	var sandwich = sandwiches[currentSandwich];
	
	if(productType != ProductTypes.salad){
		for(var i in sandwich[currentProductType].bread){
			this.check('bread', sandwich[currentProductType].bread[i].id);
		}
	}
	
	for(var i in sandwich[currentProductType].cheeses){
		this.check('cheeses', sandwich[currentProductType].cheeses[i].id);
	}
	
	for(var i in sandwich[currentProductType].veggies){
		this.check('veggies', sandwich[currentProductType].veggies[i].id);
	}
	
	for(var i in sandwich[currentProductType].sauces){
		this.check('sauces', sandwich[currentProductType].sauces[i].id);
	}
	
	for(var i in sandwich[currentProductType].meats){
		this.check('meats', sandwich[currentProductType].meats[i].id);
	}
	
	this.updateItemsSelected();
	
};

NutritionCalculator.prototype.roundTo = function(id, num){
	/*
	var tempStr = num.toString();
	var dot = tempStr.indexOf(".");
	
	if(dot > -1){
		tempStr = tempStr.substr(0, dot + 2);
	}
	
	var tempNum = parseFloat(tempStr);
	*/
	
	var tempNum = num;
	
	switch(id){
		case "serving_size":
			tempNum = this.roundToNearest(tempNum);
		break;
		case "calories":
			tempNum = this.roundToNearestMultipleOfTen(tempNum);
		break;
		case "calories_from_fat":
			tempNum = (num < 50) ? this.roundToNearestMultipleOfFive(tempNum) : this.roundToNearestMultipleOfTen(tempNum);
		break;
		case "total_fat":
			tempNum = this.roundFat(tempNum);
		break;
		case "saturated_fat":
			tempNum = this.roundFat(tempNum);
		break;
		case "trans_fat":
			tempNum = this.roundFat(tempNum);
		break;
		case "cholesterol":
			tempNum = this.roundCholesterol(tempNum);
		break;
		case "sodium":
			tempNum = this.roundVitamins(tempNum);
		break;
		case "carbohydrates":
			tempNum = this.roundToNearest(tempNum);
		break;
		case "dietary_fiber":
			tempNum = this.roundToNearest(tempNum);
		break;
		case "sugar":
			tempNum = this.roundToNearest(tempNum);
		break;
		case "protein":
			tempNum = this.roundToNearest(tempNum);
		break;
		case "vitamin_a":
			tempNum = this.roundVitamins(tempNum);
		break;
		case "vitamin_c":
			tempNum = this.roundVitamins(tempNum);
		break;
		case "calcium":
			tempNum = this.roundVitamins(tempNum);
		break;
		case "iron":
			tempNum = this.roundVitamins(tempNum);
		break;
	}
	
	if(tempNum < 0) tempNum = 0;
	
	return tempNum;
	
}

NutritionCalculator.prototype.roundToNearest = function(num){
	return Math.round(num);
}

NutritionCalculator.prototype.roundToNearestHalf = function(num){
	var tempNum = num;
	var tempStr = tempNum.toString();
	var dot = tempStr.indexOf(".");
	if(dot > -1){
		tempStr = tempStr.substr(dot);
		var remainder = parseFloat(tempStr).toFixed(2);
		if(remainder < 0.25){
			tempNum = parseFloat(tempNum - remainder).toFixed(2);
		}
		else if(remainder >= 0.25 && remainder < 0.5){
			tempNum = parseFloat(tempNum + (0.5 - remainder)).toFixed(2);
		}
		else if(remainder > 0.5 && remainder < 0.75){
			tempNum = parseFloat(tempNum - (remainder - 0.5)).toFixed(2);
		}
		else if(remainder >= 0.75){
			tempNum = parseFloat(tempNum + (1 - remainder)).toFixed(2);
		}
	}
	
	return tempNum;
}

NutritionCalculator.prototype.roundToNearestMultipleOfTwo = function(num){
	var tempNum = Math.floor(num);
	var tempStr = tempNum.toString();
	var ones = tempStr.substr(tempStr.length - 1);
	tempNum = (tempNum % 2 != 0) ? tempNum + 1 : tempNum;
	return tempNum;
}

NutritionCalculator.prototype.roundToNearestMultipleOfFive = function(num){
	var tempNum = Math.floor(num);
	var tempStr = tempNum.toString();
	var ones = tempStr.substr(tempStr.length - 1);
	ones = Math.round(parseInt(ones));
	if(ones < 3){
		tempNum = parseFloat(tempNum - ones).toFixed(2);
	}
	else if(ones >= 3 && ones < 5){
		tempNum = parseFloat(tempNum + (5 - ones)).toFixed(2);
	}
	else if(ones >= 5 && ones < 8){
		tempNum = parseFloat(tempNum - (ones - 5)).toFixed(2);
	}
	else if(ones >= 8){
		tempNum = parseFloat(tempNum + (10 - ones)).toFixed(2);
	}
	return tempNum;
}

NutritionCalculator.prototype.roundToNearestMultipleOfTen = function(num){
	var tempStr = Math.floor(num).toString();
	var tempNum = parseInt(tempStr);
	var ones = tempStr.substr(tempStr.length - 1);
	ones = parseInt(ones);
	if(ones < 5){
		tempNum = parseFloat(tempNum - ones).toFixed(2);
	}
	else{
		tempNum = parseFloat(tempNum + (10 - ones)).toFixed(2);
	}
	return tempNum;
}

NutritionCalculator.prototype.roundFat = function(num){
	var tempNum = parseFloat(num);
	var tempStr = num.toString();
	if(num < 0.5){
		tempNum = 0;
	}
	else if(num >= 0.5 && num < 5){
		tempNum = this.roundToNearestHalf(tempNum);
	}
	else if(num > 5){
		tempNum = this.roundToNearest(num);
	}
	return tempNum;
}

NutritionCalculator.prototype.roundCholesterol = function(num){
	var tempNum = parseFloat(num);
	var tempStr = num.toString();
	if(tempNum < 2){
		tempNum = 0;
	}
	else if(tempNum >= 2 && tempNum <= 5){
		tempNum = 5;
	}
	else if(tempNum > 5){
		tempNum = this.roundToNearestMultipleOfFive(tempNum);
	}
	return tempNum;
}

NutritionCalculator.prototype.roundSodium = function(num){
	var tempNum = parseFloat(num);
	var tempStr = num.toString();
	if(tempNum < 5){
		tempNum = 0;
	}
	else if(tempNum >= 5 && tempNum <= 140){
		tempNum = this.roundToNearestMultipleOfFive(tempNum);
	}
	else if(tempNum > 140){
		tempNum = this.roundToNearestMultipleOfTen(tempNum);
	}
	return tempNum;
}

NutritionCalculator.prototype.roundVitamins = function(num){
	var tempNum = parseFloat(num);
	var tempStr = num.toString();
	if(tempNum < 2){
		tempNum = 0;
	}
	else if(tempNum >= 2 && tempNum < 10){
		tempNum = this.roundToNearestMultipleOfTwo(tempNum);
	}
	else if(tempNum >= 10 && tempNum <= 50){
		tempNum = this.roundToNearestMultipleOfFive(tempNum);
	}
	else if(tempNum > 50){
		tempNum = this.roundToNearestMultipleOfTen(tempNum);
	}
	return tempNum;
}

NutritionCalculator.prototype.addTrailingZero = function(num){
	
	var tempStr = num.toString();
	var dot = tempStr.indexOf(".");
	
	if(dot == -1){
		tempStr += ".0";
	}
	else{
		tempStr = tempStr.substr(0, dot + 2);
	}
	
	return tempStr;
	
}

NutritionCalculator.prototype.setupDebug = function(){
	
	if(!showDebug) return;
	
	$('#middle').append('<div id="dubug_container"></div>');
	
	this.debugInit();
	
	var debugTable = '<table width="100%" cellpadding="2" cellspacing="0" id="debug_items" border="1"><tr><td valign="top" colspan="17" class="dubug_table_header">Items Selected</td></tr><tr><td valign="top" class="debug_column_header">Item</td><td valign="top" class="debug_column_header">Serving Size</td><td valign="top" class="debug_column_header">Calories </td><td valign="top" class="debug_column_header">Fat Calories</td><td valign="top" class="debug_column_header">Total Fat</td><td valign="top" class="debug_column_header">Sat Fat</td><td valign="top" class="debug_column_header">Trans Fat</td><td valign="top" class="debug_column_header">Cholesterol</td><td valign="top" class="debug_column_header">Sodium</td><td valign="top" class="debug_column_header">Carbs</td><td valign="top" class="debug_column_header">Fiber</td><td valign="top" class="debug_column_header">Sugar</td><td valign="top" class="debug_column_header">Protein</td><td valign="top" class="debug_column_header">Vitamin A</td><td valign="top" class="debug_column_header">Vitamin C</td><td valign="top" class="debug_column_header">Calcium</td><td valign="top" class="debug_column_header">Iron</td></tr></table>'
	
	$('#dubug_container').append(debugTable);
	
}

NutritionCalculator.prototype.debugInit = function(){
	
	if(!showDebug) return;
	
	$('#dubug_window_bottom').remove();
	var infoCopy = $('#nutrition_info').html();
	$('#dubug_container').prepend('<div id="dubug_window_bottom"></div>');
	
}

NutritionCalculator.prototype.updateDebugDefault = function(){
	
	if(!showDebug) return;
	
	$('#dubug_window_bottom').remove();
	this.debugInit();
	
}

NutritionCalculator.prototype.updateItemsSelected = function(){
	
	clearTimeout(updateTimeOut);
	updateTimeOut = setTimeout(NutritionCalculator.prototype.updateDebugResults, 100);
	
}

NutritionCalculator.prototype.updateDebugResults = function(){
	
	$('.debug_items_tr').remove();
	
	var html = "";
	var ref = this;
	var selectedBreadHTML = "";
	var selectedCheeseHTML = "";
	var selectedVeggiesHTML = "";
	var selectedSaucesHTML = "";
	
	for(var i = 0; i < nutritionInfoLookUp.length; i++){
		nutritionInfoLookUp[i].total = 0;
	}
	
	$('input:not([name="product_type"]):checked').each(function(){
		
		// This is display for print
		
		var label = $(this).attr('id');
		
		switch($(this).attr('name').toLowerCase()){
			case 'bread':
				selectedBreadHTML += '<p>' + label + '</p>';
			break;
			case 'cheeses':
				selectedCheeseHTML += '<p>' + label + '</p>';
			break;
			case 'veggies':
				selectedVeggiesHTML += '<p>' + label + '</p>';
			break;
			case 'sauces':
				selectedSaucesHTML += '<p>' + label + '</p>';
			break;
		}
		
		$('#nutrition_selected_items_bread_container').html(selectedBreadHTML);
		$('#nutrition_selected_items_cheese_container').html(selectedCheeseHTML);
		$('#nutrition_selected_items_veggies_container').html(selectedVeggiesHTML);
		$('#nutrition_selected_items_sauces_container').html(selectedSaucesHTML);
		
		if($(this).attr('value').toLowerCase() != "none"){
			
			var quantity = nutritionCalculator.getQuantity($(this).attr('name'), $(this).attr('value'));
			
			html += '<tr class="debug_items_tr">';
			html += '<td>' + $(this).attr('value') + "(" + quantity + ")" + '</td>';
			
			for(var i = 0; i < nutritionInfoLookUp.length; i++){
				
				html += '<td valign="top">' + parseFloat(categoryLookUp[$(this).attr('name')][$(this).attr('value')][currentProductType][nutritionInfoLookUp[i].id] * quantity).toFixed(2) + '</td>';
				nutritionInfoLookUp[i].total += categoryLookUp[$(this).attr('name')][$(this).attr('value')][currentProductType][nutritionInfoLookUp[i].id] * quantity;
				
			}
			
			html += '</tr>';
			
		}
		
	});
	
	// Totals
	
	html += '<tr class="debug_items_tr">';
	html += '<td valign="top" class="debug_total">RAW Total: </td>';
	
	for(var i = 0; i < nutritionInfoLookUp.length; i++){
		
		var tempStr = nutritionInfoLookUp[i].total.toString();
		
		html += '<td valign="top" class="debug_total">' + parseFloat(tempStr).toFixed(2) + '</td>';
		
	}
	
	html += '</tr>';
	
	html += '<tr class="debug_items_tr">';
	html += '<td valign="top" class="debug_total_rounded">Rounded Total: </td>';
	
	for(var i = 0; i < nutritionInfoLookUp.length; i++){
		
		var tempStr = nutritionInfoLookUp[i].total.toString();
		//var dot = tempStr.indexOf(".");
		//tempStr = (dot > -1) ? tempStr.substr(0, dot + 2) : tempStr + ".0";
		
		var tempNum = parseFloat(tempStr).toFixed(2);
		//console.log(nutritionInfoLookUp[i].id + "|" + tempNum);
		//console.log(nutritionInfoLookUp[i].id + "|" + tempNum);
		tempNum = nutritionCalculator.roundTo(nutritionInfoLookUp[i].id, tempNum);
		
		html += '<td valign="top" class="debug_total_rounded">' + nutritionCalculator.addTrailingZero(tempNum) + '</td>';
		
		nutritionInfoLookUp[i].element.html(nutritionCalculator.addTrailingZero(tempNum))
		
	}
	
	html += '</tr>';
	
	if(showDebug){
		$('#debug_items').append(html);
	}
	
};

NutritionCalculator.prototype.getQuantity = function(name, value){
	
	var qty = 1;
	
	if(sandwiches[currentSandwich][currentProductType][name][value]){
		qty = sandwiches[currentSandwich][currentProductType][name][value].qty;
	}
	else{
		for(var i in sandwiches[currentSandwich][currentProductType][name]){
			qty = sandwiches[currentSandwich][currentProductType][name][i].globalQty;
			break;
		}
	}
	
	if(!qty) qty = 1;
	
	return qty;
	
}

NutritionCalculator.prototype.hideBreadOptionsAndShowMessage = function(productType){
	
	var message = '';
	
	$('.bread_on').hide();
	$('.bread_off').show();
	
	switch(productType){
		case ProductTypes.flatbread:
			message = 'You have chosen Flatbread***';
		break;
		case ProductTypes.salad:
			message = 'You have chosen salad';
		break;
	}
	
	$('.bread_off').html(message);
	
}

NutritionCalculator.prototype.hideNonSaladDressings = function(){
	for(var i = 0; i < saladSaucesExcludeList.length; i++){
		$('#' + saladSaucesExcludeList[i]).hide();
	}
}

NutritionCalculator.prototype.check = function(name, value){
	$('input[name="'+name+'"][value="'+value+'"]').attr('checked', true);
	$('input[name="'+name+'"][value="'+value+'"]').parent().find('a').removeClass('jqTransformChecked');
	$('input[name="'+name+'"][value="'+value+'"]').parent().find('a').addClass('jqTransformChecked');
};

NutritionCalculator.prototype.uncheck = function(name, value){
	$('input[name="'+name+'"][value="'+value+'"]').attr('checked', false);
	$('input[name="'+name+'"][value="'+value+'"]').parent().find('a').removeClass('jqTransformChecked');
};

NutritionCalculator.prototype.unselectAll = function(name){
	$('input[name="'+name+'"]:checked').each(function(){
		$(this).attr('checked', false);
		$(this).parent().find('a').removeClass('jqTransformChecked')
	});
};

NutritionCalculator.prototype.hideBread = function(){
	$('.bread_on').hide();
};

NutritionCalculator.prototype.showBread = function(type){
	
	$('.bread_on').show();
	$('.sauces_on').show();
	$('.bread_off').hide();
	$('.bread_off').html('');
	
	if(type == ProductTypes.mini){
		for(var i = 0; i < miniExcludeList.length; i++){
			$('#' + miniExcludeList[i]).hide();
		}
	}
	
};

NutritionCalculator.prototype.trim = function(str){
	return str.replace(/^\s+|\s+$/g, '');
};

function trace(str){
	$('body').append('<div>' + str + '</div>');			
}

function inArray(array, value){
	for(var i = 0; i < array.length; i++){
		if(value == array[i]){
			return true;
			break;
		}
	}
	return false;
}