function ko_getCookie(cookie_name) {	
	if (document.cookie){
		index = document.cookie.indexOf(cookie_name);
		if (index != -1) {
			namestart = (document.cookie.indexOf("=", index) + 1);
			nameend = document.cookie.indexOf("koEnd", index);
			
			if (nameend == -1) {
				nameend = 0;
			}
			
			cookieContents = document.cookie.substring(namestart, nameend);
			return unescape(cookieContents);
		}
	}else{
		return null;
	}
}

function ko_setCookie(cookie_name, value, expires) {	
	// instructions: 'mycookie=valueOfCookie;expires=DateHere;path=/'
	document.cookie = cookie_name + "=" + escape(value) + "koEnd; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString()); 
	//alert("set");
} 
	
function ko_deleteCookie(cookie_name) {
	if (document.cookie != document.cookie) {
		index = document.cookie.indexOf(cookie_name);
	} else {
		index = -1;
	}
	if (index == -1) {
		document.cookie=cookie_name+"=GONEcbEndCookie; path=/; expires=Monday, 19-Aug-1996 05:00:00 GMT";
	}
	document.location.href = document.location.href;
	//to reload without queryString parameters, use the line below instead
	//document.location = document.location.href.substring(0,document.location.href.indexOf("?"));
}

function ko_removeId(id, cookie_name){
	var exp = new Date();	    //set new date object	
	exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));     //set it 30 days ahead 
	
	var currentCookie = ko_getCookie(cookie_name);
	
	if(currentCookie != null){
		//check for dups
		var allIds = currentCookie.split(",");
		alert(allIds);
		
		var newIds = "";
		for(i=0; i< allIds.length; i++){
			if(allIds[i] != id){ 
				if(newIds == ""){
					newIds = allIds[i];
					alert("first one: "+allIds[i]);
				}else{
					newIds = newIds +","+ allIds[i];
					alert(allIds[i]);
				}
			}
		}
		alert(newIds);
		
		if(newIds == ""){
			alert("deleting");
			ko_deleteCookie(cookie_name);
		}else{
			ko_setCookie(cookie_name, newIds, exp);
		}
	}
}
	
function ko_saveToPortfolio(id, cookie_name){
	var exp = new Date();	    //set new date object	
	exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));     //set it 30 days ahead 
	
	var currentCookie = ko_getCookie(cookie_name);
	
	if(currentCookie == null){
		//alert("first time");
		ko_setCookie(cookie_name, id, exp);
	}else{
		alert("The property has been added to your portfolio");
		//check for dups
		var allIds = currentCookie.split(",");
		for(i=0; i< allIds.length; i++){
			if(allIds[i] == id){ 
				//alert("already there");
				return null;
			}
		}
		
		ko_setCookie(cookie_name, currentCookie+","+id, exp);
	}
}
