var LOGGED_IN_PARAM = 'logged_in=1';
$(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("over");
				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("over");
				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 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();
		});
	});




	// 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").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#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").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("");
				// document.location.href = "/my/";
                submitLogin();
                //window.location.reload(true);
			} else {
				var icontents = $("#loginData").contents().find("#failed_login").html();
				$("#reg_shell").html(icontents);
				initForgotPassword();
			}
		}
	);
	$("#registrationData").load(function() {
		var regOk = $("#registrationOK", $("#registrationData").contents()).html();
		if (regOk) {
			$("#reg_shell").html(regOk);
		} else {
			$("#login_reg_pod").html(
				$("#login_reg_pod", $("#registrationData").contents()).html()
			);
			initForgotPassword();
		}
	});
	
	$("#signin,#signin_sweeps").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;
		var newUrl = currentURL;
		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]
		};
	}
	
	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) {
        });
	}
	
	// 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());
	});
    
    
});


