
var YOUTUBEPLAYERS = {};
function onYouTubePlayerReady(playerId) {
   YOUTUBEPLAYERS[playerId] = document.getElementById(playerId);
}

revertSingleVideo = null;

ARBYS.conversionData = {
	'iron': 18,
	'calcium': 1000,
	'vitamin-c': 60,
	'vitamin-a': 5000
};
ARBYS.cartid = 0;
ARBYS.calculateNutrition = function(items) {
	var nutrition = {};
	$.each(items, function(key, item) {
		var item_id = item['item_id'];
		var options = item['options'];
		$.each(options, function(i, option_id) {
			$.each(ARBYS.nutrition[item_id][option_id]['nutrition'], function(key, value) {
				if(!nutrition[key]) {
					nutrition[key] = 0;
				}
				nutrition[key] = nutrition[key] + parseFloat(value);
			});
		});
	});
	return nutrition;
};


/*--- Functions ---*/

/**
 * Output first store locator result
 */
function outputStoreResult(result, origin) {

	var html = "<p>Your closest Arby's&reg; location is:</p>";
	html += "<p>" + result.fields.UnitDesc + "</p>";
	html += "<p class=\"address\">" + result.fields.Phone1 + "<br />";
	html += result.fields.address + "<br />";
	html += result.fields.city + ", " + result.fields.state + " " + result.fields.postal + " " + result.fields.country + "</p>";
	html += "<p class=\"last-child\"><a href=\"" + $("#nav-store-locator-form").attr('action') + "?origin=" + encodeURIComponent(origin) + "\">View Map</a></p>";
	
	$("#nav-store-locator-result").html(html);
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+encodeURIComponent(value)+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length));
	}
	return null;
}

function findStore(origin, callback) {

	$("#nav-origin-input").val(origin);
		
	storeLocated = true;
	$("#nav-store-locator-result").html("<p>Retrieving from mapquest.com...</p>");

	$.getJSON("http://www.mapquestapi.com/search/v1/radius?key=Gmjtd%7Cluu22l01nd%2Cbs%3Do5-lz7a9&hostedData=MQA.MQ_37071_arb_locations&radius=200.0&maxMatches=1&origin=" + encodeURIComponent(origin) + " &callback=?", function(data) {
		
		// Check search results
		if(data.info.statuscode != 0) {
			$("#nav-store-locator-result").html("<p>Help us. Help you. Find us.<br />Let us know city <em>and</em> state. Or the ZIP.</p>");
			return;
		}
		else if(!data.searchResults) {
			$("#nav-store-locator-result").html("<p>Oops. Looks like there isn't an Arby's in your area yet. Check back soon!</p>");
			
		}
		else {
			outputStoreResult(data.searchResults[0], origin);
		}
		
		if(callback) {
			callback(data);
		}
	});
}

function showFoursquareStats(latlng, resultIndex) {
	
	resultIndex = resultIndex || 0;
	
	$.getJSON("https://api.foursquare.com/v2/venues/search?client_id=GTJMICLXLDZJ3S0ALFPXCTL43FBWVZ0I0QSO0ASZ0FKOUUEI&client_secret=FFER3PNXPLKUYKMQFJ34VSF0UOUA2SRKB2QBM51F4ACMAOJJ&ll=" + encodeURIComponent(latlng) + "&query=arbys&limit=" + (resultIndex + 1) + "&callback=?", function(data) {
		
		if(
			!data.response.groups[0]
			|| !data.response.groups[0].items[resultIndex]
		) {
			$(".nav-foursquare").unbind("mouseenter mouseleave");
			return false;
		}
		
		var result = data.response.groups[0].items[resultIndex];
		
		// Filter out results not in "Food" category
		var isFood = false;
		outer:
		for(var i in result.categories) {
			var category = result.categories[i];
			for(var j in category.parents) {
				var parent = category.parents[j];
				if(parent == "Food") {
					isFood = true;
					break outer;
				}
			}
		}
		
		// Try search again
		if(!isFood) {
			showFoursquareStats(latlng, resultIndex + 1);
		}
		
		var html = "<img src=\"" + result.categories[0].icon + "\" alt=\"\" />";
		html += "<p><strong>" + result.name + "</strong>";
		html += "<br />" + result.location.address;
		html += "<br />" + result.location.city + ", " + result.location.state + " " + result.location.postalCode;
		html += "<br />" + result.stats.checkinsCount + " total checkins</p>"
		$("#foursquare-status").html(html);
		
		// Toggle status messages on hover
		$(".nav-foursquare").hover(function() {
			$(this).addClass("hover");
		}, function() {
			$(this).removeClass("hover");
		});
	});
}


/*--- Page Init ---*/

var storeLocated = false;

$(function() {
	
	/*--- Header ---*/
	
	// Pre-load small rollover images
	var img1 = $('<img />').attr('src', '/assets/templates/arbys/images/search-iconRO.png');
	var img3 = $('<img />').attr('src', '/assets/templates/arbys/images/BTN_pdfRO.png');
	var img4 = $('<img />').attr('src', '/assets/templates/arbys/images/BTN_learnMoreRO.png');
	var img5 = $('<img />').attr('src', '/assets/templates/arbys/images/BTN_buildAMealRO.png');

	// Toggle food menu
	$("#nav li.nav-food").hover(
		function(evt) {
			$("li.nav-content > div").stop(true, true).clearQueue().hide();
			$("li").removeClass("nav-content");
			
			$(this).addClass("nav-content");
			Cufon.refresh("#nav>li>a");
			
			$li = $(this);
			$("#food-menu").show();
		},
		function(evt) {
			$li = $(this);
			$("#food-menu").delay(300);
			$("#food-menu").queue(function() {
				$("#food-menu").slideUp("fast", function() {
					$li.removeClass("nav-content");
					Cufon.refresh("#nav>li>a");
				});
				$(this).dequeue();
			});
		}
	);
	

	// Toggle store locator result after search	
	$("#nav li.nav-store-locator").hover(
		function(evt) {
			if(storeLocated) {
			
				$("li.nav-content > div").stop(true, true).clearQueue().hide();
				$("li").removeClass("nav-content");
				
				$(this).addClass("nav-content");
				Cufon.refresh("#nav>li>a");
				
				$("#nav-store-locator-result").show();
			}
		},
		function(evt) {
			if(storeLocated) {
				$li = $(this);
				$("#nav-store-locator-result").queue(function() {
					$("#nav-store-locator-result").slideUp("fast", function() {
						$li.removeClass("nav-content");
						Cufon.refresh("#nav>li>a");
					});
					$(this).dequeue();
				});
			}
		}
	);
	
	// Get location stored in cookie
	var origin = readCookie("origin");
	if(origin) {
		findStore(origin);
	}
	
	// Get foursquare info if latitude and longitude available
	var latlng = readCookie("latlng");
	if(latlng) {
		showFoursquareStats(latlng);
	}
	
	// Get closet store from mapquest on form submission
	$("#nav-store-locator-form").submit(function(evt) {
		evt.preventDefault();
		
		storeLocated = true;
		
		$(".nav-store-locator").addClass("nav-content");
		Cufon.refresh("#nav>li>a");
		
		origin = $("#nav-origin-input").val();
		
		// Create/update location cookie
		createCookie("origin", origin, 0);
		
		findStore(origin, function(data) {
			$("#nav-store-locator-result").show();
			
			// Save latitude and longitude and show foursquare stats
			var latlng = data.origin.latLng.lat + "," + data.origin.latLng.lng;
			createCookie("latlng", latlng, 0);
			showFoursquareStats(latlng);
		});
	});
	
	// Get latest facebook post
	$.getJSON("https://graph.facebook.com/arbys/posts?fields=message&limit=1&callback=?", function(data) {	
		if (!!data.data) {
			var intro = data.data[0].message.substring(0, 50);
			var expanded = data.data[0].message.substring(50);
			var html = "<img src=\"https://graph.facebook.com/arbys/picture\" alt=\"\" />";
			html += "<p>" + intro;
			if(expanded.length > 0) {
				html += "<span class=\"ellipsis\">&hellip;</span>";
				html += "<span class=\"expanded\">" + expanded + "</span>";
				html += "<br /><a href=\"#\" title=\"See more\" class=\"expand-link\">See more</a>";
			}
			html += "</p>";	
			$("#facebook-status").html(html);
		}
		
		$("#facebook-status .expand-link").click(function(evt) {
			evt.preventDefault();
			
			$("#facebook-status .ellipsis").toggle();
			$("#facebook-status .expanded").toggle();
			if($(this).html() == "See more") {
				$(this).html("Go back");
			}
			else {
				$(this).html("See more");
			}
		});
		
		// Toggle status message on hover
		//$(".nav-facebook").hover(function() {
		//	$(this).addClass("hover");
		//},function() {
		//	$(this).removeClass("hover");
		//});
	});
	
	// Get latest twitter post
/*
	$.getJSON("https://twitter.com/status/user_timeline/arbys.json?count=1&callback=?", function(data) {
		var intro = data[0].text.substring(0, 50);
		var expanded = data[0].text.substring(50);
		var html = "<img src=\"" + data[0].user.profile_image_url + "\" alt=\"\" />";
		html += "<p>" + intro;
		if(expanded.length > 0) {
			html += "<span class=\"ellipsis\">&hellip;</span>";
			html += "<span class=\"expanded\">" + expanded + "</span>";
			html += "<br /><a href=\"#\" title=\"See more\" class=\"expand-link\">See more</a>";
		}
		html += "</p>";
		$("#twitter-status").html(html);
		
		$("#twitter-status .expand-link").click(function(evt) {
			evt.preventDefault();
			
			$("#twitter-status .ellipsis").toggle();
			$("#twitter-status .expanded").toggle();
			if($(this).html() == "See more") {
				$(this).html("Go back");
			}
			else {
				$(this).html("See more");
			}
		});
		
		// Toggle status messages on hover
		$(".nav-twitter").hover(function() {
			$(this).addClass("hover");
		},function() {
			$(this).removeClass("hover");
		});
	});
	
*/	
	/*--- Home page ---*/
	
	// Toggle promo image hotspots
	$(".hotspot a.expand-link").click(function(evt) {
		evt.preventDefault();
		$(this).toggleClass("expanded");
		$(this).next(".hotspot-content").toggle();
	});
	$(".hotspot a.expand-link").hover(function() {
		$(this).addClass("expanded");
		$(this).next(".hotspot-content").show();
	}, function() {
		$(this).removeClass("expanded");
		$(this).next(".hotspot-content").hide();
	});
	

	// Toggle zoom tool
	$("#toggle-zoom a").click(function(e) {
		e.preventDefault();
		$(this).toggleClass("enabled");
		if(!$("#zoom-area").is(".hasZoom")) {
			$("#zoom-area").zoom({
				"detailImagePath": "/assets/templates/arbys/images/fishSandwich-large.png"
			});
		}
		$("#zoom-area").zoom("toggle");
	});

	// Toggle promo accordion
	var videoTimeout;
	$("#promo-content .close-btn").click(function(evt) {
                evt.preventDefault();
		$("#toggle-promo a").trigger("click");
	});

	$("#toggle-promo a").click(function(evt) {
		evt.preventDefault();
		
		var parent = $(this).parent();
		
		if(parent.is(".open")) {
				//alert('closing');
				parent.removeClass("open");

			$("#promo-content").slideUp(1000, function() {
                $("#taste-off-video").hide();
				clearTimeout(videoTimeout);
			});
		} else {
			//alert('opening');
			parent.addClass("open");
			$("#promo-content").show().height(1).animate({
  				  height: "739px"
  				}, 1000 );
			$("html,body").animate({scrollTop:($("#promo-content").position().top)+'px'}, 1500);
		}
	});
	$("#promo-content").tabs({});


        // Taste Off Video
        $("#taste-off-tab #play-video").click(function(evt) {
		evt.preventDefault();
                $("#taste-off-video").html(flash_video);
        });

	$("#taste-off-tab #play-video").click(function(evt) {
		evt.preventDefault();

		$("#taste-off-video").show();

		videoTimeout = setTimeout(function() {
			$("#taste-off-video").hide();
		}, 22000);
	});

        $("ul.tabs li a, .close-btn, #toggle-promo").click(function() {
		$("#taste-off-video").hide().html("");
		clearTimeout(videoTimeout);
	});

        
        // Angus Cool Video
        $("#play-ac-video").click(function(evt) {
		evt.preventDefault();
                $("#angus-cool-video").html(flash_video2);
        });
 
        $("#video-tab #play-ac-video").click(function(evt) {
		evt.preventDefault();
                $("#angus-cool-video").show();

                videoTimeout = setTimeout(function() {
                        $("#angus-cool-video").hide();
                }, 16000);
        });

	$("ul.tabs li a, .close-btn, #toggle-promo").click(function() {
		$("#angus-cool-video").hide().html("");
	});
		
		// Casting Call Video
        $("#videoPlace").click(function(evt) {
			evt.preventDefault();
			//document.getElementById("winnerVid").stopVideo();
            $("#accVideoContainer").html(flash_video3);
        });
 
        $("#casting-call-tab #play-cc-video").click(function(evt) {
			evt.preventDefault();
            $("#casting-call-video").show();

            videoTimeout = setTimeout(function() {
	            $("#casting-call-video").hide();
            }, 23000);
        });

	$("ul.tabs li a, .close-btn, #toggle-promo").click(function() {
		$("#casting-call-video").hide().html("");
	});

        // Market Fresh Video
        $("#play-mf-video").click(function(evt) {
		evt.preventDefault();
                $("#market-fresh-video").html(flash_video2);
        });
 
        $("#video-tab #play-mf-video").click(function(evt) {
		evt.preventDefault();
                $("#market-fresh-video").show();

                videoTimeout = setTimeout(function() {
                        $("#market-fresh-video").hide();
                }, 22000);
        });

	$("ul.tabs li a, .close-btn, #toggle-promo").click(function() {
		$("#market-fresh-video").hide().html("");
	});


    // Fish Sandwich Video
       $("#play-fs-video").click(function(evt) {
		evt.preventDefault();
                $("#fish-sandwich-video").html(flash_video4);
        });
 
        $("#video-tab #play-fs-video").click(function(evt) {
		evt.preventDefault();
                $("#fish-sandwich-video").show();

                videoTimeout = setTimeout(function() {
                        $("#fish-sandwich-video").hide();
                }, 40000);
        });

	$("ul.tabs li a, .close-btn, #toggle-promo").click(function() {
		$("#fish-sandwich-video").hide().html("");
	});
	
	// Promo "Angus Story" slide show
	if($("#story-slides").length > 0) {
		var slider = $('<div style="width: 1300px;" />');
		var children = $("#story-slides>div");
		$("#story-slides").append(slider);
		slider.append(children);
		
		var pagingul = $('<ul class="paging" />');
		pagingul.append('<li class="prev-link">Previous</li>');
		for(var i = 0; i < children.length; i++) {
			var current = '';
			if(i == 0) { current = 'class="current" ';}
			$(children[i]).data("page", (i+1));
			pagingul.append('<li '+current+' id="page'+(i+1)+'">'+(i+1)+'</li>');
		}
		pagingul.append('<li class="next-link">Next</li>');
		$("#story-slides").before(pagingul);
		
		pagingul.find("li").not(":first,:last").click(function() {
			var current = slider.find(">div:first");
			current.stop(true,true);
			var currentId = parseInt(current.attr("id").replace("story-slide",''));
			
			var requestedId = parseInt($(this).attr("id").replace("page",''));
			
			var i = requestedId - currentId; 
			while(i!=0) {
				if(i > 0) {
					i--;
					pagingul.find(":last").trigger('click');
				} else {
					i++;
					pagingul.find(":first").trigger('click');
				}
				pagingul.delay(100);
			}
		});
		pagingul.find(":last").click(function() {
			slider.find(">div:first").stop(true,true);
			slider.find(">div:first").animate({
				marginLeft: -730
			}, 400, 'swing', function() {
				var div = slider.find(">div:first");
				slider.append(div);
				div.css("marginLeft", "0px");
				
				pagingul.children().removeClass("current");
				var nextPage = slider.find(">div:first").data("page");
				pagingul.find("#page" + nextPage).addClass("current");
				
				slider.find(">div:first").trigger("visible");
			});
		});
		pagingul.find(":first").click(function() {
			slider.find(">div:first").stop(true,true);
			var div = slider.find(">div:last");
			div.css("marginLeft",-730);
			slider.prepend(div);
			
			slider.find(">div:first").animate({
				marginLeft: 0
			}, 400, 'swing', function() {
				pagingul.children().removeClass("current");
				pagingul.find("#page" + slider.find(">div:first").data("page")).addClass("current");
				
				slider.find(">div:first").trigger("visible");
			});
		});
	}
	
	// Secondary navigation scroll list
	var items = $(".scroll-list li").length;
	if(items > 4) {
		$(".scroll-list").css("marginLeft", 3000);
		$(".scroll-list").animate({marginLeft: 0}, 1000);
		
		//This will make it slide in, remove it to make it pop in
		$(".scroll-list").width(items * 300);
		//end slide in
		$(".scroll-list-view-pane").prev("a.scroll-left").click(function(evt) {
			evt.preventDefault();
			evt.stopPropagation();
			$(".scroll-list").stop(true,true);
			var li = $(".scroll-list li:last");
			var scrollWidth = li.outerWidth(true);
			$(".scroll-list").prepend(li);
			$(".scroll-list").css("marginLeft", -scrollWidth + "px");
			$(".scroll-list").animate({
				marginLeft: 0
			}, 400, 'swing', function() {
			});
		}).show();
		
		$(".scroll-list-view-pane").next("a.scroll-right").click(function(evt) {
			evt.preventDefault();
			evt.stopPropagation();
			$(".scroll-list").stop(true,true);
			var li = $(".scroll-list li:first");
			var scrollWidth = li.outerWidth(true);
			$(".scroll-list").animate({
				marginLeft: -scrollWidth
			}, 400, 'swing', function() {
				 $(".scroll-list").append(li);
				 $(".scroll-list").css("marginLeft", 0);
			});
		}).show();
	}
	/***********************************VIDEOS*******************************************/
	//mouse down to prevent propagation on mousedowns
	$("body#good-mood a.back-btn").mousedown(function(e) {
		e.preventDefault();
		e.stopPropagation();
	});
	$("body#good-mood a.close-btn").mousedown(function(e) {
		e.preventDefault();
		e.stopPropagation();
		
	});
	//END MOUSE DOWN
	
	revertSingleVideo = function () {
		var video = $("body#good-mood a.video_playing");
		if(video.length <1) return;
		$("#myytplayer").remove();
		var dimension = video.data("originaldimension");
		video.find("img").animate({
			width: dimension.width
		}, 400, function() {
			video.closest("div.bubble_frame").removeClass("single_video");	
		});
		video.animate({
			top: dimension.top,
			left: dimension.left,
			width: dimension.width
		},400, function() {
			video.siblings("a.video").show('fast');	
		});
		video.removeClass("video_playing");
	}
	$("body#good-mood .hotspot").hover(function() {
		$(this).next(".popup").show();
	}, function() {
		$(this).next(".popup").hide();
	});
	$("body#good-mood a.close-btn").click(function(e) {
		e.preventDefault();
		e.stopPropagation();
		revertSingleVideo();
		var overlay = $(this).closest("div.bubble_frame");
		overlay.animate({opacity: 0}, 750, 'easeInOutQuad', function() {
			overlay.hide();
			BALLDROP.play();
		});
	});
	$("body#good-mood a.back-btn").click(function(e){
		e.preventDefault();
		e.stopPropagation();
		revertSingleVideo();
	});
	$("body#good-mood a.video").click(function(e) {
		e.preventDefault();
		if ($("#myytplayer").length > 0){}
		else {
		var video = $(this);
		if(video.queue().length >= 1) return false;
		video.siblings("a.video").hide('fast');
		video.addClass("video_playing");
		
		video.data("originaldimension", {
			top:video.position().top,
			left:video.position().left,
			width: video.width()
		});
		
		video.animate({
			top: 60,
			left: 162,
			width: 771
		},400);
		video.find("img").animate({
			width: 771
		}, 400, function() {
			var params = { };
		    var atts = { id: "myytplayer" };
		    video.append('<div id="myytplayer"></div>');
		    swfobject.embedSWF("http://www.youtube.com/e/" + video.attr("href").replace('#', '') + "?enablejsapi=1&playerapiid=ytplayer&autoplay=1&rel=0","myytplayer", "772", "440", "8", null, null, params, atts);
			video.closest("div.bubble_frame").addClass("single_video");
			//replace the video with the youtube video
		});
		
		}
	});
	/*********************************************Menu BUilder**************************************/
	$( "#menu_accordion_categories" ).accordion({
		collapsible: true,
		autoHeight: false
	});
	
	function updateNutrition() {
		var menuItems = $("#menu_cart_contents>ul li").not(".empty");
		if(menuItems.length == 0) {
			//Clear all nutrition info if they cleared the cart
			$("#menu_nutrition_display li span").text(0);
			return;
		}
		
		var items = [];
		menuItems.each(function(i,e) {
			var li = $(e).closest("li");
			items.push({
				item_id: li.data("item_id"),
				options: li.data("item_options")
			});
		});
		var nutrition = ARBYS.calculateNutrition(items);
		var itemCount = 0;
		$.each(nutrition, function(key, value) {
			/*rounding rules*/
			if(key == 'serving-weight') {
				value = Math.round(value);
			} else if(key == 'calories' || key =='calories-from-fat') {
				if(value < 5) { 
					value = 0;
				} else if(value <=50) {
					value = Math.round(value/5) * 5;
				} else {
					value = Math.round(value/10) * 10;
				}
			} else if (key == "fat" || key == "saturated-fat" || key == "trans-fat") {
				if(value < .5) { 
					value = 0;
				} else if(value < 5) {
					value = Math.round(value*2) /2;
				} else {
					value = Math.round(value);
				}
			} else if (key == "cholesterol") {
				if(value < 2) { 
					value = 0;
				} else if(value < 5) {
					value = "5mg";
				} else {
					value = Math.round(value/5) * 5;
				}
			} else if (key == "sodium") {
				if(value < 5) { 
					value = 0;
				} else if(value <= 140) {
					value = Math.round(value/5) * 5;
				} else {
					value = Math.round(value/10) * 10;
				}
			} else if (key == "total-carbohydrates" || key=="dietary-fiber" || key=="sugars" || key =="proteins") {
				if(value < .5) { 
					value = 0;
				} else if(value < 1) {
					value = "1g";
				} else {
					value = Math.round(value);
				}
			} else if (key == "vitamin-a" || key == "vitamin-c" || key == "calcium" || key == "iron") {
				//gotta turn it into a percentage
				value = (value / ARBYS.conversionData[key])* 100;
				if(value < 1) { 
					value = "*";
				} else if(value <=10) {
					value = Math.round(value/2) * 2;
				} else if(value <=50) {
					value = Math.round(value/5) * 5;
				} else {
					value = Math.round(value/10) * 10;
				}
			}
			$("#" + key + " span").text(value);
		});
	}
	
	function openOptions(item, cartItem) {
		var accordion = item.closest(".ui-accordion-content");
		var items = accordion.find("ul li:not(.menu_options)");
		if(!accordion.is(".ui-accordion-content-active")) {
			$( "#menu_accordion_categories" ).accordion("activate", accordion.prev());
		}
		var position = item.prevAll("li:not(.menu_options)").length + 1;
		var insertPosition = Math.min(items.length, Math.ceil(position/3) * 3);
		
		var currentOptions = accordion.find("li.menu_options");
		if(currentOptions.length > 0 && item.attr("id") ==  currentOptions.data('item')) {
			currentOptions.hide('blind','fast', function(){
				$(this).remove();
			});
			return;
		}
		
		var newOptions = $('<li style="display: none" class="menu_options menu_options_'+ ((position-1)%3) +'"><span class="icon icon_selectarrow"></span></li>');
		if(typeof cartItem != 'undefined') {
			newOptions.data('item', cartItem);
			newOptions.append('<a href="#" class="btn update_meal_btn" data-track="meal build:update:'+item.attr('data-tag')+'" data-event="event5">Update Meal</a>');
			newOptions.attr("id", "options_" + cartItem.attr("id"));
		} else {
			newOptions.append('<a href="#" class="btn add_to_meal_btn" data-track="meal build:add:' + item.attr('data-track-name') + '" data-event="event5"  data-track-vars="eVar10=' + item.attr('data-track-name') + ';">Add to meal</a>');
			newOptions.data("item", item);
		}
		newOptions.append('<strong>Options:</strong>');
		newOptions.append('<div></div>');
                if(insertPosition >= items.length) {
			newOptions.css({borderBottom: 'none'});
		}
		
		
		$.each(ARBYS.nutrition[item.attr("id").replace("menu_item_","")], function(id,e) {
			var label = $('<label />');
			var checked = '';
			if(
				(typeof cartItem != 'undefined' && $.inArray(id, cartItem.data("item_options")) >= 0) ||
				(typeof cartItem == 'undefined' && e.selected)
			) {
				checked = 'checked="checked"';
			} 
			label.append('<input type="checkbox" data-track="meal build:select:'+item.attr('data-tag')+':item:'+e.title+'" name="option_id_'+ id +'" '+ checked +'/>').append(e.title);
			newOptions.find("div").append(label);
		});

		if(currentOptions.length) {
			currentOptions.hide('blind','fast', function(){
				$(this).remove();
				$(items[insertPosition-1]).after(newOptions);
				newOptions.show('blind','fast');
			});
		} else {
			$(items[insertPosition-1]).after(newOptions);
			newOptions.show('blind','fast');
		}
	}
	
	$("#menu_accordion_categories .add_to_meal_btn, #menu_accordion_categories .update_meal_btn").live('click', function(e) {
		e.preventDefault();
		e.stopPropagation();
		var options = [];
		var li = $(this).closest("li");
		li.find("input:checked").each(function(i,e) {
			options.push($(e).attr("name").replace("option_id_", ""));
		});
		
		if(options.length == 0) {
			alert("You must select at least 1 option");
			return;
		}
		
		if($(this).is(".add_to_meal_btn")) {
			var item = li.data("item");
			var newItem = item.clone();
			newItem.data("item_id", item.attr("id").replace("menu_item_","")).data("item_options",options).attr("id", "cart_id_" + ARBYS.cartid ++);
			$("#menu_cart_contents li.empty").text("Select an item to customize");
			$("#menu_cart_contents>ul").append(newItem);
		} else {
			li.data("item").data("item_options", options);
		}
		$("#menu_accordion_categories").find("li.menu_options").hide("blind", 'fast', function() { $(this).remove();});
		updateNutrition();
	});
	
	$( "#menu_accordion_categories li").click(function(e) {
		e.preventDefault();
		openOptions($(this));
	});
	$("#menu_cart_contents>ul li a.icon_remove").live("click", function(e) {
		e.preventDefault();
		e.stopPropagation();
		var li = $(this).closest("li");
		li.remove();
		$("#menu_accordion_categories").find("li#options_" + li.attr("id")).hide("blind", 'fast', function() { $(this).remove();});
		updateNutrition();
	});
	$("#menu_cart_contents>ul li").live("click", function(e) {
		e.preventDefault();
		e.stopPropagation();
		openOptions($("#menu_item_"+$(this).data("item_id")), $(this));
	});
	

});



$.widget("arbys.zoom", {
	zoomTool: null,
	enabled: false,
	mouseIn: false,
	detailImageLoaded: false,
	options: {
		"zoomToolId": "zoom-tool",
		"zoomFactor": 1.2,
		"cursorOffsetX": 175,
		"cursorOffsetY": 200
	},
	_showZoomTool: function() {
		this.zoomTool.hide().stop(true,true).fadeIn();
		return this;
	},
	_hideZoomTool: function()  {
		this.zoomTool.stop(true,true).fadeOut();
		return this;
	},
	_positionZoomArea: function(x,y) {
		var maxX = this.element.width();
		var maxY = this.element.height();
		x = Math.max(this.options.cursorOffsetX /2 , Math.min(maxX, x));
		y = Math.max(this.options.cursorOffsetY /2, Math.min(maxY, y));
		
		this.zoomTool.css({
			"top": (y - this.options.cursorOffsetY) + "px",
			"left": (x - this.options.cursorOffsetX) + "px"
		});
		
		if(this.detailImageLoaded)
		{
			var backgroundPositionX = (-x * this.options.zoomFactor) + this.zoomTool.width();
			var backgroundPositionY = (-y * this.options.zoomFactor) + this.zoomTool.height();
			var backgroundPosition = backgroundPositionX + "px " + backgroundPositionY + "px";

			this.zoomTool.css("background-position", backgroundPosition);
		}
		
		return this;
	},
	_create: function() {
		
		this.zoomTool = $("<div id=\"" + this.options.zoomToolId + "\" style=\"z-index:100000\"></div>");
		this.element.css("position", "relative").append(this.zoomTool);
		
		// Wait for detail image to load
		var widget = this;
		$detailImage = $("<img src=\"" + this.options.detailImagePath + "\" />").load(function(evt) {
			widget.detailImageLoaded = true;
			widget.zoomTool.css({
 				"background-image": "url('" + widget.options.detailImagePath + "')"
 			});
 			widget._positionZoomArea(evt.pageX - widget.element.offset().left, evt.pageY - widget.element.offset().top );
		});
		
		this.element.find('img').hover(function() {
			widget.mouseIn = true;
		}, function() {
			widget.mouseIn = false;
		});
		this.element.mousemove(function(evt) {
			if(widget.enabled /*&& widget.mouseIn*/) {
				widget._positionZoomArea(evt.pageX - widget.element.offset().left, evt.pageY - widget.element.offset().top );
			}
		});
		this.element.click(function(){$("#toggle-zoom a").click();});
	},
	toggle: function() {
		if(!this.enabled) {
			this.enabled = true;
			this._positionZoomArea(this.element.width() /2,this.element.height() /2)._showZoomTool();
			//this._showZoomTool();
		} else {
			this.enabled = false;
			this._hideZoomTool();
		}	
	}
});


