var rWLCookie = 'researchWatchList';
var listeners = new Array();

function addListener(callback)
{
    listeners.push(callback);
}

function notifyListeners()
{
    for(var i = 0; i < listeners.length; i++)
    {
        listeners[i]();
    }
}

function addWatchListCookie(value)
{
    var ExpireDate = new Date ();
    ExpireDate.setTime(ExpireDate.getTime() + (365 * 24 * 3600 * 1000));

    document.cookie = rWLCookie + '=' + value + '; expires=' + ExpireDate.toGMTString() + '; path=/; domain=www.sharebuilder.com;';
    notifyListeners();
}


function getWatchList()
{
    if(document.cookie != null)
    {
        var aCookie = document.cookie.split('; ');
        for(var i = 0; i < aCookie.length; i++)
        {
            var aCrumb = aCookie[i].split("=");
            if (rWLCookie == aCrumb[0]) 
            {
                 if (aCrumb[1] != undefined)
                 {
                    return unescape(aCrumb[1]).split('|');   
                 }
                 else
                 {
                    return null;
                 }
            } 
        }
    }
    return null;
}

function addSymbolToWatchList(symbol)
{   
    
//    if(symbol.length == 0)
//        return;
//    
//    if(symbol.length > 7)
//        symbol = symbol.substr(0, 7);
//        
//    symbol = symbol.toUpperCase();

    var currentValues = getWatchList();
    if(currentValues != null)
    {
	    if(currentValues.length == 25)
	    {
		    return;
        }
        for(var i = 0; i < currentValues.length; i++)
        {
            if(currentValues[i] == symbol)
            {
                return;
            }
        }
    }
    else
    {
        currentValues = new Array();
    }
    currentValues.push(symbol);
    addWatchListCookie(currentValues.join('|'));
}

function removeSymbolFromWatchList(symbol)
{
//    symbol = symbol.replace(/^\s+|\s+$/, ''); 

//    if(symbol.length == 0)
//        return;
//    
//    if(symbol.length > 7)
//        symbol = symbol.substr(0, 7);
//    
//    symbol = symbol.toUpperCase();

    var currentValues = getWatchList();
    if(currentValues != null)
    {
        for(var i = 0; i < currentValues.length; i++)
        {
            if(currentValues[i] == symbol)
            {
                currentValues[i] = null;
            }
        }
        var tmp = new Array();
        for(var i = 0; i < currentValues.length; i++)
        {
            if(currentValues[i] != null)
                tmp.push(currentValues[i]);
        }
        currentValues = tmp;
        tmp = null;
        addWatchListCookie(currentValues.join('|'));
    }
    else
    {
        notifyListeners();       
    }
}