<commit_before>$(function () {
    // Gauge chart configuration options {{{
    var gauge_options = {
        palette: 'Soft Pastel',
        animation: {
            enabled: false
        },
        valueIndicator: {
            type: 'triangleNeedle',
            color: '#7a8288'
        },
        title: {
             text: 'Cluster storage utilization',
             font: { size: 18, color: '#c8c8c8', family: 'Helvetica' },
             position: 'bottom-center'
        },
        geometry: {
            startAngle: 180,
            endAngle: 0
        },
        margin: {
            top: 0,
            right: 10
        },
        rangeContainer: {
            ranges: [
                { startValue: 0, endValue: 60, color: '#62c462' },
                { startValue: 60, endValue: 80, color: '#f89406' },
                { startValue: 80, endValue: 100, color: '#ee5f5b' }
            ]
        },
        scale: {
            startValue: 0,
            endValue: 100,
            majorTick: {
                tickInterval: 20
            },
            label: {
                customizeText: function (arg) {
                    return arg.valueText + ' %';
                }
            }
        }
    };
    // }}}

    // Graphite to flot configuration options {{{
    var flot_options = {
        grid: {
            show: true
        },
        xaxis: {
            tickFormatter: function() { return ""; }
        },
        legend: {
            show: true
        },
        yaxis: {
            //tickFormatter: function() { return ""; }
            min: 0,
        }
    }

    // TODO: Test more graphs
    function updatePlot(index, graphite_url, targets, from, labels, colors, mode) {
        combined_targets = "";
        $.each(targets, function(index, target) {
            combined_targets += "&target=" + target;
        });
        var query_url = graphite_url + "/render?format=json&from=" + from + combined_targets;

        var series = [ ];
        $.getJSON(query_url, function(targets) {
            if (targets.length > 0) {
                $.each(targets, function(index, target) {
                    var datapoints = target.datapoints;
                    var xzero = datapoints[0][1];
                    var data = $.map(target.datapoints, function(value) {
                    if (value[0] === null) return null;
                        return [[ value[1]-xzero, value[0] ]];
                    });

                    // replace null value with previous item value
                    for (var i = 0; i < data.length; i++) {
                        if (i > 0 && data[i] === null) data[i] = data[-i];
                    }

                    series.push({
                        data: data,
                        label: labels[index],
                        lines: { fill: true }
                    });
                });
                // update plot
                if (typeof mode != undefined) {
                    flot_options.yaxis.mode = mode
                }
                if (typeof color != undefined) {
                    flot_options.colors = colors
                }
                $.plot("#graphite" + index, series, flot_options);
            }
        });
    }
    // }}}

    // Pie chart configuration options {{{
    var chart_options = {
        animation: {
            enabled: false
        },
        tooltip: {
            enabled: true,
            format:"decimal",
            percentPrecision: 2,
            font: { size: 14, color: '#1c1e22', family: 'Helvetica' },
            arrowLength: 10,
            customizeText: function() {
                return this.valueText + " - " + this.argumentText + " (" + this.percentText + ")";
            }
        },
        customizePoint: function (point) {
            if (point.argument.indexOf('active+clean') >= 0) {
                return {
                    color: '#62c462'
                }
            } else if (point.argument.indexOf('active') >= 0) {
                return {
                    color: '#f89406'
                }
            } else {
                return {
                    color: '#ee5f5b'
                }
            }
        },
        size: {
            height: 350,
            width: 315
        },
        legend: {
            visible: false
        },
        series: [{
            type: "doughnut",
            argumentField: "state_name",
            valueField: "count",
            label: {
                visible: false,
            }
        }]
    };
    // }}}

    // Convert bytes to human readable form {{{
    function fmtBytes(bytes) {
        if (bytes==0) { return "0 bytes"; }
        var s = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
        var e = Math.floor(Math.log(bytes) / Math.log(1024));
        return (bytes / Math.pow(1024, e)).toFixed(2) + " " + s[e];
    }
    // }}}

    // MAKE SECTION COLLAPSABLE {{{
    $('.cd-collapsable').on("click", function (e) {
        if ($(this).hasClass('cd-collapsed')) {
            // expand the panel
            $(this).parents('.panel').find('.panel-body').slideDown();
            $(this).removeClass('cd-collapsed');
        }
        else {
            // collapse the panel
            $(this).parents('.panel').find('.panel-body').slideUp();
            $(this).addClass('cd-collapsed');
        }
    });
    // }}}

    // GENERIC AJAX WRAPER {{{
    function ajaxCall(url, callback) {
        $.ajax({
          url: url,
          dataType: 'json',
          type: 'GET',
          data: null,
          contentType: 'application/json',
          success: callback,
          complete: function() {
            setTimeout(worker, 5000);
          }
        });
    }
    // }}}

    // CREATE A ALERT MESSAGE {{{
    function message(severity, msg) {
        if (severity == 'success') { icon = 'ok' }
        if (severity == 'warning') { icon = 'flash' }
        if (severity == 'danger') { icon = 'remove' }
        return '
 ' + msg + '
';
    }
    // }}}

    // CREATE PANEL {{{
    function panel(severity, titel, message) {
        tmp = '
';
        tmp = tmp + '
' + titel + '
';
        tmp = tmp + '
';
        tmp = tmp + '
' + message + '
';
        tmp = tmp + '
';
        tmp = tmp + '
';
        return tmp;
    }
    // }}}

    // MAPPING CEPH TO BOOTSTRAP {{{
    var ceph2bootstrap = {
        HEALTH_OK: 'success',
        HEALTH_WARN: 'warning',
        HEALTH_ERR: 'danger'
    }
    // }}}

    // INITIALIZE EMPTY PIE CHART {{{
    $("#pg_status").dxPieChart($.extend(true, {}, chart_options, {
        dataSource: []
    }));
    // }}}

    // WORKER FUNCTION (UPDATED) {{{
    function worker() {
        callback = function(data, status, xhr) {
            // Update cluster fsid
            $("#cluster_fsid").html(data['fsid']);

            // load all relevant data from retrieved json {{{
            // ----------------------------------------------------------------
            // *storage capacity*
            bytesTotal = data['pgmap']['bytes_total'];
            bytesUsed = data['pgmap']['bytes_used'];
            percentUsed = Math.round((bytesUsed / bytesTotal) * 100);

            // *placement groups*
            pgsByState = data['pgmap']['pgs_by_state'];
            numPgs = data['pgmap']['num_pgs'];

            // *recovery status*
            recoverBytes = data['pgmap']['recovering_bytes_per_sec'];
            recoverKeys = data['pgmap']['recovering_keys_per_sec'];
            recoverObjects = data['pgmap']['recovering_objects_per_sec'];

            // *throughput*
            opsPerSec = data['pgmap']['op_per_sec'] || 0;
            writesPerSec = fmtBytes(data['pgmap']['write_bytes_sec'] || 0);
            readsPerSec = fmtBytes(data['pgmap']['read_bytes_sec'] || 0);

            // *osd state*
            numOSDtotal = data['osdmap']['osdmap']['num_osds'] || 0;
            numOSDin = data['osdmap']['osdmap']['num_in_osds'] || 0;
            numOSDup = data['osdmap']['osdmap']['num_up_osds'] || 0;
            numOSDunhealthy = data['osdmap']['osdmap']['num_osds'] - data['osdmap']['osdmap']['num_up_osds'] || 0;
            osdFull = data['osdmap']['osdmap']['full'];
            osdNearFull = data['osdmap']['osdmap']['nearfull'];

            // *overall status*
            clusterStatusOverall = data['health']['overall_status'];
            clusterHealthSummary = data['health']['summary'];

            // *monitor state*
            monmapMons = data['monmap']['mons'];
            timechekMons = data['health']['timechecks']['mons'];
            // }}}

            // Update Content {{{
            // ----------------------------------------------------------------
            // update storage capacity
            $("#utilization").dxCircularGauge($.extend(true, {}, gauge_options, {
                value: percentUsed
            }));
            $("#utilization_info").html(fmtBytes(bytesUsed) + " / " + fmtBytes(bytesTotal) + " (" + percentUsed + "%)");

            // update placement group chart
            var chart = $("#pg_status").dxPieChart("instance");
            chart.option('dataSource', pgsByState);

            $("#pg_status_info").html(numPgs + "  placementgroups in cluster");

            // update recovering status
            if (typeof(recoverBytes) != 'undefined') {
                $("#recovering_bytes").html(panel('warning', 'Recovering bytes / second', fmtBytes(recoverBytes)));
            } else {
                $("#recovering_bytes").empty();
            }
            if (typeof(recoverKeys) != 'undefined') {
                $("#recovering_keys").html(panel('warning', 'Recovering keys / second', recoverKeys));
            } else {
                $("#recovering_keys").empty();
            }
            if (typeof(recoverObjects) != 'undefined') {
                $("#recovering_objects").html(panel('warning', 'Recovering objects / second', recoverObjects));
            } else {
                 $("#recovering_objects").empty();
            }

            // update current throughput values
            $("#operations_per_second").html(opsPerSec);
            $("#write_bytes").html(writesPerSec);
            $("#read_bytes").html(readsPerSec);

            // update OSD states
            $("#num_osds").html(numOSDtotal);
            $("#num_in_osds").html(numOSDin);
            $("#num_up_osds").html(numOSDup);
            $("#unhealthy_osds").html(numOSDunhealthy);

            // update osd full / nearfull warnings
            $("#osd_warning").empty();
            if (osdFull == "true") {
                $("#osd_warning").append(message('danger', 'OSD FULL ERROR'));
            }
            if (osdNearFull == "true") {
                $("#osd_warning").append(message('warning', 'OSD NEARFULL WARNING'));
            }

            // update overall cluster state
            $("#overall_status").empty();
            $("#overall_status").append(message(ceph2bootstrap[clusterStatusOverall], 'Cluster Status:' + clusterStatusOverall));

            // update overall cluster status details
            $("#overall_status").append('
');
            $.each(clusterHealthSummary, function(index, obj) {
                $("#overall_status").append('
' + obj['summary'] + '
');
            });
            $("#overall_status").append('
');

            // update monitor status
            $("#monitor_status").empty();
            $.each(monmapMons, function(index, mon) {
                health = 'HEALTH_ERR'
                $.each(timechekMons, function(index, mon_health) {
                    if (mon['name'] == mon_health['name']) {
                        health = mon_health['health'];
                    }
                });
                msg = 'Monitor ' + mon['name'].toUpperCase() + ': ' + health;
                $("#monitor_status").append('
' + message(ceph2bootstrap[health], msg) + '
');
            });

            // update graphite if available
            $.each(config.graphite.metrics, function(index, metric) {
                updatePlot(index + 1, config.graphite.url, metric.targets, metric.from, metric.labels, metric.colors, metric.mode);
            });
            // }}}
        }

        ajaxCall(window.location.pathname, callback);
    };
    worker();
    // }}}
})

// vim: set foldmethod=marker foldlevel=0 ts=4 sts=4 filetype=javascript fileencoding=utf-8 formatoptions+=ro expandtab:
<commit_msg>only try to gather graphite metrics if enabled<commit_after>$(function () {
    // Gauge chart configuration options {{{
    var gauge_options = {
        palette: 'Soft Pastel',
        animation: {
            enabled: false
        },
        valueIndicator: {
            type: 'triangleNeedle',
            color: '#7a8288'
        },
        title: {
             text: 'Cluster storage utilization',
             font: { size: 18, color: '#c8c8c8', family: 'Helvetica' },
             position: 'bottom-center'
        },
        geometry: {
            startAngle: 180,
            endAngle: 0
        },
        margin: {
            top: 0,
            right: 10
        },
        rangeContainer: {
            ranges: [
                { startValue: 0, endValue: 60, color: '#62c462' },
                { startValue: 60, endValue: 80, color: '#f89406' },
                { startValue: 80, endValue: 100, color: '#ee5f5b' }
            ]
        },
        scale: {
            startValue: 0,
            endValue: 100,
            majorTick: {
                tickInterval: 20
            },
            label: {
                customizeText: function (arg) {
                    return arg.valueText + ' %';
                }
            }
        }
    };
    // }}}

    // Graphite to flot configuration options {{{
    var flot_options = {
        grid: {
            show: true
        },
        xaxis: {
            tickFormatter: function() { return ""; }
        },
        legend: {
            show: true
        },
        yaxis: {
            //tickFormatter: function() { return ""; }
            min: 0,
        }
    }

    // TODO: Test more graphs
    function updatePlot(index, graphite_url, targets, from, labels, colors, mode) {
        combined_targets = "";
        $.each(targets, function(index, target) {
            combined_targets += "&target=" + target;
        });
        var query_url = graphite_url + "/render?format=json&from=" + from + combined_targets;

        var series = [ ];
        $.getJSON(query_url, function(targets) {
            if (targets.length > 0) {
                $.each(targets, function(index, target) {
                    var datapoints = target.datapoints;
                    var xzero = datapoints[0][1];
                    var data = $.map(target.datapoints, function(value) {
                    if (value[0] === null) return null;
                        return [[ value[1]-xzero, value[0] ]];
                    });

                    // replace null value with previous item value
                    for (var i = 0; i < data.length; i++) {
                        if (i > 0 && data[i] === null) data[i] = data[-i];
                    }

                    series.push({
                        data: data,
                        label: labels[index],
                        lines: { fill: true }
                    });
                });
                // update plot
                if (typeof mode != undefined) {
                    flot_options.yaxis.mode = mode
                }
                if (typeof color != undefined) {
                    flot_options.colors = colors
                }
                $.plot("#graphite" + index, series, flot_options);
            }
        });
    }
    // }}}

    // Pie chart configuration options {{{
    var chart_options = {
        animation: {
            enabled: false
        },
        tooltip: {
            enabled: true,
            format:"decimal",
            percentPrecision: 2,
            font: { size: 14, color: '#1c1e22', family: 'Helvetica' },
            arrowLength: 10,
            customizeText: function() {
                return this.valueText + " - " + this.argumentText + " (" + this.percentText + ")";
            }
        },
        customizePoint: function (point) {
            if (point.argument.indexOf('active+clean') >= 0) {
                return {
                    color: '#62c462'
                }
            } else if (point.argument.indexOf('active') >= 0) {
                return {
                    color: '#f89406'
                }
            } else {
                return {
                    color: '#ee5f5b'
                }
            }
        },
        size: {
            height: 350,
            width: 315
        },
        legend: {
            visible: false
        },
        series: [{
            type: "doughnut",
            argumentField: "state_name",
            valueField: "count",
            label: {
                visible: false,
            }
        }]
    };
    // }}}

    // Convert bytes to human readable form {{{
    function fmtBytes(bytes) {
        if (bytes==0) { return "0 bytes"; }
        var s = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
        var e = Math.floor(Math.log(bytes) / Math.log(1024));
        return (bytes / Math.pow(1024, e)).toFixed(2) + " " + s[e];
    }
    // }}}

    // MAKE SECTION COLLAPSABLE {{{
    $('.cd-collapsable').on("click", function (e) {
        if ($(this).hasClass('cd-collapsed')) {
            // expand the panel
            $(this).parents('.panel').find('.panel-body').slideDown();
            $(this).removeClass('cd-collapsed');
        }
        else {
            // collapse the panel
            $(this).parents('.panel').find('.panel-body').slideUp();
            $(this).addClass('cd-collapsed');
        }
    });
    // }}}

    // GENERIC AJAX WRAPER {{{
    function ajaxCall(url, callback) {
        $.ajax({
          url: url,
          dataType: 'json',
          type: 'GET',
          data: null,
          contentType: 'application/json',
          success: callback,
          complete: function() {
            setTimeout(worker, 5000);
          }
        });
    }
    // }}}

    // CREATE A ALERT MESSAGE {{{
    function message(severity, msg) {
        if (severity == 'success') { icon = 'ok' }
        if (severity == 'warning') { icon = 'flash' }
        if (severity == 'danger') { icon = 'remove' }
        return '
 ' + msg + '
';
    }
    // }}}

    // CREATE PANEL {{{
    function panel(severity, titel, message) {
        tmp = '
';
        tmp = tmp + '
' + titel + '
';
        tmp = tmp + '
';
        tmp = tmp + '
' + message + '
';
        tmp = tmp + '
';
        tmp = tmp + '
';
        return tmp;
    }
    // }}}

    // MAPPING CEPH TO BOOTSTRAP {{{
    var ceph2bootstrap = {
        HEALTH_OK: 'success',
        HEALTH_WARN: 'warning',
        HEALTH_ERR: 'danger'
    }
    // }}}

    // INITIALIZE EMPTY PIE CHART {{{
    $("#pg_status").dxPieChart($.extend(true, {}, chart_options, {
        dataSource: []
    }));
    // }}}

    // WORKER FUNCTION (UPDATED) {{{
    function worker() {
        callback = function(data, status, xhr) {
            // Update cluster fsid
            $("#cluster_fsid").html(data['fsid']);

            // load all relevant data from retrieved json {{{
            // ----------------------------------------------------------------
            // *storage capacity*
            bytesTotal = data['pgmap']['bytes_total'];
            bytesUsed = data['pgmap']['bytes_used'];
            percentUsed = Math.round((bytesUsed / bytesTotal) * 100);

            // *placement groups*
            pgsByState = data['pgmap']['pgs_by_state'];
            numPgs = data['pgmap']['num_pgs'];

            // *recovery status*
            recoverBytes = data['pgmap']['recovering_bytes_per_sec'];
            recoverKeys = data['pgmap']['recovering_keys_per_sec'];
            recoverObjects = data['pgmap']['recovering_objects_per_sec'];

            // *throughput*
            opsPerSec = data['pgmap']['op_per_sec'] || 0;
            writesPerSec = fmtBytes(data['pgmap']['write_bytes_sec'] || 0);
            readsPerSec = fmtBytes(data['pgmap']['read_bytes_sec'] || 0);

            // *osd state*
            numOSDtotal = data['osdmap']['osdmap']['num_osds'] || 0;
            numOSDin = data['osdmap']['osdmap']['num_in_osds'] || 0;
            numOSDup = data['osdmap']['osdmap']['num_up_osds'] || 0;
            numOSDunhealthy = data['osdmap']['osdmap']['num_osds'] - data['osdmap']['osdmap']['num_up_osds'] || 0;
            osdFull = data['osdmap']['osdmap']['full'];
            osdNearFull = data['osdmap']['osdmap']['nearfull'];

            // *overall status*
            clusterStatusOverall = data['health']['overall_status'];
            clusterHealthSummary = data['health']['summary'];

            // *monitor state*
            monmapMons = data['monmap']['mons'];
            timechekMons = data['health']['timechecks']['mons'];
            // }}}

            // Update Content {{{
            // ----------------------------------------------------------------
            // update storage capacity
            $("#utilization").dxCircularGauge($.extend(true, {}, gauge_options, {
                value: percentUsed
            }));
            $("#utilization_info").html(fmtBytes(bytesUsed) + " / " + fmtBytes(bytesTotal) + " (" + percentUsed + "%)");

            // update placement group chart
            var chart = $("#pg_status").dxPieChart("instance");
            chart.option('dataSource', pgsByState);

            $("#pg_status_info").html(numPgs + "  placementgroups in cluster");

            // update recovering status
            if (typeof(recoverBytes) != 'undefined') {
                $("#recovering_bytes").html(panel('warning', 'Recovering bytes / second', fmtBytes(recoverBytes)));
            } else {
                $("#recovering_bytes").empty();
            }
            if (typeof(recoverKeys) != 'undefined') {
                $("#recovering_keys").html(panel('warning', 'Recovering keys / second', recoverKeys));
            } else {
                $("#recovering_keys").empty();
            }
            if (typeof(recoverObjects) != 'undefined') {
                $("#recovering_objects").html(panel('warning', 'Recovering objects / second', recoverObjects));
            } else {
                 $("#recovering_objects").empty();
            }

            // update current throughput values
            $("#operations_per_second").html(opsPerSec);
            $("#write_bytes").html(writesPerSec);
            $("#read_bytes").html(readsPerSec);

            // update OSD states
            $("#num_osds").html(numOSDtotal);
            $("#num_in_osds").html(numOSDin);
            $("#num_up_osds").html(numOSDup);
            $("#unhealthy_osds").html(numOSDunhealthy);

            // update osd full / nearfull warnings
            $("#osd_warning").empty();
            if (osdFull == "true") {
                $("#osd_warning").append(message('danger', 'OSD FULL ERROR'));
            }
            if (osdNearFull == "true") {
                $("#osd_warning").append(message('warning', 'OSD NEARFULL WARNING'));
            }

            // update overall cluster state
            $("#overall_status").empty();
            $("#overall_status").append(message(ceph2bootstrap[clusterStatusOverall], 'Cluster Status:' + clusterStatusOverall));

            // update overall cluster status details
            $("#overall_status").append('
');
            $.each(clusterHealthSummary, function(index, obj) {
                $("#overall_status").append('
' + obj['summary'] + '
');
            });
            $("#overall_status").append('
');

            // update monitor status
            $("#monitor_status").empty();
            $.each(monmapMons, function(index, mon) {
                health = 'HEALTH_ERR'
                $.each(timechekMons, function(index, mon_health) {
                    if (mon['name'] == mon_health['name']) {
                        health = mon_health['health'];
                    }
                });
                msg = 'Monitor ' + mon['name'].toUpperCase() + ': ' + health;
                $("#monitor_status").append('
' + message(ceph2bootstrap[health], msg) + '
');
            });

            if ($('#graphite1').length > 0) {
                // update graphite if available
                $.each(config.graphite.metrics, function(index, metric) {
                    updatePlot(index + 1, config.graphite.url, metric.targets, metric.from, metric.labels, metric.colors, metric.mode);
                });
            }
            // }}}
        }

        ajaxCall(window.location.pathname, callback);
    };
    worker();
    // }}}
})

// vim: set foldmethod=marker foldlevel=0 ts=4 sts=4 filetype=javascript fileencoding=utf-8 formatoptions+=ro expandtab:
<|endoftext|>


<commit_before>/* global LinearGauge:false RadialGauge:false */
$(function() {
  function handleGetResponseResHourly(data) {
    var blank_val, html, table, level_row, flow_row;
    blank_val = (' '.repeat(10) + '--').slice(-10);
    html = $.parseHTML(data.replace(/<img[^>]+>/gi, ''));
    table = $('div.content_left_column table:has(tr:nth-child(14):last-child:has(td:nth-child(15):last-child))', html);
    level_row = $('tr:has(td:nth-child(2):not(:contains(' + blank_val + ')))', table).last();
    flow_row = $('tr:has(td:nth-child(8):not(:contains(' + blank_val + '))):has(td:nth-child(10):not(:contains(' + blank_val + ')))', table).last();
    draw_gauges({
      'title': {
        'level': format_date_title($('td:nth-child(1)', level_row).text()),
        'flow': format_date_title($('td:nth-child(1)', flow_row).text())},
      'value': {
        'level': parseFloat($('td:nth-child(2)', level_row).text()),
        'inflow': parseInt($('td:nth-child(8)', flow_row).text()),
        'outflow': parseInt($('td:nth-child(6)', flow_row).text())}});
  }

  function range(start, stop, step) {
    var a, b;
    a=[start];
    b=start;
    while(b < stop) {
      b += step;
      a.push(b);
    }
    return a;
  }

  function ticks(max_val) {
    // Dynamically adjust tick size to leave gauge readable.
    var vals, order, val;
    vals = [
      {flow: 8, ticks: {major: 1, minor: 0.5}},
      {flow: 4, ticks: {major: 1, minor: 0.2}},
      {flow: 2, ticks: {major: 0.5, minor: 0.1}},
      {flow: 1, ticks: {major: 0.25, minor: 0.05}},
      {flow: 0, ticks: {major: 0.1, minor: 0.05}}
    ];
    order = Math.floor((Math.log(max_val) / Math.LN10) + 0.000000001);
    for (i = 0; i < vals.length; i++) {
      if ((max_val / Math.pow(10, order)) >= vals[i]['flow']) {
        val = vals[i];
        break;
      }
    }
    val['ticks']['major'] *= Math.pow(10, order);
    val['ticks']['minor'] *= Math.pow(10, order);
    return val['ticks'];
  }

  function max_flow(inflow_val, outflow_val) {
    // Dynamically set gauge max to next major tick.
    var max_val, tick;
    max_val = Math.max(inflow_val, outflow_val, 1);
    tick = ticks(max_val)['major'];
    if ((Math.floor(max_val / tick) * tick) == max_val) {
      // At a tick mark already, leave as-as.
      return max_val;
    }
    // Next major tick.
    return ((Math.floor(max_val / tick) + 1) * tick);
  }

  function format_date_title(date_str) {
    var d, mon, hrs, ampm;
    d = new Date(date_str);
    mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
    hrs = (d.getHours() + 12) % 12 || 12;
    ampm = (d.getHours() >= 12) ? 'pm' : 'am';
    return (mon + ' ' + d.getDate() + ' ' + hrs + ampm);
  }

  function draw_gauges(data) {
    var max_flow_val, level_gauge, inflow_gauge, outflow_gauge;
    max_flow_val = max_flow(data['value']['inflow'], data['value']['outflow']);
    $('#level-title').text('Lake Level, ' + data['title']['level']);
    $('#inflow-title').text('Inflow, ' + data['title']['flow']);
    $('#outflow-title').text('Outflow, ' + data['title']['flow']);
    level_gauge = new LinearGauge({
      renderTo: 'level-gauge',
      width: 180,
      height: 311,
      units: 'Feet',
      minValue: 600,
      maxValue: 925,
      exactTicks: true,
      majorTicks: range(600, 900, 50).concat(925),
      minorTicks: 10,
      borderShadowWidth: 0,
      borders: false,
      animationDuration: 2000,
      animationRule: 'dequint',
      needleSide: 'left',
      colorBarProgress: '#0099cc',
      colorBar: '#ffffff',
      barBeginCircle: false,
      fontValueSize: 16,
      highlights: [
        {
          from: 850,
          to: 870,
          color: 'rgba(255, 255, 0, .75)'
        }, {
          from: 870,
          to: 885,
          color: 'rgba(255, 127, 0, .75)'
        }, {
          from: 885,
          to: 901,
          color: 'rgba(200, 0, 0, .75)'
        }, {
          from: 901,
          to: 920,
          color: 'rgba(100, 100, 100, .75)'
        }
      ]
    }).draw();
    inflow_gauge = new RadialGauge({
      renderTo: 'inflow-gauge',
      width: 170,
      height: 170,
      units: 'cfps',
      minValue: 0,
      maxValue: max_flow(data['value']['inflow'], data['value']['outflow']),
      exactTicks: true,
      majorTicks: range(0, max_flow_val, ticks(max_flow_val)['major']),
      minorTicks: ticks(max_flow_val)['minor'],
      borderShadowWidth: 0,
      borders: false,
      animationDuration: 2000,
      animationRule: 'dequint',
      valueBoxWidth: 32,
      valueDec: 0,
      fontValueSize: 32,
      highlights: []
    }).draw();
    outflow_gauge = new RadialGauge({
      renderTo: 'outflow-gauge',
      width: 170,
      height: 170,
      units: 'cfps',
      minValue: 0,
      maxValue: max_flow_val,
      exactTicks: true,
      majorTicks: range(0, max_flow_val, ticks(max_flow_val)['major']),
      minorTicks: ticks(max_flow_val)['minor'],
      borderShadowWidth: 0,
      borders: false,
      animationDuration: 2000,
      animationRule: 'dequint',
      valueBoxWidth: 32,
      valueDec: 0,
      fontValueSize: 32,
      highlights: []
    }).draw();
    // Set values after drawing to cause animation.
    level_gauge.value = data['value']['level'];
    inflow_gauge.value = data['value']['inflow'];
    outflow_gauge.value = data['value']['outflow'];
  }

  jQuery(document).ready(function(){
    var CORSURLPrefix, url;
    CORSURLPrefix = 'https://cors-anywhere.herokuapp.com/';
    url = 'http://cdec.water.ca.gov/cgi-progs/queryF?ORO';
    $.get(CORSURLPrefix + url, handleGetResponseResHourly);
  });
});
<commit_msg>Fix, missing declarion on loop iterator var.<commit_after>/* global LinearGauge:false RadialGauge:false */
$(function() {
  function handleGetResponseResHourly(data) {
    var blank_val, html, table, level_row, flow_row;
    blank_val = (' '.repeat(10) + '--').slice(-10);
    html = $.parseHTML(data.replace(/<img[^>]+>/gi, ''));
    table = $('div.content_left_column table:has(tr:nth-child(14):last-child:has(td:nth-child(15):last-child))', html);
    level_row = $('tr:has(td:nth-child(2):not(:contains(' + blank_val + ')))', table).last();
    flow_row = $('tr:has(td:nth-child(8):not(:contains(' + blank_val + '))):has(td:nth-child(10):not(:contains(' + blank_val + ')))', table).last();
    draw_gauges({
      'title': {
        'level': format_date_title($('td:nth-child(1)', level_row).text()),
        'flow': format_date_title($('td:nth-child(1)', flow_row).text())},
      'value': {
        'level': parseFloat($('td:nth-child(2)', level_row).text()),
        'inflow': parseInt($('td:nth-child(8)', flow_row).text()),
        'outflow': parseInt($('td:nth-child(6)', flow_row).text())}});
  }

  function range(start, stop, step) {
    var a, b;
    a=[start];
    b=start;
    while(b < stop) {
      b += step;
      a.push(b);
    }
    return a;
  }

  function ticks(max_val) {
    // Dynamically adjust tick size to leave gauge readable.
    var vals, order, val;
    vals = [
      {flow: 8, ticks: {major: 1, minor: 0.5}},
      {flow: 4, ticks: {major: 1, minor: 0.2}},
      {flow: 2, ticks: {major: 0.5, minor: 0.1}},
      {flow: 1, ticks: {major: 0.25, minor: 0.05}},
      {flow: 0, ticks: {major: 0.1, minor: 0.05}}
    ];
    order = Math.floor((Math.log(max_val) / Math.LN10) + 0.000000001);
    for (var i = 0; i < vals.length; i++) {
      if ((max_val / Math.pow(10, order)) >= vals[i]['flow']) {
        val = vals[i];
        break;
      }
    }
    val['ticks']['major'] *= Math.pow(10, order);
    val['ticks']['minor'] *= Math.pow(10, order);
    return val['ticks'];
  }

  function max_flow(inflow_val, outflow_val) {
    // Dynamically set gauge max to next major tick.
    var max_val, tick;
    max_val = Math.max(inflow_val, outflow_val, 1);
    tick = ticks(max_val)['major'];
    if ((Math.floor(max_val / tick) * tick) == max_val) {
      // At a tick mark already, leave as-as.
      return max_val;
    }
    // Next major tick.
    return ((Math.floor(max_val / tick) + 1) * tick);
  }

  function format_date_title(date_str) {
    var d, mon, hrs, ampm;
    d = new Date(date_str);
    mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
    hrs = (d.getHours() + 12) % 12 || 12;
    ampm = (d.getHours() >= 12) ? 'pm' : 'am';
    return (mon + ' ' + d.getDate() + ' ' + hrs + ampm);
  }

  function draw_gauges(data) {
    var max_flow_val, level_gauge, inflow_gauge, outflow_gauge;
    max_flow_val = max_flow(data['value']['inflow'], data['value']['outflow']);
    $('#level-title').text('Lake Level, ' + data['title']['level']);
    $('#inflow-title').text('Inflow, ' + data['title']['flow']);
    $('#outflow-title').text('Outflow, ' + data['title']['flow']);
    level_gauge = new LinearGauge({
      renderTo: 'level-gauge',
      width: 180,
      height: 311,
      units: 'Feet',
      minValue: 600,
      maxValue: 925,
      exactTicks: true,
      majorTicks: range(600, 900, 50).concat(925),
      minorTicks: 10,
      borderShadowWidth: 0,
      borders: false,
      animationDuration: 2000,
      animationRule: 'dequint',
      needleSide: 'left',
      colorBarProgress: '#0099cc',
      colorBar: '#ffffff',
      barBeginCircle: false,
      fontValueSize: 16,
      highlights: [
        {
          from: 850,
          to: 870,
          color: 'rgba(255, 255, 0, .75)'
        }, {
          from: 870,
          to: 885,
          color: 'rgba(255, 127, 0, .75)'
        }, {
          from: 885,
          to: 901,
          color: 'rgba(200, 0, 0, .75)'
        }, {
          from: 901,
          to: 920,
          color: 'rgba(100, 100, 100, .75)'
        }
      ]
    }).draw();
    inflow_gauge = new RadialGauge({
      renderTo: 'inflow-gauge',
      width: 170,
      height: 170,
      units: 'cfps',
      minValue: 0,
      maxValue: max_flow(data['value']['inflow'], data['value']['outflow']),
      exactTicks: true,
      majorTicks: range(0, max_flow_val, ticks(max_flow_val)['major']),
      minorTicks: ticks(max_flow_val)['minor'],
      borderShadowWidth: 0,
      borders: false,
      animationDuration: 2000,
      animationRule: 'dequint',
      valueBoxWidth: 32,
      valueDec: 0,
      fontValueSize: 32,
      highlights: []
    }).draw();
    outflow_gauge = new RadialGauge({
      renderTo: 'outflow-gauge',
      width: 170,
      height: 170,
      units: 'cfps',
      minValue: 0,
      maxValue: max_flow_val,
      exactTicks: true,
      majorTicks: range(0, max_flow_val, ticks(max_flow_val)['major']),
      minorTicks: ticks(max_flow_val)['minor'],
      borderShadowWidth: 0,
      borders: false,
      animationDuration: 2000,
      animationRule: 'dequint',
      valueBoxWidth: 32,
      valueDec: 0,
      fontValueSize: 32,
      highlights: []
    }).draw();
    // Set values after drawing to cause animation.
    level_gauge.value = data['value']['level'];
    inflow_gauge.value = data['value']['inflow'];
    outflow_gauge.value = data['value']['outflow'];
  }

  jQuery(document).ready(function(){
    var CORSURLPrefix, url;
    CORSURLPrefix = 'https://cors-anywhere.herokuapp.com/';
    url = 'http://cdec.water.ca.gov/cgi-progs/queryF?ORO';
    $.get(CORSURLPrefix + url, handleGetResponseResHourly);
  });
});
<|endoftext|>


<commit_before>if (jQuery) {
    jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function (arg) {
        return function (elem) {
            return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
        };
    });
}

var erljs = {};

erljs.guid = function () {
    var ss4 = function () {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    };
    var S4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
};
erljs.xxxx = function () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : r & 0x3 | 0x8;
        return v.toString(16);
    });
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.uriToObject = function (search) {
    return search ? JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g, '":"') + '"}',
        function (key, value) {
            return key === "" ? value : decodeURIComponent(value)
        }) : {}
};

erljs.QueryStringToJSON = function (query) {
    query = query || window.location.search.slice(1);
    var pairs = query.split('&'), result = {};
    pairs.forEach(function (pair) {
        pair = pair.split('=');
        result[pair[0]] = decodeURIComponent(pair[1] || '');
    });
    return JSON.parse(JSON.stringify(result));
};

erljs.serialize = function(obj, prefix) {
  var str = [];
  for(var p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push(typeof v == "object" ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.shuffle = {
    fisher_yates: function (array) {
        var m = array.length, t, i;
        while (m) {
            i = Math.floor(Math.random() * m--);
            t = array[m];
            array[m] = array[i];
            array[i] = t;
        }
    },

    naive_swap: function (array) {
        var n = array.length, i = -1, j;
        while (++i < n) {
            j = Math.floor(Math.random() * n);
            t = array[j];
            array[j] = array[i];
            array[i] = t;
        }
    },

    naive_swap_random: function (array) {
        var n = array.length, i = -1, j, k;
        while (++i < n) {
            j = Math.floor(Math.random() * n);
            k = Math.floor(Math.random() * n);
            t = array[j];
            array[j] = array[k];
            array[k] = t;
        }
    },

    sort_random: function (array) {
        array.sort(function () {
            return Math.random() - .5;
        });
    },

    order_random: function (array) {
        var random = array.map(Math.random);
        array.sort(function (a, b) {
            return random[a] - random[b];
        });
    },

    //+ Jonas Raoni Soares Silva
    //@ http://jsfromhell.com/array/shuffle [v1.0]
    google: function (o) { //v1.0
        for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
        return o;
    }
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.getOriginalOfImg = function (img_element) {
    var native = img_element.get(0);
    var width = native.naturalWidth, height = native.naturalHeight;
    if (width && height) {
        return {width: width, height: height}
    } else {
        var t = new Image();
        t.src = (img_element.attr ? img_element.attr("src") : false) || img_element.src;
        return {width: t.width, height: t.height}
    }
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// makeClass - By John Resig (MIT Licensed)
erljs.makeClass = function () {
    return function (args) {
        if (this instanceof arguments.callee) {
            if (typeof this.init == "function")
                this.init.apply(this, args.callee ? args : arguments);
        } else
            return new arguments.callee(arguments);
    };
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.csrf = {
    csrfSafeMethod: function (method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    },
    sameOrigin: function (url) {
        // test that a given url is a same-origin URL
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    },

    getCookie: function (name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.range = function (start, stop, step) {
    if (typeof stop == 'undefined') {
        // one param defined
        stop = start;
        start = 0;
    }
    if (typeof step == 'undefined') {
        step = 1;
    }
    if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
        return [];
    }
    var result = [];
    for (var i = start; step > 0 ? i < stop : i > stop; i += step) {
        result.push(i);
    }
    return result;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// formatString('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');
erljs.formatString = function (format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function (match, number) {
        return typeof args[number] != 'undefined'
            ? args[number]
            : match
            ;
    });
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.style = {
//http://stackoverflow.com/questions/754607/can-jquery-get-all-css-styles-associated-with-an-element
//Pass a jQuery object into css() and it will return an object, which you can then plug back into jQuery's $().css(), ex:
//
//var style = css($("#elementToGetAllCSS"));
//$("#elementToPutStyleInto").css(style);

    css: function (a) {
        var sheets = document.styleSheets, o = {};
        for (var i in sheets) {
            var rules = sheets[i].rules || sheets[i].cssRules;
            for (var r in rules) {
                if (a.is(rules[r].selectorText)) {
                    o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
                }
            }
        }
        return o;
    },

    css2json: function (css) {
        var s = {};
        if (!css) return s;
        if (css instanceof CSSStyleDeclaration) {
            for (var i in css) {
                if ((css[i]).toLowerCase) {
                    s[(css[i]).toLowerCase()] = (css[css[i]]);
                }
            }
        } else if (typeof css == "string") {
            css = css.split("; ");
            for (var i in css) {
                var l = css[i].split(": ");
                s[l[0].toLowerCase()] = (l[1]);
            }
        }
        return s;
    }
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////

self.erljs = erljs;
<commit_msg>Update erl-utils.js<commit_after>if (jQuery) {
    jQuery.expr[":"].Contains = jQuery.expr.createPseudo(function (arg) {
        return function (elem) {
            return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
        };
    });
}

var erljs = {};

erljs.guid = function () {
    var ss4 = function () {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    };
    var S4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
};
erljs.xxxx = function () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : r & 0x3 | 0x8;
        return v.toString(16);
    });
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.uriToObject = function (search) {
    return search ? JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g, '":"') + '"}',
        function (key, value) {
            return key === "" ? value : decodeURIComponent(value)
        }) : {}
};

erljs.QueryStringToJSON = function (query) {
    query = query || window.location.search.slice(1);
    var pairs = query.split('&'), result = {};
    pairs.forEach(function (pair) {
        pair = pair.split('=');
        result[pair[0]] = decodeURIComponent(pair[1] || '');
    });
    return JSON.parse(JSON.stringify(result));
};

erljs.uriToObjectNormal = function (data) {
    var splits = decodeURIComponent(data).split('&'),
        i = 0,
        key = null,
        split = null,
        value = null,
        splitParts = null;

    var kv = {};
    while (split = splits[i++]) {
        splitParts = split.split('=');
        key = splitParts[0] || '';
        value = (splitParts[1] || '').replace(/\+/g, ' ');

        if (key != '') {
            if (key in kv) {
                if ($.type(kv[key]) !== 'array')
                    kv[key] = [kv[key]];

                kv[key].push(value);
            } else
                kv[key] = value;
        }
    }
    return kv;
};

erljs.serialize = function(obj, prefix) {
  var str = [];
  for(var p in obj) {
    if (obj.hasOwnProperty(p)) {
      var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
      str.push(typeof v == "object" ?
        serialize(v, k) :
        encodeURIComponent(k) + "=" + encodeURIComponent(v));
    }
  }
  return str.join("&");
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.shuffle = {
    fisher_yates: function (array) {
        var m = array.length, t, i;
        while (m) {
            i = Math.floor(Math.random() * m--);
            t = array[m];
            array[m] = array[i];
            array[i] = t;
        }
    },

    naive_swap: function (array) {
        var n = array.length, i = -1, j;
        while (++i < n) {
            j = Math.floor(Math.random() * n);
            t = array[j];
            array[j] = array[i];
            array[i] = t;
        }
    },

    naive_swap_random: function (array) {
        var n = array.length, i = -1, j, k;
        while (++i < n) {
            j = Math.floor(Math.random() * n);
            k = Math.floor(Math.random() * n);
            t = array[j];
            array[j] = array[k];
            array[k] = t;
        }
    },

    sort_random: function (array) {
        array.sort(function () {
            return Math.random() - .5;
        });
    },

    order_random: function (array) {
        var random = array.map(Math.random);
        array.sort(function (a, b) {
            return random[a] - random[b];
        });
    },

    //+ Jonas Raoni Soares Silva
    //@ http://jsfromhell.com/array/shuffle [v1.0]
    google: function (o) { //v1.0
        for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
        return o;
    }
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.getOriginalOfImg = function (img_element) {
    var native = img_element.get(0);
    var width = native.naturalWidth, height = native.naturalHeight;
    if (width && height) {
        return {width: width, height: height}
    } else {
        var t = new Image();
        t.src = (img_element.attr ? img_element.attr("src") : false) || img_element.src;
        return {width: t.width, height: t.height}
    }
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// makeClass - By John Resig (MIT Licensed)
erljs.makeClass = function () {
    return function (args) {
        if (this instanceof arguments.callee) {
            if (typeof this.init == "function")
                this.init.apply(this, args.callee ? args : arguments);
        } else
            return new arguments.callee(arguments);
    };
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.csrf = {
    csrfSafeMethod: function (method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    },
    sameOrigin: function (url) {
        // test that a given url is a same-origin URL
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    },

    getCookie: function (name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.range = function (start, stop, step) {
    if (typeof stop == 'undefined') {
        // one param defined
        stop = start;
        start = 0;
    }
    if (typeof step == 'undefined') {
        step = 1;
    }
    if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
        return [];
    }
    var result = [];
    for (var i = start; step > 0 ? i < stop : i > stop; i += step) {
        result.push(i);
    }
    return result;
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// formatString('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');
erljs.formatString = function (format) {
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/{(\d+)}/g, function (match, number) {
        return typeof args[number] != 'undefined'
            ? args[number]
            : match
            ;
    });
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
erljs.style = {
//http://stackoverflow.com/questions/754607/can-jquery-get-all-css-styles-associated-with-an-element
//Pass a jQuery object into css() and it will return an object, which you can then plug back into jQuery's $().css(), ex:
//
//var style = css($("#elementToGetAllCSS"));
//$("#elementToPutStyleInto").css(style);

    css: function (a) {
        var sheets = document.styleSheets, o = {};
        for (var i in sheets) {
            var rules = sheets[i].rules || sheets[i].cssRules;
            for (var r in rules) {
                if (a.is(rules[r].selectorText)) {
                    o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
                }
            }
        }
        return o;
    },

    css2json: function (css) {
        var s = {};
        if (!css) return s;
        if (css instanceof CSSStyleDeclaration) {
            for (var i in css) {
                if ((css[i]).toLowerCase) {
                    s[(css[i]).toLowerCase()] = (css[css[i]]);
                }
            }
        } else if (typeof css == "string") {
            css = css.split("; ");
            for (var i in css) {
                var l = css[i].split(": ");
                s[l[0].toLowerCase()] = (l[1]);
            }
        }
        return s;
    }
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////

self.erljs = erljs;
<|endoftext|>


<commit_before>/*
 * CircleType 0.31
 * Peter Hrynkow
 * Copyright 2013, Licensed GPL & MIT
 *
*/

$.fn.circleType = function(options) {

    var settings = {
        dir: 1
    };

    if (typeof($.fn.lettering) !== 'function') {
        console.log('Lettering.js is required');
        return;
    }

    return this.each(function () {

        if (options) {
            $.extend(settings, options);
        }
        var elem = this,
            delta = (180 / Math.PI),
            txt = elem.innerHTML.replace(/\s/g, ' '),
            letters;

        elem.innerHTML = txt
        $(elem).lettering();

        elem.style.position =  'relative';

        letters = elem.getElementsByTagName('span');

        var layout = function () {
            var tw = 0,
                i,
                offset = 0,
                ch = parseInt($(elem).css('line-height'), 10),
                minRadius,
                origin,
                innerRadius,
                l, style, r, transform,
                y1, y2, h;

            for (i = 0; i < letters.length; i++) {
                tw += letters[i].offsetWidth;
            }
            minRadius = (tw / Math.PI) / 2 + ch;

            if (settings.fluid) {
                settings.radius = Math.max(elem.offsetWidth / 2, minRadius);
            }
            else if (!settings.radius) {
                settings.radius = minRadius;
            }
            if (settings.dir === -1) {
                origin = 'center ' + (-settings.radius + ch) + 'px';
            } else {
                origin = 'center ' + settings.radius + 'px';
            }

            innerRadius = settings.radius - ch;

            for (i = 0; i < letters.length; i++) {
                l = letters[i];
                offset += l.offsetWidth / 2 / innerRadius * delta;
                l.rot = offset;
                offset += l.offsetWidth / 2 / innerRadius * delta;
            }
            for (i = 0; i < letters.length; i++) {
                l = letters[i]
                style = l.style
                r = (-offset * settings.dir / 2) + l.rot * settings.dir
                transform = 'rotate(' + r + 'deg)';

                style.position = 'absolute';
                style.left = '50%';
                style.marginLeft = -l.offsetWidth / 2 + 'px';

                style.webkitTransform = transform;
                style.MozTransform = transform;
                style.OTransform = transform;
                style.msTransform = transform;
                style.transform = transform;

                style.webkitTransformOrigin = origin;
                style.MozTransformOrigin = origin;
                style.OTransformOrigin = origin;
                style.msTransformOrigin = origin;
                style.transformOrigin = origin;
                if(settings.dir === -1) {
                    style.bottom = 0;
                }
            }

            y1 = getPosition(letters[Math.floor(letters.length / 2)]).top;
            y2 = getPosition(l).top;

            if (y1 < y2) {
                h = y2 - y1 + ch;
            } else {
                h = y1 - y2 + ch;
            }

            elem.style.height = h + 'px';
        };

        var getPosition = function (elem) {
        	var docElem = document.documentElement,
        	    box = elem.getBoundingClientRect();
	        return {
		        top: box.top + window.pageYOffset - docElem.clientTop,
		        left: box.left + window.pageXOffset - docElem.clientLeft
	        };
        };

        if (settings.fluid) {
            $(window).resize(function () {
                layout();
            });
        }

        if (document.readyState !== "complete") {
            elem.style.visibility = 'hidden';
            $(window).load(function () {
                elem.style.visibility = 'visible';
                layout();
            });
        } else {
            layout();
        }
    });
};
<commit_msg>Added fitText option<commit_after>/*
 * CircleType 0.32
 * Peter Hrynkow
 * Copyright 2013, Licensed GPL & MIT
 *
*/

$.fn.circleType = function(options) {

    var settings = {
        dir: 1
    };

    if (typeof($.fn.lettering) !== 'function') {
        console.log('Lettering.js is required');
        return;
    }

    return this.each(function () {

        if (options) {
            $.extend(settings, options);
        }
        var elem = this,
            delta = (180 / Math.PI),
            txt = elem.innerHTML.replace(/\s/g, ' '),
            letters;

        elem.innerHTML = txt
        $(elem).lettering();

        elem.style.position =  'relative';

        letters = elem.getElementsByTagName('span');

        var layout = function () {
            var tw = 0,
                i,
                offset = 0,
                ch = parseInt($(elem).css('line-height'), 10),
                minRadius,
                origin,
                innerRadius,
                l, style, r, transform,
                y1, y2, h;

            for (i = 0; i < letters.length; i++) {
                tw += letters[i].offsetWidth;
            }
            minRadius = (tw / Math.PI) / 2 + ch;
            if (settings.fluid) {
                settings.radius = Math.max(elem.offsetWidth / 2, minRadius);
            }
            else if (!settings.radius || settings.fitText) {
                settings.radius = minRadius;
            }
            if (settings.dir === -1) {
                origin = 'center ' + (-settings.radius + ch) + 'px';
            } else {
                origin = 'center ' + settings.radius + 'px';
            }

            innerRadius = settings.radius - ch;

            for (i = 0; i < letters.length; i++) {
                l = letters[i];
                offset += l.offsetWidth / 2 / innerRadius * delta;
                l.rot = offset;
                offset += l.offsetWidth / 2 / innerRadius * delta;
            }
            for (i = 0; i < letters.length; i++) {
                l = letters[i]
                style = l.style
                r = (-offset * settings.dir / 2) + l.rot * settings.dir
                transform = 'rotate(' + r + 'deg)';

                style.position = 'absolute';
                style.left = '50%';
                style.marginLeft = -l.offsetWidth / 2 + 'px';

                style.webkitTransform = transform;
                style.MozTransform = transform;
                style.OTransform = transform;
                style.msTransform = transform;
                style.transform = transform;

                style.webkitTransformOrigin = origin;
                style.MozTransformOrigin = origin;
                style.OTransformOrigin = origin;
                style.msTransformOrigin = origin;
                style.transformOrigin = origin;
                if(settings.dir === -1) {
                    style.bottom = 0;
                }
            }

            y1 = getPosition(letters[Math.floor(letters.length / 2)]).top;
            y2 = getPosition(l).top;

            if (y1 < y2) {
                h = y2 - y1 + ch;
            } else {
                h = y1 - y2 + ch;
            }

            elem.style.height = h + 'px';
        };

        var getPosition = function (elem) {
        	var docElem = document.documentElement,
        	    box = elem.getBoundingClientRect();
	        return {
		        top: box.top + window.pageYOffset - docElem.clientTop,
		        left: box.left + window.pageXOffset - docElem.clientLeft
	        };
        };

        if (settings.fluid) {
            $(window).resize(function () {
                layout();
            });
        }
        if (settings.fitText) {
            if (typeof($.fn.fitText) !== 'function') {
                console.log('FitText.js is required when using the fitText option');
            } else {
                $(elem).fitText();
                $(window).resize(function () {
                    layout();
                });
            }
        }

        if (document.readyState !== "complete") {
            elem.style.visibility = 'hidden';
            $(window).load(function () {
                elem.style.visibility = 'visible';
                layout();
            });
        } else {
            layout();
        }
    });
};
<|endoftext|>


<commit_before>/*
 * class.core.js Library for JavaScript v0.2.0
 *
 * Copyright 2012, Dmitriy Pakhtinov ( spb.piksel@gmail.com )
 *
 * http://spb-piksel.ru/
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Update: 12-04-2012
 */

(function( global, undefined ) {

	"use strict";

	var vbinc = 0,
		msie = eval("/*@cc_on (@_jscript_version+'').replace(/\\d\\./, '');@*/"),
		hasOwnProperty = Object.prototype.hasOwnProperty,
		hasDontEnumBug = !( { toString: null } ).propertyIsEnumerable( 'toString' ),
		dontEnums = [
			'toString',
			'toLocaleString',
			'valueOf',
			'hasOwnProperty',
			'isPrototypeOf',
			'propertyIsEnumerable',
			'constructor'
		];

	if ( msie && msie < 9 && !( "execVBscript" in window ) ) {
		execScript('Function execVBscript(code) ExecuteGlobal(code) End Function', 'VBScript');
	}

	function Class( context, rule, parentClass, struct ) {

		var nm, rules, className;

		if ( arguments.length < 3 || typeof context === "string" ) {
			struct = parentClass;
			parentClass = rule;
			rule = context;
			context = Class;
		}

		rules = typeof rule === "string" ? rule.replace( /^[\s]+|[\s](?=\s)|[\s]+$/g, '' ).split( " " ) : [];
		className = rules[ 0 ] && rules[ 0 ] !== "extends" && rules.shift() || false;

		if ( !struct ) {
			struct = parentClass;
			parentClass = null;
		} else if ( typeof parentClass === "string" ) {
			nm = parentClass;
		}

		if ( struct && ( nm || rules.shift() === "extends" || typeof rule === "function" ) ) {
			if ( ( nm || ( nm = rules.shift() ) ) && !( rule = context[ nm ] ) ) {
				throw new Error( "Parent class '" + nm + "' not Initialized or Undefined" );
			}
			parentClass = rule;
		}

		if ( typeof ( struct = struct || rule ) !== "function" ) {
			var originalStruct = struct;
			struct = function() {
				return originalStruct;
			}
		}

		var staticConstructor = function() {

			var isParent = +this === 0,
				args = arguments,
				obj = new struct(),
				copy = obj,
				owner = isParent ? args[ 0 ] : { obj: obj };

			obj.parent = null;

			if ( parentClass ) {

				obj.parent = parentClass.call( false, owner );

				var Fn = function(){}
				Fn.prototype = parentClass.prototype;
				copy = new Fn();
			} else {
				copy.shared = {}
			}

			if ( parentClass || isParent ) {

				Class.ownEach( obj, function( prop, originalProp ) {
					if ( typeof originalProp === "function" ) {
						copy[ prop ] = function() {
							var p = owner.obj.parent;
							owner.obj.parent = obj.parent;
							var result = originalProp.apply( owner.obj, arguments );
							owner.obj.parent = p;
							return result;
						}
						copy[ prop ].toString = function(){ return originalProp.toString() }
					} else {
						copy[ prop ] = originalProp;
					}
				});

				owner.obj = isParent ? owner.obj : copy;
			}

			copy.static = staticConstructor;

			if ( !isParent ) {

				var cache = {};

				if ( ( Object.defineProperty || copy.__defineGetter__ ) && ( !msie || msie > 8 ) ) {

					Class.ownEach( copy, function( prop, val ) {

						if ( !cache[ "_" + prop ] && ( cache[ "_" + prop ] = 1 ) ) {

							var propType = prop.indexOf( "$" ) === 0 ? 1 :
									prop.indexOf( "get " ) === 0 ? 2 :
									prop.indexOf( "set " ) === 0 ? 3 : 0;

							if ( propType ) {

								var nm = propType === 1 ? prop.substring( 1 ) : prop.split( " " ).pop(),
									props = {
										enumerable: 1,
										configurable: 1,
										set: null,
										get: null
									};

								if ( propType === 1 || propType === 2 ) {
									props.get = function() {
										return (copy[propType === 1 ? "__get" : prop] || function(){})(
											propType === 1 ? nm : undefined
										)
									}
								}

								if ( propType === 1 || propType === 3 ) {
									props.set = function( value ) {
										(copy[propType === 1 ? "__set" : prop] || function(){})(
											propType === 1 ? nm : value, propType === 1 ? value : undefined
										)
									}
								}

								if ( Object.defineProperty ) {

									var descr = Object.getOwnPropertyDescriptor( copy, nm );

									props.get = props.get || descr && descr.get || function(){};
									props.set = props.set || descr && descr.set || function(){};

									Object.defineProperty( copy, nm, props );

								} else {
									if ( propType === 1 || propType === 2 ) {
										copy.__defineGetter__( nm, props.set );
									}
									if ( propType === 1 || propType === 3 ) {
										copy.__defineSetter__( nm, props.set );
									}
								}
							}
						}

					}, true );

				} else if ( msie ) {

					var staticClass = "StaticClass" + vbinc++,
						parts = [ "Class " + staticClass ],
						props = [], names = [], propType, nm,
						hasAccessors = false;

					Class.ownEach( copy, function( prop, val ) {

						if ( !cache[ "_" + prop ] && ( cache[ "_" + prop ] = 1 ) ) {

							propType = prop.indexOf( "$" ) === 0 ? 1 :
									prop.indexOf( "get " ) === 0 ? 2 :
									prop.indexOf( "set " ) === 0 ? 3 : 0;

							if ( propType ) {

								hasAccessors = true;

								nm = propType === 1 ? prop.substring( 1 ) : prop.split( " " ).pop();

								if ( propType === 1 || propType === 2 ) {
									parts.push(
										"Public Property Get [" + nm + "]",
										propType === 1 ? copy.__get ? "[" + nm + "] = me.[__get]( \"" + nm + "\" )" : "" :
										copy[ prop ] ? "[" + nm + "] = me.[" + prop + "]()" : "",
										"End Property"
									);
								}
								if ( propType === 1 || propType === 3 ) {
									parts.push(
										"Public Property Let [" + nm + "]( val )",
										propType === 1 ? copy.__set ? "Call me.[__set]( \"" + nm + "\", val )" : "" :
										copy[ prop ] ? "Call me.[" + prop + "]( val )" : "",
										"End Property",
										"Public Property Set [" + nm + "]( val )",
										propType === 1 ? copy.__set ? "Call me.[__set]( \"" + nm + "\", val )" : "" :
										copy[ prop ] ? "Call me.[" + prop + "]( val )" : "",
										"End Property"
									);
								}

							}

							if ( !propType || propType > 1 ) {
								// VBScript up to 60 multiple dimensions may be declared.
								if ( names.length === 50 ) { // flush 50 items
									parts.push( "Public [" + names.join("],[") + "]" );
									names.length = 0;
								}
								names[ names.length ] = prop;
								props[ props.length ] = prop;
							}
						}

					}, true );

					if ( hasAccessors ) {

						parts.push(
							"Public [" + names.join("],[") + "]",
							"End Class",
							"Function " + staticClass + "Factory()",
							"Set " + staticClass + "Factory=New " + staticClass,
							"End Function"
						);

						execVBScript( parts.join( "\n" ) );

						cache = window[ staticClass + "Factory" ]();

						for( var i = 0; parts = props[ i++ ]; ) {
							cache[ parts ] = copy[ parts ];
						}

						props = parts = names = null;

						owner.obj = copy = cache;
					}
				}

				cache = null;
			}

			var subConstructor = isParent ? function() {
				return copy;
			} : function() {
				if ( copy.constructor && copy.constructor !== Object.prototype.constructor ) {
					copy.constructor.apply( copy, args );
				}
				return copy;
			}

			subConstructor.prototype = copy;
			staticConstructor.prototype = copy;

			return new subConstructor();
		}

		staticConstructor.toString = function() {
			return "[class " + ( className || "Object" ) + "]";
		}

		if ( className ) {
			context[ className ] = staticConstructor;
			context[ className ].className = className;
		}

		return staticConstructor;
	}

	Class.ownEach = function( obj, callback, all ) {

		var idx, val, len = dontEnums.length;

		for( idx in obj ) {

			val = obj[ idx ];

			if ( ( all || hasOwnProperty.call( obj, idx ) ) &&
					callback.call( val, idx, val ) === false ) {
				len = false;
				break;
			}
		}
		if ( len && hasDontEnumBug ) {
			for( idx = 0; idx < len; idx++ ) {

				val = obj[ dontEnums[ idx ] ];

				if ( ( hasOwnProperty.call( obj, dontEnums[ idx ] ) || ( all && val != null ) ) &&
						callback.call( val, dontEnums[ idx ], val ) === false ) {
					break;
				}
			}
		}
	}

	Class.instanceOf = function( object, constructor ) {

		while( object && object.static != null ) {

			if ( object.static === constructor ) {
				return true;
			}
			object = object.parent;
		}
		return false;
	}

	Class.toString = function() {
		return "[object Function]";
	}

	Class.msie = msie;

	global.Class = Class;

})( this || window );
<commit_msg>fixed many bugs + optimization<commit_after>/*
 * class.core.js Library for JavaScript v0.2.1
 *
 * Copyright 2012, Dmitriy Pakhtinov ( spb.piksel@gmail.com )
 *
 * http://spb-piksel.ru/
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Update: 15-04-2012
 */

(function( global, undefined ) {

	"use strict";

	var msie = eval("/*@cc_on (@_jscript_version+'').replace(/\\d\\./, '');@*/"),
		libID = ( new Date() ).getTime(),
		VBInc = ( Object.defineProperty || Object.prototype.__defineGetter__ ) && ( !msie || msie > 8 ) ? 0 : 1,
		hasOwnProperty = Object.prototype.hasOwnProperty,
		hasDontEnumBug = !( { toString: null } ).propertyIsEnumerable( 'toString' ),
		dontEnums = [
			'toString',
			'toLocaleString',
			'valueOf',
			'hasOwnProperty',
			'isPrototypeOf',
			'propertyIsEnumerable',
			'constructor'
		];

	if ( VBInc && !( "execVBscript" in window ) ) {
		execScript('Function execVBscript(code) ExecuteGlobal(code) End Function\n'+
			'Function VBCorrectVal(o,r) If IsObject(o) Then Set r=o Else r=o End If End Function', 'VBScript');
	}

	function Class( context, rule, parentClass, struct ) {

		var nm, rules, className;

		if ( arguments.length < 3 || typeof context === "string" ) {
			struct = parentClass;
			parentClass = rule;
			rule = context;
			context = Class;
		}

		rules = typeof rule === "string" ? rule.replace( /^[\s]+|[\s](?=\s)|[\s]+$/g, '' ).split( " " ) : [];
		className = rules[ 0 ] && rules[ 0 ] !== "extends" && rules.shift() || false;

		if ( !struct ) {
			struct = parentClass;
			parentClass = null;
		} else if ( typeof parentClass === "string" ) {
			nm = parentClass;
		}

		if ( struct && ( nm || rules.shift() === "extends" || typeof rule === "function" ) ) {
			if ( ( nm || ( nm = rules.shift() ) ) && !( rule = context[ nm ] ) ) {
				throw new Error( "Parent class '" + nm + "' not Initialized or Undefined" );
			}
			parentClass = rule;
		}

		if ( typeof ( struct = struct || rule ) !== "function" ) {
			var originalStruct = struct;
			struct = function() {
				return originalStruct;
			}
		}

		var staticConstructor = function() {

			var isParent = +this === 0,
				args = arguments,
				obj = new struct(),
				copy = obj,
				owner = isParent ? args[ 0 ] : { obj: obj };

			obj.parent = null;

			if ( parentClass ) {

				obj.parent = parentClass.call( false, owner );

				var Fn = function(){}
				Fn.prototype = obj.parent;
				copy = new Fn();
			} else {
				copy.shared = {}
			}

			if ( parentClass || isParent ) {

				Class.ownEach( obj, function( prop, originalProp ) {
					if ( typeof originalProp === "function" ) {
						copy[ prop ] = function() {
							var p = owner.obj.parent;
							owner.obj.parent = obj.parent;
							var result = originalProp.apply( owner.obj, arguments );
							owner.obj.parent = p;
							return result;
						}
						copy[ prop ].toString = function(){ return originalProp.toString() }
					} else {
						copy[ prop ] = originalProp;
					}
				});

				owner.obj = isParent ? owner.obj : copy;
			}

			copy.static = staticConstructor;

			if ( !isParent ) {

				if ( !VBInc ) {

					Class.ownEach( copy, function( prop, val ) {

						var propType = prop.indexOf( "$" ) === 0 ? 1 :
								prop.indexOf( "get " ) === 0 ? 2 :
								prop.indexOf( "set " ) === 0 ? 3 : 0;

						if ( propType ) {

							var nm = propType === 1 ? prop.substring( 1 ) : prop.split( " " ).pop(),
								props = {
									enumerable: 1,
									configurable: 1,
									set: null,
									get: null
								};

							if ( propType === 1 || propType === 2 ) {
								props.get = function() {
									return (copy[propType === 1 ? "__get" : prop] || function(){})(
										propType === 1 ? nm : undefined
									)
								}
							}

							if ( propType === 1 || propType === 3 ) {
								props.set = function( value ) {
									(copy[propType === 1 ? "__set" : prop] || function(){})(
										propType === 1 ? nm : value, propType === 1 ? value : undefined
									)
								}
							}

							if ( !Object.defineProperty ) {

								var descr = Object.getOwnPropertyDescriptor( copy, nm );

								props.get = props.get || descr && descr.get || function(){};
								props.set = props.set || descr && descr.set || function(){};

								Object.defineProperty( copy, nm, props );

							} else {
								if ( propType === 1 || propType === 2 ) {
									copy.__defineGetter__( nm, props.get );
								}
								if ( propType === 1 || propType === 3 ) {
									copy.__defineSetter__( nm, props.set );
								}
							}
						}

					}, true );

				} else if ( msie ) {

					var staticClass = "StaticClass" + libID + VBInc++,
						parts = [ "Class " + staticClass ],
						props = [], names = [], propType, nm,
						hasAccessors = false;

					Class.ownEach( copy, function( prop, val ) {

						propType = prop.indexOf( "$" ) === 0 ? 1 :
								prop.indexOf( "get " ) === 0 ? 2 :
								prop.indexOf( "set " ) === 0 ? 3 :
								prop === "toString" ? 4 : 0;

						if ( propType ) {

							hasAccessors = true;

							nm = propType === 4 ? "(" + prop + ")" :
								propType === 1 ? prop.substring( 1 ) : prop.split( " " ).pop();

							if ( propType === 1 || propType === 2 || propType === 4 ) {
								parts.push(
									"Public " +
									( propType === 4 ? "Default " : "" ) + "Property Get [" + nm + "]",
									"Call VBCorrectVal(" +
									( propType === 1 ? copy.__get ? "me.[__get]( \"" + nm + "\" )" : "" :
									copy[ prop ] ? "me.[" + prop + "]()" : "" ) + ", [" + nm + "])",
									"End Property"
								);
							}
							if ( propType === 1 || propType === 3 ) {
								parts.push(
									"Public Property Let [" + nm + "]( val )",
									propType === 1 ?
									copy.__set ? "Call me.[__set]( \"" + nm + "\", val )" : "" :
									copy[ prop ] ? "Call me.[" + prop + "]( val )" : "",
									"End Property",
									"Public Property Set [" + nm + "]( val )",
									propType === 1 ?
									copy.__set ? "Call me.[__set]( \"" + nm + "\", val )" : "" :
									copy[ prop ] ? "Call me.[" + prop + "]( val )" : "",
									"End Property"
								);
							}
						}

						if ( !propType || propType > 1 ) {
							// VBScript up to 60 multiple dimensions may be declared.
							if ( names.length === 50 ) { // flush 50 items
								parts.push( "Public [" + names.join("],[") + "]" );
								names.length = 0;
							}
							names[ names.length ] = prop;
							props[ props.length ] = prop;
						}

					}, true );

					if ( hasAccessors ) {

						parts.push(
							"Public [" + names.join("],[") + "]",
							"End Class",
							"Function " + staticClass + "Factory()",
							"Set " + staticClass + "Factory=New " + staticClass,
							"End Function"
						);

						execVBScript( parts.join( "\n" ) );

						staticClass = window[ staticClass + "Factory" ]();

						for( var i = 0; parts = props[ i++ ]; ) {
							staticClass[ parts ] = copy[ parts ];
						}

						owner.obj = copy = staticClass;
					}

					props = parts = names = staticClass = null;
				}
			}

			var subConstructor = isParent ? function() {
				return copy;
			} : function() {
				if ( copy.constructor && copy.constructor !== Object.prototype.constructor ) {
					copy.constructor.apply( copy, args );
				}
				return copy;
			}

			return new subConstructor();
		}

		staticConstructor.toString = function() {
			return "[class " + ( className || "Object" ) + "]";
		}

		if ( className ) {
			context[ className ] = staticConstructor;
			context[ className ].className = className;
		}

		return staticConstructor;
	}

	Class.ownEach = function( obj, callback, all ) {

		var idx, val, len = dontEnums.length;

		for( idx in obj ) {

			val = obj[ idx ];

			if ( ( ( all && val !== Object.prototype[ idx ] ) || hasOwnProperty.call( obj, idx ) ) &&
					callback.call( val, idx, val ) === false ) {
				len = false;
				break;
			}
		}

		if ( len && hasDontEnumBug ) {
			for( idx = 0; idx < len; idx++ ) {

				val = obj[ dontEnums[ idx ] ];

				if ( ( hasOwnProperty.call( obj, dontEnums[ idx ] ) ||
					( all && val != null && val !== Object.prototype[ dontEnums[ idx ] ] ) ) &&
						callback.call( val, dontEnums[ idx ], val ) === false ) {
					break;
				}
			}
		}
	}

	Class.instanceOf = function( object, constructor ) {

		while( object && object.static != null ) {

			if ( object.static === constructor ) {
				return true;
			}
			object = object.parent;
		}
		return false;
	}

	Class.toString = function() {
		return "[object Function]";
	}

	Class.msie = msie;

	global.Class = Class;

})( this || window );
<|endoftext|>


<commit_before>/**
 * Created by filip on 8/26/15.
 */
var fs = require('fs-extra');
var path = require('path');
var chalk = require('chalk');

var configDir = './server/config/';
var configTemplate = configDir + 'local.env.template.js';
var configFile = configDir + 'local.env.js';
var exec = require('child_process').exec;

/**
 * Whenever config gets changed we need to rebuild Frontend to take affect
 *
 * @param callback
 * @private
 */
var _postConfigPhase = function (callback) {

    console.log(chalk.green('Running frontend build to apply config changes...'));
    process.chdir(__dirname + '/../client');

    var child = exec('gulp build');

    //child.stdout.on('data', function(data) {
    //    //console.error(data);
    //    // do nothing we wont cluter user stdout with fe build
    //});
    //
    child.stderr.on('data', function(data) {
        console.error('Error During frontend build: ', data);
    });

    child.on('close', function() {
        console.log('Applied config change to frontend.');

        if (typeof callback === 'function') {
            callback();
        }

    });

};

/**
 * Create config from config template
 *
 * @param conf {object} Object representing configuration
 * @param root {string} Base path to root of cottontail
 * @param callback {function} Callback to be executed when config is created
 */
var create = function (conf, root, callback) {

    fs.readFile(path.normalize(root + configTemplate), 'utf8', function(err, data) {

        if (err) {
            return console.error('Failed to read config template.', err);
        }

        // Set default values if missing
        conf['NODE_ENV'] = conf['NODE_ENV'] || 'development';
        conf['WORKING_DIR'] = conf['WORKING_DIR'] || '/data/cottontail/fs';
        conf['GITHUB_ID'] = conf['GITHUB_ID'] || '';
        conf['GITHUB_SECRET'] = conf['GITHUB_SECRET'] || '';
        conf['GITHUB_SCOPE'] = conf['GITHUB_SCOPE'] || '';
        conf['STRATEGY'] = conf['STRATEGY'] || 'local';
        conf['DEBUG_LEVEL'] = conf['DEBUG_LEVEL'] || '';
        conf['DEBUG'] = typeof conf['DEBUG'] === 'undefined' ? 'true' : conf['DEBUG'].toString();

        // Do the replace
        data = data.replace(/<NODE_ENV>/g, "'" + conf['NODE_ENV'] + "'");
        data = data.replace(/<GITHUB_ID>/g, "'" + conf['GITHUB_ID'] + "'");
        data = data.replace(/<GITHUB_SECRET>/g, "'" + conf['GITHUB_SECRET'] + "'");
        data = data.replace(/<GITHUB_SCOPE>/g, "'" + conf['GITHUB_SCOPE'] + "'");
        data = data.replace(/<STRATEGY>/g, "'" + conf['STRATEGY'] + "'");
        data = data.replace(/<DEBUG_LEVEL>/g, "'" + conf['DEBUG_LEVEL'] + "'");
        data = data.replace(/<DEBUG>/g, conf['DEBUG']);

        fs.writeFile(root + configFile, data, 'utf8', function(err) {
            if (err) return console.log('Failed to write config file.', err);

            _postConfigPhase(callback);
        });

    });
};

var _readJSON = function (filePath, callback) {
    fs.readFile(path.normalize(filePath), function (err, data) {

        if (err) {
            throw err;
        }

        if (typeof callback === 'function') {
            var _json = JSON.parse(data.toString());
            callback(_json);
        }
    })
};

var fromFile = function (filePath, root, callback) {

    console.log('Got config file: ', chalk.magenta.italic(filePath));

    fs.stat(path.normalize(filePath), function (err) {

        if (err)  {
            console.error('Failed reading of config file: ', filePath, err);
            process.exit(1);
        }

        var ext = path.extname(filePath);

        if (ext !== '.js' && ext !== '.json') {
            console.error('Config file must have extension "js" or "json"');
            process.exit(1);
        }

        switch (ext) {
            case '.js':
                fs.copySync(path.normalize(filePath),  path.normalize(root + configFile));
                _postConfigPhase(callback);
                break;
            case '.json':
                _readJSON(filePath, function (data) {
                    create(data, root, callback)
                });
                break;
        }

    });

};

module.exports = {
    create: create,
    fromFile: fromFile
};
<commit_msg>changed default env<commit_after>/**
 * Created by filip on 8/26/15.
 */
var fs = require('fs-extra');
var path = require('path');
var chalk = require('chalk');

var configDir = './server/config/';
var configTemplate = configDir + 'local.env.template.js';
var configFile = configDir + 'local.env.js';
var exec = require('child_process').exec;

/**
 * Whenever config gets changed we need to rebuild Frontend to take affect
 *
 * @param callback
 * @private
 */
var _postConfigPhase = function (callback) {

    console.log(chalk.green('Running frontend build to apply config changes...'));
    process.chdir(__dirname + '/../client');

    var child = exec('gulp build');

    //child.stdout.on('data', function(data) {
    //    //console.error(data);
    //    // do nothing we wont cluter user stdout with fe build
    //});
    //
    child.stderr.on('data', function(data) {
        console.error('Error During frontend build: ', data);
    });

    child.on('close', function() {
        console.log('Applied config change to frontend.');

        if (typeof callback === 'function') {
            callback();
        }

    });

};

/**
 * Create config from config template
 *
 * @param conf {object} Object representing configuration
 * @param root {string} Base path to root of cottontail
 * @param callback {function} Callback to be executed when config is created
 */
var create = function (conf, root, callback) {

    fs.readFile(path.normalize(root + configTemplate), 'utf8', function(err, data) {

        if (err) {
            return console.error('Failed to read config template.', err);
        }

        // Set default values if missing
        conf['NODE_ENV'] = conf['NODE_ENV'] || 'production';
        conf['WORKING_DIR'] = conf['WORKING_DIR'] || '/data/cottontail/fs';
        conf['GITHUB_ID'] = conf['GITHUB_ID'] || '';
        conf['GITHUB_SECRET'] = conf['GITHUB_SECRET'] || '';
        conf['GITHUB_SCOPE'] = conf['GITHUB_SCOPE'] || '';
        conf['STRATEGY'] = conf['STRATEGY'] || 'local';
        conf['DEBUG_LEVEL'] = conf['DEBUG_LEVEL'] || '';
        conf['DEBUG'] = typeof conf['DEBUG'] === 'undefined' ? 'true' : conf['DEBUG'].toString();

        // Do the replace
        data = data.replace(/<NODE_ENV>/g, "'" + conf['NODE_ENV'] + "'");
        data = data.replace(/<GITHUB_ID>/g, "'" + conf['GITHUB_ID'] + "'");
        data = data.replace(/<GITHUB_SECRET>/g, "'" + conf['GITHUB_SECRET'] + "'");
        data = data.replace(/<GITHUB_SCOPE>/g, "'" + conf['GITHUB_SCOPE'] + "'");
        data = data.replace(/<STRATEGY>/g, "'" + conf['STRATEGY'] + "'");
        data = data.replace(/<DEBUG_LEVEL>/g, "'" + conf['DEBUG_LEVEL'] + "'");
        data = data.replace(/<DEBUG>/g, conf['DEBUG']);

        fs.writeFile(root + configFile, data, 'utf8', function(err) {
            if (err) return console.log('Failed to write config file.', err);

            _postConfigPhase(callback);
        });

    });
};

var _readJSON = function (filePath, callback) {
    fs.readFile(path.normalize(filePath), function (err, data) {

        if (err) {
            throw err;
        }

        if (typeof callback === 'function') {
            var _json = JSON.parse(data.toString());
            callback(_json);
        }
    })
};

var fromFile = function (filePath, root, callback) {

    console.log('Got config file: ', chalk.magenta.italic(filePath));

    fs.stat(path.normalize(filePath), function (err) {

        if (err)  {
            console.error('Failed reading of config file: ', filePath, err);
            process.exit(1);
        }

        var ext = path.extname(filePath);

        if (ext !== '.js' && ext !== '.json') {
            console.error('Config file must have extension "js" or "json"');
            process.exit(1);
        }

        switch (ext) {
            case '.js':
                fs.copySync(path.normalize(filePath),  path.normalize(root + configFile));
                _postConfigPhase(callback);
                break;
            case '.json':
                _readJSON(filePath, function (data) {
                    create(data, root, callback)
                });
                break;
        }

    });

};

module.exports = {
    create: create,
    fromFile: fromFile
};
<|endoftext|>


<commit_before>import axios from 'axios';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';

import { useRouterHistory, Router } from 'react-router';
import { createHistory } from 'history';

import { loadCredentials } from './actions/auth';
import routes from './routes';
import configureStore from './store/configureStore';
// Make axios aware of the base path.
axios.defaults.baseURL = window.config.BASE_URL;

// Make history aware of the base path.
const history = useRouterHistory(createHistory)({
  basename: window.config.BASE_PATH || ''
});

const store = configureStore();

// Fire first events.
store.dispatch(loadCredentials());

// Render application.
ReactDOM.render(
  <Provider store={store}>
    <Router history={history} routes={routes} />
  </Provider>,
  document.getElementById('app')
);

// Show the developer tools.
// if (process.env.NODE_ENV !== 'production') {
//   const showDevTools = require('./showDevTools');
//   showDevTools(store);
// }
<commit_msg>BASE_URL hack<commit_after>import axios from 'axios';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';

import { useRouterHistory, Router } from 'react-router';
import { createHistory } from 'history';

import { loadCredentials } from './actions/auth';
import routes from './routes';
import configureStore from './store/configureStore';
// Make axios aware of the base path.
axios.defaults.baseURL = window.config.BASE_URL;

// Make history aware of the base path.
const history = useRouterHistory(createHistory)({
  basename: window.config.BASE_URL.endsWith('/') ? window.config.BASE_PATH : window.config.BASE_PATH.substring(0, window.config.BASE_PATH.length - 1)
});

const store = configureStore();

// Fire first events.
store.dispatch(loadCredentials());

// Render application.
ReactDOM.render(
  <Provider store={store}>
    <Router history={history} routes={routes} />
  </Provider>,
  document.getElementById('app')
);

// Show the developer tools.
// if (process.env.NODE_ENV !== 'production') {
//   const showDevTools = require('./showDevTools');
//   showDevTools(store);
// }
<|endoftext|>


<commit_before>if (Meteor.isClient) {

  /**
   * Get url parameter, e.g., http://localhost:3000/?id=3 -> id = 3
   *
   * @name The parameter name.
   */
  var getParameterByName = function(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  };

  /**
   * Connects to Huddle Engine using
   *
   * 1) host and port url parameter if set
   * 2) host and port from session if set
   * 3) shows a connection dialog
   */
  var connect = function() {
    var host = getParameterByName("host");
    var port = parseInt(getParameterByName("port"));

    if (!host || !port) {
      host = Session.get("host");
      port = Session.get("port");
    }

    if (host && port) {
      createCanvas(host, port);
    }
    else {
      $('#connection-dialog').modal({
        backdrop: false,
        keyboard: false,
        show: true
      });
    }
  };

  // make canvas accessible outside of the createCanvas function
  var canvas;
  var createCanvas = function(host, port) {
    canvas = HuddleCanvas.create(host, port, {
      containerId: "huddle-canvas-container",
      backgroundImage: "/images/where-is-waldo1.jpg",
      panningEnabled: false,
      showDebugBox: false
    });
  };

  /**
   * Do connect after main application rendered.
   */
  Template.main.rendered = function() {
    // do connect to Huddle Engine, otherwise show connection dialog
    connect();
  }

  /**
   * Render the connection dialog.
   */
  Template.connectionDialog.rendered = function() {
    $('#connection-dialog').on('hidden.bs.modal', function (e) {
      var host = $('#client-host').val();
      var port = parseInt($('#client-port').val());

      createCanvas(host, port);
    });
  };

  Template.connectionDialog.helpers({

    absoluteUrl: function() {
      var host = Session.get("host") ? Session.get("host") : "localhost";
      var port = Session.get("port") ? Session.get("port") : 1948;

      var parameters = "?host=" + host;
      parameters += "&port=" + port;
      return Meteor.absoluteUrl(parameters);
    },

    host: function() {
      return Session.get("host");
    },

    port: function() {
      return Session.get("port");
    }
  });

  Template.connectionDialog.events({

    'keyup #client-host': function(e, tmpl) {
      var host = $('#client-host').val();
      Session.set("host", host);
    },

    'keyup #client-port': function(e, tmpl) {
      try {
        var port = parseInt($('#client-port').val());
        Session.set("port", port);
      }
      catch (err) {
        // ignore err
      }
    }
  });
}
<commit_msg>Enabled panning & zooming<commit_after>if (Meteor.isClient) {

  /**
   * Get url parameter, e.g., http://localhost:3000/?id=3 -> id = 3
   *
   * @name The parameter name.
   */
  var getParameterByName = function(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  };

  /**
   * Connects to Huddle Engine using
   *
   * 1) host and port url parameter if set
   * 2) host and port from session if set
   * 3) shows a connection dialog
   */
  var connect = function() {
    var host = getParameterByName("host");
    var port = parseInt(getParameterByName("port"));

    if (!host || !port) {
      host = Session.get("host");
      port = Session.get("port");
    }

    if (host && port) {
      createCanvas(host, port);
    }
    else {
      $('#connection-dialog').modal({
        backdrop: false,
        keyboard: false,
        show: true
      });
    }
  };

  // make canvas accessible outside of the createCanvas function
  var canvas;
  var createCanvas = function(host, port) {
    canvas = HuddleCanvas.create(host, port, {
      containerId: "huddle-canvas-container",
      backgroundImage: "/images/where-is-waldo1.jpg",
      panningEnabled: true, //false,
      showDebugBox: false
    });
  };

  /**
   * Do connect after main application rendered.
   */
  Template.main.rendered = function() {
    // do connect to Huddle Engine, otherwise show connection dialog
    connect();
  }

  /**
   * Render the connection dialog.
   */
  Template.connectionDialog.rendered = function() {
    $('#connection-dialog').on('hidden.bs.modal', function (e) {
      var host = $('#client-host').val();
      var port = parseInt($('#client-port').val());

      createCanvas(host, port);
    });
  };

  Template.connectionDialog.helpers({

    absoluteUrl: function() {
      var host = Session.get("host") ? Session.get("host") : "localhost";
      var port = Session.get("port") ? Session.get("port") : 1948;

      var parameters = "?host=" + host;
      parameters += "&port=" + port;
      return Meteor.absoluteUrl(parameters);
    },

    host: function() {
      return Session.get("host");
    },

    port: function() {
      return Session.get("port");
    }
  });

  Template.connectionDialog.events({

    'keyup #client-host': function(e, tmpl) {
      var host = $('#client-host').val();
      Session.set("host", host);
    },

    'keyup #client-port': function(e, tmpl) {
      try {
        var port = parseInt($('#client-port').val());
        Session.set("port", port);
      }
      catch (err) {
        // ignore err
      }
    }
  });
}
<|endoftext|>


<commit_before>
var myApp = angular.module("myApp", ["ngRoute"]);

myApp.config(function($routeProvider){
    $routeProvider
        .when('/home', {
            templateUrl: "views/home.html"
            //controller: "homeController"
        })
        .when('/contact', {
            templateUrl: "views/contact.html",
            controller: "contactController"
        })
        .when('/chords', {
            templateUrl: "views/chords.html",
            controller: "contactController"
        })
        .when('/GuitarTuning', {
            templateUrl: "views/GuitarTuning.html",
            controller: "contactController"
        })
        .when('/login', {
            templateUrl: "views/login.html",
            controller: "contactController"
        })

        .otherwise({redirectTo:'/home'});
});

<commit_msg>Delete app.js<commit_after><|endoftext|>