var BK = BK || {};
var CONTENT = BK.local.MENU_NUTRITION;

var clickCount = 0;
var DetailsUrl1;
var DisplayTitle;
var ItemID;
var selectedMenuItem = '';
var strUrl = new String(document.location);
var arrUrl = splitURLVars(strUrl);
var customize = false;
var dialogClosed = false;
var updateZQ = false;//upd size/quantity controls
var currMealItem = "";//upd size/quantity controls
var timeoutBurgerBuilder = new Array();
var intervalBurgerBuilder;
var chromeTimoutDelay;
var chromeTimeoutIntervalDelay;
var userAgent = navigator.userAgent.toLowerCase();
var totalNumberOfItems = 0;
var viewMealContainerHeight = 0;
var viewMealBackgroundHeight = 0;
var categoryItems = new Array();

$.browser = {
	version: (userAgent.match(/.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/) || [])[1],
	chrome: /chrome/.test(userAgent),
	safari: /webkit/.test(userAgent) && !/chrome/.test(userAgent),
	opera: /opera/.test(userAgent),
	msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
	mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
};


function init() {
   	//COOKIES
	var linkArray = [];
	var quantityArray = [];
	var idsArray = [];

	if ($.cookie('itemlink') != null) {
		//$('#YourMeal').show();

		if ($.cookie('itemlink') != '') {
			linkArray = $.cookie('itemlink').split(',');
		}

		if ($.cookie('itemquantities') != '') {
			quantityArray = $.cookie('itemquantities').split(',');
			totalNumberOfItems = quantityArray.length;
		}

		if ($.cookie('itemids') != '') {
			idsArray = $.cookie('itemids').split(',');
		}

	}

	BK.menuNutritionController.onInit(linkArray, idsArray, quantityArray);

	BK.menuNutritionView.Flash.loadAnimationPlayer();
	$('#loadingAnimation-flash-holder').addClass('loadingAnimationHidden');

	$('<img src="/images/menu-nutrition/bkg.a-menu-item-1row.jpg" />');
	$('<img src="/images/menu-nutrition/bkg.a-menu-item-1row-arrow.jpg" />');
	$('#list_items ul.main-menu li').remove();
	$('ul.variation-list li.filler').remove();
	$('ul.total-nutrition1 li.filler').remove();
	$('ul.total-nutrition2 li.filler').remove();
	$('ul.items-in-meal li.filler').remove();
	$('ul.allergens li.filler').remove();
	$('#under650calories').hide();
	$('#nutrition-panel').css("top", "-105px");
	$('#meal-items-holder').css("max-height", "362px");
	slideDown = true;
	$('#more-less-info').html(CONTENT.MEAL_INFO_MORE);

	$.ajax({
		url: '/cms' + CulturePrefix + 'cms_out/menu_nutrition/categories/all.xml',
		datatype: 'xml',
		type: 'get',
		success: function(data) {

			$(data).find('MenuCategory').each(function() {
				var $mainMenu = $('#list_items ul.main-menu');
				ItemId = $(this).attr('ID');
				var $xmlItemName = $(this).children('DisplayTitle').text();
				DisplayTitle = $xmlItemName/*.replace(/®/g, '<sup>®</sup>')*/;

				DetailsUrl1 = $(this).children('DetailsUrl').text();
				$mainMenu.append('<li><a href="' + CulturePrefix + 'menu-nutrition/category' + ItemId + '/index.html" class="category' + ItemId + ' first-list">' + DisplayTitle + '</a></li>');
				addSubMenus(ItemId);
			});
			
			//Call general PNG fix once builder has loaded. Calling it earlier breaks BB in IE6.
            if (document.all && /MSIE (5\.5|6)/.test(navigator.userAgent) && document.styleSheets && document.styleSheets[0] && document.styleSheets[0].addRule) {
	        	DD_belatedPNG.fix('img, h1, h2, h3, h4, h5, h6, ul, li, a, p, div, span, input, td, th, fieldset, label, dl, dd, dt');
			};
		},
		complete: function() {
			if (CategoryID != '') {
				if (ValueMealID != '') {
					$('#menu_selection ul').find('#value-meal' + ValueMealID).each(function(i) {
						if (i == 0) {
							if ($.browser.chrome) {
								//Delay firing for Chrome.
								$(this).animate({opacity:1},1000, function(){$(this).click()});
							} else {
								$(this).click();
							}
						}
					});
				}
				else if (MenuItemID != '') {
					$('#menu_selection ul').find('#menu-item' + MenuItemID).each(function(i) {
						if (i == 0) {
							if ($.browser.chrome) {
								//Delay firing for Chrome.
								$(this).animate({opacity:1},1000, function(){$(this).click()});
							} else {
								$(this).click();
							}
						}
					});
				}
				else {
					$('#menu_selection ul').find('.category' + CategoryID).each(function(i) {
						if (i == 0) {
							if ($.browser.chrome) {
								//Delay firing for Chrome.
								$(this).animate({opacity:1},1000, function(){$(this).click()});
							} else {
								$(this).click();
							}
						}
					});
				}
			} else {
				if (linkArray == '') {
					$('#intro-info-builder').show();
					if (true || $.browser.chrome) { // Force to space out loading like Chrome
					//if ($.browser.chrome) {
						// For Chrome space out loading the initial whopper and starting the animation because chrome is too quick for it's own good
					    setTimeout('BK.menuNutritionController.onPageLoadAddBurgerBuilder(\'/cms' + CulturePrefix + 'cms_out/menu_nutrition/menu_items/' + CONTENT.annimationMenuItem + '.xml\')', 1000);
						// Kicks off the first iteration of the auto burger builder
						chromeTimoutDelay = setTimeout('loadAutoBurgerBuilder()', 4000);
						// loadAutoBurgerBuilder() 1st param + 2nd param = setInterval() 2nd param
						chromeTimeoutIntervalDelay = setTimeout('intervalBurgerBuilder = setInterval(\'loadAutoBurgerBuilder()\', 7000)', 4000);
						// loadAutoBurgerBuilder() 1st param + 2nd param = setInterval() 2nd param
					} else {
						BK.menuNutritionController.onPageLoadAddBurgerBuilder('/cms' + CulturePrefix + 'cms_out/menu_nutrition/menu_items/' + CONTENT.annimationMenuItem + '.xml');
						// Kicks off the first iteration of the auto burger builder
						loadAutoBurgerBuilder();
						// loadAutoBurgerBuilder() 1st param + 2nd param = setInterval() 2nd param
						intervalBurgerBuilder = setInterval('loadAutoBurgerBuilder()', 7000);
						// loadAutoBurgerBuilder() 1st param + 2nd param = setInterval() 2nd param
					}
				} else {
					$('#YourMeal').show();
				}
			}

			if (arrUrl['banner'] == 'breakfast-value' && CategoryID == '12') {
				$('#intro-info-breakfast').css("display", "block");
			} else if (arrUrl['banner'] == 'new-breakfast-menu' && CategoryID == '6') {
				$('#intro-info-newBreakfastMenu').css("display", "block");
			} else if (arrUrl['banner'] == 'value-menu' && CategoryID == '11') {
				$('#intro-value-menu').css("display", "block");
			}

			if (BK.menuNutritionModel.meal.getItems().length > 0) {
				//$('#intro-info').css("display", "none");
				$('#intro-info-builder').css("display", "none");
			}
		}
	})

}



function loadAutoBurgerBuilder() {
	var randomPattyId;
	var randomPatty = CONTENT.randomPatty;
	var randomToppingId;
	var randomTopping = CONTENT.randomTopping;
	var patternChanges = CONTENT.patternChanges;

	var ingredientArray = new Array(2);
	for (i = 0; i < 14; i++) {
		ingredientArray[i] = new Array(14)
	}

	// The loading of the array below must match the value of intChanges and must be even.
	// The array loads a random patty or topping items and sets the item to be removed in the
	// opposite order it was added. That is why the array is not loaded in order.
	randomPattyId = Math.floor(Math.random() * 9);
	ingredientArray[0][1] = randomPatty[randomPattyId]; ingredientArray[0][2] = 'increment';
	ingredientArray[13][1] = randomPatty[randomPattyId]; ingredientArray[13][2] = 'decrement';
	randomPattyId = Math.floor(Math.random() * 9);
	ingredientArray[1][1] = randomPatty[randomPattyId]; ingredientArray[1][2] = 'increment';
	ingredientArray[12][1] = randomPatty[randomPattyId]; ingredientArray[12][2] = 'decrement';
	randomToppingId = Math.floor(Math.random() * 15);
	ingredientArray[2][1] = randomTopping[randomToppingId]; ingredientArray[2][2] = 'increment';
	ingredientArray[11][1] = randomTopping[randomToppingId]; ingredientArray[11][2] = 'decrement';
	randomPattyId = Math.floor(Math.random() * 9);
	ingredientArray[3][1] = randomPatty[randomPattyId]; ingredientArray[3][2] = 'increment';
	ingredientArray[10][1] = randomPatty[randomPattyId]; ingredientArray[10][2] = 'decrement';
	randomPattyId = Math.floor(Math.random() * 9);
	ingredientArray[4][1] = randomPatty[randomPattyId]; ingredientArray[4][2] = 'increment';
	ingredientArray[9][1] = randomPatty[randomPattyId]; ingredientArray[9][2] = 'decrement';
	randomToppingId = Math.floor(Math.random() * 15);
	ingredientArray[5][1] = randomTopping[randomToppingId]; ingredientArray[5][2] = 'increment';
	ingredientArray[8][1] = randomTopping[randomToppingId]; ingredientArray[8][2] = 'decrement';
	randomPattyId = Math.floor(Math.random() * 9);
	ingredientArray[6][1] = randomPatty[randomPattyId]; ingredientArray[6][2] = 'increment';
	ingredientArray[7][1] = randomPatty[randomPattyId]; ingredientArray[7][2] = 'decrement';

	var patternInc = 0;
	for (var i = 0; i < ingredientArray.length; i++) {
		var strId = i.toString;
		patternInc = patternInc + patternChanges[i];
		timeoutBurgerBuilder[i] = setTimeout('BK.menuNutritionView.Flash.' + ingredientArray[i][2] + 'Ingredient(' + ingredientArray[i][1] + ')', patternInc);
	}
}
function addSubMenus(currentCategory) {
	var DisplayTitle;
	var DetailsUrl;
	var ItemID;
	var IsHidden;

	$.ajax({
	    url: DetailsUrl1,
	    datatype: 'xml',
	    type: 'get',
	    async: false,
	    success: function (data) {
	        var $data = $(data);
	        var $list = $('<ul class="menu-sub-menu1" id="category_' + currentCategory + '"></ul>');
	        var $currentLI = $('ul.main-menu li a.category' + currentCategory);
	        var badgeContent = "";
	        var newlineThreshold = $.browser.msie ? 27 : 27;
	        //If less calories badge cookie is set to true
	        var IsCalorieBadgeInMenu = false;
	        if (cookie650CaloriesOrLess()) {
	            $('#select_from_menu').addClass('badge');
	            IsCalorieBadgeInMenu = true;
	        }
	        $(data).children().children().each(function () {
	            if (this.tagName == 'MenuItem' || this.tagName == 'ValueMeal') {
	                DisplayTitle = $(this).children('DisplayTitle').text();

	                DetailsUrl = $(this).children('DetailsUrl').text();
	                ItemID = $(this).attr("ID");
	                IsHidden = $(this).attr('IsHidden');

	                var fullId = (this.tagName == 'ValueMeal' ? 'value-meal' : 'menu-item') + $(this).attr('ID');
	                var itemClass = 'menu_item';
	                var displayTitleLength = DisplayTitle.length;
	                if (DisplayTitle.search('<sup>') >= 0) displayTitleLength -= 11
	                if (DisplayTitle.search('&reg;') >= 0) displayTitleLength -= 4
	                if (DisplayTitle.search('&trade;') >= 0) displayTitleLength -= 6
	                if (displayTitleLength >= newlineThreshold &&
                        (ItemID != '2000' && ItemID != '2148')
                        ) {
	                    itemClass = 'menu_item_wide';
	                }
	                if (IsCalorieBadgeInMenu) {
	                    if (categoryItems[$(this).attr('ID')] == null) {
	                        categoryItems[$(this).attr('ID')] = new BK.menuNutritionModel.CategoryItem($(this));
	                    }
	                    if ($(this).children('CaloriesBadge') != null) {
	                        //Get badge class from CaloriesBadge tag value.
	                        var badge = $(this).children('CaloriesBadge').text().toLowerCase().replace(" ", "");
	                        badgeContent = "<span class='badge " + badge + "'></span>";
	                        DisplayTitle = "<span class='title'>" + DisplayTitle + "</span>";
	                    }
	                }
	                var $itemLI = $('<li class="' + itemClass + '"><a rel="' + DetailsUrl + '" href="' + CulturePrefix + 'menu-nutrition/category' + currentCategory + '/' + fullId + '/index.html" class="ingredient_item" id="' + fullId + '">' + DisplayTitle + badgeContent + '</a></li>'); //Aday
	                if (IsHidden != "false") {
	                    $itemLI.hide();
	                }
	                $list.append($itemLI);
	            } else if (this.tagName == 'SubCategory') {
	                var $list2 = $('<ul class="menu-sub-menu2"></ul>');
	                $(this).children().each(function () {
	                    DisplayTitle = $(this).children('DisplayTitle').text();
	                    displayTitleLength = DisplayTitle.length;
	                    DetailsUrl = $(this).children('DetailsUrl').text();
	                    ItemID = $(this).attr("ID");
	                    IsHidden = $(this).attr("IsHidden");
	                    if (IsCalorieBadgeInMenu) {
	                        if (categoryItems[ItemID] == null) {
	                            categoryItems[ItemID] = new BK.menuNutritionModel.CategoryItem($(this));
	                        }
	                        if ($(this).children('CaloriesBadge') != null) {
	                            //Get badge class from CaloriesBadge tag value.
	                            var badge = $(this).children('CaloriesBadge').text().toLowerCase().replace(" ", "");
	                            badgeContent = "<span class='badge " + badge + "'></span>";
	                            DisplayTitle = "<span class='title'>" + DisplayTitle + "</span>";
	                        }
	                    }
	                    var itemClass = 'menu_item';
	                    if (displayTitleLength >= newlineThreshold &&
                            (ItemID != '192' && ItemID != '70' && ItemID != '153' && ItemID != '156' && ItemID != '2107')
                           ) {
	                        itemClass = 'menu_item_wide';
	                    }
	                    var $itemLI = $('<li class="' + itemClass + '"><a rel="' + DetailsUrl + '" href="' + CulturePrefix + 'menu-nutrition/category' + currentCategory + '/menu-item' + ItemID + '/index.html" class="sub_category" id="menu-item' + ItemID + '">' + DisplayTitle + badgeContent + '</a></li>');
	                    if (IsHidden != "false") {
	                        $itemLI.hide();
	                    }
	                    $list2.append($itemLI);
	                });
	                var $newLI = $('<li class="sub-category-name"></li>');
	                var $liContents = $('<a href="#">' + $(this).attr('Title') + '</a>');
	                $newLI.append($liContents).append($list2).appendTo($list);
	            }
	        });
	        $currentLI.parent().append($list);
	    }
	});
}

function menuActive(currentselection) {
    var $currentSelection = currentselection;
    $currentSelection.addClass('Active');
	$currentSelection.parent().siblings().find('a.Active').removeClass('Active');
	$('ul.sub-menu-2').remove();
	$('ul.menu-sub-menu1').css("display", "none");
	$currentSelection.siblings("ul").css("display", "block");
	if ($currentSelection.siblings('ul').height() < parseFloat($currentSelection.siblings('ul').css('max-height'))) {
        $currentSelection.siblings("ul").css("overflow-y", "hidden");
	}
    else {
        if ($.browser.msie && $.browser.version < 7) {
            $currentSelection.siblings("ul").css("overflow-y", "hidden");
        }
        else {
            $currentSelection.siblings("ul").css("overflow-y", "scroll");
            $currentSelection.siblings("ul").find("a").css("width", "165px");
        }
	}
    $currentSelection.siblings("ul").css("overflow-x", "hidden");
    if ($currentSelection.parent().attr("class") == "sub-category-name") {
        $currentSelection.siblings("ul").css("display", "none");
		$currentSelection.parent().parent().css("display", "block");
		var ulHtml = $currentSelection.siblings("ul").html();
		var strSubCategory = $currentSelection.text().replace(/ /g, '_').replace('\'', '').replace('®', '').replace('™', '');
		var subCatId = $currentSelection.parent().parent().attr('id');
		var subMenu2UL = $('<ul class="sub-menu-2" id="sub_' + strSubCategory + '_' + subCatId + '"></ul>');
        $(subMenu2UL).append(ulHtml);
		$(subMenu2UL).appendTo('#list_items');
    }
}

BK.menuNutritionView = {};

BK.menuNutritionView.Html = function () {
    var isUpdated = false;

    /////////////////HELPER FUNCTIONS
    var getWindowDimensions = function () {
        var myWidth = 0, myHeight = 0;
        if (typeof (window.innerWidth) == 'number') {
            //Non-IE 
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode' 
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
            //IE 4 compatible 
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        return { Width: myWidth, Height: myHeight }
    }

    var center = function (element) {
        //request data for centering
        var windowDim = getWindowDimensions();
        var elementHeight = $(element).height();
        var elementWidth = $(element).width();
        var scroll = getScrollXY();
        var top = windowDim.Height / 2 - elementHeight / 2 + scroll.Y - 15;
        var left = windowDim.Width / 2 - elementWidth / 2 + scroll.X - 15;

        if (top < 0) {
            top = 0;
        }
        if (left < 0) {
            left = 0;
        }

        //centering
        $(element).css({
            "position": "absolute",
            "top": top,
            "left": left
        });
        //only need force for IE6 

        $("#backgroundelement").css({
            "height": windowDim.Y
        });
        //window.alert("\nelement.Height="+elementHeight+"\nInner Height="+windowDim.Y);
    }

    var getScrollXY = function () {
        var scrOfX = 0, scrOfY = 0;
        if (typeof (window.pageYOffset) == 'number') {
            //Netscape compliant 
            scrOfY = window.pageYOffset;
            scrOfX = window.pageXOffset;
        } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
            //DOM compliant 
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
        } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
            //IE6 standards compliant mode 
            scrOfY = document.documentElement.scrollTop;
            scrOfX = document.documentElement.scrollLeft;
        }
        return { X: scrOfX, Y: scrOfY };
    }

    var clearDialog = function () {
        $('#dlg-message').removeClass('add-message').removeClass('update-message').removeClass('viewing-your-meal');
        $('#dlg-background').removeClass('dlg-background-viewing-your-meal').removeClass('dlg-background-normal');
        $('#dlg-close-btn').removeClass('view-your-meal-close-btn').removeClass('dlg-close-btn');
        $('#add-update-dlg').removeClass('dlg-view-your-meal').removeClass('dlg-view-your-meal-complete').removeClass('dlg-save-order').removeClass('dlg-anythingelse');
    }
    /////////////////END HELPER FUNCTIONS

    return {
        clearUpdated: function () {
            isUpdated = false;
        },

        createVariation: function (currentMenuItemId, defaultText, variationFolder, variationMenuItemId, variationText) {
            var li = $('<li class="each-variation"></li>');
            var p = $('<p class="menuItemVariations"></p>')
            var a = $('<a id="variation-' + variationMenuItemId + '" href="' + CulturePrefix + 'menu-nutrition/category3/value-meal' + variationMenuItemId + '/index.html" rel="/cms' + CulturePrefix + 'cms_out/menu_nutrition/' + variationFolder + '/' + variationMenuItemId + '.xml" title="' + defaultText + '"></a>');
            a.append('<span>' + variationText + '</span>');

            if (currentMenuItemId == variationMenuItemId) {
                a.addClass('active');
            }

            p.append(a);
            li.append(p);

            return li;
        },

        updateNonIngredientSpecificAllergens: function (menuItem) {
            for (var a in menuItem.allergens) {
                var currentAll = menuItem.allergens[a];
                var allergenID = currentAll.id;
                if ($('#Allergen_' + allergenID).size() > 0) {
                    $('#Allergen_' + allergenID).attr('rel', parseInt($('#Allergen_' + allergenID).attr('rel'), 10) + 1);
                } else {
                    $('<li id="Allergen_' + allergenID + '" rel="1">, ' + currentAll.displayTitle + '</li>').appendTo('ul.allergens');
                }
            }

            var firstAllergenLI = $('ul.allergens li:first').html();
            if (firstAllergenLI) {
                firstAllergenLI = firstAllergenLI.replace(/\,/, "");
                $('ul.allergens li:first').html(firstAllergenLI);
            }
        },

        updateItemAllergens: function (ingredient) {
            for (var a in ingredient.allergens) {
                var currentAll = ingredient.allergens[a];
                var allergenID = currentAll.id;
                if (ingredient.currentQuantity > 0) {
                    if ($('#Allergen_' + allergenID).size() > 0) {
                        $('#Allergen_' + allergenID).attr('rel', parseInt($('#Allergen_' + allergenID).attr('rel'), 10) + 1);
                    } else {
                        $('<li id="Allergen_' + allergenID + '" rel="1">, ' + currentAll.displayTitle + '</li>').appendTo('ul.allergens');
                    }
                }
            }

            var firstAllergenLI = $('ul.allergens li:first').html();
            if (firstAllergenLI) {
                firstAllergenLI = firstAllergenLI.replace(/\,/, "");
                $('ul.allergens li:first').html(firstAllergenLI);
            }
        },

        updateIngredientIcon: function (ingredient, icon) {
            var quantity = ingredient.currentQuantity;
            if (quantity == 1) {
                icon.children('span').css({ backgroundPosition: 'left top', display: 'block', width: '14px', height: '14px', left: '25px', top: '15px' });
            } else if (quantity == 2) {
                icon.children('span').css({ backgroundPosition: '-14px top', display: 'block', width: '14px', height: '14px', left: '25px', top: '15px' });
            } else if (quantity == 3) {
                icon.children('span').css({ backgroundPosition: '-28px top', display: 'block', width: '14px', height: '14px', left: '25px', top: '15px' });
            } else if (quantity == 4) {
                icon.children('span').css({ backgroundPosition: '-42px top', display: 'block', width: '14px', height: '14px', left: '25px', top: '15px' });
            } else if (quantity == 5) {
                icon.children('span').css({ backgroundPosition: '-56px top', display: 'block', width: '14px', height: '14px', left: '25px', top: '15px' });
            } else if (quantity == 0) {
                icon.children('span').css({ backgroundPosition: 'left bottom', display: 'block', width: '14px', height: '14px', left: '25px', top: '15px' });
            }

            if (quantity == ingredient.maxQuantity) {
                icon.siblings('a.addIngredient').css("background-image", "none");
            }
            else {
                icon.siblings('a.addIngredient').css("background-image", "url(/cms" + CulturePrefix + "cms_out/digital_assets/graphics/pages/bkg.a-up-arrow.gif)");
            }

            if (quantity == ingredient.minQuantity) {
                icon.siblings('a.subtractIngredient').css("background-image", "none");
            }
            else {
                icon.siblings('a.subtractIngredient').css("background-image", "url(/cms" + CulturePrefix + "cms_out/digital_assets/graphics/pages/bkg.a-down-arrow.gif)")
            }
        },

        updateValueMealOptions: function (valueMeal) {
            var badgeContent = "";
            //If less calories badge cookie is set to true
            if (cookie650CaloriesOrLess()) {
                if (categoryItems[valueMeal.id].caloriesBadge != "") {
                    badgeContent = updateCaloriesBadge(valueMeal.getNutritionTotals().Calories);
                }
            }
            $('#value-meal-headline').html(badgeContent + valueMeal.displayTitle);

            $('#value-meal-variations').empty();
            for (var i in valueMeal.variations) {
                var currentVar = valueMeal.variations[i];
                $('#value-meal-variations').append(this.createVariation(valueMeal.id, '', 'value_meals', currentVar.menuItemId, currentVar.title));
            }

            var drinksWrapper = $('#value-meal-drinks-wrapper');
            drinksWrapper.empty();

            var drinks = $('<select id="value-meal-drinks"></select>');
            drinksWrapper.append(drinks);

            for (var d in valueMeal.drinkOptions) {
                var drink = valueMeal.drinkOptions[d];
                var o = $('<option value="' + drink.id + '">' + drink.displayTitle + '</option>');
                if (drink.id == valueMeal.currentDrink.id) {
                    o.attr('selected', 'selected');
                }

                drinks.append(o);
            }

            drinks.combobox({
                comboboxContainerClass: 'value-meal-combobox-container',
                comboboxValueContainerClass: 'value-meal-combobox-value-container',
                comboboxValueContentClass: 'value-meal-combobox-value-content',
                comboboxDropDownClass: 'combobox-dropdown-container',
                comboboxDropDownItemClass: 'combobox-dropdown-item',
                comboboxDropDownButtonClass: 'value-meal-combobox-button',
                width: 270,
                height: 22,
                onChange: function (text, value) {
                    BK.menuNutritionController.onChangeValueMealDrink(value);
                }
            });

            var sidesWrapper = $('#value-meal-sides-wrapper');
            sidesWrapper.empty();

            var sides = $('<select id="value-meal-sides"></select>');
            sidesWrapper.append(sides);

            for (var s in valueMeal.sideOptions) {
                var side = valueMeal.sideOptions[s];
                var o = $('<option value="' + side.id + '">' + side.displayTitle + '</option>');
                if (side.id == valueMeal.currentSide.id) {
                    o.attr('selected', 'selected');
                }

                sides.append(o);
            }

            sides.combobox({
                comboboxContainerClass: 'value-meal-combobox-container',
                comboboxValueContainerClass: 'value-meal-combobox-value-container',
                comboboxValueContentClass: 'value-meal-combobox-value-content',
                comboboxDropDownClass: 'combobox-dropdown-container',
                comboboxDropDownItemClass: 'combobox-dropdown-item',
                comboboxDropDownButtonClass: 'value-meal-combobox-button',
                width: 270,
                height: 22,
                onChange: function (text, value) {
                    BK.menuNutritionController.onChangeValueMealSide(value);
                }
            });
        },

        displayNutritionAllergens: function () {
            var panel = $('.ui-tabs-panel:visible');
            var itemInfo = $('.current-item-info');
            var top = $('.less-caption:visible').length || $('#meal-tabs:hidden').length ? (panel.position().top + itemInfo.position().top + itemInfo.outerHeight()) : (panel.position().top + panel.height());
            var naContainer = $('#nutrition-allergens-container');
            naContainer.css('top', top);

            //Begin Override - If description is too long, add a set amount of positioning to the nutritionals / footer
            if ($('.less-caption:visible').length == 0 && $('#meal-tabs:hidden').length == 0) {
                var longDescAdj = 65;
                var theDescription = $('.current-selection-desc');
                if ((theDescription.outerHeight() - longDescAdj) > 0) {
                    naContainer.css('top', naContainer.css('top').split('px')[0] * 1 + (theDescription.outerHeight() - longDescAdj))
                }
                //value meals special case
                if ((itemInfo.outerHeight() + 67) > 131) {
                    var diff = itemInfo.outerHeight() + 67 - 131;
                    naContainer.css('top', top + diff + 'px');
                    naContainer.css('marginTop', '0px');
                }
            }
            if (naContainer.position().top + naContainer.height() + 70 > 710) {
                $('#SectionFooter').css('top', naContainer.position().top + naContainer.height() + 70)
            }
            //End Override

            //$('#add-to-meal-holder.menu-item').css('top', top + naContainer.height() + 12);
        },

        displaySelectedItem: function (menuItem, isUpdate) {
            isUpdated = false;
            this.closeDialog();
            $('#current-item-container').show();

            // Remove the ingredient list and recreate it so that we can either make it into a carousel or not
            $('.jcarousel-container').remove();
            $('#ingredient-list').remove();
            var ingredientList = $('<ul id="ingredient-list"></ul>');
            $('.current-item-info').before(ingredientList);

            // Clear specific classes from elements
            $('.current-item-info')
			    .removeClass('has-variations-and-ingredients')
			    .removeClass('no-ingredients');

            var isMeal = menuItem.sandwich;
            var currentItem = isMeal ? menuItem.sandwich : menuItem;
            var isBurgerBuilder = false;
            var isVariations = false;
            var isCustomIngredients = true;

            var ingredientCount = 0;
            var Allergens = "";

            MenuItemID = currentItem.id;

            selectedMenuItem = currentItem.displayTitle;
            if (!isMeal)
                track_menu_item_select(selectedMenuItem);

            var currentItemName = selectedMenuItem;
            if (currentItem.burgerBuilderEnabled == 'true') {
                isBurgerBuilder = true;
            }

            if (currentItemName.indexOf("...") == "19") {
                currentItemName = currentItem.title;
            }
            $('.current-item-headline').html(currentItemName);
            var briefCaption = currentItem.briefCaption;

            // Item variations		
            $('#variation-list').empty();
            var defaultMenuItemId = currentItem.defaultVariationMenuItemId;
            for (var i in currentItem.variations) {
                var currentVar = currentItem.variations[i];
                $('#variation-list').append(this.createVariation(MenuItemID, currentItem.defaultVariationMenuItemTitle, 'menu_items', currentVar.menuItemId, currentVar.abbreviation));

                isVariations = true;
            }

            this.displayAddButton(isUpdate);

            // Value meal options
            if (menuItem.sandwich) {
                this.updateValueMealOptions(menuItem);
            }

            if (defaultMenuItemId == '' || isMeal) {
                // Hide variations
                $('#variation-list').hide();

            } else {
                // Show varations and position ingredients next to the variations
                $('#variation-list').show();
                $('.current-item-info').addClass('has-variations-and-ingredients');
                ingredientList.addClass('with-variations');
            }

            // NonIngredientSpecificAllergens
            this.updateNonIngredientSpecificAllergens(currentItem);

            // Item ingredients
            for (var i in currentItem.ingredients) {
                var currentIng = currentItem.ingredients[i];

                var itemLi = $('<li class="each-ingredient" id="id' + currentIng.iconOrder + '"></li>');
                itemLi.append('<p class="rollover-name">' + currentIng.displayTitle + '</p>');
                var btns = $('<p class="ingredientBtns">');
                btns.append('<a class="addIngredient" href="#">' + CONTENT.ITEM_ADD + '</a>')
                var icon = $('<a class="icon" id="ingredient-id-' + currentIng.id + '"><span class="current-quantity"></span></a>');
                btns.append(icon);
                btns.append('<a class="subtractIngredient" href="#">' + CONTENT.ITEM_SUB + '</a>');
                itemLi.append(btns);
                this.updateIngredientIcon(currentIng, icon);

                var ingredientId = currentIng.id;

                //assigning max min values...
                var minQty = parseInt(currentIng.minQuantity);
                var maxQty = parseInt(currentIng.maxQuantity);

                this.updateItemAllergens(currentIng);

                ingredientCount += 1;

                //determine when to display the ingredient icons 
                if (minQty < maxQty) {
                    if ($(this).find('DefaultQuantity').text() != 0) {
                        variationList.prepend(itemLi);
                    }
                    else {
                        ingredientList.append(itemLi);
                    }
                }

                //                                if (MenuItemID != 2004 && MenuItemID != 2005 && MenuItemID != 2006 && MenuItemID != 2007 && MenuItemID != 2008 && MenuItemID != 2009 && MenuItemID != 2010) {
                //                                    if ((ingredientId != 85) && (ingredientId != 25) && (ingredientId != 17) && (ingredientId != 29) && (ingredientId != 120) && (ingredientId != 111)
                //                				    && (ingredientId != 134) && (ingredientId != 135) && ingredientId != 14 && ingredientId != 140 && ingredientId != 50 && ingredientId != 30
                //                				    && ingredientId != 36 && ingredientId != 127 && ingredientId != 6 && ingredientId != 129 && ingredientId != 141 && ingredientId != 19 &&
                //                				    ingredientId != 119 && ingredientId != 131 && ingredientId != 4181 && ingredientId != 4217) {
                //                                        if ($(this).find('DefaultQuantity').text() != 0) {
                //                                            variationList.prepend(itemLi);
                //                                        }
                //                                        else {
                //                                            ingredientList.append(itemLi);
                //                                        }
                //                                    }
                //                                }
            }

            // remove unused ingredients
            if (CONTENT.removeUnusedIngredients[MenuItemID]) {
                //prep selector
                var selectorStr = "";
                for (thisItem in CONTENT.removeUnusedIngredients[MenuItemID].unused) {
                    if ((parseInt(thisItem) + 1) == CONTENT.removeUnusedIngredients[MenuItemID].unused.length) {
                        selectorStr += "#ingredient-id-" + CONTENT.removeUnusedIngredients[MenuItemID].unused[thisItem];
                    }
                    else {
                        selectorStr += "#ingredient-id-" + CONTENT.removeUnusedIngredients[MenuItemID].unused[thisItem] + ", ";
                    }
                }

                if (!CONTENT.removeUnusedIngredients[MenuItemID].operator && !CONTENT.removeUnusedIngredients[MenuItemID].length) {
                    $(selectorStr).parent().parent().remove();
                }

                if (CONTENT.removeUnusedIngredients[MenuItemID].operator && CONTENT.removeUnusedIngredients[MenuItemID].length && eval($("li.each-ingredient").length + CONTENT.removeUnusedIngredients[MenuItemID].operator + CONTENT.removeUnusedIngredients[MenuItemID].length)) {
                    $(selectorStr).parent().parent().remove();
                }

            }

            // Re-order ingredients
            var iconCount = ingredientList.children().length;
            for (var i = 0; i < (iconCount + 1); i++) {
                $('.each-ingredient').each(function () {
                    var currentID = parseInt($(this).attr("id").replace(/id/, ""));
                    if (currentID == i) {
                        $(this).appendTo(ingredientList);
                    }
                });
            }

            // Turn the ingredient list into a carousel if needed
            $('#more-ingredients').hide();
            if (iconCount <= 1) {
                $('#ingredient-list').hide();
                $('.current-item-info')
				    .removeClass('has-variations-and-ingredients')
				    .addClass('no-ingredients');
                isCustomIngredients = false;
            }
            else if (iconCount > 9) {
                if (isMeal || isBurgerBuilder) {
                    ingredientList.jcarousel({
                        visible: 9
                    });
                    ingredientList.css({ 'width': '2000px', 'height': '67px' });

                    $('.jcarousel-next-horizontal, .jcarousel-prev-horizontal').hover(function () {
                        $(this).toggleClass('jcarousel-horizontal-hover');
                    },
                    function () {
                        $(this).toggleClass('jcarousel-horizontal-hover');
                    });

                    $('.jcarousel-next-horizontal, .jcarousel-prev-horizontal').bind("click", function () {
                        if ($(this).attr('disabled') != 'true') {
                            var direction = $(this).hasClass('jcarousel-prev-horizontal') ? 'Left' : 'Right';
                            BK.menuNutritionController.onValueMealCarouselClick(direction);
                        }
                    });
                }
                else {
                    $('#more-ingredients').show().removeClass('less');
                }
            }

            updateItemNutritionTotals(menuItem);

            // Set the collapsed description text
            var maxLen = 142;
            if (isMeal && briefCaption.length > maxLen) {
                var collapsedText;
                if (briefCaption.charAt(maxLen) == ' ') {
                    // Split on a space
                    collapsedText = briefCaption.substring(0, maxLen)
                }
                else if (briefCaption.charAt(maxLen + 1) == ' ') {
                    // Split before a space
                    collapsedText = briefCaption.substring(0, maxLen + 1)
                }
                else {
                    // Split in the the middle of a word, find the closest space to the end of the string
                    collapsedText = briefCaption.substring(0, maxLen)
                    for (var i = maxLen - 1; i >= 0; i--) {
                        if (collapsedText.charAt(i) == ' ') {
                            collapsedText = collapsedText.substring(0, i);
                            break;
                        }
                    }
                }

                $('.current-selection-desc-short')
				    .html(collapsedText + ' ... <a class="more-caption" href="#"><img src="/cms/en/us/cms_out/digital_assets/graphics/pages/bkg.a-caption-more.png" alt="more"/></a><div class="clearingDiv" style="height: 10px;"></div>')
				    .removeClass('desc-hidden');

                $('.current-selection-desc')
				    .html(briefCaption + ' <a class="less-caption" href="#"><img src="/cms/en/us/cms_out/digital_assets/graphics/pages/bkg.a-caption-less.png" alt="collapse"/></a><div class="clearingDiv" style="height: 10px;"></div>')
				    .addClass('desc-hidden');
            }
            else {
                $('.current-selection-desc')
				    .html(briefCaption)
				    .removeClass('desc-hidden');

                $('.current-selection-desc-short')
				    .html('')
				    .addClass('desc-hidden');
            }

            var maxTitleLen = 24;

            var strTitleH3 = $('#value-meal-builder .current-item-info h3.current-item-headline').html();
            var strTitleH3Text = $('#value-meal-builder .current-item-info h3.current-item-headline').text();
            $('#value-meal-builder .current-item-info h3.current-item-headline').css('margin-top', '0px');
            if (strTitleH3Text.length > maxTitleLen) {
                if (strTitleH3.charAt(maxLen) == ' ') {
                    strTitleH3 = strTitleH3.replace(' ', '<br />');
                    $('#value-meal-builder .current-item-info h3.current-item-headline').html(strTitleH3);
                } else {
                    var strTitleText = strTitleH3.substring(0, maxTitleLen);
                    var strTitleBegin;
                    var strTitleEnd;
                    for (var i = maxTitleLen - 1; i >= 0; i--) {
                        if (strTitleText.charAt(i) == ' ') {
                            strTitleBegin = strTitleH3.substring(0, i);
                            strTitleEnd = strTitleH3.substring(i + 1);
                            $('#value-meal-builder .current-item-info h3.current-item-headline').html(strTitleBegin + '<br />' + strTitleEnd);
                            $('#value-meal-builder .current-item-info h3.current-item-headline').css('margin-top', '-14px');
                            break;
                        }
                    }
                }
            }
            //remove previous badge.
            $('#value-meal-builder .current-item-info span').hide();
            var badgeContent = "";
            //If less calories badge cookie is set to true
            //and it is NOT value meal
            if (!isMeal && cookie650CaloriesOrLess()) {
                if (categoryItems[currentItem.id].caloriesBadge != "") {
                    badgeContent = updateCaloriesBadge(currentItem.getNutritionTotals().Calories);
                    $('.current-item-info').html(badgeContent + $('.current-item-info').html());
                }
            }

            // Setup value meal tabs
            if (isMeal || isBurgerBuilder || isVariations || isCustomIngredients) {
                $('#meal-tabs').show();
                if (isMeal) {
                    $('#info-headline').html(BK.local.MENU_NUTRITION.MEAL_INFO).show();
                    $('#meal-tabs-container').tabs('select', 0);
                    $('#options-tab').show();
                    $('#add-to-meal-holder').removeClass('builder-only').removeClass('custom');
                    $('#add-to-meal-holder').addClass('value-meal');
                    $('#value-meal-builder .current-item-info h3.current-item-headline').show();
                } else {
                    $('#info-headline').empty().hide();
                    //If less calories badge cookie is set to true
                    badgeContent = "";
                    if (cookie650CaloriesOrLess()) {
                        if (categoryItems[currentItem.id].caloriesBadge != "") {
                            badgeContent = updateCaloriesBadge(currentItem.getNutritionTotals().Calories);
                        }
                    }
                    $('#value-meal-headline').html(badgeContent + currentItemName);

                    $('#meal-tabs-container').tabs('select', 1);
                    $('#options-tab').hide();
                    $('#add-to-meal-holder').removeClass('value-meal').removeClass('custom');
                    $('#add-to-meal-holder').addClass('builder-only');
                    if (!isBurgerBuilder) {
                        $('#add-to-meal-holder').addClass('custom');
                    }
                    $('#value-meal-builder .current-item-info h3.current-item-headline').hide();
                    $('#value-meal-builder .current-item-info span').hide();
                }
                $('#value-meal-builder, #add-to-meal-holder, .current-item-headline, #nutrition-allergens-container, .current-item-info, #ingredient-list').addClass('value-meal').removeClass('menu-item');
                $('#value-meal-headline').show();
            }
            else {
                this.displayDollarBadge(MenuItemID);
                $('#meal-tabs').hide();
                $('#info-headline').hide();
                $('#meal-tabs-container').tabs('select', 1);
                $('#value-meal-builder, #add-to-meal-holder, .current-item-headline, #nutrition-allergens-container, .current-item-info, #ingredient-list').removeClass('value-meal').addClass('menu-item');
                $('#value-meal-headline').hide();
                $('#value-meal-builder .current-item-info h3.current-item-headline').show();
            }

            this.addElementStyles();
            this.displayNutritionAllergens();
            this.refreshFlash();
            return false;
        },

        addElementStyles: function () {
            // Implement CSS selectors since IE6 does not
            var valueMealClass = 'value-meal';

            // tabs
            var tabBaseStyle = {
                'width': '454px',
                'height': '131px',
                'z-index': '0',
                'top': '416px',
                'left': '292px',
                'position': 'absolute',
                'background': ''
            };
            var builderTab = $('#value-meal-builder');
            var optionsTab = $('#value-meal-options');
            if (builderTab.hasClass(valueMealClass)) {
                // Add/remove background images based on tab so that the png-fix script does not "fix" the backgrounds
                // of hidden elements
                var tab = $('#meal-tabs-container').tabs().data('selected.tabs');
                if (tab == 0) {
                    optionsTab.css($.extend({}, tabBaseStyle, { 'background': 'url(/images/menu-nutrition/bkg.div-meal-tab.png) no-repeat top left', 'z-index': '1' }));
                    builderTab.css(tabBaseStyle);
                }
                else {
                    builderTab.css($.extend({}, tabBaseStyle, { 'background': 'url(/images/menu-nutrition/bkg.div-sandwich-tab.png) no-repeat top left' }));
                    optionsTab.css(tabBaseStyle);
                }
            }
            else {
                builderTab.css($.extend({}, tabBaseStyle, { 'top': '361px', 'z-index': '1' }));
                optionsTab.css(tabBaseStyle);
            }

            // add to meal button
            var addToMeal = $('#add-to-meal-holder');
            if (addToMeal.hasClass(valueMealClass)) {
                if (addToMeal.hasClass('builder-only')) {
                    //addToMeal.css({ 'top': '392px', 'left': '447px' });
                } else {
                    //addToMeal.css({ 'top': '392px', 'left': '572px' });
                }
            }
            else {
                //addToMeal.css({ 'top': '', 'left': '292px' });
            }
            var addBtn = $('#add-to-meal-holder a');
            if (addBtn.hasClass('add-to-meal')) {
                addBtn.css('background-image', 'url(/cms' + CulturePrefix + 'cms_out/digital_assets/graphics/pages/bkg.a-add-to-order-sprite.png)');
            }
            else {
                addBtn.css('background-image', 'url(/cms' + CulturePrefix + 'cms_out/digital_assets/graphics/pages/bkg.a-update-order-sprite.png)');
            }

            // current item headline
            var ciHeadline = $('.current-item-headline');
            if (ciHeadline.hasClass(valueMealClass)) {
                ciHeadline.css({ 'font-size': '100%' });
            }
            else {
                ciHeadline.css({ 'font-size': '131%' });
            }

            // nutrition-allergen container
            var naContainer = $('#nutrition-allergens-container')
            var naBaseStyle = {
                'position': 'absolute',
                'left': '284px',
                'width': '471px',
                'height': '',
                'z-index': '0',
                'margin-top': '0'
            };
            if (naContainer.hasClass(valueMealClass)) {
                if (addToMeal.hasClass('builder-only')) {
                    naContainer.css($.extend(naBaseStyle, { 'margin-top': '30px', 'width': '311px' }));
                } else {
                    naContainer.css($.extend(naBaseStyle, { 'margin-top': '0', 'height': '100px'/*, 'background': 'transparent url(/images/menu-nutrition/bkg.div-tab-bottom.png) no-repeat left bottom'*/ }));
                }
                if (addToMeal.hasClass('custom')) {
                    naContainer.css($.extend(naBaseStyle, { 'margin-top': '12px' }));
                    $('#builder-tab a').css('background-image', 'url(/cms' + CulturePrefix + 'cms_out/digital_assets/graphics/pages/bkg.li-customize-item.png)');
                } else {
                    $('#builder-tab a').css('background-image', 'url(/cms' + CulturePrefix + 'cms_out/digital_assets/graphics/pages/bkg.li-customize-sandwich-sprite.png)');
                }
            }
            else {
                naContainer.css($.extend(naBaseStyle, { 'margin-top': '0', 'background': 'none' }));
            }

            // current item info
            var ciInfo = $('.current-item-info');
            var ciBaseStyle = {
                'width': '454px',
                'padding': '15px 6px',
                'margin-bottom': '2px',
                'position': '',
                'top': ''
            };
            if (ciInfo.hasClass(valueMealClass)) {
                ciInfo.css($.extend(ciBaseStyle, { 'padding-bottom': '0' }));
            }
            else if (ciInfo.hasClass('no-ingredients')) {
                ciInfo.css($.extend(ciBaseStyle, { 'padding-top': '30px' }));
            }
            else {
                ciInfo.css($.extend(ciBaseStyle, { 'position': 'absolute', 'top': '67px' }));
            }

            if (ciInfo.hasClass('has-variations-and-ingredients')) {
                ciInfo.css($.extend(ciBaseStyle, { 'position': 'absolute', 'top': '47px' }));
                $('#variation-list').css('margin-top', '20px');
                $('.current-selection-desc').css('margin-top', '15px');
            } else {
                $('#variation-list').css('margin-top', '0');
                $('.current-selection-desc').css('margin-top', '0px');
            }

            this.addIngredientListStyles();
            this.fixPng();
        },

        addIngredientListStyles: function () {
            // ingredient list
            var ingredientList = $('#ingredient-list:visible');
            var ilStyle = {
                'display': 'block',
                'height': '67px',
                'overflow': 'hidden',
                'width': '454px',
                'z-index': '3',
                'position': '',
                'padding': '',
                'background': '',
                'top': '',
                'left': ''
            };

            if (ingredientList.hasClass('with-variations')) {
                ilStyle = $.extend(ilStyle, { 'position': 'relative',
                    'left': '140px',
                    'top': '-57px',
                    'width': '314px',
                    'padding-left': '20px'
                });
            }
            else if (ingredientList.hasClass('menu-item')) {
                ilStyle = $.extend(ilStyle, { 'position': 'absolute' });
            }
            else if (ingredientList.hasClass('value-meal')) {
                ilStyle = $.extend(ilStyle, { 'width': '1269px' });
            }

            if (ingredientList.hasClass('more')) {
                ilStyle = $.extend(ilStyle, { 'height': '236px' });
            }
            if (ingredientList.hasClass('one-row')) {
                ilStyle = $.extend(ilStyle, { 'background': 'transparent url(/images/menu-nutrition/bkg.ingredient-tray-1row.png) no-repeat scroll 0 67px' });
            }
            if (ingredientList.hasClass('two-row')) {
                ilStyle = $.extend(ilStyle, { 'background': 'transparent url(/images/menu-nutrition/bkg.ingredient-tray-2row.png) no-repeat scroll 0 67px' });
            }

            ingredientList.css(ilStyle);
        },

        fixPng: function () {
            if (document.all && /MSIE (5\.5|6)/.test(navigator.userAgent) &&
				    document.styleSheets && document.styleSheets[0] && document.styleSheets[0].addRule) {
                // Fix elements individually, the selector argument to DD_belatedPNG.fix does not work as expected,
                // possibly because the styles are set programmatically
                try {
                    DD_belatedPNG.fixPng($('#add-to-meal-holder a')[0]);
                    DD_belatedPNG.fixPng($('#ingredient-list')[0]);
                    DD_belatedPNG.fixPng($('#nutrition-allergens-container')[0]);
                    DD_belatedPNG.fixPng($('#value-meal-options')[0]);
                    DD_belatedPNG.fixPng($('#value-meal-builder')[0]);
                } catch (e) { }
            }
        },

        displayAddButton: function (isUpdate) {
            this.hideMealLimitMessage();
            $('#add-to-meal-holder').show();
            var addButton = $('#add-to-meal-holder a');
            var dlgAddBtn = $('#dlg-add-btn');
            addButton.unbind('click');
            dlgAddBtn.unbind('click');
            if (!isUpdate) {
                addButton
				    .addClass('add-to-meal')
				    .removeClass('update-meal')
				    .click(function () {
				        track_add_to_meal(selectedMenuItem);
				        BK.menuNutritionController.onAddItemToMeal();
				        return false;
				    });

                dlgAddBtn.click(function () {
                    BK.menuNutritionController.onAddItemToMeal();
                    BK.menuNutritionView.Html.closeDialog();
                    return false;
                });
            }
            else {
                addButton
				    .removeClass('add-to-meal')
				    .addClass('update-meal')
				    .click(function () {
				        if (updateZQ) {//upd size/quantity controls
				            BK.menuNutritionModel.meal.removeItem(currMealItem);
				            BK.menuNutritionController.onAddItemToMeal();
				            updateZQ = false;
				        } else {
				            BK.menuNutritionController.onUpdateItem();
				        }
				        return false;
				    });

                dlgAddBtn.click(function () {
                    BK.menuNutritionController.onUpdateItem();
                    BK.menuNutritionView.Html.closeDialog();
                    return false;
                });
            }

            if (addButton.hasClass('add-to-meal')) {
                addButton.css('background-image', 'url(/cms' + CulturePrefix + 'cms_out/digital_assets/graphics/pages/bkg.a-add-to-order-sprite.png)');
            }
            else {
                addButton.css('background-image', 'url(/cms' + CulturePrefix + 'cms_out/digital_assets/graphics/pages/bkg.a-update-order-sprite.png)');
            }
        },

        getIngredientId: function (ingredientAction) {
            var idParts = ingredientAction.siblings("a.icon").attr('id').split('-');
            return idParts[2];
        },

        getMealItemId: function (mealAction) {
            return mealAction.parent().parent().attr('id').substring(4);
        },

        hideBreakfast: function () {
            $('#intro-info-breakfast, #intro-value-menu, #intro-info-newBreakfastMenu').hide();
        },

        displayDollarBadge: function (menuItemId) {
            /* BEGIN: Value Meal $1 Badge Remove After Promotion */
            $('#SectionFooter').css('top', '710px');

            if (CONTENT.dollarBadge[menuItemId]) {
                if ($('#dollar-badge img').length == 0) {
                    $('#dollar-badge').append('<img src=\"/cms' + CulturePrefix + 'cms_out/digital_assets/graphics/pages/one_dollar.png" alt=\"\$1" />');
                }
                if (CONTENT.dollarBadge[menuItemId].top) {
                    $('#dollar-badge').css('top', CONTENT.dollarBadge[menuItemId].top + 'px');
                }
                if (CONTENT.dollarBadge[menuItemId].left) {
                    $('#dollar-badge').css('left', CONTENT.dollarBadge[menuItemId].left + 'px');
                }
            }

            /* special case(s) */
            if (CONTENT.dollarBadgeSpecial[menuItemId]) {
                $('#' + CONTENT.dollarBadgeSpecial[menuItemId].id).css(CONTENT.dollarBadgeSpecial[menuItemId].name, CONTENT.dollarBadgeSpecial[menuItemId].value + 'px');
            }

            /* END: Value Meal $1 Badge Remove After Promotion */
        },

        hideDollarBadge: function () {
            $('#dollar-badge').empty();
        },

        updateIngredients: function (currentItem, ingredientId) {
            isUpdated = true;

            if (currentItem.sandwich) {
                currentItem = currentItem.sandwich;
            }

            var addAllergen = true;
            var ingredient = currentItem.ingredients[ingredientId];
            this.updateIngredientIcon(ingredient, $('#ingredient-id-' + ingredientId));

            updateItemNutritionTotals(currentItem);

            var strXmlReplaced = '<MenuItem ID="1"><IngredientPortion><Ingredient ID="' + ingredientId + '"/><DefaultQuantity>' + ingredient.currentQuantity + '</DefaultQuantity></IngredientPortion></MenuItem>';
            this.updateItemAllergens(ingredient);

            this.refreshFlash();
        },

        displayMealLimitMessage: function (isValueMeal) {
            var offset = $('a.add-to-meal').offset();
            var message = $('#meal-limit-message');
            if (isValueMeal) {
                message.addClass('valueMeal')
						.css({ "left": (offset.left - 56),
						    "top": (offset.top - 114),
						    "display": "block"
						});
            }
            else {
                message.removeClass('valueMeal')
						.css({ "left": (offset.left - 250),
						    "top": (offset.top - 70),
						    "display": "block"
						});
            }

            $('a.add-to-meal').css("opacity", "0.2");
        },

        hideMealLimitMessage: function () {
            $('#meal-limit-message').css("display", "none");
            $('a.add-to-meal').css("opacity", "");
        },

        showViewYourMealButton: function () {
            if (BK.menuNutritionView.Flash.mealBuilder()) {
                //$('#meal-bottom').show();
            }
            else {
                //$('#meal-bottom').hide();
            }
        },

        hideViewYourMealButton: function () {
            //$('#meal-bottom').hide();
        },

        addUpdateMealItem: function (meal) {
            isUpdated = false;
            this.showDialog();

            this.showViewYourMealButton();
            this.updateMeal(meal);
        },

        updateMeal: function (meal) {
            //$('#YourMeal').show();
            BK.local.MENU_NUTRITION.updateMealNutritionTotals(meal);

            var linkArray = new Array();
            var quantityArray = new Array();
            var idArray = new Array();

            $('ul.items-in-meal').empty();
            var mealItems = meal.getItems();
            var mealCount = mealItems.length;
            totalNumberOfItems = mealCount;

            for (var i = 0; i < mealCount; i++) {
                var currentItem = mealItems[i];
                var currentHeadline = currentItem.displayTitle.replace(/<(.|\n)*?>/g, ''); //Strip HTML
                var modifiedHeadlineCharsCount = 0;
                var modifiedHeadline = "";
                if (cookie650CaloriesOrLess()) {
                    modifiedHeadlineCharsCount = 12;
                } else {
                    modifiedHeadlineCharsCount = 20;
                }
                //If less calories badge cookie is set to true 
                if (currentHeadline.length < modifiedHeadlineCharsCount) {
                    modifiedHeadline = currentHeadline;
                }
                else {
                    modifiedHeadline = currentHeadline.substring(0, modifiedHeadlineCharsCount) + "...";
                }
                var badgeContent = "";
                //If less calories badge cookie is set to true
                if (cookie650CaloriesOrLess()) {
                    badgeContent = updateCaloriesBadge(currentItem.getNutritionTotals().Calories);
                }
                $('ul.items-in-meal').append('<li id="item' + i + '" class="' + currentItem.id + ' meal-items"><p><a title="' + currentHeadline + '" rel="' + currentItem.xmlUrl + '" href="#" class="meal-item-name">' + badgeContent + '<em>' + modifiedHeadline + '</em></a></p><p><a href="#" class="remove-meal-item">' + CONTENT.ITEM_REMOVE + '</a></p><p class="meal-item-nutrifact"><strong>' + currentItem.getNutritionTotals().Calories + '</strong>' + CONTENT.MEAL_CAL + '</p></li>');


                var quantityString = '';
                var idString = '';
                var first = true;
                for (var ing in currentItem.ingredients) {
                    if (!first) {
                        quantityString += ';';
                        idString += ';';
                    }
                    else {
                        first = false;
                    }

                    quantityString += currentItem.ingredients[ing].currentQuantity;
                    idString += currentItem.ingredients[ing].id;
                }

                linkArray.push(currentItem.xmlUrl);
                quantityArray.push(quantityString);
                idArray.push(idString);
            }

            $('ul.items-in-meal li').hover(function () {
                $(this).find('a.meal-item-name').toggleClass('hover');
            },
		    function () {
		        $(this).find('a.meal-item-name').toggleClass('hover');
		    });
            $('#Content #menu_selection #YourMeal h2 em strong').html(mealCount);
            if (!this.moreInfoPanelOpen()) {
                if (mealCount < 8) {
                    $('a.remove-meal-item').css("left", "195px");
                    $('p.meal-item-nutrifact').css("right", "10px");
                    $('#meal-items-holder').css("height", "100%");
                } else {
                    $('a.remove-meal-item').css("left", "186px");
                    $('p.meal-item-nutrifact').css("right", "2px");
                    $('#meal-items-holder').css("height", "362px");
                }
            } else {
                if (mealCount < 6) {
                    $('a.remove-meal-item').css("left", "195px");
                    $('p.meal-item-nutrifact').css("right", "10px");
                    $('#meal-items-holder').css("height", "100%");
                } else {
                    $('a.remove-meal-item').css("left", "186px");
                    $('p.meal-item-nutrifact').css("right", "2px");
                    $('#meal-items-holder').css("height", "257px");
                }
            }

            //COOKIE
            $.cookie('itemlink', linkArray);
            $.cookie('itemquantities', quantityArray);
            $.cookie('itemids', idArray);
        },

        moreInfoPanelOpen: function () {
            return $("#nutrition-panel").css('top') == '0px';
        },

        moreIngredientsButton: function (morebutton) {
            morebutton.toggleClass('less');
            if (!$('#ingredient-list').hasClass('more')) {
                track_more_expand(selectedMenuItem, 'More');

                $('#ingredient-list')
				    .addClass('more')
				    .addClass(($('#ingredient-list li').length <= 18) ? 'one-row' : 'two-row');
            } else {
                track_more_expand(selectedMenuItem, 'Less');
                $('#ingredient-list')
				    .removeClass('more')
				    .removeClass('one-row')
				    .removeClass('two-row');
            }

            this.addIngredientListStyles();
            this.fixPng();
        },

        updateValueMealTab: function (menuItem) {
            if (menuItem && menuItem.id) {
                this.displayNutritionAllergens();

                updateItemNutritionTotals(menuItem);

                this.addElementStyles();
            }
        },

        updateValueMealSize: function (valueMeal) {
            isUpdated = true;
            this.updateValueMealOptions(valueMeal);
            updateItemNutritionTotals(valueMeal);
        },

        updateValueMealSideDrink: function (valueMeal) {
            isUpdated = true;
            updateItemNutritionTotals(valueMeal);
            this.refreshFlash();
        },

        refreshFlash: function () {
            // Move a div on the flash client area to force a refresh
            $('#flash-overlay').toggleClass('move-right');
        },

        showDialog: function (showUpdate) {
            clearDialog();
            this.hideMealLimitMessage();
            $('#current-item-container').hide();

            var height = $('#SectionFooter').position().top + $('#SectionFooter').height();
            var width = $('#PageWrapper').width();
            $('#dlg-background')
			.addClass('dlg-background-normal')
            .height(height)
            .width(width);

            $('#add-update-dlg')
            .width('')
			.height('')
			.css({ 'top': '', 'left': '', 'background-position': '' });

            if (showUpdate) {
                $('#dlg-modal')
                .show()
                .height(height)
                .width(width);
                $('#add-update-dlg').addClass('dlg-save-order');
                $('#dlg-message').addClass('update-message');
                $('#dlg-actions-container').show();
                $('#dlg-container').show();
                $('#dlg-close-btn').hide();
            }
            else {
                if (!dialogClosed) {
                    var meal = BK.menuNutritionModel.meal;
                    if (meal.canAddItem()) {
                        $('#add-update-dlg').addClass('dlg-anythingelse');
                        $('#dlg-close-btn').show();
                        $('#dlg-actions-container').hide();
                        $('#dlg-message').addClass('add-message');

                        $('#dlg-close-btn').addClass('dlg-close-btn');
                        $('#dlg-container').show();
                    }
                    dialogClosed = true;
                }
            }
        },

        showViewYourMealDialog: function () {
            clearDialog();
            this.hideMealLimitMessage();
            $('#dlg-container').show();
            var windowDimensions = getWindowDimensions();
            var height = windowDimensions.Height;
            var width = $('#PageWrapper').width();

            // gray background
            $('#dlg-background')
				.height('')
				.width('')
				.addClass('dlg-background-viewing-your-meal')
				.css('opacity', '0.7');


            if ($.browser.msie && $.browser.version == "6.0") {
                $('#dlg-background')
				.height(height)
				.width(width)
				.css({ 'top': '0px', 'left': '0px', 'position': 'absolute' });
            }
            else {
                $('#dlg-background')
				.height('100%')
				.width('100%')
				.css({ 'top': '0px', 'left': '0px', 'position': 'fixed' }); ;
            }

            $('#dlg-message')
				.addClass('viewing-your-meal')
				.html('<div id="view-meal-flash-holder"></div>');

            $('#dlg-close-btn').show();
            $('#dlg-close-btn')
				.addClass('view-your-meal-close-btn');

            $('#add-update-dlg')
				.width(885)
				.height(viewMealBackgroundHeight)
				.removeClass('dlg-view-your-meal-complete')
				.addClass('dlg-view-your-meal')
				.css({ 'background-position': '0 0', 'background-color': '#ffffff' });

            center($('#add-update-dlg'));
        },

        showViewYourMealFlash: function () {
            $('#add-update-dlg')
				.css({ 'background-position': '0 0' });

        },

        closeDialog: function () {
            $('#dlg-modal').hide();
            $('#dlg-container').hide();
            $('#dlg-actions-container').hide();
            $('#dlg-message').html('');
            $('#mymeal_share').remove();
            clearDialog();
            BK.menuNutritionView.Flash.stopLoadingAnimation();
        },

        showUpdateDialog: function () {
            if (isUpdated) {
                isUpdated = false;
                this.showDialog(true);

                return true;
            }

            return false;
        },

        checkUpdateButton: function () {
            var ingrDisplay = $('#ingredient-list').css('display');
            var variationDisplay = $('#variation-list').css('display');
            if ((ingrDisplay == "none") && (variationDisplay == "none")) {
                $('#add-to-meal-holder').hide();
            }
        }
    };
} ();

BK.menuNutritionView.Flash = function () {
    return {
        trayItems: {},

        viewYourMealItems: {},

        mealBuilder: function () {
            return flash('mealbuilder');
        },

        viewYourMeal: function () {
            return flash('viewYourMeal');
        },

        loadingAnimation: function () {
            return flash('loadingAnimation');
        },

        loadPlayer: function (items) {

            this.trayItems = items;

            // embed the flash player
            $('#flash-holder').html('<div id="mealbuilder"></div>');
            var params = { allowFullScreen: true, allowScriptAccess: "always", wmode: "transparent" };
            var attributes = { id: "mealbuilder" };
            swfobject.embedSWF("/flash/mealBuilder_v2.swf", "mealbuilder", "500", "400", "9.0.115", "/flash/expressInstall.swf", null, params, attributes);

        },

        loadVYMPlayer: function (items) {
            this.viewYourMealItems = items;
            var badgesCookie = cookie650CaloriesOrLess() ? "yes" : "no";
            $('#view-meal-flash-holder').html('<div id="viewYourMealFlash"></div>');
            var flashvars = { imagePath: '/cms' + CulturePrefix + 'cms_out/digital_assets/graphics/pages/', badges: badgesCookie };
            var params = { allowFullScreen: true, allowScriptAccess: "always", wmode: "transparent" };
            var attributes = { id: "viewYourMeal" };
            swfobject.embedSWF("/page_templates/cultures" + CulturePrefix + "flash/viewYourMeal.swf", "viewYourMealFlash", "865", viewMealContainerHeight, "9.0.115", "/flash/expressInstall.swf", flashvars, params, attributes);
        },

        loadAnimationPlayer: function () {
            $('#loadingAnimation-flash-holder').html('<div id="loadingAnimation"></div>');
            var params = { allowFullScreen: true, allowScriptAccess: "always", wmode: "transparent" };
            var attributes = { id: "loadingAnimation" };
            swfobject.embedSWF("/flash/loadingAnimation.swf", "loadingAnimation", "75", "75", "9.0.115", "/js/expressInstall.swf", null, params, attributes);
        },

        startLoadingAnimation: function (cssClassName) {
            if (this.loadingAnimation()) {
                // attach class name so that the loading animation can be viewable
                var offsetIndexOfDialog = $('#add-update-dlg').offset();
                var heightOfDialog = $('#add-update-dlg').height();
                var widthOfDialog = $('#add-update-dlg').width();

                if (cssClassName == 'loadingAnimationViewMeal') {
                    $('#loadingAnimation-flash-holder')
					.removeClass()
					.css('top', offsetIndexOfDialog.top + (heightOfDialog / 2) - 25)
					.css('left', offsetIndexOfDialog.left + (widthOfDialog / 2) - 25);
                }
                else {
                    $('#loadingAnimation-flash-holder')
					.removeClass()
					.addClass(cssClassName);
                }
            }

        },

        stopLoadingAnimation: function () {
            if (this.loadingAnimation()) {
                // reset the loading animation back to hidden position
                $('#loadingAnimation-flash-holder')
				.removeClass()
				.css('top', '')
				.css('left', '')
				.addClass('loadingAnimationHidden');
            }
        },

        incrementIngredient: function (ingredientId) {
            if (this.mealBuilder()) {
                this.mealBuilder().incrementIngredient(ingredientId);
            }
        },

        decrementIngredient: function (ingredientId) {
            if (this.mealBuilder())
                this.mealBuilder().decrementIngredient(ingredientId);
        },

        changeValueMealSize: function (item) {
            if (this.mealBuilder())
                this.mealBuilder().changeValueMealSize(item.currentSide.rawXml, item.currentDrink.rawXml);
        },

        changeValueMealDrink: function (item) {
            if (this.mealBuilder())
                this.mealBuilder().changeValueMealDrinkType(item.currentDrink.rawXml);
        },

        changeValueMealSide: function (item) {
            if (this.mealBuilder())
                this.mealBuilder().changeValueMealSide(item.currentSide.rawXml);
        },

        displayMenuItem: function (item) {
            if (this.mealBuilder()) {
                if (item.sandwich) {
                    this.mealBuilder().displayValueMeal(item.sandwich.rawXml, item.currentDrink.rawXml, item.currentSide.rawXml);
                }
                else {
                    this.mealBuilder().displayMenuItem(item.rawXml);
                }
            }
            else {
                $('#flash-holder').html('<img src="' + item.imagePath + '" />');
            }
        },

        displayTrayItem: function (index, item) {
            if (this.mealBuilder()) {
                this.mealBuilder().displayTrayItem(index);
            }
            else {
                $('#flash-holder').html('<img src="' + item.imagePath + '" />');
            }
        },

        addCurrentMenuItemToTray: function () {
            if (this.mealBuilder()) {
                this.mealBuilder().addCurrentMenuItemToTray();
            }
        },

        removeMenuItemFromTray: function (menuItemIndexToRemove) {
            if (this.mealBuilder()) {
                this.mealBuilder().removeMenuItemFromTray(menuItemIndexToRemove);
            }
        },

        updateItem: function () {
            if (this.mealBuilder())
                this.mealBuilder().updateTrayItem();
        },

        removeCurrentItemInFocus: function (itemId) {
            if (this.mealBuilder()) {
                if (itemId) {
                    this.mealBuilder().removeCurrentValueMealItemInFocus(itemId);
                }
                else {
                    this.mealBuilder().removeCurrentItemInFocus()
                }
            }
        },

        publishTray: function () {
            if (this.mealBuilder()) {
                //var imageId = this.mealBuilder().publishTray();
                //TODO: get the tray image contents to display	
            }
        }
    };
} ();

///////////////////////GLOBAL FUNCTIONS/////////////////////////////////////////

function getItemsForTray() {
	return BK.menuNutritionView.Flash.trayItems;
}

function getItemsForViewYourMealTray() {
	return BK.menuNutritionView.Flash.viewYourMealItems;
}

function stopLoadingAnimation() {
	BK.menuNutritionView.Flash.stopLoadingAnimation();
}

function showViewMealFlash() {
	BK.menuNutritionView.Html.showViewYourMealFlash();
}
///////////////////////PAGE INIT///////////////////////////////////////////////

$(document).ready(function () {

    var viewHtml = BK.menuNutritionView.Html;
    var controller = BK.menuNutritionController;

    if ((location.href.indexOf('www.bk.com') > -1) ||
		(location.href.indexOf('secure.bk.com') > -1) ||
		(location.href.indexOf('redesign.bk.com') > -1) ||
		(location.href.indexOf('stage.bk.com') > -1)) {
    } else {
        $('#YourMeal .meal-totals ul.print-share').show();
    }


    init();


    $('#Content #menu_selection #select_from_menu ul li a').live("click", function () {
        $('#list_items ul.main-menu li ul').css('max-height', parseInt(($('#list_items ul.main-menu').height() - 2), 10));
    });

    $('#menu_selection ul li ul li a.ingredient_item, #menu_selection ul li ul li a.sub_category, ul.sub-menu-2 li a').live("click", function (event) {
        //$('#intro-info').css("display", "none");

        hideLowerCalorieWindow();
        clickCount++;

        if ($.browser.chrome) {
            clearTimeout(chromeTimoutDelay);
            clearTimeout(chromeTimeoutIntervalDelay);
            BK.menuNutritionView.Flash.removeCurrentItemInFocus();
        }
        clearInterval(intervalBurgerBuilder);
        for (var i = 0; i < 14; i++) {
            clearTimeout(timeoutBurgerBuilder[i]);
        }
        $('#YourMeal').show();
        $('#intro-info-builder').css("display", "none");
        if (clickCount > 1) viewHtml.hideBreakfast();
        $('ul.allergens li').remove();
        $('#Content #menu_selection #select_from_menu ul li a').removeClass('Active');
        $('ul.sub-menu-2').remove();
        $('ul.menu-sub-menu1').css("display", "none");
        viewHtml.hideDollarBadge();
        controller.onMenuItemSelect($(this).attr('rel'));
        return false;
    });
    //Updating pieces of items (e.g., Chicken Fries, Hash Browns, Sodas)
    $('#variation-list li.each-variation p a').live("click", function (event) {
        //$('#intro-info').css("display", "none");
        $('#intro-info-builder').css("display", "none");
        viewHtml.hideBreakfast();
        $('ul.allergens li').remove();
        $('#Content #menu_selection #select_from_menu ul li a').removeClass('Active');
        $('ul.sub-menu-2').remove();
        $('ul.menu-sub-menu1').css("display", "none");
        viewHtml.hideDollarBadge();
        var addButton = $('#add-to-meal-holder a');

        if (addButton.hasClass('update-meal')) {//upd size/quantity controls
            updateZQ = true;
            if (currMealItem != "") {
                BK.menuNutritionView.Flash.removeMenuItemFromTray(currMealItem);
            }
            currMealItem = "";
            controller.onMenuItemSelect($(this).attr('rel'), true);
        } else {
            controller.onMenuItemSelect($(this).attr('rel'));
        }
        return false;
    });

    $('.addIngredient').live('click', function () {
        viewHtml.hideBreakfast();
        controller.onAddIngredient(viewHtml.getIngredientId($(this)));
        return false;
    });

    $('.subtractIngredient').live('click', function () {
        viewHtml.hideBreakfast();
        controller.onSubtractIngredient(viewHtml.getIngredientId($(this)));
        return false;
    });

    $('a.remove-meal-item').live('click', function () {
        if (parseInt($('#YourMeal h2 em strong').text(), 10) == 1) {
            $('#dlg-close-btn').trigger('click');
        }
        controller.onRemoveItemFromMeal(viewHtml.getMealItemId($(this)));

        return false;
    });

    $('a.meal-item-name').live('click', function () {
        //$('#intro-info').css("display", "none");
        $('#intro-info-builder').css("display", "none");
        if (!viewHtml.showUpdateDialog()) {
            viewHtml.hideBreakfast();
            viewHtml.hideDollarBadge();
            currMealItem = viewHtml.getMealItemId($(this));
            controller.onMealItemSelect(currMealItem);
        }

        return false;
    });

    /*
    $('#share-meal').click(function() {
    $('#meal-share').toggleClass('expanded');
    return false;
    });

    $('#modal-share-meal').click(function() {
    $('#modal-meal-share').toggleClass('expanded');
    return false;
    });
    */
    var hoverTimeout;
    $('#list_items').hover(function () {
        clearTimeout(hoverTimeout);
    }, function () {
        hoverTimeout = setTimeout(function () {
            $('ul.sub-menu-2').remove();
            $('#Content #menu_selection #select_from_menu h2').css("background-position", "left bottom");
            $('#Content #menu_selection #select_from_menu h2').css("width", "202px");
            $('#Content #menu_selection #select_from_menu #list_items').css("width", "202px");
            $('ul.menu-sub-menu1').css("display", "none");
            $('#Content #menu_selection #select_from_menu ul li a').removeClass('Active');
        }, 1000);
    });

    $('#select_from_menu').mouseover(function () {
        $('#intro-info, #intro-info-breakfast, #intro-value-menu, #intro-info-newBreakfastMenu').css("display", "none");
    });

    $('#Content #menu_selection #select_from_menu ul.main-menu li a').live("click", function () {
        viewHtml.closeDialog();
        if (!viewHtml.showUpdateDialog()) {
            menuActive($(this));
        }
        return false;
    });

    $('#meal-limit-message .close').click(function () {
        $(this).parent().css("display", "none");
    });

    $('#more-ingredients').click(function () {
        viewHtml.moreIngredientsButton($(this));
        return false;
    });

    $('#more-less-info').click(function () {
        var mealCount = $('.items-in-meal li').length;
        if (!viewHtml.moreInfoPanelOpen()) {
            $("#nutrition-panel").animate({ top: "0px" }, 500);
            $("#meal-items-holder").animate({ maxHeight: "257px" }, 500);
            $(this).html(CONTENT.MEAL_INFO_LESS);
            $(this).css("background-position", "right -5px");

            if (mealCount <= 5) {
                $('a.remove-meal-item').css("left", "195px");
                $('p.meal-item-nutrifact').css("right", "10px");
            } else {
                $('a.remove-meal-item').css("left", "186px");
                $('p.meal-item-nutrifact').css("right", "2px");
            }

        } else {
            $("#nutrition-panel").animate({ top: "-105px" }, 500);
            $("#meal-items-holder").animate({ maxHeight: "362px" }, 500);
            $(this).html(CONTENT.MEAL_INFO_MORE);
            $(this).css("background-position", "right 5px");
            if (mealCount <= 7) {
                $('a.remove-meal-item').css("left", "195px");
                $('p.meal-item-nutrifact').css("right", "10px");
            } else {
                $('a.remove-meal-item').css("left", "186px");
                $('p.meal-item-nutrifact').css("right", "2px");
            }
        }
        return false;
    });
    $('.each-ingredient').live("mouseover", function () {
        $(this).children('p.ingredientBtns').children('a.icon').css("background-position", "left bottom");
        $(this).children('p.ingredientBtns').children('a.icon').children(".current-quantity").css("opacity", "0.2");
    });
    $('.each-ingredient').live("mouseout", function () {
        $(this).children('p.ingredientBtns').children('a.icon').css("background-position", "left top");
        $(this).children('p.ingredientBtns').children('a.icon').children(".current-quantity").css("opacity", "1");
    });

    $('#print-meal').click(function () {
        $('#share-meal').click();
        BK.menuNutritionController.onPrintMeal();
        setTimeout('window.print()', 2000);
    });

    if ($.browser.msie && $.browser.version < 7) {
        var intContentHeight = parseInt(($('#Content').height() + 140), 10);
        $('#MenuTab').css({ 'height': intContentHeight });
        $('#GlobalHeader').css({ 'height': intContentHeight });
    }
    //Calories Badget

    var cookie650Calories = 'cookie650CaloriesOrLess';
    var toggleRefresh = function () {
        $('#switch').bind("click", function (e) {
            e.preventDefault();
            location.reload(true);
            if ($(this).attr("class") == "off") {
                $(this).attr("class", "on");
                $.cookie(cookie650Calories, "On", { expires: 7 });
                track_lower_calorie_suggestion("calorie_badge_switch", "calorie_badge-on");
            }
            else {
                $(this).attr("class", "off");
                $.cookie(cookie650Calories, '', { expires: -1 });
                $.cookie(cookie650Calories, null);
                track_lower_calorie_suggestion("calorie_badge_switch", "calorie_badge-off");
            }
        });
    }
    setTimeout(toggleRefresh, 1000);

    if (cookie650CaloriesOrLess()) {
        $('#switch').attr("class", "on");
    }

    $('a[href=#help-info]').live('click', function (e) {
        e.preventDefault();
        $('#help-info-modal').show();
        $('#LayoutWrapper').append("<div class='UIBlock'></div>");
        $('.UIBlock').show();
    });
    $('#help-info').appendTo('#LayoutWrapper').append('<p><a href="#" class="close">Close</a></p>');
    $('#help-info-modal .close').click(function () {
        $('#help-info-modal').hide();
        $('.UIBlock').remove();
        return false;
    });
    //End Calories Badget

    //BEGIN: BACK AND NEXT BUTTONS for 650 Calories or Less info pop-up window
    var currentSection = 1;
    $("div[class^='section']").hide();
    showSection(currentSection);
    $("ul li.back a").addClass("inactive");
    $("ul li.next a").addClass("active");

    $("ul li.back a").live('click', function (e) {
        e.preventDefault();
        if (currentSection != 1) {
            currentSection--;
            showSection(currentSection);
            $("ul li.back a").addClass("active");
            $("ul li.next a").addClass("active");
            $("ul li.next a").removeClass("inactive");
        }
        if (currentSection === 1) {
            $("ul li.back a").addClass("inactive");
            $("ul li.back a").removeClass("active");
        }
    });
    $("ul li.next a").live('click', function (e) {
        e.preventDefault();
        if (currentSection != $("div[class^='section']").length) {
            currentSection++;
            showSection(currentSection);
            $("ul li.back a").addClass("active");
            $("ul li.next a").removeClass("inactive");
            
        }
        if (currentSection == 4) {
            $("ul li.next a").addClass("inactive");
            $("ul li.next a").removeClass("active");
        }
    });
    function showSection() {
        $("div[class^='section']").hide();
        $(".section" + currentSection).fadeIn();

    }
    //END: BACK AND NEXT BUTTONS for 650 Calories or Less info pop-up window

    //BEGIN: lower calorie Suggestion Checkboxes

    //End: lower calorie Suggestion Checkboxes


    // Create tabs with the show event rather than the select event so that styles can be 
    // applied to tabs appropriately in IE6
    $("#options-tab a").click(function () {
        customize = true;
    });

    $("#builder-tab a").click(function () {
        customize = true;
    });

    $('#meal-tabs-container').tabs({ show: function (event, ui) {
        if (customize) {
            if (ui.index == 0) {
                $('#info-headline').html(CONTENT.MEAL_INFO);
                controller.onMealValueMealOptionsSelect();
            }
            else {
                $('#info-headline').html(CONTENT.SANDWICH_INFO);
                controller.onMealValueMealSandwichSelect();
            }
        }
        customize = false;
    }
    });
    $('#value-meal-variations li p a').live('click', function () {
        controller.onResizeValueMeal($(this).attr('id').split('-')[1], $(this).attr('rel'));
        var newSize = $(this).find('span').text();
        BK.menuNutritionController.onLogChangeValueMealSize(newSize);
        return false;
    });

    $('.more-caption, .less-caption').live('click', function () {
        $('.current-selection-desc-short, .current-selection-desc').toggleClass('desc-hidden');
        viewHtml.displayNutritionAllergens();
        var moreLess = $(this).hasClass('more-caption') ? BK.local.MENU_NUTRITION.ITEM_MORE : BK.local.MENU_NUTRITION.ITEM_COLLAPSE;
        BK.menuNutritionController.onValueMealMoreLessClick(moreLess);
        return false;
    });

    $('#dlg-close-btn, #dlg-cancel-btn').click(function () {
        viewHtml.closeDialog();
        dialogClosed = true;
        return false;
    });

    /*$('#dlg-cancel-btn').click(function() {
    controller.onRemoveMenuItemInFocus();
    return false;
    });*/

    $('#view-your-meal,#share-meal').click(function () {
        viewMealContainerHeight = 600 + (totalNumberOfItems * 60);
        viewMealBackgroundHeight = viewMealContainerHeight + 15;
        BK.menuNutritionView.Html.showViewYourMealDialog();
        BK.menuNutritionController.onLoadViewMyMeal();
        return false;
    });

    $('#meal-share-close, #close-empty-tray, #close-meal-error').live('click', function () {
        $('#dlg-close-btn').trigger('click');
        return false;
    });

    $('#close-empty-tray').live('click', function () {
        $('#dlg-close-btn').trigger('click');
        return false;
    });

    //Check to see if there's a mymeal variable in the URL.  If so, show the lightbox with the graphic.
    var mymeal = getUrlParam('mymeal');
    if (mymeal != '') {
        $('#dlg-close-btn').trigger('click');
        var subFolderYear = mymeal.substring(0, 4);
        var subFolderMonth = mymeal.substring(4, 6);
        var subFolderDay = mymeal.substring(6, 8);
        var imageUrl = '/bk_mn_share/' + subFolderYear + '/' + subFolderMonth + '/' + subFolderDay + '/' + mymeal + '.jpg';
        BK.menuNutritionView.Html.showViewYourMealDialog();
        $('.dlg-view-your-meal').append('<div id="mymeal_share"><div><img src="' + imageUrl + '" /></div><h4>' + CONTENT.MEAL_SHARE_HEADER + '</h4><p class="tagline"></p><p class="build-meal-button"><a href="" id="meal-share-close">' + CONTENT.MEAL_SHARE_BUTTON + '</a></p><p><p></div>');
        //reposition
        $('#add-update-dlg').css('top', '30px');

    }
});

function shareClick(network, key) {
    var fullUrl = 'http://' + document.domain + CulturePrefix + 'menu-nutrition/index.html?mymeal=' + key;

    var mealUrl = '';
    var shareHref = '';
    if (network != 'print') {
    	track_meal_view_share(network);
    }
    
    if (network == 'twitter') {
    	$.ajax({
    		url: 'http://api.bit.ly/shorten?version=2.0.1&longUrl=' + fullUrl + '&login=bkmn&apiKey=R_3c2642b766b78972463bad1be64e4f92&callback=?',
    		dataType: 'json',
    		async: false,
    		success: function(data) {
    			if (data.errorCode == 0) {
    				mealUrl = data.results[fullUrl].shortUrl;
    			} else {
    				mealUrl = fullUrl;
                }
                shareHref = 'http://twitter.com/home?status=' + CONTENT.MEAL_SHARE_TITLE + ' ' + mealUrl;
    			leavingSitePrompt(shareHref);
    		}
    	});
    } else {
    	switch (network) {
    		case 'email':
    		    {
    				shareHref = 'mailto:?subject=' + CONTENT.MEAL_SHARE_EMAIL_SUBJECT + '&body=' + CONTENT.MEAL_SHARE_EMAIL_BODY1 + fullUrl + CONTENT.MEAL_SHARE_EMAIL_BODY2;
    			}
    			break;
    		case 'facebook':
    		    {
    				shareHref = 'http://www.facebook.com/sharer.php?u=' + fullUrl + '&t=' + CONTENT.MEAL_SHARE_TITLE + fullUrl;
    			}
    			break;
    		case 'digg':
    		    {
    				shareHref = 'http://www.digg.com/submit?phase=2&url=' + fullUrl + '&title=' + CONTENT.MEAL_SHARE_TITLE + '&bodytext=' + fullUrl;
    			}
    			break;
    		case 'reddit':
    			{
    			    shareHref = 'http://www.reddit.com/submit?url=' + fullUrl + '&title=' + CONTENT.MEAL_SHARE_TITLE;
    			}
    			break;
    		case 'stumble':
    			{
    			    shareHref = 'http://www.stumbleupon.com/submit?url=' + fullUrl + '&title=' + CONTENT.MEAL_SHARE_TITLE;
    			}
    			break;
    		case 'fark':
    			{
    			    shareHref = 'http://cgi.fark.com/cgi/fark/farkit.pl?h=' + CONTENT.MEAL_SHARE_TITLE + '&u=' + fullUrl;
    			}
    			break;
    		case 'delicious':
    			{
    			    shareHref = 'http://delicious.com/post?url=' + fullUrl + '&title=' + CONTENT.MEAL_SHARE_TITLE;
    			}
    			break;

    		case 'print':
    			{
    				track_print_meal();
    				window.open('/print-meal.aspx?mymeal=' + key);
    			}
    			break;
    		case 'error':
    			{
    				$('#view-meal-flash-holder').html('<a href="" id="close-meal-error">Close</a>');
    				$('#view-meal-flash-holder').css({
    					'background-image': 'url(/cms/en/us/cms_out/digital_assets/graphics/pages/bkg.div-meal-share-error.png)',
    					'background-position': '0 0',
    					'width': '227px',
    					'height': '137px',
    					'margin': '170px auto'
    				});
    			}
    			break;
    	}
    	if (network != 'error' && network != 'print') {
    		leavingSitePrompt(shareHref);
    	}
    }
}

function getUrlParam( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}
