// JavaScript Document
function resetCookie(name){
	var date = new Date();
	date.setTime(date.getTime()+((-1)*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	document.cookie = name + '=' + expires + '; path=/';
}


function storeCookie(theElement){
	var thecookie = readCookie("CGROUPID");
	box = theElement.checked;
	count = (box ? 1 : 0);
	if (count > 0){
		if (!thecookie) {
			document.cookie = "CGROUPID"+"="+theElement.value+"; path=/";
		} else {
			if(listLength(thecookie,'_') < 5){
				document.cookie = "CGROUPID="+thecookie+"_"+theElement.value+"; path=/";
			} else {
				alert("Only 5 items are comparable at a time. You can uncheck items or click compare to remove items from the compare page");
				theElement.checked = false;
				return false;
			}
		}
	} else {
		var newCookie = removeID(thecookie, "_"+theElement.value);
		newCookie = removeID(newCookie,theElement.value);
		document.cookie = "CGROUPID"+"="+newCookie+"; path=/";
	}
	
}

function removeID(myString, pattern){
	var newString = myString.replace(pattern,"");
	return(newString);
}

function readCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0){ return ''; } 
	} else {
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1) end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}



function setCompareCheckboxes(){
	var thecookie = readCookie("CGROUPID");
	checkElements(thecookie,"_");
}

function foundInList(matchId,list,sep){
	var theList = list.split(sep);
	for(var x=0;x <theList.length;x++){
		var theItem = theList[x];
		if (theItem == matchId) {
			return true;
		}
	}
	return false;
}

function listLength(list,sep){
	var theList = list.split(sep);
	var counter = 0;
	for(var i = 0; i<theList.length; i++){
		if(theList[i] != ''){
			counter++;
		}
	}
	return counter;
}

function checkElements(theElements, sep) {
    var formElements = document.getElementsByName("cgroupID[]");
    for (var z = 0; z < formElements.length; z++) {
        var theItem = formElements[z];
		
        if (theItem) {
            if (theItem.type == "checkbox" &&
                foundInList(theItem.id, theElements, sep)) {
                theItem.checked = true;
            }
        }
    }
}


