// Load jQuery
/*
google.load("jquery", "1");

window.synOnLoadCallbacks = [];
google.setOnLoadCallback(function() {
	if (synOnLoadCallbacks.length > 0) setTimeout(function() { (synOnLoadCallbacks.shift())(); }, 1);
});

synOnLoadCallbacks.push(function() {
	try {
	*/
		$(function() {
			// Set up changing message in the header
			$(".fadingMessages").each(function() {
				var container = $(this),
				    children = container.children(),
				    delay = 3000;
				container.height(Math.max.apply(Math, children.map(function() { return $(this).height(); }).get()));
				children.not(":first").hide().css("visibility", "visible").end();
				setInterval(function() {
					var visible = children.filter(":visible").stop(true, true).fadeOut(),
					    next = visible.next();
					(next.length > 0 ? next : children.filter(":first")).stop(true, true).fadeIn();
				}, delay);
			});
			
			// Change search page text
			$("#searchFormArea blockquote").empty()
			  .html("<h3 style='float: none;'>Well, this is embarrassing.</h3>" +
			  "<p>Brushlove is having trouble finding your search results. Please try again using different search words.</p>");

			// Set up fader on homepage
			$(".fader").each(function() {
				var obj = $(this),
				    children = obj.children(),
				    current = children.filter("*:visible"),
				    index = children.index(current),
				    timer = null;
				obj.bind("mouseenter", function() {
					if (timer) {
						clearInterval(timer);
					}
				}).bind("mouseleave", function() {
					timer = setInterval(function() {
						var next = $(children.get(++index % children.length));
						obj.append(next);
						next.fadeIn("slow");
						current = next;
					}, 5000);
				}).trigger("mouseleave");
			});
		});

		function echoYahooCrossSell(account, itemID) {
		    $.getJSON("http://" + account + ".csell.store.yahoo.net/cs/recommend?itemids=" + itemID + "&location=p&callback=?", function(data) {
			window.console && console.dir && console.dir(data);
			if (data && data.r && data.r.length > 0) {
			    function showValue(obj, value) {
				if (value && value !== "") {
				    var valueElements = obj.find(".value");
				    if (valueElements.length > 0) {
					valueElements.html(value);
				    } else {
					obj.html(value);
				    }
				    obj.show();
				}
			    }
			    var container = $(".echoYahooCrossSell"),
				template = container.find(".item"),
				i, item;
			    if (container.length === 0) {
				return;
			    }
			    window.console && console.log(template);
			    for (i = 0; item = data.r[i]; i++) {
				window.console && console.dir && console.dir(item);
				var href = item.id + ".html",
				    clone = template.clone().attr("product", item.id).
					find(".name").text(item.n).
					    filter("a").attr("href", href).end().end().
					find("a.link").attr("href", href).end().
					find("img.image, .image img").attr({ "src": item.i, "alt": item.n }).
					    parents("a").attr("href", href).end().end().
					find("form input[name='vwitem']").val(item.id).end();
				template.before(clone);
				window.console && console.log(clone);
				showValue(clone.find(".price"), item.p ? "$" + (item.rp || item.p) : null);
				if (item.p && item.rp && item.p !== item.rp) {
				    showValue(clone.find(".salePrice"), "$" + item.p);
				}

				(function(id) {
				    $.get(href, function(html) {
					var valueKeys = String(html).match(/<!--quickView-[\w\d-]*(?=-start-->)/g);
					$.each(valueKeys, function(key, value) {
					    var html2 = html,
						value = value.substring("<!--quickView-".length),
						marker = "<!--quickView-" + value + "-start-->",
						start = html2.indexOf(marker),
						end = html2.indexOf("<!--quickView-" + value + "-end-->");
					    if (!(start < 0 || end < 0)) {
						var str = html2.substring(start + marker.length, end);
						showValue(container.find(".item[product='" + id + "'] ." + value), str.replace(/^[\s\n\r]+/, "").replace(/[\s\n\r]+$/, ""));
					    }
					});
				    });
				})(item.id);
			    }
			    template.hide();
			    container.show().parents().not("html, body").show();
			    if ($.fn.slider) {
				container.filter(".slider").slider();
				$("#bodyBg .rightColumn").css("visibility", "visible");

				$("#bodyBg").addClass("hasRightColumn");

				// Slider animate on interval
				if (window.sliderAnimateInterval) {
				    $(function() {
					var container = $(".slider.vertical"),
					    button = container.find(".upArrow"),
					    delay = window.sliderAnimateInterval,
					    clicker = function() {
						button.click();
					    },
					    timer = setInterval(clicker, delay);
					container.hover(function() {
					    clearInterval(timer);
					}, function() {
					    timer = setInterval(clicker, delay);
					});
				    });
				}
			    }
			} else {
			    $("#bodyBg .rightColumn").hide();
			}
		    });
		}

		// Slider function
		(function() {
		    function makeArrow(className) {
			return $(document.createElement("a")).attr("href", "#").addClass(className);
		    }

		    $.fn.extend({
			"slider": function() {
			    window.console && console.log("initializing slider");
			    var container = $(this),
				children = container.children(),
				bar = $(document.createElement("div")).addClass("bar"),
				height = 0, width = 0, displayed;

			    // Remove white space
			    container.contents().filter(function() {
				return this.nodeType !== 1;
			    }).remove();

			    // Give a fixed height to the container so it doesn't lose it's height when the products are made position: absolute
			    if (container.is(".horizontal")) {
				children.each(function() {
				    height = Math.max(height, $(this).outerHeight(true));
				});
				container.height(height);
			    }
			    while (children.length && children.length < 3) {
				children = container.append(children.clone()).children();
			    }

			    // Set each name to the correct height
			    // if (container.is(".horizontal")) {
				height = 0;
				children.each(function() {
				    var child = $(this);
				    height = Math.max(height, child.find(".name").height());
				    width += child.outerWidth(true);
				});
				children.find(".name").height(height);
			    // }

			    // Set the container to the height of 3 products (hard coded for now)
			    if (container.is(".vertical")) {
				if (displayed = 3) {
				    height = 0;
				    children.slice(0, displayed).each(function() {
					height += $(this).outerHeight(true);
				    });
				    container.height(height + 45);
				}
			    }

			    // Rotate images in vertical bar (site specific)
			    if (container.is(".vertical")) {
				container.find("img").filter(function() {
				    var img = $(this);
				    return img.width() > img.height();
				}).addClass("rotated");
			    }

			    // Wrap the children in the bar that will be animated
			    // container.children().wrapAll(bar); // NOTE: this didn't work. IE was adding extra white space between the elements, but not listing it as a childNode...
			    if (container.is(".horizontal")) {
				bar.width(width);
			    }
			    container.append(bar.append(container.children()));

			    // Add the arrow buttons
			    if (container.is(".horizontal")) {
				container.append(makeArrow("arrow leftArrow")).append(makeArrow("arrow rightArrow"));
			    } else {
				container.append(makeArrow("arrow upArrow")).append(makeArrow("arrow downArrow"));
			    }

			    function scrollContainer(container, direction) {
				var firstProduct = container.find(".product:first"),
				    lastProduct = container.find(".product:last"),
				    bar = container.find(".bar").stop(true, true);

				// Some redundancy exists here. I decided after I got it working that readibility of the code (combined with my laziness) offset any benefits to further optimizing the code.
				switch (direction) {
				    case "up":
					// Animate the first product off the top edge
					bar.animate({
					    "top": -(firstProduct.outerHeight(true))
					}, "fast", function() {
					    bar.append(firstProduct).css("top", 0);
					});
					break;

				    case "left":
					// Animate the first product off the left edge
					bar.animate({
					    "left": -(firstProduct.outerWidth(true))
					}, "fast", function() {
					    // Move it to the end of the strip
					    bar.append(firstProduct).css("left", 0);
					});
					break;

				    case "down":
					// Move the last item to the beginning of the strip
					bar.css("top", -(lastProduct.outerHeight(true))).prepend(lastProduct);

					// Animate to the new item
					bar.animate({
					    "top": 0
					}, "fast");
					break;

				    case "right":
					// Move the last item to the beginning of the strip
					bar.css("left", -(lastProduct.outerWidth(true))).prepend(lastProduct);

					// Animate to the new item
					bar.animate({
					    "left": 0
					}, "fast");
					break;
				}
			    }

			    function monitorMouseMovement(e) {
				var obj = $(this),
				    mouseCoords = obj.data("mouseCoords");
				if (!obj.data("hoverStart") &&
				    ((Math.abs(mouseCoords.x - e.clientX) > 5) || (Math.abs(mouseCoords.y - e.clientY) > 5))) {
				    obj.data("hoverStart", +(new Date()));
				}
			    }

			    container.
				hover(function(e) {
				    // $(this).data("mouseCoords", { "x": e.clientX, "y": e.clientY }).mousemove(monitorMouseMovement);
				    var obj = $(this);
				    if (!obj.data("hoverStart")) {
					obj.data("hoverStart", +(new Date()));
				    }
				}, function() {
				    // $(this).unbind("mousemove", monitorMouseMovement).removeData("hoverStart");
				    $(this).removeData("hoverStart");
				}).
				bind("mousewheel", function(evt, delta) {
				    var container = $(this),
					hoverStart = container.data("hoverStart");
				    if (hoverStart && (+(new Date()) - hoverStart > 200)) {
					if (container.is(".horizontal")) {
					    scrollContainer(container, delta > 0 ? "right" : "left");
					} else {
					    scrollContainer(container, delta > 0 ? "down" : "up");
					}
					return false;
				    }
				}).
				find("a.arrow").
				    click(function() {
					var arrow = $(this),
					    container = arrow.parents(".slider");
					if (container.is(".horizontal")) {
					    scrollContainer(container, arrow.is(".leftArrow") ? "left" : "right");
					} else {
					    scrollContainer(container, arrow.is(".upArrow") ? "up" : "down");
					}
					return false;
				    });
			    }
			});
		    })();

		    // Start horizontal sliders
		    $(function() {
			$(".slider.horizontal").slider();
			if ($(".echoYahooCrossSell").length === 0) {
			    $(".slider.vertical").slider();
			}
		    });
	    /*
	    } catch(e) {
		    if (window.console) console.log(e);
	    }
	    */
	    /*
	    if (synOnLoadCallbacks.length > 0) setTimeout(function() { (synOnLoadCallbacks.shift())(); }, 1);
    });
    */

