// the function below is equivalent to the following function call:
// document.addEventListener("domcontentloaded", function() {  }, false);
// but since not all browsers support it yet (ahem, IE) we resort to this jQuery shortcut
// which is short for: $j(document).ready(function () {  })

//jQuery.fx.speeds._default = ($j.browser.msie && $j.browser.version < 8) ? 800 : 400;
//$j("#element").fadeIn("_default");

$j = jQuery.noConflict();

// as soon as the DOM is loaded (not including images, etc.), we can begin manipulating it...
$j(function () {
	var banners,
	    spinnerTimer,
	    addToCartParams,
	    section = location.pathname.split("/")[1].toLowerCase(),
	    passRecoveryLegend = $j("#gnav-modal legend").html(),
	    passRecoveryText = $j("#gnav-modal .forgot-password-button").html(),
	    passRecoveryInfo = $j("#gnav-modal .password-recovery-info .text").html(),
	    passRecoverySubmit = $j("#login-submit").attr("value");

	// unobtrusive Javascript rocks!
	$j("body").addClass('js');
	$j("#snav-" + section).css("display", "block");

	// smooth scrolling for anchored links
	$j.localScroll.defaults.duration = 800;
	$j.localScroll.defaults.easing = "easeInOutExpo";
	$j.localScroll.defaults.hash = true;
	$j.localScroll.defaults.lazy = true;
	$j.localScroll.hash();
	$j.localScroll();

	addH1Gradient();
	//bindBCEvents();
	cartSummaryUpdate();

	/**/
	// http://allcreatives.net/2009/12/05/smoother-font-face-embedding-in-ie-7-8/
	if ($j.browser.msie === true && parseInt($j.browser.version) >= 7 && parseInt($j.browser.version) <= 8) {
		$j("#header").css({
			filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="/img/pixel.png",sizingMethod=crop',
			zoom: '1'
		});

		$j("#abdomener").css({
			filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="/img/pixel.png",sizingMethod=crop',
			zoom: '1'
		});

		$j("#footer").css({
			filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="/img/pixel.png",sizingMethod=crop',
			zoom: '1'
		});
	}
	/**/

	// the {tag_cataloguebreadcrumbs} uses colons and is not customizable! Nuts.
	//$j(".breadcrumb").html($j(".breadcrumb").html().replace(" : ", " &raquo; "));

	/** /
	// 'selects' the current section in the mnav
	$j("#mnav li a:only-child").each(function () {
		if ($j(this).attr("href").indexOf("livefluid.com/" + section) > 0 && section !== "") {
			$j(this).addClass("selected");
		}
	});
	/**/

	// makes the "Like" button refer to the current page
	$j("iframe.facebook-like-button").attr("src", $j("iframe.facebook-like-button").attr("src") + "&href=" + location.href);

	// show/hide login window
	$j("#page.is-logged-in-0 #member .my-account").toggle(
	function () {
		$j("#gnav-modal").fadeIn(200);
	},
	function () {
		$j("#gnav-modal").fadeOut(200);

		/** /
		//the condition works, but actually programatically clicking it doesn't for some reason...
		if ($j("#login-pass").attr("disabled")) {
			//$j("#gnav-modal").click();
		}
		/**/
	});

	$j("#page.is-logged-in-1 #member .my-account").click(function () {
		$j(window.location).attr("href", "/account/");

		return false;
	});

	// change form's function to PASSWORD RECOVERY
	$j("#gnav-modal .forgot-password-button").toggle(
	function () {
		$j("#gnav-modal").css("background-position", "-275px 0");
		$j("#gnav-modal legend").html("Password Recovery");
		$j("#gnav-modal .sign-up").hide();

		$j("#SZPassword").slideUp("fast", function () {
			$j('label[for="SZPassword"]').css("z-index", "-1");
		});
		$j('label[for="SZPassword"]').animate({opacity : 0}, 250);
		//$j('label[for="SZPassword"]').hide();
		$j("#SZPassword").attr("disabled", "disabled");

		$j(this).html("Remembered your password?");
		$j("#gnav-modal .password-recovery-info").fadeIn(100);

		// submit button changes function
		$j("#login-submit").attr("value", "Retrieve");
		$j("#login-submit").click(function () {
			$j("#SZUsername").attr("disabled", "disabled");
			$j("#SZUsername").addClass("disabled");
			$j("#gnav-modal .password-recovery-info .text").html("Retrieving...");

			// start a spinner animation to indicate stuff is happening in the background
			spinnerTimer = setInterval(function () {
				var offset = -15;
//				var current = parseInt(document.defaultView.getComputedStyle($j("#gnav-modal .spinner"), null).getPropertyValue('background-position-y'), 10);
//$j("h1").html(parseInt(document.defaultView.getComputedStyle($j("#gnav-modal .spinner"), null).getPropertyValue('background-position-y'), 10));
				var slide = current / offset;

				// loops the matrix of images
				$j("#gnav-modal .spinner").css("background-position", "0 " + ((slide === 12) ? offset : (current + offset)) + "px");
			}, 75);

			// send data in order to retrieve the login info
			$j.post("/LostPasswordProcess.aspx", { Username: $j("#SZUsername").attr("value") }, function(data) {
				// stop spinner animation
				clearInterval(spinnerTimer);

				// display informative message
				$j("#gnav-modal .spinner").css("background-position", "0 -280px");
				$j("#gnav-modal .password-recovery-info .text").html("Your login details have been sent to your email account!");

				// hide modal window
				setTimeout(function () {
					$j("#member .my-account").click();

					setTimeout(function () {
						// clear contents of user field & make sure it's shown and enabled
						$j("#SZUsername").attr("value", "");
						$j("#SZUsername").attr("disabled", "");
						$j("#SZUsername").removeClass("disabled");
						$j("#SZUsername").blur();
						$j("#gnav-modal .password-recovery-info .spinner").css("background-position", "0 -260px");
						$j("#gnav-modal .password-recovery-info .text").html(passRecoveryInfo);

						$j("#gnav-modal .forgot-password-button").click();
					}, 200);
				}, 2000);
			});

			return false;
		});
	},
	function () {
		$j("#gnav-modal").css("background-position", "0 0");
		$j("#gnav-modal legend").html(passRecoveryLegend);
		$j("#gnav-modal .sign-up").show();

		// clear contents of passwaord field & make sure it's shown and enabled
		$j("#SZPassword").attr("value", "");
		$j("#SZPassword").attr("disabled", "");
		$j("#SZPassword").slideDown("fast");
		$j("#SZPassword").blur();
		$j('label[for="SZPassword"]').css("z-index", "0");
		$j('label[for="SZPassword"]').animate({opacity : 1}, 250);

		$j("#gnav-modal .forgot-password-button").html(passRecoveryText);
		$j("#gnav-modal .password-recovery-info").fadeOut(100);
		//hide spinner

		$j("#login-submit").attr("value", passRecoverySubmit);
		$j("#login-submit").unbind("click");//.submit();
	});

	// for all input tags fade their label out/in when focussed/blurred
	$j("input[type='text'],input[type='password']").keyup(function () {
		if ($j(this).attr("value") !== "") {
			$j("label[for=" + $j(this).attr("id") + "].placeholder").hide()/*.animate({opacity: 0, marginLeft: "4px"}, 200, "swing", function () {
				$j(this).hide();
			})*/;
		}
		else {
			$j("label[for=" + $j(this).attr("id") + "].placeholder").show()/*.animate({opacity: 1, marginLeft: "0"}, 200)*/;
		}
	}).keyup();
/*
	.each(function () {
		if ($j(this).attr("value") !== "") {
			$j("label[for=" + $j(this).attr("id") + "].placeholder").css("z-index", "-1").css("opacity", 0).css("margin-left", "-4px");
		}
	})
*/
;

	$j("label")
		.each(function (i, e) {
			var id = $j(this).attr("for");

			// hide browser's default checkbox
			if (id !== "") {
				if ($j("#" + id).is("input[type='checkbox']")) {
					$j("#" + id)
					.css({
						"position" : "absolute",
						"left" : "-9999px"
					});

					// configure our custom checkbox image behavior
					$j(this)
					.addClass("checkbox")
					.hover(function () {
						$j(this).addClass("hover");
					},
					function () {
						$j(this).removeClass("hover");
					})
					.bind("click", function () {
						if ($j("#" + id).attr("checked") === true) {
							$j(this).removeClass("checked");
						} else {
							$j(this).addClass("checked");
						}
	
						return true;
					});

					// get value of checkbox at page load and apply same value to our checkbox image
					if ($j("#" + id).attr("checked") === true) {
						$j(this).addClass("checked");
					}
				} else if ($j("#" + id).is("input[type='radio']")) {
					$j("#" + id)
					.css({
						"position" : "absolute",
						"left" : "-9999px"
					});

					// configure our custom radio image behavior
					$j(this)
					.addClass("radio")
					.hover(function () {
						$j(this).addClass("hover");
					},
					function () {
						$j(this).removeClass("hover");
					})
					.bind("click", function () {
						$j(this).addClass("checked");

						// ensure no other radio of the same group is checked
						$j(this).siblings().removeClass("checked");

						return true;
					});

					// get value of the radio group at page load and apply same value to our radio image
					if ($j("#" + id).attr("checked") === true) {
						$j(this).addClass("checked");
					}
				}
			}
		});

	/** /
  $j("input[type='radio']:checked").parent("label").addClass("checked");

  $j("input[type='radio']").closest("label").click(function() {
    $j(this).addClass("checked").siblings().removeClass("checked");
  })
  .hover(function() {
      $j(this).addClass("hover").siblings().removeClass("hover");
    }, function() {
      $j(this).removeClass("hover");
  });
  /**/

	/** /
	function parseOnlineShopLayout() {
		var clickHandler;
	
		if ((clickHandler = String($j(".cart-add-button").attr("onclick")))) {
			if ((addToCartParams = clickHandler.match(/AddToCart\((.+)\)/))) {
				addToCartParams = addToCartParams[1].split(",");	// separate individual parameters
	
				// clear the original onclick handler and define a new one...
				$j(".cart-add-button").attr("onclick", "").click(myAddToCart);
			}
		}
	}
	/**/
	
	/** /
	function myAddToCart() {
		// call BC's function that we modified & re-evaluated
		AddToCart(parseInt(addToCartParams[0]),
		          parseInt(addToCartParams[1]),
		          jQuery.trim(addToCartParams[2]),
		          parseInt(addToCartParams[3]),
		          addToCartParams[4] === "false" ? false : true);

		// refresh our own cart
		cartSummaryUpdate();
		bindBCEvents();
		parseOnlineShopLayout();

		//<input id="Units_447613" class="productTextInput" name="AddToCart_Amount" type="text" value="1" />
		//input id="Units_" + jQuery.trim(addToCartParams[1]);	// trim just in case
		//eval(function (param) {confirm(param);})(4)

		return false;
	}
	/**/

	/** /
	function customizePage(path, execute) {
		// if pathname starts with this particular path, execute custom code
		if (location.pathname.toLowerCase().indexOf(path.toLowerCase()) === 0) {
			execute();
		}
	}
	customizePage("/order", function () {
		$j("#breadcrumb").hide();
		hideSNav();
	});
	/**/
});



/**
 * 
 */
function shoppingCartUpdate() {
	var i, liElement;
	var propertyItemCount = $j(".productitemcell").size();
	var productCount = $j("table.cart td:first").children().size();

	var products = new Array(productCount);

	addH1Gradient();
	bindBCEvents();
	cartSummaryUpdate();

	// if shopping cart empty message appears
	if ($j("#catCartDetails").children().length === 1 &&
	    $j("#catCartDetails").children().text() === "Shopping cart is empty. Go Back") {
		$j("#catCartDetails").before("<h1><span></span>Your Shopping Cart</h1>");
	}
	// if shopping cart item-cells exist...
	else if (productCount > 0) {
		// hide "non-javascript" shopping cart info from BC and create our own structure
		$j("table.cart").hide().after("<ul class='cart'>");

		// group every item-cell generated by BC into an array
		$j(".productitemcell").each(function (index) {
			var productIndex = (index % productCount);

			// define each sub-array when access it for the first time
			if (typeof(products[productIndex]) === "undefined") {
				products[productIndex] = new Array();
			}

			// add the current property to the corresponding product
			products[productIndex].push($j(this));
		});
	}

	for (i = 0; i < products.length; i++) {
		liElement = "<li>" +
		"<div class='fr'>" +
		products[i][3].html() +															// input field
		" " + products[i][4].html() +													// total
		"<br />" + products[i][5].html() +												// remove link
		"</div>" +
		products[i][1].children().prepend(products[i][0].children().addClass("fl")).html() +

//		"<a href='" + products[i][1].children().attr("href") + "'>" +					// url
//		"<img src='" + products[i][0].children().attr("src") + "' class='fl' />" +		// image
//		"<h4>" + products[i][1].children().html() + "</h4>" +							// name
//		"</a>" + 


		"<span class='small'>Price: " + products[i][2].html() + "</span><br />" +		// individual item price
//		"Product Number: " + products[i][3].children().html();
		"";

		$j("ul.cart").append(liElement);
	}
}


/**
 * 
 */
function addH1Gradient() {
	if ($j("h1 span:first-child").length === 0) {
		$j("#content h1").prepend("<span>");	
	}
}


/**
 * Bind events to the product info generated by BC.
 * (which is regenerated when an item is added to the cart and/or a drop down is changed.
 */
function bindBCEvents() {
    var currentSelection = $j(".productSelectInput").attr("value"),
        cartAddQuantity = $j("div.quantity input.productTextInput");

	// relocate the Related Products
	$j("#related-products").html($j("#related-products-source").hide().html());

/**/
	// ensure events we bind later on are unbinded
	// necessary since this can be a recursive function (if a product drop down is changed)
	$j("select.productSelectInput").unbind("click.overrideBC");
	$j("div.quantity span.decrease").unbind("click.overrideBC");
	$j("div.quantity span.increase").unbind("click.overrideBC");
	$j("div.quantity span.add").unbind("click.overrideBC");

	// needed for products that have drop downs
	$j("select.productSelectInput").bind("change.overrideBC", function () {
		var pollAjax = setInterval(function () {
			if (currentSelection !== $j(".productSelectInput").attr("value")) {
				bindBCEvents();
				cartSummaryUpdate();
				clearInterval(pollAjax);
			}
		}, 500);
		//$j("img.cart-add-button").hide();
	});
/**/



	// if a BC add-to-cart-quantity field exists
	if (cartAddQuantity.length !== 0) {
		var cartVehicleBezier = {
			/*
			start : {
				x : cartAddQuantity.offset().left,
				y : cartAddQuantity.offset().top,
				angle : 90,
				length : 0.4
			},
			end : {
				x : ($j("#cart-summary").offset().left + 35),
				y : ($j("#cart-summary").offset().top + 25),
				angle : -90,
				length : 0.4
			}
			*/
			start : {
				x : cartAddQuantity.offset().left,
				y : cartAddQuantity.offset().top,
				angle : -45,
				length : 0.9
			},
			end : {
				x : ($j("#cart-summary").offset().left + 10),
				y : ($j("#cart-summary").offset().top + 6),
				angle : 140,
				length : 0.9
			}
		}

		// configure the increase/decrease buttons
		$j("div.quantity span.decrease").bind("click.overrideBC", function () {
			var currentQuantity = parseInt(cartAddQuantity.attr("value"));

			if (currentQuantity > 1) {
				cartAddQuantity.attr("value", (currentQuantity - 1));
			}

			return false;
		});
	
		$j("div.quantity span.increase").bind("click.overrideBC", function () {
			var currentQuantity = parseInt(cartAddQuantity.attr("value"));

			cartAddQuantity.attr("value", (currentQuantity + 1));

			return false;
		});

		// initiate the animation when adding to cart
		$j("div.quantity span.add").bind("click.overrideBC", function () {
			$j("#cart-quantity-vehicle").css("background-position", "0 2px");
			$j("#cart-quantity-vehicle").html(cartAddQuantity.attr("value"));
			cartAddQuantity.hide();

			$j("#cart-quantity-vehicle").animate(
			{
				path : new $j.path.bezier(cartVehicleBezier)
			}, 700, "linear", function () {
				$j("img.cart-add-button").trigger("click");
				$j("a#cart-summary .cart-quantity").css("margin-top", "0");
				//reset the customized "AddToCart" stuff (send quantity vehicle back to default position)
			});

			setTimeout(function () {
				$j("a#cart-summary .cart-quantity").css("margin-top", "1px");
			}, 650);

			return false;
		});
	}
}


/*
//
function newEmptyCartMessage() {
	if #catCartDetails.text() == "Shopping cart is empty. Go Back"
}

function UpdateProductExtras(c, p, res) {
	newEmptyCartMessage();

// c,p,res = -1 when cart is empty
console.log("c: " + c);
console.log("p: " + p);
console.log("res: " + res);
}
*/

/**
 * 
 */
function cartSummaryUpdate() {
	var cartTokens,
	    cartSummary = $j("#catCartSummary .cartSummaryItem").html();

	// parse BC's cart summary informaiton if it exists (should if the {module_shoppingcartsummary} is included)
	// and add the relevant data to our customized cart summary
	if (cartSummary) {
		cartTokens = cartSummary.match(/(\d+) item\(s\), Total: (\$\d+\.\d+)/);

		if (cartTokens) {
			$j("#cart-summary").click(function () {
				$j(window.location).attr("href", $j("a.cartSummaryLink").attr("href"));
			});
			//$j("#cart-summary").attr("href", $j("a.cartSummaryLink").attr("href"));
			$j("#cart-summary .cart-quantity").html(cartTokens[1]);
			$j("#cart-summary .cart-amount").html(cartTokens[2]);
		} else {
			$j("#cart-summary .cart-quantity").html("0");
			$j("#cart-summary .cart-amount").html("$0.00");			
		}

		$j("#cart-summary").attr("title", "Total: " + $j("#cart-summary .cart-amount").html());
	}
}


/**
 * This function is used as a by-pass to alert messages from BC.
 * It wouldn't be necessary if BC kept all the code inside their RefreshCart()
 * (as they claim to in their documentation) because then would could simply
 * override that one function. Instead, we replace BC's code to call this function
 * when they really mean to call alert() (see the last line of this script).
 */
function BC_alert(msg) {
	// if an alert message is either one of the following, update our cart information:
	// - Oshoplang.PreOrder = " item(s) pre-ordered and added to your cart."
	// - Oshoplang.Added = " item(s) added to your cart."
	if (msg.match(/^\d+ item\(s\) (pre-ordered and )?added to your cart\.$/)) {
	//if (msg.match(/^\d+ item\(s\) pre-ordered and added to your cart\.$/) ||
	//    msg.match(/^\d+ item\(s\) added to your cart\.$/)) {
//		addH1Gradient();
//		bindBCEvents();

// relocate the Related Products
$j(".productItem:eq(0) p:eq(0)").after($j("#related-products-source").detach().html());
		cartSummaryUpdate();
alert(msg);
	} else {
		alert(msg);
	}
}


/**
 * Essentially modifyies portions of code that is inside BC's AddToCart() function by:
 *
 * - pulling out the contents of BC's AddToCart function as a String.
 * - replacing some text in it
 * - and re-evaluate it into the our code
 *
 * POTENTIALLY DANGEROUS! But necessary to supress the alert that occurs everytime an
 * item is added to a user's cart without bypassing EVERY alert like so:
 *
 * window.alert = function (msg) { }
 */
if (typeof(AddToCart) === "function") {
	var modifiedFunc = String(AddToCart).replace(/alert\s*\(/g, "BC_alert(");

	// redefine the AddToCart() function
	// essentially does the same thing as: eval(modifiedFunc);
	AddToCart = (new Function("return " + modifiedFunc))();
}

/** /
if (typeof(DrawProduct) === "function") {
	eval(String(DrawProduct).replace(/\}\s*$/, ";bindBCEvents();}"));
}
/**/


/**
 * BC Alert Messages (modify to customize)
 *
 * Added: " item(s) added to your cart." (Message displayed when product is added to the shopping cart. NOTE: The system will display the number of items added to the cart followed by your message)
 * CartEmpty: "Your Shopping cart is empty." (Message displayed when the shopping cart is empty)
 * CartUpdateSuccess: "Shopping cart updated successfully." (Message displayed when the shopping cart is successfully updated)
 * ChooseAttribute: "ERROR: Please choose relevant options before adding to cart."
 * ChooseShip: "ERROR: Please select a shipping charge for your order." (Message displayed when customer tries to check out without selecting a radio button shipping option)
 * ChooseState: "ERROR: Please choose a destination state to calculate state tax." (Message displayed when customer tries to check out without selecting a destination state)
 * EnterGMessage: "ERROR: Please enter a personal message for the recipient of your gift voucher." (Message displayed when customer tries to submit the Gift Voucher form without entering a message for the recipient)
 * EnterGName: "ERROR: Please enter a name for the recipient of your gift voucher." (Message displayed when customer tries to submit the Gift Voucher form without entering the recipients name)
 * EnterZip: "ERROR: Please enter in your Zip/Postcode to calculate shipping costs for your order." (Message displayed when customer tries to check out without entering a zip code)
 * IncorrectGForm: "ERROR: Your gift voucher form is not setup correctly. Please reset to original to restore." (Message displayed when the gift voucher form in Admin -> More Customization Options -> Online Shop Layouts -> gift Voucher layout is broken)
 * InvalidGEmail: "ERROR: Please enter a valid email address for the recipient of your gift voucher." (Message displayed when customer tries to submit the Gift Voucher form without entering a proper email address)
 * InvalidQuantity: "ERROR: Quantity entered is not valid." (Message displayed when invalid quantity is added the shopping cart)
 * InvalidShip: "ERROR: Please choose a valid shipping option." (Message displayed when customer tries to check out without selecting a shipping option)
 * MaxLimit: "ERROR: Quantity entered is too large, please enter a smaller quantity."
 * MinLimit: "ERROR: Quantity entered is too small, please enter a larger quantity."
 * OutOfStock: "Either product is out of stock or choose a smaller quantity" (Message displayed when product added is out of stock)
 * PreOrder: " item(s) pre-ordered and added to your cart." (Message displayed when pre-ordered product is added to the shopping cart. NOTE: The system will display the number of items added to the cart followed by your message)
 * RemoveError: "ERROR: To remove or update quantities select the View Cart link." (Message displayed when product is removed from the shopping cart)
 */
/** /
Oshoplang = {
	Added: "",
	CartEmpty: "",
	CartUpdateSuccess: "",
	ChooseAttribute: "",
	ChooseShip: "",
	ChooseState: "",
	EnterGMessage: "",
	EnterGName: "",
	EnterZip: "",
	IncorrectGForm: "",
	InvalidGEmail: "",
	InvalidQuantity: "",
	InvalidShip: "",
	MaxLimit: "",
	MinLimit: "",
	OutOfStock: "",
	PreOrder: "",
	RemoveError: "" 
};/**/

