var BESO = BESO || {};
var LOGGED_IN_PARAM = 'logged_in=1';

function createFavorite(favData) {
	var url = '/account/add-favorite?id=' + favData.id + '&type=' + favData.type + "&timestamp=" + new Date().getTime();
	$.get(url, function(response) {
    });
}
function deleteFavorite(favData) {
	var url = '/account/remove-favorite?id=' + favData.id + '&type=' + favData.type + "&timestamp=" + new Date().getTime();
	$.get(url, function(response) {
    });
}

BESO.recent = {
	cycle_timeout:'',
	recentData:{},
	loadData:function(callback) {
		var that = this;		
		jQuery.getJSON('/my/aggregate-viewed-items',function(json) {
			jQuery("#rvrotator .loader").hide();
			that.recentData = json;
			callback();
		});
	},
	init:function() {
		var that = this;
		this.loadData(function() {that.setupRecent() });		
	},
	setupRecent:function() {
		var that = this;
		var items = this.recentData.rvItems;
		var firstThree = '';
		for (var i = 0; items != null && i < items.length && i < 3; i++) {
			var item = that.buildRecentProduct(items.shift());
			firstThree += '<li>'+item+'</li>';
		}
		jQuery("#rvrotator").prepend(firstThree);
		this.cycle_timeout = setTimeout(function() { that.initiateRotator() }, 4000);
	},
	buildRecentProduct:function(item) {
		var productPhoto = '<a href="' + item.detailsUrl + '"><img src="' + item.imageUrl +'" id="photo_'+item.id+'" border="0"/></a>';
		var productBrandCategory = '';
        if(item.brand) {
            productBrandCategory += '<a href="'+ item.brand.url + '"><span class="brand">'+ item.brand.name +' /</span> </a>';   
        }
        if (item.category) {
            productBrandCategory += '<a href="'+ item.category.url + '">'+ item.category.name + '</a>';    
        }
		var productTitle = '<p class="product-title"><a href="'+ item.detailsUrl + '">' + item.title +'</a></p>';
		var productDesc = '<p class="desc"><a href="'+ item.detailsUrl + '">' + item.desc +'</a></p>';

		var productMerchantPrice='';
        if(item.merchant) {
            productMerchantPrice +='<p class="merchant"><a href="'+ item.merchant.url + '">' + item.merchant.name +'</a>';
        }
        productMerchantPrice += '<span class="price">'+ item.price +'</span></p>';

		
		var $item = productPhoto+productBrandCategory+productTitle+productDesc+productMerchantPrice;
		return $item;
	},
	initiateRotator:function() {
		var that = this;
		var itemLength = this.recentData.rvItems.length;
		var items = this.recentData.rvItems;
		if (this.cycle_timeout) {
			clearTimeout(this.cycle_timeout);
		}
		if (itemLength > 0) {
			var next_item = that.buildRecentProduct(items.shift());
			var row = '<li></li>';
						
			jQuery("#rvrotator").prepend(jQuery(row).animate({height: '84px'}, {duration: 400, complete:function() { jQuery(this).append(next_item);}}));
			
			if ($("#rvrotator").find("li").length > 4 ) {
                $("#rvrotator").find("li:last").remove();
            }
		} else {			
			this.loadData(function() { that.initiateRotator() });
			return false;
		}
		this.cycle_timeout = setTimeout(function() { that.initiateRotator() }, 4000);
	},
	stopRotation:function() {
		clearTimeout(this.cycle_timeout);
	},
	restartRotation:function() {
		var that = this;
		this.cycle_timeout = setTimeout(function() { that.initiateRotator() }, 4000);
	}
}


BESO.favoriting = {
	cycleTimer:'',
	init:function(heart) {
		var item = jQuery(heart);
		var id = item.attr("id");
		
		item.hasClass(".faved") ? this.removeFavorite(id) : this.addFavorite(id);
	},
	openFavoriting:function(foo) {
		var layer = jQuery(foo).parent().find(".fave-choice-layer");
		var allLayers = jQuery(".fave-choice-layer");
		
		allLayers.hide();
		layer.show();
		this.cycleTimer = setTimeout(function() { layer.hide() }, 4000);
	},
	closeFavoriting:function(foo) {
		var layer = jQuery(foo).parent();
		layer.hide();
	},
	createFavorite:function(faveData) {
		var url = '/account/add-favorite?id=' + faveData.id + '&type=' + faveData.type + "&timestamp=" + new Date().getTime();
		$.get(url, function(response) {});
	},
	deleteFavorite:function(faveData) {
		var url = '/account/remove-favorite?id=' + faveData.id + '&type=' + faveData.type + "&timestamp=" + new Date().getTime();
		$.get(url, function(response) {});
	},
	extractFaveType:function(id) {
		var parts = id.split("_");
		return {
			id: parts[parts.length - 2],
			type: parts[parts.length - 3]
		};
	},
	addFavorite:function(id) {
		var faveData = this.extractFaveType(id);
		var faveClass = jQuery('.'+faveData.id);
		var that = this;

		this.createFavorite(faveData);
		$('#'+id).addClass("faved");
		
		faveClass.each(function() {
			var id = jQuery(this).attr('id');
			faveClass.addClass("faved");
			that.markOuterHeart(id);
		});
	},
	removeFavorite:function(id) {
		var faveData = this.extractFaveType(id);
		var faveClass = jQuery('.'+faveData.id);
		var that = this;

		this.deleteFavorite(faveData);
		$('#'+id).removeClass("faved");
		faveClass.each(function() {
			var id = jQuery(this).attr('id');
			faveClass.removeClass("faved");
			that.markOuterHeart(id);
		});
	},
	markOuterHeart:function(id) {
		var outerHeart = jQuery("#"+id).parents(".fave-it").find(".fave-heart");
		var listItem = jQuery("#"+id).parents(".fave-choice-layer").find("p");
		var hasFave = false;
		
		listItem.each(function() {
			var item = jQuery(this).children("a");
			
			if (item.hasClass(".faved")) {
				hasFave = true;	
				return false;
			}
		});
		if (hasFave == true) {
			outerHeart.addClass("chosen-fave");
		}
		if (hasFave == false) {
			outerHeart.removeClass("chosen-fave");
		}		
	}
}


jQuery(function($){
	$(".fave-heart").click(function(e) {
		e.preventDefault();
		BESO.favoriting.openFavoriting(this);
	});
	$(".close-fave-choice-layer").click(function(e) {
		e.preventDefault();
		BESO.favoriting.closeFavoriting(this);
	});
	$(".fave-choice-layer .favorite").click(function(e) {
		e.preventDefault();
		BESO.favoriting.init(this);
	});
	$(".fave-choice-layer").hover(
		function() {
			clearTimeout(BESO.favoriting.cycleTimer);
			$(this).show();
		},
		function() {
			$(this).fadeOut();
	});
});



$(document).ready(function(){
	
	var qviewLayer = $("#qview"); // 700px wide
	
	var qviewHeight = $("#qview").height(); //425px
	
	
	
	// Hover and Quick Detail functionality for grid view pages (ie search results and category search results)
	
	$(".product_container,.product_container_fav").each(function() {
		var productContainer = $(this);
		var theProduct = $(this).children(".product", this);
		var qviewWidth = qviewLayer.width(); //700;
		
		//var lPosition = $(this).position().left - 10; //$(this).parent(".product_container").position().left - 10
		
				
		theProduct.hover(
			function() {
				var qviewButton = $(this).children("a.see_details_button", this);
				
				productContainer.addClass("hover");
				qviewButton.show();
			    
				qviewButton.click(function(e) {
					e.preventDefault();
					
					var qviewport = $("#content").width(); // 960px
					var leftPosition = (qviewport/2) - (qviewWidth/2); //145;
					var tPosition = productContainer.position().top - 74; //$(this).parent(".product_container").position().top - 74;
					
					$(this).unbind("click");

					$("#qview .boxbody").html("");
					$("#qview .loader").show();

					$.get('/' + this.id + '/quick-detail', function(response) {
                        $("#qview .boxbody").html(response);
                        $("#qview .loader").hide();
                        initFavorites();
                    });

					qviewLayer.css("left",leftPosition);
					qviewLayer.css("top",tPosition);
					qviewLayer.fadeIn(100);
					qviewButton.hide();
				});
			},
			function() {
				var qviewButton = $(this).children("a.see_details_button", this);
				
				productContainer.removeClass("hover");
				qviewButton.hide();
			}
		);
	});
	
	$("#qview .close_button").click(function() {
		$("#qview").hide();
		$("#qview .boxbody").html("");
		$("#qview .loader").show();
	});


	// Hover and Quick Details functionality for the carousels

	$(".single_carousel,.single_carousel_five,.single_carousel_four").each(function() {
		var theCarousel = $(this);
		var singleProduct = $(this).children(".body_container").children(".bottom_shadow").children(".body").children().children(".wrapper").children("ul").children("li").children(".single_product_container").children(".single_product", this);
		
		var qviewWidth = 700; //qviewLayer.width()
		var leftPosition = 145; //(qviewport/2) - (qviewWidth/2)
		
		singleProduct.hover(
			function() {
				var qviewButton = $(this).children("a.see_details_button", this);
				
				$(this).addClass("over");
				qviewButton.show();
			
				qviewButton.click(function(e) {
					$(this).unbind("click");
					
					var carouselTop = theCarousel.position().top;
					var tPosition = (carouselTop - 57);	
					
					$("#qview .boxbody").html("");
					$("#qview .loader").show();
					
					$.get('/' + this.id + '/quick-detail', function(response) {
						$("#qview .boxbody").html(response);
						$("#qview .loader").hide();
						initFavorites();					
					});
					e.preventDefault();
					
					qviewLayer.css("left",leftPosition);					
					qviewLayer.css("top",tPosition);
					qviewLayer.fadeIn(100);
					qviewButton.hide();
				});
			},
			function() {
				var qviewButton = $(this).children("a.see_details_button", this);
				
				$(this).removeClass("over");
				qviewButton.hide();
			}
		);
	});


	// Hover and Quick Details functionality for the Related Products on the Offer Details page


	$(".related_products_grid").each(function() {
		var theGrid = $(this);
		var singleProduct = $(this).children(".body_container").children("ul").children("li").children(".single_product_container").children(".single_product", this);
		var qviewWidth = 700; //qviewLayer.width()
		var leftPosition = 145; //(qviewport/2) - (qviewWidth/2)

		singleProduct.hover(
			function() {
				var qviewButton = $(this).children("a.see_details_button", this);
				
				$(this).addClass("over");
				qviewButton.show();
				
				qviewButton.click(function(e) {
					$(this).unbind("click");
					
					var gridTop = theGrid.position().top;
					var tPosition = (gridTop + 45);	
					e.preventDefault();
					
					$("#qview .boxbody").html("");
					$("#qview .loader").show();
					
					$.get('/' + this.id + '/quick-detail-od', function(response) {
						$("#qview .boxbody").html(response);
						$("#qview .loader").hide();
						initFavorites();					
					});
					
					
					qviewLayer.css("left",leftPosition);					
					qviewLayer.css("top",tPosition);
					qviewLayer.fadeIn(100);
					qviewButton.hide();
				});
			},
			function() {
				var qviewButton = $(this).children("a.see_details_button", this);
				
				$(this).removeClass("over");
				qviewButton.hide();
			}
		);
	});







	// Hover and Quick Detail functionality for Whats New Products
	
	$("#thenewproducts .single_product_new").each(function() {
		var qviewButton = $("#thenewproducts .single_product_new").children(".middle").children(".new_product_container").children("a");
	
		var qviewWidth = 700; //qviewLayer.width()
		var leftPosition = 145; //(qviewport/2) - (qviewWidth/2)
		
		$(this).hover(function() {
			$(this).addClass("hover");
			qviewButton.show();
			
			qviewButton.click(function(e) {
				$(this).unbind("click");
	
				var topPosition = $(this).parents(".single_product_new",this).position().top + 20;
	
				e.preventDefault();
				$("#qview .boxbody").html("");
				$("#qview .loader").show();
				
				$.get('/' + this.id + '/quick-detail', function(response) {
					$("#qview .boxbody").html(response);
					$("#qview .loader").hide();
					initFavorites();
				});
				
				qviewLayer.css("left",leftPosition);
				qviewLayer.css("top",topPosition);
				qviewLayer.fadeIn(100);
				qviewButton.hide();
			});
		},function() {
			$(this).removeClass("hover");
			qviewButton.hide();
		});
	});


	
	$("#sd-email-landing .fullpage, #sd_featured_products .fullpage").each(function() {
		var theFeature = $(this);
		var singleProduct = $(this).children(".boxbody").children(".wrapper").children(".product-container").children(".product", this);
		
		var qviewWidth = 700; //qviewLayer.width()
		var leftPosition = 145; //(qviewport/2) - (qviewWidth/2)
		
		singleProduct.hover(
			function() {
				var qviewButton = $(this).children("a.peek_button", this);
				var prodTop = singleProduct.position().top;
				var featureHeight = theFeature.height();
								
				$(this).parent().addClass("over");
				qviewButton.show();
			
				qviewButton.click(function(e) {
					$(this).unbind("click");

					var featureTop = theFeature.position().top;
					var tPosition = featureTop + (featureHeight/2) - 213;	
					
					$("#qview .boxbody").html("");
					$("#qview .loader").show();
					
					$.get('/' + this.id + '/quick-detail', function(response) {
						$("#qview .boxbody").html(response);
						$("#qview .loader").hide();
						initFavorites();					
					});
					e.preventDefault();
					
					qviewLayer.css("left",leftPosition);					
					qviewLayer.css("top",tPosition);
					qviewLayer.fadeIn(100);
					qviewButton.hide();
				});
			},
			function() {
				var qviewButton = $(this).children("a.peek_button", this);
				
				$(this).parent().removeClass("over");
				qviewButton.hide();
			}
		);
	});
	
	
	


	// Search Results Page Sort functionality
	
	$("#sort_pulldown").click(function() {
		$("#sort_pulldown .sort_choices").show();

		/*		
			var theInput = $("input#sortchoice");
			var theChoices = $("#sort_pulldown .sort_choices").children(".body").children("div").children("p").children("a");
			
			theChoices.each(function() {
				$(this).click(function(e) {
					
				});
			});
		*/
	});
	
	$("#sort_pulldown .sort_choices").mouseover(function() {
		$(this).show();
	});
	
	$("#sort_pulldown .sort_choices").mouseout(function() {
		$(this).hide();
	});


	
	// Main Nav Drop Menus

	$("ul#main_nav > li > .navwrap,ul#nav_search > li > .navwrap,ul#fnav > li > .navwrap").each(function() {
		var theMenu = $(this).children(".menu_shell");
				
		$(this).hover(
			function() {
				var linkWidth = $(this).children("a").width();
				var linkHeight = $(this).children("a").height();
				var theMenuWidth = theMenu.width() + 5;
				var leftPosition = ((linkWidth + 10)/2) -65;
				
				
				$(this).addClass("on");
				theMenu.css("left",leftPosition);
				theMenu.css("top",22);
	
				theMenu.show();
	
			},function() {
				$(this).removeClass("on");
				theMenu.hide();
			});
	
	});


	$("ul#accountlinks > li.mybeso").each(function() {
		var theMenu = $(this).children(".menu_shell");
		
		$(this).hover(
			function() {
				var linkWidth = $(this).children("a").width();
				var linkHeight = $(this).children("a").height();
				var theMenuWidth = theMenu.width() + 5;
				var leftPosition = ((linkWidth)/2) -65;
				
				
				$(this).addClass("on");
				theMenu.css("left",leftPosition);
				theMenu.css("top",24);
	
				theMenu.show();
	
			},function() {
				$(this).removeClass("on");
				theMenu.hide();
			});
	});





	/*
		$("ul#nav_search > li > .navwrap").each(function() {
			$(this).mouseover(function() {
				$(this).addClass("on");
			});
			$(this).mouseout(function() {
				$(this).removeClass("on");
			});
		});
	*/


	/* Storefront About Layer */
	
	var aboutLayer = $("#storefront_about");
	
	$("#about").hover(function() {
		var aboutwidth = $(this).width();
		var testing = ((aboutwidth/2) - 145);	
			
		aboutLayer.css("left",testing);
		$("#storefront_about").animate({opacity: "show", top: "14"}, "slow");
	}, function() {
		$("#storefront_about").animate({opacity: "hide", top: "20"}, "fast");
	});
	
	
	$("#feedback_link").colorbox({initialWidth:"100px", initialHeight:"100px", inline:true, href:"#contact_us", title:"Contact Us"}, 
		function() {
			$("#contactUs_iframe").attr("src", $("#iframeUrl").text());
		});
	
	$(".contact_link").colorbox({initialWidth:"100px", initialHeight:"100px", inline:true, href:"#contact_us", title:"Contact Us"}, 
		function() {
			$("#contactUs_iframe").attr("src", $("#iframeUrl").text());
		});

	
	$("#quick_details_close").click(function() {
		details.fadeOut(50);
	});

	$("#price_change_link a").click(function() {
		openPriceRefinements();
		return false;
	});

	// Method to show the chose price range with the refinement box.

	var minPrice = $("#minPrice").val();
	var maxPrice = $("#maxPrice").val();

	var priceDisplay = $("#selected_price li").html();
	
	$("#selected_price li").html("$" + minPrice + " - $" + maxPrice);

    $("#sort_options_pulldown").change(function() { 
        document.location.href = this.value;
    });

    $('.wishlist').each(function() {
        $(this).click(function(e) {
            e.preventDefault();
            var id_array = this.id.split('_');
            var oid = id_array[ id_array.length - 1];
        });
    });
    
	var shown = false;
	$("a#debug_expand").click(function(e) {
		e.preventDefault();
		if (shown == true) {
			$("#debug_header_content").hide();
			$(this).html("Expand");
			shown = false;
		} else {
			$("#debug_header_content").show();
			$(this).html("Contract");
			shown = true;
		}
	});

    
	// Special Offers (in Quick Details i think)
	
	if ($("#special_offers .bullet").size() > 3) {
		adjustSpecialOffers();
		$("#special_offers .more_less").show();
	}


	function adjustSpecialOffers() {
		var closedHeight = 0;    
		var openHeight = 0;
		var moreSpecialOffers = false;
	
	
		$("#special_offers .bullet").each(function(i) {
			var offerHeight = $(this).outerHeight();
			
			if (i <= 2) {
				closedHeight += offerHeight;
			} 
			openHeight += offerHeight;
		
		});
		
		$("#special_offers").children(".constrainer").css("height",closedHeight - 2);
		
		
		$("#special_offers .more_less a").click(function(e) {
			e.preventDefault();
			if (moreSpecialOffers == true) {
				$("#special_offers").children(".constrainer").css("height",closedHeight-2);
				$(this).html("See More");
				moreSpecialOffers = false;
			} else {
				$("#special_offers").children(".constrainer").css("height",openHeight-2);
				$(this).html("See Less");
				moreSpecialOffers = true;
			}
		});
	}

	function initForgotPassword() {
		$("#forgot_password_link,#password-reset").click(function(e) {
			e.preventDefault();
			$.fn.colorbox({inline:true, href:"#forgot_password", open:true, title:"Reset your Password", transition:"none"},
				function() {
					$.get("/app/forgot-password", function(response) {
						var response = $("#fp_padding", response).html();
						$("#fpshell").html(response);
						
						$("#close_layer").click(function(e) {
							e.preventDefault();
							$.fn.colorbox.close();
						});
						$("#password_reset").submit(function(e) {
							e.preventDefault();
							$("#fpshell").html("");							
							$.post("/account/forgot-password", $(this).serialize(),
								function(response) {
									var success = $("#fp_complete_pod", response).html();
									$("#fpshell").html(success);
									
									$("#close_layer").click(function(e) {
										e.preventDefault();
										$("#fpshell").html("");
										$.fn.colorbox.close();
									});	
								});
							
						});
					});
				});
		});
	}
	
	initForgotPassword();				

	
	

	$("#loginData").load(
		function() {
			var response = $("#response", $("#loginData").contents()).html();
			if (response && response.length == 2) {
				$("#loginData").contents().html("");
				submitLogin();
			} else {
				var icontents = $("#loginData").contents().find("#failed_login").html();
				if (icontents) {
					$("#reg_shell").html(icontents);
					initForgotPassword();
				}
			}
		}
	);
	
	$("#registrationData").load(function() {
		var regOk = $("#registrationOK", $("#registrationData").contents()).html();
		if (regOk) {
			$("#reg_shell").html(regOk);
		} else {
			var regcontents = $("#login_reg_pod", $("#registrationData").contents()).html();
			if (regcontents) {
				$("#login_reg_pod").html(regcontents);
				initForgotPassword();
			}
		}
	});

	
	
	$("#signin,#signin_sweeps,.signin_trigger").colorbox({inline:true, href:"#ajax_registration", title:"Sign in or Sign up", transition:"none"},
		function() {
	    	$("#reg_shell").html("");
	    	$.get("/app/login-ajax", function(response) {
				$("#reg_shell").html(response);
				
				$("#close_layer").click(function(e) {
					e.preventDefault();
					$.fn.colorbox.close();
				});
				initForgotPassword();				
		});
	});

	$(".loginlink").colorbox({inline:true, href:"#ajax_registration", title:"Sign in or Sign up", transition:"none"},
		function() {
	    	$("#reg_shell").html("");
	    	$.get("/app/login-ajax", function(response) {
				$("#reg_shell").html(response);
				
				$("#close_layer").click(function(e) {
					e.preventDefault();
					$.fn.colorbox.close();
				});
				initForgotPassword();				
		});
	});


	function submitLogin() {
		var currentURL = window.location.href.split("#")[0];
		var anchor = window.location.href.split("#")[1];
		var newUrl = currentURL;		
		if (anchor) {
			newUrl += (currentURL.split("?")[1] ? '&' : '?') + LOGGED_IN_PARAM + '#' +  anchor;
		} else {
			newUrl += (currentURL.split("?")[1] ? '&' : '?') + LOGGED_IN_PARAM;
		}
        document.location =  newUrl;
	}



	function extractFavoriteFromId(id) {
		var parts = id.split("_");
		return {
			id: parts[parts.length - 1],
			type: parts[parts.length - 2]
		};
	}
	
	// favoriting mechanism

	var addFavorite = function() {
		var tooltip = $(this).parent().children(".tooltip_a");
		var ttcontent = $(this).parent().children(".tooltip_a").children(".tip");
		var ttpointer = $(this).parent().children(".tooltip_a").children(".pointer");
		var message = $(this).parent().children(".favmsg");
		var favlabel = $(this).parent().children(".fav_label")
		
		createFavorite(extractFavoriteFromId($(this).attr("id")));
		$(this).addClass("faved");
		tooltip.hide();
		favlabel.hide();
		message.html("Added to Favorites")
		message.show();
		$(this).unbind("click");
		$(this).click(removeFavorite);
		setTimeout(function() { message.fadeOut() }, 1200);
	}

	
	var removeFavorite = function() {
		var tooltip = $(this).parent().children(".tooltip_r");
		var ttcontent = $(this).parent().children(".tooltip_r").children(".tip");
		var ttpointer = $(this).parent().children(".tooltip_r").children(".pointer");
		var message = $(this).parent().children(".favmsg");
		var favlabel = $(this).parent().children(".fav_label")

		deleteFavorite(extractFavoriteFromId($(this).attr("id")));
		$(this).removeClass("faved");
		tooltip.hide();
		message.html("Removed from Favorites")
		message.show();
		$(this).unbind("click");
		$(this).click(addFavorite);
		setTimeout(function() { message.fadeOut(500, function() { favlabel.show();}); }, 1200);
		
	}

	function initFavorites() {
		$(".promote_favorite").each(function() {
			var tooltip = $(this).children(".tooltip_a");
			var tooltip2 = $(this).children(".tooltip_r");
			var f_icon = $(".favorite", this);
			
			if (f_icon.hasClass(".faved")) {
				
				f_icon.mouseover(function() {
					if (f_icon.hasClass(".faved")) {
						tooltip2.show();
					} else {
						tooltip.show();
					}
				});
				
				f_icon.mouseout(function() {
					tooltip.hide();
					tooltip2.hide();
				});
				f_icon.click(removeFavorite);
			} else {
				
				f_icon.mouseover(function() {
					if (f_icon.hasClass(".faved")) {
						tooltip2.show();
					} else {
						tooltip.show();
					}
				});
				
				f_icon.mouseout(function() {
					tooltip.hide();
					tooltip2.hide();
				});
				
				f_icon.click(addFavorite);
			}
		});
	
		$(".offer_fave_trigger").each(function() {
			var layer = $(this).children(".fav_layer");
			//var favmsg = $(this).children(".fav_layer").children(".wrapper").children(".promote_favorite").children(".favmsg", this);
			var favmsg = $(this).find(".favmsg", this);
			
			$(this).hover(function() {
				layer.fadeIn();
			},
			function() {
				layer.fadeOut();
				favmsg.each(function() {
					$(this).fadeOut();
				});
			});
		});	
	}


	$("#close_signin_msg").click(function(e) {
		e.preventDefault();
		$("#logged_in").hide();
	});

	initFavorites();

    if (/logged_in=1/.test(document.location.href) ) {
        $("#logged_in").show();
    }
    
    
    
    
	$("#rateus_tab").colorbox({initialWidth:"100px", initialHeight:"100px", inline:true, href:"#nps", title:"Rate us!"}, 
	function() {
		$("#nps_iframe").attr("src", $("#nps_iframeUrl").text());
	});
    
    
    
    
    
    
    
    
    
    
    function checkReplacementCheckbox(input) {
    	var replacementCheckbox = input.parent(".checkboximg");
    	replacementCheckbox.addClass("checked");
    }
    
    function uncheckReplacementCheckbox(input) {
    	var replacementCheckbox = input.parent(".checkboximg");
    	replacementCheckbox.removeClass("checked");
    }
    
    function clickReplacementCheckbox(input) {
    	if (input.is(':checked')) {
			input.attr('checked',false);
			uncheckReplacementCheckbox(input);
    	} else {
    		input.attr('checked',true);
    		checkReplacementCheckbox(input);
    	}
    }
    
	function selectAllReplacementCheckboxes(container) {
		var input = container.children(".checkboximg").children("input");

		input.each(function() {
			var checkbox = $(this);
			if (checkbox.is(':checked')) {
				return;
			} else {
				checkbox.attr('checked',true);
				checkReplacementCheckbox(checkbox);
			}
		});
	}
    
    
    
    function unselectAllReplacementCheckboxes(container) {
		var input = container.children(".checkboximg").children("input");

		input.each(function() {
			var checkbox = $(this);
			if (checkbox.is(':checked')) {
				input.attr('checked',false);
				uncheckReplacementCheckbox(input);
			} else {
				return;
			}
		});    
    }
       
    
    $("#email_category_selection li").each(function() {
    	var replacementCheckbox = $(this).children("div").children(".checkboximg");
    	var inputLabel = $(this).children("div").children("label");
    	var categoryImage = $(this).children("a");
    	var errormsg = $("#email_signup .submit_error");
    	
    	replacementCheckbox.click(function() {
    		var actualCheckbox = $(this).children("input");
    		if (errormsg.is(':visible')) {
    			errormsg.hide();
    		}
    		clickReplacementCheckbox(actualCheckbox);
    	});
    	
    	inputLabel.click(function() {
    		var actualCheckbox = replacementCheckbox.children("input");
    		if (errormsg.is(':visible')) {
    			errormsg.hide();
    		}
    		clickReplacementCheckbox(actualCheckbox);
    	});
    	
    	categoryImage.click(function(e) {
    		e.preventDefault();
    		var actualCheckbox = replacementCheckbox.children("input");
    		if (errormsg.is(':visible')) {
    			errormsg.hide();
    		}
    		clickReplacementCheckbox(actualCheckbox);
    	});
    });
    
    $("#frequency li.day").each(function() {
    	var replacementCheckbox = $(this).children(".checkboximg");
    	var inputLabel = $(this).children("label");
    	var errormsg = $("#email_brands_stores .submit_error_freq");
    	
    	replacementCheckbox.click(function() {
    		var actualCheckbox = $(this).children("input");
    		if (errormsg.is(':visible')) {
				errormsg.hide();
			}
    		clickReplacementCheckbox(actualCheckbox);
    	});
    	
    	inputLabel.click(function() {
    		var actualCheckbox = replacementCheckbox.children("input");
    		if (errormsg.is(':visible')) {
				errormsg.hide();
			}
    		clickReplacementCheckbox(actualCheckbox);
    	});
    	

    });
    
    
    
    
    
    $("#select_all_cats").click(function(e) {
    	var container = $("#email_category_selection li").children(".wrapper");
    	var errormsg = $("#email_signup .submit_error");
    	e.preventDefault();
    	if (errormsg.is(':visible')) {
			errormsg.hide();
		}
    	selectAllReplacementCheckboxes(container);
    });
    
    $("#unselect_all_cats").click(function(e) {
    	var container = $("#email_category_selection li").children(".wrapper");
    	e.preventDefault();
    	unselectAllReplacementCheckboxes(container);
    });
    


    
    $("#popular_set ul li,#top_set ul li").each(function() {
    	var replacementCheckbox = $(this).children(".checkboximg");
    	var inputLabel = $(this).children("label");
    	var errormsg = $("#email_brands_stores .submit_error_bns");
    	
    	replacementCheckbox.click(function() {    		
    		var theId = $(this).attr('id').split('_')[0];
    		var popularImgCheckbox = $("#" + theId + '_popular');
    		var topImgCheckbox = $("#" + theId + '_top');
    		var input = $("#"+theId + '-checkbox');    		
    		
    		if (errormsg.is(':visible')) {
				errormsg.hide();
			}

    		if (input.is(':checked')) {
				input.attr('checked',false);
				popularImgCheckbox.removeClass("checked");
				topImgCheckbox.removeClass("checked");
			} else {
				input.attr('checked',true);
				popularImgCheckbox.addClass("checked");
				topImgCheckbox.addClass("checked");
			}
    		
    	});
    	
    	
    	inputLabel.click(function(e) {
    		e.preventDefault();
    		var theId = $(this).attr('id').split('_')[0];
    		var popularImgCheckbox = $("#" + theId + '_popular');
    		var topImgCheckbox = $("#" + theId + '_top');
    		var input = $("#"+theId + '-checkbox');
    		
    		if (errormsg.is(':visible')) {
				errormsg.hide();
			}
    		
    		if (input.is(':checked')) {
				input.attr('checked',false);
				popularImgCheckbox.removeClass("checked");
				topImgCheckbox.removeClass("checked");
			} else {
				input.attr('checked',true);
				popularImgCheckbox.addClass("checked");
				topImgCheckbox.addClass("checked");
			}

    	});
    	
    });


	function selectAllStoreBrandCheckboxes(container) {
		container.each(function() {
    		var inputLabel = $(this).children("label");
    		var theId = inputLabel.attr('id').split('_')[0];
    		var input = $("#"+theId + '-checkbox');
    		var popularImgCheckbox = $("#" + theId + '_popular');
    		var topImgCheckbox = $("#" + theId + '_top');
    		var errormsg = $("#email_brands_stores .submit_error_bns");
    		
    		if (errormsg.is(':visible')) {
				errormsg.hide();
			}
    		
    		if (input.is(':checked')) {
				return;
			} else {
				input.attr('checked',true);
				popularImgCheckbox.addClass("checked");
				topImgCheckbox.addClass("checked");
			}    		
    	});
	}
    
    
    
    function unselectAllStoreBrandCheckboxes(container) {
		container.each(function() {
    		var inputLabel = $(this).children("label");
    		var theId = inputLabel.attr('id').split('_')[0];
    		var input = $("#"+theId + '-checkbox');
    		var popularImgCheckbox = $("#" + theId + '_popular');
    		var topImgCheckbox = $("#" + theId + '_top');
    		
    		if (input.is(':checked')) {
				input.attr('checked',false);
				popularImgCheckbox.removeClass("checked");
				topImgCheckbox.removeClass("checked");
			} else {
				return;
			}
			
    	});    
    }








    $("#select_all_stores_pop").click(function(e) {
    	var container = $("#popular_set.stores ul li");
    	e.preventDefault();
    	selectAllStoreBrandCheckboxes(container);
    });
    
    $("#unselect_all_stores_pop").click(function(e) {
    	var container = $("#popular_set.stores ul li");
    	e.preventDefault();
		unselectAllStoreBrandCheckboxes(container);
    });
   
    
    
    $("#select_all_brands_pop").click(function(e) {
    	var container = $("#popular_set.brands ul li");
    	e.preventDefault();
    	selectAllStoreBrandCheckboxes(container);
    });
    
    $("#unselect_all_brands_pop").click(function(e) {
    	var container = $("#popular_set.brands ul li");
    	e.preventDefault();
    	unselectAllStoreBrandCheckboxes(container);
    });
    
    
    
    

    $("#select_all_stores_top").click(function(e) {
    	var container = $("#top_set.stores ul li");
    	e.preventDefault();
    	selectAllStoreBrandCheckboxes(container);
    });
    
    $("#unselect_all_stores_top").click(function(e) {
    	var container = $("#top_set.stores ul li");
    	e.preventDefault();
    	unselectAllStoreBrandCheckboxes(container);
    });
   
    
    
    $("#select_all_brands_top").click(function(e) {
    	var container = $("#top_set.brands ul li");
    	e.preventDefault();
    	selectAllStoreBrandCheckboxes(container);
    });
    
    $("#unselect_all_brands_top").click(function(e) {
    	var container = $("#top_set.brands ul li");
    	e.preventDefault();
    	unselectAllStoreBrandCheckboxes(container);
    });
    


    $("#select_everyday").click(function(e) {
    	var container = $("#frequency li.day");
    	var errormsg = $("#email_brands_stores .submit_error_freq");
    	
    	e.preventDefault();
    	
    	if (errormsg.is(':visible')) {
			errormsg.hide();
		}
    	
    	selectAllReplacementCheckboxes(container);
    });
    
    $("#unselect_everyday").click(function(e) {
    	var container = $("#frequency li.day");
    	e.preventDefault();
    	unselectAllReplacementCheckboxes(container);
    });
    
    
    
    $("#pop_top_toggle_stores,#pop_top_toggle_brands").click(function(e) {
    	e.preventDefault();
    	$("#stores_popular").hide();
    	$("#stores_top").show();
    	$("#brands_popular").hide();
    	$("#brands_top").show();
    });
    
    $("#top_pop_toggle_stores,#top_pop_toggle_brands").click(function(e) {
    	e.preventDefault();
    	$("#stores_popular").show();
    	$("#stores_top").hide();
    	$("#brands_popular").show();
    	$("#brands_top").hide();
    });
    

    $("#postcard ul li").each(function() {
    	var link_container = $(this);
    	var link = $(this).children("a");
    	
    	link.click(function() {
    		link_container.addClass("selected");
    	});
    });
    
    
    $("#save_preferences").click(function(e) {
    	e.preventDefault();
    	
    	if($('input[@name=categories]:checked').size() == 0){
		   $("#email_signup .submit_error").show();
		   return false;
		}
    	
    	$("#email_signup_form").submit();
    });
    
    $("#save_preferences2").click(function(e) {
    	e.preventDefault();
    	
		if ($("input[name$='subscriptionAttributes']:checked").size() == 0){
			$("#email_brands_stores .submit_error_bns").show();
			$('html,body').animate({ scrollTop: $(".submit_error_bns").offset().top }, 0);
			return false;
		}
		
		if($("input[name$='schedule']:checked").size() == 0) {
			$("#email_brands_stores .submit_error_freq").show();
			return false;
		}
    	
    	$("#email_signup_form").submit();
    });

    //britle    
    $(".edit_email_settings").click(function(e) {
    	e.preventDefault();
        $(this).parent().parent().submit();
    });
    
	
	$(".jumbotron").each(function() {
		var autoscrolling = true;
		
		$(this).infiniteCarousel().mouseover(function () {
			autoscrolling = false;
		}).mouseout(function () {
			autoscrolling = true;
		});

		setInterval(function () {
			if (autoscrolling) {
				$('.jumbotron').trigger('next');
			}
		}, 7000);
	
	});
    
});


