var _domain = ".cnn.com";
var _expiration = new Date("December 31, 2048 23:59:59");

var Clean_Cookie_Value = function(string) {
	return string
		.replace( /[\n\r]/g, '' )
		.replace( /javascript:/gi, '' )
		.replace( /<\/?script\s*([^>]+)?>/gi, '' )
		.replace( /eval\s*\(.+?\)/g, '' )
		.replace( /[#&()\"'<>]/g, '' )
		.replace( /[^A-Za-z0-9+._$]/g, '' )
		.replace( /\+\++/g, '+' );
};

function Get_Cookie(name) {
	var start = document.cookie.indexOf(name+"=");
	var len = start+name.length+1;
	if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
	if (start == -1) return null;
	var end = document.cookie.indexOf(";",len);
	if (end == -1) end = document.cookie.length;
	return Clean_Cookie_Value(decodeURIComponent(document.cookie.substring(len,end)));
}

function Set_Cookie(name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + encodeURIComponent(Clean_Cookie_Value(value)) +
		( (expires) ? ";expires=" + expires.toGMTString() : "") +
		( (path) ? ";path=" + path : "") + 
		( (domain) ? ";domain=" + domain : "") +
		( (secure) ? ";secure" : "");
}

function getParamVal(name){
	s1 = location.search;
	reg = new RegExp('.*'+name+'=([^&]*).*');
	s2 = s1.replace(reg,'$1');
	if(s1.length == s2.length) { return ""; }
	else { return s2; }
}

function manipulateCookies() {
	var symb = getParamVal('symb');
	var osymb = getParamVal('osymb');
	if(symb == "" && osymb != "") {
		symb = osymb;
	}
	var cookiecontent = '';
	symb = Clean_Cookie_Value(decodeURIComponent(symb.toUpperCase()));
	if(symb != "" && symb.indexOf(",") < 0) { // single ticker symbol
		var c = Get_Cookie('last5stocks');
		if(c != null) { // the cookie is present
			var symb_array=c.split("\+");
			for(var i=0; i<symb_array.length-1; i++)
			{
				if (symb_array[i] != symb)
				cookiecontent += symb_array[i] + '+';
			}
			cookiecontent += symb + '+'; // add the symbol to the cookie
			var matches = cookiecontent.match(/\+/g);
			var count = matches.length;
			if(count > 10) { // there are more than 10 symbols in the cookie
				cookiecontent = cookiecontent.substring(cookiecontent.indexOf('+') + 1); // take the oldest symbol out
			}
			Set_Cookie('last5stocks', cookiecontent, _expiration, '/', _domain, null); // write the cookie
		} else {
			c = symb + "+"; // create a new cookie with one symbol
			Set_Cookie("last5stocks", c, _expiration, "/", _domain , null);
		}
	}
}
