$.fn.pause = function(duration) {
    $(this).animate({ dummy: 1 }, duration);
    return this;
};

$.fn.slowEach = function( interval, callback ) {
        var array = this;
        if( ! array.length ) return;
        var i = 0;
        next();
        function next() {
            if( callback.call( array[i], i, array[i] ) !== false ) 
                if( ++i < array.length )
                    setTimeout( next, interval );
        }
    };



var dominos = {
	init:function()	{
		dominos.fireCufon();
		dominos.hideSlides();
		dominos.slideListeners();
		dominos.hovers();
		dominos.itemsRollout();
		dominos.navListen();
		dominos.buildFlash();
		dominos.dateWidget();
		dominos.scroller();
		dominos.notifications();
	},
	fireCufon:function()	{
		Cufon.replace(".welcome span");
		Cufon.replace(".item h2");
		Cufon.replace(".flyoutModule h3");
		Cufon.replace("#subNav ul li a",{hover:true});
		if ($.browser.opera) {
			// Fix alignment that cufon just broke
			$("#subNav ul li .divider").css("top", "0px");
		}
		Cufon.replace("a.cufoned",{hover:true});	
		Cufon.replace(".specialtyHeader");
		Cufon.replace("#locationContainer h2");
		Cufon.replace("#locationContent > ul > li.listHeader span");
		Cufon.replace("h3.locationLinks");
		Cufon.replace(".loginPage .cufoned");
		Cufon.replace("h4 span.cufoned");
		Cufon.replace(".couponBox h3");
		Cufon.replace(".subHeading");
	},
	hideSlides:function()	{
		$(".slider").each(function()	{
			$(this).hide();
		});
	},
	addItemsDetails:function()	{
		$(".item").children(".graphic,.desc").each(function() {
			$(this).hover(function()	{
				$(this).parent().addClass("itemOptionsHover");
				Cufon.refresh(".item h2");
			}, function()	{
				$(this).parent().removeClass("itemOptionsHover");
				Cufon.refresh(".item h2");
			});
			$(this).click(function()	{
				$(this).parent().find(".slider").slideToggle("slow");
				$(this).parent().toggleClass("optionsActive");
				Cufon.refresh(".item h2");
			});
		})
	},
	slideListeners:function()	{
		$(".flyout").children(".graphic,.desc").each(function()	{
			$(this).hover(function()	{
				$(this).parent().addClass("flyoutHover");
				Cufon.refresh(".item h2");
			   }, function()	{
				$(this).parent().removeClass("flyoutHover");
				Cufon.refresh(".item h2");
								   });
            $(this).click(function()	{
            	var openingSlider = ($(this).parent().find(".slider").css("display") == "none");

				$(this).parent().find(".slider").slideToggle("slow");
				$(this).parent().toggleClass("active");
				Cufon.refresh(".item h2");		

				if (openingSlider && myEventTracker) {
					if ($(this).parent().attr("id") == "pastOrders") {
						myEventTracker('Get Started Page','Click','Past Orders Popular Items Tile'); 
					} else if ($(this).parent().attr("id") == "couponsContent") {
						myEventTracker('Get Started Page','Click','Coupons Tile');
					}
				}
			});
		});
		if ($("body").hasClass("itemsDetails")) { 
			dominos.addItemsDetails();
		}
	},
	hovers:function()	{
		if ((!$("body").hasClass("itemsDetails")) && (!$("body").hasClass("itemsGrid"))) {
			$(".item:not(.flyout)").hover(function(){
				$(this).addClass("hover");
				Cufon.refresh(".item h2");
			}, function(){
				$(this).removeClass("hover");
				Cufon.refresh(".item h2");
			});
		}
	},
	navListen:function()	{
		// Id of navigation item for current page
		var showSub = $("#nav ul li.active").attr("id");
		// Timers
		var subNavResetTimer;
		var navChangeTimer;
		
		highlightNav = function(idOfNavToShow) {
			clearTimeout(navChangeTimer);
			clearTimeout(subNavResetTimer);
			// Make all navigation items inactive, except the one we're on
			$("#nav ul li").each(function() {
				if ($(this).attr("id") != showSub) {
					$(this).removeClass("active");
				}
			});
			$("#nav ul li#" + idOfNavToShow).addClass("active");
			$("#subNav ul").hide();
			$("#" + idOfNavToShow + "SubNav").each(function() {
				$(this).show();
			});
		};
		lowlightNav = function(idOfNavLeft) {
			clearTimeout(navChangeTimer);
			clearTimeout(subNavResetTimer);
			subNavResetTimer = setTimeout("lowlightSubNav('" + idOfNavLeft + "')", 1000);
			
			$("#" + idOfNavLeft + "SubNav").hover(function() {
				highlightSubNav(idOfNavLeft + "SubNav");
			},function()	{
				lowlightSubNav(idOfNavLeft);
			});
		};
		highlightSubNav = function(idOfSubNavToShow) {
			clearTimeout(subNavResetTimer);
			// Decide what to hide and show
			$("#entreesSubNav, #sidesSubNav, #couponsSubNav, #cateringSubNav").each(function() {
				if ($(this).attr("id") == idOfSubNavToShow) {
					$(this).show();
				} else {
					$(this).hide();
				}
			});
		};
		lowlightSubNav = function(idOfNavLeft) {
			// If leaving a subnav other than current one, revert to current one
			if (showSub != idOfNavLeft) {
				$("#nav ul li#" + idOfNavLeft).removeClass("active");
				$("#" + idOfNavLeft + "SubNav").hide();
				$("#" + showSub + "SubNav").show();
			}
			highlightNav(showSub);
		};
		
		$("#subNav ul").hide();
		
		$("#nav ul li#home a").hover(function()	{
				if (showSub == "home") {
					highlightNav("home");
				} else {
					navChangeTimer = setTimeout("highlightNav('home')", 500);
				}
			},function()	{
				lowlightNav("home");
			});
		$("#nav ul li#entrees a").hover(function() {
				if (showSub == "entrees") {
					highlightNav('entrees');
				} else {
					navChangeTimer = setTimeout("highlightNav('entrees')", 500);
				}
			},function()	{
				lowlightNav("entrees");
			});
		$("#nav ul li#sides a").hover(function() {
				if (showSub == "sides") {
					highlightNav("sides");
				} else {
					navChangeTimer = setTimeout("highlightNav('sides')", 500);
				}
			},function()	{
				lowlightNav("sides");
			});	
		$("#nav ul li#coupons a").hover(function() {
				if (showSub == "coupons") {
					highlightNav("coupons");
				} else {
					navChangeTimer = setTimeout("highlightNav('coupons')", 500);
				}
			},function()	{
				lowlightNav("coupons");
			});
		$("#nav ul li#catering a").hover(function() {
				if (showSub == "catering") {
					highlightNav("catering");
				} else {
					navChangeTimer = setTimeout("highlightNav('catering')", 500);
				}
			},function()	{
				lowlightNav("catering");
			});
		$("#nav ul li#espanol a").hover(function() {
				if (showSub == "espanol") {
					highlightNav("espanol");
				} else {
					navChangeTimer = setTimeout("highlightNav('espanol')", 500);
				}
			},function()	{
				lowlightNav("espanol");
			});
				
		$("#" + showSub + "SubNav").show();	
	},
	itemsRollout:function()	{
		var displayOrder = ["newItems","ohYesWeDid","cateringContent","desserts","sidesAndDrinks","chicken","ovenBakedSandwiches","breadBowlPasta","pickSpecialtyPizza","buildYourOwnPizza","couponsContent","pastOrders"];
		if ($("body").hasClass("rollout")) {
			$(displayOrder).slowEach(500, function(){
				$("#"+this).slideDown();
			});
		}
		else {
			$(".item").show();
		}
		$('div.graphic,h1').pngFix();
		
		
	},
	buildFlash:function()	{
		if ($("#masthead").length != 0) {
			var swfUrl = $("#masthead span:eq(0)").text();
			var id = "mastheadFlash";
			var width = $("#masthead").css("width");
			var height = $("#masthead").css("height");
			var version = "8.0.0";
			var params = {wmode: "opaque", allowScriptAccess: "always"};
			
			// Build flash variables from html content
			var flashvars = {};
			$("#masthead span:[title]").each(function() {
				flashvars[$(this).attr("title")] = escape($(this).text());
			});
			
			swfobject.embedSWF(swfUrl, id, width, height, version, null, flashvars, params, null, dominos.flashCallback);
		}
	},
	flashCallback: function(e)	{
		if (e && !e.success) {
			$("#masthead").hide();
			$("#mastheadNoFlash").show();
		}
	},
	dateWidget:function()	{
		var pickImg = $(".dateInput").next("span").html();
		$(".dateInput").datepicker({showOn: 'both', minDate: 0, buttonText: 'Choose', buttonImage: pickImg, buttonImageOnly: true});

	},
	scroller: function(){
		$('.scroller').each(function(){
			$(this).cycle({
				fx: 'scrollHorz',
				prev: $(this).parent().find('.scrollLeft a'),
				next: $(this).parent().find('.scrollRight a'),
				before: dominos.onBefore,
				after: dominos.onAfter,
				timeout: 0
			});
		});
	},
	onBefore: function (curr, next, opts) {
		$(curr).parent().find("ul").css('overflow-y', 'hidden');
	},
	onAfter: function (curr, next, opts) {
		var index = opts.currSlide;
		$(curr).parent().parent().find(".scrollLeft a")[index == 0 ? 'hide' : 'show']();
		$(curr).parent().parent().find(".scrollRight a")[index == opts.slideCount - 1 ? 'hide' : 'show']();
		$(curr).parent().find("ul").css('overflow-y', 'auto');
	},
	notifications:function() {
		$("#couponCompleteNotification .closeNotification").click(
				function() {
					$(this).parent().get(0).style.display = "none";
					return false;
				});
		// Vertically center notice copy
		$("#couponCompleteNotification").each(function() {
			var ph = $(this).height();
			$(this).children(".noticeCopy").each(function() {
				$(this).css("padding-top", "0");
				$(this).css("padding-bottom", "0");
				var ch = $(this).height();
				$(this).css("padding-top", (ph-ch)/2);
			});
		});
		$(".notification .closeNotification").click(
				function() {
					if ( $(this).parent().attr("id") == "pickFutureOrderTimeNotification") {
						$("#pickFutureOrderTimeNotificationError").hide();
					}
					$(this).parent().get(0).style.display = "none";
					if ($("#builder-crust-section") && $("#builder-crust-section").get(0)
							&& !$OLO('build_own:cwRemCoup')) {
						$("#builder-crust-section").get(0).style.top = "-27px";
					} 
					if ($("builder-topping-section") && $("#builder-topping-section").get(0)
							&& !$OLO('build_own:cwRemCoup')) {
						$("#builder-topping-section").get(0).style.top = "-27px";
					}
					return false;
				});
		$("#storeClosedNotification .makeFutureOrder").click(
				function() {
					$("#storeClosedNotification").get(0).style.display = "none";
					$("#pickFutureOrderTimeNotification").get(0).style.display = "";
					return false;
				});
		$("#recentOrderNotification .trackMyOrder").click(
				function() {
					var terms = $("#recentOrderNotification input[type='checkbox']").get(0);
					if (!terms.checked) {
						$("#popupContentOIS p:first").html("You must agree to the terms of use.");
						showPopup('popupWrapperOIS', 'popupContentOIS');
						return false;
					}
					
					var phone = $("#recentOrderNotification .phoneOneBox").get(0).value;
					var ext = $("#recentOrderNotification .phoneExt").get(0).value;
					
					var regex = new RegExp("[^0-9]", "g");
					phone = phone.replace(regex, "");
					ext = ext.replace(regex, "");
					
					if (phone.length == 0) {
						$("#popupContentOIS p:first").html("You must provide a phone number.");
						showPopup('popupWrapperOIS', 'popupContentOIS');
						return false;
					}
					
					var url = this.href + "?uph=" + phone;
					if (ext.length > 0) {
						url += "+" + ext;
					}
					
					top.location.href = url;
					
					return false;
				});
	},
	navigateSave:function(formName, linkName, params) {
		document.forms[formName][formName + ':_idcl'].value=formName+':'+linkName;
		if (params) {
			for (var prop in params) {
				if (prop && document.forms[formName][prop]) {
					document.forms[formName][prop].value=params[prop];
				}
			}
		}
		document.forms[formName].submit();
		return false;
	},
	navigateCheck:function(formName, linkName, params) {
		if (params) {
			for (var prop in params) {
				if (prop && document.forms[formName][prop]) {
					document.forms[formName][prop].value=params[prop];
				}
			}
		}
		doLeavePage(formName, formName + ":_idcl", formName + ":"+ linkName);
		return false;
	},
	navigate:function(link, formName, linkName) {
		$('#'+formName+'\\:'+linkName).attr('onclick').call(link);
		return false;
	}
};
$(document).ready(dominos.init);