var COOKIE_NAME = "favorite_games";
var MONTHS_EXPIRED = 99;
var SEPARATOR = "|";

function getCookie(name) {
	var	cookies = document.cookie.split("; ");

	for (var i = 0; i < cookies.length; i++) {
		var	cookie = cookies[i].split("=");

		if (cookie[0] == name)
			return cookie[1];
	}

	return null;
}

function setCookie(name, value, expires, path, domain, secure) {
//	var cookie = name + "=" + escape(value);
	var cookie = name + "=" + value;

	if (expires)
		cookie+="; expires="+expires.toGMTString();

	if (path)
		cookie+="; path="+path;

	if (domain)
		cookie+="; domain="+domain;

	if (secure)
		cookie+="; secure";

	document.cookie = cookie;
}

function deleteCookie(name) {
	setCookie(name,'null',new Date(0),null,null,true);
}

function setFavoritesCookie(value){
	var curDate = new Date();
	var expires = new Date((curDate.getFullYear() + Math.floor((curDate.getMonth() + MONTHS_EXPIRED) / 12)), (curDate.getMonth() + MONTHS_EXPIRED) % 12, curDate.getDate());

	setCookie(COOKIE_NAME, value, expires, "/", document.location.host)
}

function addGameToFavorites(gameId){
	if(gameId == null)
		return false;

	gameId = gameId.toString();

	if(!gameId.match(/^\d+$/))
		return false;

	var cookie = getCookie(COOKIE_NAME);
	
	if(cookie == null)
		cookie = SEPARATOR;

	if(cookie.indexOf(SEPARATOR + gameId + SEPARATOR) == -1)
		cookie = SEPARATOR + gameId + cookie;
	else
		return false;

	setFavoritesCookie(cookie);

	return true;
}

function findParentNode(nodeName, el){
    if(nodeName == null || el == null)
        return;

    if (el.parentNode != null && el.parentNode.nodeType == 1 && el.parentNode.tagName.toUpperCase() != nodeName.toUpperCase())
        return findParentNode(nodeName, el.parentNode);

    return el.parentNode;
}

function removeGameFromFavorites(gameId, el){
	if(gameId == null)
		return false;

	gameId = gameId.toString();

	if(!gameId.match(/^\d+$/))
		return false;

	var cookie = getCookie(COOKIE_NAME);

	if(cookie == null)
		cookie = SEPARATOR;

	if(cookie.indexOf(SEPARATOR + gameId + SEPARATOR) != -1)
		cookie = cookie.replace(SEPARATOR + gameId + SEPARATOR, SEPARATOR);
	else
		return false;

	setFavoritesCookie(cookie);

	//var li = findParentNode("LI", el);
	//li.parentNode.removeChild(li);
	
	var li = findParentNode("TR", el);
	li.parentNode.removeChild(li);

	return true;


}

