log = true;

if(typeof(console) == "undefined") {
	log = false;
}

if(log) {
	//console.log("console logging enabled");
}

// defines whether another js call can start (like a blocker)
allowedToCall = true; 

// current XMLHttpRequest (or ie equivalent) object
thisXMLHttpRequest = null;

//current cache
var HTMLcache = {};

/*
	function: get_product_from_style_page
	Product popin requested from styles page
	Assumed no frame or blackout setup
*/
function get_product_from_style_page(request_url)
{
	setup_blackout()
	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_for_buy_page
	Product popin requested from buy page
	Assumed no frame setup
*/
function get_product_for_buy_page(request_url)
{
	if($("div#product-popin").length == 0) {
		setup_frame();
	}
	
	if(cache_hit(request_url)) {
		get_product(request_url, append_frame_to_target_and_display_product);
	}
	else {
		append_spinner_to_target();
		get_product(request_url, clear_spinner_append_frame_to_target_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_blackout
	sets up the product information frame and black/whiteout div
*/
function setup_blackout() {
	$("<div id=\"blackout\"></div>").appendTo("body");
}

/*
	function: setup_frame
	sets up the product information frame and black/whiteout div
*/
function setup_frame() {
	$("<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 append_spinner_to_target()
{
	var imageParagraph = "<p class=\"spinner\"><img src=\"" + URL_ROOT + "\a/i/" + TEMPLATE_THEME + "/ajax-loader.gif\" /></p>";
	popinTargetParent.append(imageParagraph);
}

/*
	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();
		allowedToCall = true;
		}
		return false;
	});
}

/*
	function: fade_in_frame_and_display_product
	fades in the frame (as data loaded) and displays product
	used on styles page
*/
function fade_in_frame_and_display_product(data)
{
	set_product_data(data);
	$("#product-popin").fadeIn();
	
	center_item($("div#product-popin"));
	keep_item_centered($("div#product-popin"));
	
	setup_popin_events();
}

/*
	function: clear_load_and_display_product
	clears the ajax spinner (as data loading) and displays product
	used on styles page
*/
function clear_load_and_display_product(data)
{
	set_product_data(data);
	$("#ajax-loading").fadeOut(function() {
		$("#product-popin").fadeIn();
		remove_loading_message();
	});
	
	center_item($("div#product-popin"));
	keep_item_centered($("div#product-popin"));
	
	setup_popin_events();
}


/*
	function: clear_load_and_display_product
	clears the ajax spinner (as data loading) and displays product
	used on styles page
*/
function append_frame_to_target_and_display_product(data)
{
	set_product_data(data);
	
	// determine which list item clicked on
	var index = $("#product-results li").index(popinTargetParent);
	if(index%4 > 1) {
		$("#product-popin").removeClass("left");
		$("#product-popin").addClass("right");
	}
	else {
		$("#product-popin").removeClass("right");
		$("#product-popin").addClass("left");
	}
	
	$("#product-popin").appendTo(popinTargetParent).slideDown("fast");
	setup_popin_events();
}

function clear_spinner_append_frame_to_target_and_display_product(data)
{
	popinTargetParent.find("p.spinner").fadeOut(function() {
		$(this).remove();
	});	
	append_frame_to_target_and_display_product(data);
}

/*
	function: clear_opacity_and_display_product
	clears opacity and displays product
	used on popin (see setup_colour_links)
*/
function clear_opacity_and_display_product(data)
{
	set_product_data(data);
	$("#product-popin-content").css("opacity","1");
	
	setup_popin_events();
}

/*
	function set_product_data
	takes product data and displays it in the frame
*/
function set_product_data(data)
{
	$("div#product-popin-content").html(data);
}

/*
	function: setup_popin_events
	sets up all events used with a popin
*/
function setup_popin_events() {
	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() {
	$("div.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() {
	$("input#buy-button").mouseover(function() {
		var src = $(this).attr("src");
		src = src.replace(/\.png/,"_over.png", src);
		$(this).attr("src", src);
	});
	
	$("input#buy-button").mouseout(function() {
		var src = $(this).attr("src");
		src = src.replace(/_over\.png/,".png", src);
		$(this).attr("src", src);
	});
}

/*
	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);
	});
} 
