﻿//// Simple JavaScript Templating
//// John Resig - http://ejohn.org/ - MIT Licensed
//// http://ejohn.org/blog/javascript-micro-templating/#postcomment
//(function() {
//    var cache = {};

//    this.tmpl = function tmpl(str, data) {
//        // Figure out if we're getting a template, or if we need to
//        // load the template - and be sure to cache the result.
//        var fn = !/\W/.test(str) ?
//      cache[str] = cache[str] ||
//        tmpl(document.getElementById(str).innerHTML) :

//        // Generate a reusable function that will serve as a template
//        // generator (and which will be cached).
//      new Function("obj",
//        "var p=[],print=function(){p.push.apply(p,arguments);};" +

//        // Introduce the data as local variables using with(){}
//        "with(obj){p.push('" +

//        // Convert the template into pure JavaScript
//        str
//          .replace(/[\r\t\n]/g, " ")
//          .split("<%").join("\t")
//          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
//          .replace(/\t=(.*?)%>/g, "',$1,'")
//          .split("\t").join("');")
//          .split("%>").join("p.push('")
//          .split("\r").join("\\'")
//      + "');}return p.join('');");

//        // Provide some basic currying to the user
//        return data ? fn(data) : fn;
//    };
//})();

// unblock when ajax activity stops
//$(document).ajaxStop($.unblockUI);
$(document).ajaxStop(function() { $('div.column_1').unblock(); });

// start doing stuff once the dom is ready
$(document).ready(function() {
    var options = null;

    // Corner all divs if any is found
    //=========================================================
    if ($('div.corner').length != 0)
        $('div.corner').corner();

    if ($('td.count').length != 0)
        $('td.count').corner();

    //    if ($('div.buttons').length > 0) {
    //        $('div.buttons div.buttonleft').corner(); //('TL BL 3px');
    //        $('div.buttons div.buttonright').corner(); //('TR BR 3px');
    //    }

    /*var topNav = $('div#nav li');
    if (topNav.length != 0)
    topNav.corner('3px');*/

    var spans = $('span.corner, a.corner');
    if (spans.length != 0)
        spans.corner('TL TR 3px');

    /* Adding a colortip to any tag with a title attribute: */
    //$('[title]').colorTip({ color: 'yellow' });

    // Setup all date range selectors on this page
    //=========================================================
    //    $('div.calendar span#placeholder').DatePicker({
    //        flat: true,
    //        format: 'd B, Y',
    //        date: ['6/18/2010', '6/18/2010'],
    //        calendars: 3,
    //        mode: 'range',
    //        starts: 1,
    //        onChange: function(formated) {
    //            //$('#widgetField span').get(0).innerHTML = formated.join(' &divide; ');
    //        }
    //    });
    //    var state = false;
    //    $('div.calendar > a').click(function() {
    //    $('div.calendar span#placeholder').stop().animate({ height: (state ? 0 : $('div.calendar span#placeholder div.datepicker').get(0).offsetHeight) }, 500);
    //        state = !state;
    //        return false;
    //    });
    //$('div.calendar div.datepicker').css('position', 'absolute');



    //    $('div.calendar span.picker').each(function() {
    //        var obj = $(this);
    //        obj.DatePicker({
    //            format: 'm/d/Y',
    //            date: '6/18/2010',
    //            current: '6/18/2010',
    //            starts: 1,
    //            position: 'bottom',
    //            onBeforeShow: function() {
    //                $(this).DatePickerSetDate($(this).val(), true);
    //            },
    //            onChange: function(formated, dates) {
    //                obj.val(formated);
    //                obj.DatePickerHide();
    //            }
    //        });
    //    });


    //    $('#datepickerrange').DatePicker({
    //        flat: true,
    //        format: 'd B, Y',
    //        date: [new Date(now3), new Date(now4)],
    //        calendars: 3,
    //        mode: 'range',
    //        starts: 1,
    //        onChange: function(formated) {
    //            $('#widgetField span').get(0).innerHTML = formated.join(' &divide; ');
    //        }
    //    });

    //    if ('span#dateDisplay') {
    //        var now = new Date();
    //        now.addDays(-7);

    //        var startDate = now;
    //        var endDate = new Date();

    //        if ($.cookie('enddate') != undefined) endDate = $.cookie('enddate');
    //        if ($.cookie('startdate') != undefined) startDate = $.cookie('startdate');

    //        $('span#dateDisplay').html(new Date(startDate).format('M d') + ' - ' + new Date(endDate).format('M d'));
    //    }

    // groupby
    //=========================================================
    if ($('span#groupby')) {
        $('span#groupby a').click(function() {
            global.SetGroupBy($(this).attr('rel'));
            //$.cookie(groupByCookieName, $(this).attr('rel'), { path: '/' });
            window.location = window.location;
        });

        //var defaultGroupBy = global.GetGroupBy();
        //var defaultGroupBy = 'DD';
        //if ($.cookie(groupByCookieName) != undefined) defaultGroupBy = $.cookie(groupByCookieName);
        //if ($.cookie(groupByCookieName) == undefined) $.cookie(groupByCookieName, defaultGroupBy, { path: '/' });
        $('span#groupby a').each(function() {
            if ($(this).attr('rel') == global.GetGroupBy()) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }
        });
    }

    // websites
    //=========================================================
    if ($('a#urlsddl').length != 0) {
        options = { minWidth: 220, copyClassAttr: false, offsetTop: 5, offsetLeft: -10,
            onClick: function(e) {
                dashboard.SetSelectedHost($(e.target).attr('rel'));
                dashboard.SetDirtyCookieFlag();
                window.location = window.location;
            }
        };
        $('a#urlsddl').menu(options, '#urlMenulist');
    }

    // dates
    //=========================================================
    /*
    if ($('a#datesddl').length != 0) {
    options = { minWidth: 120, copyClassAttr: false, offsetTop: 10, offsetLeft: -100,
    onClick: function(e) {
    // close all open menus
    $.Menu.closeAll();

                // handle the value received
    var args = $(e.target).attr('rel');
    var now = new Date();
    var endDate = new Date();

                // Handle days
    if ($.string(args).endsWith('d')) {
    now.addDays(parseInt(args.toString().replace('d', '')));
    }
    // Handle months
    else if ($.string(args).endsWith('m')) {
    now.addMonths(parseInt(args.toString().replace('m', '')));
    }
    // Default
    else { now.addDays(-7); }

                // Save to cookie
    $.cookie('startdate', new Date(now).format('m/d/Y'), { path: '/' });
    $.cookie('enddate', new Date(endDate).format('m/d/Y'), { path: '/' });

                // Update the display
    $('#dateDisplay').html(new Date(now).format('M d') + ' - ' + new Date(endDate).format('M d'));
    window.location = window.location;
    }
    };
    $('a#datesddl').menu(options, '#dateMenulist');
    }*/

    // Tooltip using Qtip
    //===============================================================
    /*
    $('ul#analytics-summary li p img').each(function() {
    $(this).qtip({
    content: $(this).attr('alt'), style: 'green'
    });
    });
    */
    // Create the modal backdrop on document load so all modal tooltips can use it
    //===============================================================
    /*
    $('<div id="qtip-blanket">')
    .css({
    position: 'absolute',
    top: $(document).scrollTop(), // Use document scrollTop so it's on-screen even if the window is scrolled
    left: 0,
    height: $(document).height(), // Span the full document height...
    width: '100%', // ...and full width

          opacity: 0.7, // Make it slightly transparent
    backgroundColor: 'black', // dark, green, light, red, blue
    zIndex: 5000  // Make sure the zIndex is below 6000 to keep it below tooltips!
    })
    .appendTo(document.body) // Append to the document body
    .hide(); // Hide it initially
    */
    // Create the modal backdrop on document load so all modal tooltips can use it
    //===============================================================
    /*
    $('a[rel="scriptmodal"]').each(function(e) {
    $(this).qtip({
    content: {
    title: { text: 'Website Script', button: 'Close' },
    text: '<textarea readonly="readonly" rows="8" style="width:490px;border:0">' + ShowScriptCode($(this).attr('title')) + '</textarea>'
    },
    position: {
    target: $(document.body), // Position it via the document body...
    corner: 'center' // ...at the center of the viewport
    },
    show: {
    when: 'click', // Show it on click
    solo: true // And hide all other tooltips
    },
    hide: false,
    style: {
    width: { min: 500 },
    padding: '5px',
    border: { width: 9, radius: 9, color: '#666666' },
    name: 'light'
    },
    api: {
    beforeShow: function() {
    // Fade in the modal "blanket" using the defined show speed
    $('#qtip-blanket').fadeIn(this.options.show.effect.length);
    },
    beforeHide: function() {
    // Fade out the modal "blanket" using the defined hide speed
    $('#qtip-blanket').fadeOut(this.options.hide.effect.length);
    }
    }
    })
    });*/


    // ****************************************************************
    // Custom Events
    if ($('div.logo a').length != 0) {
        $('div.logo a').click(function() {
            if (typeof fxm != 'undefined') {
                fxm.Log('Images', { 'name': 'Logo', 'action': 'Click' });
            }
        });
    }
    $('div#topnav a').click(function() { fxm.Log('TopNavLink', { 'action': 'Click' }); });
    $('div.subnav a').click(function() { fxm.Log('SubNavLink', { 'action': 'Click' }); });

    // Error Messages
    if ($('div.message-error').length != 0) {
        fxm.Log('Messages', { 'type': 'Error', 'title': $('div.message-error').html() });
    }
    // ****************************************************************

});

// Show the script code in a modal window
//===============================================================
//function ShowScriptCode(websiteId) {
//    var script = '';
//    script += '<!-- FoxMetrics Analytics -->\n';
//    script += '<script src="http://fxm1.foxmetrics.com/fxm.js" type="text/javascript"></script>\n';
//    script += '<script type="text/javascript">\n';
//    script += "    try { fxm.Init('fxm-2021-" + websiteId + "'); } catch (e) { }\n";
//    script += "	fxm.Log('pageview');\n";
//    script += '</script>\n';
//    return script;
//}


/*
** Tests - bunch of tests that I can run to simulate
**         (fxm) activities instead of actually clicking around
************************************************************/
var tests = function() {
    var websiteId = 12;
    var websiteUrl = 'http://tests.foxmetrics.com/';
    var maximumEvents = 20;
    var enableLogging = true;
    var items = [
            { event: 'itemview', id: '30899', name: 'StretchMate Orthopedic Back Stretcher', category: 'Health', unitprice: '39.99' },
            { event: 'itemview', id: '70975', name: 'Easy Spirit Women\'s Instep Slip-Ons', category: 'Casual Shoes', unitprice: '59.99' },
            { event: 'itemview', id: '90004', name: 'Jockey Long-Handled Shoe Horn, Each', category: 'Shoes', unitprice: '9.99' },
            { event: 'itemview', id: '60327', name: 'Jobst® for Men Firm Support Open Toe Over-The-Calf Socks, Pair', category: 'Socks', unitprice: '75.38' },
            { event: 'itemview', id: '85475', name: 'Old Friend Men’s Clogs', category: 'Mens Shoes', unitprice: '49.95' },

            { event: 'itemadd', id: '30899', name: 'StretchMate Orthopedic Back Stretcher', category: 'Health', unitprice: '39.99', quantity: '11' },
            { event: 'itemadd', id: '70975', name: 'Easy Spirit Women\'s Instep Slip-Ons', category: 'Casual Shoes', unitprice: '59.99', quantity: '7' },
            { event: 'itemadd', id: '90004', name: 'Jockey Long-Handled Shoe Horn, Each', category: 'Shoes', unitprice: '9.99', quantity: '6' },
            { event: 'itemadd', id: '60327', name: 'Jobst® for Men Firm Support Open Toe Over-The-Calf Socks, Pair', category: 'Socks', unitprice: '75.38', quantity: '4' },
            { event: 'itemadd', id: '85475', name: 'Old Friend Men’s Clogs', category: 'Mens Shoes', unitprice: '49.95', quantity: '4' },

            { event: 'itemremove', id: '30899', name: 'StretchMate Orthopedic Back Stretcher', category: 'Health', unitprice: '39.99', quantity: '7' },
            { event: 'itemremove', id: '70975', name: 'Easy Spirit Women\'s Instep Slip-Ons', category: 'Casual Shoes', unitprice: '59.99', quantity: '8' },
            { event: 'itemremove', id: '90004', name: 'Jockey Long-Handled Shoe Horn, Each', category: 'Shoes', unitprice: '9.99', quantity: '3' },
            { event: 'itemremove', id: '60327', name: 'Jobst® for Men Firm Support Open Toe Over-The-Calf Socks, Pair', category: 'Socks', unitprice: '75.38', quantity: '9' },
            { event: 'itemremove', id: '85475', name: 'Old Friend Men’s Clogs', category: 'Mens Shoes', unitprice: '49.95', quantity: '4' },

            { event: 'itempurchase', id: '30899', name: 'StretchMate Orthopedic Back Stretcher', category: 'Health', unitprice: '39.99', quantity: '3' },
            { event: 'itempurchase', id: '70975', name: 'Easy Spirit Women\'s Instep Slip-Ons', category: 'Casual Shoes', unitprice: '59.99', quantity: '2' },
            { event: 'itempurchase', id: '90004', name: 'Jockey Long-Handled Shoe Horn, Each', category: 'Shoes', unitprice: '9.99', quantity: '3' },
            { event: 'itempurchase', id: '60327', name: 'Jobst® for Men Firm Support Open Toe Over-The-Calf Socks, Pair', category: 'Socks', unitprice: '75.38', quantity: '4' },
            { event: 'itempurchase', id: '85475', name: 'Old Friend Men’s Clogs', category: 'Mens Shoes', unitprice: '49.95', quantity: '2' },

            { event: 'order', id: 'W123234', customerid: '1', total: '12.34', shipping: '4.96' },
            { event: 'order', id: 'W156434', customerid: '2', total: '152.34', shipping: '4.96' },
    //            { event: 'order', id: 'W187434', customerid: '3', total: '162.34', shipping: '4.96' },
    //            { event: 'order', id: 'W194434', customerid: '4', total: '712.34', shipping: '4.96' },
    //            { event: 'order', id: 'W128994', customerid: '5', total: '182.34', shipping: '4.96' },
    //            { event: 'order', id: 'W123469', customerid: '6', total: '172.34', shipping: '4.96' },
    //            { event: 'order', id: 'W123274', customerid: '7', total: '152.34', shipping: '4.96' },
    //            { event: 'order', id: 'W123963', customerid: '8', total: '122.34', shipping: '4.96' },
    //            { event: 'order', id: 'W123346', customerid: '9', total: '192.34', shipping: '4.96' },
    //            { event: 'order', id: 'W167434', customerid: '10', total: '192.34', shipping: '4.96' },
    //            { event: 'order', id: 'W135534', customerid: '11', total: '312.34', shipping: '4.96' },
    //            { event: 'order', id: 'W123478', customerid: '12', total: '212.34', shipping: '4.96' },
    //            { event: 'order', id: 'W129999', customerid: '13', total: '612.34', shipping: '4.96' },
    //            { event: 'order', id: 'W122353', customerid: '14', total: '7812.34', shipping: '4.96' },
    //            { event: 'order', id: 'W127897', customerid: '15', total: '912.34', shipping: '4.96' },
            {event: 'order', id: 'W124566', customerid: '16', total: '212.34', shipping: '4.96' },
            { event: 'order', id: 'W176866', customerid: '17', total: '412.34', shipping: '4.96' },
            { event: 'order', id: 'W123467', customerid: '18', total: '612.34', shipping: '4.96' }
        ];

    return {
        init: function() {
            fxm.Init('fxm-2021-' + websiteId);
        },
        runAnalytics: function() {
            this.init();
        },
        runEcommerce: function() {
            this.init();
            $('input#testsbutton').val('Running...');

            // Item Views
            for (var i = 0; i < maximumEvents; i++) {
                var rndItem = items[Math.floor(Math.random() * items.length)];
                fxm.Log('ecommerce', rndItem);
            }

            // Console Logging
            if (enableLogging && typeof console != 'undefined')
                console.log('ECommerce Tests Completed');

            // Button
            $('input#testsbutton').val('Run Tests');
        }
    }
} ();


// GLOBAL METHODS
//===============================================================
var global = function() {
    var groupByCookieName = 'fxmgroupby';
    var cookieName = 'fxmd';
    function Host() {
        var protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
        return protocol + (document.location.host == 'localhost' ? 'localhost/foxmetrics.dashboard/' : 'dash1.foxmetrics.com/');
    }
    return {/*
        GetHost: function() { return Host(); },
        GetDefaultHost: function() { return $.cookie('fxmd') ? $.cookie('fxmd').split('|')[0] : ''; },*/
        GetGroupBy: function() {
            var defaultGroupBy = 'DD';
            if ($.cookie(groupByCookieName) != undefined) defaultGroupBy = $.cookie(groupByCookieName);
            if ($.cookie(groupByCookieName) == undefined) $.cookie(groupByCookieName, defaultGroupBy, { path: '/' });
            return defaultGroupBy;
        },
        SetGroupBy: function(val) {
            $.cookie(groupByCookieName, val, { path: '/' });
        },
        GetStartDate: function() {
            var now = new Date();
            now.addDays(-7);

            var startDate = now;
            if ($.cookie('startdate') != undefined) startDate = $.cookie('startdate');
            return startDate;
        },
        GetEndDate: function() {
            var endDate = new Date();
            if ($.cookie('enddate') != undefined) endDate = $.cookie('enddate');
            return endDate;
        },
        ShowHtmlContent: function() {
            if ($('div#htmlcontent')) {
                $('div#htmlcontent').slideDown();
            }
        }, /*
        ColorPalette: function() {
            return ["#adb930", "#4BB2C5", "#999999", "#fa945f", "#FF0000", "#0372AB", "#FF5904"];
        },*/
        CleanId: function(name) {
            return name.replace(' ', '_');
        },
        GetRandomMaxWait: function() {
            return 3000;
        }, /*
        SetSelectedHost: function(host) {
            var cookie = $.cookie('fxmd');
            if (typeof (cookie) != undefined && cookie.length > 0) {
                cookieValues = cookie.split('|');
                cookieValues[0] = host;
                $.cookie(cookieName, cookieValues.toDelimetedString('|'), { path: '/' });
            }
        },*/
        //        SetDirtyCookieFlag: function() {
        //            var cookie = $.cookie('fxmd');
        //            if (typeof (cookie) != undefined && cookie.length > 0) {
        //                cookieValues = cookie.split('|');
        //                cookieValues[cookieValues.length] = "1";
        //                $.cookie(cookieName, cookieValues.toDelimetedString('|'), { path: '/' });
        //            }
        //        },
        ReplaceContent: function(element, value) {
            if (typeof (value) != 'undefined' && $(element)) {
                var val = $(element).html();
                if (val != value) {
                    $(element).html(value).animate({ opacity: 0 }, 500, function() { $(this).animate({ opacity: 1 }, 500); });
                }
            }
        }
    }
} ();

var dashboard = {
    // public variables that are available in this scope
    // -------------------------------------------------------------------------
    groupByCookieName: 'fxmgroupby',
    cookieName: 'fxmd',
    apiHost: (("https:" == document.location.protocol) ? "https://" : "http://") + (document.location.host == 'localhost' ? 'localhost/foxmetrics.dashboard/' : 'dash1.foxmetrics.com/'),
    selectedHost: ($.cookie('fxmd') ? $.cookie('fxmd').split('|')[0] : ''),
    dataNotAvailableRow: '<tr><td>Data Not Available</td></tr>',
    colorPalette: ["#adb930", "#4BB2C5", "#999999", "#fa945f", "#FF0000", "#0372AB", "#FF5904"],
    cleanId: function(name) {
        return name.replace(' ', '_');
    },
    // Helper/Utilities
    // -------------------------------------------------------------------------
    BlockUI: function() {
        //$.blockUI({ message: '<h3>Just a moment...</h3>', css: { padding: '5px'} });
        $('div.column_1').block({ message: '<h3>Just a moment...</h3>', css: { padding: '5px'} });
    },
    GetStartDate: function() {
        var field = $('input#startdate');
        if (field != 'undefined' && field.length > 0) return field.val();
        return new Date().format('m/d/Y');
    },
    GetEndDate: function() {
        var field = $('input#enddate');
        if (field != 'undefined' && field.length > 0) return field.val();
        return new Date().format('m/d/Y');
    },
    SetDirtyCookieFlag: function() {
        var cookie = $.cookie(dashboard.cookieName);
        if (typeof (cookie) != undefined && cookie.length > 0) {
            cookieValues = cookie.split('|');
            cookieValues[cookieValues.length] = "1";
            $.cookie(dashboard.cookieName, cookieValues.toDelimetedString('|'), { path: '/' });
        }
    },
    SetSelectedHost: function(host) {
        var cookie = $.cookie(dashboard.cookieName);
        if (typeof (cookie) != undefined && cookie.length > 0) {
            cookieValues = cookie.split('|');
            cookieValues[0] = host;
            $.cookie(dashboard.cookieName, cookieValues.toDelimetedString('|'), { path: '/' });
        }
    },
    flashElement: function(element) {
        var duration = 3000;
        element.animate({ backgroundColor: '#a7bf51' }, 800);
        //alert(current);
        //$(element).animate({ opacity: 0 }, 500, function() { $(this).animate({ opacity: 1 }, 500); });
    },
    replaceContent: function(element, value) {
        if (typeof (value) != 'undefined' && $(element)) {
            var val = $(element).html();
            if (val != value) {
                $(element).html(value).animate({ opacity: 0 }, 500, function() { $(this).animate({ opacity: 1 }, 500); });
            }
        }
    },
    updateTableRow: function(tableId, rowId, html) {
        var row = $('table#' + tableId + ' tbody tr#' + rowId);
        if (row.length > 0) {
            row.fadeOut('slow', function() {
                row.innerHtml = html;
            });
        } else {
            $('table#' + tableId + ' tbody').append('<tr id="' + rowId + '">' + html + '</tr>');
            row = $('table#' + tableId + ' tbody tr#' + rowId);
        }
        row.fadeIn('slow');
    },
    showAjaxLoading: function() {
        $('div.ajaxloading').show();
    },
    hideAjaxLoading: function() {
        $('div.ajaxloading').hide();
    },
    // Charts
    // -------------------------------------------------------------------------
    charts: {
        hitsTooltipFormatter: function(name, x, y) {
            return '<b>' + y + '</b> ' + name;
        },
        line: function(el, margin, tooltiptype, cats, series) {
            return new Highcharts.Chart({
                chart: { renderTo: el, defaultSeriesType: 'line', margin: margin },
                colors: dashboard.colorPalette,
                title: { text: null },
                xAxis: { categories: cats },
                yAxis: { min: 0, title: { text: null} },
                tooltip: {
                    formatter: function() {
                        if (tooltiptype === 'hits') return dashboard.charts.hitsTooltipFormatter(this.series.name, this.x, this.y);
                        return '<b>' + this.series.name + '</b>';
                    }
                },
                legend: {
                    layout: 'horizontal',
                    style: { left: 'auto', bottom: 'auto', right: '0px', top: '0px' }
                },
                series: series
            });
        },
        stackedBar: function(el, margin) {
            return new Highcharts.Chart({
                chart: { renderTo: el, defaultSeriesType: 'bar', margin: margin },
                colors: dashboard.colorPalette,
                title: { text: null },
                xAxis: { title: { text: null} },
                yAxis: { min: 0, title: { text: null} },
                tooltip: {
                    formatter: function() {
                        return '<b>' + this.series.name + ':</b> ' + this.y;
                    }
                },
                plotOptions: { bar: { dataLabels: { enabled: true }, borderWidth: 0, shadow: false }, series: { borderRadius: 5, stacking: 'normal'} },
                legend: {
                    layout: 'vertical',
                    style: { left: 'auto', bottom: 'auto', right: 'auto', top: '100px' },
                    borderWidth: 1
                },
                series: [{ data: []}]
            });
        },
        bar: function(el, margin) {
            return new Highcharts.Chart({
                chart: { renderTo: el, defaultSeriesType: 'bar', margin: margin },
                colors: dashboard.colorPalette,
                title: { text: null },
                xAxis: { title: { text: null} },
                yAxis: { min: 0, title: { text: null} },
                tooltip: {
                    formatter: function() {
                        return '<b>' + this.series.name + ':</b> ' + this.y;
                    }
                },
                plotOptions: { bar: { dataLabels: { enabled: true }, borderWidth: 0, shadow: false }, series: { borderRadius: 5} },
                legend: {
                    layout: 'vertical',
                    style: { left: 'auto', bottom: 'auto', right: 'auto', top: '100px' },
                    borderWidth: 1
                },
                series: [{ data: []}]
            });
        },
        column: function(el, margin, enableLegend, tooltipType, cats, series) {
            return new Highcharts.Chart({
                chart: { renderTo: el, defaultSeriesType: 'column', margin: margin },
                colors: dashboard.colorPalette,
                title: { text: null },
                legend: { enabled: enableLegend },
                tooltip: {
                    formatter: function() {
                        if (tooltipType === 'hour') {
                            var suffix = (this.x < 12) ? 'am' : 'pm';
                            var timeformat = (this.x == '0' ? '12' : this.x) + suffix + ' to ' + (parseInt(this.x) + 1) + suffix;
                            return timeformat + ', ' + this.y + ' event' + (this.y > 1 ? 's' : '');
                        }
                    }
                },
                plotOptions: { column: { pointPadding: 0, borderWidth: 0, shadow: false} },
                xAxis: { categories: cats },
                yAxis: { min: 0, title: { text: null} },
                series: series
            });
        },
        pie: function(el, margin, data) {
            if (typeof (data) == 'undefined') data = [];
            return new Highcharts.Chart({
                chart: { renderTo: el, margin: margin, defaultSeriesType: 'pie' },
                colors: dashboard.colorPalette,
                title: { text: null },
                plotArea: { shadow: null, borderWidth: null, backgroundColor: null },
                tooltip: {
                    formatter: function() {
                        return '<b>' + this.point.name + '</b>: ' + this.y;
                    }
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: false,
                        dataLabels: {
                            enabled: false/*,
                            formatter: function() {
                                if (this.y > 5) {
                                    var name = this.point.name;
                                    if (name === 'Internet Explorer') name = 'IE';
                                    return name;
                                }
                            }*/
                        }
                    }
                },
                legend: {
                    layout: 'vertical',
                    style: {
                        left: 'auto',
                        bottom: 'auto',
                        right: '0px',
                        top: '0px'
                    }
                },
                series: [{ data: data}]
            });
        }
    },
    // Loader
    load: {
        //isLoaded: false,
        trafficSourcesChart: null,
        retentionChart: null,
        activityChart: null,
        prepare: function() {
            var date = new Date();
            date.addDays(-7);
            $('input#startdate').val(date.format('m/d/Y'));
            $('input#enddate').val(new Date().format('m/d/Y'));
            $('input#startdate').simpleDatepicker();
            $('input#enddate').simpleDatepicker();
        },
        stream: function() {
            // show that we are doing something
            dashboard.showAjaxLoading();

            // variables that will be used through because I need
            // need to force a garbage collection to prevent memory leaks
            var ds1, ds2, ds3, ds4;
            var dataNotAvailableRow = dashboard.dataNotAvailableRow;

            // gets the json data and handle the response
            $.getJSON(dashboard.apiHost + 'api/dashboard/?type=wss&host=' + dashboard.selectedHost, function(json) {
                if (json == null)
                    return;

                // Engagement
                //---------------------------------                
                dashboard.replaceContent('div#engagement span#sessions', json.s);
                dashboard.replaceContent('div#engagement span#reading', json.r);
                dashboard.replaceContent('div#engagement span#writing', json.w);
                dashboard.replaceContent('div#engagement span#idle', json.i);

                // Totals
                //---------------------------------
                dashboard.replaceContent('div#engagement span#tvisitors', json.tv);
                dashboard.replaceContent('div#engagement span#tsessions', json.ts);
                dashboard.replaceContent('div#engagement span#tpageviews', json.tpv);
                dashboard.replaceContent('div#engagement span#texits', json.te);
                dashboard.replaceContent('div#engagement span#tdownloads', json.td);

                // Hourly hits chart
                //---------------------------------
                if (typeof json.hh != 'undefined' && json.hh != null && json.hh != []) {
                    ds1 = [], ds2 = [], ds3 = [], ds4 = [];
                    $.each(json.hh, function() {
                        ds4.push(this.Key);
                        var arry = this.Value.split('|');
                        ds1.push(Number(arry[0]));
                        ds2.push(Number(arry[1]));
                        ds3.push(Number(arry[2]));
                    });

                    var hits = [{ name: 'Visitors', data: ds1 }, { name: 'Sessions', data: ds2 }, { name: 'Page Views', data: ds3}]
                    if (dashboard.load.activityChart == null) {
                        dashboard.load.activityChart = dashboard.charts.line('activityChart', [30, 10, 14, 24], 'hits', ds4, hits);
                    } else {
                        dashboard.load.activityChart.series[0].setData(ds1);
                        dashboard.load.activityChart.series[1].setData(ds2);
                        dashboard.load.activityChart.series[2].setData(ds3);
                    }
                } else {
                    $('table#activity tbody').html(dataNotAvailableRow);
                }

                // Traffic Sources Chart
                //---------------------------------
                if (typeof json.tst != 'undefined' && json.tst != null && json.tst.length > 0) {
                    // first load
                    if (dashboard.load.trafficSourcesChart == null)
                        dashboard.load.trafficSourcesChart = dashboard.charts.pie('trafficSourcesChart', [0, 0, 0, -140]);

                    // build the data array
                    ds1 = [];
                    $.each(json.tst, function(idx) {
                        var entry = {};
                        entry.name = this.Key;
                        entry.y = parseInt(this.Value, 10);
                        entry.color = dashboard.colorPalette[idx];
                        ds1.push(entry);
                    });

                    // update the data array within the chart
                    dashboard.load.trafficSourcesChart.series[0].setData(ds1);
                } else {
                    $('table#trafficsources tbody').html(dataNotAvailableRow);
                }

                // Retention Chart
                //---------------------------------
                if (typeof json.ret != 'undefined' && json.ret != null && json.ret.length > 0) {
                    // first load
                    if (dashboard.load.retentionChart == null) {
                        dashboard.load.retentionChart = dashboard.charts.bar('retentionChart', [5, 10, 14, 44]);
                        dashboard.load.retentionChart.xAxis[0].setCategories(['New', 'Repeat']);
                    }
                    ds1 = [];
                    $.each(json.ret, function(idx) {
                        var entry = {};
                        entry.name = (this.Key === 'New') ? 'New' : 'Repeat';
                        entry.y = parseInt(this.Value, 10);
                        entry.color = dashboard.colorPalette[idx];
                        if (this.Key === 'New') {
                            ds1[0] = entry;
                        } else {
                            ds1[1] = entry;
                        }
                    });

                    if (ds1[0] == null) { ds1[0] = ds1[1]; ds1.remove(1); }
                    dashboard.load.retentionChart.series[0].setData(ds1);
                } else {
                    $('table#retention tbody').html(dataNotAvailableRow);
                }

                // Visitors
                //---------------------------------
                if (typeof json.v != 'undefined' && json.v != null && json.v.length > 0) {
                    $.each(json.v, function() {
                        var arry = this.split('|');
                        var divId = arry[1].replace(/\./gi, '');
                        if ($('div#v-' + divId).length <= 0) {
                            var flagImg = '<img src="' + dashboard.apiHost + 'content/images/flags/' + arry[0] + '.png" alt="Portugal" />&nbsp;&nbsp;';
                            if (arry[0] === '--' || arry[0].length <= 0) flagImg = '';
                            var temp = '<div id=v-' + divId + '><span>' + flagImg + arry[1] + '</span></div>';
                            $('div#ipaddresses').append(temp);
                        }
                    });
                } else {
                    $('div#ipaddresses').html(dataNotAvailableRow);
                }

                // Active Pages
                //---------------------------------
                $('table#activepages tbody').html('');
                if (typeof json.pg != 'undefined' && json.pg != null && json.pg.length > 0) {
                    $.each(json.pg, function() {
                        //ds1 = tmpl('<tr><td><div class="title"><%=Key.Title%></div><div class="link"><a href="<%=Key.Url%>" target=_blank><%=Key.Url%></a></div></td><td class="num"><%=Value%></td></tr>', this);
                        ds1 = '<tr><td><div class="title"><%=Key.Title%></div><div class="link"><a href="<%=Key.Url%>" target=_blank><%=Key.Url%></a></div></td><td class="num"><%=Value%></td></tr>'.tmpl(this);
                        $('table#activepages tbody').append(ds1);
                    });
                } else {
                    $('table#activepages tbody').html(dataNotAvailableRow);
                }

                // Keywords
                //---------------------------------
                $('table#keywords tbody').html('');
                if (typeof json.k != 'undefined' && json.k != null && json.k.length > 0) {
                    $.each(json.k, function() {
                        ds1 = '<tr><td><div class="title"><%=Key%></div></td><td class="when"><%=Value%></td></tr>'.tmpl(this);
                        $('table#keywords tbody').append(ds1);
                    });
                } else {
                    $('table#keywords tbody').html(dataNotAvailableRow);
                }

                // Referrer Host Names
                //---------------------------------
                $('table#referrers tbody').html('');
                if (typeof json.rfh != 'undefined' && json.rfh != null && json.rfh.length > 0) {
                    $.each(json.rfh, function() {
                        //ds1 = tmpl('<tr><td><div class="title"><a href="http://<%=Key%>" target=_blank><%=Key%></a></div></td><td class="num"><%=Value%></td></tr>', this);
                        ds1 = '<tr><td><div class="title"><a href="http://<%=Key%>" target=_blank><%=Key%></a></div></td><td class="num"><%=Value%></td></tr>'.tmpl(this);
                        $('table#referrers tbody').append(ds1);
                    });
                } else {
                    $('table#referrers tbody').html(dataNotAvailableRow);
                }

                // Countries
                //---------------------------------
                /*
                $('table#locations tbody').html('');
                if (typeof json.c != 'undefined' && json.c != null && json.c.length > 0) {
                $.each(json.c, function() {
                ds1 = this.Key.split('|');
                ds2 = ds1[0];
                ds3 = ds1[1];
                //
                ds4 = '<img style="vertical-align:middle" src="' + dashboard.apiHost + 'content/images/flags/' + ds3 + '.png' + '" alt="' + ds2 + '" />';
                if (ds2 === 'N/A') { ds2 = 'Unknown'; ds4 = ''; }
                $('table#locations tbody').append('<tr><td><div class="title">' + ds4 + '&nbsp;&nbsp;' + ds2 + '</div></td><td class="num">' + this.Value + '</td></tr>');
                });
                } else {
                $('table#locations tbody').html(dataNotAvailableRow);
                }
                */

                // Performance
                //---------------------------------
                /*
                $('table#performance tbody').html('');
                if (typeof (json.perf) != 'undefined' && json.perf != null) {
                $.each(json.perf, function() {
                ds1 = (this.Key === 'fplt' ? 'Fastest' : 'Slowest') + ' Page Load';
                $('table#performance tbody').append(tmpl('<tr><td><div class="title">' + ds1 + '</div></td><td class="num"><%=Value%> ms</td></tr>', this));
                });
                } else {
                $('table#performance tbody').html(dataNotAvailableRow);
                }
                */

                // Events
                //---------------------------------
                $('table#events tbody').html('');
                if (typeof (json.e) != 'undefined' && json.e != null) {
                    $.each(json.e, function() {
                        $('table#events tbody').append('<tr><td><div class="title"><%=Key%></div></td><td class="num"><%=Value%></td></tr>'.tmpl(this));
                    });
                } else {
                    $('table#events tbody').html(dataNotAvailableRow);
                }

            });

            // prevent memory leaks
            json = null;
            ds1 = null;
            ds2 = null;
            ds3 = null;
            ds4 = null;

            // we are done here
            dashboard.hideAjaxLoading();

            // call this again
            setTimeout('dashboard.load.stream()', 15000);
        }
    }
};

/* Content
** Content area of the dashboard, handles (pages & downloads)
*-------------------------------------------------------------*/
$.extend(dashboard.load, { content: {
    pages: function() {
        // gets the json data and handle the response
        var query = '?host=' + dashboard.selectedHost + '&startdate=' + dashboard.GetStartDate() + '&enddate=' + dashboard.GetEndDate();
        $.getJSON(dashboard.apiHost + 'reporting/pages' + query, function(json) {
            if (json == null)
                return;
            var table = $('table#sessions tbody');
            if (table != null && json.s != null && json.s.length > 0) {
                var row = 1;
                $.each(json.s, function() {
                    var url = 'http://' + dashboard.selectedHost + this.lp;
                    table.append('<tr><td class="num">'
                        + row + '.</td><td>' + this.t + '</td><td>' + this.w + '</td><td class="hits">'
                        + this.a + '</td><td><a href="' + url + '" title="' + url + '" target=_blank>' + this.lp.ellipsisText('center', 30)
                        + '</a></td><td><a href="' + this.rf + '" title="' + this.rf + '" target=_blank>'
                        + this.rfh.ellipsisText('end', 20) + '</a></td>'
                        + '<td><img src="../content/images/browsers/16x16/' + this.bn.replace('Internet Explorer', 'IE') + '.png" title="' + this.bn + '" />&nbsp<img src="../content/images/operatingsystems/16x16/' + this.osn + '.png" title="' + this.osn + '" />'
                        + '&nbsp<img src="../content/images/flags/' + this.cc + '.png" title="' + this.cn + '" /></td></tr>');
                    row++;
                });
            } else { $('table#sessions tfoot').hide(); table.append('<tr><td colspan="7">We have not recorded any sessions.</td></tr>'); }
        });
    },
    downloads: function() {
        // gets the json data and handle the response
        var query = '?host=' + dashboard.selectedHost + '&startdate=' + dashboard.GetStartDate() + '&enddate=' + dashboard.GetEndDate();
        $.getJSON(dashboard.apiHost + 'reporting/downloads' + query, function(json) {
            if (json == null)
                return;
            var table = $('table#downloads tbody');
            if (table != null && json.s != null && json.s.length > 0) {
                var row = 1;
                $.each(json.s, function() {
                    var url = 'http://' + dashboard.selectedHost + this.lp;
                    table.append('<tr><td class="num">'
                        + row + '.</td><td>' + this.t + '</td><td>' + this.w + '</td><td class="hits">'
                        + this.a + '</td><td><a href="' + url + '" title="' + url + '" target=_blank>' + this.lp.ellipsisText('center', 30)
                        + '</a></td><td><a href="' + this.rf + '" title="' + this.rf + '" target=_blank>'
                        + this.rfh.ellipsisText('end', 20) + '</a></td>'
                        + '<td><img src="../content/images/browsers/16x16/' + this.bn.replace('Internet Explorer', 'IE') + '.png" title="' + this.bn + '" />&nbsp<img src="../content/images/operatingsystems/16x16/' + this.osn + '.png" title="' + this.osn + '" />'
                        + '&nbsp<img src="../content/images/flags/' + this.cc + '.png" title="' + this.cn + '" /></td></tr>');
                    row++;
                });
            } else { $('table#downloads tfoot').hide(); table.append('<tr><td colspan="7">We have not recorded any downloads.</td></tr>'); }
        });
    }
}
});


/* Events
* Extend the dashboard.load object and a events object
*-------------------------------------------------------------*/
$.extend(dashboard.load, { events: {
    stream: function() {
        // show that we are doing something
        dashboard.showAjaxLoading();

        // gets the json data and handle the response
        $.getJSON(dashboard.apiHost + 'api/dashboard/?type=es&host=' + dashboard.selectedHost, function(json) {
            if (json == null)
                return;

            //
            dashboard.replaceContent('div#engagement span#hits', json.th);
            dashboard.replaceContent('div#engagement span#events', json.te);

            //          
            if (typeof json.he != 'undefined' && json.he != null && json.he != []) {
                var cats = [];
                var xValue = []; for (var i = 0; i < 24; i++) xValue.push(i);

                $.each(json.he, function() {
                    var eventName = this.Key;
                    var cat = null;

                    // see if we can find this entry already
                    for (var i = 0; i < cats.length; i++) {
                        if (cats[i].name === eventName) {
                            cat = this;
                            break;
                        }
                    }

                    // ensure the category exist
                    if (cat == null) {
                        cat = {};
                        cat.name = eventName;
                        cat.data = [];
                    }

                    // populate its data
                    $.each(this.Value, function() {
                        var hit = Number(this.Value);
                        cat.data.push(hit);
                    });

                    // we are dont
                    cats.push(cat);
                });

                // create the chart as needed                
                if (dashboard.load.activityChart == null) {
                    dashboard.load.activityChart = dashboard.charts.line('activityChart', [30, 10, 14, 24], 'hits', xValue, cats);
                } else {
                    /* update data */
                    for (var i = 0; i < cats.length; i++) {
                        var cat = cats[i];
                        for (var j = 0; j < dashboard.load.activityChart.series.length; j++) {
                            if (dashboard.load.activityChart.series[j].name === cat.name)
                                dashboard.load.activityChart.series[j].setData(cat.data);
                        }
                    }
                }
            }

            //
            if (typeof json.re != 'undefined' && json.re != null && json.re != []) {
                var table = $('table#recentevents tbody');
                table.html('');
                table.append('<tr><th style="width: 160px;">Name</th><th>Attributes</th></tr>');
                $.each(json.re, function() {
                    var attribs = '';
                    //
                    if (this.a != null) {
                        $.each(this.a, function() {
                            attribs += (attribs.length > 0 ? ', ' : '') + '<a href="">' + this + '</a>';
                        });
                    }
                    //
                    table.append('<tr><td><span class="name"><a href="">' + this.n + '</a></span><br /><span class="when">' + this.w + '</span></td><td class="attributes">' + attribs + '</td></tr>');
                });
            }

            //TODO:, we need to implement as call back function
            $('td.attributes a').corner('3px');
        });


        // we are done here
        dashboard.hideAjaxLoading();

        // call this again
        setTimeout('dashboard.load.events.stream()', 15000);
    }
}
});

/* Links
** Link related reports of incoming and outgoing links
*-------------------------------------------------------------*/
$.extend(dashboard.load, { links: {
    incoming: function() { },
    outgoing: function() { }
}
});

/* Visitors
* Extend the dashboard.load object and a visitors object
*-------------------------------------------------------------*/
$.extend(dashboard.load, { visitors: {
    visitors: function() {
        // gets the json data and handle the response
        var query = '?host=' + dashboard.selectedHost + '&startdate=' + dashboard.GetStartDate() + '&enddate=' + dashboard.GetEndDate();
        $.getJSON(dashboard.apiHost + 'reporting/visitors' + query, function(json) {
            if (json == null)
                return;
            var table = $('table#visitors tbody');
            if (table != null && json.s != null && json.s.length > 0) {
            }
        });
    },
    sessions: function() {
        // gets the json data and handle the response
        var query = '?host=' + dashboard.selectedHost + '&startdate=' + dashboard.GetStartDate() + '&enddate=' + dashboard.GetEndDate();
        $.getJSON(dashboard.apiHost + 'reporting/sessions' + query, function(json) {
            if (json == null)
                return;
            var table = $('table#sessions tbody');
            if (table != null && json.s != null && json.s.length > 0) {
                var row = 1;
                $.each(json.s, function() {
                    var url = 'http://' + dashboard.selectedHost + this.lp;
                    table.append('<tr><td class="num">'
                        + row + '.</td><td>' + this.t + '</td><td>' + this.w + '</td>'
                        + '<td><a href="' + url + '" title="' + url + '" target=_blank>' + this.lp.ellipsisText('center', 30)
                        + '</a></td><td><a href="' + this.rf + '" title="' + this.rf + '" target=_blank>'
                        + this.rfh.ellipsisText('end', 20) + '</a></td>'
                        + '<td><img src="../content/images/browsers/16x16/' + this.bn.replace('Internet Explorer', 'IE') + '.png" title="' + this.bn + '" />&nbsp<img src="../content/images/operatingsystems/16x16/' + this.osn + '.png" title="' + this.osn + '" />'
                        + '&nbsp<img src="../content/images/flags/' + this.cc + '.png" title="' + this.cn + '" /></td></tr>');
                    row++;
                });
            } else { $('table#sessions tfoot').hide(); table.append('<tr><td colspan="7">We have not recorded any sessions.</td></tr>'); }
        });
    }
}
});

