$.fn.extend({
	"or": function(a) {
		var found = this.find(a);
		return this.pushStack(found.length > 0 ? found : this);
	}
});

if(!Array.prototype.reduce)Array.prototype.reduce=function(e){if(this===void 0||this===null)throw new TypeError;var b=Object(this),d=b.length>>>0;if(typeof e!=="function")throw new TypeError;if(d==0&&arguments.length==1)throw new TypeError;var a=0,c;if(arguments.length>=2)c=arguments[1];else{do{if(a in b){c=b[a++];break}if(++a>=d)throw new TypeError;}while(1)}for(;a<d;){if(a in b)c=e.call(undefined,c,b[a],a,b);a++}return c};

// Display script
$(function() {
	$("a.synLoginLink").click(function() {
		var obj = $(this),
		    pos = obj.position(),
		    container = $(".synLogin");
		container.css({ "left": pos.left, "top": pos.top + obj.height() }).slideToggle();
		return false;
	});
	$(document).click(function(e) {
		if ($(e.target).parents().index($(".synLogin")) === -1) {
			$(".synLogin").slideUp();
		}
	});
});

// Custom code for this site
$(function() {
	var calculatePrice,
	    commaRe = /([^,$])(\d{3})\b/;

	function showPrice(price) {
		var formatted = (price < 0 ? "-" : "") + "$" + Math.abs(Number(price)).toFixed(2);
		while (commaRe.test(formatted)) {
			formatted = formatted.replace(commaRe, "$1,$2");
		}
		return formatted;
	}

	$(window).bind("synLoginLoggedIn synLoginLoggedOut", function(e) {
		window.console && console.log("synLogin modifications: Handling " + e.type + " event");

		var shippingOptionNames = ["Ship Option", "Shipping Option", "Freight Charge"];

		function hideTradePrice() {
			$(".tradePrice").hide();
			$("input.synLoginDiscount").attr("disabled", "disabled");
		}

		function recalculateDiscount() {
			// Any time an option is changed, recalculate the discount from all the selected options
			var optionsTotal = 0,
			    priceBeforeDiscount;
			$(".option select").filter(function() {
			    // Make sure the SELECT is not using a name from the shippingOptionNames array
			    return $.inArray($(this).attr("name"), shippingOptionNames) === -1;
			}).find("option:selected").each(function() {
			    optionsTotal += Number($(this).attr("optionprice")) || 0;
			});
			priceBeforeDiscount = window.itemPriceRange.base + optionsTotal;
			$("input.synLoginDiscount").val("Discount pricing (" + showPrice(calculatePrice(optionsTotal) - priceBeforeDiscount) + ")");
		}

		if (window.itemPriceRange.hasTradePrice !== false) {
			calculatePrice = e.type === "synLoginLoggedIn" ? function(optionTotal) {
					return Math.round((window.itemPriceRange.base + (optionTotal || 0)) * 85) / 100;
				} : function(optionTotal) {
					return window.itemPriceRange.base + (optionTotal || 0);
				};
			$(".option select").each(function() {
				var select = $(this),
				    optionName = select.attr("name"),
				    options = select.find("option"),
				    hasOptionPrices = options.filter("[value*='(']").length > 0,
				    lowPrice = 0,
				    optionPrice;
				if (options.length <= 1 || $.inArray(optionName, shippingOptionNames) > -1) {
				    // Skip this SELECT because it only has 1 (or 0) options,
				    //   or because the name is a shipping option name
				    return;
				}
				options.each(function() {
					var option = $(this);
					if (e.type === "synLoginLoggedIn") {
						// Store original data
						option.data({
							"synLogin:originalText": option.text(),
							"synLogin:originalValue": option.val()
						});
						optionPrice = Number(option.attr("optionprice"));
						option.text(option.val().replace(/\s*\([^\)]+\)\s*$/, "") + (hasOptionPrices ? " " + showPrice(calculatePrice(optionPrice)) : ""));
					} else {
						// Reload original data
						option.text(option.data("synLogin:originalText"));
						option.val(option.data("synLogin:originalValue"));
					}
				});
			}).change(recalculateDiscount);
			recalculateDiscount();
			$(".tradePrice .value").html(showPrice(calculatePrice(itemPriceRange.min)) + (itemPriceRange.min !== itemPriceRange.max ? " &ndash; " + showPrice(calculatePrice(itemPriceRange.max)) : ""));
			if (e.type === "synLoginLoggedIn") {
				$("input.synLoginDiscount").removeAttr("disabled");
				$(".tradePrice").show();
			} else {
				hideTradePrice();
			}
		} else {
			hideTradePrice();
		}
	});
});

var synLogin = new (function() {
	var synLogin = this;
	this.username = null;
	this.name = null;

	this.showMessages = function(messages) {
		var container = $(".synLogin .messages"),
		    ul = $(document.createElement("ul"));
		container.empty().append(ul);
		for (var i = 0, message; message = messages[i]; i++) {
			ul.append($(document.createElement("li")).html(message.message || message));
		}
		container.fadeIn("normal", function() {
			setTimeout(function() {
				container.one("mouseleave", function() { $(this).fadeOut("normal"); });
			}, 200);
		});
	};

	this.hideMessages = function() {
		$(".synLogin .messages").fadeOut();
	};

	this.setCookie = function() {
		EasyCookie.set("synLogin", JSON.stringify(synLogin));
	};

	this.getCookie = function() {
		var cookie = EasyCookie.get("synLogin"),
		    obj = cookie ? (function() {
			try {
				return JSON.parse(cookie)
			} catch (e) {
				return null;
			}
		    })() : null;
		if (obj) {
			$.extend(synLogin, obj);
		}
	};

	this.login = function(userData) {
		if (userData) {
			$.extend(synLogin, {
				"username": userData.username,
				"name": userData.name
			});
		}
		synLogin.setCookie();

		$("body").removeClass("synLoggedOut").addClass("synLoggedIn");
		$.event.trigger("synLoginLoggedIn");
		$("input.synLoginDiscount").removeAttr("disabled");

		$(".synLogin .loggedIn").find(".name").or(".value").text(synLogin.name);
	};

	this.logout = function() {
		$.extend(synLogin, {
			"username": null,
			"name": null
		});
		synLogin.setCookie();

		$("body").removeClass("synLoggedIn").addClass("synLoggedOut");
		$.event.trigger("synLoginLoggedOut");
		$("input.synLoginDiscount").attr("disabled", "disabled");
	};

	function addHandlers() {
		$(".synLogin form").submit(function() {
			synLogin.hideMessages();
			var obj = $(this);
			$.ajax({
				"url": obj.attr("action") + "?callback=?",
				"data": obj.serialize(),
				"dataType": "json",
				"success": function(data) {
					var message = data.message;
					obj.find("input[type='password']").val("").blur();

					if (message && message.username && message.accessLevel && (Number(message.accessLevel) & 2)) {
						obj.find("input[name='username']").val("").blur();
						synLogin.login(message);
					} else {
						synLogin.showMessages(data.error || ["Unable to authenticate this user."]);
					}
				},
				"timeout": 5000,
				"error": function(xhr, textStatus, errorThrown) {
					synLogin.showMessages(textStatus);
				}
			});
			return false;
		});
		$(".synLogin a.logout").live("click", function() {
			synLogin.hideMessages();
			synLogin.logout();
			return false;
		});
	};

	(function($) {
		$(function() {
			synLogin.getCookie();
			if (synLogin.name) {
				synLogin.login();
			}
			$(addHandlers);
		});
	})(window.jQuery);
});

