OBJECT_SEPARATOR = ";";
FIELD_SEPARATOR = ",";
COOKIENAME= "carrello";
var arrayElementi;

function recuperaCarrelloDaCookie() {
	var cookieval= GetCookie(COOKIENAME);
	arrayElementi= stringToArray(cookieval, OBJECT_SEPARATOR);
}

function eliminaCarrello(path){
	SetCookie (COOKIENAME,"", new Date(2030,1,1),path);
}

function cercaElementoDelCarrello(campiChiave){
	recuperaCarrelloDaCookie();
	for(var i=0; i<arrayElementi.length; i++){
		if(confrontaChiavi(arrayElementi[i], campiChiave)== true) {
			return i;
		}
	}
	return '-1';
}

function stringToArray(value, OBJECT_SEPARATOR){
	if(value && value.length>0) {
		return value.split(OBJECT_SEPARATOR);
	} 
	return new Array();
}

function confrontaChiavi(elemento, campiChiave){
	var campi= elemento.split(FIELD_SEPARATOR);
	var j;
	for(j=0; j<campiChiave.length; j++){
		if (campi[j]!=campiChiave[j]){		  	
			return false;
		}
	}
	return true;
}

function getElementoDelCarrello(indice){
	recuperaCarrelloDaCookie();
	return arrayElementi[indice];
}

function setElementoDelCarrello(indice, arrayValori, path){
	recuperaCarrelloDaCookie();
	arrayElementi[indice] = arrayValori.join(FIELD_SEPARATOR);
	var newcookieval= arrayElementi.join(OBJECT_SEPARATOR);
	SetCookie (COOKIENAME,newcookieval, new Date(2030,1,1),path);
}

function aggiungoElementoDelCarrello(arrayValori, path){
	recuperaCarrelloDaCookie();
	valore = arrayValori.join(FIELD_SEPARATOR);
	var nuovoValore= arrayElementi.concat(valore);
	var newcookieval= nuovoValore.join(OBJECT_SEPARATOR);
	SetCookie(COOKIENAME, newcookieval, new Date(2030,1,1),path);
}

function cancellaElementoDelCarrello(indiceElemento, path){
	recuperaCarrelloDaCookie();
	if (indiceElemento!='-1'){
		var nuovoValore = new Array();
		for (var i=0; i<arrayElementi.length; i++){
	     if(i != indiceElemento) {
		 	nuovoValore.push(arrayElementi[i]); 
	     }
		}
		var newcookieval= nuovoValore.join(OBJECT_SEPARATOR);
		SetCookie (COOKIENAME,newcookieval, new Date(2030,1,1),path);
	}
}
