$(function() {
	
	var url_opts_interm = window.location.hash.substr(1).split('&');
	var url_opts = [];
	for (var i = 0; i < url_opts_interm.length; i++) {
		var opt = url_opts_interm[i];
		var split_opt = opt.split('=');
		url_opts[split_opt[0]] = split_opt[1];
	}
	
	if (url_opts['options'] == 'open') {
		$('#options-form fieldset').show();
		$('#options-form .options-tab').addClass('up');
	}
	
	/*
	$('ul.product-name').click(function() {
		$(this).find('li').addClass('active');
	});
	$('ul.product-name').mouseout(function() {
	//	$(this).find('li').removeClass('active');
	})*/
	
	/*$('ul.promo-list li.parts h2').click(function() {
		$('#fm-parts:visible').slideUp();
		$('#fm-parts:not(:visible)').slideDown();
		return false;
	})*/
	$('.product-name > li, .quantity > li').live('click', function() {
		if (!$(this).hasClass('always-down')) {
			var position = $(this).offset().top;
			var ul_height = $(this).find('ul').height();
			var end_y = position + ul_height;
			var body_height = $('body').height() - 100;
			// this hits past the bottom of the page
			if (end_y > body_height) {
				$(this).find('ul').css({
					'position': 'absolute',
					'top': ((ul_height * -1) - 2) + 'px'
				});
			}
		}
		$(this).addClass('active').find('ul').css('display', 'none').fadeIn(250);
		return false;
	});
	var $dropdowns = $('.product-name, .quantity');
	
	$dropdowns.addClass('noselection');
	
	$(document).click(function(e) {
		$dropdowns.each(function() {
			if (!$(e.target).parents('ul').length || $(e.target).parents('ul').get(0) != $(this).get(0)) {
				$(this).find('ul').fadeOut(250, function() { $(this).parents('li').removeClass('active'); });
			}
		});
	});
	
	$('.product-name ul li, .quantity ul li').live('click', function() {
		$a = $(this).find('a');
		$parent = $a.parents('.product-name, .quantity');
		if ($parent.hasClass('.quantity')) {
			$parent.find('a:eq(0)').html('Qty: ' + $a.html());
		}
		else {
			$parent.find('a:eq(0)').html($a.html());
			var pid = (/plist-(\d+)/i).exec($a.attr('class'));
			if (pid) {
				pid = pid[1];
				$parent.find('a:eq(0)').append($('<input type="hidden" class="product_id">').val(pid));
			}
		}
		
		var match = (/(bike|product|qty)\-([a-z0-9\-\/]+)/i).exec($a.attr('class'));

		if (match) {
			$a.parents('.product-name, .quantity').removeClass('noselection').find('input').not('.product_id').val(match[2]);
		}
		
		$a.parent().parent().fadeOut(250, function() { $a.parents('li').removeClass('active'); });
		
		var this_dropdowns = $a.parents('.field-container').find('.product-name, .quantity');
		var all_ok = true;
		this_dropdowns.each(function() {
			if ($a.hasClass('noselection')) {
				all_ok = false;
			}
		});
		if (all_ok) {
			$a.parents('.field-container').find('.basket-action').removeClass('disabled');
		}
		
		if ($(this).parents('ul').hasClass('autosubmit')) {
			window.location = $(this).find('a').attr('href');
			return false;
			$form = $(this).parents('form');
			if ($form.find('.submitlink').length) {
				$form.find('.submitlink').click();
			}
			else {
				$(this).parents('form').submit();
			}
		}
		return false;
	});
	
	$('.product-name ul li, .quantity ul li').live('mouseover', function() {
		$(this).addClass('hover');
	});
	
	$('.product-name ul li, .quantity ul li').live('mouseout', function() {
		$(this).removeClass('hover');
	});
	
	function remove_action() {
		if ($(this).parents('.field-container').parent().find('.field-container').length == 2) {
			$('.assembly-add-button').slideUp(400);
		}
		$(this).parents('.field-container').slideUp(function() { $(this).remove() });
		return false;
	}
	
	function add_action() {
		if ($(this).hasClass('disabled')) return false;
		var copy = $(this).parents('.field-container').clone();
		copy.find('.add-action').click(add_action).addClass('disabled');
		copy.find('.product-name').addClass('noselection');
		copy.find('.product-name > li a').text('Please select...');
		copy.find('.do-attrib-hover').hover(attrib_hover_over, attrib_hover_out).mousemove(attrib_hover_move);
		$(this).text('Remove');
		$(this).unbind('click', add_action);
		$this = $(this);
		// IE needs the setTimeout - without it it triggers the remove action straight away. For some reason.
		setTimeout(function() {$this.click(remove_action);}, 1);
		copy.css({
			'height': '26px',
			'display': 'none'
		})
		$(this).parents('.field-container').parent().find('p').after(copy);
		copy.slideDown(400);
		if (!$('.assembly-add-button').is(':visible')) {
			$('.assembly-add-button').slideDown(400);
		}
		var $product_name = $(this).parents('.field-container').find('.product-name');
		$product_name.replaceWith($('<div class="product-name">' + $product_name.find('a:eq(0)').html() + '</div>'));
		
		var $quantity = $(this).parents('.field-container').find('.quantity');
		var quantity_val = $quantity.val();
		$quantity.replaceWith($('<div class="quantity">' + $quantity.val() + '</div>'));

		$parent = $this.parents('.field-container');
		
		$parent.find('.product_id').attr('name', 'product_id[]');
		$parent.append($('<input type="hidden" name="quantity[]">').val(quantity_val));
		return false;
	}
	
	$('.add-action').click(add_action);
	
	function attrib_hover_over(e) {
		var match = (/plist\-(\d+)/).exec($(this).attr('class'));
		if (!match) return;
		var id = parseInt(match[1]);
		var text = attribute_texts[id];
		if (!text) return;
		var dont_fade = false;
		$('.hoverbox').remove();
		var box = $('<div class="hoverbox">' + text + '</div>').css({
			'position': 'absolute',
			'top': e.pageY + 15,
			'left': e.pageX + 10,
			'background': 'black',
			'color': 'white',
			'border': '1px solid #6c6c6c',
			'padding': '4px',
			'text-align': 'left',
			'z-index': 10000,
			'display': 'none',
			'width': '180px'
		});
		box.find('strong').css({
			'display': 'block',
			'float': 'left',
			'width': '64px'
		});
		$('body').append(box);
		box.fadeIn(100);
	}
	
	function attrib_hover_out() {
		$('.hoverbox').fadeOut(250, function() { $(this).remove(); });
	}
	
	function attrib_hover_move(e) {
		$('.hoverbox').css({
			top: e.pageY + 15,
			left: e.pageX + 10
		})
	}
	
	$('.do-attrib-hover').hover(attrib_hover_over, attrib_hover_out);
	$('.do-attrib-hover').mousemove(attrib_hover_move);
	
	
	function hoverbox(x, y, w, text) {
			var top = y;
			$('.hoverbox').remove();
			var box = $('<div class="hoverbox"><div class="inner">' + text + '</div></div>');
			box.css({
				'position': 'absolute',
				'top': top - 5,
				'left': x,
				'width': w,
				'color': 'white',
				'padding': '0px',
				'padding-top': '6px',
				'background': 'url(/skin/speedaway/image/layout/box-point.gif) top center no-repeat',
				'text-align': 'left',
				'z-index': 10000,
				'opacity': 0
			});
			box.find('.inner').css({
				'background': 'black',
				'padding': '4px',
				'border-color': '#6c6c6c',
				'border-width': '0 1px 1px 1px',
				'border-style': 'solid',
				'font-size': '8pt'
			});
			box.find('strong').css({
				'margin-bottom': '5px',
				'display': 'block'
			});
			$('body').append(box);
			
			
			box.animate({top: top, opacity: 1}, 300);
	}
	
	function hoverbox_out(y) {
		$('.hoverbox').animate({top: y + 3, opacity: 0 }, 300, function() {
			$(this).remove();
		});
	}
	
	function hoverboxtop(x, y, w, text, center) {
			$('.hoverbox').remove();
			var top = y;
			var box = $('<div class="hoverbox"><div class="inner">' + text + '</div></div>').css({
				'position': 'absolute',
				'left': x,
				'width': w,
				'color': 'white',
				'padding': '0px',
				'padding-bottom': '6px',
				'background': 'url(/skin/speedaway/image/layout/box-point-down.gif) bottom center no-repeat',
				'text-align': 'left',
				'z-index': 10000,
				'opacity': 0
			});
			if (center) {
				box.css({'text-align': 'center'});
			}
			box.find('.inner').css({
				'background': 'black',
				'padding': '4px',
				'border-color': '#6c6c6c',
				'border-width': '1px 1px 0px 1px',
				'border-style': 'solid',
				'font-size': '8pt'
			});
			box.find('strong').css({
				'margin-bottom': '5px',
				'display': 'block'
			});
			$('body').append(box);
			box.css({top: (top - box.outerHeight())});
			box.animate({top: (top - box.outerHeight()) - 5, opacity: 1}, 300);
	}
	
	function hoverboxtop_out(y) {
		$('.hoverbox').animate({top: (y - $('.hoverbox').outerHeight()) - 10, opacity: 0 }, function() {
			$(this).remove();
		});
	}
	
	$('.delivery-help-hover').hover(function() {
		var page = $(this).hasClass('next-day') ? 'next-day' : $(this).hasClass('recorded') ? 'recorded' : $(this).hasClass('working-days') ? 'working-days' : '';
		if (!page) return;

		var text = texts[page];
		hoverboxtop(
			/* x */ $('#right-container').offset().left + 12,
			/* y */ $('.stock-notice').offset().top + 11,
			/* w */ $('#right-container').outerWidth() - 24,
			/* t */ text
		);
	}, function() {
		hoverboxtop_out($('.stock-notice').offset().top + 11);
	});
	
	$('.stock-hover').hover(function(e) {
		hoverboxtop(
			$(e.target).offset().left - 85,
			$(e.target).offset().top,
			170 + $(e.target).outerWidth(),
			$(e.target).attr('alt'),
			true
		);
	}, function(e) {
		hoverboxtop_out($(e.target).offset().top);
	});
	
	$('.chassis-hover').hover(function(e) {
		hoverboxtop(
			$(e.target).offset().left - 65,
			$(e.target).offset().top,
			130 + $(e.target).outerWidth(),
			'This will help us identify the exact part for your bike.',
			true
		);
	}, function(e) {
		hoverboxtop_out($(e.target).offset().top);
	});
	
	$('.out_of_stock_warning').hover(function(e) {
		hoverboxtop(
			$(e.target).offset().left - 85,
			$(e.target).offset().top,
			170 + $(e.target).outerWidth(),
			'Some items in your order are currently on special order. However, delivery should be made within 7-10 working days, which we will confirm once we receive your order.',
			true
		);
	}, function(e) {
		hoverboxtop_out($(e.target).offset().top);
	});
	
	$('.remove-hover').hover(function(e) {
		hoverboxtop(
			$(this).offset().left - 50,
			$(this).offset().top,
			100 + $(this).outerWidth(),
			'Remove this item from your basket',
			true
		);
	}, function(e) {
		hoverboxtop_out($(this).offset().top);
	});
	
	$('.next-day-only').hover(function() {
		hoverboxtop(
			$(this).offset().left - 70,
			$(this).offset().top,
			140 + $(this).outerWidth(),
			"Our Next Day service costs &pound;7.50 and, for insurance reasons, is the only delivery option available if the value of the order is over &pound;50 + VAT (whether the item is in stock or out of stock)."
		);
	}, function() {
		hoverboxtop_out($(this).offset().top);
	});
	
	$('.cat-title > a').click(function() {
		if ($(this).parent().is('.closed')) {
			$(this).parent().find('ul').slideDown();
			$(this).parent().removeClass('closed');
		}
		else {
			$(this).parent().find('ul').slideUp();
			$(this).parent().addClass('closed');
		}
		return false;
	});
	
	$('input[name="terms"]').kakartLiveSearch({
		source: '/livesearch/',
		resultsContainer: '#ajax_results',
		maxResults: 10,
		itemTemplate: function(index, item) {
			return '<li class="resultli clearfix ' + (index % 2 == 0 ? 'even' : 'odd') + '" id="variant' + item.variant_id + '">\
				<a href="/part/' + item.product_id + '/' + item.product_fname + '">\
				<span class="prodcode"><span style="float: right; width: 60px; text-align: right; ">&pound;' + item.variant_price + '</span>' + item.variant_code + '</span>\
				' + item.product_name + '\
					<span class="bike">' + item.product_root_category + ' / ' + item.category_name + '</span>\
				</a>\
			</li>';
		}
	});
	
	$('#product-selector').change(function() {
		window.location = '/part/' + $(this).find('option:selected').val();
	});
	
	$('.options-tab').click(function() {
		$fieldset = $(this).parent().parent().find('fieldset');
		if ($fieldset.is(':hidden')) {
			$fieldset.slideDown();
			$(this).addClass('up');
		}
		else {
			$fieldset.slideUp();
			$(this).removeClass('up');
			window.location.hash = '';
		}
		return false;
	});
	
	$(function() {
		$('#number').change(function() {
			add_filter('per_page', $(this).find('option:selected').val());
			return false;
		});
		$('#sort').change(function() {
			add_filter('sort', $(this).find('option:selected').val());
			return false;
		})
	});	
});

var analytics = false;
var goal_url = false;