//
// Event tracking namespace, contains methods to attach
// event handlers to clicks and other things we want to track
//

WV.Tracker = function (props) {
    this.debug  = (props.debug) ? true : false;
    this.events = (props.events) ? props.events : [];
    
    // XXX - KLN - Pass these values in as properties!
    this.partnerCode = (props.partnerCode) ? props.partnerCode : 'undefined';
    this.source      = (props.source)      ? props.source      : 'undefined';
    this.instanceId  = (props.instanceId)  ? props.instanceId  : 'undefined';
    this.campaignId  = (props.campaignId)  ? props.campaignId  : 'undefined';
    this.providerId  = (props.providerId)  ? props.providerId  : 'undefined';
    this.trackingHost  = (props.trackingHost)  ? props.trackingHost  : 'undefined';

    // Declare tracking variables
    this.sessionId        = 'undefined';
    this.userAgent        = 'undefined';
    this.ipAddress        = 'undefined';
    this.referer          = 'undefined';
    this.requestUrl       = 'undefined';
    this.loadTime         = 'undefined';
    this.startTime        = 'undefined';
    this.incomingKeywords = 'undefined';

    this.init();
};
 
WV.Tracker.prototype = {
    init : function () {
        this.startSession();
        this.registerEvents();
    },
    // Capture the event and send it to the handler to construct the JSON
    fireEvent : function (data) {
        this.logMessage("fireEvent");
        this.logMessage(data);

        if (this.debug) {
            this.logMessage(data);
        } else {
            if (data.data == undefined || data.data === undefined) {
                data.data = '{}';
            }
            var message = { 
                wvLogMsg : {
                    e: {
                        name: data.event_name,
                        details: data.data
                    },
                    p: this.partnerCode,
                    r: this.source,
                    d: (new Date()).getTime()
             }  
            };
            
            this.logMessage(message);
            this.sendMessage(this.trackingHost + '/api/log', message);
        }
    },
    // Send the message that is passed in
    sendMessage : function (url, msg) {
        var json = $.toJSON(msg);
        var img = new Image(1,1);
        img.onLoad = function () { };
        img.src = url + "?json=" + encodeURIComponent(json);
    },
    // Calculate the page load time
    getLoadTime : function () {
        this.loadTime = (new Date()).getTime() - this.startTime;
    },
    // Log the session information, set cookie
    startSession : function () {
        // Construct the message to send to session service
        var message = {
            instance: this.instanceId,
            campaign: this.campaignId,
            url     : document.location.href,
            referer : document.referrer,
            provider: this.providerId
        };
        
        // Get this from the document
        this.requestUrl = document.URL;
        
        // Send the message to get more session data
        this.sendMessage(this.trackingHost + '/api/session', message);
    },
    // Log the start of the page load
    startPageLoad : function () {
        this.logMessage("startPageLoad");

        this.startTime = (new Date()).getTime();
    },
    // Handle page load event
    postPageLoad : function () {
        this.logMessage("postPageLoad");

        var message = {
            event_name : 'page_load',
            data : {
                load_time: this.loadTime
            }
        };
        
        this.sendMessage(message);
    },

    logMessage : function (msg) {
        if (window.console && window.console.log) {
          window.console.log(msg);
        } else {
          // alert( msg);
        }
    },    
    
    // Register event listeners
    registerEvents : function () {
        this.logMessage("registerEvents");

        var obj = this;
        for (var i = 0; i < this.events.length; i++) {
            $(document).bind(this.events[i], function (e, args) {
                obj.fireEvent.apply(obj, [args]);
            });
        }
    }
};

