var cookieDomain = ".bluvu.tv";

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function createCookie(name,value,years) {
    if (years) {
        var date = new Date();
        date.setUTCFullYear(date.getUTCFullYear() + years);
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    
    var fullCookie = name+"="+value+expires+"; path=/";
    if (cookieDomain)
        fullCookie += "; domain=" + cookieDomain;
    document.cookie = fullCookie;
}

// Track the source, even if one has already been stored in a cookie
var sourceParameterPosition = document.location.search.indexOf("source=");
if (sourceParameterPosition > -1)
{
    var source = document.location.search.substring(sourceParameterPosition + "source=".length);
    
    // Separate the source parameter from any others
    var parameterSplitter = source.indexOf("&");
    if (parameterSplitter > 0)
        source = source.substring(0, parameterSplitter);

    // Now trim any cruft from the end
    if (source.charAt(source.length - 1) == '/')
        source = source.slice(0, source.length - 1);            
        
    createCookie("source", source, 10); // affiliates last 10 years unless trumped
}
