﻿// FoxMetrics Variable function
var fxm = function() {
    // private variables
    var token;
    var sessionId;
    var visitorId;
    var debugMode = false;
    var idCookieName = 'fxm1visitor';
    var sessionIdCookieName = 'fxmsession';

    // returns the host url that it should use
    //==========================================================================================
    function Host() {
        var protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
        //return protocol + 'localhost/foxmetrics.static/';
        return protocol + 'fxm1.foxmetrics.com/';
    }

    // An action that we want to record has fired. Record the action.
    // This is the heart of Foxmetrics, each event has one or more properties or params
    // Reserved names are {pageview, download, exit, funnel, event}
    //==========================================================================================
    function RecordAction(name, params) {
        if (debugMode == true) console.log('Action: ' + name);

        // begin preparing the url
        var url = Host() + 'fxm.ashx?a=' + name + '&tkn=' + token + '&sid=' + sessionId + '&vid=' + visitorId;
        var unixtime = parseInt(new Date().getTime().toString().substring(0, 10), 10);

        // handles page view, if the user doesn't specify anything then build it automatically
        if (name = 'pageview' && params == null) {
            params = {
                "href": window.location.pathname,
                "pt": document.title,
                "rf": document.referrer,
                "ltzo": new Date().getTimezoneOffset(),
                "time": unixtime,
                "scrw": screen.width,
                "scrh": screen.height,
                "lng": (navigator.browserLanguage || navigator.language || ""),
                "plt": (typeof (fxmPageStartTime) == 'undefined') ? "0" : (new Date().getTime() - fxmPageStartTime.getTime())
            };
        }

        // for each property in the param that the user passes
        for (prop in params) {
            url = url + '&' + prop + '=' + encodeURIComponent(params[prop]);
        }

        // make sure we have an href
        if (params.href == 'undefined' || params.href == null) url = url + '&href=' + encodeURIComponent(window.location.pathname);

        //
        RequestURL(url);
        WaitFor(300);

        //
        if (debugMode == true) console.log('URL: ' + url);
    }

    // Something was clicked, record the event by first trying to determine what was clicked
    //==========================================================================================
    function ClickEvent(e) {
        var el = (e.srcElement) ? e.srcElement : e.target;
        // for now we are only tracking hyperlinks, maybe we can track some other stuff in the future.
        if (el.tagName.toUpperCase() == 'A') {
            var dwn = el.pathname.match(/(?:doc|eps|jpg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)($|\&)/);
            if (dwn) {
                // is the user trying to download a file?
                RecordAction('download', { "dhref": el.href });
            } else {
                // otherwise, if the hostname is not ours then the user is exiting
                if ((!dwn || dwn == null) && el.hostname != location.host && el.hostname.indexOf('javascript') == -1 && el.hostname != '') {
                    RecordAction('exit', { "ehref": el.href });
                }
            }
        }
    }

    // adds an event
    //==========================================================================================
    function AddEvent(obj, evType, fn) {
        if (obj.addEventListener) {
            obj.addEventListener(evType, fn, false);
            return true;
        } else if (obj.attachEvent) {
            var r = obj.attachEvent("on" + evType, fn);
            return r;
        } else {
            return false;
        }
    }

    // removes and event
    //==========================================================================================
    function RemoveEvent(obj, evType, fn, useCapture) {
        if (obj.removeEventListener) {
            obj.removeEventListener(evType, fn, useCapture);
            return true;
        } else if (obj.detachEvent) {
            var r = obj.detachEvent("on" + evType, fn);
            return r;
        } else {
            //alert("Handler could not be removed");
        }
    }

    // Generates a random string
    //==========================================================================================
    function RandomString() {
        var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
        var string_length = 32;
        var randomstring = '';
        for (var i = 0; i < string_length; i++) {
            var rnum = Math.floor(Math.random() * chars.length);
            randomstring += chars.substring(rnum, rnum + 1);
        }
        return randomstring;
    }

    // save cookie to client computer
    //==========================================================================================
    function SaveCookie(name, value, days, minutes) {
        if (days) {
            var date = new Date();
            if (minutes == null) minutes = 0;

            if (minutes > 0) {
                date.setTime(date.getTime() + (60 * 1000 * minutes));
            } else {
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            }
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
        return value;
    }

    // create a cookie or get the value of a cookie
    //==========================================================================================
    function GetCookie(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;
    }

    // Gets a cookie and sets it if its null with the null params passed
    //==========================================================================================
    function GetSetCookie(cookieName, nullValue, nullExpiration) {
        var cookieValue = GetCookie(cookieName);
        if (!cookieValue) {
            SaveCookie(cookieName, nullValue, nullExpiration);
            return nullValue;
        }
        return cookieValue;
    }

    // A call to this method will automatically/seamlessly append a required js file to the head of this page.
    //==========================================================================================
    function RequestURL(url) {
        var script = document.createElement('script');
        script.type = "text/javascript";
        try {
            script.defer = "defer";
        } catch (e) { }
        script.src = url;
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    // Delay for a certain number of milliseconds (delay)
    //==========================================================================================
    function WaitFor(delay) {
        var date = new Date();
        var curDate = null;
        do { curDate = new Date(); }
        while (curDate - date < delay);
    }

    // public methods
    return {
        //==========================================================================================
        // Global values that are used accross the page
        //==========================================================================================
        Host: function() {
            // returns the host url that it should use
            return Host();
        },
        WebsiteId: function() {
            // returns the website id
            return websiteId;
        },
        Token: function() {
            // returns the website token that customer has assigned
            return token;
        },

        //==========================================================================================
        // Utilities portion of things
        //==========================================================================================
        insertScript: function(url) {
            // inject the following javascript url into the page
            RequestURL(url);
        },
        wait: function(ms) {
            // delays for the number of milliseconds specified
            WaitFor(ms);
        },
        getElement: function(id) {
            // get the element from a document and return
            return document.getElementById(id);
        },
        addEvent: function(obj, evType, fn) {
            return AddEvent(obj, evType, fn);
        },
        getCookie: function(name) {
            return GetCookie(name);
        },

        //==========================================================================================
        // Analytics portion of things
        //==========================================================================================
        Init: function(tk) {
            // the website token for this website, it is required or nothing works
            token = tk;
            if (!token) return;

            // this variable is used to track page load time
            // to really log in accurate page load times, the "pageview" log should not be called until
            // onload event
            startTime = new Date();

            // if this user has not been marked then do so. cookie that will last for 10 years
            // this is a permanent id that is unique to this pc/browser.
            visitorId = GetSetCookie(idCookieName, RandomString(), (365 * 10));

            // keep track of this session id, this cookie only last for this session
            // so that we can track sessions.
            sessionId = GetSetCookie(sessionIdCookieName, RandomString(), null);

            // starting listening to crap like mouse down events
            AddEvent(document, 'mousedown', ClickEvent);
        },

        //==========================================================================================
        // Logs an event and its properties
        //==========================================================================================
        Log: function(name, properties) {
            if (name != null && name != 'undefined') {
                RecordAction(name, properties);
            }
        }
    };
} ();
