Array.prototype.inArray = function(value) { var i; for ( i = 0; i < this.length; i++ ) { if ( this[i] == value ) { return true; } } return false; };
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++; } } } }

// PPK Cookie Functions - http://www.quirksmode.org/js/cookies.html
function createCookie(name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; }
function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; }
function deleteCookie(name) { createCookie(name,"",-1); }

// The name of the cookie...
var comparisonCookie = 'its-product-comparison';
var products = readCookie( comparisonCookie ) ? readCookie( comparisonCookie ).split('-') : [];

$("div.its-compare-snippet").each(function() {
	
	var $this = $(this);
	var productNumber = $this.attr('data-product-number');
	
	var $checkbox = $('<input/>').attr({
		"class" : "its-compare",
		"checked" : products.inArray( productNumber ) ? "checked" : null,
		"type" : "checkbox",
		"name" : "product-" + productNumber
	}).val( productNumber );
	
	$checkbox.prependTo( $this );
		
	
	$this.css( 'display', 'block' );
		
});


$("input[class='its-compare']").change(function(e) {
	
	var $this = $(this);
	
	var productNumber = $this.val();
	var checked = $this.attr('checked');
	
	products.removeItems( productNumber );
	
	if( checked ) { products.push( productNumber ); }
	createCookie( comparisonCookie, products.join('-') );
	
				
});


$('a.remove-compared-item').click(function(e) {
   
    e.preventDefault();
    var $item = $(this);
    var productNumber = $item.attr('data-product-number');
        
    if( confirm('Are you sure you want to remove this item from Comparison?') ) {
        products.removeItems( productNumber );
        $item.parents('tr').fadeOut('slow');
        createCookie( comparisonCookie, products.join('-') );
    }

});


