
//-- BLVD Status tracker
//-- Copyright 2010 BLVD Status, All Rights Reserved.

//BLVD tracking object
function BLVD() {
	
    //params
    this.host = 'http://stats.blvdstatus.com';
    this.tid = 'BS-3cefe0bc-6';
    
	//set cookie
    var blvdCookie = this._Get_Cookie('blvdS');
    if(blvdCookie) {
        this._Set_Cookie('blvdS', blvdCookie, 30,'/');
    } else {
        blvdCookie = 's3ce4c52c5099793e4.05282242';
        this._Set_Cookie('blvdS', blvdCookie, 30,'/');
    }
}

/*
 * Similar to the PHP function urlencode
 */
BLVD.prototype._urlencode = function (str) {
    str = (str+'').toString();
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

/*
 * Utility function to test if another object is actually a function.
 */
BLVD.prototype._isFunction = function (object) {
    return (typeof(object) != 'undefined' && typeof(object) == 'function');

}

BLVD.prototype._isDefined = function (object) {
    return (typeof(object) != 'undefined');
}

BLVD.prototype._Set_Cookie = function ( name, value, expires, path, domain, secure )
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );

    if ( expires )
    {
        //expires = expires * 1000 * 60 * 60 * 24;
        expires = expires * 60 * 1000;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
        ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
        ( ( path ) ? ";path=" + path : "" ) +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ( ( secure ) ? ";secure" : "" );
    
    this.blvdCookie = escape(value);
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
BLVD.prototype._Get_Cookie = function ( check_name ) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );

        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}


/*
 * The BLVD_afterLoad function, which is responsible for triggering the
 * dynamic JavaScript pull.
 */
BLVD.prototype._afterLoad = function () {
    //	We call all the existing onload functions _first_,
    //	in the hope that if they modify the document we
    //	will catch the changes.
    if (BLVD._isFunction('test')) {
        this.chain_onload();
    }
    
    // Send the data as a GIF Request
    BLVD._trackPage();
}

/***
 * Outgoing link tracking
 */
BLVD.prototype._logOutgoingLink = function (node) {
    var i = new Image(1,1);
    
    i.src =
        this.host + "/stats/track" + 
            "?url=" + this._urlencode(node.href) +
            "&blvdSessionId=" + this.blvdCookie +
            "&tid=" +  this.tid
    ;
    
    i.onload=function() { 
        i.onload = null;
        BLVD._blvdVoid(); 
    }
}

BLVD.prototype._blvdVoid = function () { 
    return false; 
}

BLVD.prototype._logOutgoingForm = function (node) {
    var i = new Image(1,1);
    var formSubmitURL;
    
    if (node.attributes && node.attributes['action']) {
        formSubmitURL = node.attributes['action'].value;
    } else if (node.getAttribute) {
        formSubmitURL = "" + node.getAttribute('action');
    } else {
        formSubmitURL = '';
    }
    
    i.src =
        this.host + "/stats/track" + 
            "?url=" + this._urlencode(node.href) +
            "&blvdSessionId=" + this.blvdCookie +
            "&tid=" +  this.tid
    ;

    i.onload=function() { BLVD._blvdVoid(); }
}

BLVD.prototype._getDomain = function (thestring) {
    //simple function that matches the beginning of a URL
    //in a string and then returns the domain.
    var urlpattern = new RegExp("(http|ftp|https)://(.*?)/.*$");
    var parsedurl = thestring.match(urlpattern);
    return parsedurl[2];
}

BLVD.prototype._chainOnClick = function (node) {
    if (this._isDefined(node.addEventListener)) {
        node.addEventListener(
            'click',
            function() {
                BLVD._logOutgoingLink(node);
            },
            false
        );
    } else if (this._isDefined(node.attachEvent)) {
        node.attachEvent(
            'onclick',
            function() {
                BLVD._logOutgoingLink(node);
            }
        );
    } else {
        var currentOnClick;
        
        currentOnClick = node.onclick;
        
        node.onclick = function() {
            //	Log the click
            BLVD._logOutgoingLink(node);
            
            //	Execute any existing on click function
            if (this._isFunction(currentOnClick)) {
                return currentOnClick();
            }
        }
    }
}

BLVD.prototype._chainOnSubmit = function (node) {
    if (this._isDefined(node.addEventListener)) {
        node.addEventListener(
            'submit',
            function() {
                this._logOutgoingForm(node);
            },
            false
        );
    } else if (this._isDefined(node.attachEvent)) {
        node.attachEvent(
            'onsubmit',
            function() {
                this._logOutgoingForm(node);
            }
        );
    } else {
        var currentOnSubmit;
        
        currentOnSubmit = node.onsubmit;
        
        node.onsubmit = function() {
            //	Log the click
            this._logOutgoingForm(node);
            
            //	Execute any existing on click function
            if (this._isFunction(currentOnSubmit)) {
                return currentOnSubmit();
            }
        }
    }
}

BLVD.prototype._replaceLinks = function (baseDocument) {
    var domain = this._getDomain(document.location.href);
   
    //	Find every link:
    //	- A tags
    var nodes = baseDocument.getElementsByTagName('a');
    
    for(var index = 0; index < nodes.length; index++) {
        //make sure its and outgoing link by seeing if the domain is in the href
        if(this._isDefined(nodes[index].href)) {
            if(nodes[index].href.indexOf(domain) < 0) {
                this._chainOnClick(nodes[index]);
            }
        }
    }
 
    //	- RSS alternate link tags
    var node;
    var typeValue;
    var nodes;
    nodes = document.getElementsByTagName('link');
    
    for(var index = 0; index < nodes.length; index++) {
        node = nodes[index];
        typeValue = node.getAttribute('type');
        
        if (typeValue == 'application/rss+xml') {
        }
    }
}

/**
 * Actually track the hit
 */
BLVD.prototype._trackPage = function (replace) {
   
    //overwrite http_referrer
    var http_referrer = '';
    if(replace) {
    	var http_referrer = "&http_referrer=" + replace;
    }
    
    var blvdtimg = new Image(1,1);
    blvdtimg.src = 

        this.host + "/stats/request" +
        "?blvdSessionId=" + this.blvdCookie +
        "&referrer=" + this._urlencode(document.referrer) +
        "&title=" + this._urlencode(document.title) +
        "&screenWidth=" + screen.width +
        "&screenHeight=" + screen.height +
        "&screenDepth=" + screen.colorDepth +
        "&tid=" + this.tid +
        http_referrer;
    
    this._replaceLinks(document);}

/*
 * Chain the BLVD _afterLoad function into the OnLoad event handler.
 * We store the current OnLoad handler first so we can call it
 * from our own function.
 */

BLVD = new BLVD;
if (BLVD._isFunction(window.addEventListener)) {
    window.addEventListener('load', BLVD._afterLoad, false);
} else if (BLVD._isFunction(window.attachEvent)) {
    window.attachEvent('load', BLVD._afterLoad);
} else {
    BLVD.chain_onload = window.onload;
    window.onload = BLVD._afterLoad;
}

