﻿var outOfStockMessages = {
	normal: "Order today and receive this product as soon as it becomes available.",
	unavailable: "This product is currently unavailable."
};
function setupCategoryPage() {
    // bind sort change events
    $("#sort").change(function () {
		sortAndFilter(this, "s", "b");
    });    
    // bind brand filter events
    $("#filter").change(function () {
		sortAndFilter(this, "f", 0);
    });
    $(".paging a,.paging-view-all a").click(function() {
		trackPaging("Category Pages", this);
	});
    // update the display price depending on option picked
    $("form select.multiple-prices").change(function() {
		var value = $(this).find("option:selected").text();
		if (value.indexOf(" - ") > 0) {
			var segs = value.split(' - ');
			/// split them in dashes. show the segment containing the price (with dollar sign)
			for (i = 0; i < segs.length; ++i) {
				if (segs[i].indexOf("$") > -1) break;
			}
			$(this).closest("td").find("span.price").html(segs[i]);
		}
    });
    $("div.content form input").click(addToCart);
    /// show/hide out of stock tooltip
    $("#main-div").append("<div class=\"note-popup\"></div>");
    $("span.note").click(function (e) {
    	var it = $(this);
    	if (it.hasClass("custom")) return false;
    	var version = it.hasClass("unavailable") ? "unavailable" : "normal";
    	var message = $(".note-popup");
    	var pos = it.offset();
    	message.css("top", (pos.top + it.height() + 4) + "px");
    	message.css("left", pos.left + "px");
    	message.html(outOfStockMessages[version]);
    	message.toggle();
    	e.stopPropagation();
    });
    $(document).click(function() { $(".note-popup").hide(); });
    $("span.rating").heartize(true);
	$('a[rel*=facebox]').facebox();
}
// using window.load instead of document.ready because images can still be loading
// after document.ready, screwing up the height calculations
function fixCategoryHeight() {
    // make sure the category description doesn't overrun into the footer
    if ($("div.category p#description").length && !$("div.brand").length) {
		var pHeight = $("div.category p#description").height();
		var dHeight = $("div.category").height();
		if (pHeight > dHeight) {
			$("div.category").css("padding-bottom", (pHeight - dHeight + 80) + "px");
		}
    }
}
function sortAndFilter(list, key, defaultValue) {
	var qs = new querystring();
	var val = $(list).val();
	if (val == '') return; // don't do anything on blank selections
	if (val == defaultValue) qs.set(key, null);
	else qs.set(key, val);
	// reset page number
	qs.set("p", null);
	
	// track event
	var event,label;
	if (key == 's') {
		event = "Sort";
		label = list.options[list.selectedIndex].text;
	}
	else if (key == 'f') {
		event = "Filter";
		if (val == defaultValue) label = null;
		else if (/\d+/g.test(val)) label = "Brand";
		else label = "Tag";
	}
	if (sr.track) pageTracker._trackEvent("Category Pages", event, label);
	
	// build URL and go to that page
	var url = document.location.toString();
	if (url.indexOf("?") > 0) url = url.substr(0, url.indexOf("?"));
	var q = qs.toString();
	if (q) url += "?" + q;
	document.location = url;
}
/// track paging function
function trackPaging(category, link) {
	var href = $(link).attr("href");
	var p;
	if (href.indexOf("?") < 0) p = 1;
	else {
		var qs = new querystring(href.substr(href.indexOf("?") + 1));
		p = qs.get("p");
	}
	if (p) {
		var label = p == "all" ? "All" : "Page " + p;
		if (sr.track) pageTracker._trackEvent(category, "Paging", label);
	}
}
// perform check on product options before
// allowing add to cart to happen
function addToCart() {
	var menu = $(this).siblings("select");
	if(menu.length > 0 && !menu.val()) {
		var msg = menu.text();
		msg = msg.substr(0, msg.indexOf("..."));
		alert("Please " + msg + ".");
		menu.focus();
		return false;
	}
}
function setupSearchPage() {
	$("#search-page a").click(function() {
		if (sr.productUrlIDMap) {
			var href = $(this).attr("href");
			$.each(sr.productUrlIDMap, function(index, item) {
				if (item[1] == href) strandsRec.trackSearchClick(sr.searchTerm, sr.strandsUserID, item[0]);
			});
		}
	});
}
function setupProductPage() {
	$("form select.multiple-prices").change(function() {
		var value = $(this).find("option:selected").text();
		if (value.indexOf(" - ") > 0) {
			var segs = value.split(' - ');
			/// split them in dashes. show the segment containing the price (with dollar sign)
			for (i = 0; i < segs.length; ++i) {
				if (segs[i].indexOf("$") > -1) break;
			}
			$("p.price").html(segs[i]);
		}
	});
	$("form.add-to-cart input").click(addToCart);
	$("span.rating").heartize();
    $(document).click(function() {
		$("#review-tooltip").hide();
	});
	$(".left span.rating").click(function(e) {
		$("#review-tooltip").show()	
		e.stopPropagation();
	});
	$(".write-review-button").click(function () {
		var url = window.location.href;
		var segs = url.split("/");
		var w = window.open("/write-review?p=" + segs[3] + "/" + segs[4], "writereview",
			"width=640,height=545,status=no,toolbar=no,location=no,menubar=no,directories=no,scrollbars=yes");
		w.focus();
		return false;
	});
	$('a[rel*=facebox]').facebox();
	if (sr.track) pageTracker._trackEvent("Product Pages", "View");
}
function zoomProduct(url) {
	var w = window.open("/product-zoom" + url, "productImageZoomed",
		"status=0,toolbar=0,location=0,menubar=0,directories=0,resizable=0,scrollbars=1,height=560,width=620");
	w.focus();
}
function setupProductZoomPage() {
	$("input").click(function() {
		// ensure that for products that require option selection has
		// an option selected. halt function otherwise
		var menu = $("select");
		if(menu.length > 0 && !menu.val()) {
			var msg = menu.text();
			msg = msg.substr(0, msg.indexOf("..."));
			alert("Please " + msg + ".");
			menu.focus();
			return;
		}
		
		// get the product ID of the matrix options
		var matrixId = $("select").val();
		if (matrixId == null) matrixId = "";
		
		// put the items into the cart by posting values to the cart page
		$.post("/cart", {
			Action: "add",
			quantity: "1",
			ProdId: prodId,
			MatrixId: matrixId
		}, addToCartComplete);
	});
}
function addToCartComplete() {
	window.close();
	window.opener.location="/cart";
	window.opener.focus();
}
// query string parser
function querystring(qs) {
	this.params = [];
	
	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

	// Turn <plus> back to <space>
	// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
	// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		
		var value = (pair.length==2)
			? decodeURIComponent(pair[1])
			: name;
		
		this.params.push({"key" : name, "value" : value});
	}
}
querystring.prototype.get = function(key) {
	for (var i = 0; i < this.params.length; ++i) {
		var k = this.params[i];
		if (k.key == key) return k.value;
	}
	return null;
}
querystring.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}
querystring.prototype.set = function(key, value) {
	for (var i = 0; i < this.params.length; ++i) {
		var k = this.params[i];
		if (k.key == key) { k.value = value; return; }
	}
	this.params.push({"key" : key, "value" : value});
}
querystring.prototype.toString = function() {
	var result = "";
	for (var i = 0; i < this.params.length; ++i) {
		var val = this.params[i];
		if (val.value != null) result += val.key + "=" + encodeURIComponent(val.value) + "&";
	}
	if (result.length > 0) result = result.substr(0, result.length - 1);
	return result;
}
