<commit_before>define('app/views/machine_monitoring',
    [
        'app/views/templated',
        'app/models/graph',
        'app/models/datasource',
        'app/models/stats_request'
    ],
    //
    //  Machine Monitoring View
    //
    //  @returns Class
    //
    function (TemplatedView, Graph, Datasource, StatsRequest) {

        'use strict';

        return App.MachineMonitoringView = TemplatedView.extend({

            //
            //
            //  Properties
            //
            //

            rules: [],
            graphs: [],
            metrics: [],
            machine: null,
            gettingCommand: null,

            //
            //
            //  Computed Properties
            //
            //

            monitoringMessage: function () {

                var finishedAt = this.machine.installationStatus.finished_at;
                var activatedAt = this.machine.installationStatus.activated_at;
                var manual = this.machine.installationStatus.manual;

                // Machine has sent data to the monitoring server
                if (activatedAt)
                    return "Fetching monitoring data";

                // In case of manual installation or
                // when collectd has been installed but data1
                // haven't arrived yet
                if (manual || finishedAt)
                    return "Waiting for monitoring data";

                return "Installing collectd monitoring agent";

            }.property('machine.installationStatus.finished_at',
                'machine.installationStatus.activated_at'),

            //
            //
            //  Initialization
            //
            //

            load: function () {

                Mist.set('ma', this);
                // Add event handlers
                Mist.rulesController.on('onAdd', this, '_ruleAdded');
                Mist.rulesController.on('onDelete', this, '_ruleDeleted');
                Mist.metricsController.on('onMetricAdd', this, '_metricAdded');
                Mist.metricsController.on('onMetricDelte', this, '_metricDeleted');
                Mist.metricsController.on('onMetricDisassociate', this, '_metricDeleted');
                Mist.graphsController.on('onFetchStats', this, '_analyzeStatsResponse');

            }.on('didInsertElement'),

            unload: function () {

                // Remove event handlers
                Mist.rulesController.off('onAdd', this, '_ruleAdded');
                Mist.rulesController.off('onDelete', this, '_ruleDeleted');
                Mist.metricsController.off('onMetricAdd', this, '_metricAdded');
                Mist.metricsController.off('onMetricDelte', this, '_metricDeleted');
                Mist.metricsController.off('onMetricDisassociate', this, '_metricDeleted');
                Mist.graphsController.off('onFetchStats', this, '_analyzeStatsResponse');

                this._clear();
                this._hideGraphs();
            }.on('willDestroyElement'),

            showMonitoring: function () {
                this._clear();
                this._updateRules();
                var that = this;
                this._updateMetrics(function () {
                    that._updateGraphs();
                    that._showGraphs();
                });
            },

            hideMonitoring: function () {
                this._hideGraphs();
                this._clear();
            },

            //
            //
            //  Methods
            //
            //

            addGraphClicked: function () {
                Mist.metricAddController.open(this.machine);
            },

            //
            //
            //  Actions
            //
            //

            actions: {

                enableMonitoringClicked: function () {

                    // Make sure user is logged in
                    if (!Mist.authenticated)
                        Mist.loginController.open();

                    // Make sure user has purchased a plan
                    else if (!Mist.current_plan)
                        this._showMissingPlanMessage();

                    // Make sure machine has a key
                    else if (!this.machine.probed)
                        this._showManualMonitoringCommand();

                    // Confrim to enable monitoring
                    else
                        this._showEnableMonitoringConfirmation();
                },

                disableMonitoringClicked: function () {
                    var machine = this.machine;
                    Mist.dialogController.open({
                        type: DIALOG_TYPES.YES_NO,
                        head: 'Disable monitoring',
                        body: [
                            {
                                paragraph: 'Are you sure you want to disable ' +
                                    'monitoring for this machine?'
                            }
                        ],
                        callback: disableMonitoring
                    });

                    function disableMonitoring (didConfirm) {

                        if (!didConfirm) return;

                        // Removing a bunch of graphs from the user's face
                        // feels clumpsy. So we scroll to top and present a
                        // nice message while disabling monitoring

                        Mist.smoothScroll(0, 50);

                        // Disable monitoring after a while to enalbe
                        // smoothScroll to scroll to top
                        Ember.run.later(function () {
                            Mist.monitoringController
                                .disableMonitoring(machine,
                                    function (success) {
                                        if (success)
                                            Mist.graphsController.close();
                                    }
                                );
                        }, 200);
                    }
                },

                addRuleClicked: function() {
                    Mist.rulesController.newRule(this.machine);
                },

                //
                //  Proxy actions for graph list bar
                //

                addGraphClicked: function () {
                    this.addGraphClicked();
                },

                graphButtonClicked: function (graph) {
                    graph.view.set('isHidden', false);

                    // Update cookie
                    var entry = Mist.cookiesController.getSingleMachineGraphEntry(
                        this.machine, graph).hidden = false;
                    Mist.cookiesController.save();

                    // Manipulate DOM

                    moveGraphToEnd(graph.id);
                    Ember.run.later(function () {
                        moveGraphButtonToEnd(graph.id);
                    }, 400);
                },

                //
                //  Proxy actions for graph list item
                //

                collapseClicked: function (graph) {
                    graph.view.set('isHidden', true);

                    // Update cookie
                    // shift indexes and set this collapsed graph to be
                    // the last one
                    var graphs = Mist.cookiesController.getSingleMachineEntry(
                        this.machine).graphs;
                    var lastIndex = this.metrics.length - 1;
                    var e;
                    forIn(graphs, function (entry) {
                        if (entry.index == graph.index)
                            e = entry;
                        else if (entry.index > graph.index)
                            entry.index -= 1;
                    });
                    e.index = lastIndex;
                    e.hidden = true;
                    graph.set('index', lastIndex);
                    Mist.cookiesController.save();

                    // Manipulate DOM
                    moveGraphButtonToEnd(graph.id);
                    Ember.run.later(function () {
                        moveGraphToEnd(graph.id);
                    }, 400);
                },

                removeClicked: function (graph) {

                    var machine = this.machine;
                    var message = 'Are you sure you want to remove "' +
                        graph.datasources[0].metric.name + '"';
                    var metric = graph.datasources[0].metric;

                    if (metric.isPlugin)
                        message += ' and disable it from server ' + machine.name;
                    message += ' ?';

                    function removeGraph (success) {
                        if (success)
                            Mist.metricsController.disassociateMetric(
                                metric,
                                machine,
                                function (success) {
                                    if (success)
                                        Mist.graphsController.content.removeObject(graph);
                                }
                            );
                        else
                            graph.set('pendingRemoval', false);
                    }

                    Mist.dialogController.open({
                        type: DIALOG_TYPES.YES_NO,
                        head: 'Remove graph',
                        body: [
                            {
                                paragraph: message
                            }
                        ],
                        callback: function (didConfirm) {
                            if (didConfirm) {
                                graph.set('pendingRemoval', true);
                                if (metric.isPlugin)
                                    Mist.metricsController.disableMetric(
                                        metric, machine, removeGraph);
                                else
                                    removeGraph(true);
                            }
                        }
                    })
                }
            },

            //
            //
            //  Pseudo-Private Methods
            //
            //

            _clear: function () {
                this.setProperties({
                    rules: new Array(),
                    graphs: new Array(),
                    metrics: new Array(),
                });
            },

            _showMissingPlanMessage: function () {
                Mist.dialogController.open({
                    type: DIALOG_TYPES.OK,
                    head: 'No plan',
                    body: [
                        {
                            paragraph: 'In order to use our monitoring' +
                                ' service you have to purchase a plan'
                        },
                        {
                            paragraph: 'You can do that in the Account' +
                                ' page, which can be accessed from the' +
                                ' menu button on the top right corner, or' +
                                ' you can the link bellow:'
                        },
                        {
                            link: 'Account page',
                            href: 'https://mist.io/account'
                        }
                    ]
                });
            },

            _showManualMonitoringCommand: function () {

                var that = this;
                this.set('gettingCommand', true);
                Mist.monitoringController.getMonitoringCommand(
                    this.machine, function (success, data) {
                        if (success) {
                            if (that.machine.get('isWindows'))
                                showCommand({
                                    body: [
                                        {
                                            paragraph: 'Run this command on your server\'s power shell' +
                                                ' to install the monitoring agent:'
                                        },
                                        {
                                            command: data.windows_command
                                        }
                                    ]
                                });
                            else if (that.machine.get('isCoreos'))
                                showCommand({
                                    body: [
                                        {
                                            paragraph: 'Run this command on your server\'s terminal' +
                                                ' to install the monitoring agent:'
                                        },
                                        {
                                            command: data.coreos_command
                                        }
                                    ]
                                });
                            else
                                showCommand({
                                    body: [
                                        {
                                            paragraph: 'Automatic installation of the monitoring agent' +
                                                ' requires an SSH key'
                                        },
                                        {
                                            paragraph: 'Run this command on your server\'s terminal' +
                                                ' to install the monitoring agent:'
                                        },
                                        {
                                            command: data.unix_command
                                        }
                                    ]
                                });
                        }
                        that.set('gettingCommand', false)
                });

                function showCommand (args) {
                    Mist.dialogController.open({
                        type: DIALOG_TYPES.OK_CANCEL,
                        head: 'Enable monitoring',
                        body: args.body,
                        callback: function (didConfirm) {
                            if (!didConfirm) return;
                            Mist.monitoringController.enableMonitoring(
                                that.machine, null, true);
                        }
                    });
                }
            },

            _showEnableMonitoringConfirmation: function () {
                var machine = this.machine;
                Mist.dialogController.open({
                    type: DIALOG_TYPES.YES_NO,
                    head: 'Enable monitoring',
                    body: [
                        {
                            paragraph: 'Are you sure you want to enable' +
                                ' monitoring for this machine?'
                        }
                    ],
                    callback: function (didConfirm) {
                        if (didConfirm)
                            Mist.monitoringController.enableMonitoring(machine);
                    }
                });
            },

            _showGraphs: function () {

                if (!this.$())
                    return;

                var cookie = Mist.cookiesController
                    .getSingleMachineEntry(this.machine);

                if (Mist.graphsController.isOpen)
                    return;
                this.set('graphs', this.graphs.sortBy('index'));

                Mist.graphsController.open({
                    graphs: this.graphs,
                    config: {
                        canModify: true,
                        canControl: true,
                        canMinimize: true,
                    }
                });

                Ember.run.next(function () {
                    return;
                    $('#time-window-control select')
                        .val(cookie.timeWindow)
                        .trigger('change');
                });
            },

            _hideGraphs: function () {
                if (!Mist.graphsController.isOpen)
                    return;
                Mist.graphsController.close();
            },

            _updateRules: function () {
                Mist.rulesController.forEach(function (rule) {
                    if (this.machine.equals(rule.machine))
                        if (!this.rules.findBy('id', rule.id))
                            this.rules.pushObject(rule);
                }, this);
            },

            _updateMetrics: function (callback) {
                this.set('pendingFirstStats', true);
                var that = this;
                var request = StatsRequest.create({
                    from: Date.now(),
                    until: Date.now(),
                    datasources: [{machine: this.machine}]
                });
                function unhandleResponse () {
                    Mist.graphsController.off(
                        'onFetchStatsFromSocket',handleResponse);
                }
                function handleResponse (data) {
                    if (data.request_id == request.id) {
                        unhandleResponse();
                        if (Object.keys(data.metrics).length > 1) {
                            forIn(that, data.metrics, function (metric, target) {
                                var metric = Mist.metricsController.getMetric(target);
                                if (metric && !that.metrics.findBy('id', metric.id))
                                    that.metrics.pushObject(metric);
                            });
                            that.set('pendingFirstStats', false);
                            callback();
                        } else {
                            Ember.run.later(getStats, TIME_MAP.SECOND * 10);
                        }
                    }
                }
                function getStats () {
                    if (that.$()) {
                        Mist.graphsController.on(
                            'onFetchStatsFromSocket',handleResponse);
                        Mist.graphsController._fetchStatsFromSocket(request);
                    } else {
                        unhandleResponse();
                    }

                }
                getStats();
            },

            _updateGraphs: function () {
                var that = this;
                var ctlWasStreaming = Mist.graphsController.stream.isStreaming;
                var graphWasAdded = false;
                this.metrics.forEach(function (metric, index) {
                    var datasource = Datasource.create({
                        metric: metric,
                        machine: this.machine
                    });
                    var graphExists = false;
                    this.graphs.some(function (graph) {
                        if (graph.datasources.findBy('id', datasource.id))
                            return graphExists = true;
                    }, this);
                    if (!graphExists) {
                        graphWasAdded = true;
                        Mist.graphsController.stream.stop();
                        var newGraph = Graph.create({
                            title: metric.name,
                            index: index,
                            datasources: [datasource],
                        });
                        newGraph.set('isHidden', getGraphCookie(newGraph).hidden);
                        newGraph.set('index', getGraphCookie(newGraph).index);
                        this.graphs.pushObject(newGraph);
                    }
                }, this);
                if (ctlWasStreaming && graphWasAdded)
                    Mist.graphsController.stream.start();
                function getGraphCookie (graph) {
                    return Mist.cookiesController
                        .getSingleMachineGraphEntry(that.machine, graph);
                }
            },

            _analyzeStatsResponse: function (response) {
                Ember.run.later(this, function () {
                    forIn(this, response, function (metric, metricId) {
                        var metric = Mist.metricsController.getMetric(metricId);
                        if (metric && !this.metrics.findBy('id', metric.id))
                            this.metrics.pushObject(metric);
                    });
                }, TIME_MAP.SECOND);
            },

            _ruleAdded: function (event) {
                if (this.machine.equals)
                    if (this.machine.equals(event.object.machine))
                        this.rules.pushObject(event.object);
            },

            _ruleDeleted: function (event) {
                if (this.machine.equals)
                    if (this.machine.equals(event.object.machine))
                        this.rules.removeObject(event.object);
            },

            _metricAdded: function (event) {
                if (this.machine.equals)
                    if (this.machine.equals(event.machine))
                        this.metrics.pushObject(event.metric);
            },

            _metricDeleted: function (event) {
                if (this.metrics.findBy('id', event.metric.id))
                    this.metrics.removeObject(event.metric);
            },

            //
            //
            //  Observers
            //
            //

            hasMonitoringObserver: function () {
                if (this.machine.hasMonitoring)
                    this.showMonitoring();
                else
                    this.hideMonitoring();
            }.observes('machine.hasMonitoring').on('didInsertElement'),

            metricsObsever: function () {
                Ember.run.once(this, '_updateGraphs');
            }.observes('metrics.@each'),
        });

        function moveGraphToEnd(graphId) {

            var parent = $("#" + graphId).parent();
            var prev = parent.prev();
            var next = parent.next();

            // Move to end
            parent.detach().appendTo('#graphs');
            prev.detach().appendTo('#graphs');
            next.detach().appendTo('#graphs');
        };

        function moveGraphButtonToEnd(graphId) {

            var parent = $("#" + graphId + '-btn').parent();
            var prev = parent.prev();
            var next = parent.next();

            // Move to end
            parent.detach().insertBefore($('#add-metric-btn'));
            prev.detach().insertBefore($('#add-metric-btn'));
            next.detach().insertBefore($('#add-metric-btn'));
        };
    }
);
<commit_msg>If machine is coreos show only manual monitoring installation<commit_after>define('app/views/machine_monitoring',
    [
        'app/views/templated',
        'app/models/graph',
        'app/models/datasource',
        'app/models/stats_request'
    ],
    //
    //  Machine Monitoring View
    //
    //  @returns Class
    //
    function (TemplatedView, Graph, Datasource, StatsRequest) {

        'use strict';

        return App.MachineMonitoringView = TemplatedView.extend({

            //
            //
            //  Properties
            //
            //

            rules: [],
            graphs: [],
            metrics: [],
            machine: null,
            gettingCommand: null,

            //
            //
            //  Computed Properties
            //
            //

            monitoringMessage: function () {

                var finishedAt = this.machine.installationStatus.finished_at;
                var activatedAt = this.machine.installationStatus.activated_at;
                var manual = this.machine.installationStatus.manual;

                // Machine has sent data to the monitoring server
                if (activatedAt)
                    return "Fetching monitoring data";

                // In case of manual installation or
                // when collectd has been installed but data1
                // haven't arrived yet
                if (manual || finishedAt)
                    return "Waiting for monitoring data";

                return "Installing collectd monitoring agent";

            }.property('machine.installationStatus.finished_at',
                'machine.installationStatus.activated_at'),

            //
            //
            //  Initialization
            //
            //

            load: function () {

                Mist.set('ma', this);
                // Add event handlers
                Mist.rulesController.on('onAdd', this, '_ruleAdded');
                Mist.rulesController.on('onDelete', this, '_ruleDeleted');
                Mist.metricsController.on('onMetricAdd', this, '_metricAdded');
                Mist.metricsController.on('onMetricDelte', this, '_metricDeleted');
                Mist.metricsController.on('onMetricDisassociate', this, '_metricDeleted');
                Mist.graphsController.on('onFetchStats', this, '_analyzeStatsResponse');

            }.on('didInsertElement'),

            unload: function () {

                // Remove event handlers
                Mist.rulesController.off('onAdd', this, '_ruleAdded');
                Mist.rulesController.off('onDelete', this, '_ruleDeleted');
                Mist.metricsController.off('onMetricAdd', this, '_metricAdded');
                Mist.metricsController.off('onMetricDelte', this, '_metricDeleted');
                Mist.metricsController.off('onMetricDisassociate', this, '_metricDeleted');
                Mist.graphsController.off('onFetchStats', this, '_analyzeStatsResponse');

                this._clear();
                this._hideGraphs();
            }.on('willDestroyElement'),

            showMonitoring: function () {
                this._clear();
                this._updateRules();
                var that = this;
                this._updateMetrics(function () {
                    that._updateGraphs();
                    that._showGraphs();
                });
            },

            hideMonitoring: function () {
                this._hideGraphs();
                this._clear();
            },

            //
            //
            //  Methods
            //
            //

            addGraphClicked: function () {
                Mist.metricAddController.open(this.machine);
            },

            //
            //
            //  Actions
            //
            //

            actions: {

                enableMonitoringClicked: function () {

                    // Make sure user is logged in
                    if (!Mist.authenticated)
                        Mist.loginController.open();

                    // Make sure user has purchased a plan
                    else if (!Mist.current_plan)
                        this._showMissingPlanMessage();

                    else if (!this.machine.probed || this.machine.get('isCoreos'))
                        this._showManualMonitoringCommand();

                    // Confrim to enable monitoring
                    else
                        this._showEnableMonitoringConfirmation();
                },

                disableMonitoringClicked: function () {
                    var machine = this.machine;
                    Mist.dialogController.open({
                        type: DIALOG_TYPES.YES_NO,
                        head: 'Disable monitoring',
                        body: [
                            {
                                paragraph: 'Are you sure you want to disable ' +
                                    'monitoring for this machine?'
                            }
                        ],
                        callback: disableMonitoring
                    });

                    function disableMonitoring (didConfirm) {

                        if (!didConfirm) return;

                        // Removing a bunch of graphs from the user's face
                        // feels clumpsy. So we scroll to top and present a
                        // nice message while disabling monitoring

                        Mist.smoothScroll(0, 50);

                        // Disable monitoring after a while to enalbe
                        // smoothScroll to scroll to top
                        Ember.run.later(function () {
                            Mist.monitoringController
                                .disableMonitoring(machine,
                                    function (success) {
                                        if (success)
                                            Mist.graphsController.close();
                                    }
                                );
                        }, 200);
                    }
                },

                addRuleClicked: function() {
                    Mist.rulesController.newRule(this.machine);
                },

                //
                //  Proxy actions for graph list bar
                //

                addGraphClicked: function () {
                    this.addGraphClicked();
                },

                graphButtonClicked: function (graph) {
                    graph.view.set('isHidden', false);

                    // Update cookie
                    var entry = Mist.cookiesController.getSingleMachineGraphEntry(
                        this.machine, graph).hidden = false;
                    Mist.cookiesController.save();

                    // Manipulate DOM

                    moveGraphToEnd(graph.id);
                    Ember.run.later(function () {
                        moveGraphButtonToEnd(graph.id);
                    }, 400);
                },

                //
                //  Proxy actions for graph list item
                //

                collapseClicked: function (graph) {
                    graph.view.set('isHidden', true);

                    // Update cookie
                    // shift indexes and set this collapsed graph to be
                    // the last one
                    var graphs = Mist.cookiesController.getSingleMachineEntry(
                        this.machine).graphs;
                    var lastIndex = this.metrics.length - 1;
                    var e;
                    forIn(graphs, function (entry) {
                        if (entry.index == graph.index)
                            e = entry;
                        else if (entry.index > graph.index)
                            entry.index -= 1;
                    });
                    e.index = lastIndex;
                    e.hidden = true;
                    graph.set('index', lastIndex);
                    Mist.cookiesController.save();

                    // Manipulate DOM
                    moveGraphButtonToEnd(graph.id);
                    Ember.run.later(function () {
                        moveGraphToEnd(graph.id);
                    }, 400);
                },

                removeClicked: function (graph) {

                    var machine = this.machine;
                    var message = 'Are you sure you want to remove "' +
                        graph.datasources[0].metric.name + '"';
                    var metric = graph.datasources[0].metric;

                    if (metric.isPlugin)
                        message += ' and disable it from server ' + machine.name;
                    message += ' ?';

                    function removeGraph (success) {
                        if (success)
                            Mist.metricsController.disassociateMetric(
                                metric,
                                machine,
                                function (success) {
                                    if (success)
                                        Mist.graphsController.content.removeObject(graph);
                                }
                            );
                        else
                            graph.set('pendingRemoval', false);
                    }

                    Mist.dialogController.open({
                        type: DIALOG_TYPES.YES_NO,
                        head: 'Remove graph',
                        body: [
                            {
                                paragraph: message
                            }
                        ],
                        callback: function (didConfirm) {
                            if (didConfirm) {
                                graph.set('pendingRemoval', true);
                                if (metric.isPlugin)
                                    Mist.metricsController.disableMetric(
                                        metric, machine, removeGraph);
                                else
                                    removeGraph(true);
                            }
                        }
                    })
                }
            },

            //
            //
            //  Pseudo-Private Methods
            //
            //

            _clear: function () {
                this.setProperties({
                    rules: new Array(),
                    graphs: new Array(),
                    metrics: new Array(),
                });
            },

            _showMissingPlanMessage: function () {
                Mist.dialogController.open({
                    type: DIALOG_TYPES.OK,
                    head: 'No plan',
                    body: [
                        {
                            paragraph: 'In order to use our monitoring' +
                                ' service you have to purchase a plan'
                        },
                        {
                            paragraph: 'You can do that in the Account' +
                                ' page, which can be accessed from the' +
                                ' menu button on the top right corner, or' +
                                ' you can the link bellow:'
                        },
                        {
                            link: 'Account page',
                            href: 'https://mist.io/account'
                        }
                    ]
                });
            },

            _showManualMonitoringCommand: function () {

                var that = this;
                this.set('gettingCommand', true);
                Mist.monitoringController.getMonitoringCommand(
                    this.machine, function (success, data) {
                        if (success) {
                            if (that.machine.get('isWindows'))
                                showCommand({
                                    body: [
                                        {
                                            paragraph: 'Run this command on your server\'s power shell' +
                                                ' to install the monitoring agent:'
                                        },
                                        {
                                            command: data.windows_command
                                        }
                                    ]
                                });
                            else if (that.machine.get('isCoreos'))
                                showCommand({
                                    body: [
                                        {
                                            paragraph: 'Run this command on your server\'s terminal' +
                                                ' to install the monitoring agent:'
                                        },
                                        {
                                            command: data.coreos_command
                                        }
                                    ]
                                });
                            else
                                showCommand({
                                    body: [
                                        {
                                            paragraph: 'Automatic installation of the monitoring agent' +
                                                ' requires an SSH key'
                                        },
                                        {
                                            paragraph: 'Run this command on your server\'s terminal' +
                                                ' to install the monitoring agent:'
                                        },
                                        {
                                            command: data.unix_command
                                        }
                                    ]
                                });
                        }
                        that.set('gettingCommand', false)
                });

                function showCommand (args) {
                    Mist.dialogController.open({
                        type: DIALOG_TYPES.OK_CANCEL,
                        head: 'Enable monitoring',
                        body: args.body,
                        callback: function (didConfirm) {
                            if (!didConfirm) return;
                            Mist.monitoringController.enableMonitoring(
                                that.machine, null, true);
                        }
                    });
                }
            },

            _showEnableMonitoringConfirmation: function () {
                var machine = this.machine;
                Mist.dialogController.open({
                    type: DIALOG_TYPES.YES_NO,
                    head: 'Enable monitoring',
                    body: [
                        {
                            paragraph: 'Are you sure you want to enable' +
                                ' monitoring for this machine?'
                        }
                    ],
                    callback: function (didConfirm) {
                        if (didConfirm)
                            Mist.monitoringController.enableMonitoring(machine);
                    }
                });
            },

            _showGraphs: function () {

                if (!this.$())
                    return;

                var cookie = Mist.cookiesController
                    .getSingleMachineEntry(this.machine);

                if (Mist.graphsController.isOpen)
                    return;
                this.set('graphs', this.graphs.sortBy('index'));

                Mist.graphsController.open({
                    graphs: this.graphs,
                    config: {
                        canModify: true,
                        canControl: true,
                        canMinimize: true,
                    }
                });

                Ember.run.next(function () {
                    return;
                    $('#time-window-control select')
                        .val(cookie.timeWindow)
                        .trigger('change');
                });
            },

            _hideGraphs: function () {
                if (!Mist.graphsController.isOpen)
                    return;
                Mist.graphsController.close();
            },

            _updateRules: function () {
                Mist.rulesController.forEach(function (rule) {
                    if (this.machine.equals(rule.machine))
                        if (!this.rules.findBy('id', rule.id))
                            this.rules.pushObject(rule);
                }, this);
            },

            _updateMetrics: function (callback) {
                this.set('pendingFirstStats', true);
                var that = this;
                var request = StatsRequest.create({
                    from: Date.now(),
                    until: Date.now(),
                    datasources: [{machine: this.machine}]
                });
                function unhandleResponse () {
                    Mist.graphsController.off(
                        'onFetchStatsFromSocket',handleResponse);
                }
                function handleResponse (data) {
                    if (data.request_id == request.id) {
                        unhandleResponse();
                        if (Object.keys(data.metrics).length > 1) {
                            forIn(that, data.metrics, function (metric, target) {
                                var metric = Mist.metricsController.getMetric(target);
                                if (metric && !that.metrics.findBy('id', metric.id))
                                    that.metrics.pushObject(metric);
                            });
                            that.set('pendingFirstStats', false);
                            callback();
                        } else {
                            Ember.run.later(getStats, TIME_MAP.SECOND * 10);
                        }
                    }
                }
                function getStats () {
                    if (that.$()) {
                        Mist.graphsController.on(
                            'onFetchStatsFromSocket',handleResponse);
                        Mist.graphsController._fetchStatsFromSocket(request);
                    } else {
                        unhandleResponse();
                    }

                }
                getStats();
            },

            _updateGraphs: function () {
                var that = this;
                var ctlWasStreaming = Mist.graphsController.stream.isStreaming;
                var graphWasAdded = false;
                this.metrics.forEach(function (metric, index) {
                    var datasource = Datasource.create({
                        metric: metric,
                        machine: this.machine
                    });
                    var graphExists = false;
                    this.graphs.some(function (graph) {
                        if (graph.datasources.findBy('id', datasource.id))
                            return graphExists = true;
                    }, this);
                    if (!graphExists) {
                        graphWasAdded = true;
                        Mist.graphsController.stream.stop();
                        var newGraph = Graph.create({
                            title: metric.name,
                            index: index,
                            datasources: [datasource],
                        });
                        newGraph.set('isHidden', getGraphCookie(newGraph).hidden);
                        newGraph.set('index', getGraphCookie(newGraph).index);
                        this.graphs.pushObject(newGraph);
                    }
                }, this);
                if (ctlWasStreaming && graphWasAdded)
                    Mist.graphsController.stream.start();
                function getGraphCookie (graph) {
                    return Mist.cookiesController
                        .getSingleMachineGraphEntry(that.machine, graph);
                }
            },

            _analyzeStatsResponse: function (response) {
                Ember.run.later(this, function () {
                    forIn(this, response, function (metric, metricId) {
                        var metric = Mist.metricsController.getMetric(metricId);
                        if (metric && !this.metrics.findBy('id', metric.id))
                            this.metrics.pushObject(metric);
                    });
                }, TIME_MAP.SECOND);
            },

            _ruleAdded: function (event) {
                if (this.machine.equals)
                    if (this.machine.equals(event.object.machine))
                        this.rules.pushObject(event.object);
            },

            _ruleDeleted: function (event) {
                if (this.machine.equals)
                    if (this.machine.equals(event.object.machine))
                        this.rules.removeObject(event.object);
            },

            _metricAdded: function (event) {
                if (this.machine.equals)
                    if (this.machine.equals(event.machine))
                        this.metrics.pushObject(event.metric);
            },

            _metricDeleted: function (event) {
                if (this.metrics.findBy('id', event.metric.id))
                    this.metrics.removeObject(event.metric);
            },

            //
            //
            //  Observers
            //
            //

            hasMonitoringObserver: function () {
                if (this.machine.hasMonitoring)
                    this.showMonitoring();
                else
                    this.hideMonitoring();
            }.observes('machine.hasMonitoring').on('didInsertElement'),

            metricsObsever: function () {
                Ember.run.once(this, '_updateGraphs');
            }.observes('metrics.@each'),
        });

        function moveGraphToEnd(graphId) {

            var parent = $("#" + graphId).parent();
            var prev = parent.prev();
            var next = parent.next();

            // Move to end
            parent.detach().appendTo('#graphs');
            prev.detach().appendTo('#graphs');
            next.detach().appendTo('#graphs');
        };

        function moveGraphButtonToEnd(graphId) {

            var parent = $("#" + graphId + '-btn').parent();
            var prev = parent.prev();
            var next = parent.next();

            // Move to end
            parent.detach().insertBefore($('#add-metric-btn'));
            prev.detach().insertBefore($('#add-metric-btn'));
            next.detach().insertBefore($('#add-metric-btn'));
        };
    }
);
<|endoftext|>


<commit_before>$.fn.showChartDataEntryTanggal = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,form){
        var x = [];
        var y = [];
        $.each(form,function(index,value){
            x.push(index);
            y.push(value);
        });
        user = user.replace(" ","_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Jumlah Entry',
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryMinggu = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,weeks){
        var x = ['Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
        var y_now = [];
        var y_last = [];
        $.each(weeks,function(week,form){
            if(week=='thisweek'){
                $.each(form,function(index,value){
                    y_now.push(value);
                });
            }else{
                $.each(form,function(index,value){
                    y_last.push(value);
                });
            }

        });
        user = user.replace(" ","_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Minggu Ini',
                    type: 'column',
                    data: y_now,
                    color: '#0000ff',
                    tooltip: {
                        valueSuffix: ''
                    }
                },{
                    name: 'Minggu Lalu',
                    type: 'column',
                    data: y_last,
                    color: '#ff0000',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryBulan = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,months){
        var x = ['Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
        var y_now = [];
        var y_last = [];
        var thisyear = 0;
        var lastyear = 0;
        $.each(months,function(month,form){
            if(month=='thisyear'){
                $.each(form,function(index,value){
                    thisyear = index.split("-");
                    y_now.push(value);
                });
            }else{
                $.each(form,function(index,value){
                    lastyear = index.split("-");
                    y_last.push(value);
                });
            }

        });
        user = user.replace(" ","_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Tahun '+thisyear[0],
                    type: 'column',
                    data: y_now,
                    color: '#0000ff',
                    tooltip: {
                        valueSuffix: ''
                    }
                },{
                    name: 'Tahun '+lastyear[0],
                    type: 'column',
                    data: y_last,
                    color: '#ff0000',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryForm = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,form){
        var x = [];
        var y = [];
        $.each(form,function(index,value){
            x.push(index);
            y.push(value);
        });
        user = user.replace(" ","_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Jumlah Entry',
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChart = function(data){
    $.each(data,function(index1,data1){
        var id = data1['page'];
        var x = [];
        var y = [];
        $.each(data1['form'],function(index2,data2){
            x.push(index2);
            y.push(data2);
        });
        Highcharts.setOptions({
            lang: {
                decimalPoint: ',',
                thousandsSep: '.'
            }
        });

        $('#'+id).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: data1['y_label'],
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true,
                pointFormat: data1['y_label']+": {point.y:.2f} %"
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y:.2f}'
                    }
                }
            },
            series: [{
                    name: data1['series_name'],
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });
};<commit_msg>AH | update chart function<commit_after>$.fn.showChartDataEntryTanggal = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,form){
        var x = [];
        var y = [];
        $.each(form,function(index,value){
            x.push(index);
            y.push(value);
        });
        user = user.replace(" ","_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Jumlah Entry',
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryMinggu = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,weeks){
        var x = ['Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
        var y_now = [];
        var y_last = [];
        $.each(weeks,function(week,form){
            if(week=='thisweek'){
                $.each(form,function(index,value){
                    y_now.push(value);
                });
            }else{
                $.each(form,function(index,value){
                    y_last.push(value);
                });
            }

        });
        user = user.replace(" ","_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Minggu Ini',
                    type: 'column',
                    data: y_now,
                    color: '#0000ff',
                    tooltip: {
                        valueSuffix: ''
                    }
                },{
                    name: 'Minggu Lalu',
                    type: 'column',
                    data: y_last,
                    color: '#ff0000',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryBulan = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,months){
        var x = ['Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
        var y_now = [];
        var y_last = [];
        var thisyear = 0;
        var lastyear = 0;
        $.each(months,function(month,form){
            if(month=='thisyear'){
                $.each(form,function(index,value){
                    thisyear = index.split("-");
                    y_now.push(value);
                });
            }else{
                $.each(form,function(index,value){
                    lastyear = index.split("-");
                    y_last.push(value);
                });
            }

        });
        user = user.replace(" ","_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Tahun '+thisyear[0],
                    type: 'column',
                    data: y_now,
                    color: '#0000ff',
                    tooltip: {
                        valueSuffix: ''
                    }
                },{
                    name: 'Tahun '+lastyear[0],
                    type: 'column',
                    data: y_last,
                    color: '#ff0000',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryForm = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,form){
        var x = [];
        var y = [];
        $.each(form,function(index,value){
            x.push(index);
            y.push(value);
        });
        user = user.replace(" ","_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Jumlah Entry',
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChart = function(data){
    $.each(data,function(index1,data1){
        var id = data1['page'];
        var x = [];
        var y = [];
        $.each(data1['form'],function(index2,data2){
            x.push(index2);
            y.push(data2);
        });
        Highcharts.setOptions({
            lang: {
                decimalPoint: ',',
                thousandsSep: '.'
            }
        });

        $('#'+id).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,minrange:100},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: data1['y_label'],
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true,
                pointFormat: data1['y_label']+": {point.y:.2f} %"
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y:.2f}'
                    }
                }
            },
            series: [{
                    name: data1['series_name'],
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });
};<|endoftext|>


<commit_before>// HELPERS
// TODO: move this as an external library
jQuery.fn.extend({
	scrollBottom: function () {
		return jQuery(this).scrollTop() + jQuery(this).height();
	},
	top: function () {
		return jQuery(this).position().top;
	},
	left: function () {
		return jQuery(this).position().left;
	},
	bottom: function () {
		return jQuery(this).position().top+jQuery(this).outerHeight();
	},
	right: function () {
		return jQuery(this).position().left+jQuery(this).outerWidth();
	}
});

jQuery.fn.cssNum = function(){
	return parseFloat(jQuery.fn.css.apply(this,arguments));
};

jQuery(function () { jQuery("[data-toggle='tooltip']").tooltip(); });

/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
* ======================================================================== */

(function($) {

	// Use this variable to set up the common and page specific functions. If you
	// rename this variable, you will also need to rename the namespace below.
	var Sage = {
		// All pages
		'common': {
			init: function() {
				// JavaScript to be fired on all pages
				//hamburger
				$('.hamburger').click(function(){
					if($(this).hasClass('is-active')){
						$(this).removeClass('is-active');
					} else {
						$(this).addClass('is-active');
					}
				});
			},
			finalize: function() {

				// scroll and URL
				var currentSection = "";
				$(".pt-page-main").bind('scroll', function() {

					var getScrollSection = function(top){
						var toReturn = null;
						$('.front-page-section').each(function(){
							var sTop, sBottom;
							var $section = $(this);
							if($section.length){
								sTop = $section.top();
								sBottom = $section.bottom();
								if((top >= sTop) && (top < sBottom)){
									toReturn = $section.prop('id');
									return false;
								}
							}
						});
						return toReturn;
					};

					var scrolledSection = getScrollSection($(this).scrollTop());

					if(scrolledSection && currentSection !== scrolledSection){
						currentSection = scrolledSection;
						//trigger enter section
						var url = "/";
						if(currentSection !== "presentacio"){
							url = "/"+currentSection;
						}
						var stateObj = { section: currentSection };
						window.history.pushState(stateObj, currentSection, url);
					}
				});

				//all other
				// JavaScript to be fired on all pages, after page specific JS is fired
				$('.spi-link').click(function(event) {
					if($('body').hasClass('home') || $('body').hasClass('page-template-front-page')){
						event.preventDefault();

						var linkElementScroll = function($anchor){
							var target = $anchor.data().target;

							$('.pt-page-main').animate({
								scrollTop: $(target).top()
							}, 1000);
						};

						var $anchor = $(this);

						if($('.hamburger').hasClass('is-active')){
							$('.hamburger').click();
							setTimeout(function(){
								linkElementScroll($anchor);
							},1000);
						}
						else {
							linkElementScroll($anchor);
						}
					}
				});

				$(window).on("popstate", function(e) {
					var section = e.originalEvent.state.section;
					if($('#'+section).length){
						$('.pt-page-main').animate({
							scrollTop: $('#'+section).top()
						}, 1000);
					}
				});

				// if it's frist load maybe we have something in the url (and not in history) and we need to apply changes
				if(window.location.pathname !== "/"){
					var id = window.location.pathname.substring(1);
					if($('#'+id).length){
						$('.pt-page-main').animate({
							scrollTop: $('#'+id).top()
						}, 1000);
					}
				}
				$(window).resize(function() {
					var size = $('.technology-panel .technology').width();
					$('.technology-panel .technology').height(size);
					$('.technology-panel .text').height($('.technology-panel .technology .icon').height());
					$('.technology-panel .text').width(size);

					if($('.pt-page-holder').height() < $(window).height()){
						$('.pt-page-holder').height($(window).height());
						$('footer').addClass("stick-to-bottom");
					} else {
						$('footer').removeClass("stick-to-bottom");
					}
				});

			}
		},
		// Home page
		'home': {
			init: function() {
				// JavaScript to be fired on the home page
			},
			finalize: function() {

				var $homeNavbar = $('.nav-home-container'),
				$primaryNavbar = $('.nav-primary-container'),
				$scrollElement = $('.pt-page-main'),
				$mainMenu = $('#menu-main-menu'),
				distance = $homeNavbar.position().top,
				fadeTime = 200,
				$window = $(window);

				var mainMenuVisible = false;

				$scrollElement.scroll(function() {
					if ($scrollElement.scrollTop() >= distance ) {
						if(!mainMenuVisible){
							mainMenuVisible = true;
							$homeNavbar.removeClass('visible');
							$primaryNavbar.addClass('visible');
							$mainMenu.addClass('dettached');
						}
					} else {
						if(mainMenuVisible){
							mainMenuVisible = false;
							$primaryNavbar.removeClass('visible');
							$homeNavbar.addClass('visible');
							$mainMenu.removeClass('dettached');
						}
					}
				});

				var scrollRepositionEnabled = false;

				var myScrollMagic = function(){
					// JavaScript to be fired on the home page, after the init JS
					var placeIcons = function(){
						$('.section-icon-holder').each(function(){
							var $icon = $(this).find('.section-icon');
							var marginTop = $( window ).height() / 2 - $icon.height() / 2;
							$(this).css('margin-top',marginTop);
						});
					};

					if(scrollRepositionEnabled){
						$( window ).resize(function() {
							placeIcons();
						});
						placeIcons();

						// SCROLL MAGIC
						var controller = new ScrollMagic.Controller();
						var scenes = [];
						var nElements = $('section').length;
						var lastMillisecondScrolled = 0;

						for (var i = 0; i < nElements; i++){
							var sectionHeight, duration, id, offset, iconHeight;

							sectionHeight = $('section').first().height();
							iconHeight = $('.section-icon').first().height();
							id = i+1;

							if(i === 0){
								offset = 0;
							} else {
								offset = sectionHeight*(i-1)+sectionHeight/2 ;
							}

							if(i === 0){
								duration =	sectionHeight / 2;
							} else if(i === (nElements-1)){
								duration =	sectionHeight / 2;
							} else {
								duration =	sectionHeight;
							}

							scenes[i] = new ScrollMagic.Scene({
								offset: offset, duration: duration
							})
							// .addIndicators({name: "i: "+i+" offset: "+offset+" duration: "+duration})
							.addTo(controller);
						}

						$.each(scenes,function(index,scene){

							scene.on("progress", function (event) {

								// HELPER VARIABLES
								var pixelsFromTop = sectionHeight*scene.progress();
								var pixelsToBottom = sectionHeight - pixelsFromTop;

								// POSITION
								var sceneN = 0;
								$('.section-icon-holder').each(function(){
									var marginTop = 0;

									if(index-1 === sceneN){

										// prev scene
										if(index === 0){
											// there is no prev scene when we are at the first scene
										} else if( index > 0 && index < nElements-1) {
											marginTop = sectionHeight-iconHeight/2+pixelsFromTop;
										} else if (index === nElements-1){
											marginTop = sectionHeight-iconHeight/2+pixelsFromTop/2;
										}

									} else if(index === sceneN){

										// current scene
										if(index === 0){
											marginTop = sectionHeight/2 + pixelsFromTop/2 - iconHeight/2;
										} else if( index > 0 && index < nElements-1) {
											marginTop = pixelsFromTop - iconHeight/2 ;
										} else if (index === nElements-1){
											marginTop = pixelsFromTop/2 - iconHeight/2;
										}

									} else if(index+1 === sceneN){

										// next scene
										if(index === 0){
											marginTop = -pixelsToBottom/2 - iconHeight/2;
										} else if( index > 0 && index < nElements-1) {
											marginTop = -pixelsToBottom -iconHeight/2;
										} else if (index === nElements-1){
											// there is no next scene when we are at the last scene
										}

									}
									sceneN++;
									$(this).css('margin-top',marginTop+'px');
								});

								// CLIPPING
								var clipping = 0;

								$('.section-icon').hide();

								if( (
									index > 0 && pixelsFromTop < iconHeight/2
								) || (
									index+1 === nElements && pixelsFromTop < iconHeight
								) ) {
									//PREV
									if(index+1 === nElements){
										clipping = iconHeight/2 - pixelsFromTop/2;
									} else {
										clipping = iconHeight/2 - pixelsFromTop;
									}
									$('.section-icon').eq(index-1).css({'clip':'rect(auto auto '+iconHeight-clipping+'px auto)'}).show();
									$('.section-icon').eq(index).css({'clip':'rect('+clipping+'px auto auto auto)'}).show();

								} else if(
									(
										index === 0 && pixelsToBottom < iconHeight
									) || (
										index >= 1 && index+1 < nElements && pixelsToBottom < iconHeight/2
									)
								) {
									//NEXT
									if(index === 0){
										clipping = iconHeight - (pixelsFromTop+iconHeight-sectionHeight)/2;
									}
									else {
										clipping = iconHeight/2 + pixelsToBottom;
									}

									$('.section-icon').eq(index).css({'clip':'rect(auto auto '+clipping+'px auto)'}).show();
									$('.section-icon').eq(index+1).css({'clip':'rect('+clipping+'px auto auto auto)'}).show();

								} else {
									// don't clip
									$('.section-icon').eq(index).css({'clip':'rect(auto auto auto auto)'}).show();
								}

							});
						});

						var magnetismEnabled = false; //not working
						//magnetism
						var stopped = true;
						var respositioning = false;
						if(magnetismEnabled){
							var globalScene = new ScrollMagic.Scene({
								offset: 0, duration: $('body').height() - $(window).height()/2
							})
							.addTo(controller);
							globalScene.on("progress", function (event) {
								if(!respositioning){
									var d = new Date();
									lastMillisecondScrolled = d.getTime();
									stopped = false;
								}
							});

							var repositionIfNeeded = function(){
								if(stopped){
									return;
								}
								var d = new Date();
								currentMillisecond = d.getTime();
								var millisecondsWithoutScroll = currentMillisecond - lastMillisecondScrolled;
								if(millisecondsWithoutScroll > 333){
									//a third of a second has passed without scroll
									var found = false;
									$('section').each(function(){
										if(!found){
											var offsetTop = $(window).scrollTop() - $(this).top();
											var offsetMinimum = $('section').first().height() * 0.33;
											//Dettect if we need to reposition because we are at least than 33% of a bonduary

											if(Math.abs(offsetTop) < offsetMinimum){
												found = true;
												if(offsetTop === 0){
													//stopped
													repositioning = false;
													stopped = true;
												}
												else {
													//go to this top
													respositioning = true;
													stopped = true;
													closestSectionId = $(this).index();
												}
											}

											if(respositioning){
												controller.scrollTo(function (newScrollPos) {
													repositioning = true;
													stopped = true;
													$("html, body").animate({scrollTop: newScrollPos},function(){
														stopped = true;
														respositioning = false;
													});
												});
												controller.scrollTo($('section').eq(closestSectionId).top());
											}
										}

									});
								}
							};

							//clock
							var clock = setInterval(function(){
								repositionIfNeeded();
							}, 33);
						}

					}
				};

				(function($, viewport){
					// Executes only in XS breakpoint
					if(viewport.is('xs')) {
						// ...
					}

					// Executes in SM, MD and LG breakpoints
					if(viewport.is('>=sm')) {
						myScrollMagic();
					}

					// Executes in XS and SM breakpoints
					if(viewport.is('<md')) {
						// ...
					}

					// Execute code each time window size changes
					$(window).resize(
						viewport.changed(function() {
							if(viewport.is('xs')) {
								// ...
							}
							// getTextWidth
						})
					);

				})(jQuery, ResponsiveBootstrapToolkit);

			}
		},
		// About us page, note the change from about-us to about_us.
		'contacte': {
			init: function() {
				// JavaScript to be fired on the contacte page

				var $contactContainer = $('.page-template-contacte-page .contact-container');
				var $imageHolder = $('.page-template-contacte-page .image-holder');
				var $image = $('.page-template-contacte-page .image-holder .image');

				$(window).resize(function() {
					if($(window).width() > 767){
						if(!$('.fake-footer').length){
							$('.pt-page-holder').append('

');
						}
						$contactContainer.height($('footer').top() - $('.contact-container').top());

						if($imageHolder.height() < $contactContainer.height()){
							$imageHolder.height($contactContainer.height());
						} else {
						}
					}
					else {
						$('.fake-footer').remove();
						$contactContainer.height('auto');
					}
				});
			}
		}
	};

	// The routing fires all common scripts, followed by the page specific scripts.
	// Add additional events for more control over timing e.g. a finalize event
	var UTIL = {
		fire: function(func, funcname, args) {
			var fire;
			var namespace = Sage;
			funcname = (funcname === undefined) ? 'init' : funcname;
			fire = func !== '';
			fire = fire && namespace[func];
			fire = fire && typeof namespace[func][funcname] === 'function';

			if (fire) {
				namespace[func][funcname](args);
			}
		},
		loadEvents: function() {
			// Fire common init JS
			UTIL.fire('common');

			// Fire page-specific init JS, and then finalize JS
			$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
				UTIL.fire(classnm);
				UTIL.fire(classnm, 'finalize');
			});

			// Fire common finalize JS
			UTIL.fire('common', 'finalize');
		}
	};

	// Load Events
	$(document).ready(UTIL.loadEvents);
	setTimeout(function(){$(window).resize();},0);
	setTimeout(function(){$(window).resize();},100);
	setTimeout(function(){$(window).resize();},250);
	setTimeout(function(){$(window).resize();},500);
	setTimeout(function(){$(window).resize();},1000);
})(jQuery); // Fully reference jQuery after this point.
<commit_msg>remove scrollmagic<commit_after>// HELPERS
// TODO: move this as an external library
jQuery.fn.extend({
	scrollBottom: function () {
		return jQuery(this).scrollTop() + jQuery(this).height();
	},
	top: function () {
		return jQuery(this).position().top;
	},
	left: function () {
		return jQuery(this).position().left;
	},
	bottom: function () {
		return jQuery(this).position().top+jQuery(this).outerHeight();
	},
	right: function () {
		return jQuery(this).position().left+jQuery(this).outerWidth();
	}
});

jQuery.fn.cssNum = function(){
	return parseFloat(jQuery.fn.css.apply(this,arguments));
};

jQuery(function () { jQuery("[data-toggle='tooltip']").tooltip(); });

/* ========================================================================
* DOM-based Routing
* Based on http://goo.gl/EUTi53 by Paul Irish
*
* Only fires on body classes that match. If a body class contains a dash,
* replace the dash with an underscore when adding it to the object below.
*
* .noConflict()
* The routing is enclosed within an anonymous function so that you can
* always reference jQuery with $, even when in .noConflict() mode.
* ======================================================================== */

(function($) {

	// Use this variable to set up the common and page specific functions. If you
	// rename this variable, you will also need to rename the namespace below.
	var Sage = {
		// All pages
		'common': {
			init: function() {
				// JavaScript to be fired on all pages
				//hamburger
				$('.hamburger').click(function(){
					if($(this).hasClass('is-active')){
						$(this).removeClass('is-active');
					} else {
						$(this).addClass('is-active');
					}
				});
			},
			finalize: function() {

				// scroll and URL
				var currentSection = "";
				$(".pt-page-main").bind('scroll', function() {

					var getScrollSection = function(top){
						var toReturn = null;
						$('.front-page-section').each(function(){
							var sTop, sBottom;
							var $section = $(this);
							if($section.length){
								sTop = $section.top();
								sBottom = $section.bottom();
								if((top >= sTop) && (top < sBottom)){
									toReturn = $section.prop('id');
									return false;
								}
							}
						});
						return toReturn;
					};

					var scrolledSection = getScrollSection($(this).scrollTop());

					if(scrolledSection && currentSection !== scrolledSection){
						currentSection = scrolledSection;
						//trigger enter section
						var url = "/";
						if(currentSection !== "presentacio"){
							url = "/"+currentSection;
						}
						var stateObj = { section: currentSection };
						window.history.pushState(stateObj, currentSection, url);
					}
				});

				//all other
				// JavaScript to be fired on all pages, after page specific JS is fired
				$('.spi-link').click(function(event) {
					if($('body').hasClass('home') || $('body').hasClass('page-template-front-page')){
						event.preventDefault();

						var linkElementScroll = function($anchor){
							var target = $anchor.data().target;

							$('.pt-page-main').animate({
								scrollTop: $(target).top()
							}, 1000);
						};

						var $anchor = $(this);

						if($('.hamburger').hasClass('is-active')){
							$('.hamburger').click();
							setTimeout(function(){
								linkElementScroll($anchor);
							},1000);
						}
						else {
							linkElementScroll($anchor);
						}
					}
				});

				$(window).on("popstate", function(e) {
					var section = e.originalEvent.state.section;
					if($('#'+section).length){
						$('.pt-page-main').animate({
							scrollTop: $('#'+section).top()
						}, 1000);
					}
				});

				// if it's frist load maybe we have something in the url (and not in history) and we need to apply changes
				if(window.location.pathname !== "/"){
					var id = window.location.pathname.substring(1);
					if($('#'+id).length){
						$('.pt-page-main').animate({
							scrollTop: $('#'+id).top()
						}, 1000);
					}
				}
				$(window).resize(function() {
					var size = $('.technology-panel .technology').width();
					$('.technology-panel .technology').height(size);
					$('.technology-panel .text').height($('.technology-panel .technology .icon').height());
					$('.technology-panel .text').width(size);

					if($('.pt-page-holder').height() < $(window).height()){
						$('.pt-page-holder').height($(window).height());
						$('footer').addClass("stick-to-bottom");
					} else {
						$('footer').removeClass("stick-to-bottom");
					}
				});

			}
		},
		// Home page
		'home': {
			init: function() {
				// JavaScript to be fired on the home page
			},
			finalize: function() {

				var $homeNavbar = $('.nav-home-container'),
				$primaryNavbar = $('.nav-primary-container'),
				$scrollElement = $('.pt-page-main'),
				$mainMenu = $('#menu-main-menu'),
				distance = $homeNavbar.position().top,
				fadeTime = 200,
				$window = $(window);

				var mainMenuVisible = false;

				$scrollElement.scroll(function() {
					if ($scrollElement.scrollTop() >= distance ) {
						if(!mainMenuVisible){
							mainMenuVisible = true;
							$homeNavbar.removeClass('visible');
							$primaryNavbar.addClass('visible');
							$mainMenu.addClass('dettached');
						}
					} else {
						if(mainMenuVisible){
							mainMenuVisible = false;
							$primaryNavbar.removeClass('visible');
							$homeNavbar.addClass('visible');
							$mainMenu.removeClass('dettached');
						}
					}
				});

				(function($, viewport){
					// Executes only in XS breakpoint
					if(viewport.is('xs')) {
						// ...
					}

					// Executes in SM, MD and LG breakpoints
					if(viewport.is('>=sm')) {
						myScrollMagic();
					}

					// Executes in XS and SM breakpoints
					if(viewport.is('<md')) {
						// ...
					}

					// Execute code each time window size changes
					$(window).resize(
						viewport.changed(function() {
							if(viewport.is('xs')) {
								// ...
							}
							// getTextWidth
						})
					);

				})(jQuery, ResponsiveBootstrapToolkit);

			}
		},
		// About us page, note the change from about-us to about_us.
		'contacte': {
			init: function() {
				// JavaScript to be fired on the contacte page

				var $contactContainer = $('.page-template-contacte-page .contact-container');
				var $imageHolder = $('.page-template-contacte-page .image-holder');
				var $image = $('.page-template-contacte-page .image-holder .image');

				$(window).resize(function() {
					if($(window).width() > 767){
						if(!$('.fake-footer').length){
							$('.pt-page-holder').append('

');
						}
						$contactContainer.height($('footer').top() - $('.contact-container').top());

						if($imageHolder.height() < $contactContainer.height()){
							$imageHolder.height($contactContainer.height());
						} else {
						}
					}
					else {
						$('.fake-footer').remove();
						$contactContainer.height('auto');
					}
				});
			}
		}
	};

	// The routing fires all common scripts, followed by the page specific scripts.
	// Add additional events for more control over timing e.g. a finalize event
	var UTIL = {
		fire: function(func, funcname, args) {
			var fire;
			var namespace = Sage;
			funcname = (funcname === undefined) ? 'init' : funcname;
			fire = func !== '';
			fire = fire && namespace[func];
			fire = fire && typeof namespace[func][funcname] === 'function';

			if (fire) {
				namespace[func][funcname](args);
			}
		},
		loadEvents: function() {
			// Fire common init JS
			UTIL.fire('common');

			// Fire page-specific init JS, and then finalize JS
			$.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
				UTIL.fire(classnm);
				UTIL.fire(classnm, 'finalize');
			});

			// Fire common finalize JS
			UTIL.fire('common', 'finalize');
		}
	};

	// Load Events
	$(document).ready(UTIL.loadEvents);
	setTimeout(function(){$(window).resize();},0);
	setTimeout(function(){$(window).resize();},100);
	setTimeout(function(){$(window).resize();},250);
	setTimeout(function(){$(window).resize();},500);
	setTimeout(function(){$(window).resize();},1000);
})(jQuery); // Fully reference jQuery after this point.
<|endoftext|>


<commit_before>define([], function() {
    'use strict';
    return ['$scope', 'Restangular', 'trackr.services.employee', '$filter', function($scope, Restangular, EmployeeService, $filter) {
        var controller = this;
        $scope.vacationRequest = {};

        controller.emitSavedVacationRequest = function(vacationRequest) {
            vacationRequest.startDate = $filter('date')(new Date(vacationRequest.startDate), 'yyyy-MM-dd');
            vacationRequest.endDate = $filter('date')(new Date(vacationRequest.endDate), 'yyyy-MM-dd');
            $scope.$emit('newVacationRequest', vacationRequest);
        };

        $scope.submitVacationRequest = function(vacationRequest) {
            vacationRequest.employee = EmployeeService.getEmployeeHref();
            Restangular.all('vacationRequests').post(vacationRequest).then(function(response) {
                controller.emitSavedVacationRequest(response);
            });
        };
    }];
});<commit_msg>TRACKR-54 - Request vacation Formatted start and end date before POSTing.<commit_after>define([], function() {
    'use strict';
    return ['$scope', 'Restangular', 'trackr.services.employee', '$filter', function($scope, Restangular, EmployeeService, $filter) {
        var controller = this;
        $scope.vacationRequest = {};

        controller.formatDate = function(date) {
            return $filter('date')(date, 'yyyy-MM-dd');
        };

        controller.emitSavedVacationRequest = function(vacationRequest) {
            vacationRequest.startDate = controller.formatDate(new Date(vacationRequest.startDate));
            vacationRequest.endDate = controller.formatDate(new Date(vacationRequest.endDate));
            $scope.$emit('newVacationRequest', vacationRequest);
        };

        $scope.submitVacationRequest = function(vacationRequest) {
            vacationRequest.employee = EmployeeService.getEmployeeHref();
            vacationRequest.startDate = controller.formatDate(vacationRequest.startDate);
            vacationRequest.endDate = controller.formatDate(vacationRequest.endDate);
            Restangular.all('vacationRequests').post(vacationRequest).then(function(response) {
                controller.emitSavedVacationRequest(response);
            });
        };
    }];
});<|endoftext|>