﻿recordIDXBrokerStat();

function recordIDXBrokerStat() {
    var leadid = findLeadID();
    var clientid = findClientID();

    insertIDXBrokerStatImage(leadid, clientid);
}

function findLeadID() {
    var leadid = '';

    leadid = parseCookieValue(getCookie("IDX-userData"), "leadID");

    if (leadid == '') {
        leadid = getCookie("RPS-userTrack");
    }

    if (leadid == '') {
        leadid = getQueryValue('id');

        if (leadid != '')
            createCookie('RPS-userTrack', leadid, 60);
    }

    return leadid;
}

function findClientID() {
    var clientid = '';

    clientid = parseCookieValue(getCookie("IDX-userData"), "leadClient");

    if (clientid == '') {
        clientid = getUrlSegment(2);
    }

    return clientid;
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function parseCookieValue(cookie, key) {
    var segments = cookie.split(';');
    for (var i = 0; i < segments.length; i++) {
        part = segments[i];

        if (isCorrectKey(part, key)) {
            return getCookieValue(segments[i + 1]);
            break;
        }
    }

    return '';
}

function getQueryValue(key) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == key)
            return unescape(pair[1]);
    }
    return '';
}

function getUrlSegment(index) {
    var segments = window.location.pathname.split('/');
    try {
        return segments[index];
    }
    catch (e) { return ''; }
}

function isCorrectKey(part, key) {
    var subparts = part.split(':');
    var subpartkey = subparts[subparts.length - 1].replace(/"/gi, '');
    return (key == subpartkey);
}

function getCookieValue(segment) {
    var parts = segment.split(':');
    return parts[parts.length - 1].replace(/"/gi, '');
}

function insertIDXBrokerStatImage(leadid, clientid) {
    if (leadid != '' && clientid != '') {
        var img = '<img src="http://ws.realproserver.com/stats/' + clientid + '/' + leadid + '/idxb.gif"' + ' alt="IDX Broker" title="" />';
        document.write(img);
    }
}
