<commit_before>
// Polyfills
// Selectors API Level 1 (http://www.w3.org/TR/selectors-api/)
// http://ajaxian.com/archives/creating-a-queryselector-for-ie-that-runs-at-native-speed
//
if (!document.querySelectorAll) {
    document.querySelectorAll = function(selectors) {
        var style = document.createElement('style'),
            elements = [],
            element;
        document.documentElement.firstChild.appendChild(style);
        document._qsa = [];

        style.styleSheet.cssText = selectors + '{x-qsa:expression(document._qsa && document._qsa.push(this))}';
        window.scrollBy(0, 0);
        style.parentNode.removeChild(style);

        while (document._qsa.length) {
            element = document._qsa.shift();
            element.style.removeAttribute('x-qsa');
            elements.push(element);
        }
        document._qsa = null;
        return elements;
    };
}

if (!document.querySelector) {
    document.querySelector = function(selectors) {
        var elements = document.querySelectorAll(selectors);
        return (elements.length) ? elements[0] : null;
    };
}

if(!Array.isArray) {
    Array.isArray = function(arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
    };
}

/* deez.js 1.0.0
 * (c) 2014 David Zuch | MIT
 * a minimal library targeted for lightweight, responsive applications
 *
 * global console */

window.deez = (function() {
    // setup shortcuts
    var win = window,
        doc = win.document,
        ua = navigator.userAgent,
        slice = Array.prototype.slice,

        metaview = doc.querySelector('meta[name="viewport"]'),
        scrollEl = ua.match(/webkit/i) ? doc.body : doc.documentElement,
        bodyScrollTop = false,

        // reuasble constructor function for prototype setting
        ctor = function(){},

        // constructor
        deez = function(selector, context) {
            return new deez.fn.init(selector, context);
        };

    // most of the prototype methods make use of deez functions further down
    deez.fn = deez.prototype = {
        constructor: deez,

        // default length for a deez object
        length: 0,

        // event handler
        on: function(evs, fn, scope) {
            deez.on(this, evs, fn, scope);

            return this;
        },

        // iterate through elements belonging to deez instance
        each: function(fn) {
            return deez.each(this, fn);
        },

        hasClass: function(classNames) {
            return deez.hasClass(this, classNames);
        },

        removeClass: function(classNames) {
            return deez.removeClass(this, classNames);
        },

        addClass: function(classNames) {
            return deez.addClass(this, classNames);
        },

        toggleClass: function(classNames) {
            return deez.toggleClass(this, classNames);
        },

        extend: function(o) {
            deez.extend(this, o);

            return this;
        },

        // retrieve any property set directly to the deez object
        // main purpose is to retrieve elements by index
        get: function(key) {
            return this[key];
        },

        // read element properties such as offsetHeight or scrollTop
        prop: function(prop) {
            return this[0] && this[0][prop];
        },

        // get or set element attributes
        // pass in an object to set multiple attributes at once
        // pass in an empty string as a value to remove the attribute
        // example get: $el.attr('name');
        // example set: $el.attr('name', 'foo');
        // example set: $el.attr({'name': 'foo', 'data-name': 'bar'});
        // example unset: $el.attr('name', '');
        attr: function(attr, set) {
            if ('object' === typeof attr) {
                for (var key in attr) {
                    this.attr(key, attr[key]);
                }
                return this;
            }
            if (undefined !== set) {
                if (set) {
                    this[0] && this[0].setAttribute(attr, set);
                } else {
                    this[0] && this[0].removeAttribute(attr);
                }
                return this;
            }
            return this[0] && this[0].getAttribute(attr);
        },

        // scroll to first element
        scrollPage: function(offset, time) {
            deez.scrollPage(this, offset, time);

            return this;
        },

        // set innerHTML for multiple elements or
        // get innerHTML for first element
        html: function(html) {
            if (undefined !== html) {
                this.each(function() {
                    this.innerHTML = html;
                });
                return this;
            }
            return this[0] && this[0].innerHTML;
        },

        // set inline style for multiple elements or
        // get existing styles for first element, inline or not
        style: function(prop, val) {
            if ('object' === typeof prop) {
                for (var key in prop) {
                    this.style(key, prop[key]);
                }
                return this;
            }
            if (undefined !== val) {
                this.each(function() {
                    this.style[prop] = val;
                });
                return this;
            }
            return deez.getStyle(this, prop);
        }
    };

    // constructor, matches selector and returns deez object with matched elements
    var init = deez.fn.init = function(selector, context) {
            if (!selector) { return this; }
            if (selector instanceof deez) { return selector; }
            if (context && context instanceof deez) { context = context[0]; }

            var match;
            // if array of selectors, join into one
            if (Array.isArray(selector) && selector[0] && 'string' === typeof selector[0]) {
                selector = selector.join(', ');
            }
            if ('string' === typeof selector) {
                // Experimental: if ID, match ID (faster), else match query
                if (/^#[^\s><+~*\[\]]+$/.test(selector)) {
                    match = [deez.matchId(selector.substr(1), context)];
                // Experimental: if tag, match tag (faster), else match query
                } else if (/^\w+[A-Za-z0-9]?$/.test(selector)) {
                    match = deez.matchTags(selector, context);
                } else {
                    match = slice.call((context || doc).querySelectorAll(selector), 0);
                }
            } else if (selector.tagName || selector === win || selector === doc) {
                match = [selector];
            }

            this.length = match && match.length;
            this.extend(Object(match));

            return this;
        },

        // deez properties and functions
        fns = {
            UA: ua,

            scrollEl: scrollEl,

            // event handling
            on: function(selector, evs, fn, scope) {
                var self = this,
                    $el = selector instanceof deez ? selector : deez(selector);
                evs = evs.split(' ');

                $el.each(function() {
                    for (var i = 0, l = evs.length; i < l; i++) {
                        self._addEvent(this, evs[i], fn, scope);
                    }
                });
            },

            _addEvent: function(el, ev, fn, scope) {
                scope = scope || ev;
                if (el.addEventListener) {
                    el.addEventListener(ev, function(e) {
                        fn.call(scope, e);
                    }, false);
                } else if (el.attachEvent) { // IE
                    el.attachEvent('on' + ev, function() {
                        fn.call(scope, window.event);
                    });
                }
            },

            // iterate through array
            each: function(arr, fn) {
                for (var i = 0, l = arr.length; i < l; i++) {
                    if (false === fn.call(arr[i], i)) { break; }
                }
                return arr;
            },

            // dom selectors
            matchId: function(id, context) {
                if (context && context instanceof deez) { context = context[0]; }
                return (context || doc).getElementById(id);
            },

            matchTags: function(tag, context) {
                if (context && context instanceof deez) { context = context[0]; }
                return slice.call((context || doc).getElementsByTagName(tag), 0);
            },

            matchTag: function(tag, context) {
                if (context && context instanceof deez) { context = context[0]; }
                return this.matchTags(tag, context)[0];
            },

            // dom class functions
            hasClass: function(selector, classNames) {
                var $el = selector instanceof deez ? selector : deez(selector),
                    match = false;
                classNames = classNames.split(' ');

                $el.each(function() {
                    for (var i = 0, l = classNames.length; i < l; i++) {
                        if ((' '+this.className+' ').indexOf(' '+classNames[i]+' ') !== -1) {
                            match = true;
                            break;
                        }
                    }

                    if (match) { return false; }
                });

                return match;
            },

            removeClass: function(selector, classNames) {
                var $el = selector instanceof deez ? selector : deez(selector);
                classNames = classNames.split(' ');

                $el.each(function() {
                    if ('className' in this && this.className) {
                        for (var i = 0, l = classNames.length; i < l; i++) {
                            this.className = (' '+this.className+' ').replace(' '+classNames[i]+' ', ' ').trim();
                        }
                    }
                });

                return $el;
            },

            addClass: function(selector, classNames) {
                var self = this,
                    $el = selector instanceof deez ? selector : deez(selector);
                classNames = classNames.split(' ');

                $el.each(function() {
                    for (var i = 0, l = classNames.length; i < l; i++) {
                        if (!self.hasClass(this, classNames[i])) {
                            this.className = this.className.trim() + ' ' + classNames[i];
                        }
                    }
                });

                return $el;
            },

            toggleClass: function(selector, classNames) {
                var self = this,
                    $el = selector instanceof deez ? selector : deez(selector);
                classNames = classNames.split(' ');

                $el.each(function() {
                    for (var i = 0, l = classNames.length; i < l; i++) {
                        var className = classNames[i];
                        if (self.hasClass(this, className)) {
                            self.removeClass(this, className);
                        } else {
                            self.addClass(this, className);
                        }
                    }
                });

                return $el;
            },

            // get computed or inline styles for an element
            getStyle: function(selector, prop) {
                var el = (selector instanceof deez ? selector : deez(selector))[0];

                if (win.getComputedStyle) { // standard
                    return win.getComputedStyle(el)[prop];
                } else if (el.currentStyle) { // IE
                    return el.currentStyle[prop];
                } else { // may as well try
                    return el.style[prop];
                }
            },

            extend: function(source, add) {
                if (!source || !add) { return; }
                for (var key in add) {
                    source[key] = add[key];
                }
            },

            // ripped straight out of underscore.js
            bind: function(fn, context) {
                var nativeBind = Function.prototype.bind,
                    args, bound;

                if (nativeBind && fn.bind === nativeBind) {
                    return nativeBind.apply(fn, slice.call(arguments, 1));
                }

                if ('function' !== typeof fn) { throw new TypeError(); }

                args = slice.call(arguments, 2);

                return bound = function() {
                    if (!(this instanceof bound)) {
                        return fn.apply(context, args.concat(slice.call(arguments)));
                    }
                    ctor.prototype = fn.prototype;
                    var self = new ctor();
                    ctor.prototype = null;
                    var result = fn.apply(self, args.concat(slice.call(arguments)));
                    if (Object(result) === result) { return result; }
                    return self;
                };
            },

            bindAll: function(o) {
                var self = this,
                    fns = slice.call(arguments, 1);
                if (!fns.length) {
                    throw new Error('bindAll must be passed funciton names');
                }
                this.each(fns, function() {
                    o[this] = self.bind(o[this], o);
                });
                return o;
            },

            // create a new inline stylesheet
            newStyle: function(css) {
                if (!css || 'string' !== typeof css) { return false; }
                var self = this,
                    head = deez('head')[0],
                    style = doc.createElement('style');

                style.type = 'text/css';
                style.media = 'screen';
                if (style.styleSheet) {
                    style.styleSheet.cssText = css;
                } else {
                    style.appendChild(document.createTextNode(css));
                }

                head.appendChild(style);

                style.update = function(css) {
                    self.updateStyle(this, css);
                };

                return style;
            },

            updateStyle: function(style, css) {
                if (!style || 'style' !== style.tagName.toLowerCase()) {
                    return this.newStyle(css);
                }
                if (style.styleSheet) {
                    style.styleSheet.cssText += css;
                } else {
                    style.appendChild(document.createTextNode(css));
                }
                return style;
            },

            replaceStyle: function(style, css) {
                if (!style || 'style' !== style.tagName.toLowerCase()) {
                    style.parentNode.removeChild(style);
                }
                return this.newStyle(css);
            },

            // scroll the page to position of targeet
            // target can be an integer or element
            scrollPage: function(target, offset, time) {
                if (!target) { return; }
                if (!offset && isNaN(offset) && this.scrollOffset) {
                    offset = this.scrollOffset;
                }

                offset = offset && isNaN(offset) ? deez(offset).prop('offsetHeight') : offset || 0;
                target = isNaN(target) ? deez(target).prop('offsetTop') + offset : target;
                time = time || 500;

                var from = scrollEl.scrollTop,
                    start = new Date().getTime(),
                    timer = setInterval(function() {
                        var step = Math.min(1, (new Date().getTime()-start) / time);
                        scrollEl.scrollTop = (from + step * (target - from));
                        if (1 === step) { clearInterval(timer); }
                    }, 25);
            },

            setScrollOffset: function(offset) {
                this.scrollOffset = offset;
            },

            // mobile fixes
            scaleFix: function() {
                if (metaview && /iPhone|iPad|iPod/.test(ua) && !/Opera Mini/.test(ua)) {
                    metaview.content = 'width=device-width, minimum-scale=1.0, maximum-scale=1.0';
                    doc.addEventListener('gesturestart', this.gestureStart, false);
                }
            },

            gestureStart: function() {
                metaview.content = 'width=device-width, minimum-scale=0.25, maximum-scale=1.6';
            },

            hideUrlBarOnLoad: function() {
                var self = this,
                    bodycheck;

                // If there's a hash, or addEventListener is undefined, stop here
                if (!location.hash && win.addEventListener) {

                    // scroll to 1
                    win.scrollTo(0, 1);
                    bodyScrollTop = 1;

                    // reset to 0 on bodyready, if needed
                    bodycheck = setInterval(function() {
                        if (doc.body) {
                            clearInterval(bodycheck);
                            bodyScrollTop = self.getScrollTop();
                            self.hideUrlBar();
                        }
                    }, 15);

                    self.on(win, 'load', function() {
                        setTimeout(function() {
                            if (self.getScrollTop() < 20) {
                                self.hideUrlBar();
                            }
                        }, 0);
                    });
                }
            },

            hideUrlBar: function() {
                if (!location.hash && bodyScrollTop !== false) {
                    win.scrollTo(0, bodyScrollTop === 1 ? 0 : 1);
                }
            },

            getScrollTop: function() {
                return win.pageYOffset || doc.compatMode === 'CSS1Compat' && doc.documentElement.scrollTop || doc.body.scrollTop || 0;
            },

            enableActive: function() {
                doc.addEventListener('touchstart', ctor, false);
            },

            // serialize form data
            serialize: function(data) {
                var arr = [];
                for (var key in data) {
                    arr.push(key + '=' + data[key]);
                }
                return arr.join('&');
            },

            initMobileFixes: function() {
                this.scaleFix();
                this.hideUrlBarOnLoad();
                this.enableActive();
            }
        };

    init.prototype = deez.fn;

    fns.extend(deez, fns);

    return deez;
})();<commit_msg>fixing scrollpage<commit_after>
// Polyfills
// Selectors API Level 1 (http://www.w3.org/TR/selectors-api/)
// http://ajaxian.com/archives/creating-a-queryselector-for-ie-that-runs-at-native-speed
//
if (!document.querySelectorAll) {
    document.querySelectorAll = function(selectors) {
        var style = document.createElement('style'),
            elements = [],
            element;
        document.documentElement.firstChild.appendChild(style);
        document._qsa = [];

        style.styleSheet.cssText = selectors + '{x-qsa:expression(document._qsa && document._qsa.push(this))}';
        window.scrollBy(0, 0);
        style.parentNode.removeChild(style);

        while (document._qsa.length) {
            element = document._qsa.shift();
            element.style.removeAttribute('x-qsa');
            elements.push(element);
        }
        document._qsa = null;
        return elements;
    };
}

if (!document.querySelector) {
    document.querySelector = function(selectors) {
        var elements = document.querySelectorAll(selectors);
        return (elements.length) ? elements[0] : null;
    };
}

if(!Array.isArray) {
    Array.isArray = function(arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
    };
}

/* deez.js 1.0.0
 * (c) 2014 David Zuch | MIT
 * a minimal library targeted for lightweight, responsive applications
 *
 * global console */

window.deez = (function() {
    // setup shortcuts
    var win = window,
        doc = win.document,
        ua = navigator.userAgent,
        slice = Array.prototype.slice,

        metaview = doc.querySelector('meta[name="viewport"]'),
        scrollEl = ua.match(/webkit/i) ? doc.body : doc.documentElement,
        bodyScrollTop = false,

        // reuasble constructor function for prototype setting
        ctor = function(){},

        // constructor
        deez = function(selector, context) {
            return new deez.fn.init(selector, context);
        };

    // most of the prototype methods make use of deez functions further down
    deez.fn = deez.prototype = {
        constructor: deez,

        // default length for a deez object
        length: 0,

        // event handler
        on: function(evs, fn, scope) {
            deez.on(this, evs, fn, scope);

            return this;
        },

        // iterate through elements belonging to deez instance
        each: function(fn) {
            return deez.each(this, fn);
        },

        hasClass: function(classNames) {
            return deez.hasClass(this, classNames);
        },

        removeClass: function(classNames) {
            return deez.removeClass(this, classNames);
        },

        addClass: function(classNames) {
            return deez.addClass(this, classNames);
        },

        toggleClass: function(classNames) {
            return deez.toggleClass(this, classNames);
        },

        extend: function(o) {
            deez.extend(this, o);

            return this;
        },

        // retrieve any property set directly to the deez object
        // main purpose is to retrieve elements by index
        get: function(key) {
            return this[key];
        },

        // read element properties such as offsetHeight or scrollTop
        prop: function(prop) {
            return this[0] && this[0][prop];
        },

        // get or set element attributes
        // pass in an object to set multiple attributes at once
        // pass in an empty string as a value to remove the attribute
        // example get: $el.attr('name');
        // example set: $el.attr('name', 'foo');
        // example set: $el.attr({'name': 'foo', 'data-name': 'bar'});
        // example unset: $el.attr('name', '');
        attr: function(attr, set) {
            if ('object' === typeof attr) {
                for (var key in attr) {
                    this.attr(key, attr[key]);
                }
                return this;
            }
            if (undefined !== set) {
                if (set) {
                    this[0] && this[0].setAttribute(attr, set);
                } else {
                    this[0] && this[0].removeAttribute(attr);
                }
                return this;
            }
            return this[0] && this[0].getAttribute(attr);
        },

        // scroll to first element
        scrollPage: function(offset, time) {
            deez.scrollPage(this, offset, time);

            return this;
        },

        // set innerHTML for multiple elements or
        // get innerHTML for first element
        html: function(html) {
            if (undefined !== html) {
                this.each(function() {
                    this.innerHTML = html;
                });
                return this;
            }
            return this[0] && this[0].innerHTML;
        },

        // set inline style for multiple elements or
        // get existing styles for first element, inline or not
        style: function(prop, val) {
            if ('object' === typeof prop) {
                for (var key in prop) {
                    this.style(key, prop[key]);
                }
                return this;
            }
            if (undefined !== val) {
                this.each(function() {
                    this.style[prop] = val;
                });
                return this;
            }
            return deez.getStyle(this, prop);
        }
    };

    // constructor, matches selector and returns deez object with matched elements
    var init = deez.fn.init = function(selector, context) {
            if (!selector) { return this; }
            if (selector instanceof deez) { return selector; }
            if (context && context instanceof deez) { context = context[0]; }

            var match;
            // if array of selectors, join into one
            if (Array.isArray(selector) && selector[0] && 'string' === typeof selector[0]) {
                selector = selector.join(', ');
            }
            if ('string' === typeof selector) {
                // Experimental: if ID, match ID (faster), else match query
                if (/^#[^\s><+~*\[\]]+$/.test(selector)) {
                    match = [deez.matchId(selector.substr(1), context)];
                // Experimental: if tag, match tag (faster), else match query
                } else if (/^\w+[A-Za-z0-9]?$/.test(selector)) {
                    match = deez.matchTags(selector, context);
                } else {
                    match = slice.call((context || doc).querySelectorAll(selector), 0);
                }
            } else if (selector.tagName || selector === win || selector === doc) {
                match = [selector];
            }

            this.length = match && match.length;
            this.extend(Object(match));

            return this;
        },

        // deez properties and functions
        fns = {
            UA: ua,

            scrollEl: scrollEl,

            // event handling
            on: function(selector, evs, fn, scope) {
                var self = this,
                    $el = selector instanceof deez ? selector : deez(selector);
                evs = evs.split(' ');

                $el.each(function() {
                    for (var i = 0, l = evs.length; i < l; i++) {
                        self._addEvent(this, evs[i], fn, scope);
                    }
                });
            },

            _addEvent: function(el, ev, fn, scope) {
                scope = scope || ev;
                if (el.addEventListener) {
                    el.addEventListener(ev, function(e) {
                        fn.call(scope, e);
                    }, false);
                } else if (el.attachEvent) { // IE
                    el.attachEvent('on' + ev, function() {
                        fn.call(scope, window.event);
                    });
                }
            },

            // iterate through array
            each: function(arr, fn) {
                for (var i = 0, l = arr.length; i < l; i++) {
                    if (false === fn.call(arr[i], i)) { break; }
                }
                return arr;
            },

            // dom selectors
            matchId: function(id, context) {
                if (context && context instanceof deez) { context = context[0]; }
                return (context || doc).getElementById(id);
            },

            matchTags: function(tag, context) {
                if (context && context instanceof deez) { context = context[0]; }
                return slice.call((context || doc).getElementsByTagName(tag), 0);
            },

            matchTag: function(tag, context) {
                if (context && context instanceof deez) { context = context[0]; }
                return this.matchTags(tag, context)[0];
            },

            // dom class functions
            hasClass: function(selector, classNames) {
                var $el = selector instanceof deez ? selector : deez(selector),
                    match = false;
                classNames = classNames.split(' ');

                $el.each(function() {
                    for (var i = 0, l = classNames.length; i < l; i++) {
                        if ((' '+this.className+' ').indexOf(' '+classNames[i]+' ') !== -1) {
                            match = true;
                            break;
                        }
                    }

                    if (match) { return false; }
                });

                return match;
            },

            removeClass: function(selector, classNames) {
                var $el = selector instanceof deez ? selector : deez(selector);
                classNames = classNames.split(' ');

                $el.each(function() {
                    if ('className' in this && this.className) {
                        for (var i = 0, l = classNames.length; i < l; i++) {
                            this.className = (' '+this.className+' ').replace(' '+classNames[i]+' ', ' ').trim();
                        }
                    }
                });

                return $el;
            },

            addClass: function(selector, classNames) {
                var self = this,
                    $el = selector instanceof deez ? selector : deez(selector);
                classNames = classNames.split(' ');

                $el.each(function() {
                    for (var i = 0, l = classNames.length; i < l; i++) {
                        if (!self.hasClass(this, classNames[i])) {
                            this.className = this.className.trim() + ' ' + classNames[i];
                        }
                    }
                });

                return $el;
            },

            toggleClass: function(selector, classNames) {
                var self = this,
                    $el = selector instanceof deez ? selector : deez(selector);
                classNames = classNames.split(' ');

                $el.each(function() {
                    for (var i = 0, l = classNames.length; i < l; i++) {
                        var className = classNames[i];
                        if (self.hasClass(this, className)) {
                            self.removeClass(this, className);
                        } else {
                            self.addClass(this, className);
                        }
                    }
                });

                return $el;
            },

            // get computed or inline styles for an element
            getStyle: function(selector, prop) {
                var el = (selector instanceof deez ? selector : deez(selector))[0];

                if (win.getComputedStyle) { // standard
                    return win.getComputedStyle(el)[prop];
                } else if (el.currentStyle) { // IE
                    return el.currentStyle[prop];
                } else { // may as well try
                    return el.style[prop];
                }
            },

            extend: function(source, add) {
                if (!source || !add) { return; }
                for (var key in add) {
                    source[key] = add[key];
                }
            },

            // ripped straight out of underscore.js
            bind: function(fn, context) {
                var nativeBind = Function.prototype.bind,
                    args, bound;

                if (nativeBind && fn.bind === nativeBind) {
                    return nativeBind.apply(fn, slice.call(arguments, 1));
                }

                if ('function' !== typeof fn) { throw new TypeError(); }

                args = slice.call(arguments, 2);

                return bound = function() {
                    if (!(this instanceof bound)) {
                        return fn.apply(context, args.concat(slice.call(arguments)));
                    }
                    ctor.prototype = fn.prototype;
                    var self = new ctor();
                    ctor.prototype = null;
                    var result = fn.apply(self, args.concat(slice.call(arguments)));
                    if (Object(result) === result) { return result; }
                    return self;
                };
            },

            bindAll: function(o) {
                var self = this,
                    fns = slice.call(arguments, 1);
                if (!fns.length) {
                    throw new Error('bindAll must be passed funciton names');
                }
                this.each(fns, function() {
                    o[this] = self.bind(o[this], o);
                });
                return o;
            },

            // create a new inline stylesheet
            newStyle: function(css) {
                if (!css || 'string' !== typeof css) { return false; }
                var self = this,
                    head = deez('head')[0],
                    style = doc.createElement('style');

                style.type = 'text/css';
                style.media = 'screen';
                if (style.styleSheet) {
                    style.styleSheet.cssText = css;
                } else {
                    style.appendChild(document.createTextNode(css));
                }

                head.appendChild(style);

                style.update = function(css) {
                    self.updateStyle(this, css);
                };

                return style;
            },

            updateStyle: function(style, css) {
                if (!style || 'style' !== style.tagName.toLowerCase()) {
                    return this.newStyle(css);
                }
                if (style.styleSheet) {
                    style.styleSheet.cssText += css;
                } else {
                    style.appendChild(document.createTextNode(css));
                }
                return style;
            },

            replaceStyle: function(style, css) {
                if (!style || 'style' !== style.tagName.toLowerCase()) {
                    style.parentNode.removeChild(style);
                }
                return this.newStyle(css);
            },

            // scroll the page to position of targeet
            // target can be an integer or element
            scrollPage: function(target, offset, time) {
                if (!target) { return; }
                if (!offset && isNaN(offset) && this.scrollOffset) {
                    offset = this.scrollOffset;
                    if ('function' === typeof offset) { offset = offset(); }
                }

                offset = offset && isNaN(offset) ? deez(offset).prop('offsetHeight') : offset || 0;
                target = isNaN(target) ? deez(target).prop('offsetTop') + offset : target;
                time = time || 500;

                var from = scrollEl.scrollTop,
                    start = new Date().getTime(),
                    timer = setInterval(function() {
                        var step = Math.min(1, (new Date().getTime()-start) / time);
                        scrollEl.scrollTop = (from + step * (target - from));
                        if (1 === step) { clearInterval(timer); }
                    }, 25);
            },

            setScrollOffset: function(offset) {
                this.scrollOffset = offset;
            },

            // mobile fixes
            scaleFix: function() {
                if (metaview && /iPhone|iPad|iPod/.test(ua) && !/Opera Mini/.test(ua)) {
                    metaview.content = 'width=device-width, minimum-scale=1.0, maximum-scale=1.0';
                    doc.addEventListener('gesturestart', this.gestureStart, false);
                }
            },

            gestureStart: function() {
                metaview.content = 'width=device-width, minimum-scale=0.25, maximum-scale=1.6';
            },

            hideUrlBarOnLoad: function() {
                var self = this,
                    bodycheck;

                // If there's a hash, or addEventListener is undefined, stop here
                if (!location.hash && win.addEventListener) {

                    // scroll to 1
                    win.scrollTo(0, 1);
                    bodyScrollTop = 1;

                    // reset to 0 on bodyready, if needed
                    bodycheck = setInterval(function() {
                        if (doc.body) {
                            clearInterval(bodycheck);
                            bodyScrollTop = self.getScrollTop();
                            self.hideUrlBar();
                        }
                    }, 15);

                    self.on(win, 'load', function() {
                        setTimeout(function() {
                            if (self.getScrollTop() < 20) {
                                self.hideUrlBar();
                            }
                        }, 0);
                    });
                }
            },

            hideUrlBar: function() {
                if (!location.hash && bodyScrollTop !== false) {
                    win.scrollTo(0, bodyScrollTop === 1 ? 0 : 1);
                }
            },

            getScrollTop: function() {
                return win.pageYOffset || doc.compatMode === 'CSS1Compat' && doc.documentElement.scrollTop || doc.body.scrollTop || 0;
            },

            enableActive: function() {
                doc.addEventListener('touchstart', ctor, false);
            },

            // serialize form data
            serialize: function(data) {
                var arr = [];
                for (var key in data) {
                    arr.push(key + '=' + data[key]);
                }
                return arr.join('&');
            },

            initMobileFixes: function() {
                this.scaleFix();
                this.hideUrlBarOnLoad();
                this.enableActive();
            }
        };

    init.prototype = deez.fn;

    fns.extend(deez, fns);

    return deez;
})();<|endoftext|>


<commit_before>

var handleReuseResults = function(grid, rowIndex, colIndex) {
  var rec = workflowStore.getAt(rowIndex);

  Ext.getCmp('viewport').setLoading(true);
  // number of asynchronous calls remaining

  var numRemaining = 3;
  alert(rec.get('runId'))
  Ext.Ajax.request({
    url: "/j2ep-1.0/prov/workflowexecutions/" + encodeURIComponent(rec.get('runId')),
    params: {},
    method: 'GET',
    success: function(response) {
      var prov_object = JSON.parse(response.responseText);

      if (prov_object == null) {
        Ext.getCmp('viewport').setLoading(true);
        Ext.Msg.alert("Error", "Workflow missing from provenance repository. Please contact support and list the workflow name and username.");
        return;
      }

      prov_object.input.forEach(function(item) {
        prov_object[item.name] = item;
      });
      delete prov_object.input;

      Ext.Ajax.request({
        url: prov_object.solverconf.url.replace(/http:\/\/[^\/]*\//, '/'),
        success: function(response) {
          var object = JSON.parse(response.responseText);
          if (object === null) {
            Ext.Msg.alert("Failed to get workflow settings");
            Ext.getCmp('viewport').setLoading(false);
            return;
          }

          // reuse velocity when velocity model store finishes loading
          var velocityCombo = Ext.getCmp('velocity');
          velocityCombo.store.addListener('refresh', function() {
            velocityCombo.setValue(object.velocity_model);
            // manually trigger keyup, because change didn't work across browsers
            // but keyup isn't triggered by setvalue
            velocityCombo.fireEvent('keyup', velocityCombo);

            if (object.custom_mesh) {
              velocityCombo.up('form').getForm().findField('minlat').setValue(object.custom_mesh_boundaries.minlat);
              velocityCombo.up('form').getForm().findField('maxlat').setValue(object.custom_mesh_boundaries.maxlat);
              velocityCombo.up('form').getForm().findField('minlon').setValue(object.custom_mesh_boundaries.minlon);
              velocityCombo.up('form').getForm().findField('maxlon').setValue(object.custom_mesh_boundaries.maxlon);
            }

            CF.app.getController('Map').getStore('SolverConf').loadData(object.fields);

            // HACK ensure correct event binding order by binding here
            var eventLayer = CF.app.getController('Map').mapPanel.map.getLayersByName('Events')[0];
            CF.app.getController('Map').getStore('Event').bind(eventLayer);

            eventLayer.events.on({
              featureadded: function(event) {},
              featuresadded: function(event) {
                event.features.forEach(function(feature) {
                  if (object.events.indexOf(feature.data.eventId) >= 0) {
                    CF.app.getController('Map').mapPanel.map.getControl('dragselect').select(feature);
                  } else {
                    CF.app.getController('Map').mapPanel.map.getControl('dragselect').unselect(feature);
                  }
                });
                eventLayer.events.un(this);
                if (--numRemaining === 0) {
                  Ext.getCmp('viewport').setLoading(false);
                }
              },
              scope: this
            });

            // reuse events
            CF.app.getController('Map').getEvents(CF.app.getController('Map'), prov_object.quakeml.url.replace(/http:\/\/[^\/]*\//, '/'));

            var stationFileType = prov_object.stations['mime-type'] === 'application/xml' ? STXML_TYPE : STPOINTS_TYPE;
            var record = Ext.getCmp('station-filetype').getStore().findRecord('abbr', stationFileType);
            Ext.getCmp('station-filetype').select(stationFileType);

            // HACK ensure correct event binding order by binding here
            var stationLayer = CF.app.getController('Map').mapPanel.map.getLayersByName('Stations')[0];
            CF.app.getController('Map').getStore('Station').bind(stationLayer);

            stationLayer.events.on({
              featureadded: function(event) {},
              featuresadded: function(event) {
                event.features.forEach(function(feature) {
                  if (object.stations.indexOf(feature.data.network + '.' + feature.data.station) >= 0) {
                    CF.app.getController('Map').mapPanel.map.getControl('dragselect').select(feature);
                  } else {
                    CF.app.getController('Map').mapPanel.map.getControl('dragselect').unselect(feature);
                  }
                });
                stationLayer.events.un(this);
                if (--numRemaining === 0) {
                  Ext.getCmp('viewport').setLoading(false);
                }
              },
              scope: this
            });

            // reuse stations
            CF.app.getController('Map').getStations(CF.app.getController('Map'), prov_object.stations.url.replace(/http:\/\/[^\/]*\//, '/'), stationFileType);

            // Only set old workflow if it's still available
            if (prov_object.workflowId != null) {
              var workflowDropdown = Ext.getCmp('wfSelection');
              if (workflowDropdown.store.findRecord('workflowId', prov_object.workflowId) == null) {
                Ext.Msg.alert("Error", "Workflow used in old run not available anymore. Select a new workflow in the Submit tab.");
                workflowDropdown.clearValue();
              } else {
                workflowDropdown.setValue(prov_object.workflowId);
              }
            }

            Ext.getCmp('submitName').setValue(prov_object._id.slice(0, -14)); // remove runid
            Ext.getCmp('submitMessage').setValue(prov_object.description);
          }, this, {
            single: true
          });

          // set mesh when solverconfstore finishes loading
          CF.app.getController('Map').getStore('SolverConf').addListener('refresh', function() {
            // reuse mesh and trigger velocity store reload
            Ext.getCmp('meshes').setValue(object.mesh);
            // manually trigger keyup, because change didn't work across browsers
            // but keyup isn't triggered by setvalue
            Ext.getCmp('meshes').fireEvent('keyup', Ext.getCmp('meshes'));

            if (--numRemaining === 0) {
              Ext.getCmp('viewport').setLoading(false);
            }
          }, this, {
            single: true
          });

          // reuse solver
          var solverType = Ext.getCmp('solvertype');
          var solver = solverType.store.findRecord('name', object.solver);
          if (solver != null) {
            solverType.clearValue();
            solverType.setValue(solver.get('abbr'));
          } else {
            // TODO fix partial reuse when solver unavailable
            Ext.Msg.alert("Solver from old run now unavailable. Please select another one on the Solver tab.");
            Ext.getCmp('viewport').setLoading(false);
            return;
          }
        },
        failure: function(response) {
          Ext.Msg.alert("Error", "Failed to get workflow settings!");
          Ext.getCmp('viewport').setLoading(false);
        }
      })
    },
    failure: function(response) {
      Ext.Msg.alert("Error", "Failed to get workflow from provenance api!");
      Ext.getCmp('viewport').setLoading(false);
    }
  })
};

Ext.define('CF.view.WorkflowSelection', {
  extend: 'Ext.grid.Panel',
  alias: 'widget.workflowselection',
  requires: [
    'CF.store.Workflow',
    'Ext.grid.plugin.BufferedRenderer'
  ],

  width: 780,
  disableSelection: true,

  autoHeight: true,

  store: Ext.data.StoreManager.lookup('provWorkflowStore'),

  border: false,

  loadMask: true,

  columns: [{
      xtype: 'rownumberer',

      sortable: false
    }, {
      header: 'Run ID',
      dataIndex: 'runId',
      flex: 5,
      sortable: false
    }, {
      header: 'Workflow Name',
      dataIndex: 'workflowName',
      flex: 3,
      sortable: false,
      groupable: false
    }, {
      header: 'Description - Click to Edit',
      dataIndex: 'description',
      flex: 3,
      sortable: false,
      field: {
        xtype: 'textfield',
        allowBlank: true,
        maxLength: 50
      }
    }, {
      header: 'Date',
      dataIndex: 'date',
      flex: 3,
      sortable: false,
      groupable: false
    }, // custom mapping
    {
      xtype: 'actioncolumn',
      width: 20,
      icon: localResourcesPath + '/img/Farm-Fresh_arrow_rotate_clockwise.png',
      tooltip: 'Reuse',
      handler: handleReuseResults
    },
    {
      xtype: 'actioncolumn',
      width: 20,
      tdCls: 'Delete',
      items: [{
        icon: localResourcesPath + '/img/delete-icon.png', // Use a URL in the icon config
        tooltip: 'Delete',
        handler: function(grid, rowIndex, colIndex) {
          var rec = grid.getStore().getAt(rowIndex);

          var storeClassName = Ext.getClassName(grid.getStore());
          var tempStore = Ext.create(storeClassName, {
            buffered: false
          });
          tempStore.add(rec);
          var xx = tempStore.getAt(0)
          messagebox = Ext.Msg.confirm('Remove Run', 'Are you sure?', function(button) {
            if (button == 'yes') {
              var tempx = tempStore.getProxy();
              tempx.api.destroy = PROV_SERVICE_BASEURL + "workflowexecutions/" + xx.get("runId")+"/delete;

              tempStore.remove(xx);

              tempStore.sync({
                success: function(args) {
                  Ext.Ajax.request({
                    url: deleteWorkflowURL,
                    params: {
                      "workflowId": xx.get('systemId')
                    },
                    success: function(response) {
                      Ext.Msg.alert("Completed", "Data for Run ID "+xx.get("runId")+" has been successfully removed")
                    },
                    failure: function(response) {
					  Ext.Msg.alert("Error", "Error deleting workflow information from gUSE")
                    }
                  })
                  //PHPSESSID=vsb9rpreoten67g945pghhtde6

                  Ext.util.Cookies.set('PHPSESSID',"1t1vt2c50oilnm21q9072gdbp6")

                  Ext.Ajax.request({
                    url: deleteWorkflowDataURL,
                    method: "POST",
                    withCredentials : true,
    				useDefaultXhrHeader : false,
                    params: {
                      "ruri": IRODS_URI,
                      "dirs[]":	xx.get("runId")

                    },
                    success: function(response) {
                      wfStore.load();
                    },
                    failure: function(response) {

                    	Ext.Msg.alert("Error", "Error deleting data for Run ID "+xx.get("runId"))

                    }
                  })

                  // workflowStore.data.clear()
                  workflowStore.load()

                },

                faliure: function(args) {

                  Ext.Msg.alert("Error", "Delete failed!");

                }

              })

            }
          })
          messagebox.zIndexManager.bringToFront(messagebox);

        }

      }]
    }
  ],
  flex: 1,
  selType: 'cellmodel',
  plugins: [
    Ext.create('Ext.grid.plugin.CellEditing', {
      clicksToEdit: 1,
      listeners: {
        'validateedit': function(c, e, eOpts) {
          var r = e.rowIdx;
          var sr = workflowStore.getAt(r);

          sr.set(e.field, e.value);

          workflowStore.load()
        }
      }
    })
  ],

  /*   verticalScroller: {
        xtype: 'paginggridscroller'
    },*/

  /* plugins: [{
        ptype: 'bufferedrenderer'
    }],*/

  /* selModel: {
        pruneRemoved: false
    },
*/
  initComponent: function() {
    this.callParent(arguments);
  },

  viewConfig: {
    enableTextSelection: true,
    listeners: {

      itemclick: function(dv, record, item, index, e) {
        workflowStore.sync()
      },
      itemdblclick: function(dataview, record, item, index, e) {

        activityStore.setProxy({
          type: 'ajax',
          //url: PROV_SERVICE_BASEURL + 'activities/' + encodeURIComponent(record.get("runId"))+'?method=aggregate',
          url: PROV_SERVICE_BASEURL + '/workflowexecutions/'+encodeURIComponent(record.get("runId"))+'/instances',

          reader: {
            rootProperty: '@graph',
            totalProperty: 'totalCount'
          },
          simpleSortMode: true

        });
        sys.prune();
        artifactStore.data.clear();
        activityStore.data.clear();
        activityStore.load({
          callback: function() {
            currentRun = record.get("runId")
            Ext.getCmp('filtercurrent').enable();
            Ext.getCmp('searchartifacts').enable();
            Ext.getCmp('downloadscript').enable();

          }

        })

        activityStore.on('load', onStoreLoad, this, {
          single: true
        });
        currentRun = record.get("runId")
        owner = userSN

      }

    }
  }

});<commit_msg>missing quote<commit_after>

var handleReuseResults = function(grid, rowIndex, colIndex) {
  var rec = workflowStore.getAt(rowIndex);

  Ext.getCmp('viewport').setLoading(true);
  // number of asynchronous calls remaining

  var numRemaining = 3;
  alert(rec.get('runId'))
  Ext.Ajax.request({
    url: "/j2ep-1.0/prov/workflowexecutions/" + encodeURIComponent(rec.get('runId')),
    params: {},
    method: 'GET',
    success: function(response) {
      var prov_object = JSON.parse(response.responseText);

      if (prov_object == null) {
        Ext.getCmp('viewport').setLoading(true);
        Ext.Msg.alert("Error", "Workflow missing from provenance repository. Please contact support and list the workflow name and username.");
        return;
      }

      prov_object.input.forEach(function(item) {
        prov_object[item.name] = item;
      });
      delete prov_object.input;

      Ext.Ajax.request({
        url: prov_object.solverconf.url.replace(/http:\/\/[^\/]*\//, '/'),
        success: function(response) {
          var object = JSON.parse(response.responseText);
          if (object === null) {
            Ext.Msg.alert("Failed to get workflow settings");
            Ext.getCmp('viewport').setLoading(false);
            return;
          }

          // reuse velocity when velocity model store finishes loading
          var velocityCombo = Ext.getCmp('velocity');
          velocityCombo.store.addListener('refresh', function() {
            velocityCombo.setValue(object.velocity_model);
            // manually trigger keyup, because change didn't work across browsers
            // but keyup isn't triggered by setvalue
            velocityCombo.fireEvent('keyup', velocityCombo);

            if (object.custom_mesh) {
              velocityCombo.up('form').getForm().findField('minlat').setValue(object.custom_mesh_boundaries.minlat);
              velocityCombo.up('form').getForm().findField('maxlat').setValue(object.custom_mesh_boundaries.maxlat);
              velocityCombo.up('form').getForm().findField('minlon').setValue(object.custom_mesh_boundaries.minlon);
              velocityCombo.up('form').getForm().findField('maxlon').setValue(object.custom_mesh_boundaries.maxlon);
            }

            CF.app.getController('Map').getStore('SolverConf').loadData(object.fields);

            // HACK ensure correct event binding order by binding here
            var eventLayer = CF.app.getController('Map').mapPanel.map.getLayersByName('Events')[0];
            CF.app.getController('Map').getStore('Event').bind(eventLayer);

            eventLayer.events.on({
              featureadded: function(event) {},
              featuresadded: function(event) {
                event.features.forEach(function(feature) {
                  if (object.events.indexOf(feature.data.eventId) >= 0) {
                    CF.app.getController('Map').mapPanel.map.getControl('dragselect').select(feature);
                  } else {
                    CF.app.getController('Map').mapPanel.map.getControl('dragselect').unselect(feature);
                  }
                });
                eventLayer.events.un(this);
                if (--numRemaining === 0) {
                  Ext.getCmp('viewport').setLoading(false);
                }
              },
              scope: this
            });

            // reuse events
            CF.app.getController('Map').getEvents(CF.app.getController('Map'), prov_object.quakeml.url.replace(/http:\/\/[^\/]*\//, '/'));

            var stationFileType = prov_object.stations['mime-type'] === 'application/xml' ? STXML_TYPE : STPOINTS_TYPE;
            var record = Ext.getCmp('station-filetype').getStore().findRecord('abbr', stationFileType);
            Ext.getCmp('station-filetype').select(stationFileType);

            // HACK ensure correct event binding order by binding here
            var stationLayer = CF.app.getController('Map').mapPanel.map.getLayersByName('Stations')[0];
            CF.app.getController('Map').getStore('Station').bind(stationLayer);

            stationLayer.events.on({
              featureadded: function(event) {},
              featuresadded: function(event) {
                event.features.forEach(function(feature) {
                  if (object.stations.indexOf(feature.data.network + '.' + feature.data.station) >= 0) {
                    CF.app.getController('Map').mapPanel.map.getControl('dragselect').select(feature);
                  } else {
                    CF.app.getController('Map').mapPanel.map.getControl('dragselect').unselect(feature);
                  }
                });
                stationLayer.events.un(this);
                if (--numRemaining === 0) {
                  Ext.getCmp('viewport').setLoading(false);
                }
              },
              scope: this
            });

            // reuse stations
            CF.app.getController('Map').getStations(CF.app.getController('Map'), prov_object.stations.url.replace(/http:\/\/[^\/]*\//, '/'), stationFileType);

            // Only set old workflow if it's still available
            if (prov_object.workflowId != null) {
              var workflowDropdown = Ext.getCmp('wfSelection');
              if (workflowDropdown.store.findRecord('workflowId', prov_object.workflowId) == null) {
                Ext.Msg.alert("Error", "Workflow used in old run not available anymore. Select a new workflow in the Submit tab.");
                workflowDropdown.clearValue();
              } else {
                workflowDropdown.setValue(prov_object.workflowId);
              }
            }

            Ext.getCmp('submitName').setValue(prov_object._id.slice(0, -14)); // remove runid
            Ext.getCmp('submitMessage').setValue(prov_object.description);
          }, this, {
            single: true
          });

          // set mesh when solverconfstore finishes loading
          CF.app.getController('Map').getStore('SolverConf').addListener('refresh', function() {
            // reuse mesh and trigger velocity store reload
            Ext.getCmp('meshes').setValue(object.mesh);
            // manually trigger keyup, because change didn't work across browsers
            // but keyup isn't triggered by setvalue
            Ext.getCmp('meshes').fireEvent('keyup', Ext.getCmp('meshes'));

            if (--numRemaining === 0) {
              Ext.getCmp('viewport').setLoading(false);
            }
          }, this, {
            single: true
          });

          // reuse solver
          var solverType = Ext.getCmp('solvertype');
          var solver = solverType.store.findRecord('name', object.solver);
          if (solver != null) {
            solverType.clearValue();
            solverType.setValue(solver.get('abbr'));
          } else {
            // TODO fix partial reuse when solver unavailable
            Ext.Msg.alert("Solver from old run now unavailable. Please select another one on the Solver tab.");
            Ext.getCmp('viewport').setLoading(false);
            return;
          }
        },
        failure: function(response) {
          Ext.Msg.alert("Error", "Failed to get workflow settings!");
          Ext.getCmp('viewport').setLoading(false);
        }
      })
    },
    failure: function(response) {
      Ext.Msg.alert("Error", "Failed to get workflow from provenance api!");
      Ext.getCmp('viewport').setLoading(false);
    }
  })
};

Ext.define('CF.view.WorkflowSelection', {
  extend: 'Ext.grid.Panel',
  alias: 'widget.workflowselection',
  requires: [
    'CF.store.Workflow',
    'Ext.grid.plugin.BufferedRenderer'
  ],

  width: 780,
  disableSelection: true,

  autoHeight: true,

  store: Ext.data.StoreManager.lookup('provWorkflowStore'),

  border: false,

  loadMask: true,

  columns: [{
      xtype: 'rownumberer',

      sortable: false
    }, {
      header: 'Run ID',
      dataIndex: 'runId',
      flex: 5,
      sortable: false
    }, {
      header: 'Workflow Name',
      dataIndex: 'workflowName',
      flex: 3,
      sortable: false,
      groupable: false
    }, {
      header: 'Description - Click to Edit',
      dataIndex: 'description',
      flex: 3,
      sortable: false,
      field: {
        xtype: 'textfield',
        allowBlank: true,
        maxLength: 50
      }
    }, {
      header: 'Date',
      dataIndex: 'date',
      flex: 3,
      sortable: false,
      groupable: false
    }, // custom mapping
    {
      xtype: 'actioncolumn',
      width: 20,
      icon: localResourcesPath + '/img/Farm-Fresh_arrow_rotate_clockwise.png',
      tooltip: 'Reuse',
      handler: handleReuseResults
    },
    {
      xtype: 'actioncolumn',
      width: 20,
      tdCls: 'Delete',
      items: [{
        icon: localResourcesPath + '/img/delete-icon.png', // Use a URL in the icon config
        tooltip: 'Delete',
        handler: function(grid, rowIndex, colIndex) {
          var rec = grid.getStore().getAt(rowIndex);

          var storeClassName = Ext.getClassName(grid.getStore());
          var tempStore = Ext.create(storeClassName, {
            buffered: false
          });
          tempStore.add(rec);
          var xx = tempStore.getAt(0)
          messagebox = Ext.Msg.confirm('Remove Run', 'Are you sure?', function(button) {
            if (button == 'yes') {
              var tempx = tempStore.getProxy();
              tempx.api.destroy = PROV_SERVICE_BASEURL + "workflowexecutions/" + xx.get("runId")+"/delete";

              tempStore.remove(xx);

              tempStore.sync({
                success: function(args) {
                  Ext.Ajax.request({
                    url: deleteWorkflowURL,
                    params: {
                      "workflowId": xx.get('systemId')
                    },
                    success: function(response) {
                      Ext.Msg.alert("Completed", "Data for Run ID "+xx.get("runId")+" has been successfully removed")
                    },
                    failure: function(response) {
					  Ext.Msg.alert("Error", "Error deleting workflow information from gUSE")
                    }
                  })
                  //PHPSESSID=vsb9rpreoten67g945pghhtde6

                  Ext.util.Cookies.set('PHPSESSID',"1t1vt2c50oilnm21q9072gdbp6")

                  Ext.Ajax.request({
                    url: deleteWorkflowDataURL,
                    method: "POST",
                    withCredentials : true,
    				useDefaultXhrHeader : false,
                    params: {
                      "ruri": IRODS_URI,
                      "dirs[]":	xx.get("runId")

                    },
                    success: function(response) {
                      wfStore.load();
                    },
                    failure: function(response) {

                    	Ext.Msg.alert("Error", "Error deleting data for Run ID "+xx.get("runId"))

                    }
                  })

                  // workflowStore.data.clear()
                  workflowStore.load()

                },

                faliure: function(args) {

                  Ext.Msg.alert("Error", "Delete failed!");

                }

              })

            }
          })
          messagebox.zIndexManager.bringToFront(messagebox);

        }

      }]
    }
  ],
  flex: 1,
  selType: 'cellmodel',
  plugins: [
    Ext.create('Ext.grid.plugin.CellEditing', {
      clicksToEdit: 1,
      listeners: {
        'validateedit': function(c, e, eOpts) {
          var r = e.rowIdx;
          var sr = workflowStore.getAt(r);

          sr.set(e.field, e.value);

          workflowStore.load()
        }
      }
    })
  ],

  /*   verticalScroller: {
        xtype: 'paginggridscroller'
    },*/

  /* plugins: [{
        ptype: 'bufferedrenderer'
    }],*/

  /* selModel: {
        pruneRemoved: false
    },
*/
  initComponent: function() {
    this.callParent(arguments);
  },

  viewConfig: {
    enableTextSelection: true,
    listeners: {

      itemclick: function(dv, record, item, index, e) {
        workflowStore.sync()
      },
      itemdblclick: function(dataview, record, item, index, e) {

        activityStore.setProxy({
          type: 'ajax',
          //url: PROV_SERVICE_BASEURL + 'activities/' + encodeURIComponent(record.get("runId"))+'?method=aggregate',
          url: PROV_SERVICE_BASEURL + '/workflowexecutions/'+encodeURIComponent(record.get("runId"))+'/instances',

          reader: {
            rootProperty: '@graph',
            totalProperty: 'totalCount'
          },
          simpleSortMode: true

        });
        sys.prune();
        artifactStore.data.clear();
        activityStore.data.clear();
        activityStore.load({
          callback: function() {
            currentRun = record.get("runId")
            Ext.getCmp('filtercurrent').enable();
            Ext.getCmp('searchartifacts').enable();
            Ext.getCmp('downloadscript').enable();

          }

        })

        activityStore.on('load', onStoreLoad, this, {
          single: true
        });
        currentRun = record.get("runId")
        owner = userSN

      }

    }
  }

});<|endoftext|>


<commit_before>import swPrecache from 'sw-precache';
import { resolve } from 'path';
import fs from 'fs';
import uglifyJs from 'uglify-js';
import webpackConfig from '../webpack/webpack.config.prod';
import pkg from '../package.json';

const publicDir = webpackConfig.output.path;

swPrecache.generate({
  cacheId: pkg.name,
  dontCacheBustUrlsMatching: /./,
  dynamicUrlToDependencies: {
    '/': [resolve(__dirname, '../server/views/index.ejs')]
  },
  navigateFallback: '/',
  staticFileGlobs: [
    `${publicDir}/{bundle,vendor}.*.{js,css,gz}`,
    `${publicDir}/manifest.json`
  ],
  stripPrefix: publicDir,
  runtimeCaching: [{
    urlPattern: /api/,
    handler: 'networkFirst'
  }]
}).then((serviceWorkerString) => {
  fs.writeFile(`${publicDir}/sw.js`, uglifyJs.minify(serviceWorkerString).code, (err) => {
    if (err) {
      return console.log(err);
    }
  });
});
<commit_msg>Update sw remove offline<commit_after>import swPrecache from 'sw-precache';
import { resolve } from 'path';
import fs from 'fs';
import uglifyJs from 'uglify-js';
import webpackConfig from '../webpack/webpack.config.prod';
import pkg from '../package.json';

const publicDir = webpackConfig.output.path;

swPrecache.generate({
  cacheId: pkg.name,
  verbose: true,
  dontCacheBustUrlsMatching: /./,
  //dynamicUrlToDependencies: {
  //  '/': [resolve(__dirname, '../server/views/index.ejs')]
  //},
  //navigateFallback: '/',
  staticFileGlobs: [
    `${publicDir}/{bundle,vendor}.*.{js,css,gz}`,
    `${publicDir}/manifest.json`
  ],
  stripPrefix: publicDir,
  runtimeCaching: [{
    urlPattern: /api/,
    handler: 'networkFirst'
  }]
}).then((serviceWorkerString) => {
  fs.writeFile(`${publicDir}/sw.js`, uglifyJs.minify(serviceWorkerString).code, (err) => {
    if (err) {
      return console.log(err);
    }
  });
});
<|endoftext|>


<commit_before>var raf = require('raf')
  , Boids = require('./')

var attractors = [[
    0 // x
  , 0 // y
  , 50 // dist
  , -2 // spd
]]

var canvas = document.createElement('canvas')
  , ctx = canvas.getContext('2d')
  , boids = Boids({
      boids: 200
    , speedLimit: 2
    , attractors: attractors
  }).on('tick', function(boids) {
    var halfHeight = canvas.height/2
      , halfWidth = canvas.width/2

    ctx.fillStyle = '#000'
    ctx.fillRect(0, 0, canvas.width, canvas.height)

    ctx.fillStyle = '#fff'
    for (var i = 0, l = boids.length; i < l; i += 1) {
      ctx.fillRect(boids[i].pos[0] + halfWidth, boids[i].pos[1] + halfHeight, 5, 5)
    }
  }).once('tick', function(boids) {
    console.log(boids)
  })

document.body.onmousemove = function(e) {
  var halfHeight = canvas.height/2
      , halfWidth = canvas.width/2

  attractors[0][0] = e.x - halfWidth
  attractors[0][1] = e.y - halfHeight
  attractors[1][0] = e.x - halfWidth
  attractors[1][1] = e.y - halfHeight
}

canvas.width = window.innerWidth
canvas.height = window.innerHeight

document.body.style.margin = '0'
document.body.style.padding = '0'
document.body.appendChild(canvas)

raf(window).on('data', boids.tick.bind(boids))
<commit_msg>fix up demo<commit_after>var raf = require('raf')
  , Boids = require('./')

var attractors = [[
    0 // x
  , 0 // y
  , 50 // dist
  , -2 // spd
]]

var canvas = document.createElement('canvas')
  , ctx = canvas.getContext('2d')
  , boids = Boids({
      boids: 200
    , speedLimit: 2
    , attractors: attractors
  })

document.body.onmousemove = function(e) {
  var halfHeight = canvas.height/2
      , halfWidth = canvas.width/2

  attractors[0][0] = e.x - halfWidth
  attractors[0][1] = e.y - halfHeight
}

canvas.width = window.innerWidth
canvas.height = window.innerHeight

document.body.style.margin = '0'
document.body.style.padding = '0'
document.body.appendChild(canvas)

var tock = 0
raf(window).on('data', function() {
  var boidData = boids.boids

  tock += 1
  tock = tock % 3
  boids.tick()

  var halfHeight = canvas.height/2
    , halfWidth = canvas.width/2

  ctx.fillStyle = '#000'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  ctx.fillStyle = '#fff'
  for (var i = 0, l = boidData.length; i < l; i += 1) {
    ctx.fillRect(boidData[i][0] + halfWidth, boidData[i][1] + halfHeight, 5, 5)
  }
})
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

let fs = require('fs'),
  Promise = require('bluebird'),
  path = require('path'),
  api = require('../../lib/');

Promise.promisifyAll(fs);

module.exports = {
  getHARresult: function(harFile) {
    return fs.readFileAsync(path.resolve(harFile))
      .then(JSON.parse)
      .then((har) => api.runHarAdvice(har, api.getHarAdvice()))
      .then((results) => {
        return results;
      });
  }
};
<commit_msg>Remove needless code.<commit_after>'use strict';

let fs = require('fs'),
  Promise = require('bluebird'),
  path = require('path'),
  api = require('../../lib/');

Promise.promisifyAll(fs);

module.exports = {
  getHARresult: function(harFile) {
    return fs.readFileAsync(path.resolve(harFile))
      .then(JSON.parse)
      .then((har) => api.runHarAdvice(har, api.getHarAdvice()));
  }
};
<|endoftext|>


<commit_before>import AuthConfiguration from 'ember-simple-auth/configuration';
import Route from '@ember/routing/route';
import ShortcutsRoute from 'ghost-admin/mixins/shortcuts-route';
import ctrlOrCmd from 'ghost-admin/utils/ctrl-or-cmd';
import windowProxy from 'ghost-admin/utils/window-proxy';
import {InitSentryForEmber} from '@sentry/ember';
import {
    isAjaxError,
    isNotFoundError,
    isUnauthorizedError
} from 'ember-ajax/errors';
import {isArray as isEmberArray} from '@ember/array';
import {
    isMaintenanceError,
    isVersionMismatchError
} from 'ghost-admin/services/ajax';
import {inject as service} from '@ember/service';

function K() {
    return this;
}

let shortcuts = {};

shortcuts.esc = {action: 'closeMenus', scope: 'default'};
shortcuts[`${ctrlOrCmd}+s`] = {action: 'save', scope: 'all'};

export default Route.extend(ShortcutsRoute, {
    ajax: service(),
    config: service(),
    feature: service(),
    ghostPaths: service(),
    notifications: service(),
    router: service(),
    session: service(),
    settings: service(),
    ui: service(),
    whatsNew: service(),

    shortcuts,

    routeAfterAuthentication: 'home',

    init() {
        this._super(...arguments);

        this.router.on('routeDidChange', () => {
            this.notifications.displayDelayed();
        });

        this.ui.initBodyDragHandlers();
    },

    beforeModel() {
        return this.prepareApp();
    },

    async afterModel(model, transition) {
        this._super(...arguments);

        if (this.get('session.isAuthenticated')) {
            this.session.appLoadTransition = transition;
        }

        this._appLoaded = true;
    },

    actions: {
        closeMenus() {
            this.ui.closeMenus();
        },

        didTransition() {
            this.session.appLoadTransition = null;
            this.send('closeMenus');
        },

        authorizationFailed() {
            windowProxy.replaceLocation(AuthConfiguration.rootURL);
        },

        // noop default for unhandled save (used from shortcuts)
        save: K,

        error(error, transition) {
            // unauthoirized errors are already handled in the ajax service
            if (isUnauthorizedError(error)) {
                return false;
            }

            if (isNotFoundError(error)) {
                if (transition) {
                    transition.abort();
                }

                let routeInfo = transition.to;
                let router = this.router;
                let params = [];

                for (let key of Object.keys(routeInfo.params)) {
                    params.push(routeInfo.params[key]);
                }

                let url = router.urlFor(routeInfo.name, ...params)
                    .replace(/^#\//, '')
                    .replace(/^\//, '')
                    .replace(/^ghost\//, '');

                return this.replaceWith('error404', url);
            }

            if (isVersionMismatchError(error)) {
                if (transition) {
                    transition.abort();
                }

                this.upgradeStatus.requireUpgrade();

                if (this._appLoaded) {
                    return false;
                }
            }

            if (isMaintenanceError(error)) {
                if (transition) {
                    transition.abort();
                }

                this.upgradeStatus.maintenanceAlert();

                if (this._appLoaded) {
                    return false;
                }
            }

            if (isAjaxError(error) || error && error.payload && isEmberArray(error.payload.errors)) {
                this.notifications.showAPIError(error);
                // don't show the 500 page if we weren't navigating
                if (!transition) {
                    return false;
                }
            }

            // fallback to 500 error page
            return true;
        }
    },

    willDestroy() {
        this.ui.cleanupBodyDragHandlers();
    },

    async prepareApp() {
        await this.config.fetchUnauthenticated();

        // init Sentry here rather than app.js so that we can use API-supplied
        // sentry_dsn and sentry_env rather than building it into release assets
        if (this.config.get('sentry_dsn')) {
            InitSentryForEmber({
                dsn: this.config.get('sentry_dsn'),
                environment: this.config.get('sentry_env'),
                release: `ghost@${this.config.get('version')}`,
                beforeSend(event) {
                    event.tags = event.tags || {};
                    event.tags.grammarly = !!document.querySelector('[data-gr-ext-installed]');
                    console.log('beforeSend', event);
                    return event;
                }
            });
        }

        if (this.session.isAuthenticated) {
            try {
                await this.session.populateUser();
            } catch (e) {
                await this.session.invalidate();
            }

            await this.session.postAuthPreparation();
        }
    }

});
<commit_msg>Removed errant console.log<commit_after>import AuthConfiguration from 'ember-simple-auth/configuration';
import Route from '@ember/routing/route';
import ShortcutsRoute from 'ghost-admin/mixins/shortcuts-route';
import ctrlOrCmd from 'ghost-admin/utils/ctrl-or-cmd';
import windowProxy from 'ghost-admin/utils/window-proxy';
import {InitSentryForEmber} from '@sentry/ember';
import {
    isAjaxError,
    isNotFoundError,
    isUnauthorizedError
} from 'ember-ajax/errors';
import {isArray as isEmberArray} from '@ember/array';
import {
    isMaintenanceError,
    isVersionMismatchError
} from 'ghost-admin/services/ajax';
import {inject as service} from '@ember/service';

function K() {
    return this;
}

let shortcuts = {};

shortcuts.esc = {action: 'closeMenus', scope: 'default'};
shortcuts[`${ctrlOrCmd}+s`] = {action: 'save', scope: 'all'};

export default Route.extend(ShortcutsRoute, {
    ajax: service(),
    config: service(),
    feature: service(),
    ghostPaths: service(),
    notifications: service(),
    router: service(),
    session: service(),
    settings: service(),
    ui: service(),
    whatsNew: service(),

    shortcuts,

    routeAfterAuthentication: 'home',

    init() {
        this._super(...arguments);

        this.router.on('routeDidChange', () => {
            this.notifications.displayDelayed();
        });

        this.ui.initBodyDragHandlers();
    },

    beforeModel() {
        return this.prepareApp();
    },

    async afterModel(model, transition) {
        this._super(...arguments);

        if (this.get('session.isAuthenticated')) {
            this.session.appLoadTransition = transition;
        }

        this._appLoaded = true;
    },

    actions: {
        closeMenus() {
            this.ui.closeMenus();
        },

        didTransition() {
            this.session.appLoadTransition = null;
            this.send('closeMenus');
        },

        authorizationFailed() {
            windowProxy.replaceLocation(AuthConfiguration.rootURL);
        },

        // noop default for unhandled save (used from shortcuts)
        save: K,

        error(error, transition) {
            // unauthoirized errors are already handled in the ajax service
            if (isUnauthorizedError(error)) {
                return false;
            }

            if (isNotFoundError(error)) {
                if (transition) {
                    transition.abort();
                }

                let routeInfo = transition.to;
                let router = this.router;
                let params = [];

                for (let key of Object.keys(routeInfo.params)) {
                    params.push(routeInfo.params[key]);
                }

                let url = router.urlFor(routeInfo.name, ...params)
                    .replace(/^#\//, '')
                    .replace(/^\//, '')
                    .replace(/^ghost\//, '');

                return this.replaceWith('error404', url);
            }

            if (isVersionMismatchError(error)) {
                if (transition) {
                    transition.abort();
                }

                this.upgradeStatus.requireUpgrade();

                if (this._appLoaded) {
                    return false;
                }
            }

            if (isMaintenanceError(error)) {
                if (transition) {
                    transition.abort();
                }

                this.upgradeStatus.maintenanceAlert();

                if (this._appLoaded) {
                    return false;
                }
            }

            if (isAjaxError(error) || error && error.payload && isEmberArray(error.payload.errors)) {
                this.notifications.showAPIError(error);
                // don't show the 500 page if we weren't navigating
                if (!transition) {
                    return false;
                }
            }

            // fallback to 500 error page
            return true;
        }
    },

    willDestroy() {
        this.ui.cleanupBodyDragHandlers();
    },

    async prepareApp() {
        await this.config.fetchUnauthenticated();

        // init Sentry here rather than app.js so that we can use API-supplied
        // sentry_dsn and sentry_env rather than building it into release assets
        if (this.config.get('sentry_dsn')) {
            InitSentryForEmber({
                dsn: this.config.get('sentry_dsn'),
                environment: this.config.get('sentry_env'),
                release: `ghost@${this.config.get('version')}`,
                beforeSend(event) {
                    event.tags = event.tags || {};
                    event.tags.grammarly = !!document.querySelector('[data-gr-ext-installed]');
                    return event;
                }
            });
        }

        if (this.session.isAuthenticated) {
            try {
                await this.session.populateUser();
            } catch (e) {
                await this.session.invalidate();
            }

            await this.session.postAuthPreparation();
        }
    }

});
<|endoftext|>


<commit_before>$(document).ready(function() {
  var $pre = $('#operations pre');
  var log = function(m) {
    $pre.append(m).append("\r\n");
  }
  var logProblem = function(m) {
    log("*Problem "+m);
    $("#review").addClass("problem");
  }
  var get = // adapted from lodash.get, with thanks
    function(o,p,v) {
      var i=0, l=p.length;
      while(o && i<l) { o = o[p[i++]]; }
      return o ? o : v;
    }
  var createOwnerPico = function(callback){
    $.getJSON("/api/new-pico", function(d) {
      if (d && d.id) {
        log("Pico created: "+d.id);
        log("Creating owner channel");
        $.getJSON("/api/pico/"+d.id+"/new-channel",
            {"name": "main", "type": "secret"},
            function(c){
              if (c && c.id) {
                log("Owner Pico ECI: "+c.id);
                callback(d.id,c.id);
              } else {
                logProblem("creating owner pico channel");
              }
            }
        );
      } else {
        logProblem("creating owner pico");
      }
    });
  };
  var hashForRid = function(rid,callback){
    log("Getting hash for "+rid);
    $.getJSON("/api/db-dump", function(db_dump){
      var hashobj;
      for (var vds in db_dump.rulesets.versions[rid]) {
        hashobj = db_dump.rulesets.versions[rid][vds];
      }
      if (hashobj) {
        for(var hash in hashobj)
        {
          log(rid+" hash is "+hash);
          callback(hash);
          return;
        }
      }
      logProblem("getting hash for "+rid);
    });
  };
  var installAndAddRuleset = function(rid,id,callback){
    log("Getting "+rid+".krl");
    $.get("https://raw.githubusercontent.com/Picolab/node-pico-engine/master/krl/"+rid+".krl",function(k){
      if (k && k.length > 0) {
        log(rid+".krl length: "+k.length);
        log("Registering "+rid);
        $.getJSON("/api/ruleset/register",{"src":k},function(rr){
          if (rr && rr.ok) {
            log(rid+" registered");
            hashForRid(rid,function(hash){
              log("Enabling "+rid);
              $.getJSON("/api/ruleset/enable/"+hash,function(re){
                if (re && re.ok) {
                  log(rid+" enabled");
                  log("Installing "+rid);
                  $.getJSON("/api/ruleset/install/"+rid,function(ri){
                    if (ri && ri.ok) {
                      log(rid+" installed");
                      log("Adding "+rid+" to pico "+id);
                      $.getJSON("/api/pico/"+id+"/add-ruleset?rid="+rid,function(ra){
                        if (ra && ra.ok) {
                          log(rid+" added to pico "+id);
                          callback();
                        } else {
                          logProblem("adding "+rid);
                        }
                      });
                    } else {
                      logProblem("installing "+rid);
                    }
                  }).fail(function() {
                    logProblem("installing "+rid+": failed to compile");
                  });
                } else {
                  logProblem("enabling "+rid);
                }
              });
            });
          } else {
            logProblem("registering "+rid);
          }
        });
      } else {
        logProblem("getting "+rid);
      }
    },"text");
  };
  log("Loading database");
  $.getJSON("/api/db-dump", function(db_dump){
    log("Database loaded");
    if (db_dump.pico) {
      log("Database has an owner pico");
      if (db_dump.rulesets) {
        log("Database has rulesets");
        $("#done").addClass("okay");
      } else {
        logProblem("finding rulesets");
      }
    } else {
      log("Creating owner pico");
      createOwnerPico(function(id,eci){
        log("Registering rulesets");
        installAndAddRuleset("io.picolabs.pico",id,function(){
          log("Sending event pico/root_created");
          $.getJSON("/sky/event/"+eci+"/19/pico/root_created",
            {"id":id,"eci":eci},function(d){
              if (d && d.directives) {
                log("Event pico/root_created processed");
              } else {
                logProblem("with event pico/root_created");
              }
          });
          installAndAddRuleset("io.picolabs.visual_params",id,function(){
            log("Sending event visual/update");
            $.getJSON("/sky/event/"+eci+"/31/visual/update",
              {"dname":"Owner Pico","color":"#87cefa"},function(d){
                if (d && d.directives) {
                  log("Event visual/update processed");
                  $("#done").addClass("okay");
                } else {
                  logProblem("with event visual/update");
                }
            });
          });
        });
      });
    }
  });
});
<commit_msg>use ruleset/register-and-enable in bootstrap<commit_after>$(document).ready(function() {
  var $pre = $('#operations pre');
  var log = function(m) {
    $pre.append(m).append("\r\n");
  }
  var logProblem = function(m) {
    log("*Problem "+m);
    $("#review").addClass("problem");
  }
  var get = // adapted from lodash.get, with thanks
    function(o,p,v) {
      var i=0, l=p.length;
      while(o && i<l) { o = o[p[i++]]; }
      return o ? o : v;
    }
  var createOwnerPico = function(callback){
    $.getJSON("/api/new-pico", function(d) {
      if (d && d.id) {
        log("Pico created: "+d.id);
        log("Creating owner channel");
        $.getJSON("/api/pico/"+d.id+"/new-channel",
            {"name": "main", "type": "secret"},
            function(c){
              if (c && c.id) {
                log("Owner Pico ECI: "+c.id);
                callback(d.id,c.id);
              } else {
                logProblem("creating owner pico channel");
              }
            }
        );
      } else {
        logProblem("creating owner pico");
      }
    });
  };
  var installAndAddRuleset = function(rid,id,callback){
    log("Getting "+rid+".krl");
    $.get("https://raw.githubusercontent.com/Picolab/node-pico-engine/master/krl/"+rid+".krl",function(k){
      if (k && k.length > 0) {
        log(rid+".krl length: "+k.length);
        log("Registering "+rid);
        $.getJSON("/api/ruleset/register-and-enable",{"src":k},function(rr){
          if (rr && rr.ok) {
            log(rid+" registered and enabled");
            log("Installing "+rid);
            $.getJSON("/api/ruleset/install/"+rid,function(ri){
              if (ri && ri.ok) {
                log(rid+" installed");
                log("Adding "+rid+" to pico "+id);
                $.getJSON("/api/pico/"+id+"/add-ruleset?rid="+rid,function(ra){
                  if (ra && ra.ok) {
                    log(rid+" added to pico "+id);
                    callback();
                  } else {
                    logProblem("adding "+rid);
                  }
                });
              } else {
                logProblem("installing "+rid);
              }
            }).fail(function() {
              logProblem("installing "+rid+": failed to compile");
            });
          } else {
            logProblem("registering "+rid);
          }
        });
      } else {
        logProblem("getting "+rid);
      }
    },"text");
  };
  log("Loading database");
  $.getJSON("/api/db-dump", function(db_dump){
    log("Database loaded");
    if (db_dump.pico) {
      log("Database has an owner pico");
      if (db_dump.rulesets) {
        log("Database has rulesets");
        $("#done").addClass("okay");
      } else {
        logProblem("finding rulesets");
      }
    } else {
      log("Creating owner pico");
      createOwnerPico(function(id,eci){
        log("Registering rulesets");
        installAndAddRuleset("io.picolabs.pico",id,function(){
          log("Sending event pico/root_created");
          $.getJSON("/sky/event/"+eci+"/19/pico/root_created",
            {"id":id,"eci":eci},function(d){
              if (d && d.directives) {
                log("Event pico/root_created processed");
              } else {
                logProblem("with event pico/root_created");
              }
          });
          installAndAddRuleset("io.picolabs.visual_params",id,function(){
            log("Sending event visual/update");
            $.getJSON("/sky/event/"+eci+"/31/visual/update",
              {"dname":"Owner Pico","color":"#87cefa"},function(d){
                if (d && d.directives) {
                  log("Event visual/update processed");
                  $("#done").addClass("okay");
                } else {
                  logProblem("with event visual/update");
                }
            });
          });
        });
      });
    }
  });
});
<|endoftext|>


<commit_before>"use strict"

var shell = require("gl-now")({clearColor: [0.2, 0.4, 0.8, 1.0]})
var camera = require("game-shell-orbit-camera")(shell)
var renderText = require("gl-render-text")
var mat4 = require("gl-mat4")
var createMesh = require("gl-mesh")
var glslify = require("glslify")

var texture
var positions = new Array(100)
var mesh
var shader

shell.on("gl-init", function() {
  var gl = shell.gl
  texture = renderText(gl, "Billboard")

  mesh = createMesh(gl,
      [
      [0, 1, 2],
      [3, 1, 2]
       ],
      { "position": [
        [0, 0, 0],
        [0, 1, 0],
        [1, 0, 0],
        [1, 1, 0]] })

  shader = glslify({
    inline: true,
    vertex: "/* voxel-decals vertex shader */\
attribute vec3 position;\
\
uniform mat4 projection;\
uniform mat4 view;\
uniform mat4 model;\
varying vec4 vColor;\
\
void main() {\
  gl_Position = projection * view * model * vec4(position, 1.0);\
  vColor = vec4(gl_Position.x, gl_Position.y, gl_Position.z, 1.0);\
}",

  fragment: "/* voxel-decals fragment shader */\
precision highp float;\
varying vec4 vColor;\
\
void main() {\
  gl_FragColor = vColor;\
}"})(gl)

})

var model = mat4.create()
mat4.translate(model, model, [0,0,10])
mat4.scale(model, model, [4,4,4])

shell.on("gl-render", function() {
  var proj = mat4.perspective(mat4.create(), Math.PI/4.0, shell.width/shell.height, 0.1, 1000.0)
  var view = camera.view()

  shader.bind()
  shader.attributes.position.location = 0
  shader.uniforms.projection = proj
  shader.uniforms.view = view
  shader.uniforms.model = model

  mesh.bind(shader)
  mesh.draw()
  mesh.unbind()
})
<commit_msg>Move projection-view-model matrix calculation to JavaScript out of GLSL<commit_after>"use strict"

var shell = require("gl-now")({clearColor: [0.2, 0.4, 0.8, 1.0]})
var camera = require("game-shell-orbit-camera")(shell)
var renderText = require("gl-render-text")
var mat4 = require("gl-mat4")
var createMesh = require("gl-mesh")
var glslify = require("glslify")

var texture
var positions = new Array(100)
var mesh
var shader

shell.on("gl-init", function() {
  var gl = shell.gl
  texture = renderText(gl, "Billboard")

  mesh = createMesh(gl,
      [
      [0, 1, 2],
      [3, 1, 2]
       ],
      { "position": [
        [0, 0, 0],
        [0, 1, 0],
        [1, 0, 0],
        [1, 1, 0]] })

  shader = glslify({
    inline: true,
    vertex: "/* voxel-decals vertex shader */\
attribute vec3 position;\
\
uniform mat4 projViewModel;\
varying vec4 vColor;\
\
void main() {\
  gl_Position = projViewModel * vec4(position, 1.0);\
  vColor = vec4(gl_Position.x, gl_Position.y, gl_Position.z, 1.0);\
}",

  fragment: "/* voxel-decals fragment shader */\
precision highp float;\
varying vec4 vColor;\
\
void main() {\
  gl_FragColor = vColor;\
}"})(gl)

})

var model = mat4.create()
mat4.translate(model, model, [0,0,10])
mat4.scale(model, model, [4,4,4])

var projViewModel = mat4.create()

shell.on("gl-render", function() {
  var proj = mat4.perspective(mat4.create(), Math.PI/4.0, shell.width/shell.height, 0.1, 1000.0)
  var view = camera.view()

  shader.bind()
  shader.attributes.position.location = 0

  mat4.multiply(projViewModel, proj, view)
  mat4.multiply(projViewModel, projViewModel, model)

  shader.uniforms.projViewModel = projViewModel

  mesh.bind(shader)
  mesh.draw()
  mesh.unbind()
})
<|endoftext|>


<commit_before>(function() {
    L.mapbox.accessToken = config.key;

    // Jerbs
    var jerbs = {};
    jerbs.jobs = {};

    jerbs.addMarker = function(title, company, location, url) {
        var latlng = [];

        title = title + " at " + company;

        if (typeof location == "string") {
            map.geocoder.query(location, function(err, data) {
                var lat = data.latlng[0];
                var lng = data.latlng[1];

                latlng = [lat, lng];

                var marker = L.marker(latlng, {
                    icon: L.mapbox.marker.icon({
                        'marker-symbol': 'suitcase',
                        'marker-color': '0044FF'
                    }),
                    title: title
                });

                marker.on('click', function(e) {
                    window.open(url);
                })

                marker.bindPopup(title);
                map.markers.addLayer(marker);
            });
        } else {
            latlng = user.position;

            var marker = L.marker(latlng, {
                icon: L.mapbox.marker.icon({
                    'marker-symbol': 'suitcase',
                    'marker-color': '0044FF'
                }),
                title: title
            });

            marker.on('click', function(e) {
                window.open(url);
            })

            marker.bindPopup(title);
            map.markers.addLayer(marker);
        }
    }

    jerbs.getData = function(term) {
        var url = 'https://jobs.github.com/positions.json';

        $.ajax({
            dataType: 'jsonp',
            url: url,
            success: function(data) {
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    var location = item.location;
                    var title = item.title;

                    if (location == "Anywhere") {
                        // anywhere todo
                        jerbs.addMarker(title, item.company,
                            user.location, item.url);
                    } else {
                        jerbs.addMarker(title, item.company,
                            location, item.url);
                    }
                }
                map.map.addLayer(map.markers);
            }
        });
    }

    // User
    var user = {};
    user.data = JSON.parse(localStorage.getItem('jerbs_data'));
    user.save = function() {
        localStorage.set('jerbs_data', user.data);
    }

    // Map
    var map = {};

    map.map = L.mapbox.map('map', 'mapbox.streets');
    map.el = document.getElementById(
        'map');
    map.markers = new L.MarkerClusterGroup();
    map.geocoder = L.mapbox.geocoder('mapbox.places');

    // Async / Events
    navigator.geolocation.getCurrentPosition(function(position) {
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;

        user.position = [lat, lng];

        // map.map.setView(user.position, 10);
    });

    map.markers.on('mouseover', function(e) {
        e.layer.openPopup();
    });

    map.markers.on('mouseout', function(e) {
        e.layer.closePopup();
    });

    // onload
    window.onload = function() {
        // handle user.data
        if (user.data == null) {
            // jerbs_data needs to be created
            user.data = {};
            localStorage.setItem('jerbs_data', JSON.stringify(user.data));
            // console.log("jerbs_data was created");
        } else {
            // jerbs_data exists already

            // console.log("jerbs_data exists");
        }

        jerbs.getData('web developer');
    }
})();
<commit_msg>fixed bug where users must refresh to load jobs<commit_after>(function() {
    L.mapbox.accessToken = config.key;

    // Jerbs
    var jerbs = {};
    jerbs.jobs = {};

    jerbs.addMarker = function(title, company, location, url) {
        var latlng = [];

        title = title + " at " + company;

        if (typeof location == "string") {
            map.geocoder.query(location, function(err, data) {
                var lat = data.latlng[0];
                var lng = data.latlng[1];

                latlng = [lat, lng];

                var marker = L.marker(latlng, {
                    icon: L.mapbox.marker.icon({
                        'marker-symbol': 'suitcase',
                        'marker-color': '0044FF'
                    }),
                    title: title
                });

                marker.on('click', function(e) {
                    window.open(url);
                })

                marker.bindPopup(title);
                map.markers.addLayer(marker);
            });
        } else {
            latlng = user.position;

            var marker = L.marker(latlng, {
                icon: L.mapbox.marker.icon({
                    'marker-symbol': 'suitcase',
                    'marker-color': '0044FF'
                }),
                title: title
            });

            marker.on('click', function(e) {
                window.open(url);
            })

            marker.bindPopup(title);
            map.markers.addLayer(marker);
        }
    }

    jerbs.getData = function(term) {
        var url = 'https://jobs.github.com/positions.json';

        $.ajax({
            dataType: 'jsonp',
            url: url,
            success: function(data) {
                for (var i = 0; i < data.length; i++) {
                    var item = data[i];
                    var location = item.location;
                    var title = item.title;

                    if (location == "Anywhere") {
                        // anywhere todo
                        jerbs.addMarker(title, item.company,
                            user.location, item.url);
                    } else {
                        jerbs.addMarker(title, item.company,
                            location, item.url);
                    }
                }
                map.map.addLayer(map.markers);
            }
        });
    }

    // User
    var user = {};
    user.data = JSON.parse(localStorage.getItem('jerbs_data'));
    user.save = function() {
        localStorage.set('jerbs_data', user.data);
    }

    // Map
    var map = {};

    map.map = L.mapbox.map('map', 'mapbox.streets').setView([
        39.50, -98.35
    ], 4);
    map.el = document.getElementById(
        'map');
    map.markers = new L.MarkerClusterGroup();
    map.geocoder = L.mapbox.geocoder('mapbox.places');

    // Async / Events
    navigator.geolocation.getCurrentPosition(function(position) {
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;

        user.position = [lat, lng];

        jerbs.getData();
        // map.map.setView(user.position, 10);
    });

    map.markers.on('mouseover', function(e) {
        e.layer.openPopup();
    });

    map.markers.on('mouseout', function(e) {
        e.layer.closePopup();
    });
})();
<|endoftext|>