$(document).ready(function(){
	log = true;
	
	if (jQuery.browser.msie && parseInt(jQuery.browser.version) <= 7) {
		//do nothing
	}
	else {
		// defines whether another js call can start (like a blocker)
		allowedToCall = true; 
		
		// current XMLHttpRequest (or ie equivalent) object
		thisXMLHttpRequest = null;
		
		//current cache
		var HTMLcache = {};
			
		if(typeof(console) == "undefined") {
			log = false;
		}
		
		if(log) {
			console.log("console logging enabled");
		}
		
		// hide the non-js enabled browser product information 
		$("#feature-bar table tr:last").hide();
		
		// show product information for js enabled browsers
		$("#feature-bar table th").each(function(i) {
			$(this).children("div.product-info-pane:first").show();
			$(this).children("h3").show();
			$(this).children("p.product-info-button").show();
			$(this).children("div.colour-well").show();
		});
		
		// change product icon when user picks a different colour
		$("div.colour-well p a").bind("mouseenter",function(){
			var th = $(this).parent("p").parent("div").parent("th");
			th.children("div.product-info-pane").hide();
			th.children("div#" + $(this).attr("id") + "-icon").show();
		});
		
		// action when user click on a colour in the colour well
		$("div.colour-well p a").click(function() {
			var request_url =  $(this).attr("href");
			get_product_from_style_page(request_url);
			return false;
		});
		
		// action when user clicks on a product information button
	   	$("p.product-info-button a").click(function(){
	   		var request_url =  $(this).attr("href");
	   		get_product_from_style_page(request_url);
	   		return false;
	   	});
   	}
   	// Functions
   	/*
   		function: get_product_from_style_page
   		Product popin requested from styles page
   		Assumed no frame setup
   	*/
   	function get_product_from_style_page(request_url)
   	{
   		setup_frame();
   		if(cache_hit(request_url)) {
   			get_product(request_url, fade_in_frame_and_display_product);
   		}
   		else {
   			show_loading_message();
   			get_product(request_url, clear_load_and_display_product);
   		}	
   	}
   	
   	/*
   		function: get_product
   		grabs the data from the cache, or loads it in using an ajax call
   	*/
   	function get_product(request_url, display_callback) {
   		if(cache_hit(request_url)) {
   			var data = get_cache_data(request_url);
   			display_callback(data);
   		}
   		else {
   			get_data(request_url, display_callback);
   		}
   	}
   	
   	/*
   		function: get_data
   		loads product data using an ajax call
   	*/
   	function get_data(request_url, display_callback)
   	{
   		if(allowedToCall) {
   			allowedToCall = false;
   			thisXMLHttpRequest = $.ajax({
   				type: "GET",
				url: request_url,
				success: function(data) {
					HTMLcache[request_url] = data;
					display_callback(data);
					allowedToCall = true;
				},
				error: function(data) {	  
					allowedToCall = true;
				}
			});
   		}
   	}
   	
   	function get_cache_data(request_url) {
   		return HTMLcache[request_url];
   	}
   	
   	/*
   		function cache_hit
   		returns true if the specified HTML resource is in the cache
   	*/
   	function cache_hit(request_url) {
   		return (request_url in HTMLcache);
   	}
   	
   	/*
   		function: setup_frame
   		sets up the product information frame and black/whiteout div
   	*/
   	function setup_frame() {
   		$("<div id=\"blackout\"></div>").appendTo("body");
   		$("<div id=\"product-popin\"></div>").appendTo("body").hide();
   		$("<div id=\"product-popin-inner\"></div>").appendTo("#product-popin");
   		$("<div id=\"product-popin-content\"></div>").appendTo("#product-popin-inner");
		$("<p id=\"close-popin\"><a href=\"#\">Close</a></p>").appendTo("#product-popin-inner");
   	}
   	
   	/*
   		function: teardown_frame
   		removes the product information frame and black/whiteout div
   	*/
   	function teardown_frame() {
   		$("div#product-popin").fadeOut("fast", function(){
			$(this).remove();
			$("div#blackout").remove();
		});	
   	}
   	
   	/*
   		function: show_loading_message
   		shows a loading message in the center of the screen
   	*/
   	function show_loading_message()
   	{
   		var imageParagraph = "<p class=\"image\"><img src=\"" + URL_ROOT + "\a/i/" + TEMPLATE_THEME + "/ajax-loader.gif\" /></p>";
   		var loadingParagraph = "<p>Loading&hellip;</p>";
   		$("<div id=\"ajax-loading\"><div>" + imageParagraph + loadingParagraph + "</div></div>").appendTo("body");
   		center_item($("div#ajax-loading"));
		keep_item_centered($("div#ajax-loading"));
		setup_loading_message_removal_event();
   	}
   	
   	/*
   		function: hide_loading_message
   		hides loading message
   	*/
   	function remove_loading_message()
   	{
   		$("div#ajax-loading").remove();
   	}
   	
   	/*
   		function: setup_blackout_removal_event
   		remove blackout if clicked
   	*/
   	function setup_loading_message_removal_event() {
   		$("div#blackout").click(function() {
   			remove_loading_message();
   			$("div#blackout").remove();
   			if(thisXMLHttpRequest != null) {
				// cancel current request
				thisXMLHttpRequest.abort();
   			}
   			return false;
   		});
   	}
   	
   	function fade_in_frame_and_display_product(data)
   	{
   		set_product_data(data);
		$("#product-popin").fadeIn();
		display_product();
   	}
   	
   	function clear_load_and_display_product(data)
   	{
   		set_product_data(data);
   		$("#ajax-loading").fadeOut(function() {
			$("#product-popin").fadeIn();
			remove_loading_message();
		});
		display_product();
   	}
   	
   	function clear_opacity_and_display_product(data)
   	{
   		set_product_data(data);
   		$("#product-popin-content").css("opacity","1");
   		display_product();
   	}
   	
   	/*
   		function set_product_data
   		sets the data for the product to be displayed
   	*/
   	function set_product_data(data)
   	{
   		$("div#product-popin-content").html(data);
   	}
   	
   	/*
   		function: display_product
		takes product data and displays it in the frame
		call setup_frame() prior to calling this method 
   	*/
   	function display_product() {
		center_item($("div#product-popin"));
		keep_item_centered($("div#product-popin"));
		
		setup_popin_removal_events();
		setup_colour_links();
		keep_subtotal_updated();
		setup_buy_button();
   	}
   	
   	/*
   		function: setup_popin_removal_events
   		remove popin if close button clicked or blackout clicked
   	*/
   	function setup_popin_removal_events() {
   		$("p#close-popin a").click(function() {
   			teardown_frame();
   			return false;
   		});
   		
   		$("div#blackout").unbind("click"); // set earlier
   		$("div#blackout").click(function() {
   			teardown_frame();
   			return false;
   		});
   		
   		
   		$(document).keyup(function(e) {
   			if (e.which == 27) {
   				teardown_frame();
   				return false;
   			}
   		});
   	}
	
   	/*
   		function: setup_colour_links
   		load in new product info if colour link button clicked
   	*/
   	function setup_colour_links() {
   		$("table.colour-options a").click(function() {
   			$("#product-popin-content").css("opacity",".5");
   			get_product($(this).attr("href"), clear_opacity_and_display_product);
   			return false;
   		});
   	}
   	
   	/*
		function: keep_subtotal_updated
		keeps subtotal updated as user types in quantity field
	*/
   	function keep_subtotal_updated() {
   		$("input[name=qty]").keyup(function() {
   			var price = $("#product-popin input[name=price]").val();
   			
   			var quantity = $(this).val();
   			if(!quantity || quantity < 1) {
   				quantity = 1;
   			}
   			
			newSubtotal = quantity * price;
			if(!newSubtotal || newSubtotal < price) {
				newSubtotal = price;
			}
			
			try {
				newSubtotal = newSubtotal.toFixed(2)
			}
			catch(err) { } // do nothing, but numbered won't be rounded nicely
			
   			$(this).parent("p").siblings("p.subtotal").html("<span>Subtotal:</span> &pound; " + newSubtotal);
   		});
   	}
   	
   	function setup_buy_button() {
		if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 8) {
	   		$("label#checkout-button").click(function() {
	   			$(this).parent("div").parent("form").trigger("submit");
	   		});
	   	}
   		
   		/*$("a#add-to-basket-button").click(function() {
   			if(allowedToCall) {
				allowedToCall = false;
				
				pricing_form = $(".pricing-details form");
				postdata = {
					"product": pricing_form.find("input[name=product]").val(),
					"units": pricing_form.find("input[name=units]").val(),
					"price": pricing_form.find("input[name=price]").val(),
					"userid": pricing_form.find("input[name=userid]").val(),
					"qty": pricing_form.find("input[name=qty]").val(),
					"return": pricing_form.find("input[name=return]").val()
				};
				
				thisXMLHttpRequest = $.ajax({
					type: "POST",
					url: "/~matthewbetts/post_dump.php",
					data: postdata,
					success: function(data) {
						allowedToCall = true;
					},
					error: function(XMLHttpRequest, textStatus) {
						alert("errror" + textStatus);
						allowedToCall = true;
					}
				});
			}
			
			return false;
   		});*/
   	}
   	
   	/*
		function: center_item
		places item in the center of the window
	*/
	function center_item(item) {
		current_window_width = $(window).width();
		current_window_height = $(window).height();
		
		this_width = item.width();
		this_height = item.height();
		
		left_position = (current_window_width / 2) - (this_width / 2);
		top_position = (current_window_height / 2) - (this_height / 2);
		
		item.css("left", left_position);
		item.css("top", top_position);
	}
	
	/*
		function: keep_item_centered
		keeps item in the center of the window
	*/
	function keep_item_centered(item) {
		var resizeTimer = null;
		$(window).bind('resize', function() {
			  if (resizeTimer) clearTimeout(resizeTimer);
			  resizeTimer = setTimeout(function() { center_item(item) }, 300);
		});
	} 
});