Array.prototype.distinct = function() {
    var derivedArray = [];
    for (var i = 0; i < this.length; i++) {
        if ($.inArray(this[i], derivedArray) == -1) {
            derivedArray.push(this[i])
        }
    }
    return derivedArray;
};

function CloneTable(index) {
    var clone = jQuery("#CartContainer table[id$='CartGrid']").clone(true);
    clone[0].setAttribute('id', clone[0].getAttribute('id') + index);
    clone.appendTo('#CartContainer');
    return clone;
}

var CloneTables = new Array();

function ViewSearchStandard() {
	$("input[type='submit']").click();
}	

function ViewSearchByProductCategory() {
	//Get the product categories
	var productParents = new Array();
	var productParentNames = new Array();
	$("#CartContainer span[class^='parent']").each(function(index, element){
		productParents.push($(element).data('parent'));
		productParentNames.push($(element).data('parent-name'));
		});
	var uniqueParentList = productParents.distinct();
	var uniqueParentNameList = productParentNames.distinct();
	
	for (var i=0; i<uniqueParentList.length; i++)
	{
		//Create one table per product category
		var table = CloneTable(i);
		CloneTables.push(table);
		$(table).find('span[class^="parent"]').not('[class="parent' + uniqueParentList[i] + '"]').parents('tr').remove();
		if (i>0)$(table).before("<br/><br/>");
		$(table).before("<h3>" + uniqueParentNameList[i] + "</h3>");
		
		//Fix issue with postbacks and cloning tables
		$(table).find('input[name*="CartGrid"]').each(function(){
			var name = $(this).attr('name');
			$(this).change(function(){
				$("input[name='"+name+"']").val($(this).val());
			})
			$(this).attr('name',name.replace(':CartGrid:', ':CartGrid'+i+':'));
		});	
	}
	jQuery("#CartContainer table[id$='CartGrid']").hide();
	$("#ViewByProduct,#ViewStandard").toggle();
}

$(document).ready(function() {
	//zdfgasfdg
});
