/*--------------------------------------------------
BASE JAVASCRIPT

Localised JavaScript on a per-site basis should 
go here. All script must be under a single global 
namespace.
--------------------------------------------------*/
var $j, IBRF;

$j = jQuery.noConflict();
IBRF = IBRF || {};

IBRF = {
	Config: {
		Content: {
			Carousel: {
				error: "Sorry, there was a problem. We can't get the recipe for you."
			}
		}
	},
	Page: {
		global: function() {
			IBRF.MiniBasket.init();
			var nav = new IBRF.Navigation("produce-nav");

			if (document.getElementById("suppliers")) {
				IBRF.Suppliers.Directory.init();
			}
		},
		checkout: function() {
			IBRF.Checkout.GiftMessage.init();
			IBRF.Checkout.Billing.init();
		},
		home: function() {

			//$j("#content-channel .summary").pngfix();
			var carousel = new IBRF.Carousel();
		},
		details: function() {
			var tab = new IBRF.Tabbed("product-details", "product-details-nav", "product-details-content");

			// If there is a first reviewer, jummp and highlight the tab.
			$j("#product-info .first-rating a").eq(0).click(function() {
				$j("#product-details-nav a").eq(2).trigger("click");

				// Stop Magento linking.
				window.location.hash = "customer-reviews";
				return false;
			});
		},
		basket: function() {
			IBRF.Checkout.DeliveryDeails.init();
		},
		product: function() {
			return;
			var items = $j("ul.product-view li").length;
			var i = (items % 4) ? items - (items % 4) - 1 : items - 5;
			$j("ul.product-view li:gt(" + i + ")").each(function() {
				$j(this).addClass("tail-child");
			});
		},
		producer: function() {
			// Show the Google Map
			if (GBrowserIsCompatible()) {
				var coord = IBRF.GeoLocation;

				var map = new GMap2(document.getElementById("producer-map"));
				map.setCenter(new GLatLng(coord.lat, coord.lng), 13);
				  
				var point = new GLatLng(coord.lat, coord.lng);
				map.addOverlay(new GMarker(point));
			}

			$j(window).unload(function() { 
				GUnload();
			});

			// Enhance the Google map in the Aside
			$j("#producer-info dt.producer-info-map").toggle(
				function() {
					var el = $j(this).html("Show Mini Map").next();
					el.css("display", "none");
				},
				function() {
					var el = $j(this).html("Hide Mini Map").next();
					el.css("display", "block");
				}
			);
			
			$j("#producer-info dt[class=]").toggle(
				function() {
					var el = $j(this).next();
					el.css("display", "block");
				},
				function() {
					var el = $j(this).next();
					el.css("display", "none");
				}
			);
			
			//$j("#content-channel .summary").pngfix();
		},
		accountEdit: function() {
			var editPassword = $j("#edit-password").hide();

			$j("#edit-account-password input").click(function() {
				editPassword.toggle();
			}).attr("checked", "");
		}
	}
};

$j(function() {
	IBRF.Page.global();
	var page, 
		bodyId = document.body.id;

	if (bodyId) {
		page = bodyId.replace(/(([a-z\-]*)(-page))/g, function() {
			return arguments[2].replace(/(\-([a-z]))/g, function() {
				return arguments[2].toUpperCase();
			});
		});

		if (IBRF.Page[page]) {
			IBRF.Page[page]();
		}
	}

	if (document.body.className.indexOf("cms-index-index") !== -1) {
		IBRF.Page.home();
	}
	if (document.body.className.indexOf("catalog-product-view") !== -1) {
		IBRF.Page.details();
	}
	if (document.body.className.indexOf("catalog-category-view") !== -1) {
		IBRF.Page.producer();
	}

});



IBRF.Suppliers = {
	Directory: {
		init: function() {
			var canvas;
			canvas = document.getElementById("suppliers");
			$j("li.details a", canvas).click(function(e) {
				$j(this.href.substring(this.href.indexOf("#"))).toggle(1000);
				return false;
			});

		}
	}
};

/**
 * Mini basket show/hide and load
 */
IBRF.MiniBasket = {
	init: function() {
		// Basket needs to be removed to prevent IE z-index layering bug rel > abs
		$j("#mini-basket")
			.eq(0)
			.appendTo("body")
			.find("ul.nav li:eq(1)")
			.click(function() {
				$j("#mini-basket ul.products").slideToggle("slow");
				return false;
			});

		$j("#mini-basket ul.products").css("display", "none");
	}
};

/**
 * Checkout
 */
IBRF.Checkout = {
	DeliveryDeails: {
		init: function() {
			// Sort out the delivery message
			$j("#delivery-terms").css("position", "absolute").hide(); 
			$j("#delivery-terms a").click(function() {
				$j("#delivery-terms").fadeOut("normal"); 
				return false;
			});

			// Apply events to the line items
			$j("#basket td.t-delivery a").click(function() {
				var pos = $j(this).position();
				$j("#delivery-terms").css({left: pos.left - 206, top: pos.top - 9}).fadeIn("normal");

				return false;
			});
		}
	},
	GiftMessage: {
		/**
		 * Setup the gift message functionality: toggle the gift message option.
		 */
		init: function() {
			var message = $j("#gift-message").wrap(document.createElement("div")).parent().css({
				"overflow": "hidden",
				"float": "left"
			});

			var check = $j("#gift-confirmation input:eq(0)").click(function() {
				message.slideToggle("slow");
			});

			if (!check.is(":checked")) {
				message.css("display", "none");
			}
		}
	},
	Billing: {
		/**
		 * Setup up the billing functionality.
		 */
		init: function() {
			$j("#shipping-method fieldset:eq(0)").find("input:eq(0)").click(function() {
				var inputs = $j("#shipping-method fieldset:gt(0) input, #shipping-method fieldset:gt(0) select");
				if ($j(this).attr("checked")) {
					inputs.attr("disabled", "disabled");
				} else {
					inputs.attr("disabled", "");
				}
			});
		}
	}
};


/**
 * Tree navigation
 * @param {String} el Id of the tree navigation container.
 */
IBRF.Navigation = function(el) {
	$j("#" + el + " li h4:first-child").each(function() {
		var next = $j(this).next();
		if (next.length && next[0].nodeName === "UL") {
			$j(this).bind("click", function(e) {
				if ($j(this).parent().hasClass("active")) {
					$j(this)
						.parent()
						.removeClass("active")
						.children("ul")
						.css("display", "none");
				} else {
					$j(this)
						.parent().siblings()
						.each(function() {
							$j(this)
							.removeClass("active")
							.children("ul")
							.css("display", "none");
						});

					$j(this)
						.parent()
						.addClass("active")
						.children("ul")
						.css("display", "block");
				}
				e.preventDefault();
			});
			$j(this)
				.children("li:[class!='active'] ul")
				.css("display", "none");
		}

	});
};

/**
 * Create a tabbed interface
 * @param {String} canvas Container of the content to use.
 * @param {String} nav Container of the list of links.
 * @param {String} content Container for the AJAX fetched data.
 */
IBRF.Tabbed = function(canvas, nav, content) {
	var instance = this;

	// Get the elements
	this.canvas = $j("#" + canvas);
	this.nav = $j("#" + nav);
	this.content = $j("div." + content);

	var reset = function() {
		instance.nav.children().each(function() {
			$j(this).removeClass("active");
		});

		instance.content.each(function() {		
			$j(this).css("display", "none");
		});
	};

	// Check for preselected
	var active = this.nav.find("li.active");
	if (active.length) {
		var href = this.nav.find("li.active a").attr("href")
		reset();
		active.addClass("active");
		$j(href).css("display", "block");
	} else {
		this.nav.children().eq(0).addClass("active");
		this.content.eq(0).css("display", "block");
	}

	this.nav.find("a").each(function() {
		$j(this).click(function() {
			reset();

			$j(this).parent().addClass("active");	
			$j(this.href.substring(this.href.indexOf("#"))).css("display", "block");

			return false;
		});
	});
};

/**
 * Carousel
 * JSON format:
 * {
 * 	image: "example.jpg",
 * 	alt: "Alt text",
 * 	href: "url",
 * 	next: "next url",
 * 	prev: "previous url"
 * }
 */
IBRF.Carousel = function() {
	this.canvas = "inspiration-nav";
	this.init();
};
IBRF.Carousel.prototype = {
	init: function() {
		// Build the carousel
		this.image = $j("<img />")
			.attr({
				id: "inspiration-canvas",
				src: ""
			})
			.insertAfter("#" + this.canvas);

		var nav2 = [
			"<ul id='inspiration-control'>",
			"<li><a href='1'><img src='/skin/frontend/IBRF/default/assets/media/images/buttons/inspiration-view.gif' alt='Show me the recipe' /></a></li>",
			"<li><a href='2'><img src='/skin/frontend/IBRF/default/assets/media/images/buttons/inspiration-prev.gif' alt='Previous recipe' /></a></li>",
			"<li><a href='3'><img src='/skin/frontend/IBRF/default/assets/media/images/buttons/inspiration-next.gif' alt='Next recipe' /></a></li>",
			"</ul>"
		];

		var nav = [
			"<ul id='inspiration-control'>",
			"<li><a href='1'><img src='/skin/frontend/IBRF/default/assets/media/images/buttons/inspiration-view.gif' alt='Show me the recipe' /></a></li>",
			"</ul>"
		];

		$j(nav.join("")).insertAfter("#" + this.canvas);

		var link = $j("#inspiration-control li a");
		this.href = link.eq(0);
		this.prev = link.eq(1);
		this.next = link.eq(2);

		var o = this;

		var href = $j("#" + this.canvas + " li")
			.each(function() {
				$j(this).click(function() {
					$j(this).siblings().removeClass("active");
					$j(this).addClass("active");


					o.fetch($j(this).find("a").eq(0));
					return false;
				});
			})
			.eq(0);
			//.addClass("active")
			//.find("a").eq(0);

		var active = $j("#inspiration-nav li.active").eq(0).find("a");

		if (!active.length) {
			active = $j("#inspiration-nav li").eq(0).addClass("active").find("a");		
		}
		this.fetch(active.eq(0));
	},
	fetch: function(link) {
		$j("#" + this.canvas + "-error").remove();

		// Ajax load
		var o = this;
		jQuery.ajax({
			timeout: 20000,
			url: link.attr("href") + "?format=json", 
			dataType: "json",
			error: function() {
				$j("<p id='" + o.canvas + "-error' class='error'>" + IBRF.Config.Content.Carousel.error + "</p>")
					.css("opacity", 0)
					.insertAfter("#" + o.canvas)
					.animate({ 
					opacity: .8
				  }, 250);
			},
			success: function(data){
				o.image.attr({
					src: data.image,
					alt: data.alt
				});

				o.href.attr("href", data.href);
				o.prev.attr("href", data.prev);
				o.next.attr("href", data.next);
			}
		});
	}
};