<commit_before>"use strict";
var wptmonitor = (function(window, $, wptmonitor){

    var chart;

    $(document).ready(function() {
        "use strict";

        var act = wptmonitor.graph.action;

        $('#graphJSONButton').on('click', function(){
            var chartContainerIsHidden = isChartContainerHidden();
            submitFormAJAX()
            .done(function(){
                if(chartContainerIsHidden){
                    scrollToGraph();
                }
            })
            .fail(function(e){
                alert(e);
            });
        });

        $('#hideGraph').click(function(e){
            e.preventDefault();
            $('#graphContainer').slideUp(function(){
                $('#graphOverlay').show();
                $('#graph').empty();
                chart = null;
            });
        });

        if(act && act === "graph") {
            if(getJobCount() > 0){
                setTimeout(function(){
                    $('#graphJSONButton').trigger('click');
                }, 50);
            }
        }

        function scrollToGraph() {
            var container = $("#graphContainer");
            $('html, body').animate({
                'scrollTop': container.offset().top - $(window).height() + container.height() },
                1000,
                'swing'
            );
        }

        $(window).bind("beforeunload", function() {
            return "You are leaving this page.";
        });

    });

    function submitFormAJAX() {
        "use strict";
        var deferred=$.Deferred();
        var serializedFormData = $('#updateForm').serializeArray();

        if(!checkJobCount()) {
            deferred.reject("No jobs selected");
        } else {
            getChartDataWithGUIBehavior(serializedFormData)
            .done(function(d){
                try {
                    d = convertData2avgCharts(d);
                    drawChart(d);
                } catch(e) {
                    alert('Error occured while drawing chart: ' + e);
                    deferred.reject(e);
                    return;
                }

                deferred.resolve();

            })
            .fail(function(a){
                deferred.reject(a.message);
            });
        }

        return deferred.promise();
    }

    function showChartContainer(){
        "use strict";
        var d = $.Deferred();
        var container = $("#graphContainer");

        if(container.is(":hidden")){
            container.slideDown(1000, function(){
                d.resolve();
            });
        } else {
            d.resolve();
        }

        return d.promise();
    }

    function isChartContainerHidden() {
        return $("#graphContainer").is(":hidden");
    }

    function getChartData(params){
        "use strict";
        var d = $.Deferred();
        $.ajax({
            url: 'jash/flashGraph.json.php',
            data: params,
            method: "POST"
        }).done(function(data){
            if(data.status !== 200) {
                d.reject({
                    status:  data.status,
                    message: data.message
                });
            } else {
                d.resolve(data.results);
            }
        }).error(function(jqxhr){
            d.reject({
                status: jqxhr.status,
                message: jqxhr.statusText
            });
        });
        return d.promise();
    }

    function getChartDataWithGUIBehavior(params){
        "use strict";
        var d = $.Deferred();
        var button = $("#graphJSONButton");

        $.when(
            getChartData(params),
            $(button).attr('disabled', 'disabled')
            ,showChartContainer().done(function(){
                $('#graphOverlay').fadeIn(100);
            })
        ).done(function(data){
            d.resolve(data);
        }).fail(function(a){
            alert('Error getting data from the server\n'+a.message+' ('+a.status+')');
            d.reject(a);
        }).always(function(){
            $('#graphOverlay').fadeOut(600, function(){
                $(button).removeAttr('disabled');
            });
        });

        return d.promise();
    }

    /**
     * Converts data returned by server to format that can be consumed by AmCharts Serial chart
     * @param {Array} data
     */
    function convertData2avgCharts (data) {
        "use strict";
        var chartData = [];
        var seriesToJobNameMap = {};
        var seriesToMetricNameMap = {};
        var seriesToJobIdMap ={};
        var valueFields = [];
        var numberOfSeries = 0;
        var previousJobId = null;
        var i, j, k;

        for(i in data.series) {
            if(data.series.hasOwnProperty(i)){
                if(previousJobId !== null) {
                    if(data.series[previousJobId].dataSet.length !== data.series[i].dataSet.length) {
                        throw "Not equal datasets";
                    }
                }
                previousJobId = i;
                numberOfSeries++;
            }
        }

        /**
         *  Iterate all jobs and metrics to create mappings between value fields names and other data
         */
        for (k=0; k < data.metrics.length; k++) {
            for(i=0; i < data.jobs.length; i++) {
                seriesToJobNameMap[data.metrics[k] + "-" + data.jobs[i]] = data.series[data.jobs[i]].jobName;
                seriesToMetricNameMap[data.metrics[k] + "-" + data.jobs[i]] = data.metrics[k];
                seriesToJobIdMap[data.metrics[k] + "-" + data.jobs[i]] = data.jobs[i];
                valueFields.push(data.metrics[k] + "-" + data.jobs[i]);
            }
        }

        /**
         *  Functions to be put on every data point to be accessible from click event handler
         */
        var getJobName    = function(seriesName){
            return seriesToJobNameMap[seriesName];
        };

        var getMetricName = function(seriesName){
            return seriesToMetricNameMap[seriesName];
        };
        var getJobId      = function(seriesName){
            return seriesToJobIdMap[seriesName];
        };

        var getInterval   = function(){
            return data.interval;
        };

        /**
         *  Iterate all points and then all series to put all series in different fields but in one data serie
         */
        for(i=0; i<data.series[previousJobId].dataSet.length; i++) {
            var tmpPoint = {};
            tmpPoint['date'] = data.series[previousJobId].dataSet[i].DateFormatted;
            tmpPoint['timestamp'] = data.series[previousJobId].dataSet[i].UnixTimestamp;
            for(j in data.jobs) {
                if(data.jobs.hasOwnProperty(j)) {
                    for (k = 0; k < data.metrics.length; k++) {
                        if (data.series[data.jobs[j]].dataSet[i][data.metrics[k]]) {
                            tmpPoint[data.metrics[k] + "-" + data.jobs[j]] = (data.series[data.jobs[j]].dataSet[i][data.metrics[k]] / 1000).toFixed(2);
                            tmpPoint.getJobId = getJobId;
                            tmpPoint.getJobName = getJobName;
                            tmpPoint.getMetricName = getMetricName;
                            tmpPoint.getInterval = getInterval;
                        }
                    }
                }
            }
            chartData.push(tmpPoint);
        }

        return {
            getJobName    : function(seriesName){return seriesToJobNameMap[seriesName];},
            getMetricName : function(seriesName){return seriesToMetricNameMap[seriesName];},
            getJobId      : function(seriesName){return seriesToJobIdMap[seriesName];},
            valueFields: valueFields,
            series: chartData
        };
    }

    function drawChart(data) {
        "use strict";

        var getMetricName = data.getMetricName || function() {return 'No getMetricName function';};
        var getJobName    = data.getJobName ||    function() {return 'No getJobName function';};
        var getJobId      = data.getJobId ||      function() {return 'No getJobId function';};
        var graphs = [];

        /**
         *  Prepare graphs configs for all data series
         */
        for(var i in data.valueFields){
            if(data.valueFields.hasOwnProperty(i)) {
                graphs.push({
                    id                         : data.valueFields[i],
                    balloonText                : "[[category]]
" + getMetricName(data.valueFields[i]) + ": [[value]]",
                    bullet                     : "round",
                    bulletSize                 : 1,
                    bulletBorderAlpha          : 1,
                    bulletColor                : "#FFFFFF",
                    hideBulletsCount           : 0,
                    title                      : getJobName(data.valueFields[i]) + " " + getMetricName(data.valueFields[i]),
                    valueField                 : data.valueFields[i],
                    useLineColorForBulletBorder: true
                });
            }
        }

        var chartScrollbar = {
            autoGridCount    : true,
            graph            : data.valueFields[0],
            "scrollbarHeight": 20, hideResizeGrips: true
            // ,updateOnReleaseOnly: true
        };

        if(chart){
            /**
             *  If a chart is already instantiated new data provider is set and the chart redrawn.
             */
            chart.dataProvider = data.series;
            chart.graphs = graphs;

            chart.removeChartScrollbar();
            chart.chartScrollbar = chartScrollbar;

            chart.validateData();
        } else {
            // chart is instantiated from scratch
            chart = AmCharts.makeChart("graph", {
                type               : "serial",
                theme              : "none",
                pathToImages       : "js/amcharts/images/",
                dataProvider       : data.series,
                zoomOutOnDataUpdate: false,
                valueAxes          : [
                    {
                        axisAlpha : 0.2,
                        dashLength: 1,
                        position  : "left",
                        minimum   : 0,
                        unit      : "s"
                    }
                ],
                graphs             : graphs,
                chartScrollbar     : chartScrollbar,
                chartCursor        : {
                    cursorPosition           : "mouse",
                    categoryBalloonDateFormat: "MMM DD JJ:NN:SS", cursorAlpha: 0.5, graphBulletSize: 2
                },
                categoryField      : "date",
                dataDateFormat     : "YYYY-MM-DD JJ:NN:SS",
                categoryAxis       : {
                    parseDates      : true,
                    minorGridEnabled: false,
                    minPeriod       : "mm"
                },
                legend             : {
                    fontSize: 9
                },
                exportConfig       : {}
            });

            chart.addListener("clickGraphItem", function(e){
                var dataContext = e.item.dataContext;
                var valueField = e.graph.valueField;
                var resultsURL = getResultsURL(dataContext.getJobId(valueField), dataContext.timestamp, dataContext.getInterval());
                window.open(resultsURL);

            });
        }

        function getResultsURL(jobId, startDateTime, interval){
            var params = {
                currentPage  : 1,
                filterField  : "WPTJob.Id",
                filterValue  : jobId,
                startDateTime: startDateTime,
                endDateTime  : startDateTime + interval
            };
            return "listResults.php?"+$.param(params);
        }
        // drawTable(data);
    }

    function getJobCount(){
        var val = $('#jobs').val();
        var count;

        if(val === null) {count = 0;}
        else {count = val.length;}

        return count;
    }

    window.getChart      = function(){return chart;};

    wptmonitor.graph = {initialized: true};

    return wptmonitor;
})(window, jQuery, wptmonitor || {});
<commit_msg>added possibility to disable confirmation before unloading the page<commit_after>"use strict";
var wptmonitor = (function(window, $, wptmonitor){

    var chart;

    var preventUnload = true;

    $(document).ready(function() {
        "use strict";

        var act = wptmonitor.graph.action;

        $('#graphJSONButton').on('click', function(){
            var chartContainerIsHidden = isChartContainerHidden();
            submitFormAJAX()
            .done(function(){
                if(chartContainerIsHidden){
                    scrollToGraph();
                }
            })
            .fail(function(e){
                alert(e);
            });
        });

        $('#hideGraph').click(function(e){
            e.preventDefault();
            $('#graphContainer').slideUp(function(){
                $('#graphOverlay').show();
                $('#graph').empty();
                chart = null;
            });
        });

        if(act && act === "graph") {
            if(getJobCount() > 0){
                setTimeout(function(){
                    $('#graphJSONButton').trigger('click');
                }, 50);
            }
        }

        function scrollToGraph() {
            var container = $("#graphContainer");
            $('html, body').animate({
                'scrollTop': container.offset().top - $(window).height() + container.height() },
                1000,
                'swing'
            );
        }

        $(window).bind("beforeunload", function() {
            if(preventUnload){
                return "You are leaving this page.";
            }
        });

    });

    function doNotPreventUnloadConfirmation(){
        preventUnload = false;
    }

    function submitFormAJAX() {
        "use strict";
        var deferred=$.Deferred();
        var serializedFormData = $('#updateForm').serializeArray();

        if(!checkJobCount()) {
            deferred.reject("No jobs selected");
        } else {
            getChartDataWithGUIBehavior(serializedFormData)
            .done(function(d){
                try {
                    d = convertData2avgCharts(d);
                    drawChart(d);
                } catch(e) {
                    alert('Error occured while drawing chart: ' + e);
                    deferred.reject(e);
                    return;
                }

                deferred.resolve();

            })
            .fail(function(a){
                deferred.reject(a.message);
            });
        }

        return deferred.promise();
    }

    function showChartContainer(){
        "use strict";
        var d = $.Deferred();
        var container = $("#graphContainer");

        if(container.is(":hidden")){
            container.slideDown(1000, function(){
                d.resolve();
            });
        } else {
            d.resolve();
        }

        return d.promise();
    }

    function isChartContainerHidden() {
        return $("#graphContainer").is(":hidden");
    }

    function getChartData(params){
        "use strict";
        var d = $.Deferred();
        $.ajax({
            url: 'jash/flashGraph.json.php',
            data: params,
            method: "POST"
        }).done(function(data){
            if(data.status !== 200) {
                d.reject({
                    status:  data.status,
                    message: data.message
                });
            } else {
                d.resolve(data.results);
            }
        }).error(function(jqxhr){
            d.reject({
                status: jqxhr.status,
                message: jqxhr.statusText
            });
        });
        return d.promise();
    }

    function getChartDataWithGUIBehavior(params){
        "use strict";
        var d = $.Deferred();
        var button = $("#graphJSONButton");

        $.when(
            getChartData(params),
            $(button).attr('disabled', 'disabled')
            ,showChartContainer().done(function(){
                $('#graphOverlay').fadeIn(100);
            })
        ).done(function(data){
            d.resolve(data);
        }).fail(function(a){
            alert('Error getting data from the server\n'+a.message+' ('+a.status+')');
            d.reject(a);
        }).always(function(){
            $('#graphOverlay').fadeOut(600, function(){
                $(button).removeAttr('disabled');
            });
        });

        return d.promise();
    }

    /**
     * Converts data returned by server to format that can be consumed by AmCharts Serial chart
     * @param {Array} data
     */
    function convertData2avgCharts (data) {
        "use strict";
        var chartData = [];
        var seriesToJobNameMap = {};
        var seriesToMetricNameMap = {};
        var seriesToJobIdMap ={};
        var valueFields = [];
        var numberOfSeries = 0;
        var previousJobId = null;
        var i, j, k;

        for(i in data.series) {
            if(data.series.hasOwnProperty(i)){
                if(previousJobId !== null) {
                    if(data.series[previousJobId].dataSet.length !== data.series[i].dataSet.length) {
                        throw "Not equal datasets";
                    }
                }
                previousJobId = i;
                numberOfSeries++;
            }
        }

        /**
         *  Iterate all jobs and metrics to create mappings between value fields names and other data
         */
        for (k=0; k < data.metrics.length; k++) {
            for(i=0; i < data.jobs.length; i++) {
                seriesToJobNameMap[data.metrics[k] + "-" + data.jobs[i]] = data.series[data.jobs[i]].jobName;
                seriesToMetricNameMap[data.metrics[k] + "-" + data.jobs[i]] = data.metrics[k];
                seriesToJobIdMap[data.metrics[k] + "-" + data.jobs[i]] = data.jobs[i];
                valueFields.push(data.metrics[k] + "-" + data.jobs[i]);
            }
        }

        /**
         *  Functions to be put on every data point to be accessible from click event handler
         */
        var getJobName    = function(seriesName){
            return seriesToJobNameMap[seriesName];
        };

        var getMetricName = function(seriesName){
            return seriesToMetricNameMap[seriesName];
        };
        var getJobId      = function(seriesName){
            return seriesToJobIdMap[seriesName];
        };

        var getInterval   = function(){
            return data.interval;
        };

        /**
         *  Iterate all points and then all series to put all series in different fields but in one data serie
         */
        for(i=0; i<data.series[previousJobId].dataSet.length; i++) {
            var tmpPoint = {};
            tmpPoint['date'] = data.series[previousJobId].dataSet[i].DateFormatted;
            tmpPoint['timestamp'] = data.series[previousJobId].dataSet[i].UnixTimestamp;
            for(j in data.jobs) {
                if(data.jobs.hasOwnProperty(j)) {
                    for (k = 0; k < data.metrics.length; k++) {
                        if (data.series[data.jobs[j]].dataSet[i][data.metrics[k]]) {
                            tmpPoint[data.metrics[k] + "-" + data.jobs[j]] = (data.series[data.jobs[j]].dataSet[i][data.metrics[k]] / 1000).toFixed(2);
                            tmpPoint.getJobId = getJobId;
                            tmpPoint.getJobName = getJobName;
                            tmpPoint.getMetricName = getMetricName;
                            tmpPoint.getInterval = getInterval;
                        }
                    }
                }
            }
            chartData.push(tmpPoint);
        }

        return {
            getJobName    : function(seriesName){return seriesToJobNameMap[seriesName];},
            getMetricName : function(seriesName){return seriesToMetricNameMap[seriesName];},
            getJobId      : function(seriesName){return seriesToJobIdMap[seriesName];},
            valueFields: valueFields,
            series: chartData
        };
    }

    function drawChart(data) {
        "use strict";

        var getMetricName = data.getMetricName || function() {return 'No getMetricName function';};
        var getJobName    = data.getJobName ||    function() {return 'No getJobName function';};
        var getJobId      = data.getJobId ||      function() {return 'No getJobId function';};
        var graphs = [];

        /**
         *  Prepare graphs configs for all data series
         */
        for(var i in data.valueFields){
            if(data.valueFields.hasOwnProperty(i)) {
                graphs.push({
                    id                         : data.valueFields[i],
                    balloonText                : "[[category]]
" + getMetricName(data.valueFields[i]) + ": [[value]]",
                    bullet                     : "round",
                    bulletSize                 : 1,
                    bulletBorderAlpha          : 1,
                    bulletColor                : "#FFFFFF",
                    hideBulletsCount           : 0,
                    title                      : getJobName(data.valueFields[i]) + " " + getMetricName(data.valueFields[i]),
                    valueField                 : data.valueFields[i],
                    useLineColorForBulletBorder: true
                });
            }
        }

        var chartScrollbar = {
            autoGridCount    : true,
            graph            : data.valueFields[0],
            "scrollbarHeight": 20, hideResizeGrips: true
            // ,updateOnReleaseOnly: true
        };

        if(chart){
            /**
             *  If a chart is already instantiated new data provider is set and the chart redrawn.
             */
            chart.dataProvider = data.series;
            chart.graphs = graphs;

            chart.removeChartScrollbar();
            chart.chartScrollbar = chartScrollbar;

            chart.validateData();
        } else {
            // chart is instantiated from scratch
            chart = AmCharts.makeChart("graph", {
                type               : "serial",
                theme              : "none",
                pathToImages       : "js/amcharts/images/",
                dataProvider       : data.series,
                zoomOutOnDataUpdate: false,
                valueAxes          : [
                    {
                        axisAlpha : 0.2,
                        dashLength: 1,
                        position  : "left",
                        minimum   : 0,
                        unit      : "s"
                    }
                ],
                graphs             : graphs,
                chartScrollbar     : chartScrollbar,
                chartCursor        : {
                    cursorPosition           : "mouse",
                    categoryBalloonDateFormat: "MMM DD JJ:NN:SS", cursorAlpha: 0.5, graphBulletSize: 2
                },
                categoryField      : "date",
                dataDateFormat     : "YYYY-MM-DD JJ:NN:SS",
                categoryAxis       : {
                    parseDates      : true,
                    minorGridEnabled: false,
                    minPeriod       : "mm"
                },
                legend             : {
                    fontSize: 9
                },
                exportConfig       : {}
            });

            chart.addListener("clickGraphItem", function(e){
                var dataContext = e.item.dataContext;
                var valueField = e.graph.valueField;
                var resultsURL = getResultsURL(dataContext.getJobId(valueField), dataContext.timestamp, dataContext.getInterval());
                window.open(resultsURL);

            });
        }

        function getResultsURL(jobId, startDateTime, interval){
            var params = {
                currentPage  : 1,
                filterField  : "WPTJob.Id",
                filterValue  : jobId,
                startDateTime: startDateTime,
                endDateTime  : startDateTime + interval
            };
            return "listResults.php?"+$.param(params);
        }
        // drawTable(data);
    }

    function getJobCount(){
        var val = $('#jobs').val();
        var count;

        if(val === null) {count = 0;}
        else {count = val.length;}

        return count;
    }

    window.getChart      = function(){return chart;};

    wptmonitor.graph = {
        initialized: true,
        doNotPreventUnloadConfirmation: doNotPreventUnloadConfirmation
    };

    return wptmonitor;
})(window, jQuery, wptmonitor || {});
<|endoftext|>


<commit_before>define('spec/serialize', ['lyria/serialize', 'jquery'], function(serialize, $) {

  describe('serialize', function() {

    it('is a function', function() {
      expect(serialize).to.be.a('function');
    });

    it('should be undefined when calling without parameters', function() {
      expect(serialize()).to.equal(undefined);
    });

    it('should return the primitive input parameter as a string', function() {
      expect(serialize('test')).to.equal('"test"');
      expect(serialize(0)).to.equal('0');
      expect(serialize(true)).to.equal('true');
      expect(serialize(false)).to.equal('false');
    });

    it('should be undefined when input is a jquery object', function() {
      expect(serialize($('body'))).to.equal(undefined);
    });

  });

});
<commit_msg>Updated serialize test<commit_after>define('spec/serialize', ['lyria/serialize', 'jquery'], function(serialize, $) {

  describe('serialize', function() {

    it('is a function', function() {
      expect(serialize).to.be.a('function');
    });

    it('should be undefined when calling without parameters', function() {
      expect(serialize()).to.equal(undefined);
    });

    it('should return the primitive input parameter as a string', function() {
      expect(serialize('test')).to.equal('"test"');
      expect(serialize(0)).to.equal('0');
      expect(serialize(true)).to.equal('true');
      expect(serialize(false)).to.equal('false');
    });

    it('returns a stringified function when input parameter is a function', function() {
      var func = function() {
        return 5;
      };

      expect(serialize(func)).to.equal(func.toString());
    });

    it('should be undefined when input is a jquery object', function() {
      expect(serialize($('body'))).to.equal(undefined);
    });

    it('jquery objects serialize to null', function() {
      expect(serialize({
        elem: $('body')
      })).to.deep.equal(JSON.stringify({
        elem: null
      }));
    });

    it('serializes primitive types', function() {
      expect(serialize({
        a: 1,
        b: 'test',
        c: false
      })).to.deep.equal(JSON.stringify({
        a: 1,
        b: 'test',
        c: false
      }));
    });

  });

});
<|endoftext|>


<commit_before>var esl = module.exports = {};

//
// ESL Object
// http://wiki.freeswitch.org/wiki/Event_Socket_Library#ESL_Object
//

esl._log = false;
esl._level = 0;

//Calling this function within your program causes your program to
// issue informative messages related to the Event Socket Library
// on STDOUT. $loglevel is an integer between 0 and 7. The values for $loglevel mean:
//
//0 is EMERG
//1 is ALERT
//2 is CRIT
//3 is ERROR
//4 is WARNING
//5 is NOTICE
//6 is INFO
//7 is DEBUG
//
//Messages that have a lower value than $loglevel will be output on STDOUT, so higher
// values of $loglevel will cause the Library to log more information. Once this
// function is called, you can reduce the amount of log messages by calling this
// function again with a $loglevel of 0, but it cannot be completely turned off.
//
//eslSetLogLevel is implemented as class-level method, as opposed to an
// instance-level method, so you do not need to create a new instance of the
// class to call this method.
esl.setLogLevel = esl.eslSetLogLevel = function(level) {
    esl._log = true;
    esl._level = level;
};

//
// ESLevent Object
// http://wiki.freeswitch.org/wiki/Event_Socket_Library#ESLevent_Object
//

esl.Event = require('./esl/event');

//
// ESLconnection Object
// http://wiki.freeswitch.org/wiki/Event_Socket_Library#ESLconnection_Object
//

esl.Connection = require('./esl/connection');

//
// ESLparser Object
// Custom object to parse ESL data into an ESLevent
//

esl.Parser = require('./esl/parser');<commit_msg>Fixed exports<commit_after>var esl = module.exports = {};

//
// ESL Object
// http://wiki.freeswitch.org/wiki/Event_Socket_Library#ESL_Object
//

esl._log = false;
esl._level = 0;

//Calling this function within your program causes your program to
// issue informative messages related to the Event Socket Library
// on STDOUT. $loglevel is an integer between 0 and 7. The values for $loglevel mean:
//
//0 is EMERG
//1 is ALERT
//2 is CRIT
//3 is ERROR
//4 is WARNING
//5 is NOTICE
//6 is INFO
//7 is DEBUG
//
//Messages that have a lower value than $loglevel will be output on STDOUT, so higher
// values of $loglevel will cause the Library to log more information. Once this
// function is called, you can reduce the amount of log messages by calling this
// function again with a $loglevel of 0, but it cannot be completely turned off.
//
//eslSetLogLevel is implemented as class-level method, as opposed to an
// instance-level method, so you do not need to create a new instance of the
// class to call this method.
esl.setLogLevel = esl.eslSetLogLevel = function(level) {
    esl._log = true;
    esl._level = level;
};

//
// ESLevent Object
// http://wiki.freeswitch.org/wiki/Event_Socket_Library#ESLevent_Object
//

esl.Event = require('./esl/event').Event;

//
// ESLconnection Object
// http://wiki.freeswitch.org/wiki/Event_Socket_Library#ESLconnection_Object
//

esl.Connection = require('./esl/connection').Connection;

//
// ESLparser Object
// Custom object to parse ESL data into an ESLevent
//

esl.Parser = require('./esl/parser').Parser;<|endoftext|>


<commit_before>/**
 * The module instance cache.
 *
 * @class Cache
 */

// require deps
var fs = require('fs-extra');

engine.modules = engine.pojo('modules');
engine.instances = engine.pojo('module_instances', true);

/**
 * Create a module instance.
 *
 * @public
 * @param {string} The module instance name.
 * @param {string} The role name.
 * @param {function} The callback function.
 */
module.exports = function (name, role, callback) {
    var module_instance = engine.instances.get(name, role);

    // check if object is already in cache
    if (module_instance) {
        return callback(null, module_instance);
    }

    // handle access denied
    if (module_instance === 0) {
        return callback(new Error('access denied.'));
    }

    // create path to composition file
    var path =  engine.paths.app_composition + name + '.json';

    // read the composition json
    fs.readJson(path, function (err, composition) {

        // handle error and check role access
        if (err || !engine.roleAccess(composition, role)) {
            err = err || new Error('access denied.');
            console.error('lib/comp.js#120', err.toString());
            return callback(err);
        }

        // watch file
        if (module_instance !== null) {
            fs.watch(path, function (event) {

                // remove cached data on file change, to force reload
                if (event === 'change') {

                    // remove the cached item
                    engine.instances.set(name, null, role);
                }
            });
        }

        var count = 0;

        // update client resources paths
        if (composition.client) {

            // update css paths with fingerprints
            if (composition.client.css) {

                ++count;

                // update paths
                engine.file.addFingerprints(engine.paths.app_public, composition.client.css, function (err, paths) {

                    if (err) {
                        console.error('lib/comp.js#72', err.toString());
                        return callback(err);
                    }

                    if (--count === 0) {

                        // create component
                        factoryModuleInstance(name, composition, module_instance, callback);
                    }
                });
            }

            // TODO update html paths if html is loaded with link import (webcomponents)
            /*if (composition.client.html) {

                ++count;

                engine.file.addFingerprints(engine.paths.app_markup, composition.client.html, function (err, paths) {

                    if (err) {
                        console.error('lib/comp.js#96', err.toString());
                        return callback(err);
                    }

                    // composition.client.html = paths;

                    if (--count === 0) {

                        // create component
                        factoryModuleInstance(name, composition, module_instance, callback);
                    }
                }, {noCompression: true});
            }*/
        }

        if (count === 0) {
            factoryModuleInstance(name, composition, module_instance, callback);
        }
    });
};

//get the module's package infos
function factoryModuleInstance (name, composition, module_instance, callback) {

    getPackackeInfo(composition.module, function (err, moduleConfig) {

        if (err) {
            console.error('lib/comp.js#141', err.toString());
            return callback(err);
        }

        // extend module instance config with the module dependencies
        composition.client = composition.client || {};

        if (moduleConfig) {

            // all dependencies of the instance dependencies must be in this array!
            // while installing a module, save all dependencies in the module deps
            // dependencies: ['./file.js', 's/o/modA/v']
            // => ModA deps: ['./file.js', 's/o/modB/v'] => ModB deps: []
            // => to client: ['./file.js', 's/o/n/v/file.js']
            if (moduleConfig.clientLoad) {
                composition.client.scripts = moduleConfig.clientLoad;
            }

            // save main start script
            if (moduleConfig.main) {
                composition.main = moduleConfig.main;
            }
        }

        // create a new module instance
        module_instance = engine.module.factory(composition);

        // handle factory error
        if (module_instance instanceof Error) {
            console.error('lib/comp.js#170', module_instance.toString());
            return callback(module_instance);
        }

        // save module instance in cache
        engine.instances.set(name, module_instance);

        // save the module instance always under the configured name
        if (composition.name !== name) {
            engine.instances.set(composition.name, module_instance);
        }

        // return data
        callback(null, module_instance);
    });
}

/**
 * Parse and get the engine package infos.
 *
 * @private
 * @param {string} The module name or the custom module config object.
 * @param {function} The callback function.
 */
function getPackackeInfo (module, callback) {

    // handle custom modules
    if (typeof module === 'object') {

        if (!module.name) {
            var error = new Error('No module name.');
            console.error('lib/comp.js#176', error.toString());
            return callback(error);
        }

        // get module package info from cache
        var modulePackage = engine.modules.get(module.name);

        // return cached object
        if (modulePackage) {
            return callback(null, modulePackage);
        }

        return handleModule(module.name, module, callback);
    }

    // get module package info from cache
    var modulePackage = engine.modules.get(module);

    // return cached object
    if (modulePackage) {
        return callback(null, modulePackage);
    }

    // create module path
    var path = engine.paths.app_modules + module + '/package.json';

    // read and parse the packackage json file
    fs.readJson(path, function (err, packageInfo) {

        // handle errors
        if (err || !packageInfo) {
            err = err || new Error('No module package found.');
            console.error('lib/comp.js#241', err.toString());
            return callback(err);
        }

        // update file on change
        // TODO remove all module instance, when module changes
        if (modulePackage !== null) {
            fs.watch(path, function (event) {

                // remove cached data on file change, to force reload
                if (event === 'change') {

                    // set the cached module to null
                    engine.modules.set(module, null);
                }
            });
        }

        handleModule(module, packageInfo, callback);
    });
}

/**
 * Add fingerprints to client load scripts.
 *
 * @private
 * @param {string} The module name or the custom module config object.
 * @param {object} The package info.
 * @param {function} The callback function.
 */
function handleModule (module, packageInfo, callback) {

    // return custom module package
    if (!packageInfo.clientLoad) {

        // save package info in cache
        engine.modules.set(module, packageInfo);

        // return custom module
        return callback(null, module);
    }

    // add fingerprints to custom module dependencies
    engine.file.addFingerprints(engine.paths.app_modules + module + '/', packageInfo.clientLoad, function (err, scripts) {

        if (err) {
            console.error('lib/comp.js#213', err.toString());
            return callback(err);
        }

        // update the module dependencies with new script paths
        packageInfo.clientLoad = scripts;

        // save package info in cache
        engine.modules.set(module, packageInfo);

        // return the custom module package
        callback(null, packageInfo);
    }, {
        prependPath: module
    });
}
<commit_msg>collect an prepare module resources<commit_after>/**
 * The module instance cache.
 *
 * @class Cache
 */

// require deps
var fs = require('fs-extra');

engine.modules = engine.pojo('modules');
engine.instances = engine.pojo('module_instances', true);

/**
 * Create a module instance.
 *
 * @public
 * @param {string} The module instance name.
 * @param {string} The role name.
 * @param {function} The callback function.
 */
module.exports = function (name, role, callback) {

    var module_instance = engine.instances.get(name, role);

    // check if object is already in cache
    if (module_instance) {
        return callback(null, module_instance);
    }

    // handle access denied
    if (module_instance === 0) {
        return callback(new Error('access denied.'));
    }

    // create path to composition file
    var path =  engine.paths.app_composition + name + '.json';

    // read the composition json
    fs.readJson(path, function (err, composition) {

        // handle error and check role access
        if (err || !engine.roleAccess(composition, role)) {
            err = err || new Error('access denied.');
            console.error('lib/comp.js#120', err.toString());
            return callback(err);
        }

        // watch file
        if (module_instance !== null) {
            fs.watch(path, function (event) {

                // remove cached data on file change, to force reload
                if (event === 'change') {
                    console.log('COMPOSITION CHANGE:', name);
                    // set cached instance to null
                    engine.instances.set(name, null, role);
                }
            });
        }

        // check if composition has a module
        if (!composition.module || (typeof composition.module === 'object' && !composition.module.name)) {

            err = new Error('Incomplete module data in composition.');
            console.error('lib/comp.js#64', err.toString());
            return callback(err);
        }

        // read package info
        getModulePackage(composition.module, function (err, modulePackage) {

            if (err) {
                console.error('lib/comp.js#73', err.toString());
                return callback(err);
            }

            // add fingerprint to module instance components
            updateComponentPaths(
                composition.client || {},
                {
                    parentDir: engine.paths.app_public,
                    markup: {
                        parentDir: engine.paths.app_markup,
                        noCompression: true
                    }
                },
                function (err, components) {

                    if (err) {
                        console.error('lib/comp.js#90', err.toString());
                        return callback(err);
                    }

                    if (modulePackage.components) {

                        if (modulePackage.components.scripts) {
                            components.scripts = modulePackage.components.scripts;
                        }

                        if (modulePackage.components.styles) {

                            // ensure module instnace styles array
                            components.styles = components.styles || [];

                            for (var i = 0; i < modulePackage.components.styles.length; ++i) {
                                components.styles.push(modulePackage.components.styles[i]);
                            }
                        }

                        if (modulePackage.components.markup) {

                            // ensure module instnace markup array
                            components.markup = components.markup || [];

                            for (var i = 0; i < modulePackage.components.markup.length; ++i) {
                                components.markup.push(modulePackage.components.markup[i]);
                            }
                        }
                    }

                    // save main start script
                    if (modulePackage.main) {
                        composition.main = modulePackage.main;
                    }

                    // save updated paths
                    composition.client = components;

                    // create a new module instance
                    module_instance = engine.module.factory(composition);

                    // handle factory error
                    if (module_instance instanceof Error) {
                        console.error('lib/comp.js#170', module_instance.toString());
                        return callback(module_instance);
                    }

                    // save module instance in cache
                    engine.instances.set(name, module_instance);

                    // save the module instance always under the configured name
                    if (composition.name !== name) {
                        engine.instances.set(composition.name, module_instance);
                    }

                    console.log(composition);
                    console.log('-----------------------------------------------');
                    console.log(modulePackage.clientDependencies, modulePackage.components);

                    // return data
                    callback(null, module_instance);
                }
            );
        });
    });
};

/**
 * Parse and get the engine package infos.
 *
 * @private
 * @param {string} The module name or the custom module config object.
 * @param {function} The callback function.
 */
function getModulePackage (module, callback) {

    var moduleName = module.name || module;

    // get module package info from cache
    var modulePackage = engine.modules.get(moduleName);

    // return cached object
    if (modulePackage) {
        return callback(null, modulePackage);
    }

    // handle custom modules
    if (typeof module === 'object') {
        return handleModule(moduleName, module, callback);
    }

    // create module path
    var path = engine.paths.app_modules + moduleName + '/package.json';

    // read and parse the packackage json file
    fs.readJson(path, function (err, packageInfo) {

        // handle errors
        if (err || !packageInfo) {
            err = err || new Error('No module package found.');
            console.error('lib/comp.js#241', err.toString());
            return callback(err);
        }

        // update file on change
        // TODO remove all module instance, when module changes
        if (modulePackage !== null) {
            fs.watch(path, function (event) {

                // remove cached data on file change, to force reload
                if (event === 'change') {
                    console.log('PACKAGE CHANGE:', moduleName);
                    // set the cached module to null
                    engine.modules.set(moduleName, null);
                }
            });
        }

        handleModule(moduleName, packageInfo, callback);
    });
}

/**
 * Add fingerprints to client load scripts.
 *
 * @private
 * @param {string} The module name or the custom module config object.
 * @param {object} The package info.
 * @param {function} The callback function.
 */
function handleModule (moduleName, modulePackage, callback) {

    // TODO handle client dependencies
    // TODO update component paths

    // all dependencies of the instance dependencies must be in this array!
    // while installing a module, save all dependencies in the module deps
    // dependencies: ['./file.js', 's/o/modA/v']
    // => ModA deps: ['./file.js', 's/o/modB/v'] => ModB deps: []
    // => to client: ['./file.js', 's/o/n/v/file.js']

    // return custom module package
    if (!modulePackage.components) {

        // save package info in cache
        engine.modules.set(moduleName, modulePackage);

        // return custom module
        return callback(null, modulePackage);
    }

    // add fingerprints to module resources
    updateComponentPaths(
        modulePackage.components,
        {
            parentDir: engine.paths.app_modules + moduleName + '/',
            scripts: {prependPath: moduleName},
            markup: {noCompression: true}
        },
        function (err, components) {

            if (err) {
                console.error('lib/comp.js#206', err.toString());
                return callback(err);
            }

            modulePackage.components = components;

            callback(null, modulePackage);
        }
    );
}

//get the module's package infos
function updateComponentPaths (components, options, callback) {

    var count = 0;
    var parentDir = options.parentDir;

    for (var type in components) {

        switch (type) {
            case 'scripts':
            case 'markup':
            case 'styles':
                break;
            default:
              continue;
        }

        ++count;

        // get parent dir
        parentDir = options[type] && options[type].parentDir ? options[type].parentDir : options.parentDir;

         // update paths
        engine.file.addFingerprints(parentDir, components[type], function (err, paths) {

            if (err) {
                console.error('lib/comp.js#238', err.toString());
                return callback(err);
            }

            if (--count === 0) {

                // create component
                callback(null, components);
            }
        }, options[type]);
    }

    if (count === 0) {
        callback(null, components);
    }
}
<|endoftext|>


<commit_before>export default [
  {
    name: 'Razvan Stoenescu',
    role: 'Creator, Lead Dev & Architect',
    avatar: 'razvan_stoenescu.jpeg',
    email: 'razvan@quasar.dev',
    twitter: 'quasarframework',
    github: 'rstoenescu',
    desc: 'Architecture and development of Quasar on all fronts.'
  },

  {
    name: 'Dan Popescu',
    role: 'Senior Core Developer',
    avatar: 'dan_popescu.jpg',
    email: 'dan@quasar.dev',
    github: 'pdanpdan',
    desc: 'Focuses on Quasar UI components, directives and plugins.'
  },

  {
    name: 'Denjell Thompson-Yvetot',
    role: 'Senior Dev & Security Engineer',
    avatar: 'daniel_thompson-yvetot.jpg',
    email: 'denjell@quasar.dev',
    twitter: 'nothingismagick',
    github: 'nothingismagick',
    desc: 'Tooling and rigging app extensions, product development, Quasar Radio Show, community manager. Also writes articles.'
  },

  {
    name: 'Jeff Galbraith',
    role: 'Senior Developer',
    avatar: 'jeff_galbraith.jpg',
    email: 'jeff@quasar.dev',
    twitter: 'jgalbraith64',
    github: 'hawkeye64',
    desc: 'UI app extensions, the Quasar Radio Show and community outreach.'
  },

  {
    name: 'Lucas Nogueira',
    role: 'Senior Developer',
    avatar: 'lucas_nogueira.jpg',
    github: 'lucasfernog',
    desc: 'Quasar CLI development, Webview Quasar mode.'
  },

  {
    name: 'Allan Gaunt',
    role: 'Senior Developer',
    avatar: 'allan_gaunt.png',
    github: 'webnoob',
    desc: 'Web products and security research.'
  },

  {
    name: 'Scott Molinari',
    role: 'DevOps / Senior Developer',
    avatar: 'scott_molinari.jpg',
    github: 'smolinari',
    desc: 'Helps with docs, bug reports, external systems, writes articles and offers community support.'
  },

  {
    name: 'Tobias Mesquita',
    role: 'Senior Developer',
    avatar: 'tobias_mesquita.jpg',
    github: 'TobyMosque',
    desc: 'Help desk'
  },

  {
    name: 'Kerry Huguet',
    role: 'Senior Developer',
    avatar: 'kerry_huguet.jpeg',
    github: 'outofmemoryagain',
    desc: 'Typescript support'
  },

  {
    name: 'Noah Klayman',
    role: 'DevOps / Community Staff',
    avatar: 'noah_klayman.jpeg',
    github: 'nklayman',
    desc: 'GraphQL, App Extensions'
  },

  {
    name: 'Aldrin Marquez',
    role: 'Community Staff',
    avatar: 'aldrin_marquez.jpg',
    github: 'metalsadman',
    desc: 'Help desk'
  },

  {
    name: 'Matyáš Racek',
    role: 'Community Staff',
    avatar: 'matyas_panstromek.jpeg',
    github: 'panstromek',
    desc: 'Help desk'
  },

  {
    name: 'James Harrington',
    role: 'Community Staff',
    avatar: 'james_harrington.jpeg',
    github: 'codenamezjames',
    desc: 'Help desk'
  },

  {
    name: 'Ross Ball',
    role: 'Designer / Community Staff',
    avatar: 'ross_ball.jpeg',
    github: 'rossity',
    desc: 'Quasar Themes'
  },

  {
    name: 'James Gilchrist',
    role: 'Community Staff',
    avatar: 'james_gilchrist.png',
    github: 'jpgilchrist',
    desc: 'Help desk'
  },

  {
    name: 'Ben Coughenour',
    role: 'Community Staff',
    avatar: 'ben_coughenour.jpg',
    github: 'sskwrl',
    desc: 'Help desk'
  },

  {
    name: 'Heitor Ribeiro',
    role: 'Community Staff',
    avatar: 'heitor_ribeiro.jpg',
    github: 'bloodf',
    desc: 'Writes articles and offers community support.'
  },

    {
    name: 'David Watson',
    role: 'Community Staff',
    avatar: 'david_watson.jpg',
    github: 'realtimeappsolutions',
    desc: 'Marketing and PR.'
  },

  {
    name: 'Stanislav Valasek',
    role: 'Community Staff',
    avatar: 'stanislav_valasek.jpg',
    github: 'valasek',
    desc: 'Marketing, Open Source Compliance, Community experience.'
  }
]
<commit_msg>Update team.js<commit_after>export default [
  {
    name: 'Razvan Stoenescu',
    role: 'Creator, Lead Dev & Architect',
    avatar: 'razvan_stoenescu.jpeg',
    email: 'razvan@quasar.dev',
    twitter: 'quasarframework',
    github: 'rstoenescu',
    desc: 'Architecture and development of Quasar on all fronts.'
  },

  {
    name: 'Dan Popescu',
    role: 'Senior Core Developer',
    avatar: 'dan_popescu.jpg',
    email: 'dan@quasar.dev',
    github: 'pdanpdan',
    desc: 'Focuses on Quasar UI components, directives and plugins.'
  },

  {
    name: 'Denjell Thompson-Yvetot',
    role: 'Senior Dev & Security Engineer',
    avatar: 'daniel_thompson-yvetot.jpg',
    email: 'denjell@quasar.dev',
    twitter: 'nothingismagick',
    github: 'nothingismagick',
    desc: 'Tooling and rigging app extensions, product development, Quasar Radio Show, community manager. Also writes articles.'
  },

  {
    name: 'Jeff Galbraith',
    role: 'Senior Developer',
    avatar: 'jeff_galbraith.jpg',
    email: 'jeff@quasar.dev',
    twitter: 'jgalbraith64',
    github: 'hawkeye64',
    desc: 'UI app extensions, the Quasar Radio Show and community outreach.'
  },

  {
    name: 'Lucas Nogueira',
    role: 'Senior Developer',
    avatar: 'lucas_nogueira.jpg',
    github: 'lucasfernog',
    desc: 'Quasar CLI development, Webview Quasar mode.'
  },

  {
    name: 'Allan Gaunt',
    role: 'Senior Developer',
    avatar: 'allan_gaunt.png',
    github: 'webnoob',
    desc: 'Web products and security research.'
  },

  {
    name: 'Scott Molinari',
    role: 'DevOps / Senior Developer',
    avatar: 'scott_molinari.jpg',
    github: 'smolinari',
    desc: 'Helps with docs, bug reports, external systems, writes articles and offers community support.'
  },

  {
    name: 'Tobias Mesquita',
    role: 'Senior Developer',
    avatar: 'tobias_mesquita.jpg',
    github: 'TobyMosque',
    desc: 'Help desk'
  },

  {
    name: 'Kerry Huguet',
    role: 'Senior Developer',
    avatar: 'kerry_huguet.jpeg',
    github: 'outofmemoryagain',
    desc: 'Typescript support'
  },

  {
    name: 'Noah Klayman',
    role: 'DevOps / Community Staff',
    avatar: 'noah_klayman.jpeg',
    github: 'nklayman',
    desc: 'GraphQL, App Extensions'
  },

  {
    name: 'Aldrin Marquez',
    role: 'Community Staff',
    avatar: 'aldrin_marquez.jpg',
    github: 'metalsadman',
    desc: 'Help desk'
  },

  {
    name: 'Matyáš Racek',
    role: 'Community Staff',
    avatar: 'matyas_panstromek.jpeg',
    github: 'panstromek',
    desc: 'Help desk'
  },

  {
    name: 'James Harrington',
    role: 'Community Staff',
    avatar: 'james_harrington.jpeg',
    github: 'codenamezjames',
    desc: 'Help desk'
  },

  {
    name: 'Ross Ball',
    role: 'Designer / Community Staff',
    avatar: 'ross_ball.jpeg',
    github: 'rossity',
    desc: 'Quasar Themes'
  },

  {
    name: 'James Gilchrist',
    role: 'Community Staff',
    avatar: 'james_gilchrist.png',
    github: 'jpgilchrist',
    desc: 'Help desk'
  },

  {
    name: 'Ben Coughenour',
    role: 'Community Staff',
    avatar: 'ben_coughenour.jpg',
    github: 'sskwrl',
    desc: 'Help desk'
  },

  {
    name: 'Heitor Ribeiro',
    role: 'Community Staff',
    avatar: 'heitor_ribeiro.jpg',
    github: 'bloodf',
    desc: 'Writes articles and offers community support.'
  },

  {
    name: 'David Watson',
    role: 'Community Staff',
    avatar: 'david_watson.jpg',
    github: 'realtimeappsolutions',
    desc: 'Marketing and PR.'
  },

  {
    name: 'Stanislav Valasek',
    role: 'Community Staff',
    avatar: 'stanislav_valasek.jpg',
    github: 'valasek',
    desc: 'Marketing, Open Source Compliance, Community experience.'
  }
]
<|endoftext|>


<commit_before>'use strict';

module.exports = {
	db: 'mongodb://localhost/sts-integratedsystem',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.min.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
			],
			js: [
				'public/lib/angular/angular.min.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-cookies/angular-cookies.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-touch/angular-touch.js',
				'public/lib/angular-sanitize/angular-sanitize.js',
				'public/lib/angular-ui-router/release/angular-ui-router.min.js',
				'public/lib/angular-ui-utils/ui-utils.min.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
			]
		},
		css: 'public/dist/application.min.css',
		js: 'public/dist/application.min.js'
	},
	facebook: {
		clientID: process.env.FACEBOOK_ID || 'APP_ID',
		clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
		callbackURL: '/auth/facebook/callback'
	},
	twitter: {
		clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
		clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
		callbackURL: '/auth/twitter/callback'
	},
	google: {
		clientID: process.env.GOOGLE_ID || 'APP_ID',
		clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
		callbackURL: '/auth/google/callback'
	},
	linkedin: {
		clientID: process.env.LINKEDIN_ID || 'APP_ID',
		clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
		callbackURL: '/auth/linkedin/callback'
	},
	github: {
		clientID: process.env.GITHUB_ID || 'APP_ID',
		clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
		callbackURL: '/auth/github/callback'
	},
	mailer: {
		from: process.env.MAILER_FROM || 'MAILER_FROM',
		options: {
			service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
			auth: {
				user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
				pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
			}
		}
	}
};
<commit_msg>Update production config<commit_after>'use strict';

module.exports = {
	db: 'mongodb://localhost/sts-integratedsystem',
	assets: {
		lib: {
			css: [
                'public/lib/bootstrap/dist/css/bootstrap.css',
                'public/lib/bootstrap-material-design/dist/css/roboto.min.css',
                'public/lib/bootstrap-material-design/dist/css/material.min.css',
                'public/lib/bootstrap-material-design/dist/css/ripples.min.css'
			],
			js: [
				'public/lib/angular/angular.min.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-cookies/angular-cookies.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-touch/angular-touch.js',
				'public/lib/angular-sanitize/angular-sanitize.js',
				'public/lib/angular-ui-router/release/angular-ui-router.min.js',
				'public/lib/angular-ui-utils/ui-utils.min.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js',
                'public/lib/bootstrap-material-design/dist/js/ripples.min.js',
                'public/lib/bootstrap-material-design/dist/js/material.min.js'
			]
		},
		css: 'public/dist/application.min.css',
		js: 'public/dist/application.min.js'
	},
	facebook: {
		clientID: process.env.FACEBOOK_ID || 'APP_ID',
		clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
		callbackURL: '/auth/facebook/callback'
	},
	twitter: {
		clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
		clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
		callbackURL: '/auth/twitter/callback'
	},
	google: {
		clientID: process.env.GOOGLE_ID || 'APP_ID',
		clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
		callbackURL: '/auth/google/callback'
	},
	linkedin: {
		clientID: process.env.LINKEDIN_ID || 'APP_ID',
		clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
		callbackURL: '/auth/linkedin/callback'
	},
	github: {
		clientID: process.env.GITHUB_ID || 'APP_ID',
		clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
		callbackURL: '/auth/github/callback'
	},
	mailer: {
		from: process.env.MAILER_FROM || 'MAILER_FROM',
		options: {
			service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
			auth: {
				user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
				pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
			}
		}
	}
};
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { FilesCollection } from 'meteor/ostrio:files';
import fs from 'fs';
import path from 'path';
import { createBucket } from './lib/grid/createBucket';
import { createOnAfterUpload } from './lib/fsHooks/createOnAfterUpload';
import { createInterceptDownload } from './lib/fsHooks/createInterceptDownload';
import { createOnAfterRemove } from './lib/fsHooks/createOnAfterRemove';

let attachmentBucket;
if (Meteor.isServer) {
  attachmentBucket = createBucket('attachments');
}

const insertActivity = (fileObj, activityType) =>
  Activities.insert({
    userId: fileObj.userId,
    type: 'card',
    activityType,
    attachmentId: fileObj._id,
    // this preserves the name so that notifications can be meaningful after
    // this file is removed
    attachmentName: fileObj.name,
    boardId: fileObj.meta.boardId,
    cardId: fileObj.meta.cardId,
    listId: fileObj.meta.listId,
    swimlaneId: fileObj.meta.swimlaneId,
  });

// XXX Enforce a schema for the Attachments FilesCollection
// see: https://github.com/VeliovGroup/Meteor-Files/wiki/Schema

Attachments = new FilesCollection({
  debug: false, // Change to `true` for debugging
  collectionName: 'attachments',
  allowClientCode: true,
  storagePath() {
    if (process.env.WRITABLE_PATH) {
      return path.join(process.env.WRITABLE_PATH, 'uploads', 'attachments');
    }
    return path.normalize(`assets/app/uploads/${this.collectionName}`);
  },
  onAfterUpload: function onAfterUpload(fileRef) {
    createOnAfterUpload(attachmentBucket).call(this, fileRef);
    // If the attachment doesn't have a source field
    // or its source is different than import
    if (!fileRef.meta.source || fileRef.meta.source !== 'import') {
      // Add activity about adding the attachment
      insertActivity(fileRef, 'addAttachment');
    }
  },
  interceptDownload: createInterceptDownload(attachmentBucket),
  onAfterRemove: function onAfterRemove(files) {
    createOnAfterRemove(attachmentBucket).call(this, files);
    files.forEach(fileObj => {
      insertActivity(fileObj, 'deleteAttachment');
    });
  },
  // We authorize the attachment download either:
  // - if the board is public, everyone (even unconnected) can download it
  // - if the board is private, only board members can download it
  protected(fileObj) {
    const board = Boards.findOne(fileObj.meta.boardId);
    if (board.isPublic()) {
      return true;
    }
    return board.hasMember(this.userId);
  },
});

if (Meteor.isServer) {
  Attachments.allow({
    insert(userId, fileObj) {
      return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
    },
    update(userId, fileObj) {
      return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
    },
    remove(userId, fileObj) {
      return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
    },
    fetch: ['meta'],
  });

  Meteor.startup(() => {
    Attachments.collection._ensureIndex({ 'meta.cardId': 1 });
    const storagePath = Attachments.storagePath();
    console.log("Meteor.startup check storagePath: ", storagePath);
    if (!fs.existsSync(storagePath)) {
      console.log("create storagePath because it doesn't exist: " + storagePath);
      fs.mkdirSync(storagePath, { recursive: true });
    }
  });
}

export default Attachments;
<commit_msg>remove old attachment storagePath log message<commit_after>import { Meteor } from 'meteor/meteor';
import { FilesCollection } from 'meteor/ostrio:files';
import fs from 'fs';
import path from 'path';
import { createBucket } from './lib/grid/createBucket';
import { createOnAfterUpload } from './lib/fsHooks/createOnAfterUpload';
import { createInterceptDownload } from './lib/fsHooks/createInterceptDownload';
import { createOnAfterRemove } from './lib/fsHooks/createOnAfterRemove';

let attachmentBucket;
if (Meteor.isServer) {
  attachmentBucket = createBucket('attachments');
}

const insertActivity = (fileObj, activityType) =>
  Activities.insert({
    userId: fileObj.userId,
    type: 'card',
    activityType,
    attachmentId: fileObj._id,
    // this preserves the name so that notifications can be meaningful after
    // this file is removed
    attachmentName: fileObj.name,
    boardId: fileObj.meta.boardId,
    cardId: fileObj.meta.cardId,
    listId: fileObj.meta.listId,
    swimlaneId: fileObj.meta.swimlaneId,
  });

// XXX Enforce a schema for the Attachments FilesCollection
// see: https://github.com/VeliovGroup/Meteor-Files/wiki/Schema

Attachments = new FilesCollection({
  debug: false, // Change to `true` for debugging
  collectionName: 'attachments',
  allowClientCode: true,
  storagePath() {
    if (process.env.WRITABLE_PATH) {
      return path.join(process.env.WRITABLE_PATH, 'uploads', 'attachments');
    }
    return path.normalize(`assets/app/uploads/${this.collectionName}`);
  },
  onAfterUpload: function onAfterUpload(fileRef) {
    createOnAfterUpload(attachmentBucket).call(this, fileRef);
    // If the attachment doesn't have a source field
    // or its source is different than import
    if (!fileRef.meta.source || fileRef.meta.source !== 'import') {
      // Add activity about adding the attachment
      insertActivity(fileRef, 'addAttachment');
    }
  },
  interceptDownload: createInterceptDownload(attachmentBucket),
  onAfterRemove: function onAfterRemove(files) {
    createOnAfterRemove(attachmentBucket).call(this, files);
    files.forEach(fileObj => {
      insertActivity(fileObj, 'deleteAttachment');
    });
  },
  // We authorize the attachment download either:
  // - if the board is public, everyone (even unconnected) can download it
  // - if the board is private, only board members can download it
  protected(fileObj) {
    const board = Boards.findOne(fileObj.meta.boardId);
    if (board.isPublic()) {
      return true;
    }
    return board.hasMember(this.userId);
  },
});

if (Meteor.isServer) {
  Attachments.allow({
    insert(userId, fileObj) {
      return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
    },
    update(userId, fileObj) {
      return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
    },
    remove(userId, fileObj) {
      return allowIsBoardMember(userId, Boards.findOne(fileObj.boardId));
    },
    fetch: ['meta'],
  });

  Meteor.startup(() => {
    Attachments.collection._ensureIndex({ 'meta.cardId': 1 });
    const storagePath = Attachments.storagePath();
    if (!fs.existsSync(storagePath)) {
      console.log("create storagePath because it doesn't exist: " + storagePath);
      fs.mkdirSync(storagePath, { recursive: true });
    }
  });
}

export default Attachments;
<|endoftext|>


<commit_before>var milkcocoa = new MilkCocoa('uniicwq7emj.mlkcca.com');
<commit_msg>app_id<commit_after>var milkcocoa = new MilkCocoa('{your-app-id}.mlkcca.com');
<|endoftext|>


<commit_before>require('proof')(2, async (okay) => {
    const Destructible = require('destructible')
    const destructible = new Destructible('split-branch.t')

    const Strata = require('../strata')
    const Cache = require('../cache')
    const utilities = require('./utilities')
    const path = require('path')
    const directory = path.join(utilities.directory, 'split-branch')
    await utilities.reset(directory)
    const leaf = utilities.alphabet(3, 3).slice(0, 20)
    await utilities.serialize(directory, {
        '0.0': [[ '0.1', null ]],
        '0.1': [[ 'right', null ]].concat(leaf.slice(1).map((word, index) => {
            return [ 'insert', index, word ]
        }))
    })

    destructible.durable('test', async function () {
        async function split () {
            const cache = new Cache
            const strata = new Strata(destructible.ephemeral('split'), { directory, cache })
            await strata.open()
            const cursor = (await strata.search(leaf[0])).get()
            cursor.insert(leaf[0], leaf[0], cursor.index)
            cursor.release()
            await cursor.flush()
            await strata.close()
            cache.purge(0)
            // **TODO** broken test...
            // okay(cache.heft, 0, 'cache purged')
        }
        await split()
        async function reopen () {
            const cache = new Cache
            const strata = new Strata(destructible.ephemeral('reopen'), { directory, cache })
            await strata.open()
            const cursor = (await strata.search(leaf[0])).get()
            okay(cursor.items[cursor.index].value, leaf[0], 'found')
            cursor.release()
            await strata.close()
        }
        await reopen()
        async function traverse () {
            const cache = new Cache
            const strata = new Strata(destructible.ephemeral('traverse'), { directory, cache })
            await strata.open()
            let right = leaf[0]
            const items = []
            do {
                const cursor = (await strata.search(right)).get()
                for (let i = cursor.index; i < cursor.items.length; i++) {
                    items.push(cursor.items[i].value)
                }
                cursor.release()
                right = cursor.page.right
            } while (right != null)
            okay(items, leaf, 'traverse')
            await strata.close()
        }
        await traverse()
    })

    await destructible.destructed
})
<commit_msg>Fix split branch test.<commit_after>require('proof')(2, async (okay) => {
    const Destructible = require('destructible')
    const destructible = new Destructible('split-branch.t')

    const Strata = require('../strata')
    const Cache = require('../cache')
    const utilities = require('./utilities')
    const path = require('path')
    const directory = path.join(utilities.directory, 'split-branch')
    await utilities.reset(directory)
    const leaf = utilities.alphabet(4, 4).slice(0, 33)
    await utilities.serialize(directory, {
        '0.0': [[ '0.1', null ]],
        '0.1': [[ 'right', null ]].concat(leaf.slice(1).map((word, index) => {
            return [ 'insert', index, word ]
        }))
    })

    destructible.durable('test', async function () {
        async function split () {
            const cache = new Cache
            const strata = new Strata(destructible.ephemeral('split'), { directory, cache })
            await strata.open()
            const cursor = (await strata.search(leaf[0])).get()
            cursor.insert(leaf[0], leaf[0], cursor.index)
            cursor.release()
            await cursor.flush()
            await strata.close()
            cache.purge(0)
            // **TODO** broken test...
            // okay(cache.heft, 0, 'cache purged')
        }
        await split()
        async function reopen () {
            const cache = new Cache
            const strata = new Strata(destructible.ephemeral('reopen'), { directory, cache })
            await strata.open()
            const cursor = (await strata.search(leaf[0])).get()
            okay(cursor.items[cursor.index].value, leaf[0], 'found')
            cursor.release()
            await strata.close()
        }
        await reopen()
        async function traverse () {
            const cache = new Cache
            const strata = new Strata(destructible.ephemeral('traverse'), { directory, cache })
            await strata.open()
            let right = leaf[0]
            const items = []
            do {
                const cursor = (await strata.search(right)).get()
                for (let i = cursor.index; i < cursor.items.length; i++) {
                    items.push(cursor.items[i].value)
                }
                cursor.release()
                right = cursor.page.right
            } while (right != null)
            okay(items, leaf, 'traverse')
            await strata.close()
        }
        await traverse()
    })

    await destructible.destructed
})
<|endoftext|>


<commit_before>FRTool.initFR(FRData);
var DEFAULT_FONT = "14pt cursive";
var DEFAULT_BACKGROUND = "transparent";
var DEFAULT_NAME_FONT = "24pt cursive";

function getRandomNumber(range) {
    return range[Math.floor(Math.random() * range.length)];
}

function getImgUrl(dragonID, isLeft) {
    if (dragonID == "") {
        if(isLeft){
            dragonID = getRandomNumber([1, 6, 7, 8, 9, 11]);
        } else {
            dragonID = getRandomNumber([2, 3, 4, 5, 10]);
        }
    }
    var dragonID = parseInt(dragonID);
    var miniDragonId = Math.ceil(dragonID / 100);
    if (dragonId % 100 == 0) {
        miniDragonId += 1;
    }
    return 'http://flightrising.com/rendern/350/' + miniDragonId + '/' + dragonID + '_350.png'
}

function initGeneSelect(id, type) {
  for (var i = 0; i < FRTool.Oddss.length; i++) {
    var genes = FRTool.getGene(FRTool.Oddss[i], type);
    var group = $("<optgroup></optgroup>")
      .attr("data-localize", FRTool.Oddss[i].Name)
      .attr("label", FRTool.Oddss[i].Name);
    for (var j = 0; j < genes.length; j++) {
      group.append($("<option></option>")
        .attr("data-localize", genes[j].Name)
        .attr("value", genes[j].Name)
        .text(genes[j].Name));
    };
    $('#' + id).append(group);
  };
}

function initColorSelect(id) {
  for (var i = 0; i < FRTool.Colors.length; i++) {
    $('#' + id).append(
      $("<option></option>")
      .attr("data-localize", FRTool.Colors[i].Name)
      .attr("class", FRTool.Colors[i].Name)
      .attr("value", FRTool.Colors[i].Name)
      .text(FRTool.Colors[i].Name)
    );
  }
}

function initBreedSelect(id) {
  for (var i = 0; i < FRTool.Oddss.length; i++) {
    var breeds = FRTool.getBreed(FRTool.Oddss[i]);
    var group = $("<optgroup></optgroup>")
    .attr("data-localize", FRTool.Oddss[i].Name)
    .attr("label", FRTool.Oddss[i].Name);
    for (var j = 0; j < breeds.length; j++) {
      group.append($("<option></option>")
        .attr("data-localize", breeds[j].Name)
        .attr("value", breeds[j].Name)
        .text(breeds[j].Name));
    };
    $('#' + id).append(group);
  };
}

function UpdateColorClass(colorSelect) {
    colorSelect.removeClass();
    colorSelect.addClass("form-control");
    colorSelect.addClass(colorSelect.val());
}

function drawName(canvasContext, text, x, y, font, textAlign, color, shadowcolor) {
    canvasContext.font = font || DEFAULT_NAME_FONT;
    canvasContext.textAlign = textAlign
    canvasContext.shadowOffsetX = 2;
    canvasContext.shadowOffsetY = 2;
    canvasContext.shadowBlur = 2;
    canvasContext.shadowColor = shadowcolor;
    canvasContext.fillStyle = color;
    canvasContext.fillText(text, x, y);
}

function drawImage(canvasContext, src, x, y, width, height, flip, callback) {
    if (src) {
        var img = new Image();
        img.src = src;

        img.onload = function() {
            if(flip) {
                img.crossOrigin = "Anonymous";
                canvasContext.scale(-1, 1);
                canvasContext.drawImage(img, -x - width, y, width, height);
                canvasContext.scale(-1, 1);
            } else {
                canvasContext.drawImage(img, x, y, width, height);
            }
            callback();
        }
    }
}

function drawColorRange(canvasContext, range, lineColor, y) {
    var single = 10;
    var width;
    do {
        single -= 1;
        width = range.length * (single + 1);
    } while (width > 200);
    var startX = 320 - width / 2;
    for (var i = 0; i < range.length; i++) {
        canvasContext.lineWidth = "2";
        canvasContext.strokeStyle = lineColor;
        canvasContext.lineCap = "square";
        canvasContext.beginPath();
        canvasContext.rect(startX, y, single, 20);
        canvasContext.stroke();

        canvasContext.fillStyle = range[i].Color;
        canvasContext.fillRect(startX, y, single, 20);
        startX += single + 1;
    }
}

function drawGene(canvasContext, font, gene1, gene2, color, leftcolor, rightcolor, y) {
    var width = 80;
    var imgWidth = 640;
    canvasContext.font = font || DEFAULT_FONT;
        if (gene1 == gene2) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = color;
            canvasContext.fillText(gene1.Name, imgWidth / 2, y);
            canvasContext.fillRect((imgWidth - width)/2, y + 4, width, 3);
        } else {
            var rate = FRTool.getGeneRate(gene1, gene2);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = leftcolor;
            canvasContext.fillText(gene1.Name, imgWidth / 2 - 6, y);
            canvasContext.fillRect(imgWidth / 2 - width - 1, y + 4, width * 2 * rate[0], 3);
            canvasContext.textAlign = "start";
            canvasContext.fillStyle = rightcolor;
            canvasContext.fillText(gene2.Name, imgWidth / 2 + 6, y);
            canvasContext.fillRect(imgWidth / 2 - width + 1 + width * 2 * rate[0], y + 4, width * 2 * rate[1], 3);
        }
}

function drawBreed(canvasContext, font, breed1, breed2, color, leftcolor, rightcolor, y) {
    var width = 80;
    var imgWidth = 640;
    canvasContext.font = font || DEFAULT_FONT;
        if (breed1 == breed2) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = color;
            canvasContext.fillText(breed1.Name, imgWidth / 2, y);
            canvasContext.fillRect((imgWidth - width)/2, y + 4, width, 3);
        } else {
            var rate = FRTool.getBreedRate(breed1, breed2);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = leftcolor;
            canvasContext.fillText(breed1.Name, imgWidth / 2 - 6, y);
            canvasContext.fillRect(imgWidth / 2 - width - 1, y + 4, width * 2 * rate[0], 3);
            canvasContext.textAlign = "start";
            canvasContext.fillStyle = rightcolor;
            canvasContext.fillText(breed2.Name, imgWidth / 2 + 6, y);
            canvasContext.fillRect(imgWidth / 2 - width + 1 + width * 2 * rate[0], y + 4, width * 2 * rate[1], 3);
        }
}

function drawCard(canvasId, cardData) {
    var canvas = document.getElementById(canvasId);
    canvas.setAttribute('width', '640');
    canvas.setAttribute('height', '240');
    var canvasContext = canvas.getContext("2d");
    canvasContext.clearRect(0, 0, 640, 240);

    // background
    canvasContext.fillStyle = cardData.background || DEFAULT_BACKGROUND;
    canvasContext.fillRect(0, 0, 640, 240);

    // breed
    drawBreed(canvasContext, cardData.geneFont,
        cardData.dragon1.breed, cardData.dragon2.breed,
        cardData.geneColor.basic, cardData.geneColor.left, cardData.geneColor.right, 31);

    // primary gene
    drawGene(canvasContext, cardData.geneFont,
        cardData.dragon1.primarygene, cardData.dragon2.primarygene,
        cardData.geneColor.basic, cardData.geneColor.left, cardData.geneColor.right, 66);

    // primary color
    drawColorRange(canvasContext,
        FRTool.getColorRange(cardData.dragon1.primarycolor, cardData.dragon2.primarycolor),
        cardData.lineColor, 80);

    // secondary gene
    drawGene(canvasContext, cardData.geneFont,
        cardData.dragon1.secondarygene, cardData.dragon2.secondarygene,
        cardData.geneColor.basic, cardData.geneColor.left, cardData.geneColor.right, 128);

    // secondary color
    drawColorRange(canvasContext,
        FRTool.getColorRange(cardData.dragon1.secondarycolor, cardData.dragon2.secondarycolor),
        cardData.lineColor, 142);

    // tertiary gene
    drawGene(canvasContext, cardData.geneFont,
        cardData.dragon1.tertiarygene, cardData.dragon2.tertiarygene,
        cardData.geneColor.basic, cardData.geneColor.left, cardData.geneColor.right, 190);

    // tertiary color
    drawColorRange(canvasContext,
        FRTool.getColorRange(cardData.dragon1.tertiarycolor, cardData.dragon2.tertiarycolor),
        cardData.lineColor, 204);

    // image 1
    drawImage(canvasContext, getImgUrl(cardData.dragon1.id, false),
        0, 0, 240, 240, cardData.dragon1.imgflip,
        function(){
            if (cardData.dragonName.enable) {
                drawName(canvasContext,
                    cardData.dragon1.name, 20, 200,
                    cardData.dragonName.font, "start",
                    cardData.dragonName.color, cardData.dragonName.shadowcolor);
            }
        });

    // image 2
    drawImage(canvasContext, getImgUrl(cardData.dragon2.id, true),
        400, 0, 240, 240, cardData.dragon2.imgflip,
        function(){
            if (cardData.dragonName.enable) {
                drawName(canvasContext,
                    cardData.dragon2.name, 620, 200,
                    cardData.dragonName.font, "end",
                    cardData.dragonName.color, cardData.dragonName.shadowcolor);
            }
        });

    return canvas;
}

function setCookie(cookie, label) {
  if(Cookies.get(cookie)){
    $('#' + label).val(Cookies.get(cookie));
  }
}

function setCheckCookie(cookie, label) {
  if(Cookies.get(cookie)){
    $('#' + label).prop("checked", Cookies.get(cookie));
  }
}

initBreedSelect('o_breed');
initBreedSelect('a_breed');

initGeneSelect('o_Primary_gene', 'Primary');
initGeneSelect('a_Primary_gene', 'Primary');
initGeneSelect('o_Secondary_gene', 'Secondary');
initGeneSelect('a_Secondary_gene', 'Secondary');
initGeneSelect('o_Tertiary_gene', 'Tertiary');
initGeneSelect('a_Tertiary_gene', 'Tertiary');

initColorSelect('o_primary_color');
initColorSelect('o_secondary_color');
initColorSelect('o_tertiary_color');
initColorSelect('a_primary_color');
initColorSelect('a_secondary_color');
initColorSelect('a_tertiary_color');

setCookie("o_breed", "o_breed");
setCookie("a_breed", "a_breed");
setCookie("o_name", "o_name");
setCookie("a_name", "a_name");
setCookie("o_id", "o_id");
setCookie("a_id", "a_id");
setCheckCookie("o_flip", "o_flip");
setCheckCookie("a_flip", "a_flip");

for (var i = $("[id$=_gene]").length - 1; i >= 0; i--) {
  var form = $($("[id$=_gene]")[i]);
  setCookie(form.attr('id').substring(0, form.attr('id').length - 5), form.attr('id'));
};

for (var i = $("[id$=_color]").length - 1; i >= 0; i--) {
  var form = $($("[id$=_color]")[i]);
  setCookie(form.attr('id'), form.attr('id'));
};

for (var i = $("[id$=_Color]").length - 1; i >= 0; i--) {
  var form = $($("[id$=_Color]")[i]);
  setCookie(form.attr('id'), form.attr('id'));
};

$("[id=draw]").click(function() {
    var card_data = {
        'dragon1': {
            'id': $('#o_id').val(),
            'name': $('#o_name').val(),
            'breed': FRTool.Breed[$('#o_breed').val()],
            'primarygene': FRTool.PrimaryGene[$('#o_Primary_gene').val()],
            'secondarygene': FRTool.SecondaryGene[$('#o_Secondary_gene').val()],
            'tertiarygene': FRTool.TertiaryGene[$('#o_Tertiary_gene').val()],
            'primarycolor': FRTool.Color[$('#o_primary_color').val()],
            'secondarycolor': FRTool.Color[$('#o_secondary_color').val()],
            'tertiarycolor': FRTool.Color[$('#o_tertiary_color').val()],
            'imgflip' : $('#o_flip').is(':checked')
        },
        'dragon2': {
            'id': $('#a_id').val(),
            'name': $('#a_name').val(),
            'breed': FRTool.Breed[$('#a_breed').val()],
            'primarygene': FRTool.PrimaryGene[$('#a_Primary_gene').val()],
            'secondarygene': FRTool.SecondaryGene[$('#a_Secondary_gene').val()],
            'tertiarygene': FRTool.TertiaryGene[$('#a_Tertiary_gene').val()],
            'primarycolor': FRTool.Color[$('#a_primary_color').val()],
            'secondarycolor': FRTool.Color[$('#a_secondary_color').val()],
            'tertiarycolor': FRTool.Color[$('#a_tertiary_color').val()],
            'imgflip' : $('#a_flip').is(':checked')
        },
        'dragonName': {
            'enable': true,
            'font': $('#name_font').val(),
            'color': $('#name_Color').val(),
            'shadowcolor': $('#name_shadow_Color').val()
        },
        'geneColor': {
            'left': $('#gene_left_Color').val(),
            'right': $('#gene_right_Color').val(),
            'basic': $('#gene_Color').val()
        },
        'geneFont': $('#gene_font').val(),
        'lineColor': $('#line_Color').val(),
        'background': $('#background').val()
    }
    drawCard('canvas_1', card_data);
});

$("[id$=_color]").change(function() {
    UpdateColorClass($(this));
    Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_Color]").change(function() {
    Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_font]").change(function() {
    Cookies.set($(this).attr('id'), $(this).val());
});

$("#background").change(function() {
    Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_color]").change();

$("[id$=_breed]").change(function() {
  Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_name]").change(function() {
  Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_id]").change(function() {
  Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_flip]").change(function() {
  Cookies.set($(this).attr('id'), $(this).prop('checked'));
});

$("[id$=_gene]").change(function() {
  var this_id = $(this).attr('id').split('_');
  var cookie_value = this_id[0] + "_" + this_id[1];
  Cookies.set(cookie_value, $(this).val());
});

$('[data-toggle="tooltip"]').tooltip();
<commit_msg>Update card.js<commit_after>FRTool.initFR(FRData);
var DEFAULT_FONT = "14pt cursive";
var DEFAULT_BACKGROUND = "transparent";
var DEFAULT_NAME_FONT = "24pt cursive";

function getRandomNumber(range) {
    return range[Math.floor(Math.random() * range.length)];
}

function getImgUrl(dragonID, isLeft) {
    if (dragonID == "") {
        if(isLeft){
            dragonID = getRandomNumber([1, 6, 7, 8, 9, 11]);
        } else {
            dragonID = getRandomNumber([2, 3, 4, 5, 10]);
        }
    }
    var dragonID = parseInt(dragonID);
    var miniDragonId = Math.ceil(dragonID / 100);
    if (dragonID % 100 == 0) {
        miniDragonId += 1;
    }
    return 'http://flightrising.com/rendern/350/' + miniDragonId + '/' + dragonID + '_350.png'
}

function initGeneSelect(id, type) {
  for (var i = 0; i < FRTool.Oddss.length; i++) {
    var genes = FRTool.getGene(FRTool.Oddss[i], type);
    var group = $("<optgroup></optgroup>")
      .attr("data-localize", FRTool.Oddss[i].Name)
      .attr("label", FRTool.Oddss[i].Name);
    for (var j = 0; j < genes.length; j++) {
      group.append($("<option></option>")
        .attr("data-localize", genes[j].Name)
        .attr("value", genes[j].Name)
        .text(genes[j].Name));
    };
    $('#' + id).append(group);
  };
}

function initColorSelect(id) {
  for (var i = 0; i < FRTool.Colors.length; i++) {
    $('#' + id).append(
      $("<option></option>")
      .attr("data-localize", FRTool.Colors[i].Name)
      .attr("class", FRTool.Colors[i].Name)
      .attr("value", FRTool.Colors[i].Name)
      .text(FRTool.Colors[i].Name)
    );
  }
}

function initBreedSelect(id) {
  for (var i = 0; i < FRTool.Oddss.length; i++) {
    var breeds = FRTool.getBreed(FRTool.Oddss[i]);
    var group = $("<optgroup></optgroup>")
    .attr("data-localize", FRTool.Oddss[i].Name)
    .attr("label", FRTool.Oddss[i].Name);
    for (var j = 0; j < breeds.length; j++) {
      group.append($("<option></option>")
        .attr("data-localize", breeds[j].Name)
        .attr("value", breeds[j].Name)
        .text(breeds[j].Name));
    };
    $('#' + id).append(group);
  };
}

function UpdateColorClass(colorSelect) {
    colorSelect.removeClass();
    colorSelect.addClass("form-control");
    colorSelect.addClass(colorSelect.val());
}

function drawName(canvasContext, text, x, y, font, textAlign, color, shadowcolor) {
    canvasContext.font = font || DEFAULT_NAME_FONT;
    canvasContext.textAlign = textAlign
    canvasContext.shadowOffsetX = 2;
    canvasContext.shadowOffsetY = 2;
    canvasContext.shadowBlur = 2;
    canvasContext.shadowColor = shadowcolor;
    canvasContext.fillStyle = color;
    canvasContext.fillText(text, x, y);
}

function drawImage(canvasContext, src, x, y, width, height, flip, callback) {
    if (src) {
        var img = new Image();
        img.src = src;

        img.onload = function() {
            if(flip) {
                img.crossOrigin = "Anonymous";
                canvasContext.scale(-1, 1);
                canvasContext.drawImage(img, -x - width, y, width, height);
                canvasContext.scale(-1, 1);
            } else {
                canvasContext.drawImage(img, x, y, width, height);
            }
            callback();
        }
    }
}

function drawColorRange(canvasContext, range, lineColor, y) {
    var single = 10;
    var width;
    do {
        single -= 1;
        width = range.length * (single + 1);
    } while (width > 200);
    var startX = 320 - width / 2;
    for (var i = 0; i < range.length; i++) {
        canvasContext.lineWidth = "2";
        canvasContext.strokeStyle = lineColor;
        canvasContext.lineCap = "square";
        canvasContext.beginPath();
        canvasContext.rect(startX, y, single, 20);
        canvasContext.stroke();

        canvasContext.fillStyle = range[i].Color;
        canvasContext.fillRect(startX, y, single, 20);
        startX += single + 1;
    }
}

function drawGene(canvasContext, font, gene1, gene2, color, leftcolor, rightcolor, y) {
    var width = 80;
    var imgWidth = 640;
    canvasContext.font = font || DEFAULT_FONT;
        if (gene1 == gene2) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = color;
            canvasContext.fillText(gene1.Name, imgWidth / 2, y);
            canvasContext.fillRect((imgWidth - width)/2, y + 4, width, 3);
        } else {
            var rate = FRTool.getGeneRate(gene1, gene2);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = leftcolor;
            canvasContext.fillText(gene1.Name, imgWidth / 2 - 6, y);
            canvasContext.fillRect(imgWidth / 2 - width - 1, y + 4, width * 2 * rate[0], 3);
            canvasContext.textAlign = "start";
            canvasContext.fillStyle = rightcolor;
            canvasContext.fillText(gene2.Name, imgWidth / 2 + 6, y);
            canvasContext.fillRect(imgWidth / 2 - width + 1 + width * 2 * rate[0], y + 4, width * 2 * rate[1], 3);
        }
}

function drawBreed(canvasContext, font, breed1, breed2, color, leftcolor, rightcolor, y) {
    var width = 80;
    var imgWidth = 640;
    canvasContext.font = font || DEFAULT_FONT;
        if (breed1 == breed2) {
            canvasContext.textAlign = "center";
            canvasContext.fillStyle = color;
            canvasContext.fillText(breed1.Name, imgWidth / 2, y);
            canvasContext.fillRect((imgWidth - width)/2, y + 4, width, 3);
        } else {
            var rate = FRTool.getBreedRate(breed1, breed2);
            canvasContext.textAlign = "end";
            canvasContext.fillStyle = leftcolor;
            canvasContext.fillText(breed1.Name, imgWidth / 2 - 6, y);
            canvasContext.fillRect(imgWidth / 2 - width - 1, y + 4, width * 2 * rate[0], 3);
            canvasContext.textAlign = "start";
            canvasContext.fillStyle = rightcolor;
            canvasContext.fillText(breed2.Name, imgWidth / 2 + 6, y);
            canvasContext.fillRect(imgWidth / 2 - width + 1 + width * 2 * rate[0], y + 4, width * 2 * rate[1], 3);
        }
}

function drawCard(canvasId, cardData) {
    var canvas = document.getElementById(canvasId);
    canvas.setAttribute('width', '640');
    canvas.setAttribute('height', '240');
    var canvasContext = canvas.getContext("2d");
    canvasContext.clearRect(0, 0, 640, 240);

    // background
    canvasContext.fillStyle = cardData.background || DEFAULT_BACKGROUND;
    canvasContext.fillRect(0, 0, 640, 240);

    // breed
    drawBreed(canvasContext, cardData.geneFont,
        cardData.dragon1.breed, cardData.dragon2.breed,
        cardData.geneColor.basic, cardData.geneColor.left, cardData.geneColor.right, 31);

    // primary gene
    drawGene(canvasContext, cardData.geneFont,
        cardData.dragon1.primarygene, cardData.dragon2.primarygene,
        cardData.geneColor.basic, cardData.geneColor.left, cardData.geneColor.right, 66);

    // primary color
    drawColorRange(canvasContext,
        FRTool.getColorRange(cardData.dragon1.primarycolor, cardData.dragon2.primarycolor),
        cardData.lineColor, 80);

    // secondary gene
    drawGene(canvasContext, cardData.geneFont,
        cardData.dragon1.secondarygene, cardData.dragon2.secondarygene,
        cardData.geneColor.basic, cardData.geneColor.left, cardData.geneColor.right, 128);

    // secondary color
    drawColorRange(canvasContext,
        FRTool.getColorRange(cardData.dragon1.secondarycolor, cardData.dragon2.secondarycolor),
        cardData.lineColor, 142);

    // tertiary gene
    drawGene(canvasContext, cardData.geneFont,
        cardData.dragon1.tertiarygene, cardData.dragon2.tertiarygene,
        cardData.geneColor.basic, cardData.geneColor.left, cardData.geneColor.right, 190);

    // tertiary color
    drawColorRange(canvasContext,
        FRTool.getColorRange(cardData.dragon1.tertiarycolor, cardData.dragon2.tertiarycolor),
        cardData.lineColor, 204);

    // image 1
    drawImage(canvasContext, getImgUrl(cardData.dragon1.id, false),
        0, 0, 240, 240, cardData.dragon1.imgflip,
        function(){
            if (cardData.dragonName.enable) {
                drawName(canvasContext,
                    cardData.dragon1.name, 20, 200,
                    cardData.dragonName.font, "start",
                    cardData.dragonName.color, cardData.dragonName.shadowcolor);
            }
        });

    // image 2
    drawImage(canvasContext, getImgUrl(cardData.dragon2.id, true),
        400, 0, 240, 240, cardData.dragon2.imgflip,
        function(){
            if (cardData.dragonName.enable) {
                drawName(canvasContext,
                    cardData.dragon2.name, 620, 200,
                    cardData.dragonName.font, "end",
                    cardData.dragonName.color, cardData.dragonName.shadowcolor);
            }
        });

    return canvas;
}

function setCookie(cookie, label) {
  if(Cookies.get(cookie)){
    $('#' + label).val(Cookies.get(cookie));
  }
}

function setCheckCookie(cookie, label) {
  if(Cookies.get(cookie)){
    $('#' + label).prop("checked", Cookies.get(cookie));
  }
}

initBreedSelect('o_breed');
initBreedSelect('a_breed');

initGeneSelect('o_Primary_gene', 'Primary');
initGeneSelect('a_Primary_gene', 'Primary');
initGeneSelect('o_Secondary_gene', 'Secondary');
initGeneSelect('a_Secondary_gene', 'Secondary');
initGeneSelect('o_Tertiary_gene', 'Tertiary');
initGeneSelect('a_Tertiary_gene', 'Tertiary');

initColorSelect('o_primary_color');
initColorSelect('o_secondary_color');
initColorSelect('o_tertiary_color');
initColorSelect('a_primary_color');
initColorSelect('a_secondary_color');
initColorSelect('a_tertiary_color');

setCookie("o_breed", "o_breed");
setCookie("a_breed", "a_breed");
setCookie("o_name", "o_name");
setCookie("a_name", "a_name");
setCookie("o_id", "o_id");
setCookie("a_id", "a_id");
setCheckCookie("o_flip", "o_flip");
setCheckCookie("a_flip", "a_flip");

for (var i = $("[id$=_gene]").length - 1; i >= 0; i--) {
  var form = $($("[id$=_gene]")[i]);
  setCookie(form.attr('id').substring(0, form.attr('id').length - 5), form.attr('id'));
};

for (var i = $("[id$=_color]").length - 1; i >= 0; i--) {
  var form = $($("[id$=_color]")[i]);
  setCookie(form.attr('id'), form.attr('id'));
};

for (var i = $("[id$=_Color]").length - 1; i >= 0; i--) {
  var form = $($("[id$=_Color]")[i]);
  setCookie(form.attr('id'), form.attr('id'));
};

$("[id=draw]").click(function() {
    var card_data = {
        'dragon1': {
            'id': $('#o_id').val(),
            'name': $('#o_name').val(),
            'breed': FRTool.Breed[$('#o_breed').val()],
            'primarygene': FRTool.PrimaryGene[$('#o_Primary_gene').val()],
            'secondarygene': FRTool.SecondaryGene[$('#o_Secondary_gene').val()],
            'tertiarygene': FRTool.TertiaryGene[$('#o_Tertiary_gene').val()],
            'primarycolor': FRTool.Color[$('#o_primary_color').val()],
            'secondarycolor': FRTool.Color[$('#o_secondary_color').val()],
            'tertiarycolor': FRTool.Color[$('#o_tertiary_color').val()],
            'imgflip' : $('#o_flip').is(':checked')
        },
        'dragon2': {
            'id': $('#a_id').val(),
            'name': $('#a_name').val(),
            'breed': FRTool.Breed[$('#a_breed').val()],
            'primarygene': FRTool.PrimaryGene[$('#a_Primary_gene').val()],
            'secondarygene': FRTool.SecondaryGene[$('#a_Secondary_gene').val()],
            'tertiarygene': FRTool.TertiaryGene[$('#a_Tertiary_gene').val()],
            'primarycolor': FRTool.Color[$('#a_primary_color').val()],
            'secondarycolor': FRTool.Color[$('#a_secondary_color').val()],
            'tertiarycolor': FRTool.Color[$('#a_tertiary_color').val()],
            'imgflip' : $('#a_flip').is(':checked')
        },
        'dragonName': {
            'enable': true,
            'font': $('#name_font').val(),
            'color': $('#name_Color').val(),
            'shadowcolor': $('#name_shadow_Color').val()
        },
        'geneColor': {
            'left': $('#gene_left_Color').val(),
            'right': $('#gene_right_Color').val(),
            'basic': $('#gene_Color').val()
        },
        'geneFont': $('#gene_font').val(),
        'lineColor': $('#line_Color').val(),
        'background': $('#background').val()
    }
    drawCard('canvas_1', card_data);
});

$("[id$=_color]").change(function() {
    UpdateColorClass($(this));
    Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_Color]").change(function() {
    Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_font]").change(function() {
    Cookies.set($(this).attr('id'), $(this).val());
});

$("#background").change(function() {
    Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_color]").change();

$("[id$=_breed]").change(function() {
  Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_name]").change(function() {
  Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_id]").change(function() {
  Cookies.set($(this).attr('id'), $(this).val());
});

$("[id$=_flip]").change(function() {
  Cookies.set($(this).attr('id'), $(this).prop('checked'));
});

$("[id$=_gene]").change(function() {
  var this_id = $(this).attr('id').split('_');
  var cookie_value = this_id[0] + "_" + this_id[1];
  Cookies.set(cookie_value, $(this).val());
});

$('[data-toggle="tooltip"]').tooltip();
<|endoftext|>