<commit_before>;(function(window, undefined) {
	"use strict";
	var ess,emptyArray = [],slice = emptyArray.slice,filter = emptyArray.filter,elementTypes = [1, 9, 11],
		WCJ = (function(){
		var WCJ = function( selector ) {
		    return new WCJ.fn.init(selector);
		};
		WCJ.fn = WCJ.prototype = {
			init:function( selector ){
				var dom ;
    			if (!selector)
    				dom = emptyArray,dom.selector = selector || '',dom.__proto__ = WCJ.fn.init.prototype;
    			else if (WCJ.isFunction(selector)) return WCJ(document).ready(selector)
    			else {
    				if (WCJ.isArray(selector))
    					dom = selector;
				    else if (WCJ.isObject(selector))
				    	dom = [selector], selector = null
	                else if (elementTypes.indexOf(selector.nodeType) >= 0 || selector === window)
	                	dom = [selector], selector = null;
	                else dom = (function(){
				        var found;
				        return (document && /^#([\w-]+)$/.test(selector))?
				        ((found = document.getElementById(RegExp.$1)) ? [found] : emptyArray ):
					    slice.call(
						    /^\.([\w-]+)$/.test(selector) ? document.getElementsByClassName(RegExp.$1) :
						    /^[\w-]+$/.test(selector) ? document.getElementsByTagName(selector) :
						    document.querySelectorAll(selector)
					    );
					})();
					dom = dom || emptyArray;
					dom.__proto__ = WCJ.fn.init.prototype;
					dom.selector = selector || '';
    			}
    			return dom;
			},
			size:function(){return this.length;}
		}
		WCJ.fn.init.prototype = WCJ.fn;
        WCJ.extend = WCJ.fn.extend = function () {
            var options, name, src, copy,
			target = arguments[0],
			i = 1,
			length = arguments.length,
			deep = false;
            //处理深拷贝的情况
            if (typeof (target) === "boolean") {
                deep = target;
                target = arguments[1] || {};
                i = 2;
            }
            //处理时，目标是一个字符串或（深拷贝可能的情况下）的东西
            if (typeof (target) !== "object" && !WCJ.isFunction(target)) {
                target = {};
            }
            //扩展WCJ的本身，如果只有一个参数传递
            if (length === i) {
                target = this;
                --i;
            }
            for (; i < length; i++) {
                if ((options = arguments[i]) != null) {
                    for (name in options) {
                        src = target[name];
                        copy = options[name];
                        if (target === copy) {
                            continue;
                        }
                        if (copy !== undefined) {
                            target[name] = copy;
                        }
                    }
                }
            }
            return target;
        };
		return WCJ;
	})();

	WCJ.fn.extend({
		forEach: emptyArray.forEach,
		concat: emptyArray.concat,
		ready: function(callback){
			if (/complete|loaded|interactive/.test(document.readyState) && document.body) callback(WCJ)
			else document.addEventListener('DOMContentLoaded', function(){callback(WCJ) }, false)
			return this
		},
	    each: function(callback){
	      this.forEach(function(el, idx){ callback.call(el, idx, el) });
	      return this;
	    },
	    map: function(fn){
	    	return WCJ(WCJ.map(this, function(el, i){ return fn.call(el, i, el) }));
	    },
	    get: function(index){
	      return index === undefined ? slice.call(this) : this[index >= 0 ? index : index + this.length];
	    },
	    empty: function(){ return this.each(function(){ this.innerHTML = '' }) },
	    text: function(text){
	      return text === undefined ?
	        (this.length > 0 ? this[0].textContent : null) :
	        this.each(function(){ this.textContent = text });
	    },
        bind: function(type, func) {
			this.each(function(){
				if (this.addEventListener) this.addEventListener(type, func, false);
				else if (this.attachEvent) this.attachEvent("on" + type, func);
				else this["on" + type] = func;
			})
			return this;
		},
		unbind:function(type, func) {
			this.each(function(ele,obj){
				if (this.removeEventListener) this.removeEventListener(type, func, false);
				else if (this[i].detachEvent) this.detachEvent("on" + type, func);
				else this["on" + type] = null;
			})
			return this;
		},
		filter:function(selector){
			return WCJ(filter.call(this, function(element){
        		return WCJ.matches(element, selector)
		    }))
		},
		pluck: function(property){ return WCJ.map(this, function(el){ return el[property] })},
		parent: function(){
			var arr=this.pluck('parentNode');
			return filter.call(arr, function(item, idx){
				return arr.indexOf(item) == idx
			});
		},
		parents: function(selector){
			var ancestors=WCJ.sibling(this,'parentNode');
    		return selector == null ? WCJ(ancestors) : WCJ(ancestors).filter(selector);
		},
		prev: function(selector){
			return WCJ(this.pluck('previousElementSibling')).filter(selector || '*')
		},
		next: function(selector){
			return WCJ(this.pluck('nextElementSibling')).filter(selector || '*')
		}
	});

	WCJ.extend({
		isDocument:function (obj) { return obj = obj ? obj != null && obj.nodeType ? obj.nodeType == obj.DOCUMENT_NODE : false : undefined;},
		isFunction:function (value) { return ({}).toString.call(value) == "[object Function]" },
		isObject:function (value) { return value instanceof Object },
		isArray:function (value) { return value instanceof Array },
		likeArray:function (obj) { return typeof obj.length == 'number' },
        type: function (obj) {
            switch (obj) {
                case null: return "Null";
                case (void 0): return "Undefined";
            }
            var type = typeof (obj);
            switch (type) {
                case 'boolean': return "Boolean";
                case 'number': return "Number";
                case 'string': return "String";
                case 'function': return "Function";
            }
            return "Object";
        },
        error:function(msg) {throw msg;},
        each:function(elements, callback){
			var i, key
			if (this.likeArray(elements)) {
				for (i = 0; i < elements.length; i++)
					if (callback.call(elements[i], i, elements[i]) === false) return elements
				} else {
				for (key in elements)
					if (callback.call(elements[key], key, elements[key]) === false) return elements
			}
			return elements
		},
		map:function(elements, callback){
			var value, values = [], i, key
			if (this.likeArray(elements))
			for (i = 0; i < elements.length; i++) {
				value = callback(elements[i], i)
				if (value != null) values.push(value)
			}
			else
			for (key in elements) {
				value = callback(elements[key], key)
				if (value != null) values.push(value)
			}
			return values.length > 0 ? WCJ.fn.concat.apply([], values) : values;
		},
		matches:function(element, selector){
			if (!selector || !element || element.nodeType !== 1) return false;
		    var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
		                          element.oMatchesSelector || element.msMatchesSelector || element.matchesSelector;
		    if (matchesSelector) return matchesSelector.call(element, selector);
		},
		inArray:function(elem, array, i){
			return emptyArray.indexOf.call(array, elem, i)
		},
	    sibling:function(nodes,ty){
			var ancestors = [];
			while (nodes.length > 0)
			nodes = WCJ.map(nodes, function(node){
				if ((node = node[ty]) && !WCJ.isDocument(node) && ancestors.indexOf(node) < 0)
					ancestors.push(node)
					return node
			});
			return ancestors;
	    }
	});

	//解决低版本浏览器对filter方法的支持
	if (!Array.prototype.filter){
		Array.prototype.filter = function(fun /*, thisArg */){
			"use strict";
			if (this === void 0 || this === null)
				throw new TypeError();
			var t = Object(this);
			var len = t.length >>> 0;
			if (typeof fun !== "function")
				throw new TypeError();
			var res = [];
			var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
			for (var i = 0; i < len; i++){
				if (i in t){
					var val = t[i];
					if (fun.call(thisArg, val, i, t))
					res.push(val);
				}
			}
			return res;
		};
	}
	//低版本IE对indexOf方法的支持
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
	//低版本IE对forEach方法的支持
	if (!Array.prototype.forEach) {
	    Array.prototype.forEach = function(fun /*, thisp*/){
	        var len = this.length;
	        if (typeof fun != "function")
	            throw new TypeError();
	        var thisp = arguments[1];
	        for (var i = 0; i < len; i++){
	            if (i in this)
	                fun.call(thisp, this[i], i, this);
	        }
	    };
	}

	//字符串处理
    WCJ.extend(String.prototype,{
        trim: function () {return this.replace(/(^\s*)|(\s*$)/g, "");},
        leftTrim: function () {return this.replace(/(^\s*)/g, "");}
    })
	window.WCJ = window.$$ = WCJ;
})(window);<commit_msg>nextAll:获取对此对象【下】所有兄弟对象(可以带上滤选择器)<commit_after>;(function(window, undefined) {
	"use strict";
	var ess,emptyArray = [],slice = emptyArray.slice,filter = emptyArray.filter,elementTypes = [1, 9, 11],
		WCJ = (function(){
		var WCJ = function( selector ) {
		    return new WCJ.fn.init(selector);
		};
		WCJ.fn = WCJ.prototype = {
			init:function( selector ){
				var dom ;
    			if (!selector)
    				dom = emptyArray,dom.selector = selector || '',dom.__proto__ = WCJ.fn.init.prototype;
    			else if (WCJ.isFunction(selector)) return WCJ(document).ready(selector)
    			else {
    				if (WCJ.isArray(selector))
    					dom = selector;
				    else if (WCJ.isObject(selector))
				    	dom = [selector], selector = null
	                else if (elementTypes.indexOf(selector.nodeType) >= 0 || selector === window)
	                	dom = [selector], selector = null;
	                else dom = (function(){
				        var found;
				        return (document && /^#([\w-]+)$/.test(selector))?
				        ((found = document.getElementById(RegExp.$1)) ? [found] : emptyArray ):
					    slice.call(
						    /^\.([\w-]+)$/.test(selector) ? document.getElementsByClassName(RegExp.$1) :
						    /^[\w-]+$/.test(selector) ? document.getElementsByTagName(selector) :
						    document.querySelectorAll(selector)
					    );
					})();
					dom = dom || emptyArray;
					dom.__proto__ = WCJ.fn.init.prototype;
					dom.selector = selector || '';
    			}
    			return dom;
			},
			size:function(){return this.length;}
		}
		WCJ.fn.init.prototype = WCJ.fn;
        WCJ.extend = WCJ.fn.extend = function () {
            var options, name, src, copy,
			target = arguments[0],
			i = 1,
			length = arguments.length,
			deep = false;
            //处理深拷贝的情况
            if (typeof (target) === "boolean") {
                deep = target;
                target = arguments[1] || {};
                i = 2;
            }
            //处理时，目标是一个字符串或（深拷贝可能的情况下）的东西
            if (typeof (target) !== "object" && !WCJ.isFunction(target)) {
                target = {};
            }
            //扩展WCJ的本身，如果只有一个参数传递
            if (length === i) {
                target = this;
                --i;
            }
            for (; i < length; i++) {
                if ((options = arguments[i]) != null) {
                    for (name in options) {
                        src = target[name];
                        copy = options[name];
                        if (target === copy) {
                            continue;
                        }
                        if (copy !== undefined) {
                            target[name] = copy;
                        }
                    }
                }
            }
            return target;
        };
		return WCJ;
	})();

	WCJ.fn.extend({
		forEach: emptyArray.forEach,
		concat: emptyArray.concat,
		ready: function(callback){
			if (/complete|loaded|interactive/.test(document.readyState) && document.body) callback(WCJ)
			else document.addEventListener('DOMContentLoaded', function(){callback(WCJ) }, false)
			return this
		},
	    each: function(callback){
	      this.forEach(function(el, idx){ callback.call(el, idx, el) });
	      return this;
	    },
	    map: function(fn){
	    	return WCJ(WCJ.map(this, function(el, i){ return fn.call(el, i, el) }));
	    },
	    get: function(index){
	      return index === undefined ? slice.call(this) : this[index >= 0 ? index : index + this.length];
	    },
	    empty: function(){ return this.each(function(){ this.innerHTML = '' }) },
	    text: function(text){
	      return text === undefined ?
	        (this.length > 0 ? this[0].textContent : null) :
	        this.each(function(){ this.textContent = text });
	    },
        bind: function(type, func) {
			this.each(function(){
				if (this.addEventListener) this.addEventListener(type, func, false);
				else if (this.attachEvent) this.attachEvent("on" + type, func);
				else this["on" + type] = func;
			})
			return this;
		},
		unbind:function(type, func) {
			this.each(function(ele,obj){
				if (this.removeEventListener) this.removeEventListener(type, func, false);
				else if (this[i].detachEvent) this.detachEvent("on" + type, func);
				else this["on" + type] = null;
			})
			return this;
		},
		filter:function(selector){
			return WCJ(filter.call(this, function(element){
        		return WCJ.matches(element, selector)
		    }))
		},
		pluck: function(property){ return WCJ.map(this, function(el){ return el[property] })},
		parent: function(){
			var arr=this.pluck('parentNode');
			return filter.call(arr, function(item, idx){
				return arr.indexOf(item) == idx
			});
		},
		parents: function(selector){
			var ancestors=WCJ.sibling(this,'parentNode');
    		return selector == null ? WCJ(ancestors) : WCJ(ancestors).filter(selector);
		},
		prev: function(selector){
			return WCJ(this.pluck('previousElementSibling')).filter(selector || '*')
		},
		next: function(selector){
			return WCJ(this.pluck('nextElementSibling')).filter(selector || '*')
		},
        nextAll: function (selector) {
      		return WCJ(WCJ.sibling(this,'nextElementSibling')).filter(selector || '*');
        }
	});

	WCJ.extend({
		isDocument:function (obj) { return obj = obj ? obj != null && obj.nodeType ? obj.nodeType == obj.DOCUMENT_NODE : false : undefined;},
		isFunction:function (value) { return ({}).toString.call(value) == "[object Function]" },
		isObject:function (value) { return value instanceof Object },
		isArray:function (value) { return value instanceof Array },
		likeArray:function (obj) { return typeof obj.length == 'number' },
        type: function (obj) {
            switch (obj) {
                case null: return "Null";
                case (void 0): return "Undefined";
            }
            var type = typeof (obj);
            switch (type) {
                case 'boolean': return "Boolean";
                case 'number': return "Number";
                case 'string': return "String";
                case 'function': return "Function";
            }
            return "Object";
        },
        error:function(msg) {throw msg;},
        each:function(elements, callback){
			var i, key
			if (this.likeArray(elements)) {
				for (i = 0; i < elements.length; i++)
					if (callback.call(elements[i], i, elements[i]) === false) return elements
				} else {
				for (key in elements)
					if (callback.call(elements[key], key, elements[key]) === false) return elements
			}
			return elements
		},
		map:function(elements, callback){
			var value, values = [], i, key
			if (this.likeArray(elements))
			for (i = 0; i < elements.length; i++) {
				value = callback(elements[i], i)
				if (value != null) values.push(value)
			}
			else
			for (key in elements) {
				value = callback(elements[key], key)
				if (value != null) values.push(value)
			}
			return values.length > 0 ? WCJ.fn.concat.apply([], values) : values;
		},
		matches:function(element, selector){
			if (!selector || !element || element.nodeType !== 1) return false;
		    var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
		                          element.oMatchesSelector || element.msMatchesSelector || element.matchesSelector;
		    if (matchesSelector) return matchesSelector.call(element, selector);
		},
		inArray:function(elem, array, i){
			return emptyArray.indexOf.call(array, elem, i)
		},
	    sibling:function(nodes,ty){
			var ancestors = [];
			while (nodes.length > 0)
			nodes = WCJ.map(nodes, function(node){
				if ((node = node[ty]) && !WCJ.isDocument(node) && ancestors.indexOf(node) < 0)
					ancestors.push(node)
					return node
			});
			return ancestors;
	    }
	});

	//解决低版本浏览器对filter方法的支持
	if (!Array.prototype.filter){
		Array.prototype.filter = function(fun /*, thisArg */){
			"use strict";
			if (this === void 0 || this === null)
				throw new TypeError();
			var t = Object(this);
			var len = t.length >>> 0;
			if (typeof fun !== "function")
				throw new TypeError();
			var res = [];
			var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
			for (var i = 0; i < len; i++){
				if (i in t){
					var val = t[i];
					if (fun.call(thisArg, val, i, t))
					res.push(val);
				}
			}
			return res;
		};
	}
	//低版本IE对indexOf方法的支持
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
	//低版本IE对forEach方法的支持
	if (!Array.prototype.forEach) {
	    Array.prototype.forEach = function(fun /*, thisp*/){
	        var len = this.length;
	        if (typeof fun != "function")
	            throw new TypeError();
	        var thisp = arguments[1];
	        for (var i = 0; i < len; i++){
	            if (i in this)
	                fun.call(thisp, this[i], i, this);
	        }
	    };
	}

	//字符串处理
    WCJ.extend(String.prototype,{
        trim: function () {return this.replace(/(^\s*)|(\s*$)/g, "");},
        leftTrim: function () {return this.replace(/(^\s*)/g, "");}
    })
	window.WCJ = window.$$ = WCJ;
})(window);<|endoftext|>


<commit_before>// Load modules

var expect = require('chai').expect;
var Hapi = require('../../lib/hapi');
var S = Hapi.Types.String;

var _routeTemplate = '{{#each routes}}{{this.method}}|{{/each}}';
var _indexTemplate = '{{#each routes}}{{this.path}}|{{/each}}';
var _server = new Hapi.Server('0.0.0.0', 8083, { name: 'test', docs: { routeTemplate: _routeTemplate, indexTemplate: _indexTemplate }});
var _serverUrl = 'http://127.0.0.1:8083';

function setupServer(done) {
    var handler = function(request) {
        request.reply('ok');
    };

    _server.addRoutes([
        { method: 'GET', path: '/test', config: { handler: handler, query: { param1: S().required() } } },
        { method: 'POST', path: '/test', config: { handler: handler, query: { param2: S() } } }
    ]);

    _server.start();
    done();
}

function teardownServer(done) {
    _server.stop();
    done();
}

function makeRequest(path, callback) {
    var next = function(res) {
      return callback(res.result);
    };

    _server.inject({
        method: 'get',
        url: _serverUrl + path
    }, next);
}

describe('Documentation generator', function() {
    before(setupServer);
    after(teardownServer);

    it('shows template when correct path is provided', function(done) {
        makeRequest('/docs?path=/test', function(res) {
            expect(res).to.equal('GET|POST|');
            done();
        });
    });

    it('has a Not Found response when wrong path is provided', function(done) {
        makeRequest('/docs?path=blah', function(res) {
            expect(res.error).to.equal('Not Found');
            done();
        });
    });

    it('displays the index if no path is provided', function(done) {
        makeRequest('/docs', function(res) {
            expect(res).to.equal('/test|/test|');
            done();
        });
    });

    it('the index does\'t have the docs endpoint listed', function(done) {
        makeRequest('/docs', function(res) {
            expect(res).to.not.contain('/docs');
            done();
        });
    });
});<commit_msg>Adding authentication: false to make authentication explicitly disabled<commit_after>// Load modules

var expect = require('chai').expect;
var Hapi = require('../../lib/hapi');
var S = Hapi.Types.String;

var _routeTemplate = '{{#each routes}}{{this.method}}|{{/each}}';
var _indexTemplate = '{{#each routes}}{{this.path}}|{{/each}}';
var _server = new Hapi.Server('0.0.0.0', 8083, { name: 'test', authentication: false, docs: { routeTemplate: _routeTemplate, indexTemplate: _indexTemplate }});
var _serverUrl = 'http://127.0.0.1:8083';

function setupServer(done) {
    var handler = function(request) {
        request.reply('ok');
    };

    _server.addRoutes([
        { method: 'GET', path: '/test', config: { handler: handler, query: { param1: S().required() } } },
        { method: 'POST', path: '/test', config: { handler: handler, query: { param2: S() } } }
    ]);

    _server.start();
    done();
}

function teardownServer(done) {
    _server.stop();
    done();
}

function makeRequest(path, callback) {
    var next = function(res) {
      return callback(res.result);
    };

    _server.inject({
        method: 'get',
        url: _serverUrl + path
    }, next);
}

describe('Documentation generator', function() {
    before(setupServer);
    after(teardownServer);

    it('shows template when correct path is provided', function(done) {
        makeRequest('/docs?path=/test', function(res) {
            expect(res).to.equal('GET|POST|');
            done();
        });
    });

    it('has a Not Found response when wrong path is provided', function(done) {
        makeRequest('/docs?path=blah', function(res) {
            expect(res.error).to.equal('Not Found');
            done();
        });
    });

    it('displays the index if no path is provided', function(done) {
        makeRequest('/docs', function(res) {
            expect(res).to.equal('/test|/test|');
            done();
        });
    });

    it('the index does\'t have the docs endpoint listed', function(done) {
        makeRequest('/docs', function(res) {
            expect(res).to.not.contain('/docs');
            done();
        });
    });
});<|endoftext|>


<commit_before>/**
 * Created by GUY on 2015/6/26.
 */

BI.Label = BI.inherit(BI.AbstractLabel, {

    props: {
        baseCls: "bi-label",
        py: "",
        keyword: ""
    },

    _createJson: function () {
        var o = this.options;
        return {
            type: "bi.text",
            textAlign: o.textAlign,
            whiteSpace: o.whiteSpace,
            lineHeight: o.textHeight,
            text: o.text,
            value: o.value,
            py: o.py,
            keyword: o.keyword,
            highLight: o.highLight
        };
    },

    doRedMark: function () {
        this.text.doRedMark.apply(this.text, arguments);
    },

    unRedMark: function () {
        this.text.unRedMark.apply(this.text, arguments);
    }
});

BI.shortcut("bi.label", BI.Label);<commit_msg>bugfix<commit_after>/**
 * Created by GUY on 2015/6/26.
 */

BI.Label = BI.inherit(BI.AbstractLabel, {

    props: {
        baseCls: "bi-label",
        py: "",
        keyword: ""
    },

    doRedMark: function () {
        this.text.doRedMark.apply(this.text, arguments);
    },

    unRedMark: function () {
        this.text.unRedMark.apply(this.text, arguments);
    }
});

BI.shortcut("bi.label", BI.Label);
<|endoftext|>


<commit_before>var fs = require('fs');

module.exports = function(config) {

  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.');
    process.exit(1);
  }

  var customLaunchers = {
    sl_chrome: {
      base: 'SauceLabs',
      browserName: 'chrome',
      platform: 'Windows 7',
      version: '35'
    },
    sl_firefox: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '30'
    },
    sl_ios_safari: {
      base: 'SauceLabs',
      browserName: 'iphone',
      platform: 'OS X 10.9',
      version: '7.1'
    },
    sl_ie_11: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 8.1',
      version: '11'
    }
  };

  config.set({

    basePath: '',

    frameworks: ['mocha', 'chai', 'effroi', 'phantomjs-shim'],

    files: [
      'html/**/*.html',
      'lib/**/*.js',
      'specs/**/*.js'
    ],

    exclude: [
      '**/*.swp'
    ],

    preprocessors: {
      'html/**/*.html' : 'html2js'
    },

    reporters: ['mocha', 'saucelabs'],

    port: 9876,

    colors: true,

    logLevel: config.LOG_DEBUG,

    sauceLabs: {
      testName: 'sDomQuery test',
      startConnect: false,
      connectOptions: {
        port: 5757,
        logfile: 'sauce_connect.log'
      }
    },
    captureTimeout: 120000,
    customLaunchers: customLaunchers,
    browsers: Object.keys(customLaunchers),

    singleRun: true

  });
};
<commit_msg>Test sauce with travis<commit_after>var fs = require('fs');

module.exports = function(config) {

  if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
    console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.');
    process.exit(1);
  }

  var customLaunchers = {
    sl_chrome: {
      base: 'SauceLabs',
      browserName: 'chrome',
      platform: 'Windows 7',
      version: '35'
    },
    sl_firefox: {
      base: 'SauceLabs',
      browserName: 'firefox',
      version: '30'
    },
    sl_ios_safari: {
      base: 'SauceLabs',
      browserName: 'iphone',
      platform: 'OS X 10.9',
      version: '7.1'
    },
    sl_ie_11: {
      base: 'SauceLabs',
      browserName: 'internet explorer',
      platform: 'Windows 8.1',
      version: '11'
    }
  };

  config.set({

    basePath: '',

    frameworks: ['mocha', 'chai', 'effroi', 'phantomjs-shim'],

    files: [
      'html/**/*.html',
      'lib/**/*.js',
      'specs/**/*.js'
    ],

    exclude: [
      '**/*.swp'
    ],

    preprocessors: {
      'html/**/*.html' : 'html2js'
    },

    reporters: ['mocha', 'saucelabs'],

    port: 9876,

    colors: true,

    logLevel: config.LOG_DEBUG,

    sauceLabs: {
      testName: 'sDomQuery test',
      //startConnect: false,
      connectOptions: {
        port: 5757,
        logfile: 'sauce_connect.log'
      }
    },
    captureTimeout: 120000,
    customLaunchers: customLaunchers,
    browsers: Object.keys(customLaunchers),

    singleRun: true

  });
};
<|endoftext|>


<commit_before>$(document).ready(function(){

	$(".edit-payments").live("click", function(){
		my_id = this.id.split("_");
		my_tour = my_id[1];
		my_payer = my_id[2];
		form_data = {
				tour_id: my_tour,
				payer_id: my_payer,
				ajax: 1
		};
		$.ajax({
			type: "get",
			url: base_url + "payment/view_list",
			data: form_data,
			success: function(data){
				show_popup("List of Payments",data, "auto");
			}
		});
	});

	$(".add-payment").live("click", function(){
		my_id = this.id.split("_");
		my_tour = my_id[1];
		my_payer = my_id[2];
		form_data = {
			tour_id: my_tour,
			payer_id: my_payer,
			ajax: 1
		};

		$.ajax({
			type: "get",
			data: form_data,
			url: base_url + "payment/create",
			success: function(data){
				$("#payment-list tbody").append(data);
			}
		});
	});

	$(".insert-payment").live("click",function(){
		my_id = this.id.split("_");
		my_tour = my_id[1];
		my_payer = my_id[2];
		form_data = {
				tour_id: my_tour,
				payer_id: my_payer,
				amount: $("#amount").val(),
				receipt_date: $("#receipt_date").val(),
				ajax: 1
		};
		$.ajax({
			type: "post",
			data: form_data,
			url: base_url + "payment/insert",
			success: function(data){
				$("#payment-list-box").html(data);
				set_payment_total();
			}
		});
	});

	$(".delete-payment").live("click",function(){
		ask = confirm("Are you sure you want to delete this payment? This cannot be undone!");
		if(ask){
			again = confirm("Are you absolutely sure?");
			if(again){

				my_id = this.id.split("_")[1];

				form_data = {
						id: my_id
				};
				$.ajax({
						type: "post",
						url: base_url + "payment/delete",
						data: form_data,
						success: function(data){
							$("#payment-row_" + my_id).remove();
							$("#payment-list-box").html(data);
							set_payment_total();
						}
			});
			}
		}
	});

});

function set_payment_total(){
	total = $("#total-paid").val();
	$("#amt_paid").val(total);
}
<commit_msg>payment auto adjustments: issue #9 in tracker<commit_after>$(document).ready(function(){

	$(".edit-payments").live("click", function(){
		my_id = this.id.split("_");
		my_tour = my_id[1];
		my_payer = my_id[2];
		form_data = {
				tour_id: my_tour,
				payer_id: my_payer,
				ajax: 1
		};
		$.ajax({
			type: "get",
			url: base_url + "payment/view_list",
			data: form_data,
			success: function(data){
				show_popup("List of Payments",data, "auto");
			}
		});
	});

	$(".add-payment").live("click", function(){
		my_id = this.id.split("_");
		my_tour = my_id[1];
		my_payer = my_id[2];
		form_data = {
			tour_id: my_tour,
			payer_id: my_payer,
			ajax: 1
		};

		$.ajax({
			type: "get",
			data: form_data,
			url: base_url + "payment/create",
			success: function(data){
				$("#payment-list tbody").append(data);
			}
		});
	});

	$(".insert-payment").live("click",function(){
		my_id = this.id.split("_");
		my_tour = my_id[1];
		my_payer = my_id[2];
		form_data = {
				tour_id: my_tour,
				payer_id: my_payer,
				amount: $("#amount").val(),
				receipt_date: $("#receipt_date").val(),
				ajax: 1
		};
		$.ajax({
			type: "post",
			data: form_data,
			url: base_url + "payment/insert",
			success: function(data){
				$("#payment-list-box").html(data);
				set_payment_total();
			}
		});
	});

	$(".delete-payment").live("click",function(){
		ask = confirm("Are you sure you want to delete this payment? This cannot be undone!");
		if(ask){
			again = confirm("Are you absolutely sure?");
			if(again){

				my_id = this.id.split("_")[1];

				form_data = {
						id: my_id
				};
				$.ajax({
						type: "post",
						url: base_url + "payment/delete",
						data: form_data,
						success: function(data){
							$("#payment-row_" + my_id).remove();
							$("#payment-list-box").html(data);
							set_payment_total();
						}
			});
			}
		}
	});

});

function set_payment_total(){
	total = $("#total-paid").val();
	$("#amt_paid").val(total);
	calculate_cost(1);
}
<|endoftext|>


<commit_before>//loading-screen
$(window).load(function()
{

    $(".loading-screen .main").fadeOut(2000,
    function()
    {
        $(this).parent().fadeOut(1000,
        function()
        {

            $("body").css("overflow","auto");

        $(this).remove();

        });
    });
});<commit_msg>Delete plugins.js<commit_after><|endoftext|>


<commit_before>var dotVoteCardButtonCallback = function (t) {
    var currentMember = {};
    return t.member('all')
    .then(function(member) {
        currentMember = member;
        return t.get('card', 'shared', UMTrello.constants.data.votes, {});
    })
    .then(function(currentVotes) {
        if(currentVotes === 0) {
            currentVotes = {};
        }
        if(!currentVotes.hasOwnProperty(currentMember.id) || currentVotes === 0) {
            currentVotes[currentMember.id] = 0;
        }
        currentVotes[currentMember.id]++;
        return t.set('card', 'shared', UMTrello.constants.data.votes, currentVotes);
    })
    .catch(function(err) {
        console.log("Voting Error");
        console.dir(err);
    });
};

var sortCardsInListPopup = function (t) {
    return t.popup({
        title: 'Select List for Sorting',
        url: './sort-list.html',
        height: 200
    })
};

var clearListVotesPopup = function (t) {
    return t.popup({
        title: 'Select List to Clear Votes',
        url: './clear-votes.html',
        height: 200
    })
};

var clearIDSPopup = function (t) {
    return t.popup({
        title: 'Select List to Clear IDS Data',
        url: './clear-ids.html',
        height: 200
    })
};

var boardButtonCallback = function (t) {
    return t.popup({
        title: 'EOS Tools Actions',
        items: [
            {
                text: 'Clear Votes on a List',
                callback: clearListVotesPopup
            },
            {
                text: 'Clear IDS Info on a List',
                callback: clearIDSPopup
            }
        ]
    });
};

var idsCallback = function (t) {
    return t.popup({
        title: 'IDS Discovery',
        url: './ids.html',
        height: 200
    })
};

var getCardBadges = function (t) {
    return t.get('card','shared', UMTrello.constants.data.votes, {})
    .then(function(dotVotes) {
        var votes = 0;
        for(var key in dotVotes) {
            votes += dotVotes[key];
        }
        if(votes > 0) {
            return [{
                text: votes,
                icon: GREY_DOT_ICON
            }];
        }
        return [];
    })
    .catch(function(err) {
        console.log("Card Badge Error");
        console.dir(err);
    });
};

var getMemberFirstName = function(id, members) {
    var member = members.find(function(element) {
        return element.id === id;
    });
    if(member) {
        return UMTrello.getMembersFirstName(member);
    }
    return "";
};

var getCardDetailBadges = function(t, members) {
    return t.get('card', 'shared', UMTrello.constants.data.votes, {})
    .then(function(dotVotes) {
        var cards = [];
        for(var key in dotVotes) {
            if(dotVotes[key] > 0) {
                var description = dotVotes[key] + " votes";
                var memberName = getMemberFirstName(key, members);
                cards.push({
                    title: memberName,
                    text: description,
                    icon: GREY_DOT_ICON
                });
            }
        }
        return cards;
    })
    .catch(function(err) {
       console.log("Error When Creating Details Cards.");
       console.dir(err);
    });
};

var isValidPersonData = function(ids, value) {
    if(!ids.hasOwnProperty(value)) {
        return false;
    }

    if(ids[value] === undefined) {
        return false;
    }

    if(ids[value] === 0) {
        return false;
    }

    if(ids[value] === '0') {
        return false;
    }

    return true;
};

var getIDSBadges = function(t, members, isDetail) {
    return t.get('card', 'shared', UMTrello.constants.data.ids, {})
    .then(function(ids) {
        var cards = [];

        if(isValidPersonData(ids, 'reporter')) {
            var name = UMTrello.getMembersNameFromID(members, ids.reporter);
            cards.push({
                title: 'IDS Reporter:',
                text: (isDetail) ? name : 'Reporter: ' + name,
                icon: null,
                callback: idsCallback
            });
        }
        if(isValidPersonData(ids, 'assignee')) {
            var name = UMTrello.getMembersNameFromID(members, ids.reporter);
            cards.push({
                title: 'IDS Assignee:',
                text: (isDetail) ? name : 'Assignee: ' + name,
                icon: null,
                callback: idsCallback
            });
        }
        if(ids.hasOwnProperty('what') && ids.what !== undefined && ids.what.trim() !== '') {
            cards.push({
                title: 'IDS Issue:',
                text: (isDetail) ? ids.what : 'Issue: ' + ids.what,
                icon: null,
                callback: idsCallback
            });
        }
        if(ids.hasOwnProperty('solution') && ids.solution !== undefined && ids.solution.trim() !== '') {
            cards.push({
                title: 'IDS Solution:',
                text: (isDetail) ? ids.solution : 'Solution: ' + ids.solution,
                icon: null,
                callback: idsCallback
            });
        }
        return cards;
    })
    .catch(function(err) {
        console.log("Error creating IDS cards");
        console.dir(err);
    })
};

var DOT_ICON = './images/dot.png';
var GREY_DOT_ICON = './images/grey-dot.png';
var IDS_ICON = './images/ids.png';

var _members;
var getMembers = function(t) {
    return new Promise(function(resolve, reject) {
        if(_members !== undefined) {
            resolve(_members);
        }
        return t.board('members')
        .then(function(board) {
            _members = board.members;
            resolve(_members);
        })
        .catch(function(err) {
            reject(err);
        });
    });

};

TrelloPowerUp.initialize({
    'board-buttons': function (t, options) {
        return [{
            icon: DOT_ICON,
            text: 'EOS Tools',
            callback: boardButtonCallback
        }];
    },
    'card-buttons': function (t, options) {
        return [{
            icon: GREY_DOT_ICON,
            text: 'Dot Vote',
            callback: dotVoteCardButtonCallback
        }, {
            icon: IDS_ICON,
            text:  'IDS',
            callback: idsCallback
        }];
    },
    'card-badges': function (t, options) {
        return getMembers(t)
        .then(function(members) {
            return Promise.all([getCardBadges(t), getIDSBadges(t, members, false)])
            .spread(function(dotVotingBadges, idsBadges) {
                var output = dotVotingBadges.concat(idsBadges);
                return output;
            });
        })
        .catch(function(err) {
            console.log("Error on Card Badges");
            console.dir(err);
        });
    },
    'card-detail-badges': function (t, options) {
        return getMembers(t)
        .then(function(members) {
            return Promise.all([getCardDetailBadges(t, members), getIDSBadges(t, members, true)])
            .spread(function (dotVotingBadges, idsBadges) {
                var output = dotVotingBadges.concat(idsBadges);
                return output;
            });
        })
        .catch(function(err) {
            console.log("Error on Detail Card Badges");
            console.dir(err);
        });
    }
});

<commit_msg>Updating assignee for card badge<commit_after>var dotVoteCardButtonCallback = function (t) {
    var currentMember = {};
    return t.member('all')
    .then(function(member) {
        currentMember = member;
        return t.get('card', 'shared', UMTrello.constants.data.votes, {});
    })
    .then(function(currentVotes) {
        if(currentVotes === 0) {
            currentVotes = {};
        }
        if(!currentVotes.hasOwnProperty(currentMember.id) || currentVotes === 0) {
            currentVotes[currentMember.id] = 0;
        }
        currentVotes[currentMember.id]++;
        return t.set('card', 'shared', UMTrello.constants.data.votes, currentVotes);
    })
    .catch(function(err) {
        console.log("Voting Error");
        console.dir(err);
    });
};

var sortCardsInListPopup = function (t) {
    return t.popup({
        title: 'Select List for Sorting',
        url: './sort-list.html',
        height: 200
    })
};

var clearListVotesPopup = function (t) {
    return t.popup({
        title: 'Select List to Clear Votes',
        url: './clear-votes.html',
        height: 200
    })
};

var clearIDSPopup = function (t) {
    return t.popup({
        title: 'Select List to Clear IDS Data',
        url: './clear-ids.html',
        height: 200
    })
};

var boardButtonCallback = function (t) {
    return t.popup({
        title: 'EOS Tools Actions',
        items: [
            {
                text: 'Clear Votes on a List',
                callback: clearListVotesPopup
            },
            {
                text: 'Clear IDS Info on a List',
                callback: clearIDSPopup
            }
        ]
    });
};

var idsCallback = function (t) {
    return t.popup({
        title: 'IDS Discovery',
        url: './ids.html',
        height: 200
    })
};

var getCardBadges = function (t) {
    return t.get('card','shared', UMTrello.constants.data.votes, {})
    .then(function(dotVotes) {
        var votes = 0;
        for(var key in dotVotes) {
            votes += dotVotes[key];
        }
        if(votes > 0) {
            return [{
                text: votes,
                icon: GREY_DOT_ICON
            }];
        }
        return [];
    })
    .catch(function(err) {
        console.log("Card Badge Error");
        console.dir(err);
    });
};

var getMemberFirstName = function(id, members) {
    var member = members.find(function(element) {
        return element.id === id;
    });
    if(member) {
        return UMTrello.getMembersFirstName(member);
    }
    return "";
};

var getCardDetailBadges = function(t, members) {
    return t.get('card', 'shared', UMTrello.constants.data.votes, {})
    .then(function(dotVotes) {
        var cards = [];
        for(var key in dotVotes) {
            if(dotVotes[key] > 0) {
                var description = dotVotes[key] + " votes";
                var memberName = getMemberFirstName(key, members);
                cards.push({
                    title: memberName,
                    text: description,
                    icon: GREY_DOT_ICON
                });
            }
        }
        return cards;
    })
    .catch(function(err) {
       console.log("Error When Creating Details Cards.");
       console.dir(err);
    });
};

var isValidPersonData = function(ids, value) {
    if(!ids.hasOwnProperty(value)) {
        return false;
    }

    if(ids[value] === undefined) {
        return false;
    }

    if(ids[value] === 0) {
        return false;
    }

    if(ids[value] === '0') {
        return false;
    }

    return true;
};

var getIDSBadges = function(t, members, isDetail) {
    return t.get('card', 'shared', UMTrello.constants.data.ids, {})
    .then(function(ids) {
        var cards = [];

        if(isValidPersonData(ids, 'reporter')) {
            var name = UMTrello.getMembersNameFromID(members, ids.reporter);
            cards.push({
                title: 'IDS Reporter:',
                text: (isDetail) ? name : 'Reporter: ' + name,
                icon: null,
                callback: idsCallback
            });
        }
        if(isValidPersonData(ids, 'assignee')) {
            var name = UMTrello.getMembersNameFromID(members, ids.assignee);
            cards.push({
                title: 'IDS Assignee:',
                text: (isDetail) ? name : 'Assignee: ' + name,
                icon: null,
                callback: idsCallback
            });
        }
        if(ids.hasOwnProperty('what') && ids.what !== undefined && ids.what.trim() !== '') {
            cards.push({
                title: 'IDS Issue:',
                text: (isDetail) ? ids.what : 'Issue: ' + ids.what,
                icon: null,
                callback: idsCallback
            });
        }
        if(ids.hasOwnProperty('solution') && ids.solution !== undefined && ids.solution.trim() !== '') {
            cards.push({
                title: 'IDS Solution:',
                text: (isDetail) ? ids.solution : 'Solution: ' + ids.solution,
                icon: null,
                callback: idsCallback
            });
        }
        return cards;
    })
    .catch(function(err) {
        console.log("Error creating IDS cards");
        console.dir(err);
    })
};

var DOT_ICON = './images/dot.png';
var GREY_DOT_ICON = './images/grey-dot.png';
var IDS_ICON = './images/ids.png';

var _members;
var getMembers = function(t) {
    return new Promise(function(resolve, reject) {
        if(_members !== undefined) {
            resolve(_members);
        }
        return t.board('members')
        .then(function(board) {
            _members = board.members;
            resolve(_members);
        })
        .catch(function(err) {
            reject(err);
        });
    });

};

TrelloPowerUp.initialize({
    'board-buttons': function (t, options) {
        return [{
            icon: DOT_ICON,
            text: 'EOS Tools',
            callback: boardButtonCallback
        }];
    },
    'card-buttons': function (t, options) {
        return [{
            icon: GREY_DOT_ICON,
            text: 'Dot Vote',
            callback: dotVoteCardButtonCallback
        }, {
            icon: IDS_ICON,
            text:  'IDS',
            callback: idsCallback
        }];
    },
    'card-badges': function (t, options) {
        return getMembers(t)
        .then(function(members) {
            return Promise.all([getCardBadges(t), getIDSBadges(t, members, false)])
            .spread(function(dotVotingBadges, idsBadges) {
                var output = dotVotingBadges.concat(idsBadges);
                return output;
            });
        })
        .catch(function(err) {
            console.log("Error on Card Badges");
            console.dir(err);
        });
    },
    'card-detail-badges': function (t, options) {
        return getMembers(t)
        .then(function(members) {
            return Promise.all([getCardDetailBadges(t, members), getIDSBadges(t, members, true)])
            .spread(function (dotVotingBadges, idsBadges) {
                var output = dotVotingBadges.concat(idsBadges);
                return output;
            });
        })
        .catch(function(err) {
            console.log("Error on Detail Card Badges");
            console.dir(err);
        });
    }
});

<|endoftext|>


<commit_before>(function ($) {
    "use strict";

    var rbvost = {

        siteurl:         window.location.href,
        templateurl:     window.location.href + "/wp-content/themes/rbvost/templates/",
        currentView:     "target",
        currentYear:     new Date().getFullYear(),
        dateRange:       { years: [] },
        cache:           {},
        calendar:        undefined,
        isotopeEl:       ".campaigns-container",
        // defaut setting to show all
        // will update through calendarShouldFilter()
        calendarFilters: {
            targets: "*",
            campaigns: "*",
            regions: "*"
        },

        init: function () {
            this.checkLoginError();
            this.setAppHeight();
            this.bindUIActions();

            // only bother to make API calls if we're logged in
            if ($("body").hasClass("logged-in")) {
                rbvost.buildMenu();
                rbvost.getContent();
            }

            // this seems to fix some bizare bug with the webfont thinking it's loaded even when it hasn't
            // it causes a refresh and seems to then make it load properly
            $("body").css({ "text-rendering" : "auto" });
        },

        // -----------------------------------------------------------------------------------------
        // API Requests
        // -----------------------------------------------------------------------------------------

        buildMenu: function () {
            // get list of years for year selector menu
            $.ajax({
                url: rbvost.siteurl + "?json=get_category_index"
            })
            .done(function (data) {
                _.each(data.categories, function (category) {
                    // if category has no parent, it's a year
                    if (!category.parent) {

                        // create period object
                        var period = {};
                        // add year to object
                        period.year = category.slug;
                        // if this year is the current calendar year, mark it as so
                        if (category.slug == rbvost.currentYear) {
                            period.isCurrent = true;
                        }
                        // push results to hoisted array
                        rbvost.dateRange.years.push(period);
                    }
                });
                // now we have a daterange array, we can render the menu
                rbvost.renderMenu();
            })
            .fail(function () {
                alert("Sorry, there is currently an error fetching the date range.");
            });
        },

        getContent: function () {
            // get all content for current year
            $.ajax({
                url: rbvost.siteurl + "?json=get_category_posts&slug=" + rbvost.currentYear
            })
            .done(function (data) {
                rbvost.cache = data;
                rbvost.router(rbvost.currentView);
            })
            .fail(function () {
                alert("Sorry, there is currently an error fetching the content.");
            });
        },

        getUniqueTargets: function () {
            var data = rbvost.cache;
            var uniqueTargets = { targets: [] };

            // for each post (year), go through all categories and find all sub categories (targets)
            // then check if this already exists in our unique collection
            // if not, push it in
            _.each(data.posts, function (post) {
                _.each(post.categories, function (category) {
                    if (category.parent) {

                        var exists = _.findWhere(uniqueTargets.targets, { slug: category.slug });

                        if (!exists) {
                            var target = {};
                            target.slug = category.slug;
                            target.title = category.title;
                            target.description = category.description;

                            uniqueTargets.targets.push(target);
                        }

                    }
                });
            });

            return uniqueTargets;
        },

        // -----------------------------------------------------------------------------------------
        // Common Functions
        // -----------------------------------------------------------------------------------------

        bindUIActions: function () {
            // App Menu
            $("[data-navigate]").on("click", function (e) { rbvost.navigate(e); });
            $("body").on("click", ".menu-item-dropdown", function (e) { rbvost.dropdownShouldToggle(e); });
            $("body").on("click", ".menu-item-dropdown li", function (e) { rbvost.yearShouldChange(e); });

            // Campaigns View
            $("body").on("click", ".campaign-filters button", function (e) { rbvost.campaignsShouldFilter(e); });
            $("body").on("click", ".tooltip", function (e) { rbvost.tooltipShouldToggle(e); });

            // Calendar View
            $("body").on("click", ".calendar-filters button", function (e) { rbvost.calendarShouldFilter(e); });
            $("body").on("click", ".clndr .day.event", function (e) { rbvost.eventPopupShouldToggle(e); });
            $("body").on("click", ".clndr .close-popup", function (e) { rbvost.eventPopupShouldClose(e); });
            $("body").on("click", ".clndr .read-more", function (e) { rbvost.calendarOverlayShouldRender(e); });
            $("body").on("click", ".close-modal", function () { rbvost.modalShouldClose(); });
        },

        router: function (view) {
            $(".switch-view").hide();

            if (view === "target") {
                rbvost.renderTargets();
            }

            if (view === "campaign") {
                rbvost.renderCampaignFilters();
                rbvost.renderCampaignList();
            }

            if (view === "calendar") {
                rbvost.renderCalendarFilters();
                rbvost.renderCalendar();
            }

            rbvost.currentView = view;
        },

        renderView: function (data, template, el, callback) {
            $.get(rbvost.templateurl + template, function (template) {
                $(el).html(
                    _.template(template, data)
                );

                $(el).fadeIn("slow");
                $("#app").css({ "background-image" : "none" });

                if (callback) { callback(); }
            });
        },

        windowResized: function () {
            // retrigger the isotope layout engine
            $(rbvost.isotopeEl).isotope("reLayout");
        },

        setAppHeight: function () {
            // set a min height minus the guessed height for redbull global header / footer
            var appHeight = $(window).height() - 286 + "px";
            $("#app").css({ "min-height" : appHeight });
        },

        navigate: function (e) {
            // Set spinner
            $("#app").css({ "background-image" : rbvost.siteurl + "/wp-content/themes/rbvost/img/ajax-loader.gif" });

            // Toggle active state in menu
            $("button[data-navigate]").removeClass("current");
            $(e.currentTarget).addClass("current");

            // Set current page and rerender
            var destination = $(e.currentTarget).data("navigate");
            rbvost.router(destination);
        },

        // -----------------------------------------------------------------------------------------
        // Login View
        // -----------------------------------------------------------------------------------------

        checkLoginError: function () {
            var querystring = window.location.href.slice(window.location.href.indexOf("?") + 1);
            if (querystring === "login-failed") {
                $(".alert").show();
            }
        },

        // -----------------------------------------------------------------------------------------
        // Menu View
        // -----------------------------------------------------------------------------------------

        renderMenu: function () {
            var data = rbvost.dateRange;
            rbvost.renderView(data, "year-selector.html", ".year-selector-view");
        },

        dropdownShouldToggle: function (e) {
            $(e.currentTarget).find(".fa").toggleClass("fa-rotate-180");
            $(e.currentTarget).find(".dropdown").slideToggle("fast");
        },

        yearShouldChange: function (e) {
            var year = $(e.currentTarget).data("value");

            // Close menu and update text
            rbvost.dropdownShouldToggle(e);
            $(".menu-item-dropdown .current-year").text(year);

            // Set spinner and it API for requested year, update cache and re-render
            $("#app").css({ "background-image" : "" });
            rbvost.currentYear = year;
            rbvost.getContent();
        },

        // -----------------------------------------------------------------------------------------
        // Targets View
        // -----------------------------------------------------------------------------------------

        renderTargets: function () {
            var data = rbvost.cache;
            var uniqueTargets = rbvost.getUniqueTargets();

            rbvost.renderView(uniqueTargets, "targets.html", ".targets-view");
        },

        // -----------------------------------------------------------------------------------------
        // Campaigns View
        // -----------------------------------------------------------------------------------------

        renderCampaignFilters: function () {
            var data = rbvost.cache;
            var uniqueTargets = rbvost.getUniqueTargets();

            rbvost.renderView(uniqueTargets, "campaign-filters.html", ".campaign-filters-view");
        },

        renderCampaignList: function () {
            var data = rbvost.cache;
            var viewData = { campaigns: [] };

            _.each(data.posts, function (post) {
                var campaign = {};

                // get target + slug
                _.each(post.categories, function (category) {
                    if (category.parent) {
                        campaign.targetName = category.title;
                        campaign.targetSlug = category.slug;
                    }
                });

                console.log(post.title);
                console.log(campaign.title);
                campaign.title = post.title;
                campaign.description = post.acf.campaign_description;
                campaign.image = post.acf.campaign_image;

                viewData.campaigns.push(campaign);
            });

            var afterRender = function () {
                $(rbvost.isotopeEl).imagesLoaded(function () {
                    $(rbvost.isotopeEl).isotope();
                });
            };

            rbvost.renderView(viewData, "campaign-list.html", ".campaign-list-view", afterRender);
        },

        campaignsShouldFilter: function (e) {
            // toggle styling
            $(e.currentTarget).siblings().removeClass("active");
            $(e.currentTarget).addClass("active");

            // hide any active tooltips
            $(".tooltip .inner").hide();

            // run the isotope filters
            var query = $(e.currentTarget).data("filter");
            $(rbvost.isotopeEl).isotope({ filter: query });
        },

        tooltipShouldToggle: function (e) {
            e.stopImmediatePropagation();
            var tooltip = $(e.currentTarget).find(".inner");

            if ($(tooltip).is(":visible")) {
                $(tooltip).hide();
            } else {
                // hide any active tooltips
                $(".tooltip .inner").hide();
                $(tooltip).show();
            }
        },

        // -----------------------------------------------------------------------------------------
        // Calendar View
        // -----------------------------------------------------------------------------------------

        renderCalendarFilters: function () {
            var data = rbvost.cache;

            var filters = {
                targets: rbvost.getUniqueTargets(),
                campaigns: [],
                regions: []
            };

            // get campaigns
            _.each(data.posts, function (post) {
                var campaign = {};
                campaign.title = post.title;
                campaign.slug = post.slug;

                filters.campaigns.push(campaign);
            });

            var getUniqueRegions = function (region) {
                var thisRegion = {};
                thisRegion.slug = region;

                if (thisRegion.slug === "national") { thisRegion.title = "National"; }
                if (thisRegion.slug === "london") { thisRegion.title = "London"; }
                if (thisRegion.slug === "north") { thisRegion.title = "North / Scotland"; }
                if (thisRegion.slug === "southwest") { thisRegion.title = "South West"; }
                if (thisRegion.slug === "midlands") { thisRegion.title = "Midlands"; }

                var exists = _.findWhere(filters.regions, { slug: thisRegion.slug });

                if (!exists) {
                    filters.regions.push(thisRegion);
                }
            };

            // get regions
            _.each(data.posts, function (post) {
                // annoyingly the API can return a string or an array for the regions list
                if (_.isArray(post.acf.region)) {
                    _.each(post.acf.region, function (region) {
                        getUniqueRegions(region);
                    });
                } else {
                    getUniqueRegions(post.acf.region);
                }
            });

            rbvost.renderView(filters, "calendar-filters.html", ".calendar-filters-view", false);
        },

        renderCalendar: function () {
            var data = rbvost.cache;
            var calendarEvents = [];

            _.each(data.posts, function (post) {
                // here we can grab stuff from the post which we can later insert into the event objects
                var campaign = post.slug;
                var region = post.acf.region;
                var target;

                // get the event target
                _.each(post.categories, function (category) {
                    if (category.parent) {
                        target = category.slug;
                    }
                });

                _.each(post.acf.events, function (event) {
                    // create event object
                    var thisEvent = {};
                    // add data to object

                    // All events are technically multi day, but we mock single day events by setting the start and end dates to be the same.
                    if (event.event_type === "Multi Day") {
                        thisEvent.startDate = event.event_start_date;
                        thisEvent.endDate = event.event_end_date;
                        thisEvent.prettyDate = moment(event.event_start_date).format("dddd Do MMMM YYYY") + " - " + moment(event.event_end_date).format("dddd Do MMMM YYYY");
                        thisEvent.prettyDateShort = moment(event.event_start_date).format("dddd Do") + " - " + moment(event.event_end_date).format("dddd Do");
                    } else {
                        thisEvent.startDate = event.event_date;
                        thisEvent.endDate = event.event_date;
                        thisEvent.prettyDate = moment(event.event_date).format("dddd Do MMMM YYYY");
                        thisEvent.prettyDateShort = moment(event.event_date).format("dddd Do");
                    }

                    // Regions might be a string or array - lets make sure they're a string
                    var regionList = region.toString().replace(",", " ");

                    thisEvent.location = event.event_location;
                    thisEvent.name = event.event_name;
                    thisEvent.campaign = campaign;
                    thisEvent.description = event.event_description;
                    thisEvent.images = event.event_images;
                    thisEvent.region = regionList;
                    thisEvent.target = target;
                    thisEvent.id = "" + (new Date().getTime()) + (Math.floor(Math.random() * 999999) + 1);
                    // push results to hoisted array
                    calendarEvents.push(thisEvent);
                });
            });

            // now we have added our unique id to each event
            // we can cache the events object so we can use it later for the event popup
            rbvost.cache.events = calendarEvents;

            // If a clndr instance already exists we can just update it
            if (rbvost.calendar) {

                rbvost.calendar.setEvents(calendarEvents);
                rbvost.calendar.setYear(rbvost.currentYear);

                $(".calendar-view").fadeIn("fast");

            // if not let's grab the template and render it out
            } else {

                $.get(rbvost.templateurl + "calendar.html", function (calendarTemplate) {
                    rbvost.calendar = $(".calendar-view").clndr({
                        template: calendarTemplate,
                        events: calendarEvents,
                        showAdjacentMonths: false,
                        multiDayEvents: {
                            startDate: "startDate",
                            endDate: "endDate"
                        },
                        lengthOfTime: {
                            months: 12,
                            startDate: rbvost.currentYear + "-01-01"
                        }
                    });

                    $(".calendar-view").fadeIn("fast");
                });

            }
        },

        calendarShouldFilter: function (e) {
            // first lets toggle the styling
            $(e.currentTarget).siblings().removeClass("active");
            $(e.currentTarget).addClass("active");

            // then we update our calendar settings object
            var type = $(e.currentTarget).data("type");
            var value = $(e.currentTarget).data("filter");
            rbvost.calendarFilters[type] = value;

            // now we can show all events, and then hide appropriate ones
            var clndr = $(".clndr");
            $(clndr).find(".day").removeClass("hidden-event");

            // loop through our filters and if they're not set to show all
            // find events that don't contain the fiter term and hide them
            _.each(rbvost.calendarFilters, function (filter) {
                if (filter !== "*") {
                    $(clndr).find(".event:not(" + filter + ")").addClass("hidden-event");
                }
            });
        },

        eventPopupShouldToggle: function (e) {
            var popup = $(e.currentTarget).find(".popup");

            if ($(popup).is(":visible")) {
                $(popup).hide();
            } else {
                // hide any active popups
                $(".clndr .popup").hide();
                $(popup).show();
            }
        },

        eventPopupShouldClose: function (e) {
            e.stopImmediatePropagation();
            $(e.currentTarget).parent().hide();
        },

        calendarOverlayShouldRender: function (e) {
            var events = rbvost.cache.events;
            var eventId = $(e.currentTarget).data("id");
            var thisEvent = { event: [] };

            thisEvent.event.push(_.findWhere(events, { id: eventId }));

            var afterRender = function () {
                $("#modal").fadeIn("fast");
                $(".flexslider").flexslider();
            };

            rbvost.renderView(thisEvent, "modal.html", ".modal-view", afterRender);
        },

        modalShouldClose: function () {
            $("#modal").fadeOut("fast");
        }

    };

    // DOM Ready
    $(function () { rbvost.init(); });
    // Window Resized (smart debounced event)
    $(window).bind("debouncedresize", function () { rbvost.windowResized(); });

} (jQuery));
<commit_msg>remove console logging<commit_after>(function ($) {
    "use strict";

    var rbvost = {

        siteurl:         window.location.href,
        templateurl:     window.location.href + "/wp-content/themes/rbvost/templates/",
        currentView:     "target",
        currentYear:     new Date().getFullYear(),
        dateRange:       { years: [] },
        cache:           {},
        calendar:        undefined,
        isotopeEl:       ".campaigns-container",
        // defaut setting to show all
        // will update through calendarShouldFilter()
        calendarFilters: {
            targets: "*",
            campaigns: "*",
            regions: "*"
        },

        init: function () {
            this.checkLoginError();
            this.setAppHeight();
            this.bindUIActions();

            // only bother to make API calls if we're logged in
            if ($("body").hasClass("logged-in")) {
                rbvost.buildMenu();
                rbvost.getContent();
            }

            // this seems to fix some bizare bug with the webfont thinking it's loaded even when it hasn't
            // it causes a refresh and seems to then make it load properly
            $("body").css({ "text-rendering" : "auto" });
        },

        // -----------------------------------------------------------------------------------------
        // API Requests
        // -----------------------------------------------------------------------------------------

        buildMenu: function () {
            // get list of years for year selector menu
            $.ajax({
                url: rbvost.siteurl + "?json=get_category_index"
            })
            .done(function (data) {
                _.each(data.categories, function (category) {
                    // if category has no parent, it's a year
                    if (!category.parent) {

                        // create period object
                        var period = {};
                        // add year to object
                        period.year = category.slug;
                        // if this year is the current calendar year, mark it as so
                        if (category.slug == rbvost.currentYear) {
                            period.isCurrent = true;
                        }
                        // push results to hoisted array
                        rbvost.dateRange.years.push(period);
                    }
                });
                // now we have a daterange array, we can render the menu
                rbvost.renderMenu();
            })
            .fail(function () {
                alert("Sorry, there is currently an error fetching the date range.");
            });
        },

        getContent: function () {
            // get all content for current year
            $.ajax({
                url: rbvost.siteurl + "?json=get_category_posts&slug=" + rbvost.currentYear
            })
            .done(function (data) {
                rbvost.cache = data;
                rbvost.router(rbvost.currentView);
            })
            .fail(function () {
                alert("Sorry, there is currently an error fetching the content.");
            });
        },

        getUniqueTargets: function () {
            var data = rbvost.cache;
            var uniqueTargets = { targets: [] };

            // for each post (year), go through all categories and find all sub categories (targets)
            // then check if this already exists in our unique collection
            // if not, push it in
            _.each(data.posts, function (post) {
                _.each(post.categories, function (category) {
                    if (category.parent) {

                        var exists = _.findWhere(uniqueTargets.targets, { slug: category.slug });

                        if (!exists) {
                            var target = {};
                            target.slug = category.slug;
                            target.title = category.title;
                            target.description = category.description;

                            uniqueTargets.targets.push(target);
                        }

                    }
                });
            });

            return uniqueTargets;
        },

        // -----------------------------------------------------------------------------------------
        // Common Functions
        // -----------------------------------------------------------------------------------------

        bindUIActions: function () {
            // App Menu
            $("[data-navigate]").on("click", function (e) { rbvost.navigate(e); });
            $("body").on("click", ".menu-item-dropdown", function (e) { rbvost.dropdownShouldToggle(e); });
            $("body").on("click", ".menu-item-dropdown li", function (e) { rbvost.yearShouldChange(e); });

            // Campaigns View
            $("body").on("click", ".campaign-filters button", function (e) { rbvost.campaignsShouldFilter(e); });
            $("body").on("click", ".tooltip", function (e) { rbvost.tooltipShouldToggle(e); });

            // Calendar View
            $("body").on("click", ".calendar-filters button", function (e) { rbvost.calendarShouldFilter(e); });
            $("body").on("click", ".clndr .day.event", function (e) { rbvost.eventPopupShouldToggle(e); });
            $("body").on("click", ".clndr .close-popup", function (e) { rbvost.eventPopupShouldClose(e); });
            $("body").on("click", ".clndr .read-more", function (e) { rbvost.calendarOverlayShouldRender(e); });
            $("body").on("click", ".close-modal", function () { rbvost.modalShouldClose(); });
        },

        router: function (view) {
            $(".switch-view").hide();

            if (view === "target") {
                rbvost.renderTargets();
            }

            if (view === "campaign") {
                rbvost.renderCampaignFilters();
                rbvost.renderCampaignList();
            }

            if (view === "calendar") {
                rbvost.renderCalendarFilters();
                rbvost.renderCalendar();
            }

            rbvost.currentView = view;
        },

        renderView: function (data, template, el, callback) {
            $.get(rbvost.templateurl + template, function (template) {
                $(el).html(
                    _.template(template, data)
                );

                $(el).fadeIn("slow");
                $("#app").css({ "background-image" : "none" });

                if (callback) { callback(); }
            });
        },

        windowResized: function () {
            // retrigger the isotope layout engine
            $(rbvost.isotopeEl).isotope("reLayout");
        },

        setAppHeight: function () {
            // set a min height minus the guessed height for redbull global header / footer
            var appHeight = $(window).height() - 286 + "px";
            $("#app").css({ "min-height" : appHeight });
        },

        navigate: function (e) {
            // Set spinner
            $("#app").css({ "background-image" : rbvost.siteurl + "/wp-content/themes/rbvost/img/ajax-loader.gif" });

            // Toggle active state in menu
            $("button[data-navigate]").removeClass("current");
            $(e.currentTarget).addClass("current");

            // Set current page and rerender
            var destination = $(e.currentTarget).data("navigate");
            rbvost.router(destination);
        },

        // -----------------------------------------------------------------------------------------
        // Login View
        // -----------------------------------------------------------------------------------------

        checkLoginError: function () {
            var querystring = window.location.href.slice(window.location.href.indexOf("?") + 1);
            if (querystring === "login-failed") {
                $(".alert").show();
            }
        },

        // -----------------------------------------------------------------------------------------
        // Menu View
        // -----------------------------------------------------------------------------------------

        renderMenu: function () {
            var data = rbvost.dateRange;
            rbvost.renderView(data, "year-selector.html", ".year-selector-view");
        },

        dropdownShouldToggle: function (e) {
            $(e.currentTarget).find(".fa").toggleClass("fa-rotate-180");
            $(e.currentTarget).find(".dropdown").slideToggle("fast");
        },

        yearShouldChange: function (e) {
            var year = $(e.currentTarget).data("value");

            // Close menu and update text
            rbvost.dropdownShouldToggle(e);
            $(".menu-item-dropdown .current-year").text(year);

            // Set spinner and it API for requested year, update cache and re-render
            $("#app").css({ "background-image" : "" });
            rbvost.currentYear = year;
            rbvost.getContent();
        },

        // -----------------------------------------------------------------------------------------
        // Targets View
        // -----------------------------------------------------------------------------------------

        renderTargets: function () {
            var data = rbvost.cache;
            var uniqueTargets = rbvost.getUniqueTargets();

            rbvost.renderView(uniqueTargets, "targets.html", ".targets-view");
        },

        // -----------------------------------------------------------------------------------------
        // Campaigns View
        // -----------------------------------------------------------------------------------------

        renderCampaignFilters: function () {
            var data = rbvost.cache;
            var uniqueTargets = rbvost.getUniqueTargets();

            rbvost.renderView(uniqueTargets, "campaign-filters.html", ".campaign-filters-view");
        },

        renderCampaignList: function () {
            var data = rbvost.cache;
            var viewData = { campaigns: [] };

            _.each(data.posts, function (post) {
                var campaign = {};

                // get target + slug
                _.each(post.categories, function (category) {
                    if (category.parent) {
                        campaign.targetName = category.title;
                        campaign.targetSlug = category.slug;
                    }
                });

                campaign.title = post.title;
                campaign.description = post.acf.campaign_description;
                campaign.image = post.acf.campaign_image;

                viewData.campaigns.push(campaign);
            });

            var afterRender = function () {
                $(rbvost.isotopeEl).imagesLoaded(function () {
                    $(rbvost.isotopeEl).isotope();
                });
            };

            rbvost.renderView(viewData, "campaign-list.html", ".campaign-list-view", afterRender);
        },

        campaignsShouldFilter: function (e) {
            // toggle styling
            $(e.currentTarget).siblings().removeClass("active");
            $(e.currentTarget).addClass("active");

            // hide any active tooltips
            $(".tooltip .inner").hide();

            // run the isotope filters
            var query = $(e.currentTarget).data("filter");
            $(rbvost.isotopeEl).isotope({ filter: query });
        },

        tooltipShouldToggle: function (e) {
            e.stopImmediatePropagation();
            var tooltip = $(e.currentTarget).find(".inner");

            if ($(tooltip).is(":visible")) {
                $(tooltip).hide();
            } else {
                // hide any active tooltips
                $(".tooltip .inner").hide();
                $(tooltip).show();
            }
        },

        // -----------------------------------------------------------------------------------------
        // Calendar View
        // -----------------------------------------------------------------------------------------

        renderCalendarFilters: function () {
            var data = rbvost.cache;

            var filters = {
                targets: rbvost.getUniqueTargets(),
                campaigns: [],
                regions: []
            };

            // get campaigns
            _.each(data.posts, function (post) {
                var campaign = {};
                campaign.title = post.title;
                campaign.slug = post.slug;

                filters.campaigns.push(campaign);
            });

            var getUniqueRegions = function (region) {
                var thisRegion = {};
                thisRegion.slug = region;

                if (thisRegion.slug === "national") { thisRegion.title = "National"; }
                if (thisRegion.slug === "london") { thisRegion.title = "London"; }
                if (thisRegion.slug === "north") { thisRegion.title = "North / Scotland"; }
                if (thisRegion.slug === "southwest") { thisRegion.title = "South West"; }
                if (thisRegion.slug === "midlands") { thisRegion.title = "Midlands"; }

                var exists = _.findWhere(filters.regions, { slug: thisRegion.slug });

                if (!exists) {
                    filters.regions.push(thisRegion);
                }
            };

            // get regions
            _.each(data.posts, function (post) {
                // annoyingly the API can return a string or an array for the regions list
                if (_.isArray(post.acf.region)) {
                    _.each(post.acf.region, function (region) {
                        getUniqueRegions(region);
                    });
                } else {
                    getUniqueRegions(post.acf.region);
                }
            });

            rbvost.renderView(filters, "calendar-filters.html", ".calendar-filters-view", false);
        },

        renderCalendar: function () {
            var data = rbvost.cache;
            var calendarEvents = [];

            _.each(data.posts, function (post) {
                // here we can grab stuff from the post which we can later insert into the event objects
                var campaign = post.slug;
                var region = post.acf.region;
                var target;

                // get the event target
                _.each(post.categories, function (category) {
                    if (category.parent) {
                        target = category.slug;
                    }
                });

                _.each(post.acf.events, function (event) {
                    // create event object
                    var thisEvent = {};
                    // add data to object

                    // All events are technically multi day, but we mock single day events by setting the start and end dates to be the same.
                    if (event.event_type === "Multi Day") {
                        thisEvent.startDate = event.event_start_date;
                        thisEvent.endDate = event.event_end_date;
                        thisEvent.prettyDate = moment(event.event_start_date).format("dddd Do MMMM YYYY") + " - " + moment(event.event_end_date).format("dddd Do MMMM YYYY");
                        thisEvent.prettyDateShort = moment(event.event_start_date).format("dddd Do") + " - " + moment(event.event_end_date).format("dddd Do");
                    } else {
                        thisEvent.startDate = event.event_date;
                        thisEvent.endDate = event.event_date;
                        thisEvent.prettyDate = moment(event.event_date).format("dddd Do MMMM YYYY");
                        thisEvent.prettyDateShort = moment(event.event_date).format("dddd Do");
                    }

                    // Regions might be a string or array - lets make sure they're a string
                    var regionList = region.toString().replace(",", " ");

                    thisEvent.location = event.event_location;
                    thisEvent.name = event.event_name;
                    thisEvent.campaign = campaign;
                    thisEvent.description = event.event_description;
                    thisEvent.images = event.event_images;
                    thisEvent.region = regionList;
                    thisEvent.target = target;
                    thisEvent.id = "" + (new Date().getTime()) + (Math.floor(Math.random() * 999999) + 1);
                    // push results to hoisted array
                    calendarEvents.push(thisEvent);
                });
            });

            // now we have added our unique id to each event
            // we can cache the events object so we can use it later for the event popup
            rbvost.cache.events = calendarEvents;

            // If a clndr instance already exists we can just update it
            if (rbvost.calendar) {

                rbvost.calendar.setEvents(calendarEvents);
                rbvost.calendar.setYear(rbvost.currentYear);

                $(".calendar-view").fadeIn("fast");

            // if not let's grab the template and render it out
            } else {

                $.get(rbvost.templateurl + "calendar.html", function (calendarTemplate) {
                    rbvost.calendar = $(".calendar-view").clndr({
                        template: calendarTemplate,
                        events: calendarEvents,
                        showAdjacentMonths: false,
                        multiDayEvents: {
                            startDate: "startDate",
                            endDate: "endDate"
                        },
                        lengthOfTime: {
                            months: 12,
                            startDate: rbvost.currentYear + "-01-01"
                        }
                    });

                    $(".calendar-view").fadeIn("fast");
                });

            }
        },

        calendarShouldFilter: function (e) {
            // first lets toggle the styling
            $(e.currentTarget).siblings().removeClass("active");
            $(e.currentTarget).addClass("active");

            // then we update our calendar settings object
            var type = $(e.currentTarget).data("type");
            var value = $(e.currentTarget).data("filter");
            rbvost.calendarFilters[type] = value;

            // now we can show all events, and then hide appropriate ones
            var clndr = $(".clndr");
            $(clndr).find(".day").removeClass("hidden-event");

            // loop through our filters and if they're not set to show all
            // find events that don't contain the fiter term and hide them
            _.each(rbvost.calendarFilters, function (filter) {
                if (filter !== "*") {
                    $(clndr).find(".event:not(" + filter + ")").addClass("hidden-event");
                }
            });
        },

        eventPopupShouldToggle: function (e) {
            var popup = $(e.currentTarget).find(".popup");

            if ($(popup).is(":visible")) {
                $(popup).hide();
            } else {
                // hide any active popups
                $(".clndr .popup").hide();
                $(popup).show();
            }
        },

        eventPopupShouldClose: function (e) {
            e.stopImmediatePropagation();
            $(e.currentTarget).parent().hide();
        },

        calendarOverlayShouldRender: function (e) {
            var events = rbvost.cache.events;
            var eventId = $(e.currentTarget).data("id");
            var thisEvent = { event: [] };

            thisEvent.event.push(_.findWhere(events, { id: eventId }));

            var afterRender = function () {
                $("#modal").fadeIn("fast");
                $(".flexslider").flexslider();
            };

            rbvost.renderView(thisEvent, "modal.html", ".modal-view", afterRender);
        },

        modalShouldClose: function () {
            $("#modal").fadeOut("fast");
        }

    };

    // DOM Ready
    $(function () { rbvost.init(); });
    // Window Resized (smart debounced event)
    $(window).bind("debouncedresize", function () { rbvost.windowResized(); });

} (jQuery));
<|endoftext|>


<commit_before>"use strict";
/* eslint-disable no-console */
/* eslint-disable import/default */
var chalk = require('chalk');
var app = require('../app.js'); // This initializes the Express application
var config = require('../../config.js');

var port = config.port || 5000;
var server = app.listen(port, err => {
  if (err) {
    console.log(chalk.red(err));
  } else {
    console.log(chalk.green('Server listening on port'), chalk.blue(port));
  }
});

module.exports = server;
<commit_msg>app(env): Move npm dotenv to dependencies instead of dev-dependencies<commit_after>"use strict";
/* eslint-disable no-console */
/* eslint-disable import/default */
var chalk = require('chalk');
var app = require('../app.js'); // This initializes the Express application
// var config = require('../../config.js');

var port = process.env.PORT || 5000;
var server = app.listen(port, err => {
  if (err) {
    console.log(chalk.red(err));
  } else {
    console.log(chalk.green('Server listening on port'), chalk.blue(port));
  }
});

module.exports = server;
<|endoftext|>


<commit_before>const Api = require('binance-api-node').default
const _ = require('lodash')

class Binance {

  constructor({key, secret}) {
    this.binance = Api({
      apiKey: key,
      apiSecret: secret
    })

  }

  //Public Methods

  ticker(pair) {
    const symbol = pair.replace('_','')
    return new Promise((resolve, reject) => {
      this.binance.dailyStats({ symbol })
        .then(ticker => {
          let { lastPrice, askPirec, bidPrice, highPrice, lowPrice, volume } = ticker
          resolve({
            last: parseFloat(lastPrice),
            ask: parseFloat(askPrice),
            bid: parseFloat(bidPrice),
            high: parseFloat(highPrice),
            low: parseFloat(lowPrice),
            volume: parseFloat(volume),
            timestamp: Date.now()
          })
        })
        .catch(err => reject(err.message))
    })
  }

  assets() {
    return new Promise((resolve, reject) => {
      this.binance.exchangeInfo()
        .then(info => {
          let pairs = []
          let symbols = info.symbols
          for (let i = 0; i < symbols.length; i++) {

            let {status, baseAsset} = symbols[i]
            // Exclude non-trading symbols
            if (status !== 'TRADING') continue
            pairs[i] = baseAsset
          }
          resolve(pairs)
        }).catch(err => reject(err.message))
    })
  }

  pairs() {
    return new Promise(((resolve, reject) => {
      this.binance.exchangeInfo().then(info => {
        let pairs = []
        let symbols = info.symbols
        for (let i = 0; i < symbols.length; i++) {

          let {status, baseAsset, quoteAsset} = symbols[i]
          // Exclude non-trading symbols
          if (status !== 'TRADING') continue
          pairs[i] = baseAsset + '_' + quoteAsset
        }

        resolve(pairs)
      }).catch(err => reject(err.message))
    }))

  }

  depth(pair, count = 50) {
    return new Promise(((resolve, reject) => {
      pair = pair.replace('_', '')

      this.binance.book({symbol: pair, limit: count})
        .then(info => {
          let depth = {
            asks: _.map(info.asks, item => [parseFloat(item.price), parseFloat(item.quantity)]),
            bids: _.map(info.bids, item => [parseFloat(item.price), parseFloat(item.quantity)])
          }
          resolve(depth)
        }).catch(err => reject(err.message))
    }))
  }

  // Authenticated Methods

  buy() {
    return privateMethods.addOrder.apply(this, ['buy', ...arguments])
  }

  sell() {
    return privateMethods.addOrder.apply(this, ['sell', ...arguments])
  }

  balances() {
    return new Promise((resolve, reject) => {
      this.binance.accountInfo()
        .then(accInfo => {
          let balances = {}
          _.map(accInfo.balances, (bal) => balances[bal.asset] = {
            balance: parseFloat(bal.free + bal.locked),
            available: parseFloat(bal.free),
            pending: parseFloat(bal.locked)
          })
          resolve(balances)
        })
        .catch(err => reject(err.message))
    })
  }

  address(asset) {
    return new Promise((resolve, reject) => {
      this.binance.depositAddress({asset: asset})
        .then(response => {
          if (response.success) resolve(response.address)
          else reject(response.success)
        })
        .catch(err => reject(err.message))
    })

  }
}

module.exports = Binance

const privateMethods = {
  addOrder(type, pair, amount, rate) {
    pair = pair.replace('_', '')
    let data = {
      symbol: pair,
      side: type.toUpperCase(),
      quantity: amount,
      price: rate
    }
    return new Promise((resolve, reject) => {
      this.binance.order(data)
        .then(response => {
          const txid = response.orderId
          resolve({txid})
        })
        .catch(err => reject(err.message))
    })
  }
}
<commit_msg>Fix Binance askPrice (#24)<commit_after>const Api = require('binance-api-node').default
const _ = require('lodash')

class Binance {

  constructor({key, secret}) {
    this.binance = Api({
      apiKey: key,
      apiSecret: secret
    })

  }

  //Public Methods

  ticker(pair) {
    const symbol = pair.replace('_','')
    return new Promise((resolve, reject) => {
      this.binance.dailyStats({ symbol })
        .then(ticker => {
          let { lastPrice, askPrice, bidPrice, highPrice, lowPrice, volume } = ticker
          resolve({
            last: parseFloat(lastPrice),
            ask: parseFloat(askPrice),
            bid: parseFloat(bidPrice),
            high: parseFloat(highPrice),
            low: parseFloat(lowPrice),
            volume: parseFloat(volume),
            timestamp: Date.now()
          })
        })
        .catch(err => reject(err.message))
    })
  }

  assets() {
    return new Promise((resolve, reject) => {
      this.binance.exchangeInfo()
        .then(info => {
          let pairs = []
          let symbols = info.symbols
          for (let i = 0; i < symbols.length; i++) {

            let {status, baseAsset} = symbols[i]
            // Exclude non-trading symbols
            if (status !== 'TRADING') continue
            pairs[i] = baseAsset
          }
          resolve(pairs)
        }).catch(err => reject(err.message))
    })
  }

  pairs() {
    return new Promise(((resolve, reject) => {
      this.binance.exchangeInfo().then(info => {
        let pairs = []
        let symbols = info.symbols
        for (let i = 0; i < symbols.length; i++) {

          let {status, baseAsset, quoteAsset} = symbols[i]
          // Exclude non-trading symbols
          if (status !== 'TRADING') continue
          pairs[i] = baseAsset + '_' + quoteAsset
        }

        resolve(pairs)
      }).catch(err => reject(err.message))
    }))

  }

  depth(pair, count = 50) {
    return new Promise(((resolve, reject) => {
      pair = pair.replace('_', '')

      this.binance.book({symbol: pair, limit: count})
        .then(info => {
          let depth = {
            asks: _.map(info.asks, item => [parseFloat(item.price), parseFloat(item.quantity)]),
            bids: _.map(info.bids, item => [parseFloat(item.price), parseFloat(item.quantity)])
          }
          resolve(depth)
        }).catch(err => reject(err.message))
    }))
  }

  // Authenticated Methods

  buy() {
    return privateMethods.addOrder.apply(this, ['buy', ...arguments])
  }

  sell() {
    return privateMethods.addOrder.apply(this, ['sell', ...arguments])
  }

  balances() {
    return new Promise((resolve, reject) => {
      this.binance.accountInfo()
        .then(accInfo => {
          let balances = {}
          _.map(accInfo.balances, (bal) => balances[bal.asset] = {
            balance: parseFloat(bal.free + bal.locked),
            available: parseFloat(bal.free),
            pending: parseFloat(bal.locked)
          })
          resolve(balances)
        })
        .catch(err => reject(err.message))
    })
  }

  address(asset) {
    return new Promise((resolve, reject) => {
      this.binance.depositAddress({asset: asset})
        .then(response => {
          if (response.success) resolve(response.address)
          else reject(response.success)
        })
        .catch(err => reject(err.message))
    })

  }
}

module.exports = Binance

const privateMethods = {
  addOrder(type, pair, amount, rate) {
    pair = pair.replace('_', '')
    let data = {
      symbol: pair,
      side: type.toUpperCase(),
      quantity: amount,
      price: rate
    }
    return new Promise((resolve, reject) => {
      this.binance.order(data)
        .then(response => {
          const txid = response.orderId
          resolve({txid})
        })
        .catch(err => reject(err.message))
    })
  }
}
<|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    // Draw drops.
    buffer.fillStyle = '#aaf';
    for(var drop in drops){
        buffer.fillRect(
          drops[drop]['x'],
          drops[drop]['y'],
          2,
          7
        );
    }

    // Draw object.
    buffer.fillStyle = '#777';
    buffer.fillRect(
      object['x'],
      object['y'],
      200,
      -40
    );

    // Draw number of particles.
    buffer.fillStyle = '#fff';
    buffer.fillText(
      drops.length,
      object['x'],
      object['y']
    );
}

function logic(){
    // Add some randomly placed drops.
    var loop_counter = drop_counter;
    do{
        drops.push({
          'x': Math.floor(Math.random() * width),
          'y': -99,
        });
    }while(loop_counter--);

    // Update drop positions.
    for(var drop in drops){
        drops[drop]['y'] += Math.random() * 9 + 9;

        // Delete drops below bottom of screen
        //   or that collided with the object.
        if(drops[drop]['y'] > height
          || !(
            drops[drop]['x'] <= object['x']
            || drops[drop]['y'] + 40 <= object['y']
            || drops[drop]['x'] - 200 >= object['x']
            || drops[drop]['y'] >= object['y']
          )){
            drops.splice(
              drop,
              1
            );
        }
    }
}

var drop_counter = 1;
var drops = [];
var object = {
  'x': 0,
  'y': 0,
};

window.onload = function(e){
    init_canvas();
    init_input(
      {
        187: {
          'todo': function(){
              drop_counter++;
          },
        },
        189: {
          'todo': function(){
              drop_counter = drop_counter > 0
                ? drop_counter - 1
                : 0;
          },
        },
      },
      {
        'mousedown': {
          'todo': function(){
              object['x'] = mouse['x'] - 100;
              object['y'] = mouse['y'];
          },
        },
        'mousemove': {
          'todo': function(){
              if(!mouse['down']){
                  return;
              }

              object['x'] = mouse['x'] - 100;
              object['y'] = mouse['y'];
          },
        },
      }
    );

    object['x'] = width / 2 - 100;
    object['y'] = height / 2;
};
<commit_msg>namespaced common input.js<commit_after>'use strict';

function draw_logic(){
    // Draw drops.
    buffer.fillStyle = '#aaf';
    for(var drop in drops){
        buffer.fillRect(
          drops[drop]['x'],
          drops[drop]['y'],
          2,
          7
        );
    }

    // Draw object.
    buffer.fillStyle = '#777';
    buffer.fillRect(
      object['x'],
      object['y'],
      200,
      -40
    );

    // Draw number of particles.
    buffer.fillStyle = '#fff';
    buffer.fillText(
      drops.length,
      object['x'],
      object['y']
    );
}

function logic(){
    // Add some randomly placed drops.
    var loop_counter = drop_counter;
    do{
        drops.push({
          'x': Math.floor(Math.random() * width),
          'y': -99,
        });
    }while(loop_counter--);

    // Update drop positions.
    for(var drop in drops){
        drops[drop]['y'] += Math.random() * 9 + 9;

        // Delete drops below bottom of screen
        //   or that collided with the object.
        if(drops[drop]['y'] > height
          || !(
            drops[drop]['x'] <= object['x']
            || drops[drop]['y'] + 40 <= object['y']
            || drops[drop]['x'] - 200 >= object['x']
            || drops[drop]['y'] >= object['y']
          )){
            drops.splice(
              drop,
              1
            );
        }
    }
}

var drop_counter = 1;
var drops = [];
var object = {
  'x': 0,
  'y': 0,
};

window.onload = function(e){
    init_canvas();
    input_init(
      {
        187: {
          'todo': function(){
              drop_counter++;
          },
        },
        189: {
          'todo': function(){
              drop_counter = drop_counter > 0
                ? drop_counter - 1
                : 0;
          },
        },
      },
      {
        'mousedown': {
          'todo': function(){
              object['x'] = input_mouse['x'] - 100;
              object['y'] = input_mouse['y'];
          },
        },
        'mousemove': {
          'todo': function(){
              if(!input_mouse['down']){
                  return;
              }

              object['x'] = input_mouse['x'] - 100;
              object['y'] = input_mouse['y'];
          },
        },
      }
    );

    object['x'] = width / 2 - 100;
    object['y'] = height / 2;
};
<|endoftext|>