var roivista_number, roivista_actual, roivista_image, roivista_image2, roivista_start = new Date();

function roivista_init(script_id, campaign_id)
{
    // check if a session cookie was set, if yes, we have a valid replacement result
    // from an earlier ROI Vista request and just repeat that throughout the site
    // of not we need to make a reauest first, see below, which will set a session cookie
    var session_cookie = getCookie("roivista_session_"+script_id.toLowerCase());
    if (session_cookie) {
        var cookie_replacement = session_cookie.split("|");
        roivista_number = cookie_replacement[0];
        roivista_actual = cookie_replacement[1];
        roivista_image  = cookie_replacement[2];
        roivista_image2 = cookie_replacement[3];
        return;
    }

    var roivista_cookie = getCookie("roivista_"+script_id.toLowerCase()),
              cid_start = window.location.href.indexOf("roiv_cid="),
               roiv_cid = "",
                      d = new Date();

    // extract campaign id if any
    if (cid_start >= 0) {
        var cid_end = window.location.href.indexOf("&", cid_start);
        if (cid_end < 0) {
            roiv_cid = window.location.href.substring(cid_start+9);
        }
        else {
            roiv_cid = window.location.href.substring(cid_start+9, cid_end);
        }
    }

    document.write(unescape("%3Cscript type='text/javascript' src='http://roivista.com/js/roivista.php?")
                  +"id="+script_id
                  +(campaign_id ? "&init_campaign="+campaign_id : "")
                  +"&roiv_cid="+roiv_cid
                  +"&roiv_ref="+escape(document.referrer)
                  +(roivista_cookie ? "&roiv_cookie="+escape(roivista_cookie) : "")
                  +"&time="+d.getTime()
                  +unescape("' %3E%3C/script%3E"));
}

function roiv_replacement(replacement_type, fallback)
{
    var replacement = roivista_number;

    if (replacement_type == 1) {
        replacement = "<img src='"+roivista_image+"' alt='"+roivista_number+"' title='"+roivista_number+"'>";
    }
    else if (replacement_type == 2) {
        replacement = "<img src='"+roivista_image2+"' alt='"+roivista_number+"' title='"+roivista_number+"'>";
    }

    document.write(typeof(roivista_number) == "string" ? replacement : fallback);
}

function getCookie(name) {

    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);

    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) {
            return null;
        }
    }
    else {
        begin += 2;
    }

    var end = document.cookie.indexOf(";", begin);

    if (end == -1) {
        end = dc.length;
    }

    return unescape(dc.substring(begin + prefix.length, end));
}
