<commit_before>
Ext.onReady(function() {

    var lightbox = new Vpc.Basic.ImageEnlarge();
    var els = document.getElementsByTagName('a');
    Ext.each(els, function(el) {
        el = Ext.get(el);
        if (el.dom.rel.match(/enlarge_[0-9]+_[0-9]+/)) {
            Ext.EventManager.addListener(el, 'click', function(e) {
                lightbox.show(el, e);
            }, lightbox, { stopEvent: true });
        }
    });
});

Ext.namespace("Vpc.Basic");
Vpc.Basic.ImageEnlarge = function()
{
    this.lightbox = Ext.get(
        Ext.DomHelper.append(Ext.getBody(),
            { tag: 'div', cls: 'lightbox' }
        )
    );
};

Vpc.Basic.ImageEnlarge.prototype =
{

    hide: function(e)
    {
        if (e) e.stopEvent();
        this.lightbox.applyStyles('display: none;');
        this.unmask();
    },

    show: function(linkEl)
    {
        this.mask();

        this.lightbox.applyStyles('display: block;');
        this.lightbox.center();

        var m = linkEl.dom.rel.match(/enlarge_([0-9]+)_([0-9]+)/);
        var imgWidth = parseInt(m[1]);
        var imgHeight = parseInt(m[2]);

        // head
        var hd = Ext.DomHelper.overwrite(this.lightbox,
            { tag: 'div', cls:'lightboxHd', html: (linkEl.dom.title ? linkEl.dom.title : ' ') }
        );

        // head - close
        var closeLink = Ext.get(Ext.DomHelper.insertFirst(hd,
            { tag: 'a', cls: 'lightboxClose', href: '#', children: [
                { tag: 'img', src: '/assets/vps/images/spacer.gif', alt: 'close' }
            ]}
        ));

        // body
        var bd = Ext.get(Ext.DomHelper.append(this.lightbox,
            { tag: 'div', cls: 'lightboxBd' }
        ));

        // body - image
        var imageTopMargin = (parseInt(bd.getStyle('height')) - imgHeight) / 2;
        if (imageTopMargin < 0) imageTopMargin = 0;

        var img = Ext.get(Ext.DomHelper.append(bd, {
            tag    : 'img',
            src    : linkEl.dom.href,
            alt    : '',
            width  : imgWidth,
            height : imgHeight,
            style  : 'margin-top: '+imageTopMargin+'px;'
        }));

        // foot
        var ft = Ext.DomHelper.append(this.lightbox,
            { tag: 'div', cls: 'lightboxFt' }
        );
        if (linkEl.nextImage) {
            // overlay next button
            var bigNext = Ext.get(Ext.DomHelper.append(bd, {
                tag: 'div', cls: 'lightboxNextBig'
            }));
            var tmpTitle = linkEl.nextImage.dom.title;
            if (tmpTitle.length > 18) {
                tmpTitle = tmpTitle.substr(0, 15)+'...';
            }
            Ext.DomHelper.append(bigNext, {
                tag: 'div', cls: 'lightboxNextBigContent', children: [
                    { tag: 'img', cls: 'lightboxNextBigButton', src: '/assets/vps/images/spacer.gif', alt: 'next' },
                    { tag: 'br' },
                    { tag: 'img', src: linkEl.nextImage.child('img').dom.src, alt: '' },
                    { tag: 'div', html: tmpTitle }
                ]
            });
            bigNext.on('click', function(e) {
                this.show(linkEl.nextImage);
            }, this, { stopEvent: true });
            bigNext.on('mouseover', function(e) {
                this.addClass('bigOver');
            }, bigPrevious);
            bigNext.on('mouseout', function(e) {
                this.removeClass('bigOver');
            }, bigPrevious);

            // small next button
            var nextButton = Ext.get(Ext.DomHelper.append(ft,
                { tag: 'a', cls:'lightboxNext', href:'#', children: [
                    { tag: 'img', src: '/assets/vps/images/spacer.gif', alt: 'next' }
                ]}
            ));
            nextButton.on('click', function(e) {
                this.show(linkEl.nextImage);
            }, this, { stopEvent: true });

            // preload next image
            var tmpNextImage = new Image();
            tmpNextImage.src = linkEl.nextImage.dom.href;
        }
        if (linkEl.previousImage) {
            // overlay previous button
            var bigPrevious = Ext.get(Ext.DomHelper.append(bd, {
                tag: 'div', cls: 'lightboxPreviousBig'
            }));
            var tmpTitle = linkEl.previousImage.dom.title;
            if (tmpTitle.length > 18) {
                tmpTitle = tmpTitle.substr(0, 15)+'...';
            }
            Ext.DomHelper.append(bigPrevious, {
                tag: 'div', cls: 'lightboxPreviousBigContent', children: [
                    { tag: 'img', cls: 'lightboxPreviousBigButton', src: '/assets/vps/images/spacer.gif', alt: 'previous' },
                    { tag: 'br' },
                    { tag: 'img', src: linkEl.previousImage.child('img').dom.src, alt: '' },
                    { tag: 'div', html: tmpTitle }
                ]
            });
            bigPrevious.on('click', function(e) {
                this.show(linkEl.previousImage);
            }, this, { stopEvent: true });
            bigPrevious.on('mouseover', function(e) {
                this.addClass('bigOver');
            }, bigPrevious);
            bigPrevious.on('mouseout', function(e) {
                this.removeClass('bigOver');
            }, bigPrevious);

            // previous small button
            var prevButton = Ext.get(Ext.DomHelper.append(ft,
                { tag: 'a', cls:'lightboxPrevious', href:'#', children: [
                    { tag: 'img', src: '/assets/vps/images/spacer.gif', alt: 'previous' }
                ]}
            ));
            prevButton.on('click', function(e) {
                this.show(linkEl.previousImage);
            }, this, { stopEvent: true });

            // preload previous image
            var tmpPreviousImage = new Image();
            tmpPreviousImage.src = linkEl.previousImage.dom.href;

        }

        closeLink.on('click', this.hide, this, { stopEvent: true });
    },

    mask: function()
    {
        var maskEl = Ext.getBody().mask();
        Ext.getBody().removeClass('x-masked');
        maskEl.addClass('lightboxMask');
        maskEl.applyStyles('height:'+this.getPageSize()[1]+'px;');
        maskEl.on('click', this.hide, this);
    },

    unmask: function()
    {
        Ext.getBody().unmask();
        Ext.getBody().removeClass('lightboxShowOverflow');
    },

    getPageSize: function()
    {
        var xScroll, yScroll;

        if (window.innerHeight && window.scrollMaxY) {
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }

        var windowWidth, windowHeight;

        if (self.innerHeight) { // all except Explorer
            if(document.documentElement.clientWidth){
                windowWidth = document.documentElement.clientWidth;
            } else {
                windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }

        // for small pages with total height less then height of the viewport
        if(yScroll < windowHeight){
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }

        // for small pages with total width less then width of the viewport
        if(xScroll < windowWidth){
            pageWidth = xScroll;
        } else {
            pageWidth = windowWidth;
        }

        arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
        return arrayPageSize;
    }
};
<commit_msg>bei mir gabs da einenf ehler, whyever<commit_after>
Ext.onReady(function() {

    var lightbox = new Vpc.Basic.ImageEnlarge();
    var els = document.getElementsByTagName('a');
    Ext.each(els, function(el) {
        el = Ext.get(el);
        if (el) {
            if (el.dom.rel.match(/enlarge_[0-9]+_[0-9]+/)) {
                Ext.EventManager.addListener(el, 'click', function(e) {
                    lightbox.show(el, e);
                }, lightbox, { stopEvent: true });
            }
        }
    });
});

Ext.namespace("Vpc.Basic");
Vpc.Basic.ImageEnlarge = function()
{
    this.lightbox = Ext.get(
        Ext.DomHelper.append(Ext.getBody(),
            { tag: 'div', cls: 'lightbox' }
        )
    );
};

Vpc.Basic.ImageEnlarge.prototype =
{

    hide: function(e)
    {
        if (e) e.stopEvent();
        this.lightbox.applyStyles('display: none;');
        this.unmask();
    },

    show: function(linkEl)
    {
        this.mask();

        this.lightbox.applyStyles('display: block;');
        this.lightbox.center();

        var m = linkEl.dom.rel.match(/enlarge_([0-9]+)_([0-9]+)/);
        var imgWidth = parseInt(m[1]);
        var imgHeight = parseInt(m[2]);

        // head
        var hd = Ext.DomHelper.overwrite(this.lightbox,
            { tag: 'div', cls:'lightboxHd', html: (linkEl.dom.title ? linkEl.dom.title : ' ') }
        );

        // head - close
        var closeLink = Ext.get(Ext.DomHelper.insertFirst(hd,
            { tag: 'a', cls: 'lightboxClose', href: '#', children: [
                { tag: 'img', src: '/assets/vps/images/spacer.gif', alt: 'close' }
            ]}
        ));

        // body
        var bd = Ext.get(Ext.DomHelper.append(this.lightbox,
            { tag: 'div', cls: 'lightboxBd' }
        ));

        // body - image
        var imageTopMargin = (parseInt(bd.getStyle('height')) - imgHeight) / 2;
        if (imageTopMargin < 0) imageTopMargin = 0;

        var img = Ext.get(Ext.DomHelper.append(bd, {
            tag    : 'img',
            src    : linkEl.dom.href,
            alt    : '',
            width  : imgWidth,
            height : imgHeight,
            style  : 'margin-top: '+imageTopMargin+'px;'
        }));

        // foot
        var ft = Ext.DomHelper.append(this.lightbox,
            { tag: 'div', cls: 'lightboxFt' }
        );
        if (linkEl.nextImage) {
            // overlay next button
            var bigNext = Ext.get(Ext.DomHelper.append(bd, {
                tag: 'div', cls: 'lightboxNextBig'
            }));
            var tmpTitle = linkEl.nextImage.dom.title;
            if (tmpTitle.length > 18) {
                tmpTitle = tmpTitle.substr(0, 15)+'...';
            }
            Ext.DomHelper.append(bigNext, {
                tag: 'div', cls: 'lightboxNextBigContent', children: [
                    { tag: 'img', cls: 'lightboxNextBigButton', src: '/assets/vps/images/spacer.gif', alt: 'next' },
                    { tag: 'br' },
                    { tag: 'img', src: linkEl.nextImage.child('img').dom.src, alt: '' },
                    { tag: 'div', html: tmpTitle }
                ]
            });
            bigNext.on('click', function(e) {
                this.show(linkEl.nextImage);
            }, this, { stopEvent: true });
            bigNext.on('mouseover', function(e) {
                this.addClass('bigOver');
            }, bigPrevious);
            bigNext.on('mouseout', function(e) {
                this.removeClass('bigOver');
            }, bigPrevious);

            // small next button
            var nextButton = Ext.get(Ext.DomHelper.append(ft,
                { tag: 'a', cls:'lightboxNext', href:'#', children: [
                    { tag: 'img', src: '/assets/vps/images/spacer.gif', alt: 'next' }
                ]}
            ));
            nextButton.on('click', function(e) {
                this.show(linkEl.nextImage);
            }, this, { stopEvent: true });

            // preload next image
            var tmpNextImage = new Image();
            tmpNextImage.src = linkEl.nextImage.dom.href;
        }
        if (linkEl.previousImage) {
            // overlay previous button
            var bigPrevious = Ext.get(Ext.DomHelper.append(bd, {
                tag: 'div', cls: 'lightboxPreviousBig'
            }));
            var tmpTitle = linkEl.previousImage.dom.title;
            if (tmpTitle.length > 18) {
                tmpTitle = tmpTitle.substr(0, 15)+'...';
            }
            Ext.DomHelper.append(bigPrevious, {
                tag: 'div', cls: 'lightboxPreviousBigContent', children: [
                    { tag: 'img', cls: 'lightboxPreviousBigButton', src: '/assets/vps/images/spacer.gif', alt: 'previous' },
                    { tag: 'br' },
                    { tag: 'img', src: linkEl.previousImage.child('img').dom.src, alt: '' },
                    { tag: 'div', html: tmpTitle }
                ]
            });
            bigPrevious.on('click', function(e) {
                this.show(linkEl.previousImage);
            }, this, { stopEvent: true });
            bigPrevious.on('mouseover', function(e) {
                this.addClass('bigOver');
            }, bigPrevious);
            bigPrevious.on('mouseout', function(e) {
                this.removeClass('bigOver');
            }, bigPrevious);

            // previous small button
            var prevButton = Ext.get(Ext.DomHelper.append(ft,
                { tag: 'a', cls:'lightboxPrevious', href:'#', children: [
                    { tag: 'img', src: '/assets/vps/images/spacer.gif', alt: 'previous' }
                ]}
            ));
            prevButton.on('click', function(e) {
                this.show(linkEl.previousImage);
            }, this, { stopEvent: true });

            // preload previous image
            var tmpPreviousImage = new Image();
            tmpPreviousImage.src = linkEl.previousImage.dom.href;

        }

        closeLink.on('click', this.hide, this, { stopEvent: true });
    },

    mask: function()
    {
        var maskEl = Ext.getBody().mask();
        Ext.getBody().removeClass('x-masked');
        maskEl.addClass('lightboxMask');
        maskEl.applyStyles('height:'+this.getPageSize()[1]+'px;');
        maskEl.on('click', this.hide, this);
    },

    unmask: function()
    {
        Ext.getBody().unmask();
        Ext.getBody().removeClass('lightboxShowOverflow');
    },

    getPageSize: function()
    {
        var xScroll, yScroll;

        if (window.innerHeight && window.scrollMaxY) {
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }

        var windowWidth, windowHeight;

        if (self.innerHeight) { // all except Explorer
            if(document.documentElement.clientWidth){
                windowWidth = document.documentElement.clientWidth;
            } else {
                windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }

        // for small pages with total height less then height of the viewport
        if(yScroll < windowHeight){
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }

        // for small pages with total width less then width of the viewport
        if(xScroll < windowWidth){
            pageWidth = xScroll;
        } else {
            pageWidth = windowWidth;
        }

        arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
        return arrayPageSize;
    }
};
<|endoftext|>


<commit_before>/*
Copyright 2015 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var app = angular.module('PerfDashApp', ['ngMaterial', 'chart.js']);

var PerfDashApp = function(http, scope) {
    this.http = http;
    this.scope = scope;
    this.testNames = [];
    this.onClick = this.onClickInternal_.bind(this);
};

PerfDashApp.prototype.onClickInternal_ = function(data) {
    console.log(data);
    // Get location
    // TODO(random-liu): Make the URL configurable if we want to support more
    // buckets in the future.
    window.location = "http://kubekins.dls.corp.google.com/job/" + this.job + "/" + data[0].label + "/";
};

// Fetch data from the server and update the data to display
PerfDashApp.prototype.refresh = function() {
    this.http.get("api")
            .success(function(data) {
                this.testNames = Object.keys(data);
                this.testName = this.testNames[0];
                this.allData = data;
                this.testNameChanged();
            }.bind(this))
    .error(function(data) {
        console.log("error fetching result");
        console.log(data);
    });
};

// Update the data to graph, using selected labels
PerfDashApp.prototype.labelChanged = function() {
    this.seriesData = [];
    this.series = [];
    result = this.getData(this.selectedLabels);
    if (result.length <= 0) {
        return;
    }
    // All the unit should be the same
    this.options = {scaleLabel: "<%=value%> "+result[0].unit};
    angular.forEach(result[0].data, function(value, name) {
        this.seriesData.push(this.getStream(result, name));
        this.series.push(name);
    }, this);
};

// Update the data to graph, using the selected testName
PerfDashApp.prototype.testNameChanged = function() {
    this.data = this.allData[this.testName].builds;
    this.job = this.allData[this.testName].job;
    this.builds = this.getBuilds();
    this.labels = this.getLabels();
    this.labelChanged();
};

// Get all of the builds for the data set (e.g. build numbers)
PerfDashApp.prototype.getBuilds = function() {
    return Object.keys(this.data)
};

// Get the set of all labels (e.g. 'resources', 'verbs') in the data set
PerfDashApp.prototype.getLabels = function() {
    var set = {};
    angular.forEach(this.data, function(items, build) {
        angular.forEach(items, function(item) {
            angular.forEach(item.labels, function(label, name) {
                if (set[name] == undefined) {
                    set[name] = {}
                }
                set[name][label] = true
            });
        });
    });

    this.selectedLabels = {}
    var labels = {};
    angular.forEach(set, function(items, name) {
        labels[name] = [];
        angular.forEach(items, function(ignore, item) {
            if (this.selectedLabels[name] == undefined) {
              this.selectedLabels[name] = item;
            }
            labels[name].push(item)
        }, this);
    }, this);
    return labels;
};

// Extract a time series of data for specific labels
PerfDashApp.prototype.getData = function(labels) {
    var result = [];
    angular.forEach(this.data, function(items, build) {
        angular.forEach(items, function(item) {
            var match = true;
            angular.forEach(labels, function(label, name) {
                if (item.labels[name] != label) {
                    match = false;
                }
            });
            if (match) {
                result.push(item);
            }
        });
    });
    return result;
};

// Given a slice of data, turn it into a time series of numbers
// 'data' is an array of APICallLatency objects
// 'stream' is a selector for latency data, (e.g. 'Perc50')
PerfDashApp.prototype.getStream = function(data, stream) {
    var result = [];
    angular.forEach(data, function(value) {
        result.push(value.data[stream]);
    });
    return result;
};

app.controller('AppCtrl', ['$scope', '$http', '$interval', function($scope, $http, $interval) {
    $scope.controller = new PerfDashApp($http, $scope);
    $scope.controller.refresh();

    // Refresh every 5 min.  The data only refreshes every 10 minutes on the server
    $interval($scope.controller.refresh.bind($scope.controller), 300000)
}]);
<commit_msg>Improve ordering of timeseries.<commit_after>/*
Copyright 2015 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var app = angular.module('PerfDashApp', ['ngMaterial', 'chart.js']);

var PerfDashApp = function(http, scope) {
    this.http = http;
    this.scope = scope;
    this.testNames = [];
    this.onClick = this.onClickInternal_.bind(this);
};

PerfDashApp.prototype.onClickInternal_ = function(data) {
    console.log(data);
    // Get location
    // TODO(random-liu): Make the URL configurable if we want to support more
    // buckets in the future.
    window.location = "http://kubekins.dls.corp.google.com/job/" + this.job + "/" + data[0].label + "/";
};

// Fetch data from the server and update the data to display
PerfDashApp.prototype.refresh = function() {
    this.http.get("api")
            .success(function(data) {
                this.testNames = Object.keys(data);
                this.testName = this.testNames[0];
                this.allData = data;
                this.testNameChanged();
            }.bind(this))
    .error(function(data) {
        console.log("error fetching result");
        console.log(data);
    });
};

// Update the data to graph, using selected labels
PerfDashApp.prototype.labelChanged = function() {
    this.seriesData = [];
    this.series = [];
    result = this.getData(this.selectedLabels);
    if (result.length <= 0) {
        return;
    }
    // All the unit should be the same
    this.options = {scaleLabel: "<%=value%> "+result[0].unit};
    // Start with higher percentiles, since their values are usually strictly higher
    // than lower percentiles, which avoids obscuring graph data. It also orders data
    // in the onHover labels more naturally.
    var seriesLabels = Object.keys(result[0].data);
    seriesLabels.sort();
    seriesLabels.reverse();
    angular.forEach(seriesLabels, function(name) {
        this.seriesData.push(this.getStream(result, name));
        this.series.push(name);
    }, this);
};

// Update the data to graph, using the selected testName
PerfDashApp.prototype.testNameChanged = function() {
    this.data = this.allData[this.testName].builds;
    this.job = this.allData[this.testName].job;
    this.builds = this.getBuilds();
    this.labels = this.getLabels();
    this.labelChanged();
};

// Get all of the builds for the data set (e.g. build numbers)
PerfDashApp.prototype.getBuilds = function() {
    return Object.keys(this.data)
};

// Get the set of all labels (e.g. 'resources', 'verbs') in the data set
PerfDashApp.prototype.getLabels = function() {
    var set = {};
    angular.forEach(this.data, function(items, build) {
        angular.forEach(items, function(item) {
            angular.forEach(item.labels, function(label, name) {
                if (set[name] == undefined) {
                    set[name] = {}
                }
                set[name][label] = true
            });
        });
    });

    this.selectedLabels = {}
    var labels = {};
    angular.forEach(set, function(items, name) {
        labels[name] = [];
        angular.forEach(items, function(ignore, item) {
            if (this.selectedLabels[name] == undefined) {
              this.selectedLabels[name] = item;
            }
            labels[name].push(item)
        }, this);
    }, this);
    return labels;
};

// Extract a time series of data for specific labels
PerfDashApp.prototype.getData = function(labels) {
    var result = [];
    angular.forEach(this.data, function(items, build) {
        angular.forEach(items, function(item) {
            var match = true;
            angular.forEach(labels, function(label, name) {
                if (item.labels[name] != label) {
                    match = false;
                }
            });
            if (match) {
                result.push(item);
            }
        });
    });
    return result;
};

// Given a slice of data, turn it into a time series of numbers
// 'data' is an array of APICallLatency objects
// 'stream' is a selector for latency data, (e.g. 'Perc50')
PerfDashApp.prototype.getStream = function(data, stream) {
    var result = [];
    angular.forEach(data, function(value) {
        result.push(value.data[stream]);
    });
    return result;
};

app.controller('AppCtrl', ['$scope', '$http', '$interval', function($scope, $http, $interval) {
    $scope.controller = new PerfDashApp($http, $scope);
    $scope.controller.refresh();

    // Refresh every 5 min.  The data only refreshes every 10 minutes on the server
    $interval($scope.controller.refresh.bind($scope.controller), 300000)
}]);
<|endoftext|>


<commit_before>openerp.board = function(instance) {
var QWeb = instance.web.qweb,
    _t = instance.web._t;

if (!instance.board) {
    /** @namespace */
    instance.board = {};
}

instance.web.form.DashBoard = instance.web.form.FormWidget.extend({
    init: function(view, node) {
        this._super(view, node);
        this.form_template = 'DashBoard';
        this.actions_attrs = {};
        this.action_managers = [];
    },
    start: function() {
        var self = this;
        this._super.apply(this, arguments);

        this.$el.find('.oe_dashboard_column').sortable({
            connectWith: '.oe_dashboard_column',
            handle: '.oe_header',
            scroll: false
        }).bind('sortstop', self.do_save_dashboard);

        // Events
        this.$el.find('.oe_dashboard_link_reset').click(this.on_reset);
        this.$el.find('.oe_dashboard_link_change_layout').click(this.on_change_layout);
        this.$el.find('h2.oe_header span.oe_header_txt').click(function(ev){
            if(ev.target === ev.currentTarget)
                self.on_header_string($(ev.target).parent());
        });
        this.$el.delegate('.oe_dashboard_column .oe_fold', 'click', this.on_fold_action);
        this.$el.delegate('.oe_dashboard_column .oe_close', 'click', this.on_close_action);

        // Init actions
        _.each(this.node.children, function(column, column_index) {
            _.each(column.children, function(action, action_index) {
                delete(action.attrs.width);
                delete(action.attrs.height);
                delete(action.attrs.colspan);
                var action_id = _.str.toNumber(action.attrs.name);
                if (!_.isNaN(action_id)) {
                    self.rpc('/web/action/load', {action_id: action_id}, function(result) {
                        self.on_load_action(result, column_index + '_' + action_index, action.attrs);
                    });
                }
            });
        });
    },
    on_header_string:function(h2){
        var self = this;
        var span = h2.find('span:first').hide();
        var input = h2.find('.oe_header_text').css('visibility','visible');
        var attr = h2.closest(".oe_action").data('action_attrs');
        var change_string = function(new_name){
                attr['string'] = new_name;
                span.text(new_name).show();
                input.css('visibility','hidden');
                self.do_save_dashboard();
        }
        input.unbind()
        .val(span.text())
        .change(function(event){
            change_string($(this).val());
        })
        .keyup(function(event){
            if(event.keyCode == 27){
                //esc key to cancel changes
                input.css('visibility','hidden');
                span.show();
            }
        });
    },
    on_reset: function() {
        this.rpc('/web/view/undo_custom', {
            view_id: this.view.fields_view.view_id,
            reset: true
        }, this.do_reload);
    },
    on_change_layout: function() {
        var self = this;
        var qdict = {
            current_layout : this.$el.find('.oe_dashboard').attr('data-layout')
        };
        var $dialog = instance.web.dialog($('<div>'), {
                            modal: true,
                            title: _t("Edit Layout"),
                            width: 'auto',
                            height: 'auto'
                        }).html(QWeb.render('DashBoard.layouts', qdict));
        $dialog.find('li').click(function() {
            var layout = $(this).attr('data-layout');
            $dialog.dialog('destroy');
            self.do_change_layout(layout);
        });
    },
    do_change_layout: function(new_layout) {
        var $dashboard = this.$el.find('.oe_dashboard');
        var current_layout = $dashboard.attr('data-layout');
        if (current_layout != new_layout) {
            var clayout = current_layout.split('-').length,
                nlayout = new_layout.split('-').length,
                column_diff = clayout - nlayout;
            if (column_diff > 0) {
                var $last_column = $();
                $dashboard.find('.oe_dashboard_column').each(function(k, v) {
                    if (k >= nlayout) {
                        $(v).find('.oe_action').appendTo($last_column);
                    } else {
                        $last_column = $(v);
                    }
                });
            }
            $dashboard.toggleClass('oe_dashboard_layout_' + current_layout + ' oe_dashboard_layout_' + new_layout);
            $dashboard.attr('data-layout', new_layout);
            this.do_save_dashboard();
        }
    },
    on_fold_action: function(e) {
        var $e = $(e.currentTarget),
            $action = $e.parents('.oe_action:first'),
            id = parseInt($action.attr('data-id'), 10);
        if ($e.is('.oe_minimize')) {
            $action.data('action_attrs').fold = '1';
        } else {
            delete($action.data('action_attrs').fold);
        }
        $e.toggleClass('oe_minimize oe_maximize');
        $action.find('.oe_content').toggle();
        this.do_save_dashboard();
    },
    on_close_action: function(e) {
        if (confirm(_t("Are you sure you want to remove this item ?"))) {
            $(e.currentTarget).parents('.oe_action:first').remove();
            this.do_save_dashboard();
        }
    },
    do_save_dashboard: function() {
        var self = this;
        var board = {
                form_title : this.view.fields_view.arch.attrs.string,
                style : this.$el.find('.oe_dashboard').attr('data-layout'),
                columns : []
            };
        this.$el.find('.oe_dashboard_column').each(function() {
            var actions = [];
            $(this).find('.oe_action').each(function() {
                var action_id = $(this).attr('data-id'),
                    new_attrs = _.clone($(this).data('action_attrs'));
                if (new_attrs.domain) {
                    new_attrs.domain = new_attrs.domain_string;
                    delete(new_attrs.domain_string);
                }
                if (new_attrs.context) {
                    new_attrs.context = new_attrs.context_string;
                    delete(new_attrs.context_string);
                }
                actions.push(new_attrs);
            });
            board.columns.push(actions);
        });
        var arch = QWeb.render('DashBoard.xml', board);
        this.rpc('/web/view/add_custom', {
            view_id: this.view.fields_view.view_id,
            arch: arch
        }, function() {
            self.$el.find('.oe_dashboard_link_reset').show();
        });
    },
    on_load_action: function(result, index, action_attrs) {
        var self = this,
            action = result.result,
            view_mode = action_attrs.view_mode;

        if (action_attrs.context && action_attrs.context['dashboard_merge_domains_contexts'] === false) {
            // TODO: replace this 6.1 workaround by attribute on <action/>
            action.context = action_attrs.context || {};
            action.domain = action_attrs.domain || [];
        } else {
            if (action_attrs.context) {
                action.context = _.extend((action.context || {}), action_attrs.context);
            }
            if (action_attrs.domain) {
                action.domain = action.domain || [];
                action.domain.unshift.apply(action.domain, action_attrs.domain);
            }
        }

        var action_orig = _.extend({ flags : {} }, action);

        if (view_mode && view_mode != action.view_mode) {
            action.views = _.map(view_mode.split(','), function(mode) {
                mode = mode === 'tree' ? 'list' : mode;
                return _(action.views).find(function(view) { return view[1] == mode; })
                    || [false, mode];
            });
        }

        action.flags = {
            search_view : false,
            sidebar : false,
            views_switcher : false,
            action_buttons : false,
            pager: false,
            low_profile: true,
            display_title: false,
            list: {
                selectable: false
            }
        };
        var am = new instance.web.ActionManager(this),
            // FIXME: ideally the dashboard view shall be refactored like kanban.
            $action = $('#' + this.view.element_id + '_action_' + index);
        $action.parent().data('action_attrs', action_attrs);
        this.action_managers.push(am);
        am.appendTo($action);
        am.do_action(action);
        am.do_action = function (action) {
            self.do_action(action);
        };
        if (action_attrs.creatable && action_attrs.creatable !== 'false') {
            var action_id = parseInt(action_attrs.creatable, 10);
            $action.parent().find('button.oe_dashboard_button_create').click(function() {
                if (isNaN(action_id)) {
                    action_orig.flags.default_view = 'form';
                    self.do_action(action_orig);
                } else {
                    self.rpc('/web/action/load', {
                        action_id: action_id
                    }, function(result) {
                        result.result.flags = result.result.flags || {};
                        result.result.flags.default_view = 'form';
                        self.do_action(result.result);
                    });
                }
            });
        }
        if (am.inner_widget) {
            am.inner_widget.on_mode_switch.add(function(mode) {
                var new_views = [];
                _.each(action_orig.views, function(view) {
                    new_views[view[1] === mode ? 'unshift' : 'push'](view);
                });
                if (!new_views.length || new_views[0][1] !== mode) {
                    new_views.unshift([false, mode]);
                }
                action_orig.views = new_views;
                action_orig.res_id = am.inner_widget.dataset.ids[am.inner_widget.dataset.index];
                self.do_action(action_orig);
            });
        }
    },
    renderElement: function() {
        this._super();

        var check = _.detect(this.node.children, function(column, column_index) {
            return _.detect(column.children,function(element){
                return element.tag === "action"? element: false;
            });
        });
        if (!check) {
            return this.no_result();
        }
        // We should start with three columns available
        for (var i = this.node.children.length; i < 3; i++) {
            this.node.children.push({
                tag: 'column',
                attrs: {},
                children: []
            });
        }
        var rendered = QWeb.render(this.form_template, this);
        this.$el.html(rendered);
    },
    no_result: function() {
        if (this.view.options.action.help) {
            this.$el.append(
                $('<div class="oe_view_nocontent">')
                    .append($('<div>').html(this.view.options.action.help || " "))
            );
        }
    },
    do_reload: function() {
        var view_manager = this.view.getParent(),
            action_manager = view_manager.getParent();
        this.view.destroy();
        action_manager.do_action(view_manager.action);
    }
});
instance.web.form.DashBoardLegacy = instance.web.form.DashBoard.extend({
    renderElement: function() {
        if (this.node.tag == 'hpaned') {
            this.node.attrs.style = '2-1';
        } else if (this.node.tag == 'vpaned') {
            this.node.attrs.style = '1';
        }
        this.node.tag = 'board';
        _.each(this.node.children, function(child) {
            if (child.tag.indexOf('child') == 0) {
                child.tag = 'column';
                var actions = [], first_child = child.children[0];
                if (first_child && first_child.tag == 'vpaned') {
                    _.each(first_child.children, function(subchild) {
                        actions.push.apply(actions, subchild.children);
                    });
                    child.children = actions;
                }
            }
        });
        this._super(this);
    }
});

instance.web.form.tags.add('hpaned', 'instance.web.form.DashBoardLegacy');
instance.web.form.tags.add('vpaned', 'instance.web.form.DashBoardLegacy');
instance.web.form.tags.add('board', 'instance.web.form.DashBoard');

instance.board.AddToDashboard = instance.web.search.Input.extend({
    template: 'SearchView.addtodashboard',
    _in_drawer: true,
    start: function () {
        var self = this;
        this.$el
            .on('click', 'h4', this.proxy('show_option'))
            .on('submit', 'form', function (e) {
                e.preventDefault();
                self.add_dashboard();
            });
        return this.load_data().then(this.proxy("render_data"));
    },
    load_data:function(){
        var board = new instance.web.Model('board.board');
        return board.call('list');
    },
    _x:function() {
        if (!instance.webclient) { return $.Deferred().reject(); }
        var dashboard_menu = instance.webclient.menu.data.data.children;
        return new instance.web.Model('ir.model.data')
                .query(['res_id'])
                .filter([['name','=','menu_reporting_dashboard']])
                .first().pipe(function (result) {
            var menu = _(dashboard_menu).chain()
                .pluck('children')
                .flatten(true)
                .find(function (child) { return child.id === result.res_id; })
                .value();
            return menu ? menu.children : [];
        });
    },
    render_data: function(dashboard_choices){
        var selection = instance.web.qweb.render(
            "SearchView.addtodashboard.selection", {
                selections: dashboard_choices});
        this.$("input").before(selection)
    },
    add_dashboard: function(){
        var self = this;
        var getParent = this.getParent();
        var view_parent = this.getParent().getParent();
        if (! view_parent.action || ! this.$el.find("select").val()) {
            this.do_warn("Can't find dashboard action");
            return;
        }
        var data = getParent.build_search_data();
        var context = new instance.web.CompoundContext(getParent.dataset.get_context() || []);
        var domain = new instance.web.CompoundDomain(getParent.dataset.get_domain() || []);
        _.each(data.contexts, context.add, context);
        _.each(data.domains, domain.add, domain);
        this.rpc('/board/add_to_dashboard', {
            menu_id: this.$el.find("select").val(),
            action_id: view_parent.action.id,
            context_to_save: context,
            domain: domain,
            view_mode: view_parent.active_view,
            name: this.$el.find("input").val()
        }, function(r) {
            if (r === false) {
                self.do_warn("Could not add filter to dashboard");
            } else {
                self.$el.toggleClass('oe_opened');
                self.do_notify("Filter added to dashboard", '');
            }
        });
    },
    show_option:function(){
        this.$el.toggleClass('oe_opened');
        if (! this.$el.hasClass('oe_opened'))
            return;
        this.$("input").val(this.getParent().fields_view.name || "" );
    }
});

instance.web.SearchView.include({
    add_common_inputs: function() {
        this._super();
        (new instance.board.AddToDashboard(this));

    }
});

};
<commit_msg>[IMP]Set title again which is replace by on_record_loaded method.<commit_after>openerp.board = function(instance) {
var QWeb = instance.web.qweb,
    _t = instance.web._t;

if (!instance.board) {
    /** @namespace */
    instance.board = {};
}

instance.web.form.DashBoard = instance.web.form.FormWidget.extend({
    init: function(view, node) {
        this._super(view, node);
        this.form_template = 'DashBoard';
        this.actions_attrs = {};
        this.action_managers = [];
    },
    start: function() {
        var self = this;
        this._super.apply(this, arguments);

        this.$el.find('.oe_dashboard_column').sortable({
            connectWith: '.oe_dashboard_column',
            handle: '.oe_header',
            scroll: false
        }).bind('sortstop', self.do_save_dashboard);

        var old_title = this.__parentedParent.get('title');
        this.__parentedParent.on_record_loaded.add_last(function(){
            self.__parentedParent.set({ 'title' : old_title});
        });
        // Events
        this.$el.find('.oe_dashboard_link_reset').click(this.on_reset);
        this.$el.find('.oe_dashboard_link_change_layout').click(this.on_change_layout);
        this.$el.find('h2.oe_header span.oe_header_txt').click(function(ev){
            if(ev.target === ev.currentTarget)
                self.on_header_string($(ev.target).parent());
        });
        this.$el.delegate('.oe_dashboard_column .oe_fold', 'click', this.on_fold_action);
        this.$el.delegate('.oe_dashboard_column .oe_close', 'click', this.on_close_action);

        // Init actions
        _.each(this.node.children, function(column, column_index) {
            _.each(column.children, function(action, action_index) {
                delete(action.attrs.width);
                delete(action.attrs.height);
                delete(action.attrs.colspan);
                var action_id = _.str.toNumber(action.attrs.name);
                if (!_.isNaN(action_id)) {
                    self.rpc('/web/action/load', {action_id: action_id}, function(result) {
                        self.on_load_action(result, column_index + '_' + action_index, action.attrs);
                    });
                }
            });
        });
    },
    on_header_string:function(h2){
        var self = this;
        var span = h2.find('span:first').hide();
        var input = h2.find('.oe_header_text').css('visibility','visible');
        var attr = h2.closest(".oe_action").data('action_attrs');
        var change_string = function(new_name){
                attr['string'] = new_name;
                span.text(new_name).show();
                input.css('visibility','hidden');
                self.do_save_dashboard();
        }
        input.unbind()
        .val(span.text())
        .change(function(event){
            change_string($(this).val());
        })
        .keyup(function(event){
            if(event.keyCode == 27){
                //esc key to cancel changes
                input.css('visibility','hidden');
                span.show();
            }
        });
    },
    on_reset: function() {
        this.rpc('/web/view/undo_custom', {
            view_id: this.view.fields_view.view_id,
            reset: true
        }, this.do_reload);
    },
    on_change_layout: function() {
        var self = this;
        var qdict = {
            current_layout : this.$el.find('.oe_dashboard').attr('data-layout')
        };
        var $dialog = instance.web.dialog($('<div>'), {
                            modal: true,
                            title: _t("Edit Layout"),
                            width: 'auto',
                            height: 'auto'
                        }).html(QWeb.render('DashBoard.layouts', qdict));
        $dialog.find('li').click(function() {
            var layout = $(this).attr('data-layout');
            $dialog.dialog('destroy');
            self.do_change_layout(layout);
        });
    },
    do_change_layout: function(new_layout) {
        var $dashboard = this.$el.find('.oe_dashboard');
        var current_layout = $dashboard.attr('data-layout');
        if (current_layout != new_layout) {
            var clayout = current_layout.split('-').length,
                nlayout = new_layout.split('-').length,
                column_diff = clayout - nlayout;
            if (column_diff > 0) {
                var $last_column = $();
                $dashboard.find('.oe_dashboard_column').each(function(k, v) {
                    if (k >= nlayout) {
                        $(v).find('.oe_action').appendTo($last_column);
                    } else {
                        $last_column = $(v);
                    }
                });
            }
            $dashboard.toggleClass('oe_dashboard_layout_' + current_layout + ' oe_dashboard_layout_' + new_layout);
            $dashboard.attr('data-layout', new_layout);
            this.do_save_dashboard();
        }
    },
    on_fold_action: function(e) {
        var $e = $(e.currentTarget),
            $action = $e.parents('.oe_action:first'),
            id = parseInt($action.attr('data-id'), 10);
        if ($e.is('.oe_minimize')) {
            $action.data('action_attrs').fold = '1';
        } else {
            delete($action.data('action_attrs').fold);
        }
        $e.toggleClass('oe_minimize oe_maximize');
        $action.find('.oe_content').toggle();
        this.do_save_dashboard();
    },
    on_close_action: function(e) {
        if (confirm(_t("Are you sure you want to remove this item ?"))) {
            $(e.currentTarget).parents('.oe_action:first').remove();
            this.do_save_dashboard();
        }
    },
    do_save_dashboard: function() {
        var self = this;
        var board = {
                form_title : this.view.fields_view.arch.attrs.string,
                style : this.$el.find('.oe_dashboard').attr('data-layout'),
                columns : []
            };
        this.$el.find('.oe_dashboard_column').each(function() {
            var actions = [];
            $(this).find('.oe_action').each(function() {
                var action_id = $(this).attr('data-id'),
                    new_attrs = _.clone($(this).data('action_attrs'));
                if (new_attrs.domain) {
                    new_attrs.domain = new_attrs.domain_string;
                    delete(new_attrs.domain_string);
                }
                if (new_attrs.context) {
                    new_attrs.context = new_attrs.context_string;
                    delete(new_attrs.context_string);
                }
                actions.push(new_attrs);
            });
            board.columns.push(actions);
        });
        var arch = QWeb.render('DashBoard.xml', board);
        this.rpc('/web/view/add_custom', {
            view_id: this.view.fields_view.view_id,
            arch: arch
        }, function() {
            self.$el.find('.oe_dashboard_link_reset').show();
        });
    },
    on_load_action: function(result, index, action_attrs) {
        var self = this,
            action = result.result,
            view_mode = action_attrs.view_mode;

        if (action_attrs.context && action_attrs.context['dashboard_merge_domains_contexts'] === false) {
            // TODO: replace this 6.1 workaround by attribute on <action/>
            action.context = action_attrs.context || {};
            action.domain = action_attrs.domain || [];
        } else {
            if (action_attrs.context) {
                action.context = _.extend((action.context || {}), action_attrs.context);
            }
            if (action_attrs.domain) {
                action.domain = action.domain || [];
                action.domain.unshift.apply(action.domain, action_attrs.domain);
            }
        }

        var action_orig = _.extend({ flags : {} }, action);

        if (view_mode && view_mode != action.view_mode) {
            action.views = _.map(view_mode.split(','), function(mode) {
                mode = mode === 'tree' ? 'list' : mode;
                return _(action.views).find(function(view) { return view[1] == mode; })
                    || [false, mode];
            });
        }

        action.flags = {
            search_view : false,
            sidebar : false,
            views_switcher : false,
            action_buttons : false,
            pager: false,
            low_profile: true,
            display_title: false,
            list: {
                selectable: false
            }
        };
        var am = new instance.web.ActionManager(this),
            // FIXME: ideally the dashboard view shall be refactored like kanban.
            $action = $('#' + this.view.element_id + '_action_' + index);
        $action.parent().data('action_attrs', action_attrs);
        this.action_managers.push(am);
        am.appendTo($action);
        am.do_action(action);
        am.do_action = function (action) {
            self.do_action(action);
        };
        if (action_attrs.creatable && action_attrs.creatable !== 'false') {
            var action_id = parseInt(action_attrs.creatable, 10);
            $action.parent().find('button.oe_dashboard_button_create').click(function() {
                if (isNaN(action_id)) {
                    action_orig.flags.default_view = 'form';
                    self.do_action(action_orig);
                } else {
                    self.rpc('/web/action/load', {
                        action_id: action_id
                    }, function(result) {
                        result.result.flags = result.result.flags || {};
                        result.result.flags.default_view = 'form';
                        self.do_action(result.result);
                    });
                }
            });
        }
        if (am.inner_widget) {
            am.inner_widget.on_mode_switch.add(function(mode) {
                var new_views = [];
                _.each(action_orig.views, function(view) {
                    new_views[view[1] === mode ? 'unshift' : 'push'](view);
                });
                if (!new_views.length || new_views[0][1] !== mode) {
                    new_views.unshift([false, mode]);
                }
                action_orig.views = new_views;
                action_orig.res_id = am.inner_widget.dataset.ids[am.inner_widget.dataset.index];
                self.do_action(action_orig);
            });
        }
    },
    renderElement: function() {
        this._super();

        var check = _.detect(this.node.children, function(column, column_index) {
            return _.detect(column.children,function(element){
                return element.tag === "action"? element: false;
            });
        });
        if (!check) {
            return this.no_result();
        }
        // We should start with three columns available
        for (var i = this.node.children.length; i < 3; i++) {
            this.node.children.push({
                tag: 'column',
                attrs: {},
                children: []
            });
        }
        var rendered = QWeb.render(this.form_template, this);
        this.$el.html(rendered);
    },
    no_result: function() {
        if (this.view.options.action.help) {
            this.$el.append(
                $('<div class="oe_view_nocontent">')
                    .append($('<div>').html(this.view.options.action.help || " "))
            );
        }
    },
    do_reload: function() {
        var view_manager = this.view.getParent(),
            action_manager = view_manager.getParent();
        this.view.destroy();
        action_manager.do_action(view_manager.action);
    }
});
instance.web.form.DashBoardLegacy = instance.web.form.DashBoard.extend({
    renderElement: function() {
        if (this.node.tag == 'hpaned') {
            this.node.attrs.style = '2-1';
        } else if (this.node.tag == 'vpaned') {
            this.node.attrs.style = '1';
        }
        this.node.tag = 'board';
        _.each(this.node.children, function(child) {
            if (child.tag.indexOf('child') == 0) {
                child.tag = 'column';
                var actions = [], first_child = child.children[0];
                if (first_child && first_child.tag == 'vpaned') {
                    _.each(first_child.children, function(subchild) {
                        actions.push.apply(actions, subchild.children);
                    });
                    child.children = actions;
                }
            }
        });
        this._super(this);
    }
});

instance.web.form.tags.add('hpaned', 'instance.web.form.DashBoardLegacy');
instance.web.form.tags.add('vpaned', 'instance.web.form.DashBoardLegacy');
instance.web.form.tags.add('board', 'instance.web.form.DashBoard');

instance.board.AddToDashboard = instance.web.search.Input.extend({
    template: 'SearchView.addtodashboard',
    _in_drawer: true,
    start: function () {
        var self = this;
        this.$el
            .on('click', 'h4', this.proxy('show_option'))
            .on('submit', 'form', function (e) {
                e.preventDefault();
                self.add_dashboard();
            });
        return this.load_data().then(this.proxy("render_data"));
    },
    load_data:function(){
        var board = new instance.web.Model('board.board');
        return board.call('list');
    },
    _x:function() {
        if (!instance.webclient) { return $.Deferred().reject(); }
        var dashboard_menu = instance.webclient.menu.data.data.children;
        return new instance.web.Model('ir.model.data')
                .query(['res_id'])
                .filter([['name','=','menu_reporting_dashboard']])
                .first().pipe(function (result) {
            var menu = _(dashboard_menu).chain()
                .pluck('children')
                .flatten(true)
                .find(function (child) { return child.id === result.res_id; })
                .value();
            return menu ? menu.children : [];
        });
    },
    render_data: function(dashboard_choices){
        var selection = instance.web.qweb.render(
            "SearchView.addtodashboard.selection", {
                selections: dashboard_choices});
        this.$("input").before(selection)
    },
    add_dashboard: function(){
        var self = this;
        var getParent = this.getParent();
        var view_parent = this.getParent().getParent();
        if (! view_parent.action || ! this.$el.find("select").val()) {
            this.do_warn("Can't find dashboard action");
            return;
        }
        var data = getParent.build_search_data();
        var context = new instance.web.CompoundContext(getParent.dataset.get_context() || []);
        var domain = new instance.web.CompoundDomain(getParent.dataset.get_domain() || []);
        _.each(data.contexts, context.add, context);
        _.each(data.domains, domain.add, domain);
        this.rpc('/board/add_to_dashboard', {
            menu_id: this.$el.find("select").val(),
            action_id: view_parent.action.id,
            context_to_save: context,
            domain: domain,
            view_mode: view_parent.active_view,
            name: this.$el.find("input").val()
        }, function(r) {
            if (r === false) {
                self.do_warn("Could not add filter to dashboard");
            } else {
                self.$el.toggleClass('oe_opened');
                self.do_notify("Filter added to dashboard", '');
            }
        });
    },
    show_option:function(){
        this.$el.toggleClass('oe_opened');
        if (! this.$el.hasClass('oe_opened'))
            return;
        this.$("input").val(this.getParent().fields_view.name || "" );
    }
});

instance.web.SearchView.include({
    add_common_inputs: function() {
        this._super();
        (new instance.board.AddToDashboard(this));

    }
});

};
<|endoftext|>


<commit_before>var dataRef = new Firebase("https://sudarshan.firebaseio.com/");
var ytplayer = null;
var mp4player = null;

var roomName = null;
var tokboxSession = null;
var tokboxToken = null;

var disableUntil;

var last_in = null;

function makeRoom (name) {
  $.getJSON("http://www.smuralidhar.com/pennapps2014s/generate.php", function(res){
    dataRef = dataRef.root();
    dataRef = dataRef.child(name);
    dataRef.on('value', incoming);
    dataRef.update(
      {"type": null, "video": null, seek: 0, timestamp: now(), playing: false, "sessionId": res.sessionId, "token": res.token}
  );
  });
}

function joinRoom (name) {
  dataRef = dataRef.root();
  dataRef = dataRef.child(name);
  dataRef.on('value', incoming);
}

function incoming (fb) {
  var data = fb.val();
  last_in = data;
  console.log("inc");
  console.log(data);

  if (data == null){
    alert("room does not exist");
  }

  if (roomName == null){
    roomName = name;
    tokboxSession = data.sessionId;
    tokboxToken = data.token;
  }

  if (data.type == null){
    showWelcomeMessage();
  }
  else if (data.type == "YT") {
    if (ytplayer == null)
      makeYtPlayer(data.video);
    else
      handleYtInc(data);
  }
  else if (data.type == "mp4"){
    if (mp4player == null)
      makeMp4Player(data);
    else
      handleMp4Inc(data);
  }
}

function outgoing (playing, seek) {
  console.log("out");
  console.log({playing:playing, seek:seek});
  dataRef.update(
    {playing: playing, seek: seek, timestamp: now()}
  );
}

function showWelcomeMessage () {
  $("#youtube").html("Choose a video: "+
    "<input id='vid' type='text' placeholder='Choose a video></input>" +
    "<button id='choose'>Load</button>");
  $("#choose").click(function(){
    var vid = $("#vid")[0].value + "#";
    if (vid.indexOf("youtube.com")>-1){
      var key = vid.substring(vid.indexOf("v=")+2, vid.indexOf("#"));
      var type = "YT";
      dataRef.update({type: type, video: key});
    }
    else if (vid.indexOf(".mp4") > -1){
      dataRef.update({type:"mp4", video: $("#vid")[0].value});
    }
    else
      alert ("link not recognized");
  });
}

function makeYtPlayer(vid) {
  disableUntil = -1;
  var params = { allowScriptAccess: "always" };
  var atts = { id: "myytplayer" };
  swfobject.embedSWF("http://www.youtube.com/v/" + vid + "?version=3&controls=1&enablejsapi=1&playerapiid=ytplayer&allowfullscreen=1",
    "ytapiplayer", "100%", "100%", "8", null, null, params, atts);
}
function makeMp4Player(data) {
  disableUntil = null;
  jwplayer("ytapiplayer").setup({file: data.video, width: "100%", height: "100%"});
  mp4player = jwplayer();
  mp4player.onReady(function() {
    var instastop = true;
    mp4player.onPlay(function(){
      if (instastop){
        console.log('setup');
        instastop = false;
        mp4player.pause(true);

        //mp4player.onSeek(mp4SeekListener);
        mp4player.onPlay(function() {mp4PlayPauseListener(true)});
        mp4player.onPause(function() {mp4PlayPauseListener(false)});

        handleMp4Inc(data);
      }
    })
    mp4player.play(true);
  })
}

function onYouTubePlayerReady(playerId) {
  ytplayer = $("#myytplayer")[0];
  ytplayer.addEventListener("onStateChange", "ytListener");

  handleYtInc(last_in);

  setInterval(function(){
    dataRef.once('value', function(data){
      var pres = now();
      var curr = ytplayer.getCurrentTime();
      data = data.val();
      if (data.playing)
        loc = data.seek + pres - data.timestamp;
      else
        loc = data.seek;
      var playing = ytplayer.getPlayerState() == 1;

      //console.log(curr - loc);
      if (Math.abs (curr - loc) > 0.5 ||
          data.playing != playing)
        handleYtInc(data);
    })
  }, 2000);
}

function handleYtInc(data) {
  // disable the listener until state is correct
  if (data.playing)
    disableUntil = 1;
  else
    disableUntil = 2;

  if (data.playing)
    data.seek += now() - data.timestamp;

  ytplayer.seekTo(data.seek);

  if (data.playing)
    ytplayer.playVideo();
  else
    ytplayer.pauseVideo();
}

function handleMp4Inc(data) {
  console.log("HANDLE");
  disableUntil = data.playing;
  if (data.playing)
    data.seek += now() - data.timestamp;

  //mp4player.seek(data.seek);

  mp4player.play(data.playing);

  setTimeout(hack, 100);

  function hack (){
    console.log("hacking");
    if (disableUntil == data.playing){
      mp4player.play(data.playing);
      setTimeout(hack, 100);
    }
  }

  console.log('done handle');
}

function ytListener (value){
  if (disableUntil > -1){
    console.log("ignoring- " + value);
    if (disableUntil == value)
      disableUntil = -1;
    return;
  }
  switch (value) {
    case -1:
      console.log("unstarted");
      disableUntil = 2;
      ytplayer.seekTo(0);
      ytplayer.pauseVideo();
      break;
    case 0:
      console.log("ended");
      break;
    case 1:
      console.log("playing");
      disableUntil = 1;
      ytplayer.pauseVideo();
      outgoing (true, ytplayer.getCurrentTime());
      break;
    case 2:
      console.log("paused");
      disableUntil = 2;
      ytplayer.playVideo();
      outgoing (false, ytplayer.getCurrentTime());
      break;
    case 3:
      console.log("buffering");
      break;
    case 5:
      console.log("cued");
      break;
  }
}

function mp4PlayPauseListener (play){
  if (disableUntil != null){
    console.log("ignoring " + play)
    if (disableUntil == play)
      disableUntil = null;
    return;
  }

  console.log(play);
  disableUntil = play;

  mp4player.pause(play);
  outgoing (play, mp4player.getPosition());
}

function now () {
  return new Date().getTime() / 1000;
}

$(document).ready (function() {
  $("#create").click(function() {
    makeRoom($("#room")[0].value)
  });
  $("#join").click(function() {
    joinRoom($("#room")[0].value)
  });
})
<commit_msg>youtube div<commit_after>var dataRef = new Firebase("https://sudarshan.firebaseio.com/");
var ytplayer = null;
var mp4player = null;

var roomName = null;
var tokboxSession = null;
var tokboxToken = null;

var disableUntil;

var last_in = null;

function makeRoom (name) {
  $.getJSON("http://www.smuralidhar.com/pennapps2014s/generate.php", function(res){
    dataRef = dataRef.root();
    dataRef = dataRef.child(name);
    dataRef.on('value', incoming);
    dataRef.update(
      {"type": null, "video": null, seek: 0, timestamp: now(), playing: false, "sessionId": res.sessionId, "token": res.token}
  );
  });
}

function joinRoom (name) {
  dataRef = dataRef.root();
  dataRef = dataRef.child(name);
  dataRef.on('value', incoming);
}

function incoming (fb) {
  var data = fb.val();
  last_in = data;
  console.log("inc");
  console.log(data);

  if (data == null){
    alert("room does not exist");
  }

  if (roomName == null){
    roomName = name;
    tokboxSession = data.sessionId;
    tokboxToken = data.token;
  }

  if (data.type == null){
    showWelcomeMessage();
  }
  else if (data.type == "YT") {
    if (ytplayer == null)
      makeYtPlayer(data.video);
    else
      handleYtInc(data);
  }
  else if (data.type == "mp4"){
    if (mp4player == null)
      makeMp4Player(data);
    else
      handleMp4Inc(data);
  }
}

function outgoing (playing, seek) {
  console.log("out");
  console.log({playing:playing, seek:seek});
  dataRef.update(
    {playing: playing, seek: seek, timestamp: now()}
  );
}

function showWelcomeMessage () {
  $("#ytapiplayer").html("Choose a video: "+
    "<input id='vid' type='text' placeholder='Choose a video></input>" +
    "<button id='choose'>Load</button>");
  $("#choose").click(function(){
    var vid = $("#vid")[0].value + "#";
    if (vid.indexOf("youtube.com")>-1){
      var key = vid.substring(vid.indexOf("v=")+2, vid.indexOf("#"));
      var type = "YT";
      dataRef.update({type: type, video: key});
    }
    else if (vid.indexOf(".mp4") > -1){
      dataRef.update({type:"mp4", video: $("#vid")[0].value});
    }
    else
      alert ("link not recognized");
  });
}

function makeYtPlayer(vid) {
  disableUntil = -1;
  var params = { allowScriptAccess: "always" };
  var atts = { id: "myytplayer" };
  swfobject.embedSWF("http://www.youtube.com/v/" + vid + "?version=3&controls=1&enablejsapi=1&playerapiid=ytplayer&allowfullscreen=1",
    "ytapiplayer", "100%", "100%", "8", null, null, params, atts);
}
function makeMp4Player(data) {
  disableUntil = null;
  jwplayer("ytapiplayer").setup({file: data.video, width: "100%", height: "100%"});
  mp4player = jwplayer();
  mp4player.onReady(function() {
    var instastop = true;
    mp4player.onPlay(function(){
      if (instastop){
        console.log('setup');
        instastop = false;
        mp4player.pause(true);

        //mp4player.onSeek(mp4SeekListener);
        mp4player.onPlay(function() {mp4PlayPauseListener(true)});
        mp4player.onPause(function() {mp4PlayPauseListener(false)});

        handleMp4Inc(data);
      }
    })
    mp4player.play(true);
  })
}

function onYouTubePlayerReady(playerId) {
  ytplayer = $("#myytplayer")[0];
  ytplayer.addEventListener("onStateChange", "ytListener");

  handleYtInc(last_in);

  setInterval(function(){
    dataRef.once('value', function(data){
      var pres = now();
      var curr = ytplayer.getCurrentTime();
      data = data.val();
      if (data.playing)
        loc = data.seek + pres - data.timestamp;
      else
        loc = data.seek;
      var playing = ytplayer.getPlayerState() == 1;

      //console.log(curr - loc);
      if (Math.abs (curr - loc) > 0.5 ||
          data.playing != playing)
        handleYtInc(data);
    })
  }, 2000);
}

function handleYtInc(data) {
  // disable the listener until state is correct
  if (data.playing)
    disableUntil = 1;
  else
    disableUntil = 2;

  if (data.playing)
    data.seek += now() - data.timestamp;

  ytplayer.seekTo(data.seek);

  if (data.playing)
    ytplayer.playVideo();
  else
    ytplayer.pauseVideo();
}

function handleMp4Inc(data) {
  console.log("HANDLE");
  disableUntil = data.playing;
  if (data.playing)
    data.seek += now() - data.timestamp;

  //mp4player.seek(data.seek);

  mp4player.play(data.playing);

  setTimeout(hack, 100);

  function hack (){
    console.log("hacking");
    if (disableUntil == data.playing){
      mp4player.play(data.playing);
      setTimeout(hack, 100);
    }
  }

  console.log('done handle');
}

function ytListener (value){
  if (disableUntil > -1){
    console.log("ignoring- " + value);
    if (disableUntil == value)
      disableUntil = -1;
    return;
  }
  switch (value) {
    case -1:
      console.log("unstarted");
      disableUntil = 2;
      ytplayer.seekTo(0);
      ytplayer.pauseVideo();
      break;
    case 0:
      console.log("ended");
      break;
    case 1:
      console.log("playing");
      disableUntil = 1;
      ytplayer.pauseVideo();
      outgoing (true, ytplayer.getCurrentTime());
      break;
    case 2:
      console.log("paused");
      disableUntil = 2;
      ytplayer.playVideo();
      outgoing (false, ytplayer.getCurrentTime());
      break;
    case 3:
      console.log("buffering");
      break;
    case 5:
      console.log("cued");
      break;
  }
}

function mp4PlayPauseListener (play){
  if (disableUntil != null){
    console.log("ignoring " + play)
    if (disableUntil == play)
      disableUntil = null;
    return;
  }

  console.log(play);
  disableUntil = play;

  mp4player.pause(play);
  outgoing (play, mp4player.getPosition());
}

function now () {
  return new Date().getTime() / 1000;
}

$(document).ready (function() {
  $("#create").click(function() {
    makeRoom($("#room")[0].value)
  });
  $("#join").click(function() {
    joinRoom($("#room")[0].value)
  });
})
<|endoftext|>


<commit_before>const kCID  = Components.ID('{cd2892e0-87a8-11e2-9e96-0800200c9a66}');
const kID   = '@clear-code.com/force-addon-status/startup;1';
const kNAME = 'ForceAddonStatusStartupService';

const Cc = Components.classes;
const Ci = Components.interfaces;

const ObserverService = Cc['@mozilla.org/observer-service;1']
                         .getService(Ci.nsIObserverService);

Components.utils.import('resource://gre/modules/AddonManager.jsm');

Components.utils.import('resource://force-addon-status-modules/lib/prefs.js');
Components.utils.import('resource://force-addon-status-modules/lib/jsdeferred.js');

const BASE = 'extensions.force-addon-status@clear-code.com.';

function ForceAddonStatusStartupService() {
}
ForceAddonStatusStartupService.prototype = {
  classID          : kCID,
  contractID       : kID,
  classDescription : kNAME,

  observe : function(aSubject, aTopic, aData)
  {
    switch (aTopic)
    {
      case 'profile-after-change':
        ObserverService.addObserver(this, 'final-ui-startup', false);
        return;

      case 'final-ui-startup':
        ObserverService.removeObserver(this, 'final-ui-startup');
        this.checkStatus();
        return;
    }
  },

  checkStatus : function()
  {
    var self = this;
    var changedCount = { value : 0 };
    this.checkExtensionsStatus(changedCount)
      .next(function() {
        return self.checkPluginsStatus(changedCount);
      })
      .next(function() {
        if (changedCount.value > 0) {
          self.restart();
        }
      })
      .error(function(error) {
        Components.utils.reportError(error);
      });
  },

  checkExtensionsStatus : function(aChangedCount)
  {
    var deferredTasks = [];

    var prefix = BASE + 'addons.';
    var keys = prefs.getDescendant(prefix);
    aChangedCount.value = aChangedCount.value || 0;
    keys.forEach(function(aKey) {
      var id = aKey.replace(prefix, '');
      var shouldBeActive = prefs.getPref(aKey);
      var deferred = new Deferred();
      AddonManager.getAddonByID(id, function(aAddon) {
        if (!aAddon || aAddon.isActive == shouldBeActive)
          return deferred.call();

        aAddon.userDisabled = !shouldBeActive;
        aChangedCount.value++;
        deferred.call();
      });
      deferredTasks.push(deferred);
    });

    if (deferredTasks.length > 0)
      return Deferred.parallel(deferredTasks);
    else
      return Deferred;
  },

  checkPluginsStatus : function(aChangedCount)
  {
    aChangedCount.value = aChangedCount.value || 0;

    var controlledPlugins = prefs.getChildren(BASE + 'plugins.');
    var allPatterns = [];
    controlledPlugins = controlledPlugins.map(function(aEntryBaseKey) {
      var pattern = prefs.getPref(aEntryBaseKey + '.patten');
      allPatterns.push(pattern);
      return {
        pattern :        new RegExp(pattern),
        shouldBeActive : prefs.getPref(aEntryBaseKey + '.status')
      };
    });
    allPatterns = new RegExp('(' + allPatterns.join('|') + ')');

    var PluginHost = Cc['@mozilla.org/plugin/host;1']
                      .getService(Ci.nsIPluginHost);
    var plugins = PluginHost.getPluginTags();
    plugins.forEach(function(aPluginTag) {
      if (!allPatterns.test(aPluginTag.name))
        return;

      controlledPlugins.some(function(control) {
        if (!control.pattern.test(aPluginTag.name))
          return false;
        if (aPluginTag.disabled == !shouldBeActive)
          return false;

        aPluginTag.disabled = !shouldBeActive;
        aChangedCount.value++;
        return true;
      });
    });

    return Deferred;
  },

  restart : function()
  {
    Cc['@mozilla.org/toolkit/app-startup;1']
      .getService(Ci.nsIAppStartup)
      .quit(Ci.nsIAppStartup.eRestart | Ci.nsIAppStartup.eForceQuit);
  },

  QueryInterface : function(aIID)
  {
    if(!aIID.equals(Ci.nsIObserver) &&
       !aIID.equals(Ci.nsISupports)) {
      throw Components.results.NS_ERROR_NO_INTERFACE;
    }
    return this;
  }
};

Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
var NSGetFactory = XPCOMUtils.generateNSGetFactory([ForceAddonStatusStartupService]);
<commit_msg>Rename temporary argument variable for common manners in Mozilla JavaScript<commit_after>const kCID  = Components.ID('{cd2892e0-87a8-11e2-9e96-0800200c9a66}');
const kID   = '@clear-code.com/force-addon-status/startup;1';
const kNAME = 'ForceAddonStatusStartupService';

const Cc = Components.classes;
const Ci = Components.interfaces;

const ObserverService = Cc['@mozilla.org/observer-service;1']
                         .getService(Ci.nsIObserverService);

Components.utils.import('resource://gre/modules/AddonManager.jsm');

Components.utils.import('resource://force-addon-status-modules/lib/prefs.js');
Components.utils.import('resource://force-addon-status-modules/lib/jsdeferred.js');

const BASE = 'extensions.force-addon-status@clear-code.com.';

function ForceAddonStatusStartupService() {
}
ForceAddonStatusStartupService.prototype = {
  classID          : kCID,
  contractID       : kID,
  classDescription : kNAME,

  observe : function(aSubject, aTopic, aData)
  {
    switch (aTopic)
    {
      case 'profile-after-change':
        ObserverService.addObserver(this, 'final-ui-startup', false);
        return;

      case 'final-ui-startup':
        ObserverService.removeObserver(this, 'final-ui-startup');
        this.checkStatus();
        return;
    }
  },

  checkStatus : function()
  {
    var self = this;
    var changedCount = { value : 0 };
    this.checkExtensionsStatus(changedCount)
      .next(function() {
        return self.checkPluginsStatus(changedCount);
      })
      .next(function() {
        if (changedCount.value > 0) {
          self.restart();
        }
      })
      .error(function(error) {
        Components.utils.reportError(error);
      });
  },

  checkExtensionsStatus : function(aChangedCount)
  {
    var deferredTasks = [];

    var prefix = BASE + 'addons.';
    var keys = prefs.getDescendant(prefix);
    aChangedCount.value = aChangedCount.value || 0;
    keys.forEach(function(aKey) {
      var id = aKey.replace(prefix, '');
      var shouldBeActive = prefs.getPref(aKey);
      var deferred = new Deferred();
      AddonManager.getAddonByID(id, function(aAddon) {
        if (!aAddon || aAddon.isActive == shouldBeActive)
          return deferred.call();

        aAddon.userDisabled = !shouldBeActive;
        aChangedCount.value++;
        deferred.call();
      });
      deferredTasks.push(deferred);
    });

    if (deferredTasks.length > 0)
      return Deferred.parallel(deferredTasks);
    else
      return Deferred;
  },

  checkPluginsStatus : function(aChangedCount)
  {
    aChangedCount.value = aChangedCount.value || 0;

    var controlledPlugins = prefs.getChildren(BASE + 'plugins.');
    var allPatterns = [];
    controlledPlugins = controlledPlugins.map(function(aEntryBaseKey) {
      var pattern = prefs.getPref(aEntryBaseKey + '.patten');
      allPatterns.push(pattern);
      return {
        pattern :        new RegExp(pattern),
        shouldBeActive : prefs.getPref(aEntryBaseKey + '.status')
      };
    });
    allPatterns = new RegExp('(' + allPatterns.join('|') + ')');

    var PluginHost = Cc['@mozilla.org/plugin/host;1']
                      .getService(Ci.nsIPluginHost);
    var plugins = PluginHost.getPluginTags();
    plugins.forEach(function(aPluginTag) {
      if (!allPatterns.test(aPluginTag.name))
        return;

      controlledPlugins.some(function(aControl) {
        if (!aControl.pattern.test(aPluginTag.name))
          return false;
        if (aPluginTag.disabled == !shouldBeActive)
          return false;

        aPluginTag.disabled = !shouldBeActive;
        aChangedCount.value++;
        return true;
      });
    });

    return Deferred;
  },

  restart : function()
  {
    Cc['@mozilla.org/toolkit/app-startup;1']
      .getService(Ci.nsIAppStartup)
      .quit(Ci.nsIAppStartup.eRestart | Ci.nsIAppStartup.eForceQuit);
  },

  QueryInterface : function(aIID)
  {
    if(!aIID.equals(Ci.nsIObserver) &&
       !aIID.equals(Ci.nsISupports)) {
      throw Components.results.NS_ERROR_NO_INTERFACE;
    }
    return this;
  }
};

Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');
var NSGetFactory = XPCOMUtils.generateNSGetFactory([ForceAddonStatusStartupService]);
<|endoftext|>


<commit_before>$(document).ready( function () {
	// initializing side nav
	$(".button-collapse").sideNav();

	$(".scrollspy").scrollSpy({
		scrollOffset:60
	});

	$('.collapsible-header').click(function(){

		$(".rotating-span").removeClass('open');
		$(".rotating-span").removeClass('open');
		if (!($(this).hasClass("active")))
			$(".rotating-span", this).toggleClass('open');
		else
			$(".rotating-span", this).removeClass('open');

	});
	$('.modal').modal();

	// autocomplete for college names
	$('input.autocomplete').autocomplete({
		data: {
			"M.H. Saboo Siddik": null,
			"D.J Sanghvi": null,
			"Don Bosco Institute": null,
			"V.J.T.I": null,
		},
		minLength: 0,
	});

	// animations

	var side_gfx = document.querySelectorAll(".side-gfx");

	function isElementInViewport(el) {
		var rect = el.getBoundingClientRect();
		return (
			rect.top >= 0 &&
			rect.left >= 0 &&
			rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
			rect.right <= (window.innerWidth || document.documentElement.clientWidth)
		);
	}

	function handleScroll(){
		var badge = document.querySelector(".trophy-badge");
		if (isElementInViewport(badge)){
			badge.classList.add('badge-visible');
		}
		for (var i = 0; i < side_gfx.length; i++) {
			if (isElementInViewport(side_gfx[i])) {
				side_gfx[i].classList.add("side-gfx-visible");
			}
		}
	}

	// event listeners
	window.addEventListener("scroll", handleScroll);

})

function loadProgress() {

	document.getElementById('loader').style.display = "none";
	document.getElementById('main').style.display = "block";
}<commit_msg>side-nav close onClick<commit_after>$(document).ready( function () {
	// initializing side nav
	// $(".button-collapse").sideNav();
	$('.button-collapse').sideNav({
      menuWidth: 300,
      edge: 'left',
      closeOnClick: true,
      draggable: true
    });
    $(".drag-target").on("swipeleft", function () {
      $("#sidenav-overlay").trigger("click");
    });

	$(".scrollspy").scrollSpy({
		scrollOffset:60
	});

	$('.collapsible-header').click(function(){

		$(".rotating-span").removeClass('open');
		$(".rotating-span").removeClass('open');
		if (!($(this).hasClass("active")))
			$(".rotating-span", this).toggleClass('open');
		else
			$(".rotating-span", this).removeClass('open');

	});
	$('.modal').modal();

	// autocomplete for college names
	$('input.autocomplete').autocomplete({
		data: {
			"M.H. Saboo Siddik": null,
			"D.J Sanghvi": null,
			"Don Bosco Institute": null,
			"V.J.T.I": null,
		},
		minLength: 0,
	});

	// animations

	var side_gfx = document.querySelectorAll(".side-gfx");

	function isElementInViewport(el) {
		var rect = el.getBoundingClientRect();
		return (
			rect.top >= 0 &&
			rect.left >= 0 &&
			rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
			rect.right <= (window.innerWidth || document.documentElement.clientWidth)
		);
	}

	function handleScroll(){
		var badge = document.querySelector(".trophy-badge");
		if (isElementInViewport(badge)){
			badge.classList.add('badge-visible');
		}
		for (var i = 0; i < side_gfx.length; i++) {
			if (isElementInViewport(side_gfx[i])) {
				side_gfx[i].classList.add("side-gfx-visible");
			}
		}
	}

	// event listeners
	window.addEventListener("scroll", handleScroll);

})

function loadProgress() {

	document.getElementById('loader').style.display = "none";
	document.getElementById('main').style.display = "block";
}<|endoftext|>


<commit_before>L.Control.TimeRangeSlider = L.Control.extend({
    options: {
        collapsed: true,
        position: 'topleft',
        autoZIndex: true,
        hideSingleBase: false
    },

    initialize: function (options) {
        L.setOptions(this, options);
        var date = new Date();
        this.sliderOptions = {
            range: {
                min: date.getTime() - 50000000,
                max: date.getTime() + 50000000
            },
            start: [0],
            connect: [true, false]
        };
        this.lastUpdate = null;
        this.lastValue = null;
        this.updateDelta = 100;
        this.valueDelta = 10; //percentage
        this.liveTime = 0;
        this.live = true;
    },

    onAdd: function (map) {
        this.initLayout();
        return this._container;
    },

    onRemove: function (map) {

    },

    initLayout: function () {
        var className = 'leaflet-control-timeRangeSlider',
            container = this._container = L.DomUtil.create('div', className);

        container.addEventListener('contextmenu', this.containerRightClick);

        this._sliderDiv = L.DomUtil.create('div', className + '-sliderDiv');
        this._slider = noUiSlider.create(this._sliderDiv, this.sliderOptions);
        this._slider.on('start', this.sliderStart.bind(this));
        this._slider.on('slide', this.sliderMove.bind(this));
        this._slider.on('set', this.sliderSet.bind(this));
        this._container.appendChild(this._sliderDiv);

        this.timeTextDiv = L.DomUtil.create('div', className + '-sliderTextDiv');
        this.timeTextDiv.innerText = 'No Time Selected';
        this._container.appendChild(this.timeTextDiv);
    },

    containerRightClick: function (e) {
        e.preventDefault(); //prevent showing of contextmenu since we use right-mouse for something else
        e.stopPropagation();
        DataManager.rangeTimeSlider.goLive();
    },

    goLive: function () {
        this.live = true;
        this._slider.set(this.liveTime);
        wsSend({
            type: "rangetimeslider",
            payload: { live: true }
        });
    },

    sliderStart: function () {
        this.lastValue = this._slider.get();
        this.lastUpdate = null;
        this.live = false;
    },

    sliderMove: function () {
        var newValue = this._slider.get();
        var newTime = new Date();
        //Math.abs(newValue - this.lastValue) / (this._slider.options.range.max - this._slider.options.range.min) > this.valueDelta ||
        if (this.lastUpdate == null || newTime - this.lastUpdate > this.updateDelta) {
            this.lastValue = newValue;
            this.lastUpdate = newTime;
            this.sliderSet();
        }

        this.updateTimeDisplay();
    },

    sliderSet: function () {
        if (!this.live) //check to see if we need to send an update
        {
            wsSend({
                type: "timerangeslider",
                payload: {
                    time: this.doubleToDate(this._slider.get())
                }
            })
        }
        this.updateTimeDisplay();
    },

    updateTimeDisplay: function () {
        this.timeTextDiv.innerText = (new Date(Math.round(this._slider.get()))).toLocaleString();
    },

    doubleToDate: function (aDouble) {
        var date = new Date(Math.round(aDouble));
        var dateString = date.toISOString();
        var dateSplit = dateString.split('T');
        dateString = dateSplit[0] + ' ' + dateSplit[1];
        return dateString.substring(0, dateString.length - 5); //trim miliseconds and Z

    },

    dateToDouble: function (aDate) {
        var dateString = aDate.replace(' ', 'T');
        dateString += 'Z';
        return (new Date(dateString)).getTime();
    },

    update: function (payload) {
        if (payload.range) {
            this.sliderOptions.range = {
                min: this.dateToDouble(payload.range.min),
                max: this.dateToDouble(payload.range.max)
            }
            this._slider.updateOptions({ range: this.sliderOptions.range });
        }

        if (payload.time)
        {
            this.liveTime = this.dateToDouble(payload.time);
            if (this.live && this._slider) {
                this._slider.set(this.liveTime);
                this.updateTimeDisplay();
            }
        }

        if (payload.live)
            this.goLive();
    }
});<commit_msg>fixed typo<commit_after>L.Control.TimeRangeSlider = L.Control.extend({
    options: {
        collapsed: true,
        position: 'topleft',
        autoZIndex: true,
        hideSingleBase: false
    },

    initialize: function (options) {
        L.setOptions(this, options);
        var date = new Date();
        this.sliderOptions = {
            range: {
                min: date.getTime() - 50000000,
                max: date.getTime() + 50000000
            },
            start: [0],
            connect: [true, false]
        };
        this.lastUpdate = null;
        this.lastValue = null;
        this.updateDelta = 100;
        this.valueDelta = 10; //percentage
        this.liveTime = 0;
        this.live = true;
    },

    onAdd: function (map) {
        this.initLayout();
        return this._container;
    },

    onRemove: function (map) {

    },

    initLayout: function () {
        var className = 'leaflet-control-timeRangeSlider',
            container = this._container = L.DomUtil.create('div', className);

        container.addEventListener('contextmenu', this.containerRightClick);

        this._sliderDiv = L.DomUtil.create('div', className + '-sliderDiv');
        this._slider = noUiSlider.create(this._sliderDiv, this.sliderOptions);
        this._slider.on('start', this.sliderStart.bind(this));
        this._slider.on('slide', this.sliderMove.bind(this));
        this._slider.on('set', this.sliderSet.bind(this));
        this._container.appendChild(this._sliderDiv);

        this.timeTextDiv = L.DomUtil.create('div', className + '-sliderTextDiv');
        this.timeTextDiv.innerText = 'No Time Selected';
        this._container.appendChild(this.timeTextDiv);
    },

    containerRightClick: function (e) {
        e.preventDefault(); //prevent showing of contextmenu since we use right-mouse for something else
        e.stopPropagation();
        DataManager.timeRangeSlider.goLive();
    },

    goLive: function () {
        this.live = true;
        this._slider.set(this.liveTime);
        wsSend({
            type: "rangetimeslider",
            payload: { live: true }
        });
    },

    sliderStart: function () {
        this.lastValue = this._slider.get();
        this.lastUpdate = null;
        this.live = false;
    },

    sliderMove: function () {
        var newValue = this._slider.get();
        var newTime = new Date();
        //Math.abs(newValue - this.lastValue) / (this._slider.options.range.max - this._slider.options.range.min) > this.valueDelta ||
        if (this.lastUpdate == null || newTime - this.lastUpdate > this.updateDelta) {
            this.lastValue = newValue;
            this.lastUpdate = newTime;
            this.sliderSet();
        }

        this.updateTimeDisplay();
    },

    sliderSet: function () {
        if (!this.live) //check to see if we need to send an update
        {
            wsSend({
                type: "timerangeslider",
                payload: {
                    time: this.doubleToDate(this._slider.get())
                }
            })
        }
        this.updateTimeDisplay();
    },

    updateTimeDisplay: function () {
        this.timeTextDiv.innerText = (new Date(Math.round(this._slider.get()))).toLocaleString();
    },

    doubleToDate: function (aDouble) {
        var date = new Date(Math.round(aDouble));
        var dateString = date.toISOString();
        var dateSplit = dateString.split('T');
        dateString = dateSplit[0] + ' ' + dateSplit[1];
        return dateString.substring(0, dateString.length - 5); //trim miliseconds and Z

    },

    dateToDouble: function (aDate) {
        var dateString = aDate.replace(' ', 'T');
        dateString += 'Z';
        return (new Date(dateString)).getTime();
    },

    update: function (payload) {
        if (payload.range) {
            this.sliderOptions.range = {
                min: this.dateToDouble(payload.range.min),
                max: this.dateToDouble(payload.range.max)
            }
            this._slider.updateOptions({ range: this.sliderOptions.range });
        }

        if (payload.time)
        {
            this.liveTime = this.dateToDouble(payload.time);
            if (this.live && this._slider) {
                this._slider.set(this.liveTime);
                this.updateTimeDisplay();
            }
        }

        if (payload.live)
            this.goLive();
    }
});<|endoftext|>


<commit_before>/**
 * Created by Vadym Yatsyuk on 29/08/16
 */
import React from 'react';

class BarComponent extends React.Component {
  render() {
    return (

{ this.props.name }

{ this.props.value }

          <div className="bar" style={{ transition: '0.5s width easi-in', width: `${ this.props.percentage }%`}}>

    )
  }
}

export default BarComponent;
<commit_msg>Fixed typo<commit_after>/**
 * Created by Vadym Yatsyuk on 29/08/16
 */
import React from 'react';

class BarComponent extends React.Component {
  render() {
    return (

{ this.props.name }

{ this.props.value }

          <div className="bar" style={{ transition: '0.5s width ease-in', width: `${ this.props.percentage }%`}}>

    )
  }
}

export default BarComponent;
<|endoftext|>