var mem = [];
var x = 0;
var list = '';

function chooseSample(name) {
	
	if(x < 3) {
		// Check if already in list
		var ok = true;
		for(var foo=0; foo<mem.length; foo++) {
			if(name == 	mem[foo]) {
				ok = false;	
			}
		}
		
		if(ok == true) {
			mem[x] = name;
			x++;
		}
		
		// Refresh list
		list = '<h3>Chosen Leather Swatches</h3><ul>';
		for(var f=0; f<x; f++) {
			list += '<li>'+ mem[f] + '<a href="#" onclick="deleteSample(\''+mem[f]+'\'); return false;"> [Remove]</a> </li>';
		}
		list += '</ul>';
		// Output List
		document.getElementById('samples').innerHTML=list;
	} else {
		// Refresh list
		list = '<h3>Chosen Leather Swatches</h3><ul>';
		for(var f=0; f<x; f++) {
			list += '<li>'+ mem[f] + '<a href="#" onclick="deleteSample(\''+mem[f]+'\'); return false;"> [Remove]</a> </li>';
		}
		list += '</ul>';
		
		list += '<p style="color:red;">The free sample service only allows a maximum choice of 3,If you would like to add a different sample please remove a sample from the above list first. if you require more please call +44(0)161 494 2100</p>';
		// Output List
		document.getElementById('samples').innerHTML=list;
	}
	
	// Update form fields
	var swatches = '';
	for(var foo=0; foo<mem.length; foo++) {
		if(foo != mem.length - 1) {
			swatches += mem[foo] + ', ';
		} else {
			swatches += mem[foo];
		}
	}
	
	document.getElementById('swatches').value=swatches;
}

function deleteSample(name) {
	// Remove item
	for(var foo=0; foo<mem.length; foo++) {
		if(mem[foo] == name) {
			mem.splice(foo, 1);	
			//alert(name + ' removed!');
		}
	}
	
	// Resort list
	var newArray = [];
	var ind = 0;
	for(var foo=0; foo<mem.length; foo++) {
		if(mem[foo] != undefined) {
			ind = newArray.length;
			newArray[ind] = mem[foo];
		}
	}
	
	var cnt = newArray.length;
	// Clear old memory
	mem.splice(0, mem.length);
	for(var foo=0; foo<cnt; foo++) {
		mem[foo] = newArray[foo];	
		//alert('mem['+foo+'] added ('+newArray[foo]+')');
	}
	if(x != 0) { x = x - 1; }
	
	// Refresh list
	list = '<h3>Chosen Leather Swatches</h3><ul>';
	for(var f=0; f<mem.length; f++) {
		list += '<li>'+ mem[f] + '<a href="#" onclick="deleteSample(\''+mem[f]+'\'); return false;"> [Remove]</a> </li>';
	}
	list += '</ul>';
	
	// Update form fields
	var swatches = '';
	for(var foo=0; foo<mem.length; foo++) {
		if(foo != mem.length - 1) {
			swatches += mem[foo] + ', ';
		} else {
			swatches += mem[foo];
		}
	}
	
	document.getElementById('swatches').value=swatches;
	
	// Output List
	document.getElementById('samples').innerHTML=list;
}
