﻿var sr = sr || {};
$(document).ready(function() {
	// allow watermark on textboxes
	swapValues = [];
	$(".swap").each(function(i) {
		var text = $(this);
		swapValues[i] = { "text": text.val(), "color": text.css("color") };
		text.css("color", "#aaa");
		text.focus(function() {
			if ($(this).val() == swapValues[i].text) $(this).val("")
			$(this).css("color", swapValues[i].color);
		}).blur(function() {
			if ($.trim($(this).val()) == "") {
				$(this).val(swapValues[i].text);
				$(this).css("color", "#aaa");
			}
		})
	});
	// awesome-persand-ize
	$("h1:contains('&'),h2:contains('&')").contents().each(function() {
		if (this.nodeType == 3) {
			$(this).replaceWith(this.nodeValue.replace(/&/g, "<span class=\"amp\">&</span>"));
		}
	});
	// validate newsletter sign up email address
	$("#newsletter .button").click(function() {
		var emailBox = $("#email");
		var verifier = /\s*[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\.[a-zA-Z]+\s*/;
		if (!emailBox.val() || !verifier.test(emailBox.val())) {
			alert("Please enter a valid email.");
			emailBox.focus();
			return false;
		}
	});
	prettifyTables();
	// add "last" class to every third div in /brands
	$(".brands-item-style div").each(function(i) {
		if (i % 3 == 2) $(this).addClass("last");
	});
	// add third css class to every third column in /all
	$("#everything>.ul:eq(2),#everything>.ul:eq(5),#everything>.ul:eq(8),#everything>.ul:eq(11)").addClass("third");
	// make immediate children clickable
	$(".children-clickable > *").click(function() {
		var links = $(this).find("a");
		if (links.length > 0 && links.attr("href") != null)
			document.location = links.attr("href");
	});
	try { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(prettifyTables); }
	catch (ex) { }
	var topMessageToggle = $(".top-message .toggler");
	var visible = false;
	topMessageToggle.click(function() {
		var it = $(this);
		it.parent().find("div").slideToggle(200);
		visible = !visible;
		it.html(visible ? "Hide" : "Find out more &raquo;");
		return false;
	});
	if (jQuery.fn.supersleight) $("#all-brands ul").supersleight({ shim: "/images/spacer.gif" });
});
function prettifyTables() {
    // add alt css class to alternate columns of tables
    $("div.copy table tr").each(function() {
		$(this).children("td:odd").addClass("alt");
		$(this).children("th:odd").addClass("alt");
	});
    // assign a css class to the first column
	$("div.copy table tr").each(function () {
		$(this).children("td:first").addClass("first");
	});
	// toggle the colors of the rows
    $("div.copy table:not(.reset) tbody tr").mouseenter(function() {
		var t = $(this);
		t.css("background-color", "#ffffe3");
		t.children("td:odd").css("background-color", "#eff3d2");
		t.mouseleave(function() {
			t.removeAttr("style");
			t.children("td:odd").removeAttr("style");
		});
	});
}
function setupHomePage() {
	$("h2 span").click(homepageTabClick);
}
// handles homepage tab click event
function homepageTabClick() {
	var jTab = $(this);
	if (jTab.hasClass("selected")) return;
	
	var jIndex = ":eq(" + jTab[0].id.replace("tab", "") + ")";
	
	$("h2 span").removeClass("selected");
	$("h2 span" + jIndex).addClass("selected");
	$(".rec").hide();
	$(".rec" + jIndex).show();
	$("h2 strong").hide();
	$("h2 strong" + jIndex).show();
}
sr.renderRecParam = {
	HOME: { trackCategory: "Homepage", show: [0, 1] },
	PRODUCT_DETAILS: { header: 1, reviews: 1, trackCategory: "Product Pages" },
	SHOPPING_CART: { reviews: 1, trackCategory: "Cart" },
	HIGH_LEVEL_CATEGORY: { reviews: 1, trackCategory: "Category Pages" },
	CATEGORY: { reviews: 1, trackCategory: "Category Pages" },
	SEARCH_RESULTS: { reviews: 1, trackCategory: "Search" },
	ORDER_CONFIRMATION: { reviews: 1, trackCategory: "Checkout" }
};
sr.renderRec = function (zones) {
	var isUSD = sr.currency == "USD";
	var pricePrefix = (isUSD ? "US" : "CA") + "$";
	var params = sr.renderRecParam[mybuys.pagetype];

	// render each zone returned
	$.each(zones, function (zoneIndex, zoneItem) {
		var target = $("div#" + zoneItem.divId);
		target.html("");
		if (params.header) target.append("<div class=\"head\">" + zoneItem.zoneTitle + "</div>");
		$.each(zoneItem.recs, function (index, item) {
			var price = isUSD ? item.price : item.priceCAD;
			var numRatings = parseInt(item.num_ratings);
			var review = params.reviews ? (numRatings ? "<span class=\"rating\" title=\"Read {1} review{2}\">{0}</span>"
				.replace("{0}", item.rating)
				.replace("{1}", numRatings)
				.replace("{2}", numRatings > 1 ? "s" : "") : "") : "";
			var div = $(("<div><div><a href=\"{link}\" class=\"name\">{store_name}</a>" +
				"<span class=\"brand\">By {brand}</span><span class=\"price\">{price}</span>{review}" +
				"</div><a href=\"{link}\" class=\"img\"><img src=\"{image_link}\" alt=\"\" /></a></div>")
				.replace(/{link}/g, item.productUrl).replace("{store_name}", item.name)
				.replace("{brand}", item.brand).replace("{price}", pricePrefix + price.toFixed(2))
				.replace("{image_link}", item.imageUrl)
				.replace("{review}", review));

			// add tracking events
			div.find("a").click(function () {
				if (!sr.track) return;
				$.ajax({ async: false, url: item.trackUrl });
				pageTracker._trackEvent(params.trackCategory, "Click Recommendation");
			});
			target.append(div);
		});

		target.find("> div:last").addClass("last"); // add last class to last item
		target.find("span.rating").heartize(true); // convert ratings to hearts
		if (!params.show || params.show[zoneIndex - 1]) target.show(); // show the recommendations only if told to
	});
};
(function ($) {
	$.fn.heartize = function (clickable) {
		return $(this).each(function () {
			var width = $(this).hasClass("large") ? 28 : 16;
			var span = $('<span />').width(parseFloat($(this).html()) * width);
			$(this).html(span);
			if (clickable) {
				$(this).click(function () {
					document.location = $(this).closest("div").find("a").attr("href") + "/reviews";
				}).css("cursor", "pointer");
			}
		});
	};
})(jQuery);
