Array.prototype.removeItems = function(itemsToRemove) { if (!/Array/.test(itemsToRemove.constructor)) { itemsToRemove = [ itemsToRemove ]; } var j; for (var i = 0; i < itemsToRemove.length; i++) { j = 0; while ( j < this.length) { if (this[j] == itemsToRemove[i]) { this.splice(j, 1); } else { j++; } } } }
Array.prototype.inArray = function(value) { var i; for (i=0; i < this.length; i++) { if (this[i] === value) { return true; } } return false; };

options = { path: '/' };

$('#compare-table td.remove form').submit(function(e) {
	
	e.preventDefault();
	id = $(this).find("input[name='product_no']").val();
	message = $(this).find("input[name='message']").val();
	products = $.cookie('comparison');
	list = [];
		
	remove = confirm(message);
	
	if(remove) {
		list = products.split(',');
		list.removeItems(id);
		$.cookie('comparison', list.join(','), options);
		$(this).parents('tr').fadeOut('slow');
	}
	
});

// Go through each product on the page and check the checkbox if the product number is in the cookie.
$("div.product div.comparison-checkbox input.compare").each(function() {
	var products = $.cookie('comparison');
	var id = $(this).val();
	if(products) {
		if(products.split(',').inArray(id)) {
			$(this).attr('checked', 'checked');
		}
	}	
});

// If the checkbox changes, we need to figure out what to do with the cookie!
$("div.product div.comparison-checkbox input.compare").change(function() {
	
	var id = $(this).val();
	var checked = $(this).attr('checked');
	var products = $.cookie('comparison');
	var label = $(this).next('label');
	var list = [];
	
	if(checked) {
		if(products) {
			list = products.split(',');
			list.removeItems(id);
			list.push(id);
			$.cookie('comparison', list.join(','), options);
		} else {
			$.cookie('comparison', id, options);
		}
	} else {
		if(products) {
			list = products.split(',');
			list.removeItems(id);
			$.cookie('comparison', list.join(','), options);
		}
	}
	
	$(':checked').next('label').addClass('selected');
	$(':not(:checked)').next('label').removeClass('selected');
		
});

$(':checked').next('label').addClass('selected');
$(':not(:checked)').next('label').removeClass('selected');

// Don't show these till we can start using the cookie functions!
$('div.product div.comparison-checkbox').css('display', 'block');