$(document).ready(function () {
    //tabs
    $('#myTab a:first').tab('show');
    $('#myTab a').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });

    $('.btn-close').click(function (e) {
        e.preventDefault();
        $(this).parent().parent().parent().fadeOut();
    });
    $('.btn-minimize').click(function(e) {
        e.preventDefault();
        var $target = $(this).parent().parent().next('.box-content');
        if ($target.is(':visible'))
            $('i', $(this)).removeClass('icon-chevron-up').addClass('icon-chevron-down');
        else
            $('i', $(this)).removeClass('icon-chevron-down').addClass('icon-chevron-up');
        $target.slideToggle();
    });

    var updateInterval = 30;
    //realtime chart
    if ($("#realtimechart").length) {
        var options = {
            series: { shadowSize: 1 }, // drawing is faster without shadows
            yaxis: { min: 0, max: 100 },
            xaxis: { show: false }
        };
        var plot = $.plot($("#realtimechart"), [getRandomData()], options);
        function update() {
            plot.setData([getRandomData()]);
            // since the axes don't change, we don't need to call plot.setupGrid()
            plot.draw();

            setTimeout(update, updateInterval);
        }

        update();
    }
});

var data = [], totalPoints = 300;
function getRandomData() {
    if (data.length > 0)
        data = data.slice(1);

    // do a random walk
    while (data.length < totalPoints) {
        var prev = data.length > 0 ? data[data.length - 1] : 50;
        var y = prev + Math.random() * 10 - 5;
        if (y < 0)
            y = 0;
        if (y > 100)
            y = 100;
        data.push(y);
    }

    // zip the generated y values with the x values
    var res = [];
    for (var i = 0; i < data.length; ++i)
        res.push([ i, data[i] ])
    return res;
}

var previousPoint = null, previousLabel = null;

$.fn.UseTooltip = function (isTime) {
    $(this).bind("plothover", function (event, pos, item) {
        if (item) {
            if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
                previousPoint = item.dataIndex;
                previousLabel = item.series.label;
                $("#tooltip").remove();

                var x = item.datapoint[0];
                var y = item.datapoint[1];

                var text = '';
                if (isTime) {
                    var date = new Date(x);
                    text = "<strong>" + formatDateWeek(date) + "</strong> (" + y + ")";
                } else {
                    //text = "<strong>" + item.series.label + "</strong><br>" + item.series.xaxis.ticks[x].label + " (<strong>" + y + "</strong>)";
                    text = "<strong>" + item.series.xaxis.ticks[x].label + "</strong> (" + y + ")";
                }
                showTooltip(item.pageX, item.pageY, item.series.color, text);
            }
        } else {
            $("#tooltip").remove();
            previousPoint = null;
        }
    });
};

function showTooltip(x, y, color, contents) {
    $('<div id="tooltip">' + contents + '</div>').css({
        position: 'absolute',
        display: 'none',
        top: y - 40,
        left: x - 120,
        border: '2px solid ' + color,
        padding: '3px',
        'font-size': '9px',
        'border-radius': '5px',
        'background-color': '#fff',
        'font-family': 'Verdana, Arial, Helvetica, Tahoma, sans-serif',
        opacity: 0.9
    }).appendTo("body").fadeIn(200);
}

function gd(year, month, day) {
    return new Date(year, month - 1, day).getTime();
}

function getWeekOfMonth(date) {
    var selectedDayOfMonth = date.getDate();

    var first = new Date(date.getFullYear() + '/' + (date.getMonth() + 1) + '/01');
    var monthFirstDateDay = first.getDay();

    return Math.ceil((selectedDayOfMonth + monthFirstDateDay) / 7);
}

function createFrequencyChart(q) {
    if ($("#frequencychart").length == 0)
        return;

    //var data = [["January", 10], ["February", 8], ["March", 4], ["April", 13], ["May", 17], ["June", 9]];
    var labels = q['hl'];
    var data = q['hd'];
    var two = $.map(labels, function (el, idx) {
        return [[el, data[idx]]];
    });
    var dataset = [{ label: "Hits", data: two }];
    var options = {
        series: {
            bars: {
                show: true,
                barWidth: 0.6,
                align: "center"
            }
        },
        xaxis: {
            mode: "categories",
            color: "#FFFFFF",
            ticks: $.map(labels, function (el, idx) {
                return [[idx, el]];
            })
        },
        yaxis: {
            color: "#FFFFFF"
        },
        legend: {
            noColumns: 0,
            labelBoxBorderColor: "#000000",
            position: "ne",
            backgroundOpacity: 0
        },
        grid: {
            hoverable: true
        }
    };
    $.plot("#frequencychart", dataset, options);
    $("#frequencychart").UseTooltip(false);
}

function createTimeChart(q) {
    if ($("#timechart").length == 0)
        return;

    //var d = [ [gd(2013, 1, 31), 100], [gd(2013, 4, 30), 10], [gd(2013, 10, 31), 50], [gd(2013, 12, 31), 180] ];
    var labels = q['twl']; // yyyy-MM-dd (the last day of week)
    var data = q['twd'];
    var two = $.map(labels, function (el, idx) {
        var dates = el.split('-');
        return [[gd(dates[0], dates[1], dates[2]), data[idx]]];
    });
    var ticks = $.map(two, function (el, idx) {
        var time = el[0];
        var label = formatDateWeek(time);
        return [[time, label]];
    });
    var dataset = [{
        label: "Weekly Stat",
        data: two,
        color: "#FF0000",
        points: { fillColor: "#FF0000", show: true },
        lines: { show: true }
    }];
    $.plot("#timechart", dataset, {
        series: {
            shadowSize: 5
        },
        xaxis: {
            mode: "time",
            color: "#FFFFFF",
            ticks: ticks,
            //tickSize: [7, "day"],
            timeformat: "%m/%d",
            //tickFormatter: formatDate,
            //labelWidth: 30
        },
        yaxis: {
            color: "#FFFFFF",
            tickDecimals: 0
        },
        legend: {
            show: false
        },
        grid: {
            hoverable: true,
            minBorderMargin: 20
        }
    });
    $("#timechart").UseTooltip(true);
}

function formatDateWeekFromString(str) {
    var dates = str.split('-');
    return formatDateWeek(gd(dates[0], dates[1], dates[2]), null);
}

function formatDateWeek(val, axis) {
    var date = new Date(val);
    return date.getFullYear() + "/" + pad(date.getMonth() + 1) + " " + getWeekOfMonth(date) + "W";
}

function formatDateTime(val) {
    var date = new Date(val);
    return date.getFullYear() + "/" + pad(date.getMonth() + 1) + "/" + pad(date.getDate()) + " " + pad(date.getHours()) + ":" + pad(date.getMinutes());
}

function pad(n) {
    return n < 10 ? '0' + n : n;
}

function go(link) {
    var qs = window.location.href.substring(window.location.href.indexOf('?') + 1);
    window.location.href = link + "?" + qs;
}
